diff --git a/bsp/phytium/.gitignore b/bsp/phytium/.gitignore new file mode 100644 index 0000000000..f577e88ffe --- /dev/null +++ b/bsp/phytium/.gitignore @@ -0,0 +1 @@ +*.dis \ No newline at end of file diff --git a/bsp/phytium/README.md b/bsp/phytium/README.md new file mode 100644 index 0000000000..74a251aabc --- /dev/null +++ b/bsp/phytium/README.md @@ -0,0 +1,171 @@ + +# PHYTIUM BSP 说明 + +## 简介 + +本文档为基于 RT-THREAD 的 Phytium 系列 CPU 相关 BSP 说明。 + +本文的主要内容如下: + +- BSP 简介 +- 移植支持情况 +- 如何在 Ubuntu/Windows 环境下使用此 BSP +- 如何进行编译与实验 +- 维护人信息 +- 注意事项 + + +## BSP简介 + +- 飞腾芯片产品具有谱系全、性能高、生态完善、自主化程度高等特点,目前主要包括高性能服务器CPU(飞腾腾云S系列)、高效能桌面CPU(飞腾腾锐D系列)、高端嵌入式CPU(飞腾腾珑E系列)和飞腾套片四大系列,为从端到云的各型设备提供核心算力支撑。 + + + +- 本BSP目前支持飞腾腾锐D系列、飞腾腾珑E系列 相关CPU,基于 Phytium-Standalone-SDK 进行开发。开发者能够使用 + +- 本BSP 支持Phytium系列CPU 工作在 aarch32/aarch64 两种执行状态 ,开发者能够根据自己的应用场景灵活选择CPU 工作状态。 + + + +## 移植支持情况 + +| **片上外设** | **支持情况** | **备注** | +| :----------------- | :----------: | :------------------------------------- | +| UART | 支持 | uart1 打印输出| + +| **芯片** | **支持情况** | **备注** | +| :----------------- | :----------: | :------------------------------------- | +| E2000D | 支持 | 支持SMP | +| E2000Q | 支持 | 支持SMP | +| E2000S | 支持 | | + + +## 如何在Ubuntu/Windows 环境下使用此BSP + + +### Ubuntu 环境 + +1. 根据 [Linux x86_64 SDK安装方法](https://gitee.com/phytium_embedded/phytium-standalone-sdk/blob/release/doc/reference/usr/install_linux_x86_64.md) 中1.1 - 1.2 节中介绍,先安装 SDK 编译环境 +2. 参考[RT-Thread/env](https://github.com/RT-Thread/env) 中Tutorial 在ubuntu 环境下安装 env 环境 +3. 在编译环境下执行 ```source ~/.env/env.sh``` +4. 以aarch32 执行状态为例,```cd bsp/phytium/aarch32``` + + +### Windows 环境 + +1. 根据[Windows 10 SDK安装方法](https://gitee.com/phytium_embedded/phytium-standalone-sdk/blob/release/doc/reference/usr/install_windows.md),安装 SDK 编译环境,编辑新建 Windows 环境变量 AARCH32_CROSS_PATH 和 AARCH64_CROSS_PATH +2. 参考[RT-Thread/env](https://github.com/RT-Thread/env) 中Tutorial 在 Windows 环境下解压 env 压缩包 +3. 以aarch32 执行状态为例,```cd bsp/phytium/aarch32``` +4. 使用 export_project.py 导出 BSP 工程到其他目录进行开发 +5. 使用 RT-Studio 导入 BSP 工程进行开发 + + +## 如何进行编译与实验 + +### 编译说明 + +- [AARCH32](./aarch32/README.md) +- [AARCH64](./aarch64/README.md) + +### 烧写及执行 + +#### Ubuntu 环境配置 tftp 服务 + +- 在开发环境`host`侧安装`tftp`服务 + +``` +sudo apt-get install tftp-hpa tftpd-hpa +sudo apt-get install xinetd +``` + +- 新建 tftboot 目录, 以`/mnt/d/tftboot`为例, 此目录应与项目编译脚本makefile中的USR_BOOT_DIR一致, 并确保 tftboot 目录有执行权限`chmod 777 /**/tftboot` + +- 配置主机 tftpboot 服务, 新建并配置文件`/etc/xinetd.d/tftp` + +``` +# /etc/xinetd.d/tftp + +server tftp +{ + socket_type = dgram + protocol = udp + wait = yes + user = root + server = /usr/sbin/in.tftpd + server_args = -s /mnt/d/tftboot + disable = no + per_source = 11 + cps = 100 2 + flags = IPv4 +} +``` + +- 启动主机`tftp`服务,生成默认配置 + +``` +$ sudo service tftpd-hpa start +``` + +- 修改主机`tftp`配置,指向`tftboot`目录 + 修改/etc/default/tftpd-hpa + +``` +$ sudo nano /etc/default/tftpd-hpa +# /etc/default/tftpd-hpa + +TFTP_USERNAME="tftp" +TFTP_DIRECTORY="/mnt/d/tftboot" +TFTP_ADDRESS=":69" +TFTP_OPTIONS="-l -c -s" +``` + +- 重启主机`tftp`服务 + +``` +$ sudo service tftpd-hpa restart +``` + +- 测试主机`tftp`服务的可用性 + > 登录`tftp`服务,获取`tftboot`目录下的一个文件 + +``` +$ tftp 192.168.4.50 +tftp> get test1234 +tftp> q +``` + +#### Windows环境下配置 tftp 服务 + +- 下载Tftpd64 工具 ,并安装Tftpd64 工具 + +![输入图片说明](./figures/tftp32_srv.png) + +- 之后每次使用前,进入Windows服务,手动将一下服务打开 + +![输入图片说明](./figures/config_tftp32.png) + +#### 利用uboot 上tftp 服务加载镜像 + +- 进入`u-boot`界面,输入如下指令,配置开发板ip,`host`侧ip和网关地址 + ``` + setenv ipaddr 192.168.4.20 + setenv serverip 192.168.4.50 + setenv gatewayip 192.168.4.1 + ``` +- 将编译好的elf 或者bin 文件拷贝至Tftpd64所设置文件夹下 +- 随后烧录的文件到开发板,输入以下指令 + + ``` + tftpboot 0x90100000 rtthread.elf + bootelf -p 0x90100000 + ``` + +### 运行结果 + +![运行结果](./figures/result.png) + + +## 维护人信息 + +- huanghe: huanghe@phytium.com.cn +- zhugengyu: zhugengyu@phytium.com.cn \ No newline at end of file diff --git a/bsp/phytium/aarch32/.config b/bsp/phytium/aarch32/.config new file mode 100644 index 0000000000..86c8e62a6a --- /dev/null +++ b/bsp/phytium/aarch32/.config @@ -0,0 +1,927 @@ +# +# Automatically generated file; DO NOT EDIT. +# RT-Thread Project Configuration +# + +# +# RT-Thread Kernel +# +CONFIG_RT_NAME_MAX=8 +# CONFIG_RT_USING_ARCH_DATA_TYPE is not set +CONFIG_RT_USING_SMP=y +CONFIG_RT_CPUS_NR=4 +CONFIG_RT_ALIGN_SIZE=4 +# CONFIG_RT_THREAD_PRIORITY_8 is not set +CONFIG_RT_THREAD_PRIORITY_32=y +# CONFIG_RT_THREAD_PRIORITY_256 is not set +CONFIG_RT_THREAD_PRIORITY_MAX=32 +CONFIG_RT_TICK_PER_SECOND=1000 +CONFIG_RT_USING_OVERFLOW_CHECK=y +CONFIG_RT_USING_HOOK=y +CONFIG_RT_HOOK_USING_FUNC_PTR=y +CONFIG_RT_USING_IDLE_HOOK=y +CONFIG_RT_IDLE_HOOK_LIST_SIZE=4 +CONFIG_IDLE_THREAD_STACK_SIZE=256 +CONFIG_SYSTEM_THREAD_STACK_SIZE=256 +CONFIG_RT_USING_TIMER_SOFT=y +CONFIG_RT_TIMER_THREAD_PRIO=4 +CONFIG_RT_TIMER_THREAD_STACK_SIZE=512 + +# +# kservice optimization +# +CONFIG_RT_KSERVICE_USING_STDLIB=y +# CONFIG_RT_KSERVICE_USING_STDLIB_MEMORY is not set +# CONFIG_RT_KSERVICE_USING_TINY_SIZE is not set +# CONFIG_RT_USING_TINY_FFS is not set +# CONFIG_RT_KPRINTF_USING_LONGLONG is not set +CONFIG_RT_DEBUG=y +# CONFIG_RT_DEBUG_COLOR is not set +# CONFIG_RT_DEBUG_INIT_CONFIG is not set +# CONFIG_RT_DEBUG_THREAD_CONFIG is not set +# CONFIG_RT_DEBUG_SCHEDULER_CONFIG is not set +# CONFIG_RT_DEBUG_IPC_CONFIG is not set +# CONFIG_RT_DEBUG_TIMER_CONFIG is not set +# CONFIG_RT_DEBUG_IRQ_CONFIG is not set +# CONFIG_RT_DEBUG_MEM_CONFIG is not set +# CONFIG_RT_DEBUG_SLAB_CONFIG is not set +# CONFIG_RT_DEBUG_MEMHEAP_CONFIG is not set +# CONFIG_RT_DEBUG_MODULE_CONFIG is not set + +# +# Inter-Thread communication +# +CONFIG_RT_USING_SEMAPHORE=y +CONFIG_RT_USING_MUTEX=y +CONFIG_RT_USING_EVENT=y +CONFIG_RT_USING_MAILBOX=y +CONFIG_RT_USING_MESSAGEQUEUE=y +# CONFIG_RT_USING_SIGNALS is not set + +# +# Memory Management +# +CONFIG_RT_USING_MEMPOOL=y +CONFIG_RT_USING_SMALL_MEM=y +# CONFIG_RT_USING_SLAB is not set +# CONFIG_RT_USING_MEMHEAP is not set +CONFIG_RT_USING_SMALL_MEM_AS_HEAP=y +# CONFIG_RT_USING_MEMHEAP_AS_HEAP is not set +# CONFIG_RT_USING_SLAB_AS_HEAP is not set +# CONFIG_RT_USING_USERHEAP is not set +# CONFIG_RT_USING_NOHEAP is not set +# CONFIG_RT_USING_MEMTRACE is not set +# CONFIG_RT_USING_HEAP_ISR is not set +CONFIG_RT_USING_HEAP=y + +# +# Kernel Device Object +# +CONFIG_RT_USING_DEVICE=y +# CONFIG_RT_USING_DEVICE_OPS is not set +# CONFIG_RT_USING_INTERRUPT_INFO is not set +CONFIG_RT_USING_CONSOLE=y +CONFIG_RT_CONSOLEBUF_SIZE=128 +CONFIG_RT_CONSOLE_DEVICE_NAME="uart1" +CONFIG_RT_VER_NUM=0x50000 +CONFIG_ARCH_ARM=y +CONFIG_RT_USING_CPU_FFS=y +CONFIG_ARCH_ARM_CORTEX_A=y +# CONFIG_RT_SMP_AUTO_BOOT is not set +# CONFIG_RT_USING_GIC_V2 is not set +CONFIG_RT_USING_GIC_V3=y +# CONFIG_ARCH_CPU_STACK_GROWS_UPWARD is not set + +# +# RT-Thread Components +# +CONFIG_RT_USING_COMPONENTS_INIT=y +CONFIG_RT_USING_USER_MAIN=y +CONFIG_RT_MAIN_THREAD_STACK_SIZE=2048 +CONFIG_RT_MAIN_THREAD_PRIORITY=10 +# CONFIG_RT_USING_LEGACY is not set +CONFIG_RT_USING_MSH=y +CONFIG_RT_USING_FINSH=y +CONFIG_FINSH_USING_MSH=y +CONFIG_FINSH_THREAD_NAME="tshell" +CONFIG_FINSH_THREAD_PRIORITY=20 +CONFIG_FINSH_THREAD_STACK_SIZE=4096 +CONFIG_FINSH_USING_HISTORY=y +CONFIG_FINSH_HISTORY_LINES=5 +CONFIG_FINSH_USING_SYMTAB=y +CONFIG_FINSH_CMD_SIZE=80 +CONFIG_MSH_USING_BUILT_IN_COMMANDS=y +CONFIG_FINSH_USING_DESCRIPTION=y +# CONFIG_FINSH_ECHO_DISABLE_DEFAULT is not set +# CONFIG_FINSH_USING_AUTH is not set +CONFIG_FINSH_ARG_MAX=10 +CONFIG_RT_USING_DFS=y +CONFIG_DFS_USING_POSIX=y +CONFIG_DFS_USING_WORKDIR=y +CONFIG_DFS_FILESYSTEMS_MAX=4 +CONFIG_DFS_FILESYSTEM_TYPES_MAX=4 +CONFIG_DFS_FD_MAX=16 +# CONFIG_RT_USING_DFS_MNTTABLE is not set +# CONFIG_RT_USING_DFS_ELMFAT is not set +# CONFIG_RT_USING_DFS_DEVFS is not set +# CONFIG_RT_USING_DFS_ROMFS is not set +# CONFIG_RT_USING_DFS_RAMFS is not set +# CONFIG_RT_USING_FAL is not set +# CONFIG_RT_USING_LWP is not set + +# +# Device Drivers +# +CONFIG_RT_USING_DEVICE_IPC=y +# CONFIG_RT_USING_SYSTEM_WORKQUEUE is not set +CONFIG_RT_USING_SERIAL=y +CONFIG_RT_USING_SERIAL_V1=y +# CONFIG_RT_USING_SERIAL_V2 is not set +CONFIG_RT_SERIAL_USING_DMA=y +CONFIG_RT_SERIAL_RB_BUFSZ=64 +# CONFIG_RT_USING_CAN is not set +# CONFIG_RT_USING_HWTIMER is not set +# CONFIG_RT_USING_CPUTIME is not set +# CONFIG_RT_USING_I2C is not set +# CONFIG_RT_USING_PHY is not set +CONFIG_RT_USING_PIN=y +# CONFIG_RT_USING_ADC is not set +# CONFIG_RT_USING_DAC is not set +# CONFIG_RT_USING_PWM is not set +# CONFIG_RT_USING_MTD_NOR is not set +# CONFIG_RT_USING_MTD_NAND is not set +# CONFIG_RT_USING_PM is not set +# CONFIG_RT_USING_RTC is not set +# CONFIG_RT_USING_SDIO is not set +# CONFIG_RT_USING_SPI is not set +# CONFIG_RT_USING_WDT is not set +# CONFIG_RT_USING_AUDIO is not set +# CONFIG_RT_USING_SENSOR is not set +# CONFIG_RT_USING_TOUCH is not set +# CONFIG_RT_USING_HWCRYPTO is not set +# CONFIG_RT_USING_PULSE_ENCODER is not set +# CONFIG_RT_USING_INPUT_CAPTURE is not set +# CONFIG_RT_USING_WIFI is not set + +# +# Using USB +# +# CONFIG_RT_USING_USB is not set +# CONFIG_RT_USING_USB_HOST is not set +# CONFIG_RT_USING_USB_DEVICE is not set + +# +# C/C++ and POSIX layer +# +CONFIG_RT_LIBC_DEFAULT_TIMEZONE=8 + +# +# POSIX (Portable Operating System Interface) layer +# +# CONFIG_RT_USING_POSIX_FS is not set +# CONFIG_RT_USING_POSIX_DELAY is not set +# CONFIG_RT_USING_POSIX_CLOCK is not set +# CONFIG_RT_USING_POSIX_TIMER is not set +# CONFIG_RT_USING_PTHREADS is not set +# CONFIG_RT_USING_MODULE is not set + +# +# Interprocess Communication (IPC) +# +# CONFIG_RT_USING_POSIX_PIPE is not set +# CONFIG_RT_USING_POSIX_MESSAGE_QUEUE is not set +# CONFIG_RT_USING_POSIX_MESSAGE_SEMAPHORE is not set + +# +# Socket is in the 'Network' category +# +# CONFIG_RT_USING_CPLUSPLUS is not set + +# +# Network +# +# CONFIG_RT_USING_SAL is not set +# CONFIG_RT_USING_NETDEV is not set +# CONFIG_RT_USING_LWIP is not set +# CONFIG_RT_USING_AT is not set + +# +# Utilities +# +# CONFIG_RT_USING_RYM is not set +# CONFIG_RT_USING_ULOG is not set +# CONFIG_RT_USING_UTEST is not set +# CONFIG_RT_USING_VAR_EXPORT is not set +# CONFIG_RT_USING_RT_LINK is not set +# CONFIG_RT_USING_VBUS is not set + +# +# RT-Thread Utestcases +# +# CONFIG_RT_USING_UTESTCASES is not set + +# +# RT-Thread online packages +# + +# +# IoT - internet of things +# +# CONFIG_PKG_USING_LWIP is not set +# CONFIG_PKG_USING_LORAWAN_DRIVER is not set +# CONFIG_PKG_USING_PAHOMQTT is not set +# CONFIG_PKG_USING_UMQTT is not set +# CONFIG_PKG_USING_WEBCLIENT is not set +# CONFIG_PKG_USING_WEBNET is not set +# CONFIG_PKG_USING_MONGOOSE is not set +# CONFIG_PKG_USING_MYMQTT is not set +# CONFIG_PKG_USING_KAWAII_MQTT is not set +# CONFIG_PKG_USING_BC28_MQTT is not set +# CONFIG_PKG_USING_WEBTERMINAL is not set +# CONFIG_PKG_USING_LIBMODBUS is not set +# CONFIG_PKG_USING_FREEMODBUS is not set +# CONFIG_PKG_USING_NANOPB is not set + +# +# Wi-Fi +# + +# +# Marvell WiFi +# +# CONFIG_PKG_USING_WLANMARVELL is not set + +# +# Wiced WiFi +# +# CONFIG_PKG_USING_WLAN_WICED is not set +# CONFIG_PKG_USING_RW007 is not set +# CONFIG_PKG_USING_COAP is not set +# CONFIG_PKG_USING_NOPOLL is not set +# CONFIG_PKG_USING_NETUTILS is not set +# CONFIG_PKG_USING_CMUX is not set +# CONFIG_PKG_USING_PPP_DEVICE is not set +# CONFIG_PKG_USING_AT_DEVICE is not set +# CONFIG_PKG_USING_ATSRV_SOCKET is not set +# CONFIG_PKG_USING_WIZNET is not set +# CONFIG_PKG_USING_ZB_COORDINATOR is not set + +# +# IoT Cloud +# +# CONFIG_PKG_USING_ONENET is not set +# CONFIG_PKG_USING_GAGENT_CLOUD is not set +# CONFIG_PKG_USING_ALI_IOTKIT is not set +# CONFIG_PKG_USING_AZURE is not set +# CONFIG_PKG_USING_TENCENT_IOT_EXPLORER is not set +# CONFIG_PKG_USING_JIOT-C-SDK is not set +# CONFIG_PKG_USING_UCLOUD_IOT_SDK is not set +# CONFIG_PKG_USING_JOYLINK is not set +# CONFIG_PKG_USING_EZ_IOT_OS is not set +# CONFIG_PKG_USING_IOTSHARP_SDK is not set +# CONFIG_PKG_USING_NIMBLE is not set +# CONFIG_PKG_USING_LLSYNC_SDK_ADAPTER is not set +# CONFIG_PKG_USING_OTA_DOWNLOADER is not set +# CONFIG_PKG_USING_IPMSG is not set +# CONFIG_PKG_USING_LSSDP is not set +# CONFIG_PKG_USING_AIRKISS_OPEN is not set +# CONFIG_PKG_USING_LIBRWS is not set +# CONFIG_PKG_USING_TCPSERVER is not set +# CONFIG_PKG_USING_PROTOBUF_C is not set +# CONFIG_PKG_USING_DLT645 is not set +# CONFIG_PKG_USING_QXWZ is not set +# CONFIG_PKG_USING_SMTP_CLIENT is not set +# CONFIG_PKG_USING_ABUP_FOTA is not set +# CONFIG_PKG_USING_LIBCURL2RTT is not set +# CONFIG_PKG_USING_CAPNP is not set +# CONFIG_PKG_USING_AGILE_TELNET is not set +# CONFIG_PKG_USING_NMEALIB is not set +# CONFIG_PKG_USING_PDULIB is not set +# CONFIG_PKG_USING_BTSTACK is not set +# CONFIG_PKG_USING_LORAWAN_ED_STACK is not set +# CONFIG_PKG_USING_WAYZ_IOTKIT is not set +# CONFIG_PKG_USING_MAVLINK is not set +# CONFIG_PKG_USING_BSAL is not set +# CONFIG_PKG_USING_AGILE_MODBUS is not set +# CONFIG_PKG_USING_AGILE_FTP is not set +# CONFIG_PKG_USING_EMBEDDEDPROTO is not set +# CONFIG_PKG_USING_RT_LINK_HW is not set +# CONFIG_PKG_USING_LORA_PKT_FWD is not set +# CONFIG_PKG_USING_LORA_GW_DRIVER_LIB is not set +# CONFIG_PKG_USING_LORA_PKT_SNIFFER is not set +# CONFIG_PKG_USING_HM is not set +# CONFIG_PKG_USING_SMALL_MODBUS is not set +# CONFIG_PKG_USING_NET_SERVER is not set +# CONFIG_PKG_USING_ZFTP is not set + +# +# security packages +# +# CONFIG_PKG_USING_MBEDTLS is not set +# CONFIG_PKG_USING_LIBSODIUM is not set +# CONFIG_PKG_USING_LIBHYDROGEN is not set +# CONFIG_PKG_USING_TINYCRYPT is not set +# CONFIG_PKG_USING_TFM is not set +# CONFIG_PKG_USING_YD_CRYPTO is not set + +# +# language packages +# + +# +# JSON: JavaScript Object Notation, a lightweight data-interchange format +# +# CONFIG_PKG_USING_CJSON is not set +# CONFIG_PKG_USING_LJSON is not set +# CONFIG_PKG_USING_RT_CJSON_TOOLS is not set +# CONFIG_PKG_USING_RAPIDJSON is not set +# CONFIG_PKG_USING_JSMN is not set +# CONFIG_PKG_USING_AGILE_JSMN is not set +# CONFIG_PKG_USING_PARSON is not set + +# +# XML: Extensible Markup Language +# +# CONFIG_PKG_USING_SIMPLE_XML is not set +# CONFIG_PKG_USING_EZXML is not set +# CONFIG_PKG_USING_LUATOS_SOC is not set +# CONFIG_PKG_USING_LUA is not set +# CONFIG_PKG_USING_JERRYSCRIPT is not set +# CONFIG_PKG_USING_MICROPYTHON is not set +# CONFIG_PKG_USING_PIKASCRIPT is not set +# CONFIG_PKG_USING_RTT_RUST is not set + +# +# multimedia packages +# + +# +# LVGL: powerful and easy-to-use embedded GUI library +# +# CONFIG_PKG_USING_LVGL is not set +# CONFIG_PKG_USING_LITTLEVGL2RTT is not set +# CONFIG_PKG_USING_LV_MUSIC_DEMO is not set +# CONFIG_PKG_USING_GUI_GUIDER_DEMO is not set + +# +# u8g2: a monochrome graphic library +# +# CONFIG_PKG_USING_U8G2_OFFICIAL is not set +# CONFIG_PKG_USING_U8G2 is not set +# CONFIG_PKG_USING_OPENMV is not set +# CONFIG_PKG_USING_MUPDF is not set +# CONFIG_PKG_USING_STEMWIN is not set +# CONFIG_PKG_USING_WAVPLAYER is not set +# CONFIG_PKG_USING_TJPGD is not set +# CONFIG_PKG_USING_PDFGEN is not set +# CONFIG_PKG_USING_HELIX is not set +# CONFIG_PKG_USING_AZUREGUIX is not set +# CONFIG_PKG_USING_TOUCHGFX2RTT is not set +# CONFIG_PKG_USING_NUEMWIN is not set +# CONFIG_PKG_USING_MP3PLAYER is not set +# CONFIG_PKG_USING_TINYJPEG is not set +# CONFIG_PKG_USING_UGUI is not set + +# +# PainterEngine: A cross-platform graphics application framework written in C language +# +# CONFIG_PKG_USING_PAINTERENGINE is not set +# CONFIG_PKG_USING_PAINTERENGINE_AUX is not set +# CONFIG_PKG_USING_MCURSES is not set +# CONFIG_PKG_USING_TERMBOX is not set +# CONFIG_PKG_USING_VT100 is not set +# CONFIG_PKG_USING_QRCODE is not set +# CONFIG_PKG_USING_GUIENGINE is not set +# CONFIG_PKG_USING_PERSIMMON is not set + +# +# tools packages +# +# CONFIG_PKG_USING_CMBACKTRACE is not set +# CONFIG_PKG_USING_EASYFLASH is not set +# CONFIG_PKG_USING_EASYLOGGER is not set +# CONFIG_PKG_USING_SYSTEMVIEW is not set +# CONFIG_PKG_USING_SEGGER_RTT is not set +# CONFIG_PKG_USING_RDB is not set +# CONFIG_PKG_USING_ULOG_EASYFLASH is not set +# CONFIG_PKG_USING_ULOG_FILE is not set +# CONFIG_PKG_USING_LOGMGR is not set +# CONFIG_PKG_USING_ADBD is not set +# CONFIG_PKG_USING_COREMARK is not set +# CONFIG_PKG_USING_DHRYSTONE is not set +# CONFIG_PKG_USING_MEMORYPERF is not set +# CONFIG_PKG_USING_NR_MICRO_SHELL is not set +# CONFIG_PKG_USING_CHINESE_FONT_LIBRARY is not set +# CONFIG_PKG_USING_LUNAR_CALENDAR is not set +# CONFIG_PKG_USING_BS8116A is not set +# CONFIG_PKG_USING_GPS_RMC is not set +# CONFIG_PKG_USING_URLENCODE is not set +# CONFIG_PKG_USING_UMCN is not set +# CONFIG_PKG_USING_LWRB2RTT is not set +# CONFIG_PKG_USING_CPU_USAGE is not set +# CONFIG_PKG_USING_GBK2UTF8 is not set +# CONFIG_PKG_USING_VCONSOLE is not set +# CONFIG_PKG_USING_KDB is not set +# CONFIG_PKG_USING_WAMR is not set +# CONFIG_PKG_USING_MICRO_XRCE_DDS_CLIENT is not set +# CONFIG_PKG_USING_LWLOG is not set +# CONFIG_PKG_USING_ANV_TRACE is not set +# CONFIG_PKG_USING_ANV_MEMLEAK is not set +# CONFIG_PKG_USING_ANV_TESTSUIT is not set +# CONFIG_PKG_USING_ANV_BENCH is not set +# CONFIG_PKG_USING_DEVMEM is not set +# CONFIG_PKG_USING_REGEX is not set +# CONFIG_PKG_USING_MEM_SANDBOX is not set +# CONFIG_PKG_USING_SOLAR_TERMS is not set +# CONFIG_PKG_USING_GAN_ZHI is not set +# CONFIG_PKG_USING_FDT is not set +# CONFIG_PKG_USING_CBOX is not set +# CONFIG_PKG_USING_SNOWFLAKE is not set +# CONFIG_PKG_USING_HASH_MATCH is not set +# CONFIG_PKG_USING_FIRE_PID_CURVE is not set +# CONFIG_PKG_USING_ARMV7M_DWT_TOOL is not set +# CONFIG_PKG_USING_VOFA_PLUS is not set + +# +# system packages +# + +# +# enhanced kernel services +# +# CONFIG_PKG_USING_RT_MEMCPY_CM is not set +# CONFIG_PKG_USING_RT_KPRINTF_THREADSAFE is not set +# CONFIG_PKG_USING_RT_VSNPRINTF_FULL is not set + +# +# acceleration: Assembly language or algorithmic acceleration packages +# +# CONFIG_PKG_USING_QFPLIB_M0_FULL is not set +# CONFIG_PKG_USING_QFPLIB_M0_TINY is not set +# CONFIG_PKG_USING_QFPLIB_M3 is not set + +# +# CMSIS: ARM Cortex-M Microcontroller Software Interface Standard +# +# CONFIG_PKG_USING_CMSIS_5 is not set +# CONFIG_PKG_USING_CMSIS_RTOS1 is not set +# CONFIG_PKG_USING_CMSIS_RTOS2 is not set + +# +# Micrium: Micrium software products porting for RT-Thread +# +# CONFIG_PKG_USING_UCOSIII_WRAPPER is not set +# CONFIG_PKG_USING_UCOSII_WRAPPER is not set +# CONFIG_PKG_USING_UC_CRC is not set +# CONFIG_PKG_USING_UC_CLK is not set +# CONFIG_PKG_USING_UC_COMMON is not set +# CONFIG_PKG_USING_UC_MODBUS is not set +# CONFIG_PKG_USING_FREERTOS_WRAPPER is not set +# CONFIG_PKG_USING_CAIRO is not set +# CONFIG_PKG_USING_PIXMAN is not set +# CONFIG_PKG_USING_PARTITION is not set +# CONFIG_PKG_USING_PERF_COUNTER is not set +# CONFIG_PKG_USING_FLASHDB is not set +# CONFIG_PKG_USING_SQLITE is not set +# CONFIG_PKG_USING_RTI is not set +# CONFIG_PKG_USING_DFS_YAFFS is not set +# CONFIG_PKG_USING_LITTLEFS is not set +# CONFIG_PKG_USING_DFS_JFFS2 is not set +# CONFIG_PKG_USING_DFS_UFFS is not set +# CONFIG_PKG_USING_LWEXT4 is not set +# CONFIG_PKG_USING_THREAD_POOL is not set +# CONFIG_PKG_USING_ROBOTS is not set +# CONFIG_PKG_USING_EV is not set +# CONFIG_PKG_USING_SYSWATCH is not set +# CONFIG_PKG_USING_SYS_LOAD_MONITOR is not set +# CONFIG_PKG_USING_PLCCORE is not set +# CONFIG_PKG_USING_RAMDISK is not set +# CONFIG_PKG_USING_MININI is not set +# CONFIG_PKG_USING_QBOOT is not set +# CONFIG_PKG_USING_PPOOL is not set +# CONFIG_PKG_USING_OPENAMP is not set +# CONFIG_PKG_USING_LPM is not set +# CONFIG_PKG_USING_TLSF is not set +# CONFIG_PKG_USING_EVENT_RECORDER is not set +# CONFIG_PKG_USING_ARM_2D is not set +# CONFIG_PKG_USING_MCUBOOT is not set +# CONFIG_PKG_USING_TINYUSB is not set +# CONFIG_PKG_USING_CHERRYUSB is not set +# CONFIG_PKG_USING_KMULTI_RTIMER is not set +# CONFIG_PKG_USING_TFDB is not set +# CONFIG_PKG_USING_QPC is not set +# CONFIG_PKG_USING_AGILE_UPGRADE is not set + +# +# peripheral libraries and drivers +# +# CONFIG_PKG_USING_SENSORS_DRIVERS is not set +# CONFIG_PKG_USING_REALTEK_AMEBA is not set +# CONFIG_PKG_USING_SHT2X is not set +# CONFIG_PKG_USING_SHT3X is not set +# CONFIG_PKG_USING_ADT74XX is not set +# CONFIG_PKG_USING_AS7341 is not set +# CONFIG_PKG_USING_STM32_SDIO is not set +# CONFIG_PKG_USING_ESP_IDF is not set +# CONFIG_PKG_USING_ICM20608 is not set +# CONFIG_PKG_USING_BUTTON is not set +# CONFIG_PKG_USING_PCF8574 is not set +# CONFIG_PKG_USING_SX12XX is not set +# CONFIG_PKG_USING_SIGNAL_LED is not set +# CONFIG_PKG_USING_LEDBLINK is not set +# CONFIG_PKG_USING_LITTLED is not set +# CONFIG_PKG_USING_LKDGUI is not set +# CONFIG_PKG_USING_NRF5X_SDK is not set +# CONFIG_PKG_USING_NRFX is not set +# CONFIG_PKG_USING_WM_LIBRARIES is not set + +# +# Kendryte SDK +# +# CONFIG_PKG_USING_K210_SDK is not set +# CONFIG_PKG_USING_KENDRYTE_SDK is not set +# CONFIG_PKG_USING_INFRARED is not set +# CONFIG_PKG_USING_MULTI_INFRARED is not set +# CONFIG_PKG_USING_AGILE_BUTTON is not set +# CONFIG_PKG_USING_AGILE_LED is not set +# CONFIG_PKG_USING_AT24CXX is not set +# CONFIG_PKG_USING_MOTIONDRIVER2RTT is not set +# CONFIG_PKG_USING_AD7746 is not set +# CONFIG_PKG_USING_PCA9685 is not set +# CONFIG_PKG_USING_I2C_TOOLS is not set +# CONFIG_PKG_USING_NRF24L01 is not set +# CONFIG_PKG_USING_TOUCH_DRIVERS is not set +# CONFIG_PKG_USING_MAX17048 is not set +# CONFIG_PKG_USING_RPLIDAR is not set +# CONFIG_PKG_USING_AS608 is not set +# CONFIG_PKG_USING_RC522 is not set +# CONFIG_PKG_USING_WS2812B is not set +# CONFIG_PKG_USING_EMBARC_BSP is not set +# CONFIG_PKG_USING_EXTERN_RTC_DRIVERS is not set +# CONFIG_PKG_USING_MULTI_RTIMER is not set +# CONFIG_PKG_USING_MAX7219 is not set +# CONFIG_PKG_USING_BEEP is not set +# CONFIG_PKG_USING_EASYBLINK is not set +# CONFIG_PKG_USING_PMS_SERIES is not set +# CONFIG_PKG_USING_CAN_YMODEM is not set +# CONFIG_PKG_USING_LORA_RADIO_DRIVER is not set +# CONFIG_PKG_USING_QLED is not set +# CONFIG_PKG_USING_PAJ7620 is not set +# CONFIG_PKG_USING_AGILE_CONSOLE is not set +# CONFIG_PKG_USING_LD3320 is not set +# CONFIG_PKG_USING_WK2124 is not set +# CONFIG_PKG_USING_LY68L6400 is not set +# CONFIG_PKG_USING_DM9051 is not set +# CONFIG_PKG_USING_SSD1306 is not set +# CONFIG_PKG_USING_QKEY is not set +# CONFIG_PKG_USING_RS485 is not set +# CONFIG_PKG_USING_RS232 is not set +# CONFIG_PKG_USING_NES is not set +# CONFIG_PKG_USING_VIRTUAL_SENSOR is not set +# CONFIG_PKG_USING_VDEVICE is not set +# CONFIG_PKG_USING_SGM706 is not set +# CONFIG_PKG_USING_STM32WB55_SDK is not set +# CONFIG_PKG_USING_RDA58XX is not set +# CONFIG_PKG_USING_LIBNFC is not set +# CONFIG_PKG_USING_MFOC is not set +# CONFIG_PKG_USING_TMC51XX is not set +# CONFIG_PKG_USING_TCA9534 is not set +# CONFIG_PKG_USING_KOBUKI is not set +# CONFIG_PKG_USING_ROSSERIAL is not set +# CONFIG_PKG_USING_MICRO_ROS is not set +# CONFIG_PKG_USING_MCP23008 is not set +# CONFIG_PKG_USING_BLUETRUM_SDK is not set +# CONFIG_PKG_USING_MISAKA_AT24CXX is not set +# CONFIG_PKG_USING_MISAKA_RGB_BLING is not set +# CONFIG_PKG_USING_LORA_MODEM_DRIVER is not set +# CONFIG_PKG_USING_BL_MCU_SDK is not set +# CONFIG_PKG_USING_SOFT_SERIAL is not set +# CONFIG_PKG_USING_MB85RS16 is not set +# CONFIG_PKG_USING_CW2015 is not set +# CONFIG_PKG_USING_RFM300 is not set +# CONFIG_PKG_USING_IO_INPUT_FILTER is not set +# CONFIG_PKG_USING_RASPBERRYPI_PICO_SDK is not set +# CONFIG_PKG_USING_LRF_NV7LIDAR is not set + +# +# AI packages +# +# CONFIG_PKG_USING_LIBANN is not set +# CONFIG_PKG_USING_NNOM is not set +# CONFIG_PKG_USING_ONNX_BACKEND is not set +# CONFIG_PKG_USING_ONNX_PARSER is not set +# CONFIG_PKG_USING_TENSORFLOWLITEMICRO is not set +# CONFIG_PKG_USING_ELAPACK is not set +# CONFIG_PKG_USING_ULAPACK is not set +# CONFIG_PKG_USING_QUEST is not set +# CONFIG_PKG_USING_NAXOS is not set + +# +# miscellaneous packages +# + +# +# project laboratory +# + +# +# samples: kernel and components samples +# +# CONFIG_PKG_USING_KERNEL_SAMPLES is not set +# CONFIG_PKG_USING_FILESYSTEM_SAMPLES is not set +# CONFIG_PKG_USING_NETWORK_SAMPLES is not set +# CONFIG_PKG_USING_PERIPHERAL_SAMPLES is not set + +# +# entertainment: terminal games and other interesting software packages +# +# CONFIG_PKG_USING_CMATRIX is not set +# CONFIG_PKG_USING_SL is not set +# CONFIG_PKG_USING_CAL is not set +# CONFIG_PKG_USING_ACLOCK is not set +# CONFIG_PKG_USING_THREES is not set +# CONFIG_PKG_USING_2048 is not set +# CONFIG_PKG_USING_SNAKE is not set +# CONFIG_PKG_USING_TETRIS is not set +# CONFIG_PKG_USING_DONUT is not set +# CONFIG_PKG_USING_COWSAY is not set +# CONFIG_PKG_USING_LIBCSV is not set +# CONFIG_PKG_USING_OPTPARSE is not set +# CONFIG_PKG_USING_FASTLZ is not set +# CONFIG_PKG_USING_MINILZO is not set +# CONFIG_PKG_USING_QUICKLZ is not set +# CONFIG_PKG_USING_LZMA is not set +# CONFIG_PKG_USING_MULTIBUTTON is not set +# CONFIG_PKG_USING_FLEXIBLE_BUTTON is not set +# CONFIG_PKG_USING_CANFESTIVAL is not set +# CONFIG_PKG_USING_ZLIB is not set +# CONFIG_PKG_USING_MINIZIP is not set +# CONFIG_PKG_USING_HEATSHRINK is not set +# CONFIG_PKG_USING_DSTR is not set +# CONFIG_PKG_USING_TINYFRAME is not set +# CONFIG_PKG_USING_KENDRYTE_DEMO is not set +# CONFIG_PKG_USING_DIGITALCTRL is not set +# CONFIG_PKG_USING_UPACKER is not set +# CONFIG_PKG_USING_UPARAM is not set +# CONFIG_PKG_USING_HELLO is not set +# CONFIG_PKG_USING_VI is not set +# CONFIG_PKG_USING_KI is not set +# CONFIG_PKG_USING_ARMv7M_DWT is not set +# CONFIG_PKG_USING_UKAL is not set +# CONFIG_PKG_USING_CRCLIB is not set +# CONFIG_PKG_USING_LWGPS is not set +# CONFIG_PKG_USING_STATE_MACHINE is not set +# CONFIG_PKG_USING_DESIGN_PATTERN is not set +# CONFIG_PKG_USING_CONTROLLER is not set +# CONFIG_PKG_USING_PHASE_LOCKED_LOOP is not set +# CONFIG_PKG_USING_MFBD is not set +# CONFIG_PKG_USING_SLCAN2RTT is not set +# CONFIG_PKG_USING_SOEM is not set +# CONFIG_PKG_USING_QPARAM is not set + +# +# Arduino libraries +# +# CONFIG_PKG_USING_RTDUINO is not set + +# +# Projects +# +# CONFIG_PKG_USING_ARDUINO_ULTRASOUND_RADAR is not set +# CONFIG_PKG_USING_ARDUINO_SENSOR_KIT is not set +# CONFIG_PKG_USING_ARDUINO_MATLAB_SUPPORT is not set + +# +# Sensors +# +# CONFIG_PKG_USING_ARDUINO_SEEED_BMP280 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADXL375 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VL53L0X is not set +# CONFIG_PKG_USING_ARDUINO_SEEED_LIS3DHTR is not set +# CONFIG_PKG_USING_ARDUINO_SEEED_DHT is not set +# CONFIG_PKG_USING_ARDUINO_CAPACITIVESENSOR is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SENSOR is not set +# CONFIG_PKG_USING_ADAFRUIT_MAX31855 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MAX31865 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MAX31856 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90614 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM9DS1 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AHTX0 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM9DS0 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP280 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADT7410 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP085 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BME680 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP9808 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP4728 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_INA219 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LTR390 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADXL345 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_DHT is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP9600 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM6DS is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BNO055 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MAX1704X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MMC56X3 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90393 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90395 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ICM20X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_DPS310 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HTS221 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SHT4X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SHT31 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADXL343 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BME280 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AS726X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AMG88XX is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AM2320 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AM2315 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LTR329_LTR303 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP085_UNIFIED is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP183 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP183_UNIFIED is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP3XX is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MS8607 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS3MDL is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90640 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MMA8451 is not set +# CONFIG_PKG_USING_ADAFRUIT_MSA301 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPL115A2 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BNO08X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BNO08X_RVC is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS2MDL is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM303DLH_MAG is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LC709203F is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_CAP1188 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_CCS811 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_NAU7802 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS331 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LPS2X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LPS35HW is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM303_ACCEL is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS3DH is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCF8591 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPL3115A2 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPR121 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPRLS is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPU6050 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCT2075 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PM25AQI is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_EMC2101 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_FXAS21002C is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SCD30 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_FXOS8700 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HMC5883_UNIFIED is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SGP30 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TMP006 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TLA202X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TCS34725 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SI7021 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SI1145 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SGP40 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SHTC3 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HDC1000 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HTU21DF is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AS7341 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HTU31D is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SENSORLAB is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_INA260 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TMP007_LIBRARY is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_L3GD20 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TMP117 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TSC2007 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TSL2561 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TSL2591_LIBRARY is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VCNL4040 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VEML6070 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VEML6075 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VEML7700 is not set + +# +# Display +# +# CONFIG_PKG_USING_ARDUINO_U8G2 is not set + +# +# Timing +# +# CONFIG_PKG_USING_ARDUINO_MSTIMER2 is not set + +# +# Data Processing +# +# CONFIG_PKG_USING_ARDUINO_KALMANFILTER is not set +# CONFIG_PKG_USING_ARDUINO_ARDUINOJSON is not set + +# +# Data Storage +# + +# +# Communication +# +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PN532 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SI4713 is not set + +# +# Device Control +# +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCF8574 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCA9685 is not set + +# +# Other +# + +# +# Signal IO +# +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BUSIO is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TCA8418 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP23017 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADS1X15 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AW9523 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP3008 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP4725 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BD3491FS is not set + +# +# Uncategorized +# + +# +# Hardware Drivers +# + +# +# On-chip Peripheral Drivers +# +CONFIG_BSP_USING_UART=y +CONFIG_RT_USING_UART1=y +# CONFIG_RT_USING_UART0 is not set + +# +# Board extended module Drivers +# +CONFIG_PHYTIUM_ARCH_AARCH32=y + +# +# Standalone Setting +# +CONFIG_TARGET_ARMV8_AARCH32=y +CONFIG_USE_AARCH64_L1_TO_AARCH32=y + +# +# Board Configuration +# +# CONFIG_TARGET_F2000_4 is not set +# CONFIG_TARGET_D2000 is not set +CONFIG_TARGET_E2000Q=y +# CONFIG_TARGET_E2000D is not set +# CONFIG_TARGET_E2000S is not set +CONFIG_TARGET_E2000=y +CONFIG_DEFAULT_DEBUG_PRINT_UART1=y +# CONFIG_DEFAULT_DEBUG_PRINT_UART0 is not set +# CONFIG_DEFAULT_DEBUG_PRINT_UART2 is not set + +# +# Components Configuration +# +# CONFIG_USE_SPI is not set +# CONFIG_USE_QSPI is not set +CONFIG_USE_GIC=y +CONFIG_ENABLE_GICV3=y +CONFIG_USE_SERIAL=y + +# +# Usart Configuration +# +CONFIG_ENABLE_Pl011_UART=y +# CONFIG_USE_GPIO is not set +# CONFIG_USE_ETH is not set +# CONFIG_USE_CAN is not set +# CONFIG_USE_I2C is not set +# CONFIG_USE_TIMER is not set +# CONFIG_USE_MIO is not set +# CONFIG_USE_SDMMC is not set +# CONFIG_USE_PCIE is not set +# CONFIG_USE_WDT is not set +# CONFIG_USE_DMA is not set +# CONFIG_USE_NAND is not set +# CONFIG_USE_RTC is not set +# CONFIG_USE_SATA is not set +# CONFIG_USE_USB is not set +# CONFIG_USE_ADC is not set +# CONFIG_USE_PWM is not set +# CONFIG_USE_IPC is not set +# CONFIG_LOG_VERBOS is not set +# CONFIG_LOG_DEBUG is not set +# CONFIG_LOG_INFO is not set +# CONFIG_LOG_WARN is not set +CONFIG_LOG_ERROR=y +# CONFIG_LOG_NONE is not set +CONFIG_USE_DEFAULT_INTERRUPT_CONFIG=y +CONFIG_INTERRUPT_ROLE_MASTER=y +# CONFIG_INTERRUPT_ROLE_SLAVE is not set +# CONFIG_LOG_EXTRA_INFO is not set +# CONFIG_BOOTUP_DEBUG_PRINTS is not set diff --git a/bsp/phytium/aarch32/Kconfig b/bsp/phytium/aarch32/Kconfig new file mode 100644 index 0000000000..cc9a3fe042 --- /dev/null +++ b/bsp/phytium/aarch32/Kconfig @@ -0,0 +1,54 @@ +mainmenu "RT-Thread Project Configuration" + +config RTT_DIR + string + option env="RTT_ROOT" + default "../../.." + +config BSP_DIR + string + option env="BSP_ROOT" + default "../." + +config STANDALONE_DIR + string + option env="STANDALONE_DIR" + default ".././libraries/standalone" + +config PKGS_DIR + string + option env="PKGS_ROOT" + default "packages" + +source "$RTT_DIR/Kconfig" +source "$PKGS_DIR/Kconfig" +source "$BSP_DIR/libraries/drivers/Kconfig" + +config PHYTIUM_ARCH_AARCH32 + bool + select ARCH_ARM_CORTEX_A + select RT_USING_COMPONENTS_INIT + select RT_USING_USER_MAIN + select RT_USING_GIC_V3 + select TARGET_ARMV8_AARCH32 + select USE_AARCH64_L1_TO_AARCH32 + default y + +menu "Standalone Setting" + config TARGET_ARMV8_AARCH32 + bool "Armv8 Aarch32" + default y + + config USE_AARCH64_L1_TO_AARCH32 + bool + prompt "Use Aarch64 L1 to Aarch32 code" + default y + help + Use the Aarch64 to Aarch32 mode function + + source "$STANDALONE_DIR/board/Kconfig" + source "$STANDALONE_DIR/drivers/Kconfig" + source "$STANDALONE_DIR/common/Kconfig" + +endmenu + diff --git a/bsp/phytium/aarch32/README.md b/bsp/phytium/aarch32/README.md new file mode 100644 index 0000000000..7dcd689949 --- /dev/null +++ b/bsp/phytium/aarch32/README.md @@ -0,0 +1,108 @@ + +# AARCH32 工作模式使用 + +- 当开发者需要基于 Phytium 系列芯片进行开发时,可以从以下几个步骤出发配置芯片 + + +## 1. 如何选择芯片 + +- Windows Env 环境下 + +```shell + menuconfig +``` + +- Linux 环境下 + +```shell + scons --menuconfig +``` + +开发者通过以下选择进行配置 + +``` +Standalone Setting > Board Configuration > Chip +``` + +![](./figures/chip_select.png) +![](./figures/phytium_cpu_select.png) + +## 2. 如何选择驱动 + + +```shell + scons --menuconfig +``` + +开发者通过以下选项进行驱动的使能 + +``` +Hardware Drivers > On-chip Peripheral Drivers +``` + +![](./figures/select_driver.png) + + +## 3. 开启SDK中内部调试信息 + + +```shell + scons --menuconfig +``` + +开发者通过以下选项进行调试信息等级的设置 + +![](./figures/select_debug_info.png) + + + +## 4. 编译程序 + +```shell + scons -c + scons +``` + +- 完成编译之后目录下将会生成以下几个文件 + +``` +rtthread_a32.bin +rtthread_a32.elf +rtthread_a32.map +``` + +## 5. 打包导出工程源代码 + + +- 指定工程名和路径,打包RT-Thread内核和Phytium BSP代码,可以导出一个工程工程 +``` +python ./export_project.py -n=phytium-a32 -o=D:/proj/rt-thread-e2000/phytium-a32 +``` + +![](./figures/export_project.png) + + +- 进入打包工程的目录,修改工程根目录 Kconfig 中的路径 BSP_DIR 和 STANDALONE_DIR +> env 环境中的 menuconfig 不会调用 SConstruct 修改路径环境变量,因此需要手动修改路径 + +``` +config BSP_DIR + string + option env="BSP_ROOT" + default "." + +config STANDALONE_DIR + string + option env="STANDALONE_DIR" + default "libraries/standalone" +``` + +- 输入 menuconfig 和 scons 完成编译 + + +## 6. 将工程导入 RT-Studio + +- 在 RT-Studio 使用功能`RT-Thread Bsp 到工作空间`,导入 5. 中导出的 BSP 工程 +- 设置 BSP 工程的交叉编译链后进行后续开发 + +![](./figures/import_project.png) \ No newline at end of file diff --git a/bsp/phytium/aarch32/SConscript b/bsp/phytium/aarch32/SConscript new file mode 100644 index 0000000000..4c815c49b8 --- /dev/null +++ b/bsp/phytium/aarch32/SConscript @@ -0,0 +1,15 @@ +# RT-Thread building script for bridge + +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/phytium/aarch32/SConstruct b/bsp/phytium/aarch32/SConstruct new file mode 100644 index 0000000000..2d1eaf98f7 --- /dev/null +++ b/bsp/phytium/aarch32/SConstruct @@ -0,0 +1,58 @@ +import os +import sys +import rtconfig + +IS_EXPORTED = False + +# setup RT-Thread Root Path +if os.getenv('RTT_ROOT'): + RTT_ROOT = os.getenv('RTT_ROOT') +else: + RTT_ROOT = os.getcwd() + '/../../..' + +sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')] +try: + from building import * +except: + print('Cannot found RT-Thread root directory, please check RTT_ROOT') + print(RTT_ROOT) + exit(-1) + +if RTT_ROOT == 'rt-thread': + IS_EXPORTED = True # if kenrel and bsp has been exported by export_project.py + +# setup Phytium BSP Root Path +if IS_EXPORTED: + BSP_ROOT = '.' +else: + BSP_ROOT = RTT_ROOT + '/bsp/phytium' + +TARGET = 'rtthread_a32.' + 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('BSP_ROOT') +Export('rtconfig') + +# prepare building environment +objs = PrepareBuilding(env, RTT_ROOT, has_libcpu = False) + +if not IS_EXPORTED: # if project is not exported, libraries and board need to manually add + # include libraries + objs.extend(SConscript(os.path.join(BSP_ROOT + '/libraries', 'SConscript'))) + + # include board + objs.extend(SConscript(os.path.join(BSP_ROOT + '/board', 'SConscript'))) + +# make a building +DoBuilding(TARGET, objs) + diff --git a/bsp/phytium/aarch32/applications/SConscript b/bsp/phytium/aarch32/applications/SConscript new file mode 100644 index 0000000000..01eb940dfb --- /dev/null +++ b/bsp/phytium/aarch32/applications/SConscript @@ -0,0 +1,11 @@ +Import('RTT_ROOT') +Import('rtconfig') +from building import * + +cwd = os.path.join(str(Dir('#')), 'applications') +src = Glob('*.c') +CPPPATH = [cwd, str(Dir('#'))] + +group = DefineGroup('Applications', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/phytium/aarch32/applications/main.c b/bsp/phytium/aarch32/applications/main.c new file mode 100644 index 0000000000..e19779e113 --- /dev/null +++ b/bsp/phytium/aarch32/applications/main.c @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include +#include + +#include + +#ifdef RT_USING_SMP + +struct rt_thread test_core[RT_CPUS_NR]; +static char *core_thread_name[8] = +{ + "core0_test", + "core1_test", + "core2_test", + "core3_test", + "core4_test", + "core5_test", + "core6_test", + "core7_test" +}; +static rt_uint8_t core_stack[RT_CPUS_NR][1024]; + +static void demo_core_thread(void *parameter) +{ + rt_base_t level; + while (1) + { + /* code */ + level = rt_cpus_lock(); + rt_kprintf("Hi, core%d \r\n", rt_hw_cpu_id()); + rt_cpus_unlock(level); + rt_thread_mdelay(2000000); + } +} + +void demo_core(void) +{ + rt_ubase_t i; + rt_ubase_t cpu_id = 0; + for (i = 0; i < RT_CPUS_NR; i++) + { + cpu_id = i; + rt_thread_init(&test_core[i], + core_thread_name[i], + demo_core_thread, + RT_NULL, + &core_stack[i], + 1024, + 20, + 32); + + rt_thread_control(&test_core[i], RT_THREAD_CTRL_BIND_CPU, (void *)cpu_id); + rt_thread_startup(&test_core[i]); + } +} +#endif + +int main(void) +{ +#ifdef RT_USING_SMP + demo_core(); +#endif + return RT_EOK; +} + diff --git a/bsp/phytium/aarch32/boot/SConscript b/bsp/phytium/aarch32/boot/SConscript new file mode 100644 index 0000000000..c05e6a119f --- /dev/null +++ b/bsp/phytium/aarch32/boot/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.S') + Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('AARCH32-BOOT', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/phytium/aarch32/boot/aarch32_boot.S b/bsp/phytium/aarch32/boot/aarch32_boot.S new file mode 100644 index 0000000000..c1e3bdf449 --- /dev/null +++ b/bsp/phytium/aarch32/boot/aarch32_boot.S @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +.global _boot +.set FPEXC_EN, 0x40000000 /* FPU enable bit, (1 << 30) */ +.org 0 +.text + +.section .boot,"ax" + +/* switch from aarch64-el2 to aarch32-el1 */ +_boot: +Startup_Aarch32: + .long 0xd5384240 /* mrs x0, currentel */ + .long 0xd342fc00 /* lsr x0, x0, #2 */ + .long 0x92400400 /* and x0, x0, #0x3 */ + .long 0xf1000c1f /* cmp x0, #0x3 */ + .long 0x540003a1 /* b.ne 1d0080c4 */ + +el3_mode: + .long 0xd53ecca0 /* mrs x0, s3_6_c12_c12_5 - ICC_SRE_EL3 */ + .long 0xb2400c00 /* orr x0, x0, #0xf */ + .long 0xd51ecca0 /* msr s3_6_c12_c12_5, x0 */ + .long 0xd5033fdf /* isb */ + .long 0xd53cc9a0 /* mrs x0, s3_4_c12_c9_5 - ICC_SRE_EL2 */ + .long 0xb2400c00 /* orr x0, x0, #0xf */ + .long 0xd51cc9a0 /* msr s3_4_c12_c9_5, x0 */ + .long 0xd5033fdf /* isb */ + .long 0xd538cca0 /* mrs x0, s3_0_c12_c12_5 - ICC_SRE_EL1 */ + .long 0xb2400000 /* orr x0, x0, #0x1 */ + .long 0xd518cca0 /* msr s3_0_c12_c12_5, x0 */ + .long 0xd5033fdf /* isb */ + + .long 0xd2803620 /* mov x0, #0x1b1 */ + .long 0xd51e1100 /* msr scr_el3, x0 */ + .long 0xd2867fe0 /* mov x0, #0x33ff */ + .long 0xd51c1140 /* msr cptr_el2, x0 */ + .long 0xd2810000 /* mov x0, #0x800 */ + .long 0xf2a61a00 /* movk x0, #0x30d0, lsl #16 */ + .long 0xd5181000 /* msr sctlr_el1, x0 */ + .long 0x910003e0 /* mov x0, sp */ + .long 0xd51c4100 /* msr sp_el1, x0 */ + .long 0xd53ec000 /* mrs x0, vbar_el3 */ + .long 0xd518c000 /* msr vbar_el1, x0 */ + .long 0xd2803a60 /* mov x0, #0x1d3 */ + .long 0xd51e4000 /* msr spsr_el3, x0 */ + .long 0x10000500 /* adr x0, 1d008158 */ + .long 0xd51e4020 /* msr elr_el3, x0 */ + .long 0xd69f03e0 /* eret */ + +el2_mode: + .long 0xd53cc9a0 /* mrs x0, s3_4_c12_c9_5 - ICC_SRE_EL2 */ + .long 0xb2400c00 /* orr x0, x0, #0xf */ + .long 0xd51cc9a0 /* msr s3_4_c12_c9_5, x0 */ + .long 0xd5033fdf /* isb */ + .long 0xd538cca0 /* mrs x0, s3_0_c12_c12_5 - ICC_SRE_EL1 */ + .long 0xb2400000 /* orr x0, x0, #0x1 */ + .long 0xd518cca0 /* msr s3_0_c12_c12_5, x0 */ + .long 0xd5033fdf /* isb */ + .long 0xd53ce100 /* mrs x0, cnthctl_el2 */ + .long 0xb2400400 /* orr x0, x0, #0x3 */ + .long 0xd51ce100 /* msr cnthctl_el2, x0 */ + .long 0xd51ce07f /* msr cntvoff_el2, xzr */ + .long 0xd5380000 /* mrs x0, midr_el1 */ + .long 0xd53800a1 /* mrs x1, mpidr_el1 */ + .long 0xd51c0000 /* msr vpidr_el2, x0 */ + .long 0xd51c00a1 /* msr vmpidr_el2, x1 */ + .long 0xd2867fe0 /* mov x0, #0x33ff */ + .long 0xd51c1140 /* msr cptr_el2, x0 */ + .long 0xd51c117f /* msr hstr_el2, xzr */ + .long 0xd2a00600 /* mov x0, #0x300000 */ + .long 0xd5181040 /* msr cpacr_el1, x0 */ + .long 0xd2800000 /* mov x0, #0x0 */ + .long 0xb2630000 /* orr x0, x0, #0x20000000 */ + .long 0xd51c1100 /* msr hcr_el2, x0 */ + .long 0xd53c1100 /* mrs x0, hcr_el2 */ + .long 0xd2810000 /* mov x0, #0x800 */ + .long 0xf2a61a00 /* movk x0, #0x30d0, lsl #16 */ + .long 0xd5181000 /* msr sctlr_el1, x0 */ + .long 0x910003e0 /* mov x0, sp */ + .long 0xd51c4100 /* msr sp_el1, x0 */ + .long 0xd53cc000 /* mrs x0, vbar_el2 */ + .long 0xd518c000 /* msr vbar_el1, x0 */ + .long 0xd2803a60 /* mov x0, #0x1d3 */ + .long 0xd51c4000 /* msr spsr_el2, x0 */ + .long 0x10000060 /* adr x0, 1d008158 */ + .long 0xd51c4020 /* msr elr_el2, x0 */ + .long 0xd69f03e0 /* eret */ + +el1_mode: + mov r0, #0 + mov r1, #0 + mov r2, #0 + mov r3, #0 + mov r4, #0 + mov r5, #0 + mov r6, #0 + mov r7, #0 + mov r8, #0 + mov r9, #0 + mov r10, #0 + mov r11, #0 + mov r12, #0 + mcr p15, 0, r0, c1, c0, 0 /* reset control register */ + isb + + /* enable vfp, therefore f_prink workable */ + vmrs r1, FPEXC /* read the exception register */ + orr r1,r1, #FPEXC_EN /* set VFP enable bit, leave the others in orig state */ + vmsr FPEXC, r1 /* write back the exception register */ + + bl system_vectors /* jump to libcpu/arm/cortex-a/vector_gcc.S */ + diff --git a/bsp/phytium/aarch32/export_project.py b/bsp/phytium/aarch32/export_project.py new file mode 100644 index 0000000000..d28e6d7430 --- /dev/null +++ b/bsp/phytium/aarch32/export_project.py @@ -0,0 +1,37 @@ +import os +import shutil +import argparse + +parser = argparse.ArgumentParser() +parser.description='please enter two parameters and ...' +parser.add_argument("-n", "--name", help="project name", type=str, default="phytium-a32") +parser.add_argument("-o", "--output", help="export path", type=str, default="./phytium-a32") +args = parser.parse_args() + +print('=== Exporting Phytium BSP for RT-Studio ====') + +board_src_path = os.path.abspath(r'../board') +librs_src_path = os.path.abspath(r'../libraries') + +board_dst_path = os.path.abspath(r'./board') +librs_dst_path = os.path.abspath(r'./libraries') + +print(' Copying BSP board from {} to {}'.format(board_src_path, board_dst_path)) +print(' Copying BSP libraries from {} to {}'.format(librs_src_path, librs_dst_path)) + +if os.path.exists(board_dst_path): + shutil.rmtree(board_dst_path) + +if os.path.exists(librs_dst_path): + shutil.rmtree(librs_dst_path) + +shutil.copytree(board_src_path, board_dst_path) +shutil.copytree(librs_src_path, librs_dst_path) + +os.system('scons --dist-ide --project-name={} --project-path={}'.format(args.name, args.output)) + +if os.path.exists(board_dst_path): + shutil.rmtree(board_dst_path) + +if os.path.exists(librs_dst_path): + shutil.rmtree(librs_dst_path) \ No newline at end of file diff --git a/bsp/phytium/aarch32/figures/chip_select.png b/bsp/phytium/aarch32/figures/chip_select.png new file mode 100644 index 0000000000..26878fe235 Binary files /dev/null and b/bsp/phytium/aarch32/figures/chip_select.png differ diff --git a/bsp/phytium/aarch32/figures/export_project.png b/bsp/phytium/aarch32/figures/export_project.png new file mode 100644 index 0000000000..d150dcd3ca Binary files /dev/null and b/bsp/phytium/aarch32/figures/export_project.png differ diff --git a/bsp/phytium/aarch32/figures/import_project.png b/bsp/phytium/aarch32/figures/import_project.png new file mode 100644 index 0000000000..5aa91d058e Binary files /dev/null and b/bsp/phytium/aarch32/figures/import_project.png differ diff --git a/bsp/phytium/aarch32/figures/phytium_cpu_select.png b/bsp/phytium/aarch32/figures/phytium_cpu_select.png new file mode 100644 index 0000000000..40af2b41c6 Binary files /dev/null and b/bsp/phytium/aarch32/figures/phytium_cpu_select.png differ diff --git a/bsp/phytium/aarch32/figures/select_debug_info.png b/bsp/phytium/aarch32/figures/select_debug_info.png new file mode 100644 index 0000000000..8d22436940 Binary files /dev/null and b/bsp/phytium/aarch32/figures/select_debug_info.png differ diff --git a/bsp/phytium/aarch32/figures/select_driver.png b/bsp/phytium/aarch32/figures/select_driver.png new file mode 100644 index 0000000000..3fa21b7e8d Binary files /dev/null and b/bsp/phytium/aarch32/figures/select_driver.png differ diff --git a/bsp/phytium/aarch32/link.lds b/bsp/phytium/aarch32/link.lds new file mode 100644 index 0000000000..d1acac738f --- /dev/null +++ b/bsp/phytium/aarch32/link.lds @@ -0,0 +1,116 @@ +OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm") +OUTPUT_ARCH(arm) + +ENTRY(_boot) + +SECTIONS +{ + . = 0x80100000; + + .text : + { + + *(.boot) + . = ALIGN(64); + + *(.vectors) + *(.text) + *(.text.*) + + /* section information for finsh shell */ + . = ALIGN(4); + __fsymtab_start = .; + KEEP(*(FSymTab)) + __fsymtab_end = .; + . = ALIGN(4); + __vsymtab_start = .; + KEEP(*(VSymTab)) + __vsymtab_end = .; + . = ALIGN(4); + + /* section information for modules */ + . = ALIGN(4); + __rtmsymtab_start = .; + KEEP(*(RTMSymTab)) + __rtmsymtab_end = .; + + /* section information for initialization */ + . = ALIGN(4); + __rt_init_start = .; + KEEP(*(SORT(.rti_fn*))) + __rt_init_end = .; + } =0 + __text_end = .; + + __rodata_start = .; + .rodata : { *(.rodata) *(.rodata.*) } + __rodata_end = .; + + . = ALIGN(4); + .ctors : + { + PROVIDE(__ctors_start__ = .); + /* new GCC version uses .init_array */ + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE(__ctors_end__ = .); + } + + .dtors : + { + PROVIDE(__dtors_start__ = .); + KEEP(*(SORT(.dtors.*))) + KEEP(*(.dtors)) + PROVIDE(__dtors_end__ = .); + } + + . = ALIGN(16 * 1024); + .l1_page_table : + { + __l1_page_table_start = .; + . += 16K; + } + + . = ALIGN(8); + __data_start = .; + .data : + { + *(.data) + *(.data.*) + } + __data_end = .; + + . = ALIGN(8); + __bss_start = .; + .bss : + { + *(.bss) + *(.bss.*) + *(COMMON) + . = ALIGN(4); + } + . = ALIGN(4); + __bss_end = .; + + .heap : + { + . = ALIGN(8); + __end__ = .; + PROVIDE(end = .); + __HeapBase = .; + . += 0x400; + __HeapLimit = .; + __heap_limit = .; /* Add for _sbrk */ + } + + /* Stabs debugging sections. */ + .stab 0 : { *(.stab) } + .stabstr 0 : { *(.stabstr) } + .stab.excl 0 : { *(.stab.excl) } + .stab.exclstr 0 : { *(.stab.exclstr) } + .stab.index 0 : { *(.stab.index) } + .stab.indexstr 0 : { *(.stab.indexstr) } + .comment 0 : { *(.comment) } + + _end = .; +} diff --git a/bsp/phytium/aarch32/rtconfig.h b/bsp/phytium/aarch32/rtconfig.h new file mode 100644 index 0000000000..cdb1dfd16b --- /dev/null +++ b/bsp/phytium/aarch32/rtconfig.h @@ -0,0 +1,261 @@ +#ifndef RT_CONFIG_H__ +#define RT_CONFIG_H__ + +/* Automatically generated file; DO NOT EDIT. */ +/* RT-Thread Project Configuration */ + +/* RT-Thread Kernel */ + +#define RT_NAME_MAX 8 +#define RT_USING_SMP +#define RT_CPUS_NR 4 +#define RT_ALIGN_SIZE 4 +#define RT_THREAD_PRIORITY_32 +#define RT_THREAD_PRIORITY_MAX 32 +#define RT_TICK_PER_SECOND 1000 +#define RT_USING_OVERFLOW_CHECK +#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 256 +#define SYSTEM_THREAD_STACK_SIZE 256 +#define RT_USING_TIMER_SOFT +#define RT_TIMER_THREAD_PRIO 4 +#define RT_TIMER_THREAD_STACK_SIZE 512 + +/* kservice optimization */ + +#define RT_KSERVICE_USING_STDLIB +#define RT_DEBUG + +/* Inter-Thread communication */ + +#define RT_USING_SEMAPHORE +#define RT_USING_MUTEX +#define RT_USING_EVENT +#define RT_USING_MAILBOX +#define RT_USING_MESSAGEQUEUE + +/* Memory Management */ + +#define RT_USING_MEMPOOL +#define RT_USING_SMALL_MEM +#define RT_USING_SMALL_MEM_AS_HEAP +#define RT_USING_HEAP + +/* Kernel Device Object */ + +#define RT_USING_DEVICE +#define RT_USING_CONSOLE +#define RT_CONSOLEBUF_SIZE 128 +#define RT_CONSOLE_DEVICE_NAME "uart1" +#define RT_VER_NUM 0x50000 +#define ARCH_ARM +#define RT_USING_CPU_FFS +#define ARCH_ARM_CORTEX_A +#define RT_USING_GIC_V3 + +/* RT-Thread Components */ + +#define RT_USING_COMPONENTS_INIT +#define RT_USING_USER_MAIN +#define RT_MAIN_THREAD_STACK_SIZE 2048 +#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 4096 +#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 +#define RT_USING_DFS +#define DFS_USING_POSIX +#define DFS_USING_WORKDIR +#define DFS_FILESYSTEMS_MAX 4 +#define DFS_FILESYSTEM_TYPES_MAX 4 +#define DFS_FD_MAX 16 + +/* Device Drivers */ + +#define RT_USING_DEVICE_IPC +#define RT_USING_SERIAL +#define RT_USING_SERIAL_V1 +#define RT_SERIAL_USING_DMA +#define RT_SERIAL_RB_BUFSZ 64 +#define RT_USING_PIN + +/* Using USB */ + + +/* C/C++ and POSIX layer */ + +#define RT_LIBC_DEFAULT_TIMEZONE 8 + +/* POSIX (Portable Operating System Interface) layer */ + + +/* Interprocess Communication (IPC) */ + + +/* Socket is in the 'Network' category */ + + +/* Network */ + + +/* Utilities */ + + +/* RT-Thread Utestcases */ + + +/* RT-Thread online packages */ + +/* IoT - internet of things */ + + +/* Wi-Fi */ + +/* Marvell WiFi */ + + +/* Wiced WiFi */ + + +/* IoT Cloud */ + + +/* security packages */ + + +/* language packages */ + +/* JSON: JavaScript Object Notation, a lightweight data-interchange format */ + + +/* XML: Extensible Markup Language */ + + +/* multimedia packages */ + +/* LVGL: powerful and easy-to-use embedded GUI library */ + + +/* u8g2: a monochrome graphic library */ + + +/* PainterEngine: A cross-platform graphics application framework written in C language */ + + +/* tools packages */ + + +/* system packages */ + +/* enhanced kernel services */ + + +/* acceleration: Assembly language or algorithmic acceleration packages */ + + +/* CMSIS: ARM Cortex-M Microcontroller Software Interface Standard */ + + +/* Micrium: Micrium software products porting for RT-Thread */ + + +/* peripheral libraries and drivers */ + + +/* Kendryte SDK */ + + +/* AI packages */ + + +/* miscellaneous packages */ + +/* project laboratory */ + +/* samples: kernel and components samples */ + + +/* entertainment: terminal games and other interesting software packages */ + + +/* Arduino libraries */ + + +/* Projects */ + + +/* Sensors */ + + +/* Display */ + + +/* Timing */ + + +/* Data Processing */ + + +/* Data Storage */ + +/* Communication */ + + +/* Device Control */ + + +/* Other */ + +/* Signal IO */ + + +/* Uncategorized */ + +/* Hardware Drivers */ + +/* On-chip Peripheral Drivers */ + +#define BSP_USING_UART +#define RT_USING_UART1 + +/* Board extended module Drivers */ + +#define PHYTIUM_ARCH_AARCH32 + +/* Standalone Setting */ + +#define TARGET_ARMV8_AARCH32 +#define USE_AARCH64_L1_TO_AARCH32 + +/* Board Configuration */ + +#define TARGET_E2000Q +#define TARGET_E2000 +#define DEFAULT_DEBUG_PRINT_UART1 + +/* Components Configuration */ + +#define USE_GIC +#define ENABLE_GICV3 +#define USE_SERIAL + +/* Usart Configuration */ + +#define ENABLE_Pl011_UART +#define LOG_ERROR +#define USE_DEFAULT_INTERRUPT_CONFIG +#define INTERRUPT_ROLE_MASTER + +#endif diff --git a/bsp/phytium/aarch32/rtconfig.py b/bsp/phytium/aarch32/rtconfig.py new file mode 100644 index 0000000000..a5202911db --- /dev/null +++ b/bsp/phytium/aarch32/rtconfig.py @@ -0,0 +1,68 @@ +import os +import rtconfig + +# toolchains options +ARCH='arm' +CPU='cortex-a' +CROSS_TOOL='gcc' + +if os.getenv('RTT_ROOT'): + RTT_ROOT = os.getenv('RTT_ROOT') +else: + RTT_ROOT = r'../../..' + +if os.getenv('RTT_CC'): + CROSS_TOOL = os.getenv('RTT_CC') + +# only support GNU GCC compiler. +PLATFORM = 'gcc' +EXEC_PATH = r'/usr/lib/arm-none-eabi/bin' +if os.getenv('AARCH32_CROSS_PATH'): + EXEC_PATH = os.getenv('AARCH32_CROSS_PATH') + print('EXEC_PATH = {}'.format(EXEC_PATH)) +else: + print('AARCH32_CROSS_PATH not found') + +BUILD = 'debug' + +LIBPATH = EXEC_PATH + r'/../lib' + +if PLATFORM == 'gcc': + # toolchains + PREFIX = 'arm-none-eabi-' + 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' + STRIP = PREFIX + 'strip' + + DEVICE = ' -g -DGUEST -ffreestanding -Wextra -g -mfpu=crypto-neon-fp-armv8 -mfloat-abi=softfp -march=armv8-a -fdiagnostics-color=always' + + # CFLAGS = DEVICE + ' -Wall' + CFLAGS = DEVICE + AFLAGS = ' -c'+ DEVICE + ' -fsingle-precision-constant -fno-builtin -x assembler-with-cpp -D__ASSEMBLY__' + LINK_SCRIPT = 'link.lds' + LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread_a32.map,-cref,-u,system_vectors'+\ + ' -T %s' % LINK_SCRIPT + + CPATH = '' + LPATH = LIBPATH + + # generate debug info in all cases + AFLAGS += ' -gdwarf-2' + CFLAGS += ' -g -gdwarf-2' + + if BUILD == 'debug': + CFLAGS += ' -O0' + else: + CFLAGS += ' -O2' + + CXXFLAGS = CFLAGS + + POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread_a32.bin\n' +\ + SIZE + ' $TARGET \n' diff --git a/bsp/phytium/aarch32/sdkconfig.h b/bsp/phytium/aarch32/sdkconfig.h new file mode 100644 index 0000000000..8913e55fd9 --- /dev/null +++ b/bsp/phytium/aarch32/sdkconfig.h @@ -0,0 +1,75 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: sdkconfig.h + * Date: 2022-10-13 15:53:46 + * LastEditTime: 2022-10-13 15:53:46 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + +#ifndef SDK_CONFIG_H__ +#define SDK_CONFIG_H__ + +#include "rtconfig.h" + + +/* arch */ + +#if defined(TARGET_ARMV8_AARCH32) + #define CONFIG_TARGET_ARMV8_AARCH32 +#endif + +#if defined(USE_AARCH64_L1_TO_AARCH32) + #define CONFIG_USE_AARCH64_L1_TO_AARCH32 +#endif + +/* board */ + +/* E2000 */ + +#if defined(TARGET_E2000) + #define CONFIG_TARGET_E2000 +#endif + + +/* debug */ + +#ifdef LOG_VERBOS + #define CONFIG_LOG_VERBOS +#endif + +#ifdef LOG_ERROR + #define CONFIG_LOG_ERROR +#endif + +#ifdef LOG_WARN + #define CONFIG_LOG_WARN +#endif + +#ifdef LOG_INFO + #define CONFIG_LOG_INFO +#endif + +#ifdef LOG_DEBUG + #define CONFIG_LOG_DEBUG +#endif + +#ifdef BOOTUP_DEBUG_PRINTS + #define CONFIG_BOOTUP_DEBUG_PRINTS +#endif + +#endif diff --git a/bsp/phytium/aarch64/.config b/bsp/phytium/aarch64/.config new file mode 100644 index 0000000000..a98a9cbc22 --- /dev/null +++ b/bsp/phytium/aarch64/.config @@ -0,0 +1,922 @@ +# +# Automatically generated file; DO NOT EDIT. +# RT-Thread Project Configuration +# + +# +# RT-Thread Kernel +# +CONFIG_RT_NAME_MAX=16 +# CONFIG_RT_USING_ARCH_DATA_TYPE is not set +CONFIG_RT_USING_SMP=y +CONFIG_RT_CPUS_NR=4 +CONFIG_RT_ALIGN_SIZE=4 +# CONFIG_RT_THREAD_PRIORITY_8 is not set +CONFIG_RT_THREAD_PRIORITY_32=y +# CONFIG_RT_THREAD_PRIORITY_256 is not set +CONFIG_RT_THREAD_PRIORITY_MAX=32 +CONFIG_RT_TICK_PER_SECOND=100 +CONFIG_RT_USING_OVERFLOW_CHECK=y +CONFIG_RT_USING_HOOK=y +CONFIG_RT_HOOK_USING_FUNC_PTR=y +CONFIG_RT_USING_IDLE_HOOK=y +CONFIG_RT_IDLE_HOOK_LIST_SIZE=4 +CONFIG_IDLE_THREAD_STACK_SIZE=4096 +CONFIG_SYSTEM_THREAD_STACK_SIZE=4096 +CONFIG_RT_USING_TIMER_SOFT=y +CONFIG_RT_TIMER_THREAD_PRIO=4 +CONFIG_RT_TIMER_THREAD_STACK_SIZE=4096 + +# +# kservice optimization +# +CONFIG_RT_KSERVICE_USING_STDLIB=y +# CONFIG_RT_KSERVICE_USING_STDLIB_MEMORY is not set +# CONFIG_RT_KSERVICE_USING_TINY_SIZE is not set +# CONFIG_RT_USING_TINY_FFS is not set +CONFIG_RT_KPRINTF_USING_LONGLONG=y +CONFIG_RT_DEBUG=y +# CONFIG_RT_DEBUG_COLOR is not set +# CONFIG_RT_DEBUG_INIT_CONFIG is not set +# CONFIG_RT_DEBUG_THREAD_CONFIG is not set +# CONFIG_RT_DEBUG_SCHEDULER_CONFIG is not set +# CONFIG_RT_DEBUG_IPC_CONFIG is not set +# CONFIG_RT_DEBUG_TIMER_CONFIG is not set +# CONFIG_RT_DEBUG_IRQ_CONFIG is not set +# CONFIG_RT_DEBUG_MEM_CONFIG is not set +# CONFIG_RT_DEBUG_SLAB_CONFIG is not set +# CONFIG_RT_DEBUG_MEMHEAP_CONFIG is not set +# CONFIG_RT_DEBUG_MODULE_CONFIG is not set + +# +# Inter-Thread communication +# +CONFIG_RT_USING_SEMAPHORE=y +CONFIG_RT_USING_MUTEX=y +CONFIG_RT_USING_EVENT=y +CONFIG_RT_USING_MAILBOX=y +CONFIG_RT_USING_MESSAGEQUEUE=y +# CONFIG_RT_USING_SIGNALS is not set + +# +# Memory Management +# +CONFIG_RT_USING_MEMPOOL=y +CONFIG_RT_USING_SMALL_MEM=y +# CONFIG_RT_USING_SLAB is not set +# CONFIG_RT_USING_MEMHEAP is not set +CONFIG_RT_USING_SMALL_MEM_AS_HEAP=y +# CONFIG_RT_USING_MEMHEAP_AS_HEAP is not set +# CONFIG_RT_USING_SLAB_AS_HEAP is not set +# CONFIG_RT_USING_USERHEAP is not set +# CONFIG_RT_USING_NOHEAP is not set +# CONFIG_RT_USING_MEMTRACE is not set +# CONFIG_RT_USING_HEAP_ISR is not set +CONFIG_RT_USING_HEAP=y + +# +# Kernel Device Object +# +CONFIG_RT_USING_DEVICE=y +# CONFIG_RT_USING_DEVICE_OPS is not set +# CONFIG_RT_USING_INTERRUPT_INFO is not set +CONFIG_RT_USING_CONSOLE=y +CONFIG_RT_CONSOLEBUF_SIZE=128 +CONFIG_RT_CONSOLE_DEVICE_NAME="uart1" +CONFIG_RT_VER_NUM=0x50000 +CONFIG_ARCH_CPU_64BIT=y +# CONFIG_RT_USING_CPU_FFS is not set +CONFIG_ARCH_ARMV8=y +# CONFIG_ARCH_CPU_STACK_GROWS_UPWARD is not set + +# +# RT-Thread Components +# +CONFIG_RT_USING_COMPONENTS_INIT=y +CONFIG_RT_USING_USER_MAIN=y +CONFIG_RT_MAIN_THREAD_STACK_SIZE=4096 +CONFIG_RT_MAIN_THREAD_PRIORITY=10 +# CONFIG_RT_USING_LEGACY is not set +CONFIG_RT_USING_MSH=y +CONFIG_RT_USING_FINSH=y +CONFIG_FINSH_USING_MSH=y +CONFIG_FINSH_THREAD_NAME="tshell" +CONFIG_FINSH_THREAD_PRIORITY=20 +CONFIG_FINSH_THREAD_STACK_SIZE=4096 +CONFIG_FINSH_USING_HISTORY=y +CONFIG_FINSH_HISTORY_LINES=5 +CONFIG_FINSH_USING_SYMTAB=y +CONFIG_FINSH_CMD_SIZE=80 +CONFIG_MSH_USING_BUILT_IN_COMMANDS=y +CONFIG_FINSH_USING_DESCRIPTION=y +# CONFIG_FINSH_ECHO_DISABLE_DEFAULT is not set +# CONFIG_FINSH_USING_AUTH is not set +CONFIG_FINSH_ARG_MAX=10 +CONFIG_RT_USING_DFS=y +CONFIG_DFS_USING_POSIX=y +CONFIG_DFS_USING_WORKDIR=y +CONFIG_DFS_FILESYSTEMS_MAX=4 +CONFIG_DFS_FILESYSTEM_TYPES_MAX=4 +CONFIG_DFS_FD_MAX=16 +# CONFIG_RT_USING_DFS_MNTTABLE is not set +# CONFIG_RT_USING_DFS_ELMFAT is not set +# CONFIG_RT_USING_DFS_DEVFS is not set +# CONFIG_RT_USING_DFS_ROMFS is not set +# CONFIG_RT_USING_DFS_RAMFS is not set +# CONFIG_RT_USING_FAL is not set + +# +# Device Drivers +# +CONFIG_RT_USING_DEVICE_IPC=y +CONFIG_RT_USING_SYSTEM_WORKQUEUE=y +CONFIG_RT_SYSTEM_WORKQUEUE_STACKSIZE=8192 +CONFIG_RT_SYSTEM_WORKQUEUE_PRIORITY=23 +CONFIG_RT_USING_SERIAL=y +CONFIG_RT_USING_SERIAL_V1=y +# CONFIG_RT_USING_SERIAL_V2 is not set +CONFIG_RT_SERIAL_USING_DMA=y +CONFIG_RT_SERIAL_RB_BUFSZ=64 +# CONFIG_RT_USING_CAN is not set +# CONFIG_RT_USING_HWTIMER is not set +# CONFIG_RT_USING_CPUTIME is not set +# CONFIG_RT_USING_I2C is not set +# CONFIG_RT_USING_PHY is not set +CONFIG_RT_USING_PIN=y +# CONFIG_RT_USING_ADC is not set +# CONFIG_RT_USING_DAC is not set +# CONFIG_RT_USING_PWM is not set +# CONFIG_RT_USING_MTD_NOR is not set +# CONFIG_RT_USING_MTD_NAND is not set +# CONFIG_RT_USING_PM is not set +# CONFIG_RT_USING_RTC is not set +# CONFIG_RT_USING_SDIO is not set +# CONFIG_RT_USING_SPI is not set +# CONFIG_RT_USING_WDT is not set +# CONFIG_RT_USING_AUDIO is not set +# CONFIG_RT_USING_SENSOR is not set +# CONFIG_RT_USING_TOUCH is not set +# CONFIG_RT_USING_HWCRYPTO is not set +# CONFIG_RT_USING_PULSE_ENCODER is not set +# CONFIG_RT_USING_INPUT_CAPTURE is not set +# CONFIG_RT_USING_WIFI is not set + +# +# Using USB +# +# CONFIG_RT_USING_USB is not set +# CONFIG_RT_USING_USB_HOST is not set +# CONFIG_RT_USING_USB_DEVICE is not set + +# +# C/C++ and POSIX layer +# +CONFIG_RT_LIBC_DEFAULT_TIMEZONE=8 + +# +# POSIX (Portable Operating System Interface) layer +# +# CONFIG_RT_USING_POSIX_FS is not set +# CONFIG_RT_USING_POSIX_DELAY is not set +# CONFIG_RT_USING_POSIX_CLOCK is not set +# CONFIG_RT_USING_POSIX_TIMER is not set +# CONFIG_RT_USING_PTHREADS is not set +# CONFIG_RT_USING_MODULE is not set + +# +# Interprocess Communication (IPC) +# +# CONFIG_RT_USING_POSIX_PIPE is not set +# CONFIG_RT_USING_POSIX_MESSAGE_QUEUE is not set +# CONFIG_RT_USING_POSIX_MESSAGE_SEMAPHORE is not set + +# +# Socket is in the 'Network' category +# +# CONFIG_RT_USING_CPLUSPLUS is not set + +# +# Network +# +# CONFIG_RT_USING_SAL is not set +# CONFIG_RT_USING_NETDEV is not set +# CONFIG_RT_USING_LWIP is not set +# CONFIG_RT_USING_AT is not set + +# +# Utilities +# +# CONFIG_RT_USING_RYM is not set +# CONFIG_RT_USING_ULOG is not set +# CONFIG_RT_USING_UTEST is not set +# CONFIG_RT_USING_VAR_EXPORT is not set +# CONFIG_RT_USING_RT_LINK is not set +# CONFIG_RT_USING_VBUS is not set + +# +# RT-Thread Utestcases +# +# CONFIG_RT_USING_UTESTCASES is not set + +# +# RT-Thread online packages +# + +# +# IoT - internet of things +# +# CONFIG_PKG_USING_LWIP is not set +# CONFIG_PKG_USING_LORAWAN_DRIVER is not set +# CONFIG_PKG_USING_PAHOMQTT is not set +# CONFIG_PKG_USING_UMQTT is not set +# CONFIG_PKG_USING_WEBCLIENT is not set +# CONFIG_PKG_USING_WEBNET is not set +# CONFIG_PKG_USING_MONGOOSE is not set +# CONFIG_PKG_USING_MYMQTT is not set +# CONFIG_PKG_USING_KAWAII_MQTT is not set +# CONFIG_PKG_USING_BC28_MQTT is not set +# CONFIG_PKG_USING_WEBTERMINAL is not set +# CONFIG_PKG_USING_LIBMODBUS is not set +# CONFIG_PKG_USING_FREEMODBUS is not set +# CONFIG_PKG_USING_NANOPB is not set + +# +# Wi-Fi +# + +# +# Marvell WiFi +# +# CONFIG_PKG_USING_WLANMARVELL is not set + +# +# Wiced WiFi +# +# CONFIG_PKG_USING_WLAN_WICED is not set +# CONFIG_PKG_USING_RW007 is not set +# CONFIG_PKG_USING_COAP is not set +# CONFIG_PKG_USING_NOPOLL is not set +# CONFIG_PKG_USING_NETUTILS is not set +# CONFIG_PKG_USING_CMUX is not set +# CONFIG_PKG_USING_PPP_DEVICE is not set +# CONFIG_PKG_USING_AT_DEVICE is not set +# CONFIG_PKG_USING_ATSRV_SOCKET is not set +# CONFIG_PKG_USING_WIZNET is not set +# CONFIG_PKG_USING_ZB_COORDINATOR is not set + +# +# IoT Cloud +# +# CONFIG_PKG_USING_ONENET is not set +# CONFIG_PKG_USING_GAGENT_CLOUD is not set +# CONFIG_PKG_USING_ALI_IOTKIT is not set +# CONFIG_PKG_USING_AZURE is not set +# CONFIG_PKG_USING_TENCENT_IOT_EXPLORER is not set +# CONFIG_PKG_USING_JIOT-C-SDK is not set +# CONFIG_PKG_USING_UCLOUD_IOT_SDK is not set +# CONFIG_PKG_USING_JOYLINK is not set +# CONFIG_PKG_USING_EZ_IOT_OS is not set +# CONFIG_PKG_USING_IOTSHARP_SDK is not set +# CONFIG_PKG_USING_NIMBLE is not set +# CONFIG_PKG_USING_LLSYNC_SDK_ADAPTER is not set +# CONFIG_PKG_USING_OTA_DOWNLOADER is not set +# CONFIG_PKG_USING_IPMSG is not set +# CONFIG_PKG_USING_LSSDP is not set +# CONFIG_PKG_USING_AIRKISS_OPEN is not set +# CONFIG_PKG_USING_LIBRWS is not set +# CONFIG_PKG_USING_TCPSERVER is not set +# CONFIG_PKG_USING_PROTOBUF_C is not set +# CONFIG_PKG_USING_DLT645 is not set +# CONFIG_PKG_USING_QXWZ is not set +# CONFIG_PKG_USING_SMTP_CLIENT is not set +# CONFIG_PKG_USING_ABUP_FOTA is not set +# CONFIG_PKG_USING_LIBCURL2RTT is not set +# CONFIG_PKG_USING_CAPNP is not set +# CONFIG_PKG_USING_AGILE_TELNET is not set +# CONFIG_PKG_USING_NMEALIB is not set +# CONFIG_PKG_USING_PDULIB is not set +# CONFIG_PKG_USING_BTSTACK is not set +# CONFIG_PKG_USING_LORAWAN_ED_STACK is not set +# CONFIG_PKG_USING_WAYZ_IOTKIT is not set +# CONFIG_PKG_USING_MAVLINK is not set +# CONFIG_PKG_USING_BSAL is not set +# CONFIG_PKG_USING_AGILE_MODBUS is not set +# CONFIG_PKG_USING_AGILE_FTP is not set +# CONFIG_PKG_USING_EMBEDDEDPROTO is not set +# CONFIG_PKG_USING_RT_LINK_HW is not set +# CONFIG_PKG_USING_LORA_PKT_FWD is not set +# CONFIG_PKG_USING_LORA_GW_DRIVER_LIB is not set +# CONFIG_PKG_USING_LORA_PKT_SNIFFER is not set +# CONFIG_PKG_USING_HM is not set +# CONFIG_PKG_USING_SMALL_MODBUS is not set +# CONFIG_PKG_USING_NET_SERVER is not set +# CONFIG_PKG_USING_ZFTP is not set + +# +# security packages +# +# CONFIG_PKG_USING_MBEDTLS is not set +# CONFIG_PKG_USING_LIBSODIUM is not set +# CONFIG_PKG_USING_LIBHYDROGEN is not set +# CONFIG_PKG_USING_TINYCRYPT is not set +# CONFIG_PKG_USING_TFM is not set +# CONFIG_PKG_USING_YD_CRYPTO is not set + +# +# language packages +# + +# +# JSON: JavaScript Object Notation, a lightweight data-interchange format +# +# CONFIG_PKG_USING_CJSON is not set +# CONFIG_PKG_USING_LJSON is not set +# CONFIG_PKG_USING_RT_CJSON_TOOLS is not set +# CONFIG_PKG_USING_RAPIDJSON is not set +# CONFIG_PKG_USING_JSMN is not set +# CONFIG_PKG_USING_AGILE_JSMN is not set +# CONFIG_PKG_USING_PARSON is not set + +# +# XML: Extensible Markup Language +# +# CONFIG_PKG_USING_SIMPLE_XML is not set +# CONFIG_PKG_USING_EZXML is not set +# CONFIG_PKG_USING_LUATOS_SOC is not set +# CONFIG_PKG_USING_LUA is not set +# CONFIG_PKG_USING_JERRYSCRIPT is not set +# CONFIG_PKG_USING_MICROPYTHON is not set +# CONFIG_PKG_USING_PIKASCRIPT is not set +# CONFIG_PKG_USING_RTT_RUST is not set + +# +# multimedia packages +# + +# +# LVGL: powerful and easy-to-use embedded GUI library +# +# CONFIG_PKG_USING_LVGL is not set +# CONFIG_PKG_USING_LITTLEVGL2RTT is not set +# CONFIG_PKG_USING_LV_MUSIC_DEMO is not set +# CONFIG_PKG_USING_GUI_GUIDER_DEMO is not set + +# +# u8g2: a monochrome graphic library +# +# CONFIG_PKG_USING_U8G2_OFFICIAL is not set +# CONFIG_PKG_USING_U8G2 is not set +# CONFIG_PKG_USING_OPENMV is not set +# CONFIG_PKG_USING_MUPDF is not set +# CONFIG_PKG_USING_STEMWIN is not set +# CONFIG_PKG_USING_WAVPLAYER is not set +# CONFIG_PKG_USING_TJPGD is not set +# CONFIG_PKG_USING_PDFGEN is not set +# CONFIG_PKG_USING_HELIX is not set +# CONFIG_PKG_USING_AZUREGUIX is not set +# CONFIG_PKG_USING_TOUCHGFX2RTT is not set +# CONFIG_PKG_USING_NUEMWIN is not set +# CONFIG_PKG_USING_MP3PLAYER is not set +# CONFIG_PKG_USING_TINYJPEG is not set +# CONFIG_PKG_USING_UGUI is not set + +# +# PainterEngine: A cross-platform graphics application framework written in C language +# +# CONFIG_PKG_USING_PAINTERENGINE is not set +# CONFIG_PKG_USING_PAINTERENGINE_AUX is not set +# CONFIG_PKG_USING_MCURSES is not set +# CONFIG_PKG_USING_TERMBOX is not set +# CONFIG_PKG_USING_VT100 is not set +# CONFIG_PKG_USING_QRCODE is not set +# CONFIG_PKG_USING_GUIENGINE is not set + +# +# tools packages +# +# CONFIG_PKG_USING_CMBACKTRACE is not set +# CONFIG_PKG_USING_EASYFLASH is not set +# CONFIG_PKG_USING_EASYLOGGER is not set +# CONFIG_PKG_USING_SYSTEMVIEW is not set +# CONFIG_PKG_USING_SEGGER_RTT is not set +# CONFIG_PKG_USING_RDB is not set +# CONFIG_PKG_USING_ULOG_EASYFLASH is not set +# CONFIG_PKG_USING_ULOG_FILE is not set +# CONFIG_PKG_USING_LOGMGR is not set +# CONFIG_PKG_USING_ADBD is not set +# CONFIG_PKG_USING_COREMARK is not set +# CONFIG_PKG_USING_DHRYSTONE is not set +# CONFIG_PKG_USING_MEMORYPERF is not set +# CONFIG_PKG_USING_NR_MICRO_SHELL is not set +# CONFIG_PKG_USING_CHINESE_FONT_LIBRARY is not set +# CONFIG_PKG_USING_LUNAR_CALENDAR is not set +# CONFIG_PKG_USING_BS8116A is not set +# CONFIG_PKG_USING_GPS_RMC is not set +# CONFIG_PKG_USING_URLENCODE is not set +# CONFIG_PKG_USING_UMCN is not set +# CONFIG_PKG_USING_LWRB2RTT is not set +# CONFIG_PKG_USING_CPU_USAGE is not set +# CONFIG_PKG_USING_GBK2UTF8 is not set +# CONFIG_PKG_USING_VCONSOLE is not set +# CONFIG_PKG_USING_KDB is not set +# CONFIG_PKG_USING_WAMR is not set +# CONFIG_PKG_USING_MICRO_XRCE_DDS_CLIENT is not set +# CONFIG_PKG_USING_LWLOG is not set +# CONFIG_PKG_USING_ANV_TRACE is not set +# CONFIG_PKG_USING_ANV_MEMLEAK is not set +# CONFIG_PKG_USING_ANV_TESTSUIT is not set +# CONFIG_PKG_USING_ANV_BENCH is not set +# CONFIG_PKG_USING_DEVMEM is not set +# CONFIG_PKG_USING_REGEX is not set +# CONFIG_PKG_USING_MEM_SANDBOX is not set +# CONFIG_PKG_USING_SOLAR_TERMS is not set +# CONFIG_PKG_USING_GAN_ZHI is not set +# CONFIG_PKG_USING_FDT is not set +# CONFIG_PKG_USING_CBOX is not set +# CONFIG_PKG_USING_SNOWFLAKE is not set +# CONFIG_PKG_USING_HASH_MATCH is not set +# CONFIG_PKG_USING_FIRE_PID_CURVE is not set +# CONFIG_PKG_USING_ARMV7M_DWT_TOOL is not set +# CONFIG_PKG_USING_VOFA_PLUS is not set + +# +# system packages +# + +# +# enhanced kernel services +# +# CONFIG_PKG_USING_RT_MEMCPY_CM is not set +# CONFIG_PKG_USING_RT_KPRINTF_THREADSAFE is not set +# CONFIG_PKG_USING_RT_VSNPRINTF_FULL is not set + +# +# acceleration: Assembly language or algorithmic acceleration packages +# +# CONFIG_PKG_USING_QFPLIB_M0_FULL is not set +# CONFIG_PKG_USING_QFPLIB_M0_TINY is not set +# CONFIG_PKG_USING_QFPLIB_M3 is not set + +# +# CMSIS: ARM Cortex-M Microcontroller Software Interface Standard +# +# CONFIG_PKG_USING_CMSIS_5 is not set +# CONFIG_PKG_USING_CMSIS_RTOS1 is not set +# CONFIG_PKG_USING_CMSIS_RTOS2 is not set + +# +# Micrium: Micrium software products porting for RT-Thread +# +# CONFIG_PKG_USING_UCOSIII_WRAPPER is not set +# CONFIG_PKG_USING_UCOSII_WRAPPER is not set +# CONFIG_PKG_USING_UC_CRC is not set +# CONFIG_PKG_USING_UC_CLK is not set +# CONFIG_PKG_USING_UC_COMMON is not set +# CONFIG_PKG_USING_UC_MODBUS is not set +# CONFIG_PKG_USING_FREERTOS_WRAPPER is not set +# CONFIG_PKG_USING_CAIRO is not set +# CONFIG_PKG_USING_PIXMAN is not set +# CONFIG_PKG_USING_PARTITION is not set +# CONFIG_PKG_USING_PERF_COUNTER is not set +# CONFIG_PKG_USING_FLASHDB is not set +# CONFIG_PKG_USING_SQLITE is not set +# CONFIG_PKG_USING_RTI is not set +# CONFIG_PKG_USING_DFS_YAFFS is not set +# CONFIG_PKG_USING_LITTLEFS is not set +# CONFIG_PKG_USING_DFS_JFFS2 is not set +# CONFIG_PKG_USING_DFS_UFFS is not set +# CONFIG_PKG_USING_LWEXT4 is not set +# CONFIG_PKG_USING_THREAD_POOL is not set +# CONFIG_PKG_USING_ROBOTS is not set +# CONFIG_PKG_USING_EV is not set +# CONFIG_PKG_USING_SYSWATCH is not set +# CONFIG_PKG_USING_SYS_LOAD_MONITOR is not set +# CONFIG_PKG_USING_PLCCORE is not set +# CONFIG_PKG_USING_RAMDISK is not set +# CONFIG_PKG_USING_MININI is not set +# CONFIG_PKG_USING_QBOOT is not set +# CONFIG_PKG_USING_PPOOL is not set +# CONFIG_PKG_USING_OPENAMP is not set +# CONFIG_PKG_USING_LPM is not set +# CONFIG_PKG_USING_TLSF is not set +# CONFIG_PKG_USING_EVENT_RECORDER is not set +# CONFIG_PKG_USING_ARM_2D is not set +# CONFIG_PKG_USING_MCUBOOT is not set +# CONFIG_PKG_USING_TINYUSB is not set +# CONFIG_PKG_USING_CHERRYUSB is not set +# CONFIG_PKG_USING_KMULTI_RTIMER is not set +# CONFIG_PKG_USING_TFDB is not set +# CONFIG_PKG_USING_QPC is not set +# CONFIG_PKG_USING_AGILE_UPGRADE is not set + +# +# peripheral libraries and drivers +# +# CONFIG_PKG_USING_SENSORS_DRIVERS is not set +# CONFIG_PKG_USING_REALTEK_AMEBA is not set +# CONFIG_PKG_USING_SHT2X is not set +# CONFIG_PKG_USING_SHT3X is not set +# CONFIG_PKG_USING_ADT74XX is not set +# CONFIG_PKG_USING_AS7341 is not set +# CONFIG_PKG_USING_STM32_SDIO is not set +# CONFIG_PKG_USING_ESP_IDF is not set +# CONFIG_PKG_USING_ICM20608 is not set +# CONFIG_PKG_USING_BUTTON is not set +# CONFIG_PKG_USING_PCF8574 is not set +# CONFIG_PKG_USING_SX12XX is not set +# CONFIG_PKG_USING_SIGNAL_LED is not set +# CONFIG_PKG_USING_LEDBLINK is not set +# CONFIG_PKG_USING_LITTLED is not set +# CONFIG_PKG_USING_LKDGUI is not set +# CONFIG_PKG_USING_NRF5X_SDK is not set +# CONFIG_PKG_USING_NRFX is not set +# CONFIG_PKG_USING_WM_LIBRARIES is not set + +# +# Kendryte SDK +# +# CONFIG_PKG_USING_K210_SDK is not set +# CONFIG_PKG_USING_KENDRYTE_SDK is not set +# CONFIG_PKG_USING_INFRARED is not set +# CONFIG_PKG_USING_MULTI_INFRARED is not set +# CONFIG_PKG_USING_AGILE_BUTTON is not set +# CONFIG_PKG_USING_AGILE_LED is not set +# CONFIG_PKG_USING_AT24CXX is not set +# CONFIG_PKG_USING_MOTIONDRIVER2RTT is not set +# CONFIG_PKG_USING_AD7746 is not set +# CONFIG_PKG_USING_PCA9685 is not set +# CONFIG_PKG_USING_I2C_TOOLS is not set +# CONFIG_PKG_USING_NRF24L01 is not set +# CONFIG_PKG_USING_TOUCH_DRIVERS is not set +# CONFIG_PKG_USING_MAX17048 is not set +# CONFIG_PKG_USING_RPLIDAR is not set +# CONFIG_PKG_USING_AS608 is not set +# CONFIG_PKG_USING_RC522 is not set +# CONFIG_PKG_USING_WS2812B is not set +# CONFIG_PKG_USING_EMBARC_BSP is not set +# CONFIG_PKG_USING_EXTERN_RTC_DRIVERS is not set +# CONFIG_PKG_USING_MULTI_RTIMER is not set +# CONFIG_PKG_USING_MAX7219 is not set +# CONFIG_PKG_USING_BEEP is not set +# CONFIG_PKG_USING_EASYBLINK is not set +# CONFIG_PKG_USING_PMS_SERIES is not set +# CONFIG_PKG_USING_CAN_YMODEM is not set +# CONFIG_PKG_USING_LORA_RADIO_DRIVER is not set +# CONFIG_PKG_USING_QLED is not set +# CONFIG_PKG_USING_PAJ7620 is not set +# CONFIG_PKG_USING_AGILE_CONSOLE is not set +# CONFIG_PKG_USING_LD3320 is not set +# CONFIG_PKG_USING_WK2124 is not set +# CONFIG_PKG_USING_LY68L6400 is not set +# CONFIG_PKG_USING_DM9051 is not set +# CONFIG_PKG_USING_SSD1306 is not set +# CONFIG_PKG_USING_QKEY is not set +# CONFIG_PKG_USING_RS485 is not set +# CONFIG_PKG_USING_RS232 is not set +# CONFIG_PKG_USING_NES is not set +# CONFIG_PKG_USING_VIRTUAL_SENSOR is not set +# CONFIG_PKG_USING_VDEVICE is not set +# CONFIG_PKG_USING_SGM706 is not set +# CONFIG_PKG_USING_STM32WB55_SDK is not set +# CONFIG_PKG_USING_RDA58XX is not set +# CONFIG_PKG_USING_LIBNFC is not set +# CONFIG_PKG_USING_MFOC is not set +# CONFIG_PKG_USING_TMC51XX is not set +# CONFIG_PKG_USING_TCA9534 is not set +# CONFIG_PKG_USING_KOBUKI is not set +# CONFIG_PKG_USING_ROSSERIAL is not set +# CONFIG_PKG_USING_MICRO_ROS is not set +# CONFIG_PKG_USING_MCP23008 is not set +# CONFIG_PKG_USING_BLUETRUM_SDK is not set +# CONFIG_PKG_USING_MISAKA_AT24CXX is not set +# CONFIG_PKG_USING_MISAKA_RGB_BLING is not set +# CONFIG_PKG_USING_LORA_MODEM_DRIVER is not set +# CONFIG_PKG_USING_BL_MCU_SDK is not set +# CONFIG_PKG_USING_SOFT_SERIAL is not set +# CONFIG_PKG_USING_MB85RS16 is not set +# CONFIG_PKG_USING_CW2015 is not set +# CONFIG_PKG_USING_RFM300 is not set +# CONFIG_PKG_USING_IO_INPUT_FILTER is not set +# CONFIG_PKG_USING_RASPBERRYPI_PICO_SDK is not set +# CONFIG_PKG_USING_LRF_NV7LIDAR is not set + +# +# AI packages +# +# CONFIG_PKG_USING_LIBANN is not set +# CONFIG_PKG_USING_NNOM is not set +# CONFIG_PKG_USING_ONNX_BACKEND is not set +# CONFIG_PKG_USING_ONNX_PARSER is not set +# CONFIG_PKG_USING_TENSORFLOWLITEMICRO is not set +# CONFIG_PKG_USING_ELAPACK is not set +# CONFIG_PKG_USING_ULAPACK is not set +# CONFIG_PKG_USING_QUEST is not set +# CONFIG_PKG_USING_NAXOS is not set + +# +# miscellaneous packages +# + +# +# project laboratory +# + +# +# samples: kernel and components samples +# +# CONFIG_PKG_USING_KERNEL_SAMPLES is not set +# CONFIG_PKG_USING_FILESYSTEM_SAMPLES is not set +# CONFIG_PKG_USING_NETWORK_SAMPLES is not set +# CONFIG_PKG_USING_PERIPHERAL_SAMPLES is not set + +# +# entertainment: terminal games and other interesting software packages +# +# CONFIG_PKG_USING_CMATRIX is not set +# CONFIG_PKG_USING_SL is not set +# CONFIG_PKG_USING_CAL is not set +# CONFIG_PKG_USING_ACLOCK is not set +# CONFIG_PKG_USING_THREES is not set +# CONFIG_PKG_USING_2048 is not set +# CONFIG_PKG_USING_SNAKE is not set +# CONFIG_PKG_USING_TETRIS is not set +# CONFIG_PKG_USING_DONUT is not set +# CONFIG_PKG_USING_COWSAY is not set +# CONFIG_PKG_USING_LIBCSV is not set +# CONFIG_PKG_USING_OPTPARSE is not set +# CONFIG_PKG_USING_FASTLZ is not set +# CONFIG_PKG_USING_MINILZO is not set +# CONFIG_PKG_USING_QUICKLZ is not set +# CONFIG_PKG_USING_LZMA is not set +# CONFIG_PKG_USING_MULTIBUTTON is not set +# CONFIG_PKG_USING_FLEXIBLE_BUTTON is not set +# CONFIG_PKG_USING_CANFESTIVAL is not set +# CONFIG_PKG_USING_ZLIB is not set +# CONFIG_PKG_USING_MINIZIP is not set +# CONFIG_PKG_USING_HEATSHRINK is not set +# CONFIG_PKG_USING_DSTR is not set +# CONFIG_PKG_USING_TINYFRAME is not set +# CONFIG_PKG_USING_KENDRYTE_DEMO is not set +# CONFIG_PKG_USING_DIGITALCTRL is not set +# CONFIG_PKG_USING_UPACKER is not set +# CONFIG_PKG_USING_UPARAM is not set +# CONFIG_PKG_USING_HELLO is not set +# CONFIG_PKG_USING_VI is not set +# CONFIG_PKG_USING_KI is not set +# CONFIG_PKG_USING_ARMv7M_DWT is not set +# CONFIG_PKG_USING_UKAL is not set +# CONFIG_PKG_USING_CRCLIB is not set +# CONFIG_PKG_USING_LWGPS is not set +# CONFIG_PKG_USING_STATE_MACHINE is not set +# CONFIG_PKG_USING_DESIGN_PATTERN is not set +# CONFIG_PKG_USING_CONTROLLER is not set +# CONFIG_PKG_USING_PHASE_LOCKED_LOOP is not set +# CONFIG_PKG_USING_MFBD is not set +# CONFIG_PKG_USING_SLCAN2RTT is not set +# CONFIG_PKG_USING_SOEM is not set +# CONFIG_PKG_USING_QPARAM is not set + +# +# Arduino libraries +# +# CONFIG_PKG_USING_RTDUINO is not set + +# +# Projects +# +# CONFIG_PKG_USING_ARDUINO_ULTRASOUND_RADAR is not set +# CONFIG_PKG_USING_ARDUINO_SENSOR_KIT is not set +# CONFIG_PKG_USING_ARDUINO_MATLAB_SUPPORT is not set + +# +# Sensors +# +# CONFIG_PKG_USING_ARDUINO_SEEED_BMP280 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADXL375 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VL53L0X is not set +# CONFIG_PKG_USING_ARDUINO_SEEED_LIS3DHTR is not set +# CONFIG_PKG_USING_ARDUINO_SEEED_DHT is not set +# CONFIG_PKG_USING_ARDUINO_CAPACITIVESENSOR is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SENSOR is not set +# CONFIG_PKG_USING_ADAFRUIT_MAX31855 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MAX31865 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MAX31856 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90614 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM9DS1 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AHTX0 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM9DS0 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP280 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADT7410 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP085 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BME680 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP9808 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP4728 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_INA219 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LTR390 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADXL345 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_DHT is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP9600 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM6DS is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BNO055 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MAX1704X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MMC56X3 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90393 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90395 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ICM20X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_DPS310 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HTS221 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SHT4X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SHT31 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADXL343 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BME280 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AS726X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AMG88XX is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AM2320 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AM2315 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LTR329_LTR303 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP085_UNIFIED is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP183 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP183_UNIFIED is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BMP3XX is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MS8607 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS3MDL is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MLX90640 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MMA8451 is not set +# CONFIG_PKG_USING_ADAFRUIT_MSA301 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPL115A2 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BNO08X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BNO08X_RVC is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS2MDL is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM303DLH_MAG is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LC709203F is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_CAP1188 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_CCS811 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_NAU7802 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS331 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LPS2X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LPS35HW is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LSM303_ACCEL is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_LIS3DH is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCF8591 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPL3115A2 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPR121 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPRLS is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MPU6050 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCT2075 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PM25AQI is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_EMC2101 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_FXAS21002C is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SCD30 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_FXOS8700 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HMC5883_UNIFIED is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SGP30 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TMP006 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TLA202X is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TCS34725 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SI7021 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SI1145 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SGP40 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SHTC3 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HDC1000 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HTU21DF is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AS7341 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_HTU31D is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SENSORLAB is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_INA260 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TMP007_LIBRARY is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_L3GD20 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TMP117 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TSC2007 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TSL2561 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TSL2591_LIBRARY is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VCNL4040 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VEML6070 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VEML6075 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_VEML7700 is not set + +# +# Display +# +# CONFIG_PKG_USING_ARDUINO_U8G2 is not set + +# +# Timing +# +# CONFIG_PKG_USING_ARDUINO_MSTIMER2 is not set + +# +# Data Processing +# +# CONFIG_PKG_USING_ARDUINO_KALMANFILTER is not set +# CONFIG_PKG_USING_ARDUINO_ARDUINOJSON is not set + +# +# Data Storage +# + +# +# Communication +# +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PN532 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_SI4713 is not set + +# +# Device Control +# +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCF8574 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_PCA9685 is not set + +# +# Other +# + +# +# Signal IO +# +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BUSIO is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_TCA8418 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP23017 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_ADS1X15 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_AW9523 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP3008 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_MCP4725 is not set +# CONFIG_PKG_USING_ARDUINO_ADAFRUIT_BD3491FS is not set + +# +# Uncategorized +# + +# +# Hardware Drivers +# + +# +# On-chip Peripheral Drivers +# +CONFIG_BSP_USING_UART=y +CONFIG_RT_USING_UART1=y +# CONFIG_RT_USING_UART0 is not set + +# +# Board extended module Drivers +# +CONFIG_BSP_USING_GIC=y +CONFIG_BSP_USING_GICV3=y +CONFIG_PHYTIUM_ARCH_AARCH64=y + +# +# Standalone Setting +# +CONFIG_TARGET_ARMV8_AARCH64=y + +# +# Board Configuration +# +# CONFIG_TARGET_F2000_4 is not set +# CONFIG_TARGET_D2000 is not set +CONFIG_TARGET_E2000Q=y +# CONFIG_TARGET_E2000D is not set +# CONFIG_TARGET_E2000S is not set +CONFIG_TARGET_E2000=y +CONFIG_DEFAULT_DEBUG_PRINT_UART1=y +# CONFIG_DEFAULT_DEBUG_PRINT_UART0 is not set +# CONFIG_DEFAULT_DEBUG_PRINT_UART2 is not set + +# +# Components Configuration +# +# CONFIG_USE_SPI is not set +# CONFIG_USE_QSPI is not set +# CONFIG_USE_GIC is not set +CONFIG_USE_SERIAL=y + +# +# Usart Configuration +# +CONFIG_ENABLE_Pl011_UART=y +# CONFIG_USE_GPIO is not set +# CONFIG_USE_ETH is not set +# CONFIG_USE_CAN is not set +# CONFIG_USE_I2C is not set +# CONFIG_USE_TIMER is not set +# CONFIG_USE_MIO is not set +# CONFIG_USE_SDMMC is not set +# CONFIG_USE_PCIE is not set +# CONFIG_USE_WDT is not set +# CONFIG_USE_DMA is not set +# CONFIG_USE_NAND is not set +# CONFIG_USE_RTC is not set +# CONFIG_USE_SATA is not set +# CONFIG_USE_USB is not set +# CONFIG_USE_ADC is not set +# CONFIG_USE_PWM is not set +# CONFIG_USE_IPC is not set +# CONFIG_LOG_VERBOS is not set +# CONFIG_LOG_DEBUG is not set +# CONFIG_LOG_INFO is not set +# CONFIG_LOG_WARN is not set +CONFIG_LOG_ERROR=y +# CONFIG_LOG_NONE is not set +# CONFIG_USE_DEFAULT_INTERRUPT_CONFIG is not set +# CONFIG_LOG_EXTRA_INFO is not set +# CONFIG_BOOTUP_DEBUG_PRINTS is not set diff --git a/bsp/phytium/aarch64/Kconfig b/bsp/phytium/aarch64/Kconfig new file mode 100644 index 0000000000..973bc46fe1 --- /dev/null +++ b/bsp/phytium/aarch64/Kconfig @@ -0,0 +1,55 @@ +mainmenu "RT-Thread Project Configuration" + +config RTT_DIR + string + option env="RTT_ROOT" + default "../../.." + +config BSP_DIR + string + option env="BSP_ROOT" + default "../." + +config STANDALONE_DIR + string + option env="STANDALONE_DIR" + default ".././libraries/standalone" + +config PKGS_DIR + string + option env="PKGS_ROOT" + default "packages" + +source "$RTT_DIR/Kconfig" +source "$PKGS_DIR/Kconfig" +source "$BSP_DIR/libraries/drivers/Kconfig" + +config BSP_USING_GIC + bool + default y + config BSP_USING_GICV3 + bool + default y + +config PHYTIUM_ARCH_AARCH64 + bool + select ARCH_ARMV8 + select RT_USING_COMPONENTS_INIT + select RT_USING_USER_MAIN + select ARCH_CPU_64BIT + select TARGET_ARMV8_AARCH64 + default y + +menu "Standalone Setting" + config TARGET_ARMV8_AARCH64 + bool "Armv8 Aarch64" + default y + + source "$STANDALONE_DIR/board/Kconfig" + source "$STANDALONE_DIR/drivers/Kconfig" + source "$STANDALONE_DIR/common/Kconfig" + +endmenu + + + diff --git a/bsp/phytium/aarch64/README.md b/bsp/phytium/aarch64/README.md new file mode 100644 index 0000000000..8ca947b5d8 --- /dev/null +++ b/bsp/phytium/aarch64/README.md @@ -0,0 +1,121 @@ + + +# AARCH64 工作模式使用 + +- 当开发者需要基于 Phytium 系列芯片进行开发时,可以从以下几个步骤出发配置芯片 + +## 1. 如何选择芯片 + +```shell + scons --menuconfig +``` + +开发者通过以下选择进行配置 + +``` +Standalone Setting > Board Configuration > Chip +``` + +![](./figures/chip_select.png) +![](./figures/phytium_cpu_select.png) + +## 2. 如何选择驱动 + + +```shell + scons --menuconfig +``` + +开发者通过以下选项进行驱动的使能 + +``` +Hardware Drivers Config > On-chip Peripheral Drivers +``` + +![](./figures/select_driver.png) + + +## 3. 开启SDK中内部调试信息 + + +```shell + scons --menuconfig +``` + +开发者通过以下选项进行调试信息等级的设置 + +![](./figures/select_debug_info.png) + + + +## 4. 编译程序 + +```shell + scons -c + scons +``` + +- 完成编译之后目录下将会生成以下几个文件 + +``` +rtthread_a64.bin +rtthread_a64.elf +rtthread_a64.map +``` + +## 5. 打包导出工程源代码 + + +- 指定工程名和路径,打包RT-Thread内核和Phytium BSP代码,可以导出一个工程工程 +``` +python ./export_project.py -n=phytium-a64 -o=D:/proj/rt-thread-e2000/phytium-a64 +``` + +![](./figures/export_project.png) + + +- 进入打包工程的目录,修改工程根目录 Kconfig 中的路径 BSP_DIR 和 STANDALONE_DIR +> env 环境中的 menuconfig 不会调用 SConstruct 修改路径环境变量,因此需要手动修改路径 + +``` +config BSP_DIR + string + option env="BSP_ROOT" + default "." + +config STANDALONE_DIR + string + option env="STANDALONE_DIR" + default "libraries/standalone" +``` + +- 输入 menuconfig 和 scons 完成编译 + + +## 6. 将工程导入 RT-Studio + +- 在 RT-Studio 使用功能`RT-Thread Bsp 到工作空间`,导入 5. 中导出的 BSP 工程 +- 设置 BSP 工程的交叉编译链后进行后续开发 + +![](./figures/import_project.png) \ No newline at end of file diff --git a/bsp/phytium/aarch64/SConscript b/bsp/phytium/aarch64/SConscript new file mode 100644 index 0000000000..4c815c49b8 --- /dev/null +++ b/bsp/phytium/aarch64/SConscript @@ -0,0 +1,15 @@ +# RT-Thread building script for bridge + +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/phytium/aarch64/SConstruct b/bsp/phytium/aarch64/SConstruct new file mode 100644 index 0000000000..ae659dfb21 --- /dev/null +++ b/bsp/phytium/aarch64/SConstruct @@ -0,0 +1,58 @@ +import os +import sys +import rtconfig + +IS_EXPORTED = False + +# setup RT-Thread Root Path +if os.getenv('RTT_ROOT'): + RTT_ROOT = os.getenv('RTT_ROOT') +else: + RTT_ROOT = os.getcwd() + '/../../..' + +sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')] +try: + from building import * +except: + print('Cannot found RT-Thread root directory, please check RTT_ROOT') + print(RTT_ROOT) + exit(-1) + +if RTT_ROOT == 'rt-thread': + IS_EXPORTED = True # if kenrel and bsp has been exported by export_project.py + +# setup Phytium BSP Root Path +if IS_EXPORTED: + BSP_ROOT = '.' +else: + BSP_ROOT = RTT_ROOT + '/bsp/phytium' + +TARGET = 'rtthread_a64.' + 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('BSP_ROOT') +Export('rtconfig') + +# prepare building environment +objs = PrepareBuilding(env, RTT_ROOT, has_libcpu = False) + +if not IS_EXPORTED: # if project is not exported, libraries and board need to manually add + # include libraries + objs.extend(SConscript(os.path.join(BSP_ROOT + '/libraries', 'SConscript'))) + + # include board + objs.extend(SConscript(os.path.join(BSP_ROOT + '/board', 'SConscript'))) + +# make a building +DoBuilding(TARGET, objs) + diff --git a/bsp/phytium/aarch64/applications/SConscript b/bsp/phytium/aarch64/applications/SConscript new file mode 100644 index 0000000000..01eb940dfb --- /dev/null +++ b/bsp/phytium/aarch64/applications/SConscript @@ -0,0 +1,11 @@ +Import('RTT_ROOT') +Import('rtconfig') +from building import * + +cwd = os.path.join(str(Dir('#')), 'applications') +src = Glob('*.c') +CPPPATH = [cwd, str(Dir('#'))] + +group = DefineGroup('Applications', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/phytium/aarch64/applications/main.c b/bsp/phytium/aarch64/applications/main.c new file mode 100644 index 0000000000..96c5ad2dc0 --- /dev/null +++ b/bsp/phytium/aarch64/applications/main.c @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include +#include + +#include + +#ifdef RT_USING_SMP + +struct rt_thread test_core[RT_CPUS_NR]; +static char *core_thread_name[8] = +{ + "core0_test", + "core1_test", + "core2_test", + "core3_test", + "core4_test", + "core5_test", + "core6_test", + "core7_test" +}; +static rt_uint8_t core_stack[RT_CPUS_NR][1024]; + +static void demo_core_thread(void *parameter) +{ + rt_base_t level; + while (1) + { + /* code */ + level = rt_cpus_lock(); + rt_kprintf("Hi, core%d \r\n", rt_hw_cpu_id()); + rt_cpus_unlock(level); + rt_thread_mdelay(2000000); + } +} + +void demo_core(void) +{ + rt_ubase_t i; + rt_ubase_t cpu_id = 0; + for (i = 0; i < RT_CPUS_NR; i++) + { + cpu_id = i; + rt_thread_init(&test_core[i], + core_thread_name[i], + demo_core_thread, + RT_NULL, + &core_stack[i], + 1024, + 20, + 32); + + rt_thread_control(&test_core[i], RT_THREAD_CTRL_BIND_CPU, (void *)cpu_id); + rt_thread_startup(&test_core[i]); + } +} +#endif + +int main(void) +{ +#ifdef RT_USING_SMP + demo_core(); +#endif + return RT_EOK; +} + diff --git a/bsp/phytium/aarch64/export_project.py b/bsp/phytium/aarch64/export_project.py new file mode 100644 index 0000000000..d4c690c7cb --- /dev/null +++ b/bsp/phytium/aarch64/export_project.py @@ -0,0 +1,37 @@ +import os +import shutil +import argparse + +parser = argparse.ArgumentParser() +parser.description='please enter two parameters and ...' +parser.add_argument("-n", "--name", help="project name", type=str, default="phytium-a64") +parser.add_argument("-o", "--output", help="export path", type=str, default="./phytium-a64") +args = parser.parse_args() + +print('=== Exporting Phytium BSP for RT-Studio ====') + +board_src_path = os.path.abspath(r'../board') +librs_src_path = os.path.abspath(r'../libraries') + +board_dst_path = os.path.abspath(r'./board') +librs_dst_path = os.path.abspath(r'./libraries') + +print(' Copying BSP board from {} to {}'.format(board_src_path, board_dst_path)) +print(' Copying BSP libraries from {} to {}'.format(librs_src_path, librs_dst_path)) + +if os.path.exists(board_dst_path): + shutil.rmtree(board_dst_path) + +if os.path.exists(librs_dst_path): + shutil.rmtree(librs_dst_path) + +shutil.copytree(board_src_path, board_dst_path) +shutil.copytree(librs_src_path, librs_dst_path) + +os.system('scons --dist-ide --project-name={} --project-path={}'.format(args.name, args.output)) + +if os.path.exists(board_dst_path): + shutil.rmtree(board_dst_path) + +if os.path.exists(librs_dst_path): + shutil.rmtree(librs_dst_path) \ No newline at end of file diff --git a/bsp/phytium/aarch64/figures/chip_select.png b/bsp/phytium/aarch64/figures/chip_select.png new file mode 100644 index 0000000000..26878fe235 Binary files /dev/null and b/bsp/phytium/aarch64/figures/chip_select.png differ diff --git a/bsp/phytium/aarch64/figures/export_project.png b/bsp/phytium/aarch64/figures/export_project.png new file mode 100644 index 0000000000..d150dcd3ca Binary files /dev/null and b/bsp/phytium/aarch64/figures/export_project.png differ diff --git a/bsp/phytium/aarch64/figures/import_project.png b/bsp/phytium/aarch64/figures/import_project.png new file mode 100644 index 0000000000..5aa91d058e Binary files /dev/null and b/bsp/phytium/aarch64/figures/import_project.png differ diff --git a/bsp/phytium/aarch64/figures/phytium_cpu_select.png b/bsp/phytium/aarch64/figures/phytium_cpu_select.png new file mode 100644 index 0000000000..40af2b41c6 Binary files /dev/null and b/bsp/phytium/aarch64/figures/phytium_cpu_select.png differ diff --git a/bsp/phytium/aarch64/figures/select_debug_info.png b/bsp/phytium/aarch64/figures/select_debug_info.png new file mode 100644 index 0000000000..8d22436940 Binary files /dev/null and b/bsp/phytium/aarch64/figures/select_debug_info.png differ diff --git a/bsp/phytium/aarch64/figures/select_driver.png b/bsp/phytium/aarch64/figures/select_driver.png new file mode 100644 index 0000000000..3fa21b7e8d Binary files /dev/null and b/bsp/phytium/aarch64/figures/select_driver.png differ diff --git a/bsp/phytium/aarch64/link.lds b/bsp/phytium/aarch64/link.lds new file mode 100644 index 0000000000..86bb78e88e --- /dev/null +++ b/bsp/phytium/aarch64/link.lds @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * 2017-5-30 bernard first version + */ + +/* _EL1_STACK_SIZE = DEFINED(_EL1_STACK_SIZE) ? _EL1_STACK_SIZE : 0x20000; */ + +SECTIONS +{ + . = 0x80100000; + . = ALIGN(4096); + .text : + { + KEEP(*(.text.entrypoint)) /* The entry point */ + *(.vectors) + *(.text) /* remaining code */ + *(.text.*) /* remaining code */ + + *(.rodata) /* read-only data (constants) */ + *(.rodata*) + *(.glue_7) + *(.glue_7t) + *(.gnu.linkonce.t*) + + *(COMMON) + + /* section information for finsh shell */ + . = ALIGN(16); + __fsymtab_start = .; + KEEP(*(FSymTab)) + __fsymtab_end = .; + . = ALIGN(16); + __vsymtab_start = .; + KEEP(*(VSymTab)) + __vsymtab_end = .; + . = ALIGN(16); + + /* section information for initial. */ + . = ALIGN(16); + __rt_init_start = .; + KEEP(*(SORT(.rti_fn*))) + __rt_init_end = .; + . = ALIGN(16); + + . = ALIGN(16); + _etext = .; + } + . = ALIGN(4); + .eh_frame_hdr : + { + *(.eh_frame_hdr) + *(.eh_frame_entry) + } + .eh_frame : ONLY_IF_RO { KEEP (*(.eh_frame)) } + + . = ALIGN(16); + .data : + { + *(.data) + *(.data.*) + + *(.data1) + *(.data1.*) + + . = ALIGN(16); + _gp = ABSOLUTE(.); /* Base of small data */ + + *(.sdata) + *(.sdata.*) + } + + . = ALIGN(16); + .ctors : + { + PROVIDE(__ctors_start__ = .); + /* new GCC version uses .init_array */ + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE(__ctors_end__ = .); + } + . = ALIGN(4); + .dtors : + { + PROVIDE(__dtors_start__ = .); + KEEP(*(SORT(.dtors.*))) + KEEP(*(.dtors)) + PROVIDE(__dtors_end__ = .); + } + + . = ALIGN(16); + .bss : + { + PROVIDE(__bss_start = .); + *(.bss) + *(.bss.*) + *(.dynbss) + . = ALIGN(32); + PROVIDE(__bss_end = .); + } + + . = ALIGN(4); + .heap : + { + PROVIDE(__heap_start = .); + . = ALIGN(8); + PROVIDE(end = .); + } + + _end = .; + + /* Stabs debugging sections. */ + .stab 0 : { *(.stab) } + .stabstr 0 : { *(.stabstr) } + .stab.excl 0 : { *(.stab.excl) } + .stab.exclstr 0 : { *(.stab.exclstr) } + .stab.index 0 : { *(.stab.index) } + .stab.indexstr 0 : { *(.stab.indexstr) } + .comment 0 : { *(.comment) } + /* DWARF debug sections. + * Symbols in the DWARF debugging sections are relative to the beginning + * of the section so we begin them at 0. */ + /* DWARF 1 */ + .debug 0 : { *(.debug) } + .line 0 : { *(.line) } + /* GNU DWARF 1 extensions */ + .debug_srcinfo 0 : { *(.debug_srcinfo) } + .debug_sfnames 0 : { *(.debug_sfnames) } + /* DWARF 1.1 and DWARF 2 */ + .debug_aranges 0 : { *(.debug_aranges) } + .debug_pubnames 0 : { *(.debug_pubnames) } + /* DWARF 2 */ + .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } + .debug_abbrev 0 : { *(.debug_abbrev) } + .debug_line 0 : { *(.debug_line) } + .debug_frame 0 : { *(.debug_frame) } + .debug_str 0 : { *(.debug_str) } + .debug_loc 0 : { *(.debug_loc) } + .debug_macinfo 0 : { *(.debug_macinfo) } + /* SGI/MIPS DWARF 2 extensions */ + .debug_weaknames 0 : { *(.debug_weaknames) } + .debug_funcnames 0 : { *(.debug_funcnames) } + .debug_typenames 0 : { *(.debug_typenames) } + .debug_varnames 0 : { *(.debug_varnames) } +} + +__bss_size = SIZEOF(.bss); \ No newline at end of file diff --git a/bsp/phytium/aarch64/rtconfig.h b/bsp/phytium/aarch64/rtconfig.h new file mode 100644 index 0000000000..c72b07bd19 --- /dev/null +++ b/bsp/phytium/aarch64/rtconfig.h @@ -0,0 +1,260 @@ +#ifndef RT_CONFIG_H__ +#define RT_CONFIG_H__ + +/* Automatically generated file; DO NOT EDIT. */ +/* RT-Thread Project Configuration */ + +/* RT-Thread Kernel */ + +#define RT_NAME_MAX 16 +#define RT_USING_SMP +#define RT_CPUS_NR 4 +#define RT_ALIGN_SIZE 4 +#define RT_THREAD_PRIORITY_32 +#define RT_THREAD_PRIORITY_MAX 32 +#define RT_TICK_PER_SECOND 100 +#define RT_USING_OVERFLOW_CHECK +#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 +#define SYSTEM_THREAD_STACK_SIZE 4096 +#define RT_USING_TIMER_SOFT +#define RT_TIMER_THREAD_PRIO 4 +#define RT_TIMER_THREAD_STACK_SIZE 4096 + +/* kservice optimization */ + +#define RT_KSERVICE_USING_STDLIB +#define RT_KPRINTF_USING_LONGLONG +#define RT_DEBUG + +/* Inter-Thread communication */ + +#define RT_USING_SEMAPHORE +#define RT_USING_MUTEX +#define RT_USING_EVENT +#define RT_USING_MAILBOX +#define RT_USING_MESSAGEQUEUE + +/* Memory Management */ + +#define RT_USING_MEMPOOL +#define RT_USING_SMALL_MEM +#define RT_USING_SMALL_MEM_AS_HEAP +#define RT_USING_HEAP + +/* Kernel Device Object */ + +#define RT_USING_DEVICE +#define RT_USING_CONSOLE +#define RT_CONSOLEBUF_SIZE 128 +#define RT_CONSOLE_DEVICE_NAME "uart1" +#define RT_VER_NUM 0x50000 +#define ARCH_CPU_64BIT +#define ARCH_ARMV8 + +/* RT-Thread Components */ + +#define RT_USING_COMPONENTS_INIT +#define RT_USING_USER_MAIN +#define RT_MAIN_THREAD_STACK_SIZE 4096 +#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 4096 +#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 +#define RT_USING_DFS +#define DFS_USING_POSIX +#define DFS_USING_WORKDIR +#define DFS_FILESYSTEMS_MAX 4 +#define DFS_FILESYSTEM_TYPES_MAX 4 +#define DFS_FD_MAX 16 + +/* Device Drivers */ + +#define RT_USING_DEVICE_IPC +#define RT_USING_SYSTEM_WORKQUEUE +#define RT_SYSTEM_WORKQUEUE_STACKSIZE 8192 +#define RT_SYSTEM_WORKQUEUE_PRIORITY 23 +#define RT_USING_SERIAL +#define RT_USING_SERIAL_V1 +#define RT_SERIAL_USING_DMA +#define RT_SERIAL_RB_BUFSZ 64 +#define RT_USING_PIN + +/* Using USB */ + + +/* C/C++ and POSIX layer */ + +#define RT_LIBC_DEFAULT_TIMEZONE 8 + +/* POSIX (Portable Operating System Interface) layer */ + + +/* Interprocess Communication (IPC) */ + + +/* Socket is in the 'Network' category */ + + +/* Network */ + + +/* Utilities */ + + +/* RT-Thread Utestcases */ + + +/* RT-Thread online packages */ + +/* IoT - internet of things */ + + +/* Wi-Fi */ + +/* Marvell WiFi */ + + +/* Wiced WiFi */ + + +/* IoT Cloud */ + + +/* security packages */ + + +/* language packages */ + +/* JSON: JavaScript Object Notation, a lightweight data-interchange format */ + + +/* XML: Extensible Markup Language */ + + +/* multimedia packages */ + +/* LVGL: powerful and easy-to-use embedded GUI library */ + + +/* u8g2: a monochrome graphic library */ + + +/* PainterEngine: A cross-platform graphics application framework written in C language */ + + +/* tools packages */ + + +/* system packages */ + +/* enhanced kernel services */ + + +/* acceleration: Assembly language or algorithmic acceleration packages */ + + +/* CMSIS: ARM Cortex-M Microcontroller Software Interface Standard */ + + +/* Micrium: Micrium software products porting for RT-Thread */ + + +/* peripheral libraries and drivers */ + + +/* Kendryte SDK */ + + +/* AI packages */ + + +/* miscellaneous packages */ + +/* project laboratory */ + +/* samples: kernel and components samples */ + + +/* entertainment: terminal games and other interesting software packages */ + + +/* Arduino libraries */ + + +/* Projects */ + + +/* Sensors */ + + +/* Display */ + + +/* Timing */ + + +/* Data Processing */ + + +/* Data Storage */ + +/* Communication */ + + +/* Device Control */ + + +/* Other */ + +/* Signal IO */ + + +/* Uncategorized */ + +/* Hardware Drivers */ + +/* On-chip Peripheral Drivers */ + +#define BSP_USING_UART +#define RT_USING_UART1 + +/* Board extended module Drivers */ + +#define BSP_USING_GIC +#define BSP_USING_GICV3 +#define PHYTIUM_ARCH_AARCH64 + +/* Standalone Setting */ + +#define TARGET_ARMV8_AARCH64 + +/* Board Configuration */ + +#define TARGET_E2000Q +#define TARGET_E2000 +#define DEFAULT_DEBUG_PRINT_UART1 + +/* Components Configuration */ + +#define USE_SERIAL + +/* Usart Configuration */ + +#define ENABLE_Pl011_UART +#define LOG_ERROR + +#endif diff --git a/bsp/phytium/aarch64/rtconfig.py b/bsp/phytium/aarch64/rtconfig.py new file mode 100644 index 0000000000..9bb9671efb --- /dev/null +++ b/bsp/phytium/aarch64/rtconfig.py @@ -0,0 +1,52 @@ +import os + +# toolchains options +ARCH ='aarch64' +CPU ='cortex-a' +CROSS_TOOL ='gcc' + +if os.getenv('RTT_ROOT'): + RTT_ROOT = os.getenv('RTT_ROOT') +else: + RTT_ROOT = r'../../..' + +PLATFORM = 'gcc' +EXEC_PATH = r'/opt/gcc-arm-8.3-2019.03-x86_64-aarch64-elf/bin/' +if os.getenv('AARCH64_CROSS_PATH'): + EXEC_PATH = os.getenv('AARCH64_CROSS_PATH') + print('EXEC_PATH = {}'.format(EXEC_PATH)) +else: + print('AARCH64_CROSS_PATH not found') + +BUILD = 'debug' + +if PLATFORM == 'gcc': + # toolchains + PREFIX = 'aarch64-none-elf-' + 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' + + DEVICE = ' -march=armv8-a -mtune=cortex-a72' + CFLAGS = DEVICE + ' -Wall' + AFLAGS = ' -c' + ' -x assembler-with-cpp -D__ASSEMBLY__' + LFLAGS = DEVICE + ' -nostartfiles -Wl,--gc-sections,-Map=rtthread_a64.map,-cref,-u,system_vectors -T link.lds -fdiagnostics-color=always' + CPATH = '' + LPATH = '' + + if BUILD == 'debug': + CFLAGS += ' -O0 -gdwarf-2' + AFLAGS += ' -gdwarf-2' + else: + CFLAGS += ' -O2' + + CXXFLAGS = CFLAGS + +DUMP_ACTION = OBJDUMP + ' -D -S $TARGET > rtthread_a64.dis\n' +POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread_a64.bin\n' + SIZE + ' $TARGET \n' diff --git a/bsp/phytium/aarch64/sdkconfig.h b/bsp/phytium/aarch64/sdkconfig.h new file mode 100644 index 0000000000..d799f85053 --- /dev/null +++ b/bsp/phytium/aarch64/sdkconfig.h @@ -0,0 +1,71 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: sdkconfig.h + * Date: 2022-10-09 15:04:36 + * LastEditTime: 2022-10-09 15:04:37 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + +#ifndef SDK_CONFIG_H__ +#define SDK_CONFIG_H__ + +#include "rtconfig.h" + +/* board */ + +/* E2000 */ + +#if defined(TARGET_E2000) + #define CONFIG_TARGET_E2000 +#endif + +#if defined(TARGET_E2000Q) + #define CONFIG_TARGET_E2000Q +#endif + +#if defined(TARGET_ARMV8_AARCH64) + #define CONFIG_TARGET_ARMV8_AARCH64 +#endif + +/* debug */ + +#ifdef LOG_VERBOS + #define CONFIG_LOG_VERBOS +#endif + +#ifdef LOG_ERROR + #define CONFIG_LOG_ERROR +#endif + +#ifdef LOG_WARN + #define CONFIG_LOG_WARN +#endif + +#ifdef LOG_INFO + #define CONFIG_LOG_INFO +#endif + +#ifdef LOG_DEBUG + #define CONFIG_LOG_DEBUG +#endif + +#ifdef BOOTUP_DEBUG_PRINTS + #define CONFIG_BOOTUP_DEBUG_PRINTS +#endif + +#endif diff --git a/bsp/phytium/board/SConscript b/bsp/phytium/board/SConscript new file mode 100644 index 0000000000..c86f3413fb --- /dev/null +++ b/bsp/phytium/board/SConscript @@ -0,0 +1,25 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.S') +src += Glob('*.c') + +if GetDepend(['TARGET_E2000']): + if GetDepend(['TARGET_E2000Q']): + src += Glob(cwd + '/e2000/q/parameters.c') + elif GetDepend(['TARGET_E2000D']): + src += Glob(cwd + '/e2000/d/parameters.c') + elif GetDepend(['TARGET_E2000S']): + src += Glob(cwd + '/e2000/s/parameters.c') + +if GetDepend(['TARGET_F2000_4']): + src += Glob(cwd + '/d2000/parameters.c') + +if GetDepend(['TARGET_D2000']): + src += Glob(cwd + '/ft2004/parameters.c') + +CPPPATH = [cwd] + +group = DefineGroup('Board', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/phytium/board/board.c b/bsp/phytium/board/board.c new file mode 100644 index 0000000000..b02fd10b13 --- /dev/null +++ b/bsp/phytium/board/board.c @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * 2022-10-26 zhugengyu support aarch64 + * + */ + +#include "rtconfig.h" +#include +#include + +#include + +#include +#if defined(TARGET_ARMV8_AARCH64) + #include + #include + #include +#else + #include "fgeneric_timer.h" /* for aarch32 */ +#endif +#include +#include + +#include "fdebug.h" +#include "fprintk.h" +#include "fearly_uart.h" +#include "fcpu_info.h" +#include "fpsci.h" + +#define LOG_DEBUG_TAG "BOARD" +#define BSP_LOG_ERROR(format, ...) FT_DEBUG_PRINT_E(LOG_DEBUG_TAG, format, ##__VA_ARGS__) +#define BSP_LOG_WARN(format, ...) FT_DEBUG_PRINT_W(LOG_DEBUG_TAG, format, ##__VA_ARGS__) +#define BSP_LOG_INFO(format, ...) FT_DEBUG_PRINT_I(LOG_DEBUG_TAG, format, ##__VA_ARGS__) +#define BSP_LOG_DEBUG(format, ...) FT_DEBUG_PRINT_D(LOG_DEBUG_TAG, format, ##__VA_ARGS__) + +/* mmu config */ +struct mem_desc platform_mem_desc[] = +#if defined(TARGET_E2000) +{ + { + 0x00U, + 0x00U + 0x40000000U, + 0x00U, + DEVICE_MEM + }, + { + 0x40000000U, + 0x40000000U + 0x10000000U, + 0x40000000U, + DEVICE_MEM + }, + { + 0x50000000U, + 0x50000000U + 0x30000000U, + 0x50000000U, + DEVICE_MEM + }, + { + 0x80000000U, + 0xffffffffU, + 0x80000000U, + NORMAL_MEM + }, +#if defined(TARGET_ARMV8_AARCH64) + { + 0x1000000000, + 0x1000000000 + 0x1000000000, + 0x1000000000, + DEVICE_MEM + }, + { + 0x2000000000, + 0x2000000000 + 0x2000000000, + 0x2000000000, + NORMAL_MEM + }, +#endif +}; +#elif defined(TARGET_F2000_4) || defined(TARGET_D2000) +{ + { + 0x80000000, + 0xFFFFFFFF, + 0x80000000, + DDR_MEM + }, + { + 0, //< QSPI + 0x1FFFFFFF, + 0, + DEVICE_MEM + }, + { + 0x20000000, // + +#include "fcpu_info.h" +#include "fparameters.h" + + +/** + * @name: GetCpuMaskToAffval + * @msg: Convert information in cpu_mask to cluster_ID and target_list + * @param {u32} *cpu_mask is each bit of cpu_mask represents a selected CPU, for example, 0x3 represents core0 and CORE1 . + * @param {u32} *cluster_id is information about the cluster in which core resides ,format is + * |--------[bit31-24]-------[bit23-16]-------------[bit15-8]-----------[bit7-0] + * |--------Affinity level3-----Affinity level2-----Affinity level1-----Affinity level0 + * @param {u32} *target_list is core mask in cluster + * @return {u32} 0 indicates that the conversion was not successful , 1 indicates that the conversion was successful + */ +u32 GetCpuMaskToAffval(u32 *cpu_mask, u32 *cluster_id, u32 *target_list) +{ + if (*cpu_mask == 0) + { + return 0; + } + + *target_list = 0; + *cluster_id = 0; + + if (*cpu_mask & 0x3) + { + if ((*cpu_mask & 0x3) == 0x3) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x1)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0x3; + } + else if (*cpu_mask & 0xc) + { + *cluster_id = 0x100; + if ((*cpu_mask & 0xc) == 0xc) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x4)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0xc; + } + else if (*cpu_mask & 0x30) + { + *cluster_id = 0x200; + if ((*cpu_mask & 0x30) == 0x30) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x10)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0x30; + } + else if (*cpu_mask & 0xc0) + { + *cluster_id = 0x300; + if ((*cpu_mask & 0xc0) == 0xc0) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x40)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0xc0; + } + else + { + *cpu_mask = 0; + return 0; + } + + return 1; +} \ No newline at end of file diff --git a/bsp/phytium/board/e2000/d/parameters.c b/bsp/phytium/board/e2000/d/parameters.c new file mode 100644 index 0000000000..5a5c55a845 --- /dev/null +++ b/bsp/phytium/board/e2000/d/parameters.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include "rtconfig.h" +#include + +#include "fcpu_info.h" +#include "fparameters.h" + +u32 GetCpuMaskToAffval(u32 *cpu_mask, u32 *cluster_id, u32 *target_list) +{ + if (*cpu_mask == 0) + { + return 0; + } + + *target_list = 0; + *cluster_id = 0; + + if (*cpu_mask & 0x3) + { + *cluster_id = 0x200; + if ((*cpu_mask & 0x3) == 0x3) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x1)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0x3; /* clear all mask */ + } + else + { + *cpu_mask = 0; + return 0; + } + + return 1; +} diff --git a/bsp/phytium/board/e2000/q/parameters.c b/bsp/phytium/board/e2000/q/parameters.c new file mode 100644 index 0000000000..d3d3432c15 --- /dev/null +++ b/bsp/phytium/board/e2000/q/parameters.c @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include "rtconfig.h" +#include + +#include "fcpu_info.h" +#include "fparameters.h" + + +/** + * @name: GetCpuMaskToAffval + * @msg: 参考 GetCpuMaskToAffval 进行参数的重新定义 ,两个小核心定义的id 为0,1 ,两个大核的id 为 2,3 + * @return {*} + * @note: + * @param {u32} *cpu_mask + * @param {u32} *cluster_id + * @param {u32} *target_list + */ +u32 GetCpuMaskToAffval(u32 *cpu_mask, u32 *cluster_id, u32 *target_list) +{ + if (*cpu_mask == 0) + { + return 0; + } + + *target_list = 0; + *cluster_id = 0; + + if (*cpu_mask & 0x4) + { + *target_list = 1; + *cpu_mask &= ~0x4; + } + else if (*cpu_mask & 0x8) + { + *cluster_id = 0x100; + *target_list = 1; + *cpu_mask &= ~0x8; + } + else if (*cpu_mask & 0x3) + { + *cluster_id = 0x200; + if ((*cpu_mask & 0x3) == 0x3) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x4)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0x3; + } + else + { + *cpu_mask = 0; + return 0; + } + + return 1; +} \ No newline at end of file diff --git a/bsp/phytium/board/e2000/s/parameters.c b/bsp/phytium/board/e2000/s/parameters.c new file mode 100644 index 0000000000..b711d6704b --- /dev/null +++ b/bsp/phytium/board/e2000/s/parameters.c @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include "rtconfig.h" +#include + +#include "fcpu_info.h" +#include "fparameters.h" + +u32 GetCpuMaskToAffval(u32 *cpu_mask, u32 *cluster_id, u32 *target_list) +{ + if (*cpu_mask == 0) + { + return 0; + } + + *target_list = 0; + *cluster_id = 0; + + if (*cpu_mask & 0x1) + { + *target_list = 1; + *cluster_id = 0x200; + *cpu_mask &= ~0x1; + } + else + { + *cpu_mask = 0; + return 0; + } + + return 1; +} diff --git a/bsp/phytium/board/ft2004/parameters.c b/bsp/phytium/board/ft2004/parameters.c new file mode 100644 index 0000000000..8bf9da3f51 --- /dev/null +++ b/bsp/phytium/board/ft2004/parameters.c @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include "rtconfig.h" +#include + +#include "fcpu_info.h" +#include "fparameters.h" + + +u32 GetCpuMaskToAffval(u32 *cpu_mask, u32 *cluster_id, u32 *target_list) +{ + if (*cpu_mask == 0) + { + return 0; + } + + *target_list = 0; + *cluster_id = 0; + + if (*cpu_mask & 0x3) + { + if ((*cpu_mask & 0x3) == 0x3) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x1)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0x3; + } + else if (*cpu_mask & 0xc) + { + *cluster_id = 0x100; + if ((*cpu_mask & 0xc) == 0xc) + { + *target_list = 3; + } + else if ((*cpu_mask & 0x4)) + { + *target_list = 1; + } + else + { + *target_list = 2; + } + *cpu_mask &= ~0xc; + } + else + { + *cpu_mask = 0; + return 0; + } + + return 1; +} \ No newline at end of file diff --git a/bsp/phytium/board/phytium_cpu.c b/bsp/phytium/board/phytium_cpu.c new file mode 100644 index 0000000000..d4dac0a31e --- /dev/null +++ b/bsp/phytium/board/phytium_cpu.c @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include "rtconfig.h" +#include +#include "gicv3.h" + +#include "fparameters.h" +#include "fcpu_info.h" + +#include "phytium_cpu.h" + +int phytium_cpu_id_mapping(int cpu_id) +{ +#if defined(TARGET_E2000Q) + switch (cpu_id) + { + case 0: + return 2; + case 1: + return 3; + case 2: + return 0; + case 3: + return 1; + default: + RT_ASSERT(0); + return 0; + break; + } +#else + return (int)cpu_id; +#endif +} + +#if defined(TARGET_ARMV8_AARCH64) + +int phytium_cpu_id(void) +{ + FError ret; + u32 cpu_id; + ret = GetCpuId(&cpu_id); + + if (ret != ERR_SUCCESS) + { + RT_ASSERT(0); + } + return phytium_cpu_id_mapping(cpu_id); +}; + +#else + +int rt_hw_cpu_id(void) +{ + FError ret; + u32 cpu_id; + ret = GetCpuId(&cpu_id); + + if (ret != ERR_SUCCESS) + { + RT_ASSERT(0); + } + + return phytium_cpu_id_mapping(cpu_id); +}; + + + +rt_uint64_t get_main_cpu_affval(void) +{ +#if defined(TARGET_E2000Q) + return CORE2_AFF; +#else + return CORE0_AFF; +#endif +} + + +extern u32 GetCpuMaskToAffval(u32 *cpu_mask, u32 *cluster_id, u32 *target_list); +rt_uint32_t arm_gic_cpumask_to_affval(rt_uint32_t *cpu_mask, rt_uint32_t *cluster_id, rt_uint32_t *target_list) +{ + return GetCpuMaskToAffval(cpu_mask, cluster_id, target_list); +} + + +#ifdef RT_USING_SMP + +void send_core_isg(void) +{ + for (rt_size_t i = 0; i <= 0xf; i++) + { + /* code */ + rt_kprintf("i %x \r\n", i); + arm_gic_send_affinity_sgi(0, 0, i, 0); + rt_thread_mdelay(100); + } +} +MSH_CMD_EXPORT(send_core_isg, send_core_isg); + +#endif + + +#endif \ No newline at end of file diff --git a/bsp/phytium/board/phytium_cpu.h b/bsp/phytium/board/phytium_cpu.h new file mode 100644 index 0000000000..d0d16dff0e --- /dev/null +++ b/bsp/phytium/board/phytium_cpu.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#ifndef __PHYTIUM_CPU_H__ +#define __PHYTIUM_CPU_H__ + +#include +#include +#include "fparameters.h" + +#define ARM_GIC_MAX_NR 1 +#define MAX_HANDLERS 160 +#define GIC_IRQ_START 0 +#define GIC_ACK_INTID_MASK 0x000003ff + + +rt_uint64_t get_main_cpu_affval(void); + +rt_inline rt_uint32_t platform_get_gic_dist_base(void) +{ + return GICV3_DISTRIBUTOR_BASEADDRESS; +} + +#if defined(TARGET_ARMV8_AARCH64) + +/* the basic constants and interfaces needed by gic */ +rt_inline rt_uint32_t platform_get_gic_redist_base(void) +{ + extern int phytium_cpu_id(void); + + s32 cpu_offset = 0; +#if defined(FT_GIC_REDISTRUBUTIOR_OFFSET) + cpu_offset = FT_GIC_REDISTRUBUTIOR_OFFSET ; +#endif + +#if defined(TARGET_E2000Q) + u32 cpu_id = 0; + cpu_id = phytium_cpu_id(); + + switch (cpu_id) + { + case 0: + case 1: + cpu_offset = 2; + break; + case 2: + case 3: + cpu_offset = -2; + default: + break; + } +#endif + + rt_kprintf("offset is %x\n", cpu_offset); + return (GICV3_RD_BASEADDRESS + (cpu_offset) * GICV3_RD_OFFSET); +} + +rt_inline rt_uint32_t platform_get_gic_cpu_base(void) +{ + return 0U; /* unused in gicv3 */ +} + +#endif + + +int phytium_cpu_id_mapping(int cpu_id); + + + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/board/secondary_cpu.c b/bsp/phytium/board/secondary_cpu.c new file mode 100644 index 0000000000..1e46537e59 --- /dev/null +++ b/bsp/phytium/board/secondary_cpu.c @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * 2022-10-26 zhugengyu support aarch64 + * + */ + +#include +#include "board.h" +#include +#include "rtconfig.h" +#include "phytium_cpu.h" + +#if defined(TARGET_ARMV8_AARCH64) + #include "cpuport.h" + #include "gtimer.h" + #include "mmu.h" +#endif + +#ifdef RT_USING_SMP +#include + +#if defined(TARGET_ARMV8_AARCH64) + #include "psci.h" +#endif + +#include "fpsci.h" + +rt_uint64_t rt_cpu_mpidr_early[] = +{ +#if defined(TARGET_E2000D) + [0] = 0x80000200, + [1] = 0x80000201, +#elif defined(TARGET_E2000Q) + [0] = 0x80000200, + [1] = 0x80000201, + [2] = 0x80000000, + [3] = 0x80000100, +#elif defined(TARGET_F2000_4) || defined(TARGET_D2000) + [0] = 0x80000000, + [1] = 0x80000001, + [2] = 0x80000100, + [3] = 0x80000101, +#if defined(TARGET_D2000) + [4] = 0x80000200, + [5] = 0x80000201, + [6] = 0x80000300, + [7] = 0x80000301, +#endif +#endif + +}; + +extern int rt_hw_timer_init(void); +extern void secondary_cpu_start(void); + +void rt_hw_secondary_cpu_up(void) +{ + rt_uint32_t i; + rt_uint32_t cpu_mask = 0; + + rt_kprintf("rt_hw_secondary_cpu_up is processing \r\n"); + for (i = 1; i < RT_CPUS_NR; i++) + { + + cpu_mask = 1 << phytium_cpu_id_mapping(i); + + /* code */ + PsciCpuOn(cpu_mask, (uintptr)secondary_cpu_start); + + +#if defined(TARGET_ARMV8_AARCH64) + __DSB(); +#else + __asm__ volatile("dsb" ::: "memory"); +#endif + } +} + +void secondary_cpu_c_start(void) +{ + /* mmu init */ +#if defined(TARGET_ARMV8_AARCH64) + rt_hw_mmu_init(); +#endif + /* spin lock init */ + rt_hw_spin_lock(&_cpus_lock); + /* interrupt init */ +#if defined(TARGET_ARMV8_AARCH64) + arm_gic_cpu_init(0, platform_get_gic_cpu_base()); + arm_gic_redist_init(0, platform_get_gic_redist_base()); +#else + arm_gic_cpu_init(0); + arm_gic_redist_init(0); +#endif + + /* vector init */ + rt_hw_vector_init(); + /* gtimer init */ +#if defined(TARGET_ARMV8_AARCH64) + rt_hw_gtimer_local_enable(); +#else + rt_hw_timer_init(); +#endif + rt_hw_interrupt_umask(RT_SCHEDULE_IPI); + + /* start scheduler */ + + rt_kprintf("\rcall cpu %d on success\n", rt_hw_cpu_id()); + rt_hw_secondary_cpu_idle_exec(); + rt_system_scheduler_start(); +} + +void rt_hw_secondary_cpu_idle_exec(void) +{ +#if defined(TARGET_ARMV8_AARCH64) + __WFE(); +#else + asm volatile("wfe" :: + : "memory", "cc"); +#endif +} + +#endif diff --git a/bsp/phytium/figures/config_tftp32.png b/bsp/phytium/figures/config_tftp32.png new file mode 100644 index 0000000000..3e52a8d10b Binary files /dev/null and b/bsp/phytium/figures/config_tftp32.png differ diff --git a/bsp/phytium/figures/result.png b/bsp/phytium/figures/result.png new file mode 100644 index 0000000000..d9910bc1c7 Binary files /dev/null and b/bsp/phytium/figures/result.png differ diff --git a/bsp/phytium/figures/sdk_setup.png b/bsp/phytium/figures/sdk_setup.png new file mode 100644 index 0000000000..aabfd65ce4 Binary files /dev/null and b/bsp/phytium/figures/sdk_setup.png differ diff --git a/bsp/phytium/figures/tftp32_srv.png b/bsp/phytium/figures/tftp32_srv.png new file mode 100644 index 0000000000..6fedb850f4 Binary files /dev/null and b/bsp/phytium/figures/tftp32_srv.png differ diff --git a/bsp/phytium/libraries/SConscript b/bsp/phytium/libraries/SConscript new file mode 100644 index 0000000000..afb3769ac9 --- /dev/null +++ b/bsp/phytium/libraries/SConscript @@ -0,0 +1,76 @@ +import os +from building import * + +objs = [] +cwd = GetCurrentDir() + +STANDALONE_DIR = cwd + '/standalone' + +# common source +src = Glob(STANDALONE_DIR+'/common/*.c') + +path = [STANDALONE_DIR + '/common'] + +# arch +path += [STANDALONE_DIR + '/arch/common'] + +if GetDepend(['TARGET_ARMV8_AARCH32']): + src += Glob(STANDALONE_DIR+'/arch/armv8/aarch32/*.c') + Glob(STANDALONE_DIR+'/arch/armv8/aarch32/gcc/*.S') + path += [STANDALONE_DIR + '/arch/armv8/aarch32'] +elif GetDepend(['TARGET_ARMV8_AARCH64']): + src += Glob(STANDALONE_DIR+'/arch/armv8/aarch64/*.c') + Glob(STANDALONE_DIR+'/arch/armv8/aarch64/gcc/*.S') + path += [STANDALONE_DIR + '/arch/armv8/aarch64'] + +# board +src += Glob(STANDALONE_DIR+'/board/common/*.c') + Glob(STANDALONE_DIR+'/board/common/*.S') +path += [STANDALONE_DIR + '/board/common'] + +if GetDepend(['TARGET_F2000_4']): + src += Glob(STANDALONE_DIR+'/board/ft2004/*.c') + path += [STANDALONE_DIR + '/board/ft2004'] + +if GetDepend(['TARGET_E2000']): + src += Glob(STANDALONE_DIR+'/board/e2000/*.c') + path += [STANDALONE_DIR + '/board/e2000'] + + if GetDepend(['TARGET_E2000Q']): + src += Glob(STANDALONE_DIR+'/board/e2000/q/*.c') + path += [STANDALONE_DIR + '/board/e2000/q'] + + if GetDepend(['TARGET_E2000D']): + src += Glob(STANDALONE_DIR+'/board/e2000/d/*.c') + path += [STANDALONE_DIR + '/board/e2000/d'] + + if GetDepend(['ARGET_E2000S']): + src += Glob(STANDALONE_DIR+'/board/e2000/s/*.c') + path += [STANDALONE_DIR + '/board/e2000/s'] + +if GetDepend(['TARGET_D2000']): + src += Glob(STANDALONE_DIR+'/board/d2000/*.c') + path += [STANDALONE_DIR + '/board/d2000'] + +# driver + +## serial +if GetDepend(['ENABLE_Pl011_UART']): + src += Glob(STANDALONE_DIR+'/drivers/serial/fpl011/*.c') + path += [STANDALONE_DIR + '/drivers/serial/fpl011'] + +## gicv3 +if GetDepend(['ENABLE_GICV3']): + src += Glob(STANDALONE_DIR+'/drivers/gic/fgic/*.c') + Glob(STANDALONE_DIR+'/drivers/gic/fgic/*.S') + path += [STANDALONE_DIR + '/drivers/gic/fgic'] + + +# phytium ports rt-thread drivers +PORT_DRV_DIR = cwd + '/drivers' + +src += Glob(PORT_DRV_DIR + '/*.S') +src += Glob(PORT_DRV_DIR + '/*.c') + +ASFLAGS = '' +group = DefineGroup('FT_DRIVER', src, depend=[ + ''], CPPPATH=path, ASFLAGS = ASFLAGS) + + +Return('group') diff --git a/bsp/phytium/libraries/drivers/Kconfig b/bsp/phytium/libraries/drivers/Kconfig new file mode 100644 index 0000000000..3e264eedfd --- /dev/null +++ b/bsp/phytium/libraries/drivers/Kconfig @@ -0,0 +1,29 @@ +menu "Hardware Drivers" + +menu "On-chip Peripheral Drivers" + menuconfig BSP_USING_UART + bool "Enable UART" + default y + select USE_SERIAL # sdk serial component + select ENABLE_Pl011_UART # select sdk pl011 driver + select RT_USING_SERIAL + if BSP_USING_UART + config RT_USING_UART1 + bool "Enable UART1" + default y + + config RT_USING_UART0 + bool "Enable UART0" + default n + + endif + + + +endmenu + +menu "Board extended module Drivers" + +endmenu + +endmenu diff --git a/bsp/phytium/libraries/drivers/drv_usart.c b/bsp/phytium/libraries/drivers/drv_usart.c new file mode 100644 index 0000000000..788456040a --- /dev/null +++ b/bsp/phytium/libraries/drivers/drv_usart.c @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#include "board.h" +#include "drv_usart.h" +#include "interrupt.h" +#include "fpl011.h" +#include "rtconfig.h" +#include "fprintk.h" + +#ifdef RT_USING_SERIAL + +extern u32 FUart_GetInterruptMask(FPl011 *uart_ptr); + +static void Ft_Os_Uart_Callback(void *Args, u32 Event, u32 EventData); + +static void rt_hw_uart_isr(int irqno, void *param) +{ + FPl011InterruptHandler(irqno, param); +} + +static rt_err_t uart_configure(struct rt_serial_device *serial, struct serial_configure *cfg) +{ + struct drv_usart *uart = RT_NULL; + FPl011 *uart_hw = RT_NULL; + u32 intr_mask; + FPl011Config config; + + RT_ASSERT(serial != RT_NULL); + RT_ASSERT(cfg != RT_NULL); + uart = rt_container_of(serial, struct drv_usart, serial); + uart_hw = uart->handle; + config = *(const FPl011Config *)FPl011LookupConfig(uart->config.uart_instance); + + RT_ASSERT(FPl011CfgInitialize(uart_hw, &config) == FT_SUCCESS); + FPl011SetHandler(uart_hw, Ft_Os_Uart_Callback, serial); + + FPl011SetRxFifoThreadhold(uart_hw, FPL011IFLS_RXIFLSEL_1_4); + FPl011SetTxFifoThreadHold(uart_hw, FPL011IFLS_TXIFLSEL_1_2); + + //config.isr_event_mask; + FPl011SetInterruptMask(uart_hw, intr_mask); + FPl011SetOptions(uart_hw, FPL011_OPTION_UARTEN | FPL011_OPTION_RXEN | FPL011_OPTION_TXEN | FPL011_OPTION_FIFOEN); + + rt_hw_interrupt_set_priority(uart_hw->config.irq_num, uart->config.isr_priority); + rt_hw_interrupt_install(uart_hw->config.irq_num, rt_hw_uart_isr, uart_hw, "uart"); + rt_hw_interrupt_umask(uart_hw->config.irq_num); + + return RT_EOK; +} + +static rt_err_t uart_control(struct rt_serial_device *serial, int cmd, void *arg) +{ + struct drv_usart *uart = RT_NULL; + FPl011 *uart_ptr = RT_NULL; + RT_ASSERT(serial != RT_NULL); + + uart = rt_container_of(serial, struct drv_usart, serial); + uart_ptr = uart->handle; + + switch (cmd) + { + case RT_DEVICE_CTRL_CLR_INT: + /* disable rx irq */ + rt_hw_interrupt_mask(uart_ptr->config.irq_num); + break; + + case RT_DEVICE_CTRL_SET_INT: + /* enable rx irq */ + rt_hw_interrupt_umask(uart_ptr->config.irq_num); + break; + } + + return RT_EOK; +} + +static void Ft_Os_Uart_Callback(void *Args, u32 Event, u32 EventData) +{ + struct rt_serial_device *serial = (struct rt_serial_device *)Args; + + if (FPL011_EVENT_RECV_DATA == Event || FPL011_EVENT_RECV_TOUT == Event) + { + if (serial->serial_rx) + rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_IND); + } + else if (FPL011_EVENT_RECV_ERROR == Event) + { + } + else if (FPL011_EVENT_SENT_DATA == Event) + { + } + else if (FPL011_EVENT_PARE_FRAME_BRKE == Event) + { + } + else if (FPL011_EVENT_RECV_ORERR == Event) + { + } + + if (FPL011_EVENT_SENT_DATA == Event) + { + } + else + { + } +} + +static int uart_putc(struct rt_serial_device *serial, char c) +{ + struct drv_usart *uart = RT_NULL; + FPl011 *uart_ptr = RT_NULL; + RT_ASSERT(serial != RT_NULL); + + uart = rt_container_of(serial, struct drv_usart, serial); + uart_ptr = uart->handle; + + FPl011SendByte(uart_ptr->config.base_address, c); + + return 1; +} + +u8 FPl011RecvByteNoBlocking(u32 addr) +{ + u32 recieved_byte; + + while (FUART_ISRECEIVEDATA(addr)) + { + return 0xff; + } + recieved_byte = FUART_READREG32(addr, FPL011DR_OFFSET); + return recieved_byte; +} + +static int uart_getc(struct rt_serial_device *serial) +{ + int ch; + struct drv_usart *uart = RT_NULL; + FPl011 *uart_ptr = RT_NULL; + RT_ASSERT(serial != RT_NULL); + + uart = rt_container_of(serial, struct drv_usart, serial); + uart_ptr = uart->handle; + + ch = FPl011RecvByteNoBlocking(uart_ptr->config.base_address); + if (ch == 0xff) + { + ch = -1; + rt_kprintf("") ; + } + else + { + // + } + + return ch; +} + +static const struct rt_uart_ops _uart_ops = +{ + uart_configure, + uart_control, + uart_putc, + uart_getc, + NULL +}; + +#define RT_USING_UART0 +#define RT_USING_UART1 + + +#ifdef RT_USING_UART0 + static FPl011 Ft_Uart0; + static struct drv_usart _RtUart0; +#endif + +#ifdef RT_USING_UART1 + static FPl011 Ft_Uart1; + static struct drv_usart _RtUart1; +#endif + +int rt_hw_uart_init(void) +{ + struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT; + +#ifdef RT_USING_UART0 + config.bufsz = RT_SERIAL_RB_BUFSZ; + _RtUart0.serial.ops = &_uart_ops; + _RtUart0.serial.config = config; + // Ft_Uart0.config.instance_id = FUART0_ID; + + _RtUart0.handle = &Ft_Uart0; + _RtUart0.config.uart_instance = FUART0_ID; + _RtUart0.config.isr_priority = 0xd0; + _RtUart0.config.isr_event_mask = (RTOS_UART_ISR_OEIM_MASK | RTOS_UART_ISR_BEIM_MASK | RTOS_UART_ISR_PEIM_MASK | RTOS_UART_ISR_FEIM_MASK | RTOS_UART_ISR_RTIM_MASK | RTOS_UART_ISR_RXIM_MASK); + _RtUart0.config.uart_baudrate = 115200; + + rt_hw_serial_register(&_RtUart0.serial, "uart0", + RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, + &_RtUart0); +#endif + +#ifdef RT_USING_UART1 + config.bufsz = RT_SERIAL_RB_BUFSZ; + _RtUart1.serial.ops = &_uart_ops; + _RtUart1.serial.config = config; + // Ft_Uart1.config.instance_id = FUART1_ID; + _RtUart1.handle = &Ft_Uart1; + + _RtUart1.config.uart_instance = FUART1_ID; + _RtUart1.config.isr_priority = 0xd0; + _RtUart1.config.isr_event_mask = (RTOS_UART_ISR_OEIM_MASK | RTOS_UART_ISR_BEIM_MASK | RTOS_UART_ISR_PEIM_MASK | RTOS_UART_ISR_FEIM_MASK | RTOS_UART_ISR_RTIM_MASK | RTOS_UART_ISR_RXIM_MASK); + _RtUart1.config.uart_baudrate = 115200; + + rt_hw_serial_register(&_RtUart1.serial, "uart1", + RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, + &_RtUart1); +#endif + + return 0; +} +INIT_BOARD_EXPORT(rt_hw_uart_init); + +#endif /* RT_USING_SERIAL */ diff --git a/bsp/phytium/libraries/drivers/drv_usart.h b/bsp/phytium/libraries/drivers/drv_usart.h new file mode 100644 index 0000000000..f82b3dc4d3 --- /dev/null +++ b/bsp/phytium/libraries/drivers/drv_usart.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Email: opensource_embedded@phytium.com.cn + * + * Change Logs: + * Date Author Notes + * 2022-10-26 huanghe first commit + * + */ + +#ifndef __DRV_USART_H__ +#define __DRV_USART_H__ + +#include +#include "rtdevice.h" +#include "fpl011.h" +#include "fpl011_hw.h" + +#define RTOS_UART_ISR_OEIM_MASK FPL011IMSC_OEIM /* Overrun error interrupt mask. */ +#define RTOS_UART_ISR_BEIM_MASK FPL011IMSC_BEIM /* Break error interrupt mask */ +#define RTOS_UART_ISR_PEIM_MASK FPL011IMSC_PEIM /* Parity error interrupt mask. */ +#define RTOS_UART_ISR_FEIM_MASK FPL011IMSC_FEIM /* Framing error interrupt mask. */ +#define RTOS_UART_ISR_RTIM_MASK FPL011IMSC_RTIM /* Receive timeout interrupt mask. */ +#define RTOS_UART_ISR_TXIM_MASK FPL011IMSC_TXIM /* Transmit interrupt mask. */ +#define RTOS_UART_ISR_RXIM_MASK FPL011IMSC_RXIM /* Receive interrupt mask. */ + + +typedef struct +{ + u32 uart_instance; /* select uart global object */ + u32 isr_priority; /* irq Priority */ + u32 isr_event_mask; /* followed by RTOS_UART_ISR_XX */ + u32 uart_baudrate; +} FtFreertosUartConfig; + + +struct drv_usart +{ + FPl011 *handle; + FtFreertosUartConfig config; + struct rt_serial_device serial; +}; + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/LICENSE b/bsp/phytium/libraries/standalone/LICENSE new file mode 100644 index 0000000000..30bd97be52 --- /dev/null +++ b/bsp/phytium/libraries/standalone/LICENSE @@ -0,0 +1,28 @@ + + Phytium Public License 1.0 (PPL-1.0) + +UNLESS IT HAS ITS OWN COPYRIGHT/LICENSE EMBEDDED IN ITS BODY, EACH FILE IS SUBJECT TO THE FOLLOWING LICENSE TERMS + +Copyright (C) 2022, Phytium Technology Co., Ltd. +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that +the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the +following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and +the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. If the name of phytium or the names of its contributors are needed to endorse or promote products +derived from this software ,Prior written permission should be required. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/README.md b/bsp/phytium/libraries/standalone/README.md new file mode 100644 index 0000000000..a9dbcff01a --- /dev/null +++ b/bsp/phytium/libraries/standalone/README.md @@ -0,0 +1,291 @@ +# Phytium-Standalone-SDK + +**v0.3.1** [ReleaseNote](./doc/ChangeLog.md) + +## 1. 项目概要 + +### 1.1 基本介绍 + +本项目发布了 Phytium 系列 CPU 的 嵌入式软件开发工具包,包括板级支持包、第三方开源中间件、交叉编译构建工具、及其 Baremetal 参考例程,在支持多平台裸机应用开发的基础上,能够为多种RTOS提供外设驱动和配置构建工具。 + +![LetterShell](./doc/fig/letter_shell.png) + + +### 1.2 系统架构 + + +本项目的整体设计如下所示,自下而上可以分为平台层、组件层、框架层和应用层。 + +![Framework](./doc/design/system_2.png) + +- 平台层(Platform)在整个软件框架中位于最底层,提供了基本数据结构类型定义、驱动参数标定、硬件平台耦合的寄存器自检、板级启动、CPU 内存虚拟等功能 + +- 组件层(Component)在整个软件框架中位于中间位置,向下依赖于平台层提供的参数配置与内存方案,向上提供应用开发与模块测试的支持 + +- 框架层(Framework)为开发主机提供了开发环境,支持SDK安装,应用工程配置和二进制文件构建及烧录等工具。 + +- 应用层(Application)提供了应用开发模板和例程,帮助开发者迅速熟悉SDK的使用,进行不同类型的应用程序开发 + +### 1.3. 源代码结构 + +``` +. +├── Kconfig --> 配置定义 +├── LICENSE --> 版权声明 +├── README.md --> 使用说明 +├── arch +│   └── armv8 --> 架构相关 +├── baremetal +│   └── example --> 裸机例程 +├── board +│   ├── d2000 +│   ├── e2000 +│   └── ft2004 --> 平台相关 +├── common +│   ├── fprintf.c +│   ├── fprintf.h +│   ├── fsleep.c +│   └── fsleep.h --> 通用方法 +├── configs +│   ├── ft2004_aarch32_defconfig +│   └── ft2004_aarch64_defconfig --> 各平台默认配置 +├── doc +│   ├── ChangeLog.md --> 修改记录 +│   └── reference --> 接口说明文档 +├── drivers +│   ├── can +│   ├── dma +│   └── watchdog --> 外设驱动 +├── install.py --> 安装脚本 +├── lib +│   ├── Kconfiglib +│   ├── lib.mk +│   ├── libc +│   └── nostdlib --> 依赖库 +├── make +│   ├── build_baremetal.mk +│   ├── buildinfo.mk +│   ├── complier.mk +│   └── preconfig.mk --> 编译脚本和链接脚本 +├── requirements.txt --> python环境依赖组件 +├── scripts +├── standalone.mk +├── third-party +│   └── letter-shell-3.1 --> 第三方库 +├── tools +``` + +--- + +## 2. 快速入门 + +- 目前支持在Windows和Linux上使用SDK,支持在x86_64和ARM AARCH64设备上完成交叉编译 + +![windows](./doc/fig/windows.png)![linux](./doc/fig/linux.png)![输入图片说明](./doc/fig/kylin.png) + + +- 参考[Windows10 快速入门](./doc/reference/usr/install_windows.md), [Linux x86_64 快速入门](./doc/reference/usr/install_linux_x86_64.md) + +- 参考[使用说明](./doc/reference/usr/usage.md), 新建Phytium Standalone SDK的应用工程,与开发板建立连接 + +- 参考[例程](./baremetal/example),开始使用SDK + +--- + +## 3. 硬件参考 + +### 3.1 FT2000-4 + +FT-2000/4 是一款面向桌面应用的高性能通用 4 核处理器。每 2 个核构成 1 个处理器核簇(Cluster),并共享 L2 Cache。主要技术特征如下: + +- 兼容 ARM v8 64 位指令系统,兼容 32 位指令 +- 支持单精度、双精度浮点运算指令 +- 支持 ASIMD 处理指令 +- 集成 2 个 DDR4 通道,可对 DDR 存储数据进行实时加密 +- 集成 34 Lane PCIE3.0 接口:2 个 X16(每个可拆分成 2 个 X8),2 个 X1 +- 集成 2 个 GMAC,RGMII 接口,支持 10/100/1000 自适应 +- 集成 1 个 SD 卡控制器,兼容 SD 2.0 规范 +- 集成 1 个 HDAudio,支持音频输出,可同时支持最多 4 个 Codec +- 集成 SM2、SM3、SM4 模块 +- 集成 4 个 UART,1 个 LPC,32 个 GPIO,4 个 I2C,1 个 QSPI,2 个通 用 SPI,2 个 WDT,16 个外部中断(和 GPIO 共用 IO) +- 集成温度传感器 + +### 3.2 D2000 + +D2000 是一款面向桌面应用的高性能通用 8 核处理器。每 2 个核构成 1 个处理器核簇(Cluster),并共享 L2 Cache。存储系统包含 Cache 子系统和 DDR,I/O 系统包含 PCIe、高速 IO 子系统、千兆位以太网 GMAC 和低速 IO 子系统,主要技术特征如下, + +- 兼容 ARM v8 64 位指令系统,兼容 32 位指令 +- 支持单精度、双精度浮点运算指令 +- 支持 ASIMD 处理指令 +- 集成 2 个 DDR 通道,支持 DDR4 和 LPDDR4,可对 DDR 存储数据进行实时加密 +- 集成 34 Lane PCIE3.0 接口:2 个 X16(每个可拆分成 2 个 X8),2 个 X1 +- 集成 2 个 GMAC,RGMII 接口,支持 10/100/1000 自适应 +- 集成 1 个 SD 卡控制器,兼容 SD 2.0 规范 +- 集成 1 个 HDAudio,支持音频输出,可同时支持最多 4 个 Codec +- 集成 SM2、SM3、SM4、SM9 模块 +- 集成 4 个 UART,1 个 LPC,32 个 GPIO,4 个 I2C,1 个 QSPI,2 个通用 SPI,2 个 WDT,16 个外部中断(和 GPIO 共用 IO) +- 集成 2 个温度传感器 + + +### 3.3 E2000D + +- E2000D 1个cluster有2个cpu,共两核。主要技术特征如下: + +- 兼容ARM v8 64 位指令系统,兼容32 位指令 +- 支持单精度、双精度浮点运算指令 +- L1有32KB,L2有256KB +- 集成1个DDR4 通道,可对DDR 存储数据进行实时加密 +- 集成4 Lane PCIE3.0 接口(4X1) +- 集成网络接口4x1000M SGMII,1路支持RGMII/RMII,支持1路TSN +- 集成2个USB2.0(OTG)接口 +- 集成1个HDAudio,支持音频输出;2路DP显示接口 +- 集成2路SATA3.0模块 +- 集成常用低速接口:WDT,DMAC,QSPI,PWM,Nand,SD/SDIO/eMMC ,SPI_M,UART,I2C,MIO,CAN, LPC_M_S,GPIO,LBC,Timer + +### 3.4 E2000S + +- E2000S 1个cluster有1个cpu,单核结构。主要技术特征如下: + +- 兼容ARM v8 64 位指令系统,兼容32 位指令 +- 支持单精度、双精度浮点运算指令 +- L1有32KB,L2有256KB +- 集成1个DDR4 通道,可对DDR 存储数据进行实时加密 +- 集成2 Lane PCIE3.0 接口(2X1) +- 集成网络接口2x1000M SGMII/RGMII/RMII,支持2路NCSI +- 集成2个USB2.0(OTG)接口 +- 集成1个HDAudio,支持音频输出;2路DP显示接口 +- 集成JPEG Encoder模块 +- 集成常用低速接口:WDT,DMAC,PWM,QSPI,SD/SDIO/eMMC,SPI_M,UART,I2C,MIO,I3C,PMBUS, LPC_M_S,GPIO,oneWire,Timer + + +## 4 外设驱动支持情况 + +| Hardware Interface | Platform Supported | Platform Developing | Component | +| ------------------------------ | -------------------------- | --------------------------- | ------------------------- | +| Generic Intrrupt Controller v3 | FT2000/4
E2000
D2000 | | gic/fgic | +| Generic Timer | FT2000/4
E2000
D2000 | | generic_timer | +| UART (PrimeCell PL011) | FT2000/4
E2000
D2000 | | usart/pl011_uart | +| 10/100/1000MB-ETHERNET | FT2000/4
E2000
D2000 | | eth/fgmac
eth/fxmac | +| ADC | E2000 | | adc/fadc | +| CAN | FT2000/4
E2000
D2000 | | can/fcan | +| DDMA | | E2000 | dma/fddma | +| GDMA | E2000 | | dma/gdma | +| GPIO | FT2000/4
E2000
D2000 | | gpio/fgpio | +| I2C | FT2000/4
E2000
D2000 | | i2c/fi2c | +| QSPI (Nor Flash) | FT2000/4
E2000
D2000 | | qspi/fqspi | +| SPI | FT2000/4
E2000
D2000 | | spi/fspim | +| TIMER & TACHO | E2000 | | timer/ftimer_tacho | +| MIO | E2000 | | mio/fmio | +| SDMMC | | FT2000/4
D2000 | mmc/fsdmmc | +| SDIO | E2000 | | mmc/fsdio | +| PCIE | FT2000/4
D2000
E2000 | | pcie/fpcie | +| NAND | E2000 | | nand/fnand | +| RTC | FT2000/4
D2000 | | rtc/frtc | +| SATA | FT2000/4
D2000
E2000 | | sata/fsata | +| USB-PCI | | FT2000/4
E2000
D2000 | usb/fxhci | +| PWM | E2000 | | pwm/fpwm | +| WDT | FT2000/4
D2000
E2000 | | watchdog/fwdt | + + +| Third-Party | Platform Supported | Platform Developing | Component | +| ------------------------------ | -------------------------- | --------------------------- | ------------------------- | +| LWIP 2.1.2 | FT2000/4
D2000
E2000 | | lwip-2.1.2 | +| Letter shell 3.1 | FT2000/4
D2000
E2000 | | letter-shell-3.1 | +| Sdmmc | FT2000/4
D2000 | | sdmmc | +| Sfud 1.1.0 | FT2000/4
D2000
E2000 | | sfud-1.1.0 | +| Backtrace | FT2000/4
D2000
E2000 | | backtrace | +| Tlsf | FT2000/4
D2000
E2000 | | tlsf-3.1.0 | +| Fatfs (RAM/Sd/SATA) | FT2000/4
D2000
E2000 | | fatfs-0.1.3 | +| Ymodem | FT2000/4
D2000
E2000 | | | +| OpenAMP | FT2000/4
D2000
E2000 | | openamp | +| LittleFS-2.4.2 | | FT2000/4
E2000
D2000 | littlefs-2.4.2 | +| SPIFFS-0.3.7 | FT2000/4
D2000
E2000 | | spiffs-0.3.7 | + +--- + +## 5. API指南 + +### 5.1 DRIVERS + +#### 5.1.1 [FI2C](./doc/reference/driver/fi2c.md) + +#### 5.1.2 [FPL011](./doc/reference/driver/fpl011.md) + +#### 5.1.3 [FRTC](./doc/reference/driver/frtc.md) + +#### 5.1.4 [FWDT](./doc/reference/driver/fwdt.md) + +#### 5.1.5 [FSPIM](./doc/reference/driver/fspim.md) + +#### 5.1.6 [FQSPI](./doc/reference/driver/fqspi.md) + +#### 5.1.7 [FSDMMC](./doc/reference/driver/fsdmmc.md) + +#### 5.1.8 [FSATA](./doc/reference/driver/fsata.md) + +#### 5.1.9 [FPCIE](./doc/reference/driver/fpcie.md) + +#### 5.1.10 [FUSB](./doc/reference/driver/fusb.md) + +#### 5.1.11 [FGPIO](./doc/reference/driver/fgpio.md) + +#### 5.1.12 [FGIC](./doc/reference/driver/fgic.md) + +#### 5.1.13 [FDDMA](./doc/reference/driver/fddma.md) + +#### 5.1.14 [FCAN](./doc/reference/driver/fcan.md) + +#### 5.1.15 [FADC](./doc/reference/driver/fadc.md) + +#### 5.1.16 [FPWM](./doc/reference/driver/fpwm.md) + +#### 5.1.17 [FSDIO](./doc/reference/driver/fsdio.md) + +### 5.2 MEMORY +#### 5.2.1 [FMEMORY_POOL](./doc/reference/sdk/fmemory_pool.md) + +### 5.3 CPU + +#### 5.3.1 [MMU](./doc/reference/processor/mmu.md) + +#### 5.3.2 [FPINCTRL](./doc/reference/sdk/fpinctrl.md) + +#### 5.3.2 [INTERRUPT](./doc/reference/processor/interrupt.md) + +--- + +## 6. 贡献方法 + +请联系飞腾嵌入式软件部 + +huanghe@phytium.com.cn + +zhugengyu@phytium.com.cn + +wangxiaodong1030@phytium.com.cn + +liushengming1118@phytium.com.cn + + +--- + +## 6. 相关资源 + + +- ARM Architecture Reference Manual +- ARM Cortex-A Series Programmer’s Guide +- Programmer Guide for ARMv8-A +- ARM System Developers Guide Designing and Optimizing System Software +- FT-2000/4 软件编程手册-V1.4 +- D2000 软件编程手册-V1.0 +- Bare-metal programming for ARM —— A hands-on guide +- Using the GNU Compiler Collection +- Using ld, The GNU Linker +- Using as, The GNU Assembler +- Armv8-A memory model guide + +--- + +## 7. 许可协议 + +Phytium Public License 1.0 (PPL-1.0) diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch32/faarch32.h b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/faarch32.h new file mode 100644 index 0000000000..0a7778fad2 --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/faarch32.h @@ -0,0 +1,416 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: faarch32.h + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:28:37 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Huanghe 2021/7/3 init + * 1.1 Wangxiaodong 2021/9/24 modify sys_icc_bpr_set and sys_icc_bpr_get + */ + +#ifndef BSP_AARCH32_ASM_H +#define BSP_AARCH32_ASM_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" + +#define __ASM __asm +#define __STATIC_INLINE static inline +#define __STRINGIFY(x) #x +/* C语言实现MCR指令 */ +#define __MCR(coproc, opcode_1, src, CRn, CRm, opcode_2) \ + __ASM volatile("MCR " __STRINGIFY(p##coproc) ", " __STRINGIFY(opcode_1) ", " \ + "%0, " __STRINGIFY(c##CRn) ", " __STRINGIFY(c##CRm) ", " __STRINGIFY(opcode_2) \ + : \ + : "r"(src) \ + : "memory"); + +/* C语言实现MRC指令 */ +#define __MRC(coproc, opcode_1, CRn, CRm, opcode_2) \ + ( \ + { \ + u32 __dst; \ + __ASM volatile("MRC " __STRINGIFY(p##coproc) ", " __STRINGIFY(opcode_1) ", " \ + "%0, " __STRINGIFY(c##CRn) ", " __STRINGIFY(c##CRm) ", " __STRINGIFY(opcode_2) \ + : "=r"(__dst)::"memory"); \ + __dst; \ + }) + +/* C语言实现MRRC指令 */ +#define __MRRC(coproc, opcode_1, dst_1, dst_2, CRm) ( \ + { \ + __asm__ __volatile__( \ + "MRRC " __STRINGIFY(p##coproc) ", " __STRINGIFY(opcode_1) ", " \ + "%0,%1," __STRINGIFY(c##CRm) \ + : "=r"(dst_1), "=r"(dst_2)); \ + }) + +/** + * @name: aarch32_cntp_ctl_get + * @msg: Read the register that holds the timer value for the EL1 physical timer. + * @return {__STATIC_INLINEu32}: TimerValue, bits [31:0] The TimerValue view of the EL1 physical timer. + */ +__attribute__((always_inline)) __STATIC_INLINE u32 aarch32_cntp_ctl_get(void) +{ + /* MRC p15(coproc) 0(opcode1) CR14(n) CR2(m) 1(opcode2) */ + return __MRC(15, 0, 14, 2, 1); +} + +/** + * @name: aarch32_cntp_tlb_get + * @msg: + * @return {*} + * @param {__STATIC_INLINE u32} aarch32_cntp_ctl_get + */ +__attribute__((always_inline)) __STATIC_INLINE u32 aarch32_cntp_tlb_get(void) +{ + return __MRC(15, 0, 0, 2, 0); +} + +/** + * @name: aarch32_cntp_ctl_set + * @msg: Read the register that holds the timer value for the EL1 physical timer. + * @return {__STATIC_INLINEu32}: TimerValue, bits [31:0] The TimerValue view of the EL1 physical timer. + */ +__attribute__((always_inline)) __STATIC_INLINE void aarch32_cntp_ctl_set(u32 regVal) +{ + /* MRC p15(coproc) regVal 0(opcode1) CR14(n) CR2(m) 1(opcode2) */ + __MCR(15, 0, regVal, 14, 2, 1); +} + +/** + * @name: arm_aarch32_cntfrq_get + * @msg: This register is provided so that software can discover the frequency of the system counter. + * @return {__STATIC_INLINEu32}: frequency of the system counter + */ +__attribute__((always_inline)) __STATIC_INLINE u32 aarch32_cntfrq_get(void) +{ + return __MRC(15, 0, 14, 0, 0); +} + +/** + * @name: aarch32_cntpct_get + * @msg: get the 64-bit physical count value + * @return {*} + * @param {__STATIC_INLINE u64} aarch32_cntpct_get + */ +__attribute__((always_inline)) __STATIC_INLINE u64 aarch32_cntpct_get() +{ + u64 cnt = 0; + u32 cnt_low = 0, cnt_high = 0; + __MRRC(15, 0, cnt_low, cnt_high, 14); + cnt = (u64)cnt_high << 32 | cnt_low; + return cnt; +} + +/** + * @name: aarch32_cntp_tval_set + * @msg: write the register that control register for the EL1 physical timer. + * @in param {u32}: TimerValue, bits [31:0] The TimerValue view of the EL1 physical timer. + */ +__attribute__((always_inline)) __STATIC_INLINE void aarch32_cntp_tval_set(u32 RegValue) +{ + __MCR(15, 0, RegValue, 14, 2, 0); +} + +/** + * @name: aarch32_sctrl_get + * @msg: read the register that control system + */ +__attribute__((always_inline)) __STATIC_INLINE u32 aarch32_sctrl_get() +{ + return __MRC(15, 0, 1, 0, 0); +} + +/** + * @name: aarch32_sctrl_set + * @msg: read the register that control system + */ +#define AARCH32_SCTRL_CACHE_BIT (1 << 2) /* 1: enable, 0: disable */ +__attribute__((always_inline)) __STATIC_INLINE void aarch32_sctrl_set(u32 RegVal) +{ + __MCR(15, 0, RegVal, 1, 0, 0); +} + +/**********************************************/ + +__attribute__((always_inline)) __STATIC_INLINE u32 __get_VBAR(void) +{ + return __MRC(15, 0, 12, 0, 0); +} + +__attribute__((always_inline)) __STATIC_INLINE void __set_VBAR(u32 vbar) +{ + __MCR(15, 0, vbar, 12, 0, 0); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_igrpen0_set(u32 value) +{ + __MCR(15, 0, value, 12, 12, 6); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_igrpen0_get(void) +{ + return __MRC(15, 0, 12, 12, 6); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_igrpen1_set(u32 value) +{ + __MCR(15, 0, value, 12, 12, 7); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_igrpen1_get(void) +{ + return __MRC(15, 0, 12, 12, 7); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_ctlr_set(u32 value) +{ + __MCR(15, 0, value, 12, 12, 4); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_ctlr_get(void) +{ + return __MRC(15, 0, 12, 12, 4); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_hppir0_get(void) +{ + return __MRC(15, 0, 12, 8, 2); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_bpr_set(u32 value) +{ + __MCR(15, 0, value, 12, 12, 3); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_bpr_get(void) +{ + return __MRC(15, 0, 12, 12, 3); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_hppir1_get(void) +{ + return __MRC(15, 0, 12, 12, 2); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_eoir0_set(u32 value) +{ + __MCR(15, 0, value, 12, 8, 1); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_eoir1_set(u32 value) +{ + __MCR(15, 0, value, 12, 12, 1); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_pmr_set(u32 value) +{ + __MCR(15, 0, value, 4, 6, 0); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_pmr_get(void) +{ + return __MRC(15, 0, 4, 6, 0); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_iar1_get(void) +{ + return __MRC(15, 0, 12, 12, 0); +} + +__attribute__((always_inline)) __STATIC_INLINE void sys_icc_sre_set(u32 value) +{ + __MCR(15, 0, value, 12, 12, 5); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_sre_get(void) +{ + return __MRC(15, 0, 12, 12, 5); +} + +__attribute__((always_inline)) __STATIC_INLINE u32 sys_icc_rpr_get(void) +{ + return __MRC(15, 0, 12, 11, 3); +} + +/* Generic Timer registers */ +/** + * @name: arm_aarch32_cntfrq_get + * @msg: This register is provided so that software can discover the frequency of the system counter. + * @return {__STATIC_INLINEu32}: frequency of the system counter + */ +__attribute__((always_inline)) __STATIC_INLINE u32 arm_aarch32_cntfrq_get(void) +{ + return __MRC(15, 0, 14, 0, 0); +} + +/* arm_aarch32_cnttimer_set */ +__attribute__((always_inline)) __STATIC_INLINE void arm_aarch32_cnttimer_set(u32 RegValue) +{ + __MCR(15, 0, RegValue, 14, 2, 2); +} + +/** + * @name: arm_aarch32_cnthv_tval_get + * @msg: Provides AArch32 access to the timer value for the EL2 virtual timer. + * @return {__STATIC_INLINEu32}: EL2 virtual timer Cnt. + */ +__attribute__((always_inline)) __STATIC_INLINE u32 arm_aarch32_cnthv_tval_get(void) +{ + return __MRC(15, 0, 14, 3, 0); +} + +/** + * @name: arm_aarch32_cnthv_ctl_set + * @msg: Provides AArch32 access to the control register for the EL2 virtual timer. + * @in param {u32}: RegValue;ENABLE: bit [0] 0 Timer disabled,1 Timer enabled. + * IMASK,bit [1]: 0 Timer interrupt is not masked by the IMASK bit. 1 Timer interrupt is masked by the IMASK bit. + * ISTATUS, bit [2]: 0 Timer condition is not met. 1 Timer condition is met. rea-only + */ +__attribute__((always_inline)) __STATIC_INLINE void arm_aarch32_cnthv_ctl_set(u32 RegValue) +{ + __MCR(15, 0, RegValue, 14, 3, 1); +} + +/** + * @name: arm_aarch32_cnthv_ctl_get + * @msg: Provides AArch32 access to the control register for the EL2 virtual timer. + * @return {__STATIC_INLINEu32}: RegValue;ENABLE: bit [0] 0 Timer disabled,1 Timer enabled. + * IMASK,bit [1]: 0 Timer interrupt is not masked by the IMASK bit. 1 Timer interrupt is masked by the IMASK bit. + * ISTATUS, bit [2]: 0 Timer condition is not met. 1 Timer condition is met. read-only + */ +__attribute__((always_inline)) __STATIC_INLINE u32 arm_aarch32_cnthv_ctl_get(void) +{ + return __MRC(15, 0, 14, 3, 1); +} + +/** + * @name: arm_aarch32_cnthv_tval_set + * @msg: Provides AArch32 access to the timer value for the EL2 virtual timer. + * @in param {u32}: TimerValue, bits [31:0] The TimerValue view of the EL2 virtual timer. + */ +__attribute__((always_inline)) __STATIC_INLINE void arm_aarch32_cnthv_tval_set(u32 RegValue) +{ + __MCR(15, 0, RegValue, 14, 3, 0); +} + +/** + * @name: arm_aarch32_cntvct_get + * @msg: Read the register that holds the 64-bit virtual count value. The virtual count value is equal to the physical count value visible in CNTPCT minus the virtual offset visible in CNTVOFF. + * @return {__STATIC_INLINEu64}Bits [63:0] Virtual count value. + */ +__attribute__((always_inline)) __STATIC_INLINE u64 arm_aarch32_cntvct_get(void) +{ + /* "r0" --- low, + "r1" --- hi + */ + u32 low; + u32 hi; + __asm__ volatile( + ".word 0xec510f1e \n" /* mrrc p15, 1, r0, r1, c14 */ + "mov %0, r0 \n" + "mov %1, r1 \n" + : "=&r"(low), "=&r"(hi)); + return (((u64)hi) << 32) | low; +} + +/* physical */ + +/** + * @name: arm_aarch32_cntp_tval_get + * @msg: Read the register that holds the timer value for the EL1 physical timer. + * @return {__STATIC_INLINEu32}: TimerValue, bits [31:0] The TimerValue view of the EL1 physical timer. + */ +__attribute__((always_inline)) __STATIC_INLINE u32 arm_aarch32_cntp_tval_get(void) +{ + return __MRC(15, 0, 14, 2, 0); +} + +/** + * @name: arm_aarch32_cntp_tval_set + * @msg: write the register that control register for the EL1 physical timer. + * @in param {u32}: TimerValue, bits [31:0] The TimerValue view of the EL1 physical timer. + */ +__attribute__((always_inline)) __STATIC_INLINE void arm_aarch32_cntp_tval_set(u32 RegValue) +{ + __MCR(15, 0, RegValue, 14, 2, 0); +} + +/** + * @name: arm_aarch32_cntp_ctl_set + * @msg: write the register that control register for the EL1 physical timer. + * @in param {u32}: ENABLE, bit[0] Enables the timer ; IMASK, bit [1] Timer interrupt mask bit; ISTATUS, bit [2] The status of the timer. + */ +__attribute__((always_inline)) __STATIC_INLINE void arm_aarch32_cntp_ctl_set(u32 RegValue) +{ + __MCR(15, 0, RegValue, 14, 2, 1); +} + +/** + * @name: arm_aarch32_cntp_ctl_get + * @msg: Read the register that control register for the EL1 physical timer. + * @return {__STATIC_INLINEu32}: ENABLE, bit[0] Enables the timer ; IMASK, bit [1] Timer interrupt mask bit; ISTATUS, bit [2] The status of the timer. + */ +__attribute__((always_inline)) __STATIC_INLINE u32 arm_aarch32_cntp_ctl_get(void) +{ + return __MRC(15, 0, 14, 2, 1); +} + +/** + * @name: arm_aarch32_cntpct_get + * @msg: Read the register that holds the 64-bit physical count value. + * @return {__STATIC_INLINEu64} CompareValue, bits [63:0] Physical count value. + */ +__attribute__((always_inline)) __STATIC_INLINE u64 arm_aarch32_cntpct_get(void) +{ + /* "r0" --- low, + "r1" --- hi + */ + u32 low; + u32 hi; + __asm__ volatile( + + ".word 0xec510f0e \n" /* mrrc p15, 0, r0, r1, c14 */ + "mov %0, r0 \n" + "mov %1, r1 \n" + : "=&r"(low), "=&r"(hi)); + return (((u64)hi) << 32) | low; +} + +#define INTERRUPT_DISABLE() \ + __asm volatile("CPSID i" :: \ + : "memory"); \ + __asm volatile("DSB"); \ + __asm volatile("ISB"); + +#define INTERRUPT_ENABLE() \ + __asm volatile("CPSIE i" :: \ + : "memory"); \ + __asm volatile("DSB"); \ + __asm volatile("ISB"); + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fgeneric_timer.c b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fgeneric_timer.c new file mode 100644 index 0000000000..082a74eb4e --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fgeneric_timer.c @@ -0,0 +1,154 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: generic_timer.c + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:30:07 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fparameters.h" +#include "fgeneric_timer.h" +#include "faarch32.h" +#include "sdkconfig.h" + +#ifndef SDK_CONFIG_H__ + #warning "Please include sdkconfig.h" +#endif + +#ifdef CONFIG_USE_SYS_TICK + #include "fassert.h" + #include "finterrupt.h" + + static volatile u32 genericTick; + static GenericTimerTickHandler usr_tick_handler = NULL; +#endif + +#define AARCH32_CNTP_CTL_ENABLE_MASK (1ul << 0) +#define AARCH32_CNTP_CTL_INTERRUPT_MASK (1ul << 1) + +void GenericTimerStart(void) +{ + u32 ctrl = aarch32_cntp_ctl_get(); + + if (!(ctrl & AARCH32_CNTP_CTL_ENABLE_MASK)) + { + ctrl |= AARCH32_CNTP_CTL_ENABLE_MASK; + aarch32_cntp_ctl_set(ctrl); + } +} + +void GenericTimerStop(void) +{ + u32 ctrl = aarch32_cntp_ctl_get(); + if ((ctrl & AARCH32_CNTP_CTL_ENABLE_MASK)) + { + ctrl &= ~AARCH32_CNTP_CTL_ENABLE_MASK; + aarch32_cntp_ctl_set(ctrl); + } +} + +void GenericTimerInterruptEnable(void) +{ + u32 ctrl = aarch32_cntp_ctl_get(); + if (ctrl & AARCH32_CNTP_CTL_INTERRUPT_MASK) + { + ctrl &= ~AARCH32_CNTP_CTL_INTERRUPT_MASK; + aarch32_cntp_ctl_set(ctrl); + } +} + +void GenericTimerInterruptDisable(void) +{ + u64 ctrl = aarch32_cntp_ctl_get(); + if (!(ctrl & AARCH32_CNTP_CTL_INTERRUPT_MASK)) + { + ctrl |= AARCH32_CNTP_CTL_INTERRUPT_MASK; + aarch32_cntp_ctl_set(ctrl); + } +} + +u32 GenericTimerFrequecy(void) +{ + u32 rate = aarch32_cntfrq_get(); + return (rate != 0) ? rate : 1000000; +} + +u64 GenericTimerRead(void) +{ + return aarch32_cntpct_get(); +} + +void GenericTimerCompare(u32 interval) +{ + aarch32_cntp_tval_set(interval); +} + +#ifdef CONFIG_USE_SYS_TICK +static void GenericTimerClearTickIntr(u32 tickRateHz) +{ + GenericTimerCompare(GenericTimerFrequecy() / tickRateHz); +} + +static void GenericTimerTickIntrHandler(s32 vector, void *param) +{ + u32 tickRateHz = (u32)param; + (void)vector; + genericTick++; /* tick */ + GenericTimerClearTickIntr(tickRateHz); /* clear tick intrrupt */ + + if (usr_tick_handler) /* execute user handler */ + usr_tick_handler(); +} +#endif + +void GenericTimerSetupSystick(u32 tickRateHz, GenericTimerTickHandler tickHandler, u32 intrPrority) +{ +#ifdef CONFIG_USE_SYS_TICK + u32 cntFrq; + + /* disable timer and get system frequency */ + GenericTimerStop(); + cntFrq = GenericTimerFrequecy(); + + /* set tick rate */ + GenericTimerCompare(cntFrq / tickRateHz); + GenericTimerInterruptEnable(); + + /* set generic timer intrrupt */ + InterruptSetPriority(GENERIC_TIMER_NS_IRQ_NUM, intrPrority); + + /* install tick handler */ + usr_tick_handler = tickHandler; + InterruptInstall(GENERIC_TIMER_NS_IRQ_NUM, GenericTimerTickIntrHandler, + (void *)tickRateHz, "GenericTimerTick"); + + /* enable intrrupt */ + InterruptUmask(GENERIC_TIMER_NS_IRQ_NUM); + GenericTimerStart(); +#endif +} + +u32 GenericGetTick(void) +{ +#ifdef CONFIG_USE_SYS_TICK + return genericTick; +#else + return 0xffU; +#endif +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fgeneric_timer.h b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fgeneric_timer.h new file mode 100644 index 0000000000..5a247c3fbd --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fgeneric_timer.h @@ -0,0 +1,51 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgeneric_timer.h + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:30:13 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef BSP_ARCH_ARMV8_AARCH32_GENERIC_TIMER_H +#define BSP_ARCH_ARMV8_AARCH32_GENERIC_TIMER_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" + +typedef void (* GenericTimerTickHandler)(); + +void GenericTimerStart(void); +void GenericTimerStop(void); +void GenericTimerInterruptEnable(void); +void GenericTimerInterruptDisable(void); +u32 GenericTimerFrequecy(void); +u64 GenericTimerRead(void); +void GenericTimerCompare(u32 interval); +void GenericTimerSetupSystick(u32 tickRateHz, GenericTimerTickHandler tickHandler, u32 intrPrority); +u32 GenericGetTick(void); + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fpsci.c b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fpsci.c new file mode 100644 index 0000000000..2c2e298b23 --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fpsci.c @@ -0,0 +1,75 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: psci.c + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:30:35 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fpsci.h" +#include "fsmc.h" +#include "fcpu_info.h" +#include "ferror_code.h" +#include "fparameters.h" +#include "ftypes.h" + +#define PSCI_CPUON_NUM 0x84000003 +#define PSCI_RESET_NUM 0x84000009 + +/** + * @name: FPsci_CpuOn + * @msg: Power up a core + * @in param cpu_id_mask: cpu id mask + * @in param bootaddr: a 32-bit entry point physical address (or IPA). + * @return FError + */ +FError PsciCpuOn(s32 cpu_id_mask, uintptr bootaddr) +{ + FError ret ; + u64 cluster = 0; + FSmc_Data_t input = {0}; + FSmc_Data_t output = {0}; + input.function_identifier = PSCI_CPUON_NUM; + ret = GetCpuAffinityByMask(cpu_id_mask, &cluster); + if (ret != ERR_SUCCESS) + { + return ret; + } + + input.a1 = cluster; + + input.a2 = (u32)(bootaddr & 0xFFFFFFFF); + FSmcCall(&input, &output); + __asm__ volatile("NOP"); + return ERR_SUCCESS; +} + +void PsciCpuReset(void) +{ + + FSmc_Data_t input = {0}; + FSmc_Data_t output = {0}; + + input.function_identifier = PSCI_RESET_NUM; + FSmcCall(&input, &output); + + __asm__ volatile("NOP"); + while (1) + ; +} diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fpsci.h b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fpsci.h new file mode 100644 index 0000000000..d79f0ba548 --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fpsci.h @@ -0,0 +1,43 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpsci.h + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:30:40 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef BSP_ARCH_ARMV8_AARCH32_PSCI_H +#define BSP_ARCH_ARMV8_AARCH32_PSCI_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "ferror_code.h" + +FError PsciCpuOn(s32 cpu_id_mask, uintptr bootaddr); +void PsciCpuReset(void); + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fsmc.h b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fsmc.h new file mode 100644 index 0000000000..8fc2005940 --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/fsmc.h @@ -0,0 +1,53 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsmc.h + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:30:49 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef BSP_ARCH_ARMV8_AARCH32_SMC_H +#define BSP_ARCH_ARMV8_AARCH32_SMC_H + +#ifdef __cplusplus +extern "C" +{ +#endif +#include "ftypes.h" + +typedef struct +{ + /* data */ + u32 function_identifier; + u32 a1; + u32 a2; + u32 a3; + u32 a4; + u32 a5; + u32 a6; + +} FSmc_Data_t; + +void FSmcCall(FSmc_Data_t *Input, FSmc_Data_t *Output); + +#ifdef __cplusplus +} +#endif + +#endif // !FT_SMC_H diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch32/gcc/fsmccc_call.S b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/gcc/fsmccc_call.S new file mode 100644 index 0000000000..16b14b209e --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch32/gcc/fsmccc_call.S @@ -0,0 +1,58 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: smccc-call.S + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:28:10 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/******************************************************************************* +* +* FSmcCall - initiate SMC call +* +* This routine initiates SMC call which traps the processor into Monitor Mode. +* The ARM SMC Call Convetion defines that up to eight registers can be exchanged +* during an SMC call. The input parameter contains eight INT32 valeus which are +* to be passed in the SMC call; similarily the output parameter also contains +* eight INT32 values which are returned from the SMC call. +* +* \NOMANUAL +* +* RETURNS: OK +* +* void FSmcCall +* ( +* FSmc_Data_t * input, /@ r0 - input register values @/ +* FSmc_Data_t * output /@ r1 - output register values @/ +* ) +*/ + +.arm +.align 4 +.globl FSmcCall +FSmcCall: + STMDB sp!, {r0-r7} /* save clobbered registers to stack */ + ldr r12, [sp, #(4 * 0)] /* get 1st argument (ptr to input struct) */ + ldmia r12, {r0-r7} /* save input argument to r0-r7 */ + smc #0 + ldr r12, [sp, #(4 * 1)] /* get 2th argument (ptr to output result) */ + stmia r12, {r0-r7} /* get output argument from r0-r7 */ + ldmfd sp!, {r0-r7} /* restore clobbered registers from stack */ + bx lr +.size FSmcCall, .- FSmcCall diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch64/farm_smccc.h b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/farm_smccc.h new file mode 100644 index 0000000000..c682d38533 --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/farm_smccc.h @@ -0,0 +1,125 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: farm_smccc.h + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:32:15 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef __LINUX_ARM_SMCCC_H +#define __LINUX_ARM_SMCCC_H + +/* + * This file provides common defines for ARM SMC Calling Convention as + * specified in + * http://infocenter.arm.com/help/topic/com.arm.doc.den0028a/index.html + */ + +#define ARM_SMCCC_STD_CALL 0 +#define ARM_SMCCC_FAST_CALL 1 +#define ARM_SMCCC_TYPE_SHIFT 31 + +#define ARM_SMCCC_SMC_32 0 +#define ARM_SMCCC_SMC_64 1 +#define ARM_SMCCC_CALL_CONV_SHIFT 30 + +#define ARM_SMCCC_OWNER_MASK 0x3F +#define ARM_SMCCC_OWNER_SHIFT 24 + +#define ARM_SMCCC_FUNC_MASK 0xFFFF + +#define ARM_SMCCC_IS_FAST_CALL(smc_val) \ + ((smc_val) & (ARM_SMCCC_FAST_CALL << ARM_SMCCC_TYPE_SHIFT)) +#define ARM_SMCCC_IS_64(smc_val) \ + ((smc_val) & (ARM_SMCCC_SMC_64 << ARM_SMCCC_CALL_CONV_SHIFT)) +#define ARM_SMCCC_FUNC_NUM(smc_val) ((smc_val)&ARM_SMCCC_FUNC_MASK) +#define ARM_SMCCC_OWNER_NUM(smc_val) \ + (((smc_val) >> ARM_SMCCC_OWNER_SHIFT) & ARM_SMCCC_OWNER_MASK) + +#define ARM_SMCCC_CALL_VAL(type, calling_convention, owner, func_num) \ + (((type) << ARM_SMCCC_TYPE_SHIFT) | \ + ((calling_convention) << ARM_SMCCC_CALL_CONV_SHIFT) | \ + (((owner)&ARM_SMCCC_OWNER_MASK) << ARM_SMCCC_OWNER_SHIFT) | \ + ((func_num)&ARM_SMCCC_FUNC_MASK)) + +#define ARM_SMCCC_OWNER_ARCH 0 +#define ARM_SMCCC_OWNER_CPU 1 +#define ARM_SMCCC_OWNER_SIP 2 +#define ARM_SMCCC_OWNER_OEM 3 +#define ARM_SMCCC_OWNER_STANDARD 4 +#define ARM_SMCCC_OWNER_TRUSTED_APP 48 +#define ARM_SMCCC_OWNER_TRUSTED_APP_END 49 +#define ARM_SMCCC_OWNER_TRUSTED_OS 50 +#define ARM_SMCCC_OWNER_TRUSTED_OS_END 63 + +#define ARM_SMCCC_QUIRK_NONE 0 +#define ARM_SMCCC_QUIRK_QCOM_A6 1 /* Save/restore register a6 */ + +#ifndef __ASSEMBLY__ + +#include +/** + * struct arm_smccc_res - Result from SMC/HVC call + * @a0-a3 result values from registers 0 to 3 + */ +struct arm_smccc_res +{ + unsigned long a0; + unsigned long a1; + unsigned long a2; + unsigned long a3; +}; + +/** + * struct arm_smccc_quirk - Contains quirk information + * @id: quirk identification + * @state: quirk specific information + * @a6: Qualcomm quirk entry for returning post-smc call contents of a6 + */ +struct arm_smccc_quirk +{ + int id; + union + { + unsigned long a6; + } state; +}; + +/** + * __arm_smccc_smc() - make SMC calls + * @a0-a7: arguments passed in registers 0 to 7 + * @res: result values from registers 0 to 3 + * @quirk: points to an arm_smccc_quirk, or NULL when no quirks are required. + * + * This function is used to make SMC calls following SMC Calling Convention. + * The content of the supplied param are copied to registers 0 to 7 prior + * to the SMC instruction. The return values are updated with the content + * from register 0 to 3 on return from the SMC instruction. An optional + * quirk structure provides vendor specific behavior. + */ +void __arm_smccc_smc(unsigned long a0, unsigned long a1, + unsigned long a2, unsigned long a3, unsigned long a4, + unsigned long a5, unsigned long a6, unsigned long a7, + struct arm_smccc_res *res, struct arm_smccc_quirk *quirk); + +#define arm_smccc_smc(...) __arm_smccc_smc(__VA_ARGS__, NULL) + +#define arm_smccc_smc_quirk(...) __arm_smccc_smc(__VA_ARGS__) + +#endif /*__ASSEMBLY__*/ +#endif /*__LINUX_ARM_SMCCC_H*/ \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch64/fpsci.c b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/fpsci.c new file mode 100644 index 0000000000..fb5f8ec686 --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/fpsci.c @@ -0,0 +1,47 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: psci.c + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:33:51 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fpsci.h" +#include "farm_smccc.h" +#include "ftypes.h" +#include "fcpu_info.h" +#include "ferror_code.h" + +FError PsciCpuOn(s32 cpu_id_mask, uintptr bootaddr) +{ + FError ret ; + u64 cluster = 0; + ret = GetCpuAffinityByMask(cpu_id_mask, &cluster); + if (ret != ERR_SUCCESS) + { + printf("GetCpuAffinity is failed \r\n") ; + return ret ; + } + arm_smccc_smc(0xc4000003, cluster, bootaddr, 0, 0, 0, 0, 0, 0); + return ERR_SUCCESS ; +} +void PsciCpuReset(void) +{ + struct arm_smccc_res res; + arm_smccc_smc(0x84000009, 0, 0, 0, 0, 0, 0, 0, &res); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch64/fpsci.h b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/fpsci.h new file mode 100644 index 0000000000..513332661b --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/fpsci.h @@ -0,0 +1,41 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpsci.h + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:34:06 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef BSP_ARCH_AARMV8_AARCH64_PSCI_H +#define BSP_ARCH_AARMV8_AARCH64_PSCI_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "ferror_code.h" +void PsciCpuReset(void); +FError PsciCpuOn(s32 cpu_id_mask, uintptr bootaddr); + +#ifdef __cplusplus +} +#endif +#endif // !BSP_ARCH_AARMV8_AARCH64_PSCI_H \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/arch/armv8/aarch64/gcc/fsmccc_call.S b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/gcc/fsmccc_call.S new file mode 100644 index 0000000000..78464c59bf --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/armv8/aarch64/gcc/fsmccc_call.S @@ -0,0 +1,49 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: smccc-call.S + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:31:23 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +.macro SMCCC instr + \instr #0 + ldr x4, [sp] + stp x0, x1, [x4, #0] + stp x2, x3, [x4, #16] + ldr x4, [sp, #8] + cbz x4, 1f /* no quirk structure */ + ldr x9, [x4, #0] + cmp x9, #1 + b.ne 1f + str x6, [x4, 4] +1: ret +.endm SMCCC instr + +/* + * void arm_smccc_smc(unsigned long a0, unsigned long a1, unsigned long a2, + * unsigned long a3, unsigned long a4, unsigned long a5, + * unsigned long a6, unsigned long a7, struct arm_smccc_res *res, + * struct arm_smccc_quirk *quirk) + */ + .globl __arm_smccc_smc +.type __arm_smccc_smc, "function" + .cfi_startproc +__arm_smccc_smc: + SMCCC smc + .cfi_endproc diff --git a/bsp/phytium/libraries/standalone/arch/common/fkernel.h b/bsp/phytium/libraries/standalone/arch/common/fkernel.h new file mode 100644 index 0000000000..60efa30bb4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/arch/common/fkernel.h @@ -0,0 +1,237 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: kernel.h + * Date: 2022-02-10 14:53:41 + * LastEditTime: 2022-02-17 17:35:07 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef KERNEL_H +#define KERNEL_H + +#ifdef __ASSEMBLY__ + #define _AC(X, Y) X + #define _AT(T, X) X +#else + #define __AC(X, Y) (X##Y) + #define _AC(X, Y) __AC(X, Y) + #define _AT(T, X) ((T)(X)) +#endif + +#define _UL(x) (_AC(x, UL)) +#define _ULL(x) (_AC(x, ULL)) + +#define _BITUL(x) (_UL(1) << (x)) +#define _BITULL(x) (_ULL(1) << (x)) + +#define UL(x) (_UL(x)) +#define ULL(x) (_ULL(x)) + +#define min(x, y) ( \ + { \ + typeof(x) _min1 = (x); \ + typeof(y) _min2 = (y); \ + (void)(&_min1 == &_min2); \ + _min1 < _min2 ? _min1 : _min2; \ + }) + +#define max(x, y) ( \ + { \ + typeof(x) _max1 = (x); \ + typeof(y) _max2 = (y); \ + (void)(&_max1 == &_max2); \ + _max1 > _max2 ? _max1 : _max2; \ + }) + +#define min3(x, y, z) min((typeof(x))min(x, y), z) +#define max3(x, y, z) max((typeof(x))max(x, y), z) + +/** + * clamp - return a value clamped to a given range with strict typechecking + * @val: current value + * @lo: lowest allowable value + * @hi: highest allowable value + * + * This macro does strict typechecking of @lo/@hi to make sure they are of the + * same type as @val. See the unnecessary pointer comparisons. + */ +#define clamp(val, lo, hi) min((typeof(val))max(val, lo), hi) + +/** + * do_div - returns 2 values: calculate remainder and update new dividend + * @n: uint64_t dividend (will be updated) + * @base: uint32_t divisor + * + * Summary: + * ``uint32_t remainder = n % base;`` + * ``n = n / base;`` + * + * Return: (uint32_t)remainder + * + * NOTE: macro parameter @n is evaluated multiple times, + * beware of side effects! + */ +#define do_div(n, base) ( \ + { \ + uint32_t __base = (base); \ + uint32_t __rem; \ + __rem = ((uint64_t)(n)) % __base; \ + (n) = ((uint64_t)(n)) / __base; \ + __rem; \ + }) + +/* The `const' in roundup() prevents gcc-3.3 from calling __divdi3 */ +#define roundup(x, y) ( \ + { \ + const typeof(y) __y = y; \ + ((x + (__y - 1)) / __y) * __y; \ + }) +#define rounddown(x, y) ( \ + { \ + typeof(x) __x = (x); \ + __x - (__x % (y)); \ + }) + +#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d)) + +#if defined(__aarch64__) + #define BITS_PER_LONG 64 +#else + #define BITS_PER_LONG 32 +#endif + +#ifndef BITS_PER_LONG_LONG + #define BITS_PER_LONG_LONG 64 +#endif + +#define BIT(nr) (1ULL << (nr)) +#define BIT_ULL(nr) (1ULL << (nr)) +#define BIT_MASK(nr) (BIT(nr) - 1UL) +#define BIT_WORD(nr) ((nr) / BITS_PER_LONG) +#define BIT_ULL_MASK(nr) (1ULL << ((nr) % BITS_PER_LONG_LONG)) +#define BIT_ULL_WORD(nr) ((nr) / BITS_PER_LONG_LONG) +#define BITS_PER_BYTE 8 + +#define DIV_ROUND_DOWN_ULL(ll, d) \ + ({ unsigned long long _tmp = (ll); do_div(_tmp, d); _tmp; }) +#define DIV_ROUND_UP_ULL(ll, d) DIV_ROUND_DOWN_ULL((ll) + (d) - 1, (d)) + +#if BITS_PER_LONG == 32 + #define DIV_ROUND_UP_SECTOR_T(ll,d) DIV_ROUND_UP_ULL(ll, d) +#else + #define DIV_ROUND_UP_SECTOR_T(ll,d) DIV_ROUND_UP(ll,d) +#endif + +/* + * Create a contiguous bitmask starting at bit position @l and ending at + * position @h. For example + * GENMASK_ULL(39, 21) gives us the 64bit vector 0x000000ffffe00000. + */ +#define GENMASK(h, l) \ + (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h)))) + +#define GENMASK_ULL(h, l) \ + (((~0ULL) - (1ULL << (l)) + 1) & \ + (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h)))) + +#define SZ_1 0x00000001 +#define SZ_2 0x00000002 +#define SZ_4 0x00000004 +#define SZ_8 0x00000008 +#define SZ_16 0x00000010 +#define SZ_32 0x00000020 +#define SZ_64 0x00000040 +#define SZ_128 0x00000080 +#define SZ_256 0x00000100 +#define SZ_512 0x00000200 + +#define SZ_1K 0x00000400 +#define SZ_2K 0x00000800 +#define SZ_4K 0x00001000 +#define SZ_8K 0x00002000 +#define SZ_16K 0x00004000 +#define SZ_32K 0x00008000 +#define SZ_64K 0x00010000 +#define SZ_128K 0x00020000 +#define SZ_256K 0x00040000 +#define SZ_512K 0x00080000 + +#define SZ_1M 0x00100000 +#define SZ_2M 0x00200000 +#define SZ_4M 0x00400000 +#define SZ_8M 0x00800000 +#define SZ_16M 0x01000000 +#define SZ_32M 0x02000000 +#define SZ_64M 0x04000000 +#define SZ_128M 0x08000000 +#define SZ_256M 0x10000000 +#define SZ_512M 0x20000000 + +#define SZ_1G 0x40000000 +#define SZ_2G 0x80000000 +#define SZ_3G 0xC0000000 +#define SZ_4G 0x100000000ULL +#define SZ_8G 0x200000000ULL + +#define NANO_TO_MICRO 1000 +#define NANO_TO_KILO 1000000 + +/** + * UPPER_32_BITS - return bits 32-63 of a number + * @n: the number we're accessing + * + * A basic shift-right of a 64- or 32-bit quantity. Use this to suppress + * the "right shift count >= width of type" warning when that quantity is + * 32-bits. + * Note that do not input signed int 'n' + */ +#define UPPER_32_BITS(n) ((uint32_t)(((n) >> 16) >> 16)) + +/** + * LOWER_32_BITS - return bits 0-31 of a number + * @n: the number we're accessing + * Note that do not input signed int 'n' + */ +#define LOWER_32_BITS(n) ((uint32_t)((n)&0xffffffff)) +#define IS_ALIGNED(x, a) (((x) & ((typeof(x))(a)-1)) == 0) + +#ifndef __aligned + #define __aligned(x) __attribute__((__aligned__(x))) +#endif + +/** + * CONTAINER_OF - return the member address of ptr, if the type of ptr is the + * struct type. + */ +#define CONTAINER_OF(ptr, type, member) \ + ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) + +#ifndef ARRAY_SIZE + #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#endif + +/* set 32-bit register [a:b] as x, where a is high bit, b is low bit, x is setting/getting value */ +#define GET_REG32_BITS(x, a, b) (u32)((((u32)(x)) & GENMASK(a, b)) >> b) +#define SET_REG32_BITS(x, a, b) (u32)((((u32)(x)) << b) & GENMASK(a, b)) + +/* Integer alignment down */ +#define PALIGN_DOWN(x,align) (x & ~(align-1)) +/* Integer alignment up */ +#define PALIGN_UP(x,align) ((x + (align-1)) & ~(align-1)) +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/Kconfig b/bsp/phytium/libraries/standalone/board/Kconfig new file mode 100644 index 0000000000..c8fee782a4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/Kconfig @@ -0,0 +1,50 @@ +menu "Board Configuration" + + choice BUILD_TARGET_CHIP_TYPE + prompt "Chip" + default TARGET_E2000Q + help + Select chip type for build + + config TARGET_F2000_4 + bool "FT2000-4" + + config TARGET_D2000 + bool "D2000" + + config TARGET_E2000Q + bool "E2000Q" + select TARGET_E2000 + + config TARGET_E2000D + bool "E2000D" + select TARGET_E2000 + + config TARGET_E2000S + bool "E2000S" + select TARGET_E2000 + + endchoice # BUILD_TARGET_CHIP_TYPE + + # an invisible config to define common code of E2000 Q/D/S + config TARGET_E2000 + bool + default y if TARGET_E2000Q || TARGET_E2000D || TARGET_E2000S + + choice DEBUG_PRINT_UART + prompt "Select Debug uart instance" + default DEFAULT_DEBUG_PRINT_UART1 + help + Select arch for build + config DEFAULT_DEBUG_PRINT_UART1 + bool "Use uart1" + config DEFAULT_DEBUG_PRINT_UART0 + bool "Use uart0" + config DEFAULT_DEBUG_PRINT_UART2 + bool "Use uart2" + endchoice # DEBUG_PRINT_UART + + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/board/common/fcpu_asm.S b/bsp/phytium/libraries/standalone/board/common/fcpu_asm.S new file mode 100644 index 0000000000..530186fecf --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/common/fcpu_asm.S @@ -0,0 +1,63 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: _cpu_asm.S + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-17 17:57:55 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "sdkconfig.h" + +#ifdef CONFIG_TARGET_ARMV8_AARCH64 +// ------------------------------------------------------------ + .global GetAffinity + //uint32_t GetAffinity(void); + .type GetAffinity, @function +GetAffinity: + MRS x0, MPIDR_EL1 + RET + + +.global ArchSpinLock; +.text; +ArchSpinLock: + mov w2, #1 + sevl +1: + wfe + ldaxr w1, [x0] + cbnz w1, 1b + stxr w1, w2, [x0] + cbnz w1, 1b + ret + + +.global ArchSpinUnlock; +.text; +ArchSpinUnlock: + stlr xzr, [x0] + ret + +#else + +.globl GetAffinity +GetAffinity: + mrc p15, #0, r0, c0, c0, #5 @ read multiprocessor affinity register + bx lr + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/common/fcpu_info.c b/bsp/phytium/libraries/standalone/board/common/fcpu_info.c new file mode 100644 index 0000000000..7e711e2018 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/common/fcpu_info.c @@ -0,0 +1,264 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: cpu_info.c + * Date: 2022-03-08 19:37:19 + * LastEditTime: 2022-03-15 11:18:14 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fcpu_info.h" +#include "ferror_code.h" +#include "fparameters.h" +#include "fprintk.h" + +FError GetCpuId(u32 *cpu_id_p) +{ + u32 affinity = GetAffinity(); + FError ret = ERR_SUCCESS ; + + switch (affinity & 0xfff) + { +#ifdef CORE0_AFF + case CORE0_AFF: + *cpu_id_p = 0 ; + break; +#endif +#ifdef CORE1_AFF + case CORE1_AFF: + *cpu_id_p = 1 ; + break; +#endif +#ifdef CORE2_AFF + case CORE2_AFF: + *cpu_id_p = 2; + break; +#endif +#ifdef CORE3_AFF + case CORE3_AFF: + *cpu_id_p = 3 ; + break; +#endif +#ifdef CORE4_AFF + case CORE4_AFF: + *cpu_id_p = 4 ; + break; +#endif +#ifdef CORE5_AFF + case CORE5_AFF: + *cpu_id_p = 5 ; + break; +#endif +#ifdef CORE6_AFF + case CORE6_AFF: + *cpu_id_p = 6 ; + break; +#endif +#ifdef CORE7_AFF + case CORE7_AFF: + *cpu_id_p = 7 ; + break; +#endif + default: + ret = ERR_GENERAL ; + break; + } + return ret; +} + +/** + * @name: GetCpuAffinityByMask + * @msg: Determine the cluster information using the CPU ID + * @param {u32} cpu_id cpu id mask .for example : 1 is core0 ,2 is core1 ..... + * @param {u64} *affinity_level_p cluster information , format is: + * |--------[bit31-24]-------[bit23-16]-------------[bit15-8]--------[bit7-0] + * |--------Affinity level3-----Affinity level2-----Affinity level1---Affinity level0 + * @return {*} ERR_SUCCESS is ok + */ +FError GetCpuAffinityByMask(u32 cpu_id_mask, u64 *affinity_level_p) +{ + FError ret = ERR_SUCCESS ; + switch (cpu_id_mask) + { +#ifdef CORE0_AFF + case (1<<0): + *affinity_level_p = CORE0_AFF; + break ; +#endif +#ifdef CORE1_AFF + case (1<<1): + *affinity_level_p = CORE1_AFF; + break ; +#endif +#ifdef CORE2_AFF + case (1<<2): + *affinity_level_p = CORE2_AFF; + break ; +#endif +#ifdef CORE3_AFF + case (1<<3): + *affinity_level_p = CORE3_AFF; + break ; +#endif +#ifdef CORE4_AFF + case (1<<4): + *affinity_level_p = CORE4_AFF; + break ; +#endif +#ifdef CORE5_AFF + case (1<<5): + *affinity_level_p = CORE5_AFF; + break ; +#endif +#ifdef CORE6_AFF + case (1<<6): + *affinity_level_p = CORE6_AFF; + break ; +#endif +#ifdef CORE7_AFF + case (1<<7): + *affinity_level_p = CORE7_AFF; + break ; +#endif + default: + ret = ERR_GENERAL; + break; + } + return ret; +} + + +/** + * @name: GetCpuAffinity + * @msg: Determine the cluster information using the CPU ID + * @param {u32} cpu_id cpu id .for example : 0 is core0 ,1 is core1 ..... + * @param {u64} *affinity_level_p cluster information , format is: + * |--------[bit31-24]-------[bit23-16]-------------[bit15-8]--------[bit7-0] + * |--------Affinity level3-----Affinity level2-----Affinity level1---Affinity level0 + * @return {*} ERR_SUCCESS is ok + */ +FError GetCpuAffinity(u32 cpu_id, u64 *affinity_level_p) +{ + FError ret = ERR_SUCCESS ; + switch (cpu_id) + { +#ifdef CORE0_AFF + case (0): + *affinity_level_p = CORE0_AFF; + break ; +#endif +#ifdef CORE1_AFF + case (1): + *affinity_level_p = CORE1_AFF; + break ; +#endif +#ifdef CORE2_AFF + case (2): + *affinity_level_p = CORE2_AFF; + break ; +#endif +#ifdef CORE3_AFF + case (3): + *affinity_level_p = CORE3_AFF; + break ; +#endif +#ifdef CORE4_AFF + case (4): + *affinity_level_p = CORE4_AFF; + break ; +#endif +#ifdef CORE5_AFF + case (5): + *affinity_level_p = CORE5_AFF; + break ; +#endif +#ifdef CORE6_AFF + case (6): + *affinity_level_p = CORE6_AFF; + break ; +#endif +#ifdef CORE7_AFF + case (7): + *affinity_level_p = CORE7_AFF; + break ; +#endif + default: + ret = ERR_GENERAL; + break; + } + return ret; +} + + +/** + * @name: UseAffinityGetCpuId + * @msg: Get the core value from affinity level + * @param {u64} affinity_level is cpu affinity level value + * @param {u32*} cpu_id_p is pointer to get cpu id value + * @return {*} ERR_SUCCESS is ok , ERR_GENERAL is fail + */ +FError UseAffinityGetCpuId(u64 affinity_level, u32 *cpu_id_p) +{ + FError ret = ERR_SUCCESS ; + switch (affinity_level) + { +#ifdef CORE0_AFF + case CORE0_AFF: + *cpu_id_p = 0; + break ; +#endif +#ifdef CORE1_AFF + case CORE1_AFF: + *cpu_id_p = 1; + break ; +#endif +#ifdef CORE2_AFF + case CORE2_AFF: + *cpu_id_p = 2; + break ; +#endif +#ifdef CORE3_AFF + case CORE3_AFF: + *cpu_id_p = 3; + break ; +#endif +#ifdef CORE4_AFF + case CORE4_AFF: + *cpu_id_p = 4; + break ; +#endif +#ifdef CORE5_AFF + case CORE5_AFF: + *cpu_id_p = 5; + break ; +#endif +#ifdef CORE6_AFF + case CORE6_AFF: + *cpu_id_p = 6; + break ; +#endif +#ifdef CORE7_AFF + case CORE7_AFF: + *cpu_id_p = 7; + break ; +#endif + default: + ret = ERR_GENERAL; + break; + } + return ret; +} diff --git a/bsp/phytium/libraries/standalone/board/common/fcpu_info.h b/bsp/phytium/libraries/standalone/board/common/fcpu_info.h new file mode 100644 index 0000000000..b5434f2d19 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/common/fcpu_info.h @@ -0,0 +1,44 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcpu_info.h + * Date: 2022-03-08 19:37:19 + * LastEditTime: 2022-03-15 11:18:07 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BOARD_COMMON_CPU_INFO_H +#define BOARD_COMMON_CPU_INFO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "ferror_code.h" +u32 GetAffinity(void); +FError GetCpuId(u32 *cpu_id_p); +FError GetCpuAffinity(u32 cpu_id, u64 *cluster_value_p); +FError GetCpuAffinityByMask(u32 cpu_id, u64 *affinity_level_p); +FError UseAffinityGetCpuId(u64 affinity_level, u32 *cpu_id_p); +u32 GetCpuMaskToAffval(u32 *cpu_mask, u32 *cluster_id, u32 *target_list); +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/common/fsmp.h b/bsp/phytium/libraries/standalone/board/common/fsmp.h new file mode 100644 index 0000000000..b0ee12f339 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/common/fsmp.h @@ -0,0 +1,34 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsmp.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-17 17:58:18 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef BSP_BOARD_COMMON_SMP_H +#define BSP_BOARD_COMMON_SMP_H + +#include "ftypes.h" + +void SpinLockInit(unsigned long global_addr); +void SpinLock(void); +void SpinUnlock(void); + +#endif // DEBUG \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/d/fiopad.h b/bsp/phytium/libraries/standalone/board/e2000/d/fiopad.h new file mode 100644 index 0000000000..41af7df2ed --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/d/fiopad.h @@ -0,0 +1,269 @@ + +#ifndef BOARD_E2000D_FIOPAD_H +#define BOARD_E2000D_FIOPAD_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fiopad_comm.h" + +/************************** Constant Definitions *****************************/ +/* register offset of iopad function / pull / driver strength */ +#define FIOPAD_AN55 (FPinIndex)FIOPAD_INDEX(FIOPAD_0_FUNC_OFFSET) +#define FIOPAD_AW43 (FPinIndex)FIOPAD_INDEX(FIOPAD_2_FUNC_OFFSET) +#define FIOPAD_AR51 (FPinIndex)FIOPAD_INDEX(FIOPAD_9_FUNC_OFFSET) +#define FIOPAD_AJ51 (FPinIndex)FIOPAD_INDEX(FIOPAD_10_FUNC_OFFSET) +#define FIOPAD_AL51 (FPinIndex)FIOPAD_INDEX(FIOPAD_11_FUNC_OFFSET) +#define FIOPAD_AL49 (FPinIndex)FIOPAD_INDEX(FIOPAD_12_FUNC_OFFSET) +#define FIOPAD_AN47 (FPinIndex)FIOPAD_INDEX(FIOPAD_13_FUNC_OFFSET) +#define FIOPAD_AR47 (FPinIndex)FIOPAD_INDEX(FIOPAD_14_FUNC_OFFSET) +#define FIOPAD_BA53 (FPinIndex)FIOPAD_INDEX(FIOPAD_15_FUNC_OFFSET) +#define FIOPAD_BA55 (FPinIndex)FIOPAD_INDEX(FIOPAD_16_FUNC_OFFSET) +#define FIOPAD_AW53 (FPinIndex)FIOPAD_INDEX(FIOPAD_17_FUNC_OFFSET) +#define FIOPAD_AW55 (FPinIndex)FIOPAD_INDEX(FIOPAD_18_FUNC_OFFSET) +#define FIOPAD_AU51 (FPinIndex)FIOPAD_INDEX(FIOPAD_19_FUNC_OFFSET) +#define FIOPAD_AN53 (FPinIndex)FIOPAD_INDEX(FIOPAD_20_FUNC_OFFSET) +#define FIOPAD_AL55 (FPinIndex)FIOPAD_INDEX(FIOPAD_21_FUNC_OFFSET) +#define FIOPAD_AJ55 (FPinIndex)FIOPAD_INDEX(FIOPAD_22_FUNC_OFFSET) +#define FIOPAD_AJ53 (FPinIndex)FIOPAD_INDEX(FIOPAD_23_FUNC_OFFSET) +#define FIOPAD_AG55 (FPinIndex)FIOPAD_INDEX(FIOPAD_24_FUNC_OFFSET) +#define FIOPAD_AG53 (FPinIndex)FIOPAD_INDEX(FIOPAD_25_FUNC_OFFSET) +#define FIOPAD_AE55 (FPinIndex)FIOPAD_INDEX(FIOPAD_26_FUNC_OFFSET) +#define FIOPAD_AC55 (FPinIndex)FIOPAD_INDEX(FIOPAD_27_FUNC_OFFSET) +#define FIOPAD_AC53 (FPinIndex)FIOPAD_INDEX(FIOPAD_28_FUNC_OFFSET) +#define FIOPAD_AR45 (FPinIndex)FIOPAD_INDEX(FIOPAD_31_FUNC_OFFSET) +#define FIOPAD_BA51 (FPinIndex)FIOPAD_INDEX(FIOPAD_32_FUNC_OFFSET) +#define FIOPAD_BA49 (FPinIndex)FIOPAD_INDEX(FIOPAD_33_FUNC_OFFSET) +#define FIOPAD_AR55 (FPinIndex)FIOPAD_INDEX(FIOPAD_34_FUNC_OFFSET) +#define FIOPAD_AU55 (FPinIndex)FIOPAD_INDEX(FIOPAD_35_FUNC_OFFSET) +#define FIOPAD_AR53 (FPinIndex)FIOPAD_INDEX(FIOPAD_36_FUNC_OFFSET) +#define FIOPAD_BA45 (FPinIndex)FIOPAD_INDEX(FIOPAD_37_FUNC_OFFSET) +#define FIOPAD_AW51 (FPinIndex)FIOPAD_INDEX(FIOPAD_38_FUNC_OFFSET) +#define FIOPAD_A31 (FPinIndex)FIOPAD_INDEX(FIOPAD_39_FUNC_OFFSET) +#define FIOPAD_R53 (FPinIndex)FIOPAD_INDEX(FIOPAD_40_FUNC_OFFSET) +#define FIOPAD_R55 (FPinIndex)FIOPAD_INDEX(FIOPAD_41_FUNC_OFFSET) +#define FIOPAD_U55 (FPinIndex)FIOPAD_INDEX(FIOPAD_42_FUNC_OFFSET) +#define FIOPAD_W55 (FPinIndex)FIOPAD_INDEX(FIOPAD_43_FUNC_OFFSET) +#define FIOPAD_U53 (FPinIndex)FIOPAD_INDEX(FIOPAD_44_FUNC_OFFSET) +#define FIOPAD_AA53 (FPinIndex)FIOPAD_INDEX(FIOPAD_45_FUNC_OFFSET) +#define FIOPAD_AA55 (FPinIndex)FIOPAD_INDEX(FIOPAD_46_FUNC_OFFSET) +#define FIOPAD_AW47 (FPinIndex)FIOPAD_INDEX(FIOPAD_47_FUNC_OFFSET) +#define FIOPAD_AU47 (FPinIndex)FIOPAD_INDEX(FIOPAD_48_FUNC_OFFSET) +#define FIOPAD_A35 (FPinIndex)FIOPAD_INDEX(FIOPAD_49_FUNC_OFFSET) +#define FIOPAD_C35 (FPinIndex)FIOPAD_INDEX(FIOPAD_50_FUNC_OFFSET) +#define FIOPAD_C33 (FPinIndex)FIOPAD_INDEX(FIOPAD_51_FUNC_OFFSET) +#define FIOPAD_A33 (FPinIndex)FIOPAD_INDEX(FIOPAD_52_FUNC_OFFSET) +#define FIOPAD_A37 (FPinIndex)FIOPAD_INDEX(FIOPAD_53_FUNC_OFFSET) +#define FIOPAD_A39 (FPinIndex)FIOPAD_INDEX(FIOPAD_54_FUNC_OFFSET) +#define FIOPAD_A41 (FPinIndex)FIOPAD_INDEX(FIOPAD_55_FUNC_OFFSET) +#define FIOPAD_C41 (FPinIndex)FIOPAD_INDEX(FIOPAD_56_FUNC_OFFSET) +#define FIOPAD_A43 (FPinIndex)FIOPAD_INDEX(FIOPAD_57_FUNC_OFFSET) +#define FIOPAD_A45 (FPinIndex)FIOPAD_INDEX(FIOPAD_58_FUNC_OFFSET) +#define FIOPAD_C45 (FPinIndex)FIOPAD_INDEX(FIOPAD_59_FUNC_OFFSET) +#define FIOPAD_A47 (FPinIndex)FIOPAD_INDEX(FIOPAD_60_FUNC_OFFSET) +#define FIOPAD_A29 (FPinIndex)FIOPAD_INDEX(FIOPAD_61_FUNC_OFFSET) +#define FIOPAD_C29 (FPinIndex)FIOPAD_INDEX(FIOPAD_62_FUNC_OFFSET) +#define FIOPAD_C27 (FPinIndex)FIOPAD_INDEX(FIOPAD_63_FUNC_OFFSET) +#define FIOPAD_A27 (FPinIndex)FIOPAD_INDEX(FIOPAD_64_FUNC_OFFSET) +#define FIOPAD_AJ49 (FPinIndex)FIOPAD_INDEX(FIOPAD_65_FUNC_OFFSET) +#define FIOPAD_AL45 (FPinIndex)FIOPAD_INDEX(FIOPAD_66_FUNC_OFFSET) +#define FIOPAD_AL43 (FPinIndex)FIOPAD_INDEX(FIOPAD_67_FUNC_OFFSET) +#define FIOPAD_AN45 (FPinIndex)FIOPAD_INDEX(FIOPAD_68_FUNC_OFFSET) +#define FIOPAD_AG47 (FPinIndex)FIOPAD_INDEX(FIOPAD_148_FUNC_OFFSET) +#define FIOPAD_AJ47 (FPinIndex)FIOPAD_INDEX(FIOPAD_69_FUNC_OFFSET) +#define FIOPAD_AG45 (FPinIndex)FIOPAD_INDEX(FIOPAD_70_FUNC_OFFSET) +#define FIOPAD_AE51 (FPinIndex)FIOPAD_INDEX(FIOPAD_71_FUNC_OFFSET) +#define FIOPAD_AE49 (FPinIndex)FIOPAD_INDEX(FIOPAD_72_FUNC_OFFSET) +#define FIOPAD_AG51 (FPinIndex)FIOPAD_INDEX(FIOPAD_73_FUNC_OFFSET) +#define FIOPAD_AJ45 (FPinIndex)FIOPAD_INDEX(FIOPAD_74_FUNC_OFFSET) +#define FIOPAD_AC51 (FPinIndex)FIOPAD_INDEX(FIOPAD_75_FUNC_OFFSET) +#define FIOPAD_AC49 (FPinIndex)FIOPAD_INDEX(FIOPAD_76_FUNC_OFFSET) +#define FIOPAD_AE47 (FPinIndex)FIOPAD_INDEX(FIOPAD_77_FUNC_OFFSET) +#define FIOPAD_W47 (FPinIndex)FIOPAD_INDEX(FIOPAD_78_FUNC_OFFSET) +#define FIOPAD_W51 (FPinIndex)FIOPAD_INDEX(FIOPAD_79_FUNC_OFFSET) +#define FIOPAD_W49 (FPinIndex)FIOPAD_INDEX(FIOPAD_80_FUNC_OFFSET) +#define FIOPAD_U51 (FPinIndex)FIOPAD_INDEX(FIOPAD_81_FUNC_OFFSET) +#define FIOPAD_U49 (FPinIndex)FIOPAD_INDEX(FIOPAD_82_FUNC_OFFSET) +#define FIOPAD_AE45 (FPinIndex)FIOPAD_INDEX(FIOPAD_83_FUNC_OFFSET) +#define FIOPAD_AC45 (FPinIndex)FIOPAD_INDEX(FIOPAD_84_FUNC_OFFSET) +#define FIOPAD_AE43 (FPinIndex)FIOPAD_INDEX(FIOPAD_85_FUNC_OFFSET) +#define FIOPAD_AA43 (FPinIndex)FIOPAD_INDEX(FIOPAD_86_FUNC_OFFSET) +#define FIOPAD_AA45 (FPinIndex)FIOPAD_INDEX(FIOPAD_87_FUNC_OFFSET) +#define FIOPAD_W45 (FPinIndex)FIOPAD_INDEX(FIOPAD_88_FUNC_OFFSET) +#define FIOPAD_AA47 (FPinIndex)FIOPAD_INDEX(FIOPAD_89_FUNC_OFFSET) +#define FIOPAD_U45 (FPinIndex)FIOPAD_INDEX(FIOPAD_90_FUNC_OFFSET) +#define FIOPAD_G55 (FPinIndex)FIOPAD_INDEX(FIOPAD_91_FUNC_OFFSET) +#define FIOPAD_J55 (FPinIndex)FIOPAD_INDEX(FIOPAD_92_FUNC_OFFSET) +#define FIOPAD_L53 (FPinIndex)FIOPAD_INDEX(FIOPAD_93_FUNC_OFFSET) +#define FIOPAD_C55 (FPinIndex)FIOPAD_INDEX(FIOPAD_94_FUNC_OFFSET) +#define FIOPAD_E55 (FPinIndex)FIOPAD_INDEX(FIOPAD_95_FUNC_OFFSET) +#define FIOPAD_J53 (FPinIndex)FIOPAD_INDEX(FIOPAD_96_FUNC_OFFSET) +#define FIOPAD_L55 (FPinIndex)FIOPAD_INDEX(FIOPAD_97_FUNC_OFFSET) +#define FIOPAD_N55 (FPinIndex)FIOPAD_INDEX(FIOPAD_98_FUNC_OFFSET) +#define FIOPAD_C53 (FPinIndex)FIOPAD_INDEX(FIOPAD_29_FUNC_OFFSET) +#define FIOPAD_E53 (FPinIndex)FIOPAD_INDEX(FIOPAD_30_FUNC_OFFSET) +#define FIOPAD_E27 (FPinIndex)FIOPAD_INDEX(FIOPAD_99_FUNC_OFFSET) +#define FIOPAD_G27 (FPinIndex)FIOPAD_INDEX(FIOPAD_100_FUNC_OFFSET) +#define FIOPAD_N37 (FPinIndex)FIOPAD_INDEX(FIOPAD_101_FUNC_OFFSET) +#define FIOPAD_N35 (FPinIndex)FIOPAD_INDEX(FIOPAD_102_FUNC_OFFSET) +#define FIOPAD_J29 (FPinIndex)FIOPAD_INDEX(FIOPAD_103_FUNC_OFFSET) +#define FIOPAD_N29 (FPinIndex)FIOPAD_INDEX(FIOPAD_104_FUNC_OFFSET) +#define FIOPAD_L29 (FPinIndex)FIOPAD_INDEX(FIOPAD_105_FUNC_OFFSET) +#define FIOPAD_N41 (FPinIndex)FIOPAD_INDEX(FIOPAD_106_FUNC_OFFSET) +#define FIOPAD_N39 (FPinIndex)FIOPAD_INDEX(FIOPAD_107_FUNC_OFFSET) +#define FIOPAD_L27 (FPinIndex)FIOPAD_INDEX(FIOPAD_108_FUNC_OFFSET) +#define FIOPAD_J27 (FPinIndex)FIOPAD_INDEX(FIOPAD_109_FUNC_OFFSET) +#define FIOPAD_J25 (FPinIndex)FIOPAD_INDEX(FIOPAD_110_FUNC_OFFSET) +#define FIOPAD_E25 (FPinIndex)FIOPAD_INDEX(FIOPAD_111_FUNC_OFFSET) +#define FIOPAD_G25 (FPinIndex)FIOPAD_INDEX(FIOPAD_112_FUNC_OFFSET) +#define FIOPAD_N23 (FPinIndex)FIOPAD_INDEX(FIOPAD_113_FUNC_OFFSET) +#define FIOPAD_L25 (FPinIndex)FIOPAD_INDEX(FIOPAD_114_FUNC_OFFSET) +#define FIOPAD_J33 (FPinIndex)FIOPAD_INDEX(FIOPAD_115_FUNC_OFFSET) +#define FIOPAD_J35 (FPinIndex)FIOPAD_INDEX(FIOPAD_116_FUNC_OFFSET) +#define FIOPAD_G37 (FPinIndex)FIOPAD_INDEX(FIOPAD_117_FUNC_OFFSET) +#define FIOPAD_E39 (FPinIndex)FIOPAD_INDEX(FIOPAD_118_FUNC_OFFSET) +#define FIOPAD_L39 (FPinIndex)FIOPAD_INDEX(FIOPAD_119_FUNC_OFFSET) +#define FIOPAD_C39 (FPinIndex)FIOPAD_INDEX(FIOPAD_120_FUNC_OFFSET) +#define FIOPAD_E37 (FPinIndex)FIOPAD_INDEX(FIOPAD_121_FUNC_OFFSET) +#define FIOPAD_L41 (FPinIndex)FIOPAD_INDEX(FIOPAD_122_FUNC_OFFSET) +#define FIOPAD_J39 (FPinIndex)FIOPAD_INDEX(FIOPAD_123_FUNC_OFFSET) +#define FIOPAD_J37 (FPinIndex)FIOPAD_INDEX(FIOPAD_124_FUNC_OFFSET) +#define FIOPAD_L35 (FPinIndex)FIOPAD_INDEX(FIOPAD_125_FUNC_OFFSET) +#define FIOPAD_E33 (FPinIndex)FIOPAD_INDEX(FIOPAD_126_FUNC_OFFSET) +#define FIOPAD_E31 (FPinIndex)FIOPAD_INDEX(FIOPAD_127_FUNC_OFFSET) +#define FIOPAD_G31 (FPinIndex)FIOPAD_INDEX(FIOPAD_128_FUNC_OFFSET) +#define FIOPAD_J31 (FPinIndex)FIOPAD_INDEX(FIOPAD_129_FUNC_OFFSET) +#define FIOPAD_L33 (FPinIndex)FIOPAD_INDEX(FIOPAD_130_FUNC_OFFSET) +#define FIOPAD_N31 (FPinIndex)FIOPAD_INDEX(FIOPAD_131_FUNC_OFFSET) +#define FIOPAD_R47 (FPinIndex)FIOPAD_INDEX(FIOPAD_132_FUNC_OFFSET) +#define FIOPAD_R45 (FPinIndex)FIOPAD_INDEX(FIOPAD_133_FUNC_OFFSET) +#define FIOPAD_N47 (FPinIndex)FIOPAD_INDEX(FIOPAD_134_FUNC_OFFSET) +#define FIOPAD_N51 (FPinIndex)FIOPAD_INDEX(FIOPAD_135_FUNC_OFFSET) +#define FIOPAD_L51 (FPinIndex)FIOPAD_INDEX(FIOPAD_136_FUNC_OFFSET) +#define FIOPAD_J51 (FPinIndex)FIOPAD_INDEX(FIOPAD_137_FUNC_OFFSET) +#define FIOPAD_J41 (FPinIndex)FIOPAD_INDEX(FIOPAD_138_FUNC_OFFSET) +#define FIOPAD_E43 (FPinIndex)FIOPAD_INDEX(FIOPAD_139_FUNC_OFFSET) +#define FIOPAD_G43 (FPinIndex)FIOPAD_INDEX(FIOPAD_140_FUNC_OFFSET) +#define FIOPAD_J43 (FPinIndex)FIOPAD_INDEX(FIOPAD_141_FUNC_OFFSET) +#define FIOPAD_J45 (FPinIndex)FIOPAD_INDEX(FIOPAD_142_FUNC_OFFSET) +#define FIOPAD_N45 (FPinIndex)FIOPAD_INDEX(FIOPAD_143_FUNC_OFFSET) +#define FIOPAD_L47 (FPinIndex)FIOPAD_INDEX(FIOPAD_144_FUNC_OFFSET) +#define FIOPAD_L45 (FPinIndex)FIOPAD_INDEX(FIOPAD_145_FUNC_OFFSET) +#define FIOPAD_N49 (FPinIndex)FIOPAD_INDEX(FIOPAD_146_FUNC_OFFSET) +#define FIOPAD_J49 (FPinIndex)FIOPAD_INDEX(FIOPAD_147_FUNC_OFFSET) + +/* register offset of iopad delay */ +#define FIOPAD_AJ51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_10_DELAY_OFFSET) +#define FIOPAD_AL51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_11_DELAY_OFFSET) +#define FIOPAD_AL49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_12_DELAY_OFFSET) +#define FIOPAD_AN47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_13_DELAY_OFFSET) +#define FIOPAD_AR47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_14_DELAY_OFFSET) +#define FIOPAD_AJ53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_23_DELAY_OFFSET) +#define FIOPAD_AG55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_24_DELAY_OFFSET) +#define FIOPAD_AG53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_25_DELAY_OFFSET) +#define FIOPAD_AE55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_26_DELAY_OFFSET) +#define FIOPAD_BA51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_32_DELAY_OFFSET) +#define FIOPAD_BA49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_33_DELAY_OFFSET) +#define FIOPAD_AR55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_34_DELAY_OFFSET) +#define FIOPAD_AU55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_35_DELAY_OFFSET) +#define FIOPAD_A41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_55_DELAY_OFFSET) +#define FIOPAD_C41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_56_DELAY_OFFSET) +#define FIOPAD_A43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_57_DELAY_OFFSET) +#define FIOPAD_A45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_58_DELAY_OFFSET) +#define FIOPAD_C45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_59_DELAY_OFFSET) +#define FIOPAD_A47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_60_DELAY_OFFSET) +#define FIOPAD_A29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_61_DELAY_OFFSET) +#define FIOPAD_C29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_62_DELAY_OFFSET) +#define FIOPAD_C27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_63_DELAY_OFFSET) +#define FIOPAD_A27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_64_DELAY_OFFSET) +#define FIOPAD_AJ49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_65_DELAY_OFFSET) +#define FIOPAD_AL45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_66_DELAY_OFFSET) +#define FIOPAD_AL43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_67_DELAY_OFFSET) +#define FIOPAD_AN45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_68_DELAY_OFFSET) +#define FIOPAD_AG47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_148_DELAY_OFFSET) +#define FIOPAD_AJ47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_69_DELAY_OFFSET) +#define FIOPAD_AG45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_70_DELAY_OFFSET) +#define FIOPAD_AE51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_71_DELAY_OFFSET) +#define FIOPAD_AE49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_72_DELAY_OFFSET) +#define FIOPAD_AG51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_73_DELAY_OFFSET) +#define FIOPAD_AJ45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_74_DELAY_OFFSET) +#define FIOPAD_AC51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_75_DELAY_OFFSET) +#define FIOPAD_AC49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_76_DELAY_OFFSET) +#define FIOPAD_AE47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_77_DELAY_OFFSET) +#define FIOPAD_W47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_78_DELAY_OFFSET) +#define FIOPAD_W49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_80_DELAY_OFFSET) +#define FIOPAD_U51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_81_DELAY_OFFSET) +#define FIOPAD_U49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_82_DELAY_OFFSET) +#define FIOPAD_AE45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_83_DELAY_OFFSET) +#define FIOPAD_AC45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_84_DELAY_OFFSET) +#define FIOPAD_AE43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_85_DELAY_OFFSET) +#define FIOPAD_AA43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_86_DELAY_OFFSET) +#define FIOPAD_AA45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_87_DELAY_OFFSET) +#define FIOPAD_W45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_88_DELAY_OFFSET) +#define FIOPAD_AA47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_89_DELAY_OFFSET) +#define FIOPAD_U45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_90_DELAY_OFFSET) +#define FIOPAD_J55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_92_DELAY_OFFSET) +#define FIOPAD_L53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_93_DELAY_OFFSET) +#define FIOPAD_C55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_94_DELAY_OFFSET) +#define FIOPAD_E55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_95_DELAY_OFFSET) +#define FIOPAD_J53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_96_DELAY_OFFSET) +#define FIOPAD_L55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_97_DELAY_OFFSET) +#define FIOPAD_N55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_98_DELAY_OFFSET) +#define FIOPAD_E27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_99_DELAY_OFFSET) +#define FIOPAD_G27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_100_DELAY_OFFSET) +#define FIOPAD_N37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_101_DELAY_OFFSET) +#define FIOPAD_N35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_102_DELAY_OFFSET) +#define FIOPAD_J29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_103_DELAY_OFFSET) +#define FIOPAD_N29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_104_DELAY_OFFSET) +#define FIOPAD_L29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_105_DELAY_OFFSET) +#define FIOPAD_N41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_106_DELAY_OFFSET) +#define FIOPAD_N39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_107_DELAY_OFFSET) +#define FIOPAD_L27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_108_DELAY_OFFSET) +#define FIOPAD_J27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_109_DELAY_OFFSET) +#define FIOPAD_J25_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_110_DELAY_OFFSET) +#define FIOPAD_E25_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_111_DELAY_OFFSET) +#define FIOPAD_G25_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_112_DELAY_OFFSET) +#define FIOPAD_J33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_115_DELAY_OFFSET) +#define FIOPAD_J35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_116_DELAY_OFFSET) +#define FIOPAD_G37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_117_DELAY_OFFSET) +#define FIOPAD_E39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_118_DELAY_OFFSET) +#define FIOPAD_L39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_119_DELAY_OFFSET) +#define FIOPAD_C39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_120_DELAY_OFFSET) +#define FIOPAD_E37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_121_DELAY_OFFSET) +#define FIOPAD_L41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_122_DELAY_OFFSET) +#define FIOPAD_J39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_123_DELAY_OFFSET) +#define FIOPAD_J37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_124_DELAY_OFFSET) +#define FIOPAD_L35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_125_DELAY_OFFSET) +#define FIOPAD_E33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_126_DELAY_OFFSET) +#define FIOPAD_E31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_127_DELAY_OFFSET) +#define FIOPAD_G31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_128_DELAY_OFFSET) +#define FIOPAD_L51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_136_DELAY_OFFSET) +#define FIOPAD_J51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_137_DELAY_OFFSET) +#define FIOPAD_J41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_138_DELAY_OFFSET) +#define FIOPAD_E43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_139_DELAY_OFFSET) +#define FIOPAD_G43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_140_DELAY_OFFSET) +#define FIOPAD_J43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_141_DELAY_OFFSET) +#define FIOPAD_J45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_142_DELAY_OFFSET) +#define FIOPAD_N45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_143_DELAY_OFFSET) +#define FIOPAD_L47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_144_DELAY_OFFSET) +#define FIOPAD_L45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_145_DELAY_OFFSET) +#define FIOPAD_N49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_146_DELAY_OFFSET) +#define FIOPAD_J49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_147_DELAY_OFFSET) + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + + + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/d/fiopad_config.c b/bsp/phytium/libraries/standalone/board/e2000/d/fiopad_config.c new file mode 100644 index 0000000000..b1faaa7dad --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/d/fiopad_config.c @@ -0,0 +1,562 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fiopad_config.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for io-pad function definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021/11/5 init commit + * 1.1 zhugengyu 2022/3/21 adopt to lastest tech spec. + */ + +/***************************** Include Files *********************************/ +#include "fiopad.h" +#include "fparameters.h" +#include "fdebug.h" +#include "fpinctrl.h" +#include "fassert.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FIOPAD_DEBUG_TAG "FIOPAD-CFG" +#define FIOPAD_ERROR(format, ...) FT_DEBUG_PRINT_E(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_WARN(format, ...) FT_DEBUG_PRINT_W(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_INFO(format, ...) FT_DEBUG_PRINT_I(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_DEBUG(format, ...) FT_DEBUG_PRINT_D(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ +/** + * @name: FIOPadSetSpimMux + * @msg: set iopad mux for spim + * @return {*} + * @param {u32} spim_id, instance id of spi + */ +void FIOPadSetSpimMux(u32 spim_id) +{ + if (FSPI2_ID == spim_id) + { + FPinSetFunc(FIOPAD_A29, FPIN_FUNC0); /* sclk */ + FPinSetFunc(FIOPAD_C29, FPIN_FUNC0); /* txd */ + FPinSetFunc(FIOPAD_C27, FPIN_FUNC0); /* rxd */ + FPinSetFunc(FIOPAD_A27, FPIN_FUNC0); /* csn0 */ + } +} + +/** + * @name: FIOPadSetGpioMux + * @msg: set iopad mux for gpio + * @return {*} + * @param {u32} gpio_id, instance id of gpio + * @param {u32} pin_id, index of pin + */ +void FIOPadSetGpioMux(u32 gpio_id, u32 pin_id) +{ + if (FGPIO_ID_3 == gpio_id) + { + switch (pin_id) + { + case 3: /* gpio 3-a-3 */ + FPinSetFunc(FIOPAD_A29, FPIN_FUNC6); + break; + case 4: /* gpio 3-a-4 */ + FPinSetFunc(FIOPAD_C29, FPIN_FUNC6); + break; + case 5: /* gpio 3-a-5 */ + FPinSetFunc(FIOPAD_C27, FPIN_FUNC6); + break; + case 6: /* gpio 3-a-6 */ + FPinSetFunc(FIOPAD_A27, FPIN_FUNC6); + break; + case 7: /* gpio 3-a-7 */ /*cannot use this pin*/ + FPinSetFunc(FIOPAD_AJ49, FPIN_FUNC6); + break; + case 8: /* gpio 3-a-8 */ + FPinSetFunc(FIOPAD_AL45, FPIN_FUNC6); + break; + case 9: /* gpio 3-a-9 */ + FPinSetFunc(FIOPAD_AL43, FPIN_FUNC6); + break; + default: + break; + } + } +} + +/** + * @name: FIOPadSetCanMux + * @msg: set iopad mux for can + * @return {*} + * @param {u32} can_id, instance id of can + */ +void FIOPadSetCanMux(u32 can_id) +{ + if (can_id == FCAN_INSTANCE_0) + { + /* mio0 */ + FPinSetFunc(FIOPAD_A37, FPIN_FUNC0); /* can0-tx: func 0 */ + FPinSetFunc(FIOPAD_A39, FPIN_FUNC0); /* can0-rx: func 0 */ + } + else if (can_id == FCAN_INSTANCE_1) + { + /* mio1 */ + FPinSetFunc(FIOPAD_A41, FPIN_FUNC0); /* can1-tx: func 0 */ + FPinSetFunc(FIOPAD_C41, FPIN_FUNC0); /* can1-rx: func 0 */ + } + else + { + FIOPAD_ERROR("can id is error.\r\n"); + } +} + +/** + * @name: FIOPadSetQspiMux + * @msg: set iopad mux for qspi + * @return {*} + * @param {u32} qspi_id, id of qspi instance + * @param {u32} cs_id, id of qspi cs + */ +void FIOPadSetQspiMux(u32 qspi_id, u32 cs_id) +{ + + if (qspi_id == FQSPI_INSTANCE_0) + { + /* add sck, io0-io3 iopad multiplex */ + } + + if (cs_id == FQSPI_CS_0) + { + FPinSetFunc(FIOPAD_AR51, FPIN_FUNC0); + } + else if (cs_id == FQSPI_CS_1) + { + FPinSetFunc(FIOPAD_AR45, FPIN_FUNC0); + } + else if (cs_id == FQSPI_CS_2) + { + FPinSetFunc(FIOPAD_C33, FPIN_FUNC5); + } + else if (cs_id == FQSPI_CS_3) + { + FPinSetFunc(FIOPAD_A33, FPIN_FUNC5); + } + else + { + FIOPAD_ERROR("can id is error.\r\n"); + } +} + + +/** + * @name: FIOPadSetPwmMux + * @msg: set iopad mux for pwm + * @return {*} + * @param {u32} pwm_id, id of pwm instance + * @param {u32} pwm_channel, channel of pwm instance + */ +void FIOPadSetPwmMux(u32 pwm_id, u32 pwm_channel) +{ + FASSERT(pwm_id < FPWM_INSTANCE_NUM); + FASSERT(pwm_channel < FPWM_CHANNEL_NUM); + + switch (pwm_id) + { + case FPWM_INSTANCE_0: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_AL55, FPIN_FUNC1); /* PWM0_OUT: func 1 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_AJ53, FPIN_FUNC1); /* PWM1_OUT: func 1 */ + } + break; + + case FPWM_INSTANCE_1: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_AG53, FPIN_FUNC1); /* PWM2_OUT: func 1 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_AC55, FPIN_FUNC1); /* PWM3_OUT: func 1 */ + } + break; + + case FPWM_INSTANCE_2: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_BA51, FPIN_FUNC1); /* PWM4_OUT: func 1 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_C35, FPIN_FUNC2); /* PWM5_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_3: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_A33, FPIN_FUNC2); /* PWM6_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_A39, FPIN_FUNC2); /* PWM7_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_4: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_C41, FPIN_FUNC2); /* PWM8_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_A45, FPIN_FUNC2); /* PWM9_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_5: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_A47, FPIN_FUNC2); /* PWM10_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_C29, FPIN_FUNC2); /* PWM11_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_6: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_A27, FPIN_FUNC2); /* PWM12_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_J35, FPIN_FUNC3); /* PWM13_OUT: func 3 */ + } + break; + + case FPWM_INSTANCE_7: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_E39, FPIN_FUNC3); /* PWM14_OUT: func 3 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_C39, FPIN_FUNC3); /* PWM15_OUT: func 3 */ + } + break; + + default: + FIOPAD_ERROR("pwm id is error.\r\n"); + break; + } +} + + +/** + * @name: FIOPadSetAdcMux + * @msg: set iopad mux for adc + * @return {*} + * @param {u32} adc_id, id of adc instance + * @param {u32} adc_channel, id of adc channel + */ +void FIOPadSetAdcMux(u32 adc_id, u32 adc_channel) +{ + + if (adc_id == FADC_INSTANCE_0) + { + switch (adc_channel) + { + case FADC_CHANNEL_0: + FPinSetFunc(FIOPAD_R47, FPIN_FUNC7); /* adc0-0: func 7 */ + break; + case FADC_CHANNEL_1: + FPinSetFunc(FIOPAD_R45, FPIN_FUNC7); /* adc0-1: func 7 */ + break; + case FADC_CHANNEL_2: + FPinSetFunc(FIOPAD_N47, FPIN_FUNC7); /* adc0-2: func 7 */ + break; + case FADC_CHANNEL_3: + FPinSetFunc(FIOPAD_N51, FPIN_FUNC7); /* adc0-3: func 7 */ + break; + case FADC_CHANNEL_4: + FPinSetFunc(FIOPAD_L51, FPIN_FUNC7); /* adc0-4: func 7 */ + break; + case FADC_CHANNEL_5: + FPinSetFunc(FIOPAD_J51, FPIN_FUNC7); /* adc0-5: func 7 */ + break; + case FADC_CHANNEL_6: + FPinSetFunc(FIOPAD_J41, FPIN_FUNC7); /* adc0-6: func 7 */ + break; + case FADC_CHANNEL_7: + FPinSetFunc(FIOPAD_E43, FPIN_FUNC7); /* adc0-7: func 7 */ + break; + default: + FIOPAD_ERROR("adc %d channel %d is error.\r\n", adc_id, adc_channel); + break; + } + } + else if (adc_id == FADC_INSTANCE_1) + { + switch (adc_channel) + { + case FADC_CHANNEL_0: + FPinSetFunc(FIOPAD_G43, FPIN_FUNC7); /* adc1-0: func 7 */ + break; + case FADC_CHANNEL_1: + FPinSetFunc(FIOPAD_J43, FPIN_FUNC7); /* adc1-1: func 7 */ + break; + case FADC_CHANNEL_2: + FPinSetFunc(FIOPAD_J45, FPIN_FUNC7); /* adc1-2: func 7 */ + break; + case FADC_CHANNEL_3: + FPinSetFunc(FIOPAD_N45, FPIN_FUNC7); /* adc1-3: func 7 */ + break; + case FADC_CHANNEL_4: + FPinSetFunc(FIOPAD_L47, FPIN_FUNC7); /* adc1-4: func 7 */ + break; + case FADC_CHANNEL_5: + FPinSetFunc(FIOPAD_L45, FPIN_FUNC7); /* adc1-5: func 7 */ + break; + case FADC_CHANNEL_6: + FPinSetFunc(FIOPAD_N49, FPIN_FUNC7); /* adc1-6: func 7 */ + break; + case FADC_CHANNEL_7: + FPinSetFunc(FIOPAD_J49, FPIN_FUNC7); /* adc1-7: func 7 */ + break; + default: + FIOPAD_ERROR("adc %d channel %d is error.\r\n", adc_id, adc_channel); + break; + } + } + else + { + FIOPAD_ERROR("adc %d channel %d is error.\r\n", adc_id, adc_channel); + } +} + +/** + * @name: FIOPadSetMioMux + * @msg: set iopad mux for mio + * @return {*} + * @param {u32} mio_id, instance id of i2c + */ +void FIOPadSetMioMux(u32 mio_id) +{ + switch (mio_id) + { + case MIO_INSTANCE_0: + { + FPinSetFunc(FIOPAD_A37, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A39, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_1: + { + FPinSetFunc(FIOPAD_A41, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_C41, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_2: + { + FPinSetFunc(FIOPAD_A43, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A45, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_3: + { + FPinSetFunc(FIOPAD_BA51, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_BA49, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_4: + { + FPinSetFunc(FIOPAD_R55, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U55, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_5: + { + FPinSetFunc(FIOPAD_W45, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U53, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_6: + { + FPinSetFunc(FIOPAD_AA53, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_AA55, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_7: + { + FPinSetFunc(FIOPAD_A35, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_C35, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_8: + { + FPinSetFunc(FIOPAD_AA45, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_W45, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_9: + { + FPinSetFunc(FIOPAD_AA47, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U45, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_10: + { + FPinSetFunc(FIOPAD_C45, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A47, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_11: + { + FPinSetFunc(FIOPAD_N23, FPIN_FUNC3); /* scl */ + FPinSetFunc(FIOPAD_L25, FPIN_FUNC3); /* sda */ + } + break; + case MIO_INSTANCE_12: + { + FPinSetFunc(FIOPAD_E37, FPIN_FUNC3); /* scl */ + FPinSetFunc(FIOPAD_L41, FPIN_FUNC3); /* sda */ + } + break; + case MIO_INSTANCE_13: + { + FPinSetFunc(FIOPAD_J45, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_N45, FPIN_FUNC6); /* sda */ + } + break; + case MIO_INSTANCE_14: + { + FPinSetFunc(FIOPAD_L47, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_L45, FPIN_FUNC6); /* sda */ + } + break; + case MIO_INSTANCE_15: + { + FPinSetFunc(FIOPAD_N49, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_J49, FPIN_FUNC6); /* sda */ + } + break; + default: + break; + } +} + +/** + * @name: FIOPadSetTachoMux + * @msg: set iopad mux for pwm_in + * @return {*} + * @param {u32} pwm_in_id, instance id of tacho + */ +void FIOPadSetTachoMux(u32 pwm_in_id) +{ + switch (pwm_in_id) + { + case TACHO_INSTANCE_0: + FPinSetFunc(FIOPAD_AN53, FPIN_FUNC1); + break; + case TACHO_INSTANCE_1: + FPinSetFunc(FIOPAD_AJ55, FPIN_FUNC1); + break; + case TACHO_INSTANCE_2: + FPinSetFunc(FIOPAD_AG55, FPIN_FUNC1); + break; + case TACHO_INSTANCE_3: + FPinSetFunc(FIOPAD_AE55, FPIN_FUNC1); + break; + case TACHO_INSTANCE_4: + FPinSetFunc(FIOPAD_AC53, FPIN_FUNC1); + break; + case TACHO_INSTANCE_5: + FPinSetFunc(FIOPAD_BA49, FPIN_FUNC1); + break; + case TACHO_INSTANCE_6: + FPinSetFunc(FIOPAD_C33, FPIN_FUNC2); + break; + case TACHO_INSTANCE_7: + FPinSetFunc(FIOPAD_A37, FPIN_FUNC2); + break; + case TACHO_INSTANCE_8: + FPinSetFunc(FIOPAD_A41, FPIN_FUNC2); + break; + case TACHO_INSTANCE_9: + FPinSetFunc(FIOPAD_A43, FPIN_FUNC2); + break; + case TACHO_INSTANCE_10: + FPinSetFunc(FIOPAD_C45, FPIN_FUNC2); + break; + case TACHO_INSTANCE_11: + FPinSetFunc(FIOPAD_A29, FPIN_FUNC2); + break; + case TACHO_INSTANCE_12: + FPinSetFunc(FIOPAD_C27, FPIN_FUNC2); + break; + case TACHO_INSTANCE_13: + FPinSetFunc(FIOPAD_AA45, FPIN_FUNC2); + break; + case TACHO_INSTANCE_14: + FPinSetFunc(FIOPAD_AA47, FPIN_FUNC2); + break; + case TACHO_INSTANCE_15: + FPinSetFunc(FIOPAD_G55, FPIN_FUNC2); + break; + default: + break; + } +} + +/** + * @name: FIOPadSetUartMux + * @msg: set iopad mux for uart + * @return {*} + * @param {u32} uart_id, instance id of uart + */ +void FIOPadSetUartMux(u32 uart_id) +{ + switch (uart_id) + { + case FUART0_ID: + FPinSetFunc(FIOPAD_J33, FPIN_FUNC4); + FPinSetFunc(FIOPAD_J35, FPIN_FUNC4); + break; + case FUART1_ID: + FPinSetFunc(FIOPAD_AW47, FPIN_FUNC0); + FPinSetFunc(FIOPAD_AU47, FPIN_FUNC0); + break; + case FUART2_ID: + FPinSetFunc(FIOPAD_A43, FPIN_FUNC0); + FPinSetFunc(FIOPAD_A45, FPIN_FUNC0); + break; + case FUART3_ID: + FPinSetFunc(FIOPAD_L33, FPIN_FUNC2); + FPinSetFunc(FIOPAD_N31, FPIN_FUNC2); + break; + default: + break; + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/d/fparameters.h b/bsp/phytium/libraries/standalone/board/e2000/d/fparameters.h new file mode 100644 index 0000000000..3703d3e78b --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/d/fparameters.h @@ -0,0 +1,55 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fparameters.h + * Date: 2022-02-11 13:33:28 + * LastEditTime: 2022-02-17 18:00:50 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BOARD_E2000D_PARAMTERERS_H +#define BOARD_E2000D_PARAMTERERS_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fparameters_comm.h" + +/************************** Constant Definitions *****************************/ +#define CORE0_AFF 0x200U +#define CORE1_AFF 0x201U + +#define FT_CPUS_NR 2U + +/* GIC offset */ + +#define FT_GIC_REDISTRUBUTIOR_OFFSET 2 + +/*****************************************************************************/ + + + + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/fearly_uart.c b/bsp/phytium/libraries/standalone/board/e2000/fearly_uart.c new file mode 100644 index 0000000000..a330aa37b3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/fearly_uart.c @@ -0,0 +1,59 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: early_uart.c + * Date: 2022-02-11 13:33:28 + * LastEditTime: 2022-02-17 17:59:26 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ +#include "fkernel.h" +#include "fio.h" +#include "fparameters.h" +#include "fearly_uart.h" + +/**************************** Type Definitions *******************************/ + +/************************** Constant Definitions *****************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/*****************************************************************************/ +void OutByte(s8 byte) +{ + /* wait until tx fifo is not full */ + while ((FtIn32(EARLY_UART_UARTFR) & EARLY_UART_TXFF) == EARLY_UART_TXFF) + { + + } + + FtOut32(EARLY_UART_UARTDR, (((u32)byte) & EARLY_UART_DATA_MASK)); +} + +char GetByte(void) +{ + /* wait until rx fifo is not empty */ + while ((FtIn32(EARLY_UART_UARTFR) & EARLY_UART_RXFE) == EARLY_UART_RXFE) + { + + } + + return (char)(EARLY_UART_DATA_MASK & FtIn32(EARLY_UART_UARTDR)); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/fearly_uart.h b/bsp/phytium/libraries/standalone/board/e2000/fearly_uart.h new file mode 100644 index 0000000000..cbb47a898f --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/fearly_uart.h @@ -0,0 +1,83 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fearly_uart.h + * Date: 2022-02-11 13:33:28 + * LastEditTime: 2022-02-17 18:00:16 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 rtos 2022/6/25 init commit + */ +#ifndef BOARD_E2000_EARLY_UART_H +#define BOARD_E2000_EARLY_UART_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "ftypes.h" +#include "fio.h" +#include "fparameters.h" +#include "sdkconfig.h" + +/**************************** Type Definitions *******************************/ + +/************************** Constant Definitions *****************************/ +#if defined(CONFIG_DEFAULT_DEBUG_PRINT_UART2) +#define EARLY_UART_BASE FUART2_BASE_ADDR +#define EARLY_UART_IRQ_NUM FUART2_IRQ_NUM +#elif defined(CONFIG_DEFAULT_DEBUG_PRINT_UART0) +#define EARLY_UART_BASE FUART0_BASE_ADDR +#define EARLY_UART_IRQ_NUM FUART0_IRQ_NUM +#else +#define EARLY_UART_BASE FUART1_BASE_ADDR +#define EARLY_UART_IRQ_NUM FUART1_IRQ_NUM +#endif + +#define EARLY_UART_UARTDR (EARLY_UART_BASE + 0x0) /* UART 数据寄存器地址 */ +#define EARLY_UART_UARTFR (EARLY_UART_BASE + 0x18) /* UART 状态寄存器地址 */ +#define EARLY_UART_UARTCR (EARLY_UART_BASE + 0x30) +#define EARLY_UART_UARTCR_UARTEN BIT(0) +#define EARLY_UART_UARTCR_TXE BIT(8) +#define EARLY_UART_UARTCR_RXE BIT(9) +#define EARLY_UART_UARTCR_INIT (EARLY_UART_UARTCR_UARTEN | EARLY_UART_UARTCR_TXE | \ + EARLY_UART_UARTCR_RXE) +#define EARLY_UART_UARTIMSC (EARLY_UART_BASE + 0x38) +#define EARLY_UART_UARTIMSC_RXIM BIT(4) +#define EARLY_UART_UARTIMSC_RTIM BIT(6) +#define EARLY_UART_UARTMIS (EARLY_UART_BASE + 0x40) +#define EARLY_UART_UARTICR (EARLY_UART_BASE + 0x44) +#define EARLY_UART_TXFF BIT(5) /* 发送 FIFO 已满标志位 */ +#define EARLY_UART_RXFE BIT(4) /* 接收 FIFO 为空标志位 */ +#define EARLY_UART_DATA_MASK GENMASK(7, 0) +#define EARLY_UART_RXI_MASK BIT(4) + +#define STDOUT_BASEADDRESS +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/*****************************************************************************/ +void OutByte(s8 byte); +char GetByte(void); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/fiopad_comm.c b/bsp/phytium/libraries/standalone/board/e2000/fiopad_comm.c new file mode 100644 index 0000000000..e26cafcc8d --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/fiopad_comm.c @@ -0,0 +1,572 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fiopad_comm.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for io-pad function definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021/11/5 init commit + * 1.1 zhugengyu 2022/3/21 adopt to lastest tech spec. + */ + + +/***************************** Include Files *********************************/ +#include "fparameters.h" +#include "fio.h" +#include "fkernel.h" +#include "fassert.h" +#include "fdebug.h" +#include "stdio.h" +#include "fpinctrl.h" + +/************************** Constant Definitions *****************************/ +/** @name IO PAD Control Register + */ +#define FIOPAD_X_REG0_BEG_OFFSET 0x0 /* 上下拉/驱动能力/复用功能配置 */ +#define FIOPAD_X_REG0_END_OFFSET 0x24c + +#define FIOPAD_X_REG1_BEG_OFFSET 0x1024 /* 输入/输出延时配置 */ +#define FIOPAD_X_REG1_END_OFFSET 0x124c + +/** @name X_reg0 Register + */ +#define FIOPAD_X_REG0_PULL_MASK GENMASK(9, 8) /* 上下拉配置 */ +#define FIOPAD_X_REG0_PULL_GET(x) GET_REG32_BITS((x), 9, 8) +#define FIOPAD_X_REG0_PULL_SET(x) SET_REG32_BITS((x), 9, 8) + +#define FIOPAD_X_REG0_DRIVE_MASK GENMASK(7, 4) /* 驱动能力配置 */ +#define FIOPAD_X_REG0_DRIVE_GET(x) GET_REG32_BITS((x), 7, 4) +#define FIOPAD_X_REG0_DRIVE_SET(x) SET_REG32_BITS((x), 7, 4) + +#define FIOPAD_X_REG0_FUNC_MASK GENMASK(2, 0) /* 引脚复用配置 */ +#define FIOPAD_X_REG0_FUNC_GET(x) GET_REG32_BITS((x), 2, 0) +#define FIOPAD_X_REG0_FUNC_SET(x) SET_REG32_BITS((x), 2, 0) + +/** @name X_reg1 Register + */ +#define FIOPAD_X_REG1_OUT_DELAY_EN BIT(8) +#define FIOPAD_X_REG1_OUT_DELAY_DELICATE_MASK GENMASK(11, 9) +#define FIOPAD_X_REG1_OUT_DELAY_DELICATE_GET(x) GET_REG32_BITS((x), 11, 9) /* 延时精调 */ +#define FIOPAD_X_REG1_OUT_DELAY_DELICATE_SET(x) SET_REG32_BITS((x), 11, 9) +#define FIOPAD_X_REG1_OUT_DELAY_ROUGH_MASK GENMASK(14, 12) +#define FIOPAD_X_REG1_OUT_DELAY_ROUGH_GET(x) GET_REG32_BITS((x), 14, 12) /* 延时粗调 */ +#define FIOPAD_X_REG1_OUT_DELAY_ROUGH_SET(x) SET_REG32_BITS((x), 14, 12) + +#define FIOPAD_X_REG1_IN_DELAY_EN BIT(0) +#define FIOPAD_X_REG1_IN_DELAY_DELICATE_MASK GENMASK(3, 1) +#define FIOPAD_X_REG1_IN_DELAY_DELICATE_GET(x) GET_REG32_BITS((x), 3, 1) /* 延时精调 */ +#define FIOPAD_X_REG1_IN_DELAY_DELICATE_SET(x) SET_REG32_BITS((x), 3, 1) +#define FIOPAD_X_REG1_IN_DELAY_ROUGH_MASK GENMASK(6, 4) +#define FIOPAD_X_REG1_IN_DELAY_ROUGH_GET(x) GET_REG32_BITS((x), 6, 4) /* 延时粗调 */ +#define FIOPAD_X_REG1_IN_DELAY_ROUGH_SET(x) SET_REG32_BITS((x), 6, 4) + +#define FIOPAD_DELAY_MAX 15 + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +static inline u32 FIOPadRead(FPinIndex pin) +{ + return FtIn32(FIOPAD_BASE_ADDR + pin.reg_off); +} + +static inline void FIOPadWrite(FPinIndex pin, u32 reg_val) +{ + FtOut32(FIOPAD_BASE_ADDR + pin.reg_off, reg_val); + return; +} + +#define FIOPAD_ASSERT_REG0_OFF(pin) FASSERT_MSG((FIOPAD_X_REG0_END_OFFSET >= pin.reg_off), "invalid reg0 offset @0x%x\r\n", (pin.reg_off)) +#define FIOPAD_ASSERT_FUNC(func) FASSERT_MSG((func < FPIN_NUM_OF_FUNC), "invalid func as %d\r\n", (func)) +#define FIOPAD_ASSERT_PULL(pull) FASSERT_MSG((pull < FPIN_NUM_OF_PULL), "invalid pull as %d\r\n", (pull)) +#define FIOPAD_ASSERT_DRIVE(drive) FASSERT_MSG((drive < FPIN_NUM_OF_DRIVE), "invalid pull as %d\r\n", (drive)) + +#define FIOPAD_ASSERT_REG1_OFF(pin) FASSERT_MSG(((FIOPAD_X_REG1_BEG_OFFSET <= pin.reg_off) && (FIOPAD_X_REG1_END_OFFSET >= pin.reg_off)), "invalid reg1 offset @0x%x\r\n", (pin.reg_off)) +#define FIOPAD_ASSERT_DELAY(delay) FASSERT_MSG((delay < FPIN_NUM_OF_DELAY), "invalid delay as %d\r\n", (delay)) + +#define FIOPAD_DEBUG_TAG "FIOPAD" +#define FIOPAD_ERROR(format, ...) FT_DEBUG_PRINT_E(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_WARN(format, ...) FT_DEBUG_PRINT_W(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_INFO(format, ...) FT_DEBUG_PRINT_I(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_DEBUG(format, ...) FT_DEBUG_PRINT_D(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +/** + * @name: FPinGetFunc + * @msg: 获取IO引脚当前的复用功能 + * @return {FPinFunc} 当前的复用功能 + * @param {FPinIndex} pin IO引脚索引 + * @note 参考编程手册,使用 FIOPAD_INDEX 宏定义index的值 + */ +FPinFunc FPinGetFunc(const FPinIndex pin) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + u32 func = FIOPAD_X_REG0_FUNC_GET(FIOPadRead(pin)); + FIOPAD_ASSERT_FUNC(func); + return (FPinFunc)func; +} + +/** + * @name: FPinSetFunc + * @msg: 设置IO引脚复用功能 + * @return {*} + * @param {FPinIndex} pin IO引脚索引 + * @param {FPinFunc} func IO复用功能 + * @note 参考编程手册,使用 FIOPAD_INDEX 宏定义index的值 + */ +void FPinSetFunc(const FPinIndex pin, FPinFunc func) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + FIOPAD_ASSERT_FUNC(func); + u32 reg_val = FIOPadRead(pin); + u32 test_val = 0; + + reg_val &= ~FIOPAD_X_REG0_FUNC_MASK; + reg_val |= FIOPAD_X_REG0_FUNC_SET(func); + + FIOPadWrite(pin, reg_val); + + test_val = FIOPadRead(pin); + + if (reg_val != test_val) + { + FIOPAD_ERROR("ERROR: FIOPad write is failed ,pin is %x\n, 0x%x != 0x%x", + pin.reg_off, reg_val, test_val); + } + + return; +} + +/** + * @name: FPinGetDrive + * @msg: 获取IO引脚的驱动能力 + * @return {FPinDrive} 引脚的当前的驱动能力 + * @param {FPinIndex} pin IO引脚索引 + */ +FPinDrive FPinGetDrive(const FPinIndex pin) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + u32 drive = FIOPAD_X_REG0_DRIVE_GET(FIOPadRead(pin)); + FIOPAD_ASSERT_DRIVE(drive); + return (FPinDrive)drive; +} + +/** + * @name: FPinSetDrive + * @msg: 设置IO引脚的驱动能力 + * @return {*} + * @param {FPinIndex} pin, IO引脚索引 + * @param {FPinDrive} drive, 引脚驱动能力设置 + */ +void FPinSetDrive(const FPinIndex pin, FPinDrive drive) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + FIOPAD_ASSERT_DRIVE(drive); + u32 reg_val = FIOPadRead(pin); + + reg_val &= ~FIOPAD_X_REG0_DRIVE_MASK; + reg_val |= FIOPAD_X_REG0_DRIVE_SET(drive); + + FIOPadWrite(pin, reg_val); + return; +} + +void FPinGetConfig(const FPinIndex pin, FPinFunc *func, FPinPull *pull, FPinDrive *drive) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + u32 reg_val = FIOPadRead(pin); + + if (func) + { + *func = FIOPAD_X_REG0_FUNC_GET(reg_val); + } + + if (pull) + { + *pull = FIOPAD_X_REG0_PULL_GET(reg_val); + } + + if (drive) + { + *pull = FIOPAD_X_REG0_DRIVE_GET(reg_val); + } + + return; +} + +void FPinSetConfig(const FPinIndex pin, FPinFunc func, FPinPull pull, FPinDrive drive) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + u32 reg_val = FIOPadRead(pin); + + reg_val &= ~FIOPAD_X_REG0_FUNC_MASK; + reg_val |= FIOPAD_X_REG0_FUNC_SET(func); + + reg_val &= ~FIOPAD_X_REG0_PULL_MASK; + reg_val |= FIOPAD_X_REG0_PULL_SET(pull); + + reg_val &= ~FIOPAD_X_REG0_DRIVE_MASK; + reg_val |= FIOPAD_X_REG0_DRIVE_SET(drive); + + FIOPadWrite(pin, reg_val); + return; +} + +/** + * @name: FPinGetPull + * @msg: 获取IO引脚当前的上下拉设置 + * @return {*} + * @param {FPinIndex} pin IO引脚索引 + * @note 参考编程手册,使用 FIOPAD_INDEX 宏定义index的值 + */ +FPinPull FPinGetPull(const FPinIndex pin) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + u32 pull = FIOPAD_X_REG0_PULL_GET(FIOPadRead(pin)); + FIOPAD_ASSERT_PULL(pull); + return (FPinPull)pull; +} + +/** + * @name: FPinSetPull + * @msg: 设置IO引脚当前的上下拉 + * @return {*} + * @param {FPinIndex} pin IO引脚索引 + * @param {FPinPull} pull 上下拉设置 + */ +void FPinSetPull(const FPinIndex pin, FPinPull pull) +{ + FIOPAD_ASSERT_REG0_OFF(pin); + FIOPAD_ASSERT_PULL(pull); + + u32 reg_val = FIOPadRead(pin); + + reg_val &= ~FIOPAD_X_REG0_PULL_MASK; + reg_val |= FIOPAD_X_REG0_PULL_SET(pull); + + FIOPadWrite(pin, reg_val); + return; +} + +/** + * @name: FPinGetDelay + * @msg: 获取IO引脚当前的延时设置 + * @return {FPinDelay} 当前的延时设置 + * @param {FPinIndex} pin IO引脚延时设置索引 + * @param {FPinDelayDir} dir 输入/输出延时 + * @param {FPinDelayType} type 精调/粗调延时 + */ +FPinDelay FPinGetDelay(const FPinIndex pin, FPinDelayDir dir, FPinDelayType type) +{ + FIOPAD_ASSERT_REG1_OFF(pin); + const u32 reg_val = FIOPadRead(pin); + u8 delay = 0; + + if (FPIN_OUTPUT_DELAY == dir) + { + if (FPIN_DELAY_FINE_TUNING == type) + { + delay = FIOPAD_X_REG1_OUT_DELAY_DELICATE_GET(reg_val); + } + else if (FPIN_DELAY_COARSE_TUNING == type) + { + delay = FIOPAD_X_REG1_OUT_DELAY_ROUGH_GET(reg_val); + } + else + { + FASSERT(0); + } + } + else if (FPIN_INPUT_DELAY == dir) + { + if (FPIN_DELAY_FINE_TUNING == type) + { + delay = FIOPAD_X_REG1_IN_DELAY_DELICATE_GET(reg_val); + } + else if (FPIN_DELAY_COARSE_TUNING == type) + { + delay = FIOPAD_X_REG1_IN_DELAY_ROUGH_GET(reg_val); + } + else + { + FASSERT(0); + } + } + else + { + FASSERT(0); + } + + FIOPAD_ASSERT_DELAY(delay); + return (FPinDelay)delay; +} + +/** + * @name: FPinGetDelayEn + * @msg: 获取IO引脚当前的延时使能标志位 + * @return {*} + * @param {FPinIndex} pin IO引脚延时设置索引 + * @param {FPinDelayDir} dir 输入/输出延时 + */ +boolean FPinGetDelayEn(const FPinIndex pin, FPinDelayDir dir) +{ + FIOPAD_ASSERT_REG1_OFF(pin); + const u32 reg_val = FIOPadRead(pin); + boolean enabled = FALSE; + + if (FPIN_OUTPUT_DELAY == dir) + { + if (FIOPAD_X_REG1_OUT_DELAY_EN & reg_val) + enabled = TRUE; + else + enabled = FALSE; + } + else if (FPIN_INPUT_DELAY == dir) + { + if (FIOPAD_X_REG1_IN_DELAY_EN & reg_val) + enabled = TRUE; + else + enabled = FALSE; + } + else + { + FASSERT(0); + } + + return enabled; +} + +/** + * @name: FPinSetDelay + * @msg: 设置IO引脚延时 + * @return {*} + * @param {FPinIndex} pin IO引脚延时设置索引 + * @param {FPinDelayDir} dir 输入/输出延时 + * @param {FPinDelayType} type 精调/粗调延时 + * @param {FPinDelay} delay 延时设置 + */ +void FPinSetDelay(const FPinIndex pin, FPinDelayDir dir, FPinDelayType type, FPinDelay delay) +{ + FIOPAD_ASSERT_REG1_OFF(pin); + FIOPAD_ASSERT_DELAY(delay); + u32 reg_val = FIOPadRead(pin); + + if (FPIN_OUTPUT_DELAY == dir) + { + if (FPIN_DELAY_FINE_TUNING == type) + { + reg_val &= ~FIOPAD_X_REG1_OUT_DELAY_DELICATE_MASK; + reg_val |= FIOPAD_X_REG1_OUT_DELAY_DELICATE_SET(delay); + } + else if (FPIN_DELAY_COARSE_TUNING == type) + { + reg_val &= ~FIOPAD_X_REG1_OUT_DELAY_ROUGH_MASK; + reg_val |= FIOPAD_X_REG1_OUT_DELAY_ROUGH_SET(delay); + } + else + { + FASSERT(0); + } + } + else if (FPIN_INPUT_DELAY == dir) + { + if (FPIN_DELAY_FINE_TUNING == type) + { + reg_val &= ~FIOPAD_X_REG1_IN_DELAY_DELICATE_MASK; + reg_val |= FIOPAD_X_REG1_IN_DELAY_DELICATE_SET(delay); + } + else if (FPIN_DELAY_COARSE_TUNING == type) + { + reg_val &= ~FIOPAD_X_REG1_IN_DELAY_ROUGH_MASK; + reg_val |= FIOPAD_X_REG1_IN_DELAY_ROUGH_SET(delay); + } + else + { + FASSERT(0); + } + } + else + { + FASSERT(0); + } + + FIOPadWrite(pin, reg_val); + return; +} + +/** + * @name: FPinSetDelayEn + * @msg: 使能/去使能IO引脚延时 + * @return {*} + * @param {FPinIndex} pin IO引脚延时设置索引 + * @param {FPinDelayDir} dir 输入/输出延时 + * @param {boolean} enable TRUE: 使能, FALSE: 去使能 + */ +void FPinSetDelayEn(const FPinIndex pin, FPinDelayDir dir, boolean enable) +{ + FIOPAD_ASSERT_REG1_OFF(pin); + u32 reg_val = FIOPadRead(pin); + + if (FPIN_OUTPUT_DELAY == dir) + { + if (enable) + reg_val |= FIOPAD_X_REG1_OUT_DELAY_EN; + else + reg_val &= ~FIOPAD_X_REG1_OUT_DELAY_EN; + } + else if (FPIN_INPUT_DELAY == dir) + { + if (enable) + reg_val |= FIOPAD_X_REG1_IN_DELAY_EN; + else + reg_val &= ~FIOPAD_X_REG1_IN_DELAY_EN; + } + else + { + FASSERT(0); + } + + FIOPadWrite(pin, reg_val); + return; +} + + +/** + * @name: FPinSetDelayConfig + * @msg: Update and enable common IO pin delay config + * @return {NONE} + * @param {FPinIndex} pin, IO pin index + * @param {FPinDelayIOType} in_out_type, Select the input and output types , + * @param {FPinDelay} roungh_delay, delay rough setting + * @param {FPinDelay} delicate_delay, delay delicate setting + * @param {boolean} enable, enable delay + */ +void FPinSetDelayConfig(const FPinIndex pin, FPinDelayIOType in_out_type, FPinDelay roungh_delay, FPinDelay delicate_delay, boolean enable) +{ + FIOPAD_ASSERT_REG1_OFF(pin); + u32 reg_val = FIOPadRead(pin); + + if (in_out_type == FPIN_DELAY_IN_TYPE) + { + reg_val = FIOPadRead(pin); + + /* update delicate input delay */ + reg_val &= ~FIOPAD_X_REG1_IN_DELAY_DELICATE_MASK; + reg_val |= FIOPAD_X_REG1_IN_DELAY_DELICATE_SET(delicate_delay); + + /* update rough input delay */ + reg_val &= ~FIOPAD_X_REG1_IN_DELAY_ROUGH_MASK; + reg_val |= FIOPAD_X_REG1_IN_DELAY_ROUGH_SET(roungh_delay); + + /* enable input delay */ + if (enable) + { + reg_val |= FIOPAD_X_REG1_IN_DELAY_EN; + } + else + { + reg_val &= ~FIOPAD_X_REG1_IN_DELAY_EN; + } + } + else + { + /* update delicate output delay */ + reg_val &= ~FIOPAD_X_REG1_OUT_DELAY_DELICATE_MASK; + reg_val |= FIOPAD_X_REG1_OUT_DELAY_DELICATE_SET(delicate_delay); + + /* update rough output delay */ + reg_val &= ~FIOPAD_X_REG1_OUT_DELAY_ROUGH_MASK; + reg_val |= FIOPAD_X_REG1_OUT_DELAY_ROUGH_SET(roungh_delay); + + /* enable output delay */ + if (enable) + { + reg_val |= FIOPAD_X_REG1_OUT_DELAY_EN; + } + else + { + reg_val &= ~FIOPAD_X_REG1_OUT_DELAY_EN; + } + } + + FIOPadWrite(pin, reg_val); + return; +} + +/** + * @name: FPinGetDelayConfig + * @msg: Get current common IO pin delay config + * @return {NONE} + * @param {FPinIndex} pin, IO pin index + * @param {FPinDelay} *in_roungh_delay, input delay rough setting (输入粗调) + * @param {FPinDelay} *in_delicate_delay, input delay delicate setting (输入精调) + * @param {FPinDelay} *out_roungh_delay, output delay rough setting (输出粗调) + * @param {FPinDelay} *out_delicate_delay, output delay delicate setting (输出精调) + */ +void FPinGetDelayConfig(const FPinIndex pin, FPinDelay *in_roungh_delay, FPinDelay *in_delicate_delay, + FPinDelay *out_roungh_delay, FPinDelay *out_delicate_delay) +{ + FIOPAD_ASSERT_REG1_OFF(pin); + u32 reg_val = FIOPadRead(pin); + + if (out_delicate_delay) + { + *out_delicate_delay = FIOPAD_X_REG1_OUT_DELAY_DELICATE_GET(reg_val); + } + + if (out_roungh_delay) + { + *out_roungh_delay = FIOPAD_X_REG1_OUT_DELAY_ROUGH_GET(reg_val); + } + + if (in_delicate_delay) + { + *in_delicate_delay = FIOPAD_X_REG1_IN_DELAY_DELICATE_GET(reg_val); + } + + if (in_roungh_delay) + { + *in_roungh_delay = FIOPAD_X_REG1_IN_DELAY_ROUGH_GET(reg_val); + } + + return; +} + +/** + * @name: FIOPadDumpPadFunc + * @msg: print information of all iopad + * @return {*} + */ +void FIOPadDumpPadFunc(void) +{ + uintptr beg_off = FIOPAD_0_FUNC_OFFSET; + uintptr end_off = FIOPAD_147_FUNC_OFFSET; + uintptr off; + FPinIndex pin; + const char *pull_state[FPIN_NUM_OF_PULL] = {"none", "down", "up"}; + + FIOPAD_DEBUG("Pad Func Info..."); + for (off = beg_off; off <= end_off; off += 4U) + { + pin.reg_off = off; + FIOPAD_DEBUG(" [0x%x] func: %d, ds: %d, pull: %s ", + pin.reg_off, + FPinGetFunc(pin), + FPinGetDrive(pin), + pull_state[FPinGetPull(pin)]); + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/fiopad_comm.h b/bsp/phytium/libraries/standalone/board/e2000/fiopad_comm.h new file mode 100644 index 0000000000..311fb6f076 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/fiopad_comm.h @@ -0,0 +1,310 @@ +#ifndef BOARD_E2000_FIOPAD_COMMON_H +#define BOARD_E2000_FIOPAD_COMMON_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "ftypes.h" + +/**************************** Type Definitions *******************************/ + +/************************** Constant Definitions *****************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FIOPAD_INDEX(offset) \ + { \ + /* reg_off */ (offset), \ + /* reg_bit */ (0) \ + } + +/*****************************************************************************/ +/* register offset of iopad function / pull / driver strength */ +#define FIOPAD_0_FUNC_OFFSET 0x0000U +#define FIOPAD_2_FUNC_OFFSET 0x0004U +#define FIOPAD_3_FUNC_OFFSET 0x0008U +#define FIOPAD_4_FUNC_OFFSET 0x000CU +#define FIOPAD_5_FUNC_OFFSET 0x0010U +#define FIOPAD_6_FUNC_OFFSET 0x0014U +#define FIOPAD_7_FUNC_OFFSET 0x0018U +#define FIOPAD_8_FUNC_OFFSET 0x001CU +#define FIOPAD_9_FUNC_OFFSET 0x0020U +#define FIOPAD_10_FUNC_OFFSET 0x0024U +#define FIOPAD_11_FUNC_OFFSET 0x0028U +#define FIOPAD_12_FUNC_OFFSET 0x002CU +#define FIOPAD_13_FUNC_OFFSET 0x0030U +#define FIOPAD_14_FUNC_OFFSET 0x0034U +#define FIOPAD_15_FUNC_OFFSET 0x0038U +#define FIOPAD_16_FUNC_OFFSET 0x003CU +#define FIOPAD_17_FUNC_OFFSET 0x0040U +#define FIOPAD_18_FUNC_OFFSET 0x0044U +#define FIOPAD_19_FUNC_OFFSET 0x0048U +#define FIOPAD_20_FUNC_OFFSET 0x004CU +#define FIOPAD_21_FUNC_OFFSET 0x0050U +#define FIOPAD_22_FUNC_OFFSET 0x0054U +#define FIOPAD_23_FUNC_OFFSET 0x0058U +#define FIOPAD_24_FUNC_OFFSET 0x005CU +#define FIOPAD_25_FUNC_OFFSET 0x0060U +#define FIOPAD_26_FUNC_OFFSET 0x0064U +#define FIOPAD_27_FUNC_OFFSET 0x0068U +#define FIOPAD_28_FUNC_OFFSET 0x006CU +#define FIOPAD_31_FUNC_OFFSET 0x0070U +#define FIOPAD_32_FUNC_OFFSET 0x0074U +#define FIOPAD_33_FUNC_OFFSET 0x0078U +#define FIOPAD_34_FUNC_OFFSET 0x007CU +#define FIOPAD_35_FUNC_OFFSET 0x0080U +#define FIOPAD_36_FUNC_OFFSET 0x0084U +#define FIOPAD_37_FUNC_OFFSET 0x0088U +#define FIOPAD_38_FUNC_OFFSET 0x008CU +#define FIOPAD_39_FUNC_OFFSET 0x0090U +#define FIOPAD_40_FUNC_OFFSET 0x0094U +#define FIOPAD_41_FUNC_OFFSET 0x0098U +#define FIOPAD_42_FUNC_OFFSET 0x009CU +#define FIOPAD_43_FUNC_OFFSET 0x00A0U +#define FIOPAD_44_FUNC_OFFSET 0x00A4U +#define FIOPAD_45_FUNC_OFFSET 0x00A8U +#define FIOPAD_46_FUNC_OFFSET 0x00ACU +#define FIOPAD_47_FUNC_OFFSET 0x00B0U +#define FIOPAD_48_FUNC_OFFSET 0x00B4U +#define FIOPAD_49_FUNC_OFFSET 0x00B8U +#define FIOPAD_50_FUNC_OFFSET 0x00BCU +#define FIOPAD_51_FUNC_OFFSET 0x00C0U +#define FIOPAD_52_FUNC_OFFSET 0x00C4U +#define FIOPAD_53_FUNC_OFFSET 0x00C8U +#define FIOPAD_54_FUNC_OFFSET 0x00CCU +#define FIOPAD_55_FUNC_OFFSET 0x00D0U +#define FIOPAD_56_FUNC_OFFSET 0x00D4U +#define FIOPAD_57_FUNC_OFFSET 0x00D8U +#define FIOPAD_58_FUNC_OFFSET 0x00DCU +#define FIOPAD_59_FUNC_OFFSET 0x00E0U +#define FIOPAD_60_FUNC_OFFSET 0x00E4U +#define FIOPAD_61_FUNC_OFFSET 0x00E8U +#define FIOPAD_62_FUNC_OFFSET 0x00ECU +#define FIOPAD_63_FUNC_OFFSET 0x00F0U +#define FIOPAD_64_FUNC_OFFSET 0x00F4U +#define FIOPAD_65_FUNC_OFFSET 0x00F8U +#define FIOPAD_66_FUNC_OFFSET 0x00FCU +#define FIOPAD_67_FUNC_OFFSET 0x0100U +#define FIOPAD_68_FUNC_OFFSET 0x0104U +#define FIOPAD_148_FUNC_OFFSET 0x0108U +#define FIOPAD_69_FUNC_OFFSET 0x010CU +#define FIOPAD_70_FUNC_OFFSET 0x0110U +#define FIOPAD_71_FUNC_OFFSET 0x0114U +#define FIOPAD_72_FUNC_OFFSET 0x0118U +#define FIOPAD_73_FUNC_OFFSET 0x011CU +#define FIOPAD_74_FUNC_OFFSET 0x0120U +#define FIOPAD_75_FUNC_OFFSET 0x0124U +#define FIOPAD_76_FUNC_OFFSET 0x0128U +#define FIOPAD_77_FUNC_OFFSET 0x012CU +#define FIOPAD_78_FUNC_OFFSET 0x0130U +#define FIOPAD_79_FUNC_OFFSET 0x0134U +#define FIOPAD_80_FUNC_OFFSET 0x0138U +#define FIOPAD_81_FUNC_OFFSET 0x013CU +#define FIOPAD_82_FUNC_OFFSET 0x0140U +#define FIOPAD_83_FUNC_OFFSET 0x0144U +#define FIOPAD_84_FUNC_OFFSET 0x0148U +#define FIOPAD_85_FUNC_OFFSET 0x014CU +#define FIOPAD_86_FUNC_OFFSET 0x0150U +#define FIOPAD_87_FUNC_OFFSET 0x0154U +#define FIOPAD_88_FUNC_OFFSET 0x0158U +#define FIOPAD_89_FUNC_OFFSET 0x015CU +#define FIOPAD_90_FUNC_OFFSET 0x0160U +#define FIOPAD_91_FUNC_OFFSET 0x0164U +#define FIOPAD_92_FUNC_OFFSET 0x0168U +#define FIOPAD_93_FUNC_OFFSET 0x016CU +#define FIOPAD_94_FUNC_OFFSET 0x0170U +#define FIOPAD_95_FUNC_OFFSET 0x0174U +#define FIOPAD_96_FUNC_OFFSET 0x0178U +#define FIOPAD_97_FUNC_OFFSET 0x017CU +#define FIOPAD_98_FUNC_OFFSET 0x0180U +#define FIOPAD_29_FUNC_OFFSET 0x0184U +#define FIOPAD_30_FUNC_OFFSET 0x0188U +#define FIOPAD_99_FUNC_OFFSET 0x018CU +#define FIOPAD_100_FUNC_OFFSET 0x0190U +#define FIOPAD_101_FUNC_OFFSET 0x0194U +#define FIOPAD_102_FUNC_OFFSET 0x0198U +#define FIOPAD_103_FUNC_OFFSET 0x019CU +#define FIOPAD_104_FUNC_OFFSET 0x01A0U +#define FIOPAD_105_FUNC_OFFSET 0x01A4U +#define FIOPAD_106_FUNC_OFFSET 0x01A8U +#define FIOPAD_107_FUNC_OFFSET 0x01ACU +#define FIOPAD_108_FUNC_OFFSET 0x01B0U +#define FIOPAD_109_FUNC_OFFSET 0x01B4U +#define FIOPAD_110_FUNC_OFFSET 0x01B8U +#define FIOPAD_111_FUNC_OFFSET 0x01BCU +#define FIOPAD_112_FUNC_OFFSET 0x01C0U +#define FIOPAD_113_FUNC_OFFSET 0x01C4U +#define FIOPAD_114_FUNC_OFFSET 0x01C8U +#define FIOPAD_115_FUNC_OFFSET 0x01CCU +#define FIOPAD_116_FUNC_OFFSET 0x01D0U +#define FIOPAD_117_FUNC_OFFSET 0x01D4U +#define FIOPAD_118_FUNC_OFFSET 0x01D8U +#define FIOPAD_119_FUNC_OFFSET 0x01DCU +#define FIOPAD_120_FUNC_OFFSET 0x01E0U +#define FIOPAD_121_FUNC_OFFSET 0x01E4U +#define FIOPAD_122_FUNC_OFFSET 0x01E8U +#define FIOPAD_123_FUNC_OFFSET 0x01ECU +#define FIOPAD_124_FUNC_OFFSET 0x01F0U +#define FIOPAD_125_FUNC_OFFSET 0x01F4U +#define FIOPAD_126_FUNC_OFFSET 0x01F8U +#define FIOPAD_127_FUNC_OFFSET 0x01FCU +#define FIOPAD_128_FUNC_OFFSET 0x0200U +#define FIOPAD_129_FUNC_OFFSET 0x0204U +#define FIOPAD_130_FUNC_OFFSET 0x0208U +#define FIOPAD_131_FUNC_OFFSET 0x020CU +#define FIOPAD_132_FUNC_OFFSET 0x0210U +#define FIOPAD_133_FUNC_OFFSET 0x0214U +#define FIOPAD_134_FUNC_OFFSET 0x0218U +#define FIOPAD_135_FUNC_OFFSET 0x021CU +#define FIOPAD_136_FUNC_OFFSET 0x0220U +#define FIOPAD_137_FUNC_OFFSET 0x0224U +#define FIOPAD_138_FUNC_OFFSET 0x0228U +#define FIOPAD_139_FUNC_OFFSET 0x022CU +#define FIOPAD_140_FUNC_OFFSET 0x0230U +#define FIOPAD_141_FUNC_OFFSET 0x0234U +#define FIOPAD_142_FUNC_OFFSET 0x0238U +#define FIOPAD_143_FUNC_OFFSET 0x023CU +#define FIOPAD_144_FUNC_OFFSET 0x0240U +#define FIOPAD_145_FUNC_OFFSET 0x0244U +#define FIOPAD_146_FUNC_OFFSET 0x0248U +#define FIOPAD_147_FUNC_OFFSET 0x024CU + +/* register offset of iopad delay */ +#define FIOPAD_10_DELAY_OFFSET 0x1024U +#define FIOPAD_11_DELAY_OFFSET 0x1028U +#define FIOPAD_12_DELAY_OFFSET 0x102CU +#define FIOPAD_13_DELAY_OFFSET 0x1030U +#define FIOPAD_14_DELAY_OFFSET 0x1034U +#define FIOPAD_23_DELAY_OFFSET 0x1058U +#define FIOPAD_24_DELAY_OFFSET 0x105CU +#define FIOPAD_25_DELAY_OFFSET 0x1060U +#define FIOPAD_26_DELAY_OFFSET 0x1064U +#define FIOPAD_32_DELAY_OFFSET 0x1074U +#define FIOPAD_33_DELAY_OFFSET 0x1078U +#define FIOPAD_34_DELAY_OFFSET 0x107CU +#define FIOPAD_35_DELAY_OFFSET 0x1080U +#define FIOPAD_55_DELAY_OFFSET 0x10D0U +#define FIOPAD_56_DELAY_OFFSET 0x10D4U +#define FIOPAD_57_DELAY_OFFSET 0x10D8U +#define FIOPAD_58_DELAY_OFFSET 0x10DCU +#define FIOPAD_59_DELAY_OFFSET 0x10E0U +#define FIOPAD_60_DELAY_OFFSET 0x10E4U +#define FIOPAD_61_DELAY_OFFSET 0x10E8U +#define FIOPAD_62_DELAY_OFFSET 0x10ECU +#define FIOPAD_63_DELAY_OFFSET 0x10F0U +#define FIOPAD_64_DELAY_OFFSET 0x10F4U +#define FIOPAD_65_DELAY_OFFSET 0x10F8U +#define FIOPAD_66_DELAY_OFFSET 0x10FCU +#define FIOPAD_67_DELAY_OFFSET 0x1100U +#define FIOPAD_68_DELAY_OFFSET 0x1104U +#define FIOPAD_148_DELAY_OFFSET 0x1108U +#define FIOPAD_69_DELAY_OFFSET 0x110CU +#define FIOPAD_70_DELAY_OFFSET 0x1110U +#define FIOPAD_71_DELAY_OFFSET 0x1114U +#define FIOPAD_72_DELAY_OFFSET 0x1118U +#define FIOPAD_73_DELAY_OFFSET 0x111CU +#define FIOPAD_74_DELAY_OFFSET 0x1120U +#define FIOPAD_75_DELAY_OFFSET 0x1124U +#define FIOPAD_76_DELAY_OFFSET 0x1128U +#define FIOPAD_77_DELAY_OFFSET 0x112CU +#define FIOPAD_78_DELAY_OFFSET 0x1130U +#define FIOPAD_80_DELAY_OFFSET 0x1138U +#define FIOPAD_81_DELAY_OFFSET 0x113CU +#define FIOPAD_82_DELAY_OFFSET 0x1140U +#define FIOPAD_83_DELAY_OFFSET 0x1144U +#define FIOPAD_84_DELAY_OFFSET 0x1148U +#define FIOPAD_85_DELAY_OFFSET 0x114CU +#define FIOPAD_86_DELAY_OFFSET 0x1150U +#define FIOPAD_87_DELAY_OFFSET 0x1154U +#define FIOPAD_88_DELAY_OFFSET 0x1158U +#define FIOPAD_89_DELAY_OFFSET 0x115CU +#define FIOPAD_90_DELAY_OFFSET 0x1160U +#define FIOPAD_92_DELAY_OFFSET 0x1168U +#define FIOPAD_93_DELAY_OFFSET 0x116CU +#define FIOPAD_94_DELAY_OFFSET 0x1170U +#define FIOPAD_95_DELAY_OFFSET 0x1174U +#define FIOPAD_96_DELAY_OFFSET 0x1178U +#define FIOPAD_97_DELAY_OFFSET 0x117CU +#define FIOPAD_98_DELAY_OFFSET 0x1180U +#define FIOPAD_99_DELAY_OFFSET 0x118CU +#define FIOPAD_100_DELAY_OFFSET 0x1190U +#define FIOPAD_101_DELAY_OFFSET 0x1194U +#define FIOPAD_102_DELAY_OFFSET 0x1198U +#define FIOPAD_103_DELAY_OFFSET 0x119CU +#define FIOPAD_104_DELAY_OFFSET 0x11A0U +#define FIOPAD_105_DELAY_OFFSET 0x11A4U +#define FIOPAD_106_DELAY_OFFSET 0x11A8U +#define FIOPAD_107_DELAY_OFFSET 0x11ACU +#define FIOPAD_108_DELAY_OFFSET 0x11B0U +#define FIOPAD_109_DELAY_OFFSET 0x11B4U +#define FIOPAD_110_DELAY_OFFSET 0x11B8U +#define FIOPAD_111_DELAY_OFFSET 0x11BCU +#define FIOPAD_112_DELAY_OFFSET 0x11C0U +#define FIOPAD_115_DELAY_OFFSET 0x11CCU +#define FIOPAD_116_DELAY_OFFSET 0x11D0U +#define FIOPAD_117_DELAY_OFFSET 0x11D4U +#define FIOPAD_118_DELAY_OFFSET 0x11D8U +#define FIOPAD_119_DELAY_OFFSET 0x11DCU +#define FIOPAD_120_DELAY_OFFSET 0x11E0U +#define FIOPAD_121_DELAY_OFFSET 0x11E4U +#define FIOPAD_122_DELAY_OFFSET 0x11E8U +#define FIOPAD_123_DELAY_OFFSET 0x11ECU +#define FIOPAD_124_DELAY_OFFSET 0x11F0U +#define FIOPAD_125_DELAY_OFFSET 0x11F4U +#define FIOPAD_126_DELAY_OFFSET 0x11F8U +#define FIOPAD_127_DELAY_OFFSET 0x11FCU +#define FIOPAD_128_DELAY_OFFSET 0x1200U +#define FIOPAD_136_DELAY_OFFSET 0x1220U +#define FIOPAD_137_DELAY_OFFSET 0x1224U +#define FIOPAD_138_DELAY_OFFSET 0x1228U +#define FIOPAD_139_DELAY_OFFSET 0x122CU +#define FIOPAD_140_DELAY_OFFSET 0x1230U +#define FIOPAD_141_DELAY_OFFSET 0x1234U +#define FIOPAD_142_DELAY_OFFSET 0x1238U +#define FIOPAD_143_DELAY_OFFSET 0x123CU +#define FIOPAD_144_DELAY_OFFSET 0x1240U +#define FIOPAD_145_DELAY_OFFSET 0x1244U +#define FIOPAD_146_DELAY_OFFSET 0x1248U +#define FIOPAD_147_DELAY_OFFSET 0x124CU + +/************************** Function Prototypes ******************************/ +/* set iopad mux for spim */ +void FIOPadSetSpimMux(u32 spim_id); + +/* set iopad mux for gpio */ +void FIOPadSetGpioMux(u32 gpio_id, u32 pin_id); + +/* set iopad mux for mio */ +void FIOPadSetMioMux(u32 mio_id); + +/* print information of all iopad */ +void FIOPadDumpPadFunc(void); + +/* set iopad mux for can */ +void FIOPadSetCanMux(u32 can_id); + +/* set iopad mux for qspi */ +void FIOPadSetQspiMux(u32 qspi_id, u32 cs_id); + +/* set iopad mux for pwm */ +void FIOPadSetPwmMux(u32 pwm_id, u32 pwm_channel); + +/* set iopad mux for adc */ +void FIOPadSetAdcMux(u32 adc_id, u32 adc_channel); + +/* set iopad mux for tacho*/ +void FIOPadSetTachoMux(u32 pwm_in_id); + +/* set iopad mux for uart*/ +void FIOPadSetUartMux(u32 uart_id); + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/fparameters_comm.h b/bsp/phytium/libraries/standalone/board/e2000/fparameters_comm.h new file mode 100644 index 0000000000..5f807e7843 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/fparameters_comm.h @@ -0,0 +1,624 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fparameters_comm.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-17 18:01:11 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BOARD_E2000_PARAMTERERS_COMMON_H +#define BOARD_E2000_PARAMTERERS_COMMON_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#if !defined(__ASSEMBLER__) +#include "ftypes.h" +#endif + +/************************** Constant Definitions *****************************/ +/* CACHE */ +#define CACHE_LINE_ADDR_MASK 0x3FU +#define CACHE_LINE 64U + +/* DEVICE Register Address */ +#define FT_DEV_BASE_ADDR 0x28000000U +#define FT_DEV_END_ADDR 0x2FFFFFFFU + +/* PCI */ +#define FT_PCIE_NUM 1 +#define FT_PCIE0_ID 0 +#define FT_PCIE0_MISC_IRQ_NUM 40 + +#define FT_PCIE_CFG_MAX_NUM_OF_BUS 256 +#define FT_PCIE_CFG_MAX_NUM_OF_DEV 32 +#define FT_PCIE_CFG_MAX_NUM_OF_FUN 8 + +#define FT_PCI_CONFIG_BASEADDR 0x40000000U +#define FT_PCI_CONFIG_REG_LENGTH 0x10000000U + +#define FT_PCI_IO_CONFIG_BASEADDR 0x50000000U +#define FT_PCI_IO_CONFIG_REG_LENGTH 0x08000000U + +#define FT_PCI_MEM32_BASEADDR 0x58000000U +#define FT_PCI_MEM32_REG_LENGTH 0x27FFFFFFU + +#define FT_PCI_MEM64_BASEADDR 0x1000000000U +#define FT_PCI_MEM64_REG_LENGTH 0x1000000000U + +#define FT_PCI_EU0_C0_CONTROL_BASEADDR 0x29000000U +#define FT_PCI_EU0_C1_CONTROL_BASEADDR 0x29010000U +#define FT_PCI_EU0_C2_CONTROL_BASEADDR 0x29020000U +#define FT_PCI_EU1_C0_CONTROL_BASEADDR 0x29030000U +#define FT_PCI_EU1_C1_CONTROL_BASEADDR 0x29040000U +#define FT_PCI_EU1_C2_CONTROL_BASEADDR 0x29050000U + +#define FT_PCI_EU0_CONFIG_BASEADDR 0x29100000U +#define FT_PCI_EU1_CONFIG_BASEADDR 0x29101000U + +#define FT_PCI_INTA_IRQ_NUM 36 +#define FT_PCI_INTB_IRQ_NUM 37 +#define FT_PCI_INTC_IRQ_NUM 38 +#define FT_PCI_INTD_IRQ_NUM 39 + +#define FT_PCI_NEED_SKIP 0 + +#define FT_PCI_INTX_PEU0_STAT 0x29100000U +#define FT_PCI_INTX_PEU1_STAT 0x29101000U + +#define FT_PCI_INTX_EU0_C0_CONTROL 0x29000184U +#define FT_PCI_INTX_EU0_C1_CONTROL 0x29010184U +#define FT_PCI_INTX_EU0_C2_CONTROL 0x29020184U +#define FT_PCI_INTX_EU1_C0_CONTROL 0x29030184U +#define FT_PCI_INTX_EU1_C1_CONTROL 0x29040184U +#define FT_PCI_INTX_EU1_C2_CONTROL 0x29050184U + +#define FT_PCI_INTX_CONTROL_NUM 6 /* Total number of controllers */ +#define FT_PCI_INTX_SATA_NUM 2 /* Total number of controllers */ + + +/* platform ahci host */ +#define PLAT_AHCI_HOST_MAX_COUNT 5 +#define AHCI_BASE_0 0 +#define AHCI_BASE_1 0 +#define AHCI_BASE_2 0 +#define AHCI_BASE_3 0 +#define AHCI_BASE_4 0 + +#define AHCI_IRQ_0 0 +#define AHCI_IRQ_1 0 +#define AHCI_IRQ_2 0 +#define AHCI_IRQ_3 0 +#define AHCI_IRQ_4 0 + +/* sata controller */ +#define FSATA0_BASEADDR 0x31A40000U +#define FSATA1_BASEADDR 0x32014000U + +#define FSATA0_IRQNUM 74 +#define FSATA1_IRQNUM 75 + +#if !defined(__ASSEMBLER__) +typedef enum +{ + FSATA_INSTANCE_0 = 0, + FSATA_INSTANCE_1 = 1, + + FSATA_INSTANCE_NUM +} FSataInstance; +#endif + +/* Generic Timer */ +#define GENERIC_TIMER_CLK_FREQ_MHZ 48U +#define GENERIC_TIMER_NS_IRQ_NUM 30U +#define GENERIC_TIMER_NS_CLK_FREQ 2000000U +#define COUNTS_PER_SECOND GENERIC_TIMER_NS_CLK_FREQ + +/* UART */ +#define FUART_NUM 4U +#define FUART_REG_LENGTH 0x18000U + +#define FUART0_ID 0U +#define FUART0_IRQ_NUM (85 + 30) +#define FUART0_BASE_ADDR 0x2800c000U +#define FUART0_CLK_FREQ_HZ 100000000U + +#define FUART1_ID 1U +#define FUART1_IRQ_NUM (86 + 30) +#define FUART1_BASE_ADDR 0x2800d000U +#define FUART1_CLK_FREQ_HZ 100000000U + +#define FUART2_ID 2U +#define FUART2_IRQ_NUM (87 + 30) +#define FUART2_BASE_ADDR 0x2800e000U +#define FUART2_CLK_FREQ_HZ 100000000U + +#define FUART3_BASE_ADDR 0x2800f000U +#define FUART3_ID 3U +#define FUART3_IRQ_NUM (88 + 30) +#define FUART3_CLK_FREQ_HZ 100000000U + +#define FT_STDOUT_BASE_ADDR FUART1_BASE_ADDR +#define FT_STDIN_BASE_ADDR FUART1_BASE_ADDR + +/****** GIC v3 *****/ +#define FT_GICV3_INSTANCES_NUM 1U +#define GICV3_REG_LENGTH 0x00009000U + +/* + * The maximum priority value that can be used in the GIC. + */ +#define GICV3_MAX_INTR_PRIO_VAL 240U +#define GICV3_INTR_PRIO_MASK 0x000000f0U + +#define ARM_GIC_NR_IRQS 160U +#define ARM_GIC_IRQ_START 0U +#define FGIC_NUM 1U + +#define ARM_GIC_IPI_COUNT 16U /* MPCore IPI count */ +#define SGI_INT_MAX 16U +#define SPI_START_INT_NUM 32U /* SPI start at ID32 */ +#define PPI_START_INT_NUM 16U /* PPI start at ID16 */ +#define GIC_INT_MAX_NUM 1020U /* GIC max interrupts count */ + +#define GICV3_BASEADDRESS 0x30800000U +#define GICV3_DISTRIBUTOR_BASEADDRESS (GICV3_BASEADDRESS + 0) +#define GICV3_RD_BASEADDRESS (GICV3_BASEADDRESS + 0x80000U) +#define GICV3_RD_OFFSET (2U << 16) +#define FT_GICV3_VECTORTABLE_NUM GIC_INT_MAX_NUM + +/* GPIO */ +#define FGPIO_ID_0 0U +#define FGPIO_ID_1 1U +#define FGPIO_ID_2 2U +#define FGPIO_WITH_PIN_IRQ 2U /* max id of gpio assign irq for each pin */ +#define FGPIO_ID_3 3U +#define FGPIO_ID_4 4U +#define FGPIO_ID_5 5U +#define FGPIO_NUM 6U + +#define FGPIO_0_BASE_ADDR 0x28034000U +#define FGPIO_1_BASE_ADDR 0x28035000U +#define FGPIO_2_BASE_ADDR 0x28036000U +#define FGPIO_3_BASE_ADDR 0x28037000U +#define FGPIO_4_BASE_ADDR 0x28038000U +#define FGPIO_5_BASE_ADDR 0x28039000U + +#define FGPIO_CTRL_PIN_NUM 16U + +#define FGPIO_PIN_IRQ_BASE 140U +#define FGPIO_PIN_IRQ_NUM_GET(id, pin) (FGPIO_PIN_IRQ_BASE + FGPIO_CTRL_PIN_NUM * (id) + (pin)) + +#define FGPIO_3_IRQ_NUM 188U +#define FGPIO_4_IRQ_NUM 189U +#define FGPIO_5_IRQ_NUM 190U + +#define FGPIO_PIN_IRQ_TOTAL 51U + +/* SPI */ +#define FSPI0_BASE 0x2803A000U +#define FSPI1_BASE 0x2803B000U +#define FSPI2_BASE 0x2803C000U +#define FSPI3_BASE 0x2803D000U +#define FSPI0_ID 0U +#define FSPI1_ID 1U +#define FSPI2_ID 2U +#define FSPI3_ID 3U + +#define FSPI0_IRQ_NUM 191U +#define FSPI1_IRQ_NUM 192U +#define FSPI2_IRQ_NUM 193U +#define FSPI3_IRQ_NUM 194U + +#define FSPI_FREQ 50000000U +#define FSPI_DEVICE_NUM 4U + +/* XMAC */ +#define FT_XMAC_NUM 4U + +#define FT_XMAC0_ID 0U +#define FT_XMAC1_ID 1U +#define FT_XMAC2_ID 2U +#define FT_XMAC3_ID 3U + +#define FT_XMAC0_BASEADDRESS 0x3200C000U +#define FT_XMAC1_BASEADDRESS 0x3200E000U +#define FT_XMAC2_BASEADDRESS 0x32010000U +#define FT_XMAC3_BASEADDRESS 0x32012000U + +#define FT_XMAC0_MODE_SEL_BASEADDRESS 0x3200DC00U +#define FT_XMAC0_LOOPBACK_SEL_BASEADDRESS 0x3200DC04U +#define FT_XMAC1_MODE_SEL_BASEADDRESS 0x3200FC00U +#define FT_XMAC1_LOOPBACK_SEL_BASEADDRESS 0x3200FC04U +#define FT_XMAC2_MODE_SEL_BASEADDRESS 0x32011C00U +#define FT_XMAC2_LOOPBACK_SEL_BASEADDRESS 0x32011C04U +#define FT_XMAC3_MODE_SEL_BASEADDRESS 0x32013C00U +#define FT_XMAC3_LOOPBACK_SEL_BASEADDRESS 0x32013C04U + +#define FT_XMAC0_PCLK 50000000U +#define FT_XMAC1_PCLK 50000000U +#define FT_XMAC2_PCLK 50000000U +#define FT_XMAC3_PCLK 50000000U +#define FT_XMAC0_HOTPLUG_IRQ_NUM (53U + 30U) +#define FT_XMAC1_HOTPLUG_IRQ_NUM (54U + 30U) +#define FT_XMAC2_HOTPLUG_IRQ_NUM (55U + 30U) +#define FT_XMAC3_HOTPLUG_IRQ_NUM (56U + 30U) + +#define FT_XMAC_QUEUE_MAX_NUM 16U + +#define FT_XMAC0_QUEUE0_IRQ_NUM (57U + 30U) +#define FT_XMAC0_QUEUE1_IRQ_NUM (58U + 30U) +#define FT_XMAC0_QUEUE2_IRQ_NUM (59U + 30U) +#define FT_XMAC0_QUEUE3_IRQ_NUM (60U + 30U) +#define FT_XMAC0_QUEUE4_IRQ_NUM (30U + 30U) +#define FT_XMAC0_QUEUE5_IRQ_NUM (31U + 30U) +#define FT_XMAC0_QUEUE6_IRQ_NUM (32U + 30U) +#define FT_XMAC0_QUEUE7_IRQ_NUM (33U + 30U) + +#define FT_XMAC1_QUEUE0_IRQ_NUM (61U + 30U) +#define FT_XMAC1_QUEUE1_IRQ_NUM (62U + 30U) +#define FT_XMAC1_QUEUE2_IRQ_NUM (63U + 30U) +#define FT_XMAC1_QUEUE3_IRQ_NUM (64U + 30U) + +#define FT_XMAC2_QUEUE0_IRQ_NUM (66U + 30U) +#define FT_XMAC2_QUEUE1_IRQ_NUM (67U + 30U) +#define FT_XMAC2_QUEUE2_IRQ_NUM (68U + 30U) +#define FT_XMAC2_QUEUE3_IRQ_NUM (69U + 30U) + +#define FT_XMAC3_QUEUE0_IRQ_NUM (70U + 30U) +#define FT_XMAC3_QUEUE1_IRQ_NUM (71U + 30U) +#define FT_XMAC3_QUEUE2_IRQ_NUM (72U + 30U) +#define FT_XMAC3_QUEUE3_IRQ_NUM (73U + 30U) + +#define FT_XMAC_PHY_MAX_NUM 32U + +/* QSPI */ + +#define FQSPI_BASEADDR 0x028008000U + +#if !defined(__ASSEMBLER__) + +typedef enum +{ + FQSPI_INSTANCE_0 = 0, + + FQSPI_INSTANCE_NUM +} FQspiInstance; + +/* FQSPI cs 0_3, chip number */ +typedef enum +{ + FQSPI_CS_0 = 0, + FQSPI_CS_1 = 1, + FQSPI_CS_2 = 2, + FQSPI_CS_3 = 3, + FQSPI_CS_NUM +} FQspiChipCS; + +#endif + +#define FQSPI_MEM_START_ADDR 0x0U +#define FQSPI_MEM_END_ADDR 0x0FFFFFFFU /* 256MB */ +#define FQSPI_MEM_START_ADDR_64 0x100000000U +#define FQSPI_MEM_END_ADDR_64 0x17FFFFFFFU /* 2GB */ + +/* TIMER and TACHO */ +#define TIMER_NUM 38U +#define TACHO_NUM 16U +#define TIMER_CLK_FREQ_HZ 50000000U /* 50MHz */ +#define TIMER_TICK_PERIOD_NS 20U /* 20ns */ +#define TIMER_TACHO_IRQ_ID(n) (226U + (n)) +#define TIMER_TACHO_BASE_ADDR(n) (0x28054000U + 0x1000U * (n)) + +#if !defined(__ASSEMBLER__) +typedef enum +{ + TACHO_INSTANCE_0 = 0, + TACHO_INSTANCE_1 = 1, + TACHO_INSTANCE_2 = 2, + TACHO_INSTANCE_3 = 3, + TACHO_INSTANCE_4 = 4, + TACHO_INSTANCE_5 = 5, + TACHO_INSTANCE_6 = 6, + TACHO_INSTANCE_7 = 7, + TACHO_INSTANCE_8 = 8, + TACHO_INSTANCE_9 = 9, + TACHO_INSTANCE_10 = 10, + TACHO_INSTANCE_11 = 11, + TACHO_INSTANCE_12 = 12, + TACHO_INSTANCE_13 = 13, + TACHO_INSTANCE_14 = 14, + TACHO_INSTANCE_15 = 15, + + TACHO_INSTANCE_NUM +} TachoInstance; +#endif + +/* GDMA */ +#define FGDMA0_ID 0U +#define FGDMA0_BASE_ADDR 0x32B34000U +#define FGDMA0_IRQ_NUM 266U + +#define FGDMA_INSTANCE_NUM 1U + +/* CANFD */ +#define FCAN_REF_CLOCK 200000000U + +#define FCAN0_BASEADDR 0x2800A000U +#define FCAN1_BASEADDR 0x2800B000U + +#define FCAN0_IRQNUM 113U +#define FCAN1_IRQNUM 114U + +#if !defined(__ASSEMBLER__) +typedef enum +{ + FCAN_INSTANCE_0 = 0, + FCAN_INSTANCE_1 = 1, + + FCAN_INSTANCE_NUM +} FCanInstance; +#endif + +/* WDT */ +#if !defined(__ASSEMBLER__) +typedef enum +{ + FWDT_INSTANCE_0 = 0, + FWDT_INSTANCE_1, + + FWDT_INSTANCE_NUM +} FWdtInstance; +#endif + +#define FWDT0_REFRESH_BASE 0x28040000U +#define FWDT0_CONTROL_BASE 0x28041000U +#define FWDT1_REFRESH_BASE 0x28042000U +#define FWDT1_CONTROL_BASE 0x28043000U + +#define FWDT0_INTR_IRQ 196U +#define FWDT1_INTR_IRQ 197U + +#define FWDT_CLK 48000000U /* 48MHz */ + +/*MIO*/ +#define FMIO_NUM 16 +#define FMIO_BASE_ADDR(n) (0x28014000 + 0x2000 * (n)) +#define FMIO_CONF_ADDR(n) FMIO_BASE_ADDR(n)+0x1000 +#define FMIO_IRQ_NUM(n) (124+n) +#define MIO_REF_CLK_HZ 50000000 /* 50MHz */ + +#if !defined(__ASSEMBLER__) +typedef enum +{ + MIO_INSTANCE_0 = 0, + MIO_INSTANCE_1, + MIO_INSTANCE_2, + MIO_INSTANCE_3, + MIO_INSTANCE_4, + MIO_INSTANCE_5, + MIO_INSTANCE_6, + MIO_INSTANCE_7, + MIO_INSTANCE_8, + MIO_INSTANCE_9, + MIO_INSTANCE_10, + MIO_INSTANCE_11, + MIO_INSTANCE_12, + MIO_INSTANCE_13, + MIO_INSTANCE_14, + MIO_INSTANCE_15, + + MIO_INSTANCE_NUM +} MioInstance; +#endif + +#if !defined(__ASSEMBLER__) +/*I2C0 -> PMBUS0 +* I2C1 -> PMBUS1 +* I2C2 -> SMBUS0 +*/ +typedef enum +{ + I2C_INSTANCE_0 = 0, + I2C_INSTANCE_1, + I2C_INSTANCE_2, + + I2C_INSTANCE_NUM +} I2cInstance; +#endif + +#define I2C_0_BASEADDR 0x28011000 +#define I2C_1_BASEADDR 0x28012000 +#define I2C_2_BASEADDR 0x28013000 + +#define I2C_0_INTR_IRQ 121 +#define I2C_1_INTR_IRQ 122 +#define I2C_2_INTR_IRQ 123 + +#define I2C_REF_CLK_HZ 50000000 /* 50MHz */ + +/* SDIO */ +#if !defined(__ASSEMBLER__) +enum +{ + FSDIO_HOST_INSTANCE_0 = 0, + FSDIO_HOST_INSTANCE_1, + + FSDIO_HOST_INSTANCE_NUM +}; +#endif + +#define FSDIO_HOST_0_BASE_ADDR 0x28000000U +#define FSDIO_HOST_1_BASE_ADDR 0x28001000U + +#define FSDIO_HOST_0_IRQ_NUM 104U +#define FSDIO_HOST_1_IRQ_NUM 105U + +#define FSDIO_CLK_RATE_HZ (1200000000UL) /* 1.2GHz */ + +/* NAND */ +#define FNAND_NUM 1U +#define FNAND_INSTANCE0 0U +#define FNAND_BASEADDRESS 0x28002000U +#define FNAND_IRQ_NUM (106U) +#define FNAND_CONNECT_MAX_NUM 1U + +#define FIOPAD_BASE_ADDR 0x32B30000U + +/* DDMA */ +#define FDDMA0_ID 0U +#define FDDMA0_BASE_ADDR 0x28003000U +#define FDDMA0_IRQ_NUM 107U + +#define FDDMA1_ID 1U +#define FDDMA1_BASE_ADDR 0x28004000U +#define FDDMA1_IRQ_NUM 108U + +#define FDDMA_INSTANCE_NUM 2U + +#define FDDMA0_UART0_TX_SLAVE_ID 2U /* uart0 tx slave-id */ +#define FDDMA0_UART1_TX_SLAVE_ID 3U /* uart1 tx slave-id */ +#define FDDMA0_UART2_TX_SLAVE_ID 4U /* uart2 tx slave-id */ +#define FDDMA0_UART3_TX_SLAVE_ID 5U /* uart3 tx slave-id */ + +#define FDDMA0_SPIM0_TX_SLAVE_ID 6U /* spi0 tx slave-id */ +#define FDDMA0_SPIM1_TX_SLAVE_ID 7U /* spi1 tx slave-id */ +#define FDDMA0_SPIM2_TX_SLAVE_ID 8U /* spi2 tx slave-id */ +#define FDDMA0_SPIM3_TX_SLAVE_ID 9U /* spi3 tx slave-id */ + +#define FDDMA0_UART0_RX_SLAVE_ID 15U /* uart0 rx slave-id */ +#define FDDMA0_UART1_RX_SLAVE_ID 16U /* uart1 rx slave-id */ +#define FDDMA0_UART2_RX_SLAVE_ID 17U /* uart2 rx slave-id */ +#define FDDMA0_UART3_RX_SLAVE_ID 18U /* uart3 rx slave-id */ + +#define FDDMA0_SPIM0_RX_SLAVE_ID 19U /* spi0 rx slave-id */ +#define FDDMA0_SPIM1_RX_SLAVE_ID 20U /* spi1 rx slave-id */ +#define FDDMA0_SPIM2_RX_SLAVE_ID 21U /* spi2 rx slave-id */ +#define FDDMA0_SPIM3_RX_SLAVE_ID 22U /* spi3 rx slave-id */ + +#define FDDMA_MIN_SLAVE_ID 0U +#define FDDMA_MAX_SLAVE_ID 31U + +/* ADC */ +#if !defined(__ASSEMBLER__) +typedef enum +{ + FADC_INSTANCE_0 = 0, + FADC_INSTANCE_1, + + FADC_INSTANCE_NUM +} FAdcInstance; + +typedef enum +{ + FADC_CHANNEL_0 = 0, + FADC_CHANNEL_1 = 1, + FADC_CHANNEL_2, + FADC_CHANNEL_3, + FADC_CHANNEL_4, + FADC_CHANNEL_5, + FADC_CHANNEL_6, + FADC_CHANNEL_7, + + FADC_CHANNEL_NUM +} FAdcChannel; + +#endif + +#define FADC0_CONTROL_BASE 0x2807B000U +#define FADC1_CONTROL_BASE 0x2807C000U + +#define FADC0_INTR_IRQ 264U +#define FADC1_INTR_IRQ 265U + +/* PWM */ +#if !defined(__ASSEMBLER__) +typedef enum +{ + FPWM_INSTANCE_0 = 0, + FPWM_INSTANCE_1, + FPWM_INSTANCE_2, + FPWM_INSTANCE_3, + FPWM_INSTANCE_4, + FPWM_INSTANCE_5, + FPWM_INSTANCE_6, + FPWM_INSTANCE_7, + + FPWM_INSTANCE_NUM +} FPwmInstance; + +typedef enum +{ + FPWM_CHANNEL_0 = 0, + FPWM_CHANNEL_1, + + FPWM_CHANNEL_NUM +} FPwmChannel; +#endif + +#define FPWM_CONTROL_BASE 0x2804A000U + +#define FPWM_CLK 50000000U /* 50MHz */ + +#define FPWM0_INTR_IRQ 205U +#define FPWM1_INTR_IRQ 206U +#define FPWM2_INTR_IRQ 207U +#define FPWM3_INTR_IRQ 208U +#define FPWM4_INTR_IRQ 209U +#define FPWM5_INTR_IRQ 210U +#define FPWM6_INTR_IRQ 211U +#define FPWM7_INTR_IRQ 212U +#define FPWM8_INTR_IRQ 213U +#define FPWM9_INTR_IRQ 214U +#define FPWM10_INTR_IRQ 215U +#define FPWM11_INTR_IRQ 216U +#define FPWM12_INTR_IRQ 217U +#define FPWM13_INTR_IRQ 218U +#define FPWM14_INTR_IRQ 219U +#define FPWM15_INTR_IRQ 220U + +/* Semaphore */ +#define FSEMA0_ID 0U +#define FSEMA0_BASE_ADDR 0x32B36000U +#define FSEMA_INSTANCE_NUM 1U + +/* LSD Config */ +#define FLSD_CONFIG_BASE 0x2807E000U +#define FLSD_NAND_MMCSD_HADDR 0xC0U +#define FLSD_CK_STOP_CONFIG0_HADDR 0x10U + +/* USB3 */ +#define FUSB3_ID_0 0U +#define FUSB3_ID_1 1U +#define FUSB3_NUM 2U +#define FUSB3_XHCI_OFFSET 0x8000U +#define FUSB3_0_BASE_ADDR 0x31A00000U +#define FUSB3_1_BASE_ADDR 0x31A20000U +#define FUSB3_0_IRQ_NUM 48U +#define FUSB3_1_IRQ_NUM 49U +/*****************************************************************************/ + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/q/fiopad.h b/bsp/phytium/libraries/standalone/board/e2000/q/fiopad.h new file mode 100644 index 0000000000..74eb5aa77e --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/q/fiopad.h @@ -0,0 +1,266 @@ + +#ifndef BOARD_E2000Q_FIOPAD_H +#define BOARD_E2000Q_FIOPAD_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fiopad_comm.h" + +/************************** Constant Definitions *****************************/ +/* register offset of iopad function / pull / driver strength */ +#define FIOPAD_AN59 (FPinIndex)FIOPAD_INDEX(FIOPAD_0_FUNC_OFFSET) +#define FIOPAD_AW47 (FPinIndex)FIOPAD_INDEX(FIOPAD_2_FUNC_OFFSET) +#define FIOPAD_AR55 (FPinIndex)FIOPAD_INDEX(FIOPAD_9_FUNC_OFFSET) +#define FIOPAD_AJ55 (FPinIndex)FIOPAD_INDEX(FIOPAD_10_FUNC_OFFSET) +#define FIOPAD_AL55 (FPinIndex)FIOPAD_INDEX(FIOPAD_11_FUNC_OFFSET) +#define FIOPAD_AL53 (FPinIndex)FIOPAD_INDEX(FIOPAD_12_FUNC_OFFSET) +#define FIOPAD_AN51 (FPinIndex)FIOPAD_INDEX(FIOPAD_13_FUNC_OFFSET) +#define FIOPAD_AR51 (FPinIndex)FIOPAD_INDEX(FIOPAD_14_FUNC_OFFSET) +#define FIOPAD_BA57 (FPinIndex)FIOPAD_INDEX(FIOPAD_15_FUNC_OFFSET) +#define FIOPAD_BA59 (FPinIndex)FIOPAD_INDEX(FIOPAD_16_FUNC_OFFSET) +#define FIOPAD_AW57 (FPinIndex)FIOPAD_INDEX(FIOPAD_17_FUNC_OFFSET) +#define FIOPAD_AW59 (FPinIndex)FIOPAD_INDEX(FIOPAD_18_FUNC_OFFSET) +#define FIOPAD_AU55 (FPinIndex)FIOPAD_INDEX(FIOPAD_19_FUNC_OFFSET) +#define FIOPAD_AN57 (FPinIndex)FIOPAD_INDEX(FIOPAD_20_FUNC_OFFSET) +#define FIOPAD_AL59 (FPinIndex)FIOPAD_INDEX(FIOPAD_21_FUNC_OFFSET) +#define FIOPAD_AJ59 (FPinIndex)FIOPAD_INDEX(FIOPAD_22_FUNC_OFFSET) +#define FIOPAD_AJ57 (FPinIndex)FIOPAD_INDEX(FIOPAD_23_FUNC_OFFSET) +#define FIOPAD_AG59 (FPinIndex)FIOPAD_INDEX(FIOPAD_24_FUNC_OFFSET) +#define FIOPAD_AG57 (FPinIndex)FIOPAD_INDEX(FIOPAD_25_FUNC_OFFSET) +#define FIOPAD_AE59 (FPinIndex)FIOPAD_INDEX(FIOPAD_26_FUNC_OFFSET) +#define FIOPAD_AC59 (FPinIndex)FIOPAD_INDEX(FIOPAD_27_FUNC_OFFSET) +#define FIOPAD_AC57 (FPinIndex)FIOPAD_INDEX(FIOPAD_28_FUNC_OFFSET) +#define FIOPAD_AR49 (FPinIndex)FIOPAD_INDEX(FIOPAD_31_FUNC_OFFSET) +#define FIOPAD_BA55 (FPinIndex)FIOPAD_INDEX(FIOPAD_32_FUNC_OFFSET) +#define FIOPAD_BA53 (FPinIndex)FIOPAD_INDEX(FIOPAD_33_FUNC_OFFSET) +#define FIOPAD_AR59 (FPinIndex)FIOPAD_INDEX(FIOPAD_34_FUNC_OFFSET) +#define FIOPAD_AU59 (FPinIndex)FIOPAD_INDEX(FIOPAD_35_FUNC_OFFSET) +#define FIOPAD_AR57 (FPinIndex)FIOPAD_INDEX(FIOPAD_36_FUNC_OFFSET) +#define FIOPAD_BA49 (FPinIndex)FIOPAD_INDEX(FIOPAD_37_FUNC_OFFSET) +#define FIOPAD_AW55 (FPinIndex)FIOPAD_INDEX(FIOPAD_38_FUNC_OFFSET) +#define FIOPAD_A35 (FPinIndex)FIOPAD_INDEX(FIOPAD_39_FUNC_OFFSET) +#define FIOPAD_R57 (FPinIndex)FIOPAD_INDEX(FIOPAD_40_FUNC_OFFSET) +#define FIOPAD_R59 (FPinIndex)FIOPAD_INDEX(FIOPAD_41_FUNC_OFFSET) +#define FIOPAD_U59 (FPinIndex)FIOPAD_INDEX(FIOPAD_42_FUNC_OFFSET) +#define FIOPAD_W59 (FPinIndex)FIOPAD_INDEX(FIOPAD_43_FUNC_OFFSET) +#define FIOPAD_U57 (FPinIndex)FIOPAD_INDEX(FIOPAD_44_FUNC_OFFSET) +#define FIOPAD_AA57 (FPinIndex)FIOPAD_INDEX(FIOPAD_45_FUNC_OFFSET) +#define FIOPAD_AA59 (FPinIndex)FIOPAD_INDEX(FIOPAD_46_FUNC_OFFSET) +#define FIOPAD_AW51 (FPinIndex)FIOPAD_INDEX(FIOPAD_47_FUNC_OFFSET) +#define FIOPAD_AU51 (FPinIndex)FIOPAD_INDEX(FIOPAD_48_FUNC_OFFSET) +#define FIOPAD_A39 (FPinIndex)FIOPAD_INDEX(FIOPAD_49_FUNC_OFFSET) +#define FIOPAD_C39 (FPinIndex)FIOPAD_INDEX(FIOPAD_50_FUNC_OFFSET) +#define FIOPAD_C37 (FPinIndex)FIOPAD_INDEX(FIOPAD_51_FUNC_OFFSET) +#define FIOPAD_A37 (FPinIndex)FIOPAD_INDEX(FIOPAD_52_FUNC_OFFSET) +#define FIOPAD_A41 (FPinIndex)FIOPAD_INDEX(FIOPAD_53_FUNC_OFFSET) +#define FIOPAD_A43 (FPinIndex)FIOPAD_INDEX(FIOPAD_54_FUNC_OFFSET) +#define FIOPAD_A45 (FPinIndex)FIOPAD_INDEX(FIOPAD_55_FUNC_OFFSET) +#define FIOPAD_C45 (FPinIndex)FIOPAD_INDEX(FIOPAD_56_FUNC_OFFSET) +#define FIOPAD_A47 (FPinIndex)FIOPAD_INDEX(FIOPAD_57_FUNC_OFFSET) +#define FIOPAD_A49 (FPinIndex)FIOPAD_INDEX(FIOPAD_58_FUNC_OFFSET) +#define FIOPAD_C49 (FPinIndex)FIOPAD_INDEX(FIOPAD_59_FUNC_OFFSET) +#define FIOPAD_A51 (FPinIndex)FIOPAD_INDEX(FIOPAD_60_FUNC_OFFSET) +#define FIOPAD_A33 (FPinIndex)FIOPAD_INDEX(FIOPAD_61_FUNC_OFFSET) +#define FIOPAD_C33 (FPinIndex)FIOPAD_INDEX(FIOPAD_62_FUNC_OFFSET) +#define FIOPAD_C31 (FPinIndex)FIOPAD_INDEX(FIOPAD_63_FUNC_OFFSET) +#define FIOPAD_A31 (FPinIndex)FIOPAD_INDEX(FIOPAD_64_FUNC_OFFSET) +#define FIOPAD_AJ53 (FPinIndex)FIOPAD_INDEX(FIOPAD_65_FUNC_OFFSET) +#define FIOPAD_AL49 (FPinIndex)FIOPAD_INDEX(FIOPAD_66_FUNC_OFFSET) +#define FIOPAD_AL47 (FPinIndex)FIOPAD_INDEX(FIOPAD_67_FUNC_OFFSET) +#define FIOPAD_AN49 (FPinIndex)FIOPAD_INDEX(FIOPAD_68_FUNC_OFFSET) +#define FIOPAD_AG51 (FPinIndex)FIOPAD_INDEX(FIOPAD_148_FUNC_OFFSET) +#define FIOPAD_AJ51 (FPinIndex)FIOPAD_INDEX(FIOPAD_69_FUNC_OFFSET) +#define FIOPAD_AG49 (FPinIndex)FIOPAD_INDEX(FIOPAD_70_FUNC_OFFSET) +#define FIOPAD_AE55 (FPinIndex)FIOPAD_INDEX(FIOPAD_71_FUNC_OFFSET) +#define FIOPAD_AE53 (FPinIndex)FIOPAD_INDEX(FIOPAD_72_FUNC_OFFSET) +#define FIOPAD_AG55 (FPinIndex)FIOPAD_INDEX(FIOPAD_73_FUNC_OFFSET) +#define FIOPAD_AJ49 (FPinIndex)FIOPAD_INDEX(FIOPAD_74_FUNC_OFFSET) +#define FIOPAD_AC55 (FPinIndex)FIOPAD_INDEX(FIOPAD_75_FUNC_OFFSET) +#define FIOPAD_AC53 (FPinIndex)FIOPAD_INDEX(FIOPAD_76_FUNC_OFFSET) +#define FIOPAD_AE51 (FPinIndex)FIOPAD_INDEX(FIOPAD_77_FUNC_OFFSET) +#define FIOPAD_W51 (FPinIndex)FIOPAD_INDEX(FIOPAD_78_FUNC_OFFSET) +#define FIOPAD_W55 (FPinIndex)FIOPAD_INDEX(FIOPAD_79_FUNC_OFFSET) +#define FIOPAD_W53 (FPinIndex)FIOPAD_INDEX(FIOPAD_80_FUNC_OFFSET) +#define FIOPAD_U55 (FPinIndex)FIOPAD_INDEX(FIOPAD_81_FUNC_OFFSET) +#define FIOPAD_U53 (FPinIndex)FIOPAD_INDEX(FIOPAD_82_FUNC_OFFSET) +#define FIOPAD_AE49 (FPinIndex)FIOPAD_INDEX(FIOPAD_83_FUNC_OFFSET) +#define FIOPAD_AC49 (FPinIndex)FIOPAD_INDEX(FIOPAD_84_FUNC_OFFSET) +#define FIOPAD_AE47 (FPinIndex)FIOPAD_INDEX(FIOPAD_85_FUNC_OFFSET) +#define FIOPAD_AA47 (FPinIndex)FIOPAD_INDEX(FIOPAD_86_FUNC_OFFSET) +#define FIOPAD_AA49 (FPinIndex)FIOPAD_INDEX(FIOPAD_87_FUNC_OFFSET) +#define FIOPAD_W49 (FPinIndex)FIOPAD_INDEX(FIOPAD_88_FUNC_OFFSET) +#define FIOPAD_AA51 (FPinIndex)FIOPAD_INDEX(FIOPAD_89_FUNC_OFFSET) +#define FIOPAD_U49 (FPinIndex)FIOPAD_INDEX(FIOPAD_90_FUNC_OFFSET) +#define FIOPAD_G59 (FPinIndex)FIOPAD_INDEX(FIOPAD_91_FUNC_OFFSET) +#define FIOPAD_J59 (FPinIndex)FIOPAD_INDEX(FIOPAD_92_FUNC_OFFSET) +#define FIOPAD_L57 (FPinIndex)FIOPAD_INDEX(FIOPAD_93_FUNC_OFFSET) +#define FIOPAD_C59 (FPinIndex)FIOPAD_INDEX(FIOPAD_94_FUNC_OFFSET) +#define FIOPAD_E59 (FPinIndex)FIOPAD_INDEX(FIOPAD_95_FUNC_OFFSET) +#define FIOPAD_J57 (FPinIndex)FIOPAD_INDEX(FIOPAD_96_FUNC_OFFSET) +#define FIOPAD_L59 (FPinIndex)FIOPAD_INDEX(FIOPAD_97_FUNC_OFFSET) +#define FIOPAD_N59 (FPinIndex)FIOPAD_INDEX(FIOPAD_98_FUNC_OFFSET) +#define FIOPAD_C57 (FPinIndex)FIOPAD_INDEX(FIOPAD_29_FUNC_OFFSET) +#define FIOPAD_E57 (FPinIndex)FIOPAD_INDEX(FIOPAD_30_FUNC_OFFSET) +#define FIOPAD_E31 (FPinIndex)FIOPAD_INDEX(FIOPAD_99_FUNC_OFFSET) +#define FIOPAD_G31 (FPinIndex)FIOPAD_INDEX(FIOPAD_100_FUNC_OFFSET) +#define FIOPAD_N41 (FPinIndex)FIOPAD_INDEX(FIOPAD_101_FUNC_OFFSET) +#define FIOPAD_N39 (FPinIndex)FIOPAD_INDEX(FIOPAD_102_FUNC_OFFSET) +#define FIOPAD_J33 (FPinIndex)FIOPAD_INDEX(FIOPAD_103_FUNC_OFFSET) +#define FIOPAD_N33 (FPinIndex)FIOPAD_INDEX(FIOPAD_104_FUNC_OFFSET) +#define FIOPAD_L33 (FPinIndex)FIOPAD_INDEX(FIOPAD_105_FUNC_OFFSET) +#define FIOPAD_N45 (FPinIndex)FIOPAD_INDEX(FIOPAD_106_FUNC_OFFSET) +#define FIOPAD_N43 (FPinIndex)FIOPAD_INDEX(FIOPAD_107_FUNC_OFFSET) +#define FIOPAD_L31 (FPinIndex)FIOPAD_INDEX(FIOPAD_108_FUNC_OFFSET) +#define FIOPAD_J31 (FPinIndex)FIOPAD_INDEX(FIOPAD_109_FUNC_OFFSET) +#define FIOPAD_J29 (FPinIndex)FIOPAD_INDEX(FIOPAD_110_FUNC_OFFSET) +#define FIOPAD_E29 (FPinIndex)FIOPAD_INDEX(FIOPAD_111_FUNC_OFFSET) +#define FIOPAD_G29 (FPinIndex)FIOPAD_INDEX(FIOPAD_112_FUNC_OFFSET) +#define FIOPAD_N27 (FPinIndex)FIOPAD_INDEX(FIOPAD_113_FUNC_OFFSET) +#define FIOPAD_L29 (FPinIndex)FIOPAD_INDEX(FIOPAD_114_FUNC_OFFSET) +#define FIOPAD_J37 (FPinIndex)FIOPAD_INDEX(FIOPAD_115_FUNC_OFFSET) +#define FIOPAD_J39 (FPinIndex)FIOPAD_INDEX(FIOPAD_116_FUNC_OFFSET) +#define FIOPAD_G41 (FPinIndex)FIOPAD_INDEX(FIOPAD_117_FUNC_OFFSET) +#define FIOPAD_E43 (FPinIndex)FIOPAD_INDEX(FIOPAD_118_FUNC_OFFSET) +#define FIOPAD_L43 (FPinIndex)FIOPAD_INDEX(FIOPAD_119_FUNC_OFFSET) +#define FIOPAD_C43 (FPinIndex)FIOPAD_INDEX(FIOPAD_120_FUNC_OFFSET) +#define FIOPAD_E41 (FPinIndex)FIOPAD_INDEX(FIOPAD_121_FUNC_OFFSET) +#define FIOPAD_L45 (FPinIndex)FIOPAD_INDEX(FIOPAD_122_FUNC_OFFSET) +#define FIOPAD_J43 (FPinIndex)FIOPAD_INDEX(FIOPAD_123_FUNC_OFFSET) +#define FIOPAD_J41 (FPinIndex)FIOPAD_INDEX(FIOPAD_124_FUNC_OFFSET) +#define FIOPAD_L39 (FPinIndex)FIOPAD_INDEX(FIOPAD_125_FUNC_OFFSET) +#define FIOPAD_E37 (FPinIndex)FIOPAD_INDEX(FIOPAD_126_FUNC_OFFSET) +#define FIOPAD_E35 (FPinIndex)FIOPAD_INDEX(FIOPAD_127_FUNC_OFFSET) +#define FIOPAD_G35 (FPinIndex)FIOPAD_INDEX(FIOPAD_128_FUNC_OFFSET) +#define FIOPAD_J35 (FPinIndex)FIOPAD_INDEX(FIOPAD_129_FUNC_OFFSET) +#define FIOPAD_L37 (FPinIndex)FIOPAD_INDEX(FIOPAD_130_FUNC_OFFSET) +#define FIOPAD_N35 (FPinIndex)FIOPAD_INDEX(FIOPAD_131_FUNC_OFFSET) +#define FIOPAD_R51 (FPinIndex)FIOPAD_INDEX(FIOPAD_132_FUNC_OFFSET) +#define FIOPAD_R49 (FPinIndex)FIOPAD_INDEX(FIOPAD_133_FUNC_OFFSET) +#define FIOPAD_N51 (FPinIndex)FIOPAD_INDEX(FIOPAD_134_FUNC_OFFSET) +#define FIOPAD_N55 (FPinIndex)FIOPAD_INDEX(FIOPAD_135_FUNC_OFFSET) +#define FIOPAD_L55 (FPinIndex)FIOPAD_INDEX(FIOPAD_136_FUNC_OFFSET) +#define FIOPAD_J55 (FPinIndex)FIOPAD_INDEX(FIOPAD_137_FUNC_OFFSET) +#define FIOPAD_J45 (FPinIndex)FIOPAD_INDEX(FIOPAD_138_FUNC_OFFSET) +#define FIOPAD_E47 (FPinIndex)FIOPAD_INDEX(FIOPAD_139_FUNC_OFFSET) +#define FIOPAD_G47 (FPinIndex)FIOPAD_INDEX(FIOPAD_140_FUNC_OFFSET) +#define FIOPAD_J47 (FPinIndex)FIOPAD_INDEX(FIOPAD_141_FUNC_OFFSET) +#define FIOPAD_J49 (FPinIndex)FIOPAD_INDEX(FIOPAD_142_FUNC_OFFSET) +#define FIOPAD_N49 (FPinIndex)FIOPAD_INDEX(FIOPAD_143_FUNC_OFFSET) +#define FIOPAD_L51 (FPinIndex)FIOPAD_INDEX(FIOPAD_144_FUNC_OFFSET) +#define FIOPAD_L49 (FPinIndex)FIOPAD_INDEX(FIOPAD_145_FUNC_OFFSET) +#define FIOPAD_N53 (FPinIndex)FIOPAD_INDEX(FIOPAD_146_FUNC_OFFSET) +#define FIOPAD_J53 (FPinIndex)FIOPAD_INDEX(FIOPAD_147_FUNC_OFFSET) + +/* register offset of iopad delay */ +#define FIOPAD_AJ55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_10_DELAY_OFFSET) +#define FIOPAD_AL55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_11_DELAY_OFFSET) +#define FIOPAD_AL53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_12_DELAY_OFFSET) +#define FIOPAD_AN51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_13_DELAY_OFFSET) +#define FIOPAD_AR51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_14_DELAY_OFFSET) +#define FIOPAD_AJ57_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_23_DELAY_OFFSET) +#define FIOPAD_AG59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_24_DELAY_OFFSET) +#define FIOPAD_AG57_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_25_DELAY_OFFSET) +#define FIOPAD_AE59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_26_DELAY_OFFSET) +#define FIOPAD_BA55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_32_DELAY_OFFSET) +#define FIOPAD_BA53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_33_DELAY_OFFSET) +#define FIOPAD_AR59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_34_DELAY_OFFSET) +#define FIOPAD_AU59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_35_DELAY_OFFSET) +#define FIOPAD_A45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_55_DELAY_OFFSET) +#define FIOPAD_C45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_56_DELAY_OFFSET) +#define FIOPAD_A47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_57_DELAY_OFFSET) +#define FIOPAD_A49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_58_DELAY_OFFSET) +#define FIOPAD_C49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_59_DELAY_OFFSET) +#define FIOPAD_A51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_60_DELAY_OFFSET) +#define FIOPAD_A33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_61_DELAY_OFFSET) +#define FIOPAD_C33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_62_DELAY_OFFSET) +#define FIOPAD_C31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_63_DELAY_OFFSET) +#define FIOPAD_A31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_64_DELAY_OFFSET) +#define FIOPAD_AJ53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_65_DELAY_OFFSET) +#define FIOPAD_AL49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_66_DELAY_OFFSET) +#define FIOPAD_AL47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_67_DELAY_OFFSET) +#define FIOPAD_AN49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_68_DELAY_OFFSET) +#define FIOPAD_AG51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_148_DELAY_OFFSET) +#define FIOPAD_AJ51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_69_DELAY_OFFSET) +#define FIOPAD_AG49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_70_DELAY_OFFSET) +#define FIOPAD_AE55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_71_DELAY_OFFSET) +#define FIOPAD_AE53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_72_DELAY_OFFSET) +#define FIOPAD_AG55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_73_DELAY_OFFSET) +#define FIOPAD_AJ49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_74_DELAY_OFFSET) +#define FIOPAD_AC55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_75_DELAY_OFFSET) +#define FIOPAD_AC53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_76_DELAY_OFFSET) +#define FIOPAD_AE51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_77_DELAY_OFFSET) +#define FIOPAD_W51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_78_DELAY_OFFSET) +#define FIOPAD_W53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_80_DELAY_OFFSET) +#define FIOPAD_U55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_81_DELAY_OFFSET) +#define FIOPAD_U53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_82_DELAY_OFFSET) +#define FIOPAD_AE49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_83_DELAY_OFFSET) +#define FIOPAD_AC49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_84_DELAY_OFFSET) +#define FIOPAD_AE47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_85_DELAY_OFFSET) +#define FIOPAD_AA47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_86_DELAY_OFFSET) +#define FIOPAD_AA49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_87_DELAY_OFFSET) +#define FIOPAD_W49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_88_DELAY_OFFSET) +#define FIOPAD_AA51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_89_DELAY_OFFSET) +#define FIOPAD_U49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_90_DELAY_OFFSET) +#define FIOPAD_J59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_92_DELAY_OFFSET) +#define FIOPAD_L57_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_93_DELAY_OFFSET) +#define FIOPAD_C59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_94_DELAY_OFFSET) +#define FIOPAD_E59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_95_DELAY_OFFSET) +#define FIOPAD_J57_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_96_DELAY_OFFSET) +#define FIOPAD_L59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_97_DELAY_OFFSET) +#define FIOPAD_N59_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_98_DELAY_OFFSET) +#define FIOPAD_E31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_99_DELAY_OFFSET) +#define FIOPAD_G31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_100_DELAY_OFFSET) +#define FIOPAD_N41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_101_DELAY_OFFSET) +#define FIOPAD_N39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_102_DELAY_OFFSET) +#define FIOPAD_J33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_103_DELAY_OFFSET) +#define FIOPAD_N33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_104_DELAY_OFFSET) +#define FIOPAD_L33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_105_DELAY_OFFSET) +#define FIOPAD_N45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_106_DELAY_OFFSET) +#define FIOPAD_N43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_107_DELAY_OFFSET) +#define FIOPAD_L31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_108_DELAY_OFFSET) +#define FIOPAD_J31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_109_DELAY_OFFSET) +#define FIOPAD_J29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_110_DELAY_OFFSET) +#define FIOPAD_E29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_111_DELAY_OFFSET) +#define FIOPAD_G29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_112_DELAY_OFFSET) +#define FIOPAD_J37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_115_DELAY_OFFSET) +#define FIOPAD_J39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_116_DELAY_OFFSET) +#define FIOPAD_G41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_117_DELAY_OFFSET) +#define FIOPAD_E43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_118_DELAY_OFFSET) +#define FIOPAD_L43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_119_DELAY_OFFSET) +#define FIOPAD_C43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_120_DELAY_OFFSET) +#define FIOPAD_E41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_121_DELAY_OFFSET) +#define FIOPAD_L45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_122_DELAY_OFFSET) +#define FIOPAD_J43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_123_DELAY_OFFSET) +#define FIOPAD_J41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_124_DELAY_OFFSET) +#define FIOPAD_L39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_125_DELAY_OFFSET) +#define FIOPAD_E37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_126_DELAY_OFFSET) +#define FIOPAD_E35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_127_DELAY_OFFSET) +#define FIOPAD_G35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_128_DELAY_OFFSET) +#define FIOPAD_L55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_136_DELAY_OFFSET) +#define FIOPAD_J55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_137_DELAY_OFFSET) +#define FIOPAD_J45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_138_DELAY_OFFSET) +#define FIOPAD_E47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_139_DELAY_OFFSET) +#define FIOPAD_G47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_140_DELAY_OFFSET) +#define FIOPAD_J47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_141_DELAY_OFFSET) +#define FIOPAD_J49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_142_DELAY_OFFSET) +#define FIOPAD_N49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_143_DELAY_OFFSET) +#define FIOPAD_L51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_144_DELAY_OFFSET) +#define FIOPAD_L49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_145_DELAY_OFFSET) +#define FIOPAD_N53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_146_DELAY_OFFSET) +#define FIOPAD_J53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_147_DELAY_OFFSET) + +/***************** Macros (Inline Functions) Definitions *********************/ + +/*****************************************************************************/ + + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/q/fiopad_config.c b/bsp/phytium/libraries/standalone/board/e2000/q/fiopad_config.c new file mode 100644 index 0000000000..b29a9e0a2b --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/q/fiopad_config.c @@ -0,0 +1,619 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fiopad_config.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for io-pad function definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021/11/5 init commit + * 1.1 zhugengyu 2022/3/21 adopt to lastest tech spec. + */ + +/***************************** Include Files *********************************/ +#include "fiopad.h" +#include "fparameters.h" +#include "fdebug.h" +#include "fpinctrl.h" +#include "fassert.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FIOPAD_DEBUG_TAG "FIOPAD-CFG" +#define FIOPAD_ERROR(format, ...) FT_DEBUG_PRINT_E(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_WARN(format, ...) FT_DEBUG_PRINT_W(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_INFO(format, ...) FT_DEBUG_PRINT_I(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) +#define FIOPAD_DEBUG(format, ...) FT_DEBUG_PRINT_D(FIOPAD_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ +/** + * @name: FIOPadSetSpimMux + * @msg: set iopad mux for spim + * @return {*} + * @param {u32} spim_id, instance id of spi + */ +void FIOPadSetSpimMux(u32 spim_id) +{ + if (FSPI0_ID == spim_id) + { + FIOPAD_INFO("%d-%d-%d-%d", FPinGetFunc(FIOPAD_W55), + FPinGetFunc(FIOPAD_W53), FPinGetFunc(FIOPAD_U55), + FPinGetFunc(FIOPAD_U53)); + FPinSetFunc(FIOPAD_W55, FPIN_FUNC2); /* sclk */ + FPinSetFunc(FIOPAD_W53, FPIN_FUNC2); /* txd */ + FPinSetFunc(FIOPAD_U55, FPIN_FUNC2); /* rxd */ + FPinSetFunc(FIOPAD_U53, FPIN_FUNC2); /* csn0 */ + FIOPAD_INFO("%d-%d-%d-%d", FPinGetFunc(FIOPAD_W55), + FPinGetFunc(FIOPAD_W53), FPinGetFunc(FIOPAD_U55), + FPinGetFunc(FIOPAD_U53)); + } + else if (FSPI1_ID == spim_id) + { + FIOPAD_INFO("%d-%d-%d-%d", FPinGetFunc(FIOPAD_N43), + FPinGetFunc(FIOPAD_L31), FPinGetFunc(FIOPAD_J31), + FPinGetFunc(FIOPAD_J29)); + FPinSetFunc(FIOPAD_N43, FPIN_FUNC4); /* sclk */ + FPinSetFunc(FIOPAD_L31, FPIN_FUNC4); /* txd */ + FPinSetFunc(FIOPAD_J31, FPIN_FUNC4); /* rxd */ + FPinSetFunc(FIOPAD_J29, FPIN_FUNC4); /* csn0 */ + FIOPAD_INFO("%d-%d-%d-%d", FPinGetFunc(FIOPAD_N43), + FPinGetFunc(FIOPAD_L31), FPinGetFunc(FIOPAD_J31), + FPinGetFunc(FIOPAD_J29)); + } + else if (FSPI2_ID == spim_id) + { + FPinSetFunc(FIOPAD_A33, FPIN_FUNC0); /* sclk */ + FPinSetFunc(FIOPAD_C33, FPIN_FUNC0); /* txd */ + FPinSetFunc(FIOPAD_C31, FPIN_FUNC0); /* rxd */ + FPinSetFunc(FIOPAD_A31, FPIN_FUNC0); /* csn0 */ + } + else if (FSPI3_ID == spim_id) + { + FPinSetFunc(FIOPAD_AC55, FPIN_FUNC2); /* sclk */ + FPinSetFunc(FIOPAD_AC53, FPIN_FUNC2); /* txd */ + FPinSetFunc(FIOPAD_AE51, FPIN_FUNC2); /* rxd */ + FPinSetFunc(FIOPAD_W51, FPIN_FUNC2); /* csn0 */ + } +} + +/** + * @name: FIOPadSetGpioMux + * @msg: set iopad mux for gpio + * @return {*} + * @param {u32} gpio_id, instance id of gpio + * @param {u32} pin_id, index of pin + */ +void FIOPadSetGpioMux(u32 gpio_id, u32 pin_id) +{ + if (FGPIO_ID_2 == gpio_id) + { + switch (pin_id) + { + case 11: /* gpio 2-a-11 */ + FPinSetFunc(FIOPAD_N49, FPIN_FUNC0); + break; + case 12: /* gpio 2-a-12 */ + FPinSetFunc(FIOPAD_L51, FPIN_FUNC0); + break; + case 13: /* gpio 2-a-13 */ + FPinSetFunc(FIOPAD_L49, FPIN_FUNC0); + break; + case 14: /* gpio 2-a-14 */ + FPinSetFunc(FIOPAD_N53, FPIN_FUNC0); + break; + case 15: /* gpio 2-a-15 */ + FPinSetFunc(FIOPAD_J53, FPIN_FUNC0); + break; + } + } + else if (FGPIO_ID_3 == gpio_id) + { + switch (pin_id) + { + case 3: /* gpio 3-a-3 */ + FPinSetFunc(FIOPAD_A33, FPIN_FUNC6); + break; + case 4: /* gpio 3-a-4 */ + FPinSetFunc(FIOPAD_C33, FPIN_FUNC6); + break; + case 5: /* gpio 3-a-5 */ + FPinSetFunc(FIOPAD_C31, FPIN_FUNC6); + break; + case 6: /* gpio 3-a-6 */ + FPinSetFunc(FIOPAD_A31, FPIN_FUNC6); + break; + default: + break; + } + } + else if (FGPIO_ID_4 == gpio_id) + { + switch (pin_id) + { + case 5: /* gpio 4-a-5 */ + FPinSetFunc(FIOPAD_W51, FPIN_FUNC6); + break; + case 9: /* gpio 4-a-9 */ + FPinSetFunc(FIOPAD_U53, FPIN_FUNC6); + break; + default: + break; + } + } +} + + +/** + * @name: FIOPadSetCanMux + * @msg: set iopad mux for can + * @return {*} + * @param {u32} can_id, instance id of can + */ +void FIOPadSetCanMux(u32 can_id) +{ + if (can_id == FCAN_INSTANCE_0) + { + /* mio0 */ + FPinSetFunc(FIOPAD_A41, FPIN_FUNC0); /* can0-tx: func 0 */ + FPinSetFunc(FIOPAD_A43, FPIN_FUNC0); /* can0-rx: func 0 */ + } + else if (can_id == FCAN_INSTANCE_1) + { + /* mio1 */ + FPinSetFunc(FIOPAD_A45, FPIN_FUNC0); /* can1-tx: func 0 */ + FPinSetFunc(FIOPAD_C45, FPIN_FUNC0); /* can1-rx: func 0 */ + } + else + { + FIOPAD_ERROR("can id is error.\r\n"); + } +} + +/** + * @name: FIOPadSetQspiMux + * @msg: set iopad mux for qspi + * @return {*} + * @param {u32} qspi_id, id of qspi instance + * @param {u32} cs_id, id of qspi cs + */ +void FIOPadSetQspiMux(u32 qspi_id, u32 cs_id) +{ + + if (qspi_id == FQSPI_INSTANCE_0) + { + /* add sck, io0-io3 iopad multiplex */ + } + + if (cs_id == FQSPI_CS_0) + { + FPinSetFunc(FIOPAD_AR55, FPIN_FUNC0); + } + else if (cs_id == FQSPI_CS_1) + { + FPinSetFunc(FIOPAD_AR49, FPIN_FUNC0); + } + else if (cs_id == FQSPI_CS_2) + { + FPinSetFunc(FIOPAD_C37, FPIN_FUNC5); + } + else if (cs_id == FQSPI_CS_3) + { + FPinSetFunc(FIOPAD_A37, FPIN_FUNC5); + } + else + { + FIOPAD_ERROR("can id is error.\r\n"); + } +} + +/** + * @name: FIOPadSetPwmMux + * @msg: set iopad mux for pwm + * @return {*} + * @param {u32} pwm_id, id of pwm instance + * @param {u32} pwm_channel, channel of pwm instance + */ +void FIOPadSetPwmMux(u32 pwm_id, u32 pwm_channel) +{ + FASSERT(pwm_id < FPWM_INSTANCE_NUM); + FASSERT(pwm_channel < FPWM_CHANNEL_NUM); + + switch (pwm_id) + { + case FPWM_INSTANCE_0: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_AL59, FPIN_FUNC1); /* PWM0_OUT: func 1 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_AJ57, FPIN_FUNC1); /* PWM1_OUT: func 1 */ + } + break; + + case FPWM_INSTANCE_1: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_AG57, FPIN_FUNC1); /* PWM2_OUT: func 1 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_AC59, FPIN_FUNC1); /* PWM3_OUT: func 1 */ + } + break; + + case FPWM_INSTANCE_2: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_BA55, FPIN_FUNC1); /* PWM4_OUT: func 1 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_C39, FPIN_FUNC2); /* PWM5_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_3: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_A37, FPIN_FUNC2); /* PWM6_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_A43, FPIN_FUNC2); /* PWM7_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_4: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_C45, FPIN_FUNC2); /* PWM8_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_A49, FPIN_FUNC2); /* PWM9_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_5: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_A51, FPIN_FUNC2); /* PWM10_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_C33, FPIN_FUNC2); /* PWM11_OUT: func 2 */ + } + break; + + case FPWM_INSTANCE_6: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_A31, FPIN_FUNC2); /* PWM12_OUT: func 2 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_J39, FPIN_FUNC3); /* PWM13_OUT: func 3 */ + } + break; + + case FPWM_INSTANCE_7: + if (pwm_channel == 0) + { + FPinSetFunc(FIOPAD_E43, FPIN_FUNC3); /* PWM14_OUT: func 3 */ + } + if (pwm_channel == 1) + { + FPinSetFunc(FIOPAD_C43, FPIN_FUNC3); /* PWM15_OUT: func 3 */ + } + break; + + default: + FIOPAD_ERROR("pwm id is error.\r\n"); + break; + } +} + + +/** + * @name: FIOPadSetAdcMux + * @msg: set iopad mux for adc + * @return {*} + * @param {u32} adc_id, id of adc instance + * @param {u32} adc_channel, id of adc channel + */ +void FIOPadSetAdcMux(u32 adc_id, u32 adc_channel) +{ + if (adc_id == FADC_INSTANCE_0) + { + switch (adc_channel) + { + case FADC_CHANNEL_0: + FPinSetFunc(FIOPAD_R51, FPIN_FUNC7); /* adc0-0: func 7 */ + break; + case FADC_CHANNEL_1: + FPinSetFunc(FIOPAD_R49, FPIN_FUNC7); /* adc0-1: func 7 */ + break; + case FADC_CHANNEL_2: + FPinSetFunc(FIOPAD_N51, FPIN_FUNC7); /* adc0-2: func 7 */ + break; + case FADC_CHANNEL_3: + FPinSetFunc(FIOPAD_N55, FPIN_FUNC7); /* adc0-3: func 7 */ + break; + case FADC_CHANNEL_4: + FPinSetFunc(FIOPAD_L55, FPIN_FUNC7); /* adc0-4: func 7 */ + break; + case FADC_CHANNEL_5: + FPinSetFunc(FIOPAD_J55, FPIN_FUNC7); /* adc0-5: func 7 */ + break; + case FADC_CHANNEL_6: + FPinSetFunc(FIOPAD_J45, FPIN_FUNC7); /* adc0-6: func 7 */ + break; + case FADC_CHANNEL_7: + FPinSetFunc(FIOPAD_E47, FPIN_FUNC7); /* adc0-7: func 7 */ + break; + default: + FIOPAD_ERROR("adc %d channel %d is error.\r\n", adc_id, adc_channel); + break; + } + } + else if (adc_id == FADC_INSTANCE_1) + { + switch (adc_channel) + { + case FADC_CHANNEL_0: + FPinSetFunc(FIOPAD_G47, FPIN_FUNC7); /* adc1-0: func 7 */ + break; + case FADC_CHANNEL_1: + FPinSetFunc(FIOPAD_J47, FPIN_FUNC7); /* adc1-1: func 7 */ + break; + case FADC_CHANNEL_2: + FPinSetFunc(FIOPAD_J49, FPIN_FUNC7); /* adc1-2: func 7 */ + break; + case FADC_CHANNEL_3: + FPinSetFunc(FIOPAD_N49, FPIN_FUNC7); /* adc1-3: func 7 */ + break; + case FADC_CHANNEL_4: + FPinSetFunc(FIOPAD_L51, FPIN_FUNC7); /* adc1-4: func 7 */ + break; + case FADC_CHANNEL_5: + FPinSetFunc(FIOPAD_L49, FPIN_FUNC7); /* adc1-5: func 7 */ + break; + case FADC_CHANNEL_6: + FPinSetFunc(FIOPAD_N53, FPIN_FUNC7); /* adc1-6: func 7 */ + break; + case FADC_CHANNEL_7: + FPinSetFunc(FIOPAD_J53, FPIN_FUNC7); /* adc1-7: func 7 */ + break; + default: + FIOPAD_ERROR("adc %d channel %d is error.\r\n", adc_id, adc_channel); + break; + } + } + else + { + FIOPAD_ERROR("adc %d channel %d is error.\r\n", adc_id, adc_channel); + } +} + +/** + * @name: FIOPadSetMioMux + * @msg: set iopad mux for mio + * @return {*} + * @param {u32} mio_id, instance id of i2c + */ +void FIOPadSetMioMux(u32 mio_id) +{ + switch (mio_id) + { + case MIO_INSTANCE_0: + { + FPinSetFunc(FIOPAD_A41, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A43, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_1: + { + FPinSetFunc(FIOPAD_A45, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_C45, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_2: + { + FPinSetFunc(FIOPAD_A47, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A49, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_3: + { + FPinSetFunc(FIOPAD_BA55, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_BA53, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_4: + { + FPinSetFunc(FIOPAD_R59, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U59, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_5: + { + FPinSetFunc(FIOPAD_W49, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U57, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_6: + { + FPinSetFunc(FIOPAD_AA57, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_AA59, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_7: + { + FPinSetFunc(FIOPAD_A39, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_C39, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_8: + { + FPinSetFunc(FIOPAD_AA49, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_W49, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_9: + { + FPinSetFunc(FIOPAD_AA51, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U49, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_10: + { + FPinSetFunc(FIOPAD_C49, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A51, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_11: + { + FPinSetFunc(FIOPAD_N27, FPIN_FUNC3); /* scl */ + FPinSetFunc(FIOPAD_L29, FPIN_FUNC3); /* sda */ + } + break; + case MIO_INSTANCE_12: + { + FPinSetFunc(FIOPAD_E41, FPIN_FUNC3); /* scl */ + FPinSetFunc(FIOPAD_L45, FPIN_FUNC3); /* sda */ + } + break; + case MIO_INSTANCE_13: + { + FPinSetFunc(FIOPAD_J49, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_N49, FPIN_FUNC6); /* sda */ + } + break; + case MIO_INSTANCE_14: + { + FPinSetFunc(FIOPAD_L51, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_L49, FPIN_FUNC6); /* sda */ + } + break; + case MIO_INSTANCE_15: + { + FPinSetFunc(FIOPAD_N53, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_J53, FPIN_FUNC6); /* sda */ + } + break; + default: + break; + } +} + +/** + * @name: FIOPadSetTachoMux + * @msg: set iopad mux for pwm_in + * @return {*} + * @param {u32} pwm_in_id, instance id of tacho + */ +void FIOPadSetTachoMux(u32 pwm_in_id) +{ + switch (pwm_in_id) + { + case TACHO_INSTANCE_0: + FPinSetFunc(FIOPAD_AN57, FPIN_FUNC1); + break; + case TACHO_INSTANCE_1: + FPinSetFunc(FIOPAD_AJ59, FPIN_FUNC1); + break; + case TACHO_INSTANCE_2: + FPinSetFunc(FIOPAD_AG59, FPIN_FUNC1); + break; + case TACHO_INSTANCE_3: + FPinSetFunc(FIOPAD_AE59, FPIN_FUNC1); + break; + case TACHO_INSTANCE_4: + FPinSetFunc(FIOPAD_AC57, FPIN_FUNC1); + break; + case TACHO_INSTANCE_5: + FPinSetFunc(FIOPAD_BA53, FPIN_FUNC1); + break; + case TACHO_INSTANCE_6: + FPinSetFunc(FIOPAD_C37, FPIN_FUNC2); + break; + case TACHO_INSTANCE_7: + FPinSetFunc(FIOPAD_A41, FPIN_FUNC2); + break; + case TACHO_INSTANCE_8: + FPinSetFunc(FIOPAD_A45, FPIN_FUNC2); + break; + case TACHO_INSTANCE_9: + FPinSetFunc(FIOPAD_A47, FPIN_FUNC2); + break; + case TACHO_INSTANCE_10: + FPinSetFunc(FIOPAD_C49, FPIN_FUNC2); + break; + case TACHO_INSTANCE_11: + FPinSetFunc(FIOPAD_A33, FPIN_FUNC2); + break; + case TACHO_INSTANCE_12: + FPinSetFunc(FIOPAD_C31, FPIN_FUNC2); + break; + case TACHO_INSTANCE_13: + FPinSetFunc(FIOPAD_AA49, FPIN_FUNC2); + break; + case TACHO_INSTANCE_14: + FPinSetFunc(FIOPAD_AA51, FPIN_FUNC2); + break; + case TACHO_INSTANCE_15: + FPinSetFunc(FIOPAD_G59, FPIN_FUNC2); + break; + default: + break; + } +} + +/** + * @name: FIOPadSetUartMux + * @msg: set iopad mux for uart + * @return {*} + * @param {u32} uart_id, instance id of uart + */ +void FIOPadSetUartMux(u32 uart_id) +{ + switch (uart_id) + { + case FUART0_ID: + FPinSetFunc(FIOPAD_J37, FPIN_FUNC4); + FPinSetFunc(FIOPAD_J39, FPIN_FUNC4); + break; + case FUART1_ID: + FPinSetFunc(FIOPAD_AW51, FPIN_FUNC0); + FPinSetFunc(FIOPAD_AU51, FPIN_FUNC0); + break; + case FUART2_ID: + FPinSetFunc(FIOPAD_A47, FPIN_FUNC0); + FPinSetFunc(FIOPAD_A49, FPIN_FUNC0); + break; + case FUART3_ID: + FPinSetFunc(FIOPAD_L37, FPIN_FUNC2); + FPinSetFunc(FIOPAD_N35, FPIN_FUNC2); + break; + default: + break; + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/q/fparameters.h b/bsp/phytium/libraries/standalone/board/e2000/q/fparameters.h new file mode 100644 index 0000000000..9d7a5691e8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/q/fparameters.h @@ -0,0 +1,50 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fparameters.h + * Date: 2022-02-11 13:33:28 + * LastEditTime: 2022-02-17 18:00:50 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BOARD_E2000Q_PARAMTERERS_H +#define BOARD_E2000Q_PARAMTERERS_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fparameters_comm.h" + +/************************** Constant Definitions *****************************/ +#define CORE0_AFF 0x000U +#define CORE1_AFF 0x100U +#define CORE2_AFF 0x200U +#define CORE3_AFF 0x201U + +#define FT_CPUS_NR 4U +/*****************************************************************************/ + + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/s/fiopad.h b/bsp/phytium/libraries/standalone/board/e2000/s/fiopad.h new file mode 100644 index 0000000000..d6588ad99e --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/s/fiopad.h @@ -0,0 +1,270 @@ + +#ifndef BOARD_E2000Q_FIOPAD_H +#define BOARD_E2000Q_FIOPAD_H + +#ifdef __cplusplus +extern "C" +{ +#endif + + +/***************************** Include Files *********************************/ +#include "fiopad_comm.h" + +/************************** Constant Definitions *****************************/ +/* register offset of iopad function / pull / driver strength */ +#define FIOPAD_AN55 (FPinIndex)FIOPAD_INDEX(FIOPAD_0_FUNC_OFFSET) +#define FIOPAD_AW43 (FPinIndex)FIOPAD_INDEX(FIOPAD_2_FUNC_OFFSET) +#define FIOPAD_AR51 (FPinIndex)FIOPAD_INDEX(FIOPAD_9_FUNC_OFFSET) +#define FIOPAD_AJ51 (FPinIndex)FIOPAD_INDEX(FIOPAD_10_FUNC_OFFSET) +#define FIOPAD_AL51 (FPinIndex)FIOPAD_INDEX(FIOPAD_11_FUNC_OFFSET) +#define FIOPAD_AL49 (FPinIndex)FIOPAD_INDEX(FIOPAD_12_FUNC_OFFSET) +#define FIOPAD_AN47 (FPinIndex)FIOPAD_INDEX(FIOPAD_13_FUNC_OFFSET) +#define FIOPAD_AR47 (FPinIndex)FIOPAD_INDEX(FIOPAD_14_FUNC_OFFSET) +#define FIOPAD_BA53 (FPinIndex)FIOPAD_INDEX(FIOPAD_15_FUNC_OFFSET) +#define FIOPAD_BA55 (FPinIndex)FIOPAD_INDEX(FIOPAD_16_FUNC_OFFSET) +#define FIOPAD_AW53 (FPinIndex)FIOPAD_INDEX(FIOPAD_17_FUNC_OFFSET) +#define FIOPAD_AW55 (FPinIndex)FIOPAD_INDEX(FIOPAD_18_FUNC_OFFSET) +#define FIOPAD_AU51 (FPinIndex)FIOPAD_INDEX(FIOPAD_19_FUNC_OFFSET) +#define FIOPAD_AN53 (FPinIndex)FIOPAD_INDEX(FIOPAD_20_FUNC_OFFSET) +#define FIOPAD_AL55 (FPinIndex)FIOPAD_INDEX(FIOPAD_21_FUNC_OFFSET) +#define FIOPAD_AJ55 (FPinIndex)FIOPAD_INDEX(FIOPAD_22_FUNC_OFFSET) +#define FIOPAD_AJ53 (FPinIndex)FIOPAD_INDEX(FIOPAD_23_FUNC_OFFSET) +#define FIOPAD_AG55 (FPinIndex)FIOPAD_INDEX(FIOPAD_24_FUNC_OFFSET) +#define FIOPAD_AG53 (FPinIndex)FIOPAD_INDEX(FIOPAD_25_FUNC_OFFSET) +#define FIOPAD_AE55 (FPinIndex)FIOPAD_INDEX(FIOPAD_26_FUNC_OFFSET) +#define FIOPAD_AC55 (FPinIndex)FIOPAD_INDEX(FIOPAD_27_FUNC_OFFSET) +#define FIOPAD_AC53 (FPinIndex)FIOPAD_INDEX(FIOPAD_28_FUNC_OFFSET) +#define FIOPAD_AR45 (FPinIndex)FIOPAD_INDEX(FIOPAD_31_FUNC_OFFSET) +#define FIOPAD_BA51 (FPinIndex)FIOPAD_INDEX(FIOPAD_32_FUNC_OFFSET) +#define FIOPAD_BA49 (FPinIndex)FIOPAD_INDEX(FIOPAD_33_FUNC_OFFSET) +#define FIOPAD_AR55 (FPinIndex)FIOPAD_INDEX(FIOPAD_34_FUNC_OFFSET) +#define FIOPAD_AU55 (FPinIndex)FIOPAD_INDEX(FIOPAD_35_FUNC_OFFSET) +#define FIOPAD_AR53 (FPinIndex)FIOPAD_INDEX(FIOPAD_36_FUNC_OFFSET) +#define FIOPAD_BA45 (FPinIndex)FIOPAD_INDEX(FIOPAD_37_FUNC_OFFSET) +#define FIOPAD_AW51 (FPinIndex)FIOPAD_INDEX(FIOPAD_38_FUNC_OFFSET) +#define FIOPAD_A31 (FPinIndex)FIOPAD_INDEX(FIOPAD_39_FUNC_OFFSET) +#define FIOPAD_R53 (FPinIndex)FIOPAD_INDEX(FIOPAD_40_FUNC_OFFSET) +#define FIOPAD_R55 (FPinIndex)FIOPAD_INDEX(FIOPAD_41_FUNC_OFFSET) +#define FIOPAD_U55 (FPinIndex)FIOPAD_INDEX(FIOPAD_42_FUNC_OFFSET) +#define FIOPAD_W55 (FPinIndex)FIOPAD_INDEX(FIOPAD_43_FUNC_OFFSET) +#define FIOPAD_U53 (FPinIndex)FIOPAD_INDEX(FIOPAD_44_FUNC_OFFSET) +#define FIOPAD_AA53 (FPinIndex)FIOPAD_INDEX(FIOPAD_45_FUNC_OFFSET) +#define FIOPAD_AA55 (FPinIndex)FIOPAD_INDEX(FIOPAD_46_FUNC_OFFSET) +#define FIOPAD_AW47 (FPinIndex)FIOPAD_INDEX(FIOPAD_47_FUNC_OFFSET) +#define FIOPAD_AU47 (FPinIndex)FIOPAD_INDEX(FIOPAD_48_FUNC_OFFSET) +#define FIOPAD_A35 (FPinIndex)FIOPAD_INDEX(FIOPAD_49_FUNC_OFFSET) +#define FIOPAD_C35 (FPinIndex)FIOPAD_INDEX(FIOPAD_50_FUNC_OFFSET) +#define FIOPAD_C33 (FPinIndex)FIOPAD_INDEX(FIOPAD_51_FUNC_OFFSET) +#define FIOPAD_A33 (FPinIndex)FIOPAD_INDEX(FIOPAD_52_FUNC_OFFSET) +#define FIOPAD_A37 (FPinIndex)FIOPAD_INDEX(FIOPAD_53_FUNC_OFFSET) +#define FIOPAD_A39 (FPinIndex)FIOPAD_INDEX(FIOPAD_54_FUNC_OFFSET) +#define FIOPAD_A41 (FPinIndex)FIOPAD_INDEX(FIOPAD_55_FUNC_OFFSET) +#define FIOPAD_C41 (FPinIndex)FIOPAD_INDEX(FIOPAD_56_FUNC_OFFSET) +#define FIOPAD_A43 (FPinIndex)FIOPAD_INDEX(FIOPAD_57_FUNC_OFFSET) +#define FIOPAD_A45 (FPinIndex)FIOPAD_INDEX(FIOPAD_58_FUNC_OFFSET) +#define FIOPAD_C45 (FPinIndex)FIOPAD_INDEX(FIOPAD_59_FUNC_OFFSET) +#define FIOPAD_A47 (FPinIndex)FIOPAD_INDEX(FIOPAD_60_FUNC_OFFSET) +#define FIOPAD_A29 (FPinIndex)FIOPAD_INDEX(FIOPAD_61_FUNC_OFFSET) +#define FIOPAD_C29 (FPinIndex)FIOPAD_INDEX(FIOPAD_62_FUNC_OFFSET) +#define FIOPAD_C27 (FPinIndex)FIOPAD_INDEX(FIOPAD_63_FUNC_OFFSET) +#define FIOPAD_A27 (FPinIndex)FIOPAD_INDEX(FIOPAD_64_FUNC_OFFSET) +#define FIOPAD_AJ49 (FPinIndex)FIOPAD_INDEX(FIOPAD_65_FUNC_OFFSET) +#define FIOPAD_AL45 (FPinIndex)FIOPAD_INDEX(FIOPAD_66_FUNC_OFFSET) +#define FIOPAD_AL43 (FPinIndex)FIOPAD_INDEX(FIOPAD_67_FUNC_OFFSET) +#define FIOPAD_AN45 (FPinIndex)FIOPAD_INDEX(FIOPAD_68_FUNC_OFFSET) +#define FIOPAD_AG47 (FPinIndex)FIOPAD_INDEX(FIOPAD_148_FUNC_OFFSET) +#define FIOPAD_AJ47 (FPinIndex)FIOPAD_INDEX(FIOPAD_69_FUNC_OFFSET) +#define FIOPAD_AG45 (FPinIndex)FIOPAD_INDEX(FIOPAD_70_FUNC_OFFSET) +#define FIOPAD_AE51 (FPinIndex)FIOPAD_INDEX(FIOPAD_71_FUNC_OFFSET) +#define FIOPAD_AE49 (FPinIndex)FIOPAD_INDEX(FIOPAD_72_FUNC_OFFSET) +#define FIOPAD_AG51 (FPinIndex)FIOPAD_INDEX(FIOPAD_73_FUNC_OFFSET) +#define FIOPAD_AJ45 (FPinIndex)FIOPAD_INDEX(FIOPAD_74_FUNC_OFFSET) +#define FIOPAD_AC51 (FPinIndex)FIOPAD_INDEX(FIOPAD_75_FUNC_OFFSET) +#define FIOPAD_AC49 (FPinIndex)FIOPAD_INDEX(FIOPAD_76_FUNC_OFFSET) +#define FIOPAD_AE47 (FPinIndex)FIOPAD_INDEX(FIOPAD_77_FUNC_OFFSET) +#define FIOPAD_W47 (FPinIndex)FIOPAD_INDEX(FIOPAD_78_FUNC_OFFSET) +#define FIOPAD_W51 (FPinIndex)FIOPAD_INDEX(FIOPAD_79_FUNC_OFFSET) +#define FIOPAD_W49 (FPinIndex)FIOPAD_INDEX(FIOPAD_80_FUNC_OFFSET) +#define FIOPAD_U51 (FPinIndex)FIOPAD_INDEX(FIOPAD_81_FUNC_OFFSET) +#define FIOPAD_U49 (FPinIndex)FIOPAD_INDEX(FIOPAD_82_FUNC_OFFSET) +#define FIOPAD_AE45 (FPinIndex)FIOPAD_INDEX(FIOPAD_83_FUNC_OFFSET) +#define FIOPAD_AC45 (FPinIndex)FIOPAD_INDEX(FIOPAD_84_FUNC_OFFSET) +#define FIOPAD_AE43 (FPinIndex)FIOPAD_INDEX(FIOPAD_85_FUNC_OFFSET) +#define FIOPAD_AA43 (FPinIndex)FIOPAD_INDEX(FIOPAD_86_FUNC_OFFSET) +#define FIOPAD_AA45 (FPinIndex)FIOPAD_INDEX(FIOPAD_87_FUNC_OFFSET) +#define FIOPAD_W45 (FPinIndex)FIOPAD_INDEX(FIOPAD_88_FUNC_OFFSET) +#define FIOPAD_AA47 (FPinIndex)FIOPAD_INDEX(FIOPAD_89_FUNC_OFFSET) +#define FIOPAD_U45 (FPinIndex)FIOPAD_INDEX(FIOPAD_90_FUNC_OFFSET) +#define FIOPAD_G55 (FPinIndex)FIOPAD_INDEX(FIOPAD_91_FUNC_OFFSET) +#define FIOPAD_J55 (FPinIndex)FIOPAD_INDEX(FIOPAD_92_FUNC_OFFSET) +#define FIOPAD_L53 (FPinIndex)FIOPAD_INDEX(FIOPAD_93_FUNC_OFFSET) +#define FIOPAD_C55 (FPinIndex)FIOPAD_INDEX(FIOPAD_94_FUNC_OFFSET) +#define FIOPAD_E55 (FPinIndex)FIOPAD_INDEX(FIOPAD_95_FUNC_OFFSET) +#define FIOPAD_J53 (FPinIndex)FIOPAD_INDEX(FIOPAD_96_FUNC_OFFSET) +#define FIOPAD_L55 (FPinIndex)FIOPAD_INDEX(FIOPAD_97_FUNC_OFFSET) +#define FIOPAD_N55 (FPinIndex)FIOPAD_INDEX(FIOPAD_98_FUNC_OFFSET) +#define FIOPAD_C53 (FPinIndex)FIOPAD_INDEX(FIOPAD_29_FUNC_OFFSET) +#define FIOPAD_E53 (FPinIndex)FIOPAD_INDEX(FIOPAD_30_FUNC_OFFSET) +#define FIOPAD_E27 (FPinIndex)FIOPAD_INDEX(FIOPAD_99_FUNC_OFFSET) +#define FIOPAD_G27 (FPinIndex)FIOPAD_INDEX(FIOPAD_100_FUNC_OFFSET) +#define FIOPAD_N37 (FPinIndex)FIOPAD_INDEX(FIOPAD_101_FUNC_OFFSET) +#define FIOPAD_N35 (FPinIndex)FIOPAD_INDEX(FIOPAD_102_FUNC_OFFSET) +#define FIOPAD_J29 (FPinIndex)FIOPAD_INDEX(FIOPAD_103_FUNC_OFFSET) +#define FIOPAD_N29 (FPinIndex)FIOPAD_INDEX(FIOPAD_104_FUNC_OFFSET) +#define FIOPAD_L29 (FPinIndex)FIOPAD_INDEX(FIOPAD_105_FUNC_OFFSET) +#define FIOPAD_N41 (FPinIndex)FIOPAD_INDEX(FIOPAD_106_FUNC_OFFSET) +#define FIOPAD_N39 (FPinIndex)FIOPAD_INDEX(FIOPAD_107_FUNC_OFFSET) +#define FIOPAD_L27 (FPinIndex)FIOPAD_INDEX(FIOPAD_108_FUNC_OFFSET) +#define FIOPAD_J27 (FPinIndex)FIOPAD_INDEX(FIOPAD_109_FUNC_OFFSET) +#define FIOPAD_J25 (FPinIndex)FIOPAD_INDEX(FIOPAD_110_FUNC_OFFSET) +#define FIOPAD_E25 (FPinIndex)FIOPAD_INDEX(FIOPAD_111_FUNC_OFFSET) +#define FIOPAD_G25 (FPinIndex)FIOPAD_INDEX(FIOPAD_112_FUNC_OFFSET) +#define FIOPAD_N23 (FPinIndex)FIOPAD_INDEX(FIOPAD_113_FUNC_OFFSET) +#define FIOPAD_L25 (FPinIndex)FIOPAD_INDEX(FIOPAD_114_FUNC_OFFSET) +#define FIOPAD_J33 (FPinIndex)FIOPAD_INDEX(FIOPAD_115_FUNC_OFFSET) +#define FIOPAD_J35 (FPinIndex)FIOPAD_INDEX(FIOPAD_116_FUNC_OFFSET) +#define FIOPAD_G37 (FPinIndex)FIOPAD_INDEX(FIOPAD_117_FUNC_OFFSET) +#define FIOPAD_E39 (FPinIndex)FIOPAD_INDEX(FIOPAD_118_FUNC_OFFSET) +#define FIOPAD_L39 (FPinIndex)FIOPAD_INDEX(FIOPAD_119_FUNC_OFFSET) +#define FIOPAD_C39 (FPinIndex)FIOPAD_INDEX(FIOPAD_120_FUNC_OFFSET) +#define FIOPAD_E37 (FPinIndex)FIOPAD_INDEX(FIOPAD_121_FUNC_OFFSET) +#define FIOPAD_L41 (FPinIndex)FIOPAD_INDEX(FIOPAD_122_FUNC_OFFSET) +#define FIOPAD_J39 (FPinIndex)FIOPAD_INDEX(FIOPAD_123_FUNC_OFFSET) +#define FIOPAD_J37 (FPinIndex)FIOPAD_INDEX(FIOPAD_124_FUNC_OFFSET) +#define FIOPAD_L35 (FPinIndex)FIOPAD_INDEX(FIOPAD_125_FUNC_OFFSET) +#define FIOPAD_E33 (FPinIndex)FIOPAD_INDEX(FIOPAD_126_FUNC_OFFSET) +#define FIOPAD_E31 (FPinIndex)FIOPAD_INDEX(FIOPAD_127_FUNC_OFFSET) +#define FIOPAD_G31 (FPinIndex)FIOPAD_INDEX(FIOPAD_128_FUNC_OFFSET) +#define FIOPAD_J31 (FPinIndex)FIOPAD_INDEX(FIOPAD_129_FUNC_OFFSET) +#define FIOPAD_L33 (FPinIndex)FIOPAD_INDEX(FIOPAD_130_FUNC_OFFSET) +#define FIOPAD_N31 (FPinIndex)FIOPAD_INDEX(FIOPAD_131_FUNC_OFFSET) +#define FIOPAD_R47 (FPinIndex)FIOPAD_INDEX(FIOPAD_132_FUNC_OFFSET) +#define FIOPAD_R45 (FPinIndex)FIOPAD_INDEX(FIOPAD_133_FUNC_OFFSET) +#define FIOPAD_N47 (FPinIndex)FIOPAD_INDEX(FIOPAD_134_FUNC_OFFSET) +#define FIOPAD_N51 (FPinIndex)FIOPAD_INDEX(FIOPAD_135_FUNC_OFFSET) +#define FIOPAD_L51 (FPinIndex)FIOPAD_INDEX(FIOPAD_136_FUNC_OFFSET) +#define FIOPAD_J51 (FPinIndex)FIOPAD_INDEX(FIOPAD_137_FUNC_OFFSET) +#define FIOPAD_J41 (FPinIndex)FIOPAD_INDEX(FIOPAD_138_FUNC_OFFSET) +#define FIOPAD_E43 (FPinIndex)FIOPAD_INDEX(FIOPAD_139_FUNC_OFFSET) +#define FIOPAD_G43 (FPinIndex)FIOPAD_INDEX(FIOPAD_140_FUNC_OFFSET) +#define FIOPAD_J43 (FPinIndex)FIOPAD_INDEX(FIOPAD_141_FUNC_OFFSET) +#define FIOPAD_J45 (FPinIndex)FIOPAD_INDEX(FIOPAD_142_FUNC_OFFSET) +#define FIOPAD_N45 (FPinIndex)FIOPAD_INDEX(FIOPAD_143_FUNC_OFFSET) +#define FIOPAD_L47 (FPinIndex)FIOPAD_INDEX(FIOPAD_144_FUNC_OFFSET) +#define FIOPAD_L45 (FPinIndex)FIOPAD_INDEX(FIOPAD_145_FUNC_OFFSET) +#define FIOPAD_N49 (FPinIndex)FIOPAD_INDEX(FIOPAD_146_FUNC_OFFSET) +#define FIOPAD_J49 (FPinIndex)FIOPAD_INDEX(FIOPAD_147_FUNC_OFFSET) + +/* register offset of iopad delay */ +#define FIOPAD_AJ51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_10_DELAY_OFFSET) +#define FIOPAD_AL51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_11_DELAY_OFFSET) +#define FIOPAD_AL49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_12_DELAY_OFFSET) +#define FIOPAD_AN47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_13_DELAY_OFFSET) +#define FIOPAD_AR47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_14_DELAY_OFFSET) +#define FIOPAD_AJ53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_23_DELAY_OFFSET) +#define FIOPAD_AG55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_24_DELAY_OFFSET) +#define FIOPAD_AG53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_25_DELAY_OFFSET) +#define FIOPAD_AE55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_26_DELAY_OFFSET) +#define FIOPAD_BA51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_32_DELAY_OFFSET) +#define FIOPAD_BA49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_33_DELAY_OFFSET) +#define FIOPAD_AR55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_34_DELAY_OFFSET) +#define FIOPAD_AU55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_35_DELAY_OFFSET) +#define FIOPAD_A41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_55_DELAY_OFFSET) +#define FIOPAD_C41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_56_DELAY_OFFSET) +#define FIOPAD_A43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_57_DELAY_OFFSET) +#define FIOPAD_A45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_58_DELAY_OFFSET) +#define FIOPAD_C45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_59_DELAY_OFFSET) +#define FIOPAD_A47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_60_DELAY_OFFSET) +#define FIOPAD_A29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_61_DELAY_OFFSET) +#define FIOPAD_C29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_62_DELAY_OFFSET) +#define FIOPAD_C27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_63_DELAY_OFFSET) +#define FIOPAD_A27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_64_DELAY_OFFSET) +#define FIOPAD_AJ49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_65_DELAY_OFFSET) +#define FIOPAD_AL45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_66_DELAY_OFFSET) +#define FIOPAD_AL43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_67_DELAY_OFFSET) +#define FIOPAD_AN45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_68_DELAY_OFFSET) +#define FIOPAD_AG47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_148_DELAY_OFFSET) +#define FIOPAD_AJ47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_69_DELAY_OFFSET) +#define FIOPAD_AG45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_70_DELAY_OFFSET) +#define FIOPAD_AE51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_71_DELAY_OFFSET) +#define FIOPAD_AE49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_72_DELAY_OFFSET) +#define FIOPAD_AG51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_73_DELAY_OFFSET) +#define FIOPAD_AJ45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_74_DELAY_OFFSET) +#define FIOPAD_AC51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_75_DELAY_OFFSET) +#define FIOPAD_AC49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_76_DELAY_OFFSET) +#define FIOPAD_AE47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_77_DELAY_OFFSET) +#define FIOPAD_W47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_78_DELAY_OFFSET) +#define FIOPAD_W49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_80_DELAY_OFFSET) +#define FIOPAD_U51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_81_DELAY_OFFSET) +#define FIOPAD_U49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_82_DELAY_OFFSET) +#define FIOPAD_AE45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_83_DELAY_OFFSET) +#define FIOPAD_AC45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_84_DELAY_OFFSET) +#define FIOPAD_AE43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_85_DELAY_OFFSET) +#define FIOPAD_AA43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_86_DELAY_OFFSET) +#define FIOPAD_AA45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_87_DELAY_OFFSET) +#define FIOPAD_W45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_88_DELAY_OFFSET) +#define FIOPAD_AA47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_89_DELAY_OFFSET) +#define FIOPAD_U45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_90_DELAY_OFFSET) +#define FIOPAD_J55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_92_DELAY_OFFSET) +#define FIOPAD_L53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_93_DELAY_OFFSET) +#define FIOPAD_C55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_94_DELAY_OFFSET) +#define FIOPAD_E55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_95_DELAY_OFFSET) +#define FIOPAD_J53_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_96_DELAY_OFFSET) +#define FIOPAD_L55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_97_DELAY_OFFSET) +#define FIOPAD_N55_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_98_DELAY_OFFSET) +#define FIOPAD_E27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_99_DELAY_OFFSET) +#define FIOPAD_G27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_100_DELAY_OFFSET) +#define FIOPAD_N37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_101_DELAY_OFFSET) +#define FIOPAD_N35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_102_DELAY_OFFSET) +#define FIOPAD_J29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_103_DELAY_OFFSET) +#define FIOPAD_N29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_104_DELAY_OFFSET) +#define FIOPAD_L29_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_105_DELAY_OFFSET) +#define FIOPAD_N41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_106_DELAY_OFFSET) +#define FIOPAD_N39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_107_DELAY_OFFSET) +#define FIOPAD_L27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_108_DELAY_OFFSET) +#define FIOPAD_J27_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_109_DELAY_OFFSET) +#define FIOPAD_J25_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_110_DELAY_OFFSET) +#define FIOPAD_E25_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_111_DELAY_OFFSET) +#define FIOPAD_G25_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_112_DELAY_OFFSET) +#define FIOPAD_J33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_115_DELAY_OFFSET) +#define FIOPAD_J35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_116_DELAY_OFFSET) +#define FIOPAD_G37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_117_DELAY_OFFSET) +#define FIOPAD_E39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_118_DELAY_OFFSET) +#define FIOPAD_L39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_119_DELAY_OFFSET) +#define FIOPAD_C39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_120_DELAY_OFFSET) +#define FIOPAD_E37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_121_DELAY_OFFSET) +#define FIOPAD_L41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_122_DELAY_OFFSET) +#define FIOPAD_J39_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_123_DELAY_OFFSET) +#define FIOPAD_J37_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_124_DELAY_OFFSET) +#define FIOPAD_L35_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_125_DELAY_OFFSET) +#define FIOPAD_E33_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_126_DELAY_OFFSET) +#define FIOPAD_E31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_127_DELAY_OFFSET) +#define FIOPAD_G31_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_128_DELAY_OFFSET) +#define FIOPAD_L51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_136_DELAY_OFFSET) +#define FIOPAD_J51_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_137_DELAY_OFFSET) +#define FIOPAD_J41_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_138_DELAY_OFFSET) +#define FIOPAD_E43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_139_DELAY_OFFSET) +#define FIOPAD_G43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_140_DELAY_OFFSET) +#define FIOPAD_J43_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_141_DELAY_OFFSET) +#define FIOPAD_J45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_142_DELAY_OFFSET) +#define FIOPAD_N45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_143_DELAY_OFFSET) +#define FIOPAD_L47_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_144_DELAY_OFFSET) +#define FIOPAD_L45_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_145_DELAY_OFFSET) +#define FIOPAD_N49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_146_DELAY_OFFSET) +#define FIOPAD_J49_DELAY (FPinIndex)FIOPAD_INDEX(FIOPAD_147_DELAY_OFFSET) + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + + + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/s/fiopad_config.c b/bsp/phytium/libraries/standalone/board/e2000/s/fiopad_config.c new file mode 100644 index 0000000000..8ab06f4837 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/s/fiopad_config.c @@ -0,0 +1,291 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fiopad_config.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for io-pad function definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021/11/5 init commit + * 1.1 zhugengyu 2022/3/21 adopt to lastest tech spec. + */ + +/***************************** Include Files *********************************/ +#include "fiopad.h" +#include "fparameters.h" +#include "fpinctrl.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ +/** + * @name: FIOPadSetSpimMux + * @msg: set iopad mux for spim + * @return {*} + * @param {u32} spim_id, instance id of spi + */ +void FIOPadSetSpimMux(u32 spim_id) +{ + if (FSPI2_ID == spim_id) + { + FPinSetFunc(FIOPAD_A29, FPIN_FUNC0); /* sclk */ + FPinSetFunc(FIOPAD_C29, FPIN_FUNC0); /* txd */ + FPinSetFunc(FIOPAD_C27, FPIN_FUNC0); /* rxd */ + FPinSetFunc(FIOPAD_A27, FPIN_FUNC0); /* csn0 */ + } +} + +/** + * @name: FIOPadSetGpioMux + * @msg: set iopad mux for gpio + * @return {*} + * @param {u32} gpio_id, instance id of gpio + * @param {u32} pin_id, index of pin + */ +void FIOPadSetGpioMux(u32 gpio_id, u32 pin_id) +{ + if (FGPIO_ID_3 == gpio_id) + { + switch (pin_id) + { + case 3: /* gpio 3-a-3 */ + FPinSetFunc(FIOPAD_A29, FPIN_FUNC6); + break; + case 4: /* gpio 3-a-4 */ + FPinSetFunc(FIOPAD_C29, FPIN_FUNC6); + break; + case 5: /* gpio 3-a-5 */ + FPinSetFunc(FIOPAD_C27, FPIN_FUNC6); + break; + case 6: /* gpio 3-a-6 */ + FPinSetFunc(FIOPAD_A27, FPIN_FUNC6); + break; + default: + break; + } + } +} + +/** + * @name: FIOPadSetMioMux + * @msg: set iopad mux for mio + * @return {*} + * @param {u32} mio_id, instance id of i2c + */ +void FIOPadSetMioMux(u32 mio_id) +{ + switch (mio_id) + { + case MIO_INSTANCE_0: + { + FPinSetFunc(FIOPAD_A37, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A39, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_1: + { + FPinSetFunc(FIOPAD_A41, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_C41, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_2: + { + FPinSetFunc(FIOPAD_A43, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A45, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_3: + { + FPinSetFunc(FIOPAD_BA51, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_BA49, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_4: + { + FPinSetFunc(FIOPAD_R55, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U55, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_5: + { + FPinSetFunc(FIOPAD_W45, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U53, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_6: + { + FPinSetFunc(FIOPAD_AA53, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_AA55, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_7: + { + FPinSetFunc(FIOPAD_A35, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_C35, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_8: + { + FPinSetFunc(FIOPAD_AA45, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_W45, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_9: + { + FPinSetFunc(FIOPAD_AA47, FPIN_FUNC4); /* scl */ + FPinSetFunc(FIOPAD_U45, FPIN_FUNC4); /* sda */ + } + break; + case MIO_INSTANCE_10: + { + FPinSetFunc(FIOPAD_C45, FPIN_FUNC5); /* scl */ + FPinSetFunc(FIOPAD_A47, FPIN_FUNC5); /* sda */ + } + break; + case MIO_INSTANCE_11: + { + FPinSetFunc(FIOPAD_N23, FPIN_FUNC3); /* scl */ + FPinSetFunc(FIOPAD_L25, FPIN_FUNC3); /* sda */ + } + break; + case MIO_INSTANCE_12: + { + FPinSetFunc(FIOPAD_E37, FPIN_FUNC3); /* scl */ + FPinSetFunc(FIOPAD_L41, FPIN_FUNC3); /* sda */ + } + break; + case MIO_INSTANCE_13: + { + FPinSetFunc(FIOPAD_J45, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_N45, FPIN_FUNC6); /* sda */ + } + break; + case MIO_INSTANCE_14: + { + FPinSetFunc(FIOPAD_L47, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_L45, FPIN_FUNC6); /* sda */ + } + break; + case MIO_INSTANCE_15: + { + FPinSetFunc(FIOPAD_N49, FPIN_FUNC6); /* scl */ + FPinSetFunc(FIOPAD_J49, FPIN_FUNC6); /* sda */ + } + break; + default: + break; + } +} + +/** + * @name: FIOPadSetTachoMux + * @msg: set iopad mux for pwm_in + * @return {*} + * @param {u32} pwm_in_id, instance id of tacho + */ +void FIOPadSetTachoMux(u32 pwm_in_id) +{ + switch (pwm_in_id) + { + case TACHO_INSTANCE_0: + FPinSetFunc(FIOPAD_AN53, FPIN_FUNC1); + break; + case TACHO_INSTANCE_1: + FPinSetFunc(FIOPAD_AJ55, FPIN_FUNC1); + break; + case TACHO_INSTANCE_2: + FPinSetFunc(FIOPAD_AG55, FPIN_FUNC1); + break; + case TACHO_INSTANCE_3: + FPinSetFunc(FIOPAD_AE55, FPIN_FUNC1); + break; + case TACHO_INSTANCE_4: + FPinSetFunc(FIOPAD_AC53, FPIN_FUNC1); + break; + case TACHO_INSTANCE_5: + FPinSetFunc(FIOPAD_BA49, FPIN_FUNC1); + break; + case TACHO_INSTANCE_6: + FPinSetFunc(FIOPAD_C33, FPIN_FUNC2); + break; + case TACHO_INSTANCE_7: + FPinSetFunc(FIOPAD_A37, FPIN_FUNC2); + break; + case TACHO_INSTANCE_8: + FPinSetFunc(FIOPAD_A41, FPIN_FUNC2); + break; + case TACHO_INSTANCE_9: + FPinSetFunc(FIOPAD_A43, FPIN_FUNC2); + break; + case TACHO_INSTANCE_10: + FPinSetFunc(FIOPAD_C45, FPIN_FUNC2); + break; + case TACHO_INSTANCE_11: + FPinSetFunc(FIOPAD_A29, FPIN_FUNC2); + break; + case TACHO_INSTANCE_12: + FPinSetFunc(FIOPAD_C27, FPIN_FUNC2); + break; + case TACHO_INSTANCE_13: + FPinSetFunc(FIOPAD_AA45, FPIN_FUNC2); + break; + case TACHO_INSTANCE_14: + FPinSetFunc(FIOPAD_AA47, FPIN_FUNC2); + break; + case TACHO_INSTANCE_15: + FPinSetFunc(FIOPAD_G55, FPIN_FUNC2); + break; + default: + break; + } +} + +/** + * @name: FIOPadSetUartMux + * @msg: set iopad mux for uart + * @return {*} + * @param {u32} uart_id, instance id of uart + */ +void FIOPadSetUartMux(u32 uart_id) +{ + switch (uart_id) + { + case FUART0_ID: + FPinSetFunc(FIOPAD_J33, FPIN_FUNC4); + FPinSetFunc(FIOPAD_J35, FPIN_FUNC4); + break; + case FUART1_ID: + FPinSetFunc(FIOPAD_AW47, FPIN_FUNC0); + FPinSetFunc(FIOPAD_AU47, FPIN_FUNC0); + break; + case FUART2_ID: + FPinSetFunc(FIOPAD_A43, FPIN_FUNC0); + FPinSetFunc(FIOPAD_A45, FPIN_FUNC0); + break; + case FUART3_ID: + FPinSetFunc(FIOPAD_L33, FPIN_FUNC2); + FPinSetFunc(FIOPAD_N31, FPIN_FUNC2); + break; + default: + break; + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/board/e2000/s/fparameters.h b/bsp/phytium/libraries/standalone/board/e2000/s/fparameters.h new file mode 100644 index 0000000000..24b67ac122 --- /dev/null +++ b/bsp/phytium/libraries/standalone/board/e2000/s/fparameters.h @@ -0,0 +1,53 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fparameters.h + * Date: 2022-02-11 13:33:28 + * LastEditTime: 2022-02-17 18:00:50 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BOARD_E2000S_PARAMTERERS_H +#define BOARD_E2000S_PARAMTERERS_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fparameters_comm.h" + +/************************** Constant Definitions *****************************/ +#define CORE0_AFF 0x200U + +#define FT_CPUS_NR 1U + + +/* GIC offset */ + +#define FT_GIC_REDISTRUBUTIOR_OFFSET 2 + +/*****************************************************************************/ + + +#ifdef __cplusplus +} + +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/common/Kconfig b/bsp/phytium/libraries/standalone/common/Kconfig new file mode 100644 index 0000000000..3ffaf15c65 --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/Kconfig @@ -0,0 +1,64 @@ + + + +choice DEBUG_LOG_LEVEL + prompt "Debug Log Level" + default LOG_ERROR + help + VERBOS: Print bigger chunks of debugging information + DEBUG: Print extra information for debugging + INFO: Print necessary information messages + WARN: Print error conditions from which recovery measures have been taken + ERROR: Print critical errors, software module can not recover on its own + + config LOG_VERBOS + bool "VERBOS" + config LOG_DEBUG + bool "DEBUG" + config LOG_INFO + bool "INFO" + config LOG_WARN + bool "WARN" + config LOG_ERROR + bool "ERROR" + config LOG_NONE + bool "NONE" + +endchoice # DEBUG_LOG_LEVEL + + +config USE_DEFAULT_INTERRUPT_CONFIG + bool + prompt "Use default interrupt configuration" + default y + help + "If this option is not selected, core0 is used as the main core by default and all interrupt driver modules are initialized. Non-0 core initializes only the necessary interrupt driver modules. If this option is selected, the developer needs to initiate each module independently " + if USE_DEFAULT_INTERRUPT_CONFIG + choice INTERRUPT_ROLE_SELECT + prompt "Interrupt role select" + default INTERRUPT_ROLE_MASTER + help + "Select Interrupt role" + + config INTERRUPT_ROLE_MASTER + bool "use master role" + + config INTERRUPT_ROLE_SLAVE + bool "use slave role" + + endchoice # INTERRUPT_ROLE_SELECT + endif + +config LOG_EXTRA_INFO + bool "Debug Log with Extra Info" + default n + help + Print debug information with source file name and source code line num. + +config BOOTUP_DEBUG_PRINTS + bool + prompt "Bootup debug" + default n + help + Enable Bootup debug printing + diff --git a/bsp/phytium/libraries/standalone/common/fassert.c b/bsp/phytium/libraries/standalone/common/fassert.c new file mode 100644 index 0000000000..ec1ade974b --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fassert.c @@ -0,0 +1,118 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ft_assert.c + * Date: 2021-04-07 09:53:07 + * LastEditTime: 2022-02-17 18:04:28 + * Description:  This files is for assertion implmentation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021.4 init commit + * 1.1 zhugengyu 2022.3 re-define assert macro + */ + +/***************************** Include Files *********************************/ +#include "ftypes.h" +#include "fassert.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ +typedef struct +{ + u32 status; /* 当前断言状态 */ + FAssertCB cb; /* 断言回调函数 */ +} FAssertInfo; /* 断言实例类型 */ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +static void FAssertCallback(const char *file, s32 line, int ret); + +/************************** Variable Definitions *****************************/ +static FAssertInfo assert_info = +{ + .status = FASSERT_NONE, + .cb = FAssertCallback +}; /* 断言实例 */ + +/*****************************************************************************/ +/** + * @name: FAssertSetStatus + * @msg: 设置断言状态 + * @return {*} + * @param {FAssertStatus} status, 断言状态 + */ +void FAssertSetStatus(FAssertStatus status) +{ + assert_info.status = status; +} + +/** + * @name: FAssertGetStatus + * @msg: 获取当前断言状态 + * @return {FAssertStatus} 当前断言状态 + */ +FAssertStatus FAssertGetStatus(void) +{ + return assert_info.status; +} + +/** + * @name: FAssertCallback + * @msg: 默认的断言回调函数 + * @return {*} + * @param {char} *file, 断言发生的源文件 + * @param {s32} line, 断言发生的源文件行号 + * @param {int} ret, 保留给Non-block断言使用 + */ +static void FAssertCallback(const char *file, s32 line, int ret) +{ + f_printk("Assert Error at %s : %ld \r\n", file, line); +} + +/** + * @name: FAssertSetCB + * @msg: 设置断言回调函数 + * @return {*} + * @param {FAssertCB} cb, 断言回调函数 + */ +void FAssertSetCB(FAssertCB cb) +{ + if (NULL != cb) + assert_info.cb = cb; +} + +/** + * @name: FAssert + * @msg: 断言实现 + * @return {*} + * @param {char} *file, 断言发生的源文件 + * @param {s32} line, 断言发生的源文件行号 + * @param {int} code, 断言发生的退出码,保留给Non-block断言使用 + */ +void FAssert(const char *file, s32 line, int code) +{ + if (NULL != assert_info.cb) + { + /* 如果要实现Non-block断言,需要在回调中返回 */ + assert_info.cb(file, line, code); + } + + while (TRUE) + { + ; + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/common/fassert.h b/bsp/phytium/libraries/standalone/common/fassert.h new file mode 100644 index 0000000000..9bb44362ff --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fassert.h @@ -0,0 +1,102 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fassert.h + * Date: 2021-04-07 09:53:07 + * LastEditTime: 2022-02-17 18:04:35 + * Description:  This files is for assertion defintion + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021.4 init commit + * 1.1 zhugengyu 2022.3 re-define assert macro + */ + +#ifndef FT_ASSERT_H +#define FT_ASSERT_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fprintk.h" +#include "ferror_code.h" +#include "ftypes.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ +typedef enum +{ + FASSERT_NONE = 0, + FASSERT_OCCURRED +} FAssertStatus; /* 断言状态 */ + +/* 断言处理回调函数 */ +typedef void (*FAssertCB)(const char *file, s32 line, int ret); + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FASSERT_MSG(expression, fmt, ...) \ + { \ + if (expression) \ + { \ + FAssertSetStatus(FASSERT_NONE); \ + } \ + else \ + { \ + FAssertSetStatus(FASSERT_OCCURRED); \ + f_printk(fmt, ##__VA_ARGS__); \ + FAssert(__FILE__, __LINE__, 0xff); \ + } \ + } + +#define FASSERT(expression)\ + { \ + if (expression) \ + { \ + FAssertSetStatus(FASSERT_NONE); \ + } \ + else \ + { \ + FAssertSetStatus(FASSERT_OCCURRED); \ + FAssert(__FILE__, __LINE__, 0xff); \ + } \ + } + +/* 检查静态断言状态 */ +#define FASSERT_STATIC(expression) \ + extern int assert_static[(expression) ? 1 : -1] + +/************************** Function Prototypes ******************************/ +/* 设置断言状态 */ +void FAssertSetStatus(FAssertStatus status); + +/* 获取当前断言状态 */ +FAssertStatus FAssertGetStatus(void); + +/* 设置断言回调函数 */ +void FAssertSetCB(FAssertCB cb); + +/* 断言实现 */ +void FAssert(const char *file, s32 line, int code); + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/common/fdebug.c b/bsp/phytium/libraries/standalone/common/fdebug.c new file mode 100644 index 0000000000..2a6d906e59 --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fdebug.c @@ -0,0 +1,106 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ft_debug.c + * Date: 2021-04-25 16:44:23 + * LastEditTime: 2022-02-17 18:04:50 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fdebug.h" +#include "fprintf.h" +#include "stdio.h" + +#define __is_print(ch) ((unsigned int)((ch) - ' ') < 127u - ' ') +void FtDumpHexByte(const u8 *ptr, u32 buflen) +{ + u8 *buf = (u8 *)ptr; + fsize_t i, j; + + for (i = 0; i < buflen; i += 16) + { + printf("%p: ", ptr + i); + + for (j = 0; j < 16; j++) + if (i + j < buflen) + printf("%02X ", buf[i + j]); + else + printf(" "); + printf(" "); + + for (j = 0; j < 16; j++) + if (i + j < buflen) + printf("%c", (char)(__is_print(buf[i + j]) ? buf[i + j] : '.')); + printf("\r\n"); + } +} + +void FtDumpHexByteDebug(const u8 *ptr, u32 buflen) +{ + u8 *buf = (u8 *)ptr; + fsize_t i, j; + + for (i = 0; i < buflen; i += 16) + { + f_printf("%x: ", ptr + i); + + for (j = 0; j < 16; j++) + if (i + j < buflen) + f_printf("%x ", buf[i + j]); + else + f_printf(" "); + f_printf(" "); + + for (j = 0; j < 16; j++) + if (i + j < buflen) + f_printf("%c", (char)(__is_print(buf[i + j]) ? buf[i + j] : '.')); + f_printf("\r\n"); + } +} + + +void FtDumpHexWord(const u32 *ptr, u32 buflen) +{ + u32 *buf = (u32 *)ptr; + u8 *char_data = (u8 *)ptr; + fsize_t i, j; + buflen = buflen / 4; + for (i = 0; i < buflen; i += 4) + { + printf("%p: ", ptr + i); + + for (j = 0; j < 4; j++) + { + if (i + j < buflen) + { + printf("%lx ", buf[i + j]); + } + else + { + printf(" "); + } + } + + printf(" "); + + for (j = 0; j < 16; j++) + if (i + j < buflen) + printf("%c", (char)(__is_print(char_data[i + j]) ? char_data[i + j] : '.')); + + printf("\r\n"); + } +} diff --git a/bsp/phytium/libraries/standalone/common/fdebug.h b/bsp/phytium/libraries/standalone/common/fdebug.h new file mode 100644 index 0000000000..84f283b75e --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fdebug.h @@ -0,0 +1,127 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fdebug.h + * Date: 2021-04-07 09:53:07 + * LastEditTime: 2022-02-17 18:04:58 + * Description:  This files is for debug functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_COMMON_FT_DEBUG_H +#define BSP_COMMON_FT_DEBUG_H +#include +#include "sdkconfig.h" +#include "ftypes.h" + +typedef enum +{ + FT_LOG_NONE, /* No log output */ + FT_LOG_ERROR, /* Critical errors, software module can not recover on its own */ + FT_LOG_WARN, /* Error conditions from which recovery measures have been taken */ + FT_LOG_INFO, /* Information messages which describe normal flow of events */ + FT_LOG_DEBUG, /* Extra information which is not necessary for normal use (values, pointers, sizes, etc). */ + FT_LOG_VERBOSE /* Bigger chunks of debugging information, or frequent messages which can potentially flood the output. */ +} ft_log_level_t; + +#define LOG_COLOR_BLACK "30" +#define LOG_COLOR_RED "31" +#define LOG_COLOR_GREEN "32" +#define LOG_COLOR_BROWN "33" +#define LOG_COLOR_BLUE "34" +#define LOG_COLOR_PURPLE "35" +#define LOG_COLOR_CYAN "36" +#define LOG_COLOR(COLOR) "\033[0;" COLOR "m" +#define LOG_BOLD(COLOR) "\033[1;" COLOR "m" +#define LOG_RESET_COLOR "\033[0m" +#define LOG_COLOR_E LOG_COLOR(LOG_COLOR_RED) +#define LOG_COLOR_W LOG_COLOR(LOG_COLOR_BROWN) +#define LOG_COLOR_I LOG_COLOR(LOG_COLOR_GREEN) +#define LOG_COLOR_D LOG_COLOR(LOG_COLOR_CYAN) +#define LOG_COLOR_V LOG_COLOR(LOG_COLOR_PURPLE) + +/* select debug log level */ +#ifdef CONFIG_LOG_VERBOS + #define LOG_LOCAL_LEVEL FT_LOG_VERBOSE +#endif + +#ifdef CONFIG_LOG_ERROR + #define LOG_LOCAL_LEVEL FT_LOG_ERROR +#endif + +#ifdef CONFIG_LOG_WARN + #define LOG_LOCAL_LEVEL FT_LOG_WARN +#endif + +#ifdef CONFIG_LOG_INFO + #define LOG_LOCAL_LEVEL FT_LOG_INFO +#endif + +#ifdef CONFIG_LOG_DEBUG + #define LOG_LOCAL_LEVEL FT_LOG_DEBUG +#endif + +#define LOG_FORMAT(letter, format) LOG_COLOR_##letter " %s: " format LOG_RESET_COLOR "\r\n" + +#define PORT_KPRINTF printf + +#ifndef CONFIG_LOG_EXTRA_INFO +#define LOG_EARLY_IMPL(tag, format, log_level, log_tag_letter, ...) \ + do \ + { \ + if (LOG_LOCAL_LEVEL < log_level) \ + break; \ + PORT_KPRINTF(LOG_FORMAT(log_tag_letter, format), tag, ##__VA_ARGS__); \ + } while (0) +#else +#include +#define __FILENAME__ (strrchr(__FILE__, '/') ? (strrchr(__FILE__, '/') + 1):__FILE__) +/* print debug information with source file name and source code line num. */ +#define LOG_EARLY_IMPL(tag, format, log_level, log_tag_letter, ...) \ + do \ + { \ + if (LOG_LOCAL_LEVEL < log_level) \ + break; \ + PORT_KPRINTF(LOG_FORMAT(log_tag_letter, format" @%s:%d"), tag, ##__VA_ARGS__, __FILENAME__, __LINE__); \ + } while (0) +#endif + +#define EARLY_LOGE(tag, format, ...) LOG_EARLY_IMPL(tag, format, FT_LOG_ERROR, E, ##__VA_ARGS__) +#define EARLY_LOGI(tag, format, ...) LOG_EARLY_IMPL(tag, format, FT_LOG_INFO, I, ##__VA_ARGS__) +#define EARLY_LOGD(tag, format, ...) LOG_EARLY_IMPL(tag, format, FT_LOG_DEBUG, D, ##__VA_ARGS__) +#define EARLY_LOGW(tag, format, ...) LOG_EARLY_IMPL(tag, format, FT_LOG_WARN, W, ##__VA_ARGS__) +#define EARLY_LOGV(tag, format, ...) LOG_EARLY_IMPL(tag, format, FT_LOG_VERBOSE, W, ##__VA_ARGS__) + +/* do not compile log if define CONFIG_LOG_NONE */ +#ifndef CONFIG_LOG_NONE + #define FT_DEBUG_PRINT_I(TAG, format, ...) EARLY_LOGI(TAG, format, ##__VA_ARGS__) + #define FT_DEBUG_PRINT_E(TAG, format, ...) EARLY_LOGE(TAG, format, ##__VA_ARGS__) + #define FT_DEBUG_PRINT_D(TAG, format, ...) EARLY_LOGD(TAG, format, ##__VA_ARGS__) + #define FT_DEBUG_PRINT_W(TAG, format, ...) EARLY_LOGW(TAG, format, ##__VA_ARGS__) + #define FT_DEBUG_PRINT_V(TAG, format, ...) EARLY_LOGV(TAG, format, ##__VA_ARGS__) +#else + #define FT_DEBUG_PRINT_I(TAG, format, ...) + #define FT_DEBUG_PRINT_E(TAG, format, ...) + #define FT_DEBUG_PRINT_D(TAG, format, ...) + #define FT_DEBUG_PRINT_W(TAG, format, ...) + #define FT_DEBUG_PRINT_V(TAG, format, ...) +#endif + +#define FT_RAW_PRINTF(format, ...) PORT_KPRINTF(format, ##__VA_ARGS__) + +void FtDumpHexWord(const u32 *ptr, u32 buflen); +void FtDumpHexByte(const u8 *ptr, u32 buflen); +#endif // ! diff --git a/bsp/phytium/libraries/standalone/common/ferror_code.h b/bsp/phytium/libraries/standalone/common/ferror_code.h new file mode 100644 index 0000000000..f00bcba001 --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/ferror_code.h @@ -0,0 +1,106 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ferror_code.h + * Date: 2021-04-07 09:53:30 + * LastEditTime: 2022-02-17 18:05:27 + * Description:  This files is for error code functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#ifndef _FT_ERROR_CODE_H +#define _FT_ERROR_CODE_H + +#include "ftypes.h" + +typedef u32 FError; + +#define FT_SUCCESS 0 + +/* 系统错误码模块定义 */ +typedef enum +{ + ErrorModGeneral = 0, + ErrModBsp, + ErrModAssert, + ErrModPort, + StatusModBsp, + ErrModMaxMask = 255, + +} FtErrorCodeModuleMask; + +/* COMMON组件的错误码子模块定义 */ +typedef enum +{ + ErrCommGeneral = 0, + ErrCommMemp, + ErrInterrupt, +} FtErrCodeCommMask; + +/* BSP模块的错误子模块定义 */ +typedef enum +{ + ErrBspGeneral = 0, + ErrBspClk, + ErrBspRtc, + ErrBspTimer, + ErrBspUart, + ErrBspGpio, + ErrBspSpi, + ErrBspEth, + ErrBspCan, + ErrPcie, + ErrBspQSpi, + ErrBspMio, + ErrBspI2c, + ErrBspMmc, + ErrBspWdt, + ErrGic, + ErrGdma, + ErrNand, + ErrIoMux, + ErrBspSata, + ErrUsb, + ErrEthPhy, + ErrDdma, + ErrBspAdc, + ErrBspPwm, + ErrSema, + + ErrBspModMaxMask = 255 +} FtErrCodeBspMask; + +#define FT_ERRCODE_SYS_MODULE_OFFSET (u32)24 +#define FT_ERRCODE_SUB_MODULE_OFFSET (u32)16 + +#define FT_ERRCODE_SYS_MODULE_MASK ((u32)0xff << FT_ERRCODE_SYS_MODULE_OFFSET) /* bit 24 .. 31 */ +#define FT_ERRCODE_SUB_MODULE_MASK ((u32)0xff << FT_ERRCODE_SUB_MODULE_OFFSET) /* bit 16 .. 23 */ +#define FT_ERRCODE_TAIL_VALUE_MASK ((u32)0xffff) /* bit 1 .. 15 */ + +/* Offset error code */ +#define FT_ERRCODE_OFFSET(code, offset, mask) \ + (((code) << (offset)) & (mask)) + +/* Assembly error code */ +#define FT_MAKE_ERRCODE(sys_mode, sub_mode, tail) \ + ((FT_ERRCODE_OFFSET((u32)sys_mode, FT_ERRCODE_SYS_MODULE_OFFSET, FT_ERRCODE_SYS_MODULE_MASK)) | \ + (FT_ERRCODE_OFFSET((u32)sub_mode, FT_ERRCODE_SUB_MODULE_OFFSET, FT_ERRCODE_SUB_MODULE_MASK)) | \ + ((u32)tail & FT_ERRCODE_TAIL_VALUE_MASK)) +#define FT_CODE_ERR FT_MAKE_ERRCODE + +#define ERR_SUCCESS FT_MAKE_ERRCODE(ErrorModGeneral, ErrBspGeneral, 0) /* 成功 */ +#define ERR_GENERAL FT_MAKE_ERRCODE(ErrorModGeneral, ErrBspGeneral, 1) /* 一般错误 */ + +#endif diff --git a/bsp/phytium/libraries/standalone/common/fio.h b/bsp/phytium/libraries/standalone/common/fio.h new file mode 100644 index 0000000000..1f1d8331cf --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fio.h @@ -0,0 +1,113 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fio.h + * Date: 2021-04-07 09:53:07 + * LastEditTime: 2022-02-18 08:24:01 + * Description:  This files is for general reigster io functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef FT_IO_H +#define FT_IO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" + +static _INLINE u8 FtIn8(uintptr addr) +{ + return *(volatile u8 *)addr; +} + +static _INLINE u16 FtIn16(uintptr addr) +{ + return *(volatile u16 *)addr; +} + +static _INLINE u32 FtIn32(uintptr addr) +{ + return *(volatile u32 *)addr; +} + +static _INLINE u64 FtIn64(uintptr addr) +{ + return *(volatile u64 *)addr; +} + +static _INLINE void FtOut8(uintptr addr, u8 value) +{ + volatile u8 *local_addr = (volatile u8 *)addr; + *local_addr = value; +} + +static _INLINE void FtOut16(uintptr addr, u16 value) +{ + volatile u16 *local_addr = (volatile u16 *)addr; + *local_addr = value; +} + +static _INLINE void FtOut32(uintptr addr, u32 value) +{ + volatile u32 *local_addr = (volatile u32 *)addr; + *local_addr = value; +} + +static _INLINE void FtOut64(uintptr addr, u64 value) +{ + volatile u64 *local_addr = (volatile u64 *)addr; + *local_addr = value; +} + +static _INLINE void FtSetBit32(uintptr addr, u32 value) +{ + volatile u32 last_value; + last_value = FtIn32(addr); + last_value |= value; + FtOut32(addr, last_value); +} + +static _INLINE void FtClearBit32(uintptr addr, u32 value) +{ + volatile u32 last_value; + last_value = FtIn32(addr); + last_value &= ~value; + FtOut32(addr, last_value); +} + +static _INLINE void FtToggleBit32(uintptr addr, u32 toggle_pos) +{ + volatile u32 value; + value = FtIn32(addr); + value ^= (1 << toggle_pos); + FtOut32(addr, value); +} + +static _INLINE u16 FtEndianSwap16(u16 data) +{ + return (u16)(((data & 0xFF00U) >> 8U) | ((data & 0x00FFU) << 8U)); +} +#define FT_WRITE32(_reg, _val) (*(volatile uint32_t *)&_reg = _val) +#define FT_READ32(_reg) (*(volatile uint32_t *)&_reg) + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/common/fpinctrl.h b/bsp/phytium/libraries/standalone/common/fpinctrl.h new file mode 100644 index 0000000000..891e8f74de --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fpinctrl.h @@ -0,0 +1,211 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpinctrl.h + * Date: 2022-03-28 14:16:09 + * LastEditTime: 2022-03-28 14:16:10 + * Description:  This files is for IO pin ctrl API definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022/3/28 init commit + */ +#ifndef COMMON_FPINCTRL_H +#define COMMON_FPINCTRL_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "ftypes.h" +#include "sdkconfig.h" + +#if defined(CONFIG_TARGET_F2000_4) || defined(CONFIG_TARGET_D2000) +#ifndef FPIN_IO_CTRL +#define FPIN_IO_CTRL +#endif +#endif + +#if defined(CONFIG_TARGET_E2000) +#ifndef FPIN_IO_PAD +#define FPIN_IO_PAD +#endif +#endif + +#if defined(FPIN_IO_CTRL) +#include "fioctrl.h" +#endif + +#if defined(FPIN_IO_PAD) +#include "fiopad.h" +#endif + +/**************************** Type Definitions *******************************/ + +typedef enum +{ + FPIN_FUNC0 = 0b000, + FPIN_FUNC1, + FPIN_FUNC2, + FPIN_FUNC3 = 0b011, +#if defined(FPIN_IO_PAD) /* E2000 support more pin func */ + FPIN_FUNC4, + FPIN_FUNC5, + FPIN_FUNC6, + FPIN_FUNC7 = 0b111, +#endif + FPIN_NUM_OF_FUNC +} FPinFunc; /* 引脚复用功能配置, func0为默认功能 */ + +#if defined(FPIN_IO_PAD) /* Only support driver strength config in E2000 */ +typedef enum +{ + FPIN_DRV0 = 0b0000, + FPIN_DRV1, + FPIN_DRV2, + FPIN_DRV3, + FPIN_DRV4, + FPIN_DRV5, + FPIN_DRV6, + FPIN_DRV7, + FPIN_DRV8, + FPIN_DRV9, + FPIN_DRV10, + FPIN_DRV11, + FPIN_DRV12, + FPIN_DRV13, + FPIN_DRV14, + FPIN_DRV15 = 0b1111, + + FPIN_NUM_OF_DRIVE +} FPinDrive; /* 引脚驱动能力配置 */ +#endif + +typedef enum +{ + FPIN_PULL_NONE = 0b00, + FPIN_PULL_DOWN = 0b01, + FPIN_PULL_UP = 0b10, + + FPIN_NUM_OF_PULL +} FPinPull; /* 引脚上下拉配置 */ + +typedef enum +{ + FPIN_OUTPUT_DELAY = 0, /* 延时设置方向为输出 */ + FPIN_INPUT_DELAY, /* 延时设置方向为输入 */ + + FPIN_NUM_OF_DELAY_DIR +} FPinDelayDir; /* 引脚延时配置方向 */ + +typedef enum +{ + FPIN_DELAY_COARSE_TUNING = 0, /* 延迟粗调档位 */ + FPIN_DELAY_FINE_TUNING, /* 延迟精调档位 */ + + FPIN_NUM_OF_DELAY_TYPE +} FPinDelayType; /* 引脚延时配置类型 */ + +typedef enum +{ + FPIN_DELAY_NONE = 0, + FPIN_DELAY_1, + FPIN_DELAY_2, + FPIN_DELAY_3, + FPIN_DELAY_4, + FPIN_DELAY_5, + FPIN_DELAY_6, + FPIN_DELAY_7, + + FPIN_NUM_OF_DELAY +} FPinDelay; + +typedef enum +{ + FPIN_DELAY_IN_TYPE = 0, /* input delay */ + FPIN_DELAY_OUT_TYPE = 1, /* output delay */ +} FPinDelayIOType; + +typedef struct +{ + u32 reg_off; /* 引脚配置寄存器偏移量 */ + u32 reg_bit; /* 引脚配置起始位 */ +} FPinIndex; /* 引脚索引 */ +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FPIN_NULL {0xffffffff, 0} + +/************************** Function Prototypes ******************************/ +/* 获取IO引脚当前的复用功能 */ +FPinFunc FPinGetFunc(const FPinIndex pin); + +/* 设置IO引脚复用功能 */ +void FPinSetFunc(const FPinIndex pin, FPinFunc func); + +/* 获取IO引脚当前的上下拉设置 */ +FPinPull FPinGetPull(const FPinIndex pin); + +/* 设置IO引脚的上下拉 */ +void FPinSetPull(const FPinIndex pin, FPinPull pull); + +#if defined(FPIN_IO_PAD) +/* 获取IO引脚的驱动能力 */ +FPinDrive FPinGetDrive(const FPinIndex pin); + +/* 设置IO引脚的驱动能力 */ +void FPinSetDrive(const FPinIndex pin, FPinDrive drive); + +/* 获取IO引脚的复用、上下拉和驱动能力设置 */ +void FPinGetConfig(const FPinIndex pin, FPinFunc *func, FPinPull *pull, FPinDrive *drive); + +/* 设置IO引脚的复用、上下拉和驱动能力 */ +void FPinSetConfig(const FPinIndex pin, FPinFunc func, FPinPull pull, FPinDrive drive); + +#else + +/* 获取IO引脚的复用、上下拉和驱动能力设置 */ +void FPinGetConfig(const FPinIndex pin, FPinFunc *func, FPinPull *pull); + +/* 设置IO引脚的复用、上下拉和驱动能力 */ +void FPinSetConfig(const FPinIndex pin, FPinFunc func, FPinPull pull); + +#endif + +/* 获取IO引脚当前的单项延时设置 */ +FPinDelay FPinGetDelay(const FPinIndex pin, FPinDelayDir dir, FPinDelayType type); + +/* 检查IO引脚延时是否使能 */ +boolean FPinGetDelayEn(const FPinIndex pin, FPinDelayDir dir); + +/* 设置IO引脚单项延时 */ +void FPinSetDelay(const FPinIndex pin, FPinDelayDir dir, FPinDelayType type, FPinDelay delay); + +/* 使能或去使能IO引脚延时 */ +void FPinSetDelayEn(const FPinIndex pin, FPinDelayDir dir, boolean enable); + +/* Update and enable common IO pin delay config */ +void FPinSetDelayConfig(const FPinIndex pin, FPinDelayIOType in_out_type, FPinDelay roungh_delay, FPinDelay delicate_delay, boolean enable); + +/* Get current common IO pin delay config */ +void FPinGetDelayConfig(const FPinIndex pin, FPinDelay *in_roungh_delay, FPinDelay *in_delicate_delay, + FPinDelay *out_roungh_delay, FPinDelay *out_delicate_delay); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/common/fprintf.c b/bsp/phytium/libraries/standalone/common/fprintf.c new file mode 100644 index 0000000000..a37c4d3e2a --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fprintf.c @@ -0,0 +1,265 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: f_printf.c + * Date: 2021-08-23 16:24:02 + * LastEditTime: 2022-02-17 18:01:19 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include +#include "fearly_uart.h" + +#define putchar(c) OutByte(c) +#define PAD_RIGHT 1 +#define PAD_ZERO 2 + +static void printchar(char **str, int c) +{ + if (str) + { + **str = c; + ++(*str); + } + else + (void)putchar((const char)c); +} + +static int prints(char **out, const char *string, int width, int pad) +{ + register int pc = 0, padchar = ' '; + + if (width > 0) + { + register int len = 0; + register const char *ptr; + for (ptr = string; *ptr; ++ptr) + ++len; + if (len >= width) + width = 0; + else + width -= len; + if (pad & PAD_ZERO) + padchar = '0'; + } + if (!(pad & PAD_RIGHT)) + { + for (; width > 0; --width) + { + printchar(out, padchar); + ++pc; + } + } + for (; *string; ++string) + { + printchar(out, *string); + ++pc; + } + for (; width > 0; --width) + { + printchar(out, padchar); + ++pc; + } + + return pc; +} + +/* the following should be enough for 32 bit int */ +#define PRINT_BUF_LEN 12 + +static int printi(char **out, int i, int b, int sg, int width, int pad, int letbase) +{ + char print_buf[PRINT_BUF_LEN]; + register char *s; + register int t, neg = 0, pc = 0; + register unsigned int u = i; + + if (i == 0) + { + print_buf[0] = '0'; + print_buf[1] = '\0'; + return prints(out, print_buf, width, pad); + } + + if (sg && b == 10 && i < 0) + { + neg = 1; + u = -i; + } + + s = print_buf + PRINT_BUF_LEN - 1; + *s = '\0'; + + while (u) + { + t = u % b; + if (t >= 10) + t += letbase - '0' - 10; + *--s = t + '0'; + u /= b; + } + + if (neg) + { + if (width && (pad & PAD_ZERO)) + { + printchar(out, '-'); + ++pc; + --width; + } + else + { + *--s = '-'; + } + } + + return pc + prints(out, s, width, pad); +} + +static int print(char **out, const char *format, va_list args) +{ + register int width, pad; + register int pc = 0; + char scr[2]; + + for (; *format != 0; ++format) + { + if (*format == '%') + { + ++format; + width = pad = 0; + if (*format == '\0') + break; + if (*format == '%') + goto out; + if (*format == '-') + { + ++format; + pad = PAD_RIGHT; + } + while (*format == '0') + { + ++format; + pad |= PAD_ZERO; + } + for (; *format >= '0' && *format <= '9'; ++format) + { + width *= 10; + width += *format - '0'; + } + if (*format == 's') + { + //register char *s = (char *)va_arg( args, int ); + register char *s = (char *)va_arg(args, char *); + pc += prints(out, s ? s : "(null)", width, pad); + continue; + } + if (*format == 'd') + { + pc += printi(out, va_arg(args, int), 10, 1, width, pad, 'a'); + continue; + } + if (*format == 'x') + { + pc += printi(out, va_arg(args, int), 16, 0, width, pad, 'a'); + continue; + } + if (*format == 'X') + { + pc += printi(out, va_arg(args, int), 16, 0, width, pad, 'A'); + continue; + } + if (*format == 'u') + { + pc += printi(out, va_arg(args, int), 10, 0, width, pad, 'a'); + continue; + } + if (*format == 'c') + { + /* char are converted to int then pushed on the stack */ + scr[0] = (char)va_arg(args, int); + scr[1] = '\0'; + pc += prints(out, scr, width, pad); + continue; + } + } + else + { +out: + printchar(out, *format); + ++pc; + } + } + if (out) + **out = '\0'; + va_end(args); + return pc; +} + +int f_printf(const char *format, ...) +{ + va_list args; + + va_start(args, format); + return print(0, format, args); +} + +#ifdef TEST_PRINTF +int test_printf(void) +{ + char *ptr = "Hello world!"; + char *np = 0; + int i = 5; + unsigned int bs = sizeof(int) * 8; + int mi; + char buf[80]; + + mi = (1 << (bs - 1)) + 1; + f_printf("%s\n", ptr); + f_printf("printf test\n"); + f_printf("%s is null pointer\n", np); + f_printf("%d = 5\n", i); + f_printf("%d = - max int\n", mi); + f_printf("char %c = 'a'\n", 'a'); + f_printf("hex %x = ff\n", 0xff); + f_printf("hex %02x = 00\n", 0); + f_printf("signed %d = unsigned %u = hex %x\n", -3, -3, -3); + f_printf("%d %s(s)%", 0, "message"); + f_printf("\n"); + f_printf("%d %s(s) with %%\n", 0, "message"); + sprintf(buf, "justif: \"%-10s\"\n", "left"); + f_printf("%s", buf); + sprintf(buf, "justif: \"%10s\"\n", "right"); + f_printf("%s", buf); + sprintf(buf, " 3: %04d zero padded\n", 3); + f_printf("%s", buf); + sprintf(buf, " 3: %-4d left justif.\n", 3); + f_printf("%s", buf); + sprintf(buf, " 3: %4d right justif.\n", 3); + f_printf("%s", buf); + sprintf(buf, "-3: %04d zero padded\n", -3); + f_printf("%s", buf); + sprintf(buf, "-3: %-4d left justif.\n", -3); + f_printf("%s", buf); + sprintf(buf, "-3: %4d right justif.\n", -3); + f_printf("%s", buf); + + return 0; +} + +#endif diff --git a/bsp/phytium/libraries/standalone/common/fprintf.h b/bsp/phytium/libraries/standalone/common/fprintf.h new file mode 100644 index 0000000000..4877234b82 --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fprintf.h @@ -0,0 +1,38 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fprintf.h + * Date: 2021-08-23 16:24:02 + * LastEditTime: 2022-02-17 18:01:24 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef COMMON_F_PRINTF_H +#define COMMON_F_PRINTF_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +int f_printf(const char *format, ...) ; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/common/fprintk.c b/bsp/phytium/libraries/standalone/common/fprintk.c new file mode 100644 index 0000000000..d07f6b994a --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fprintk.c @@ -0,0 +1,418 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: f_printk.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-17 18:01:29 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include +#include +#include +#include "fkernel.h" +#include "ftypes.h" +#include "fearly_uart.h" + +#ifndef __fallthrough + #if __GNUC__ >= 7 + #define __fallthrough __attribute__((fallthrough)) + #else + #define __fallthrough + #endif /* __GNUC__ >= 7 */ +#endif + +typedef int (*cbprintf_cb)(int c, void *ctx); +#define CONFIG_CBPRINTF_FULL_INTEGRAL + +#ifdef CONFIG_CBPRINTF_FULL_INTEGRAL + typedef intmax_t int_value_type; + typedef uintmax_t uint_value_type; + #define DIGITS_BUFLEN 21 +#else + typedef s32 int_value_type; + typedef u32 uint_value_type; + #define DIGITS_BUFLEN 10 +#endif + +#define ALPHA(fmt) (((fmt)&0x60) - '0' - 10 + 1) + +struct str_context +{ + char *str; + int max; + int count; +}; + +static int char_out(int c, void *ctx_p) +{ + struct str_context *ctx = ctx_p; + + ctx->count++; + OutByte((s8)c); + return 1; +} + +/* Convert value to string, storing characters downwards */ +static inline int convert_value(uint_value_type num, unsigned int base, + unsigned int alpha, char *buftop) +{ + int i = 0; + + do + { + unsigned int c = num % base; + if (c >= 10) + { + c += alpha; + } + buftop[--i] = c + '0'; + num /= base; + } + while (num); + + return -i; +} + +#define OUTC(_c) \ + do \ + { \ + out((int)(_c), ctx); \ + count++; \ + } while (0) + +#define PAD_ZERO BIT(0) +#define PAD_TAIL BIT(1) + +/** + * @brief Printk internals + * + * See printk() for description. + * @param fmt Format string + * @param ap Variable parameters + * + * @return printed byte count if CONFIG_CBPRINTF_LIBC_SUBSTS is set + */ +int cbvprintf(cbprintf_cb out, void *ctx, const char *fmt, va_list ap) +{ + size_t count = 0; + char buf[DIGITS_BUFLEN]; + char *prefix, *data; + int min_width, precision, data_len; + char padding_mode, length_mod, special; + + /* we pre-increment in the loop afterwards */ + fmt--; + +start: + while (*++fmt != '%') + { + if (*fmt == '\0') + { + return count; + } + OUTC(*fmt); + } + + min_width = -1; + precision = -1; + prefix = ""; + padding_mode = 0; + length_mod = 0; + special = 0; + + for (fmt++;; fmt++) + { + switch (*fmt) + { + case 0: + return count; + + case '%': + OUTC('%'); + goto start; + + case '-': + padding_mode = PAD_TAIL; + continue; + + case '.': + precision = 0; + padding_mode &= (char)~PAD_ZERO; + continue; + + case '0': + if (min_width < 0 && precision < 0 && !padding_mode) + { + padding_mode = PAD_ZERO; + continue; + } + __fallthrough; + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (precision >= 0) + { + precision = 10 * precision + *fmt - '0'; + } + else + { + if (min_width < 0) + { + min_width = 0; + } + min_width = 10 * min_width + *fmt - '0'; + } + continue; + + case '*': + if (precision >= 0) + { + precision = va_arg(ap, int); + } + else + { + min_width = va_arg(ap, int); + if (min_width < 0) + { + min_width = -min_width; + padding_mode = PAD_TAIL; + } + } + continue; + + case '+': + case ' ': + case '#': + special = *fmt; + continue; + + case 'h': + case 'l': + case 'z': + if (*fmt == 'h' && length_mod == 'h') + { + length_mod = 'H'; + } + else if (*fmt == 'l' && length_mod == 'l') + { + length_mod = 'L'; + } + else if (length_mod == '\0') + { + length_mod = *fmt; + } + else + { + OUTC('%'); + OUTC(*fmt); + goto start; + } + continue; + + case 'd': + case 'i': + case 'u': + { + uint_value_type d; + + if (length_mod == 'z') + { + d = va_arg(ap, ssize_t); + } + else if (length_mod == 'l') + { + d = va_arg(ap, long); + } + else if (length_mod == 'L') + { + long long lld = va_arg(ap, long long); + + if (sizeof(int_value_type) < 8U && + lld != (int_value_type)lld) + { + data = "ERR"; + data_len = 3; + precision = 0; + break; + } + d = (uint_value_type)lld; + } + else if (*fmt == 'u') + { + d = va_arg(ap, unsigned int); + } + else + { + d = va_arg(ap, int); + } + + if (*fmt != 'u' && (int_value_type)d < 0) + { + d = -d; + prefix = "-"; + min_width--; + } + else if (special == ' ') + { + prefix = " "; + min_width--; + } + else if (special == '+') + { + prefix = "+"; + min_width--; + } + else + { + ; + } + data_len = convert_value(d, 10, 0, buf + sizeof(buf)); + data = buf + sizeof(buf) - data_len; + break; + } + + case 'p': + case 'x': + case 'X': + { + uint_value_type x; + + if (*fmt == 'p') + { + x = (uintptr_t)va_arg(ap, void *); + if (x == (uint_value_type)0) + { + data = "(nil)"; + data_len = 5; + precision = 0; + break; + } + special = '#'; + } + else if (length_mod == 'l') + { + x = va_arg(ap, unsigned long); + } + else if (length_mod == 'L') + { + x = va_arg(ap, unsigned long long); + } + else + { + x = va_arg(ap, unsigned int); + } + if (special == '#') + { + prefix = (*fmt & 0x20) ? "0x" : "0x"; + min_width -= 2; + } + data_len = convert_value(x, 16, ALPHA(*fmt), + buf + sizeof(buf)); + data = buf + sizeof(buf) - data_len; + break; + } + + case 's': + { + data = va_arg(ap, char *); + data_len = strlen(data); + if (precision >= 0 && data_len > precision) + { + data_len = precision; + } + precision = 0; + break; + } + + case 'c': + { + int c = va_arg(ap, int); + + buf[0] = c; + data = buf; + data_len = 1; + precision = 0; + break; + } + + default: + OUTC('%'); + OUTC(*fmt); + goto start; + } + + if (precision < 0 && (padding_mode & PAD_ZERO)) + { + precision = min_width; + } + min_width -= data_len; + precision -= data_len; + if (precision > 0) + { + min_width -= precision; + } + + if (!(padding_mode & PAD_TAIL)) + { + while (--min_width >= 0) + { + OUTC(' '); + } + } + while (*prefix) + { + OUTC(*prefix++); + } + while (--precision >= 0) + { + OUTC('0'); + } + while (--data_len >= 0) + { + OUTC(*data++); + } + while (--min_width >= 0) + { + OUTC(' '); + } + + goto start; + } +} + +static int f_vprintf(const char *restrict format, va_list vargs) +{ + struct str_context ctx = {0}; + cbvprintf(char_out, &ctx, format, vargs); +} + +void f_printk(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + f_vprintf(fmt, ap); + va_end(ap); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/common/fprintk.h b/bsp/phytium/libraries/standalone/common/fprintk.h new file mode 100644 index 0000000000..907b841ca7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fprintk.h @@ -0,0 +1,38 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fprintk.h + * Date: 2021-08-23 16:24:02 + * LastEditTime: 2022-02-17 18:01:35 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef COMMON_F_PRINTK_H +#define COMMON_F_PRINTK_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +int f_printk(const char *format, ...) ; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/common/fsleep.h b/bsp/phytium/libraries/standalone/common/fsleep.h new file mode 100644 index 0000000000..f9d29c201e --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/fsleep.h @@ -0,0 +1,34 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsleep.h + * Date: 2021-05-28 08:48:40 + * LastEditTime: 2022-02-17 18:02:51 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef _BSP_ARCH_ARMV8_FSLEEP_H +#define _BSP_ARCH_ARMV8_FSLEEP_H + +#include "ftypes.h" + +u32 fsleep_seconds(u32 seconds); /* 按秒延迟 */ +u32 fsleep_millisec(u32 mseconds); /* 按毫秒延迟 */ +u32 fsleep_microsec(u32 useconds); /* 按微秒延迟 */ + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/common/ftypes.h b/bsp/phytium/libraries/standalone/common/ftypes.h new file mode 100644 index 0000000000..aa097b3ade --- /dev/null +++ b/bsp/phytium/libraries/standalone/common/ftypes.h @@ -0,0 +1,95 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ftypes.h + * Date: 2021-05-27 13:30:03 + * LastEditTime: 2022-02-18 08:24:15 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef _BSP_COMMON_FT_TYPE_H +#define _BSP_COMMON_FT_TYPE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include +#include + +#define FT_COMPONENT_IS_READY 0x11111111U +#define FT_COMPONENT_IS_STARTED 0x22222222U + +typedef uint8_t u8; /* unsigned 8-bit */ +typedef char s8; /* signed 8-bit */ +typedef uint16_t u16; /* unsigned 16-bit */ +typedef short s16; /* signed 16-bit */ +typedef uint32_t u32; /* unsigned 32-bit */ +typedef int32_t s32; /* signed 32-bit */ +typedef uint64_t u64; /* unsigned 64-bit */ +typedef int64_t s64; /* unsigned */ +typedef float f32; /* 32-bit floating point */ +typedef double f64; /* 64-bit double precision FP */ +typedef unsigned long boolean; /* boolean */ +typedef uint64_t _time_t; +typedef size_t fsize_t; + +typedef intptr_t intptr; /* intptr_t是为了跨平台,其长度总是所在平台的位数,所以用来存放地址。 */ +typedef uintptr_t uintptr; +typedef ptrdiff_t ptrdiff; + +#ifdef __aarch64__ +typedef u64 tick_t; +#else +typedef u32 tick_t; +#endif + +/** @}*/ +#if !defined(LONG) || !defined(ULONG) +typedef long LONG; +typedef unsigned long ULONG; +#endif + +#define ULONG64_HI_MASK 0xFFFFFFFF00000000U +#define ULONG64_LO_MASK ~ULONG64_HI_MASK + +#ifndef TRUE +#define TRUE 1U +#endif + +#ifndef FALSE +#define FALSE 0U +#endif + +#ifndef NULL +#define NULL 0U +#endif + +#define _INLINE inline +#define _WEAK __attribute__((weak)) + +typedef void (*FIrqHandler)(void *InstancePtr); + +typedef void (*FExceptionHandler)(void *InstancePtr); + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/doc/ChangeLog.md b/bsp/phytium/libraries/standalone/doc/ChangeLog.md new file mode 100644 index 0000000000..376e459c68 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/ChangeLog.md @@ -0,0 +1,1431 @@ +# Phytium Standalone SDK 2022-10-26 ChangeLog + +Change Log sinc 2022-10-21 + +## aarch + +- rename system file with f prefix + +## board + +- rename system file with f prefix + +## common + +- rename system file with f prefix + +## board + +- adopt to new system header file + +## tools + +- add script to export rt-trhead BSP from SDK +- adjust Kconfig blank line to support scons + +# Phytium Standalone SDK 2022-10-21 ChangeLog + +Change Log sinc 2022-10-15 + +## drivers + +- Optimize sata +- Optimize can + +## third-party + +- Adapt fatfs to e2000 demo board for sata + +## Phytium Standalone SDK 2022-10-10 ChangeLog + +Change Log since 2022-9-26 + +## drivers + +- support fxhci in E2000 +- remove support of fxhci with PCIe in FT2000/4 + +## example + +- add hid support for fxhci_host, demo keyboard input + +## third-party + +- remove usb disk port in fatfs + +## Phytium Standalone SDK 2022-9-26 ChangeLog + +Change Log since 2022-9-23 + +## drivers + +- Move some function from fpl011.c to fpl011_options.c +- Add RTS CTS DDMA option define + +## example + +- add flow control and ddma example + +# Phytium Standalone SDK 2022-9-23 ChangeLog + +Change Log since 2022-9-15 + +## drivers + +- Optimize can drivers interface adapter freertos + +## example + +- Modify can test example, add auto loopback test + +# Phytium Standalone SDK 2022-9-7 ChangeLog + +Change Log since 2022-08-30 + +## drivers + +- Add qspi boya flash quad read function +- Optimize qspi drivers interface adapter freertos +- Optimize sata drivers interface adapter freertos + +## example + +- Modify qspi, sfud, spiffs test example, add auto test +- Modify sata test example, add auto test + +Change Log since 2022-08-29 + +## drivers + +- repair timer_tacho error + +## example + +- Modify i2c test example, add auto test +- Modify timer_tacho test example, add auto test +- remove E2000 i2c_master_slave example +- move E2000 RTC example to i2c + +# Phytium Standalone SDK 2022-8-29 ChangeLog + +Change Log since 2022-08-24 + +## drivers + +- Add adc drivers interface adapter freertos + +## example + +- Modify adc test example, add auto test + + +# Phytium Standalone SDK 2022-8-18 ChangeLog + +Change Log since 2022-08-16 + +## drivers + +- Add pwm drivers interface adapter freertos + +## example + +- Modify pwm test example, add auto test + +# Phytium Standalone SDK 2022-8-11 ChangeLog + +Change Log since 2022-8-16 + +## common + +- fix generic timer tick bug +- fix early trace issue: extra operation for early trace call + +## drivers + +- delete spi poll-by-byte API and related code +- makeup FGpioGetPinIrqSourceType API +- fix uart compile issue + +## third-party + +- sdmmc: merge fsdmmc_irq and fsdmmc_poll +- sdmmc: fix csd issue, which is reversed in FT20004/D2000 +- sdmmc: remove cmd-23 for FT20004/D2000, since they do not support SD-3.0 +- fastfs-sd: compatible with sdmmc modifications + +## example + +- modify fspim_loopback, support FT20004/D2000/E2000 +- modify fgpio_test, simplify code implementation +- add fddma_spi, test ok in E2000 + +# Phytium Standalone SDK 2022-8-16 ChangeLog + +Change Log since 2022-08-11 + +## board/e2000/q + +- add E2000Q mio pin function,board support + +## example + +- Modify i2c fi2c_master_slave example to support e2000q,add e2000q default configs +- Modify serial example to support e2000q,add e2000q default configs +- Modify rtc rtc_ds1339 example to support e2000q,add e2000q default configs +- Modify timer timer_tacho example to support e2000q,add e2000q default configs + + +# Phytium Standalone SDK 2022-8-11 v0.3.1 ChangeLog + +Change Log since v0.3.0 + +## README +- add E2000D/S description + +# Phytium Standalone SDK 2022-8-5 v0.3.0 ChangeLog + +Change Log since 2022-08-04 + +## drivers + +- Add and restruct some drivers adapter e2000 interface + +## example + +- Add and restruct some test examples adapter e2000 interface +- Modify the example documentations and default configs + +## third-party + +- Restruct adapter e2000 + +# Phytium Standalone SDK 2022-08-04 ChangeLog + +Change Log since 2022-08-03 + +## example + +- Modify the delay interface function in the XMAC example + +# Phytium Standalone SDK 2022-08-04 ChangeLog + +Change Log since 2022-08-01 + +## common + +- add e2000d sata controller +- add can2.0 and canfd test choose config +- delete ddma and littlefs examples + +# Phytium Standalone SDK 2022-08-03 ChangeLog + +Change Log since 2022-08-02 + +## common + +- add e2000d some configuration for interrupt + +# Phytium Standalone SDK 2022-08-03 ChangeLog + +Change Log since 2022-08-02 + +## drivers + +- fix fgpio FGpioGetPinIrqSourceType bug + +# Phytium Standalone SDK 2022-08-02 ChangeLog + +Change Log since 2022-07-31 + +## example + +- fix tftp bug + +# Phytium Standalone SDK 2022-07-31 ChangeLog + +Change Log since 2022-07-30 + +## board + +- fix ROARSE and FRAC delay mis-typing, replace with ROUGH and DELICATE, for E2000 and D2000/FT2004 +- add shortcut API to support set delay and get delay + +## driver + +- remove is_busy flag from fspim +- fix cpol and cpha mistype in fspim +- fix register value overlapping in fspim +- simplify fgpio API FGpioGetPinIrqSourceType + +## third-party + +- support BY25Q32BS and BY25Q64BS in sfud + +# Phytium Standalone SDK 2022-07-30 ChangeLog + +Change Log since 2022-7-29 + +## driver + +- fix fnand bug +- fix fxmac bug + +## third-party + +- add lwip_port some user setting parameters + +## example + +- Modify the lwip_echo example +# Phytium Standalone SDK 2022-07-29 ChangeLog + +Change Log since 2022-07-18 + +# board + +- fix parameters pcie mem32 space, support for pcie-sata aarch32 read/write + +# driver + +- modify qspi, support spiffs read/write +- modify wdt, support get timeout remaining time +- fix pwm config, support pwm 0~15 channel configuration + +# third-party + +- fix sfud, spiffs, fatfs modules +# Phytium Standalone SDK 2022-07-27 ChangeLog + +Change Log since 2022-07-14 + +## board + +- fix parameters sdio clk hz + +## driver + +- modify fsdio, support DMA and PIO read/write + +## third-party + +- modify sdmmc, support eMMc + +# Phytium Standalone SDK 2022-07-14 ChangeLog + +Change Log since 2022-7-05 + +## driver + +- add fnand controler +- add fxmac controler + +## example + +- add fnand_example + +## third-party + +- Port the fnand controller to lwip + +# Phytium Standalone SDK 2022-07-13 ChangeLog + +Change Log since 2022-6-20 + +# board + +- modify e2000 iomux set function +- modify some parameters + +# driver + +- modify qspi read and write driver for E2000, add register port read and write data +- modify sata controller and pcie-sata read and write driver for E2000 +- modify can driver for E2000, support for can and canfd +- modify pwm driver for E2000 +- modify adc driver for E2000, support for adc0-0 +- modify wdt driver for E2000 + +# example + +- modify qspi norflash example +- modify sata controller read and write to support E2000 +- modify can send and receive example +- modify adc example to collect voltage + +# Phytium Standalone SDK 2022-07-12 ChangeLog + +Change Log since 2022-07-05 + +# driver + +- move spi dma function to fspim_dma +- modify gdma api + +# board + +- remove parameters of gdma1 + +# example + +- modify fgdma and fddma example + +# Phytium Standalone SDK 2022-07-05 ChangeLog + +Change Log since 2022-6-30 + +# board + +- modify e2000 fparameters_comm.h and add set mio function + +# driver + +- add fi2c configs and init things +- create Mio driver for E2000 +- modify uart configs to support E2000 + +# example + +- add RTC1339 example +- modify i2c/fi2c_master_slave to support E2000 +- modify serial/fpl011_test to support E2000 +- modify timer_tacho adapt to new iopad modifications + +# Phytium Standalone SDK 2022-06-30 ChangeLog + +Change Log since 2022-6-28 + +# board + +- modify GPIO parameters in FT2000/4 and D2000 +- add iopad configs for spi 0~3 + +# driver + +- fix bug that spi busy status mis-set in interrupt mode +- add cs-set function for E2000 + +# third-party + +- modify sfud fspim port to support cs-set + +# example + +- modify fspim_loopback and tested in E2000 +- modify spi_sfud and tested in E2000 +- modify littlefs_test and tested in E2000 +- modify spiffs_test and tested in E2000 + +# Phytium Standalone SDK 2022-06-28 ChangeLog + +Change Log since 2022-6-20 + +# board + +- merge common parameters / early uart implmenetation of E2000 D/Q/S +- implment all io pad definition +- add iopad function to set func, pull, drive strength at one call + +# driver + +- update fgpio for E2000 + + +# Phytium Standalone SDK 2022-06-20 ChangeLog + +Change Log since 2022-6-16 +## arch + +- fix aarch32 Bss clear bug + +# Phytium Standalone SDK 2022-6-16 v0.2.0 ChangeLog + +Change Log since 2022-5-30 + +## drivers + +- Restruct gmac driver +- adapt to freertos lwip function + +## example + +- Restruct lwip_echo example + +## third-party + +- modify lwip config + +# Phytium Standalone SDK 2022-06-15 ChangeLog + +Change Log since 2022-6-14 + +## drivers + +- add timer_tacho driver +- modified fi2c_g.c to support e2000 + +## example + +- add timer example +- add tacho example + +## board + +- Modify fparameters.h to support timer_tacho and i2c + +# Phytium Standalone SDK 2022-06-14 ChangeLog + +Change Log since 2022-6-10 + +## arch + +- Add aarch32/aarch64 trace uart in assembly +- Add trace stub function in bootup process + +## example + +- Add example to demo exception trap + +## board + +- Modify fparameters.h to support assembly + +# Phytium Standalone SDK 2022-6-09 ChangeLog + +Change Log since 2022-6-10 + +## drivers + +- Add nand driver + +## example + +- Add nand flash example + +## arch + +- clear HCR_EL2.TGE +- AARCH64 enable irq exception + +## board + +- FPinSetPull mistype + +## README + +- remove Linux arm aarch64 development environment + +# Phytium Standalone SDK 2022-6-10 ChangeLog + +Change Log since 2022-5-24 + +## drivers + +- Restruct SDIO driver + +## example + +- Delete fsdio_probe example +- Add fsdio_cmd example + +## third-party + +- port fsdio to sdmmc freamwork +- add shell title for E2000 D/Q/S +- add prompt info for building E2000 D/Q/S images + +# Phytium Standalone SDK 2022-5-24 ChangeLog + +Change Log since 2022-5-18 + +## drivers + +- Add Semaphore driver +- Restruct GDMA driver + +## example + +- Restruct GDMA async memcpy example +- Add Semaphore lock/unlock example + +## common + +- Change interrupt source trace to DEBUG level +- Fix memory-pool bug: not set is_ready flag when deinit memory-pool +- Add FASSERT_STATIC to check structure size + +# Phytium Standalone SDK 2022-5-18 ChangeLog + +Change Log since 2022-5-7 + +## drivers + +- Restruct can driver +- Add pwm driver to support E2000 +- Add adc driver to support E2000 + +## example + +- Add can send and recv test +- Add pwm test +- Add adc test + +## doc + +- Add fcan.md + +# Phytium Standalone SDK 2022-5-13 ChangeLog + + +Change Log since 2022-5-5 + +## drivers + +- Add DDMA driver +- Modify SPIM driver to support E2000 +- Modify GPIO driver to support E2000 + +## example + +- Add SPI + DDMA loopback test +- Modify SPI loopback test to support E2000 + +## common + +- Add interrupt source trace +- Skip l3 cache operations when it disabled + +## doc + +- Update code_convention.md +- Update PR check list + +# Phytium Standalone SDK 2022-5-5 ChangeLog + +Change Log since 2022-4-15 + +## drivers + +- Slave interrupt handle modified + +## example + +- Change the command interface +- Add virtual eeprom +- Simulate master-slave communication at D2000 + +# Phytium Standalone SDK 2022-4-22 ChangeLog + +Change Log since 2022-4-15 +## drivers + +- Restruct I2C driver +- modified master poll write read +- add master intr poll write read + +## example + +- Restruct fi2c_eeprom example +- Solve the problem of reading across pages +- complete eeprom page alignment + +# Phytium Standalone SDK 2022-4-20 ChangeLog + +Change Log since 2022-4-11 + +## drivers + +- Restruct gmac driver +- Restruct xmac driver + +## example + +- Restruct ipv4 test +- Add ipv4 dhcp test +- Add ipv6 test + +## third-party + +- Add mac lwip port layer to support gmac and xmac +- Restruct gmac and xmac lwip interface +# Phytium Standalone SDK 2022-4-15 ChangeLog + +Change Log since 2022-4-8 + +## drivers + +- Restruct GIC driver + +## common + +- Restruct Interrupt code + +## arch + +- aarch32/64 support for interrupt preemption + +# Phytium Standalone SDK 2022-4-14 ChangeLog + +Change Log since 2022-4-8 + +## drivers + +- support test mode in fspim +- support tx and rx run at the same transfer api call + +## example + +- add fspim loopback test +- add fspim sfud test +- add spiffs filesystem test +- add littlefs filesystem test + +## third-party + +- add spiffs +- add littlefs, support littlefs dry-run + +## common + +- modify the way debug trace to have src file + src line tag + +# Phytium Standalone SDK 2022-4-8 v0.1.17 ChangeLog + +Change Log since 2022-2-18 + +- update openamp function +- update assert method +- re-construct fgpio, support gpio interrupt +- re-construct qspi norflash and watchdog driver + +# Phytium Standalone SDK 2022-3-31 ChangeLog + +## drivers + +- Restruct watch dog driver, add some additional functions + +## example + +- Restruct example of wdt test +- Improve manual documentation + +# Phytium Standalone SDK 2022-3-28 ChangeLog + +## drivers + +- Restruct qspi norflash driver, add some additional functions +- Adapt to different norflash manufacturers + +## example + +- re-organize example of qspi test, broken down into peripheral and storage + + +# Phytium Standalone SDK 2022-3-25 ChangeLog + +Chang Log since 2022-3-18 + +## driver + +- re-construct fgpio, support gpio interrupt +- re-construct fioctrl and fiopad + +## example + +- add fgpio-irq to demo usage of gpio interrupt +- add fgpio-softpwm to demo generate pwm with gpio +- add fioctrl-test to demo usage of ioctrl +- add fiopad-test to demo usage of iopad + +## common + +- add e2000 s/d/q default configs +- support print source file and source code line in FT_DEBUG +- convert config item DON_T_BINARY_OUTPUT to OUTPUT_BINARY + +# Phytium Standalone SDK 2022-3-18 ChangeLog + +Chang Log since 2022-2-18 + +## script + +- Support SDK version +- Move uninstall.py to unsetup.py + +## common + +- Unify assert api with FASSERT and FASSERT_MSG + +## third-party + +- Letter-shell: add SHELL_EXPORT_EXIT_MSG and SHELL_EXPORT_EXIT_MSG to support exit msg print when return from cmd rountine + +## tools + +- Remove build_all_app and intergrate_test_app + +# Phytium Standalone SDK 2022-3-09 ChangeLog + +Change Log since 2022-2-18 + +## arch + +- Modified some parameters in the MMU and added FSetTlbAttributes interfaces + +## third-party + +- Add OpenAMP library + +## example + +- Add OpenAMP example + +# Phytium Standalone SDK 2022-2-18 v0.1.16 ChangeLog + +Change Log since 2022-2-15 + +- replace LICENSE with Phytium Public License 1.0 (PPL-1.0) +- update file COPYRIGHT declaration with PPL-1.0 + +# Phytium Standalone SDK 2022-2-15 ChangeLog + +Change Log since 2022-2-7 + +## drivers + +- add fusb driver +- add fxhci driver + +## example + +- add fxhci-pcie-usb example to support usb device discovery +- add fusbdisk example to port fatfs for usb mass storage device + +# Phytium Standalone SDK 2022-2-10 ChangeLog + +Change Log since 2021-02-7 + +## arch + +- Modifying Some variable definitions in cache + +## common + +- Modify the function interface in the _cpu.c document to change the core content not to respond when the work core does not support it + +- Fixing interrupt.c initialization problems + +## gicv3 + +- Modifying cpu interface processing of multi-core interfaces in gicv3 + +## example + +- Modifying the handling of multi-core function interfaces in Libmetal + +## board + +- Add a new cpu directory + +# Phytium Standalone SDK 2022-2-07 ChangeLog + +Change Log since 2021-12-10 + +## drivers + +- add sata driver +- add fpcie driver + +## example + +- add sata test example +- add sata fatfs test example +- add pcie probe test example + +# Phytium Standalone SDK 2021-12-10 v0.1.15 ChangeLog + +Change Log since 2021-12-07 + +## third-party + +- fix get ocr timeout in ft2004 +- rename assert and delay macro +- rename ymodem + +## example + +- unify example makefile setting + +# Phytium Standalone SDK 2021-12-07 ChangeLog + +Change Log since 2021-12-6 + +## third-party + +- add ymodem transfer + +## example + +- add rtc module test function + +# Phytium Standalone SDK 2021-12-6 ChangeLog + +Change Log since 2021-11-29 + +## drivers + +1. re-construct fsdio and fsdmmc + +## example + +1. add memory test example +2. add fsdio probe example +3. add fsdmmc probe example +4. add fsdmmc cmd example +5. add fsdmmc fatfs example + +## common + +1. add slink fslink_list.c +2. add memory pool fmemory_pool.c + +## configs + +1. update default configs for all platform + +## third-party + +1. re-construct sdmmc port in poll and irq +2. add tlfs to support fmemory_pool.c + +## script + +1. modify serial_trans.py to improve cmd-trans in D2000 + +# Phytium Standalone SDK 2021-11-29 ChangeLog + +Change Log since 2021-11-25 + +## arch + +1. Add stack initialization +2. Locate the final mode in SVC mode +3. Initialize the BSS and SBSS segments +4. Copy data to the RAM +5. Enable the FPU function +6. Fpu is pushed when irq is abnormal +7. Other exceptions are treated as error exceptions + +## ld + +1. Add stack parameter Settings for different exceptions +2. Rename variables in different sections + +## example + +1. Letter_shell test modifies the makefile + + +# Phytium Standalone SDK 2021-11-25 ChangeLog + +Change Log since v0.1.14 + +## third-party + +- add sfud qspi test +- restruct sfud_port.c, add spi and qspi probe + +## drivers + +- restruct qspi norflash driver + +## example + +- re-organize example of qspi test +- make spi and qspi compatible in sfud + +# Phytium Standalone SDK 2021-11-23 ChangeLog + +Change Log since v0.1.13 + +## third-party + +- add coremark 1.01 for core performace test +- add llcbench for cache performance test +- add memperf for memory performace test +- add unity-2.5.2 to support unit test + +## drivers + +- rename fxmac according to name convention +- update user interface of frtc + +## example + +- re-organize example with category, e.g. benchmark, eth +- add catche_bench、cormark_bench and memperf_bench + +## tools + +- add intergrate_test_app and unit_test_app to demo usage of two + +# Phytium Standalone SDK 2021-11-17 ChangeLog + +Change Log since v0.1.12 + +## aarch64/gcc + +- remodify boot.S +- remodify crt0.S +- remodify vector.S + +## aarch64 + +- remodify exception.c +- remodify mmu.c +- add l3cache.c + +## board + +- remodify parameters.c + +# Phytium Standalone SDK v0.1.12 ChangeLog + +Change Log since v0.1.11, 2021.11.15 + +## example + +- add fgmac link example +- add fgmac lwip echo-ping example +- add fgmac lwip tftp example + +## driver + +- re-construct fgmac driver + +## third-party + +- modify port of fgmac lwip +- add fatfs, port for ramdisk + +# Phytium Standalone SDK v0.1.11 ChangeLog + +Change Log since v0.1.10, 2021.11.9 + +## example + +- add fspi nor flash example + +## driver + +- re-construct fspim driver + +## script + +- add flash_boot.mk, support make flash monitor + +## doc + +- add fspim driver api reference +- add sfud reference + +# Phytium Standalone SDK v0.1.10 ChangeLog + +Change Log since v0.1.9, 2021.11.5 + +## example + +- add rtc driver and test example + +## driver + +- re-construct wdt drivers +- add rtc driver + +## doc + +- add wdt driver api reference +- add rtc driver api reference + +# Phytium Standalone SDK v0.1.9 ChangeLog + +Change Log since v0.1.8, 2021.11.1 + +## example + +- add uart test example + +## driver + +- re-construct uart fpl011 drivers + +## doc + +- add fpl011 driver api reference +- add uart test readme + +## arch + +- add L3 cache disable +- modify the savefloatRegister location +- add + +# Phytium Standalone SDK v0.1.8 ChangeLog + +Change Log since v0.1.7, 2021.11.1 + +## example + +- add i2c eeprom example +- add i2c slave example + +## driver + +- re-construct i2c drivers +- support i2c slave + +## tools + +- add test utility to build example images for all supported platform + +## script + +- add build_all.mk to support test utility +- support make ldconfig and make setconfig + +## doc + +- add i2c driver api refernce +- add i2c slave & i2c eeprom readme +- add driver template +- add more design figure *.dio + +## bug-fix + +- fix CONFIG_USE_LIBC bug, which is converted to CONFIG_USE_G_LIBC in all example + +# Phytium Standalone SDK v0.1.7 ChangeLog + +Change Log since v0.1.6, 2021.10.20 + +- re-organize readme and docs + +# Phytium Standalone SDK v0.1.6 ChangeLog + +Change Log since v0.1.5, 2021.10.19 + +## example + +- add project to demo usage of newlib + +## script + +- add `PHYTIUM_DEV_PATH` for all platforms +- install cross tool to `PHYTIUM_DEV_PATH` +- update GNU CC version to 10.3.1-2021.07 +- modify CC libc.a for printf issue +- merge newlib to CC tool + +# Phytium Standalone SDK v0.1.5 ChangeLog + +Change Log since v0.1.4, 2021.10.14 + +## example + +- add project template to support Windows10 + mingw64 developing + +## script + +- modify install.py to support Windows10 + mingw64 +- add Windows10 cmd script to access mingw64 shell and Windows tftpd tool +- modify compiler.mk to support Windows10 + mingw64 +- add uninstall.py to support uninstall sdk + +# Phytium Standalone SDK v0.1.4 ChangeLog + +Change Log since v0.1.3, 2021.10.13 + +## driver + +- add iomux for E2000 +- add nandflash driver for E2000 + +## third-party + +- add yaffs2 for ramsim + +## lib + +- Modify the standard system call implementation + +## common + +- add printf for trap functions + +# Phytium Standalone SDK v0.1.3 ChangeLog + +Change Log since v0.1.2, 2021.10.08 + +## drivers + +- modify sdmmc drivers for FT2000/4 and D2000 to adopt sdmmc cmd component +- add sdio driver for E2000 + +## example + +- add mmc cmds for overall_test example + +## third-party + +- modify letter shell to get reture result +- add sdmmc cmd component + +## script + +- add install.py as alternative install script + +# Phytium Standalone SDK v0.1.2 ChangeLog + +Change Log since v0.1.1, 2021.9.24 + +## drivers + +- modify gmac_dma driver adapting to freertos lwip + +# Phytium Standalone SDK v0.1.1 ChangeLog + +Change Log since v0.1.0 + +## drivers + +- support watchdog timer + +## baremetal/example + +- add wdt_test example + +# Phytium Standalone SDK v0.1.0 ChangeLog + +Change Log since v0.0.11 + +## drivers + +- support gicv3 init with multiple cores +- support watchdog timer + +## baremetal/example + +- add letter shell test to demo application of shell +- add libmetal test to demo core0 - core1 commuication with libmetal support + +## third-party + +- add letter shell 3.1 +- add libmetal 1.0.0 + +## tools + +- include elfio tools + +## script + +- support linkscript config with sdkconfig.h + +# Phytium Standalone SDK v0.0.11 ChangeLog +Change Log since v0.0.10 + +## drivers + +- add f_gmac for FT2000-4 and D2000 +- support generic timer tick +- unify api interface for cache operation + +## baremetal/example + +- add gmac_test example to support gmac 'recv intrrupt' +- add lwip_test example to support 'host ping' + +## third-party + +- port lwip 2.1.2 for FT2000-4 and D2000 with f_gmac + +# Phytium Standalone SDK v0.0.10 ChangeLog + +Change Log since v0.0.9 + +## drivers + +- add gdma for E2000 + +## baremetal/example + +- add gdma example for aarch32/aarch64 +- gdma example surpport direct and bdl mode + +# Phytium Standalone SDK v0.0.9 ChangeLog + +Change Log since v0.0.8 + +## drivers + +- add pcie for FT200-4 + +## board + +- merge D2000 board + +## baremetal/example + +- add pcie example for aarch32/aarch64 +- pcie example surpport dma and mmio + +# Phytium Standalone SDK v0.0.8 ChangeLog + +Change Log since v0.0.7 + +## board + +- support D2000 +- add D2000 AARCH32/AARCH64 deconfigs + +## drivers + +- add sdci for D2000/FT2000-4 +- add mci for E2000 (to do) +- fix timer & tacho review issues + +## make + +- support switch platform + +Change Log sinc v0.0.6 + +## board + +- add ft2004 io mux parameters + +## common + +- support delay sleep by ms and us + +## configs + +- add default configs for supported platform + +## drivers + +- add i2c drivers +- add qspi drivers +- add timer & tacho drivers + +## example + +- add i2c eeprom master example +- add qspi nor flash example +- add timer example for e2000 + +# Phytium Standalone SDK v0.0.6 ChangeLog + +Change Log sinc v0.0.5 + +## driver + +- add canfd +- xmac +- spi + +## baremetal/example + +- add can_test +- add spi_test + +# Phytium Standalone SDK v0.0.5 ChangeLog + +Change Log sinc v0.0.4 + +## BSP + +- add board to support platforms +- support iomux, gpio and eth drivers + +## Scripts + +- update install.sh + +## Others + +- add git attr to fix cr/lr issue + +# Phytium Standalone SDK v0.0.4 ChangeLog + +Change Log sinc v0.0.2 + +## BSP + +- support Rt-Thread 32 bit single and smp Mode +- Support Rt-Thread 64 bit single Mode +- 32bit , 64 bit baremetal support libc +- 32bit , 64 bit support fpu + +## baremetal/example + +- aarch32_math_test + +## tools + +- add sdkconfig.h header + +# Phytium Standalone SDK v0.0.2 ChangeLog + +Change Log sinc v0.0.1 + +## BSP + +- support SYS Mode for Freertos +- support OS defined Irq/Swi handler for FreeRTOS + +## Doc + +- add checklist for pre-release check +- update Readme + +Change Log since init + +## Baremetal + +### add aarch32 & aarch64 example + +- aarch32_hello_world: hello world run in ft2000-4/e2000 +- aarch32_qemu_debug: hello world and step debug in qemu +- aarch32_timer_irq: run with generic timer tick irq +- aarch32_cache_mmu_wr: run with cache (L1/L2/L3) and mmu enabled +- aarch32_uart_irq: run with uart tx and rx irq +- aarch64_uart_irq_send: run with uart tx and rx irq in aarch64 + +## BSP + +- support armv8 aarch32/aarch64 +- support platform FT2000-4/E2000/Qemu-AARCH32 +- support cache and mmu +- support irq, system trap +- support generic timer +- support assert and debug trace +- support early uart print during system init +- support system error coding + +## Lib + +- support c standard lib +- support c no standard lib +- add kconfiglib to support menuconfig + +## Make + +- add basic compile scripts, 'complier.mk' 'ld.mk' +- add compile info print script, 'buildinfo.mk' +- add menuconfig setting script, 'preconfig.mk' +- add source code export script, 'packsource.mk' + +## Scripts + +- add sdk install and register script, 'export.sh' +- add utility script diff --git a/bsp/phytium/libraries/standalone/doc/design/baremetal.dio b/bsp/phytium/libraries/standalone/doc/design/baremetal.dio new file mode 100644 index 0000000000..34341657ca --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/baremetal.dio @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/build.dio b/bsp/phytium/libraries/standalone/doc/design/build.dio new file mode 100644 index 0000000000..080a9d64b6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/build.dio @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/driver.dio b/bsp/phytium/libraries/standalone/doc/design/driver.dio new file mode 100644 index 0000000000..0c0205c4c5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/driver.dio @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/framework.dio b/bsp/phytium/libraries/standalone/doc/design/framework.dio new file mode 100644 index 0000000000..0e48de454e --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/framework.dio @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/freertos_system.dio b/bsp/phytium/libraries/standalone/doc/design/freertos_system.dio new file mode 100644 index 0000000000..ee395bec82 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/freertos_system.dio @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/freertos_system.png b/bsp/phytium/libraries/standalone/doc/design/freertos_system.png new file mode 100644 index 0000000000..ed6d47af0d Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/design/freertos_system.png differ diff --git a/bsp/phytium/libraries/standalone/doc/design/freertos_system_deps.dio b/bsp/phytium/libraries/standalone/doc/design/freertos_system_deps.dio new file mode 100644 index 0000000000..e1424158df --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/freertos_system_deps.dio @@ -0,0 +1,202 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/freertos_system_deps.png b/bsp/phytium/libraries/standalone/doc/design/freertos_system_deps.png new file mode 100644 index 0000000000..5e85f2ac14 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/design/freertos_system_deps.png differ diff --git a/bsp/phytium/libraries/standalone/doc/design/middleware.dio b/bsp/phytium/libraries/standalone/doc/design/middleware.dio new file mode 100644 index 0000000000..ecfe1e64b4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/middleware.dio @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/platform_test.dio b/bsp/phytium/libraries/standalone/doc/design/platform_test.dio new file mode 100644 index 0000000000..a557546310 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/platform_test.dio @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/system.dio b/bsp/phytium/libraries/standalone/doc/design/system.dio new file mode 100644 index 0000000000..1dc4317445 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/system.dio @@ -0,0 +1,253 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/system.png b/bsp/phytium/libraries/standalone/doc/design/system.png new file mode 100644 index 0000000000..a6919e5ff1 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/design/system.png differ diff --git a/bsp/phytium/libraries/standalone/doc/design/system_2.dio b/bsp/phytium/libraries/standalone/doc/design/system_2.dio new file mode 100644 index 0000000000..223e2bf0d6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/system_2.dio @@ -0,0 +1,181 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/system_2.png b/bsp/phytium/libraries/standalone/doc/design/system_2.png new file mode 100644 index 0000000000..33d0803e34 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/design/system_2.png differ diff --git a/bsp/phytium/libraries/standalone/doc/design/system_2_deps.dio b/bsp/phytium/libraries/standalone/doc/design/system_2_deps.dio new file mode 100644 index 0000000000..7e5258f8f9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/design/system_2_deps.dio @@ -0,0 +1,229 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/design/system_2_deps.png b/bsp/phytium/libraries/standalone/doc/design/system_2_deps.png new file mode 100644 index 0000000000..dbc5e89b2f Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/design/system_2_deps.png differ diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/foox_hw.c b/bsp/phytium/libraries/standalone/doc/driver_template/foox_hw.c new file mode 100644 index 0000000000..75fb743759 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/foox_hw.c @@ -0,0 +1,54 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: foox_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:47 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "foox_hw.h" +#include "fooxx.h" + + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +void FooxHwWrite(uintptr base, char byte) +{ + +} + +char FooxHwRead(uintptr base) +{ + +} + +void FooxxReset(Fooxx *instance_p) +{ + +} diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/foox_hw.h b/bsp/phytium/libraries/standalone/doc/driver_template/foox_hw.h new file mode 100644 index 0000000000..47bbfb4a1f --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/foox_hw.h @@ -0,0 +1,84 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: foox_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:52 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_XXXX_FOOXX_HW_H +#define DRIVERS_XXXX_FOOXX_HW_H + + +/* - 传入模块基地址,不能复杂结构体 +- hardware interface of device || low-level driver function prototypes + +- 包括驱动寄存器参数和low-level操作定义 +1. 定义寄存器偏移 +2. 对上提供该模块寄存器操作的接口 +3. 一些简单外设提供直接操作接口 +4. 可以定义一些状态的接口,用于响应驱动状态的变化 + +note: 本文件不能引用fooxx.h +*/ + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fparameters.h" +#include "fio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/** @name Register Map + * + * Register offsets from the base address of an SD device. + * @{ + */ + +#define FOOXX_XX_OFFSET + +/** @name FOOXX_XX_OFFSET Register + */ + +#define FOOXX_XX_STATE + + +#define FOOXX_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) +#define FOOXX_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)(reg_offset), (u32)(reg_value)) + + +/************************** Function Prototypes ******************************/ +void FooxHwWrite(uintptr base, char byte); + +char FooxHwRead(uintptr base); + +#ifdef __cplusplus +} +#endif + diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/foox_options.c b/bsp/phytium/libraries/standalone/doc/driver_template/foox_options.c new file mode 100644 index 0000000000..cd0ae66d34 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/foox_options.c @@ -0,0 +1,73 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: foox_options.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:58 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/* + - The implementation of the options functions for the driver. + - 用户选项实现 + 1. 速度参数配置 + 2. 工作模式参数 + 3. fifo功能 + 1. 深度 + 2. 使能 + - 用户常用的功能寄存器读写动作,建议通过option提供快捷方式 + +*/ + +/***************************** Include Files *********************************/ + +#include "fooxx.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + + + +u32 FXxxGetOptions(FXxx *instance_p) +{ + +} + +u32 FXxxSetOptions(FXxx *instance_p, u32 options) +{ + +} + +u32 FXxxSetData(FXxx *instance_p, void *data_struct) +{ + +} + +u32 FXxxGetOptions(FXxx *instance_p, void *data_struct) +{ + +} + + diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/foox_role.c b/bsp/phytium/libraries/standalone/doc/driver_template/foox_role.c new file mode 100644 index 0000000000..90960fc4f1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/foox_role.c @@ -0,0 +1,50 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: foox_role.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:03 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/* + - 一些驱动模块,直接操作硬件的I/O接口,无法实现有意义的操作,此时需要针对中间件或者用户使用习惯设计此模块 (i2c,nand,eth) + - 部分场景适用, 分角色的 I/O 操作 + - 此模块的函数原型,在fooxx.h 中声明一次,方便用户或者中间件层调用 + +*/ + + +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "foox_hw.h" +#include "fooxx.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/fooxx.c b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx.c new file mode 100644 index 0000000000..539688f246 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx.c @@ -0,0 +1,67 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fooxx.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "foox_hw.h" +#include "fooxx.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/* 此文件主要为了完成用户对外接口,用户可以使用这些接口直接开始工作 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/** + * @name: FooxxCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {Fooxx} *instance_p is a pointer to the driver instance. + * @param {FooxxConfig} *config_p is a reference to a structure containing information + * about a specific driver. + * @return SUCCESS if initialization was successful + * ERROR + */ +FError FooxxCfgInitialize(Fooxx *instance_p, FooxxConfig *config_p) +{ + +} + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/fooxx.h b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx.h new file mode 100644 index 0000000000..ad27bbaf05 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx.h @@ -0,0 +1,106 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fooxx.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:35 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_模块名_FOOXX_H +#define DRIVERS_模块名_FOOXX_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" + +/************************** Constant Definitions *****************************/ + +/* Configuration options */ +#define FOOXX_OPTION_XX + +/* Operational Mode */ + +#define FOOXX_OPER_MODE_XX + +/**************************** Type Definitions *******************************/ + +/** + * This typedef contains configuration information for the device. + */ +typedef struct +{ + u32 instance_id; /**< Device instance id */ + uintptr base_addr; /**< Device base address */ +} FooxxConfig; + +/** + * This typedef contains driver instance data. The user is required to allocate a + * variable of this type for every device in the system. A pointer + * to a variable of this type is then passed to the driver API functions. + */ +typedef struct +{ + FooxxConfig config; /**< Current active configs */ + u32 is_ready; /**< Device is initialized and ready */ +} Fooxx; /**< Device instance */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/** + * @name: FXxxLookupConfig + * @msg: Get the device instance default configure + * @return {*} + * @param {u32} instance_id + */ +const FooxxConfig *FXxxLookupConfig(u32 instance_id); + +/* + * @name: FooxxCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {Fooxx} *instance_p is a pointer to the driver instance. + * @param {FooxxConfig} *config_p is a reference to a structure containing information + * about a specific driver. + * @return SUCCESS if initialization was successful + * ERROR + */ +FError FooxxCfgInitialize(Fooxx *instance_p, const FooxxConfig *cofig_p); + +/** + * @name: FooxxDeInitialize + * @msg: DeInitialization function for the device instance + * @return {*} + * @param {Fooxx} *instance_p + */ +void FooxxDeInitialize(Fooxx *instance_p); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/fooxx_g.c b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx_g.c new file mode 100644 index 0000000000..f3a10eec57 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx_g.c @@ -0,0 +1,53 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fooxx_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:09 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/* - This file contains a configuration table that specifies the configuration +- 驱动全局变量定义,包括静态配置参数 */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fooxx.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +const FooxxConfig FOOXX_CONFIG_TBL[NUM] = +{ + { + .instance_id = 0, /* Id of device*/ + .base_address = FOOXX_BASE, + }, +}; + + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/doc/driver_template/fooxx_sinit.c b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx_sinit.c new file mode 100644 index 0000000000..fa31af0ae9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/driver_template/fooxx_sinit.c @@ -0,0 +1,61 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fooxx_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:15 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + + +/* - This file contains the implementation of driver's static initialization functionality. +- 驱动静态初始化 */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fooxx.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +extern const FooxxConfig FOOXX_CONFIG_TBL[NUM]; + +/************************** Function Prototypes ******************************/ +const FooxxConfig *FooxxLookupConfig(u32 instance_id) +{ + const FooxxConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)NUM; index++) + { + if (FOOXX_CONFIG_TBL[index].instance_id == instance_id) + { + ptr = &FOOXX_CONFIG_TBL[index]; + break; + } + } + + return (const FooxxConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/fig/Serial_inform.png b/bsp/phytium/libraries/standalone/doc/fig/Serial_inform.png new file mode 100644 index 0000000000..ea19d25db3 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/Serial_inform.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/add_path_for_win.png b/bsp/phytium/libraries/standalone/doc/fig/add_path_for_win.png new file mode 100644 index 0000000000..4299c540eb Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/add_path_for_win.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/admin_rights.png b/bsp/phytium/libraries/standalone/doc/fig/admin_rights.png new file mode 100644 index 0000000000..66a6320f6b Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/admin_rights.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/bin_show.png b/bsp/phytium/libraries/standalone/doc/fig/bin_show.png new file mode 100644 index 0000000000..a7ac6c10bb Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/bin_show.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/check_env_for_aarch64.png b/bsp/phytium/libraries/standalone/doc/fig/check_env_for_aarch64.png new file mode 100644 index 0000000000..6b02afe82d Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/check_env_for_aarch64.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/check_env_for_win.png b/bsp/phytium/libraries/standalone/doc/fig/check_env_for_win.png new file mode 100644 index 0000000000..fa1e3f6f5e Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/check_env_for_win.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/check_env_for_x86.png b/bsp/phytium/libraries/standalone/doc/fig/check_env_for_x86.png new file mode 100644 index 0000000000..26a7f2d2c8 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/check_env_for_x86.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/compiling.png b/bsp/phytium/libraries/standalone/doc/fig/compiling.png new file mode 100644 index 0000000000..d1ee3cef6b Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/compiling.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/config_tftp32.png b/bsp/phytium/libraries/standalone/doc/fig/config_tftp32.png new file mode 100644 index 0000000000..3e52a8d10b Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/config_tftp32.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/git_url.png b/bsp/phytium/libraries/standalone/doc/fig/git_url.png new file mode 100644 index 0000000000..93cc44497e Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/git_url.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/install_for_aarch64.png b/bsp/phytium/libraries/standalone/doc/fig/install_for_aarch64.png new file mode 100644 index 0000000000..d6d81a2cf7 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/install_for_aarch64.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/install_for_mingw.png b/bsp/phytium/libraries/standalone/doc/fig/install_for_mingw.png new file mode 100644 index 0000000000..1b7ff94d9b Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/install_for_mingw.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/install_for_x86.png b/bsp/phytium/libraries/standalone/doc/fig/install_for_x86.png new file mode 100644 index 0000000000..be52daa09b Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/install_for_x86.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/install_msys2.png b/bsp/phytium/libraries/standalone/doc/fig/install_msys2.png new file mode 100644 index 0000000000..9aa9105490 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/install_msys2.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/installing_msys2.png b/bsp/phytium/libraries/standalone/doc/fig/installing_msys2.png new file mode 100644 index 0000000000..d48d93a074 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/installing_msys2.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/ipv4_setting.png b/bsp/phytium/libraries/standalone/doc/fig/ipv4_setting.png new file mode 100644 index 0000000000..f18182064e Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/ipv4_setting.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/is_aarch64.png b/bsp/phytium/libraries/standalone/doc/fig/is_aarch64.png new file mode 100644 index 0000000000..7ff6724a89 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/is_aarch64.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/is_x86_64.png b/bsp/phytium/libraries/standalone/doc/fig/is_x86_64.png new file mode 100644 index 0000000000..1424e80a46 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/is_x86_64.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/kylin.png b/bsp/phytium/libraries/standalone/doc/fig/kylin.png new file mode 100644 index 0000000000..034448a821 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/kylin.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/letter_shell.png b/bsp/phytium/libraries/standalone/doc/fig/letter_shell.png new file mode 100644 index 0000000000..1c36452e7e Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/letter_shell.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/linux.png b/bsp/phytium/libraries/standalone/doc/fig/linux.png new file mode 100644 index 0000000000..a9e7c11a6a Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/linux.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/load_image.png b/bsp/phytium/libraries/standalone/doc/fig/load_image.png new file mode 100644 index 0000000000..83a6ee5470 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/load_image.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/setup_aarch64_dev.png b/bsp/phytium/libraries/standalone/doc/fig/setup_aarch64_dev.png new file mode 100644 index 0000000000..f9775e8520 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/setup_aarch64_dev.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/setup_win.png b/bsp/phytium/libraries/standalone/doc/fig/setup_win.png new file mode 100644 index 0000000000..5b287cf745 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/setup_win.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/setup_x86_dev.png b/bsp/phytium/libraries/standalone/doc/fig/setup_x86_dev.png new file mode 100644 index 0000000000..f9775e8520 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/setup_x86_dev.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/tftp32_srv.png b/bsp/phytium/libraries/standalone/doc/fig/tftp32_srv.png new file mode 100644 index 0000000000..6fedb850f4 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/tftp32_srv.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/uncompress_for_x86.png b/bsp/phytium/libraries/standalone/doc/fig/uncompress_for_x86.png new file mode 100644 index 0000000000..9a4f434237 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/uncompress_for_x86.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/update_packman.png b/bsp/phytium/libraries/standalone/doc/fig/update_packman.png new file mode 100644 index 0000000000..13566d39f7 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/update_packman.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/windows.png b/bsp/phytium/libraries/standalone/doc/fig/windows.png new file mode 100644 index 0000000000..4389fb08c7 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/windows.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/wsl_l_v.png b/bsp/phytium/libraries/standalone/doc/fig/wsl_l_v.png new file mode 100644 index 0000000000..a6def1b048 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/wsl_l_v.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/wsl_make_success.png b/bsp/phytium/libraries/standalone/doc/fig/wsl_make_success.png new file mode 100644 index 0000000000..3cf3f5281f Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/wsl_make_success.png differ diff --git a/bsp/phytium/libraries/standalone/doc/fig/wsl_teiminal.png b/bsp/phytium/libraries/standalone/doc/fig/wsl_teiminal.png new file mode 100644 index 0000000000..740ced10c9 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/fig/wsl_teiminal.png differ diff --git a/bsp/phytium/libraries/standalone/doc/reference/cpu/figs/NotUseDefaultConfig.png b/bsp/phytium/libraries/standalone/doc/reference/cpu/figs/NotUseDefaultConfig.png new file mode 100644 index 0000000000..bb48e1143d Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/reference/cpu/figs/NotUseDefaultConfig.png differ diff --git a/bsp/phytium/libraries/standalone/doc/reference/cpu/figs/UseDefaultConfig.png b/bsp/phytium/libraries/standalone/doc/reference/cpu/figs/UseDefaultConfig.png new file mode 100644 index 0000000000..b05944de3e Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/reference/cpu/figs/UseDefaultConfig.png differ diff --git a/bsp/phytium/libraries/standalone/doc/reference/cpu/interrupt.md b/bsp/phytium/libraries/standalone/doc/reference/cpu/interrupt.md new file mode 100644 index 0000000000..cb5360de7f --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/cpu/interrupt.md @@ -0,0 +1,442 @@ + + +# interrupt + +## 1概述 + +此处提到的中断,主要是面向与Armv8 架构中异步异常IRQ 这个中断这个概念进行对齐,本模块主要为开发者提供软件层面管理中断相关接口,具体实现了以下这些特性: +1.基于中断id 的开关功能 +2.中断生命周期中需要使用到的,模式切换函数。(sdk 自动调用,一般不需要开发者操作) +3.核间中断触发接口 +4.中断优先级相关接口(优先级设置、优先级掩码、优先级抢占分组设置) +5.提供两种角色选择初始化中断 + +## 2驱动功能 + +驱动组成由以下所示 +. +├── finterrupt.c +└── finterrupt.h + +为用户提供两种初始化中断的方式: +1.不使用默认初始化的方式,在参数配置项选择“Not use default interrupt configuration”,参数配置如下: + +![](./figs/NotUseDefaultConfig.png) + +用户在这种模式下手动编写初始化代码,具体可以参考 /baremetal/example/peripheral/gic/fgic_test 下例程 + +2.使用默认初始化的方式,此时默认以CORE0 作为主核,默认会初始化中断驱动中的所有组件,非0核 将只会初始化与多核特性相关的部分组件。具体配置如下: + +![](./figs/UseDefaultConfig.png) + +## 3数据结构 + +``` +typedef void (*IrqHandler)(s32 vector, void *param); /* IRQ 中断回调函数的类型 */ + +``` + +``` +struct IrqDesc +{ + IrqHandler handler; /* IRQ 中断回调函数的指针 */ + void *param; /* IRQ 中断回调函数的变量 */ +}; +``` + + +``` +#define INTERRUPT_CPU_ALL_SELECT 0xffffffffffffffffULL /* 当进行核间,发送给所有核心时需要用到的参数 */ +#define INTERRUPT_CPU_TARGET_ALL_SET 0xffffffffUL /* 设置SPI 中断亲和度时,此值默认SPI 中断发送给所有人 */ + +#define IRQ_MODE_TRIG_LEVEL (0x00) /* Trigger: level triggered interrupt */ +#define IRQ_MODE_TRIG_EDGE (0x01) /* Trigger: edge triggered interrupt */ +``` + +``` +typedef enum +{ + INTERRUPT_ROLE_MASTER = 0 , /* 作为主核模式进行中断初始化,会初始化中断驱动中的所有组件 */ + INTERRUPT_ROLE_SLAVE, /* 作为从核模式进行中断初始化,会初始化与多核特性相关的部分组件 */ +}INTERRUPT_ROLE_SELECT; /* 此枚举应用于手动初始化中断的接口中 */ +``` + +``` +#define IRQ_GROUP_PRIORITY_3 3 /* group priority valid mask is bit[7:3],subpriority valid mask is bit[4:0] */ +#define IRQ_GROUP_PRIORITY_4 4 /* group priority valid mask is bit[7:4],subpriority valid mask is bit[3:0] */ +#define IRQ_GROUP_PRIORITY_5 5 /* group priority valid mask is bit[7:5],subpriority valid mask is bit[4:0] */ +#define IRQ_GROUP_PRIORITY_6 6 /* group priority valid mask is bit[7:6],subpriority valid mask is bit[5:0] */ +#define IRQ_GROUP_PRIORITY_7 7 /* group priority valid mask is bit[7],subpriority valid mask is bit[6:0] */ +``` + +IRQ_GROUP_PRIORITY_* 用于定义组优先级的有效位。 当存在抢占中断时,group priority 为抢占优先级,subpriority 为子优先级,如果某个中断的组优先级的值比当前正在运行中断的组优先级要小,则此中断将会抢占当前运行的优先级 。 + +``` +#define IRQ_PRIORITY_VALUE_0 0 +#define IRQ_PRIORITY_VALUE_1 0x10 +#define IRQ_PRIORITY_VALUE_2 0x20 +#define IRQ_PRIORITY_VALUE_3 0x30 +#define IRQ_PRIORITY_VALUE_4 0x40 +#define IRQ_PRIORITY_VALUE_5 0x50 +#define IRQ_PRIORITY_VALUE_6 0x60 +#define IRQ_PRIORITY_VALUE_7 0x70 +#define IRQ_PRIORITY_VALUE_8 0x80 +#define IRQ_PRIORITY_VALUE_9 0x90 +#define IRQ_PRIORITY_VALUE_10 0xa0 +#define IRQ_PRIORITY_VALUE_11 0xb0 +#define IRQ_PRIORITY_VALUE_12 0xc0 +#define IRQ_PRIORITY_VALUE_13 0xe0 +#define IRQ_PRIORITY_VALUE_14 0xf0 +``` + +IRQ_PRIORITY_VALUE_* 中断优先级一共支持以上这16个挡位,优先级的值越低优先级越高。 + +``` +#define IRQ_PRIORITY_MASK_0 0 +#define IRQ_PRIORITY_MASK_1 0x10 +#define IRQ_PRIORITY_MASK_2 0x20 +#define IRQ_PRIORITY_MASK_3 0x30 +#define IRQ_PRIORITY_MASK_4 0x40 +#define IRQ_PRIORITY_MASK_5 0x50 +#define IRQ_PRIORITY_MASK_6 0x60 +#define IRQ_PRIORITY_MASK_7 0x70 +#define IRQ_PRIORITY_MASK_8 0x80 +#define IRQ_PRIORITY_MASK_9 0x90 +#define IRQ_PRIORITY_MASK_10 0xa0 +#define IRQ_PRIORITY_MASK_11 0xb0 +#define IRQ_PRIORITY_MASK_12 0xc0 +#define IRQ_PRIORITY_MASK_13 0xe0 +#define IRQ_PRIORITY_MASK_14 0xf0 +``` + +IRQ_PRIORITY_MASK_* 中断优先级掩码一共支持以上这16个挡位,当设置掩码之后,中断优先级的值必须比此值小,才能被CPU进行响应 + +## 4错误码定义 + +#define FINT_SET_TARGET_ERR /* 涉及到CPU id 的配置时,CPU 不具有此ID 信息 */ +#define FINT_INT_NUM_NOT_FIT /* 使用中断号不符合当前实际情况 */ + + +## 5应用示例 +/baremetal/example/peripheral/gic/fgic_test gic与interrupt 特性例程 + + +## 6API使用步骤 + +1. 初始化中断模块,根据当前使用此核心角色的定位(主核、从核),进行初始化 + +``` +InterruptInit(&interrupt_instance,INTERRUPT_DRV_INTS_ID,INTERRUPT_ROLE_MASTER); +``` + +2. 全局设置组优先级 ,此接口影响中断嵌套过程中的抢占优先级有效位 + +``` +InterruptSetPriorityGroupBits(IRQ_GROUP_PRIORITY_*); +``` + +3. 全局设置中断优先级掩码,此参数设置之后,CPU响应中断优先级的值必须比此值小 + +``` +InterruptSetPriorityMask(IRQ_PRIORITY_MASK_*); +``` + +4. 设置具体中断的优先级。此优先级由抢占优先级与子优先级组成,具体优先级的划分由 InterruptSetPriorityGroupBits 决定。 + +``` +InterruptSetPriority(INT_NUM,priority); +``` + +5. 设置中断路由至特定CPU + +``` +InterruptSetTargetCpus(INT_NUM,CPU_ID) +``` + +6. 中断回调函数注册,当中断事件出现时,回调此注册函数 + +``` +InterruptInstall(INT_NUM,int_handler,int_args,"int_name") +``` + +7. 使能具体中断号的中断 + +``` +InterruptUmask(INT_NUM) +``` + +8. 如果是使用核间中断,使用以下接口进行触发 + +``` +InterruptCoreInterSend(INT_NUM,CPU_MASK) +``` + +9. 关闭具体中断号的中断 + +``` +InterruptMask(INT_NUM) +``` + +## 7API介绍 + +### 1. InterruptInit + + +``` +void InterruptInit(InterruptDrvType * int_driver_p,u32 instance_id,INTERRUPT_ROLE_SELECT role_select) +``` + +#### 介绍 +初始化中断模块的接口函数 + +#### 参数 +- InterruptDrvType * int_driver_p : 指向中断驱动实例的指针 +- u32 instance_id: 驱动实例的标号 +- INTERRUPT_ROLE_SELECT role_select :初始化中断接口时的角色选择。INTERRUPT_ROLE_MASTER 作为主核角色,INTERRUPT_ROLE_SLAVE 作为从核角色。具体特点参照数据结构中的描述 + +#### 返回 +无 + +### 2. InterruptMask + +``` +void InterruptMask(int int_id) +``` + +#### 介绍 +基于中断ID关闭对应的中断 + +#### 参数 +- int int_id :中断的id 编号 + +#### 返回 +无 + +### 3. InterruptUmask + +``` +void InterruptUmask(int int_id) +``` + +#### 介绍 +基于中断ID开启对应的中断 + +#### 参数 +- int int_id :中断的id 编号 + +#### 返回 +无 + +### 4. InterruptSetTargetCpus + +``` +FError InterruptSetTargetCpus(int int_id,u32 cpu_id) +``` + +#### 介绍 +将中断路由给特定的CPU,或者路由给所有的CPU + +#### 参数 +- int int_id :中断的id 编号 ,中断优先级范围为 32-1019 +- u32 cpu_id : 需要路由给CPU的编号,如果值为INTERRUPT_CPU_TARGET_ALL_SET 则路由给芯片中所有可以接收此中断的CPU + +#### 返回 +FError FINT_SUCCESS:设置成功,FINT_INT_NUM_NOT_FIT:使用中断号不符合当前实际情况 ,FINT_SET_TARGET_ERR: 涉及到CPU id 的配置时,CPU 不具有此ID 信息 + +### 5. InterruptGetTargetCpus + +``` +FError InterruptGetTargetCpus(int int_id,u32 *cpu_p) +``` + +#### 介绍 +基于中断ID 获取中断的路由信息 + +#### 参数 +- int int_id :中断的id 编号 +- u32 *cpu_p : 它的值为:需要路由给CPU的编号,如果值为INTERRUPT_CPU_TARGET_ALL_SET 则路由给芯片中所有可以接收此中断的CPU + +#### 返回 +FError FINT_SUCCESS:设置成功,FINT_INT_NUM_NOT_FIT:使用中断号不符合当前实际情况 ,FINT_SET_TARGET_ERR: 涉及到CPU id 的配置时,CPU 不具有此ID 信息 + +### 6. InterruptSetTrigerMode + +``` +void InterruptSetTrigerMode(int int_id, unsigned int mode) +``` + +#### 介绍 +基于中断ID 设置中断的触发方式 + +#### 参数 +- int int_id :中断的id 编号 +- unsigned int mode : IRQ_MODE_TRIG_LEVEL :(0x00) /* Trigger: level triggered interrupt */ +- IRQ_MODE_TRIG_EDGE :(0x01) /* Trigger: edge triggered interrupt */ + +#### 返回 +无 + +### 7. InterruptGetTrigerMode + +``` +unsigned int InterruptGetTrigerMode(int int_id) +``` + +#### 介绍 +基于中断ID 获取中断的触发方式 + +#### 参数 +- int int_id :中断的id 编号 + +#### 返回 +- unsigned int mode : IRQ_MODE_TRIG_LEVEL :(0x00) /* Trigger: level triggered interrupt */ +- IRQ_MODE_TRIG_EDGE :(0x01) /* Trigger: edge triggered interrupt */ + +### 8. InterruptSetPriority + +``` +void InterruptSetPriority(int int_id, unsigned int priority) +``` + +#### 介绍 +基于中断ID 设置中断的触发方式 + +#### 参数 +- int int_id :中断的id 编号 +- unsigned int priority :中断优先级的值 ,采用IRQ_PRIORITY_VALUE_*的值作为输入 + +#### 返回 +无 + +### 9. InterruptGetPriority + +``` + unsigned int InterruptGetPriority(int int_id) +``` + +#### 介绍 +基于中断ID获取中断的触发方式 + +#### 参数 +- int int_id :中断的id 编号 +- unsigned int priority :中断优先级的值 + +#### 返回 +无 + +### 10. InterruptSetPriorityMask + +``` +void InterruptSetPriorityMask(unsigned int priority) +``` + +#### 介绍 +设置中断优先级掩码 + +#### 参数 +- unsigned int priority :中断掩码值,当设置此掩码之后,各个中断优先级的值必须小于此值,才能被CPU 承认,并且转为激活态 。采用IRQ_PRIORITY_MASK_* 参数作为输入 + +#### 返回 +无 + +### 11. InterruptGetPriorityMask + +``` +void InterruptGetPriorityMask(void) +``` + +#### 介绍 +获取中断优先级掩码 + +#### 参数 + +#### 返回 +- unsigned int priority :中断掩码值,当设置此掩码之后,各个中断优先级的值必须小于此值,才能被CPU 承认,并且转为激活态 + +### 12. InterruptSetPriorityGroupBits + +``` +void InterruptSetPriorityGroupBits(unsigned int bits) +``` + +#### 介绍 +设置中断优先级分组位 + +#### 参数 +- unsigned int bits :该字段的值控制如何将8位中断优先级字段拆分为组优先级字段与子优先级字段,采用IRQ_GROUP_PRIORITY_*参数作为输入。 分组关系如下: + * |bits 取值 ----------------0-------1--------2------3-------4------5-------6-------7 + * |组 优先级有效值取值------[---]----[7:1]---[7:2]--[7:3]---[7:4]--[7:5]--[7:6]---[7] + * |子 优先级有效值取值------[---]-----[0]----[1:0]--[2:0]---[3:0]---[4:0]--[5:0]--[6:0] + +#### 返回 +无 + +### 13. InterruptInstall + +``` +IrqHandler InterruptInstall(int int_id, IrqHandler handler,void *param, const char *name) +``` + +#### 介绍 +本函数将自定义的中断回调函数与回调参数注册至对应中断id数据结构中 + +#### 参数 +- int int_id:中断的id 编号 +- IrqHandler handler:中断回调函数 +- void *param:中断回调参数 +- const char *name:中断函数的命名 + +#### 返回 +无 + +### 14. InterruptCoreInterSend + +``` +void InterruptCoreInterSend(int ipi_vector, u64 cpu_mask) +``` + +#### 介绍 +核心间中断触发函数 + +#### 参数 +- int int_id:中断的id 编号 ,中断范围 0~15 +- u64 cpu_mask:cpu_mask表示每一位代表所选CPU,例如,0x3代表core0和CORE1。 + +#### 返回 +无 + +### 15. InterruptEarlyInit + +``` +void InterruptEarlyInit(void) +``` + +#### 介绍 +中断提前初始化函数,此函数一般在汇编代码时被调用,当用户设置默认初始化模式时,本函数将会使用CORE0为主核心并且初始化中断驱动中所有组件,其他CORE为从属核心将初始化中断驱动中必备的组件。 + +#### 参数 +无 + +#### 返回 +无 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/cpu/mmu.md b/bsp/phytium/libraries/standalone/doc/reference/cpu/mmu.md new file mode 100644 index 0000000000..d7389a32df --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/cpu/mmu.md @@ -0,0 +1,98 @@ + + +# MMU + +## 1. 概述 + +- 虚拟内存系统(VMSA)提供了一套内存管理单元(MMU), 它控制着地址转换、访问权限和内存属性的确定和检查。 + +- 地址转换过程将CPU使用的虚拟地址(VAs)映射到物理内存系统的物理地址(PAs)上。 + +- 在本SDK中 aarch32 state 采用 section 格式的转换表 +- 在本SDK中 aarch64 state 采用 4KB 粒度 格式的转换表 + +## 2. 功能 + +- MMU功能支持用户根据需要修改MMU表的默认内存属性。 + +## 3. 配置方法 + +## 4. 应用示例 + +"baremetal/example/system/amp/libmetal_test" +"baremetal/example/system/amp/openamp" + +## 5. API参考 + + +### 5.1 用户定义 + + +/* 访问权限 */ +``` +#define MT_P_NA_U_NA /* higher Exception level access=NA, user=NA */ +#define MT_P_RW_U_NA /* higher Exception level access=RW, user=NA */ +#define MT_P_RW_U_RO /* higher Exception level access=RW, user=RO */ +#define MT_P_RW_U_RW /* higher Exception level access=RW, user=RW */ +#define MT_P_RO_U_NA /* higher Exception level access=RO, user=NA */ +#define MT_P_RO_U_RO /* higher Exception level access=RO, user=RO */ +``` + +/* 内存属性参数 */ +``` +#define MT_DEVICE_NGNRNE /* Device-nGnRnE , Outer Shareable */ +#define MT_DEVICE_NGNRE /* Device-nGnRE , Outer Shareable */ + +#define MT_NORMAL_WT /* Outer and Inner Write-Through, Read-Allocate No Write-Allocate , Outer Shareable */ + +#define MT_NORMAL_WB_WCN /* Outer and Inner Write-Back, Read-Allocate No Write-Allocate , Outer Shareable */ + +#define MT_NORMAL_NC /* Outer and Inner Non-cacheable , Outer Shareable , Outer Shareable */ +#define MT_NORMAL /* Outer and Inner Write-Back, Read-Allocate Write-Allocate , Outer Shareable , Outer Shareable */ + +``` + +### 5.2 用户API接口 + +- 此函数用于配置转换表中地址对应条目的内存属性与访问权限 + +```c +void FSetTlbAttributes(uintptr addr, fsize_t size, u32 attrib); +``` + + Note: + aarch32 state 采用 section 页表,由此addr 建议采用1MB 地址对齐,size 建议为MB的整数倍。 + aarch64 state 采用 4KB 粒度 页表,由此addr 建议采用4KB 地址对齐,size 建议为4KB的整数倍。 + + Input: + + - addr , 需要为内存区域设置属性与权限的起始地址 + + - size , 内存区域的范围 + + - attrib,指定内存区域的属性 ,内存属性的取值由 访问权限 与 内存属性参数 组成,具体类型参考 ### 5.1 用户定义 + + Return: + + - void diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fadc.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fadc.md new file mode 100644 index 0000000000..eaee72661c --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fadc.md @@ -0,0 +1,327 @@ +# FADC 驱动程序 + +## 1. 概述 + +ADC,Analog-to-Digital Converter的缩写,指模/数转换器或者模拟/数字转换器。是将连续变量的模拟信号转换为离散的数字信号的器件。真实世界的模拟信号,例如温度、压力、声音或者图像等,需要转换成更容易储存、处理和发射的数字形式。模/数转换器可以实现这个功能,典型的模拟数字转换器将模拟信号转换为表示一定比例电压值的数字信号。 + +## 2. 功能 + +adc控制器驱动提供了adc的控制访问方法, +- 初始化adc控制器,配置相关参数,如转换模式,通道使能等 +- 读adc转换数据 +- 转换完成与结果阈值的中断触发 + +驱动相关的源文件包括 +``` +. +├── fadc_g.c +├── fadc_hw.c +├── fadc_hw.h +├── fadc_intr.c +├── fadc_sinit.c +├── fadc.c +└── fadc.h +``` + +## 3. 配置方法 + +以下部分将指导您完成 fadc 驱动的软件配置: + +- 初始化adc控制器 +- 设置adc的中断处理函数 +- 根据adc转换完成状态读取adc转换结果 + +## 4 应用示例 + +### [adc收发数据](../../../baremetal/example/peripheral/adc) + +## 5. API参考 + +### 5.1. 用户数据结构 + +- fadc控制数据 + +```c +typedef struct +{ + FAdcConfig config;/* adc config */ + FAdcConvertConfig convert_config; /* adc convert config */ + FAdcThresholdConfig threshold_config; /* adc channel threshold config */ + u32 is_ready;/* adc init ready flag */ + u16 value[FADC_CHANNEL_NUM]; /* adc value */ + boolean convert_complete[FADC_CHANNEL_NUM]; /*!< Specifies whether the conversion is complete> */ + FAdcIntrEventHandler event_handler[FADC_INTR_EVENT_NUM]; /* event handler for interrupt */ + void *event_param[FADC_INTR_EVENT_NUM]; /* parameters of event handler */ + +}FAdcCtrl; +``` + +- fadc配置数据,FAdcConfig主要是adc控制器id、基地址和中断号,FAdcConvertConfig主要包括用户可配置的参数,包括转换间隔时间、转换模式、通道模式等,FAdcThresholdConfig主要包含具体通道的结果阈值 + +```c +typedef struct +{ + u32 instance_id;/* adc id */ + uintptr base_addr;/* adc control register base address*/ + u32 irq_num;/* adc interrupt number */ + u32 irq_prority;/* adc interrupt priority*/ + const char *instance_name;/* instance name */ + +} FAdcConfig; + +typedef struct +{ + u32 convert_interval; /* convert interval time */ + u32 clk_div; /* clock divider */ + FAdcConvertMode convert_mode;/*!< convert mode */ + FAdcChannelMode channel_mode;/*!< channel mode */ + +} FAdcConvertConfig; + +typedef struct +{ + u16 high_threshold[FADC_CHANNEL_NUM]; /*!< Configures the ADC analog high threshold value. + This parameter must be a 10-bit value. */ + u16 low_threshold[FADC_CHANNEL_NUM]; /*!< Configures the ADC analog low threshold value. + This parameter must be a 10-bit value. */ +} FAdcThresholdConfig; +``` + +- fadc转换模式,单次转换和连续转换 +```c +typedef enum +{ + FADC_CONTINUOUS_CONVERT = 0,/* continuous conversion*/ + FADC_SINGLE_CONVERT = 1, /* single conversion*/ + + FADC_CONVERT_MODE_NUM + +} FAdcCovertMode; +``` + +- fadc通道模式,多通道顺序转换和固定通道转换 +```c +typedef enum +{ + FADC_MULTI_CHANNEL = 0, /* multi channel conversion*/ + FADC_FIXED_CHANNEL = 1, /* fixed channel conversion*/ + + FADC_CHANNEL_MODE_NUM +} FAdcChannelMode; +``` + +- fadc中断事件类型 +```c +typedef enum +{ + FADC_INTR_EVENT_COVFIN = 0, /**< Handler type for convert finish interrupt */ + FADC_INTR_EVENT_DLIMIT = 1, /**< Handler type for low limit interrupt*/ + FADC_INTR_EVENT_ULIMIT = 2, /**< Handler type for high limit interrupt*/ + FADC_INTR_EVENT_ERROR = 3, /**< Handler type for error interrupt*/ + + FADC_INTR_EVENT_NUM +} FAdcIntrEventType; + +``` + +### 5.2 错误码定义 + +- FADC_SUCCESS 执行成功 +- FADC_ERR_INVAL_PARM 参数无效 +- FADC_ERR_NOT_READY 驱动未初始化 +- FADC_ERR_TIMEOUT 超时 +- FADC_ERR_CMD_FAILED 执行失败 + +### 5.3. 用户API接口 + +#### FAdcLookupConfig + +- 获取fadc控制器默认配置 + +```c +const FAdcConfig *FAdcLookupConfig(FAdcInstance instance_id); +``` + +Note: + +- 获取默认配置参数,包括基地址、中断号等 + +Input: + +- {FAdcInstance} instance_id,adc控制器id号 + +Return: + +- {const FAdcConfig *} adc默认配置,返回NULL如果找不到默认配置 + +#### FAdcCfgInitialize + +- 初始化fadc控制器, 使之可以使用 + +```c +FError FAdcCfgInitialize(FAdcCtrl *pctrl, const FAdcConfig *input_config_p); +``` + +Note: + +- 输入配置通过FAdcLookupConfig获取,用户按照需要修改后传入此函数 + +Input: + +- {FAdcCtrl} *pctrl,adc驱动控制数据 +- {FAdcConfig} *input_config_p,adc用户输入配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FADC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FAdcVariableConfig + +- 设置adc可配置参数 + +```c +FError FAdcVariableConfig(FAdcCtrl *pctrl, u8 channel, FAdcConvertConfig *convert_config, + FAdcThresholdConfig *threshold_config); +``` + +Note: + +- 设置指定adc控制器的可配置参数,包括转换模式,通道阈值等 + +Input: + +- {FAdcCtrl} *pctrl,adc驱动控制数据 +- {u8} channel,adc通道号 +- {FAdcConvertConfig} *convert_config,adc转换参数配置 +- {FAdcThresholdConfig} *threshold_config,adc通道转换结果阈值配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FADC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FAdcChannelThresholdSet + +- 设置adc通道的转换结果阈值,使能该通道 + +```c +FError FAdcChannelThresholdSet(FAdcCtrl *pctrl, u8 channel, FAdcThresholdConfig *threshold_config); +``` + +Note: + +- 设置指定adc控制器的指定通道的转换结果阈值,使能该通道 + +Input: + +- {FAdcCtrl} *pctrl,adc驱动控制数据 +- {u8} channel,adc通道号 +- {FAdcThresholdConfig} *threshold_config,adc通道转换结果阈值配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FADC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FAdcConvertStart + +- 设置adc控制器转换开始 + +```c +FError FAdcConvertStart(FAdcCtrl *pctrl); +``` + +Note: + +- 设置指定adc控制器转换开始 + +Input: + +- {FAdcCtrl} *pctrl,adc驱动控制数据 + +Return: + +- {FError} 驱动初始化的错误码信息,FADC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FAdcInterruptEnable + +- 使能adc通道的中断 + +```c +FError FAdcInterruptEnable(FAdcCtrl *pctrl, u8 channel, FAdcIntrEventType event_type); +``` + +Note: + +- 使能指定adc控制器的指定通道的中断 + +Input: + +- {FAdcCtrl} *pctrl,adc驱动控制数据 +- {u8} channel,adc通道号 +- {FAdcIntrEventType} event_type,中断事件类型 + +Return: + +- {FError} 驱动初始化的错误码信息,FADC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + + +#### FAdcReadConvertResult + +- 读adc通道的转换结果 + +```c +FError FAdcReadConvertResult(FAdcCtrl *pctrl, u8 channel, u16 *val); +``` + +Note: + +- 读指定adc控制器的指定通道的转换结果 + +Input: + +- {FAdcCtrl} *pctrl,adc驱动控制数据 +- {u8} channel,adc通道号 +- {u16} *val,存储转换结果的指针 + +Return: + +- {FError} 驱动初始化的错误码信息,FADC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + + +#### FAdcRegisterInterruptHandler + +- 注册adc中断事件函数 + +```c +void FAdcRegisterInterruptHandler(FAdcCtrl *instance_p, FAdcIntrEventType event_type, + FAdcIntrEventHandler handler, void *param); +``` + +Note: +- 无 + +Input: +- {FAdcCtrl} *instance_p,fadc驱动控制数据 +- {FAdcIntrEventType} event_type,中断事件类型 +- {FAdcIntrEventHandler} handler,中断事件回调函数 +- {void} *param,回调函数参数 + +Return: +- 无 + +#### FAdcIntrHandler + +- adc中断处理函数入口 + +```c +void FAdcIntrHandler(s32 vector, void *args); +``` + +Note: +- 根据中断类型,设置对应的回调函数和参数传入 + +Input: +- {s32} vector +- {void} *param, 输入参数,指向fadc驱动控制数据 + +Return: +- 无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fcan.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fcan.md new file mode 100644 index 0000000000..449d9c8993 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fcan.md @@ -0,0 +1,248 @@ +# FCAN 驱动程序 + +## 1. 概述 + +CAN 是控制器局域网络(Controller Area Network)的缩写,由以研发和生产汽车电子产品著称的德国BOSCH公司开发,并最终成为国际标准(ISO 11898),是国际上应用最广泛的现场总线之一。 + +## 2. 功能 + +CAN控制器驱动提供了CAN的控制访问方法, +- 初始化CAN控制器 +- 以轮询方式发送/接收数据 +- 发送/接收数据的中断触发 + +驱动相关的源文件包括, +``` +. +├── fcan_g.c +├── fcan_hw.c +├── fcan_hw.h +├── fcan_intr.c +├── fcan_sinit.c +├── fcan.c +└── fcan.h +``` + +## 3. 配置方法 + +以下部分将指导您完成 fcan 驱动的软件配置: + +- 初始化CAN控制器 +- 设置CAN的中断处理函数,包括收发中断 + +## 4 应用示例 + +### [can收发数据](../../../baremetal/example/peripheral/can) + +## 5. API参考 + +### 5.1. 用户数据结构 + +- fcan控制数据 + +```c +typedef struct +{ + FCanConfig config; + u32 is_ready; /* Device is initialized and ready */ + boolean use_canfd; /* if use canfd function */ + + FCanIntrEventConfig intr_event[FCAN_INTR_EVENT_NUM];/* event handler and parameters for interrupt */ +} FCanCtrl; +``` + +- fcan配置数据,FCanConfig主要是can控制器id、基地址和中断号,FCanIntrEventConfig主要包括中断处理函数 + +```c +typedef struct +{ + u32 instance_id; /* Id of device */ + uintptr base_address; /* Can base Address */ + u32 irq_num; /* interrupt number */ + u32 irq_prority;/* interrupt priority*/ +}FCanConfig; +``` + +- fcan波特率配置 +```c +typedef struct +{ + FCanSegmentType segment; + boolean auto_calc; /* if auto calculate baudrate parameters */ + u32 baudrate; /* baudrate */ + u32 sample_point; /* sample point */ + u32 prop_seg; /* Propagation segment in TQs */ + u32 phase_seg1; /* Phase buffer segment 1 in TQs */ + u32 phase_seg2; /* Phase buffer segment 2 in TQs */ + u32 sjw; /* Synchronisation jump width in TQs */ + u32 brp; /* Baudrate prescaler */ +}FCanBaudrateConfig; +``` + +- fcan报文 +```c +typedef struct +{ + u32 canid; + u8 candlc; + u8 flags; /* additional flags for CAN FD */ + u8 data[FCAN_DATA_LENGTH] __attribute__((aligned(8))); +}FCanFrame; +``` + +- fcan中断事件类型 +```c +typedef enum +{ + FCAN_INTR_EVENT_SEND = 0, /* Handler type for frame sending interrupt */ + FCAN_INTR_EVENT_RECV = 1, /* Handler type for frame reception interrupt */ + FCAN_INTR_EVENT_ERROR, /* Handler type for error interrupt */ + FCAN_INTR_EVENT_NUM +} FCanIntrEventType; +``` + +### 5.2 错误码定义 + +- FCAN_SUCCESS 执行成功 +- FCAN_NOT_READY 驱动未初始化 +- FCAN_FAILURE 执行失败 +- FCAN_INVAL_PARAM 参数无效 + +### 5.3. 用户API接口 + +#### FCanLookupConfig + +- 获取Fata控制器默认配置 + +```c +const FCanConfig *FCanLookupConfig(FCanInstance instance_id); +``` + +Note: + +- 获取默认配置参数,包括基地址、中断号等 + +Input: + +- {FCanInstance} instance_id,控制器id号 + +Return: + +- {const FCanConfig *} fcan默认配置,返回NULL如果找不到默认配置 + +#### FCanCfgInitialize + +- 初始化fcan控制器, 使之可以使用 + +```c +FError FCanCfgInitialize(FCanCtrl *instance_p, const FCanConfig *input_config_p); +``` + +Note: + +- 输入配置通过FCanLookupConfig获取,用户按照需要修改后传入此函数 + +Input: + +- {FCanCtrl} *instance_p fcan驱动控制数据 +- {FCanConfig} *input_config_p fcan用户输入配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FCAN_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FCanSend + +- 发送can数据 + +```c +FError FCanSend(FCanCtrl *instance_p, FCanFrame *frame_p); +``` + +Note: + +- 指定can控制器发送can数据 + +Input: + +- {FCanCtrl} *instance_p,fcan驱动控制数据 +- {FCanFrame} *frame_p,can数据 + +Return: + +- {FError} 驱动初始化的错误码信息,FCAN_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FCanRecv + +- 接收can数据 + +```c +FError FCanRecv(FCanCtrl *instance_p, FCanFrame *frame_p); +``` + +Note: + +- 指定can控制器接收can数据 + +Input: + +- {FCanCtrl} *instance_p,fcan驱动控制数据 +- {FCanFrame} *frame_p,can数据 + +Return: + +- {FError} 驱动初始化的错误码信息,FCAN_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FCanRegisterInterruptHandler + +- 注册can中断事件函数 + +```c +void FCanRegisterInterruptHandler(FCanCtrl *instance_p, FCanIntrEventConfig *intr_event_p); +``` + +Note: +- 无 + +Input: +- {FCanCtrl} *instance_p,fcan驱动控制数据 +- {FCanIntrEventConfig} *intr_event_p,中断事件类型,回调函数,回调函数参数 + +Return: +- 无 + +#### FCanIntrHandler + +- can中断处理函数入口 + +```c +void FCanIntrHandler(s32 vector, void *args); +``` + +Note: +- 根据中断类型,设置对应的回调函数和参数传入 + +Input: +- {s32} vector +- {void} *param, 输入参数,指向fcan驱动控制数据 + +Return: +- 无 + +#### FCanIdMaskFilterSet + +- can id过滤设置 + +```c +FError FCanIdMaskFilterSet(FCanCtrl *instance_p, FCanIdMaskConfig *id_mask_p); +``` + +Note: +- 设置可接收帧id值和掩码 + +Input: +- {FCanCtrl} *instance_p, fcan驱动控制数据 +- {FCanIdMaskConfig} *id_mask_p, 过滤寄存器序号,可接收帧id,可接收帧id掩码 + +Return: +- {FError} 驱动初始化的错误码信息,FCAN_SUCCESS 表示初始化成功,其它返回值表示初始化失败 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fddma.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fddma.md new file mode 100644 index 0000000000..0663e4b980 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fddma.md @@ -0,0 +1,288 @@ +# FDDMA 驱动程序 + +## 1. 概述 + +DDMA(Device Direct Memory Access)是E2000提供的一个通用DMA控制模块,支持典型的DMA操作,提供多个DMA通道,多个通道可以同时工作,独立配置给不同外设使用 + +## 2. 功能 + +FDDMA 驱动程序主要完成 DDMA 模块的初始化,DDMA通道的分配与释放, +相关源文件为: +``` +fddma + . + ├── fddma.c + ├── fddma.h + ├── fddma_g.c + ├── fddma_hw.c + ├── fddma_hw.h + ├── fddma_intr.c + ├── fddma_selftest.c + └── fddma_sinit.c +``` + +## 3. 配置方法 + +以下部分将指导您完成 FDDMA 驱动的软件配置: + +- 初始化 DDMA 控制器 +- 配置 DDMA 通道,与外设完成绑定 +- 启动 DDMA 通道 + +## 4 应用示例 + +### [通过DDMA搬运SPI数据完成回环测试](../../../baremetal/example/peripheral/dma/fddma_spi) + +## 5. API参考 + +### 5.1. 用户数据结构 + +#### FDdmaConfig + +- DDMA 实例配置 + +```c +typedef struct +{ + u32 id; /* DDMA ctrl id */ + uintptr base_addr; /* DDMA ctrl base address */ + u32 irq_num; /* DDMA ctrl interrupt id */ + u32 irq_prority; /* DDMA ctrl interrupt priority */ +} FDdmaConfig; /* DDMA instance configuration */ +``` + +#### FDdmaChanConfig + +- DDMA 通道配置 + +```c +typedef struct +{ + FDdmaChanIndex id; /* DMA channel index */ + u32 slave_id; /* Perpherial slave id for DDMA */ + FDdmaChanRequst req_mode; /* DMA transfer direction */ + uintptr ddr_addr; /* DMA channel DDR address, could be source or destination */ + u32 dev_addr; /* DMA channel Perpherial, could be source or destination */ + u32 trans_len; /* DMA channel transfer length */ +#define FDDMA_MAX_TRANSFER_LEN 64 /* max bytes in transfer */ +#define FDDMA_MIN_TRANSFER_LEN 4 /* min bytes in transfer */ + u32 timeout; /* timeout = 0 means no use DMA timeout */ +} FDdmaChanConfig; /* DDMA channel instance */ +``` + +#### FDdmaChan + +- DDMA 通道实例 + +```c +typedef struct FDdmaChan_ +{ + FDdmaChanConfig config; /* DDMA channel configuration */ + boolean is_used; /* TRUE means channel is in use */ + FDdma *dma; /* DMA instance of this channel */ + FDdmaChanEvtHandler evt_handler[FDDMA_NUM_OF_CHAN_EVT]; /* interrupt evt */ + void *evt_handler_args[FDDMA_NUM_OF_CHAN_EVT]; /* interrupt evt args */ +} FDdmaChan; /* DDMA channel instance */ +``` + +#### FDdma + +- DDMA 控制器实例 + +```c +typedef struct FDdma_ +{ + FDdmaConfig config; /* DDMA instance configuration */ + FDdmaChan *chan[FDDMA_NUM_OF_CHAN]; /* DDMA channel instance, NULL means channel not yet allocate */ + u32 is_ready; /* TRUE means DDMA init ok */ + u32 bind_status; /* channel bind status, BIT(n) = 1 means channel n is allocated */ +} FDdma; /* DDMA instance */ +``` + +### 5.2 错误码定义 + + +- FDDMA_SUCCESS : 成功 +- FDDMA_ERR_NOT_INIT :驱动未初始化 +- FDDMA_ERR_CHAN_BINDED :通道已经绑定无法分配 +- FDDMA_ERR_CHAN_RUNNING : 通道正在工作无法分配 +- FDDMA_ERR_INVALID_TRANS_SIZE : DMA传输字节数不合法 +- FDDMA_ERR_WAIT_TIMEOUT : DMA等待超时 +- FDDMA_ERR_INVALID_DDR_ADDR : DMA传输地址不合法 + +### 5.3. 用户API接口 + +#### FDdmaLookupConfig + + +```c +const FDdmaConfig *FDdmaLookupConfig(u32 instance_id); +``` + +Note: + +- 获取DDMA实例默认配置 + +Input: + +- {u32} instance_id, DDMA实例号 + +Return: + +- {const FDdmaConfig *} DDMA控制器默认配置 + +#### FDdmaCfgInitialization + + +```c +FError FDdmaCfgInitialization(FDdma *const instance, const FDdmaConfig *input_config); +``` + +Note: + +- 初始化DDMA控制器 + +Input: + +- {FDdma} *instance, DDMA控制器实例 +- {FDdmaConfig} *input_config, DDMA控制器配置 + +Return: + +- {FError} FDDMA_SUCCESS表示初始化成功,其它返回值表示初始化失败 + +#### FDdmaDeInitialization + + +```c +void FDdmaDeInitialization(FDdma *const instance); +``` + +Note: + +- 去初始化DDMA控制器 + +Input: + +- {FDdma} *instance, DDMA控制器实例 + +Return: + +- 无 + +#### FDdmaAllocateChan + +```c +FError FDdmaAllocateChan(FDdma *const instance, FDdmaChan *const dma_chan, const FDdmaChanConfig *dma_chan_config); +``` + +Note: + +- 按照配置分配并使能DDMA通道 + +Input: + +- {FDdma} *instance, DDMA控制器实例 +- {FDdmaChan} *dma_chan, DDMA通道实例 +- {FDdmaChanConfig} *dma_chan_config, DDMA通道配置 + +Return: + +- {FError} FDDMA_SUCCESS表示分配成功,其它返回值表示分配失败 + +#### FDdmaDellocateChan + +```c +FError FDdmaDellocateChan(FDdmaChan *const dma_chan); +``` + +Note: + +- 释放之前分配的DDMA通道 + +Input: + +- {FDdmaChan} *dma_chan, DDMA控制器实例 + +Return: + +- {FError} FDDMA_SUCCESS表示释放成功,其它返回值表示释放失败 + +#### FDdmaStart + +```c +FError FDdmaStart(FDdma *const instance); +``` + +Note: + +- 启动DDMA控制器,开始传输 + +Input: + +- {FDdma} *instance, DDMA控制器实例 + +Return: + +- {FError} FDDMA_SUCCESS表示启动成功,其它返回值表示启动失败 + +#### FDdmaStop + +```c +FError FDdmaStop(FDdma *const instance); +``` + +Note: + +- 停止DDMA控制器 + +Input: + +- {FDdma} *instance, DDMA控制器实例 + +Return: + +- {FError} FDDMA_SUCCESS表示停止成功,其它返回值表示停止失败 + +#### FDdmaIrqHandler + +```c +void FDdmaIrqHandler(s32 vector, void *args) +``` + +Note: + +- DDMA中断处理函数 + +Input: + +- {s32} vector +- {void} *param, 输入参数 + +Return: + +- 无 + +#### FDdmaRegisterChanEvtHandler + +```c +void FDdmaRegisterChanEvtHandler(FDdmaChan *const dma_chan, + FDdmaChanEvt evt, + FDdmaChanEvtHandler handler, + void *handler_arg); +``` + +Note: + +- 注册DDMA通道中断响应事件函数 + +Input: + +- {FDdmaChan} *dma_chan, DDMA通道 +- {FDdmaChanEvt} evt, 中断事件 +- {FDdmaChanEvtHandler} handler, 中断响应事件函数 +- {void} *handler_arg, 中断响应事件函数输入参数 + +Return: + +- 无 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fgdma.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fgdma.md new file mode 100644 index 0000000000..4305d062be --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fgdma.md @@ -0,0 +1,372 @@ +# FGDMA 驱动程序 + +## 1. 概述 + +GDMA(Generic Direct Memory Access),提供多个DMA通道,多个通道可以同时工作,独立配置给不同内存数据搬运使用 + + +## 2. 功能 + +FGDMA 驱动程序主要完成 GDMA 模块的初始化,GDMA 通道的分配与释放, +相关源文件为: +``` +fgdma + . + ├── fgdma.c + ├── fgdma.h + ├── fgdma_g.c + ├── fgdma_hw.h + ├── fgdma_intr.c + ├── fgdma_selftest.c + └── fgdma_sinit.c +``` + +## 3. 配置方法 + +以下部分将指导您完成 FGDMA 驱动的软件配置: + +- 初始化 GDMA 控制器 +- 配置 GDMA 通道,使用直接模式或者 BDL 模式进行操作 +- 启动 GDMA 通道 + +## 4. 应用示例 + +### [通过GDMA拷贝内存数据](../../../baremetal/example/peripheral/dma/fgdma_async_memcpy) + +## 5. API参考 + +### 5.1. 用户数据结构 + +#### FGdmaConfig + +- GDMA控制器配置 + +```c +typedef struct +{ + u32 instance_id; /* GDMA控制器ID */ + u32 irq_num; /* GDMA控制器中断号 */ + u32 irq_prority; /* GDMA控制器中断优先级 */ + volatile uintptr_t base_addr; /* GDMA控制器基地址 */ + FGdmaOperPriority rd_qos; /* 读操作优先级 */ + FGdmaOperPriority wr_qos; /* 写操作优先级 */ +} FGdmaConfig; +``` + +#### FGdmaChanConfig + +- DMA通道配置 + +```c +typedef struct +{ + FGdmaChanIndex chan_id; /* DMA通道ID */ + FGdmaOperPriority rd_qos; /* DMA通道读Qos配置 */ + FGdmaOperPriority wr_qos; /* DMA通道写Qos配置 */ + FGdmaOperMode trans_mode; /* DMA通道的操作模式,直接模式或者BDL模式 */ + /* Direct模式有效 */ + FGdmaBurstSize rd_align; /* DMA读请求的Burst对齐方式 */ + FGdmaBurstSize wr_align; /* DMA写请求的Burst对齐方式 */ + /* BDL模式有效 */ + boolean roll_back; /* 循环模式,TRUE: 当前BDL列表完成后,从第一个BDL项从新开始传输 */ + FGdmaBdlDesc *descs; + u32 total_desc_num; + u32 valid_desc_num; +} FGdmaChanConfig; /* DMA通道配置 */ +``` + +#### FGdmaChan + +- GDMA通道实例 + +```c +typedef struct _FGdmaChan +{ + FGdmaChanConfig config; /* DMA通道配置 */ + FGdma *gdma; /* DMA控制器实例 */ + FGdmaChanEvtHandler evt_handlers[FGDMA_CHAN_NUM_OF_EVT]; /* DMA通道事件回调函数 */ + void *evt_handler_args[FGDMA_CHAN_NUM_OF_EVT]; /* DMA通道事件回调函数入参 */ +} FGdmaChan; /* GDMA通道实例 */ +``` + +#### FGdma + +- GDMA控制器实例 + +```c +typedef struct _FGdma +{ + FGdmaConfig config; /* GDMA控制器配置 */ + u32 is_ready; /* GDMA控制器初始化是否完成 */ + FGdmaChan *chans[FGDMA_NUM_OF_CHAN]; /* GDMA通道实例,如果通道没有分配,值为NULL */ +} FGdma; /* GDMA控制器实例 */ +``` + +#### FGdmaBdlDesc + +- BDL描述符 + +```c +typedef struct +{ + u32 src_addr_l; /* 0x0, 数据源地址低32位 */ + u32 src_addr_h; /* 0x4, 数据源地址高32位 */ + u32 dst_addr_l; /* 0x8, 数据目的地址低32位 */ + u32 dst_addr_h; /* 0xc, 数据目的地址高32位 */ +#define FGDMA_SRC_TC_BDL_BURST_SET(x) SET_REG32_BITS((x), 1U, 0U) +#define FGDMA_SRC_TC_BDL_SIZE_SET(x) SET_REG32_BITS((x), 6U, 4U) +#define FGDMA_SRC_TC_BDL_LEN_SET(x) SET_REG32_BITS((x), 15U, 8U) + u32 src_tc; /* 0x10, 源传输控制位 */ +#define FGDMA_DST_TC_BDL_BURST_SET(x) SET_REG32_BITS((x), 1U, 0U) +#define FGDMA_DST_TC_BDL_SIZE_SET(x) SET_REG32_BITS((x), 6U, 4U) +#define FGDMA_DST_TC_BDL_LEN_SET(x) SET_REG32_BITS((x), 15U, 8U) + u32 dst_tc; /* 0x14, 目的传输控制 */ + u32 total_bytes;/* 0x18, 传输数据总量,以Byte为单位 */ + u32 ioc; /* 0x1c, 该条目传输完成中断产生控制位 */ +} __attribute__((__packed__)) FGdmaBdlDesc; /* BDL描述符 */ +``` + +### 5.2 错误码定义 + +#define FGDMA_SUCCESS : 成功 +#define FGDMA_ERR_NOT_INIT : 驱动未初始化 +#define FGDMA_ERR_CHAN_IN_USE : 通道已经绑定无法分配 +#define FGDMA_ERR_CHAN_NOT_INIT : 通道未初始化 +#define FGDMA_ERR_INVALID_ADDR : 传输地址非法 +#define FGDMA_ERR_INVALID_SIZE : 传输字节数非法 +#define FGDMA_ERR_BDL_NOT_ENOUGH : BDL已经使用完 + + +### 5.3. 用户API接口 + +#### FGdmaLookupConfig + +```c +const FGdmaConfig *FGdmaLookupConfig(u32 instance_id) +``` + +Note: + +- 获取GDMA控制器默认配置 + +Input: + +- {u32} instance_id, GDMA控制器ID + +Return: + +- {const FGdmaConfig *} 控制器默认配置 + +#### FGdmaCfgInitialize + +```c +FError FGdmaCfgInitialize(FGdma *const instance_p, const FGdmaConfig *input_config) +``` + +Note: + +- 初始化GDMA控制器实例 + +Input: + +- FGdma *const instance_p, GDMA控制器实例 +- const FGdmaConfig *input_config, GDMA控制器配置 + +Return: + +- {FError} 返回FGDMA_SUCCESS表示初始化成功,返回其它表示失败 + +#### FGdmaDeInitialize + +```c +void FGdmaDeInitialize(FGdma *const instance_p) +``` + +Note: + +- 去初始化GDMA控制器实例 + +Input: + +- FGdma *const instance_p, GDMA控制器实例 + +Return: + +- 无 + +#### FGdmaAllocateChan + +```c +FError FGdmaAllocateChan(FGdma *const instance_p, FGdmaChan *const dma_chan, + const FGdmaChanConfig *dma_chan_config) +``` + +Note: + +- 分配指定GDMA通道 + +Input: + +- FGdma *const instance_p, GDMA控制器实例 +- FGdmaChan *const dma_chan, GDMA通道实例 +- const FGdmaChanConfig *dma_chan_config, GDMA通道配置 + +Return: + +- {FError} FGDMA_SUCCESS表示分配成功,返回其它值表示分配失败 + +#### FGdmaDellocateChan + +```c +FError FGdmaDellocateChan(FGdmaChan *const dma_chan) +``` + +Note: + +- 释放GDMA通道 + +Input: + +- FGdmaChan *const dma_chan, GDMA通道实例 + +Return: + +- {FError} FGDMA_SUCCESS表示处理成功 + +#### FGdmaDirectTransfer + +```c +FError FGdmaDirectTransfer(FGdmaChan *const chan_p, uintptr src_addr, uintptr dst_addr, fsize_t data_len); + +``` + +Note: + +- 直接操作模式下发起DMA传输 + +Input: + +- FGdmaChan *const chan_p, GDMA通道实例 +- uintptr src_addr, 传输源地址 +- uintptr dst_addr, 传输目的地址 + +Return: + +- {FError} FGDMA_SUCCESS表示传输成功 + +#### FGdmaAppendBDLEntry + +```c +FError FGdmaAppendBDLEntry(FGdmaChan *const chan_p, uintptr src_addr, uintptr dst_addr, fsize_t data_len) +``` + +Note: + +- 设置BDL描述符的一个条目 + +Input: + +- FGdmaBdlDesc *desc_entry, 一条BDL描述符 +- uintptr src_addr, 传输源地址 +- uintptr dst_addr, 传输目的地址 +- fsize_t data_len, 传输数据长度 + +Return: + +- {FError} FGDMA_SUCCESS 表示设置成功 + +#### FGdmaBDLTransfer + +```c +FError FGdmaBDLTransfer(FGdmaChan *const chan_p) +``` + +Note: + +- BDL操作模式下发起DMA传输 + +Input: + +- FGdmaChan *const chan_p, DMA通道实例 + +Return: + +- {FError} FGDMA_SUCCESS 表示传输成功 + +#### FGdmaStart + +```c +FError FGdmaStart(FGdma *const instance_p) +``` + +Note: + +- 使能启动GDMA控制器 +- 先调用此函数,后调用FGdmaAllocateChan配置特定通道 + +Input: + +- FGdma *const instance_p, GDMA控制器实例 + +Return: + +- {FError} FGDMA_SUCCESS表示启动成功 + +#### FGdmaStop + +```c +FError FGdmaStop(FGdma *const instance_p) +``` + +Note: + +- 停止GDMA控制器 + +Input: + +- FGdma *const instance_p, GDMA控制器实例 + +Return: + +- {FError} FGDMA_SUCCESS表示处理成功 + +#### FGdmaIrqHandler + +```c +void FGdmaIrqHandler(s32 vector, void *args) +``` + +Note: + +- GDMA中断处理函数 + +Input: + +- {s32} vector, 中断号 +- {void} *args, 中断参数 + +Return: + +- 无 + +#### FGdmaChanRegisterEvtHandler + +```c +void FGdmaChanRegisterEvtHandler(FGdmaChan *const chan_p, FGdmaChanEvtType evt, + FGdmaChanEvtHandler handler, void *handler_arg) +``` + +Note: + +- 注册GDMA通道事件回调函数 + +Input: + +- {FGdmaChan} *chan_p, GDMA通道实例 +- {FGdmaChanEvtType} evt, 通道事件 +- {FGdmaChanEvtHandler} handler, 事件回调函数 +- {void} *handler_arg, 事件回调函数输入参数 + +Return: + +- 无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fgic.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fgic.md new file mode 100644 index 0000000000..88ca7a1ee8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fgic.md @@ -0,0 +1,441 @@ + + + +# GIC 驱动说明 + +## 1.驱动概述 + +GIC 是通用中断控制器,它为ARM CPU提供外设中断与软件中断的控制,GIC主要支持SPI\SGI\PPI等不同类型的中断,本版本支持的驱动版本为GICv3,并且支持了以下特性: +1.SPI支持多核心路由配置、优先级配置、使能关闭功能 +2.SGI提供软件触发接口、优先级配置、支持多核触发、目标核心触发、使能关闭功能 +3.PPI 提供优先级配置、使能关闭功能 +4.支持CPU interface 中断掩码配置 +5.支持组优先级分组配置 +6.当前仅支持双安全态下的Non-secure访问 + +## 2.驱动功能 + +驱动组成由以下所示 +``` +. +├── fgic.c +├── fgic.h +├── fgic_cpu_interface.S +├── fgic_cpu_interface.h +├── fgic_distributor.h +├── fgic_g.c +├── fgic_hw.h +├── fgic_redistributor.h +└── fgic_sinit.c +``` +- 其中fgic.c/h 为开发者提供以下功能: +1. 初始化GIC 中断实例 +2. 提供基于中断号中断开关功能 +3. 提供基于中断号中断优先级设置与获取功能 +4. 提供基于中断号触发方式 +5. 提供SGI中断触发功能 +6. 提供中断承认(Acknowledge)接口 +7. 提供中断优先级掩码配置与获取功能 +8. 提供Distrutior、Redistrubutior、CPU interface 的 初始化功能 + +## 3.数据结构 + +``` +typedef struct +{ +    u32 instance_id; /*Gic 实例编号*/ +    uintptr dis_base; /* Distributor 基地址*/ +    +} FGicConfig; + +``` + +``` +typedef struct +{ +    FGicConfig config; /* 配置数据结构*/ +    u32 is_ready;       /* 驱动实例的状态 */ +    uintptr redis_base; /* 当前实例核心对应的Redistributor 地址  */ +    SECURITY_STATE security ; /* GIC 驱动当前支持的安全态模式 */ +    s32 max_spi_num;    /* SPI 最大中断优先级ID */ +} FGic; +``` + +## 4.错误码定义 + +``` +FGIC_CTLR_ERR_TYPE   /* 错误选择CTLR 寄存器 */ +FGIC_CTLR_ERR_NUM     /* 当前控制器不支持此中断id */ +FGIC_CTLR_ERR_IN_SET   /* 在设置过程中出现的异常 */ +FGIC_CTLR_ERR_IN_GET   /* 在获取过程中出现的异常 */ +``` + +## 5.应用示例 + +common/interrupt.c 中断接口提供底层支持 +/baremetal/example/peripheral/gic/fgic_test gic特性例程 + +## 6.API介绍 + +### 1. FGicLookupConfig + +``` +FGicConfig *FGicLookupConfig(u32 instance_id) +``` + +#### 介绍 +获取当前GIC 驱动默认配置 +#### 参数 +- u32 instance_id :当前GIC 驱动中对应的ID + +#### 返回 +- FGicConfig * :静态默认配置 + +### 2. FGicCfgInitialize + +``` +FError FGicCfgInitialize(FGic *instance_p, const FGicConfig *input_config_p , uintptr redis_base) +``` + +#### 介绍 +根据传入配置,初始化GIC 驱动实例 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- const FGicConfig *input_config_p:需要应用于示例中的配置项 +- redis_base:是当前内核的重分发地址 + +#### 返回 +- FError :FGIC_SUCCESS 为初始成功 + + +### 3. FGicDistrubutiorInit + +``` +void FGicDistrubutiorInit(FGic *instance_p) +``` + +#### 介绍 +初始化Distrubutior 模块 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 + +#### 返回 +无 + +### 4. FGicRedistrubutiorInit + +``` +FError FGicRedistrubutiorInit(FGic *instance_p) +``` + +#### 介绍 +初始化Redistrubutior 模块 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 + +#### 返回 +- {FError} FGIC_SUCCESS is success ,FGIC_ERR_IN_TIMEOUT is timeout + +### 5. FGicCpuInterfaceInit + +``` +void FGicCpuInterfaceInit(void) +``` + +#### 介绍 +初始化当前核心下的cpu interface模块 + +#### 返回 +无 + +### 6. FGicIntEnable + +``` +FError FGicIntEnable(FGic *instance_p,s32 int_id) +``` + +#### 介绍 +基于中断号使能中断功能 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID + +#### 返回 +- FError :FGIC_SUCCESS 为操作成功 + +### 7. FGicIntDisable + +``` +FError FGicIntDisable(FGic *instance_p,s32 int_id) +``` + +#### 介绍 +基于中断号关闭中断功能 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID + +#### 返回 +- FError :FGIC_SUCCESS 为操作成功 + +### 8. FGicSetPriority + +``` +FError FGicSetPriority(FGic *instance_p,s32 int_id,u32 priority) +``` + +#### 介绍 +基于中断号设置当前中断优先级的值 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID +- u32 priority: 中断优先级的值,有效值8bit + +#### 返回 +- FError :FGIC_SUCCESS 为操作成功 ,当反馈为FGIC_CTLR_ERR_IN_GET 时,表示中断ID超过范围 + +### 9. FGicGetPriority + +``` +u32 FGicGetPriority(FGic *instance_p,s32 int_id) +``` + +#### 介绍 +基于中断号获取当前中断优先级的值 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID + +#### 返回 +- u32 :中断优先级的值,有效值8bit 。当反馈为FGIC_CTLR_ERR_IN_GET 时,表示中断ID超过范围 + +### 10. FGicSetTriggerLevel + +``` +FError FGicSetTriggerLevel(FGic *instance_p,s32 int_id,TRIGGER_LEVEL trigger_way) +``` + +#### 介绍 +基于当前中断号配置中断触发模式 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID +- TRIGGER_LEVEL trigger_way:中断触发模式 , 参数为0的时为电平触发,参数为1的时为电平触发 + +#### 返回 +- FError :FGIC_SUCCESS 为操作成功 ,当反馈为FGIC_CTLR_ERR_IN_GET 时,表示中断ID超过范围 + +### 11. FGicGetTriggerLevel + +``` +u32 FGicGetTriggerLevel(FGic *instance_p,s32 int_id) +``` + +#### 介绍 +基于当前中断号获取中断触发模式 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID + +#### 返回 +- TRIGGER_LEVEL trigger_way:中断触发模式 , 参数为0的时为电平触发,参数为1的时为电平触发 + +### 12. FGicSetSpiAffinityRouting + +``` +FError FGicSetSpiAffinityRouting(FGic *instance_p,s32 int_id,SPI_ROUTING_MODE route_mode,u64 affinity) +``` + +#### 介绍 +为特定的SPI中断设置中间路由信息 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID +- SPI_ROUTING_MODE route_mode:中断路由模式 ,SPI_ROUTING_TO_SPECIFIC spi 中断路由给特定PE ,SPI_ROUTING_TO_ANY spi 中断将路由给任何开启本SPI 的PE处 +- u64 affinity:亲和度参数,它的格式为: + * |--------[bit39-32]-------[bit23-16]-------------[bit15-8]--------[bit7-0] + * |--------Affinity level3-----Affinity level2-----Affinity level1---Affinity level0 + +#### 返回 +- FError :FGIC_SUCCESS 为操作成功,FGIC_CTLR_ERR_IN_SET 为中断ID 不符合SPI的范围 + + +### 13. FGicGetAffinityRouting + +``` +FError FGicGetAffinityRouting(FGic *instance_p,s32 int_id,SPI_ROUTING_MODE *route_mode_p,u64 *affinity_p) +``` + +#### 介绍 +获取特定的SPI中断设置路由信息 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID +- SPI_ROUTING_MODE *route_mode_p:中断路由模式实例的指针 ,当参数为SPI_ROUTING_TO_SPECIFIC spi 中断路由给特定PE , SPI_ROUTING_TO_ANY spi 中断将路由给任何开启本SPI 中断的PE处 +- u64 *affinity_p:亲和度参数实例的指针,它的值格式为: + * |--------[bit39-32]-------[bit23-16]-------------[bit15-8]--------[bit7-0] + * |--------Affinity level3-----Affinity level2-----Affinity level1---Affinity level0 + +#### 返回 +- FError :FGIC_SUCCESS 为操作成功,FGIC_CTLR_ERR_IN_GET 为中断ID 不符合SPI的范围 + +### 14. FGicGenerateSgi +``` +FError FGicGenerateSgi(FGic *instance_p,s32 int_id,u32 target_list,SGI_ROUTING_MODE routing_mode,u64 affinity) +``` + +#### 介绍 +基于中断id产生SGI中断的接口 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID +- u32 target_list:将为其生成SGI中断的pe集合 。每一位对应一个集群内的一个PE +SGI_ROUTING_MODE routing_mode:SGI 的路由模式,SGI_ROUTING_TO_SPECIFIC 为特定的PE,SGI_ROUTING_TO_ANY 为所有的PE 除开自己这个核心。 +- u64 affinity :亲和度参数,它的格式为: + * |--------[bit55-48]-------[bit39-32]-------------[bit23-16] + * |--------Affinity level3-----Affinity level2-----Affinity level1 + +#### 返回 +- FError :FGIC_SUCCESS 为操作成功,FGIC_CTLR_ERR_IN_SET 为中断ID 不符合SGI的范围 + +### 15. FGicDeactionInterrupt + +``` +void FGicDeactionInterrupt(FGic *instance_p,s32 int_id) +``` + +#### 介绍 +钝化正处于激活态的中断 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- s32 int_id:中断ID + +#### 返回 +无 + +### 16. FGicAcknowledgeInt + +``` +s32 FGicAcknowledgeInt(FGic *instance_p) +``` + +#### 介绍 +承认当前被挂起的中断 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 + +#### 返回 +- s32 int_id:被承认的中断ID + + +### 17. FGicSetPriorityFilter + +``` +void FGicSetPriorityFilter(FGic *instance_p,u32 priority_mask) +``` + +#### 介绍 +通过设置ICC_PMR参数,确定中断控制器可以响应的中断范围 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- u32 priority_mask:如果一个中断的优先级低于该字段所指定的值,则接口向PE发送中断信号。 priority_mask的参考值如下所示 : + * |priority_mask---------------256-------254--------252------248-------240 + * |Implemented priority bits---[7:0]----[7:1]------[7:2]-----[7:3]-----[7:4] + * |priority the growing steps--any-----even value----4---------8--------16 + +#### 返回 +无 + +### 18. FGicSetPriorityGroup + +``` +void FGicSetPriorityGroup(FGic *instance_p,u32 binary_point) +``` + +#### 介绍 +设置当前组优先级的值 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 +- u32 binary_point:该字段的值控制如何将8位中断优先级字段拆分为组优先级和子优先级, +- binary_point值与分组的关系如下所示 + * |return value----------------0-------1--------2------3-------4------5------6-------7 + * |Group priority field------[---]----[7:1]---[7:2]--[7:3]---[7:4]---[7:5]---[7:6]---[7] + * |Subpriority field---------[---]-----[0]----[1:0]--[2:0]---[3:0]---[4:0]---[5:0]---[6:0] + +#### 返回 +无 + + +### 19. FGicGetPriorityFilter + +``` +u32 FGicGetPriorityFilter(FGic *instance_p) +``` + +#### 介绍 +获取当前优先级过滤值 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 + +#### 返回 +- u32 Priority Mask,CPU接口中的优先级掩码 ,如果一个中断的优先级低于该字段所指定的值,则接口向PE发送中断信号。 priority_mask的参考值如下所示 : + * |return value------------------256------254--------252------248-------240 + * |Implemented priority bits---[7:0]----[7:1]------[7:2]-----[7:3]-----[7:4] + * |priority the growing steps---any-----even value----4--------8-------16 + +### 20. FGicGetPriorityGroup + +``` +u32 FGicGetPriorityGroup(FGic *instance_p) +``` + +#### 介绍 +获取当前CPU interface 中的分组值 + +#### 参数 +- FGic *instance_p:指向FGic实例的指针 + +#### 返回 +- u32 Priority group,该字段的值控制如何将8位中断优先级字段拆分为组优先级和子优先级, +binary_point值与分组的关系如下所示 + * |return value----------------0-------1--------2------3-------4------5------6-------7 + * |Group priority field------[---]----[7:1]---[7:2]--[7:3]---[7:4]---[7:5]---[7:6]---[7] + * |Subpriority field---------[---]-----[0]----[1:0]--[2:0]---[3:0]---[4:0]---[5:0]---[6:0] \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fgmac.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fgmac.md new file mode 100644 index 0000000000..6fa5768cf2 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fgmac.md @@ -0,0 +1,466 @@ +# FGMAC 驱动程序 + +## 1. 概述 + +以太网控制器(GMAC)的主要功能是在兼容 IEEE802.3-2005 标准的以太网中发送和接收数据,支持 RGMII 的 PHY 接口 + +GMAC 接口特点包括 +- 支持速率 1000Mbps/100Mbps/10Mbps +- 支持 IEEE 802.3-2005 Ethernet MAC,Reduced Gigabit Media Independent Interface (RGMII) + +## 2. 功能 + +FGMAC 驱动程序提供了以太网控制器初始化,发送/接收数据和配置PHY接口等功能 + +FGMAC 驱动程序的源文件包括, + +``` +├── Kconfig +├── fgmac.c +├── fgmac.h +├── fgmac_dma.c +├── fgmac_g.c +├── fgmac_hw.c +├── fgmac_hw.h +├── fgmac_intr.c +├── fgmac_sinit.c +└── phy + ├── ar803x + │   ├── fgmac_ar803x.c + │   └── fgmac_ar803x.h + ├── fgmac_phy.c + └── fgmac_phy.h +``` + +## 3. 配置方法 + +以下部分将指导您完成 FGMAC 驱动的硬件/软件配置: + +- 选择开发板上的特定 GMAC 控制器,连通网线 +- 通过驱动 API,获取指定 GMAC 控制器的默认配置 +- 按需要修改获取的 GMAC 默认配置,通过驱动API,进行 GMAC 控制器的初始化 +- 通过驱动API,获取 PHY 的默认配置 +- 按需要修改获取的 PHY 默认配置,通过驱动API,进行 PHY 的初始化 +- 分配 GMAC 数据传输使用的 DMA 描述符和 DMA 缓存区,通过驱动 API 进行注册 +- 通过驱动 API 发送/接收数据 + +网络通信依赖协议栈,可以参考应用例程,使用LWIP网络协议栈进行通信, + +## 4 应用示例 + +### [fgmac_link](../../../baremetal/example/fgmac_link/README.md) + +启动GMAC,接收网络数据并打印 + +### [fgmac_lwip_echo](../../../baremetal/example/fgmac_lwip_echo/README.md) + +启动LWIP网络协议栈,通过FGMAC驱动,支持开发板和网络主机的ping通 + +### [fgmac_lwip_tftp](../../../baremetal/example/fgmac_lwip_tftp/README.md) + +启动LWIP网络协议栈,通过FGMAC驱动,支持开发板通过tftp服务获取文件 + +## 5. API参考 + +### 5.1. 用户数据结构 + +- FGMAC 驱动配置数据 +```c +typedef struct +{ + u32 instance_id; /* device instance id */ + uintptr base_addr; /* device base address */ + u32 irq_num; /* irq num */ + u32 cheksum_mode; /* hardware or software checksum */ + u32 duplex_mode; /* selects the MAC duplex mode: Half-Duplex or Full-Duplex mode */ + u32 max_packet_size; /* max num of bytes in frame transfer */ + u32 mdc_clk_hz; /* MDC clock access PHY. [1.0MHz ~2.5MHz] */ + boolean en_auto_negtiation; /* auto-negotiation or not */ + u32 speed; /* sets the Ethernet speed: 10/100/1000 Mbps.*/ + +} FGmacConfig; /* FGMAC 驱动配置数据 */ +``` + +- FGMAC 驱动控制数据 +```c + +typedef struct +{ + FGmacConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + FGmacRingDescData rx_ring; /* RX DMA descriptor data (idx, length) */ + volatile FGmacDmaDesc *rx_desc; /* RX DMA descriptor table in ring */ + FGmacRingDescData tx_ring; /* TX DMA descriptor data (idx, length) */ + volatile FGmacDmaDesc *tx_desc; /* TX DMA descriptor table in ring */ + FGmacEvtHandler evt_handler[FGMAC_INTR_EVT_NUM]; /* User registered interrupt handler */ + u32 phy_valid_mask; + u32 phy_speed; + u32 phy_addr; /* phy ic addr */ +} FGmac; /* FGMAC 驱动控制数据 */ +``` + +- FGMAC DMA描述符 + +```c +typedef struct +{ + volatile u32 status; + u32 ctrl; + u32 buf_addr; + u32 next; +} FGmacDmaDesc; +``` + +- FGMAC DMA描述符表(链式)相关数据 +```c +typedef struct +{ + u32 desc_idx; /* For Current Desc position */ + u32 desc_buf_idx; /* For Current Desc buffer buf position */ + u32 desc_max_num; /* Max Number for Desc and Desc buffer */ + u8 *desc_buf_base; /* Desc buffer Base */ +} FGmacRingDescData; +``` + +- FGMAC 校验方法选择 +```c +enum +{ + FGMAC_CHECKSUM_BY_SOFTWARE = 0, + FGMAC_CHECKSUM_BY_HARDWARE +}; +``` + +- FGMAC 中断事件类型 +```c +enum +{ + FGMAC_TX_COMPLETE_EVT = 0, + FGMAC_RX_COMPLETE_EVT, + FGMAC_LINK_STATUS_EVT, + FGMAC_PHY_STATUS_EVT, + FGMAC_DMA_ERR_EVT, + + FGMAC_INTR_EVT_NUM +}; +``` + +### 5.2 错误码定义 + +- 模块错误码编号:0x1070000 +- [0x0] FGMAC: Success +- [0x1070001] FGMAC: wait timeout +- [0x1070002] FGMAC: DMA address invalid +- [0x1070003] FGMAC: driver not ready +- [0x1070004] FGMAC: data transaction failed +- [0x1070005] FGMAC: PHY type not support +- [0x1070006] FGMAC: PHY is not found + +### 5.3. 用户API接口 + +#### FGmacLookupConfig + +- 获取FGMAC驱动的默认配置参数 + +```c +const FGmacConfig *FGmacLookupConfig(u32 instance_id); +``` + +Note: + +- 返回FGMAC的默认配置,复制后修改配置 +- 需要确认当前平台支持输入的instance_id + +Input: + +- {u32} instance_id, 驱动控制器号 + +Return: + +- {const FGmacConfig *}, 驱动默认配置 +#### FGmacCfgInitialize + +- 完成FGMAC驱动实例的初始化,使之可以使用 + +```c +FError FGmacCfgInitialize(FGmac *instance_p, const FGmacConfig *cofig_p); +``` + +Note: + +- 此函数会重置FGMAC控制器和FGMAC控制数据 + +Input: + +- {FGmac} *instance_p 驱动控制数据 + +- {FGmacConfig} *cofig_p 驱动配置数据 + +Return: + +- {FError} 驱动初始化的错误码信息,FGMAC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FGmacDeInitialize + +- 完成FGMAC驱动实例去使能,清零实例数据 + +```c +FError FGmacDeInitialize(FGmac *instance_p); +``` + +Note: + +- 此函数会重置FGMAC控制数据 + +Input: + +- {FGmac} *instance_p 驱动控制数据 + +Return: + +- {FError} 驱动初始化的错误码信息,FGMAC_SUCCESS 表示去初始化成功,其它返回值表示去初始化失败 + +#### FGmacSetupTxDescRing + +- 配置FGMAC的发送DMA描述符和缓冲区 + +```c +FError FGmacSetupTxDescRing(FGmac *instance_p, volatile FGmacDmaDesc *tx_desc_tbl, u8 *tx_buf, const fsize_t tx_pre_buf_len, const fsize_t tx_buf_num); +``` + +Note: + +- 传入的tx_desc_tbl和tx_buf必须为32位空间地址 + +Input: + +- {FGmac *}instance_p 驱动控制数据 + +- {volatile FGmacDmaDesc *} tx_desc_tbl 发送DMA描述符表(数组) + +- {u8} *tx_buf 发送DMA缓冲区(数组,每一个描述符对应一个缓冲区) + +- {const fsize_t} tx_pre_buf_len 单个DMA缓冲区的字节数 + +- {const fsize_t} tx_buf_num DMA描述符或者DMA缓存区的数目 + +Return: + +- {FError} TX DMA初始化的错误码信息,FGMAC_SUCCESS 表示TX DMA初始化成功,其它返回值表示TX DMA初始化失败 + +#### FGmacSetupRxDescRing + +- 配置FGMAC的接收DMA描述符和缓冲区 + +```c +FError FGmacSetupRxDescRing(FGmac *instance_p, volatile FGmacDmaDesc *rx_desc_tbl, u8 *rx_buf, const fsize_t rx_pre_buf_len, const fsize_t rx_buf_num); +``` + +Note: + +- 传入的rx_desc_tbl和rx_buf必须为32位空间地址 + +Input: + +- {FGmac *}instance_p 驱动控制数据 +- {volatile FGmacDmaDesc *} rx_desc_tbl 接收DMA描述符表(数组) +- {u8} *rx_buf 接收DMA缓冲区(数组,每一个描述符对应一个缓冲区) +- {const fsize_t} rx_pre_buf_len 单个DMA缓冲区的字节数 +- {const fsize_t} rx_buf_num DMA描述符或者DMA缓存区的数目 + +Return: + +- {FError} RX DMA初始化的错误码信息,FGMAC_SUCCESS 表示RX DMA初始化成功,其它返回值表示RX DMA初始化失败 + +#### FGmacInterruptHandler + +- FGMAC中断处理函数 + +```c +void FGmacInterruptHandler(s32 vector, void *param); +``` + +Note: + +- 此函数运行在中断上下文 + +Input: + +- {s32} vector, 中断向量号,此处没有用到 +- {void} *param, 中断输入参数,此处传入的是FGMAC的驱动控制数据 + +Return: + +无 + +#### FGmacRegisterEvtHandler + +- 注册FGMAC中断事件响应函数 + +```c +void FGmacRegisterEvtHandler(FGmac *instance_p, u32 evt, FGmacEvtHandler handler); +``` + +Note: + +- 注册的函数handler会在中断上下文执行 + +Input: + +- {FGmac} *instance_p 驱动控制数据 +- {u32} evt 中断事件类型 +- {FGmacEvtHandler} handler 中断事件响应函数 + +Return: + +无 + +#### FGmacStartTrans + +- 使能FGMAC DMA,使之可以接收/发送数据 + +```c +FError FGmacStartTrans(FGmac *instance_p); +``` + +Note: + +- 调用函数前需要确保FGMAC驱动初始化成功 + +Input: + +- {FGmac} *instance_p 驱动控制数据 + +Return: + +- {FError} FGMAC_SUCCESS 表示启动成功,其它返回值表示启动失败 + +#### FGmacStopTrans + +- 去使能FGMAC DMA, 使之不再能接收/发送数据 + +```c +FError FGmacStopTrans(FGmac *instance_p); +``` + +Note: + +- 调用函数前需要确保FGMAC驱动初始化成功 + +Input: + +- {FGmac} *instance_p 驱动控制数据 + +Return: + +- {FError} FGMAC_SUCCESS 表示去启动成功,其它返回值表示去启动失败 + +#### FGmacRecvFrame + +- 通过FGMAC接收数据帧 + +```c +FError FGmacRecvFrame(FGmac *instance_p) +``` + +Note: + +- 调用函数前需要确保FGMAC驱动初始化成功 + +Input: + +- {FGmac} *instance_p 驱动控制数据 + +Return: + +- {FError} FGMAC_SUCCESS 表示接收数据帧成功,其它返回值表示接收数据帧失败 + +#### FGmacSendFrame + +- 通过FGMAC发送数据帧 + +```c +FError FGmacSendFrame(FGmac *instance_p, u32 frame_len); +``` + +Note: + +- 通过FGMAC发送数据帧 + +Input: + +- {FGmac} *instance_p 驱动控制数据 + +- {u32} frame_len 数据帧长度 + +Return: + +- {FError} FGMAC_SUCCESS 表示发送数据帧成功,其它返回值表示发送数据帧失败 + + +#### FGmacPhyLookupConfig + +- 获取FGMAC PHY默认配置参数 + +```c +void FGmacPhyLookupConfig(u32 gmac_instance_id, FGmac *instance_p); +``` + +Note: + +调用此函数前确保 FGMAC 驱动初始化已经成功 + +Input: + +- {u32} gmac_instance_id FGMAC id +- {FGmac} *instance_p FGMAC 控制数据 + +Return: + +无 + +#### FGmacPhyCfgInitialize + +- 查找GMAC连接的phy芯片地址,完成FGMAC PHY驱动实例的初始化,使之可以使用 + +```c +FError FGmacPhyCfgInitialize(FGmac *instance_p); +``` + +Note: + +- 调用此函数前确保 FGMAC 驱动初始化已经成功 + +Input: + +- {FGmac} *instance_p GMAC控制数据 + +Return: + +- {FError} FGMAC_SUCCESS 表示PHY设置成功,其它返回值表示PHY设置失败 + +#### FGmacSetInterruptMask + +- 设置FGMAC中断屏蔽位 + +```c +void FGmacSetInterruptMask(FGmac *instance_p, u32 intr_type, u32 mask, boolean enable); +``` + +Note: + +- 在FGMAC驱动初始化成功后调用此函数 + +Input: + +- {FGmac} *instance_p 驱动控制数据 + +- {u32} intr_type 中断类型 GMAC中断/DMA中断 + +- {u32} mask 中断屏蔽标志位 + +- {boolean} enable TRUE: 使能中断,FALSE: 去使能中断 + +Return: + +无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fgpio.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fgpio.md new file mode 100644 index 0000000000..26010668e1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fgpio.md @@ -0,0 +1,454 @@ +# FGPIO 驱动程序 + +## 1. 概述 + +- GPIO(General-purpose input/output),即通用型输入输出,其引脚可以供使用者通过程序控制其输入、输出,常用于产生时钟,作为片选信号和模拟低速通信协议等场景 + +- FT2000/4和D2000提供两个 GPIO 模块,每个 GPIO 模块有 16 位接口,每8位一组,分别是A组和B组,GPIO可以控制外部IO的输入输出方向,作为输出时,内部寄存器的数据输出到片外,作为输入时,片外的数据被锁存在内部寄存器 + +- FGPIO 驱动支持配置 GPIO 引脚的输入输出方向,输出高低电平,或者获取输入电平,配置引脚的中断触发模式,配置引脚的中断响应回调函数等 + +- FGPIO_VERSION_1 对应 FT2000/4和D2000 的 GPIO,FGPIO_VERSION_2 对应 E2000的 GPIO,具体差异请参考软件编程手册 + +## 2. 功能 + +- FGPIO 驱动程序主要完成GPIO相关的功能配置,包括 + +- 1. GPIO 控制器初始化 +- 2. GPIO 引脚输入输出方向设置 +- 3. GPIO 引脚输出和输入 +- 4. GPIO 引脚中断使能和屏蔽 +- 5. GPIO 引脚中断类型设置 +- 6. GPIO 引脚中断回调函数注册 + +- 驱动相关的源文件如下, +- drivers/pin/fgpio +``` +. +├── Kconfig +├── fgpio.c +├── fgpio.h +├── fgpio_g.c +├── fgpio_hw.h +├── fgpio_selftest.c +├── fgpio_intr.c +└── fgpio_sinit.c +``` + +## 3. 配置方法 + +- FGPIO 驱动支持 FT2000/4, D2000和E2000,在 D2000 和 E2000 上完成测试 + +- 参考以下步骤完成 FGPIO 硬件配置, +- 1. 获取FT2000/4, D2000或E2000的软件编程手册,参考引脚复用表,设置引脚复用为 GPIO +- 2. 初始化 GPIO 控制器实例 +- 3. 设置 GPIO 引脚的输入,输出方向 +- 4. 获取 GPIO 引脚上的输入,或者设置 GPIO 引脚的输出电平 +- 5. 设置 GPIO 引脚的中断屏蔽位和中断触发类型,注册引脚的中断回调函数 + +## 4 应用示例 + +- 设置 GPIO 引脚的输出电平,获取引脚的输入电平,通过外部输入触发 GPIO 中断 + +### [fgpio_irq](../../../baremetal/example/peripheral/pin/fgpio_irq) + +- 通过 GPIO 产生占空比和频率可配的 PWM 波形 + +### [fgpio_soft_pwm](../../../baremetal/example/peripheral/pin/fgpio_soft_pwm) + +## 5. API参考 + +### 5.1. 用户数据结构 + +#### FGpioConfig + +```c +typedef struct +{ + u32 instance_id; /* GPIO实例ID */ + uintptr base_addr; /* GPIO控制器基地址 */ +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + u32 irq_num; /* GPIO控制器中断号 */ +#elif defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ + u32 irq_num[FGPIO_PIN_NUM]; /* GPIO各引脚的中断号 */ +#endif + u32 irq_priority; /* 中断优先级 */ +} FGpioConfig; /* GPIO控制器配置 */ +``` + +#### FGpioPin + +```c +typedef struct _FGpioPin +{ + FGpioPinId index; /* 索引 */ + u32 is_ready; + FGpio *instance; + FGpioInterruptCallback irq_cb; /* 中断回调函数, Port-A有效 */ + void *irq_cb_params; /* 中断回调函数的入参, Port-A有效 */ + boolean irq_one_time; /* Port-A有效, TRUE: 进入中断后关闭该引脚的中断,用于电平敏感中断,防止一直进入中断 */ +} FGpioPin; /* GPIO引脚实例 */ +``` + +#### FGpio + +```c +typedef struct _FGpio +{ + FGpioConfig config; + u32 is_ready; + FGpioPin *pins[FGPIO_PORT_NUM][FGPIO_PIN_NUM]; +} FGpio; /* GPIO控制器实例 */ +``` +### 5.2 错误码定义 + +- [0x0] FGPIO_SUCCESS : success + +- [0x1050000] FGPIO_ERR_INVALID_PARA : invalid input parameters + +- [0x1050001] FGPIO_ERR_INVALID_STATE : invalid state + + +### 5.3 用户API接口 + +#### FGpioLookupConfig + +```c +const FGpioConfig *FGpioLookupConfig(u32 instance_id); +``` + +Note: + +- 获取GPIO控制器的默认配置 + +Input: + +- {u32} instance_id, GPIO控制器实例号 + +Return: + +- {const FGpioConfig *} GPIO控制器的默认配置 + +#### FGpioCfgInitialize + +```c +FError FGpioCfgInitialize(FGpio *const instance, const FGpioConfig *const config); +``` + +Note: + +- 初始化GPIO控制器实例 + +Input: + +- {FGpio} *instance, GPIO控制器实例 +- {FGpioConfig} *config, GPIO控制器配置 + +Return: + +- {FError} FGPIO_SUCCESS 表示初始化成功 + +#### FGpioDeInitialize + +```c +void FGpioDeInitialize(FGpio *const instance); +``` + +Note: + +- 去初始化GPIO控制器实例 + +Input: + +- {FGpio} *instance, GPIO控制器实例 + +Return: + +- 无 + +#### FGpioPinInitialize + +```c +FError FGpioPinInitialize(FGpio *const instance, FGpioPin *const pin, + const FGpioPinId pin_id); +``` + +Note: + +- 初始化GPIO引脚实例 + +Input: + +- {FGpio} *instance, GPIO控制器实例 +- {FGpioPin} *pin_instance, GPIO引脚实例 +- {FGpioPinId} index, GPIO引脚索引 + +Return: + +- {FError} FGPIO_SUCCESS 表示初始化成功 + +#### FGpioPinDeInitialize + +```c +void FGpioPinDeInitialize(FGpioPin *const pin); +``` + +Note: + +- 去初始化GPIO引脚实例 + +Input: + +- {FGpioPin} *pin_instance, GPIO引脚实例 + +Return: + +- {FError} FGPIO_SUCCESS 表示初始化成功 + +#### FGpioGetPinIrqSourceType + +```c +FGpioIrqSourceType FGpioGetPinIrqSourceType(FGpioPin *const pin); +``` + +Note: + +- 获取引脚中断的上报方式 + +Input: + +- {FGpioPin} *pin_instance, GPIO引脚实例 + +Return: + +- {FGpioIrqSourceType} 引脚中断的上报方式 + +#### FGpioSetDirection + +```c +void FGpioSetDirection(FGpioPin *const pin, FGpioDirection dir); +``` + +Note: + +- 设置GPIO引脚的输入输出方向 +- 初始化 GPIO 实例后使用此函数 + +Input: + +- @param {FGpioPin} *instance, GPIO控制器实例 +- @param {FGpioDirection} dir, 待设置的GPIO的方向 + +Return: + +- 无 + +#### FGpioGetDirection + +```c +FGpioDirection FGpioGetDirection(FGpioPin *const pin); +``` + +Note: + +- 获取GPIO引脚的输入输出方向 +- 初始化 GPIO 实例后使用此函数 + +Input: + +- {FGpioPin} *pin, GPIO引脚实例 + +Return: + +- {FGpioDirection} GPIO引脚方向 + +#### FGpioSetOutputValue + +```c +FError FGpioSetOutputValue(FGpioPin *const pin, const FGpioPinVal output); +``` + +Note: + +- 设置GPIO引脚的输出值 +- 初始化 GPIO 实例后使用此函数,先设置 GPIO 引脚为输出后调用此函数 + +Input: + +- {FGpioPin} *pin, GPIO引脚实例 +- {FGpioPinVal} output, GPIO引脚的输出值 + +Return: + +- {FError} FGPIO_SUCCESS 表示设置成功 + +#### FGpioGetInputValue + +- 获取GPIO引脚的输入值 + +```c +FGpioPinVal FGpioGetInputValue(FGpioPin *const pin); +``` + +Note: + +- 初始化 GPIO 实例后使用此函数,先设置 GPIO 引脚为输入后调用此函数 + +Input: + +- {FGpioPin} *instance, GPIO引脚实例 +- {FGpioPinVal} output, GPIO引脚的输出值 + +Return: + +- {FGpioPinVal} 获取的输入值,高电平/低电平 + +#### FGpioGetInterruptMask + +- 获取GPIO A组引脚的中断屏蔽位 + +```c +void FGpioGetInterruptMask(FGpio *const instance, u32 *mask, u32 *enabled) +``` + +Note: + +- 获取的是A组所有Pin的中断屏蔽位和中断使能位 + +Input: + +- {FGpio} *instance, GPIO控制器实例 +- {u32} *mask, 返回的GPIO A组引脚中断屏蔽位 +- {u32} *enabled, 返回的GPIO A组中断使能位 + +Return: + +- 无 +#### FGpioSetInterruptMask + +- 设置GPIO A组引脚的中断屏蔽位 + +```c +void FGpioSetInterruptMask(FGpioPin *const pin, boolean enable); +``` + +Note: + +- index对应的引脚必须为A组引脚,B组引脚不支持中断 + +Input: + +- {FGpioPin} *pin, GPIO引脚实例 +- {boolean} enable, TRUE表示使能GPIO引脚中断,FALSE表示去使能GPIO引脚中断 + +Return: + +- 无 +#### FGpioGetInterruptType + +- 获取GPIO A组引脚的中断类型和中断极性 + +```c +void FGpioGetInterruptType(FGpio *const instance, u32 *levels, u32 *polarity) +``` + +Note: + +- 获取的是A组所有Pin的电平和极性 + +Input: + +- {FGpio} *instance, GPIO控制器实例 +- {u32} *levels, GPIO A组引脚中断电平类型 +- {u32} *polarity, GPIO A组引脚中断极性类型 + +Return: + +- 无 + +#### FGpioSetInterruptType + +- 设置GPIO引脚的中断类型 + +```c +void FGpioSetInterruptType(FGpioPin *const pin, const FGpioIrqType type) +``` + +Note: + +- index对应的引脚必须为A组引脚,B组引脚不支持中断 + +Input: + +- {FGpioPin} *pin, GPIO引脚实例 +- {FGpioIrqType} type, GPIO引脚中断触发类型 + +Return: + +- 无 + +#### FGpioInterruptHandler + +- GPIO中断处理函数 + +```c +void FGpioInterruptHandler(s32 vector, void *param) +``` + +Note: + +- 需要用户将此函数注册到Interrtup上,使能GPIO中断才能生效 + +Input: + +- {s32} vector, 中断输入参数1 +- {void} *param, 中断输入参数2 + +Return: + +- 无 + + +#### FGpioPinInterruptHandler + +- GPIO中断处理函数 + +```c +void FGpioPinInterruptHandler(s32 vector, void *param) +``` + +Note: + +- 需要用户将此函数注册Gic上,才能生效 + +Input: + +- {s32} vector, 中断输入参数1 +- {void} *param, 中断输入参数2 + +Return: + +- 无 + +#### FGpioRegisterInterruptCB + +- 注册GPIO引脚中断回调函数 + +```c +void FGpioRegisterInterruptCB(FGpioPin *const pin, FGpioInterruptCallback cb, void *cb_param, boolean irq_one_time) +``` + +Note: + +- 注册的回调函数在`FGpioInterruptHandler`中被调用 + +Input: + +- {FGpioPin} pin, GPIO引脚实例 +- {FGpioInterruptCallback} cb, GPIO引脚中断回调函数 +- {void} *cb_param, GPIO引脚中断回调函数输入参数 +- {boolean} irq_one_time, TRUE表示引脚中断触发一次后自动关闭中断,用于电平敏感中断 + +Return: + +- 无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fi2c.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fi2c.md new file mode 100644 index 0000000000..5321e1a7c9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fi2c.md @@ -0,0 +1,340 @@ +# I2C 驱动程序 + +## 1. 概述 + + +- I2C 是一种串行同步半双工通信协议,总线上可以同时挂载多个主机和从机。I2C 总线由串行数据线 (SDA) 和串行时钟线 (SCL) 线构成。这些线都需要上拉电阻。 + +- I2C 具有简单且制造成本低廉等优点,主要用于低速外围设备的短距离通信(一英尺以内)。 + +- I2C 驱动支持的平台包括 FT2000/4、D2000。 + + +## 2. 驱动功能 + +I2C 驱动程序管理在 I2C 总线上设备的通信,该驱动程序具备以下功能: + +- 在主机模式下读写字节 +- 支持从机模式 + +## 3. 使用方法 + +以下部分将指导您完成 I2C 驱动的硬件配置: + +- 1. I2C驱动支持 FT2000/4, D2000和E2000,在FT2000/4上完成测试 +- 2. FT2000/4, D2000上,使用I2C驱动需要打开IO复用,I2C0的引脚默认设置为给I2C使用,I2C1/I2C2/I2C3需要先设置IO复用才能使用 +- 3. E2000上,使用MIO的的IIC驱动需要打开MIO配置功能寄存器,设置IIC模式,引脚复用设置为MIO功能,才能使用 +- 4. FT2000/4, D2000上,I2C的参考时钟为48MHz,在E2000上,I2C的参考时钟为50MHz 不支持修改设置 + +以下部分将指导您完成 I2C 驱动的软件配置: + +- 1. 配置驱动程序,新建应用工程,使能I2C驱动模块 +- 2. 设置配置参数,选择为 I2C 主机还是从机,调整默认的 I2C 通信参数(如时序、位序等) +- 3. 配置中断服务 +- 4. 处理错误码 +- 5. 去使能驱动程序 + +## 4. 应用示例 + +### [fi2c_eeprom](../../../baremetal/example/peripheral/i2c/fi2c_eeprom/README.md) + +### [fi2c_slave](../../../baremetal/example/peripheral/i2c/fi2c_master_slave/README.md) + + +## 5. API参考 + + +### 5.1. 用户数据结构 + +- drivers/i2c/fi2c/fi2c.h + +```c + +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num; /* Device intrrupt id */ + u32 irq_prority; /* Device intrrupt priority */ + u32 ref_clk_hz; /* Input reference clock frequency in Hz */ + u32 work_mode; /* Device work mode Slave or Master */ + u32 slave_addr; /* Slave Address writing/reading to/from */ + boolean use_7bit_addr; /* Slave in-chip address offset in 7bit or 10bit */ + u32 speed_rate; /* I2C speed rate */ +} FI2cConfig; /* Device configure setting */ +``` + +- I2C驱动实例配置 + +```c + +typedef struct +{ + FI2cConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + volatile u32 status; + FI2cFrameTX txframe; + FI2cFrameRX rxframe; + /** only apply to master device **/ + /* Master intrrupt handler */ + FI2cEvtHandler master_evt_handlers[FI2C_MASTER_INTR_EVT_NUM]; + + /** only apply to slave device **/ + /* Slave intrrupt handler */ + FI2cEvtHandler slave_evt_handlers[FI2C_SLAVE_INTR_EVT_NUM]; + +} FI2c; /* Device instance */ +``` + +- I2C驱动实例 + +### 5.2 错误码定义 + +- 模块错误码编号 `0x10b0000` + +- [0x0] FI2C_SUCCESS : fi2c success + +- [0x10b0001] FI2C_ERR_INVAL_PARM : fi2c invalid input parameters + +- [0x10b0002] FI2C_ERR_NOT_READY : fi2c driver not ready + +- [0x10b0001] FI2C_ERR_INVAL_PARM : fi2c invalid input parameters + +- [0x10b0003] FI2C_ERR_TIMEOUT : fi2c wait timeout + +- [0x10b0004] FI2C_ERR_NOT_SUPPORT : fi2c non support operation + +- [0x10b0005] FI2C_ERR_INVAL_STATE : fi2c invalid state + +### 5.3 用户API接口 + + +```c +const FI2cConfig *FI2cLookupConfig(u32 instance_id); +``` +- 获取I2C驱动的默认配置参数 + +Note: + + - 用户需要修改配置参数时,可以通过修改返回的FI2cConfig副本,作为FI2cCfgInitialize函数的入参, + +Input: + + - u32 instance_id, 当前控制的I2C控制器实例号 + +Return: + + - const FI2cConfig *, 返回驱动默认参数, NULL表示失败 + + +```c +FError FI2cCfgInitialize(FI2c *instance_p, const FI2cConfig *cofig_p); +``` +- 完成I2C驱动实例的初始化,使之可以使用 + +Note: + + - 此函数会将驱动实例中的所有数据全部重置,同时会进行I2C控制器的重置,请不要在I2C数据传输过程中调用此函数 + +Input: + + - FI2c *instance_p, I2C驱动实例数据 + + - const FI2cConfig *cofig_p, I2C驱动配置数据 + +Return: + + FError,参考6.2章错误码定义 + +```c +void FI2cDeInitialize(FI2c *instance_p); +``` + +- 完成I2C驱动实例去使能,清零实例数据 + +Note: + + - 此函数会将驱动实例中的所有数据全部重置, + +Input: + + - FI2c *instance_p, I2C驱动实例数据 + +Return: + + 无 + +```c +const char *FI2cErrorToMessage(FError error); +``` + +- 获取I2C模块错误码对应的错误信息 + +Note: + + - 请输入属于FI2C模块的错误码,否则返回的错误信息为空 + +Input: + + - {FError} error, I2C输入错误码 + +Return: + + - {const char *}, 错误码信息,NULL表示失败 + +```c +FError FI2cMasterReadPoll(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, u8 *buf_p, u32 buf_len); +``` +- I2C主机读,阻塞直到完成读操作或失败 + +Note: + - 请先初始化I2C驱动再调用此函数 + - 请在Master工作模式下调用此函数 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + - @param {u32} inchip_addr 从机的内部偏移地址 + - @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + - @param {u8} *buf_p 读目的缓冲区 + - @param {int} buf_len 读目的缓冲区长度 + +Return: + - @return {FError *} 返回错误码 + +```c +FError FI2cMasterReadIntr(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, u8 *buf_p, u32 buf_len); +``` +- I2C主机读,接收中断读操作或者失败 + +Note: + - 请先初始化I2C驱动再调用此函数 + - 请在Master工作模式下调用此函数 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + - @param {u32} inchip_addr 从机的内部偏移地址 + - @param {u8} *buf_p 读目的缓冲区 + - @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + - @param {int} buf_len 读目的缓冲区长度 + +Return: + - @return {FError *} 返回错误码 + +```c +FError FI2cMasterWriteIntr(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, const u8 *buf_p, u32 buf_len); +``` +- I2C主机读,中断发送直到完成写操作或失败 +Note: + - 请先初始化I2C驱动再调用此函数 + - 请在Master工作模式下调用此函数 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + - @param {u32} inchip_addr 从机的内部偏移地址 + - @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + - @param {u8} *buf_p 写源缓冲区 + - @param {size_t} buf_len 写源缓冲区长度 + +Return: + - @return {FError *} 返回错误码 + +```c +FError FError FI2cMasterWritePoll(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, const u8 *buf_p, u32 buf_len); +``` +- I2C主机写,阻塞直到完成写操作或失败 + +Note: + - 请先初始化I2C驱动再调用此函数 + - 请在Master工作模式下调用此函数 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + - @param {u32} inchip_addr 从机的内部偏移地址 + - @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + - @param {u8} *buf_p 写源缓冲区 + - @param {size_t} buf_len 写源缓冲区长度 + +Return: + - @return {FError *} 返回错误码 + +```c +u32 FI2cGetIntr(FI2c *instance_p); +``` +- 获取I2C instance_p的中断值 + +Note: + - 请先初始化I2C驱动再调用此函数 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + +Return: + - @return {u32} 中断状态寄存器的值 + +```c +FError FI2cMasterSetupIntr(FI2c *instance_p,u32 mask); +``` +- 设置I2C主机的中断 + +Note: + - 请先初始化I2C驱动再调用此函数 + - 请在Master工作模式下调用此函数 + +Input: + - {FI2c} *instance_p I2C驱动实例数据 + - {u32} mask 需要操作的中断寄存器位 +Return: + - {FError *} 返回错误码 + +```c +void FI2cMasterRegisterIntrHandler(FI2c *instance_p, u32 evt, FI2cEvtHandler handler); +``` +- 注册I2C主机中断事件函数 + +Note: + 无 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + - @param {u32} evt 中断事件,参考 FI2C_MASTER_INTR_EVT_NUM + - @param {FI2cEvtHandler} handler 中断事件回调函数 + +Return: + + 无 + +```c +FError FI2cSlaveSetupIntr(FI2c *instance_p); +``` + +- 设置I2C从机的中断 + +Note: + - 请先初始化I2C驱动再调用此函数 + - 请在Slave工作模式下调用此函数 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + - @param {u32} evt 中断事件,参考 FI2C_MASTER_INTR_EVT_NUM + - @param {FI2cEvtHandler} handler 中断事件回调函数 + +Return: + - {FError *} 返回错误码 + +```c +void FI2cSlaveRegisterIntrHandler(FI2c *instance_p, u32 evt, FI2cEvtHandler handler); +``` + +- 注册I2C从机中断事件函数 + +Note: + 无 + +Input: + - @param {FI2c} *instance_p I2C驱动实例数据 + - @param {u32} evt 中断事件,参考 FI2C_SLAVE_INTR_EVT_NUM + - @param {FI2cEvtHandler} handler 中断事件回调函数 + +Return: + + 无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/figs/pwm_duty.png b/bsp/phytium/libraries/standalone/doc/reference/driver/figs/pwm_duty.png new file mode 100644 index 0000000000..8de9c1cd82 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/reference/driver/figs/pwm_duty.png differ diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/figs/spi_app.dio b/bsp/phytium/libraries/standalone/doc/reference/driver/figs/spi_app.dio new file mode 100644 index 0000000000..3e019f2ea7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/figs/spi_app.dio @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/figs/spi_app.png b/bsp/phytium/libraries/standalone/doc/reference/driver/figs/spi_app.png new file mode 100644 index 0000000000..8dbd4fcdc1 Binary files /dev/null and b/bsp/phytium/libraries/standalone/doc/reference/driver/figs/spi_app.png differ diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fmio.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fmio.md new file mode 100644 index 0000000000..02fd557322 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fmio.md @@ -0,0 +1,180 @@ +# I2C 驱动程序 + +## 1. 概述 + +- E2000 的 MIO 接口可配置为 UART 或 I2C,具体时序特性要求需满足复用功能的时序特性要求。当需要使用对应的功能时,只需要软件进行相应配置. +- MIO 仅仅支持E2000系列芯片 + +## 2. 驱动功能 + +MIO 驱动程序管理MIO的功能复用,该驱动程序具备以下功能: + +- 选择设置I2C模式或者串口模式 +- 获取状态信息和版本信息 + +## 3. 使用方法 + +以下部分将指导您完成 MIO 驱动的硬件配置: + +- 1. MIO驱动支持 E2000 Q D S,在E2000上完成测试 +- 2. 本驱动仅仅作为IIC、串口的功能开启关闭使用,搭配串口驱动,与IIC驱动去使用,无法单独调用去实现具体功能 + +以下部分将指导您完成 MIO 驱动的软件配置: + +- 1. 配置驱动程序,新建应用工程,传入设备ID参数,获取设备参数 +- 2. 得到设备参数,操作设置配置项目 +- 3. 进行I2C或者uart操作配置流程 + +## 5. API参考 + +### 5.1. 用户数据结构 + +- drivers/mio/fmio/fmio.h + +```c + +typedef struct +{ + FMioConfig config; /* mio config */ + u32 is_ready; /* mio initialize the complete flag */ +}FMioCtrl; + +``` + +```c + +typedef struct +{ + u32 instance_id; /*mio id*/ + uintptr func_base_addr; /*I2C or UART function address*/ + u32 irq_num; /* Device intrrupt id */ + uintptr mio_base_addr; /*MIO control address*/ + u32 version; /*mio version*/ + u32 function_type; /*mio function type*/ + u32 mio_status; /*mio function type status*/ +} FMioConfig; /*mio configs*/ + +``` +- MIO驱动实例 + +### 5.3 用户API接口 + +```c +const FMioConfig *FMioLookupConfig(u32 instance_id); +``` +- 获取MIO驱动的默认配置参数 + +Note: + + - 用户需要修改配置参数时,可以通过修改返回的FMioConfig副本,作为FMioSelectFunc函数的入参, + +Input: + + - u32 instance_id, 当前控制的MIO控制器实例号 + +Return: + + - const FMioConfig *, 返回驱动默认参数, NULL表示失败 + + +```c +FError FMioSelectFunc(uintptr addr, u32 mio_type); +``` +- 设置MIO驱动的功能配置 + +Note: + - 设置Mio功能 + +Input: + - uintptr addr, 当前控制器的MIO基地址 + - u32 mio_type, 想要设置的MIO功能 +Return: + - @return {FError *} 返回错误码 + +```c +u32 FMioGetFunc(uintptr addr); +``` +- 获取当前MIO的配置 + +Note: + - 获取Mio功能 + +Input: + - uintptr addr, 当前控制器的MIO基地址 + +Return: + - @return {u32} 返回MIO的状态 + +```c +u32 FMioGetVersion(uintptr addr); +``` +- 获取版本信息 + +Note: + - 获取Mio版本 + +Input: + - uintptr addr, 当前控制器的MIO基地址 + +Return: + - @return {u32} 返回MIO的版本 + +```c +FError FMioFuncInit(FMioCtrl *instance_p, u32 mio_type) +``` +- 初始化MIO + +Note: + - 初始化MIO的功能 + +Input: + - FMioCtrl *instance_p, 当前控制器的结构体 + - u32 mio_type,需要配置的选项,串口还是IIC + +Return: + - @return {u32} 返回初始化的状态 + +```c +FError FMioFuncDeinit(FMioCtrl *instance_p) +``` + +- 去初始化MIO + +Note: + - 去初始化MIO的结构体,和相关寄存器 + +Input: + - FMioCtrl *instance_p, 当前控制器的结构体 + +Return: + - @return {u32} 返回去初始化的状态 + +```c +uintptr FMioFuncGetAddress(FMioCtrl *instance_p,u32 mio_type); +``` +- 获取功能配置的基地址 + +Note: + - 获取功能配置的基地址,如果当前配置和目标配置不一致,则失败 + +Input: + - FMioCtrl *instance_p, 当前控制器的结构体 + - u32 mio_type, 目标配置的类型UART或者I2c + +Return: + - @return {uintptr} 返回基地址的值 + +```c +u32 FMioFuncGetIrqNum(FMioCtrl *instance_p,u32 mio_type); +``` +- 获取功能的中断号 + +Note: + - 获取功能配置的中断号,如果当前配置和目标配置不一致,则失败 + +Input: + - FMioCtrl *instance_p, 当前控制器的结构体 + - u32 mio_type, 目标配置的类型UART或者I2c + +Return: + - @return {u32} 返回中断号 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fnand.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fnand.md new file mode 100644 index 0000000000..75e7aab9e4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fnand.md @@ -0,0 +1,447 @@ + + +# 驱动概述 +- NAND 作为廉价的存储介质,在大文件的存储场景中占有重要的地位,由此在嵌入式方案中,如何将此驱动做稳定做易用,尤为重要。NAND 控制器驱动具有以下特性: + +1. 支持模式 Toggle 介质模式 +2. 支持模式时序配置 ,同步模式,异步模式 +3. 支持请求之间时间间隔 +4. 采用dma 数据方式进行传输 +5. 支持时序模式下的高频时钟采样相位调节 +6. 支持硬件ECC纠错 +当前NAND 驱动控制器主要为用户提供了以下功能接口: +1. NAND 控制器状态初始化函数 +2. NAND 介质扫描接口 +3. NAND 介质page读/写接口,块擦除接口,spare space 读写接口 +4. 中断相关接口 +5. 坏块管理接口 + +## 驱动功能 + +驱动组成由以下所示 : + +. +├── fnand_bbm.c +├── fnand_bbm.h +├── fnand.c +├── fnand_dma.c +├── fnand_dma.h +├── fnand_ecc.c +├── fnand_ecc.h +├── fnand_g.c +├── fnand.h +├── fnand_hw.c +├── fnand_hw.h +├── fnand_intr.c +├── fnand_option.c +├── fnand_sinit.c +├── fnand_timing.c +├── fnand_timing.h +├── fnand_toggle.c +└── fnand_toggle.h + +其中fnand.h 为用户开发者主要使用接口,提供了以下功能: +1. Nand 控制器初始化接口 +2. 根据Nand 介质id 初始化介质页/块的大小 +3. Nand 控制器相关状态位的回调函数注册 +4. Nand 控制器中断处理函数 +5. Nand 坏块管理函数 + + +## 数据结构 +```c + typedef struct _FNand + { + u32 is_ready; /* Device is ininitialized and ready*/ + FNandConfig config; + u32 work_mode; /* NAND controler work mode */ + + /* nand flash info */ + FNandInterMode inter_mode[FNAND_CONNECT_MAX_NUM]; /* NAND controler timing work mode */ + FNandTimingMode timing_mode[FNAND_CONNECT_MAX_NUM]; + u32 nand_flash_interface[FNAND_CONNECT_MAX_NUM] ; /* Nand Flash Interface , followed by FNAND_ONFI_MODE \ FNAND_TOGGLE_MODE*/ + + struct FNandDmaBuffer dma_data_buffer; /* DMA data buffer */ + struct FNandDmaBuffer descriptor_buffer; /* DMA descriptor */ + struct FNandDmaDescriptor descriptor[2]; /* DMA descriptor */ + struct FNandSdrTimings sdr_timing; /* SDR NAND chip timings */ + + /* bbm */ + FNandBadBlockManager bbt_manager[FNAND_CONNECT_MAX_NUM]; /* bad block manager handler */ + /* nand detect */ + FNandNandGeometry nand_geometry[FNAND_CONNECT_MAX_NUM]; /* nand flash infomation */ + /* dma 页操作 */ + FnandIrqEventHandler irq_event_fun_p; /* Interrupt event response function */ + void *irq_args; + + FNandOperationWaitIrqCallback wait_irq_fun_p; /* The NAND controller operates the wait function */ + void *wait_args; + + /* operations */ + FNandTransferP write_p ; /* Write page function */ + FNandTransferP read_p ; /* Read page function */ + FNandTransferP write_oob_p ; /* Write page spare space function */ + FNandTransferP read_oob_p ; /* Read page spare space function */ + FNandTransferP write_hw_ecc_p ; /* Write page with hardware function */ + FNandTransferP read_hw_ecc_p ; /* Read page with hardware function */ + FNandEraseP erase_p; /* Erase block function */ + } FNand; +``` + +## 错误码定义 +``` +FNAND_ERR_OPERATION /* NAND 控制器操作NAND flash 失败 */ +FNAND_ERR_INVAILD_PARAMETER /* 当NAND 控制器配置信息不存在 */ +FNAND_IS_BUSY /* NAND 控制器操作NAND flash ,控制器正忙 */ +FNAND_OP_TIMEOUT /* NAND 控制器操作超时*/ +FNAND_VALUE_ERROR /* NAND 控制器在进行BBM 搜索过程时,获取坏块管理信息不匹配 */ +FNAND_VALUE_FAILURE /* 获取的数据与预期不相符合 */ +FNAND_NOT_FET_TOGGLE_MODE /* toggle 模式 */ +FNAND_ERR_READ_ECC /* 读取过程中,进行硬件ecc ,错误超过纠错的范围 */ +FNAND_ERR_IRQ_OP_FAILED /* 中断进行读/写/擦操作时,回调函数反馈错误 */ +FNAND_ERR_IRQ_LACK_OF_CALLBACK /* 中断进行读/写/擦操作时,缺少回调函数 */ +FNAND_ERR_IRQ_OP_FAILED /* 等待中断回应失败 */ +FNAND_ERR_NOT_MATCH /* 进行flash id 检测时,检测结果与预期不符合 */ +``` +## 应用例程 +- baremetal/example/peripheral/nand/nand_test +## API 介绍 + +### 1. FNandLookupConfig + +``` +FNandConfig *FNandLookupConfig(u32 instance_id) +``` + +#### 介绍 +- 获取当前FNand驱动默认配置 + +#### 参数 +- u32 instance_id :当前Nand驱动中对应的ID + +#### 返回 +FGicConfig * :静态默认配置 + + +### 2. FNandCfgInitialize + +``` +FError FNandCfgInitialize(FNand *instance_p,FNandConfig *config_p) +``` + +#### 介绍 +- 根据传入配置,初始化NAND驱动实例 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- FNandConfig * 需要应用于示例中的配置项 + +#### 返回 +- FError :FT_SUCCESS 为初始成功 + +### 3. FNandScan + +``` +FError FNandScan(FNand *instance_p) +``` + +#### 介绍 +- Nand flash 扫描,此接口调用之后会自动扫描Nand flash 介质信息 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 + +#### 返回 +- FError :FT_SUCCESS 为初始成功 + +### 4. FNandWritePage + +``` +FError FNandWritePage(FNand *instance_p,u32 page_addr,u8 *buffer,u32 page_copy_offset ,u32 length,u8 *oob_buffer,u32 oob_copy_offset,u32 oob_length,u32 chip_addr) +``` + +#### 介绍 +- 每次写一个页面的操作,包括写页面数据和空闲数据 ,默认会进行硬件ecc 编码写入 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- u32 page_addr 页操作地址,单位为页 +- u8 *buffer 指向写入内容缓冲区的指针 +- u32 page_copy_offset 写入某一页中的具体位置,当此参数非0 时,写入的地址为 ,在page_addr 对应的页面下,0 + page_copy_offset 开始的地址,未覆盖的地方默认填入0xff +- u32 length 数据写入页面下的长度 +- u8 *oob_buffer 指向写入spare space内容 缓冲区的指针 +- u32 oob_copy_offset 写入某一页中spare space 的具体位置,当此参数非0 时,在page_addr 对应的页面下,写入的地址为 页长度 + page_copy_offset 开始的地址,未覆盖的地方默认填入0xff +- u32 oob_length spare space数据写入页面下的长度 +- u32 chip_addr 芯片地址 + +#### 返回 +- FError :FT_SUCCESS 为写入成功 + +### 5. FNandWritePageRaw + +``` +FError FNandWritePageRaw(FNand *instance_p,u32 page_addr,u8 *buffer,u32 page_copy_offset ,u32 length,u8 *oob_buffer,u32 oob_copy_offset,u32 oob_length,u32 chip_addr) +``` + +#### 介绍 +- 每次写一个页面的操作,包括写页面数据和空闲数据 ,默认不会进行硬件ecc 编码写入 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- u32 page_addr 页操作地址,单位为页 +- u8 *buffer 指向写入内容缓冲区的指针 +- u32 page_copy_offset 写入某一页中的具体位置,当此参数非0 时,写入的地址为 ,在page_addr 对应的页面下,0 + page_copy_offset 开始的地址,未覆盖的地方默认填入0xff +- u32 length 数据写入页面下的长度 +- u8 *oob_buffer 指向写入spare space内容 缓冲区的指针 +- u32 oob_copy_offset 写入某一页中spare space 的具体位置,当此参数非0 时,在page_addr 对应的页面下,写入的地址为 页长度 + page_copy_offset 开始的地址,未覆盖的地方默认填入0xff +- u32 oob_length spare space数据写入页面下的长度 +- u32 chip_addr 芯片地址 + +#### 返回 +- FError :FT_SUCCESS 为写入成功 + + +### 6. FNandReadPage + +``` +FError FNandReadPage(FNand *instance_p,u32 page_addr,u8 *buffer,u32 page_copy_offset,u32 length,u8 *oob_buffer,u32 oob_copy_offset,u32 oob_length,u32 chip_addr) +``` + +#### 介绍 +- 每次读出一个页面的操作,包括读页面数据和空闲数据 ,默认会进行ecc 纠错 + +#### 参数 +``` +FNand *instance_p FNand 控制器实例的指针 +u32 page_addr 页操作地址,单位为页 +u8 *buffer 指向读出内容缓冲区的指针 +u32 page_copy_offset 读出某一页中的具体位置,当此参数非0 时,读出的地址为 ,在page_addr 对应的页面下 0 + page_copy_offset 开始的地址 +u32 length 数据读出页面下的长度 +u8 *oob_buffer 指向读出spare space内容 缓冲区的指针 +u32 oob_copy_offset 读出某一页中spare space 的具体位置,当此参数非0 时,在page_addr 对应的页面下,读出的地址为 页长度 + page_copy_offset 开始的地址 +u32 oob_length spare space数据读出的长度 +u32 chip_addr 芯片地址 +``` + + +#### 返回 +- FError :FT_SUCCESS 为读出成功 + +### 7. FNandReadPageRaw + +``` +FError FNandReadPageRaw(FNand *instance_p,u32 page_addr,u8 *buffer,u32 page_copy_offset,u32 length,u8 *oob_buffer,u32 oob_copy_offset,u32 oob_length,u32 chip_addr) +``` + +#### 介绍 +- 每次读出一个页面的操作,包括读页面数据和空闲数据 ,不会进行ecc 纠错 + +#### 参数 +``` +FNand *instance_p FNand 控制器实例的指针 +u32 page_addr 页操作地址,单位为页 +u8 *buffer 指向读出内容缓冲区的指针 +u32 page_copy_offset 读出某一页中的具体位置,当此参数非0 时,读出的地址为 ,在page_addr 对应的页面下 0 + page_copy_offset 开始的地址 +u32 length 数据读出页面下的长度 +u8 *oob_buffer 指向读出spare space内容 缓冲区的指针 +u32 oob_copy_offset 读出某一页中spare space 的具体位置,当此参数非0 时,在page_addr 对应的页面下,读出的地址为 页长度 + page_copy_offset 开始的地址 +u32 oob_length spare space数据读出的长度 +u32 chip_addr 芯片地址 +``` + + +#### 返回 +- FError :FT_SUCCESS 为读出成功 + +### 8. FNandEraseBlock + +``` +FError FNandEraseBlock(FNand *instance_p, u32 block, u32 chip_addr) +``` + +#### 介绍 +- 擦除块数据 + +#### 参数 +FNand *instance_p FNand 控制器实例的指针 +u32 block 块的位置号 +u32 chip_addr 芯片地址 + +#### 返回 +- FError :FT_SUCCESS 为写入成功 + + + +### 9. FNandReadPageOOb + +``` +FError FNandReadPageOOb(FNand *instance_p,u32 page_addr,u8 *oob_buffer,u32 oob_copy_offset,u32 oob_length,u32 chip_addr) +``` + +#### 介绍 +- 读取每一页中的 spare space 内容 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- u32 page_addr 需要读取空闲空间的Row Address +- u8 * oob_buffer 指向读取数据的缓冲区 +- u32 oob_copy_offset 读出某一页中spare space 中位置的偏移,当此参数非0 时,读出的地址为 ,在page_addr 对应的页面下 page length + oob_copy_offset 开始的地址 +- u32 oob_length 需要读取是页面中spare space 中的长度 +- u32 chip_addr 芯片地址 + +#### 返回 +- FError :FT_SUCCESS 为写入成功 + +### 10. FNandWritePageOOb + + +``` +FError FNandWritePageOOb(FNand *instance_p,u32 page_addr,u8 *oob_buffer,u32 page_copy_offset,u32 oob_length,u32 chip_addr) +``` + +#### 介绍 +- 读取每一页中的 spare space 内容 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- u32 page_addr 需要写入空闲空间的Row Address +- u8 * oob_buffer 指向写入数据的缓冲区 +- u32 oob_copy_offset 写入某一页中spare space 中位置的偏移,当此参数非0时,写入的地址为 ,在page_addr 对应的页面下 page length + oob_copy_offset 开始的地址 +- u32 oob_length 需要写入是页面中spare space 中的长度 +- u32 chip_addr 芯片地址 + +#### 返回 +- FError :FT_SUCCESS 为写入成功 + + +### 11. FNandSetIsrHandler + +``` +void FNandSetIsrHandler(FNand *instance_p, FnandIrqEventHandler event_p, void *irq_args) +``` + +#### 介绍 +- 初始化中断事件回调函数 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- FnandIrqEventHandler event_p 中断事件回调函数 +- void *irq_args 回调函数传入参数 + +#### 返回 +无 + +### 12. FNandIrqHandler + +``` +void FNandIrqHandler(s32 vector, void *param) +``` + +#### 介绍 +- Nand 控制器中断响应函数 + +#### 参数 +- s32 vector 中断ID +- void * param 中断传入参数 + +#### 返回 +- 无 + +### 13. FNandInitBbtDesc + +``` +void FNandInitBbtDesc(FNand *instance_p) +``` + +#### 介绍 +- 坏块表初始化 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 + +#### 返回 +- 无 + + +### 10. FNandScanBbt + +``` +FError FNandScanBbt(FNand *instance_p, u32 target_addr) +``` + +#### 介绍 +- 在Nand flash中扫描具体目标地址的坏块表 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- u32 chip_addr 芯片地址 + +#### 返回 +- FError :FT_SUCCESS 为扫描成功 + +### 11. FNandIsBlockBad + +``` +FError FNandIsBlockBad(FNand *instance_p, u32 block, u32 target_addr) +``` +#### 介绍 +- 检查当前块是否为坏块 + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- u32 block 需要检查的块ID号 +- u32 chip_addr 芯片地址 + +#### 返回 +- FError :FT_SUCCESS 为当前块为坏块 + +### 12. FNandOperationWaitIrqRegister + +``` +void FNandOperationWaitIrqRegister(FNand *instance_p,FNandOperationWaitIrqCallback wait_irq_fun_p ,void *wait_args) +``` + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- FNandOperationWaitIrqCallback 用户使用读/写/擦接口过程中,等待中断完成的回调函数接口 ,用户的回调函数,驱动以FT_SUCCESS 作为成功判断,否则为失败 +- void *wait_args 用户需要传入至回调函数中的参数 + +### 返回 + +无 + + +### 13. FNandSetOption + +- 依据options 选项参数,配置对应参数 + +```c +FError FNandSetOption(FNand *instance_p,u32 options,u32 value) +``` + +#### 参数 +- FNand *instance_p FNand 控制器实例的指针 +- u32 option 具体配置项 +- u32 value 配置项中对应的参数 + diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fpcie.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fpcie.md new file mode 100644 index 0000000000..4a93dd9539 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fpcie.md @@ -0,0 +1,450 @@ +# FPCIE 驱动程序 + +## 1. 概述 + + +- PCIe总线使用端到端的连接方式,在一条PCIe链路的两端只能各连接一个设备,这两个设备互为是数据发送端和数据接收端。PCIe总线除了总线链路外,还具有多个层次,发送端发送数据时将通过这些层次,而接收端接收数据时也使用这些层次。似 + +- FPCIE 模块内置两个 PCIE 单元(PCI-E Unit,PEU),分别为 PEU0 和 PEU1。每个 PEU 包含 3 个控制器:C0、C1 和 C2。当 PEU 拆分模式为 X16 时,C1 不可见。 + +- 本模块特点如下 + +1. 支持 Root Complex 和 End Point 两种模式; +2. 共 34 lane,两路 X16(可拆分为 2 个 X8)和两路 X1; +3. 内部集成 DMA 引擎,一读一写两个通道。 + +## 2. 功能 + + +- 驱动相关的源文件如下, +- drivers/pcie/fpcie + +``` +. +├── fpcie.c +├── fpcie.h +├── fpcie.md +├── fpcie_common.h +├── fpcie_config.c +├── fpcie_dma.c +├── fpcie_dma.h +├── fpcie_ep.c +├── fpcie_g.c +├── fpcie_hw.c +├── fpcie_hw.h +├── fpcie_misc.c +├── fpcie_sinit.c +├── fpcir_intx.c +└── fspim.md +``` + +## 3. 配置方法 + +以下部分将指导您完成 PCIE 驱动的软件配置: + +- 初始化PCIE控制器 +- 通过API 获取特定设备的 bar 空间地址 +- 使用INTX 中断响应设备中断响应函数 +- 使用DMA模式完成数据通信 + +## 4. 应用示例 + +"/baremetal/example/peripheral/fpcie_probe " + +## 5. API参考 + +### 5.1 用户数据结构 + + + +- 中断注册回调函数 + +```c + typedef struct + { + void (*IntxCallBack)(void *args) ; + void *args ; + s32 bdf ; + } FPcieIntxFun; +``` + +- 初始化配置空间地址 + +```c + struct FPcieRegion { + FPcieAddr bus_start; /* Start on the bus */ + FPciePhysAddr phys_start; /* Start in physical address space */ + FPcieSize size; /* Size */ + unsigned long flags; /* Resource flags */ + FPcieAddr bus_lower; + u32 exist_flg; /* exist flg */ + }; +``` + +- 驱动配置数据 + +```c + typedef struct + { + u32 instance_id; /* Id of device */ + u32 irq_num; /* Irq number */ + uintptr_t ecam; /* The Memory way */ + uintptr_t peu0_config_address; + uintptr_t peu1_config_address; + + uintptr_t control_c0_address; + uintptr_t control_c1_address; + uintptr_t control_c2_address; + uintptr_t control_c3_address; + uintptr_t control_c4_address; + uintptr_t control_c5_address; + + u32 io_base_addr; + u32 io_size ; + u32 npmem_base_addr; + u32 npmem_size; + u64 pmem_base_addr; /* Prefetchable memory */ + u64 pmem_size; + + u8 inta_irq_num ; + u8 intb_irq_num ; + u8 intc_irq_num ; + u8 intd_irq_num ; + u8 need_skip ; + + } FPcieConfig; +``` + +- 驱动控制数据 + +```c + typedef struct + { + u32 is_ready; /* Device is ininitialized and ready*/ + FPcieConfig config; + + struct FPcieRegion mem; + struct FPcieRegion mem_prefetch; + struct FPcieRegion mem_io; + + s32 bus_max; /* 当前最大bus num */ + + FPcieIrqCallBack fpcie_dma_rx_cb; + void *dma_rx_args; + + FPcieIrqCallBack fpcie_dma_tx_cb; + void *dma_tx_args; + + FPcieIrqCallBack fpcie_dma_rx_error_cb; + void *dma_rx_error_args; + + FPcieIrqCallBack fpcie_dma_tx_error_cb; + void *dma_tx_error_args; + + FPcieIntxFun inta_fun; + + FPcieIntxFun intb_fun; + + FPcieIntxFun intc_fun; + + FPcieIntxFun intd_fun; + + } FPcie; +``` + + +- 配置空间标记参数 + +``` +#define FPCIE_REGION_MEM 0x00000000 /* PCI memory space */ +#define FPCIE_REGION_IO 0x00000001 /* PCI IO space */ +#define PCI_REGION_PREFETCH 0x00000008 /* prefetchable PCI memory */ +``` + + +- 配置空间中对应的bar 标号 + +``` +#define FPCIE_BAR_0 0 +#define FPCIE_BAR_1 1 +#define FPCIE_BAR_2 2 +#define FPCIE_BAR_3 3 +#define FPCIE_BAR_4 4 +#define FPCIE_BAR_5 5 +``` + + +### 5.2 错误码定义 + +- 模块错误码编号:0x1090000 +- [0x0] FT_SUCCESS +- [0x1090001] FPCIE_ERR_INVALID_PARAM +- [0x1090002] FPCIE_ERR_OUTOF_BUS +- [0x1090003] FPCIE_ERR_CONFIG_WRITE +- [0x1090004] FPCIE_ERR_TYPE0 +- [0x1090005] FPCIE_ERR_TIMEOUT +- [0x1090006] FPCIE_NEED_SKIP +- [0x1090007] FPCIE_NOT_FOUND + + +### 5.3 用户API接口 + + +#### FPcieLookupConfig + +- 获取FPCIE驱动的默认配置参数 + +```c +const FPcieConfig *FPcieLookupConfig(u32 instance_id) +``` + +Note: + +- 用户可以通过此接口获取驱动默认配置的副本,进行修改后,作为`FPcieCfgInitialize`函数的入参使用 + +Input: + +- u32 instance_id, 选择的FPcie控制器实例号 + +Return: + +- const FPcieConfig *, 返回的默认驱动配置,返回NULL表示失败 + + + +#### FPcieCfgInitialize + +- 初始化配置空间和FPCIE 实例 + +```c +FError FPcieCfgInitialize(FPcie *instance_p, FPcieConfig *config_p) +``` + +Note: + +- 用户可以使用'FPcieLookupConfig'所产生的配置参数进行初始化,也可以自己组织配置参数进行初始化 + +Input: + +- FPcie *instance_p 指向FPcie实例的指针。 + +- FPcieConfig *config_p 指向FPcieConfig的指针。 + +Return : + +- 成功返回 FT_SUCCESS + + +#### FPcieDmaDescSet + +- PCIE DMA描述符分组包 + +```c +FError FPcieDmaDescSet(uintptr axi_addr, + uintptr bar_addr, + u32 length, + struct FPcieDmaDescriptor *desc, + struct FPcieDmaDescriptor *next_desc) +``` + +Note: + +- 用户使用dma 方式进行PCIE 数据传输时,用此函数将源地址与目标地址进行组合打包 + + +Input: + +- uintptr axi_addr 内存地址,可以为接收地址也可为发送地址 + +- uintptr bar_addr 需要通信function中对应的bar寄存器中分配的地址空间,可以为接收地址也可为发送地址 + +- u32 length 需要传输的字节长度 + +- struct FPcieDmaDescriptor *next_desc 是下一个需要发送的描述符 + +Output: + +- struct FPcieDmaDescriptor *desc 需要要配置的描述符 + + + +#### FPcieDmaRead + +Note: + +- 通过dma的方式读取Pcie function + +```c +void FPcieDmaRead(uintptr bar_address, struct FPcieDmaDescriptor *desc) +``` + +Input: + +- uintptr bar_address 基地地址寄存器的值 + +- struct FPcieDmaDescriptor *desc 接收描述符的起始地址 + +#### FPcieDmaWrite + +- 通过dma的方式写入Pcie function + +```c +void FPcieDmaWrite(uintptr bar_address, struct FPcieDmaDescriptor *desc) +``` + +Input: + +- uintptr bar_address 基地地址寄存器的值 + +- struct FPcieDmaDescriptor *desc 发送描述符的起始地址 + + +#### FPcieDmaPollDone + +- 轮询等待DMA完成 + +```c +FError FPcieDmaPollDone(struct FPcieDmaDescriptor *desc, u32 wait_cnt) +``` + +Input: + +- struct FPcieDmaDescriptor *desc Desc是需要等待完成的dma 描述符 + +- u32 wait_cnt 是需要等待结束的计数 + +#### FPcieFetchDeviceInBus + +- 该功能用于扫描整个总线上的树形结构,并且对其中的节点进行初始化与配置空间的设置 + +```c +FError FPcieFetchDeviceInBus(FPcie *instance_p, u32 bus_num) +``` + +Input: + +- FPcie *instance_p 指向FPcie实例的指针。 + +- u32 bus_num 扫描对应总线上已经连接的网桥/端点。 + +Output: + +- FError FT_SUCCESS 为成功 + + +#### FPcieFindDeviceNum + +- 根据输入的Vendor ID 与 Device ID ,获取当前PCIE 总线上一共存在多少此类设备 + +```c +u32 FPcieFindDeviceNum(FPcie *instance_p, u32 bus_num,u32 vendor_id,u32 device_id) +``` + +Input: + +- FPcie *instance_p 指向FPcie实例的指针。 + +- u32 bus_num 需要查找的bus号 + +- u32 vendor_id 目标 Vendor ID + +- u32 device_id 目标 Device ID + +Output: + +- u32 return 所需查找设备的数量 + + + +#### FPcieGetBusDeviceBarInfo + +- 通过Vendor ID和device ID获取对应的function id、device id 和 bar 空间 + +```c +FError FPcieGetBusDeviceBarInfo(FPcie *instance_p,u32 bus,u32 vendor_id,u32 device_id,u32 bar_num ,u32 *device_p,u32 *function_p,uintptr *bar_addr_p) +``` + +Input: +- FPcie *instance_p 指向FPcie实例的指针。 + +- u32 bus 需要查找的bus号 + +- u32 vendor_id 目标 Vendor ID + +- u32 device_id 目标 Device ID + +- u32 bar_num 需要查找对应bar空间的编号 + +Output: + +- u32 * device_p 需要获取对应设备号的指针 + +- u32 * function_p 需要获取对应功能号的指针 + +- uintptr * bar_addr_p 需要获取对应bar地址空间的指针 + +- FError return FT_SUCCESS 为成功 + + +#### FPcieSearchFunByClass + +- 使用 class code 获取设备的信息 + +```c +u32 FPcieSearchFunByClass(FPcie *instance_p,u32 class_code,FPcieSearchFunNode *node_p ,u32 node_num) +``` + +Input: + +- FPcie *instance_p 指向FPcie实例的指针。 + +- u32 class_code 对应的类号 + +- FPcieSearchFunNode * node_p 是一个存放特定函数信息缓冲区的指针 + +- u32 node_num 缓冲器的数量 + +Output: + +- u32 return 输出中的实际节点的个数 + + + +#### FPcieIntxIrqHandler + +- fpcie的Intx中断服务函数 + +```c +void FPcieIntxIrqHandler(s32 vector, void *args) +``` + +Input: + +- s32 vector 中断向量号 + +- void * args 需要传入的参数 + + +#### FPcieIntxRegiterIrqHandler + +- 使用bus id、device id 和function id在INTX上注册中断响应函数 + +```c +FError FPcieIntxRegiterIrqHandler(FPcie *instance_p, + u32 bus, + u32 device, + u32 function, + FPcieIntxFun *intx_fun_p) +``` + +Input: + +- FPcie *instance_p 指向FPcie实例的指针。 + +- u32 bus 需要配置的bus id + +- u32 device 需要配置的device id + +- u32 function 需要配置的function id + +- FPcieIntxFun * intx_fun_p 是用户用来注册回调函数信息的指针 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fpl011.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fpl011.md new file mode 100644 index 0000000000..0cff6c4bba --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fpl011.md @@ -0,0 +1,368 @@ +# FPL011 驱动程序 + +## 1. 概述 + +- 通用异步收发传输器(Universal Asynchronous Receiver/Transmitter),通常称作UART。它将要传输的资料在串行通信与并行通信之间加以转换。作为把并行输入信号转成串行输出信号的芯片,UART通常被集成于其他通讯接口的连结上。 + +- 本模块目前支持FT2000-4/D2000/E2000 + +- 本模块可使用MIO的uart功能 +## 2. 功能 + +- 1. 支持轮询接收发送数据 + 2. 中断接收发送数据 + 3. 接收发送有独立fifo + 4. 支持回传测试模式 + +相关源文件为: +``` +fpl011 + ├── fpl011.c + ├── fpl011.h + ├── fpl011_g.c + ├── fpl011_hw.c + ├── fpl011_hw.h + ├── fpl011_intr.c + ├── fpl011_options.c + └── fpl011_sinit.c +``` + + +## 3. 配置方法 + +### 参数配置 + +#### 通信参数配置 + +FPl011SetDataFormat()并将一个FPl011Format结构传递给它。FPl011Format结构应该包含所有必需的参数。参见下面的示例。 + +``` +FPl011Format format = +{ + u32 baudrate = 115200; /* In bps, ie 1200 */ + u32 data_bits = FPL011_FORMAT_WORDLENGTH_8BIT ; /* Number of data bits */ + u32 parity = FPL011_FORMAT_NO_PARITY ; /* Parity */ + u8 stopbits = FPL011_FORMAT_1_STOP_BIT ; /* Number of stop bits */ +}; + +FPl011SetDataFormat(&uart,&format); + +``` + +#### Running UART Communication + +- Transmitting ,此接口兼容轮询与中断模式,用户传入特定buffer,函数外通过判断标志位确认发送是否完成。 + +``` +u8 buffer_p[10] ; +u32 len = 0 ; +len = FPl011Send(&uart,buffer_p,sizeof(buffer_p)) ; +``` + +- Receiving ,此接口兼容轮询与中断模式,用户传入特定buffer,函数外通过判断标志位确认发送是否完成。 + +``` +u8 buffer_p[10] ; +u32 len = 0 ; +len = FPl011Receive(&uart,buffer_p,sizeof(buffer_p)) ; +``` + +## 4 应用示例 + +baremetal/example/uart_test + +## 4. API参考 + +## FPl011Config *FPl011LookupConfig(u32 instance_id) + +初始化特定的FPl011实例,以便它可以被使用。 +Initializes a specific FPl011 instance such that it is ready to be used. + +- 参数 +instance_id 是对应驱动的编号 + + +- Parameters + +instance_id contains the ID of the device + +- 返回 + +FPl011Config *指向配置结构的指针,如果指定的设备不在系统中,则为NULL。 + + +- Return + +FPl011Config *A pointer to the configuration structure or NULL if the specified device is not in the system. + + +## u32 FPl011Send(FPl011 *uart_p, u8 *byte_p, u32 length) + +这个函数使用设备发送指定的缓冲区,采用轮询或中断驱动模式。 + +This functions sends the specified buffer using the device in either + polled or interrupt driven mode. + + +- 参数 + +uart_p 是指向FPl011实例的指针。 +byte_p 是指向要发送的数据缓冲区的指针。 +length 表示发送的字节数。任何已经放入传输FIFO的数据将被发送。 + +- Parameters +uart_p is a pointer to the FPl011 instance. +byte_p is pointer to a buffer of data to be sent. +length contains the number of bytes to be sent. Any data that was already put into the transmit FIFO will be sent. + +- 返回 + +实际发送的字节数。 + + +- Return + +The number of bytes actually sent. + +## u32 FPl011Receive(FPl011 *uart_p, u8 *byte_p, u32 length) + +此函数尝试从设备接收指定字节数的数据,并将其存储到指定的缓冲区中。 + +This function attempts to receive a specified number of bytes of data from the device and store it into the specified buffer. + +- 参数 + +uart_p 是指向FPl011实例的指针 +byte_p 是用于接收数据的缓冲区指针 +length 表示接收的字节数。 + +- Parameters + +uart_p is a pointer to the FPl011 instance +byte_p is pointer to buffer for data to be received into +length is the number of bytes to be received. + +- 返回 + +接收的字节数。 + +- Return + +The number of bytes received. + + +## void FPl011ProgramCtlReg(FPl011 *uart_p,u32 ctrl_reg) + + This function reprograms the control register according to the following + sequence mentioned in the TRM + +- 参数 +uart_p 是指向FPl011实例的指针 +ctrl_reg 想要被写入的控制寄存器的参数 + + - Parameters + +uart_p is a pointer to the FPl011 instance +ctrl_reg value to be written + + + +## void FPl011SetOperMode(FPl011 *uart_p,u8 operation_mode) + +该函数设置UART的操作模式。 UART可以操作 两种模式之一:正常模式、本地环回模式。 + +This function sets the operational mode of the UART. The UART can operate + in one of four modes: Normal, Local Loopback. + +- 参数 + +uart_p是指向FPl011实例的指针。 + +operation mode为UART模式。 + +- Parameters + + uart_p is a pointer to the FPl011 instance. + + operation_mode is the mode of the UART. + +## void FPl011SetSpecificOptions(FPl011 *uart_p, u32 options) + +为指定的驱动程序实例设置选项。 + +Sets the options for the specified driver instance. + +- Parameters + +uart_p是指向FPl011实例的指针。 + +uart_p is a pointer to the FPl011 instance. + +options contains the options to be set which are bit masks contained in the file FPl011_uart.h and named FUART_OPTION_*. + + +## void FPl011ClearSpecificOptions(FPl011 *uart_p, u32 options) + + +清除指定驱动程序实例的选项。 + +Clear the options for the specified driver instance. + +- 参数 + +uart_p是指向fpl011实例的指针。 + +options 包含要设置的选项,这些选项是包含在文件FPl011_uart.h和名为FUART_OPTION_*的位掩码。 + +- Parameters + +uart_p is a pointer to the fpl011 instance. + +options contains the options to be set which are bit masks contained in the file FPl011_uart.h and named FUART_OPTION_*. + +## FError FPl011SetBaudRate(FPl011 *uart_p, u32 baudrate) + +设置设备波特率。 + +Sets the baud rate for the device. + +- 参数 + +uart p是指向FPl011实例的指针 + +BaudRate 所要设置波特率 + +- Parameters + +uart_p is a pointer to the FPl011 instance + +BaudRate to be set + +- 返回 + +如果一切都按照预期配置,则返回FT_SUCCESS + +如果请求的速率不可用,则返回FPL011_ERROR_PARAM + +- Return + + FT_SUCCESS if everything configured as expected + + FPL011_ERROR_PARAM if the requested rate is not available + because there was too much error + +## void FPl011GetDataFormat(FPl011 *uart_p,FPl011Format *format_p) + +获取指定UART的数据格式。 + +Gets the data format for the specified UART. + +- 参数 + +uart_p 是指向fpl011实例的指针。 + +format_p 是一个指向格式结构的指针,该结构将在调用完成后包含数据格式。 + +- Parameters + +uart_p is a pointer to the fpl011 instance. + +format_p is a pointer to a format structure that will contain the data format after this call completes. + +## FError FPl011SetDataFormat(FPl011 *uart_p,FPl011Format *format_p) + +将需要的参数格式,设置至特定的串口驱动中 + +Sets the data format for the specified UART. + +- 参数 + +Uart_p 是指向fpl011实例的指针。 + +format_p 是一个指向格式结构的指针,该结构将在调用完成后包含数据格式。 + +- Parameters + +uart_p is a pointer to the fpl011 instance. + +format_p is a pointer to a format structure that will contain the data format after this call completes. + +- 返回 + + 如果一切都按照预期配置,则使用FT_SUCCESS + 如果其中一个参数无效,则返回FPL011_ERROR_PARAM + +- Return + + FT_SUCCESS if everything configured as expected + FPL011_ERROR_PARAM if one of the parameters was not valid. + + +## void FPl011SetTxFifoThreadHold(FPl011 *uart_p, u8 trigger_level) + +这个函数设置Tx FIFO触发器级别为'TriggerLevel'参数。 + +This functions sets the Tx FIFO trigger level to the 'TriggerLevel' argument. + +- 参数 + +uart_p 是指向fpl011实例的指针。 +Trigger_level包含要设置的触发器级别。 这个值从0-32 (FPL011IFLS_TXIFLSEL_1_8 - FPL011IFLS_TXIFLSEL_7_8) + + +- Parameters + +uart_p is a pointer to the fpl011 instance. + +trigger_level contains the trigger level to set. This is a value from 0-32 (FPL011IFLS_TXIFLSEL_1_8 - FPL011IFLS_TXIFLSEL_7_8) + + +## void FPl011SetRxFifoThreadhold(FPl011 *uart_p, u8 trigger_level) + +这个函数将Rx FIFO触发器级别设置为'TriggerLevel'参数。 + +This functions sets the Rx FIFO trigger level to the 'TriggerLevel' argument. + +- 参数 + +uart_p 是指向fpl011实例的指针。 +Trigger_level包含要设置的触发器级别。 这个值从0-32 (FPL011IFLS_RXIFLSEL_1_8 - FPL011IFLS_RXIFLSEL_7_8) + +- Parameters + +uart_p is a pointer to the fpl011 instance. + +trigger_level contains the trigger level to set. This is a value from 0-32 (FPL011IFLS_RXIFLSEL_1_8 - FPL011IFLS_RXIFLSEL_7_8) + +## u32 FPl011GetInterruptMask(FPl011 *uart_p) + +这个函数获取中断掩码。 + +This function gets the interrupt mask. + +- 参数 + +uart_p是指向PFl011实例的指针 + +- Parameters + +uart_p is a pointer to the PFl011 instance + + +## void FPl011SetInterruptMask(FPl011 *uart_p, u32 mask) + +这个函数设置中断掩码。 + +This function sets the interrupt mask. + +- 参数 + +uart_p是指向PFl011实例的指针 + +mask包含要启用或禁用的中断。 '1'启用中断,'0'禁用中断。 + +- Parameters + +uart_p is a pointer to the PFl011 instance + +mask contains the interrupts to be enabled or disabled. A '1' enables an interrupt, and a '0' disables. diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fpwm.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fpwm.md new file mode 100644 index 0000000000..c39a9c29a4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fpwm.md @@ -0,0 +1,313 @@ +# FPWM 驱动程序 + +## 1. 概述 + +PWM(Pulse Width Modulation)简称脉宽调制,是利用微处理器的数字输出来对模拟电路进行控制的一种非常有效的技术,广泛应用在测量、通信、工控等方面。 + +## 2. 功能 + +pwm控制器驱动提供了pwm的控制访问方法, +- 初始化pwm控制器,配置相关参数,如时钟分频,周期,占空比,输出极性等 +- 计数中断与FIFO_EMPTY中断的触发等 +- E2000共有8个PWM模块(控制器),每个模块集成了两个子模块pwm0和pwm1,我们习惯性的称为channel0和channel1,在死区输出模式配置为bypass时,这两个channel可以作为两路独立的pwm输出使用,在非bypass模式下,则输出为死区配置,此时需要选择输入源是channel0还是channel1,然后配置对应项即可 + +驱动相关的源文件包括 +``` +. +├── fpwm_g.c +├── fpwm_hw.c +├── fpwm_hw.h +├── fpwm_intr.c +├── fpwm_sinit.c +├── fpwm.c +└── fpwm.h +``` + +## 3. 配置方法 + +以下部分将指导您完成 fpwm 驱动的软件配置: + +- 初始化pwm控制器 +- 配置pwm的两个通道的输出模式,以及是否死区输出等 +- 注册中断处理函数,使能中断 +- pwm的周期,频率,占空比设置方法如下: +![pwm_duty](./figs/pwm_duty.png) + +e2000的参考时钟是50M,freq为频率,duty为占空比,1/freq就是周期; +perioad对应寄存器FPWM_PERIOD_OFFSET,div对应FPWM_TIM_CTRL_OFFSET寄存器中的DIV,ccr对应寄存器FPWM_CCR_OFFSET; + +## 4 应用示例 + +### [pwm波形输出](../../../baremetal/example/peripheral/pwm) + +## 5. API参考 + +### 5.1. 用户数据结构 + +- fpwm控制数据 + +```c +typedef struct +{ + FPwmConfig config;/* Pwm配置 */ + u32 is_ready;/* Pwm初始化完成标志 */ + + u8 channel_ctrl_enable[2]; /* pwm channel ctrl enable state */ + + FPwmIntrEventHandler event_handler[FPWM_INTR_EVENT_NUM]; /* event handler for interrupt */ + void *event_param[FPWM_INTR_EVENT_NUM]; /* parameters ptr of event handler */ + +} FPwmCtrl; +``` + +- fpwm配置数据,FPwmConfig主要是pwm控制器id、基地址和中断号,FPwmDbVariableConfig主要包括用户可配置的死区参数,包括死区输出模式、输出极性、输入源选择、上下沿延迟等,FPwmVariableConfig主要包含pwm的输出参数,包括分频、周期、占空比、极性等 + +```c +typedef struct +{ + u8 instance_id;/* pwm id */ + uintptr db_base_addr; + uintptr pwm_base_addr; + + u64 base_clk; + u32 irq_num; /* pwm irq num*/ + u32 irq_prority; /* pwm irq priority */ + const char *instance_name;/* instance name */ + +}FPwmConfig;/* Pwm配置 */; + +typedef struct +{ + FPwmDbPolarity db_polarity_sel; + FPwmDbOutMode db_out_mode; + FPwmDbInMode db_in_mode; + u16 db_fall_cycle; + u16 db_rise_cycle; +}FPwmDbVariableConfig; + +typedef struct +{ + u8 tim_ctrl_enable;/* pwm time ctrl enable state */ + FPwmTimCtrlMode tim_ctrl_mode; + u16 tim_ctrl_div; + u16 pwm_period; + FPwmCtrlMode pwm_mode; + FPwmPolarity pwm_polarity; + FPwmDutySourceMode pwm_duty_source_mode; + u16 pwm_pulse; + +}FPwmVariableConfig; +``` + +- 死区输出模式 +```c +typedef enum +{ + FPWM_DB_OUT_MODE_BYPASS = 0b00, + FPWM_DB_OUT_MODE_FORBID_RISE = 0b01, + FPWM_DB_OUT_MODE_FORBID_FALL = 0b10, + FPWM_DB_OUT_MODE_ENABLE_RISE_FALL = 0b11, + FPWM_DB_OUT_MODE_NUM +} FPwmDbOutMode; +``` + +- fpwm duty比较值来源选择 +```c +typedef enum +{ + FPWM_DUTY_CCR = 0, + FPWM_DUTY_FIFO = 1, + + FPWM_DUTY_SEL_MODE_NUM + +} FPwmDutySourceMode;; +``` + +- fpwm中断事件类型 +```c +typedef enum +{ + FPWM_INTR_EVENT_COUNTER = 0, /**< Handler type for counter interrupt */ + FPWM_INTR_EVENT_FIFO_EMPTY = 1, /**< Handler type for fifo empty interrupt*/ + FPWM_INTR_EVENT_NUM +} FPwmIntrEventType; + +``` + +### 5.2 错误码定义 + +- FPWM_SUCCESS 执行成功 +- FPWM_ERR_INVAL_PARM 参数无效 +- FPWM_ERR_NOT_READY 驱动未初始化 +- FPWM_ERR_TIMEOUT 超时 +- FPWM_ERR_NOT_SUPPORT 不支持 +- FPWM_ERR_CMD_FAILED 执行失败 + +### 5.3. 用户API接口 + +#### FPwmLookupConfig + +- 获取Fata控制器默认配置 + +```c +const FPwmConfig *FPwmLookupConfig(FPwmInstance instance_id); +``` + +Note: + +- 获取默认配置参数,包括基地址、中断号等 + +Input: + +- {FPwmInstance} instance_id,pwm控制器id号 + +Return: + +- {const FPwmConfig *} pwm默认配置,返回NULL如果找不到默认配置 + +#### FPwmCfgInitialize + +- 初始化fpwm控制器, 使之可以使用 + +```c +FError FPwmCfgInitialize(FPwmCtrl *pctrl, const FPwmConfig *input_config_p); +``` + +Note: + +- 输入配置通过FPwmLookupConfig获取,用户按照需要修改后传入此函数 + +Input: + +- {FPwmCtrl} *pctrl,pwm驱动控制数据 +- {FPwmConfig} *input_config_p,pwm用户输入配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FPWM_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FPwmDbVariableSet + +- 设置pwm死区输出的配置参数 + +```c +FError FPwmDbVariableSet(FPwmCtrl *pctrl, FPwmDbVariableConfig *db_cfg); +``` + +Note: + +- 设置指定pwm控制器的死区可配置参数,包括死区输出模式、输出极性、输入源选择、上下沿延迟等 + +Input: + +- {FPwmCtrl} *pctrl,pwm驱动控制数据 +- {FPwmDbVariableConfig} *db_cfg,pwm死区参数配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FPWM_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FPwmVariableSet + +- 设置pwm通道的参数,使能该通道 + +```c +FError FPwmVariableSet(FPwmCtrl *pctrl, u32 channel, FPwmVariableConfig *pwm_cfg); +``` + +Note: + +- 设置指定pwm控制器的指定通道的分频、周期、占空比、极性,使能该通道 + +Input: + +- {FPwmCtrl} *pctrl,pwm驱动控制数据 +- {u32} channel,pwm通道号 +- {FPwmVariableConfig} *pwm_cfg,pwm通道配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FPWM_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + + +#### FPwmPulseSet + +- 设置pwm通道的占空比比较值 + +```c +FError FPwmPulseSet(FPwmCtrl *pctrl, u32 channel, u16 pwm_ccr); +``` + +Note: + +- 设置指定pwm控制器的指定通道的占空比比较值 + +Input: + +- {FPwmCtrl} *pctrl,pwm驱动控制数据 +- {u32} channel,pwm通道号 +- {u16} pwm_ccr,占空比比较值 + +Return: + +- {FError} 驱动初始化的错误码信息,FPWM_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FPwmEnable + +- 使能pwm控制器 + +```c +void FPwmEnable(FPwmCtrl *pctrl, u32 channel); +``` + +Note: + +- 使能指定pwm控制器的指定通道 + +Input: + +- {FPwmCtrl} *pctrl,pwm驱动控制数据 +- {u32} channel,pwm通道号 + +Return: + +- {FError} 驱动初始化的错误码信息,FPWM_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FPwmRegisterInterruptHandler + +- 注册pwm中断事件函数 + +```c +void FPwmRegisterInterruptHandler(FPwmCtrl *instance_p, FPwmIntrEventType event_type, + FPwmIntrEventHandler handler, void *param); +``` + +Note: +- 无 + +Input: +- {FPwmCtrl} *instance_p,fpwm驱动控制数据 +- {FPwmIntrEventType} event_type,中断事件类型 +- {FPwmIntrEventHandler} handler,中断事件回调函数 +- {void} *param,回调函数参数 + +Return: +- 无 + +#### FPwmIntrHandler + +- pwm中断处理函数入口 + +```c +void FPwmIntrHandler(s32 vector, void *args); +``` + +Note: +- 根据中断类型,设置对应的回调函数和参数传入 + +Input: +- {s32} vector +- {void} *param, 输入参数,指向fpwm驱动控制数据 + +Return: +- 无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fqspi.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fqspi.md new file mode 100644 index 0000000000..1cbb485681 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fqspi.md @@ -0,0 +1,409 @@ +# FQSPI 驱动程序 + +## 1. 概述 + +- QSPI是Motorola公司推出的SPI接口的扩展,比SPI应用更加广泛。在SPI协议的基础上,Motorola公司对其功能进行了增强,大幅提升了数据交换能力。QSPI 是一种专用的通信接口,连接单、双或四(条数据线) SPI Flash 存储介质。 + +- 本驱动程序提供了FT2000/4、D2000、E2000平台的QSPI功能 + +- FT2000/4、D2000上包含 1 个通用 QSPI 接口控制器,作为QSPI Flash接口使用,片最大支持 2Gb(256MB)的容量,最大支持连接四个相同容量的Flash + + +## 2. 功能 + + +- 驱动相关的源文件如下, +- drivers/qspi/fqspi + +``` +. +├── fqspi_norflash.c +├── fqspi_norflash.h +├── fqspi_g.c +├── fqspi_hw.c +├── fqspi_hw.h +├── fqspi_sinit.c +├── fqspi.h +└── fqspi.c +``` + + +## 3. 配置方法 + + +以下部分将指导您完成 FQSPI 驱动的软件配置: + +### 3.1 使用 SFUD 通用SPI协议框架 + +- 使能 CONFIG_USE_QSPI 和 CONFIG_USE_SFUD 配置 +- 初始化 SFUD 框架 +- 调用 SFUD 提供的 API 读写 QSPI 设备 + +关于 SFUD 框架的使用,可以参考[sfud.md](./sfud.md) + +### 3.2 不使用 SFUD 通用SPI协议框架 + +- 使能 CONFIG_USE_QSPI 配置 +- 初始 QSPI 驱动 +- 调用 QSPI 提供的 API 读写 QSPI 设备,需要按照 QSPI 设备的手册实现相关的命令和协议 + +## 4 应用示例 + +### [fqspi_nor_flash](../../../baremetal/example/peripheral/qspi/qspi_nor_flash/README.md) + +### [qspi_sfud](../../../baremetal/example/storage/qspi_sfud/README.md) + +## 4. API参考 + +### 4.1 用户数据结构 + +- QSPI 驱动配置数据 +```c +typedef struct +{ + u32 instance_id; /* Id of device */ + uintptr base_addr; /* Base address of qspi */ + uintptr mem_start; /* Start address of qspi memory */ + u32 capacity; /* Flash capacity */ + u32 dev_num; /* Qspi device number */ + u32 channel; /* channel number */ +} FQspiConfig; +``` + +- QSPI 驱动控制数据 +```c +typedef struct +{ + FQspiConfig config; + FQspiRdCfgDef rd_cfg; + FQspiWrCfgDef wr_cfg; + FQspiCommandPortDef cmd_def; + FQspiCsTimingCfgDef cs_timing_cfg; + u32 is_ready; /**< Device is initialized and ready */ + u32 flash_size; /* size of QSPI flash */ +} FQspiCtrl; +``` + +- QSPI 传输命令协议,指定传输的指令、地址和修饰符、数据三者的宽度 +```c +typedef enum +{ + FQSPI_TRANSFER_1_1_1 = 0x0, + FQSPI_TRANSFER_1_1_2 = 0x1, + FQSPI_TRANSFER_1_1_4 = 0x2, + FQSPI_TRANSFER_1_2_2 = 0x3, + FQSPI_TRANSFER_1_4_4 = 0x4, + FQSPI_TRANSFER_2_2_2 = 0x5, + FQSPI_TRANSFER_4_4_4 = 0x6 +}FQspiTransferMode; +``` + +- QSPI Flash的容量大小 +```c +typedef enum +{ + FQSPI_FLASH_CAP_4MB = 0b000, + FQSPI_FLASH_CAP_8MB = 0b001, + FQSPI_FLASH_CAP_16MB = 0b010, + FQSPI_FLASH_CAP_32MB = 0b011, + FQSPI_FLASH_CAP_64MB = 0b100, + FQSPI_FLASH_CAP_128MB = 0b101, + FQSPI_FLASH_CAP_256MB = 0b110, +} FQspiFlashCapcityType; +``` + +- QSPI的SCK分频系数 +```c +typedef enum +{ + FQSPI_SCK_DIV_128 = 0x0, + FQSPI_SCK_DIV_2 = 0x1, + FQSPI_SCK_DIV_4 = 0x2, + FQSPI_SCK_DIV_8 = 0x3, + FQSPI_SCK_DIV_16 = 0x4, + FQSPI_SCK_DIV_32 = 0x5, + FQSPI_SCK_DIV_64 = 0x6 +}FQspiSckDivType; +``` + +- QSPI的地址长度格式 +```c +typedef enum +{ + FQSPI_ADDR_SEL_3 = 0x0, + FQSPI_ADDR_SEL_4 = 0x1, +}FQspiAddrType; +``` + +### 4.2 错误码定义 + +- FQSPI_SUCCESS : fqspi success +- FQSPI_INVAL_PARAM : fqspi invalid input parameters +- FQSPI_NOT_READY : fqspi driver not ready +- FQSPI_NOT_ALLIGN : fqspi address not alligned +- FQSPI_NOT_SUPPORT : fqspi not support operation +- FQSPI_TIMEOUT : fqspi wait timeout + +### 4.3 用户API接口 + +#### FQspiLookupConfig + +- 获取FQSPI驱动的默认配置参数 + +```c +const FQspiConfig *FQspiLookupConfig(u32 instance_id) +``` + +Note: + +- 用户可以通过此接口获取驱动默认配置的副本,进行修改后,作为`FQspiCfgInitialize`函数的入参使用 + +Input: + +- u32 instance_id, 选择的FQSPI控制器实例号 + +Return: + +- const FQspiConfig *, 返回的默认驱动配置,返回NULL表示失败 + + +#### FQspiCfgInitialize + +- 完成FQSPI驱动实例的初始化,使之可以使用 + +```c +FError FQspiCfgInitialize(FQspiCtrl *instance_p, const FQspiConfig *input_config_p); +``` + +Note: + +- 此函数会重置FQSPI控制器和FQSPI控制数据 + +Input: + +- FQspiCtrl *instance_p, FQSPI驱动控制数据 + +- const FQspiConfig *input_config_p, FQSPI驱动配置数据 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + + +#### FQspiDeInitialize + +- 完成FQSPI驱动实例去初始化,之后不能使用 + +```c +void FQspiDeInitialize(FQspiCtrl *instance_p) +``` + +Note: + +- 此函数会重置FQSPI控制数据 + +Input: + +- FQspiCtrl *instance_p, FQSPI驱动控制数据 + +Return: + +无 + + +#### FQspiCommandPortConfig +- 配置FQSPI命令端口寄存器的值 + +```c +FError FQspiCommandPortConfig(FQspiCtrl *pctrl) +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 +- 配置FQSPI命令端口寄存器 + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示数据读取成功,其它返回值表示读取失败 + + +#### FQspiRdCfgConfig + +- 配置FQSPI地址访问读配置寄存器的值 + +```c +FError FQspiRdCfgConfig(FQspiCtrl *pctrl) +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 +- 配置QSPI地址访问读配置寄存器 + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示数据读取成功,其它返回值表示读取失败 + + +#### FQspiSetLdPortData + +- 写FQSPI低位数据端口寄存器的值 + +```c +FError FQspiSetLdPortData(FQspiCtrl *pctrl, const u8 *buf, size_t len) +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 +- 设置寄存器的值,可用于向flash传送数据 + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +- const u8 *buf, 写缓存,存储要写入的数据 + +- size_t len, 要读取的buf长度 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示数据写入成功,其它返回值表示写入失败 + +#### FQspiFlashSpecialInstruction +- 读flash某些状态寄存器的值,此函数适配的flash型号为S25FS256S NorFlash芯片 + +```c +FError FQspiFlashSpecialInstruction(FQspiCtrl *pctrl, u8 cmd, u8 *buf, size_t len); +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 +- 读取flash寄存器的值,主要支持RDID, RDSR1, RDSR2, RDCR指令 + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +- u8 cmd, 读寄存器状态的指令,具体参见flash芯片手册 + +- u8 *buf, 读缓存,存储读到的寄存器值 + +- size_t len, 要读取的buf长度 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示数据读取成功,其它返回值表示读取失败 + +#### FQspiFlashWriteReg +- 写flash寄存器的值 + +```c +FError FQspiFlashWriteReg(FQspiCtrl *pctrl, u8 command, const u8 *buf, size_t len) +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +- u8 command, 写寄存器的指令 + +- const u8 *buf, 写缓存,存储写入的寄存器值 + +- size_t len, 要写入的buf长度 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示数据写入成功,其它返回值表示写入失败 + +#### FQspiFlashReadDataConfig + +- 读flash配置 + +```c +FError FQspiFlashReadDataConfig(FQspiCtrl *pctrl, u8 command) +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 +- 配置采用何种方式读flash中的数据,read、fast read、quad read + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +- u8 command 读flash数据的指令,具体参见flash芯片手册 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示读配置成功,其它返回值表示读配置失败 + +#### FQspiFlashReadData + +- 读取norflash的数据 + +```c +size_t FQspiFlashReadData(FQspiCtrl *pctrl, u32 chip_addr, u8 *buf, size_t len) +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 +- 使用此函数前需要使用FQspiFlashReadDataConfig函数配置读方式 + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +- u32 chip_addr, 读数据的起始地址 + +- u8 *buf 读缓存, 存储读到的数据 + +- size_t len, 要读取的buf长度 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示数据读取成功,其它返回值表示读取失败 + +#### FQspiNorFlashWrite + +- 写norflash数据函数 + +```c +FError FQspiFlashWriteData(FQspiCtrl *pctrl, u8 command, u32 chip_addr, const u8 *buf, size_t len) +``` + +Note: + +- 使用此函数前需要确保FQSPI驱动初始化成功 + +Input: + +- FQspiCtrl *pctrl, FQSPI驱动控制数据 + +- u8 command 写flash数据的指令,具体参见flash手册 + +- u32 chip_addr, 写数据的起始地址 + +- u8 *buf 写缓存, 存储要写入的数据 + +- size_t len, 要写入的buf长度 + +Return: + +- FError, 错误码信息,FQSPI_SUCCESS 表示数据写入成功,其它返回值表示写入失败 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/frtc.md b/bsp/phytium/libraries/standalone/doc/reference/driver/frtc.md new file mode 100644 index 0000000000..3458c320f8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/frtc.md @@ -0,0 +1,196 @@ +# RTC 驱动程序 + +## 1. 概述 + +- 实时时钟(RTC)提供可靠的系统时间,包括年月日和时分秒。 + +- 通过采用电池供电,在系统处于关机状态时,RTC也能正常工作。 + +- RTC 驱动支持的平台包括 FT2000/4、D2000。 + +## 2. 功能 + +RTC 驱动程序主要完成RTC模块的初始化、时间设置和读取,该驱动程序具备以下功能: +- 初始化RTC模块 +- 设置RTC时间 +- 读取RTC时间 + +相关源文件为: +``` +frtc + ├── frtc.c + ├── frtc.h + ├── frtc_g.c + ├── frtc_hw.c + ├── frtc_hw.h + ├── frtc_intr.c + └── frtc_sinit.c +``` + + +## 3. 配置方法 + +以下部分将指导您完成 RTC 驱动的软件配置: + +- 配置驱动程序,新建应用工程,使能RTC驱动模块 +- 设置配置参数 +- 设置RTC时间 +- 读取RTC时间 + +## 4. 应用示例 + + +### [rtc_test](../../../baremetal/example/rtc_test/README.md) + + +## 5. API参考 + + +### 5.1. 用户数据结构 + +- drivers/rtc/frtc/frtc.h + +```c +typedef struct +{ + uintptr control_base_addr; /* rtc控制寄存器基地址 */ + const char *instance_name; /* instance name */ +} FRtcConfig; /* rtc配置 */ + +typedef struct +{ + FRtcConfig config; /* rtc配置 */ + u32 is_ready; /* rtc初始化完成标志 */ +} FRtcCtrl; +``` + +- RTC时间实例配置 + +```c +typedef struct +{ + u16 year; /*Specifies the RTC Date Year. + This parameter must be a number between Min_Data = 2000 and Max_Data = 2099 */ + u8 month; /*Specifies the RTC Date Month. + This parameter must be a number between Min_Data = 1 and Max_Data = 12 */ + u8 mday; /*Specifies the RTC day of Month. + This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ + u8 hour; /*Specifies the RTC Time Hour. + This parameter must be a number between Min_Data = 0 and Max_Data = 23 */ + u8 minute; /*Specifies the RTC Time Minute. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + u8 second; /*Specifies the RTC Time Second. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ +} FRtcDateTime; +``` +### 5.2 错误码定义 + +- 模块错误码编号 `0x1020000` + +- [0x0] FRTC_SUCCESS : success + +- [0x1020001] FRTC_ERR_DATE_INVALID : invalid date parameters + +- [0x1020002] FRTC_ERR_TIME_INVALID : invalid time parameters + + +### 5.3. 用户API接口 + +- 获取RTC驱动的默认配置参数 + +```c +const FRtcConfig *FRtcLookupConfig(void); +``` + + Note: + + - 用户需要修改配置参数时,可以通过修改返回的FRtcConfig副本,作为后续使用函数的入参, + + Input: + + - void, 只有一个RTC模块 + + Return: + + - const FRTCConfig *, 返回驱动默认参数, NULL表示失败 + + +- 初始化RTC驱动 +```c +FError FRtcCfgInitialize(FRtcCtrl *instance_p, const FRtcConfig *config_p); +``` + + Note: + + - 用户需要修改配置参数时,可以通过修改返回的FRtcConfig副本,作为后续使用函数的入参, + + Input: + + - FRtcCtrl *instance_p, RTC驱动控制块 + - const FRtcConfig *config_p, RTC驱动配置数据 + + Return: + + - 返回初始化错误码,FRTC_SUCCESS表示初始化成功 + +- 设置RTC时间 + +```c +FError FRtcSetDateTime(FRtcCtrl *pctrl, const FRtcDateTime *date_time); +``` + + Note: + + - 此函数会根据传入的时间初始化RTC时间寄存器 + + Input: + + - FRtcCtrl *pctrl, RTC驱动实例数据 + + - const FRtcDateTime *date, 设置的RTC时间年月日时分秒 + + Return: + + - u32, 参考5.2章错误码定义 + +- 读取RTC时间 + +```c +FError FRtcGetDateTime(FRtcCtrl *pctrl, FRtcDateTime *date_time); +``` + + Note: + + - 此函数会获取当前的RTC时间 + + Input: + + - FRtcCtrl *pctrl, RTC驱动实例数据 + + - FRtcDateTime *date, 获取的RTC时间年月日时分秒 + + Return: + + - u32, 参考5.2章错误码定义 + +- 读取RTC时间戳 + +```c +time_t FRtcReadTimeStamp(FRtcCtrl *pctrl, time_t *sec, time_t *msec); +``` + + Note: + + - 此函数会读取RTC时间,并返回time_t格式的时间值 + + Input: + + - FRtcCtrl *pctrl, RTC驱动实例数据 + + - time_t *sec, 获取的秒时间戳,传入NULL表示不需要获取 + + - time_t *msec, 获取的毫秒时间戳,传入NULL表示不需要获取 + + Return: + + - time_t, 详见中的定义 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fsata.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fsata.md new file mode 100644 index 0000000000..7ac282a90c --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fsata.md @@ -0,0 +1,310 @@ +# FSATA 驱动程序 + +## 1. 概述 + +串口硬盘SATA(Serial ATA)与以往的并口硬盘PATA(Parallel ATA)相比,数据传输速度更加快捷,并支持热插拔; +SATA总线使用嵌入式时钟信号,具备了更强的纠错能力,能对传输指令进行检查,如果发现错误会自动矫正,提高了数据传输的可靠性; + +## 2. 功能 + +AHCI控制器驱动提供了SATA的控制访问方法, +- 初始化AHCI控制器 +- 以PIO方式发送/接收数据和命令 +- 以DMA方式发送/接收数据和命令 +- 设置AHCI控制器的中断工作模式和中断响应函数 + +驱动相关的源文件包括, +``` +fsata + + ├── fsata_g.c + ├── fsata_hw.c + ├── fsata_hw.h + ├── fsata_intr.c + ├── fsata_sinit.c + ├── fsata.c + └── fsata.h +``` + +## 3. 配置方法 + +以下部分将指导您完成 fsata 驱动的软件配置: + +- 初始化ahci控制器 +- 通过协议命令读写sata数据 + +## 4 应用示例 + +### [读写sata二进制数据](../../../baremetal/example/peripheral/sata) + +### [通过文件系统使用sata](../../../baremetal/example/storage/sata_fatfs) + +## 5. API参考 + +### 5.1. 用户数据结构 + +- fsata控制数据 + +```c +typedef struct +{ + FSataConfig config; /* sata配置 */ + u32 is_ready; /* sata初始化完成标志 */ + u32 private_data; + FSataAhciIoPorts port[FSATA_AHCI_MAX_PORTS]; + u16 *ataid[FSATA_AHCI_MAX_PORTS]; + u32 n_ports; + u32 cap; /* cache of HOST_CAP register */ + u32 port_map; /* cache of HOST_PORTS_IMPL reg */ + u32 link_port_map; /*linkup port map*/ + + FSataIrqCallBack fsata_dhrs_cb; /* device-to-host register fis interrupt */ + void *dhrs_args; + FSataIrqCallBack fsata_pss_cb; /* pio setup fis interrupt */ + void *pss_args; + FSataIrqCallBack fsata_dss_cb; /* dma setup fis interrupt */ + void *dss_args; + FSataIrqCallBack fsata_sdbs_cb; /* set device bits interrupt */ + void *sdbs_args; + FSataIrqCallBack fsata_pcs_cb; /* port connect change status interrupt */ + void *pcs_args; +} FSataCtrl; +``` + +- fsata配置数据 + +```c +typedef struct +{ + uintptr base_addr; /* sata控制寄存器基地址 */ + const char *instance_name; /* instance name */ + u32 irq_num; /* Irq number */ +} FSataConfig; /* sata配置 */ +``` + +- fsata port memmory +```c +typedef struct +{ + uintptr port_mmio; + FSataAhciCommandList *cmd_list; /* Command List structure, will include cmd_tbl's address */ + uintptr cmd_tbl_base_addr; /* command table addr, also the command table's first part */ + FSataAhciCommandTablePrdt *cmd_tbl_prdt; /* command table's second part , cmd_tbl + cmd_tbl_prdt = command table*/ + FSataAhciRecvFis *rx_fis; /* Received FIS Structure */ + uintptr mem; + FSataInfo dev_info; +} FSataAhciIoPorts; +``` + +- fsata属性 +```c +typedef struct +{ + unsigned char if_type; /* type of the interface */ + unsigned char part_type; /* partition type */ + unsigned char type; /* device type */ + unsigned char removable; /* removable device */ + char vendor[BLK_VEN_SIZE + 1]; /* device vendor string */ + char product[BLK_PRD_SIZE + 1]; /* device product number */ + char revision[BLK_REV_SIZE + 1]; /* firmware revision */ + unsigned long lba; /* number of blocks */ + unsigned long blksz; /* block size */ + +}FSataInfo; +``` + +- fsata中断类型和中断事件 +```c +#define FSATA_PORT_IRQ_COLD_PRES BIT(31) /* cold presence detect */ +#define FSATA_PORT_IRQ_TF_ERR BIT(30) /* task file error */ +#define FSATA_PORT_IRQ_HBUS_ERR BIT(29) /* host bus fatal error */ +#define FSATA_PORT_IRQ_HBUS_DATA_ERR BIT(28) /* host bus data error */ +#define FSATA_PORT_IRQ_IF_ERR BIT(27) /* interface fatal error */ +#define FSATA_PORT_IRQ_IF_NONFATAL BIT(26) /* interface non-fatal error */ +#define FSATA_PORT_IRQ_OVERFLOW BIT(24) /* xfer exhausted available S/G */ +#define FSATA_PORT_IRQ_BAD_PMP BIT(23) /* incorrect port multiplier */ + +#define FSATA_PORT_IRQ_PHYRDY BIT(22) /* PhyRdy changed */ +#define FSATA_PORT_IRQ_DEV_ILCK BIT(7) /* device interlock */ +#define FSATA_PORT_IRQ_CONNECT BIT(6) /* port connect change status */ +#define FSATA_PORT_IRQ_SG_DONE BIT(5) /* descriptor processed */ +#define FSATA_PORT_IRQ_UNK_FIS BIT(4) /* unknown FIS rx'd */ +#define FSATA_PORT_IRQ_SDB_FIS BIT(3) /* Set Device Bits FIS rx'd */ +#define FSATA_PORT_IRQ_DMAS_FIS BIT(2) /* DMA Setup FIS rx'd */ +#define FSATA_PORT_IRQ_PIOS_FIS BIT(1) /* PIO Setup FIS rx'd */ +#define FSATA_PORT_IRQ_D2H_REG_FIS BIT(0) /* D2H Register FIS rx'd */ +``` + +### 5.2 错误码定义 + +- FSATA_SUCCESS : success +- FSATA_ERR_INVAILD_PARAMETER : 参数无效 +- FSATA_ERR_TIMEOUT : 数据或者命令传输等待超时 +- FSATA_ERR_OPERATION : 错误操作 +- FSATA_UNKNOWN_DEVICE : 未知设备 + +### 5.3. 用户API接口 + +#### FSataLookupConfig + +- 获取Fata控制器默认配置 + +```c +const FSataConfig *FSataLookupConfig(void); +``` + +Note: + +- 获取默认配置参数,包括中断号,instance_name等 + +Input: + +- {void} + +Return: + +- {const FSataConfig *} fsata默认配置,返回NULL如果找不到默认配置 + +#### FSataCfgInitialize + +- 初始化fsata控制器, 使之可以使用 + +```c +FError FSataCfgInitialize(FSataCtrl *instance_p, const FSataConfig *input_config_p); +``` + +Note: + +- 输入配置通过FSataLookupConfig获取,用户按照需要修改后传入此函数 + +Input: + +- {FSataCtrl} *instance_p fsata驱动控制数据 +- {FSataConfig} *input_config_p fsata用户输入配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FSATA_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FSataAhciInit + +- 初始化ahci, 使之可以使用 + +```c +FError FSataAhciInit(FSataCtrl *instance_p); +``` + +Note: + +- 包含ahci初始化和port memory的内存分配输入,用户需保证mem的大小足够 + +Input: + +- {FSataCtrl} *instance_p fsata驱动控制数据 + +Return: + +- {FError} 驱动初始化的错误码信息,FSATA_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + + +#### FSataAhciReadInfo + +- 读取sata信息,包括型号、容量等,通过串口输出 + +```c +FError FSataAhciReadInfo(FSataCtrl *instance_p, u8 port); +``` + +Note: + +- 输入配置通过FSataLookupConfig获取,用户按照需要修改后传入此函数 + +Input: + +- {FSataCtrl} *instance_p fsata驱动控制数据 +- {u8} port fsata的port端口号 + +Return: + +- {FError} 驱动初始化的错误码信息,FSATA_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FSataReadWrite + +- pio方式读写sata数据 + +```c +FError FSataReadWrite(FSataCtrl *instance_p, u8 port, u32 start, + u16 blk_cnt, u8 *buffer, u8 is_write); +``` + +Note: + +- 以pio方式读写sata数据,需注意传入的buffer是否完整 + +Input: + +- {FSataCtrl} *instance_p fsata驱动控制数据 +- {u8} port fsata的port端口号 +- {u32} start 读写的起始block +- {u16} blk_cnt 读写的block个数 +- {u8} *buffer 读写数据的缓存地址 +- {u8} is_write 读/写的标志位 + +Return: + +- {FError} 驱动初始化的错误码信息,FSATA_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FSataFPDmaReadWrite + +- dma方式读写sata数据 + +```c +FError FSataFPDmaReadWrite(FSataCtrl *instance_p, u8 port, u32 start, + u16 blk_cnt, u8 *buffer, u8 is_write); +``` + +Note: + +- 以dma方式读写sata数据,需注意传入的buffer是否完整 + +Input: + +- {FSataCtrl} *instance_p fsata驱动控制数据 +- {u8} port fsata的port端口号 +- {u32} start 读写的起始block +- {u16} blk_cnt 读写的block个数 +- {u8} *buffer 读写数据的缓存地址 +- {u8} is_write 读/写的标志位 + +Return: + +- {FError} 驱动初始化的错误码信息,FSATA_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +/* set specific sata irq function entry */ +FError FSataSetHandler(FSataCtrl *instance_p, u32 handler_type, + void *func_pointer, void *call_back_ref); + + +#### FSataSetHandler + +- 设置各中断的处理函数 + +```c +FError FSataSetHandler(FSataCtrl *instance_p, u32 handler_type, + void *func_pointer, void *call_back_ref); +``` + +Note: + +- 根据中断类型,设置对应的回调函数和参数传入 + +Input: + +- {FSataCtrl} *instance_p fsata驱动控制数据 +- {u32} handler_type 中断类型 +- {void} *func_pointer 回调函数入口 +- {void} *call_back_ref 回调函数参数 + +Return: + +- {FError} 驱动初始化的错误码信息,FSATA_SUCCESS 表示初始化成功,其它返回值表示初始化失败 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fsdio.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fsdio.md new file mode 100644 index 0000000000..ec8029e973 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fsdio.md @@ -0,0 +1,436 @@ +# FSDIO 驱动程序 + +## 1. 概述 + +SD/SDIO/eMMC控制器,主要支持SD卡,eMMC介质的访问能力,同时支持连接SDIO接口设备,目前 FSDIO 驱动已经支持 SD 卡的访问 + +## 2. 功能 + +FSDIO 驱动提供了SD/MMC卡的控制访问方法, +- 初始化SD/MMC控制器 +- 以轮询方式发送/接收数据和命令 + +访问SD/MMC卡需要兼容一系列协议命令,这一部分驱动不提供,可以通过第三方框架sdmmc使用 + +驱动相关的源文件包括, +``` +fsdio + ├── fsdio.c + ├── fsdio.h + ├── fsdio_cmd.c + ├── fsdio_dma.c + ├── fsdio_g.c + ├── fsdio_hw.h + ├── fsdio_intr.c + ├── fsdio_pio.c + ├── fsdio_selftest. +``` + +## 3. 配置方法 + +以下部分将指导您完成 FSDIO 驱动的软件配置: + +- 初始化 FSDIO 控制器 +- 通过协议命令完成 SD/MMC 卡初始化 +- 通过协议命令读写 SD/MMC 卡数据 + +## 4 应用示例 + + +### [通过协议命令读写SD卡](../../../baremetal/example/storage/sdio_cmds) + +## 5. API参考 + +### 5.1. 用户数据结构 + +#### FSdio + +- SDIO intance + +```c +typedef struct _FSdio +{ + FSdioConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + FSdioIDmaDescList desc_list; /* DMA descriptor list, valid in DMA trans mode */ + FSdioEvtHandler evt_handlers[FSDIO_NUM_OF_EVT]; /* call-backs for interrupt event */ + void *evt_args[FSDIO_NUM_OF_EVT]; /* arguments for event call-backs */ +} FSdio; /* SDIO intance */ +``` + +#### FSdioConfig + +- SDIO intance configuration + +```c +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num; /* Interrupt num */ + FSdioTransMode trans_mode; /* Trans mode, PIO/DMA */ + FSdioSpeedType speed; /* Trans speed type */ + FSdioVoltageType voltage; /* Card voltage type */ +} FSdioConfig; /* SDIO intance configuration */ +``` +#### FSdioCmdData + +- SDIO trans command and data + +```c +typedef struct +{ + u32 cmdidx; /* command index */ + u32 cmdarg; /* command argument */ + u32 response[4]; /* command response buffer */ + u32 flag; /* command flags */ +#define FSDIO_CMD_FLAG_NEED_INIT BIT(1) /* need initialization */ +#define FSDIO_CMD_FLAG_EXP_RESP BIT(2) /* need reply */ +#define FSDIO_CMD_FLAG_EXP_LONG_RESP BIT(3) /* need 136 bits long reply */ +#define FSDIO_CMD_FLAG_NEED_RESP_CRC BIT(4) /* need CRC */ +#define FSDIO_CMD_FLAG_EXP_DATA BIT(5) /* need trans data */ +#define FSDIO_CMD_FLAG_WRITE_DATA BIT(6) /* need trans data to write card */ +#define FSDIO_CMD_FLAG_READ_DATA BIT(7) /* need trans data to read card */ +#define FSDIO_CMD_FLAG_NEED_AUTO_STOP BIT(8) /* need auto stop after command */ +#define FSDIO_CMD_FLAG_ADTC BIT(9) /* need ADTC */ +#define FSDIO_CMD_FLAG_SWITCH_VOLTAGE BIT(10) /* need switch voltage */ + FSdioData *data_p; /* SDIO trans data */ +} FSdioCmdData; /* SDIO trans command and data */ +``` +#### FSdioIDmaDesc + +- SDIO DMA descriptor + +```c +typedef struct +{ + u32 attribute; /* ds0 */ +#define FSDIO_IDMAC_DES0_DIC BIT(1)/* 内部描述表不触发TI/RI中断 */ +#define FSDIO_IDMAC_DES0_LD BIT(2)/* 数据的最后一个描述符 */ +#define FSDIO_IDMAC_DES0_FD BIT(3)/* 数据的第一个描述符 */ +#define FSDIO_IDMAC_DES0_CH BIT(4)/* 链接下一个描述符地址 */ +#define FSDIO_IDMAC_DES0_ER BIT(5)/* 链表已经到达最后一个链表 */ +#define FSDIO_IDMAC_DES0_CES BIT(30)/* RINTSTS寄存器错误汇总 */ +#define FSDIO_IDMAC_DES0_OWN BIT(31)/* 描述符关联DMA,完成传输后该位置置0 */ + u32 non1; /* ds1 --> unused */ + u32 len; /* ds2 bit[25:13] buffer2 size,bit[12:0] buffer1 size*/ +#define FSDIO_IDMAC_DES2_BUF1_MASK GENMASK(12, 0) +#define FSDIO_IDMAC_DES2_BUF1_SIZE(x) (FSDIO_IDMAC_DES2_BUF1_MASK & (x)) +#define FSDIO_IDMAC_DES2_BUF2_MASK GENMASK(25, 13) +#define FSDIO_IDMAC_DES2_BUF2_SIZE(x) (FSDIO_IDMAC_DES2_BUF2_MASK & (x << 13)) + u32 non2; /* ds3 --> unused */ + u32 addr_lo; /* ds4 Lower 32-bits of Buffer Address Pointer 1 --> buffer 1 */ + u32 addr_hi; /* ds5 Upper 32-bits of Buffer Address Pointer 1 */ + u32 desc_lo; /* ds6 Lower 32-bits of Next Descriptor Address --> buffer 2 */ + u32 desc_hi; /* ds7 Upper 32-bits of Next Descriptor Address */ +} __attribute__ ((packed)) __attribute((aligned(4))) FSdioIDmaDesc; /* SDIO DMA descriptor */ + +``` + +### 5.2 错误码定义 + +- FSDIO_SUCCESS : 操作成功 +- FSDIO_ERR_TIMEOUT :操作超时失败 +- FSDIO_ERR_NOT_INIT :控制器未初始化 +- FSDIO_ERR_SHORT_BUF :缓冲区大小不足 +- FSDIO_ERR_NOT_SUPPORT :操作不支持 +- FSDIO_ERR_INVALID_STATE :控制器的状态不合法 +- FSDIO_ERR_TRANS_TIMEOUT :传输数据超时失败 +- FSDIO_ERR_CMD_TIMEOUT :传输命令超时失败 +- FSDIO_ERR_NO_CARD :卡不在位 +- FSDIO_ERR_BUSY : 卡处于繁忙状态 + +### 5.3. 用户API接口 + +#### FSdioLookupConfig + +```c +const FSdioConfig *FSdioLookupConfig(u32 instance_id) +``` + +Note: + +- Get the device instance default configure + +Input: + +- {u32} instance_id + +Return: + +- {const FSdioConfig *} default configure + +#### FSdioCfgInitialize + +```c +FError FSdioCfgInitialize(FSdio *const instance_p, const FSdioConfig *input_config_p) +``` + +Note: + +- initialization SDIO controller instance +- get into card-detect mode after initialization, bus width = 1, card freq = 400kHz + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioConfig} *input_config_p, SDIO controller configure + +Return: + +- {FError} FSDIO_SUCCESS if initialization success, otherwise failed + +#### FSdioDeInitialize + +```c +void FSdioDeInitialize(FSdio *const instance_p) +``` + +Note: + +- deinitialization SDIO controller instance + +Input: + +- {FSdio} *instance_p, SDIO controller instance + +Return: + +- {NONE} + +#### FSdioSetIDMAList + +```c +FError FSdioSetIDMAList(FSdio *const instance_p, volatile FSdioIDmaDesc *desc, u32 desc_num) +``` + +Note: + +- Setup DMA descriptor for SDIO controller instance + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {volatile FSdioIDmaDesc} *desc, first item in DMA descriptor lists +- {u32} desc_num, number of items in DMA descriptor lists + +Return: + +- {FError} FSDIO_SUCCESS if setup done, otherwise failed + +#### FSdioSetClkFreq + +```c +void FSdioSetClkFreq(FSdio *const instance_p, u32 input_clk_hz) +``` + +Note: + +- Set the Card clock freqency + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {u32} input_clk_hz, Card clock freqency in Hz + +Return: + +- {None} + +#### FSdioDMATransfer + +```c +FError FSdioDMATransfer(FSdio *const instance_p, FSdioCmdData *const cmd_data_p) +``` + +Note: + +- Start command and data transfer in DMA mode + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioCmdData} *cmd_data_p, contents of transfer command and data + +Return: + +- {FError} FSDIO_SUCCESS if transfer success, otherwise failed + +#### FSdioPollWaitDMAEnd + +```c +FError FSdioPollWaitDMAEnd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p, FSdioRelaxHandler relax) +``` + +Note: + +- Wait DMA transfer finished by poll + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioCmdData} *cmd_data_p, contents of transfer command and data +- {FSdioRelaxHandler} relax, handler of relax when wait busy + +Return: + +- {FError} FSDIO_SUCCESS if wait success, otherwise wait failed + +#### FSdioGetInterruptMask + + +```c +u32 FSdioGetInterruptMask(FSdio *const instance_p, FSdioIntrType type) +``` + +Note: + +- Get SDIO controller interrupt mask + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioIntrType} type, Type of interrupt, controller/DMA interrupt + +Return: + +- {u32} interrupt mask bits + +#### FSdioSetInterruptMask + + +```c +void FSdioSetInterruptMask(FSdio *const instance_p, FSdioIntrType type, u32 set_mask, boolean enable) +``` + +Note: + +- Enable/Disable SDIO controller interrupt + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioIntrType} type, Type of interrupt, controller/DMA interrupt +- {u32} set_mask, interrupt mask bits +- {boolean} enable, TRUE: enable interrupt mask bits + +Return: + +- {NONE} + +#### FSdioInterruptHandler + +```c +void FSdioInterruptHandler(s32 vector, void *param) +``` + +Note: + +- Interrupt handler for SDIO instance + +Input: + +- {s32} vector, Interrupt id +- {void} *param, Interrupt params, is SDIO instance + +Return: + +- {NONE} + +#### FSdioRegisterEvtHandler + +```c +void FSdioRegisterEvtHandler(FSdio *const instance_p, FSdioEvtType evt, FSdioEvtHandler handler, void *handler_arg) +``` + +Note: + +- Register event call-back function as handler for interrupt events + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioEvtType} evt, interrupt event +- {FSdioEvtHandler} handler, event call-back function +- {void} *handler_arg, argument of event call-back function + +Return: + +- {NONE} + + +#### FSdioPIOTransfer + +```c +FError FSdioPIOTransfer(FSdio *const instance_p, FSdioCmdData *const cmd_data_p) +``` + +Note: + +- Start command and data transfer in PIO mode + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioCmdData} *cmd_data_p, contents of transfer command and data + +Return: + +- {FError} FSDIO_SUCCESS if transfer success, otherwise failed + +#### FSdioPollWaitPIOEnd + +```c +FError FSdioPollWaitPIOEnd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p, FSdioRelaxHandler relax); +``` + +Note: + +- Wait PIO transfer finished by poll + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioCmdData} *cmd_data_p, contents of transfer command and data +- {FSdioRelaxHandler} relax, handler of relax when wait busy + +Return: + +- {FError} FSDIO_SUCCESS if wait success, otherwise wait failed + +#### FSdioGetCmdResponse + +```c +FError FSdioGetCmdResponse(FSdio *const instance_p, FSdioCmdData *const cmd_data_p) +``` + +Note: + +- Get cmd response and received data after wait poll status or interrupt signal + +Input: + +- {FSdio} *instance_p, SDIO controller instance +- {FSdioCmdData} *cmd_data_p, contents of transfer command and data + +Return: + +- {FError} FSDIO_SUCCESS if get success + +#### FSdioRestart + +```c +FError FSdioRestart(FSdio *const instance_p) +``` + +Note: + +- reset controller from error state + +Input: + +- {FSdio} *instance_p, instance of controller + +Return: + +- {FError} FSDIO_SUCCESS if restart success diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fsdmmc.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fsdmmc.md new file mode 100644 index 0000000000..e4805188bf --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fsdmmc.md @@ -0,0 +1,383 @@ +# FSDMMC 驱动程序 + +## 1. 概述 + +SD/MMC控制器主要提供对固态非易失性存储的内存卡的访问能力,包括多媒体存储卡(MMC,MultiMedia Card)和安全和数据保护卡(SD,Secure Digital Card)。 + +## 2. 功能 + +SD/MMC控制器驱动提供了SD/MMC卡的控制访问方法, +- 初始化SD/MMC控制器 +- 以轮询方式发送/接收数据和命令 +- 以中断方式发送/接收数据和命令 +- 设置SD/MMC控制器的中断工作模式和中断响应函数 + +访问SD/MMC卡需要兼容一系列协议命令,这一部分驱动不提供,可以通过第三方框架sdmmc使用 + +驱动相关的源文件包括, +``` +fsdmmc + ├── fsdmmc.c + ├── fsdmmc.h + ├── fsdmmc_dma.c + ├── fsdmmc_dma.h + ├── fsdmmc_g.c + ├── fsdmmc_hw.c + ├── fsdmmc_hw.h + ├── fsdmmc_intr.c + └── fsdmmc_sinit.c +``` + +## 3. 配置方法 + +以下部分将指导您完成 FSDMMC 驱动的软件配置: + +- 初始化FSDMMC控制器 +- 通过协议命令完成SD/MMC卡初始化 +- 通过协议命令读写SD/MMC卡数据 + +## 4 应用示例 + +### [检测SD卡](../../../baremetal/example/peripheral/mmc/fsdmmc_probe) + +### [SD/MMC卡协议实现](../../../third-party/sdmmc) + +### [通过协议命令读写SD卡](../../../baremetal/example/storage/sdmmc_cmds) + +### [通过文件系统使用SD卡](../../../baremetal/example/storage/sdmmc_fatfs) + +## 5. API参考 + +### 5.1. 用户数据结构 + +- FSDMMC控制数据 + +```c +typedef struct +{ + FSdmmcConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + FSdmmcEventHandler evt_handler[FSDMMC_EVT_NUM]; +} FSdmmc; /* Device instance */ +``` + +- FSDMMC配置数据 + +```c +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num[FSDMMC_INTR_NUM]; +} FSdmmcConfig; +``` + +- FSDMMC命令结构 +```c +typedef struct +{ + u32 cmdidx; + u32 cmdarg; + u32 resptype; + u32 response[4]; + u32 flag; +#define FSDMMC_CMD_FLAG_NEED_STOP BIT(0) +#define FSDMMC_CMD_FLAG_NEED_INIT BIT(1) +#define FSDMMC_CMD_FLAG_EXP_RESP BIT(2) +#define FSDMMC_CMD_FLAG_EXP_LONG_RESP BIT(3) +#define FSDMMC_CMD_FLAG_NEED_RESP_CRC BIT(4) +#define FSDMMC_CMD_FLAG_EXP_DATA BIT(5) +#define FSDMMC_CMD_FLAG_WRITE_DATA BIT(6) +#define FSDMMC_CMD_FLAG_READ_DATA BIT(7) +#define FSDMMC_CMD_FLAG_NEED_AUTO_STOP BIT(8) +#define FSDMMC_CMD_FLAG_ADTC BIT(9) + FSdmmcData *data_p; +} FSdmmcCmd; +``` + +- FSDMMC数据结构 +```c +typedef struct +{ + u8 *buf; + u32 blksz; + u32 blkcnt; + u32 datalen; +} FSdmmcData; +``` + +- FSDMMC中断类型和中断事件 +```c +enum +{ + FSDMMC_DMA_BD_INTR = 0, + FSDMMC_CMD_INTR, + FSDMMC_ERROR_INTR, + + FSDMMC_INTR_NUM +}; /* 中断类型 */ + +enum +{ + FSDMMC_EVT_CARD_REMOVED = 0, + FSDMMC_EVT_CMD_DONE, + FSDMMC_EVT_CMD_ERROR, + FSDMMC_EVT_CMD_RESP_ERROR, + FSDMMC_EVT_DATA_ERROR, + FSDMMC_EVT_DATA_READ_DONE, + FSDMMC_EVT_DATA_WRITE_DONE, + + FSDMMC_EVT_NUM +}; /* 事件类型 */ +``` + +### 5.2 错误码定义 + +- [0x0] FSDMMC_SUCCESS : success + +- [0x10c0001] FSDMMC_ERR_NOT_READY : FSDMMC控制器未初始化 + +- [0x10c0001] FSDMMC_ERR_TIMEOUT : 数据或者命令传输等待超时 + +- [0x10c0001] FSDMMC_ERR_CMD_FAILED : 命令传输失败 + +- [0x10c0001] FSDMMC_ERR_DATA_FAILED : 数据传输失败 + +- [0x10c0001] FSDMMC_ERR_CARD_NO_FOUND : 卡未检测到 + +- [0x10c0001] FSDMMC_ERR_INVALID_BUF : 数据缓冲区不合法 + +### 5.3. 用户API接口 + +#### FSdmmcLookupConfig + +- 获取FSDMMC控制器默认配置 + +```c +const FSdmmcConfig *FSdmmcLookupConfig(u32 instance_id); +``` + +Note: + +- instance_id从0开始,取决于FSDMMC控制器的个数 + +Input: + +- {u32} instance_id 驱动控制器ID + +Return: + +- {const FSdmmcConfig *} FSDMMC默认配置,返回NULL如果找不到默认配置 + +#### FSdmmcCfgInitialize + +- 初始化FSDMMC控制器, 使之可以使用 + +```c +FError FSdmmcCfgInitialize(FSdmmc *instance_p, const FSdmmcConfig *input_config_p); +``` + +Note: + +- 输入配置通过FSdmmcLookupConfig获取,用户按照需要修改后传入此函数 + +Input: + +- {FSdmmc} *instance_p FSDMMC驱动控制数据 +- {FSdmmcConfig} *input_config_p FSDMMC用户输入配置 + +Return: + +- {FError} 驱动初始化的错误码信息,FSDMMC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FSdmmcDeInitialize + +- 去使能FSDMMC控制器, 清零实例数据 + +```c +void FSdmmcDeInitialize(FSdmmc *instance_p); +``` + +Note: + +- 无 + +Input: + +- {FSdmmc} *instance_p FSDMMC驱动控制数据 + +Return: + +- 无 + +#### FSdmmcPollTransfer + +- 通过FSDMMC轮询方式发送/接收数据和命令 + +```c +FError FSdmmcPollTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p); +``` + +Note: + +- FSDMMC控制器初始化后才能调用此函数 + +Input: + +- {FSdmmc} *instance_p FSDMMC驱动控制数据 +- {FSdmmcCmd} *cmd_data_p FSDMMC数据和命令 + +Return: + +- {FError} 驱动初始化的错误码信息,FSDMMC_SUCCESS 表示发送/接收成功,其它返回值表示发送/接收失败 + +#### FSdmmcInterruptTransfer + +- 通过FSDMMC中断方式发送/接收数据和命令 + +```c +FError FSdmmcInterruptTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p); +``` + +Note: + +- FSDMMC控制器初始化后才能调用此函数,使用前需要确保FSDMMC中断设置完成 + +Input: + +- {FSdmmc} *instance_p FSDMMC驱动控制数据 +- {FSdmmcCmd} *cmd_data_p FSDMMC数据和命令 + +Return: + +- {FError} 驱动初始化的错误码信息,FSDMMC_SUCCESS 表示发送/接收成功,其它返回值表示发送/接收失败 + +#### FSdmmcGetInterruptMask + +- 获取FSDMMC的中断掩码 + +```c +u32 FSdmmcGetInterruptMask(uintptr base_addr, u32 intr_type); +``` + +Note: + +- FSDMMC控制器初始化后才能调用此函数 + +Input: + +- {uintptr} base_addr FSDMMC控制器基地址 +- {u32} intr_type FSDMMC中断类型, 参考FSDMMC_INTR_NUM + +Return: + +- {u32} 中断掩码 + +#### FSdmmcSetInterruptMask + +- 设置FSDMMC的中断掩码 + +```c +void FSdmmcSetInterruptMask(uintptr base_addr, u32 intr_type, u32 mask, boolean enable); +``` + +Note: + +- FSDMMC控制器初始化后才能调用此函数 + +Input: + +- {uintptr} base_addr FSDMMC控制器基地址 +- {u32} intr_type FSDMMC中断类型, 参考FSDMMC_INTR_NUM +- {u32} mask 中断掩码 +- {boolean} enable TRUE:打开中断, FALSE:关闭中断 + +Return: + +- 无 + +#### FSdmmcCmdInterrupHandler + +- 命令中断响应函数 + +```c +void FSdmmcCmdInterrupHandler(s32 vector, void *param); +``` + +Note: + +- 此函数用于设置FSDMMC中断时注册,用户可以自定义一个中断响应函数替换此函数 + +Input: + +- vector 中断向量号 +- {void} *param 中断响应输入参数 + +Return: + +- 无 + +#### FSdmmcDmaInterrupHandler + +- DMA中断响应函数 + +```c +void FSdmmcDmaInterrupHandler(s32 vector, void *param); +``` + +Note: + +- 此函数用于设置FSDMMC中断时注册,用户可以自定义一个中断响应函数替换此函数 + +Input: + +- {s32} vector 中断向量号 +- {void} *param 中断响应输入参数 + +Return: + +- 无 + +#### FSdmmcErrInterrupHandler + +- 错误中断响应函数 + +```c +void FSdmmcErrInterrupHandler(s32 vector, void *param); +``` + +Note: + +- 此函数用于设置FSDMMC中断时注册,用户可以自定义一个中断响应函数替换此函数 + +Input: + +- {s32} vector 中断向量号 +- {void} *param 中断响应输入参数 + +Return: + +- 无 + +#### FSdmmcRegisterInterruptHandler + +- 注册中断事件响应函数 + +```c +void FSdmmcRegisterInterruptHandler(FSdmmc *instance_p, u32 event, FSdmmcEventHandler handler); +``` + +Note: + +- 此函数用于设置FSDMMC中断时注册,被注册的函数被FSdmmcCmdInterrupHandler、FSdmmcErrInterrupHandler + * 和FSdmmcDmaInterrupHandler调用 + +Input: + +- {FSdmmc} *instance_p FSDMMC驱动控制数据 +- {u32} event FSDMMC中断事件类型,参考FSDMMC_EVT_NUM +- {FSdmmcEventHandler} handler, FSDMMC中断事件响应函数 + +Return: + +- 无 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fsemaphore.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fsemaphore.md new file mode 100644 index 0000000000..8419c8d613 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fsemaphore.md @@ -0,0 +1,254 @@ +# FSemaphore 驱动程序 + +## 1. 概述 + +硬件信号量(Semaphore)是E2000提供的一个二值信号量模块,支持 32 个硬件信号量。每个信号量包括 UNLOCK 和 LOCKED 两个状态 + +## 2. 功能 + +FSemaphore 驱动程序主要完成 Semaphore 模块的初始化,锁的分配、获取与释放, +相关源文件为: +``` +fsemaphore + . + ├── fsemaphore.c + ├── fsemaphore.h + ├── fsemaphore_g.c + ├── fsemaphore_hw.h + └── fsemaphore_sinit.c +``` + +## 3. 配置方法 + +以下部分将指导您完成 FSemaphore 驱动的软件配置: + +- 初始化 Semaphore 控制器 +- 获取 Semaphore 锁 +- 加锁/解锁操作 + +## 4. 应用示例 + +### [Semaphore加锁解锁测试](../../../baremetal/example/peripheral/ipc/fsemaphore_test) + +## 5. API参考 + + +### 5.1. 用户数据结构 + +#### FSemaConfig + +- Semaphore控制器配置 + +```c +typedef struct +{ + u32 id; /* Semaphore控制器id */ + uintptr base_addr; /* Semaphore控制器基地址 */ +} FSemaConfig; /* Semaphore控制器配置 */ +``` + +#### FSemaLocker + +- Semaphore锁实例 + +```c +typedef struct +{ + u32 index; /* Semaphore锁id */ +#define FSEMA_LOCKER_NAME_LEN 32U + char name[FSEMA_LOCKER_NAME_LEN]; /* Semaphore锁的名字 */ + u32 owner; /* Semaphore锁的拥有者 */ + FSema *sema; /* Semaphore控制器实例 */ +} FSemaLocker; /* Semaphore锁实例 */ +``` + +#### FSema + +- Semaphore控制器实例 + +```c +typedef struct _FSema +{ + FSemaConfig config; /* Semaphore控制器配置 */ + u32 is_ready; /* Semaphore控制器初始化是否完成 */ + FSemaLocker *locker[FSEMA_NUM_OF_LOCKER]; /* Semaphore锁实例,locker[i] == NULL 表示锁尚未分配 */ +} FSema; /* Semaphore控制器实例 */ +``` +### 5.2 错误码定义 + +FSEMA_SUCCESS :成功 +FSEMA_ERR_NOT_INIT :控制器未初始化 +FSEMA_ERR_NO_AVAILABLE_LOCKER :没有空闲的锁可以分配 +FSEMA_ERR_LOCK_TIMEOUT :锁被占用,获取锁失败 +FSEMA_ERR_NO_PERMISSION :当前角色没有权限操作 + +### 5.3. 用户API接口 + +#### FSemaLoopkupConfig + +```c +const FSemaConfig *FSemaLoopkupConfig(u32 instance_id) +``` + +Note: + +- 获取Semaphore的默认配置 + +Input: + +- {u32} instance_id, Semaphore的实例id + +Return: + +- {const FSemaConfig *} Semaphore的默认配置 + +#### FSemaCfgInitialize + +```c +FError FSemaCfgInitialize(FSema *const instance, const FSemaConfig *input_config) +``` + +Note: + +- 初始化Semaphore控制器 + +Input: + +- {FSema} *instance, Semaphore控制器实例 +- {FSemaConfig} *input_config, Semaphore控制器配置 + +Return: + +- {FError} FSEMA_SUCCESS 表示初始化成功 + +#### FSemaDeInitialize + +```c +void FSemaDeInitialize(FSema *const instance) +``` + +Note: + +- 去初始化Semaphore控制器 + +Input: + +- {FSema} *instance, Semaphore控制器实例 + +Return: + +- 无 + +#### FSemaCreateLocker + +```c +FError FSemaCreateLocker(FSema *const instance, FSemaLocker *const locker) +``` + +Note: + +- 分配和创建Semaphore锁 + +Input: + +- {FSema} *instance, Semaphore控制器实例 +- {FSemaLocker} *locker, Semaphore锁的实例 + +Return: + +- {FError} FSEMA_SUCCESS 表示分配成功 + +#### FSemaDeleteLocker + +```c +FError FSemaDeleteLocker(FSemaLocker *const locker) +``` + +Note: + +- 强制解除Semaphore锁并删除锁实例 + +Input: + +- {FSemaLocker} *locker, Semaphore锁实例 + +Return: + +- {FError} FSEMA_SUCCESS 表示删除锁成功 + +#### FSemaTryLock + +```c +FError FSemaTryLock(FSemaLocker *const locker, u32 owner, u32 try_times, FSemaRelaxHandler relax_handler) +``` + +Note: + +- 尝试获取Semaphore锁 + +Input: + +- {FSemaLocker} *locker, Semaphore锁的实例 +- {u32} owner, 当前尝试获取锁的是谁 +- {u32} try_times, 尝试获取的次数 +- {FSemaRelaxHandler} relax_handler, 每次尝试获取锁失败后的relax函数 + +Return: + +- {FError} FSEMA_SUCCESS 表示成功获取锁,FSEMA_ERR_LOCK_TIMEOUT 表示锁已经被占用 + +#### FSemaUnlock + +```c +FError FSemaUnlock(FSemaLocker *const locker, u32 owner) +``` + +Note: + +- 尝试释放Semaphore锁 + +Input: + +- {FSemaLocker} *locker, Semaphore锁实例 +- {u32} owner, 当前尝试释放锁的身份 + +Return: + +- {FError} FSEMA_SUCCESS释放锁成功 + +#### FSemaUnlockAll + +```c +FError FSemaUnlockAll(FSema *const instance) +``` + +Note: + +- 强制解除所有Semaphore锁 + +Input: + +- {FSema} *instance, Semaphore控制器实例 + +Return: + +- {FError} FSEMA_SUCCESS表示强制解锁成功 + +#### FSemaIsLocked + +```c +boolean FSemaIsLocked(FSemaLocker *locker) +``` + +Note: + +- 检查指定Semaphore锁是否处于锁定状态 + +Input: + +- {FSemaLocker} *locker, Semaphore锁实例 + +Return: + +- {boolean} TRUE: 处于锁定状态 + diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fspim.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fspim.md new file mode 100644 index 0000000000..909cd4dfe5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fspim.md @@ -0,0 +1,374 @@ +# FSPIM 驱动程序 + +## 1. 概述 + + +- SPI 总线是一种4线总线,提供了一种高速、高效率的串行通信技术。SPI 通信通常有一个主设备和一个或多个从设备,需要至少4根线,它们是 MISO(主设备数据输入)、MOSI(主设备数据输出)、SCLK(时钟)、CS(片选) + +- 其中,CS是从芯片是否被主芯片选中的控制信号,SCLK提供时钟脉冲,SDI,SDO则基于此脉冲完成数据传输 + +- 本驱动程序提供了FT2000/4、D2000平台的SPI主设备功能 + +- FT2000/4、D2000上包含 2 个通用 SPI 接口,仅作为通用 SPI 主设备使用,外部最多挂载 4 个 SPI 从设备 + + +## 2. 功能 + + +- 驱动相关的源文件如下, +- drivers/spi/fspim + +``` +. +├── fspim.c +├── fspim.h +├── fspim_g.c +├── fspim_hw.c +├── fspim_hw.h +├── fspim_intr.c +├── fspim_options.c +└── fspim_sinit.c +``` + +- FSPIM 常用于读写Nor-flash,其应用可以参考以下结构,最底层的硬件是 SPI 主机控制器和 Nor-flash, 其上由 FSPIM 驱动和 SFUD 提供 Spi Nor-flash的读写接口,面向SPI文件系统,如 LittleFS 和 SPIFFS,文件系统提供负载均衡、坏块检测和断电保护等特性,并为上层应用提供文件创建/读写等接口,使用方法参考`4 应用示例` + +![spi_app](./figs/spi_app.png) + +## 3. 配置方法 + + +以下部分将指导您完成 FSPIM 驱动的软件配置: + +### 3.1 使用 SFUD 通用SPI协议框架 + +- 使能 CONFIG_USE_FSPIM 和 CONFIG_USE_SFUD 配置 +- 初始化 SFUD 框架 +- 调用 SFUD 提供的 API 读写 SPI 从设备 + +关于 SFUD 框架的使用,可以参考[sfud.md](./sfud.md) + +### 3.2 不使用 SFUD 通用SPI协议框架 + +- 使能 CONFIG_USE_FSPIM 配置 +- 初始 FSPIM 驱动 +- 调用 FSPIM 提供的 API 读写 SPI 从设备,需要按照 SPI 从设备的手册实现相关的命令和协议 + +## 4 应用示例 + +### [SPI 回环测试](../../../baremetal/example/peripheral/spi/fspim_loopback/README.md) + +### [SPI Norflash读写测试](../../../baremetal/example/storage/spi_sfud/README.md) + +### [SPI Norflash文件系统测试-LittleFS](../../../baremetal/example/storage/littlefs_test/README.md) + +### [SPI Norflash文件系统测试-SPIFFS](../../../baremetal/example/storage/spiffs_test/README.md) + +## 4. API参考 + +### 4.1 用户数据结构 + +- SPIM 驱动配置数据 +```c +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num; /* Device intrrupt id */ + u32 irq_prority; /* Device intrrupt priority */ + FSpimSlaveDevice slave_dev_id; /* Slave device id */ + u32 max_freq_hz; /* Clock frequency in Hz */ + FSpimTransByte n_bytes; /* Bytes in transfer */ + FSpimCpolType cpol; /* Polarity of the clock */ + FSpimCphaType cpha; /* Phase of the clock */ + boolean en_test; /* Enable test mode */ +} FSpimConfig; +``` + +- SPIM 驱动控制数据 +```c +typedef struct +{ + FSpimConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + u32 length; /* Data length in transfer */ + const void *tx_buff; /* Tx buffer beg */ + void *rx_buff; /* Rx buffer beg */ + const void *tx_buff_end; /* Tx buffer end */ + void *rx_buff_end; /* Rx buffer end */ + u32 tx_fifo_len; /* Depth of tx fifo */ + u32 rx_fifo_len; /* Depth of rx fifo */ + FSpimEvtHandler evt_handler[FSPIM_INTR_EVT_NUM]; /* event handler for interrupt */ + void *evt_param[FSPIM_INTR_EVT_NUM]; /* parameters ptr of event handler */ +} FSpim; +``` + +- SPI 从设备ID,最多支持4个从设备 +```c +enum +{ + FSPIM_SLAVE_DEV_0 = 0, + FSPIM_SLAVE_DEV_1, + FSPIM_SLAVE_DEV_2, + FSPIM_SLAVE_DEV_3, + + FSPIM_NUM_OF_SLAVE_DEV +}; +``` + +- 一次 SPI 传输的数据量,一个字节或者两个字节 +```c +enum +{ + FSPIM_1_BYTE = 1, + FSPIM_2_BYTE = 2, + + FSPIM_MAX_BYTES_NUM +}; +``` + +- SPI传输,选择接收/发送 +```c +enum +{ + FSPIM_TRANS_MODE_RX_TX = 0x0, + FSPIM_TRANS_MODE_TX_ONLY = 0x1, + FSPIM_TRANS_MODE_RX_ONLY = 0x2, + FSPIM_TRANS_MODE_READ_EEPROM = 0x3, + + FSPIM_TRANS_MODE_MAX +}; +``` + +- SPI的时钟极性和相位 +```c +enum +{ + FSPIM_CPOL_LOW = 0, + FSPIM_CPOL_HIGH +}; + +enum +{ + FSPIM_CPHA_1_EDGE = 0, + FSPIM_CPHA_2_EDGE +}; +``` + +### 4.2 错误码定义 + +- 模块错误码编号:0x1060000 +- [0x0] FSPIM_SUCCESS : fspim success +- [0x1060000] FSPIM_SUCCESS : fspim success +- [0x1060001] FSPIM_ERR_INVAL_STATE : fspim invalid state +- [0x1060002] FSPIM_ERR_NOT_READY : fspim driver not ready +- [0x1060003] FSPIM_ERR_INVAL_PARAM : fspim invalid input parameters +- [0x1060004] FSPIM_ERR_BUS_BUSY : fspim bus is busy +- [0x1060005] FSPIM_ERR_NOT_SUPPORT : fspim not support operation +- [0x1060006] FSPIM_ERR_TIMEOUT : fspim wait timeout + +### 4.3 用户API接口 + +#### FSpimLookupConfig + +- 获取FSPIM驱动的默认配置参数 + +```c +const FSpimConfig *FSpimLookupConfig(u32 instance_id) +``` + +Note: + +- 用户可以通过此接口获取驱动默认配置的副本,进行修改后,作为`FSpimCfgInitialize`函数的入参使用 + +Input: + +- u32 instance_id, 选择的FSPIM控制器实例号 + +Return: + +- const FSpimConfig *, 返回的默认驱动配置,返回NULL表示失败 + + +#### FSpimCfgInitialize + +- 完成FSPIM驱动实例的初始化,使之可以使用 + +```c +FError FSpimCfgInitialize(FSpim *instance_p, const FSpimConfig *cofig_p); +``` + +Note: + +- 此函数会重置FSPIM控制器和FSPIM控制数据 + +Input: + +- FSpim *instance_p, FSPIM驱动控制数据 + +- const FSpimConfig *input_config_p, FSPIM驱动配置数据 + +Return: + +- FError, 驱动初始化的错误码信息,FSPIM_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FSpimDeInitialize + +- 完成FSPIM驱动实例去初始化,之后不能使用 + +```c +void FSpimDeInitialize(FSpim *instance_p) +``` + +Note: + +- 此函数会重置FSPIM控制数据 + +Input: + +- FSpim *instance_p, FSPIM驱动控制数据 + +Return: + +无 + +#### FSpimTransferPollFifo +- 先发送后接收数据 (阻塞处理),利用Fifo进行处理 + +```c +FError FSpimTransferPollFifo(FSpim *instance_p, const void *tx_buf, void *rx_buf, fsize_t len); +``` + +Note: + +- 使用此函数前需要确保FSPIM驱动初始化成功 +- 从函数不会使用中断,会按照TX FIFO的深度进行传输,每次发送填满TX FIFO后触发发送/接收动作 + +Input: + +- FSpim *instance_p, FSPIM驱动控制数据 + +- const void *tx_buf, 写缓冲区,可以为空,为空时表示只关注读数据,此时驱动会发送0xff读数据 + +- void *rx_buf, 读缓冲区, 可以为空,为空时表示值关注写数据,此时SPI总线上返回的数据会被抛弃 + +- fsize_t len, 进行传输的长度,如果tx_buf或者rx_buf不为空,则两个buf的长度必须为len + +Return: + +- FError, 驱动初始化的错误码信息,FSPIM_SUCCESS 表示数据交换成功,其它返回值表示交换失败 + +#### FSpimTransferByInterrupt + +- 先发送后接收数据 (中断处理),利用Fifo进行处理 + +```c +FError FSpimTransferByInterrupt(FSpim *instance_p, const void *tx_buf, void *rx_buf, fsize_t len); +``` + +Note: + +- 使用此函数前需要确保FSPIM驱动初始化成功 +- 此函数会安装TX FIFO的深度进行传输,每次发送填满TX FIFO后在中断中处理发送/接收动作,用户需要注册FSPIM_INTR_EVT_RX_DONE事件,传输过程中用户处理其它任务,等待传输完成后从tx_buf和rx_buf中读数据 + +Input: + +- FSpim *instance_p, FSPIM驱动控制数据 + +- const void *tx_buf, 写缓冲区,可以为空,为空时表示只关注读数据,此时驱动会发送0xff读数据 + +- void *rx_buf, 读缓冲区, 可以为空,为空时表示值关注写数据,此时SPI总线上返回的数据会被抛弃 + +- fsize_t len, 进行传输的长度,如果tx_buf或者rx_buf不为空,则两个buf的长度必须为len + +Return: + +- FError, 驱动初始化的错误码信息,FSPIM_SUCCESS 表示数据交换成功,其它返回值表示交换失败 + +#### FSpimInterruptHandler + +- SPIM中断处理函数 + +```c +void FSpimInterruptHandler(s32 vector, void *param); +``` + +Note: + +- 此函数给用户注册在中断处理模块中,从而在中断触发时进行处理 +- 使用此函数前,用户需要打开部分中断屏蔽位 + +Input: + +- s32 vector, 中断向量号,此处不关心此参数 + +- void *param, 中断输入参数, 指向FSPIM的驱动控制实例 + +Return: + +无 + +#### FSpimRegisterIntrruptHandler +- SPIM中断事件注册函数 + +```c +void FSpimRegisterIntrruptHandler(FSpim *instance_p, u32 evt, FSpimEvtHandler handler, void *param) +``` + +Note: + +- 此函数与FSpimInterruptHandler配套使用,为中断处理注册事件回调函数 + +Input: + +- FSpim *instance_p, FSPIM驱动控制数据 + +- u32 evt, 中断事件号码,参考FSPIM_INTR_EVT_NUM + +- FSpimEvtHandler handler, 中断事件回调函数 + +- void *param, 中断事件回调函数的入参,取决于中断事件回调函数的实现 + +Return: + +无 + +#### FSpimErrorToMessage + +- 获取FSPIM驱动错误码 + +```c +const char *FSpimErrorToMessage(FError error); +``` + +Note: + +无 + +Input: + +- FError error, FSPIM模块错误码 + +Return: + +const char *, FSPIM模块错误码对应的信息 + +#### FSpimSetChipSelection + +- 获取FSPIM驱动错误码 + +```c +void FSpimSetChipSelection(FSpim *instance_p, boolean on); +``` + +Note: + +无 + +Input: + +- {FSpim} *instance_p, 驱动控制数据 +- {boolean} on, TRUE: 片选打开, FALSE: 片选关闭 + +Return: + +- 无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fusb.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fusb.md new file mode 100644 index 0000000000..16c74266ae --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fusb.md @@ -0,0 +1,535 @@ + +# FUSB 驱动程序 + +## 1. 概述 + +USB是通用串行总线(Universal Serial Bus)的缩写, USB是一种简易、双向、快速、同步、即插即用(Plug and Play,PnP)且支持热插拔功能的串行接口。USB设备现在已经非常普及,如U盘、鼠标、键盘等。USB协议曾经出现过多种版本,如USB1.0、USB1.1、USB2.0、USB3.0等 + +USB总线体系中, USB主机(Host)是系统的主人, 负责USB通信过程中数据的控制和处理, USB设备(Device)是系统的从机,用于实现特定的功能,如常用的U盘、移动硬盘、鼠标、键盘、游戏手柄等,在USB传输过程中,USB主机处于主导地位,由USB主机发起数据和命令的传输,USB设备被动响应USB主机发来的请求命令,USB总线中的主要角色包括USB主机、根Hub、USB Hub和USB设备等 + +USB主机和USB设备间的通信是通过管道(Pipe)进行的,管道是指在USB主机端的一组缓冲区,用于管道中数据的收发;在USB设备端,有一个特定端点(Endpoint,ENDP)与管道对接 + +USB可靠传输(具有反馈机制)的最小单位是事务,事务就是利用令牌包、数据包和握手包实现一个带有错误反馈机制的通信,使USB传输更加安全可靠,按照令牌包的类型可以分为,Setup事务、IN事务、OUT事务等。基于事务,USB协议定义了传输(Transfer)用于完成一组具有特定目的的事务,包括控制传输、中断传输、批量传输和同步传输 + +## 2. 功能 + +- 驱动相关的源文件如下, +- drivers/usb +``` +. +├── Kconfig +├── fusb.c +├── fusb.h +├── fusb_debug.c +├── fusb_def.h +├── fusb_dev.c +├── fusb_g.c +├── fusb_generic_hub.c +├── fusb_generic_hub.h +├── fusb_hid.c +├── fusb_hid.h +├── fusb_hub.c +├── fusb_hub.h +├── fusb_msc.c +├── fusb_msc.h +├── fusb_private.h +├── fusb_sinit.c +``` + +- 关于 [XHCI](./fxhci.md) + +## 3. 配置方法 + +参考以下步骤完成 FUSB 硬件配置, + +- 1. FUSB驱动支持 E2000,在 E2000 上完成测试 + +参考以下步骤完成 FUSB 软件配置, + +- 1. 选择USB控制器类型为 XHCI +- 2. 配置 FUSB 的内存池空间,推荐在1Mb以上 +- 3. 注册USB设备驱动 +- 4. 调用USB控制器驱动接口启动FUSB实例 +- 5. 调用USB控制器驱动接口轮询FUSB,更新USB设备状态 +- 6. 调用USB设备驱动操作USB设备 + +## 4 应用示例 + +- USB主机操作和USB设备发现 +### [fxhci_host](../../../baremetal/example/peripheral/usb/fxhci_host) + +- USB大容量存储器读写 +### [fusb_fatfs](../../../baremetal/example/storage/fusb_fatfs) + +## 5. API参考 + +### 5.1. 用户数据结构 + +#### 5.1.1 USB端点 + +```c +typedef struct +{ + FUsbDev *dev; /* device instance of this endpoint */ + int endpoint; /* endpoint address ep0 = 0, epn = n */ + FUsbDirection direction; /* type or direction of ep */ + int toggle; /* ep state for some device to toggle */ + int maxpacketsize; /* max packet size for ep transfer */ + FUsbEpType type; /* transfer type of ep, control, bulk or so on */ + int interval; /* expressed as binary logarithm of the number + of microframes (i.e. t = 125us * 2^interval) */ +} FUsbEndpoint; /* encapsulates a single endpoint of an USB device */ +``` + +#### 5.1.2 USB设备 + +```c +typedef struct _FUsbDev +{ + FUsbHc *controller; /* Hc instance where device attached */ + FUsbEndpoint endpoints[FUSB_MAX_EP_NUM]; /* all Ep instance of device */ + int num_endp; /* num of Ep in use */ + FUsbDevAddr address; /* USB address */ + FUsbDevClass class; /* USB device class, e.g hid */ + int hub; /* hub where device is attached to */ + int port; /* port where device is attached */ + FUsbSpeed speed; /* speed type of device */ + void *data; /* private data for specific type of device */ + FUsbDeviceDescriptor *descriptor; /* device descriptor ever get from device hw */ + FUsbConfigurationDescriptor *configuration; /* configure descriptor followed with interface descriptor ever get from device hw */ + FUsbConfigParser config_parser; /* parser for configure descriptor */ + FUsbStringParser string_parser; /* parser for string descriptor */ + void (*init)(FUsbDev *dev); /* device init function of specific device type for register */ + void (*destroy) (FUsbDev *dev); /* device deinit function of specific device type for register */ + void (*poll) (FUsbDev *dev); /* device poll function of specific device type for register */ +} FUsbDev; /* encapsulates a single USB device */ +``` + +#### 5.1.3 USB主机 + +```c +typedef struct _FUsbHc +{ + FUsbHc *next; /* next Hc instance in the list */ + uintptr reg_base; /* base address of Hc register */ + FUsb *usb; /* instance of USB system */ + FUsbHcType type; /* type of Hc, e.g XHCI */ + FUsbDev *devices[FUSB_MAX_DEV_NUM]; /* dev 0 is root hub, 127 is last addressable */ + + /* start(): Resume operation. */ + void (*start) (FUsbHc *controller); + /* stop(): Stop operation but keep controller initialized. */ + void (*stop) (FUsbHc *controller); + /* reset(): Perform a controller reset. The controller needs to + be (re)initialized afterwards to work (again). */ + void (*reset) (FUsbHc *controller); + /* init(): Initialize a (previously reset) controller + to a working state. */ + void (*init) (FUsbHc *controller); + /* shutdown(): Stop operation, detach host controller and shutdown + this driver instance. After calling shutdown() any + other usage of this hci_t* is invalid. */ + void (*shutdown) (FUsbHc *controller); + + FUsbTransCode (*bulk) (FUsbEndpoint *ep, int size, u8 *data, int finalize); + FUsbTransCode (*control) (FUsbDev *dev, FUsbDirection pid, int dr_length, + void *devreq, int data_length, u8 *data); + void* (*create_intr_queue) (FUsbEndpoint *ep, int reqsize, int reqcount, int reqtiming); + void (*destroy_intr_queue) (FUsbEndpoint *ep, void *queue); + u8* (*poll_intr_queue) (void *queue); + void *instance; /* instance to specific Hc implementation, e.g XHCI */ + + /* set_address(): Tell the USB device its address (xHCI + controllers want to do this by + themselves). Also, allocate the FUsbDev + structure, initialize enpoint 0 + (including MPS) and return it. */ + FUsbDev *(*set_address) (FUsbHc *controller, FUsbSpeed speed, + int hubport, int hubaddr); + /* finish_device_config(): Another hook for xHCI, returns 0 on success. */ + int (*finish_device_config) (FUsbDev *dev); + /* destroy_device(): Finally, destroy all structures that + were allocated during set_address() + and finish_device_config(). */ + void (*destroy_device) (FUsbHc *controller, int devaddr); +} FUsbHc; /* encapsulates a single USB host */ +``` + +#### 5.1.4 USB系统配置 + +```c +typedef struct +{ + void *(*malloc_align)(size_t size, size_t align); + void (*free)(void *mem); +} FUsbMemAllocator; /* memory allocator used in USB system */ + +typedef struct +{ + u32 instance_id; /* id for this USB system */ + uintptr base_addr; /* base addr of Hc register, set as 0 for pci-usb */ + u32 irq_num; + u32 irq_priority; + FUsbMemAllocator allocator; /* memory allocator to support dynamic memory */ +} FUsbConfig; /* configure data of the USB system */ +``` + +#### 5.1.4 USB系统 + +```c +typedef struct _FUsb +{ + FUsbConfig config; /* configuration of USB system */ + void *pcie_instance; /* NULL if unused */ + void *pcie_info[FUSB_MAX_CTRL_NUM]; /* NULL if unused */ + FUsbHc *hc; /* first hc, there might have multiple hc in pcie-mode */ + /* hook to set init function for specific device type */ + FUsbDevInitFunc dev_init[FUSB_MAX_DEV_TYPE_NUM]; + u32 dev_init_num; /* number of init function in used */ + u32 is_ready; /* indicator of system okay */ +} FUsb; /* instance of the USB system */ +``` + +### 5.2 错误码定义 + + +- 模块错误码编号 `0x1110000` + +- [0x0] FUSB_SUCCESS : success +- [0x1110000] FUSB_ERR_WAIT_TIMEOUT : wait for status timeout +- [0x1110001] FUSB_ERR_INVALID_PARA : invalid input parameters +- [0x1110002] FUSB_ERR_NOT_SUPPORT : parameters or feature not supported +- [0x1110003] FUSB_ERR_NON_INSTANCE : cannot find instance +- [0x1110004] FUSB_ERR_INVALID_DATA : invalid input data +- [0x1110005] FUSB_ERR_DESC_PARSE_ERR : failed to parse descriptor +- [0x1110006] FUSB_ERR_ALLOCATE_FAIL : failed to allocate memory from memory pool +- [0x1110007] FUSB_ERR_TRANS_FAIL : failed to transfer data + + +- 传输过程完成错误码 + +- [0] FUSB_CC_ZERO_BYTES : failed, transfer zero bytes +- [1] FUSB_CC_SUCCESS : transfer success with bytes unkonwn + +### 5.3. 用户API接口 + +#### FUsbLookupConfig + +```c +const FUsbConfig *FUsbLookupConfig(u32 instance_id) +``` + +Note: + +- 获取USB的默认配置 + +Input: + +- {u32} instance_id USB实例号 + +Return: + +- {const FUsbConfig *} USB默认配置 + +#### FUsbCfgInitialize + +```c +FError FUsbCfgInitialize(FUsb *instance, const FUsbConfig *input_config) +``` + +Note: + +- 初始化USB实例 +- 在PCIE模式下,USB Hc实例在PCIE总线发现控制器后创建 + +Input: + +- {FUsb} *instance, USB实例 +- {const FUsbConfig} *input_config, USB输入配置 + +Return: + +- {FError} 初始化错误码 + +#### FUsbDeInitialize + +```c +void FUsbDeInitialize(FUsb *instance); +``` + +Note: + +- 去初始化USB实例 + +Input: + +- {FUsb} *instance, USB实例 + +Return: + +- 无 + +#### FUsbPoll + +```c +void FUsbPoll(FUsb *instance) +``` + +Note: + +- 轮询USB控制器连接的所有设备, 更新设备拓扑 + +Input: + +- {FUsb} *instance, USB实例 + +Return: + +- 无 + +#### FUsbExit + +```c +void FUsbExit(FUsb *instance) +``` + +Note: + +- 关闭所有的USB控制器,移除所有连接的设备 + +Input: + +- {FUsb} *instance, USB实例 + +Return: + +- 无 + + +#### FUsbAssignDevInitFunc + +```c +FError FUsbAssignDevInitFunc(FUsb *instance, const FUsbDevIndex *index, FUsbDevInitHandler handler) +``` + +Note: + +- 指定特定USB设备的初始化函数,供创建USB设备实例时使用 + +Input: + +- {FUsb} *instance, USB实例 +- {FUsbDevIndex} *index, 特定USB设备的索引 +- {FUsbDevInitHandler} handler, 特定USB设备的初始化函数 + +Return: + +- {FError} 处理返回错误码 + +#### FUsbGetAllDevEntries + +```c +size_t FUsbGetAllDevEntries(FUsbHc *controller, FUsbDev *devs[], size_t max_dev_num) +``` + +Note: + +- 获取USB控制器上连接的所有USB设备实例 + +Input: + +- {FUsbHc} *controller, USB控制器实例 +- {FUsbDev} *devs, 放置USB设备实例的缓冲区 +- {size_t} max_dev_num, 最多可以获取的USB设备实例数目 + +Return: + +- {size_t} 实际获取的USB设备实例数目 + +#### FUsbSetFeature + +```c +FUsbTransCode FUsbSetFeature(FUsbDev *dev, int endp, int feature, int rtype) +``` + +Note: + +- 标准USB主机请求,使能设备/接口/端点的某个特性 + +Input: + +- {FUsbDev} *dev, USB设备实例 +- {int} endp, 设备号(0x00)/接口号/端点号 +- {int} feature, 待使能的特性 +- {int} rtype, 请求类型,由FUsbGenerateReqType生成 + +Return: + +- {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + +#### FUsbGetStatus + +```c +FUsbTransCode FUsbGetStatus(FUsbDev *dev, int intf, int rtype, int len, void *data) +``` + +Note: + +- 标准USB主机请求,获取设备/接口/端点的状态 + +Input: + +- {FUsbDev} *dev, USB设备实例 +- {int} intf,设备号(0x00)/接口号/端点号 +- {int} rtype, 请求类型,由FUsbGenerateReqType生成 +- {int} len, Data Stage的数据长度 +- {void} *data, Data Stage的数据缓冲区 + +Return: + +- {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + +#### FUsbGetDescriptor + +```c +FUsbTransCode FUsbGetDescriptor(FUsbDev *dev, int rtype, FUsbDescriptorType desc_type, int desc_idx, void *data, size_t len) +``` + +Note: + +- 标准USB主机请求,获取指定描述符 + +Input: + +- {FUsbDev} *dev, USB设备实例 +- {int} rtype, 请求类型,由FUsbGenerateReqType生成 +- {FUsbDescriptorType} desc_type, 描述符类型 +- {int} desc_idx, 描述符索引 +- {void} *data, Data Stage的数据缓冲区 +- {size_t} len, Data Stage的数据长度 + +Return: + +- {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + +#### FUsbGetStringDescriptor + +```c +FUsbTransCode FUsbGetStringDescriptor(FUsbDev *dev, int rtype, FUsbDescriptorType desc_type, int desc_idx, int lang_id, void *data, size_t len) +``` + +Note: + +- USB主机请求,获取字符串描述符 + +Input: + +- {FUsbDev} *dev, USB设备实例 +- {int} rtype, 请求类型,由FUsbGenerateReqType生成 +- {int} desc_type, 描述符类型 +- {int} desc_idx, 描述符索引 +- {int} lang_id, 语言类型 +- {void} *data, Data Stage的数据缓冲区 +- {size_t} len, Data Stage的数据长度 + +Return: + +- {int} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + +#### FUsbSetConfiguration + +```c +FUsbTransCode FUsbSetConfiguration(FUsbDev *dev) +``` + +Note: + +- 标准USB主机请求,设置配置值 + +Input: + +- {FUsbDev} *dev, USB设备实例 + +Return: + +- {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + +#### FUsbClearFeature + +```c +FUsbTransCode FUsbClearFeature(FUsbDev *dev, int endp, int feature, int rtype) +``` + +Note: + +- 标准USB主机请求,去使能设备/接口/端点的某个特性 + +Input: + +- {FUsbDev} *dev, USB设备实例 +- {int} endp, 设备号(0x00)/接口号/端点号 +- {int} feature,待去除的特性 +- {int} rtype, 请求类型,由FUsbGenerateReqType生成 + +Return: + +- {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + +#### FUsbDumpAllDescriptors + +```c +void FUsbDumpAllDescriptors(FUsbDev *dev) +``` + +Note: + +- 打印USB设备的描述符信息(设备描述符,配置描述符和接口描述符) + +Input: + +- {FUsbDev} *dev, USB设备实例,已完成初始化 + +Return: + +- 无 + +#### FUsbDetachDev + +```c +void FUsbDetachDev(FUsbHc *controller, int devno) +``` + +Note: + +- 从USB主机移除指定USB设备(USB设备驱动使用) + +Input: + +- {FUsbHc} *controller, USB控制器实例 +- {int} devno, USB设备地址 + +Return: + +- 无 + + +#### FUsbAttachDev + +```c +FUsbDevAddr FUsbAttachDev(FUsbHc *controller, int hubaddress, int port, FUsbSpeed speed) +``` + +Note: + +- 向USB主机添加USB设备(USB设备驱动使用) + +Input: + +- {FUsbHc} *controller, USB控制器实例 +- {int} hubaddress, Hub地址 +- {int} port, 连接的Port +- {FUsbSpeed} speed, USB设备的设置速度类型 + +Return: + +- {FUsbDevAddr} 分配的USB设备地址 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fwdt.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fwdt.md new file mode 100644 index 0000000000..c24f78e303 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fwdt.md @@ -0,0 +1,171 @@ +# WDT 驱动程序 + +## 1. 概述 + +- WDT(watchdog timer)看门狗定时器是一种监控系统运行状况的手段,软件需在运行过程中定时向看门狗发送喂狗信号。 + +- 若看门狗定时器在一段时间内没有收到来自软件的喂狗信号,则认为系统故障,会强制系统复位。 + +- WDT 驱动支持的平台包括 FT2000/4、D2000、E2000。 + +## 2. 功能 + +WDT 驱动程序主要完成WDT模块的初始化、超时时间设置和超时中断函数,该驱动程序具备以下功能: + +- 模块初始化 +- 超时时间设置 +- 超时中断函数设置 + +相关源文件为: +``` +fwdt + ├── fwdt.c + ├── fwdt.h + ├── fwdt_g.c + ├── fwdt_hw.c + ├── fwdt_hw.h + ├── fwdt_intr.c + └── fwdt_sinit.c +``` + +## 3. 配置方法 + +以下部分将指导您完成 WDT 驱动的软件配置: + +- 配置驱动程序,新建应用工程,使能WDT驱动模块 +- 设置配置参数 +- 设置超时时间 +- 设置超时中断函数喂狗 + +## 4. 应用示例 + + +### [wdt_test](../../../baremetal/example/peripheral/timer/wdt_test/README.md) + + +## 5. API参考 + + +### 5.1. 用户数据结构 + +- drivers/wdt/fwdt/fwdt.h + +- wdt实例配置 + +```c +typedef struct +{ + u32 instance_id;/* wdt id */ + uintptr refresh_base_addr;/* wdt refresh base addr */ + uintptr control_base_addr;/* wdt control base addr */ + u32 irq_num; /* wdt ir num */ + u32 irq_prority;/* wdt irq priority */ + const char *instance_name;/* instance name */ +}FWdtConfig;/* wdt config */ +``` + +### 5.2 错误码定义 + +- FWDT_SUCCESS : success +- FWDT_ERR_INVAL_PARM : invalid input parameters +- FWDT_NOT_READY : driver not ready +- FWDT_NOT_SUPPORT : not support operation +- FWDT_TIMEOUT : wait timeout + +### 5.3. 用户API接口 + +- 获取wdt驱动的默认配置参数 + +```c +const FWdtConfig *FWdtLookupConfig(u32 instance_id); +``` + + Note: + + - 用户需要修改配置参数时,可以通过修改返回的FWdtConfig副本,作为后续使用函数的入参, + + Input: + + - u32 instance_id, 当前控制的WDT控制器实例号 + + Return: + + - const FWdtConfig *, 返回驱动默认参数, NULL表示失败 + + +- 设置wdt超时时间 + +```c +u32 FWdtSetTimeout(FWdtCtrl *pCtrl, u32 timeout); +``` + + Note: + + - 此函数会根据传入的超时时间初始化WDT寄存器; + - WDT两次超时后,才执行系统复位操作;例如希望WDT 6s后复位,则应设置timeout=3; + + Input: + + - FWdtCtrl *pCtrl, WDT驱动实例数据 + + - u32 timeout, 设置的WDT超时时间,最大不超过89 + + Return: + + - u32, 参考5.2章错误码定义 + + +- WDT喂狗函数 + +```c +u32 FWdtRefresh(FWdtCtrl *pCtrl); +``` + + Note: + + - 此函数会刷新wdt寄存器,重新开始计时 + + Input: + + - FWdtCtrl *pCtrl, WDT驱动实例数据 + + Return: + + - u32, 参考5.2章错误码定义 + +- WDT使能函数 + +```c +u32 FWdtStart(FWdtCtrl *pCtrl); +``` + + Note: + + - 此函数会使能wdt + + Input: + + - FWdtCtrl *pCtrl, WDT驱动实例数据 + + Return: + + - u32, 参考5.2章错误码定义 + + +- WDT停止函数 + +```c +u32 FWdtStop(FWdtCtrl *pCtrl); +``` + + Note: + + - 此函数会停止wdt + + Input: + + - FWdtCtrl *pCtrl, WDT驱动实例数据 + + Return: + + - u32, 参考5.2章错误码定义 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fxhci.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fxhci.md new file mode 100644 index 0000000000..6be1857604 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fxhci.md @@ -0,0 +1,104 @@ +# FXHCI 驱动程序 + +## 1. 概述 + +XHCI,即可扩展的主机控制器接口,是英特尔公司开发的一个USB主机控制器接口,它主要是面向USB 3.0的,同时它也支持USB 2.0及以下的设备,包括所有种类速度的USB设备(USB 3.0 SuperSpeed, USB 2.0 Low-, Full-, and High-speed, USB 1.1 Low- and Full-speed),是UHCI/OHCI/EHCI等接口标准的升级版本 + +XHCI接口架构主要包括三大部分, + +1. 主机配置空间(Host Configuration Space) + +- 每个xHC实现都应包括一种通过系统软件识别和枚举主机控制器的方法。本规范提供了一个主机配置空间的PCI示例,它被称为PCI配置空间。PCI配置空间定义提供了一个关于系统xHC枚举和资源(中断、电源、虚拟化等)的配置空间使用的工作示例 + +2. 寄存器空间(MMIO Space) + +- 寄存器空间表示xHC向驻留在内存地址空间中的系统软件提供的硬件寄存器。寄存器空间提供了在xHCI正常和扩展功能寄存器中定义的实现特定参数、操作和运行时控制和状态寄存器,以及用于标记对单个USB设备的访问的门钟阵列。该空间,通常被称为I/O空间,被实现为内存映射的I/O(MMIO)空间 + +3. 主机空间(Host Memory) + +- 主机空间由控制数据结构(设备上下文基地址阵列、设备上下文、传输环等)定义。以及由xHC驱动程序分配和管理的数据缓冲区,以启用单个设备的端点流量。此空间将在内存地址空间的内核和用户区域中分配 + +## 2. 功能 + +- 驱动相关的源文件如下, + +``` +drivers/usb/fxhci +├── fxhci.c +├── fxhci.h +├── fxhci_cmd.c +├── fxhci_debug.c +├── fxhci_dev.c +├── fxhci_evt.c +├── fxhci_hw.c +├── fxhci_hw.h +├── fxhci_private.h +└── fxhci_roothub.c +``` + +## 3. 配置方法 + +- 1. 通过 PCIe 总线连接或者板载外设, 连接 XHCI 控制器 +- 2. 如果使用 PCIe 总线连接的 XHCI 控制器,先调用 FPCIE 驱动完成设备枚举和 PCIe 配置 +- 3. 初始化 FUSB 驱动,通过 FUSB 驱动框架,初始化 FXHCI 控制器驱动 +- 4. 通过 FUSB 驱动完成控制器和设备初始化 +- 5. 调用 FUSB 轮询接口更新设备状态 + +## 4 应用示例 + +- USB主机操作和USB设备发现 +### [fxhci_host_pcie](../../../baremetal/example/peripheral/usb/fxhci_host_pcie) + +- USB大容量存储器读写 +### [fusb_fatfs](../../../baremetal/example/storage/fusb_fatfs) + +## 5. API参考 + +### 5.1. 用户数据结构 + +无 + +### 5.2 错误码定义 + +- [1] FXHCI_CC_SUCCESS : success +- [-65] FXHCI_CC_TIMEOUT : wait transfer timeout +- [-66] FXHCI_CC_CONTROLLER_ERROR : usb controller in wrong state +- [-67] FXHCI_CC_COMMUNICATION_ERROR : communication error +- [-68] FXHCI_CC_OUT_OF_MEMORY : memory used up +- [-69] FXHCI_CC_DRIVER_ERROR : driver in wrong state +- [-1] FXHCI_CC_GENERAL_ERROR : general error +- [0] FXHCI_CC_ZERO_BYTES : failed, transfer zero bytes + +>下列错误码来自XHCI标准 +- [5] FXHCI_CC_TRB_ERROR : TRB error (XHCI spec.) +- [6] FXHCI_CC_STALL_ERROR : stall error (XHCI spec.) +- [7] FXHCI_CC_RESOURCE_ERROR : resource error (XHCI spec.) +- [8] FXHCI_CC_BANDWIDTH_ERROR : bandwidth error (XHCI spec.) +- [9] FXHCI_CC_NO_SLOTS_AVAILABLE : No available slot error (XHCI spec.) +- [13] FXHCI_CC_SHORT_PACKET : short packet error (XHCI spec.) +- [21] FXHCI_CC_EVENT_RING_FULL_ERROR : event ring full error (XHCI spec.) +- [24] FXHCI_CC_COMMAND_RING_STOPPED : command ring stopped error (XHCI spec.) +- [25] FXHCI_CC_STOPPED : command abort error (XHCI spec.) +- [26] FXHCI_CC_TRB_ERROR : stopped error (XHCI spec.) +- [27] FXHCI_CC_STOPPED_LENGTH_INVALID : stopped invalid length error (XHCI spec.) + +### 5.3. 用户API接口 + +#### FXhciHcInit + +```c +FUsbHc *FXhciHcInit (FUsb *instance, uintptr base_addr) +``` + +Note: + +- 创建XHCI USB 控制器实例,完成初始化 + +Input: + +- {FUsb} *instance, USB实例 +- {uintptr} base_addr, XHCI控制器基地址 + +Return: + +- {FUsbHc *} 类型为XHCI的USB控制器实例 diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/fxmac.md b/bsp/phytium/libraries/standalone/doc/reference/driver/fxmac.md new file mode 100644 index 0000000000..d3d6fe56fe --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/fxmac.md @@ -0,0 +1,496 @@ + +# FXMAC 驱动程序 + +## 1. 概述 + +以太网控制器(XMAC)的主要功能是在兼容 IEEE802.3 standard 标准的以太网中发送和接收数据,当前支持 SGMII/RGMII 的 PHY 接口 + +XMAC 接口特点包括 +- 支持速率 1000Mbps/100Mbps/10Mbps +- 支持 Reduced Gigabit Media Independent Interface (RGMII) +- 支持 SGMII Serial Gigabit Media-Independent Interface (SGMII) + +## 2. 功能 + +XMAC 驱动提供了以太网控制器的初始化,DMA 环形队列使用函数,外部PHY 接口相关的配置功能 + +XMAC 驱动程序的源文件包括, + +``` +. +├── fxmac_bd.h +├── fxmac_bdring.c +├── fxmac_bdring.h +├── fxmac.c +├── fxmac_g.c +├── fxmac.h +├── fxmac_hw.h +├── fxmac_intr.c +├── fxmac_options.c +├── fxmac_phy.c +├── fxmac_phy.h +├── fxmac_sinit.c +├── Kconfig +└── phy + ├── eth_ieee_reg.h + └── yt + ├── phy_yt.c + └── phy_yt.h +``` + +- 其中fxmac.h/fxmac.c 为开发者提供以下功能: +1. mac 控制器实例初始化 +2. 设置每个控制器实例中4个mac地址的接口 +3. 设置每个控制器实例中4个mac匹配地址的接口 +4. 外置phy 芯片交互接口 +5. 中断相关接口 + +- 其中fxmac_bdring.h/fxmac_bdring.c 为开发者提供了以下功能: +1. 创建dma 环形队列 +2. 环形队列数据拷贝 +3. 环形队列描述符分配 +4. 环形队列描述符释放 + + + +## 4 应用示例 + +### [fgmac_lwip_echo](../../../baremetal/example/fgmac_lwip_echo/README.md) + +- 启动LWIP网络协议栈,通过FXMAC驱动,支持开发板和网络主机的ping通 + +### [lwip port](../../../third-party/lwip-2.1.2/ports/fxmac/) + +- fxmac 耦合lwip 功能 + +## 5. API参考 + +### 5.1. 用户数据结构 + +- FXMAC 驱动配置数据 +```c + typedef struct + { + u32 instance_id; /* Id of device*/ + volatile uintptr_t base_address; + volatile uintptr_t extral_mode_base; + volatile uintptr_t extral_loopback_base; + FXmacPhyInterface interface; /* 接口类型,提供SGMII/RGMII 选择 */ + u32 speed; /* FXMAC_SPEED_XXX */ + u32 duplex; /* 1 is full-duplex , 0 is half-duplex */ + u32 auto_neg; /* Enable auto-negotiation - when set active high, autonegotiation operation is enabled. */ + u32 pclk_hz; + u32 max_queue_num; /* Number of Xmac Controller Queues */ + u32 tx_queue_id; /* 0 ~ FT_XMAC_QUEUE_MAX_NUM ,Index queue number */ + u32 rx_queue_id; /* 0 ~ FT_XMAC_QUEUE_MAX_NUM ,Index queue number */ + u32 hotplug_irq_num; + u32 dma_brust_length; /* burst length */ + u32 network_default_config; /* mac 控制器默认配置 */ + u32 queue_irq_num[FT_XMAC_QUEUE_MAX_NUM]; /* mac0 8个 ,其他的 4个 */ + } FXmacConfig; +``` + +- FGMAC 驱动控制数据 +```c + typedef struct + { + FXmacConfig config; + u32 is_ready; /* Device is ininitialized and ready*/ + u32 is_started; + u32 link_status; /* indicates link status ,FXMAC_LINKUP is link up ,FXMAC_LINKDOWN is link down,FXMAC_NEGOTIATING is need to negotiating*/ + u32 options; + + FXmacQueue tx_bd_queue; /* Transmit Queue */ + FXmacQueue rx_bd_queue; /* Receive Queue */ + + FXmacIrqHandler send_irq_handler; + void *send_args; + + FXmacIrqHandler recv_irq_handler; + void *recv_args; + + FXmacErrorIrqHandler error_irq_handler; + void *error_args; + + FXmacIrqHandler link_change_handler; + void *link_change_args; + + FXmacIrqHandler restart_handler; + void *restart_args; + + u32 moudle_id; /* Module identification number */ + u32 max_mtu_size; + u32 max_frame_size; + + u32 phy_address; /* phy address */ + u32 rxbuf_mask; /* Filter length */ /* 1000,100,10 */ + + } FXmac; +``` + +- FGMAC DMA描述符 + +```c + typedef struct + { + uintptr phys_base_addr; /* Physical address of 1st BD in list */ + uintptr base_bd_addr; /* Virtual address of 1st BD in list */ + uintptr high_bd_addr; /* Virtual address of last BD in the list */ + u32 length; /* Total size of ring in bytes */ + u32 run_state; /* Flag to indicate DMA is started */ + u32 separation; /* Number of bytes between the starting address + of adjacent BDs */ + FXmacBd *free_head; + /* First BD in the free group */ + FXmacBd *pre_head; /* First BD in the pre-work group */ + FXmacBd *hw_head; /* First BD in the work group */ + FXmacBd *hw_tail; /* Last BD in the work group */ + FXmacBd *post_head; + /* First BD in the post-work group */ + FXmacBd *bda_restart; + /* BDA to load when channel is started */ + + volatile u32 hw_cnt; /* Number of BDs in work group */ + u32 pre_cnt; /* Number of BDs in pre-work group */ + u32 free_cnt; /* Number of allocatable BDs in the free group */ + u32 post_cnt; /* Number of BDs in post-work group */ + u32 all_cnt; /* Total Number of BDs for channel */ + } FXmacBdRing; +``` + +- FGMAC DMA描述符表(链式)相关数据 +```c +typedef struct +{ + u32 desc_idx; /* For Current Desc position */ + u32 desc_buf_idx; /* For Current Desc buffer buf position */ + u32 desc_max_num; /* Max Number for Desc and Desc buffer */ + u8 *desc_buf_base; /* Desc buffer Base */ +} FGmacRingDescData; +``` + + +### 5.2 错误码定义 + +- 模块错误码编号:0x1070000 +- [0x0] FGMAC: Success +- FXMAC_ERR_INVALID_PARAM : Invalid parameter +- FXMAC_ERR_SG_LIST : dma ring out of sequence +- FXMAC_ERR_GENERAL :the number of BDs to allocate greater that the number of BDs in the preprocessing state. +- FXMAC_ERR_SG_NO_LIST : dma ring is not allocated +- FXMAC_ERR_PHY_BUSY : if there is another PHY operation in progress +- FXMAC_PHY_IS_NOT_FOUND : phy is not found +- FXMAC_PHY_AUTO_AUTONEGOTIATION_FAILED : PHY autonegotiation is error +- FXMAC_ERR_MAC_IS_PROCESSING : MAC controllers are enabled together. As a result, some operations cannot be mirrored + + +### 5.3 初始化流程 + +1. FXmacLookupConfig 获取默认配置 +2. 修改默认配置 中 phy interface 类型、协商模式 +3. 初始化mac 模块 +4. 初始化phy 模块 +5. 初始化mac 中断 +6. 初始化dma 模块 +7. 根据mac 默认配置启动mac 功能 + + +### 5.4. 用户API接口 + +#### FXmacLookupConfig + +- 获取FXMAC驱动的默认配置参数 + +```c +const FXmacConfig *FXmacLookupConfig(u32 instance_id); +``` + +Note: + +- 返回FXMAC的默认配置,复制后修改配置 +- 需要确认当前平台支持输入的instance_id + +Input: + +- {u32} instance_id, 驱动控制器号 + +Return: + +- {const FXmacConfig *}, 驱动默认配置 +#### FXmacCfgInitialize + +- 完成FGMAC驱动实例的初始化,使之可以使用 + +```c +FError FXmacCfgInitialize(FXmac *instance_p, const FXmacConfig *config_p) +``` + +Note: + +- 此函数会重置FGMAC控制器和FGMAC控制数据 + +Input: + +- {FXmac} *instance_p MAC 控制器实例指针 + +- {FXmacConfig} *cofig_p 控制器驱动配置数据 + +Return: + +- {FError} 驱动初始化的错误码信息,FGMAC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + +#### FXmacInitInterface + +- 根据phy 接口类型 ,初始化mac 控制器配置 + +```c +void FXmacInitInterface(FXmac *instance_p) +``` + +Note: +- 此函数一般用于 PHY 芯片协商完成之后被调用,与PHY配置进行适配 + +Input: +- {FXmac} *instance_p MAC 控制器实例指针 + +#### FXmacGetMacAddress + +- 根据index 获取mac 地址 + +```c +void FXmacGetMacAddress(FXmac *instance_p, u8 *address_ptr, u8 index) +``` + +Input : + +- {FGmac} *instance_p MAC 控制器实例指针 +- {u8} index MAC(0-3)地址的索引 + +Output : +- {u8} *address_ptr 是指向缓冲区的指针当前MAC地址将被复制。 + + +#### FXmacSetMacAddress + +- 根据index 写入mac 地址 + +```c +FError FXmacSetMacAddress(FXmac *instance_p, u8 *address_ptr, u8 index); +``` + +Input : + +- {FGmac} *instance_p MAC 控制器实例指针 +- {u8} *address_ptr 是指向缓冲区的指针当前MAC地址将被复制。 +- {u8} index MAC(0-3)地址的索引 + +Output : + +- {FError} FT_SUCCESS 如果MAC地址设置成功 + +#### FXmacSetOptions + +- 设置FXmac 中的相关配置信息 + +```c +FError FXmacSetOptions(FXmac *instance_p, u32 options, u32 queue_num) +``` + +Note: +- 必须在mac 控制器关闭的情况被调用 + +Input: +- {FGmac} *instance_p MAC 控制器实例指针 +- {u32} options 是要设置的选项。 选项参数位于 fxmac.h 中的 FXMAC_****_OPTION +- {u32} queue_num mac控制器中队列的选项,仅在 FXMAC_JUMBO_ENABLE_OPTION 配置时被使用 + +Return: +- {FError} FT_SUCCESS 设置成功 + +#### FXmacClearOptions + +- 清除FXmac 中的相关配置信息 + +```c +FError FXmacClearOptions(FXmac *instance_p, u32 options, u32 queue_num) +``` + +Note: +- 必须在mac 控制器关闭的情况被调用 + +Input: +- {FGmac} *instance_p MAC 控制器实例指针 +- {u32} options 是要设置的选项。 选项参数位于 fxmac.h 中的 FXMAC_****_OPTION +- {u32} queue_num mac控制器中队列的选项,仅在 FXMAC_JUMBO_ENABLE_OPTION 配置时被使用 + +Return: +- {FError} FT_SUCCESS 清除成功 + +#### FXmacStart + +- 启动以太网控制器 + +```c +void FXmacStart(FXmac *instance_p) +``` + +note: + +- 根据 network_default_config 中的 FXMAC_TRANSMIT_ENABLE_OPTION 与 +FXMAC_RECEIVER_ENABLE_OPTION ,决定是否开启控制器的接收与发送功能。并且默认开启接收与发送相关中断 + +Input: + +- {FGmac} *instance_p MAC 控制器实例指针 + + +#### FXmacStop + +- 关闭以太网控制器 + +```c +void FXmacStop(FXmac *instance_p) +``` + +note: +- 关闭所有中断,关闭接收与发送功能 + +Input: + +- {FGmac} *instance_p MAC 控制器实例指针 + + +#### FXmacSetQueuePtr + +- 设置mac 控制器中接收/发送缓冲区 的描述符环形队列的首地址 + +```c +void FXmacSetQueuePtr(FXmac *instance_p, uintptr queue_p, u8 queue_num, + u32 direction) +``` + +Note: +- 描述符环形队列的首地址按照128bit 对其 + +Input: + +- {FXmac} *instance_p MAC 控制器实例指针 +- {uintptr} queue_p 写入队列的地址 +- {u8} queue_num 缓冲队列索引 +- {u32} direction 当为 FXMAC_SEND 表示方向为发送,当为 FXMAC_RECV 表示方向为接收 + + +#### FXmacPhyWrite + +- 将数据写入指定的PHY寄存器。 + +```c +FError FXmacPhyWrite(FXmac *instance_p, u32 phy_address, + u32 register_num, u16 phy_data) +``` + +Note: +- 这个函数不是线程安全的。 用户必须提供互斥的如果有多个线程可以调用该函数,则访问该函数。 + +Input: +- {FXmac} *instance_p MAC 控制器实例指针 +- {u32} phy_address 要写入的PHY的地址 +- {u32} register_num 要写入的PHY的地址,特定PHY寄存器的寄存器号0-31 +- {u16} phy_data 需要写入对应PHY 芯片中 对应register_num 的参数 + +Return: + +- {FError} FT_SUCCESS PHY 写入成功 + + +#### FXmacPhyRead + +- 指定PHY 芯片中对应的寄存器号,读出其中对应的参数 + +```c +FError FXmacPhyRead(FXmac *instance_p, u32 phy_address, + u32 register_num, u16 *phydat_aptr) +``` + +Note: + +- 这个函数不是线程安全的。 用户必须提供互斥的如果有多个线程可以调用该函数,则访问该函数。 + +Input: +- {FXmac} *instance_p MAC 控制器实例指针 +- {u32} phy_address 要写入的PHY的地址 +- {u32} register_num 要写入的PHY的地址,特定PHY寄存器的寄存器号0-31 + +Output: +- {u16} *phydat_aptr 需要读出对应PHY 芯片中 对应register_num中值的指针 + +Return: + +- {FError} FT_SUCCESS PHY 读入成功 + + +#### FXmacPhyInit + +- 初始化PHY 芯片 ,首先检查出当前已连接的PHY 芯片地址,然后根据协商方式,确定 + +```c +FError FXmacPhyInit(FXmac *instance_p, u32 speed,u32 duplex_mode, u32 autonegotiation_en); +``` + +Input: +- {FXmac} *instance_p MAC 控制器实例指针 +- {u32} speed 需要设置的速度 +- {u32} duplex_mode 双工模式配置,1为全双工,0 为半双工 +- {u32} autonegotiation_en 为1 时,PHY 会进行自协商操作。为0时 ,将根据配置项进行协商 + +Return: +- FError FT_SUCCESS 初始化成功 + + +#### FXmacSelectClk + +- 根据MAC 与 PHY 芯片连接的情况,设置相关时钟参数 + +```c +void FXmacSelectClk(FXmac *instance_p ) +``` + +Input: +- {FXmac} *instance_p MAC 控制器实例指针 + + +#### FXmacSetHandler + +- 设置中断回调函数 + +```c +FError FXmacSetHandler(FXmac *instance_p, u32 handler_type, void *func_pointer, void *call_back_ref) +``` + +Input: +- {FXmac} *instance_p MAC 控制器实例指针 +- {u32} handler_type 指示中断处理程序类型 ,具体参数参考 FXMAC_HANDLER_*** +- {void } *func_pointer 回调函数接口 +- {void } *call_back_ref 回调函数的传入参数 + diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/sfud.md b/bsp/phytium/libraries/standalone/doc/reference/driver/sfud.md new file mode 100644 index 0000000000..1d4d042466 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/sfud.md @@ -0,0 +1,42 @@ +# SFUD 驱动框架 + +## 1. 概述 + + +- [SFUD Gitee](https://gitee.com/Armink/SFUD) +- SFUD 是一款开源的串行 SPI Flash 通用驱动库 + +## 2. 功能 + +- third-party/sfud-1.1.0 +- 目前SFUD框架实现对接FSPIM驱动的对接,用于读写SPI Flash +``` +├── Kconfig +├── inc +│   ├── sfud.h +│   ├── sfud_cfg.h +│   ├── sfud_def.h +│   └── sfud_flash_def.h +├── library.json +├── ports +│   └── f_spim +│   └── sfud_port.c +└── src + ├── sfud.c + └── sfud_sfdp.c +``` + +## 3. 配置方法 + +- 使能 CONFIG_USE_SFUD 配置 +- 选择底层的SPI驱动,如CONFIG_USE_FSPIM +- 调用 SFUD 提供的 API 读写 SPI 从设备 + +## 4 应用示例 + +### [fspim_nor_flash](../../../baremetal/example/fspim_nor_flash/README.md) + +## 4. API参考 + +- sfud.h 和 sfud_port.c 是主要需要对接的源文件 +- 参考[SFUD API指南](https://gitee.com/Armink/SFUD/) \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/template.md b/bsp/phytium/libraries/standalone/doc/reference/driver/template.md new file mode 100644 index 0000000000..37a6cf3ec8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/template.md @@ -0,0 +1,22 @@ +# XX 驱动程序 + +## 1. 概述 + +`XX的基本概念, XX驱动支持的硬件平台` + +## 2. 功能 + +`XX驱动程序支持的功能,关联的源文件` + +## 3. 配置方法 + +`XX驱动使用的一般过程和方法` +`XX驱动的配置方法和参数设置` + +## 4 应用示例 + +`XX驱动的example使用` + +## 5. API参考 + +`XX驱动用户API说明` \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/driver/timer_tacho.md b/bsp/phytium/libraries/standalone/doc/reference/driver/timer_tacho.md new file mode 100644 index 0000000000..5941cf2064 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/driver/timer_tacho.md @@ -0,0 +1,454 @@ +# TIMER_TACHO 驱动程序 + +## 1. 概述 + + +- TIMER_TACHO包含了2种功能,定时器和输入捕获。其中定时计数作为通用定时器供软件使用,输入捕获功能主要用来测试输入方波的高电平持续时间,该方波是由风扇设备设备发出,通过PAD直接连接到控制器模块输入端。 +- 对于定时功能,有若干可配置参数,例如产生中断次数,是否对当前计数值进行清空,是否使能计数器,计数器位宽选择(32/64),或者是restart/free模式,以及当进行了初值配置是否需要强制更新,以及可以通过配置寄存器对控制器模块进行复位操作。 +- 对于输入捕获,控制器模块设置了上下阈值,也就是当捕获到的高电平时间低于或者高于阈值都会发出中断(此时分别对应风扇不同的故障)。同时对输入信号进行消抖处理,也可以对消抖级数进行配置。 +- 本驱动程序提供了E2000(D、Q、S)平台的定时器和输入捕获功能 +- E2000(D、Q、S)上包含了38个定时器控制器,(D、Q)上包含了4个tacho输入捕获接口,(S)上包含了16个输入捕获接口 + +## 2. 功能 + +- 驱动相关的源文件如下: +- drivers/timer/ftimer_tacho + +``` +. +├── ftacho.c --> 转速计功能实现 +├── ftimer_tacho_g.c --> 相关配置和全局变量 +├── ftimer_tacho_hw.h --> 寄存器操作 +├── ftimer_tacho_intr.c --> 中断相关处理 +├── ftimer_tacho.h --> 用户接口 +└── ftimer.c --> 定时器功能实现 +``` + +## 3. 配置方法 + +以下部分将指导您完成ftimer_tacho驱动的软件配置: + +- 初始化timer_tacho控制器,使用timer功能还是tacho功能 +- 分别配置两个功能的参数,配置使用timer功能的id,定时时间,计数方式等;配置使用tacho功能的id,阈值,输入消抖级数等。 +- 注册中断处理函数,使能中断 + +## 4. 应用示例 + +### [timer定时器](../../../baremetal/example/peripheral/timer/timer_tacho/README.md) + +#### timer +- FTimerFunctionInit 获取cmd传递进来的最基本参数 +- FTimerCfgInit 对传递的参数以及默认参数进行配置,并启动中断 +- FTimerStartTest 定时器开始工作,如果是单次计时,则可以传递新的参数并计时,循环模式则仅仅进行启动 +- 在中断中进行回调 + +#### tacho +- FTachoFunctionInit 获取cmd传递进来的参数,使用计时器的id以及工作模式 +- FTachoCfgInit 配置工作参数 +- TachoEnableIntr 启用事件中断 +- FTimerStart tacho开始工作 +- FTachoGetRPM 可以获取RPM参数了 + +#### timer与tacho的切换 +- 注意需要对定时器控制器进行disable,可以调用各自的F****DeInit函数,也可以FTimerSwithMode进行操作 + +## 5. API参考 + +### 5.1 用户数据结构 + +- ftimer_tacho控制数据 + +```c +typedef struct +{ + FTimerTachoConfig config; /* Current active configs */ + boolean isready; /* Device is initialized and ready */ + FTimerEventHandler evt_handlers[FMAX_TIMER_TACHO_EVENT];/* event handler for interrupt */ +}FTimerTachoCtrl; +``` + +- ftimer_tacho配置数据 + +```c +typedef struct +{ + u32 id; /* id of timer tacho */ + char name[12]; /* instance name */ + u32 irq_priority; /* intr priority */ + u32 work_mode; /* timer/tacho/capture mode */ + /* for timer function */ + u32 timer_mode; /* free-run/restart */ + u32 timer_bits; /* 32/64 bits */ + u32 cmp_type; /* once/cycle cmp */ + boolean clear_cnt; /* clear timer counts */ + boolean force_load; /* start count from start val */ + /* for tacho function */ + u32 edge_mode; /* rising/falling/double */ + u32 jitter_level; /* jitter level */ + u32 plus_num; /* plus_num of period to calculate rpm */ + u32 captue_cnt; /* in capture mode, when cnt reach this val, intr asserted */ +}FTimerTachoConfig; +``` + +- ftimer_tacho工作模式 +```c +typedef enum +{ + /*TimerTacho mode */ + FTIMER_WORK_MODE_TIMER = 0, + FTIMER_WORK_MODE_TACHO, + FTIMER_WORK_MODE_CAPTURE +}FTimerTachoModeType; +``` + +- timer计数模式 +```c +typedef enum +{ + /*Timer count mode*/ + FTIMER_FREE_RUN = 0, + FTIMER_RESTART +}FTimerCntModeType; +``` + +- ftimer_tacho中断事件类型 +```c +typedef enum +{ + FTACHO_EVENT_OVER = 0, /*tacho超速事件*/ + FTACHO_EVENT_UNDER, /*tacho低速事件*/ + FTIMER_EVENT_ROLL_OVER, /*计数器翻转事件*/ + FTIMER_EVENT_ONCE_CMP, /*单次定时输出事件*/ + FTIMER_EVENT_CYC_CMP, /*重复定时输出事件*/ + FTACHO_EVENT_CAPTURE, /*tacho输入捕获事件*/ + + FMAX_TIMER_TACHO_EVENT +}FTimerTachoEventType; +``` + +- tacho输入模式选择 +```c +typedef enum +{ + FTACHO_FALLING_EDGE = 0, + FTACHO_RISING_EDGE, + FTACHO_DOUBLE_EDGE +}FTachoEdgeType; +``` + +- tacho消抖级数选择 +```c +typedef enum +{ + FTACHO_JITTER_LEVEL0 = 0, + FTACHO_JITTER_LEVEL1, + FTACHO_JITTER_LEVEL2, + FTACHO_JITTER_LEVEL3, +}FTachoJitterLevelType; +``` + +### 5.2 错误码定义 + +- FTIMER_TACHO_ERR_IS_READ 已经初始化 +- FTIMER_TACHO_ERR_NOT_READY 未初始化 +- FTIMER_TACHO_ERR_INVAL_PARM 参数错误 +- FTIMER_TACHO_ERR_INIT_FAILED 初始化错误 +- FTIMER_TACHO_ERR_ABORT 运行中止 +- FTIMER_TACHO_ERR_FAILED 运行错误 +- FTIMER_TACHO_ERR_NOT_SUPPORT 不支持此配置 + +### 5.3 用户API接口 + +#### Time & Tacho API + +##### FTimerSoftwareReset + +- 将控制器复位 + +```c +FError FTimerSoftwareReset(FTimerTachoCtrl *instance_p); +``` + +Note: + +- 复位控制器 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- {FError} 驱动的错误码信息 + +##### FTimerSetInterruptMask + +- 设置中断 + +```c +void FTimerSetInterruptMask(FTimerTachoCtrl *instance_p, + FTimerTachoEventType intrType, + boolean enable); +``` + +Note: + +- 设置中断,根据不同的intrType,将对于的中断mask置位 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 +- {FTimerTachoEventType} intrType,timer_tacho中断类型 +- {boolean} enable,开启还是关闭中断 + +Return: + +- void 无 + +##### FTimerStart + +- 启动timer_tacho + +```c +FError FTimerStart(FTimerTachoCtrl *instance_p); +``` + +Note: + +- 启动已经初始化完成的timer_tacho外设,根据不同的功能,开启使能位 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- {FError} 驱动的错误码信息 + +##### FTimerStop + +- 停止timer外设 + +```c +FError FTimerStop(FTimerTachoCtrl *instance_p); +``` + +Note: + +- 停止timer外设,根据不同的功能,关闭使能位,计数值停止并冻结 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- {FError} 驱动的错误码信息 + +##### FTimerSwithMode + +- timer 与 tacho-capture两种模式的切换 + +```c +FError FTimerSwithMode(FTimerTachoCtrl *instance_p, FTimerTachoConfig *new_config_p); +``` + +Note: + +- 用于timer 与 tacho-capture两种模式的切换,切换需要失能和清除计数器 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 +- {FTimerTachoConfig} *new_config_p,timer_tacho配置数据 + +Return: + +- {FError} 驱动的错误码信息 + +##### FTimerRegisterEvtCallback + +- 注册中断事件处理回调函数 + +```c +void FTimerRegisterEvtCallback(FTimerTachoCtrl *instance_p, + FTimerTachoEventType evt, + FTimerEventHandler callback); +``` + +Note: + +- 注册中断事件处理回调函数,根据不同的中断事件类型,当发生中断后,会跳转到注册的函数中 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 +- {FTimerTachoEventType} evt,中断事件类型 +- {FTimerEventHandler} callback,用户自己定义的中断回调函数 + +Return: + +- void 无 + +##### FTimeSettingDump + +- 打印寄存器信息 + +```c +FError FTimeSettingDump(const FTimerTachoCtrl *instance_p); +``` + +Note: + +- 打印已经初始化成功的timer_tacho控制器寄存器信息 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- {FError} 驱动的错误码信息 + +##### FTimerTachoIntrHandler + +- TimerTacho中断处理函数 + +```c +void FTimerTachoIntrHandler(s32 vector, void *param); +``` + +Note: + +- TimerTacho中断处理函数,如果注册回调函数,则跳转到回调函数 + +Input: + +- {s32} vector,中断向量号 +- {void} *param, 中断输入参数, 指向FTimerTachoCtrl的驱动控制实例 + +Return: + +- void 无 + +##### FTimerTachoSetIntr + +- 根据工作模式和状态设置相应的中断 + +```c +void FTimerTachoSetIntr(FTimerTachoCtrl *instance_p); +``` + +Note: + +- 根据工作模式和状态设置相应的中断,此函数根据设置的模式自动配置中断,特殊需求可更改 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- void 无 + +##### FTimerInit + +- TimerTacho驱动实例的初始化 + +```c +FError FTimerInit(FTimerTachoCtrl *instance_p, const FTimerTachoConfig *config_p); +``` + +Note: + +- 完成TimerTacho驱动实例的初始化,使之在就绪状态,配合FTimerStart使用 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 +- {FTimerTachoConfig} *config_p,timer_tacho配置数据 + +Return: + +- {FError} 驱动的错误码信息 + +##### FTimerDeInit + +- Timer驱动实例去使能,清零实例数据 + +```c +void FTimerDeInit(FTimerTachoCtrl *instance_p); +``` + +Note: + +- 对已经完成初始化的实例,进行Timer驱动实例去使能,清零实例数据 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- void 无 + +##### FTachoInit + +- 完成Tacho驱动实例的初始化 + +```c +FError FTachoInit(FTimerTachoCtrl *instance_p, const FTimerTachoConfig *config_p); +``` + +Note: + +- 完成Tacho驱动实例的初始化,使之在就绪状态 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- void 无 + +##### FTachoGetFanRPM + +- 获取风扇的转速值 + +```c +FError FTachoGetFanRPM(FTimerTachoCtrl *instance_p,u32 *rpm); +``` + +Note: + +- 根据预设采样周期的值,来获取风扇的转速值 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 +- {u32} *rpm,传入保存转数数据的指针 + +Return: + +- {FError} 驱动的错误码信息 + +##### FTachoDeInit + +- Tacho驱动实例去使能,清零实例数据 + +```c +void FTachoDeInit(FTimerTachoCtrl *instance_p); +``` + +Note: + +- 完成Tacho驱动实例去使能,清零实例数据 + +Input: + +- {FTimerTachoCtrl} *instance_p,timer_tacho驱动控制数据 + +Return: + +- void 无 diff --git a/bsp/phytium/libraries/standalone/doc/reference/hw/template.md b/bsp/phytium/libraries/standalone/doc/reference/hw/template.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/bsp/phytium/libraries/standalone/doc/reference/sdk/fmemory_pool.md b/bsp/phytium/libraries/standalone/doc/reference/sdk/fmemory_pool.md new file mode 100644 index 0000000000..3af23ce41b --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/sdk/fmemory_pool.md @@ -0,0 +1,279 @@ + +# Memory pool + +## 1. 概述 + +内存池 (Memory Pool)是一种内存分配方式,是为了减少频繁使用 malloc/free new/delete 等系统调用而造成的性能损耗而设计的,具有效率高、内存碎片少和防止内存泄漏等特性。内存池根据实际需要,在初始状态获取一大块内存(堆区或者静态内存),然后划分成若干内存页,进行管理,将内存页中的块传递给申请者使用。SDK中采用TLSF内存分配器管理,专门设计用于满足实时要求。 + +TLSF (Two-Level Segregated Fit memory allocator), 是一款通用的动态内存分配器,具有以下特点, + +- malloc,free,realloc,memalign的算法复杂度变为O(1) +- 每次分配的开销极低(4字节) +- 低碎片化 +- 支持动态添加和删除内存池区域 + +TLSF主要采用两级位图(Two-Level Bitmap)与分级空闲块链表(Segregated Free List)的数据结构管理动态内存池(memory pool)以及其中的空闲块(free blocks),用Good-Fit的策略进行分配。 + +TLSF算法分配速度不一定快,只是说能保证分配的时间是个常数(malloc不能保证)。 + +TLSF也叫多内存堆管理算法,支持动态增加或者删除多块不连续的内存,将它们作为一个内存堆使用。 + +## 2. 功能 + +FMemory Pool主要完成内存池的初始化,为用户提供多种内存申请方法,支持内存池的使用情况监测, +- 初始化内存池 +- 删除内存池 +- 申请一段空间(不要求对齐) +- 按指定字节数申请一段对齐的内存 +- 申请一段数组,返回被清零的空间 +- 回收原来申请的空间并重新分配 +- 跟踪当前内存池的使用情况 + +相关源文件为: +``` +fmempory_pool + ├── fmempory_pool.c + └── fmempory_pool.h +``` + +``` +tlsf + ├── tlsf.c + └── tlsf.h +``` + +## 3. 配置方法 + +以下部分将指导您完成 FMemory Pool 的软件配置: +- 使能TLSF组件 + +## 4. 应用示例 + +### [memory pool](../../../baremetal/example/system/memory_pool_test) + +## 5. API参考 + +### 5.1. 用户数据结构 + +- common/fmempory_pool.h + +```c +typedef struct +{ + pool_t pool_addr; + FSListNode list; +} FMempPoolList; /* 内存池控制数据 */ + +typedef struct +{ + FMempPoolList *pools_list; /* 内存池链表 */ + tlsf_t tlsf_ptr; /* tlsf内存池 */ + u32 is_ready; /* 内存池初始化完成标志 */ +} FMemp; /* 内存池控制数据 */ +``` + +### 5.2 错误码定义 + +- 模块错误码编号 `0x0010000` + +- [0x0] FMEMP_SUCCESS : success + +- [0x0010000] FMEMP_ERR_INVALID_BUF : 输入的内存池缓存区不合法 + +- [0x0010001] FMEMP_ERR_INIT_TLFS : 初始化TLFS内存池失败 + +- [0x0010002] FMEMP_ERR_BAD_MALLOC : 从TLFS内存池分配空间失败 + +### 5.3. 用户API接口 + +#### FMempInit +- 初始化内存池, 分配内存池的内存空间 + +```c +FError FMempInit(FMemp *memp, void *begin_addr, void *end_addr); +``` + +Note: + +- begin_addr end_addr 指向为内存池指定的缓冲区的起止地址 + +Input: + +- {FMemp} *memp, 内存池的控制数据 +- {void} *begin_addr, 分配给内存池的空间起始地址 +- {void} *end_addr, 分配给内存池的空间结束地址 + +Return: + +- {FError} FMEMP_SUCCESS表示初始化成功,返回其它值表示初始化失败 + +#### FMempRemove + +- 释放所有分配的内存,删除内存池 + +```c +void FMempRemove(FMemp *memp); +``` + +Note: + +- 需要初始化后才能调用,调用此函数后,内存池分配的空间不再能使用 + +Input: + +- {FMemp} *memp 内存池控制数据 + +Return: + +- 无 + +#### FMempMalloc + +- 从内存池申请一段空间 + +```c +void *FMempMalloc(FMemp *memp, fsize_t nbytes); +``` + +Note: + +- 需要初始化后才能调用,申请的空间再不再使用后需要调用FMempFree释放 + +Input: + +- {FMemp} *memp 内存池控制数据 +- {fsize_t} nbytes 申请的字节数 + +Return: + +- {void *} 申请到的空间,如果申请失败,返回NULL + +#### FMempCalloc + +- 从内存池申请一段数组空间并清零 + +```c +void *FMempCalloc(FMemp *memp, fsize_t count, fsize_t size) +``` + +Note: + +- 需要初始化后才能调用,申请的空间再不再使用后需要调用FMempFree释放 + +Input: + +- {FMemp} *memp 内存池控制数据 +- {fsize_t} count 数据成员格式 +- {fsize_t} size 单个数据成员的字节数 + +Return: + +- {void *} 申请到的空间,如果申请失败,返回NULL + +#### FMempMallocAlign + +- 按指定对齐方式申请一段空间 + +```c +void *FMempMallocAlign(FMemp *memp, fsize_t size, fsize_t align); +``` + +Note: + +- 需要初始化后才能调用,申请的空间再不再使用后需要调用FMempFree释放 + +Input: + +- {FMemp} *memp 内存池控制数据 +- {fsize_t} size 申请的字节数 +- {fsize_t} align 对齐字节数 + +Return: + +- {void *} 申请到的空间,如果申请失败,返回NULL + +#### FMempRealloc + +- 回收原来申请的空间并重新分配 + +```c +void *FMempRealloc(FMemp *memp, void *ptr, fsize_t nbytes); +``` + +Note: + +- 需要初始化后才能调用,申请的空间再不再使用后需要调用FMempFree释放,调用函数后,原来的空间不再能使用,原空间的数据被移动到返回指针指向的空间 + +Input: + +- {FMemp} *memp 内存池控制数据 +- {void} *ptr 原来的空间 +- {fsize_t} nbytes 新申请的字节数 + +Return: + +- {void *} 替换后空间,如果替换失败,返回NULL + +#### FMempFree + +- 释放一段从内存池申请的空间 + +```c +void FMempFree(FMemp *memp, void *ptr); +``` + +Note: + +- 需要初始化后才能调用,传入的指针需要是FMempMalloc/FMempCalloc/FMempMallocAlign/FMempRealloc返回的 + +Input: + +- {FMemp} *memp 内存池控制数据 +- {void} *ptr 待释放的空间地址 + +Return: + +- 无 + +#### FMemProbe + +- 跟踪当前内存池的使用情况 + +```c +void FMemProbe(FMemp *memp, u32 *total, u32 *used, u32 *max_used); +``` + +Note: + +- 需要初始化后才能调用 + +Input: + +- {FMemp} *memp 内存池控制数据 +- {u32} *total 总可用字节数 +- {u32} *used 已使用字节数 +- {u32} *max_used 已使用字节数的峰值 + +Return: + +- 无 + +#### FMemListAll + +- 打印当前分配的内存块信息 + +```c +void FMemListAll(FMemp *memp); +``` + +Note: + +- 需要初始化后才能调用 + +Input: + +- {FMemp} *memp 内存池控制数据 + +Return: + +- 无 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/sdk/fpinctrl.md b/bsp/phytium/libraries/standalone/doc/reference/sdk/fpinctrl.md new file mode 100644 index 0000000000..958156f695 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/sdk/fpinctrl.md @@ -0,0 +1,266 @@ +# 芯片引脚控制 + +## 1. 概述 + +- 芯片引脚控制 (Pin Ctrl)用于引脚功能配置和引脚延迟配置,开发板上常存在某些 IO 之间存在共用同一物理引脚情况,即引脚复用,同时,通用 IO 引脚还可以配置引脚延迟 +- FPinCtrl 支持芯片引脚控制功能,支持 FT2000/4、D2000 和 E2000 + +## 2. 功能 + +- FPinCtrl 主要提供引脚控制相关的功能配置,包括 +- 1. 控制复用功能 +- 2. 控制引脚驱动能力,只支持E2000平台 +- 3. 配置引脚的上下拉电阻 +- 4. 调节引脚的输入输出延迟 + +- 相关的源文件包括 +``` +fpinctrl.h + fiopad.h --> E2000 + fiopad.c + + fioctrl.h --> FT2000/4, D2000 + fioctrl.c +``` + +## 3. 配置方法 + +- 不需要特别配置 + +## 4. 应用示例 + +- 设置引脚的复用,驱动能力和上下拉电阻等 + +### [fpin_test](../../../baremetal/example/peripheral/pin/fioctrl_test) + +- IO 引脚延时配置索引,参考 D2000/FT2000-4 数据手册的"表 5-32 通用 IO 引脚延时配置寄存 + +> 调用 FIOCTRL_INDEX 生成PAD对应的索引,e.g. + +| 偏移 | 位域 | 说明 | +| -------- | ------- | ------- | +|0x0208 | [27 : 26] | 控制 i2c_0_scl_pad 的上下拉 2'b10 | +| | [25 : 24] | 控制 i2c_0_scl_pad 的复用功能 2'b00 | + +```c + #define FIOCTRL_I2C0_SCL_PAD (FPinIndex)FIOCTRL_INDEX(0x208, 24) /* i2c0-scl: func 0 */ +``` +> 定义控制域为 i2c0_scl_pad 的PAD,其中延时配置寄存器偏移量为0x208, 输入延时配置位从第24位开始 + +## 5. API参考 + +Note: + +- FT2000/4 和 D2000 平台,使用FIOCTRL_INDEX 宏定义的 index 作为引脚索引 +- E2000 平台,使用 FIOPAD_INDEX 宏定义的 index 作为引脚索引 + +#### FPinGetFunc + +```c +FPinFunc FPinGetFunc(const FPinIndex pin); +``` + +Note: + +- 获取IO引脚当前的复用功能 + +Input: + +- {FPinIndex} pin IO引脚索引 + +Return: + +- {FPinFunc} 当前的复用功能 + +#### FPinSetFunc + +```c +void FPinSetFunc(const FPinIndex pin, FPinFunc func); +``` + +Note: + +- 设置IO引脚复用功能 + +Input: + +- {FPinIndex} pin IO引脚索引 +- {FPinFunc} func IO复用功能 + +Return: + +- 无 + +#### FPinGetPull + +```c +FPinPull FPinGetPull(const FPinIndex pin); +``` + +Note: + +- 获取IO引脚当前的上下拉设置 + +Input: + +- {FPinIndex} pin IO引脚索引 + +Return: + +- {FPinPull} 当前的上下拉设置 + +#### FPinSetPull + +```c +void FPinSetPull(const FPinIndex pin, FPinPull pull); +``` + +Note: + +- 设置IO引脚当前的上下拉 + +Input: + +- {FPinIndex} pin IO引脚索引 +- {FPinPull} pull 上下拉设置 + +Return: + +- 无 + +#### FPinGetDelay + +```c +FPinDelay FPinGetDelay(const FPinIndex pin, FPinDelayDir dir, FPinDelayType type); +``` + +Note: + +- 获取IO引脚当前的延时设置 + +Input: + +- {FPinIndex} pin IO引脚延时设置索引 +- {FPinDelayDir} dir 输入/输出延时 +- {FPinDelayType} type 精调/粗调延时 + +Return: + +- {FPinDelay} 当前的延时设置 + +#### FPinGetDelayEn + +```c +boolean FPinGetDelayEn(const FPinIndex pin, FPinDelayDir dir); +``` + +Note: + +- 获取IO引脚当前的延时使能标志位 + +Input: + +- {FPinIndex} pin IO引脚延时设置索引 +- {FPinDelayDir} dir 输入/输出延时 + +Return: + +- {boolean} TRUE: 使能延时, FALSE: 去使能延时 + +#### FPinSetDelay + +```c +void FPinSetDelay(const FPinIndex pin, FPinDelayDir dir, FPinDelayType type, FPinDelay delay); +``` + +Note: + +- 设置IO引脚延时 + +Input: + +- {FPinIndex} pin IO引脚延时设置索引 +- {FPinDelayDir} dir 输入/输出延时 +- {FPinDelayType} type 精调/粗调延时 +- {FPinDelay} delay 延时设置 + +Return: + +- 无 + +#### FPinSetDelayEn + +```c +void FPinSetDelayEn(const FPinIndex pin, FPinDelayDir dir, boolean enable); +``` + +Note: + +- 使能/去使能IO引脚延时 + +Input: + +- {FPinIndex} pin IO引脚延时设置索引 +- {FPinDelayDir} dir 输入/输出延时 +- {boolean} enable TRUE: 使能, FALSE: 去使能 + +Return: + +- 无 + +#### FPinGetDrive + +```c +FPinDrive FPinGetDrive(const FPinIndex pin); +``` + +Note: + +- 获取IO引脚的驱动能力 +- 只支持 E2000 平台 + +Input: + +- {FPinIndex} pin IO引脚索引 + +Return: + +- {FPinDrive} 引脚的当前的驱动能力 + +#### FPinSetDrive + +```c +void FPinSetDrive(const FPinIndex pin, FPinDrive drive); +``` + +Note: + +- 设置IO引脚的驱动能力 +- 只支持 E2000 平台 + +Input: + +- {FPinIndex} pin, IO引脚索引 +- {FPinDrive} drive, 引脚驱动能力设置 + +Return: + +- 无 + +#### + +```c + +``` + +Note: + +- + +Input: + +- + +Return: + +- \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/sdk_reference.md b/bsp/phytium/libraries/standalone/doc/reference/sdk_reference.md new file mode 100644 index 0000000000..d8096d7960 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/sdk_reference.md @@ -0,0 +1,42 @@ +# SDK参考手册 + +`SDK参考手册模板` + +- 版本:v0.1 + +## 1. SDK用户指南 + +`提供使用API过程中可能遇到的问题,按照用户使用的一般顺序排列` + +### 1.1 配套目标平台 + +### 1.2 使用构建系统 + +### 1.3 使用驱动组件 + +### 1.4 生成链接器脚本 + +### 1.5 完成引导加载 + +### 1.6 处理API错误码 + +## 2. 组件使用指南 + +`提供分模块的具体API说明,按照模块分类说明,模块内按照字母顺序排列,方便检索` + +### I2C + +(./driver_reference/i2c.md) + + + +## 3. 硬件使用指南 + +`提供硬件平台的参考资料,按字母顺序排列` + +### D2000 + +### E2000 + +### FT2000/4 + diff --git a/bsp/phytium/libraries/standalone/doc/reference/usr/install_linux_aarch64.md b/bsp/phytium/libraries/standalone/doc/reference/usr/install_linux_aarch64.md new file mode 100644 index 0000000000..e5deacef74 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/usr/install_linux_aarch64.md @@ -0,0 +1,77 @@ +# 1. Linux arm aarch64 SDK安装方法 + +Linux arm aarch64下通过通过下载SDK开发工具包完成安装,运行脚本`./setup_dev.py`完成安装,安装前请先确认当前设备属于`Linux arm aarch64` + +![linux-aarch64](../../fig/is_aarch64.png) + +Linux arm aarch64安装包集成了: +- `gcc-arm-10.3-2021.07-aarch64-aarch64-none-elf.tar.xz`和`gcc-arm-10.3-2021.07-aarch64-arm-none-eabi.tar.xz`,aarch64交叉编译链,SDK安装过程中会被解压到DEV目录的`cross_tool`目录下 +- `setup_dev.py`, 安装脚本,主要的功能包括创建sdk的profile文件,创建`PHYTIUM_DEV_PATH`环境变量,通过git拉取SDK源码,以及完成SDK安装 + + +## 1.1 获取SDK的开发环境 + +- [Linux arm aarch64](https://pan.baidu.com/s/1lQC4n8wRDSLAMTXvzPn98g) + +> 提取码:LA64 + +- Linux环境下可以用unzip命令解压 +- Linux环境下需要通过`sudo apt-get install build-essential`安装git, make和python3等工具 + +## 1.2 安装SDK开发环境 + +- (1). 解压开发环境压缩包,形成DEV目录 + +- (2). 进入DEV目录,运行`./setup_dev.py`,安装开发环境 + +![安装开发环境](../../fig/setup_aarch64_dev.png) + +- (3). 通过git拉取Phytium Standalone SDK的代码,如 + +``` +git clone https://gitee.com/phytium_embedded/phytium-standalone-sdk.git ./phytium-standalone-sdk +``` + +- (4). 进入Phytium Standalone SDK代码目录,运行`./install.py` + +``` +cd ./phytium-standalone-sdk +./install.py +``` + +![输入图片说明](../../fig/install_for_aarch64.png) + +- (5). 安装完成后重启系统 + +### Q: 如果当前环境无法连接互联网 + +- 在执行第(2)步前,需要手动下载Phytium Standalone SDK,放置在DEV目录下 +- https://gitee.com/phytium_embedded/phytium-standalone-sdk + +## 1.3 检查安装是否成功 + +- 打印下列环境变量,观察各变量是否存在,指向的目录是否正确 +> `PHYTIUM_DEV_PATH`指向DEV目录 + +> `STANDALONE_SDK_ROOT`指向SDK源文件目录 + +> `AARCH32_CROSS_PATH`指向32位交叉编译链目录 + +> `AARCH64_CROSS_PATH`指向64位交叉编译链目录 + +``` +echo $PHYTIUM_DEV_PATH +echo $STANDALONE_SDK_ROOT +echo $AARCH32_CROSS_PATH +echo $AARCH64_CROSS_PATH +``` +![检查环境变量](../../fig/check_env_for_aarch64.png) + +- 环境变量打印正确无误,表示**安装成功** +## 1.4 卸载开发环境 + +- 在DEV目录运行`./uninstall.py`完成SDK卸载 + +- 运行`rm /etc/profile.d/phytium_standalone_sdk.sh`,删除SDK配置文件 + +- 重启系统完成卸载 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/usr/install_linux_x86_64.md b/bsp/phytium/libraries/standalone/doc/reference/usr/install_linux_x86_64.md new file mode 100644 index 0000000000..d90077e33a --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/usr/install_linux_x86_64.md @@ -0,0 +1,75 @@ + +# 1. Linux x86_64 SDK安装方法 + +Linux x86_64下通过通过下载SDK开发工具包完成安装,运行脚本`./setup_dev.py`完成安装,安装前请先确认当前设备属于`Linux x86_64` + +![linux-x86_64](../../fig/is_x86_64.png) + +Linux x86_64安装包集成了, +- `gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz`和`gcc-arm-10.3-2021.07-x86_64-arm-none-eabi.tar.xz`,aarch64交叉编译链,SDK安装过程中会被解压到DEV目录的`cross_tool`目录下 +- `setup_dev.py`, 安装脚本,主要的功能包括创建sdk的profile文件,创建`PHYTIUM_DEV_PATH`环境变量,通过git拉取SDK源码,以及完成SDK安装 + +## 1.1 获取SDK的开发环境 + +- [Linux x86_64](https://pan.baidu.com/s/1KsGcHoqOJ8nv4G1G-L5gtQ ) + +>提取码:LX64 + +- Linux环境下可以用unzip命令解压 +- Linux环境下需要通过`sudo apt-get install build-essential`安装git, make和python3等工具 + +## 1.2 安装SDK开发环境 + +- (1). 解压开发环境压缩包,形成DEV目录 + +![解压DEV](../../fig/uncompress_for_x86.png) + +- (2). 进入DEV目录,运行`./setup_dev.py`,安装开发环境 + +![安装开发环境](../../fig/setup_x86_dev.png) + +-(3). 通过git拉取Phytium Standalone SDK的代码,如 + +``` +git clone https://gitee.com/phytium_embedded/phytium-standalone-sdk.git ./phytium-standalone-sdk +``` + +- (4). 进入Phytium Standalone SDK代码目录,运行`./install.py` + +``` +cd ./phytium-standalone-sdk +./install.py +``` +![安装完成](../../fig/install_for_x86.png) + +- (3). 安装完成后重启系统 + +### Q: 如果当前环境无法连接互联网 + +- 在执行第(2)步前,需要手动下载Phytium Standalone SDK,放置在DEV目录下 +- https://gitee.com/phytium_embedded/phytium-standalone-sdk + +## 1.3 检查安装是否成功 + +- 打印下列环境变量,观察各变量是否存在,指向的目录是否正确 +> `PHYTIUM_DEV_PATH`指向DEV目录 + +> `STANDALONE_SDK_ROOT`指向SDK源文件目录 + +> `AARCH32_CROSS_PATH`指向32位交叉编译链目录 + +> `AARCH64_CROSS_PATH`指向64位交叉编译链目录 + +``` +echo $PHYTIUM_DEV_PATH $STANDALONE_SDK_ROOT $AARCH32_CROSS_PATH $AARCH64_CROSS_PATH +``` +![检查环境变量](../../fig/check_env_for_x86.png) + +- 环境变量打印正确无误,表示**安装成功** +## 1.4 卸载开发环境 + +- 在DEV目录运行`./uninstall.py`完成SDK卸载 + +- 运行`rm /etc/profile.d/phytium_standalone_sdk.sh`,删除SDK配置文件 + +- 重启系统完成卸载 diff --git a/bsp/phytium/libraries/standalone/doc/reference/usr/install_windos_wsl.md b/bsp/phytium/libraries/standalone/doc/reference/usr/install_windos_wsl.md new file mode 100644 index 0000000000..98ee0ab9df --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/usr/install_windos_wsl.md @@ -0,0 +1,113 @@ + +# 1. Windows下WSL Linux子系统 SDK安装方法 + + +在Windows下,可以通过WSL Linux子系统来获得Linux环境,并且,这种环境下的Linux系统与Windows系统的文件是完全共享的 +Linux x86_64下通过通过下载SDK开发工具包完成安装,安装前请先确认当前设备属于`Linux x86_64` +``` +uname -a +``` +![linux-x86_64](../../fig/is_x86_64.png) + +接下来正式开始安装SDK开发环境 + +## 1.1 系统安装与获取SDK的开发环境 + +- [Linux x86_64](https://pan.baidu.com/s/1KsGcHoqOJ8nv4G1G-L5gtQ ) + +>提取码:LX64 + +Windows用户可以参考此链接,安装WSL Linux子系统,并做好相应准备工作: +- [WSL Linux子系统安装教程](https://zhuanlan.zhihu.com/p/146545159) + +安装完毕后,启动Ubuntu,如果出现运行问题,可参考 +- [WSL 无法安装解决方法](https://blog.csdn.net/qq_18625805/article/details/109732122) + +在cmd上输入如下指令,查看WSL版本 +``` +wsl -l -v +``` +由于WSL2不支持本地网线连接,如果发现目前版本是WSL2,需要退回到WSL1 +``` +wsl --set-version Ubuntu-20.04 1 +``` + +>这里的20.04是Ubuntu的版本号,根据实际情况调整 + +正确结果如下 +![wsl_l_v](../../fig/wsl_l_v.png) +通过下面的指令完成对Linux系统的更新 +``` +apt update +apt upgrade +``` +Linux环境下需要通过代码安装git, make和python3等工具 +``` +sudo apt-get install build-essential +``` + +## 1.2 安装SDK开发环境 + +- (1). 解压开发环境压缩包,形成DEV目录 + +![解压DEV](../../fig/uncompress_for_x86.png) + +Linux x86_64安装包集成了: +- `gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz`和`gcc-arm-10.3-2021.07-x86_64-arm-none-eabi.tar.xz`,aarch64交叉编译链,在SDK安装过程中会被解压到DEV目录的`cross_tool`目录下 +- `setup_dev.py`, 一种安装脚本,主要的功能包括创建sdk的profile文件,创建`PHYTIUM_DEV_PATH`环境变量,通过git拉取SDK源码,以及完成SDK安装 + + +- (2). 进入DEV目录,运行`./setup_dev.py`,安装开发环境 + +![安装开发环境](../../fig/setup_x86_dev.png) +*如果无法正常运行请使用如下代码或者重启系统* +``` +python3 setup_dev.py +``` +>指令执行完毕后,请关注回执信息中[5],按要求输入`source /etc/profile.d/phytium_dev.sh`指令获取环境变量或者重启系统 + +- (3). 通过git拉取Phytium Standalone SDK的代码,如 + +``` +git clone https://gitee.com/phytium_embedded/phytium-standalone-sdk.git ./phytium-standalone-sdk +``` + +- (4). 进入Phytium Standalone SDK代码目录,运行`./install.py` + +``` +cd ./phytium-standalone-sdk +./install.py +``` +![安装完成](../../fig/install_for_x86.png) + +- (5). 安装完成后重启系统 + +### Q: 如果当前环境无法连接互联网 + +- 在执行第(2)步前,需要手动下载Phytium Standalone SDK,放置在DEV目录下 +- https://gitee.com/phytium_embedded/phytium-standalone-sdk + +## 1.3 检查安装是否成功 + +- 打印下列环境变量,观察各变量是否存在,指向的目录是否正确 +> `PHYTIUM_DEV_PATH`指向DEV目录 + +> `STANDALONE_SDK_ROOT`指向SDK源文件目录 + +> `AARCH32_CROSS_PATH`指向32位交叉编译链目录 + +> `AARCH64_CROSS_PATH`指向64位交叉编译链目录 + +``` +echo $PHYTIUM_DEV_PATH $STANDALONE_SDK_ROOT $AARCH32_CROSS_PATH $AARCH64_CROSS_PATH +``` +![检查环境变量](../../fig/check_env_for_x86.png) + +- 环境变量打印正确无误,表示**安装成功** +## 1.4 如何卸载开发环境 + +- 在DEV目录运行`./uninstall.py`完成SDK卸载 + +- 运行`rm /etc/profile.d/phytium_standalone_sdk.sh`,删除SDK配置文件 + +- 重启系统完成卸载 diff --git a/bsp/phytium/libraries/standalone/doc/reference/usr/install_windows.md b/bsp/phytium/libraries/standalone/doc/reference/usr/install_windows.md new file mode 100644 index 0000000000..e73ae689ed --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/usr/install_windows.md @@ -0,0 +1,142 @@ +# 1. Windows10 SDK安装方法 + +Windows 10 SDK开发环境集成了, +- `msys64`,Msys2 portable环境, 主要提供Windows上的shell命令行开发环境,包括了Cygwin (POSIX 兼容性层) 和 MinGW-w64(从"MinGW-生成") +- `setup_dev.py`, 安装脚本,主要的功能包括创建sdk的profile文件,创建`PHYTIUM_DEV_PATH`环境变量,通过git拉取SDK源码,以及完成SDK安装 +- `gcc-arm-10.3-2021.07-mingw-w64-i686-aarch64-none-elf.tar.xz`和`gcc-arm-10.3-2021.07-mingw-w64-i686-arm-none-eabi.tar.xz`, mingw64交叉编译链, SDK安装过程中会被解压到DEV目录的`cross_tool`目录下 +- `tftp`, tftp工具, 提供tftp服务,用于开发板下载二进制镜像文件,主要的功能包括安装tftp32服务和配置tftp目录 +- `run_msys2.cmd`,用于打开和配置msys2 shell的脚本,需要设置`PHYTIUM_DEV_PATH`后才能使用 +- `run_tftd.cmd`,用于打开tftpd工具的脚本,需要设置`PHYTIUM_DEV_PATH`后才能使用 +- `tftp/reinstall.cmd`, 用于安装和配置tftpd服务的脚本 +- `tftp/uninstall.cmd`, 用于卸载tftpd服务的脚本 + +## 1.1 获取SDK的开发环境 + +- [Windows10](https://pan.baidu.com/s/1V96isNcPq4F7nKi3_8GoGg) +>提取码:WX64 + +- Windows环境下可以用通用的unzip工具解压,如7zip和winrar + +## 1.2 安装SDK开发环境 + +- (1). 添加Windows环境变量,`PHYTIUM_DEV_PATH`(环境变量名**不能自定义**),例如,指向文件夹`E:\phytium-dev-windows-nt`(可以自定义) + +![配置环境变量](../../fig/add_path_for_win.png) + +- (2). 进入DEV目录,双击脚本`run_msys2.cmd`, 进入msys2控制台, 运行`./setup_dev.py`,注册开发环境 + +![安装开发环境](../../fig/install_for_mingw.png) + +-(3). DEV目录注册完成后,通过git拉取Phytium Standalone SDK的代码,如 + +``` +git clone https://gitee.com/phytium_embedded/phytium-standalone-sdk.git ./phytium-standalone-sdk +``` + +- (4). 进入Phytium Standalone SDK代码目录,运行`./install.py` + +``` +cd ./phytium-standalone-sdk +./install.py +``` + +![开发环境安装完成](../../fig/setup_win.png) + +- (5). 安装完成后重启系统 + +### Q: 如果当前环境无法连接互联网 + +- 在执行第(2)步前,需要手动下载Phytium Standalone SDK,放置在DEV目录下 +- https://gitee.com/phytium_embedded/phytium-standalone-sdk + +![手动下载SDK](../../fig/git_url.png) + +## 1.3 检查安装是否成功 + +- 打印下列环境变量,观察各变量是否存在,指向的目录是否正确 +> `PHYTIUM_DEV_PATH`指向DEV目录 + +> `STANDALONE_SDK_ROOT`指向SDK源文件目录 + +> `AARCH32_CROSS_PATH`指向32位交叉编译链目录 + +> `AARCH64_CROSS_PATH`指向64位交叉编译链目录 + +``` +echo $PHYTIUM_DEV_PATH $STANDALONE_SDK_ROOT $AARCH32_CROSS_PATH $AARCH64_CROSS_PATH +``` + +- 环境变量打印正确无误,表示**安装成功** +## 1.4 Windows 10安装Msys2(可选) + +- (1). 获取[Windows环境安装包](https://pan.baidu.com/s/17WX5hec7t8_ubAKzFCwQAA) + +> 提取码:MGW6 + +- msys2, `msys2-x86_64-20210725.exe` +- mingw64-arm交叉编译链, `gcc-arm-10.3-2021.07-mingw-w64-i686-arm-none-eabi.tar.xz`, `gcc-arm-10.3-2021.07-mingw-w64-i686-aarch64-none-elf.tar.xz` +- tftp工具,`tftp.zip` + +- (2). 创建Windows集成开发环境(DEV目录),如`D:/phytium-dev`, 将DEV目录添加在Windows环境变量中,变量名为`PHYTIUM_DEV_PATH`,如下图所示,保存环境变量, + +> 对于Windows 10,在桌面左下角系统搜索框中输入“环境变量”即可进入环境变量编辑界面 + +> DEV目录中不要留空格 + +![输入图片说明](../../fig/add_path_for_win.png) + +- (3). 保存DEV环境变量后,打开一个控制台,输入`echo %PHYTIUM_DEV_PATH%`,检查环境变量是否设置成功, + +![输入图片说明](../../fig/check_env_for_win.png) + +- (4). 双击`msys2-x86_64-20210725.exe`,设置`Msys2`的安装路径在DEV路径下,其余设置按默认安装,注意安装完成后不要马上启动,最后一步取消勾选“马上启动Msys2” + +![输入图片说明](../../fig/install_msys2.png) + +![Msys2安装过程](../../fig/installing_msys2.png) + +- (5). `Msys2`安装完成后,需要添加国内软件源,否则下载速度会很慢,进入`D:\phytium-dev\msys64\etc\pacman.d`目录下,找到以下三个文件,在文件末尾分别添加对应的软件源 + +- mirrorlist.mingw32 +``` +Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/i686 +``` + +- mirrorlist.mingw64 +``` +Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/x86_64 +``` + +- mirrorlist.msys +``` +Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/msys/$arch +``` + +- (6). 进入`D:\phytium-dev\msys64`目录,双击`msys2_shell.cmd`启动运行`Msys2`,输入以下命令,更新`Msys2`软件,安装必要组件 + +> 如果执行失败,可以多次尝试,直到没有报错 + +> 安装过程全部选用默认方式`default`或选择`y`,注意如果没有`default = all`,需要输入`y` + +``` +$ pacman -Syu +$ pacman -S mingw-w64-x86_64-toolchain +$ pacman -S base-devel git python3 python3-pip +``` + +![更新Msys2软件源](../../fig/update_packman.png) + +- (7). 运行以下命令,检查组件是否安装完全 +``` +$ pacman -Q make git wget python3 python3-pip +``` + +## 1.5 卸载开发环境 + +- 在DEV目录下双击`run_msys2.cmd`, 启动`Msys2`控制台,在控制台输入`./uninstall.py`完成SDK卸载 + +- 在`Msys2`控制台运行`rm /etc/profile.d/phytium_standalone_sdk.sh`,删除SDK配置文件 + +- 在DEV目录`D:\phytium-dev\tftp`下以**管理员权限**打开Windows命令行中断,运行`uninstall.cmd`完成Tftd卸载 + +- 重启系统完成卸载 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/doc/reference/usr/usage.md b/bsp/phytium/libraries/standalone/doc/reference/usr/usage.md new file mode 100644 index 0000000000..2e03a76df1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/doc/reference/usr/usage.md @@ -0,0 +1,224 @@ +# 使用方法 +## 1.1前期配置 +在正式调用SDK实例前,需要对tftp进行一系列配置,Windows下与Linux下的方法有很大的区别,下面我们正式开始 +>对于权限不够的问题,普通用户可以在指令前加上`sudo`来暂时获得root权限 + +### 1.1.1 在 host 侧(Ubuntu 20.04)配置 tftp 服务 + +- 在开发环境`host`侧安装`tftp`服务 + +``` +sudo apt-get install tftp-hpa tftpd-hpa +sudo apt-get install xinetd +``` + +- 新建 `tftboot`目录, `/mnt/d/tftboot`, 此目录应与项目编译脚本makefile中的USR_BOOT_DIR一致, 并确保 tftboot 目录有执行权限`chmod 777 /**/tftboot` + +- 配置主机 tftpboot 服务, 新建并配置文件`/etc/xinetd.d/tftp` + +``` +# /etc/xinetd.d/tftp + +server tftp +{ + socket_type = dgram + protocol = udp + wait = yes + user = root + server = /usr/sbin/in.tftpd + server_args = -s /mnt/d/tftboot + disable = no + per_source = 11 + cps = 100 2 + flags = IPv4 +} +``` +--- +在配置上述文件时,如果之前没有使用过Linux文件编写,可以使用自带的vim编辑器 +``` +vim /etc/xinetd.d/tftp +``` +--- +- 启动主机`tftp`服务,生成默认配置 + +``` +$ sudo service tftpd-hpa start +``` + +- 修改主机`tftp`配置,指向`tftboot`目录 + 修改/etc/default/tftpd-hpa +``` +vim /etc/default/tftpd-hpa +``` + +``` +$ sudo vim /etc/default/tftpd-hpa +# /etc/default/tftpd-hpa + +TFTP_USERNAME="tftp" +TFTP_DIRECTORY="/mnt/d/tftboot" +TFTP_ADDRESS=":69" +TFTP_OPTIONS="-l -c -s" +``` + +- 重启主机`tftp`服务 + +``` +$ sudo service tftpd-hpa restart +``` +>注意,每次进入Linux系统时都需要使用该代码重启主机`tftp`服务 +- 测试主机`tftp`服务的可用性 +登录`tftp`服务,获取`tftboot`目录下的一个文件 + +``` +$ tftp 192.168.4.50 +tftp> get test1234 +tftp> q +``` + +### 1.1.2 在 host 侧(Windows)配置 tftp 服务 + +- 将`tftp.zip`解压到开发环境,如`D:\**\phytium-dev-windows-nt\tftp` + >如果`phytium-dev-windows-nt\tftp`已经存在,则直接进行下一步 +- 以**管理员权限**打开Windows cmd,进入`D:\**\phytium-dev-windows-nt\tftp`,运行`.\reinstall.cmd`完成Tftpd服务安装 +![输入图片说明](../../fig/admin_rights.png) +![输入图片说明](../../fig/tftp32_srv.png) + >注意每次使用前,都需要进入Windows服务,手动将tftp服务打开 + +### 1.1.3 配置以太网ipv4设置 +- 为了连接串口,打开windows下的以太网设置界面,选择手动设置,配置相关地址 +![输入图片说明](../../fig/ipv4_setting.png) + +## 1.2 连接开发板,着手跑通用例 +- 在完成前面的步骤后,就可以着手连接开发板。连接之前,需要下载Windows下与的开发板配套软件 +[MobaXterm_Portable_v22.0](https://pan.baidu.com/s/1IjDG2j5YwK9IhpBR4ChoYA ) + >提取码:ROOT + +- 如果是不用内置Linux子系统的windows用户还需要在`tftp`中配置。配置完成后,进入SDK,双击`D:\phytium-dev\phytium-standalone-sdk`目录下的`run_tftd.cmd`,启动tftp工具,设置tftp目录和ip +![输入图片说明](../../fig/config_tftp32.png) + +### 1.2.1 编译获取.elf与.bin文件 +以WSL为例: +- 进入SDK所在目录,右键打开Windows终端,输入以下指令 + ``` + wsl + ``` + ![输入图片说明](../../fig/wsl_teiminal.png) +- 进入`baremetal`文件夹,选取一个希望执行的用例。以`uart测试`为例,在wsl下输入如下指令,进入测试用例所在文件夹 + ``` + cd baremetal/example/peripheral/serial/fpl011_test + ``` +- 根据需求,配置在不同芯片下32位或64位的编译模式,这里以`飞腾新四核芯片`的32位为例,输入以下指令 + ``` + make load_ft2004_aarch32 + ``` +- 编译测试用例,输入以下指令 + ``` + make clean boot + ``` +- 出现如下信息,表示编译成功,编译结果.elf与.bin文件已经保存至tftboot文件夹内 +![输入图片说明](../../fig/wsl_make_success.png) +![输入图片说明](../../fig/bin_show.png) + +### 1.2.2 配置开发板ip,连通host下载启动镜像 +- 连通开发板串口,打开windows的设备管理器,在端口栏确认串口是否成果接入 +![输入图片说明](../../fig/Serial_inform.png) + +- 打开MobaXterm_Portable软件,选择`Session`,然后选择`Serial`,选择串口(如上图所示串口号为`COM3`),设置波特率`bps`为115200 + +- 进入`u-boot`界面,输入如下指令,配置开发板ip,`host`侧ip和网关地址 + ``` + setenv ipaddr 192.168.4.20 + setenv serverip 192.168.4.50 + setenv gatewayip 192.168.4.1 + ``` +- 随后烧录`tftboot`文件夹下的文件到开发板,输入以下指令 + ``` + tftpboot 0x90100000 baremetal.elf + bootelf -p 0x90100000 + ``` + + > 镜像启动的地址为`0x80100000`, 对于`BIN`文件,需要直接加载到`0x80100000`,对于`ELF`文件,启动地址会自动获取,需要加载到`DRAM`中一段可用的地址,这里选择`0x90100000` + +- 见到如下结果,表示成功进入测试环境,可以自行浏览每个测试用例文件夹下对应的`README.md`文件,根据其中的提示,进行用例调试 +![输入图片说明](../../fig/letter_shell.png) + + + + + +## 1.3 新建一个baremetal应用工程 +如果您希望自己建立一个应用工程,可以参考下面的流程 +### 1.3.1 选择工程模板 + +- 复制`~/standalone-sdk/example/template`目录,作为 baremetal 应用工程 + + > `*` 表示可选文件/目录 + ``` + $ ls + Kconfig --> 应用工程配置menu文件 + makefile --> makefile + main.c --> 包含main函数 + sdkconfig --> 配置输出 + sdkconfig.h --> 配置输出 + inc --> 用户头文件* + src --> 用户源文件* + ``` + >请注意使用小写makefile,使用Makefile在部分平台不能被识别 + +### 1.3.2 选择目标平台 + +- 切换目标平台, e.g `FT2000/4 AARCH32`, 加载默认配置 + + ``` + make config_ft2004_aarch32 + ``` + + > 使用`FT2000-4`作为目标编译平台,通过`make config_ft2004_aarch32`和`make config_ft2004_aarch64`加载默认配置 + + > 使用`D2000`作为目标编译平台,通过`make config_d2000_aarch32`和`make config_d2000_aarch64`加载默认配置 + +- 编译应用工程, 生成`*.bin`文件用于下载到开发板 + ``` + $ make + $ ls + template.bin --> 二进制文件 + template.dis --> 反汇编文件 + template.elf --> ELF文件 + template.map --> 内存布局文件 + ``` + ![输入图片说明](../../fig/compiling.png) + +### 1.3.3 快速使用例程 + +- 将`BIN`文件或者`ELF`文件复制到`tftpboot`目录 + ``` + $ cp ./baremetal.bin /mnt/d/tftboot + $ cp ./baremetal.elf /mnt/d/tftboot + ``` + > ~/standalone-sdk/example/aarch32_hello_world + ![输入图片说明](../../fig/load_image.png) +- 结合1.2节中的操作,即可快速使用自己创建的例程 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/Kconfig b/bsp/phytium/libraries/standalone/drivers/Kconfig new file mode 100644 index 0000000000..69f79376af --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/Kconfig @@ -0,0 +1,237 @@ +menu "Components Configuration" +config USE_SPI + bool + prompt "Use Spi" + default n + help + Include SPI modules and enable SPI + + if USE_SPI + source "$STANDALONE_DIR/drivers/spi/Kconfig" + endif + +config USE_QSPI + bool + prompt "Use QSpi" + default n + help + Include QSPI modules and enable QSPI + + if USE_QSPI + source "$STANDALONE_DIR/drivers/qspi/Kconfig" + endif + +config USE_GIC + bool + prompt "Use Gic" + default y + help + Include Generic Interrupt Controllor + + if USE_GIC + source "$STANDALONE_DIR/drivers/gic/Kconfig" + endif + +config USE_SERIAL + bool + prompt "Use SERIAL" + default n + help + Include serial modules and enable serial + + if USE_SERIAL + source "$STANDALONE_DIR/drivers/serial/Kconfig" + endif + + +config USE_GPIO + bool + prompt "Use Gpio" + default n + help + Include GPIO modules and enable GPIO + + if USE_GPIO + source "$STANDALONE_DIR/drivers/pin/fgpio/Kconfig" + endif + +config USE_ETH + bool + prompt "Use Eth" + default n + help + Include eth + + if USE_ETH + source "$STANDALONE_DIR/drivers/eth/Kconfig" + endif + +config USE_CAN + bool + prompt "Use Can" + default n + help + Include can + + if USE_CAN + source "$STANDALONE_DIR/drivers/can/Kconfig" + endif + +config USE_I2C + bool + prompt "Use I2C" + default n + help + Include I2C modules and enable I2C + + if USE_I2C + source "$STANDALONE_DIR/drivers/i2c/Kconfig" + endif + + +config USE_TIMER + bool + prompt "Use Timer" + default n + help + Include Timer modules and enable Timer + + if USE_TIMER + source "$STANDALONE_DIR/drivers/timer/Kconfig" + endif + +config USE_MIO + bool + prompt "Use Mio" + default n + help + Include Mio modules and enable Mio + + if USE_MIO + source "$STANDALONE_DIR/drivers/mio/Kconfig" + endif + +config USE_SDMMC + bool + prompt "Use SD/MMC" + default n + help + Include SD/MMC modules and enable Timer + + if USE_SDMMC + source "$STANDALONE_DIR/drivers/mmc/Kconfig" + endif + +config USE_PCIE + bool + prompt "Use PCIE" + default n + help + Include PCIE + + if USE_PCIE + source "$STANDALONE_DIR/drivers/pcie/Kconfig" + endif + +config USE_WDT + bool + prompt "Use WDT" + default n + help + Include watchdog timer modules and enable watchdog timer + + if USE_WDT + source "$STANDALONE_DIR/drivers/watchdog/Kconfig" + endif + + +config USE_DMA + bool + prompt "Use DMA" + default n + help + Include DMA + + if USE_DMA + source "$STANDALONE_DIR/drivers/dma/Kconfig" + endif + +config USE_NAND + bool + prompt "Use NAND" + help + Include NAND + + if USE_NAND + source "$STANDALONE_DIR/drivers/nand/Kconfig" + endif + +config USE_RTC + bool + prompt "Use RTC" + default n + help + Include system rtc service + + if USE_RTC + source "$STANDALONE_DIR/drivers/rtc/Kconfig" + endif + +config USE_SATA + bool + prompt "Use SATA" + default n + help + Include system sata service + + if USE_SATA + source "$STANDALONE_DIR/drivers/sata/Kconfig" + endif + +config USE_USB + bool + prompt "Use USB" + default n + help + Include USB Subsystem + + if USE_USB + source "$STANDALONE_DIR/drivers/usb/Kconfig" + endif + +config USE_ADC + bool + prompt "Use ADC" + default n + help + Include adc modules and enable adc + + if USE_ADC + source "$STANDALONE_DIR/drivers/adc/Kconfig" + endif + +config USE_PWM + bool + prompt "Use PWM" + default n + help + Include system pwm + + if USE_PWM + source "$STANDALONE_DIR/drivers/pwm/Kconfig" + endif + +config USE_IPC + bool + prompt "Use IPC" + default n + help + Include IPC Service + + if USE_IPC + source "$STANDALONE_DIR/drivers/ipc/Kconfig" + endif + + +endmenu + diff --git a/bsp/phytium/libraries/standalone/drivers/adc/Kconfig b/bsp/phytium/libraries/standalone/drivers/adc/Kconfig new file mode 100644 index 0000000000..58f7dd8a6f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/Kconfig @@ -0,0 +1,10 @@ + +menu "ADC Configuration" + config USE_FADC + bool + prompt "Use FADC" + default n + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc.c b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc.c new file mode 100644 index 0000000000..83247b60e6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc.c @@ -0,0 +1,535 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fadc.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:28:45 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include +#include "fgeneric_timer.h" +#include "fkernel.h" +#include "ftypes.h" +#include "ferror_code.h" +#include "fdebug.h" +#include "fadc.h" +#include "fadc_hw.h" +#include "fparameters.h" +#include "fassert.h" +#include "fsleep.h" + +#define FADC_DEBUG_TAG "FT_ADC" +#define FADC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FADC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FADC_INFO(format, ...) FT_DEBUG_PRINT_I(FADC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FADC_WARN(format, ...) FT_DEBUG_PRINT_W(FADC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FADC_ERROR(format, ...) FT_DEBUG_PRINT_E(FADC_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FADC_MAX_CLOCK_PRESC 16 + +#define FADC_MAX_THRESHOLD 0x400 + + +/** + * @name: FAdcPowerDownControl + * @msg: Set power down signal + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {u8} power_state, this parameter must be enable or disable. + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +static FError FAdcPowerDownControl(FAdcCtrl *pctrl, u8 power_state) +{ + + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.base_addr; + reg_val = FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET); + if (power_state == FADC_CTRL_PD_ENABLE) + { + reg_val |= FADC_CTRL_REG_PD_EN; + } + else + { + reg_val &= ~(FADC_CTRL_REG_PD_EN); + } + + FADC_WRITE_REG32(base_addr, FADC_CTRL_REG_OFFSET, reg_val); + + return FADC_SUCCESS; +} + +/** + * @name: FAdcChannelEnable + * @msg: enable channel, corresponding to fix channel mode or multi channel mode. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcChannel} channel, adc channel number. + * @param {boolean} state, TRUE-enable, FALSE-disable + * @return void + */ +void FAdcChannelEnable(FAdcCtrl *pctrl, FAdcChannel channel, boolean state) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + FASSERT(channel < FADC_CHANNEL_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.base_addr; + reg_val = FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET); + + if (state == TRUE) + { + if (reg_val & FADC_CTRL_REG_FIX_CHANNEL) + { + reg_val &= ~(FADC_CTRL_REG_FIX_CHANNEL_NUM_MASK); + reg_val |= FADC_CTRL_REG_FIX_CHANNEL_NUM(channel); + } + else + { + reg_val |= FADC_CTRL_REG_CHANNEL_EN(channel); + } + } + else + { + /* fix channel mode, disable means stop convert */ + if (reg_val & FADC_CTRL_REG_FIX_CHANNEL) + { + reg_val &= ~(FADC_CTRL_REG_SOC_EN); + + } + else + { + reg_val &= ~(FADC_CTRL_REG_CHANNEL_EN(channel)); + } + } + + + FADC_WRITE_REG32(base_addr, FADC_CTRL_REG_OFFSET, reg_val); + +} + +/** + * @name: FAdcChannelThresholdSet + * @msg: Set adc channel high_threshold and low_threshold. + * you need use this function after FAdcConvertSet. If you want to use this function to + * add other channel enable when the adc conversion is started, you need to restart the + * adc convert start signal(adc_soc_en) after use to make the operation valid. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcChannel} channel, adc channel number. + * @param {FAdcThresholdConfig} *threshold_config, pointer to adc channel threshold value struct. + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +FError FAdcChannelThresholdSet(FAdcCtrl *pctrl, FAdcChannel channel, FAdcThresholdConfig *threshold_config) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + FASSERT(channel < FADC_CHANNEL_NUM); + + u16 low_threshold = threshold_config->low_threshold; + u16 high_threshold = threshold_config->high_threshold; + + FASSERT(high_threshold < FADC_MAX_THRESHOLD); + FASSERT(low_threshold < high_threshold); + + uintptr base_addr = pctrl->config.base_addr; + + u32 threshold = (FADC_LEVEL_REG_HIGH_LEVEL(high_threshold)) | + (FADC_LEVEL_REG_LOW_LEVEL(low_threshold)); + FADC_WRITE_REG32(base_addr, (FADC_LEVEL_REG_OFFSET(channel)), threshold); + + return FADC_SUCCESS; +} + +/** + * @name: FAdcConvertSet + * @msg: config adc convert parameters. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcConvertConfig} *convert_config, include convert mode,channel mode, + * clock divider and convert_interval. + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +FError FAdcConvertSet(FAdcCtrl *pctrl, FAdcConvertConfig *convert_config) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + + u32 reg_val = 0; + uintptr base_addr = pctrl->config.base_addr; + reg_val = FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET); + + /* clk_div config */ + u32 clk_div = convert_config->clk_div; + FASSERT(clk_div < FADC_MAX_CLOCK_PRESC); + if (clk_div % 2 == 1) + { + FADC_ERROR("clk_div is not even."); + return FADC_ERR_INVAL_PARM; + } + reg_val &= (~FADC_CTRL_REG_CLK_DIV_MASK); + reg_val |= FADC_CTRL_REG_CLK_DIV(clk_div); + + /* config convert mode */ + FAdcConvertMode convert_mode = convert_config->convert_mode; + FASSERT(convert_mode < FADC_CONVERT_MODE_NUM); + if (convert_mode == FADC_SINGLE_CONVERT) + { + reg_val |= FADC_CTRL_REG_SINGLE_CONVERT; + } + else + { + reg_val &= ~(FADC_CTRL_REG_SINGLE_CONVERT); + } + + /* config channel mode */ + FAdcChannelMode channel_mode = convert_config->channel_mode; + FASSERT(channel_mode < FADC_CHANNEL_MODE_NUM); + + if (channel_mode == FADC_FIXED_CHANNEL) + { + reg_val |= FADC_CTRL_REG_FIX_CHANNEL; + } + else + { + reg_val &= ~(FADC_CTRL_REG_FIX_CHANNEL); + } + FADC_WRITE_REG32(base_addr, FADC_CTRL_REG_OFFSET, reg_val); + + /* config time interval between two converts */ + FADC_WRITE_REG32(base_addr, FADC_INTER_REG_OFFSET, convert_config->convert_interval); + + return FADC_SUCCESS; +} + + +/** + * @name: FAdcInterruptEnable + * @msg: enable channel interrupt. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcChannel} channel, adc channel number. + * @param {FAdcIntrEvtType} event_type, interrupt event type + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +FError FAdcInterruptEnable(FAdcCtrl *pctrl, FAdcChannel channel, FAdcIntrEventType event_type) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + + uintptr base_addr = pctrl->config.base_addr; + u32 reg_val = 0; + reg_val = FADC_READ_REG32(base_addr, FADC_INTRMASK_REG_OFFSET); + switch (event_type) + { + case FADC_INTR_EVENT_COVFIN: /* enable channel convert complete irq */ + reg_val &= ~(FADC_INTRMASK_REG_COVFIN_MASK(channel)); + break; + + case FADC_INTR_EVENT_DLIMIT: + reg_val &= ~(FADC_INTRMASK_REG_DLIMIT_MASK(channel)); + break; + + case FADC_INTR_EVENT_ULIMIT: + reg_val &= ~(FADC_INTRMASK_REG_ULIMIT_MASK(channel)); + break; + + case FADC_INTR_EVENT_ERROR: + reg_val &= ~(FADC_INTRMASK_REG_ERR_MASK); + break; + + default: + break; + } + + FADC_WRITE_REG32(base_addr, FADC_INTRMASK_REG_OFFSET, reg_val); + + return FADC_SUCCESS; +} + +/** + * @name: FAdcInterruptDisable + * @msg: disable channel interrupt. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcChannel} channel, adc channel number. + * @param {FAdcIntrEvtType} event_type, interrupt event type + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +FError FAdcInterruptDisable(FAdcCtrl *pctrl, FAdcChannel channel, FAdcIntrEventType event_type) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + FASSERT(channel < FADC_CHANNEL_NUM); + + uintptr base_addr = pctrl->config.base_addr; + u32 reg_val = 0; + reg_val = FADC_READ_REG32(base_addr, FADC_INTRMASK_REG_OFFSET); + switch (event_type) + { + case FADC_INTR_EVENT_COVFIN: /* enable channel convert complete irq */ + reg_val |= (FADC_INTRMASK_REG_COVFIN_MASK(channel)); + break; + + case FADC_INTR_EVENT_DLIMIT: + reg_val |= (FADC_INTRMASK_REG_DLIMIT_MASK(channel)); + break; + + case FADC_INTR_EVENT_ULIMIT: + reg_val |= (FADC_INTRMASK_REG_ULIMIT_MASK(channel)); + break; + + case FADC_INTR_EVENT_ERROR: + reg_val |= (FADC_INTRMASK_REG_ERR_MASK); + break; + + default: + break; + } + + FADC_WRITE_REG32(base_addr, FADC_INTRMASK_REG_OFFSET, reg_val); + + return FADC_SUCCESS; +} + +/** + * @name: FAdcConvertStart + * @msg: Start adc convert. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @return + */ +void FAdcConvertStart(FAdcCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.base_addr; + reg_val = FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET); + reg_val |= FADC_CTRL_REG_SOC_EN; + FADC_WRITE_REG32(base_addr, FADC_CTRL_REG_OFFSET, reg_val); + +} + +/** + * @name: FAdcConvertStop + * @msg: Stop adc convert. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @return + */ +void FAdcConvertStop(FAdcCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.base_addr; + reg_val = FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET); + reg_val &= (~FADC_CTRL_REG_SOC_EN); + FADC_WRITE_REG32(base_addr, FADC_CTRL_REG_OFFSET, reg_val); + +} + +/** + * @name: FAdcInit + * @msg: init adc variable configuration. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcConvertConfig} *convert_config, pointer to adc convert configuration + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +FError FAdcVariableConfig(FAdcCtrl *pctrl, FAdcConvertConfig *convert_config) +{ + FASSERT(pctrl != NULL); + FASSERT(convert_config != NULL); + + FError ret = FADC_SUCCESS; + + /* disable power down signal */ + ret = FAdcPowerDownControl(pctrl, FADC_CTRL_PD_DISABLE); + if (ret != FADC_SUCCESS) + { + FADC_ERROR("FAdcPowerDownControl failed."); + return FADC_ERR_CMD_FAILED; + } + + /* set time interval between two converts */ + ret = FAdcConvertSet(pctrl, convert_config); + if (ret != FADC_SUCCESS) + { + FADC_ERROR("FAdcConvertSet failed."); + return FADC_ERR_CMD_FAILED; + } + + return ret; +} + +/** + * @name: FAdcSingleConvertEnable + * @msg: Enable single convert signal, when convert mode is set to single conversion. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +static FError FAdcSingleConvertEnable(FAdcCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.base_addr; + reg_val = FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET); + reg_val |= FADC_CTRL_REG_SINGLE_CONVERT_EN; + FADC_WRITE_REG32(base_addr, FADC_CTRL_REG_OFFSET, reg_val); + + return FADC_SUCCESS; +} + +/** + * @name: FAdcReadConvertResult + * @msg: read adc channel convert result value. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcChannel} channel, adc channel number. + * @param {u16} *val, pointer to adc convert result value. + * @return err code information, FADC_SUCCESS indicates success,others indicates failed. + */ +FError FAdcReadConvertResult(FAdcCtrl *pctrl, FAdcChannel channel, u16 *val) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FADC_CHANNEL_NUM); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + int timeout = FADC_READ_DELAY; + uintptr base_addr = pctrl->config.base_addr; + + u32 reg_val = FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET); + /* single conversion */ + if (reg_val & FADC_CTRL_REG_SINGLE_CONVERT) + { + FAdcSingleConvertEnable(pctrl); + } + + do + { + fsleep_millisec(10); + } + while ((!pctrl->convert_complete[channel]) && (0 <= --timeout)); + + if (0 >= timeout) + { + FADC_ERROR("timeout when read adc data, convert is not completed."); + *val = 0; + return FADC_ERR_TIMEOUT; + } + + FADC_CONVERT_UNCOMPLETE(pctrl->convert_complete[channel]); + *val = pctrl->value[channel]; + + return FADC_SUCCESS; +} + +/** + * @name: FAdcReadFinishCnt + * @msg: read adc channel convert finish count. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcChannel} channel, adc channel number. + * @param {u32} *count, pointer to adc convert finish count. + * @return err code information, FADC_SUCCESS indicates success,others indicates failed. + */ +FError FAdcReadFinishCnt(FAdcCtrl *pctrl, FAdcChannel channel, u32 *count) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + + uintptr base_addr = pctrl->config.base_addr; + *count = FADC_READ_REG32(base_addr, FADC_FINISH_CNT_REG_OFFSET(channel)); + return FADC_SUCCESS; +} + +/** + * @name: FAdcReadHisLimit + * @msg: read adc channel history limit value, include upper limit and lower limit. + * @param {FAdcCtrl} *pctrl, pointer to a FAdcCtrl structure that contains + * the configuration information for the specified adc module. + * @param {FAdcChannel} channel, adc channel number. + * @param {u16} *u_his_limit, pointer to adc convert history upper limit value. + * @param {u16} *d_his_limit, pointer to adc convert history lower limit value. + * @return err code information, FADC_SUCCESS indicates success,others indicates failed. + */ +FError FAdcReadHisLimit(FAdcCtrl *pctrl, FAdcChannel channel, u16 *u_his_limit, u16 *d_his_limit) +{ + FASSERT(pctrl != NULL); + FASSERT(FT_COMPONENT_IS_READY == pctrl->is_ready); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.base_addr; + + reg_val = FADC_READ_REG32(base_addr, FADC_HIS_LIMIT_REG_OFFSET(channel)); + + *u_his_limit = (reg_val & FADC_HIS_LIMIT_REG_UMASK) >> 16; + *d_his_limit = (reg_val & FADC_HIS_LIMIT_REG_DMASK) ; + + return FADC_SUCCESS; +} + +/** + * @name: FAdcDeInitialize + * @msg: DeInitialization function for the device instance + * @param {FAdcCtrl} *pctrl, instance of FADC controller + * @return {*} + */ +void FAdcDeInitialize(FAdcCtrl *pctrl) +{ + FASSERT(pctrl); + + pctrl->is_ready = 0; + memset(pctrl, 0, sizeof(*pctrl)); + + return; +} + +/** + * @name: FAdcCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {FAdcCtrl} *pctrl, instance of FADC controller + * @param {FAdcConfig} *input_config_p, Default configuration parameters of FADC + * @return err code information, FADC_SUCCESS indicates success,others indicates failed + */ +FError FAdcCfgInitialize(FAdcCtrl *pctrl, const FAdcConfig *input_config_p) +{ + FASSERT(pctrl && input_config_p); + + FError ret = FADC_SUCCESS; + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == pctrl->is_ready) + { + FADC_WARN("device is already initialized!!!"); + } + + /*Set default values and configuration data */ + FAdcDeInitialize(pctrl); + + pctrl->config = *input_config_p; + + pctrl->is_ready = FT_COMPONENT_IS_READY; + + return ret; +} diff --git a/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc.h b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc.h new file mode 100644 index 0000000000..a7c96131f9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc.h @@ -0,0 +1,179 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fadc.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:29:10 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef FT_ADC_H +#define FT_ADC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fdebug.h" +#include "ferror_code.h" +#include "fkernel.h" +#include "fparameters.h" + + +#define FADC_SUCCESS FT_SUCCESS +#define FADC_ERR_INVAL_PARM FT_MAKE_ERRCODE(ErrModBsp, ErrBspAdc, 1) +#define FADC_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspAdc, 2) +#define FADC_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspAdc, 3) +#define FADC_ERR_CMD_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspAdc, 4) +#define FADC_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspAdc, 5) + +#define FADC_CTRL_PD_DISABLE 0 +#define FADC_CTRL_PD_ENABLE 1 + +#define FADC_CONVERT_COMPLETE(x) (x=TRUE) +#define FADC_CONVERT_UNCOMPLETE(x) (x=FALSE) +#define FADC_READ_TIMEOUT (600) +#define FADC_READ_DELAY (10) + +/* adc interrupt event type */ +typedef enum +{ + FADC_INTR_EVENT_COVFIN = 0, /**< Handler type for convert finish interrupt */ + FADC_INTR_EVENT_DLIMIT = 1, /**< Handler type for low limit interrupt*/ + FADC_INTR_EVENT_ULIMIT = 2, /**< Handler type for high limit interrupt*/ + FADC_INTR_EVENT_ERROR = 3, /**< Handler type for error interrupt*/ + + FADC_INTR_EVENT_NUM +} FAdcIntrEventType; + +/* adc convert mode */ +typedef enum +{ + FADC_CONTINUOUS_CONVERT = 0,/* continuous conversion*/ + FADC_SINGLE_CONVERT = 1, /* single conversion*/ + + FADC_CONVERT_MODE_NUM + +} FAdcConvertMode; + +/* adc channel mode */ +typedef enum +{ + FADC_MULTI_CHANNEL = 0, /* multi channel conversion*/ + FADC_FIXED_CHANNEL = 1, /* fixed channel conversion*/ + + FADC_CHANNEL_MODE_NUM +} FAdcChannelMode; + +/* adc base configuration */ +typedef struct +{ + u32 instance_id;/* adc id */ + uintptr base_addr;/* adc control register base address*/ + u32 irq_num;/* adc interrupt number */ + u32 irq_prority;/* adc interrupt priority*/ + const char *instance_name;/* instance name */ + +} FAdcConfig; + +typedef struct +{ + u32 convert_interval; /* convert interval time */ + u32 clk_div; /* clock divider, must be even*/ + FAdcConvertMode convert_mode;/*!< convert mode */ + FAdcChannelMode channel_mode;/*!< channel mode */ + +} FAdcConvertConfig; + +/* adc variable config */ +typedef struct +{ + u16 high_threshold; /*!< Configures the ADC analog high threshold value. + This parameter must be a 10-bit value. */ + u16 low_threshold; /*!< Configures the ADC analog low threshold value. + This parameter must be a 10-bit value. */ +} FAdcThresholdConfig; + + +typedef void (*FAdcIntrEventHandler)(void *param); + +typedef struct +{ + FAdcConfig config;/* adc config */ + u32 is_ready;/* adc init ready flag */ + u16 value[FADC_CHANNEL_NUM]; /* adc value */ + boolean convert_complete[FADC_CHANNEL_NUM]; /*!< Specifies whether the conversion is complete> */ + FAdcIntrEventHandler event_handler[FADC_INTR_EVENT_NUM]; /* event handler for interrupt */ + void *event_param[FADC_INTR_EVENT_NUM]; /* parameters of event handler */ + +} FAdcCtrl; + +/* get default configuration of specific adc id */ +const FAdcConfig *FAdcLookupConfig(FAdcInstance instance_id); + +/* DeInitialization function for the device instance */ +void FAdcDeInitialize(FAdcCtrl *pctrl); + +/* Initializes a specific instance such that it is ready to be used */ +FError FAdcCfgInitialize(FAdcCtrl *pctrl, const FAdcConfig *input_config_p); + +/* config adc convert parameters */ +FError FAdcConvertSet(FAdcCtrl *pctrl, FAdcConvertConfig *convert_config); + +/* Set adc channel high_threshold and low_threshold */ +FError FAdcChannelThresholdSet(FAdcCtrl *pctrl, FAdcChannel channel, FAdcThresholdConfig *threshold_config); + +/* init adc variable configuration */ +FError FAdcVariableConfig(FAdcCtrl *pctrl, FAdcConvertConfig *convert_config); + +/* enable channel interrupt */ +FError FAdcInterruptEnable(FAdcCtrl *pctrl, FAdcChannel channel, FAdcIntrEventType event_type); + +/* disable channel interrupt */ +FError FAdcInterruptDisable(FAdcCtrl *pctrl, FAdcChannel channel, FAdcIntrEventType event_type); + +void FAdcChannelEnable(FAdcCtrl *pctrl, FAdcChannel channel, boolean state); + +/* Start adc convert */ +void FAdcConvertStart(FAdcCtrl *pctrl); + +/* Stop adc convert */ +void FAdcConvertStop(FAdcCtrl *pctrl); + +/* read adc channel convert result value */ +FError FAdcReadConvertResult(FAdcCtrl *pctrl, FAdcChannel channel, u16 *val); + +/* read adc channel convert finish count */ +FError FAdcReadFinishCnt(FAdcCtrl *pctrl, FAdcChannel channel, u32 *count); + +/* read adc channel history limit value, include high limit and low limit */ +FError FAdcReadHisLimit(FAdcCtrl *pctrl, FAdcChannel channel, u16 *u_his_limit, u16 *d_his_limit); + +/* interrupt handler for the driver */ +void FAdcIntrHandler(s32 vector, void *args); + +/* register FAdc interrupt handler function */ +void FAdcRegisterInterruptHandler(FAdcCtrl *instance_p, FAdcIntrEventType event_type, + FAdcIntrEventHandler handler, void *param); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_g.c b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_g.c new file mode 100644 index 0000000000..aae6f24981 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_g.c @@ -0,0 +1,45 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fadc_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:28:45 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "fparameters.h" +#include "fadc.h" + +/* default configs of wdt ctrl */ +const FAdcConfig FAdcConfigTbl[FADC_INSTANCE_NUM] = +{ + { + .instance_id = FADC_INSTANCE_0, + .base_addr = FADC0_CONTROL_BASE, + .irq_num = FADC0_INTR_IRQ, + .irq_prority = 0, + .instance_name = "ADC-0" + + }, + + { + .instance_id = FADC_INSTANCE_1, + .base_addr = FADC1_CONTROL_BASE, + .irq_num = FADC1_INTR_IRQ, + .irq_prority = 0, + .instance_name = "ADC-1" + } +}; \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_hw.c b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_hw.c new file mode 100644 index 0000000000..c1e5cc63f7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_hw.c @@ -0,0 +1,48 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fadc_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fparameters.h" +#include "fadc_hw.h" +#include "stdio.h" + +/** + * @name: FAdcDump + * @msg: debug register value for adc channel. + * @param {uintptr} base_addr, base address of FADC controller + * @param {u8} channel, adc channel number + * @return {*} + */ +void FAdcDump(uintptr base_addr, u8 channel) +{ + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_CTRL_REG_OFFSET, FADC_READ_REG32(base_addr, FADC_CTRL_REG_OFFSET)); + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_INTER_REG_OFFSET, FADC_READ_REG32(base_addr, FADC_INTER_REG_OFFSET)); + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_STATE_REG_OFFSET, FADC_READ_REG32(base_addr, FADC_STATE_REG_OFFSET)); + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_INTRMASK_REG_OFFSET, FADC_READ_REG32(base_addr, FADC_INTRMASK_REG_OFFSET)); + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_INTR_REG_OFFSET, FADC_READ_REG32(base_addr, FADC_INTR_REG_OFFSET)); + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_COV_RESULT_REG_OFFSET(channel), FADC_READ_REG32(base_addr, FADC_COV_RESULT_REG_OFFSET(channel))); + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_FINISH_CNT_REG_OFFSET(channel), FADC_READ_REG32(base_addr, FADC_FINISH_CNT_REG_OFFSET(channel))); + printf("Off[0x%02x]: = 0x%08x\r\n", FADC_HIS_LIMIT_REG_OFFSET(channel), FADC_READ_REG32(base_addr, FADC_HIS_LIMIT_REG_OFFSET(channel))); + + printf("\r\n"); + +} diff --git a/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_hw.h b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_hw.h new file mode 100644 index 0000000000..e9abff56b2 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_hw.h @@ -0,0 +1,121 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fadc_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:28:45 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#ifndef BSP_DRIVERS_ADC_HW_H +#define BSP_DRIVERS_ADC_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fkernel.h" +#include "ftypes.h" +#include "fio.h" + +/* Generic ADC register definitions */ + +/* FADC register */ +#define FADC_CTRL_REG_OFFSET 0x00 +#define FADC_INTER_REG_OFFSET 0x04 +#define FADC_STATE_REG_OFFSET 0x08 +#define FADC_ERRCLR_REG_OFFSET 0x0c +#define FADC_LEVEL_REG_OFFSET(x) (0x10+(x)*4) +#define FADC_INTRMASK_REG_OFFSET 0x30 +#define FADC_INTR_REG_OFFSET 0x34 +#define FADC_COV_RESULT_REG_OFFSET(x) (0x38+(x)*4) +#define FADC_FINISH_CNT_REG_OFFSET(x) (0x58+(x)*4) +#define FADC_HIS_LIMIT_REG_OFFSET(x) (0x78+(x)*4) + +#define FADC_CTRL_REG_PD_EN BIT(31) +#define FADC_CTRL_REG_FIX_CHANNEL_NUM_MASK GENMASK(18, 16) +#define FADC_CTRL_REG_FIX_CHANNEL_NUM(x) ((x)<<16) +#define FADC_CTRL_REG_CLK_DIV(x) ((x)<<12) +#define FADC_CTRL_REG_CLK_DIV_MASK GENMASK(15, 12) +#define FADC_CTRL_REG_CHANNEL_EN(x) BIT((x)+4) +#define FADC_CTRL_REG_FIX_CHANNEL BIT(3) +#define FADC_CTRL_REG_SINGLE_CONVERT_EN BIT(2) +#define FADC_CTRL_REG_SINGLE_CONVERT BIT(1) +#define FADC_CTRL_REG_SOC_EN BIT(0) + +#define FADC_STATE_REG_B_STA(x) ((x)<<8) +#define FADC_STATE_REG_EOC_STA BIT(7) +#define FADC_STATE_REG_S_STA(x) ((x)<<4) +#define FADC_STATE_REG_SOC_STA BIT(3) +#define FADC_STATE_REG_ERR_STA BIT(2) +#define FADC_STATE_REG_COV_FINISH_STA BIT(1) +#define FADC_STATE_REG_CTL_BUSY_STA BIT(0) + +#define FADC_LEVEL_REG_HIGH_LEVEL(x) ((x)<<16) +#define FADC_LEVEL_REG_LOW_LEVEL(x) ((x)<<0) + +#define FADC_INTRMASK_REG_ERR_MASK BIT(24) +#define FADC_INTRMASK_REG_ULIMIT_MASK(x) BIT((x)*2+9) +#define FADC_INTRMASK_REG_DLIMIT_MASK(x) BIT((x)*2+8) +#define FADC_INTRMASK_REG_COVFIN_MASK(x) BIT((x)) + +#define FADC_INTR_REG_ERR BIT(24) +#define FADC_INTR_REG_ULIMIT(x) BIT((x)*2+9) +#define FADC_INTR_REG_DLIMIT(x) BIT((x)*2+8) +#define FADC_INTR_REG_COVFIN(x) BIT((x)) +#define FADC_INTR_REG_COVFIN_MASK GENMASK(7, 0) +#define FADC_INTR_REG_LIMIT_MASK GENMASK(23, 8) + +/* convert result range */ +#define FADC_COV_RESULT_REG_MASK GENMASK(9, 0) + +#define FADC_HIS_LIMIT_REG_UMASK GENMASK(25, 16) +#define FADC_HIS_LIMIT_REG_DMASK GENMASK(9, 0) + +/***************** Macros (Inline Functions) Definitions *********************/ + +/** + * @name: FADC_READ_REG32 + * @msg: 读取FADC寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @return {u32} 寄存器参数 + */ +#define FADC_READ_REG32(addr, reg_offset) FtIn32(addr + (u32)(reg_offset)) + +/** + * @name: FADC_WRITE_REG32 + * @msg: 写入FADC寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @param {u32} reg_value 写入寄存器参数 + * @return {void} + */ +#define FADC_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)(reg_offset), (u32)(reg_value)) + +#define FADC_SETBIT(base_addr, reg_offset, data) FtSetBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FADC_CLEARBIT(base_addr, reg_offset, data) FtClearBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +/* debug register value for adc channel */ +void FAdcDump(uintptr base_addr, u8 channel); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_intr.c b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_intr.c new file mode 100644 index 0000000000..6a6ac7ba60 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_intr.c @@ -0,0 +1,133 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fadc_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:28:45 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "fparameters.h" +#include "fassert.h" +#include "finterrupt.h" +#include "fadc.h" +#include "fadc_hw.h" + +#define FADC_DEBUG_TAG "FT_ADC_INTR" +#define FADC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FADC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FADC_INFO(format, ...) FT_DEBUG_PRINT_I(FADC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FADC_WARN(format, ...) FT_DEBUG_PRINT_W(FADC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FADC_ERROR(format, ...) FT_DEBUG_PRINT_E(FADC_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FADC_CALL_INTR_EVENT_HANDLDER(instance_p, event) \ + if (instance_p->event_handler[event]) \ + instance_p->event_handler[event](instance_p->event_param[event]) + +/** + * @name: FAdcRegisterInterruptHandler + * @msg: register FAdc interrupt handler function + * @param {FAdc} *instance_p, pointer to the adc instance + * @param {FAdcIntrEvtType} event_type, interrupt event type + * @param {FAdcEvtHandler} handler, interrupt event handler + * @param {void} *param, contains a pointer to the driver instance + * @return {*} + */ +void FAdcRegisterInterruptHandler(FAdcCtrl *instance_p, FAdcIntrEventType event_type, + FAdcIntrEventHandler handler, void *param) +{ + FASSERT(instance_p); + FASSERT(event_type < FADC_INTR_EVENT_NUM); + instance_p->event_handler[event_type] = handler; + instance_p->event_param[event_type] = param; +} + +/** + * @name: FAdcIntrHandler + * @msg: This function is the interrupt handler for the driver. + * It must be connected to an interrupt system by the application such that it + * can be called when an interrupt occurs. + * @param vector Irq num ,Don't need attention . + * @param args contains a pointer to the driver instance + */ +void FAdcIntrHandler(s32 vector, void *args) +{ + FASSERT(args != NULL); + FAdcCtrl *pctrl = (FAdcCtrl *)args; + u32 status = 0; + u32 intrmask = 0; + u32 cfg = 0; + u32 channel = 0; + uintptr base_addr = pctrl->config.base_addr; + + status = FADC_READ_REG32(base_addr, FADC_INTR_REG_OFFSET); + /* channel convert complete irq mask */ + intrmask = FADC_READ_REG32(base_addr, FADC_INTRMASK_REG_OFFSET); + + /* adc error interrupt */ + if (status & FADC_INTR_REG_ERR) + { + /* clear error interrupt status */ + FADC_SETBIT(base_addr, FADC_INTR_REG_OFFSET, FADC_INTR_REG_ERR); + + /* write error clear register, adc_errclr_reg=0 */ + FADC_WRITE_REG32(base_addr, FADC_ERRCLR_REG_OFFSET, 0); + + FADC_CALL_INTR_EVENT_HANDLDER(pctrl, FADC_INTR_EVENT_ERROR); + } + + if (status & FADC_INTR_REG_LIMIT_MASK) + { + for (channel = 0; channel < FADC_CHANNEL_NUM; channel++) + { + if (status & FADC_INTR_REG_DLIMIT(channel)) + { + /* clear dlimit interrupt status */ + FADC_SETBIT(base_addr, FADC_INTR_REG_OFFSET, FADC_INTR_REG_DLIMIT(channel)); + FADC_CALL_INTR_EVENT_HANDLDER(pctrl, FADC_INTR_EVENT_DLIMIT); + } + if (status & FADC_INTR_REG_ULIMIT(channel)) + { + /* clear ulimit interrupt status */ + FADC_SETBIT(base_addr, FADC_INTR_REG_OFFSET, FADC_INTR_REG_ULIMIT(channel)); + FADC_CALL_INTR_EVENT_HANDLDER(pctrl, FADC_INTR_EVENT_ULIMIT); + } + } + } + + /* 有中断转换完成的情况下,根据adc_intr_reg寄存器的通道转换完成中断标志位bit0~7,读取转换结果 */ + if (status & FADC_INTR_REG_COVFIN_MASK) + { + for (channel = 0; channel < FADC_CHANNEL_NUM; channel++) + { + if (status & FADC_INTR_REG_COVFIN(channel)) + { + pctrl->value[channel] = FADC_READ_REG32(base_addr, FADC_COV_RESULT_REG_OFFSET(channel)) & FADC_COV_RESULT_REG_MASK; + FADC_CONVERT_COMPLETE(pctrl->convert_complete[channel]); + /* clear convert finish interrupt status */ + FADC_SETBIT(base_addr, FADC_INTR_REG_OFFSET, FADC_INTR_REG_COVFIN(channel)); + } + } + + FADC_CALL_INTR_EVENT_HANDLDER(pctrl, FADC_INTR_EVENT_COVFIN); + } + else + { + + } + + return; +} + diff --git a/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_sinit.c b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_sinit.c new file mode 100644 index 0000000000..b6f415db2a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/adc/fadc/fadc_sinit.c @@ -0,0 +1,67 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fadc_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ + + +#include "fparameters.h" +#include "fadc.h" +#include "fassert.h" + +extern FAdcConfig FAdcConfigTbl[FADC_INSTANCE_NUM]; + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + +/** + * @name: FAdcLookupConfig + * @msg: get default configuration of specific adc id. + * @param {FAdcInstance} instance_id, instance id of FADC controller + * @return {FAdcConfig*} Default configuration parameters of FADC + */ +const FAdcConfig *FAdcLookupConfig(FAdcInstance instance_id) +{ + const FAdcConfig *pconfig = NULL; + FASSERT(instance_id < FADC_INSTANCE_NUM); + + u32 index = 0; + + for (index = 0; index < (u32)FADC_INSTANCE_NUM; index++) + { + if (FAdcConfigTbl[index].instance_id == instance_id) + { + pconfig = &FAdcConfigTbl[index]; + break; + } + } + + return (FAdcConfig *)pconfig; +} diff --git a/bsp/phytium/libraries/standalone/drivers/can/Kconfig b/bsp/phytium/libraries/standalone/drivers/can/Kconfig new file mode 100644 index 0000000000..a6b59e8753 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/Kconfig @@ -0,0 +1,18 @@ + +menu "CAN Configuration" + config USE_FCAN + bool + prompt "Use FCAN" + default n + if USE_FCAN + config FCAN_USE_CANFD + depends on TARGET_E2000 + bool + prompt "Use CanFD" + default n + help + use canfd protocol + endif + +endmenu + diff --git a/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan.c b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan.c new file mode 100644 index 0000000000..9de3f128f4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan.c @@ -0,0 +1,1060 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcan.c + * Date: 2021-04-29 10:21:53 + * LastEditTime: 2022-02-18 08:29:20 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "string.h" +#include +#include +#include "fkernel.h" +#include "fcan.h" +#include "fcan_hw.h" +#include "fassert.h" +#include "fdebug.h" +#include "fswap.h" +#include "fparameters.h" +#include "fsleep.h" + + +#define FT_CAN_DEBUG_TAG "FT_CAN" +#define FCAN_DEBUG(format, ...) FT_DEBUG_PRINT_D(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_INFO(format, ...) FT_DEBUG_PRINT_I(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_WARN(format, ...) FT_DEBUG_PRINT_W(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_ERROR(format, ...) FT_DEBUG_PRINT_E(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) + +typedef struct +{ + u32 tseg1_min; /* Time segement 1 = prop_seg + phase_seg1 */ + u32 tseg1_max; + u32 tseg2_min; /* Time segement 2 = phase_seg2 */ + u32 tseg2_max; + u32 sjw_max; /* Synchronisation jump width */ + u32 brp_min; /* Bit-rate prescaler */ + u32 brp_max; + u32 brp_inc; +} FCanBittimingConst; + +/* 仲裁段速率默认值 */ +static const FCanBittimingConst FCanArbBitConst = +{ + .tseg1_min = FCAN_ARB_TSEG1_MIN, /* Time segement 1 = prop_seg + phase_seg1 */ + .tseg1_max = FCAN_ARB_TSEG1_MAX, + .tseg2_min = FCAN_ARB_TSEG2_MIN, /* Time segement 2 = phase_seg2 */ + .tseg2_max = FCAN_ARB_TSEG2_MAX, + .sjw_max = FCAN_ARB_SJW_MAX, /* Synchronisation jump width */ + .brp_min = FCAN_ARB_BRP_MIN, /* Bit-rate prescaler */ + .brp_max = FCAN_ARB_BRP_MAX, + .brp_inc = FCAN_ARB_BRP_INC, +}; + +/* 数据段速率默认值 */ +static const FCanBittimingConst FCanDataBitConst = +{ + .tseg1_min = FCAN_DATA_TSEG1_MIN, /* Time segement 1 = prop_seg + phase_seg1 */ + .tseg1_max = FCAN_DATA_TSEG1_MAX, + .tseg2_min = FCAN_DATA_TSEG2_MIN, /* Time segement 2 = phase_seg2 */ + .tseg2_max = FCAN_DATA_TSEG2_MAX, + .sjw_max = FCAN_DATA_SJW_MAX, /* Synchronisation jump width */ + .brp_min = FCAN_DATA_BRP_MIN, /* Bit-rate prescaler */ + .brp_max = FCAN_DATA_BRP_MAX, + .brp_inc = FCAN_DATA_BRP_INC, +}; + +/* calculate the can sample point */ +static s32 FCanUpdateSamplePoint(const FCanBittimingConst *btc, + u32 sample_point_nominal, u32 tseg, + u32 *tseg1_ptr, u32 *tseg2_ptr, + u32 *sample_point_error_ptr) +{ + u32 sample_point_error, best_sample_point_error = UINT_MAX; + u32 sample_point, best_sample_point = 0; + u32 tseg1, tseg2; + s32 i; + + for (i = 0; i <= 1; i++) + { + tseg2 = tseg + CAN_CALC_SYNC_SEG - (sample_point_nominal * (tseg + CAN_CALC_SYNC_SEG)) / 1000 - i; + tseg2 = clamp(tseg2, btc->tseg2_min, btc->tseg2_max); + tseg1 = tseg - tseg2; + if (tseg1 > btc->tseg1_max) + { + tseg1 = btc->tseg1_max; + tseg2 = tseg - tseg1; + } + + sample_point = 1000 * (tseg + CAN_CALC_SYNC_SEG - tseg2) / (tseg + CAN_CALC_SYNC_SEG); + sample_point_error = abs(sample_point_nominal - sample_point); + + if ((sample_point <= sample_point_nominal) && (sample_point_error < best_sample_point_error)) + { + best_sample_point = sample_point; + best_sample_point_error = sample_point_error; + *tseg1_ptr = tseg1; + *tseg2_ptr = tseg2; + } + } + + if (sample_point_error_ptr) + *sample_point_error_ptr = best_sample_point_error; + + return best_sample_point; +} + +/** + * @name: FCanCalcBittiming + * @msg: This routine calculate Bit timing + * @param {structFCanBittiming} *bt_p is is a structure that contains the CAN baud rate configuration parameter , The user needs to fill in the baudrate first + * @param {u32} target_baudrate, parameters of target baudrate + * @param {u32} target_sample_point, parameters of target sample point, 0 means the general configuration is used + * @param {FCanSegmentType} target_segment, specifies which target is to be selected. followed by FCAN_ARB_SEGMENT or FCAN_DATA_SEGMENT + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed + */ +static FError FCanCalcBittiming(FCanBaudrateConfig *bt_p, u32 target_baudrate, u32 target_sample_point, FCanSegmentType target_segment) +{ + u32 baudrate; /* current baudrate */ + u32 baudrate_error; /* difference between current and nominal value */ + u32 best_baudrate_error = UINT_MAX; + u32 sample_point_error; /* difference between current and nominal value */ + u32 best_sample_point_error = UINT_MAX; + u32 sample_point_nominal; /* nominal sample point */ + u32 best_tseg = 0; /* current best value for tseg */ + u32 best_brp = 0; /* current best value for brp */ + u32 brp, tsegall, tseg, tseg1 = 0, tseg2 = 0; + u64 v64; + + u32 reg_val; + + const FCanBittimingConst *btc; + FCanBaudrateConfig *bt = bt_p; + FASSERT(bt_p != NULL); + FASSERT(target_segment < FCAN_SEGMENT_TYPE_NUM); + + if (target_segment == FCAN_DATA_SEGMENT) + { + btc = &FCanDataBitConst; + } + else + { + btc = &FCanArbBitConst; + } + + if (target_sample_point) + { + sample_point_nominal = target_sample_point; + } + else + { + if (target_baudrate > 1000000) + sample_point_nominal = 650; + else if (target_baudrate > 800000) + sample_point_nominal = 750; + else if (target_baudrate > 500000) + sample_point_nominal = 800; + else + sample_point_nominal = 875; + } + + for (tseg = (btc->tseg1_max + btc->tseg2_max) * 2 + 1; + tseg >= (btc->tseg1_min + btc->tseg2_min) * 2; tseg--) + { + tsegall = CAN_CALC_SYNC_SEG + tseg / 2; + + /* Compute all possible tseg choices (tseg=tseg1+tseg2) */ + brp = FCAN_REF_CLOCK / (tsegall * target_baudrate) + tseg % 2; + + /* choose brp step which is possible in system */ + brp = (brp / btc->brp_inc) * btc->brp_inc; + + if ((brp < btc->brp_min) || (brp > btc->brp_max)) + continue; + + baudrate = FCAN_REF_CLOCK / (brp * tsegall); + baudrate_error = abs(target_baudrate - baudrate); + + /* tseg brp biterror */ + if (baudrate_error > best_baudrate_error) + continue; + + /* reset sample point error if we have a better baudrate */ + if (baudrate_error < best_baudrate_error) + best_sample_point_error = UINT_MAX; + + FCanUpdateSamplePoint(btc, sample_point_nominal, tseg / 2, &tseg1, &tseg2, &sample_point_error); + + FCAN_DEBUG("target_segment=%d, brp=%d, tseg=%d, tseg1=%d, tseg2=%d, sample_point_nominal=%d", + target_segment, brp, tseg, tseg1, tseg2, sample_point_nominal); + + u32 prop_seg = tseg1 / 2; + u32 phase_seg1 = tseg1 - prop_seg; + u32 phase_seg2 = tseg2; + u32 sjw = 1; + + /* Setting Baud Rate prescalar value in BRPR Register */ + reg_val = (brp - 1) << 16; + reg_val |= (prop_seg - 1) << 2; + reg_val |= (phase_seg1 - 1) << 5; + reg_val |= (phase_seg2 - 1) << 8; + reg_val |= (sjw - 1); + FCAN_DEBUG("reg_val=%#x\n", reg_val); + + if (sample_point_error > best_sample_point_error) + continue; + + best_sample_point_error = sample_point_error; + best_baudrate_error = baudrate_error; + best_tseg = tseg / 2; + best_brp = brp; + + if (baudrate_error == 0 && sample_point_error == 0) + break; + } + + if (best_baudrate_error) + { + /* Error in one-tenth of a percent */ + v64 = (u64)best_baudrate_error * 1000; + do_div(v64, target_baudrate); + baudrate_error = (u32)v64; + if (baudrate_error > CAN_CALC_MAX_ERROR) + { + FCAN_ERROR("baudrate error"); + return FCAN_FAILURE; + } + } + + /* real sample point */ + FCanUpdateSamplePoint(btc, sample_point_nominal, best_tseg, + &tseg1, &tseg2, NULL); + FCAN_DEBUG("tseg1=%d, tseg2=%d, sample_point_nominal=%d", tseg1, tseg2, sample_point_nominal); + + bt->prop_seg = tseg1 / 2; + bt->phase_seg1 = tseg1 - bt->prop_seg; + bt->phase_seg2 = tseg2; + + /* check for sjw user settings */ + if (!bt->sjw || !btc->sjw_max) + { + bt->sjw = 1; + } + else + { + /* bt->sjw is at least 1 -> sanitize upper bound to sjw_max */ + if (bt->sjw > btc->sjw_max) + bt->sjw = btc->sjw_max; + /* bt->sjw must not be higher than tseg2 */ + if (tseg2 < bt->sjw) + bt->sjw = tseg2; + } + + bt->brp = best_brp; + + /* real baudrate */ + if (target_baudrate != FCAN_REF_CLOCK / (bt->brp * (CAN_CALC_SYNC_SEG + tseg1 + tseg2))) + { + FCAN_ERROR("target baudrate calculate timing failed"); + return FCAN_FAILURE; + } + + FCAN_DEBUG("bt->prop_seg=%d, bt->phase_seg1=%d, bt->phase_seg2=%d, bt->sjw=%d, bt->brp=%d", + bt->prop_seg, bt->phase_seg1, bt->phase_seg2, bt->sjw, bt->brp); + + return FCAN_SUCCESS; +} + +static u32 FCanGetDlcLen(u32 dlc) +{ + u32 dlc_len = 0; + if (dlc == 0) + { + dlc_len = 8; + } + + switch (dlc) + { + case 1: + dlc_len = 1; + break; + case 2: + dlc_len = 2; + break; + case 3: + dlc_len = 3; + break; + case 4: + dlc_len = 4; + break; + case 5: + dlc_len = 5; + break; + case 6: + dlc_len = 6; + break; + case 7: + dlc_len = 7; + break; + case 8: + dlc_len = 8; + break; + case 9: + dlc_len = 12; + break; + case 10: + dlc_len = 16; + break; + case 11: + dlc_len = 20; + break; + case 12: + dlc_len = 24; + break; + case 13: + dlc_len = 32; + break; + case 14: + dlc_len = 48; + break; + case 15: + dlc_len = 64; + break; + default : + dlc_len = 0; + break; + } + + return dlc_len; + +} + +static u32 FCanSetDlcLen(u32 len) +{ + if (len <= 8) + { + return len; + } + else if (len <= 12) + { + return 9; + } + else if (len <= 16) + { + return 10; + } + else if (len <= 20) + { + return 11; + } + else if (len <= 24) + { + return 12; + } + else if (len <= 32) + { + return 13; + } + else if (len <= 48) + { + return 14; + } + else if (len <= 64) + { + return 15; + } + else + { + return 0; + } +} + +/** + * @name: FCanReset + * @msg: reset a specific can instance + * @param {FCanCtrl} *pctrl, instance of FCan controller + * @return {*} + */ +void FCanReset(FCanCtrl *instance_p) +{ + u32 reg_value; + FCanConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + + FCAN_WRITE_REG32(config_p->base_address, FCAN_CTRL_OFFSET, 0); + reg_value = FCAN_READ_REG32(config_p->base_address, FCAN_CTRL_OFFSET); + if (reg_value & FCAN_CTRL_XFER_MASK) + { + FCAN_ERROR("FT can is not in configration mode\n"); + return; + } + + /* reset can */ + FCAN_WRITE_REG32(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_RST_MASK); +} + +/** + * @name: FCanDeInitialize + * @msg: Deinitializes a specific can instance + * @param {FCanCtrl} *pctrl, instance of FCan controller + * @return {*} + */ +void FCanDeInitialize(FCanCtrl *instance_p) +{ + FASSERT(instance_p); + instance_p->is_ready = 0; + memset(instance_p, 0, sizeof(*instance_p)); + return; +} + +/** + * @name: FCanCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @param {FCanConfig} *input_config_p, configuration parameters of FCanCtrl + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed + */ +FError FCanCfgInitialize(FCanCtrl *instance_p, const FCanConfig *input_config_p) +{ + FASSERT(instance_p != NULL); + FASSERT(input_config_p != NULL); + + FError ret = FCAN_SUCCESS; + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FCAN_WARN("device is already initialized!!!"); + } + + /*Set default values and configuration data */ + FCanDeInitialize(instance_p); + + instance_p->config = *input_config_p; + + instance_p->is_ready = FT_COMPONENT_IS_READY; + + FCanReset(instance_p); + + return ret; +} + +/** + * @name: FCanStatusGet + * @msg: read can status, include transfer status, error and fifo count. + * @param {FCanCtrl} *instance_p, pointer to a FCanCtrl structure that contains + * the configuration information for the specified can module. + * @param {FCanStatus} *status_p, pointer to can status, include send and receive, error and fifo count . + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed. + */ +FError FCanStatusGet(FCanCtrl *instance_p, FCanStatus *status_p) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(status_p != NULL); + uintptr base_address = instance_p->config.base_address; + + u32 reg_val = 0; + reg_val = FCAN_READ_REG32(base_address, FCAN_XFER_STS_OFFSET); + + status_p->xfer_status.xfers = FCAN_XFER_STS_XFERS_GET(reg_val); + status_p->xfer_status.rs = FCAN_XFER_STS_RS_GET(reg_val); + status_p->xfer_status.ts = FCAN_XFER_STS_TS_GET(reg_val); + status_p->xfer_status.fies = FCAN_XFER_STS_FIES_GET(reg_val); + status_p->xfer_status.fras = FCAN_XFER_STS_FRAS_GET(reg_val); + + reg_val = FCAN_READ_REG32(base_address, FCAN_ERR_CNT_OFFSET); + status_p->rx_err_cnt = FCAN_ERR_CNT_RFN_GET(reg_val); + status_p->tx_err_cnt = FCAN_ERR_CNT_TFN_GET(reg_val); + + reg_val = FCAN_READ_REG32(base_address, FCAN_FIFO_CNT_OFFSET); + status_p->tx_fifo_cnt = FCAN_FIFO_CNT_TFN_GET(reg_val); + status_p->rx_fifo_cnt = FCAN_FIFO_CNT_RFN_GET(reg_val); + + return FCAN_SUCCESS; +} + +/** + * @name: FCanRecv + * @msg: receive can message by specific can instance. + * @param {FCanCtrl} *instance_p, pointer to a FCanCtrl structure that contains + * the configuration information for the specific can module. + * @param {FCanFrame} *frame_p, can message receive struct. + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed. + */ +FError FCanRecv(FCanCtrl *instance_p, FCanFrame *frame_p) +{ + u32 canid; + u32 dlc; + int i = 0, j = 0; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(frame_p != NULL); + uintptr base_address = instance_p->config.base_address; + + memset(frame_p, 0, sizeof(FCanFrame)); + + /* Read a frame from Phytium CAN */ + canid = FCAN_READ_REG32(base_address, FCAN_RX_FIFO_OFFSET); + /* if canid is big-endian ,use swap change to little-endian */ + canid = be32_to_cpu(canid); + + FCAN_DEBUG("FCanRecv canid = %#x\n", canid); + + /* identifier extension */ + if (canid & FCAN_IDR_IDE_MASK) + { + dlc = FCAN_READ_REG32(base_address, FCAN_RX_FIFO_OFFSET); + dlc = be32_to_cpu(dlc); + FCAN_DEBUG("FCanRecv dlc = %#x\n", dlc); + + if (dlc & FTCANFD_ID2_FDL_MASK) + { + if (dlc & FTCANFD_ID2_BRS_MASK) + { + frame_p->flags |= CANFD_BRS; + } + + if (dlc & FTCANFD_ID2_ESI_MASK) + { + frame_p->flags |= CANFD_ESI; + } + dlc = FTCANFD_ID2_EDLC_GET(dlc); + } + else + { + dlc = FCAN_IDR_EDLC_GET(dlc); + } + + frame_p->canid = FCAN_IDR_ID1_GET(canid) << FCAN_ACC_IDN_SHIFT; + frame_p->canid |= FCAN_IDR_ID2_GET(canid); + frame_p->canid |= CAN_EFF_FLAG; + + if (canid & FCAN_IDR_RTR_MASK) + { + frame_p->canid |= CAN_RTR_FLAG; + } + } + else + { + if (canid & FTCANFD_ID1_FDL_MASK) + { + if (canid & FTCANFD_ID1_BRS_MASK) + { + frame_p->flags |= CANFD_BRS; + } + + if (canid & FTCANFD_ID1_ESI_MASK) + { + frame_p->flags |= CANFD_ESI; + } + dlc = FTCANFD_ID1_SDLC_GET(canid); + } + else + { + dlc = FCAN_IDR_DLC_GET(canid); + } + + /* The received frame is a standard format frame */ + frame_p->canid = FCAN_IDR_ID1_GET(canid); + if (canid & FCAN_IDR_SRR_MASK) + { + frame_p->canid |= CAN_RTR_FLAG; + } + } + + frame_p->candlc = FCanGetDlcLen(dlc); + FCAN_DEBUG("FCanRecv frame_p->candlc = %d\n", frame_p->candlc); + + if (!(frame_p->canid & CAN_RTR_FLAG)) + { + j = 0; + for (i = frame_p->candlc; i > 0; i -= 4) + { + *(u32 *)(frame_p->data + j) = FCAN_READ_REG32(base_address, FCAN_RX_FIFO_OFFSET); + j += 4; + } + + if (i > 0) + { + *(u32 *)(frame_p->data + j) = FCAN_READ_REG32(base_address, FCAN_RX_FIFO_OFFSET); + } + } + + return FCAN_SUCCESS; +} + +/** + * @name: FCanSend + * @msg: send can message by specific can instance. + * @param {FCanCtrl} *instance_p, pointer to a FCanCtrl structure that contains + * the configuration information for the specific can module. + * @param {FCanFrame} *frame_p, can message send struct. + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed. + */ +FError FCanSend(FCanCtrl *instance_p, FCanFrame *frame_p) +{ + u32 id, dlc; + + int i = 0, j = 0; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + uintptr base_address = instance_p->config.base_address; + + while (FCAN_TX_FIFO_FULL(instance_p)); + + u32 can_send_dlc = FCanSetDlcLen(frame_p->candlc); + + if (frame_p->canid & CAN_EFF_FLAG) + { + /* Extended CAN id format */ + id = FCAN_IDR_ID2_GET(frame_p->canid & CAN_EFF_MASK); + id |= FCAN_IDR_ID1_GET((frame_p->canid & CAN_EFF_MASK) >> + (CAN_EFF_ID_BITS - CAN_SFF_ID_BITS)); + + /* The substibute remote TX request bit should be "1" + * for extended frames as in the Phytium CAN datasheet + */ + id |= FCAN_IDR_IDE_MASK | FCAN_IDR_SRR_MASK; + if (frame_p->canid & CAN_RTR_FLAG) + { + id |= FCAN_IDR_RTR_MASK; + } + + if (instance_p->use_canfd == TRUE) + { + dlc = can_send_dlc << FCANFD_IDR_EDLC_SHIFT; + dlc |= FTCANFD_ID2_FDL_MASK; + + /* enable brs-Bit Rate Switch */ + frame_p->flags |= CANFD_BRS; + + if (frame_p->flags & CANFD_BRS) + { + dlc |= FTCANFD_ID2_BRS_MASK; + } + + if (frame_p->flags & CANFD_ESI) + { + dlc |= FTCANFD_ID2_ESI_MASK; + } + } + else + { + dlc = can_send_dlc << FCAN_IDR_EDLC_SHIFT; + } + + FCAN_DEBUG("FCanSend id = %#x\n", id); + FCAN_DEBUG("FCanSend dlc = %#x\n", dlc); + FCAN_WRITE_REG32(base_address, FCAN_TX_FIFO_OFFSET, be32_to_cpu(id)); + FCAN_WRITE_REG32(base_address, FCAN_TX_FIFO_OFFSET, be32_to_cpu(dlc)); + } + else + { + /* Standard CAN id format */ + id = FCAN_IDR_ID1_GET(frame_p->canid & CAN_SFF_MASK); + + if (frame_p->canid & CAN_RTR_FLAG) + id |= FCAN_IDR_SRR_MASK; + + FCAN_DEBUG("instance_p->use_canfd = %d, can_send_dlc = %d \n", + instance_p->use_canfd, can_send_dlc); + + if (instance_p->use_canfd == TRUE) + { + dlc = ((can_send_dlc << FCANFD_IDR1_SDLC_SHIFT) | FTCANFD_IDR_PAD_MASK); + + dlc |= FTCANFD_ID1_FDL_MASK; + + /* enable brs-Bit Rate Switch */ + frame_p->flags |= CANFD_BRS; + + if (frame_p->flags & CANFD_BRS) + { + dlc |= FTCANFD_ID1_BRS_MASK; + } + + if (frame_p->flags & CANFD_ESI) + { + dlc |= FTCANFD_ID1_ESI_MASK; + } + } + else + { + dlc = ((can_send_dlc << FCAN_IDR_SDLC_SHIFT) | FCAN_IDR_PAD_MASK); + } + + id |= dlc; + FCAN_DEBUG("can_send id = %#x\n", id); + FCAN_WRITE_REG32(base_address, FCAN_TX_FIFO_OFFSET, be32_to_cpu(id)); + + } + + if (!(frame_p->canid & CAN_RTR_FLAG)) + { + j = 0; + FCAN_DEBUG("frame_p->canid=%#x, frame_p->candlc = %d\n", frame_p->canid, frame_p->candlc); + for (i = frame_p->candlc; i > 0; i -= 4) + { + FCAN_WRITE_REG32(base_address, FCAN_TX_FIFO_OFFSET, *(u32 *)(frame_p->data + j)); + j += 4; + } + + if (i > 0) + { + FCAN_WRITE_REG32(base_address, FCAN_TX_FIFO_OFFSET, *(u32 *)(frame_p->data + j)); + } + + } + + /* triggers tranmission */ + FCAN_CLEARBIT(base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK); + FCAN_SETBIT(base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_TXREQ_MASK | FCAN_CTRL_XFER_MASK); + + return FCAN_SUCCESS; +} + +/** + * @name: FCan_SetTiming + * @msg: This routine sets Bit time + * @param {FCanCtrl} *instance_p is a pointer to the FCanCtrl instance. + * @param {FCanBaudrateConfig} *bittiming_p, parameters of arbitration or data segment baudrate + * @param {FCanSegmentType} target_segment, specifies which target is to be selected. followed by FCAN_ARB_SEGMENT or FCAN_DATA_SEGMENT + * @out param: + * @return {*} + */ +static FError FCanSetTiming(FCanCtrl *instance_p, FCanBaudrateConfig *bittiming_p, FCanSegmentType target_segment) +{ + u32 reg_val = 0; + u32 transfer_enable; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(target_segment < FCAN_SEGMENT_TYPE_NUM); + uintptr base_address = instance_p->config.base_address; + + FASSERT(bittiming_p->brp != 0); + FASSERT(bittiming_p->prop_seg != 0); + FASSERT(bittiming_p->phase_seg1 != 0); + FASSERT(bittiming_p->phase_seg2 != 0); + + FCAN_DEBUG("brp=%d, prop_seg=%d, phase_seg1=%d, phase_seg2=%d, sjw=%d", + bittiming_p->brp, bittiming_p->prop_seg, bittiming_p->phase_seg1, + bittiming_p->phase_seg2, bittiming_p->sjw); + + /* Setting Baud Rate prescalar value in BRPR Register */ + reg_val = (bittiming_p->brp - 1) << 16; + reg_val |= (bittiming_p->prop_seg - 1) << 2; + reg_val |= (bittiming_p->phase_seg1 - 1) << 5; + reg_val |= (bittiming_p->phase_seg2 - 1) << 8; + reg_val |= (bittiming_p->sjw - 1); + + transfer_enable = (FCAN_READ_REG32(base_address, FCAN_CTRL_OFFSET) & FCAN_CTRL_XFER_MASK); + if (transfer_enable) + { + FCAN_CLEARBIT(base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK); + } + + if (reg_val) + { + if (target_segment == FCAN_DATA_SEGMENT) + FCAN_WRITE_REG32(base_address, FCAN_DAT_RATE_CTRL_OFFSET, reg_val); + else + FCAN_WRITE_REG32(base_address, FCAN_ARB_RATE_CTRL_OFFSET, reg_val); + } + else + { + FCAN_ERROR("FCanSetTiming reg_val failed"); + return FCAN_FAILURE; + } + + return FCAN_SUCCESS; +} + +/** + * @name: FCanBaudrateSet + * @msg: Set the fcan baudrate by FCanBaudrateConfig parameters. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @param {FCanBaudrateConfig} *baudrate_p, parameters of arbitration or data segment baudrate + * include baudrate, parameters of target baudrate + * include sample_point, parameters of target sample point, 0 means the general configuration is used. + * The value is the percentage of sampling points multiplied by 1000. + * For example, if sample point is 0.75, set target_sample_point = 750. + * Or manual config baudrate parameters. + * @param {FCanSegmentType} segment, specifies data segment or arbitration segment is selected. followed by FCAN_ARB_SEGMENT or FCAN_DATA_SEGMENT + * @return err code information, FQSPI_SUCCESS indicates success,others indicates failed + * @note this function is to set arb and data segment baudrate, according to the prop_seg, + * phase_seg1, phase_seg2 ,brp and sjw parameters, users can use this function to set can baudrate. + * A formula to calculate baudrate is: + * baudrate = FCAN_REF_CLOCK/(brp*(sjw+prop_seg+phase_seg1++phase_seg2)) + * sample point = (sjw+prop_seg+phase_seg1)/(sjw+prop_seg+phase_seg1++phase_seg2) + * Recommended sample point : + * 75.0% : baudrate > 800000 + * 80.0% : baudrate > 500000 + * 87.5% : baudrate <= 500000 + */ +FError FCanBaudrateSet(FCanCtrl *instance_p, FCanBaudrateConfig *baudrate_p) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FCanSegmentType segment = baudrate_p->segment; + FASSERT(segment < FCAN_SEGMENT_TYPE_NUM); + u32 baudrate = baudrate_p->baudrate; + u32 sample_point = baudrate_p->sample_point; + if (baudrate_p->auto_calc == TRUE) + { +#if defined(CONFIG_TARGET_F2000_4) || defined(CONFIG_TARGET_D2000) + if ((segment == FCAN_ARB_SEGMENT) && ((baudrate > FCAN_BAUDRATE_1000K) || (baudrate < FCAN_BAUDRATE_50K))) + { + FCAN_ERROR("FCanBaudrateSet FCAN_ARB_SEGMENT baudrate = %d invalid", baudrate); + return FCAN_INVAL_PARAM; + } + if ((segment == FCAN_DATA_SEGMENT) && ((baudrate > FCAN_BAUDRATE_1000K) || (baudrate < FCAN_BAUDRATE_50K))) + { + FCAN_ERROR("FCanBaudrateSet FCAN_DATA_SEGMENT baudrate = %d invalid", baudrate); + return FCAN_INVAL_PARAM; + } +#elif defined(CONFIG_TARGET_E2000) + if ((segment == FCAN_ARB_SEGMENT) && ((baudrate > FCAN_BAUDRATE_1000K) || (baudrate < FCAN_BAUDRATE_10K))) + { + FCAN_ERROR("FCanBaudrateSet FCAN_ARB_SEGMENT baudrate = %d invalid", baudrate); + return FCAN_INVAL_PARAM; + } + if ((segment == FCAN_DATA_SEGMENT) && ((baudrate > FCAN_BAUDRATE_5000K) || (baudrate < FCAN_BAUDRATE_10K))) + { + FCAN_ERROR("FCanBaudrateSet FCAN_DATA_SEGMENT baudrate = %d invalid", baudrate); + return FCAN_INVAL_PARAM; + } +#endif + } + + FError ret = FCAN_SUCCESS; + FCanBaudrateConfig timing_config; + memset(&timing_config, 0, sizeof(timing_config)); + + /* Automatically calculate parameters based on baudrate and sample point */ + if (baudrate_p->auto_calc == TRUE) + { + ret = FCanCalcBittiming(&timing_config, baudrate, sample_point, segment); + if (ret != FCAN_SUCCESS) + { + FCAN_ERROR("FCanCalcBittiming %d failed", segment); + return FCAN_FAILURE; + } + + ret = FCanSetTiming(instance_p, &timing_config, segment); + if (ret != FCAN_SUCCESS) + { + FCAN_ERROR("FCanSetTiming %d failed", segment); + return FCAN_FAILURE; + } + } + else + { + ret = FCanSetTiming(instance_p, baudrate_p, segment); + if (ret != FCAN_SUCCESS) + { + FCAN_ERROR("FCanSetTiming failed"); + return FCAN_FAILURE; + } + } + + return ret; +} + +/** + * @name: FCanFdEnable + * @msg: Enable or disable can. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @param {boolean} enable, TRUE-enable canfd, FALSE-disable canfd. + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed + */ +FError FCanEnable(FCanCtrl *instance_p, boolean enable) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + uintptr base_addr = instance_p->config.base_address; + + if (enable == TRUE) + { + FCAN_SETBIT(base_addr, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK); + } + else + { + FCAN_CLEARBIT(base_addr, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK); + } + return FCAN_SUCCESS; +} + +/** + * @name: FCanIdMaskFilterSet + * @msg: Set the can mask and umask id. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @param {FCanIdMaskConfig} *id_mask_p, include filter register index, umask id and mask id + * id indicates a specific ID can receive + * mask indicates mask the corresponding bit of the id + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed + */ +FError FCanIdMaskFilterSet(FCanCtrl *instance_p, FCanIdMaskConfig *id_mask_p) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(id_mask_p); + u32 filter_index = id_mask_p->filter_index; + FASSERT(filter_index < FCAN_ACC_ID_REG_NUM); + uintptr base_address = instance_p->config.base_address; + u32 id_reg_offset = 0; + u32 mask_reg_offset = 0; + u32 id = 0; + u32 mask = 0; + + switch (filter_index) + { + case 0: + id_reg_offset = FCAN_ACC_ID0_OFFSET; + mask_reg_offset = FCAN_ACC_ID0_MASK_OFFSET; + break; + case 1: + id_reg_offset = FCAN_ACC_ID1_OFFSET; + mask_reg_offset = FCAN_ACC_ID1_MASK_OFFSET; + break; + case 2: + id_reg_offset = FCAN_ACC_ID2_OFFSET; + mask_reg_offset = FCAN_ACC_ID2_MASK_OFFSET; + break; + case 3: + id_reg_offset = FCAN_ACC_ID3_OFFSET; + mask_reg_offset = FCAN_ACC_ID3_MASK_OFFSET; + break; + default: + return FCAN_FAILURE; + } + + if (id_mask_p->type == FCAN_STANDARD_FRAME) + { + id = id_mask_p->id << FCAN_ACC_IDN_SHIFT; + mask = id_mask_p->mask << FCAN_ACC_IDN_SHIFT; + } + + FCAN_WRITE_REG32(base_address, id_reg_offset, id); + FCAN_WRITE_REG32(base_address, mask_reg_offset, mask); + + return FCAN_SUCCESS; +} + +/** + * @name: FCanIdMaskFilterEnable + * @msg: Set the can id mask filter enable. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @return {*} + */ +void FCanIdMaskFilterEnable(FCanCtrl *instance_p) +{ + FCanConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + FCAN_SETBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_AIME_MASK); +} + +/** + * @name: FCanIdMaskFilterDisable + * @msg: Set the can id mask filter disable. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @return {*} + */ +void FCanIdMaskFilterDisable(FCanCtrl *instance_p) +{ + FCanConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + FCAN_CLEARBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_AIME_MASK); +} + +/** + * @name: FCanInterruptEnable + * @msg: Enable can interrupt. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @param {FCanIntrEventType} event_type, interrupt event type + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed + */ +FError FCanInterruptEnable(FCanCtrl *instance_p, FCanIntrEventType event_type) +{ + FASSERT(instance_p != NULL); + FASSERT(FT_COMPONENT_IS_READY == instance_p->is_ready); + + uintptr base_addr = instance_p->config.base_address; + u32 reg_val = 0; + reg_val = FCAN_READ_REG32(base_addr, FCAN_INTR_OFFSET); + + switch (event_type) + { + case FCAN_INTR_EVENT_SEND: + reg_val |= FCAN_INTR_TEIE_MASK; + break; + + case FCAN_INTR_EVENT_RECV: + reg_val |= FCAN_INTR_REIE_MASK; + break; + + case FCAN_INTR_EVENT_ERROR: + reg_val |= FCAN_INTR_EIE_MASK; + break; + + default: + break; + } + + FCAN_WRITE_REG32(base_addr, FCAN_INTR_OFFSET, reg_val); + + return FCAN_SUCCESS; +} + +/** + * @name: FCanFdEnable + * @msg: Enable or disable can fd. + * @param {FCanCtrl} *instance_p, instance of FCanCtrl controller + * @param {boolean} enable, TRUE-enable canfd, FALSE-disable canfd. + * @return err code information, FCAN_SUCCESS indicates success,others indicates failed + */ +FError FCanFdEnable(FCanCtrl *instance_p, boolean enable) +{ + FASSERT(instance_p != NULL); + FASSERT(FT_COMPONENT_IS_READY == instance_p->is_ready); + uintptr base_addr = instance_p->config.base_address; + + if (enable == TRUE) + { + instance_p->use_canfd = TRUE; + FCAN_SETBIT(base_addr, FCAN_CTRL_OFFSET, FCAN_CTRL_FDCRC_MASK | FCAN_CTRL_IOF_MASK); + } + else + { + instance_p->use_canfd = FALSE; + FCAN_SETBIT(base_addr, FCAN_CTRL_OFFSET, FCAN_CTRL_IOF_MASK); + FCAN_CLEARBIT(base_addr, FCAN_CTRL_OFFSET, FCAN_CTRL_FDCRC_MASK); + } + + return FCAN_SUCCESS; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan.h b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan.h new file mode 100644 index 0000000000..d35076fd74 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan.h @@ -0,0 +1,249 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcan.h + * Date: 2021-04-27 15:08:44 + * LastEditTime: 2022-02-18 08:29:25 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef FT_CAN_H +#define FT_CAN_H + +#include "ftypes.h" +#include "ferror_code.h" +#include "fparameters.h" +#include "fkernel.h" +#include "fcan_hw.h" + +typedef enum +{ + FCAN_INTR_EVENT_SEND = 0, /* Handler type for frame sending interrupt */ + FCAN_INTR_EVENT_RECV = 1, /* Handler type for frame reception interrupt */ + FCAN_INTR_EVENT_ERROR, /* Handler type for error interrupt */ + FCAN_INTR_EVENT_NUM +} FCanIntrEventType; + +#define FCAN_SUCCESS FT_SUCCESS /* SUCCESS */ +#define FCAN_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspCan, 1) +#define FCAN_FAILURE FT_MAKE_ERRCODE(ErrModBsp, ErrBspCan, 2) /* failed */ +#define FCAN_INVAL_PARAM FT_MAKE_ERRCODE(ErrModBsp, ErrBspCan, 3) /* invalid parameters */ + +#if defined(CONFIG_FCAN_USE_CANFD) + #define FCAN_DATA_LENGTH 64U +#else + #define FCAN_DATA_LENGTH 8U +#endif + +/* CAN payload length and DLC definitions according to ISO 11898-1 */ +#define CAN_MAX_DLC 8 +#define CAN_MAX_DLEN 8 +#define CAN_MAX_CTL 3 +#define CAN_SFF_ID_BITS 11 +#define CAN_EFF_ID_BITS 29 + +/* special address description flags for the CAN_ID */ +#define CAN_EFF_FLAG 0x80000000U /* EFF/SFF is set in the MSB */ +#define CAN_RTR_FLAG 0x40000000U /* remote transmission request */ +#define CAN_ERR_FLAG 0x20000000U /* error message frame */ + +/* valid bits in CAN ID for frame formats */ +#define CAN_SFF_MASK 0x000007FFU /* standard frame format (SFF) */ +#define CAN_EFF_MASK 0x1FFFFFFFU /* extended frame format (EFF) */ +#define CAN_ERR_MASK 0x1FFFFFFFU /* omit EFF, RTR, ERR flags */ + +/* Frame type */ +#define STANDARD_FRAME 0 /* standard frame */ +#define EXTEND_FRAME 1 /* extended frame */ + +/* Bit timing calculate */ +#define CAN_CALC_MAX_ERROR 50 /* in one-tenth of a percent */ +#define CAN_CALC_SYNC_SEG 1 + +/* can segment type */ +typedef enum +{ + FCAN_ARB_SEGMENT = 0, /* Arbitration segment */ + FCAN_DATA_SEGMENT = 1, /* Data segment */ + FCAN_SEGMENT_TYPE_NUM +} FCanSegmentType; + +/* Can error status bit mask */ +#define FCAN_BUS_ERROR_MASK 1 +#define FCAN_PASSIVE_ERROR_MASK 2 +#define FCAN_PASSIVE_WARNING_MASK 4 +#define FCAN_FIFO_RX_OVERFLOW_MASK 8 + +/* Can frame select */ +#define FCAN_STANDARD_FRAME 0 +#define FCAN_EXTENDARD_FRAME 1 + +/* can baudrate */ +#define FCAN_BAUDRATE_10K 10000 +#define FCAN_BAUDRATE_50K 50000 +#define FCAN_BAUDRATE_100K 100000 +#define FCAN_BAUDRATE_200K 200000 +#define FCAN_BAUDRATE_250K 250000 +#define FCAN_BAUDRATE_500K 500000 +#define FCAN_BAUDRATE_1000K 1000000 +#define FCAN_BAUDRATE_2000K 2000000 +#define FCAN_BAUDRATE_3000K 3000000 +#define FCAN_BAUDRATE_4000K 4000000 +#define FCAN_BAUDRATE_5000K 5000000 + +/* + * defined bits for FCanFrame.flags + * + * The use of struct FCanFrame implies the Extended Data Length (EDL) bit to + * be set in the CAN frame bitstream on the wire. The EDL bit switch turns + * the CAN controllers bitstream processor into the CAN FD mode which creates + * two new options within the CAN FD frame specification: + * + * Bit Rate Switch - to indicate a second baudrate is/was used for the payload + * Error State Indicator - represents the error state of the transmitting node + * + * As the CANFD_ESI bit is internally generated by the transmitting CAN + * controller only the CANFD_BRS bit is relevant for real CAN controllers when + * building a CAN FD frame for transmission. Setting the CANFD_ESI bit can make + * sense for virtual CAN interfaces to test applications with echoed frames. + */ +#define CANFD_BRS 0x02 /* bit rate switch (second baudrate for payload data) */ +#define CANFD_ESI 0x04 /* error state indicator of the transmitting node */ + +typedef void (*FCanIntrEventHandler)(void *param); + +typedef struct +{ + FCanIntrEventType type; + FCanIntrEventHandler handler; + void *param; +} FCanIntrEventConfig; + +typedef struct +{ + u32 filter_index;/* filter register index*/ + u32 id; /* id bit to receive */ + u32 mask;/* id mask bit to receive */ + u32 type;/* frame type, standard or extended*/ +} FCanIdMaskConfig; + +typedef struct +{ + u32 canid;/* can frame id */ + u8 candlc;/* can frame length */ + u8 flags; /* additional flags for CAN FD */ + u8 data[FCAN_DATA_LENGTH] __attribute__((aligned(8))); +} FCanFrame; + +typedef struct +{ + u32 instance_id; /* Id of device */ + uintptr base_address; /* Can base Address */ + u32 irq_num; /* interrupt number */ + u32 irq_prority;/* interrupt priority*/ +} FCanConfig; + +typedef struct +{ + FCanSegmentType segment; + boolean auto_calc; /* if auto calculate baudrate parameters */ + u32 baudrate; /* baudrate */ + u32 sample_point; /* sample point */ + u32 prop_seg; /* Propagation segment in TQs */ + u32 phase_seg1; /* Phase buffer segment 1 in TQs */ + u32 phase_seg2; /* Phase buffer segment 2 in TQs */ + u32 sjw; /* Synchronisation jump width in TQs */ + u32 brp; /* Baudrate prescaler */ +} FCanBaudrateConfig; + +typedef struct +{ + u8 xfers;/* transfer status */ + u8 rs; /* receive status */ + u8 ts; /* transmit status */ + u8 fies; /* Current status of the controller state machine */ + u8 fras; /* Frame tagging status */ +} FCanXferStatus; + +typedef struct +{ + FCanXferStatus xfer_status; + u32 tx_err_cnt; + u32 rx_err_cnt; + u32 tx_fifo_cnt; + u32 rx_fifo_cnt; +} FCanStatus; + +typedef struct +{ + FCanConfig config; + u32 is_ready; /* Device is initialized and ready */ + boolean use_canfd; /* if use canfd function */ + + FCanIntrEventConfig intr_event[FCAN_INTR_EVENT_NUM];/* event handler and parameters for interrupt */ +} FCanCtrl; + +/* get default configuration of specific can id */ +const FCanConfig *FCanLookupConfig(FCanInstance instance_id); + +/* reset a specific can instance */ +void FCanReset(FCanCtrl *instance_p); + +/* Deinitializes a specific can instance */ +void FCanDeInitialize(FCanCtrl *instance_p); + +/* Initializes a specific can instance */ +FError FCanCfgInitialize(FCanCtrl *instance_p, const FCanConfig *input_config_p); + +/* Set the fcan baudrate */ +FError FCanBaudrateSet(FCanCtrl *instance_p, FCanBaudrateConfig *baudrate_p); + +/* interrupt handler for the driver */ +void FCanIntrHandler(s32 vector, void *args); + +/* register FCanCtrl interrupt handler function */ +void FCanRegisterInterruptHandler(FCanCtrl *instance_p, FCanIntrEventConfig *intr_event_p); + +/* receive can message by specific can instance */ +FError FCanRecv(FCanCtrl *instance_p, FCanFrame *frame_p); + +/* send can message by specific can instance */ +FError FCanSend(FCanCtrl *instance_p, FCanFrame *frame_p); + +/* Enable the specific can instance */ +FError FCanEnable(FCanCtrl *instance_p, boolean enable); + +/* read can status, include send and receive error count */ +FError FCanStatusGet(FCanCtrl *instance_p, FCanStatus *status_p); + +/* Set the can mask and umask id */ +FError FCanIdMaskFilterSet(FCanCtrl *instance_p, FCanIdMaskConfig *id_mask_p); + +/* Set the can id mask filter enable */ +void FCanIdMaskFilterEnable(FCanCtrl *instance_p); + +/* Set the can id mask filter disable */ +void FCanIdMaskFilterDisable(FCanCtrl *instance_p); + +/* Enable can interrupt */ +FError FCanInterruptEnable(FCanCtrl *instance_p, FCanIntrEventType event_type); + +/* Enable or disable can fd */ +FError FCanFdEnable(FCanCtrl *instance_p, boolean enable); + +#endif // !FT_CAN_H diff --git a/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_g.c b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_g.c new file mode 100644 index 0000000000..62d126a570 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_g.c @@ -0,0 +1,48 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcan_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:28:45 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fcan.h" +#include "fparameters.h" + +const FCanConfig FCanConfigTbl[FCAN_INSTANCE_NUM] = +{ + { + .instance_id = FCAN_INSTANCE_0, /* Id of device */ + .base_address = FCAN0_BASEADDR, /* Can base Address */ + .irq_num = FCAN0_IRQNUM, + }, + { + .instance_id = FCAN_INSTANCE_1, /* Id of device */ + .base_address = FCAN1_BASEADDR, /* Can base Address */ + .irq_num = FCAN1_IRQNUM, + }, +#if defined(CONFIG_TARGET_F2000_4) || defined(CONFIG_TARGET_D2000) + { + .instance_id = FCAN_INSTANCE_2, /* Id of device */ + .base_address = FCAN2_BASEADDR, /* Can base Address */ + .irq_num = FCAN2_IRQNUM, + } +#endif + +}; diff --git a/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_hw.c b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_hw.c new file mode 100644 index 0000000000..dedaa33077 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_hw.c @@ -0,0 +1,67 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcan_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:28:50 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fcan_hw.h" +#include "fparameters.h" +#include "fassert.h" +#include "fdebug.h" + +#define CAN_HW_DEBUG_TAG "CAN_HW" +#define FCAN_DEBUG(format, ...) FT_DEBUG_PRINT_D(CAN_HW_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_INFO(format, ...) FT_DEBUG_PRINT_I(CAN_HW_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_WARN(format, ...) FT_DEBUG_PRINT_W(CAN_HW_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_ERROR(format, ...) FT_DEBUG_PRINT_E(CAN_HW_DEBUG_TAG, format, ##__VA_ARGS__) + + +void FCanDump(uintptr base_addr) +{ + + printf("Off[0x%x]: FCAN_CTRL_OFFSET = 0x%08x\r\n", base_addr + FCAN_CTRL_OFFSET, FCAN_READ_REG32(base_addr, FCAN_CTRL_OFFSET)); + printf("Off[0x%x]: FCAN_INTR_OFFSET = 0x%08x\r\n", base_addr + FCAN_INTR_OFFSET, FCAN_READ_REG32(base_addr, FCAN_INTR_OFFSET)); + printf("Off[0x%x]: FCAN_ARB_RATE_CTRL_OFFSET = 0x%08x\r\n", base_addr + FCAN_ARB_RATE_CTRL_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ARB_RATE_CTRL_OFFSET)); + printf("Off[0x%x]: FCAN_DAT_RATE_CTRL_OFFSET = 0x%08x\r\n", base_addr + FCAN_DAT_RATE_CTRL_OFFSET, FCAN_READ_REG32(base_addr, FCAN_DAT_RATE_CTRL_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID0_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID0_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID0_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID1_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID1_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID1_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID2_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID2_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID2_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID3_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID3_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID3_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID0_MASK_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID0_MASK_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID0_MASK_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID1_MASK_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID1_MASK_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID1_MASK_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID2_MASK_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID2_MASK_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID2_MASK_OFFSET)); + printf("Off[0x%x]: FCAN_ACC_ID3_MASK_OFFSET = 0x%08x\r\n", base_addr + FCAN_ACC_ID3_MASK_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ACC_ID3_MASK_OFFSET)); + printf("Off[0x%x]: FCAN_XFER_STS_OFFSET = 0x%08x\r\n", base_addr + FCAN_XFER_STS_OFFSET, FCAN_READ_REG32(base_addr, FCAN_XFER_STS_OFFSET)); + printf("Off[0x%x]: FCAN_ERR_CNT_OFFSET = 0x%08x\r\n", base_addr + FCAN_ERR_CNT_OFFSET, FCAN_READ_REG32(base_addr, FCAN_ERR_CNT_OFFSET)); + + printf("Off[0x%x]: FCAN_FIFO_CNT_OFFSET = 0x%08x\r\n", base_addr + FCAN_FIFO_CNT_OFFSET, FCAN_READ_REG32(base_addr, FCAN_FIFO_CNT_OFFSET)); + printf("Off[0x%x]: FCAN_DMA_CTRL_OFFSET = 0x%08x\r\n", base_addr + FCAN_DMA_CTRL_OFFSET, FCAN_READ_REG32(base_addr, FCAN_DMA_CTRL_OFFSET)); + + printf("Off[0x%x]: FCAN_XFER_EN_OFFSET = 0x%08x\r\n", base_addr + FCAN_XFER_EN_OFFSET, FCAN_READ_REG32(base_addr, FCAN_XFER_EN_OFFSET)); + + printf("Off[0x%x]: FCAN_FRM_INFO_OFFSET = 0x%08x\r\n", base_addr + FCAN_FRM_INFO_OFFSET, FCAN_READ_REG32(base_addr, FCAN_FRM_INFO_OFFSET)); + + printf("Off[0x%x]: FCAN_TX_FIFO_OFFSET = 0x%08x\r\n", base_addr + FCAN_TX_FIFO_OFFSET, FCAN_READ_REG32(base_addr, FCAN_TX_FIFO_OFFSET)); + printf("Off[0x%x]: FCAN_RX_FIFO_OFFSET = 0x%08x\r\n", base_addr + FCAN_RX_FIFO_OFFSET, FCAN_READ_REG32(base_addr, FCAN_RX_FIFO_OFFSET)); + + printf("\r\n"); + +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_hw.h b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_hw.h new file mode 100644 index 0000000000..1117d962bc --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_hw.h @@ -0,0 +1,246 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcan_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:29:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef FT_CAN_HW_H +#define FT_CAN_HW_H + +#include "ftypes.h" +#include "fio.h" +#include "sdkconfig.h" + +/***ft CAN REGISTER offset*/ +#define FCAN_CTRL_OFFSET 0x00 /* Global control register */ +#define FCAN_INTR_OFFSET 0x04 /* Interrupt register */ +#define FCAN_ARB_RATE_CTRL_OFFSET 0x08 /* Arbitration rate control register */ +#define FCAN_DAT_RATE_CTRL_OFFSET 0x0C /* Data rate control register */ +#define FCAN_ACC_ID0_OFFSET 0x10 /* Acceptance identifier0 register */ +#define FCAN_ACC_ID1_OFFSET 0x14 /* Acceptance identifier1 register */ +#define FCAN_ACC_ID2_OFFSET 0x18 /* Acceptance identifier2 register */ +#define FCAN_ACC_ID3_OFFSET 0x1C /* Acceptance identifier3 register */ +#define FCAN_ACC_ID0_MASK_OFFSET 0x20 /* Acceptance identifier0 mask register */ +#define FCAN_ACC_ID1_MASK_OFFSET 0x24 /* Acceptance identifier1 mask register */ +#define FCAN_ACC_ID2_MASK_OFFSET 0x28 /* Acceptance identifier2 mask register */ +#define FCAN_ACC_ID3_MASK_OFFSET 0x2C /* Acceptance identifier3 mask register */ +#define FCAN_XFER_STS_OFFSET 0x30 /* Transfer status register */ +#define FCAN_ERR_CNT_OFFSET 0x34 /* Error counter register */ +#define FCAN_FIFO_CNT_OFFSET 0x38 /* FIFO counter register */ +#define FCAN_DMA_CTRL_OFFSET 0x3C /* DMA request control register */ +#define FCAN_XFER_EN_OFFSET 0x40 /* Transfer enable register */ +#define FCAN_FRM_INFO_OFFSET 0x48 /* Frame valid number register */ +#define FCAN_TX_FIFO_OFFSET 0x100/* TX FIFO shadow register */ +#define FCAN_RX_FIFO_OFFSET 0x200/* RX FIFO shadow register */ + +/*----------------------------------------------------------------------------*/ +/* CAN register bit masks - FCAN___MASK */ +/*----------------------------------------------------------------------------*/ + +/* FCAN_CTRL mask */ +#define FCAN_CTRL_XFER_MASK BIT(0) /*Transfer enable*/ +#define FCAN_CTRL_TXREQ_MASK BIT(1) /*Transmit request*/ +#define FCAN_CTRL_AIME_MASK BIT(2) /*Acceptance identifier mask enable*/ +#define FCAN_CTRL_RST_MASK BIT(7) /* Soft rest 1:reset and auto clear */ +#define FCAN_CTRL_RFEIDF_MASK BIT(8) /* whether generates frame recv completion interrupt when filtering frames */ +#define FCAN_CTRL_IRFEDT_MASK BIT(9) /* whether generates frame recv completion interrupt when sending frame */ +#define FCAN_CTRL_IOF_MASK BIT(10) /* send overload frame */ +#define FCAN_CTRL_FDCRC_MASK BIT(11) /* Stuff count, crc mode */ + +/* FCAN_INTR mask */ +#define FCAN_INTR_BOIS_MASK BIT(0) /* Bus off interrupt status*/ +#define FCAN_INTR_PWIS_MASK BIT(1) /* Passive warning interrupt status*/ +#define FCAN_INTR_PEIS_MASK BIT(2) /* Passive error interrupt status*/ +#define FCAN_INTR_RFIS_MASK BIT(3) /* RX FIFO full interrupt status*/ +#define FCAN_INTR_TFIS_MASK BIT(4) /* TX FIFO empty interrupt status*/ +#define FCAN_INTR_REIS_MASK BIT(5) /* RX frame end interrupt status*/ +#define FCAN_INTR_TEIS_MASK BIT(6) /* TX frame end interrupt status*/ +#define FCAN_INTR_EIS_MASK BIT(7) /* Error interrupt status*/ +#define FCAN_INTR_BOIE_MASK BIT(8) /* Bus off interrupt enable*/ +#define FCAN_INTR_PWIE_MASK BIT(9) /* Passive warning interrupt enable*/ +#define FCAN_INTR_PEIE_MASK BIT(10) /* Passive error interrupt enable*/ +#define FCAN_INTR_RFIE_MASK BIT(11) /* RX FIFO full interrupt enable*/ +#define FCAN_INTR_TFIE_MASK BIT(12) /* TX FIFO empty interrupt enable*/ +#define FCAN_INTR_REIE_MASK BIT(13) /* RX frame end interrupt enable*/ +#define FCAN_INTR_TEIE_MASK BIT(14) /* TX frame end interrupt enable*/ +#define FCAN_INTR_EIE_MASK BIT(15) /* Error interrupt enable*/ +#define FCAN_INTR_BOIC_MASK BIT(16) /* Bus off interrupt clear*/ +#define FCAN_INTR_PWIC_MASK BIT(17) /* Passive warning interrupt clear*/ +#define FCAN_INTR_PEIC_MASK BIT(18) /* Passive error interrupt clear*/ +#define FCAN_INTR_RFIC_MASK BIT(19) /* RX FIFO full interrupt clear*/ +#define FCAN_INTR_TFIC_MASK BIT(20) /* TX FIFO empty interrupt clear*/ +#define FCAN_INTR_REIC_MASK BIT(21) /* RX frame end interrupt clear*/ +#define FCAN_INTR_TEIC_MASK BIT(22) /* TX frame end interrupt clear*/ +#define FCAN_INTR_EIC_MASK BIT(23) /* Error interrupt clear*/ +#define FCAN_INTR_BORIS_MASK BIT(24) +#define FCAN_INTR_PWRIS_MASK BIT(25) +#define FCAN_INTR_PERIS_MASK BIT(26) +#define FCAN_INTR_RFRIS_MASK BIT(27) +#define FCAN_INTR_TFRIS_MASK BIT(28) +#define FCAN_INTR_RERIS_MASK BIT(29) +#define FCAN_INTR_TERIS_MASK BIT(30) +#define FCAN_INTR_ERIS_MASK BIT(31) + +/* FCAN_DAT_RATE_CTRL mask */ + +/* FCAN_ACC_ID(0-3)_MASK mask */ +#define FCAN_ACC_IDN_MASK GENMASK(28, 0)/*don’t care the matching */ + +#define FCAN_ACC_ID_REG_NUM 4 + +/* FCAN_XFER_STS mask */ +#define FCAN_XFER_STS_XFERS_GET(x) GET_REG32_BITS((x), 10, 10) +#define FCAN_XFER_STS_RS_GET(x) GET_REG32_BITS((x), 9, 9) +#define FCAN_XFER_STS_TS_GET(x) GET_REG32_BITS((x), 8, 8) +#define FCAN_XFER_STS_FIES_GET(x) GET_REG32_BITS((x), 7, 3) +#define FCAN_XFER_STS_FRAS_GET(x) GET_REG32_BITS((x), 2, 0) + +/* FCAN_ERR_CNT_OFFSET mask */ +#define FCAN_ERR_CNT_RFN_MASK GENMASK(8, 0) /*Receive error counter*/ +#define FCAN_ERR_CNT_RFN_GET(x) GET_REG32_BITS((x), 8, 0) +#define FCAN_ERR_CNT_RFN_SET(x) SET_REG32_BITS((x), 8, 0) + +#define FCAN_ERR_CNT_TFN_MASK GENMASK(24, 16) /*Transmit error counter*/ +#define FCAN_ERR_CNT_TFN_GET(x) GET_REG32_BITS((x), 24, 16) +#define FCAN_ERR_CNT_TFN_SET(x) SET_REG32_BITS((x), 24, 16) + +/* FCAN_FIFO_CNT_OFFSET mask */ +#define FCAN_FIFO_CNT_RFN_MASK GENMASK(6, 0) /*Receive FIFO valid data number*/ +#define FCAN_FIFO_CNT_RFN_GET(x) GET_REG32_BITS((x), 6, 0) +#define FCAN_FIFO_CNT_RFN_SET(x) SET_REG32_BITS((x), 6, 0) + +#define FCAN_FIFO_CNT_TFN_MASK GENMASK(6, 0) /*Transmit FIFO valid data number*/ +#define FCAN_FIFO_CNT_TFN_GET(x) GET_REG32_BITS((x), 22, 16) +#define FCAN_FIFO_CNT_TFN_SET(x) SET_REG32_BITS((x), 22, 16) + +#define FCAN_IDR_ID1_SHIFT 21 /* Standard Messg Identifier */ +#define FCAN_IDR_SDLC_SHIFT 14 +#define FCANFD_IDR_EDLC_SHIFT 24 +#define FCAN_IDR_EDLC_SHIFT 26 +#define FCAN_ACC_IDN_SHIFT 18 /*Standard ACC ID shift*/ +#define FCANFD_IDR_GET_EDLC_SHIFT 12 +#define FCANFD_IDR1_SDLC_SHIFT 11 + +/* can */ +#define FCAN_IDR_ID2_GET(x) GET_REG32_BITS((x), 18, 1) /* Get extended message ident */ +#define FCAN_IDR_ID2_SET(x) SET_REG32_BITS((x), 18, 1) /* Set extended message ident */ +#define FCAN_IDR_ID1_GET(x) GET_REG32_BITS((x), 31, 21) /* Get standard msg identifier */ +#define FCAN_IDR_ID1_SET(x) SET_REG32_BITS((x), 31, 21) /* Set standard msg identifier */ +#define FCAN_IDR_IDE_MASK BIT(19) /* Identifier extension */ +#define FCAN_IDR_SRR_MASK BIT(20) /* Substitute remote TXreq */ +#define FCAN_IDR_RTR_MASK BIT(0) /* Extended frames remote TX request */ +#define FCAN_IDR_PAD_MASK GENMASK(13, 0) /* Standard msg padding 1 */ +#define FCAN_IDR_DLC_GET(x) GET_REG32_BITS((x), 17, 14) /* Standard msg dlc */ +#define FCAN_IDR_EDLC_GET(x) GET_REG32_BITS((x), 29, 26) /* Extended msg dlc */ + +/* canfd */ +#define FTCANFD_ID1_FDL_MASK BIT(18) /* CANFD Standard FDF */ +#define FTCANFD_ID1_BRS_MASK BIT(16) /* CANFD Standard BRS */ +#define FTCANFD_ID1_ESI_MASK BIT(15) /* CANFD Standard ESI */ +#define FTCANFD_ID1_SDLC_GET(x) GET_REG32_BITS((x),14, 11) /* CANFD Standard msg dlc */ +#define FTCANFD_IDR_PAD_MASK GENMASK(10, 0) /* CANFD Standard msg padding 1 */ + +#define FTCANFD_ID2_FDL_MASK BIT(31) /* CANFD Extended FDF */ +#define FTCANFD_ID2_BRS_MASK BIT(29) /* CANFD Extended BRS */ +#define FTCANFD_ID2_ESI_MASK BIT(28) /* CANFD Extended ESI */ +#define FTCANFD_ID2_EDLC_GET(x) GET_REG32_BITS((x), 27, 24) /* CANFD Extended msg dlc */ + +#define FTCAN_INTR_EN (FTCAN_INTR_TEIE_MASK | FTCAN_INTR_REIE_MASK | FTCAN_INTR_RFIE_MASK) + +/* Can timming */ +#if defined(CONFIG_TARGET_F2000_4) || defined(CONFIG_TARGET_D2000) + + #define FCAN_ARB_TSEG1_MIN 1 + #define FCAN_ARB_TSEG1_MAX 16 + #define FCAN_ARB_TSEG2_MIN 1 + #define FCAN_ARB_TSEG2_MAX 8 + #define FCAN_ARB_SJW_MAX 4 + #define FCAN_ARB_BRP_MIN 1 + #define FCAN_ARB_BRP_MAX 512 + #define FCAN_ARB_BRP_INC 1 + + #define FCAN_DATA_TSEG1_MIN 1 + #define FCAN_DATA_TSEG1_MAX 16 + #define FCAN_DATA_TSEG2_MIN 1 + #define FCAN_DATA_TSEG2_MAX 8 + #define FCAN_DATA_SJW_MAX 4 + #define FCAN_DATA_BRP_MIN 1 + #define FCAN_DATA_BRP_MAX 512 + #define FCAN_DATA_BRP_INC 1 + +#elif defined(CONFIG_TARGET_E2000) + + #define FCAN_ARB_TSEG1_MIN 1 + #define FCAN_ARB_TSEG1_MAX 16 + #define FCAN_ARB_TSEG2_MIN 1 + #define FCAN_ARB_TSEG2_MAX 8 + #define FCAN_ARB_SJW_MAX 4 + #define FCAN_ARB_BRP_MIN 1 + #define FCAN_ARB_BRP_MAX 8192 + #define FCAN_ARB_BRP_INC 1 + + #define FCAN_DATA_TSEG1_MIN 1 + #define FCAN_DATA_TSEG1_MAX 16 + #define FCAN_DATA_TSEG2_MIN 1 + #define FCAN_DATA_TSEG2_MAX 8 + #define FCAN_DATA_SJW_MAX 4 + #define FCAN_DATA_BRP_MIN 1 + #define FCAN_DATA_BRP_MAX 8192 + #define FCAN_DATA_BRP_INC 1 + +#endif + + +#define FCAN_FIFO_DEPTH 64 + +/** +* This macro reads the given register. +* @param base_addr is the base address of the device. +* @param reg_offset is the register offset to be read. +* @return The 32-bit value of the register +* @note None. +*****************************************************************************/ +#define FCAN_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) + +/****************************************************************************/ +/** +* This macro writes the given register. +* @param base_addr is the base address of the device. +* @param reg_offset is the register offset to be written. +* @param data is the 32-bit value to write to the register. +* @return None. +* @note None. +*****************************************************************************/ +#define FCAN_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)reg_offset, (u32)reg_value) + +#define FCAN_SETBIT(base_addr, reg_offset, data) FtSetBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FCAN_CLEARBIT(base_addr, reg_offset, data) FtClearBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + + +#define FCAN_TX_FIFO_FULL(instance_p) (FCAN_FIFO_DEPTH == FCAN_FIFO_CNT_TFN_GET(FCAN_READ_REG32(instance_p->config.base_address, FCAN_FIFO_CNT_OFFSET))) + +#define FCAN_RX_FIFO_EMPTY(instance_p) (0 == FCAN_FIFO_CNT_RFN_GET(FCAN_READ_REG32(instance_p->config.base_address, FCAN_FIFO_CNT_OFFSET))) + + +void FCanDump(uintptr base_addr); + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_intr.c b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_intr.c new file mode 100644 index 0000000000..a792448e73 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_intr.c @@ -0,0 +1,128 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcan_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:29:10 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "finterrupt.h" +#include "fcan.h" +#include "fcan_hw.h" +#include "fassert.h" +#include "ftypes.h" +#include "fdebug.h" + +#define FT_CAN_DEBUG_TAG "FT_CAN_INTR" +#define FCAN_DEBUG(format, ...) FT_DEBUG_PRINT_D(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_INFO(format, ...) FT_DEBUG_PRINT_I(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_WARN(format, ...) FT_DEBUG_PRINT_W(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) +#define FCAN_ERROR(format, ...) FT_DEBUG_PRINT_E(FT_CAN_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FCAN_CALL_INTR_EVENT_HANDLDER(instance_p, event) \ + if (instance_p->intr_event[event].handler) \ + instance_p->intr_event[event].handler(instance_p->intr_event[event].param) + +/** + * @name: FCanRegisterInterruptHandler + * @msg: register FCanCtrl interrupt handler function + * @param {FCanCtrl} *instance_p, pointer to the Can instance + * @param {FCanIntrEventConfig} *intr_event_p, interrupt event type, handler and parameters + * @return {*} + */ +void FCanRegisterInterruptHandler(FCanCtrl *instance_p, FCanIntrEventConfig *intr_event_p) +{ + FASSERT(instance_p); + FASSERT(intr_event_p); + FCanIntrEventType type = intr_event_p->type; + FASSERT(intr_event_p->type < FCAN_INTR_EVENT_NUM); + instance_p->intr_event[type].type = type; + instance_p->intr_event[type].handler = intr_event_p->handler; + instance_p->intr_event[type].param = intr_event_p->param; +} + +/** + * @name: FCanIntrHandler + * @msg: This function is the interrupt handler for the driver. + * It must be connected to an interrupt system by the application such that it + * can be called when an interrupt occurs. + * @param vector Irq num, Don't need attention. + * @param args contains a pointer to the driver instance + * @return {*} + */ +void FCanIntrHandler(s32 vector, void *args) +{ + u32 irq_status; + FCanCtrl *instance_p = (FCanCtrl *)args; + FCanConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + irq_status = FCAN_READ_REG32(config_p->base_address, FCAN_INTR_OFFSET); + + if (0 == irq_status) + { + return; + } + + /* Check for the type of error interrupt and Processing it */ + if (irq_status & FCAN_INTR_TEIS_MASK) + { + irq_status &= ~FCAN_INTR_REIS_MASK; + FCAN_SETBIT(config_p->base_address, FCAN_INTR_OFFSET, + FCAN_INTR_TEIC_MASK | FCAN_INTR_REIC_MASK); + FCAN_CLEARBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK); + FCAN_SETBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_TXREQ_MASK); + FCAN_SETBIT(config_p->base_address, FCAN_CTRL_OFFSET, FCAN_CTRL_XFER_MASK); + + FCAN_CALL_INTR_EVENT_HANDLDER(instance_p, FCAN_INTR_EVENT_SEND); + } + + if (irq_status & (FCAN_INTR_EIS_MASK | FCAN_INTR_RFIS_MASK | FCAN_INTR_TFIS_MASK | + FCAN_INTR_BOIS_MASK | FCAN_INTR_PEIS_MASK | FCAN_INTR_PWIS_MASK)) + { + FCAN_CALL_INTR_EVENT_HANDLDER(instance_p, FCAN_INTR_EVENT_ERROR); + + FCAN_SETBIT(config_p->base_address, FCAN_INTR_OFFSET, + (FCAN_INTR_EIC_MASK | FCAN_INTR_RFIC_MASK | FCAN_INTR_BOIC_MASK | + FCAN_INTR_PEIC_MASK | FCAN_INTR_PWIC_MASK)); + + /* Check for rx fifo full interrupt and output error information */ + if (irq_status & FCAN_INTR_RFIS_MASK) + { + FCAN_ERROR("rx_fifo is full!!!"); + /* disable rx fifo full interrupt */ + FCAN_CLEARBIT(config_p->base_address, FCAN_INTR_OFFSET, FCAN_INTR_RFIE_MASK); + } + + if (irq_status & FCAN_INTR_TFIS_MASK) + { + FCAN_ERROR("tx_fifo is empty!!!"); + /* disable tx fifo empty interrupt */ + FCAN_CLEARBIT(config_p->base_address, FCAN_INTR_OFFSET, FCAN_INTR_TFIE_MASK); + } + } + + if (irq_status & FCAN_INTR_REIS_MASK) + { + FCAN_SETBIT(config_p->base_address, FCAN_INTR_OFFSET, FCAN_INTR_REIE_MASK); + FCAN_SETBIT(config_p->base_address, FCAN_INTR_OFFSET, FCAN_INTR_REIC_MASK); + FCAN_SETBIT(config_p->base_address, FCAN_INTR_OFFSET, FCAN_INTR_REIE_MASK); + FCAN_CALL_INTR_EVENT_HANDLDER(instance_p, FCAN_INTR_EVENT_RECV); + } +} diff --git a/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_sinit.c b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_sinit.c new file mode 100644 index 0000000000..15dbb27ba0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/can/fcan/fcan_sinit.c @@ -0,0 +1,52 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fcan_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:29:15 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fcan.h" +#include "fparameters.h" +#include "fassert.h" + +extern const FCanConfig FCanConfigTbl[FCAN_INSTANCE_NUM]; + +/** + * @name: FCanLookupConfig + * @msg: get default configuration of specific can instance_id. + * @param {FCanInstance} instance_id, instance id of Can controller + * @return {FCanConfig*} Default configuration parameters of Can + */ +const FCanConfig *FCanLookupConfig(FCanInstance instance_id) +{ + FASSERT(instance_id < FCAN_INSTANCE_NUM); + const FCanConfig *pconfig = NULL; + u32 index; + + for (index = 0; index < (u32)FCAN_INSTANCE_NUM; index++) + { + if (FCanConfigTbl[index].instance_id == instance_id) + { + pconfig = &FCanConfigTbl[index]; + break; + } + } + return (FCanConfig *)pconfig; +} diff --git a/bsp/phytium/libraries/standalone/drivers/dma/Kconfig b/bsp/phytium/libraries/standalone/drivers/dma/Kconfig new file mode 100644 index 0000000000..9ed7f94848 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/Kconfig @@ -0,0 +1,10 @@ + +config ENABLE_FGDMA + bool + prompt "Use FGDMA" + default n + +config ENABLE_FDDMA + bool + prompt "Use FDDMA" + default n \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma.c b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma.c new file mode 100644 index 0000000000..494af32fde --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma.c @@ -0,0 +1,380 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:47 + * Description:  This files is for ddma interface implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +/***************************** Include Files *********************************/ +#include + +#include "fkernel.h" +#include "fparameters.h" +#include "fassert.h" +#include "fdebug.h" + +#include "fddma_hw.h" +#include "fddma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FDDMA_DEBUG_TAG "DDMA" +#define FDDMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_WARN(format, ...) FT_DEBUG_PRINT_W(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_INFO(format, ...) FT_DEBUG_PRINT_I(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +static FError FDdmaReset(FDdma *const instance); + +/****************************************************************************/ +/** + * @name: FDdmaCfgInitialization + * @msg: 初始化DDMA控制器 + * @return {FError} FDDMA_SUCCESS表示初始化成功,其它返回值表示初始化失败 + * @param {FDdma} *instance, DDMA控制器实例 + * @param {FDdmaConfig} *input_config, DDMA控制器配置 + */ +FError FDdmaCfgInitialization(FDdma *const instance, const FDdmaConfig *input_config) +{ + FASSERT(instance && input_config); + uintptr base_addr = input_config->base_addr; + FError ret = FDDMA_SUCCESS; + + if (FT_COMPONENT_IS_READY == instance->is_ready) + { + FDDMA_WARN("device is already initialized!!!"); + } + + FDdmaDeInitialization(instance); + instance->config = *input_config; + + ret = FDdmaReset(instance); + if (FDDMA_SUCCESS == ret) + { + instance->is_ready = FT_COMPONENT_IS_READY; + FDDMA_INFO("ddma@0x%x init success !!!", base_addr); + } + + return ret; +} + +/** + * @name: FDdmaStart + * @msg: 启动DDMA控制器,开始传输 + * @return {FError} FDDMA_SUCCESS表示启动成功,其它返回值表示启动失败 + * @param {FDdma} *instance, DDMA控制器实例 + */ +FError FDdmaStart(FDdma *const instance) +{ + FASSERT(instance); + FError ret = FDDMA_SUCCESS; + uintptr base_addr = instance->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FDDMA_ERROR("dma instance not init !!!"); + return FDDMA_ERR_NOT_INIT; + } + + FDdmaEnableGlobalIrq(base_addr); /* enable ddma irq */ + FDdmaEnable(base_addr); + return FDDMA_SUCCESS; +} + +/** + * @name: FDdmaStop + * @msg: 停止DDMA控制器 + * @return {FError} FDDMA_SUCCESS表示停止成功,其它返回值表示停止失败 + * @param {FDdma} *instance, DDMA控制器实例 + */ +FError FDdmaStop(FDdma *const instance) +{ + FASSERT(instance); + FError ret = FDDMA_SUCCESS; + uintptr base_addr = instance->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FDDMA_ERROR("dma instance not init !!!"); + return FDDMA_ERR_NOT_INIT; + } + + FDdmaDisableGlobalIrq(base_addr); /* enable ddma irq */ + FDdmaDisable(base_addr); + return FDDMA_SUCCESS; +} + +/** + * @name: FDdmaDeInitialization + * @msg: 去初始化DDMA控制器 + * @return {无} + * @param {FDdma} *instance, DDMA控制器实例 + */ +void FDdmaDeInitialization(FDdma *const instance) +{ + FASSERT(instance); + u32 chan; + + for (chan = 0; chan < FDDMA_NUM_OF_CHAN; chan++) + { + if (instance->bind_status & BIT(chan)) + { + FDDMA_WARN("channel %d has not been unbind", chan); + } + } + + memset(instance, 0, sizeof(*instance)); + return; +} + +/** + * @name: FDdmaAllocateChan + * @msg: 按照配置分配DDMA通道 + * @return {FError} FDDMA_SUCCESS表示分配成功,其它返回值表示分配失败 + * @param {FDdma} *instance, DDMA控制器实例 + * @param {FDdmaChan} *dma_chan, DDMA通道实例 + * @param {FDdmaChanConfig} *dma_chan_config, DDMA通道配置 + */ +FError FDdmaAllocateChan(FDdma *const instance, FDdmaChan *const dma_chan, const FDdmaChanConfig *dma_chan_config) +{ + FASSERT(instance && dma_chan && dma_chan_config); + FError ret = FDDMA_SUCCESS; + const FDdmaChanIndex chan_idx = dma_chan_config->id; + u32 reg_val; + uintptr base_addr = instance->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FDDMA_ERROR("dma instance not init !!!"); + return FDDMA_ERR_NOT_INIT; + } + + if ((TRUE == dma_chan->is_used) || (BIT(chan_idx) & instance->bind_status)) + { + FDDMA_ERROR("chan-%d is already is use !!!", chan_idx); + return FDDMA_ERR_CHAN_BINDED; + } + + if (FDdmaIsChanRunning(base_addr, chan_idx)) + { + FDDMA_ERROR("chan-%d is already running !!!", chan_idx); + return FDDMA_ERR_CHAN_BINDED; + } + + if (dma_chan_config->ddr_addr % FDDMA_DDR_ADDR_ALIGMENT) + { + FDDMA_ERROR("ddr addr 0x%x must align with %d bytes", + dma_chan_config->ddr_addr, FDDMA_DDR_ADDR_ALIGMENT); + return FDDMA_ERR_INVALID_DDR_ADDR; + } + + if ((FDDMA_MAX_TRANSFER_LEN < dma_chan_config->trans_len) || + (FDDMA_MIN_TRANSFER_LEN > dma_chan_config->trans_len) || + (0 != dma_chan_config->trans_len % FDDMA_MIN_TRANSFER_LEN)) + { + FDDMA_ERROR("invalid transfer size %d Bytes !!!", dma_chan_config->trans_len); + return FDDMA_ERR_INVALID_TRANS_SIZE; + } + + dma_chan->dma = instance; + instance->chan[chan_idx] = dma_chan; + + if (&(dma_chan->config) != dma_chan_config) + dma_chan->config = *dma_chan_config; + + FDdmaStop(instance); /* disable irq */ + + if (FDDMA_SUCCESS != FDdmaDisableChan(base_addr, chan_idx)) + { + FDDMA_ERROR("disable DDMA@0x%x channel %d failed !!!", base_addr, chan_idx); + return FDDMA_ERR_WAIT_TIMEOUT; + } + + FDdmaResetChan(base_addr, chan_idx); /* reset channel */ + FDdmaSetChanSelection(base_addr, chan_idx, dma_chan->config.slave_id); /* select channel */ + FDdmaSetChanBind(base_addr, chan_idx, TRUE); /* bind channel */ + + /* setup transfer src and dst */ + /* dma_tx_req: ddr --> dev 从内存中读取数据,写入外设 */ + /* dma_rx_req: dev --> ddr 从外设读取数据到内存 */ +#ifdef __aarch64___ + FDdmaWriteReg(base_addr, FDDMA_CHAN_DDR_LOW_ADDR_OFFSET(chan_idx), LOWER_32_BITS(dma_chan_config->ddr_addr)); + FDdmaWriteReg(base_addr, FDDMA_CHAN_DDR_UP_ADDR_OFFSET(chan_idx), UPPER_32_BITS(dma_chan_config->ddr_addr)); +#else + FDdmaWriteReg(base_addr, FDDMA_CHAN_DDR_LOW_ADDR_OFFSET(chan_idx), (u32)(dma_chan_config->ddr_addr)); + FDdmaWriteReg(base_addr, FDDMA_CHAN_DDR_UP_ADDR_OFFSET(chan_idx), 0); +#endif + + FDdmaWriteReg(base_addr, FDDMA_CHAN_DEV_ADDR_OFFSET(chan_idx), dma_chan_config->dev_addr); + FDdmaWriteReg(base_addr, FDDMA_CHAN_TS_OFFSET(chan_idx), dma_chan_config->trans_len); /* block size */ + + /* set channel request direction */ + FDdmaSetChanDirection(base_addr, chan_idx, + (FDDMA_CHAN_REQ_RX == dma_chan->config.req_mode) ? TRUE : FALSE); + + FDDMA_INFO("chan-%d ddr @0x%x", chan_idx, FDDMA_CHAN_DDR_LOW_ADDR_OFFSET(chan_idx)); + FDDMA_INFO("ddr addr: 0x%x", FDdmaReadReg(base_addr, FDDMA_CHAN_DDR_LOW_ADDR_OFFSET(chan_idx))); + FDDMA_INFO("dev addr: 0x%x", FDdmaReadReg(base_addr, FDDMA_CHAN_DEV_ADDR_OFFSET(chan_idx))); + FDDMA_INFO("trans len: %d", FDdmaReadReg(base_addr, FDDMA_CHAN_TS_OFFSET(chan_idx))); + + FDdmaSetChanTimeout(base_addr, chan_idx, 0xffff); + FDdmaEnableChanIrq(base_addr, chan_idx); + + if (FDDMA_SUCCESS == ret) + { + instance->bind_status |= BIT(chan_idx); + dma_chan->is_used = TRUE; + FDDMA_INFO("allocate channel %d", chan_idx); + } + + return ret; +} + +/** + * @name: FDdmaDellocateChan + * @msg: 释放之前分配的DDMA通道 + * @return {FError} FDDMA_SUCCESS表示释放成功,其它返回值表示释放失败 + * @param {FDdmaChan} *dma_chan, DDMA控制器实例 + */ +FError FDdmaDellocateChan(FDdmaChan *const dma_chan) +{ + FASSERT(dma_chan && dma_chan->dma); + FDdma *const instance = dma_chan->dma; + const FDdmaChanIndex chan_idx = dma_chan->config.id; + uintptr base_addr = instance->config.base_addr; + FError ret = FDDMA_SUCCESS; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FDDMA_ERROR("dma instance not init !!!"); + return FDDMA_ERR_NOT_INIT; + } + + if (FDDMA_SUCCESS != FDdmaDisableChan(base_addr, chan_idx)) + { + FDDMA_ERROR("disable DDMA@0x%x channel %d failed !!!", base_addr, chan_idx); + return FDDMA_ERR_WAIT_TIMEOUT; + } + + FDdmaResetChan(base_addr, chan_idx); + + FDdmaSetChanBind(base_addr, chan_idx, FALSE); /* unbind channel */ + ret = FDdmaDisableChan(base_addr, chan_idx); + if (FDDMA_SUCCESS != ret) /* disable channel */ + { + FDDMA_ERROR("disable ddma@%p channel %d failed !!!", base_addr, chan_idx); + return ret; + } + + FDdmaDisableChanIrq(base_addr, chan_idx); /* disable channel irq */ + + instance->bind_status &= ~BIT(chan_idx); /* set bind status */ + instance->chan[chan_idx] = NULL; + + FDDMA_INFO("deallocate channel %d", chan_idx); + memset(dma_chan, 0, sizeof(*dma_chan)); + + return ret; +} + +/** + * @name: FDdmaActiveChan + * @msg: 使能指定的DDMA通道 + * @note: 调用FDdmaAllocateChan后无需调用此函数 + * @return {FError} 返回FDDMA_SUCCESS表示成功,返回其它表示失败 + * @param FDdmaChan *const dma_chan, DDMA通道实例 + */ +FError FDdmaActiveChan(FDdmaChan *const dma_chan) +{ + FASSERT(dma_chan && dma_chan->dma); + FDdma *const instance = dma_chan->dma; + uintptr base_addr = instance->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FDDMA_ERROR("dma instance not init !!!"); + return FDDMA_ERR_NOT_INIT; + } + + FDdmaEnableChan(base_addr, dma_chan->config.id); + FDdmaClearChanIrq(base_addr, dma_chan->config.id); /* clear interrupt status */ + return FDDMA_SUCCESS; +} + +FError FDdmaDeactiveChan(FDdmaChan *const dma_chan) +{ + FASSERT(dma_chan && dma_chan->dma); + FDdma *const instance = dma_chan->dma; + uintptr base_addr = instance->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FDDMA_ERROR("dma instance not init !!!"); + return FDDMA_ERR_NOT_INIT; + } + + return FDdmaDisableChan(base_addr, dma_chan->config.id); +} + +/** + * @name: FDdmaReset + * @msg: 重置DDMA控制器 + * @return {FError} FDDMA_SUCCESS表示重置成功,其它返回值表示失败 + * @param {FDdma} *instance, DDMA控制器实例 + */ +static FError FDdmaReset(FDdma *const instance) +{ + FASSERT(instance); + uintptr base_addr = instance->config.base_addr; + FError ret = FDDMA_SUCCESS; + u32 reg_val; + u32 chan; + + if (0 != instance->bind_status) + { + FDDMA_WARN("some channel not yet un-bind !!!"); + } + + FDdmaDisable(base_addr); /* disable ddma */ + FDdmaSoftwareReset(base_addr); /* do software reset */ + FDdmaDisableGlobalIrq(base_addr); + + /* disable channel and its irq */ + for (u32 chan = FDDMA_CHAN_0; chan < FDDMA_NUM_OF_CHAN; chan++) + { + /* disable channel */ + ret = FDdmaDisableChan(base_addr, chan); + if (FDDMA_SUCCESS != ret) + { + FDDMA_ERROR("disable ddma@%p channel %d failed !!!", base_addr, chan); + break; + } + } + + FDdmaDumpRegisters(base_addr); + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma.h b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma.h new file mode 100644 index 0000000000..486876a698 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma.h @@ -0,0 +1,169 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:52 + * Description:  This files is for ddma interface definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +#ifndef DRIVER_FDDMA_H +#define DRIVER_FDDMA_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "ferror_code.h" + +/************************** Constant Definitions *****************************/ +typedef enum +{ + FDDMA_CHAN_0 = 0, + FDDMA_CHAN_1, + FDDMA_CHAN_2, + FDDMA_CHAN_3, + FDDMA_CHAN_4, + FDDMA_CHAN_5, + FDDMA_CHAN_6, + FDDMA_CHAN_7, + + FDDMA_NUM_OF_CHAN +} FDdmaChanIndex; /* DDMA channel index */ + +typedef enum +{ + FDDMA_CHAN_REQ_RX = 0, + FDDMA_CHAN_REQ_TX, +} FDdmaChanRequst; /* DDMA channel direction */ + +typedef enum +{ + FDDMA_CHAN_EVT_REQ_DONE = 0, + FDDMA_CHAN_EVT_FIFO_EMPTY, + FDDMA_CHAN_EVT_FIFO_FULL, + + FDDMA_NUM_OF_CHAN_EVT +} FDdmaChanEvt; /* DDMA channel interrupt event */ + +#define FDDMA_SUCCESS FT_SUCCESS +#define FDDMA_ERR_NOT_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrDdma, 0) +#define FDDMA_ERR_CHAN_BINDED FT_MAKE_ERRCODE(ErrModBsp, ErrDdma, 1) +#define FDDMA_ERR_CHAN_RUNNING FT_MAKE_ERRCODE(ErrModBsp, ErrDdma, 2) +#define FDDMA_ERR_INVALID_TRANS_SIZE FT_MAKE_ERRCODE(ErrModBsp, ErrDdma, 3) +#define FDDMA_ERR_WAIT_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrDdma, 4) +#define FDDMA_ERR_INVALID_DDR_ADDR FT_MAKE_ERRCODE(ErrModBsp, ErrDdma, 5) + +/**************************** Type Definitions *******************************/ +typedef struct FDdma_ FDdma; +typedef struct FDdmaChan_ FDdmaChan; + +typedef void (*FDdmaChanEvtHandler)(FDdmaChan *const dma_chan, void *arg); /* DMA interrupt event handler */ + +typedef struct +{ + u32 id; /* DDMA ctrl id */ + uintptr base_addr; /* DDMA ctrl base address */ + u32 irq_num; /* DDMA ctrl interrupt id */ + u32 irq_prority; /* DDMA ctrl interrupt priority */ +} FDdmaConfig; /* DDMA instance configuration */ + +typedef struct +{ + FDdmaChanIndex id; /* DMA channel index */ + u32 slave_id; /* Perpherial slave id for DDMA */ + FDdmaChanRequst req_mode; /* DMA transfer direction */ + uintptr ddr_addr; /* DMA channel DDR address, could be source or destination */ + u32 dev_addr; /* DMA channel Perpherial, could be source or destination */ + u32 trans_len; /* DMA channel transfer length */ +#define FDDMA_MAX_TRANSFER_LEN 64 /* max bytes in transfer */ +#define FDDMA_MIN_TRANSFER_LEN 4 /* min bytes in transfer */ + u32 timeout; /* timeout = 0 means no use DMA timeout */ +} FDdmaChanConfig; /* DDMA channel instance */ + +typedef struct FDdmaChan_ +{ + FDdmaChanConfig config; /* DDMA channel configuration */ + boolean is_used; /* TRUE means channel is in use */ + FDdma *dma; /* DMA instance of this channel */ + FDdmaChanEvtHandler evt_handler[FDDMA_NUM_OF_CHAN_EVT]; /* interrupt evt */ + void *evt_handler_args[FDDMA_NUM_OF_CHAN_EVT]; /* interrupt evt args */ +} FDdmaChan; /* DDMA channel instance */ + +typedef struct FDdma_ +{ + FDdmaConfig config; /* DDMA instance configuration */ + FDdmaChan *chan[FDDMA_NUM_OF_CHAN]; /* DDMA channel instance, NULL means channel not yet allocate */ + u32 is_ready; /* TRUE means DDMA init ok */ + u32 bind_status; /* channel bind status, BIT(n) = 1 means channel n is allocated */ +} FDdma; /* DDMA instance */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FDDMA_DDR_ADDR_ALIGMENT 128 /* DMA DDR Buffer need align wiht 128 bytes */ + +/************************** Function Prototypes ******************************/ +/* 获取DDMA实例默认配置 */ +const FDdmaConfig *FDdmaLookupConfig(u32 instance_id); + +/* 初始化DDMA控制器 */ +FError FDdmaCfgInitialization(FDdma *const instance, const FDdmaConfig *input_config); + +/* 去初始化DDMA控制器 */ +void FDdmaDeInitialization(FDdma *const instance); + +/* 按照配置分配DDMA通道 */ +FError FDdmaAllocateChan(FDdma *const instance, FDdmaChan *const dma_chan, const FDdmaChanConfig *dma_chan_config); + +/* 释放之前分配的DDMA通道 */ +FError FDdmaDellocateChan(FDdmaChan *const dma_chan); + +/* 使能指定的DDMA通道,调用FDdmaAllocateChan后无需调用此函数 */ +FError FDdmaActiveChan(FDdmaChan *const dma_chan); + +/* 去使能DDMA通道 */ +FError FDdmaDeactiveChan(FDdmaChan *const dma_chan); + +/* 启动DDMA控制器并开始传输 */ +FError FDdmaStart(FDdma *const instance); + +/* 停止DDMA控制器 */ +FError FDdmaStop(FDdma *const instance); + +/* DDMA中断处理函数 */ +void FDdmaIrqHandler(s32 vector, void *args); + +/* 注册DDMA通道中断响应事件函数 */ +void FDdmaRegisterChanEvtHandler(FDdmaChan *const dma_chan, + FDdmaChanEvt evt, + FDdmaChanEvtHandler handler, + void *handler_arg); +/* DDMA控制器寄存器自检测试 */ +void FDdmaDumpRegisters(uintptr base_addr); + +void FDdmaDumpChanRegisters(uintptr base_addr, FDdmaChanIndex chan); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_g.c b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_g.c new file mode 100644 index 0000000000..4204d9d23e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_g.c @@ -0,0 +1,57 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:47 + * Description:  This files is for ddma static configuration + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +/***************************** Include Files *********************************/ +#include "fparameters.h" + +#include "fddma_hw.h" +#include "fddma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ +const FDdmaConfig fddma_cfg_tbl[FDDMA_INSTANCE_NUM] = +{ + [FDDMA0_ID] = + { + .id = FDDMA0_ID, + .base_addr = FDDMA0_BASE_ADDR, + .irq_num = FDDMA0_IRQ_NUM, + .irq_prority = 0 + }, + + [FDDMA1_ID] = + { + .id = FDDMA1_ID, + .base_addr = FDDMA1_BASE_ADDR, + .irq_num = FDDMA1_IRQ_NUM, + .irq_prority = 0 + } +}; /* DDMA控制器默认配置 */ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_hw.c b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_hw.c new file mode 100644 index 0000000000..dfbe76576e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_hw.c @@ -0,0 +1,372 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:47 + * Description:  This files is for ddma register rw operations + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +/***************************** Include Files *********************************/ +#include + +#include "fkernel.h" +#include "fparameters.h" +#include "fassert.h" +#include "fdebug.h" + +#include "fddma_hw.h" +#include "fddma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FDDMA_DEBUG_TAG "DDMA-HW" +#define FDDMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_WARN(format, ...) FT_DEBUG_PRINT_W(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_INFO(format, ...) FT_DEBUG_PRINT_I(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/****************************************************************************/ +/** + * @name: FDdmaDisable + * @msg: 去使能DDMA控制器 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + */ +void FDdmaDisable(uintptr base_addr) +{ + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CTL_OFFSET); + reg_val &= ~FDDMA_CTL_ENABLE; + FDdmaWriteReg(base_addr, FDDMA_CTL_OFFSET, reg_val); + FDDMA_DEBUG("ddma @%p disabled : 0x%x", base_addr, FDdmaReadReg(base_addr, FDDMA_CTL_OFFSET)); + return; +} + +/** + * @name: FDdmaEnable + * @msg: 使能DDMA控制器 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + */ +void FDdmaEnable(uintptr base_addr) +{ + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CTL_OFFSET); + reg_val |= FDDMA_CTL_ENABLE; + FDdmaWriteReg(base_addr, FDDMA_CTL_OFFSET, reg_val); + FDDMA_DEBUG("ddma @%p enabled : 0x%x", base_addr, FDdmaReadReg(base_addr, FDDMA_CTL_OFFSET)); + return; +} + +/** + * @name: FDdmaSoftwareReset + * @msg: 复位DDMA控制器 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + */ +void FDdmaSoftwareReset(uintptr base_addr) +{ + int delay = 10000; + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CTL_OFFSET); + reg_val |= FDDMA_CTL_SRST; + FDdmaWriteReg(base_addr, FDDMA_CTL_OFFSET, reg_val); + FDDMA_DEBUG("ddma @%p software reset start : 0x%x", base_addr, FDdmaReadReg(base_addr, FDDMA_CTL_OFFSET)); + + while (--delay > 0) /* wait a while to do reset */ + ; + + reg_val &= ~FDDMA_CTL_SRST; + FDdmaWriteReg(base_addr, FDDMA_CTL_OFFSET, reg_val); /* exit from software reset */ + FDDMA_DEBUG("ddma @%p software reset end : 0x%x", base_addr, FDdmaReadReg(base_addr, FDDMA_CTL_OFFSET)); + return; +} + +/** + * @name: FDdmaDisableGlobalIrq + * @msg: 关闭DDMA全局中断 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + */ +void FDdmaDisableGlobalIrq(uintptr base_addr) +{ + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_MASK_INTR_OFFSET); + reg_val |= FDDMA_MASK_EN_GLOBAL_INTR; /* write 1 and disable interrupt */ + FDdmaWriteReg(base_addr, FDDMA_MASK_INTR_OFFSET, reg_val); + return; +} + +/** + * @name: FDdmaEnableGlobalIrq + * @msg: 打开DDMA全局中断 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + */ +void FDdmaEnableGlobalIrq(uintptr base_addr) +{ + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_MASK_INTR_OFFSET); + reg_val &= ~FDDMA_MASK_EN_GLOBAL_INTR; /* write 0 and enable interrupt */ + FDdmaWriteReg(base_addr, FDDMA_MASK_INTR_OFFSET, reg_val); + return; +} + +/** + * @name: FDdmaDisableChanIrq + * @msg: 关闭DDMA通道中断 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + */ +void FDdmaDisableChanIrq(uintptr base_addr, u32 chan) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_MASK_INTR_OFFSET); + reg_val |= FDDMA_MASK_EN_CHAN_INTR(chan); + FDdmaWriteReg(base_addr, FDDMA_MASK_INTR_OFFSET, reg_val); + return; +} + +/** + * @name: FDdmaEnableChanIrq + * @msg: 打开DDMA通道中断 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + */ +void FDdmaEnableChanIrq(uintptr base_addr, u32 chan) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_MASK_INTR_OFFSET); + reg_val &= ~FDDMA_MASK_EN_CHAN_INTR(chan); /* write 0 and enable */ + FDdmaWriteReg(base_addr, FDDMA_MASK_INTR_OFFSET, reg_val); + return; +} + +/** + * @name: FDdmaDisableChan + * @msg: 去使能DDMA通道 + * @return {FError} FDDMA_SUCCESS 表示去使能成功 + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + */ +FError FDdmaDisableChan(uintptr base_addr, u32 chan) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + int delay = 1000; + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan)); + reg_val &= ~FDDMA_CHAN_CTL_EN; + FDdmaWriteReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan), reg_val); + + /* 先写该位 1’b0,随后读取到该位是 1’b0 的时候,才能复位该通道 */ + do + { + reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan)); + if (delay-- <= 0) + break; + } + while (reg_val & FDDMA_CHAN_CTL_EN); + + FDDMA_DEBUG("ddma @%p chan %d disabled : 0x%x", base_addr, chan, FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan))); + return (delay > 0) ? FDDMA_SUCCESS : FDDMA_ERR_WAIT_TIMEOUT; +} + +/** + * @name: FDdmaEnableChan + * @msg: 使能DDMA通道 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + */ +void FDdmaEnableChan(uintptr base_addr, u32 chan) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan)); + reg_val |= FDDMA_CHAN_CTL_EN; + FDdmaWriteReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan), reg_val); + FDDMA_DEBUG("ddma @%p chan %d enabled : 0x%x", base_addr, chan, FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan))); + return; +} + +/** + * @name: FDdmaClearChanIrq + * @msg: 清除DDMA通道中断状态 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + */ +void FDdmaClearChanIrq(uintptr base_addr, u32 chan) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + /* write 1 to clear irq status of channel */ + FDdmaWriteReg(base_addr, FDDMA_STA_OFFSET, FDDMA_STA_CHAN_REQ_DONE(chan)); +} + +/** + * @name: FDdmaResetChan + * @msg: 重置DDMA通道 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + */ +void FDdmaResetChan(uintptr base_addr, u32 chan) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + int delay = 1000; + u32 reg_val; + + if (FDdmaIsChanRunning(base_addr, chan)) /* disable channel if running */ + (void)FDdmaDisableChan(base_addr, chan); + + reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan)); + reg_val |= FDDMA_CHAN_CTL_SRST; + FDdmaWriteReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan), reg_val); + + while (--delay > 0) /* wait a while to do reset */ + ; + + reg_val &= ~FDDMA_CHAN_CTL_SRST; + FDdmaWriteReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan), reg_val); + FDDMA_DEBUG("chan reset done, ctrl: 0x%x", FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan))); + return; +} + +/** + * @name: FDdmaIsChanRunning + * @msg: 检查通道是否在工作中 + * @return {boolean} TRUE: 在工作中 + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + */ +boolean FDdmaIsChanRunning(uintptr base_addr, u32 chan) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan)); + return (FDDMA_CHAN_CTL_EN & reg_val) ? TRUE : FALSE; +} + +/** + * @name: FDdmaSetChanSelection + * @msg: 将DDMA通道与外设绑定 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + * @param {u32} slave_id, 外设对应的slave id + */ +void FDdmaSetChanSelection(uintptr base_addr, u32 chan, u32 slave_id) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + FASSERT_MSG((FDDMA_MAX_SLAVE_ID >= slave_id), "invalid slave id %d", slave_id); + u32 reg_val; + + if (FDDMA_CHAN_4 > chan) + { + reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_0_3_CFG_OFFSET); + reg_val &= ~FDDMA_CHAN_0_3_SEL_MASK(chan); + reg_val |= FDDMA_CHAN_0_3_SEL(chan, slave_id); + reg_val |= FDDMA_CHAN_0_3_SEL_EN(chan); + FDdmaWriteReg(base_addr, FDDMA_CHAN_0_3_CFG_OFFSET, reg_val); + FDDMA_DEBUG("ddma@%p set chan-%d slave id-%d, 0x%x", base_addr, chan, slave_id, FDdmaReadReg(base_addr, FDDMA_CHAN_0_3_CFG_OFFSET)); + } + else + { + reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_4_7_CFG_OFFSET); + reg_val &= ~FDDMA_CHAN_4_7_SEL_MASK(chan); + reg_val |= FDDMA_CHAN_4_7_SEL(chan, slave_id); + reg_val |= FDDMA_CHAN_4_7_SEL_EN(chan); + FDdmaWriteReg(base_addr, FDDMA_CHAN_4_7_CFG_OFFSET, reg_val); + FDDMA_DEBUG("ddma@%p set chan-%d slave id-%d, 0x%x", base_addr, chan, slave_id, FDdmaReadReg(base_addr, FDDMA_CHAN_4_7_CFG_OFFSET)); + } + + return; +} + +/** + * @name: FDdmaSetChanBind + * @msg: 修改通道的绑定状态 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + * @param {boolean} bind, TRUE: 绑定,FALSE: 解除绑定 + */ +void FDdmaSetChanBind(uintptr base_addr, u32 chan, boolean bind) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_BIND_OFFSET); + + if (bind) + reg_val |= BIT(chan); + else + reg_val &= ~BIT(chan); + + FDDMA_DEBUG("ddma@%p %s chan-%d, 0x%x", base_addr, bind ? "bind" : "unbind", chan, FDdmaReadReg(base_addr, FDDMA_CHAN_BIND_OFFSET)); + FDdmaWriteReg(base_addr, FDDMA_CHAN_BIND_OFFSET, reg_val); + return; +} + +/** + * @name: FDdmaSetChanDirection + * @msg: 设置通道的方向 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + * @param {boolean} is_rx, TRUE: 接收, FALSE: 发送 + */ +void FDdmaSetChanDirection(uintptr base_addr, u32 chan, boolean is_rx) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan)); + if (is_rx) + reg_val |= FDDMA_CHAN_CTL_RX_MODE; /* device to memory */ + else + reg_val &= ~FDDMA_CHAN_CTL_RX_MODE; /* memory to device */ + FDdmaWriteReg(base_addr, FDDMA_CHAN_CTL_OFFSET(chan), reg_val); + return; +} + +/** + * @name: FDdmaSetChanTimeout + * @msg: 设置通道超时 + * @return {*} + * @param {uintptr} base_addr, DDMA控制器基地址 + * @param {u32} chan, DDMA通道号 + * @param {u32} timeout, 超时设置,0表示不启用超时 + */ +void FDdmaSetChanTimeout(uintptr base_addr, u32 chan, u32 timeout) +{ + FASSERT_MSG((FDDMA_NUM_OF_CHAN > chan), "chan %d not support", chan); + u32 reg_val = FDdmaReadReg(base_addr, FDDMA_CHAN_TIMEOUT_CNT_OFFSET(chan)); + + if (0 < timeout) + { + reg_val &= ~FDDMA_CHAN_TIMEOUT_CNT_MASK; + reg_val |= FDDMA_CHAN_TIMEOUT_CNT_SET(timeout); + reg_val |= FDDMA_CHAN_TIMEOUT_EN; + } + else + { + reg_val &= ~FDDMA_CHAN_TIMEOUT_EN; + } + + FDdmaWriteReg(base_addr, FDDMA_CHAN_TIMEOUT_CNT_OFFSET(chan), reg_val); + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_hw.h b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_hw.h new file mode 100644 index 0000000000..2334abd184 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_hw.h @@ -0,0 +1,223 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:52 + * Description:  This files is for register definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +#ifndef DRIVERS_FDDMA_HW_H +#define DRIVERS_FDDMA_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fassert.h" +#include "ftypes.h" +#include "fio.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ +/** @name Register Map + * + * Register offsets from the base address of an GPIO device. + * @{ + */ +#define FDDMA_CTL_OFFSET 0x0 /* 全局控制类寄存器 */ +#define FDDMA_CHAN_0_3_CFG_OFFSET 0x4 /* DMA通道0~3选择配置寄存器 */ +#define FDDMA_STA_OFFSET 0x8 /* 中断状态寄存器 */ +#define FDDMA_MASK_INTR_OFFSET 0xC /* 中断掩码寄存器 */ +/* AXI读写相关的配置硬件暂未开放 */ +#define FDDMA_UP_AXI_AW_CFG_OFFSET 0x10 /* 上行AXI写通道配置寄存器 */ +#define FDDMA_UP_AXI_AR_CFG_OFFSET 0x14 /* 上行AXI读通道配置寄存器 */ +#define FDDMA_DOWN_AXI_AW_CFG_OFFSET 0x18 /* 下行AXI写通道配置寄存器 */ +#define FDDMA_DOWN_AXI_AR_CFG_OFFSET 0x1C /* 下行AXI读通道配置寄存器 */ + +#define FDDMA_CHAN_BIND_OFFSET 0x20 /* DMA通道绑定寄存器 */ +#define FDDMA_GCAP_OFFSET 0x24 /* DMA通道数寄存器(只读) */ +#define FDDMA_CHAN_4_7_CFG_OFFSET 0x28 /* DMA通道4~7选择配置寄存器 */ + +#define FDDMA_CHAN_OFFSET(chan) (0x40 * (chan)) +#define FDDMA_CHAN_DDR_UP_ADDR_OFFSET(chan) (0x40 + FDDMA_CHAN_OFFSET(chan)) /* 内存中源/目的地址高32位 */ +#define FDDMA_CHAN_DDR_LOW_ADDR_OFFSET(chan) (0x44 + FDDMA_CHAN_OFFSET(chan)) /* 内存中源/目的地址低32位 */ +#define FDDMA_CHAN_DEV_ADDR_OFFSET(chan) (0x48 + FDDMA_CHAN_OFFSET(chan)) /* 设备中源/目的地址32位 */ +#define FDDMA_CHAN_TS_OFFSET(chan) (0x4C + FDDMA_CHAN_OFFSET(chan)) /* 需要传输的总数据字节数 */ +#define FDDMA_CHAN_CRT_UP_ADDR_OFFSET(chan) (0x50 + FDDMA_CHAN_OFFSET(chan)) /* 当前内存需要读写数据的高32位 */ +#define FDDMA_CHAN_CRT_LOW_ADDR_OFFSET(chan) (0x54 + FDDMA_CHAN_OFFSET(chan)) /* 当前内存需要读写数据的低32位 */ +#define FDDMA_CHAN_CTL_OFFSET(chan) (0x58 + FDDMA_CHAN_OFFSET(chan)) /* 通道控制寄存器 */ +#define FDDMA_CHAN_STS_OFFSET(chan) (0x5C + FDDMA_CHAN_OFFSET(chan)) /* 通道状态寄存器 */ +#define FDDMA_CHAN_TIMEOUT_CNT_OFFSET(chan) (0x60 + FDDMA_CHAN_OFFSET(chan)) /* 超时等待阈值 */ + +/** @name FDDMA_CTL_OFFSET Register + */ +#define FDDMA_CTL_SRST BIT(1) /* 1: 全局软复位 */ +#define FDDMA_CTL_ENABLE BIT(0) /* 1: 全局使能控制 */ + +/** @name FDDMA_CHAN_0_3_CFG_OFFSET Register + */ +#define FDDMA_CHAN_0_3_SEL_EN(chan) BIT((chan) * 8 + 7) /* 1: 通道chan信号源选择有效 */ +#define FDDMA_CHAN_0_3_SEL(chan, sel) ((sel) << ((chan) * 8)) /* 通道chan信号源选择sel项 */ +#define FDDMA_CHAN_0_3_SEL_MASK(chan) (GENMASK(7, 0) << ((chan) * 8)) + +/** @name FDDMA_STA_OFFSET Register + */ +#define FDDMA_STA_CHAN_REQ_DONE(chan) BIT((chan) * 4) /* 通道chan的block请求完成时置1,写1后清0 */ + +/** @name FDDMA_MASK_INTR_OFFSET Register + */ +#define FDDMA_MASK_EN_GLOBAL_INTR BIT(31) /* 全局中断使能输出控制位 */ +#define FDDMA_MASK_EN_CHAN_INTR(chan) BIT(chan) /* 通道chan的中断输出控制位 */ + +/** @name FDDMA_CHAN_BIND_OFFSET Register + */ +#define FDDMA_CHAN_BIND(chan) BIT(chan) /* 1: 通道已绑定了外设DMA请求信号线 */ + +/** @name FDDMA_CHAN_4_7_CFG_OFFSET Register + */ +#define FDDMA_CHAN_4_7_SEL_EN(chan) BIT(((chan) - 4) * 8 + 7) /* 1: 通道chan信号源选择有效 */ +#define FDDMA_CHAN_4_7_SEL(chan, sel) ((sel) << (((chan) - 4) * 8)) /* 通道chan信号源选择sel项 */ +#define FDDMA_CHAN_4_7_SEL_MASK(chan) (GENMASK(7, 0) << (((chan) - 4) * 8)) + +/** @name FDDMA_CHAN_CTL_OFFSET Register + */ +#define FDDMA_CHAN_CTL_RX_MODE BIT(2) /* 1:接收外设 dma_rx_req, 0:接收外设 dma_tx_req */ +#define FDDMA_CHAN_CTL_SRST BIT(1) /* 1: 复位通道 */ +#define FDDMA_CHAN_CTL_EN BIT(0) /* 1: 使能通道 */ + +/** @name FDDMA_CHAN_STS_OFFSET Register + */ +#define FDDMA_CHAN_STS_FIFO_EMPTY BIT(1) /* 1: FIFO空状态 */ +#define FDDMA_CHAN_STS_FIFO_FULL BIT(0) /* 1: FIFO满状态 */ + +/** @name FDDMA_CHAN_TIMEOUT_CNT_OFFSET Register + */ +#define FDDMA_CHAN_TIMEOUT_EN BIT(32) /* 1: 使能超时机制 */ +#define FDDMA_CHAN_TIMEOUT_CNT_SET(cnt) SET_REG32_BITS((cnt), 27, 0) /* 超时阈值 */ +#define FDDMA_CHAN_TIMEOUT_CNT_MASK GENMASK(27, 0) +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +/** + * @name: FDdmaReadReg + * @msg: 读DDMA寄存器 + * @return {u32} 获取的寄存器值 + * @param {uintptr} base_addr, DDMA寄存器基地址 + * @param {u32} reg_off, DDMA寄存器偏移量 + */ +static inline u32 FDdmaReadReg(uintptr base_addr, u32 reg_off) +{ + return FtIn32(base_addr + reg_off); +} + +/** + * @name: FDdmaWriteReg + * @msg: 写DDMA寄存器 + * @return {无} + * @param {uintptr} base_addr, DDMA寄存器基地址 + * @param {u32} reg_off, DDMA寄存器偏移量 + * @param {u32} reg_val, 设置的寄存器值 + */ +static inline void FDdmaWriteReg(uintptr base_addr, u32 reg_off, u32 reg_val) +{ + FtOut32(base_addr + reg_off, reg_val); + return; +} + +/** + * @name: FDdmaReadStatus + * @msg: 获取DDMA中断状态 + * @return {u32} 中断状态 + * @param {uintptr} base_addr, DDMA寄存器基地址 + */ +static inline u32 FDdmaReadStatus(uintptr base_addr) +{ + return FDdmaReadReg(base_addr, FDDMA_STA_OFFSET); +} + +/** + * @name: FDdmaReadChanStatus + * @msg: 获取DDMA通道中断状态 + * @return {u32} 中断状态 + * @param {uintptr} base_addr, DDMA寄存器基地址 + * @param {u32} chan, DDMA通道号 + */ +static inline u32 FDdmaReadChanStatus(uintptr base_addr, u32 chan) +{ + return FDdmaReadReg(base_addr, FDDMA_CHAN_STS_OFFSET(chan)); +} + +/************************** Function Prototypes ******************************/ +/* 复位DDMA控制器 */ +void FDdmaSoftwareReset(uintptr base_addr); + +/* 去使能DDMA控制器 */ +void FDdmaDisable(uintptr base_addr); + +/* 使能DDMA控制器 */ +void FDdmaEnable(uintptr base_addr); + +/* 重置DDMA通道 */ +void FDdmaResetChan(uintptr base_addr, u32 chan); + +/* 去使能DDMA通道 */ +FError FDdmaDisableChan(uintptr base_addr, u32 chan); + +/* 使能DDMA通道 */ +void FDdmaEnableChan(uintptr base_addr, u32 chan); + +/* 关闭DDMA全局中断 */ +void FDdmaDisableGlobalIrq(uintptr base_addr); + +/* 打开DDMA全局中断 */ +void FDdmaEnableGlobalIrq(uintptr base_addr); + +/* 关闭DDMA通道中断 */ +void FDdmaDisableChanIrq(uintptr base_addr, u32 chan); + +/* 打开DDMA通道中断 */ +void FDdmaEnableChanIrq(uintptr base_addr, u32 chan); + +/* 清除DDMA通道中断状态 */ +void FDdmaClearChanIrq(uintptr base_addr, u32 chan); + +/* 检查通道是否在工作中 */ +boolean FDdmaIsChanRunning(uintptr base_addr, u32 chan); + +/* 将DDMA通道与外设绑定 */ +void FDdmaSetChanSelection(uintptr base_addr, u32 chan, u32 slave_id); + +/* 修改通道的绑定状态 */ +void FDdmaSetChanBind(uintptr base_addr, u32 chan, boolean bind); + +/* 设置通道的方向 */ +void FDdmaSetChanDirection(uintptr base_addr, u32 chan, boolean is_rx); + +/* 设置通道超时 */ +void FDdmaSetChanTimeout(uintptr base_addr, u32 chan, u32 timeout); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_intr.c b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_intr.c new file mode 100644 index 0000000000..c71ba37018 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_intr.c @@ -0,0 +1,141 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:47 + * Description:  This files is for ddma interrupt implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +/***************************** Include Files *********************************/ +#include + +#include "fkernel.h" +#include "fparameters.h" +#include "fassert.h" +#include "fdebug.h" + +#include "fddma_hw.h" +#include "fddma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FDDMA_DEBUG_TAG "DDMA-INTR" +#define FDDMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_WARN(format, ...) FT_DEBUG_PRINT_W(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_INFO(format, ...) FT_DEBUG_PRINT_I(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FDDMA_CALL_EVT_HANDLER(express, dma_chan, args) \ + if (express) \ + { \ + express(dma_chan, args); \ + } + +/************************** Function Prototypes ******************************/ + +/****************************************************************************/ +/** + * @name: FDdmaChanIrqHandler + * @msg: DDMA通道中断处理函数 + * @return {*} + * @param {FDdma} *instance, DDMA实例 + * @param {FDdmaChanIndex} chan_idx, DDMA通道号 + */ +static void FDdmaChanIrqHandler(FDdma *const instance, FDdmaChanIndex chan_idx) +{ + FASSERT(instance && instance->chan[chan_idx]); + FDdmaChan *const dma_chan = instance->chan[chan_idx]; + uintptr base_addr = instance->config.base_addr; + u32 status = FDdmaReadChanStatus(base_addr, chan_idx); + + FDDMA_INFO("chan-%d irq status: 0x%x", chan_idx, status); + + FDDMA_CALL_EVT_HANDLER(dma_chan->evt_handler[FDDMA_CHAN_EVT_REQ_DONE], dma_chan, + dma_chan->evt_handler_args[FDDMA_CHAN_EVT_REQ_DONE]); + + if (FDDMA_CHAN_STS_FIFO_EMPTY & status) + { + FDDMA_CALL_EVT_HANDLER(dma_chan->evt_handler[FDDMA_CHAN_EVT_FIFO_EMPTY], dma_chan, + dma_chan->evt_handler_args[FDDMA_CHAN_EVT_FIFO_EMPTY]); + } + + if (FDDMA_CHAN_STS_FIFO_FULL & status) + { + FDDMA_CALL_EVT_HANDLER(dma_chan->evt_handler[FDDMA_CHAN_EVT_FIFO_FULL], dma_chan, + dma_chan->evt_handler_args[FDDMA_CHAN_EVT_FIFO_FULL]); + } + + /* submit queued descriptor after processing the completed ones */ + return; +} + +/** + * @name: FDdmaIrqHandler + * @msg: DDMA中断处理函数 + * @return {无} + * @param {s32} vector + * @param {void} *param, 输入参数 + */ +void FDdmaIrqHandler(s32 vector, void *args) +{ + FASSERT(NULL != args); + FDdma *const instance = (FDdma * const)args; + uintptr base_addr = instance->config.base_addr; + u32 status = FDdmaReadStatus(base_addr); + u32 chan; + + FDDMA_INFO("ddma irq 0x%x", status); + FDdmaDisableGlobalIrq(base_addr); /* disable interrupt from occur again */ + + /* poll, clear and process every chanel interrupt status */ + for (chan = FDDMA_CHAN_0; chan < FDDMA_NUM_OF_CHAN; chan++) + { + if (0 == (FDDMA_STA_CHAN_REQ_DONE(chan) & status)) + continue; + + FDDMA_INFO("handle chan %d", chan); + FDdmaClearChanIrq(base_addr, chan); /* clear interrupt status */ + FDdmaChanIrqHandler(instance, chan); /* channel interrupt handle */ + } + + FDdmaEnableGlobalIrq(base_addr); /* re-enable interrupt */ + return; +} + +/** + * @name: FDdmaRegisterChanEvtHandler + * @msg: 注册DDMA通道中断响应事件函数 + * @return {无} + * @param {FDdmaChan} *dma_chan, DDMA通道 + * @param {FDdmaChanEvt} evt, 中断事件 + * @param {FDdmaChanEvtHandler} handler, 中断响应事件函数 + * @param {void} *handler_arg, 中断响应事件函数输入参数 + */ +void FDdmaRegisterChanEvtHandler(FDdmaChan *const dma_chan, FDdmaChanEvt evt, FDdmaChanEvtHandler handler, void *handler_arg) +{ + FASSERT(dma_chan); + dma_chan->evt_handler[evt] = handler; + dma_chan->evt_handler_args[evt] = handler_arg; + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_selftest.c b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_selftest.c new file mode 100644 index 0000000000..dfe9dea6a5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_selftest.c @@ -0,0 +1,85 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma_selftest.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:47 + * Description:  This files is for ddma self test + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +/***************************** Include Files *********************************/ +#include + +#include "fkernel.h" +#include "fparameters.h" +#include "fassert.h" +#include "fdebug.h" + +#include "fddma_hw.h" +#include "fddma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FDDMA_DEBUG_TAG "DDMA-TEST" +#define FDDMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_WARN(format, ...) FT_DEBUG_PRINT_W(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_INFO(format, ...) FT_DEBUG_PRINT_I(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FDDMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FDDMA_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FDDMA_DUMPER(base_addr, reg_off, reg_name) \ + FDDMA_DEBUG("\t\t[%s]@0x%x\t=\t0x%x", reg_name, (reg_off), FDdmaReadReg((base_addr), (reg_off))) +/************************** Function Prototypes ******************************/ + +/****************************************************************************/ + + +void FDdmaDumpRegisters(uintptr base_addr) +{ + FDDMA_DEBUG("ddma@0x%x", base_addr); + FDDMA_DUMPER(base_addr, FDDMA_CTL_OFFSET, "ctl"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_0_3_CFG_OFFSET, "chan_0_3"); + FDDMA_DUMPER(base_addr, FDDMA_STA_OFFSET, "sta"); + FDDMA_DUMPER(base_addr, FDDMA_MASK_INTR_OFFSET, "mask_intr"); + FDDMA_DUMPER(base_addr, FDDMA_UP_AXI_AW_CFG_OFFSET, "up_axi_aw"); + FDDMA_DUMPER(base_addr, FDDMA_UP_AXI_AR_CFG_OFFSET, "up_axi_ar"); + FDDMA_DUMPER(base_addr, FDDMA_DOWN_AXI_AW_CFG_OFFSET, "dw_axi_aw"); + FDDMA_DUMPER(base_addr, FDDMA_DOWN_AXI_AR_CFG_OFFSET, "dw_axi_ar"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_BIND_OFFSET, "chan_bind"); + FDDMA_DUMPER(base_addr, FDDMA_GCAP_OFFSET, "gcap"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_4_7_CFG_OFFSET, "chan_4_7"); +} + +void FDdmaDumpChanRegisters(uintptr base_addr, FDdmaChanIndex chan) +{ + FDDMA_DEBUG("\tchan-%d", chan); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_DDR_UP_ADDR_OFFSET(chan), "ddr_up"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_DDR_LOW_ADDR_OFFSET(chan), "ddr_low"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_DEV_ADDR_OFFSET(chan), "dev"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_TS_OFFSET(chan), "ts"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_CRT_UP_ADDR_OFFSET(chan), "crt_up"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_CRT_LOW_ADDR_OFFSET(chan), "crt_low"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_CTL_OFFSET(chan), "ctl"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_STS_OFFSET(chan), "sts"); + FDDMA_DUMPER(base_addr, FDDMA_CHAN_TIMEOUT_CNT_OFFSET(chan), "cnt"); +} + diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_sinit.c b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_sinit.c new file mode 100644 index 0000000000..0a7ad7f430 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fddma/fddma_sinit.c @@ -0,0 +1,63 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fddma_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:47 + * Description:  This files is for static initialization + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/5/13 init commit + */ + +/***************************** Include Files *********************************/ +#include "fparameters.h" +#include "fassert.h" + +#include "fddma_hw.h" +#include "fddma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ +extern const FDdmaConfig fddma_cfg_tbl[FDDMA_INSTANCE_NUM]; + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/** + * @name: FDdmaLookupConfig + * @msg: 获取DDMA实例默认配置 + * @return {const FDdmaConfig *} DDMA控制器默认配置 + * @param {u32} instance_id, DDMA实例号 + */ +const FDdmaConfig *FDdmaLookupConfig(u32 instance_id) +{ + const FDdmaConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FDDMA_INSTANCE_NUM; index++) + { + if (fddma_cfg_tbl[index].id == instance_id) + { + ptr = &fddma_cfg_tbl[index]; + break; + } + } + + return (const FDdmaConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma.c b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma.c new file mode 100644 index 0000000000..f43a56bd27 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma.c @@ -0,0 +1,652 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgdma.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021-11-5 init commit + * 1.1 zhugengyu 2022-5-16 support chan alloc. and qos setting + */ + + +/***************************** Include Files *********************************/ +#include + +#include "fdebug.h" + +#include "fgdma_hw.h" +#include "fgdma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGDMA_DEBUG_TAG "GDMA" +#define FGDMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_WARN(format, ...) FT_DEBUG_PRINT_W(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_INFO(format, ...) FT_DEBUG_PRINT_I(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +static void FGdmaReset(FGdma *const instance_p); + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/** + * @name: FGdmaCfgInitialize + * @msg: 初始化GDMA控制器实例 + * @return {FError} 返回FGDMA_SUCCESS表示初始化成功,返回其它表示失败 + * @param FGdma *const instance_p, GDMA控制器实例 + * @param const FGdmaConfig *input_config, GDMA控制器配置 + */ +FError FGdmaCfgInitialize(FGdma *const instance_p, const FGdmaConfig *input_config) +{ + FASSERT(instance_p && input_config); + uintptr base_addr = input_config->base_addr; + FError ret = FGDMA_SUCCESS; + + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FGDMA_WARN("device is already initialized!!!"); + } + + FGdmaDeInitialize(instance_p); + + if (&instance_p->config != input_config) + instance_p->config = *input_config; + + FASSERT_MSG((0 != base_addr), "invalid device base address"); + FGdmaReset(instance_p); + + if (FGDMA_SUCCESS == ret) + { + instance_p->is_ready = FT_COMPONENT_IS_READY; + } + + return ret; +} + +/** + * @name: FGdmaDeInitialize + * @msg: 去初始化GDMA控制器实例 + * @return {void} 无 + * @param FGdma *const instance_p, GDMA控制器实例 + */ +void FGdmaDeInitialize(FGdma *const instance_p) +{ + FASSERT(instance_p); + u32 chan; + + for (chan = FGDMA_CHAN0_INDEX; chan < FGDMA_NUM_OF_CHAN; chan++) + { + if (NULL != instance_p->chans[chan]) + { + FGDMA_WARN("chan-%d might be in use !!!", chan); + } + } + + memset(instance_p, 0, sizeof(*instance_p)); + return; +} + +/** + * @name: FGdmaSetChanQos + * @msg: 设置GDMA通道的Qos配置 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {FGdmaChan} *dma_chan, GDMA通道实例 + */ +static void FGdmaSetChanQos(uintptr base_addr, FGdmaChan *const dma_chan) +{ + FASSERT(dma_chan); + FGdmaChanIndex chan_id = dma_chan->config.chan_id; + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_CHX_MODE_OFFSET(chan_id)); + FGdmaOperPriority prev_rd_qos = FGDMA_CHX_MODE_RD_QOS_GET(reg_val); + FGdmaOperPriority prev_wr_qos = FGDMA_CHX_MODE_WR_QOS_GET(reg_val); + + FGDMA_INFO("prev rd qos: 0x%x, set rd qos: 0x%x", prev_rd_qos, dma_chan->config.rd_qos); + FGDMA_INFO("prev wr qos: 0x%x, set wr qos: 0x%x", prev_wr_qos, dma_chan->config.wr_qos); + + if (prev_rd_qos != dma_chan->config.rd_qos) /* need to update rd qos */ + { + /* replace with new rd qos config */ + reg_val &= ~FGDMA_CHX_MODE_RD_QOS_MASK; + reg_val |= FGDMA_CHX_MODE_RD_QOS_EN | + FGDMA_CHX_MODE_RD_QOS_SET(dma_chan->config.rd_qos); + } + + if (prev_wr_qos != dma_chan->config.wr_qos) /* need to update wr qos */ + { + /* replace with new wr qos config */ + reg_val &= ~FGDMA_CHX_MODE_WR_QOS_MASK; + reg_val |= FGDMA_CHX_MODE_WR_QOS_EN | + FGDMA_CHX_MODE_WR_QOS_SET(dma_chan->config.wr_qos); + } + + FGDMA_WRITEREG(base_addr, FGDMA_CHX_MODE_OFFSET(chan_id), reg_val); + return; +} + +/** + * @name: FGdmaAllocateChan + * @msg: 分配指定GDMA通道 + * @return {FError} FGDMA_SUCCESS表示分配成功,返回其它值表示分配失败 + * @param FGdma *const instance_p, GDMA控制器实例 + * @param FGdmaChan *const dma_chan, GDMA通道实例 + * @param const FGdmaChanConfig *dma_chan_config, GDMA通道配置 + */ +FError FGdmaAllocateChan(FGdma *const instance_p, FGdmaChan *const dma_chan, + const FGdmaChanConfig *dma_chan_config) +{ + FASSERT(instance_p); + FASSERT(dma_chan); + FASSERT(dma_chan_config); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGDMA_SUCCESS; + FGdmaChanIndex chan_idx = dma_chan_config->chan_id; + u32 reg_val; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGDMA_ERROR("dma instance not init !!!"); + return FGDMA_ERR_NOT_INIT; + } + + if (NULL != instance_p->chans[chan_idx]) + { + FGDMA_ERROR("chan %d is in use !!!", chan_idx); + return FGDMA_ERR_CHAN_IN_USE; + } + + if (&dma_chan->config != dma_chan_config) + dma_chan->config = *dma_chan_config; + + /* disable and reset chan */ + FGdmaChanDisable(base_addr, chan_idx); + FGdmaChanReset(base_addr, chan_idx); + + /* enable channel clock */ + FGdmaSetChanClock(base_addr, chan_idx, TRUE); + + /* set chan mode */ + reg_val = FGDMA_READREG(base_addr, FGDMA_CHX_MODE_OFFSET(chan_idx)); + if (FGDMA_OPER_BDL == dma_chan->config.trans_mode) + { + FGDMA_INFO("set as BDL mode"); + reg_val |= FGDMA_CHX_MODE_BDL_EN; + + if (dma_chan->config.roll_back) + { + reg_val |= FGDMA_CHX_MODE_BDL_ROLL_EN; /* run BDL in roll-back mode */ + } + else + { + reg_val &= ~FGDMA_CHX_MODE_BDL_ROLL_EN; + } + } + else + { + FGDMA_INFO("set as Direct mode"); + reg_val &= ~FGDMA_CHX_MODE_BDL_EN; + reg_val &= ~FGDMA_CHX_MODE_BDL_ROLL_EN; + } + FGDMA_WRITEREG(base_addr, FGDMA_CHX_MODE_OFFSET(chan_idx), reg_val); + + FGdmaSetChanQos(base_addr, dma_chan); + FGDMA_INFO("mode: 0x%x", FGDMA_READREG(base_addr, FGDMA_CHX_MODE_OFFSET(chan_idx))); + + /* set xfer config */ + reg_val = 0; + reg_val |= FGDMA_CHX_XFER_CFG_AR_LEN_SET(FGDMA_MAX_BURST_LEN) | /* burst length configed as max 8, which adapted when trans bytes less than 8 */ + FGDMA_CHX_XFER_CFG_AR_SIZE_SET((u32)dma_chan->config.rd_align) | + FGDMA_CHX_XFER_CFG_AR_BRUST_SET(FGDMA_INCR); /* mem to mem trans work in incr mode */ + + reg_val |= FGDMA_CHX_XFER_CFG_AW_LEN_SET(FGDMA_MAX_BURST_LEN) | + FGDMA_CHX_XFER_CFG_AW_SIZE_SET((u32)dma_chan->config.wr_align) | + FGDMA_CHX_XFER_CFG_AW_BRUST_SET(FGDMA_INCR); /* mem to mem trans work in incr mode */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_XFER_CFG_OFFSET(chan_idx), reg_val); + FGDMA_INFO("xfer cfg: 0x%x", FGDMA_READREG(base_addr, FGDMA_CHX_XFER_CFG_OFFSET(chan_idx))); + + instance_p->chans[chan_idx] = dma_chan; + dma_chan->gdma = instance_p; + + return ret; +} + +/** + * @name: FGdmaDellocateChan + * @msg: 释放GDMA通道 + * @return {FError} FGDMA_SUCCESS表示处理成功 + * @param FGdmaChan *const dma_chan, GDMA通道实例 + */ +FError FGdmaDellocateChan(FGdmaChan *const dma_chan) +{ + FASSERT(dma_chan); + FASSERT(dma_chan->gdma); + FGdma *const instance_p = dma_chan->gdma; + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGDMA_SUCCESS; + FGdmaChanIndex chan_idx = dma_chan->config.chan_id; + u32 reg_val; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGDMA_ERROR("dma instance not init !!!"); + return FGDMA_ERR_NOT_INIT; + } + + if (dma_chan != instance_p->chans[chan_idx]) + { + FGDMA_ERROR("chan %d not bind !!!", chan_idx); + return FGDMA_ERR_CHAN_NOT_INIT; + } + + /* disable chan and it irq */ + FGdmaChanIrqDisable(base_addr, chan_idx); + FGdmaChanDisable(base_addr, chan_idx); + + /* disable channel clock */ + FGdmaSetChanClock(base_addr, chan_idx, FALSE); + + instance_p->chans[chan_idx] = NULL; + memset(dma_chan, 0, sizeof(*dma_chan)); + + return ret; +} + +/** + * @name: FGdmaDirectTransfer + * @msg: 直接操作模式下发起DMA传输 + * @return {FError} FGDMA_SUCCESS表示传输成功 + * @param FGdmaChan *const chan_p, GDMA通道实例 + * @param uintptr src_addr, 传输源地址 + * @param uintptr dst_addr, 传输目的地址 + */ +FError FGdmaDirectTransfer(FGdmaChan *const chan_p, uintptr src_addr, uintptr dst_addr, fsize_t data_len) +{ + FASSERT(chan_p); + FASSERT(chan_p->gdma); + u32 reg_val; + FGdma *const instance_p = chan_p->gdma; + uintptr base_addr = instance_p->config.base_addr; + FGdmaChanIndex chan_idx = chan_p->config.chan_id; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGDMA_ERROR("dma instance not init !!!"); + return FGDMA_ERR_NOT_INIT; + } + + if ((src_addr % FGDMA_GET_BURST_SIZE(chan_p->config.rd_align)) || + (dst_addr % FGDMA_GET_BURST_SIZE(chan_p->config.wr_align))) + { + FGDMA_ERROR("src addr 0x%x or dst addr 0x%x not aligned with %d bytes", + src_addr, dst_addr, FGDMA_ADDR_ALIGMENT); + return FGDMA_ERR_INVALID_ADDR; + } + + if (0 != (data_len % chan_p->config.wr_align)) + { + FGDMA_ERROR("data length %d must be N times of burst size %d !!!", + data_len, chan_p->config.wr_align); + return FGDMA_ERR_INVALID_SIZE; + } + + /* src address */ +#ifdef __aarch64__ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_UPSADDR_OFFSET(chan_idx), UPPER_32_BITS(src_addr)); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LWSADDR_OFFSET(chan_idx), LOWER_32_BITS(src_addr)); +#else + FGDMA_WRITEREG(base_addr, FGDMA_CHX_UPSADDR_OFFSET(chan_idx), 0x0U); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LWSADDR_OFFSET(chan_idx), (u32)(src_addr)); +#endif + + FGDMA_INFO("src: 0x%x-0x%x", + FGDMA_READREG(base_addr, FGDMA_CHX_UPSADDR_OFFSET(chan_idx)), + FGDMA_READREG(base_addr, FGDMA_CHX_LWSADDR_OFFSET(chan_idx))); + + /* dest address */ +#ifdef __aarch64__ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_UPDADDR_OFFSET(chan_idx), UPPER_32_BITS(dst_addr)); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LWDADDR_OFFSET(chan_idx), LOWER_32_BITS(dst_addr)); +#else + FGDMA_WRITEREG(base_addr, FGDMA_CHX_UPDADDR_OFFSET(chan_idx), 0x0U); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LWDADDR_OFFSET(chan_idx), (u32)(dst_addr)); +#endif + + FGDMA_INFO("dst: 0x%x-0x%x", + FGDMA_READREG(base_addr, FGDMA_CHX_UPDADDR_OFFSET(chan_idx)), + FGDMA_READREG(base_addr, FGDMA_CHX_LWDADDR_OFFSET(chan_idx))); + + /* num of BDL entry not used in direct mode */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LVI_OFFSET(chan_idx), 0x0U); + + /* length of data to transfer */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_TS_OFFSET(chan_idx), data_len); + + FGDMA_INFO("ts: 0x%x", FGDMA_READREG(base_addr, FGDMA_CHX_TS_OFFSET(chan_idx))); + + /* enable channel interrupt */ + FGdmaChanIrqEnable(base_addr, chan_idx, FGDMA_CHX_INT_CTRL_TRANS_END_ENABLE); + + /* enable channel and start transfer */ + FGdmaChanEnable(base_addr, chan_idx); + + return FGDMA_SUCCESS; +} + +/** + * @name: FGdmaSetupBDLEntry + * @msg: 设置BDL描述符的一个条目 + * @return {FError} FGDMA_SUCCESS 表示设置成功 + * @param FGdmaBdlDesc *desc_entry, 一条BDL描述符 + * @param uintptr src_addr, 传输源地址 + * @param uintptr dst_addr, 传输目的地址 + * @param fsize_t data_len, 传输数据长度 + */ +FError FGdmaAppendBDLEntry(FGdmaChan *const chan_p, uintptr src_addr, uintptr dst_addr, fsize_t data_len) +{ + FASSERT(chan_p); + FASSERT_MSG((chan_p->config.descs) && (chan_p->config.total_desc_num > 0), "BDL descriptor list not yet assign !!!"); + u32 desc_idx = chan_p->config.valid_desc_num; + FGdmaBdlDesc *desc_entry = &(chan_p->config.descs[desc_idx]); + + if (chan_p->config.valid_desc_num >= chan_p->config.total_desc_num) + { + FGDMA_ERROR("total BDL descriptor num is %d, already used up", chan_p->config.total_desc_num); + return FGDMA_ERR_BDL_NOT_ENOUGH; + } + + if ((0U != (dst_addr % FGDMA_GET_BURST_SIZE(chan_p->config.wr_align))) || + (0U != (src_addr % FGDMA_GET_BURST_SIZE(chan_p->config.rd_align)))) + { + FGDMA_ERROR("src addr 0x%x or dst addr 0x%x not aligned with %d bytes", + src_addr, dst_addr, FGDMA_GET_BURST_SIZE(chan_p->config.wr_align)); + return FGDMA_ERR_INVALID_ADDR; + } + + if (0U != (data_len % chan_p->config.wr_align)) + { + FGDMA_ERROR("data length %d must be N times of burst size %d !!!", + data_len, chan_p->config.wr_align); + return FGDMA_ERR_INVALID_SIZE; + } + +#ifdef __aarch64___ + desc_entry->src_addr_h = UPPER_32_BITS(src_addr); + desc_entry->src_addr_l = LOWER_32_BITS(src_addr); + desc_entry->dst_addr_h = UPPER_32_BITS(dst_addr); + desc_entry->dst_addr_l = LOWER_32_BITS(dst_addr); +#else + desc_entry->src_addr_h = 0U; + desc_entry->src_addr_l = src_addr; + desc_entry->dst_addr_h = 0U; + desc_entry->dst_addr_l = dst_addr; +#endif + + /* rd = src */ + desc_entry->src_tc = FGDMA_SRC_TC_BDL_BURST_SET(FGDMA_INCR) | + FGDMA_SRC_TC_BDL_SIZE_SET((u32)chan_p->config.rd_align) | + FGDMA_SRC_TC_BDL_LEN_SET(FGDMA_MAX_BURST_LEN); + + /* wr = dst */ + desc_entry->dst_tc = FGDMA_DST_TC_BDL_BURST_SET(FGDMA_INCR) | + FGDMA_DST_TC_BDL_SIZE_SET((u32)chan_p->config.wr_align) | + FGDMA_DST_TC_BDL_LEN_SET(FGDMA_MAX_BURST_LEN); + + desc_entry->total_bytes = data_len; + desc_entry->ioc = 0U; + + chan_p->config.valid_desc_num++; + + return FGDMA_SUCCESS; +} + +/** + * @name: FGdmaBDLTransfer + * @msg: BDL操作模式下发起DMA传输 + * @return {FError} FGDMA_SUCCESS 表示传输成功 + * @param FGdmaChan *const chan_p, DMA通道实例 + */ +FError FGdmaBDLTransfer(FGdmaChan *const chan_p) +{ + FASSERT(chan_p); + FASSERT(chan_p->gdma); + FASSERT_MSG((chan_p->config.descs) && (chan_p->config.total_desc_num > 0), "BDL descriptor list not yet assign !!!"); + u32 reg_val; + FGdma *const instance_p = chan_p->gdma; + uintptr base_addr = instance_p->config.base_addr; + FGdmaChanIndex chan_idx = chan_p->config.chan_id; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGDMA_ERROR("dma instance not init !!!"); + return FGDMA_ERR_NOT_INIT; + } + + if (0 == chan_p->config.valid_desc_num) + { + FGDMA_WARN("need to assign BDL entry fisrt !!!"); + return FGDMA_SUCCESS; + } + + if (((uintptr)(void *)chan_p->config.descs) % FGDMA_ADDR_ALIGMENT) + { + FGDMA_ERROR("BDL addr %p not aligned with %d bytes", chan_p->config.descs, FGDMA_ADDR_ALIGMENT); + return FGDMA_ERR_INVALID_ADDR; + } + + u32 desc_idx = chan_p->config.valid_desc_num - 1; + FGdmaBdlDesc *descs = chan_p->config.descs; /* get the first BDL entry */ + + chan_p->config.descs[desc_idx].ioc = 1U; /* set as the last BDL entry */ + + /* src address, and dst address has been defined in BDL */ +#ifdef __aarch64__ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_UPSADDR_OFFSET(chan_idx), UPPER_32_BITS((uintptr)descs)); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LWSADDR_OFFSET(chan_idx), LOWER_32_BITS((uintptr)descs)); +#else + FGDMA_WRITEREG(base_addr, FGDMA_CHX_UPSADDR_OFFSET(chan_idx), 0x0U); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LWSADDR_OFFSET(chan_idx), (u32)((uintptr)descs)); +#endif + + /* dst address not used in BDL mode */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_UPDADDR_OFFSET(chan_idx), 0x0U); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LWDADDR_OFFSET(chan_idx), 0x0U); + + /* ts not used in BDL mode */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_TS_OFFSET(chan_idx), 0x0U); + + /* num of BDL entry */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_LVI_OFFSET(chan_idx), FGDMA_CHX_LVI_SET(chan_p->config.valid_desc_num)); + + /* enable channel interrupt */ + FGdmaChanIrqEnable(base_addr, chan_idx, FGDMA_CHX_INT_CTRL_TRANS_END_ENABLE); + + /* enable channel and start transfer */ + FGdmaChanEnable(base_addr, chan_idx); + + return FGDMA_SUCCESS; +} + +/** + * @name: FGdmaStart + * @msg: 使能启动GDMA控制器 + * @return {FError} FGDMA_SUCCESS表示启动成功 + * @param FGdma *const instance_p, GDMA控制器实例 + * @note: 先调用此函数,后调用FGdmaAllocateChan配置特定通道 + */ +FError FGdmaStart(FGdma *const instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGDMA_ERROR("dma instance not init !!!"); + return FGDMA_ERR_NOT_INIT; + } + + FGdmaIrqEnable(base_addr); + + reg_val = FGDMA_READREG(base_addr, FGDMA_CTL_OFFSET); + reg_val &= ~FGDMA_CTL_OT_MASK; + reg_val |= FGDMA_CTL_OT_SET(FGDMA_OUTSTANDING); /* 设置传输outstanding数 */ + reg_val |= FGDMA_CTL_ENABLE; /* 使能DMA传输 */ + FGDMA_WRITEREG(base_addr, FGDMA_CTL_OFFSET, reg_val); + + return FGDMA_SUCCESS; // 放到初始化 +} + +/** + * @name: FGdmaStop + * @msg: 停止GDMA控制器 + * @return {FError} FGDMA_SUCCESS表示处理成功 + * @param FGdma *const instance_p, GDMA控制器实例 + */ +FError FGdmaStop(FGdma *const instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + u32 chan_id; + u32 chan_status; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGDMA_ERROR("dma instance not init !!!"); + return FGDMA_ERR_NOT_INIT; + } + + /* Abort 流程 */ + for (chan_id = FGDMA_CHAN0_INDEX; chan_id < FGDMA_NUM_OF_CHAN; chan_id++) + { + if (NULL == instance_p->chans[chan_id]) + continue; /* skip un-allocate channel */ + + chan_status = FGdmaReadChanStatus(base_addr, chan_id); + if (FGDMA_CHX_INT_STATE_BUSY & chan_status) + { + FGDMA_WARN("chan-%d has abort unfinished request !!!", chan_id); + FGdmaChanDisable(base_addr, chan_id); /* 关闭通道 */ + FGdmaChanReset(base_addr, chan_id); /* 需要进行软复位,否则再次使能通道时,仍然会执行之前的请求 */ + } + else + { + FGdmaChanDisable(base_addr, chan_id); /* 关闭通道 */ + } + + FGdmaClearChanStatus(base_addr, chan_id, chan_status); /* 清除通道状态 */ + } + + FGdmaDisable(base_addr); + + return FGDMA_SUCCESS; +} + +/** + * @name: FGdmaSetQos + * @msg: 设置GDMA控制器的全局Qos配置 + * @return {void} 无 + * @param {FGdma} *instance_p, GDMA控制器实例 + */ +static void FGdmaSetQos(FGdma *const instance_p) +{ + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + + /* enable/disable Qos */ + reg_val = FGDMA_READREG(base_addr, FGDMA_CTL_OFFSET); + if (FGDMA_OPER_NONE_PRIORITY_POLL == instance_p->config.rd_qos) /* Poll mode */ + { + reg_val &= ~FGDMA_CTL_RD_ARB; + } + else /* Qos mode */ + { + reg_val |= FGDMA_CTL_RD_ARB; + } + + if (FGDMA_OPER_NONE_PRIORITY_POLL == instance_p->config.wr_qos) /* Poll mode */ + { + reg_val &= ~FGDMA_CTL_WR_ARB; + } + else /* Qos mode */ + { + reg_val |= FGDMA_CTL_WR_ARB; + } + FGDMA_WRITEREG(base_addr, FGDMA_CTL_OFFSET, reg_val); + + /* set Qos configure */ + reg_val = FGDMA_READREG(base_addr, FGDMA_QOS_CFG_OFFSET); + if (FGDMA_OPER_NONE_PRIORITY_POLL == instance_p->config.rd_qos) /* Poll mode */ + { + reg_val &= ~FGDMA_QOS_CFG_ARGOS_MASK; + } + else /* Qos value */ + { + reg_val |= FGDMA_QOS_CFG_ARGOS_SET((u32)instance_p->config.rd_qos); + } + + if (FGDMA_OPER_NONE_PRIORITY_POLL == instance_p->config.wr_qos) /* Poll mode */ + { + reg_val &= ~FGDMA_QOS_CFG_AWQOS_MASK; + } + else /* Qos value */ + { + reg_val |= FGDMA_QOS_CFG_AWQOS_SET((u32)instance_p->config.wr_qos); + } + FGDMA_WRITEREG(base_addr, FGDMA_QOS_CFG_OFFSET, reg_val); + + return; +} + +/** + * @name: FGdmaReset + * @msg: 重置GDMA控制器 + * @return {void} 无 + * @param {FGdma} *instance_p, GDMA控制器实例 + */ +static void FGdmaReset(FGdma *const instance_p) +{ + uintptr base_addr = instance_p->config.base_addr; + u32 chan; + u32 reg_val; + + FGDMA_INFO("reset ctrl @0x%x ...", base_addr); + + FGdmaDisable(base_addr); + FGdmaSoftwareReset(base_addr); + + FGdmaSetQos(instance_p); + + FGDMA_INFO("reset chan ..."); + + for (chan = FGDMA_CHAN0_INDEX; chan < FGDMA_NUM_OF_CHAN; chan++) + { + FGdmaChanDisable(base_addr, chan); + FGdmaChanIrqDisable(base_addr, chan); + FGdmaChanReset(base_addr, chan); + FGdmaSetChanClock(base_addr, chan, FALSE); + } + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma.h b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma.h new file mode 100644 index 0000000000..0319af3618 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma.h @@ -0,0 +1,265 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgdma.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:35 + * Description:  This files is for gdma user api implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021-11-5 init commit + * 1.1 zhugengyu 2022-5-16 modify according to tech manual. + */ + +#ifndef DRIVERS_FGDMA_H +#define DRIVERS_FGDMA_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" +#include "ferror_code.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ +typedef enum +{ + FGDMA_CHAN0_INDEX = 0, + FGDMA_CHAN1_INDEX = 1, + FGDMA_CHAN2_INDEX = 2, + FGDMA_CHAN3_INDEX = 3, + FGDMA_CHAN4_INDEX = 4, + FGDMA_CHAN5_INDEX = 5, + FGDMA_CHAN6_INDEX = 6, + FGDMA_CHAN7_INDEX = 7, + FGDMA_CHAN8_INDEX = 8, + FGDMA_CHAN9_INDEX = 9, + FGDMA_CHAN10_INDEX = 10, + FGDMA_CHAN11_INDEX = 11, + FGDMA_CHAN12_INDEX = 12, + FGDMA_CHAN13_INDEX = 13, + FGDMA_CHAN14_INDEX = 14, + FGDMA_CHAN15_INDEX = 15, + + FGDMA_NUM_OF_CHAN +} FGdmaChanIndex; /* 16个独立通道, 0 ~ 15 */ + +typedef enum +{ + FGDMA_OPER_NONE_PRIORITY_POLL = -1, /* Priority = -1 表示读写请求仲裁模式为Poll */ + FGDMA_OPER_PRIORITY0 = 0, /* Priority >= 0 表示读写请求仲裁模式为Qos */ + FGDMA_OPER_PRIORITY1 = 1, + FGDMA_OPER_PRIORITY2 = 2, + FGDMA_OPER_PRIORITY3 = 3, + FGDMA_OPER_PRIORITY4 = 4, + FGDMA_OPER_PRIORITY5 = 5, + FGDMA_OPER_PRIORITY6 = 6, + FGDMA_OPER_PRIORITY7 = 7, + FGDMA_OPER_PRIORITY8 = 8, + FGDMA_OPER_PRIORITY9 = 9, + FGDMA_OPER_PRIORITY10 = 10, + FGDMA_OPER_PRIORITY11 = 11, + FGDMA_OPER_PRIORITY12 = 12, + FGDMA_OPER_PRIORITY13 = 13, + FGDMA_OPER_PRIORITY14 = 14, + FGDMA_OPER_PRIORITY15 = 15 +} FGdmaOperPriority; /* Qos配置,值越高,优先级越高 */ + +typedef enum +{ + FGDMA_OPER_DIRECT = 0, /* 直接操作模式 */ + FGDMA_OPER_BDL /* BDL操作模式 */ +} FGdmaOperMode; /* 支持的操作模式 */ + +typedef enum +{ + FGDMA_BURST_SIZE_1_BYTE = 0, + FGDMA_BURST_SIZE_2_BYTE = 1, + FGDMA_BURST_SIZE_4_BYTE = 2, + FGDMA_BURST_SIZE_8_BYTE = 3, + FGDMA_BURST_SIZE_16_BYTE = 4 +} FGdmaBurstSize; /* 支持的读写请求size大小 */ + +#define FGDMA_GET_BURST_SIZE(brust_align) (1U << brust_align) + +typedef enum +{ + FGDMA_CHAN_EVT_FIFO_EMPTY = 0, /* 通道Fifo空事件 */ + FGDMA_CHAN_EVT_FIFO_FULL, /* 通道Fifo满事件 */ + FGDMA_CHAN_EVT_BDL_END, /* BDL模式下一个BDL条目传输完成 */ + FGDMA_CHAN_EVT_TRANS_END, /* 所有传输数据完成 */ + FGDMA_CHAN_EVT_BUSY, /* 前一次传输未完成,当前还处于传输中 */ + + FGDMA_CHAN_NUM_OF_EVT +} FGdmaChanEvtType; /* 通道中断事件 */ + +#define FGDMA_SUCCESS FT_SUCCESS +#define FGDMA_ERR_NOT_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrGdma, 0) +#define FGDMA_ERR_CHAN_IN_USE FT_MAKE_ERRCODE(ErrModBsp, ErrGdma, 1) +#define FGDMA_ERR_CHAN_NOT_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrGdma, 2) +#define FGDMA_ERR_INVALID_ADDR FT_MAKE_ERRCODE(ErrModBsp, ErrGdma, 3) +#define FGDMA_ERR_INVALID_SIZE FT_MAKE_ERRCODE(ErrModBsp, ErrGdma, 4) +#define FGDMA_ERR_BDL_NOT_ENOUGH FT_MAKE_ERRCODE(ErrModBsp, ErrGdma, 5) + +#define FGDMA_ADDR_ALIGMENT 128U /* 直接模式和BDL模式的地址需要按128位对齐 */ + +/**************************** Type Definitions *******************************/ +typedef struct _FGdma FGdma; +typedef struct _FGdmaChan FGdmaChan; + +typedef struct +{ + u32 instance_id; /* GDMA控制器ID */ + u32 irq_num; /* GDMA控制器中断号 */ + u32 irq_prority; /* GDMA控制器中断优先级 */ + volatile uintptr_t base_addr; /* GDMA控制器基地址 */ + FGdmaOperPriority rd_qos; /* 读操作优先级 */ + FGdmaOperPriority wr_qos; /* 写操作优先级 */ +} FGdmaConfig; /* GDMA控制器配置 */ + +typedef struct +{ + u32 src_addr_l; /* 0x0, 数据源地址低32位 */ + u32 src_addr_h; /* 0x4, 数据源地址高32位 */ + u32 dst_addr_l; /* 0x8, 数据目的地址低32位 */ + u32 dst_addr_h; /* 0xc, 数据目的地址高32位 */ +#define FGDMA_SRC_TC_BDL_BURST_SET(x) SET_REG32_BITS((x), 1U, 0U) +#define FGDMA_SRC_TC_BDL_SIZE_SET(x) SET_REG32_BITS((x), 6U, 4U) +#define FGDMA_SRC_TC_BDL_LEN_SET(x) SET_REG32_BITS((x), 15U, 8U) + u32 src_tc; /* 0x10, 源传输控制位 */ +#define FGDMA_DST_TC_BDL_BURST_SET(x) SET_REG32_BITS((x), 1U, 0U) +#define FGDMA_DST_TC_BDL_SIZE_SET(x) SET_REG32_BITS((x), 6U, 4U) +#define FGDMA_DST_TC_BDL_LEN_SET(x) SET_REG32_BITS((x), 15U, 8U) + u32 dst_tc; /* 0x14, 目的传输控制 */ + u32 total_bytes;/* 0x18, 传输数据总量,以Byte为单位 */ + u32 ioc; /* 0x1c, 该条目传输完成中断产生控制位 */ +} __attribute__((__packed__)) FGdmaBdlDesc; /* BDL描述符 */ + +FASSERT_STATIC(0x20U == sizeof(FGdmaBdlDesc)); + +typedef struct +{ + FGdmaChanIndex chan_id; /* DMA通道ID */ + FGdmaOperPriority rd_qos; /* DMA通道读Qos配置 */ + FGdmaOperPriority wr_qos; /* DMA通道写Qos配置 */ + FGdmaOperMode trans_mode; /* DMA通道的操作模式,直接模式或者BDL模式 */ + /* Direct模式有效 */ + FGdmaBurstSize rd_align; /* DMA读请求的Burst对齐方式 */ + FGdmaBurstSize wr_align; /* DMA写请求的Burst对齐方式 */ + /* BDL模式有效 */ + boolean roll_back; /* 循环模式,TRUE: 当前BDL列表完成后,从第一个BDL项从新开始传输 */ + FGdmaBdlDesc *descs; + u32 total_desc_num; + u32 valid_desc_num; +} FGdmaChanConfig; /* DMA通道配置 */ + +typedef void (*FGdmaChanEvtHandler)(FGdmaChan *const chan, void *args); + +typedef struct _FGdmaChan +{ + FGdmaChanConfig config; /* DMA通道配置 */ + FGdma *gdma; /* DMA控制器实例 */ + FGdmaChanEvtHandler evt_handlers[FGDMA_CHAN_NUM_OF_EVT]; /* DMA通道事件回调函数 */ + void *evt_handler_args[FGDMA_CHAN_NUM_OF_EVT]; /* DMA通道事件回调函数入参 */ +} FGdmaChan; /* GDMA通道实例 */ + +typedef struct _FGdma +{ + FGdmaConfig config; /* GDMA控制器配置 */ + u32 is_ready; /* GDMA控制器初始化是否完成 */ + FGdmaChan *chans[FGDMA_NUM_OF_CHAN]; /* GDMA通道实例,如果通道没有分配,值为NULL */ +} FGdma; /* GDMA控制器实例 */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +/* 获取默认的通道配置 */ +#define FGDMA_DEFAULT_DIRECT_CHAN_CONFIG(_chan_id)\ +(FGdmaChanConfig){ \ + .chan_id = (_chan_id),\ + .rd_align = FGDMA_BURST_SIZE_4_BYTE,\ + .wr_align = FGDMA_BURST_SIZE_4_BYTE,\ + .rd_qos = FGDMA_OPER_NONE_PRIORITY_POLL,\ + .wr_qos = FGDMA_OPER_NONE_PRIORITY_POLL,\ + .trans_mode = FGDMA_OPER_DIRECT,\ + .roll_back = FALSE\ +} + +#define FGDMA_DEFAULT_BDL_CHAN_CONFIG(_chan_id, _bdl_descs, _bdl_desc_num)\ +(FGdmaChanConfig){ \ + .chan_id = (_chan_id),\ + .rd_align = FGDMA_BURST_SIZE_4_BYTE,\ + .wr_align = FGDMA_BURST_SIZE_4_BYTE,\ + .rd_qos = FGDMA_OPER_NONE_PRIORITY_POLL,\ + .wr_qos = FGDMA_OPER_NONE_PRIORITY_POLL,\ + .trans_mode = FGDMA_OPER_BDL,\ + .roll_back = FALSE,\ + .descs = _bdl_descs,\ + .total_desc_num = _bdl_desc_num,\ + .valid_desc_num = 0U\ +} + +/************************** Function Prototypes ******************************/ +/* 获取GDMA控制器默认配置 */ +const FGdmaConfig *FGdmaLookupConfig(u32 instance_id); + +/* 初始化GDMA控制器实例 */ +FError FGdmaCfgInitialize(FGdma *const instance_p, const FGdmaConfig *config_p); + +/* 去初始化GDMA控制器实例 */ +void FGdmaDeInitialize(FGdma *const instance_p); + +/* 分配指定GDMA通道 */ +FError FGdmaAllocateChan(FGdma *const instance_p, FGdmaChan *const chan_p, + const FGdmaChanConfig *config_p); + +/* 释放GDMA通道 */ +FError FGdmaDellocateChan(FGdmaChan *const chan_p); + +/* 直接操作模式下发起DMA传输 */ +FError FGdmaDirectTransfer(FGdmaChan *const chan_p, uintptr src_addr, uintptr dst_addr, fsize_t data_len); + +/* 设置BDL描述符的一个条目 */ +FError FGdmaAppendBDLEntry(FGdmaChan *const chan_p, uintptr src_addr, uintptr dst_addr, fsize_t data_len); + +/* BDL操作模式下发起DMA传输 */ +FError FGdmaBDLTransfer(FGdmaChan *const chan_p); + +/* 使能启动GDMA控制器 */ +FError FGdmaStart(FGdma *const instance_p); + +/* 停止GDMA控制器 */ +FError FGdmaStop(FGdma *const instance_p); + +/* GDMA中断处理函数 */ +void FGdmaIrqHandler(s32 vector, void *args); + +/* 注册GDMA通道事件回调函数 */ +void FGdmaChanRegisterEvtHandler(FGdmaChan *const chan_p, FGdmaChanEvtType evt, + FGdmaChanEvtHandler handler, void *handler_arg); + +/* 打印当前的GDMA寄存器值, DEBUG模式下有效 */ +void FGdmaDumpRegisterVals(uintptr base_addr, u32 max_chan); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_g.c b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_g.c new file mode 100644 index 0000000000..8cb1ba77f8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_g.c @@ -0,0 +1,58 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgdma_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:09 + * Description:  This files is for static variables definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021-11-5 init commit + * 1.1 zhugengyu 2022-5-16 modify according to tech manual. + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" + +#include "fgdma.h" +#include "fgdma_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +const FGdmaConfig fgdma_cfg_tbl[FGDMA_INSTANCE_NUM] = +{ + [FGDMA0_ID] = + { + .instance_id = FGDMA0_ID, + .base_addr = FGDMA0_BASE_ADDR, + .irq_num = FGDMA0_IRQ_NUM, + .irq_prority = 0, + .rd_qos = FGDMA_OPER_NONE_PRIORITY_POLL, + .wr_qos = FGDMA_OPER_NONE_PRIORITY_POLL + } +}; + + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_hw.h b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_hw.h new file mode 100644 index 0000000000..14e45c451e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_hw.h @@ -0,0 +1,447 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgdma_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:52 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021-11-5 init commit + * 1.1 zhugengyu 2022-5-16 modify according to tech manual. + */ + +#ifndef DRIVERS_FGDMA_HW_H +#define DRIVERS_FGDMA_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fparameters.h" +#include "fio.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ + +/** @name Register Map + * + * Register offsets from the base address of an GDMA device. + * @{ + */ +#define FGDMA_CTL_OFFSET 0x0U /* 全局控制类寄存器 */ +#define FGDMA_INTR_STATE_OFFSET 0x4U /* 中断状态寄存器 */ +#define FGDMA_INTR_CTRL_OFFSET 0x8U /* 中断使能控制寄存器 */ +#define FGDMA_LP_OFFSET 0xCU /* 每一位对应一个通道时钟开启和关断 */ +#define FGDMA_QOS_CFG_OFFSET 0x10U /* 读写请求的 QoS 配置 */ + +/* Channel register */ +#define FGDMA_CHX_OFFSET(x) ((x) * 0x60U) +#define FGDMA_CHX_CTL_OFFSET(x) (0x20 + FGDMA_CHX_OFFSET(x)) /* 软复位信号与使能控制信号 */ +#define FGDMA_CHX_MODE_OFFSET(x) (0x24 + FGDMA_CHX_OFFSET(x)) /* 模式寄存器 */ +#define FGDMA_CHX_INT_CTRL_OFFSET(x) (0x28 + FGDMA_CHX_OFFSET(x)) /* 中断输出控制寄存器 */ +#define FGDMA_CHX_INT_STATE_OFFSET(x) (0x2C + FGDMA_CHX_OFFSET(x)) /* 状态寄存器 */ +#define FGDMA_CHX_LVI_OFFSET(x) (0x30 + FGDMA_CHX_OFFSET(x)) /* 链表模式下 BDL 有效条目 */ +#define FGDMA_CHX_TS_OFFSET(x) (0x34 + FGDMA_CHX_OFFSET(x)) /* 直接操作模式下总 Byte 数据量 */ +#define FGDMA_CHX_UPSADDR_OFFSET(x) (0x38 + FGDMA_CHX_OFFSET(x)) /* 源地址寄存器(高32位) */ +#define FGDMA_CHX_LWSADDR_OFFSET(x) (0x3C + FGDMA_CHX_OFFSET(x)) /* 源地址寄存器(低32位) */ +#define FGDMA_CHX_UPDADDR_OFFSET(x) (0x40 + FGDMA_CHX_OFFSET(x)) /* 目的地址寄存器(高32位) */ +#define FGDMA_CHX_LWDADDR_OFFSET(x) (0x44 + FGDMA_CHX_OFFSET(x)) /* 目的地址寄存器(低32位) */ +#define FGDMA_CHX_XFER_CFG_OFFSET(x) (0x48 + FGDMA_CHX_OFFSET(x)) /* 读写请求 Burst 信息 */ +#define FGDMA_CHX_LCP_OFFSET(x) (0x4C + FGDMA_CHX_OFFSET(x)) /* 当前操作了多少个 BDL 列表 */ +#define FGDMA_CHX_SECCTL_OFFSET(x) (0x50 + FGDMA_CHX_OFFSET(x)) /* 安全控制寄存器 */ +#define FGDMA_CHX_SEC_ATST_OFFSET(x) (0x54 + FGDMA_CHX_OFFSET(x)) /* Secssid 和 Atst信号控制寄存器 */ +#define FGDMA_CHX_NSID_STRMID_OFFSET(x) (0x58 + FGDMA_CHX_OFFSET(x)) /* NSAID 和 StreamID 控制寄存器 */ +#define FGDMA_CHX_AW_CFG_OFFSET(x) (0x5C + FGDMA_CHX_OFFSET(x)) /* 控制 AXI AW 通道配置寄存器 */ +#define FGDMA_CHX_AR_CFG_OFFSET(x) (0x60 + FGDMA_CHX_OFFSET(x)) /* 控制 AXI AR 通道配置寄存器 */ +#define FGDMA_CHX_SECRSP_OFFSET(x) (0x64 + FGDMA_CHX_OFFSET(x)) /* 通道 Response 安全控制寄存器 */ + +/** @name FGDMA_CTL_OFFSET Register + */ +#define FGDMA_CTL_OT_MASK GENMASK(11, 8) +#define FGDMA_CTL_OT_SET(ot) SET_REG32_BITS(ot, 11, 8) /* dma 传输outstanding 控制,实际数量为该寄存器值+1 */ +#define FGDMA_CTL_RD_ARB BIT(5) /* dma 读请求仲裁模式: 0:轮询模式,1:采用Qos判断模式 */ +#define FGDMA_CTL_WR_ARB BIT(4) /* dma 写请求仲裁模式: 0:轮询模式,1:采用Qos判断模式 */ +#define FGDMA_CTL_SOFT_RESET BIT(1) /* dma 软件复位信号,1表示进行复位,写0退出 */ +#define FGDMA_CTL_ENABLE BIT(0) /* dma 使能信号,1表示使能,写0表示disable */ + +/** @name FGDMA_INTR_STATE_OFFSET Register + */ +#define FGDMA_CHX_INTR_STATE(x) BIT(x) /* channel-x 中断状态标志位 */ + +/** @name FGDMA_INTR_CTRL_OFFSET Register + */ +#define FGDMA_CHX_INTR_MASK(x) BIT(x) /* channel-x 中断使能控制,1 表示使能,0 表示不使能 */ +#define FGDMA_CHX_INTR_GLOBAL_MASK BIT(31) /* 全局中断输出 mask 控制信号,1表示允许中断输出,0 表示不允许 */ + +/** @name FGDMA_LP_OFFSET Register + */ +#define FGDMA_CHX_LP_CTL(x) BIT(x) /* channel-x 时钟开启和关断,1 表示关断,默认开启 */ + +/** @name FGDMA_QOS_CFG_OFFSET Register + */ +#define FGDMA_QOS_CFG_ARGOS_MASK GENMASK(7, 4) +#define FGDMA_QOS_CFG_ARGOS_SET(qos) SET_REG32_BITS((qos), 7, 4) /* 读请求的 QoS 配置 */ +#define FGDMA_QOS_CFG_AWQOS_MASK GENMASK(3, 0) +#define FGDMA_QOS_CFG_AWQOS_SET(qos) SET_REG32_BITS((qos), 3, 0) /* 写请求的 QoS 配置 */ + +/** @name FGDMA_CHX_CTL_OFFSET Register + */ +#define FGDMA_CHX_CTL_SOFT_RESET BIT(4) /* 软复位信号,1 表示进行软复位,写 0 退出 */ +#define FGDMA_CHX_CTL_ENABLE BIT(0) /* 使能控制信号,1 表示使能该通道,0 表示不使能 */ + +/** @name FGDMA_CHX_MODE_OFFSET Register + */ +#define FGDMA_CHX_MODE_RD_QOS_MASK GENMASK(23, 20) +#define FGDMA_CHX_MODE_RD_QOS_SET(qos) SET_REG32_BITS((qos), 23, 20) /* CHX 读请求 Qos 配置 */ +#define FGDMA_CHX_MODE_RD_QOS_GET(qos) GET_REG32_BITS((qos), 23, 20) +/* 是否用 cd_rd_qos 的值替换该通道的去请求 QoSS,1 表示替换, 0 不替换 */ +#define FGDMA_CHX_MODE_RD_QOS_EN BIT(16) + +#define FGDMA_CHX_MODE_WR_QOS_MASK GENMASK(15, 12) +#define FGDMA_CHX_MODE_WR_QOS_SET(qos) SET_REG32_BITS((qos), 15, 12) /* CHX 写请求 Qos 配置 */ +#define FGDMA_CHX_MODE_WR_QOS_GET(qos) GET_REG32_BITS((qos), 15, 12) +/* 是否用 cx_wr_qos 中的值替换该通道写请求的 QoS:1 表示替换, 0 不替换 */ +#define FGDMA_CHX_MODE_WR_QOS_EN BIT(8) + +/* 是否用CHX qos cfg 中的值替换该读请求的 Qos:1 表示替换 ,0 不替换 */ +#define FGDMA_CHX_MODE_BDL_ROLL_EN BIT(4) +#define FGDMA_CHX_MODE_BDL_EN BIT(0) /* 配置当前采用direct 或者BDL 链表模式, 0 采用Direct 模式, 1 采用BDL 模式 */ + +/** @name FGDMA_CHX_INT_CTRL_OFFSET Register + */ +#define FGDMA_CHX_INT_CTRL_TRANS_END_ENABLE BIT(3) /* CHX 所以数据传输完成中断输出控制,1表示允许输出,0表示不允许 */ +#define FGDMA_CHX_INT_CTRL_BDL_END_ENABLE BIT(2) /* CHX bdl 条目数据传输完成中断输出控制,1表示允许输出,0表示不允许 */ +#define FGDMA_CHX_INT_CTRL_FIFO_FULL_ENABLE BIT(1) /* CHX ARM满中断 1表示允许输出,0表示不允许 */ +#define FGDMA_CHX_INT_CTRL_FIFO_EMPTY_ENABLE BIT(0) /* CHX ARM空中断 1表示允许输出,0表示不允许 */ + +/** @name FGDMA_CHX_INT_STATE_OFFSET Register + */ +#define FGDMA_CHX_INT_STATE_BUSY BIT(4) /* CHX 处于数据传输中,写1 清0 */ +#define FGDMA_CHX_INT_STATE_TRANS_END BIT(3) /* CHX 处于传输完成状态,direct 模式时,表示所有数据传输完成,BDL 模式表示当前所有BDL条目传输完成: 写1清0 */ +#define FGDMA_CHX_INT_STATE_BDL_END BIT(2) /* CHX 在BDL模式下,表示当前一个BDL 条目数据传输完成;Direct 模式下该位始终为0 , 写1清0 */ +#define FGDMA_CHX_INT_STATE_FIFO_FULL BIT(1) /* CHX FIFO 满状态,写1清0 */ +#define FGDMA_CHX_INT_STATE_FIFO_EMPTY BIT(0) /* CHX FIFO 空状态,写1清0 */ +#define FGDMA_CHX_INT_STATE_ALL GENMASK(4, 0) + +/** @name FGDMA_CHX_LVI_OFFSET Register + */ +#define FGDMA_CHX_LVI_SET(lvi) SET_REG32_BITS((lvi - 1), 31, 0) /* CHX last vaild index, 即链表末模式下BDL有效条目,实际有效条目=该寄存器值+1 */ + +/** @name FGDMA_CHX_TS_OFFSET Register + */ +#define FGDMA_CHX_TS_SET(ts) SET_REG32_BITS((ts), 31, 0) /* CHX 在direct 模式下操作的的总Byte数量 */ + +/** @name FGDMA_CHX_UPSADDR_OFFSET Register + */ +#define FGDMA_CHX_UPSADDR_SET(addr) SET_REG32_BITS((addr), 31, 0) /* CHX 源地址高32bits */ + +/** @name FGDMA_CHX_LWSADDR_OFFSET Register + */ +#define FGDMA_CHX_LWSADDR_SET(addr) SET_REG32_BITS((addr), 31, 0) /* CHX 源地址低32bits */ + +/** @name FGDMA_CHX_UPDADDR_OFFSET Register + */ +#define FGDMA_CHX_UPDADDR_SET(addr) SET_REG32_BITS((addr), 31, 0) /* CHX 目标地址高32bits */ + +/** @name FGDMA_CHX_LWDADDR_OFFSET Register + */ +#define FGDMA_CHX_LWDADDR_SET(addr) SET_REG32_BITS((addr), 31, 0) /* CHX 目标地址低32bits */ + +/** @name FGDMA_CHX_XFER_CFG_OFFSET Register + */ +#define FGDMA_CHX_XFER_CFG_AR_LEN_SET(len) SET_REG32_BITS((len), 31, 24) /* CHX 读请求Burst length 大小 */ +#define FGDMA_CHX_XFER_CFG_AR_SIZE_SET(size) SET_REG32_BITS((size), 22, 20) /* CHX 读请求Size 大小 , 支持 1、2、8、16 Byte */ +#define FGDMA_CHX_XFER_CFG_AR_BRUST_SET(type) SET_REG32_BITS((type), 17, 16) /* CHX 读请求Brust 类型: 0:fix ,1:incr */ +#define FGDMA_CHX_XFER_CFG_AW_LEN_SET(len) SET_REG32_BITS((len), 15, 8) /* CHX 写请求Burst length 大小 */ +#define FGDMA_CHX_XFER_CFG_AW_SIZE_SET(size) SET_REG32_BITS((size), 6, 4) /* CHX 写请求Size 大小 , 支持 1、2、8、16 Byte */ +#define FGDMA_CHX_XFER_CFG_AW_BRUST_SET(type) SET_REG32_BITS((type), 1, 0) /* CHX 写请求Brust 类型: 0:fix ,1:incr */ + +#define FGDMA_INCR 1U +#define FGDMA_FIX 0U + +#define FGDMA_MAX_BURST_LEN 8U + +/** @name FGDMA_CHX_LCP_OFFSET Register + */ +#define FGDMA_CHX_LCP_GET(reg_val) GET_REG32_BITS((reg_val), 31, 0) /* 当前操作了多少个 BDL 列表 */ + +/** @name FGDMA_CHX_SECCTL_OFFSET Register + */ +#define FGDMA_CHX_SECCTL_SET(val) GET_REG32_BITS((val), 31, 0) /* CHX 安全控制寄存器,仅安全状态可访问 */ + +/** @name FGDMA_CHX_SEC_ATST_OFFSET Register + */ +#define FGDMA_CHX_SEC_ATST_SET(val) SET_REG32_BITS((val), 31, 0) + +/** @name FGDMA_CHX_NSID_STRMID_OFFSET Register + */ +#define FGDMA_CHX_NSID_STRMID_SET(val) SET_REG32_BITS((val), 31, 0) + +/** @name FGDMA_CHX_AW_CFG_OFFSET Register + */ +#define FGDMA_CHX_AW_CFG_AWCACHE_SET(val) SET_REG32_BITS((val), 3, 0) /* CHX dma arcache */ +#define FGDMA_CHX_AW_CFG_AWREGION_MASK_SET(val) SET_REG32_BITS((val), 7, 4) /* CHX dma arregion */ +#define FGDMA_CHX_AW_CFG_AWPROT_SET(val) SET_REG32_BITS((val), 9, 8) +#define FGDMA_CHX_AW_CFG_AWDOMAIN_SET(val) SET_REG32_BITS((val), 13, 12) /* chx ardomain */ +#define FGDMA_CHX_AW_CFG_AWSNOOP_SET(val) SET_REG32_BITS((val), 18, 16) +#define FGDMA_CHX_AW_CFG_AWBAR_SET(val) SET_REG32_BITS((val), 21, 20) + +/** @name FGDMA_CHX_AR_CFG_OFFSET Register + */ +#define FGDMA_CHX_AR_CFG_AWCACHE_SET(val) SET_REG32_BITS((val), 3, 0) /* CHX dma arcache */ +#define FGDMA_CHX_AR_CFG_AWREGION_MASK_SET(val) SET_REG32_BITS((val), 7, 4) /* CHX dma arregion */ +#define FGDMA_CHX_AR_CFG_AWPROT_SET(val) SET_REG32_BITS((val), 9, 8) +#define FGDMA_CHX_AR_CFG_AWDOMAIN_SET(val) SET_REG32_BITS((val), 13, 12) /* chx ardomain */ +#define FGDMA_CHX_AR_CFG_AWSNOOP_SET(val) SET_REG32_BITS((val), 19, 16) +#define FGDMA_CHX_AR_CFG_AWBAR_SET(val) SET_REG32_BITS((val), 21, 20) + +/** @name FGDMA_CHX_SECRSP_OFFSET Register + */ +#define FGDMA_CHX_SECRSP BIT(0) /* response 安全控制位 */ + +#define FGDMA_OUTSTANDING 0xfU /* 实际outstanding数目为0xf + 1 */ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGDMA_READREG(base_addr, reg_offset) \ + FtIn32((base_addr) + (u32)(reg_offset)) + +#define FGDMA_WRITEREG(base_addr, reg_offset, data) \ + FtOut32((base_addr) + (u32)(reg_offset), (u32)(data)) + +/** + * @name: FGdmaDisable + * @msg: 去使能GDMA控制器 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + */ +static inline void FGdmaDisable(uintptr base_addr) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_CTL_OFFSET); + reg_val &= ~FGDMA_CTL_ENABLE; + FGDMA_WRITEREG(base_addr, FGDMA_CTL_OFFSET, reg_val); +} + +/** + * @name: FGdmaEnable + * @msg: 使能GDMA控制器 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + */ +static inline void FGdmaEnable(uintptr base_addr) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_CTL_OFFSET); + reg_val |= FGDMA_CTL_ENABLE; + FGDMA_WRITEREG(base_addr, FGDMA_CTL_OFFSET, reg_val); +} + +/** + * @name: FGdmaSoftwareReset + * @msg: 完成GDMA控制器软复位 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + */ +static inline void FGdmaSoftwareReset(uintptr base_addr) +{ + int delay = 100; + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_CTL_OFFSET); + reg_val |= FGDMA_CTL_SOFT_RESET; + FGDMA_WRITEREG(base_addr, FGDMA_CTL_OFFSET, reg_val); + + while (--delay > 0) + ; + + reg_val = FGDMA_READREG(base_addr, FGDMA_CTL_OFFSET); + reg_val &= ~FGDMA_CTL_SOFT_RESET; + FGDMA_WRITEREG(base_addr, FGDMA_CTL_OFFSET, reg_val); +} + +/** + * @name: FGdmaIrqEnable + * @msg: 开启GDMA控制器中断 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + */ +static inline void FGdmaIrqEnable(uintptr base_addr) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_INTR_CTRL_OFFSET); + reg_val |= FGDMA_CHX_INTR_GLOBAL_MASK; + FGDMA_WRITEREG(base_addr, FGDMA_INTR_CTRL_OFFSET, reg_val); +} + +/** + * @name: FGdmaIrqDisable + * @msg: 关闭GDMA控制器中断 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + */ +static inline void FGdmaIrqDisable(uintptr base_addr) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_INTR_CTRL_OFFSET); + reg_val &= ~FGDMA_CHX_INTR_GLOBAL_MASK; + FGDMA_WRITEREG(base_addr, FGDMA_INTR_CTRL_OFFSET, reg_val); +} + +/** + * @name: FGdmaChanDisable + * @msg: 去使能GDMA通道 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, GDMA通道号 + */ +static inline void FGdmaChanDisable(uintptr base_addr, u32 chan) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan)); + reg_val &= ~FGDMA_CHX_CTL_ENABLE; /* 禁用通道 */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan), reg_val); +} + +/** + * @name: FGdmaChanEnable + * @msg: 使能GDMA通道 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, GDMA通道号 + */ +static inline void FGdmaChanEnable(uintptr base_addr, u32 chan) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan)); + reg_val |= FGDMA_CHX_CTL_ENABLE; /* 使能通道 */ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan), reg_val); +} + +/** + * @name: FGdmaChanIrqDisable + * @msg: 关闭GDMA通道中断 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, GDMA通道号 + */ +static inline void FGdmaChanIrqDisable(uintptr base_addr, u32 chan) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_INTR_CTRL_OFFSET); + reg_val &= ~FGDMA_CHX_INTR_MASK(chan); /* 禁用通道中断 */ + FGDMA_WRITEREG(base_addr, FGDMA_INTR_CTRL_OFFSET, reg_val); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_INT_CTRL_OFFSET(chan), 0x0U); /* 禁用通道所有中断位 */ +} + +/** + * @name: FGdmaChanIrqEnable + * @msg: 打开GDMA通道中断 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, GDMA通道号 + * @param {u32} umask, 使能的通道中断位 + */ +static inline void FGdmaChanIrqEnable(uintptr base_addr, u32 chan, u32 umask) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_INTR_CTRL_OFFSET); + reg_val |= FGDMA_CHX_INTR_MASK(chan); /* 使能通道中断 */ + FGDMA_WRITEREG(base_addr, FGDMA_INTR_CTRL_OFFSET, reg_val); + FGDMA_WRITEREG(base_addr, FGDMA_CHX_INT_CTRL_OFFSET(chan), umask); /* 使能通道指定中断位 */ +} + +/** + * @name: FGdmaChanReset + * @msg: 完成GDMA通道软复位 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, GDMA通道号 + */ +static inline void FGdmaChanReset(uintptr base_addr, u32 chan) +{ + int delay = 100; + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan)); + reg_val |= FGDMA_CHX_CTL_SOFT_RESET; + FGDMA_WRITEREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan), reg_val); + + while (--delay > 0) + ; + + reg_val = FGDMA_READREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan)); + reg_val &= ~FGDMA_CHX_CTL_SOFT_RESET; + FGDMA_WRITEREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan), reg_val); +} + +/** + * @name: FGdmaReadStatus + * @msg: 获取GDMA控制器中断状态 + * @return {u32} 中断状态位 + * @param {uintptr} base_addr, GDMA控制器基地址 + */ +static inline u32 FGdmaReadStatus(uintptr base_addr) +{ + return FGDMA_READREG(base_addr, FGDMA_INTR_STATE_OFFSET); +} + +/** + * @name: FGdmaReadChanStatus + * @msg: 获取GDMA通道中断状态 + * @return {u32} 中断状态位 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, 通道号 + */ +static inline u32 FGdmaReadChanStatus(uintptr base_addr, u32 chan) +{ + return FGDMA_READREG(base_addr, FGDMA_CHX_INT_STATE_OFFSET(chan)); +} + +/** + * @name: FGdmaClearChanStatus + * @msg: 清除GDMA通道中断状态 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, 通道号 + * @param {u32} status, 待清除的中断状态 + */ +static inline void FGdmaClearChanStatus(uintptr base_addr, u32 chan, u32 status) +{ + FGDMA_WRITEREG(base_addr, FGDMA_CHX_INT_STATE_OFFSET(chan), status); /* 写1清0 */ +} + +/** + * @name: FGdmaSetChanClock + * @msg: 打开/关闭GDMA通道时钟 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} chan, 通道号 + * @param {boolean} enable,TRUE: 打开时钟, FALSE: 关闭时钟 + */ +static inline void FGdmaSetChanClock(uintptr base_addr, u32 chan, boolean enable) +{ + u32 reg_val = FGDMA_READREG(base_addr, FGDMA_LP_OFFSET); + if (enable) + reg_val &= ~FGDMA_CHX_LP_CTL(chan); /* 写0开启通道时钟 */ + else + reg_val |= FGDMA_CHX_LP_CTL(chan); /* 写1关断通道时钟 */ + FGDMA_WRITEREG(base_addr, FGDMA_LP_OFFSET, reg_val); + + return; +} + +/************************** Function Prototypes ******************************/ + + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_intr.c b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_intr.c new file mode 100644 index 0000000000..80ba4ea4d4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_intr.c @@ -0,0 +1,156 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgdma_intr.c + * Date: 2022-05-16 17:01:48 + * LastEditTime: 2022-05-16 17:01:49 + * Description:  This files is for interrupt api implmentation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021-11-5 init commit + * 1.1 zhugengyu 2022-5-16 modify according to tech manual. + */ + +/***************************** Include Files *********************************/ +#include + +#include "fdebug.h" +#include "fassert.h" + +#include "fgdma_hw.h" +#include "fgdma.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGDMA_DEBUG_TAG "GDMA-INTR" +#define FGDMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_WARN(format, ...) FT_DEBUG_PRINT_W(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_INFO(format, ...) FT_DEBUG_PRINT_I(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FGDMA_CALL_EVT_HANDLER(express, dma_chan, args) \ + do \ + { \ + if (express) \ + { \ + express(dma_chan, args); \ + } \ + } while (0) + +/************************** Function Prototypes ******************************/ +/** + * @name: FGdmaChanIrqHandler + * @msg: GDMA通道中断处理函数 + * @return {void} 无 + * @param {FGdmaChan} *chan_p, GDMA通道实例 + */ +static void FGdmaChanIrqHandler(FGdmaChan *const chan_p) +{ + FGdma *const instance_p = chan_p->gdma; + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 chan_status = FGdmaReadChanStatus(base_addr, chan_p->config.chan_id); + + if (FGDMA_CHX_INT_STATE_BUSY & chan_status) + { + FGDMA_CALL_EVT_HANDLER(chan_p->evt_handlers[FGDMA_CHAN_EVT_BUSY], + chan_p, chan_p->evt_handler_args[FGDMA_CHAN_EVT_BUSY]); + } + + if (FGDMA_CHX_INT_STATE_TRANS_END & chan_status) + { + FGDMA_CALL_EVT_HANDLER(chan_p->evt_handlers[FGDMA_CHAN_EVT_TRANS_END], + chan_p, chan_p->evt_handler_args[FGDMA_CHAN_EVT_TRANS_END]); + } + + if (FGDMA_CHX_INT_STATE_BDL_END & chan_status) + { + FGDMA_CALL_EVT_HANDLER(chan_p->evt_handlers[FGDMA_CHAN_EVT_BDL_END], + chan_p, chan_p->evt_handler_args[FGDMA_CHAN_EVT_BDL_END]); + } + + if (FGDMA_CHX_INT_STATE_FIFO_FULL & chan_status) + { + FGDMA_CALL_EVT_HANDLER(chan_p->evt_handlers[FGDMA_CHAN_EVT_FIFO_FULL], + chan_p, chan_p->evt_handler_args[FGDMA_CHAN_EVT_FIFO_FULL]); + } + + if (FGDMA_CHX_INT_STATE_FIFO_EMPTY & chan_status) + { + FGDMA_CALL_EVT_HANDLER(chan_p->evt_handlers[FGDMA_CHAN_EVT_FIFO_EMPTY], + chan_p, chan_p->evt_handler_args[FGDMA_CHAN_EVT_FIFO_EMPTY]); + } + + FGdmaClearChanStatus(base_addr, chan_p->config.chan_id, chan_status); + return; +} + +/** + * @name: FGdmaIrqHandler + * @msg: GDMA中断处理函数 + * @return {void} 无 + * @param {s32} vector, 中断号 + * @param {void} *args, 中断参数 + */ +void FGdmaIrqHandler(s32 vector, void *args) +{ + FASSERT(args); + FGdma *const instance_p = (FGdma * const)args; + FASSERT(FT_COMPONENT_IS_READY == instance_p->is_ready); + uintptr base_addr = instance_p->config.base_addr; + u32 chan_id; + + u32 status = FGdmaReadStatus(base_addr); + FGDMA_INFO("status: 0x%x", status); + + FGdmaIrqDisable(base_addr); + for (chan_id = FGDMA_CHAN0_INDEX; chan_id < FGDMA_NUM_OF_CHAN; chan_id++) + { + if (!(FGDMA_CHX_INTR_STATE(chan_id) & status)) + continue; + + /* channel interrupt happens */ + FASSERT_MSG((NULL != instance_p->chans[chan_id]), "invalid chan interrupt event !!!"); + FGdmaChanIrqHandler(instance_p->chans[chan_id]); + } + FGdmaIrqEnable(base_addr); + + return; +} + +/** + * @name: FGdmaChanRegisterEvtHandler + * @msg: 注册GDMA通道事件回调函数 + * @return {void} 无 + * @param {FGdmaChan} *chan_p, GDMA通道实例 + * @param {FGdmaChanEvtType} evt, 通道事件 + * @param {FGdmaChanEvtHandler} handler, 事件回调函数 + * @param {void} *handler_arg, 事件回调函数输入参数 + */ +void FGdmaChanRegisterEvtHandler(FGdmaChan *const chan_p, FGdmaChanEvtType evt, + FGdmaChanEvtHandler handler, void *handler_arg) +{ + FASSERT(chan_p); + FASSERT(FGDMA_CHAN_NUM_OF_EVT > evt); + + chan_p->evt_handlers[evt] = handler; + chan_p->evt_handler_args[evt] = handler_arg; + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_selftest.c b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_selftest.c new file mode 100644 index 0000000000..fe16b3e525 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_selftest.c @@ -0,0 +1,87 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgdma_selftest.c + * Date: 2022-05-20 13:39:27 + * LastEditTime: 2022-05-20 13:39:27 + * Description:  This files is for self test implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021-11-5 init commit + * 1.1 zhugengyu 2022-5-16 modify according to tech manual. + */ +/***************************** Include Files *********************************/ +#include + +#include "fdebug.h" + +#include "fgdma_hw.h" +#include "fgdma.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGDMA_DEBUG_TAG "GDMA-TEST" +#define FGDMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_WARN(format, ...) FT_DEBUG_PRINT_W(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_INFO(format, ...) FT_DEBUG_PRINT_I(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGDMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGDMA_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/****************************************************************************/ +/** + * @name: FGdmaDumpRegisterVals + * @msg: 打印当前的GDMA寄存器值 + * @return {void} 无 + * @param {uintptr} base_addr, GDMA控制器基地址 + * @param {u32} max_chan, 打印从 0 ~ max_chan 的通道寄存器值 + */ +void FGdmaDumpRegisterVals(uintptr base_addr, u32 max_chan) +{ + FGDMA_DEBUG("ctrl[0x%x]: 0x%x", FGDMA_CTL_OFFSET, FGDMA_READREG(base_addr, FGDMA_CTL_OFFSET)); + FGDMA_DEBUG("state[0x%x]: 0x%x", FGDMA_INTR_STATE_OFFSET, FGDMA_READREG(base_addr, FGDMA_INTR_STATE_OFFSET)); + FGDMA_DEBUG("intr[0x%x]: 0x%x", FGDMA_INTR_CTRL_OFFSET, FGDMA_READREG(base_addr, FGDMA_INTR_CTRL_OFFSET)); + FGDMA_DEBUG("lp[0x%x] : 0x%x", FGDMA_LP_OFFSET, FGDMA_READREG(base_addr, FGDMA_LP_OFFSET)); + FGDMA_DEBUG("qos[0x%x] : 0x%x", FGDMA_QOS_CFG_OFFSET, FGDMA_READREG(base_addr, FGDMA_QOS_CFG_OFFSET)); + + for (u32 chan = FGDMA_CHAN0_INDEX; chan <= max_chan; chan++) + { + FGDMA_DEBUG("chan-%d", chan); + FGDMA_DEBUG(" ctrl[0x%x]: 0x%x", FGDMA_CHX_CTL_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_CTL_OFFSET(chan))); + FGDMA_DEBUG(" mode[0x%x]: 0x%x", FGDMA_CHX_MODE_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_MODE_OFFSET(chan))); + FGDMA_DEBUG(" intr[0x%x]: 0x%x", FGDMA_CHX_INT_CTRL_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_INT_CTRL_OFFSET(chan))); + FGDMA_DEBUG(" state[0x%x]: 0x%x", FGDMA_CHX_INT_STATE_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_INT_STATE_OFFSET(chan))); + FGDMA_DEBUG(" lvi[0x%x]: 0x%x", FGDMA_CHX_LVI_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_LVI_OFFSET(chan))); + FGDMA_DEBUG(" ts[0x%x]: 0x%x", FGDMA_CHX_TS_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_TS_OFFSET(chan))); + FGDMA_DEBUG(" src-up[0x%x]: 0x%x", FGDMA_CHX_UPSADDR_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_UPSADDR_OFFSET(chan))); + FGDMA_DEBUG(" src-low[0x%x]: 0x%x", FGDMA_CHX_LWSADDR_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_LWSADDR_OFFSET(chan))); + FGDMA_DEBUG(" dst-up[0x%x]: 0x%x", FGDMA_CHX_UPDADDR_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_UPDADDR_OFFSET(chan))); + FGDMA_DEBUG(" dst-low[0x%x]: 0x%x", FGDMA_CHX_LWDADDR_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_LWDADDR_OFFSET(chan))); + FGDMA_DEBUG(" xfer[0x%x]: 0x%x", FGDMA_CHX_XFER_CFG_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_XFER_CFG_OFFSET(chan))); + FGDMA_DEBUG(" lpc[0x%x]: 0x%x", FGDMA_CHX_LCP_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_LCP_OFFSET(chan))); + FGDMA_DEBUG(" sec[0x%x]: 0x%x", FGDMA_CHX_SECCTL_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_SECCTL_OFFSET(chan))); + FGDMA_DEBUG(" atst[0x%x]: 0x%x", FGDMA_CHX_SEC_ATST_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_SEC_ATST_OFFSET(chan))); + FGDMA_DEBUG(" nsid[0x%x]: 0x%x", FGDMA_CHX_NSID_STRMID_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_NSID_STRMID_OFFSET(chan))); + FGDMA_DEBUG(" aw[0x%x]: 0x%x", FGDMA_CHX_AW_CFG_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_AW_CFG_OFFSET(chan))); + FGDMA_DEBUG(" ar[0x%x]: 0x%x", FGDMA_CHX_AR_CFG_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_AR_CFG_OFFSET(chan))); + FGDMA_DEBUG(" resp[0x%x]: 0x%x", FGDMA_CHX_SECRSP_OFFSET(chan), FGDMA_READREG(base_addr, FGDMA_CHX_SECRSP_OFFSET(chan))); + } + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_sinit.c b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_sinit.c new file mode 100644 index 0000000000..bb315ae0c0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/dma/fgdma/fgdma_sinit.c @@ -0,0 +1,64 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgdma_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:15 + * Description:  This files is for gdma static init + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 huanghe 2021-11-5 init commit + * 1.1 zhugengyu 2022-5-16 modify according to tech manual. + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" + +#include "fgdma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ +extern const FGdmaConfig fgdma_cfg_tbl[FGDMA_INSTANCE_NUM]; + +/************************** Function Prototypes ******************************/ +/** + * @name: FGdmaLookupConfig + * @msg: 获取GDMA控制器默认配置 + * @return {const FGdmaConfig *} 控制器默认配置 + * @param {u32} instance_id, GDMA控制器ID + */ +const FGdmaConfig *FGdmaLookupConfig(u32 instance_id) +{ + const FGdmaConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FGDMA_INSTANCE_NUM; index++) + { + if (fgdma_cfg_tbl[index].instance_id == instance_id) + { + ptr = &fgdma_cfg_tbl[index]; + break; + } + } + + return (const FGdmaConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/Kconfig b/bsp/phytium/libraries/standalone/drivers/eth/Kconfig new file mode 100644 index 0000000000..f041d27764 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/Kconfig @@ -0,0 +1,22 @@ + +menu "Eth Configuration" + config ENABLE_FXMAC + bool + prompt "Use FXMAC" + default n + + config ENABLE_FGMAC + bool + prompt "Use FGMAC" + default n + + if ENABLE_FGMAC + source "$STANDALONE_DIR/drivers/eth/fgmac/Kconfig" + endif + + if ENABLE_FXMAC + source "$STANDALONE_DIR/drivers/eth/fxmac/Kconfig" + endif + +endmenu + diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/Kconfig b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/Kconfig new file mode 100644 index 0000000000..af211a4c2d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/Kconfig @@ -0,0 +1,13 @@ +choice FGMAC_PHY_TYPE + prompt "PHY Type" + default FGMAC_PHY_COMMON + help + Select PHY for FGMAC + + config FGMAC_PHY_COMMON + bool "Common" + config FGMAC_PHY_AR803X + bool "AR803X" + +endchoice # FGMAC_PHY_TYPE + diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac.c new file mode 100644 index 0000000000..bef00ec931 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac.c @@ -0,0 +1,497 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ +#include + +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" +#include "fassert.h" +#include "fgmac_hw.h" +#include "fgmac_phy.h" +#include "fgmac.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGMAC_DEBUG_TAG "FGMAC" +#define FGMAC_ERROR(format, ...) FT_DEBUG_PRINT_E(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_WARN(format, ...) FT_DEBUG_PRINT_W(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_INFO(format, ...) FT_DEBUG_PRINT_I(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) + + +/************************** Function Prototypes ******************************/ +static FError FGmacReset(FGmac *instance_p); +static FError FGmacDmaConfigure(FGmac *instance_p); +static FError FGmacControllerConfigure(FGmac *instance_p); +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/* 此文件主要为了完成用户对外接口,用户可以使用这些接口直接开始工作 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/* + * @name: FGmacStop + * @msg: 停止FGMAC控制器寄存器 + * @return {*} + * @param {FGmac} *instance_p 驱动控制数据 + */ +void FGmacStop(FGmac *instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + + /* disable dma tx and rx */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_DMA_OP_OFFSET); + reg_val &= (~FGMAC_DMA_OP_ST); + reg_val &= (~FGMAC_DMA_OP_SR); + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_OP_OFFSET, reg_val); + + /* disable gmac tx and rx */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_CONF_OFFSET); + reg_val &= (~FGMAC_CONF_TX_EN); + reg_val &= (~FGMAC_CONF_RX_EN); + FGMAC_WRITE_REG32(base_addr, FGMAC_CONF_OFFSET, reg_val); + +} + + +/** + * @name: FGmacCfgInitialize + * @msg: init FGMAC controller + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {FGmacConfig} *cofig_p, input configuration parameters + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacCfgInitialize(FGmac *instance_p, const FGmacConfig *input_config_p) +{ + FASSERT(instance_p && input_config_p); + FError ret = FGMAC_SUCCESS; + + /* indicating device is started */ + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FGMAC_WARN("device is already initialized!!!"); + } + + /* de-initialize device instance */ + FGmacDeInitialize(instance_p); + instance_p->config = *input_config_p; + + + /*Phy Awaken*/ + + ret = FGmacPhyAwaken(instance_p); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("phy awaken failed!"); + return ret; + } + + + /* initialize the gmac controller */ + ret = FGmacReset(instance_p); // permmit failed + if (FGMAC_SUCCESS != ret) + { + printf("FGmacReset failed \r\n"); + } + + + ret = FGmacControllerConfigure(instance_p); + if (FGMAC_SUCCESS != ret) + return ret; + + /* initialize the gmac dma controller */ + ret = FGmacDmaConfigure(instance_p); + if (FGMAC_SUCCESS == ret) + { + instance_p->is_ready = FT_COMPONENT_IS_READY; + } + + return ret; +} + +/** + * @name: FGmacDeInitialize + * @msg: deinit FGMAC controller + * @param {FGmac} *instance_p, instance of FGmac controller + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacDeInitialize(FGmac *instance_p) +{ + FASSERT(instance_p); + FError ret = FGMAC_SUCCESS; + + instance_p->is_ready = 0; + memset(instance_p, 0, sizeof(*instance_p)); + + return ret; +} + +/** + * @name: FGmacReset + * @msg: reset FGMAC controller + * @param {FGmac} *instance_p, instance of FGmac controller + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +static FError FGmacReset(FGmac *instance_p) +{ + FASSERT(instance_p); + FGmacMacAddr mac_addr; + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGMAC_SUCCESS; + u32 reg_val; + + + /* backup mac address before software reset */ + memset(mac_addr, 0, sizeof(mac_addr)); + FGmacGetMacAddr(base_addr, mac_addr); + + /* disable all gmac & dma intr */ + FGmacSetInterruptMask(instance_p, FGMAC_CTRL_INTR, FGMAC_ISR_MASK_ALL_BITS); + FGmacSetInterruptMask(instance_p, FGMAC_DMA_INTR, FGMAC_DMA_INTR_ENA_ALL_MASK); + + /* stop gmac/dma tx and rx */ + FGmacStop(instance_p); + + /* do software reset per init */ + ret = FGmacSoftwareReset(base_addr, FGMAC_RETRY_TIMES); + + + /* disable gmac & dma interrupts */ + FGmacSetInterruptMask(instance_p, FGMAC_CTRL_INTR, FGMAC_ISR_MASK_ALL_BITS); + FGmacSetInterruptMask(instance_p, FGMAC_DMA_INTR, FGMAC_DMA_INTR_ENA_ALL_MASK); + + /* recover mac address after softwate reset */ + FGmacSetMacAddr(base_addr, mac_addr); + + return ret;// may return error +} + +/** + * @name: FGmacControllerSpeedConfig + * @msg: fgmac speed configuration + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} speed, speed value + * @return {*} + */ +void FGmacControllerSpeedConfig(FGmac *instance_p, u32 speed) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val = 0; + + /* MAC配置寄存器 */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_CONF_OFFSET); + + /* 设置通信速度FES=1000Mbps */ + if (speed == FGMAC_PHY_SPEED_1000) + { + reg_val &= (~FGMAC_CONF_PORTSELECT); + reg_val &= (~FGMAC_CONF_FES); + } + + /* 设置通信速度FES=100Mbps */ + if (speed == FGMAC_PHY_SPEED_100) + { + reg_val |= FGMAC_CONF_PORTSELECT; + reg_val |= FGMAC_CONF_FES; + } + + /* 设置通信速度FES=10Mbps */ + if (speed == FGMAC_PHY_SPEED_10) + { + reg_val |= FGMAC_CONF_PORTSELECT; + reg_val &= (~FGMAC_CONF_FES); + } + + FGMAC_WRITE_REG32(base_addr, FGMAC_CONF_OFFSET, reg_val); +} + +/** + * @name: FGmacControllerDuplexConfig + * @msg: fgmac deplex mode configuration + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} duplex, duplex mode + * @return {*} + */ +void FGmacControllerDuplexConfig(FGmac *instance_p, u32 duplex) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val = 0; + + /* MAC配置寄存器 */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_CONF_OFFSET); + + /* 设置双工模式 */ + if (duplex == FGMAC_PHY_MODE_FULLDUPLEX) + reg_val |= FGMAC_CONF_DUPLEX_MODE; + else + reg_val &= ~FGMAC_CONF_DUPLEX_MODE; + + FGMAC_WRITE_REG32(base_addr, FGMAC_CONF_OFFSET, reg_val); + +} + +/** + * @name: FGmacControllerConfigure + * @msg: config FGMAC controller + * @param {FGmac} *instance_p, instance of FGmac controller + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +static FError FGmacControllerConfigure(FGmac *instance_p) +{ + FASSERT(instance_p); + FGmacMacAddr mac_addr; + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGMAC_SUCCESS; + u32 reg_val = 0; + + /********gmac ctrl reg init*********/ + /* Set the WD bit according to ETH Watchdog value */ + /* Set the JD: bit according to ETH Jabber value */ + /* Set the IFG bit according to ETH InterFrameGap value */ + /* Set the DCRS bit according to ETH CarrierSense value */ + /* Set the FES bit according to ETH Speed value */ + /* Set the DO bit according to ETH ReceiveOwn value */ + /* Set the LM bit according to ETH LoopbackMode value */ + /* Set the DM bit according to ETH Mode value */ + /* Set the IPCO bit according to ETH ChecksumOffload value */ + /* Set the DR bit according to ETH RetryTransmission value */ + /* Set the ACS bit according to ETH AutomaticPadCRCStrip value */ + /* Set the BL bit according to ETH BackOffLimit value */ + /* Set the DC bit according to ETH DeferralCheck value */ + + /* MAC配置寄存器 */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_CONF_OFFSET); + + /* 使能载波侦听DCRS、失能环回模式LM */ + reg_val &= ~(FGMAC_CONF_DCRS | FGMAC_CONF_LOOPBACK_MODE); + + /* 设置帧内间隔IFG */ + reg_val |= FGMAC_CONF_IFG(0); + + /* 1000Mbps default */ + reg_val &= (~FGMAC_CONF_PORTSELECT); + reg_val &= (~FGMAC_CONF_FES); + + /* 双工模式 */ + if (instance_p->config.duplex_mode) + reg_val |= FGMAC_CONF_DUPLEX_MODE; + else + reg_val &= ~FGMAC_CONF_DUPLEX_MODE; + + /* 使能校验和卸载IPS */ + if (FGMAC_CHECKSUM_BY_HARDWARE == instance_p->config.cheksum_mode) + reg_val |= FGMAC_CONF_IPC; + else + reg_val &= ~FGMAC_CONF_IPC; + + /* 重发DR=1, 重发一次 */ + reg_val |= FGMAC_CONF_DISABLE_RETRY; + + /* 自动 PAD/ CRC 剥线, 全双工模式保留 */ + reg_val |= FGMAC_CONF_ACS; + + /* 后退限制, 全双工模式保留 */ + reg_val |= FGMAC_CONF_BL(0); + + /* 延期检查禁用 */ + reg_val &= ~FGMAC_CONF_DC; + + /* 使能类型帧的CRC剥离、禁用看门狗WD、禁用Jabber JD、帧突发启用BE、不能自接收DO(全双工保留)*/ + reg_val |= (FGMAC_CONF_CST | FGMAC_CONF_WD | FGMAC_CONF_JD | FGMAC_CONF_BE | FGMAC_CONF_DO); + + FGMAC_WRITE_REG32(base_addr, FGMAC_CONF_OFFSET, reg_val); + + /********gmac filter reg init*********/ + /* Set the RA bit according to ETH ReceiveAll value */ + /* Set the SAF and SAIF bits according to ETH SourceAddrFilter value */ + /* Set the PCF bit according to ETH PassControlFrames value */ + /* Set the DBF bit according to ETH BroadcastFramesReception value */ + /* Set the DAIF bit according to ETH DestinationAddrFilter value */ + /* Set the PR bit according to ETH PromiscuousMode value */ + /* Set the PM, HMC and HPF bits according to ETH MulticastFramesFilter value */ + /* Set the HUC and HPF bits according to ETH UnicastFramesFilter value */ + + /* MAC帧过滤寄存器 */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_FRAME_FILTER_OFFSET); + + /* 全部接收RA */ + reg_val |= FGMAC_FRAME_FILTER_RA; + + /* 通过控制帧PCF 10b */ + reg_val |= FGMAC_FRAME_FILTER_PCF(2); + + /* 失能禁用广播帧DBF */ + reg_val &= ~FGMAC_FRAME_FILTER_DBF; + + /* 失能通过所有多播PM */ + reg_val &= ~FGMAC_FRAME_FILTER_PM; + + /* 失能目的地址反向过滤DAIF */ + reg_val &= ~FGMAC_FRAME_FILTER_DAIF; + + /* 失能哈希单播PR */ + reg_val &= ~FGMAC_FRAME_FILTER_PR; + FGMAC_WRITE_REG32(base_addr, FGMAC_FRAME_FILTER_OFFSET, reg_val); + + /********hash reg*********/ + FGMAC_WRITE_REG32(base_addr, FGMAC_HASH_HIGH_OFFSET, 0x0); + FGMAC_WRITE_REG32(base_addr, FGMAC_HASH_LOW_OFFSET, 0x0); + + /********gmac flow ctrl reg init*********/ + + /* Set the PT bit according to ETH PauseTime value */ + /* Set the DZPQ bit according to ETH ZeroQuantaPause value */ + /* Set the PLT bit according to ETH PauseLowThreshold value */ + /* Set the UP bit according to ETH UnicastPauseFrameDetect value */ + /* Set the RFE bit according to ETH ReceiveFlowControl value */ + /* Set the TFE bit according to ETH TransmitFlowControl value */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_FLOW_CTRL_OFFSET); + /* 禁用自动零暂停帧生成DZPQ */ + reg_val |= FGMAC_FLOW_DZPQ; + + /* 暂停低阈值PLT */ + reg_val |= FGMAC_FLOW_PLT(0); + + /* 禁用接收流控制RFE */ + reg_val &= ~FGMAC_FLOW_RFE; + + /* 禁用传输流控制TFE */ + reg_val &= ~FGMAC_FLOW_TFE; + FGMAC_WRITE_REG32(base_addr, FGMAC_FLOW_CTRL_OFFSET, reg_val); + + /********vlan tag reg*********/ + /* Set the ETV bit according to ETH VLANTagComparison value */ + /* Set the VL bit according to ETH VLANTagIdentifier value */ + /* 接收帧的 VLAN 标记标识符 VL */ + reg_val = FGMAC_VLAN_TAG_VL(0); + /* 设置VLAN 标记比较的位数ETV 1-12bit 0-16bit */ + reg_val &= ~FGMAC_VLAN_TAG_ETV; + FGMAC_WRITE_REG32(base_addr, FGMAC_VLAN_TAG_OFFSET, reg_val); + + return ret; +} + +static FError FGmacDmaConfigure(FGmac *instance_p) +{ + FASSERT(instance_p); + u32 reg_val; + FError ret = FGMAC_SUCCESS; + uintptr base_addr = instance_p->config.base_addr; + + /********DMA总线模式寄存器*********/ + /* Set the AAL bit according to ETH AddressAlignedBeats value */ + /* Set the FB bit according to ETH FixedBurst value */ + /* Set the RPBL and 4*PBL bits according to ETH RxDMABurstLength value */ + /* Set the PBL and 4*PBL bits according to ETH TxDMABurstLength value */ + /* Set the Enhanced DMA descriptors bit according to ETH EnhancedDescriptorFormat value*/ + /* Set the DSL bit according to ETH DesciptorSkipLength value */ + /* Set the PR and DA bits according to ETH DMAArbitration value */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_DMA_BUS_MODE_OFFSET); + reg_val |= FGMAC_DMA_BUS_AAL; + /* 使用单独的 PBL USP */ + reg_val |= FGMAC_DMA_BUS_USP; + /* RxDMA PBL RPBL */ + reg_val |= FGMAC_DMA_BUS_RPBL(32); + + /* 固定突发 FB */ + reg_val |= FGMAC_DMA_BUS_FB; + + /* 控制 RxDMA 和 TxDMA 之间的加权循环仲裁中的优先级比率 PR */ + reg_val |= FGMAC_DMA_BUS_PR(0); + + /* 可编程突发长度 PBL */ + reg_val |= FGMAC_DMA_BUS_PBL(32); + + /* 交替描述表大小 ATDS */ + reg_val |= FGMAC_DMA_BUS_ATDS; + + + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_BUS_MODE_OFFSET, reg_val); + + /* dma set bus mode */ + // FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_BUS_MODE_OFFSET, FGMAC_DMA_BUS_INIT); + + /********DMA操作模式寄存器*********/ + /* Set the DT bit according to ETH DropTCPIPChecksumErrorFrame value */ + /* Set the RSF bit according to ETH ReceiveStoreForward value */ + /* Set the DFF bit according to ETH FlushReceivedFrame value */ + /* Set the TSF bit according to ETH TransmitStoreForward value */ + /* Set the TTC bit according to ETH TransmitThresholdControl value */ + /* Set the FEF bit according to ETH ForwardErrorFrames value */ + /* Set the FUF bit according to ETH ForwardUndersizedGoodFrames value */ + /* Set the RTC bit according to ETH ReceiveThresholdControl value */ + /* Set the OSF bit according to ETH SecondFrameOperate value */ + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_DMA_OP_OFFSET); + reg_val &= FGMAC_DMA_OP_CLEAR_MASK; + /* 丢弃 TCP / IP 校验和错误帧 DT */ + reg_val &= ~FGMAC_DMA_OP_DT; + + /* 接收存储转发 RSF */ + reg_val |= FGMAC_DMA_OP_RSF; + + /* 刷新正在接收的帧 DFF */ + reg_val &= ~FGMAC_DMA_OP_DFF; + + /* 发送存储和转发 TSF */ + reg_val |= FGMAC_DMA_OP_TSF; + + /* 传输阈值控制 TTC */ + reg_val |= FGMAC_DMA_OP_TTC(7); + + /* 在第二帧上操作 OSF */ + reg_val |= FGMAC_DMA_OP_OSF; + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_OP_OFFSET, reg_val); + + /* 刷新DMA发送FIFO FTF */ + ret = FGmacFlushTxFifo(base_addr, FGMAC_RETRY_TIMES); + + if (FGMAC_SUCCESS != ret) + { + printf("FGmac Flush Failed\r\n"); + } + + /* AXI 突发长度 BLEN 16,8,4 */ + reg_val = (FGMAC_DMA_AXI_BUS_MOD_BLEN16 | FGMAC_DMA_AXI_BUS_MOD_BLEN8 | FGMAC_DMA_AXI_BUS_MOD_BLEN4); + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_AXI_BUS_MOD_OFFSET, reg_val); + + return ret; +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac.h b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac.h new file mode 100644 index 0000000000..e4dc25d5fc --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac.h @@ -0,0 +1,259 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_ETH_FGMAC_H +#define DRIVERS_ETH_FGMAC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" +#include "ferror_code.h" +#include "fkernel.h" + +#define FGMAC_PHY_MAX_NUM 32U + +/************************** Constant Definitions *****************************/ +#define FGMAC_SUCCESS FT_SUCCESS +#define FGMAC_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 1) +#define FGMAC_ERR_INVALID_DMA_MEM FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 2) +#define FGMAC_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 3) +#define FGMAC_ERR_TRANS_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 4) +#define FGMAC_ERR_PHY_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 5) +#define FGMAC_ERR_PHY_IS_NOT_FOUND FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 6) +#define FGMAC_ERR_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 7) +#define FGMAC_ERR_PHY_AUTO_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 8) + + +#define FGMAC_ERR_CODE_PREFIX FGMAC_ERR_TIMEOUT & (FT_ERRCODE_SYS_MODULE_MASK | FT_ERRCODE_SUB_MODULE_MASK) +#define FGMAC_NUM_OF_ERR_CODE 5 + +/********发送描述符********/ + +/* TDES0 包含发送的帧状态和描述符所有权信息 */ +#define FGMAC_DMA_TDES0_DEFERRED BIT(0) +#define FGMAC_DMA_TDES0_UNDERFLOW_ERROR BIT(1) +#define FGMAC_DMA_TDES0_EXCESSIVE_DEFERRAL BIT(2) +#define FGMAC_DMA_TDES0_COLLISION_COUNT_MASK GENMASK(6, 3) +#define FGMAC_DMA_TDES0_VLAN_FRAME BIT(7) +#define FGMAC_DMA_TDES0_EXCESSIVE_COLLISIONS BIT(8) +#define FGMAC_DMA_TDES0_LATE_COLLISION BIT(9) +#define FGMAC_DMA_TDES0_NO_CARRIER BIT(10) +#define FGMAC_DMA_TDES0_LOSS_CARRIER BIT(11) +#define FGMAC_DMA_TDES0_PAYLOAD_ERROR BIT(12) +#define FGMAC_DMA_TDES0_FRAME_FLUSHED BIT(13) +#define FGMAC_DMA_TDES0_JABBER_TIMEOUT BIT(14) +#define FGMAC_DMA_TDES0_ERROR_SUMMARY BIT(15) +#define FGMAC_DMA_TDES0_IP_HEADER_ERROR BIT(16) +#define FGMAC_DMA_TDES0_TIME_STAMP_STATUS BIT(17) /* 指示已捕获相应发送帧的时间戳 */ +#define FGMAC_DMA_TDES0_OWN BIT(31) /* 该位表示描述符归 DMA 所有 */ + +/* TDES1 包含缓冲区大小和控制描述符链/环和正在传输的帧的其他位 */ +#define FGMAC_DMA_TDES1_BUFFER1_SIZE_MASK GENMASK(10, 0) +#define FGMAC_DMA_TDES1_BUFFER2_SIZE_MASK GENMASK(21, 11) +#define FGMAC_DMA_TDES1_BUFFER2_SIZE_SHIFT 11 +#define FGMAC_DMA_TDES1_TIME_STAMP_ENABLE BIT(22) +#define FGMAC_DMA_TDES1_DISABLE_PADDING BIT(23) +#define FGMAC_DMA_TDES1_SECOND_ADDRESS_CHAINED BIT(24) +#define FGMAC_DMA_TDES1_END_RING BIT(25) +#define FGMAC_DMA_TDES1_CRC_DISABLE BIT(26) +#define FGMAC_DMA_TDES1_CHECKSUM_INSERTION_MASK GENMASK(28, 27) +#define FGMAC_DMA_TDES1_CHECKSUM_INSERTION_SHIFT 27 +#define FGMAC_DMA_TDES1_FIRST_SEGMENT BIT(29) +#define FGMAC_DMA_TDES1_LAST_SEGMENT BIT(30) +#define FGMAC_DMA_TDES1_INTERRUPT BIT(31) + +/********接收描述符********/ + +/* RDES0 包含接收的帧状态,帧长度和描述符所有权信息 */ +#define FGMAC_DMA_RDES0_PAYLOAD_CSUM_ERR BIT(0) +#define FGMAC_DMA_RDES0_CRC_ERROR BIT(1) +#define FGMAC_DMA_RDES0_DRIBBLING BIT(2) +#define FGMAC_DMA_RDES0_MII_ERROR BIT(3) +#define FGMAC_DMA_RDES0_RECEIVE_WATCHDOG BIT(4) +#define FGMAC_DMA_RDES0_FRAME_TYPE BIT(5) +#define FGMAC_DMA_RDES0_COLLISION BIT(6) +#define FGMAC_DMA_RDES0_IPC_CSUM_ERROR BIT(7) +#define FGMAC_DMA_RDES0_LAST_DESCRIPTOR BIT(8) +#define FGMAC_DMA_RDES0_FIRST_DESCRIPTOR BIT(9) +#define FGMAC_DMA_RDES0_VLAN_TAG BIT(10) +#define FGMAC_DMA_RDES0_OVERFLOW_ERROR BIT(11) +#define FGMAC_DMA_RDES0_LENGTH_ERROR BIT(12) +#define FGMAC_DMA_RDES0_SA_FILTER_FAIL BIT(13) +#define FGMAC_DMA_RDES0_DESCRIPTOR_ERROR BIT(14) +#define FGMAC_DMA_RDES0_ERROR_SUMMARY BIT(15) +#define FGMAC_DMA_RDES0_FRAME_LEN_MASK (0x3FFF << 16) /* GENMASK(29, 16)*/ +#define FGMAC_DMA_RDES0_FRAME_LEN_SHIFT 16 +#define FGMAC_DMA_RDES0_DA_FILTER_FAIL BIT(30) +#define FGMAC_DMA_RDES0_OWN BIT(31) + +/* RDES1 包含缓冲区大小和控制描述符链/环的其他位 */ +#define FGMAC_DMA_RDES1_BUFFER1_SIZE_MASK GENMASK(10, 0) +#define FGMAC_DMA_RDES1_BUFFER2_SIZE_MASK GENMASK(21, 11) +#define FGMAC_DMA_RDES1_BUFFER2_SIZE_SHIFT 11 +#define FGMAC_DMA_RDES1_SECOND_ADDRESS_CHAINED BIT(24) +#define FGMAC_DMA_RDES1_END_RING BIT(25) +#define FGMAC_DMA_RDES1_DISABLE_IC BIT(31) + +/* Operational Mode */ +enum +{ + FGMAC_CHECKSUM_BY_SOFTWARE = 0, + FGMAC_CHECKSUM_BY_HARDWARE +}; /* software checksum or hardware checksum */ + +enum +{ + FGMAC_TX_COMPLETE_EVT = 0, + FGMAC_RX_COMPLETE_EVT, + FGMAC_LINK_STATUS_EVT, + FGMAC_PHY_STATUS_EVT, + FGMAC_DMA_ERR_EVT, + + FGMAC_INTR_EVT_NUM +}; /* interrupt event type */ + + +/**************************** Type Definitions *******************************/ + +/** + * This typedef contains configuration information for the device. + */ +typedef struct +{ + u32 instance_id; /* device instance id */ + uintptr base_addr; /* device base address */ + u32 irq_num; /* irq num */ + u32 irq_prority; /* device intrrupt priority */ + u32 cheksum_mode; /* hardware or software checksum */ + u32 duplex_mode; /* selects the MAC duplex mode: Half-Duplex or Full-Duplex mode */ + u32 max_packet_size; /* max num of bytes in frame transfer */ + u32 mdc_clk_hz; /* MDC clock access PHY. [1.0MHz ~2.5MHz] */ + boolean en_auto_negtiation; /* auto-negotiation or not */ + u32 speed; /* sets the Ethernet speed: 10/100/1000 Mbps. */ + +} FGmacConfig; /* FGMAC 驱动配置数据 */ + +/** + * This typedef contains driver instance data. The user is required to allocate a + * variable of this type for every device in the system. A pointer + * to a variable of this type is then passed to the driver API functions. + */ + +typedef struct +{ + volatile u32 status; + u32 ctrl; + u32 buf_addr; + u32 next; +} FGmacDmaDesc; /* FGMAC DMA描述符 */ + +typedef struct +{ + u32 desc_idx; /* For Current Desc position */ + u32 desc_buf_idx; /* For Current Desc buffer buf position */ + u32 desc_max_num; /* Max Number for Desc and Desc buffer */ + u8 *desc_buf_base; /* Desc buffer Base */ +} FGmacRingDescData; /* FGMAC DMA描述符表(链式)相关数据 */ + +typedef void (*FGmacEvtHandler)(void *pCtrl); + +typedef struct +{ + FGmacConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + FGmacRingDescData rx_ring; /* RX DMA descriptor data (idx, length) */ + volatile FGmacDmaDesc *rx_desc; /* RX DMA descriptor table in ring */ + FGmacRingDescData tx_ring; /* TX DMA descriptor data (idx, length) */ + volatile FGmacDmaDesc *tx_desc; /* TX DMA descriptor table in ring */ + FGmacEvtHandler evt_handler[FGMAC_INTR_EVT_NUM]; /* User registered interrupt handler */ + u32 phy_valid_mask; /* phy valid addr sequence mask */ + u32 phy_speed; + u32 phy_addr; /* phy max valid addr, or the unique value */ + u16 phy_id1; /*phy tag,only value to identify phy*/ +} FGmac; /* FGMAC 驱动控制数据 */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/* 获取FGMAC驱动的默认配置参数 */ +const FGmacConfig *FGmacLookupConfig(u32 instance_id); + +/* 完成FGMAC驱动实例的初始化,使之可以使用 */ +FError FGmacCfgInitialize(FGmac *instance_p, const FGmacConfig *cofig_p); + +/* 完成FGMAC驱动实例去使能,清零实例数据 */ +FError FGmacDeInitialize(FGmac *instance_p); + +/* 配置FGMAC的发送DMA描述符和缓冲区 */ +FError FGmacSetupTxDescRing(FGmac *instance_p, volatile FGmacDmaDesc *tx_desc_tbl, + u8 *tx_buf, const fsize_t tx_pre_buf_len, const fsize_t tx_buf_num); + +/* 配置FGMAC的接收DMA描述符和缓冲区 */ +FError FGmacSetupRxDescRing(FGmac *instance_p, volatile FGmacDmaDesc *rx_desc_tbl, + u8 *rx_buf, const fsize_t rx_pre_buf_len, const fsize_t rx_buf_num); + +/* FGMAC中断处理函数 */ +void FGmacInterruptHandler(s32 vector, void *param); + +/* 注册FGMAC中断事件处理函数 */ +void FGmacRegisterEvtHandler(FGmac *instance_p, u32 evt, FGmacEvtHandler handler); + +/* 使能FGMAC DMA,使之可以接收/发送数据 */ +FError FGmacStartTrans(FGmac *instance_p); + +/* 去使能FGMAC DMA, 使之不再能接收/发送数据 */ +FError FGmacStopTrans(FGmac *instance_p); + +/* 通过FGMAC接收数据帧 */ +FError FGmacRecvFrame(FGmac *instance_p); + +/* 通过FGMAC发送数据帧 */ +FError FGmacSendFrame(FGmac *instance_p, u32 frame_len); + +/* 设置FGMAC中断屏蔽位 */ +void FGmacSetInterruptMask(FGmac *instance_p, u32 intr_type, u32 mask); + +/* 设置FGMAC中断使能位 */ +void FGmacSetInterruptUmask(FGmac *instance_p, u32 intr_type, u32 mask); + +/*fgmac deplex mode configuration */ +void FGmacControllerDuplexConfig(FGmac *instance_p, u32 duplex); + +/*fgmac speed configuration */ +void FGmacControllerSpeedConfig(FGmac *instance_p, u32 speed); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_dma.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_dma.c new file mode 100644 index 0000000000..019c4f659a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_dma.c @@ -0,0 +1,342 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_dma.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include +#include "fassert.h" +#include "fkernel.h" +#include "fcache.h" +#include "fdebug.h" +#include "fgmac.h" +#include "fgmac_hw.h" + +/************************** Constant Definitions *****************************/ +#if defined(__aarch64__) + #define FGMAC_DMA_IS_64_BIT_MEMORY(addr) (GENMASK_ULL(63, 32) & (uintptr)(addr)) +#else + #define FGMAC_DMA_IS_64_BIT_MEMORY(addr) (FALSE) +#endif + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGMAC_DEBUG_TAG "FGMAC-DMA" +#define FGMAC_ERROR(format, ...) FT_DEBUG_PRINT_E(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_WARN(format, ...) FT_DEBUG_PRINT_W(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_INFO(format, ...) FT_DEBUG_PRINT_I(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + +/** + * @name: FGmacSetupTxDescRing + * @msg: 配置FGMAC的接收DMA描述符和缓冲区 + * @param {FGmac *}instance_p 驱动控制数据 + * {volatile FGmacDmaDesc *} rx_desc_tbl 接收DMA描述符表(数组) + * {u8} *rx_buf 接收DMA缓冲区(数组,每一个描述符对应一个缓冲区) + * {const fsize_t} rx_pre_buf_len 单个DMA缓冲区的字节数 + * {const fsize_t} rx_buf_num DMA描述符或者DMA缓存区的数目 + * @return {FError} RX DMA初始化的错误码信息,FGMAC_SUCCESS 表示RX DMA初始化成功,其它返回值表示RX DMA初始化失败 + * @note 传入的rx_desc_tbl和rx_buf必须为32位空间地址 + */ +FError FGmacSetupRxDescRing(FGmac *instance_p, volatile FGmacDmaDesc *rx_desc_tbl, + u8 *rx_buf, const fsize_t rx_pre_buf_len, const fsize_t rx_buf_num) +{ + FASSERT(instance_p && rx_desc_tbl && rx_buf); + u32 i; + volatile FGmacDmaDesc *cur_rx_desc; + FGmacRingDescData *rx_ring_p = &instance_p->rx_ring; + uintptr base_addr = instance_p->config.base_addr; + void *desc_end = (void *)(rx_desc_tbl + rx_buf_num * sizeof(FGmacDmaDesc)); + void *buf_end = (void *)(rx_buf + rx_buf_num * rx_pre_buf_len); + + /* check if end address of descriptor or buffer is in 64 bit memory, + if TRUE, return error because DMA register can only hold 32 bit memory address */ + if ((FGMAC_DMA_IS_64_BIT_MEMORY(desc_end)) || (FGMAC_DMA_IS_64_BIT_MEMORY(buf_end))) + { + FGMAC_ERROR("invalid rx descriptor memory %p or rx dma buf memory %p", + desc_end, buf_end); + return FGMAC_ERR_INVALID_DMA_MEM; + } + + /* init rx dma ring data */ + memset(rx_ring_p, 0, sizeof(*rx_ring_p)); + rx_ring_p->desc_max_num = rx_buf_num; /* total num of rx desc and rx buf */ + rx_ring_p->desc_idx = 0; /* idx of rx desc */ + rx_ring_p->desc_buf_idx = 0; /* idx of rx buf */ + rx_ring_p->desc_buf_base = rx_buf; /* base addr of rx buf */ + + /* init rx dma descriptor table */ + memset((void *)rx_desc_tbl, 0, sizeof(FGmacDmaDesc) * rx_buf_num); + + for (i = 0; i < rx_buf_num; i++) + { + cur_rx_desc = rx_desc_tbl + i; + cur_rx_desc->status = FGMAC_DMA_RDES0_OWN; + cur_rx_desc->ctrl = (FGMAC_DMA_RDES1_BUFFER1_SIZE_MASK & rx_pre_buf_len); + FCacheDCacheInvalidateRange((uintptr)&rx_buf[i * rx_pre_buf_len], rx_pre_buf_len); + cur_rx_desc->buf_addr = (u32)((uintptr)&rx_buf[i * rx_pre_buf_len]); + + if ((rx_buf_num - 1) == i) + { + cur_rx_desc->ctrl |= FGMAC_DMA_RDES1_END_RING; + } + } + + /* flush descriptor */ + instance_p->rx_desc = rx_desc_tbl; + FCacheDCacheInvalidateRange((uintptr)instance_p->rx_desc, sizeof(FGmacDmaDesc) * rx_buf_num); + + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_RX_LIST_BASE_OFFSET, (u32)(uintptr)rx_desc_tbl); + return FGMAC_SUCCESS; +} + +/** + * @name: FGmacSetupTxDescRing + * @msg: 配置FGMAC的发送DMA描述符和缓冲区 + * @param {FGmac *}instance_p 驱动控制数据 + * {volatile FGmacDmaDesc *} tx_desc_tbl 发送DMA描述符表(数组) + * {u8} *tx_buf 发送DMA缓冲区(数组,每一个描述符对应一个缓冲区) + * {const fsize_t} tx_pre_buf_len 单个DMA缓冲区的字节数 + * {const fsize_t} tx_buf_num DMA描述符或者DMA缓存区的数目 + * @return {FError} TX DMA初始化的错误码信息,FGMAC_SUCCESS 表示TX DMA初始化成功,其它返回值表示TX DMA初始化失败 + * @note 传入的tx_desc_tbl和tx_buf必须为32位空间地址 + */ +FError FGmacSetupTxDescRing(FGmac *instance_p, volatile FGmacDmaDesc *tx_desc_tbl, + u8 *tx_buf, const fsize_t tx_pre_buf_len, const fsize_t tx_buf_num) +{ + FASSERT(instance_p && tx_desc_tbl && tx_buf); + u32 i; + volatile FGmacDmaDesc *cur_tx_desc; + FGmacRingDescData *tx_ring_p = &instance_p->tx_ring; + uintptr base_addr = instance_p->config.base_addr; + void *desc_end = (void *)(tx_desc_tbl + tx_buf_num * sizeof(FGmacDmaDesc)); + void *buf_end = (void *)(tx_buf + tx_buf_num * tx_pre_buf_len); + + /* check if end address of descriptor or buffer is in 64 bit memory, + if TRUE, return error because DMA register can only hold 32 bit memory address */ + if ((FGMAC_DMA_IS_64_BIT_MEMORY(desc_end)) || (FGMAC_DMA_IS_64_BIT_MEMORY(buf_end))) + { + FGMAC_ERROR("invalid rx descriptor memory %p or rx dma buf memory %p", + desc_end, buf_end); + return FGMAC_ERR_INVALID_DMA_MEM; + } + + /* setup DMA descriptor ring data */ + memset(tx_ring_p, 0, sizeof(*tx_ring_p)); + tx_ring_p->desc_max_num = tx_buf_num; + tx_ring_p->desc_idx = 0; + tx_ring_p->desc_buf_idx = 0; + tx_ring_p->desc_buf_base = tx_buf; + + /* setup DMA descriptor */ + memset((void *)tx_desc_tbl, 0, tx_buf_num * sizeof(FGmacDmaDesc)); + tx_desc_tbl[tx_buf_num - 1].ctrl |= FGMAC_DMA_TDES1_END_RING; + for (i = 0; i < tx_buf_num; i++) + { + cur_tx_desc = tx_desc_tbl + i; + FCacheDCacheInvalidateRange((uintptr)&tx_buf[i * tx_pre_buf_len], tx_pre_buf_len); + cur_tx_desc->buf_addr = (u32)((uintptr)&tx_buf[i * tx_pre_buf_len]); + cur_tx_desc->status = 0; + } + + /* flush descriptor */ + instance_p->tx_desc = tx_desc_tbl; + FCacheDCacheInvalidateRange((uintptr)instance_p->tx_desc, tx_buf_num * sizeof(FGmacDmaDesc)); + + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_TX_LIST_BASE_OFFSET, (u32)(uintptr)tx_desc_tbl); + return FGMAC_SUCCESS; +} + +/** + * @name: FGmacStartTrans + * @msg: 使能FGMAC DMA,使之可以接收/发送数据 + * @return {FError} FGMAC_SUCCESS 表示启动成功,其它返回值表示启动失败 + * @param {FGmac} *instance_p 驱动控制数据 + * @note 调用函数前需要确保FGMAC驱动初始化成功 + */ +FError FGmacStartTrans(FGmac *instance_p) +{ + FASSERT(instance_p); + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGMAC_ERROR("device is already initialized!!!"); + return FGMAC_ERR_NOT_READY; + } + + FGmacStartDmaTrans(instance_p->config.base_addr); + return FGMAC_SUCCESS; +} + +/** + * @name: FGmacStopTrans + * @msg: 去使能FGMAC DMA, 使之不再能接收/发送数据 + * @return {FError} FGMAC_SUCCESS 表示去启动成功,其它返回值表示去启动失败 + * @param {FGmac} *instance_p 驱动控制数据 + * @note 调用函数前需要确保FGMAC驱动初始化成功 + */ +FError FGmacStopTrans(FGmac *instance_p) +{ + FASSERT(instance_p); + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FGMAC_ERROR("device is already initialized!!!"); + return FGMAC_ERR_NOT_READY; + } + + FGmacStopDmaTrans(instance_p->config.base_addr); + return FGMAC_SUCCESS; +} + +/** + * @name: FGmacRecvFrame + * @msg: 通过FGMAC接收数据帧 + * @return {FError} FGMAC_SUCCESS 表示接收数据帧成功,其它返回值表示接收数据帧失败 + * @param {FGmac} *instance_p 驱动控制数据 + * @note 调用函数前需要确保FGMAC驱动初始化成功 + */ +FError FGmacRecvFrame(FGmac *instance_p) +{ + FASSERT(instance_p); + FGmacRingDescData *rx_ring = &instance_p->rx_ring; + volatile FGmacDmaDesc *cur_rx_desc = &instance_p->rx_desc[rx_ring->desc_idx]; + u32 desc_cnt = 0; + u32 flag = (FGMAC_DMA_RDES0_FIRST_DESCRIPTOR | FGMAC_DMA_RDES0_LAST_DESCRIPTOR); + + while ((0 == (FGMAC_DMA_RDES0_OWN & cur_rx_desc->status)) && + (desc_cnt < rx_ring->desc_max_num)) + { + desc_cnt++; + + if (FGMAC_DMA_RDES0_FIRST_DESCRIPTOR == (flag & cur_rx_desc->status)) + { + rx_ring->desc_buf_idx = rx_ring->desc_idx; + FGMAC_DMA_INC_DESC(rx_ring->desc_idx, rx_ring->desc_max_num); + cur_rx_desc = &instance_p->rx_desc[rx_ring->desc_idx]; + } + else if (0 == (flag & cur_rx_desc->status)) + { + FGMAC_DMA_INC_DESC(rx_ring->desc_idx, rx_ring->desc_max_num); + cur_rx_desc = &instance_p->rx_desc[rx_ring->desc_idx]; + } + else + { + rx_ring->desc_buf_idx = rx_ring->desc_idx; + FGMAC_DMA_INC_DESC(rx_ring->desc_idx, rx_ring->desc_max_num); + return FGMAC_SUCCESS; + } + } + + return FGMAC_ERR_TRANS_FAILED; +} + +/** + * @name: FGmacSendFrame + * @msg: 通过FGMAC发送数据帧 + * @return {FError} FGMAC_SUCCESS 表示发送数据帧成功,其它返回值表示发送数据帧失败 + * @param {FGmac} *instance_p 驱动控制数据 + * @param {u32} frame_len 数据帧长度 + * @note 调用函数前需要确保FGMAC驱动初始化成功 + */ +FError FGmacSendFrame(FGmac *instance_p, u32 frame_len) +{ + FASSERT(instance_p); + u32 size = 0U; + u32 i = 0U; + u32 buf_cnt = 0U; + FError ret = FGMAC_SUCCESS; + volatile FGmacDmaDesc *tx_desc; + FGmacRingDescData *tx_ring = &instance_p->tx_ring; + const u32 max_packet_size = instance_p->config.max_packet_size; + + if (0U == frame_len) + { + return FGMAC_SUCCESS; + } + + if (max_packet_size < frame_len) + { + buf_cnt = frame_len / max_packet_size; + if (frame_len % max_packet_size) + buf_cnt++; + } + else + { + buf_cnt = 1U; + } + + if (1U == buf_cnt) + { + tx_desc = &instance_p->tx_desc[tx_ring->desc_idx]; + + /* Set LAST and FIRST segment */ + tx_desc->ctrl |= (FGMAC_DMA_TDES1_FIRST_SEGMENT | FGMAC_DMA_TDES1_LAST_SEGMENT); + + /* Set frame size */ + tx_desc->ctrl &= ~(FGMAC_DMA_TDES1_BUFFER1_SIZE_MASK); + tx_desc->ctrl |= (frame_len & FGMAC_DMA_TDES1_BUFFER1_SIZE_MASK); + + /* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */ + tx_desc->status |= FGMAC_DMA_TDES0_OWN; + FGMAC_DMA_INC_DESC(tx_ring->desc_idx, tx_ring->desc_max_num); + + } + else + { + for (i = 0U; i < buf_cnt; i++) + { + tx_desc = &instance_p->tx_desc[tx_ring->desc_idx]; + + /* Clear FIRST and LAST segment bits */ + tx_desc->ctrl &= ~(FGMAC_DMA_TDES1_FIRST_SEGMENT | FGMAC_DMA_TDES1_LAST_SEGMENT); + + if (0U == i) + { + tx_desc->ctrl |= FGMAC_DMA_TDES1_FIRST_SEGMENT; /* Setting the first segment bit */ + } + + /* Program size */ + tx_desc->ctrl &= ~(FGMAC_DMA_TDES1_BUFFER1_SIZE_MASK); + tx_desc->ctrl |= (max_packet_size & FGMAC_DMA_TDES1_BUFFER1_SIZE_MASK); + + if ((buf_cnt - 1) == i) + { + /* Setting the last segment bit */ + tx_desc->ctrl |= FGMAC_DMA_TDES1_LAST_SEGMENT; + size = frame_len - (buf_cnt - 1U) * max_packet_size; + tx_desc->ctrl &= ~(FGMAC_DMA_TDES1_BUFFER1_SIZE_MASK); + tx_desc->ctrl |= (size & FGMAC_DMA_TDES1_BUFFER1_SIZE_MASK); + } + + /* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */ + tx_desc->status |= FGMAC_DMA_TDES0_OWN; + FGMAC_DMA_INC_DESC(tx_ring->desc_idx, tx_ring->desc_max_num); + } + } + + FGmacResumeDmaSend(instance_p->config.base_addr); + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_g.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_g.c new file mode 100644 index 0000000000..a72ab1b34b --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_g.c @@ -0,0 +1,65 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_g.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/* - This file contains a configuration table that specifies the configuration +- 驱动全局变量定义,包括静态配置参数 */ + +/***************************** Include Files *********************************/ + +#include "fparameters.h" +#include "fgmac.h" + +/************************** Constant Definitions *****************************/ + +const FGmacConfig FGMAC_CONFIG_TBL[GMAC_INSTANCE_NUM] = +{ + [GMAC_INSTANCE_0] = + { + .instance_id = GMAC_INSTANCE_0, + .base_addr = GMAC_INSTANCE_0_BASE_ADDR, + .irq_num = GMAC_INSTANC_0_IRQ, + .irq_prority = 0, + .cheksum_mode = FGMAC_CHECKSUM_BY_SOFTWARE, + .max_packet_size = GMAC_MAX_PACKET_SIZE + }, + + [GMAC_INSTANCE_1] = + { + .instance_id = GMAC_INSTANCE_1, + .base_addr = GMAC_INSTANCE_1_BASE_ADDR, + .irq_num = GMAC_INSTANC_1_IRQ, + .irq_prority = 0, + .cheksum_mode = FGMAC_CHECKSUM_BY_SOFTWARE, + .max_packet_size = GMAC_MAX_PACKET_SIZE + } +}; + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_hw.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_hw.c new file mode 100644 index 0000000000..b4a493a2dd --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_hw.c @@ -0,0 +1,166 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_hw.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fassert.h" +#include "fdebug.h" + +#include "fgmac.h" +#include "fgmac_hw.h" + + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGMAC_DEBUG_TAG "FGMAC-HW" +#define FGMAC_ERROR(format, ...) FT_DEBUG_PRINT_E(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_WARN(format, ...) FT_DEBUG_PRINT_W(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_INFO(format, ...) FT_DEBUG_PRINT_I(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/** + * @name: FGmacGetMacAddr + * @msg: 获取FGMAC控制器配置的MAC地址 + * @return {*} + * @param {uintptr} base_addr 控制器寄存器基地址 + * @param {FGmacMacAddr} mac_addr 配置的MAC地址 + */ +void FGmacGetMacAddr(uintptr base_addr, FGmacMacAddr mac_addr) +{ + u32 mac_high = FGMAC_READ_REG32(base_addr, FGMAC_MAC_ADDR0_UPPER16BIT_OFFSET); + u32 mac_low = FGMAC_READ_REG32(base_addr, FGMAC_MAC_ADDR0_LOWER32BIT_OFFSET); + + /* get lower 32 bits of mac addr */ + mac_addr[0] = (u8)(mac_low & 0xff); + mac_addr[1] = (u8)((mac_low >> 8) & 0xff); + mac_addr[2] = (u8)((mac_low >> 16) & 0xff); + mac_addr[3] = (u8)((mac_low >> 24) & 0xff); + + /* get upper 16 bits of mac addr */ + mac_addr[4] = (u8)(mac_high & 0xff); + mac_addr[5] = (u8)((mac_high >> 8) & 0xff); + + return; +} + +/** + * @name: FGmacSetMacAddr + * @msg: 设置FGMAC控制器的MAC地址 + * @return {*} + * @param {uintptr} base_addr 控制器寄存器基地址 + * @param {FGmacMacAddr} mac_addr 配置的MAC地址 + */ +void FGmacSetMacAddr(uintptr base_addr, const FGmacMacAddr mac_addr) +{ + u32 reg_val; + + reg_val = ((u32)mac_addr[5] << 8) | (u32)mac_addr[4]; + FGMAC_WRITE_REG32(base_addr, FGMAC_MAC_ADDR0_UPPER16BIT_OFFSET, reg_val); + reg_val = ((u32)mac_addr[3] << 24) | ((u32)mac_addr[2] << 16) | ((u32)mac_addr[1] << 8) | mac_addr[0]; + FGMAC_WRITE_REG32(base_addr, FGMAC_MAC_ADDR0_LOWER32BIT_OFFSET, reg_val); + + return; +} + +/** + * @name: FGmacSoftwareReset + * @msg: 触发FGMAC控制器软件复位 GMac DMA寄存器列表 和 控制寄存器列表 + * @return {*} + * @param {uintptr} base_addr 控制器寄存器基地址 + * @param {int} timeout 等待复位完成的状态检测周期数目 + */ +FError FGmacSoftwareReset(uintptr base_addr, int timeout) +{ + FASSERT(timeout > 1); /* 至少等待一个周期 */ + u32 reg_val; + + FGMAC_SET_REG32(base_addr, FGMAC_DMA_BUS_MODE_OFFSET, FGMAC_DMA_BUS_SWR); /*最后一位写为1 此时MAC DMA 控制器将复位所有 GMAC子系统内部寄存器和逻辑。 完成后会自动清0*/ + do + { + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_DMA_BUS_MODE_OFFSET); + } + while ((reg_val & FGMAC_DMA_BUS_SWR) && (--timeout > 0)); /*判断swr位是否为1,当读到0时此时判断 复位操作已完成 软件复位成功*/ + + if ((0 >= timeout) && (reg_val & FGMAC_DMA_BUS_SWR)) + { + FGMAC_ERROR("reset timeout, please check phy connection!!!"); + return FGMAC_ERR_TIMEOUT; + } + + return FGMAC_SUCCESS; +} + +FError FGmacFlushTxFifo(uintptr base_addr, int timeout) +{ + FASSERT(timeout > 1); /* 至少等待一个周期 */ + u32 reg_val; + FGMAC_SET_REG32(base_addr, FGMAC_DMA_OP_OFFSET, FGMAC_DMA_OP_FTF); + + do + { + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_DMA_OP_OFFSET); + } + while ((reg_val & FGMAC_DMA_OP_FTF) && (--timeout > 0)); + + if ((0 >= timeout) && (reg_val & FGMAC_DMA_OP_FTF)) + { + FGMAC_ERROR("flush tx fifo timeout !!!"); + return FGMAC_ERR_TIMEOUT; + } + + return FGMAC_SUCCESS; +} + +/** + * @name: FGmacPhyWaitBusBusy + * @msg: wait phy gmii is not busy + * @param {uintptr} base_addr, base address of FGmac controller register + * @param {int} timeout, wait timeout + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacPhyWaitBusBusy(uintptr base_addr, int timeout) +{ + u32 reg_val; + + /* Check for the Busy flag */ + do + { + reg_val = FGMAC_READ_REG32(base_addr, FGMAC_GMII_ADDR_OFFSET); + } + while ((FGMAC_MII_ADDR_GB & reg_val) && (0 <= --timeout)); + + if (0 >= timeout) + { + FGMAC_ERROR("timeout when wait GMII timeout"); + return FGMAC_ERR_TIMEOUT; + } + + return FGMAC_SUCCESS; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_hw.h b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_hw.h new file mode 100644 index 0000000000..d192d81f4c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_hw.h @@ -0,0 +1,554 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_hw.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_ETH_FGMAC_HW_H +#define DRIVERS_ETH_FGMAC_HW_H + + +/* - 传入模块基地址,不能复杂结构体 +- hardware interface of device || low-level driver function prototypes + +- 包括驱动寄存器参数和low-level操作定义 +1. 定义寄存器偏移 +2. 对上提供该模块寄存器操作的接口 +3. 一些简单外设提供直接操作接口 +4. 可以定义一些状态的接口,用于响应驱动状态的变化 + +note: 本文件不能引用fooxx.h +*/ + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fkernel.h" +#include "fio.h" +#include "ftypes.h" + +/************************** Constant Definitions *****************************/ + +/** @name Register Map + * + * Register offsets from the base address of an SD device. + * @{ + */ +/**** FGMAC CTRL ****/ +#define FGMAC_CONF_OFFSET 0x00U /* MAC 配置寄存器 */ +#define FGMAC_FRAME_FILTER_OFFSET 0x04U /* Mac 帧过滤 */ +#define FGMAC_HASH_HIGH_OFFSET 0x08U /* 哈希表高位寄存器 */ +#define FGMAC_HASH_LOW_OFFSET 0x0cU /* 哈希表低位寄存器 */ +#define FGMAC_GMII_ADDR_OFFSET 0x10U /* GMII 地址寄存器 */ +#define FGMAC_GMII_DATA_OFFSET 0x14U /* GMII 数据寄存器 */ +#define FGMAC_FLOW_CTRL_OFFSET 0x18U /* 流控寄存器 */ +#define FGMAC_VLAN_TAG_OFFSET 0x1cU /* VLAN 标记寄存器 */ +#define FGMAC_VERSION_OFFSET 0x20U /* 版本寄存器 */ +#define FGMAC_DEBUG_STATUS_OFFSET 0x24U /* 调试寄存器 */ +#define FGMAC_LPI_CTRL_STATUS_OFFSET 0x30U /* LPI (低功耗空闲) 控制和状态寄存器 */ +#define FGMAC_LPI_TIMER_CTRL_OFFSET 0x34U /* LPI 定时器控制寄存器 */ +#define FGMAC_INTR_STATUS_OFFSET 0x38U /* 中断状态寄存器 */ +#define FGMAC_INTR_MASK_OFFSET 0x3CU /* 中断屏蔽寄存器 */ +#define FGMAC_MAC_ADDR0_UPPER16BIT_OFFSET 0x40U /* 第一个 MAC 地址的高 16 位。 */ +#define FGMAC_MAC_ADDR0_LOWER32BIT_OFFSET 0x44U /* 第一个 MAC 地址的低 32 位。。 */ +#define FGMAC_MAC_ADDR1_UPPER16BIT_OFFSET 0x48U /* 第二个 MAC 地址的高 16 位。 */ +#define FGMAC_MAC_ADDR1_LOWER32BIT_OFFSET 0x4CU /* 第二个 MAC 地址的低 32 位。。 */ +#define FGMAC_MAC_PHY_STATUS 0xD8U /* MAC PHY 状态 */ + +/**** FGMAC DMA CTRL ****/ +#define FGMAC_DMA_BUS_MODE_OFFSET 0x1000U /* 总线模式寄存器 */ +#define FGMAC_DMA_TX_POLL_REQ_OFFSET 0x1004U /* 发送轮询请求寄存器 */ +#define FGMAC_DMA_RX_POLL_REQ_OFFSET 0x1008U /* 接收轮询请求寄存器 */ +#define FGMAC_DMA_RX_LIST_BASE_OFFSET 0x100cU /* 接收描述符列表地址寄存器 */ +#define FGMAC_DMA_TX_LIST_BASE_OFFSET 0x1010U /* 发送描述符列表地址寄存器 */ +#define FGMAC_DMA_STATUS_OFFSET 0x1014U /* 状态寄存器 */ +#define FGMAC_DMA_OP_OFFSET 0x1018U /* 操作模式寄存器 */ +#define FGMAC_DMA_INTR_OFFSET 0x101cU /* 中断使能寄存器 */ +#define FGMAC_DMA_MISSED_FRAME_CNT_OFFSET 0x1020U /* 丢帧和缓冲区溢出计数器寄存器 */ +#define FGMAC_DMA_RX_WATCHDOG_OFFSET 0x1024U /* 接收中断看门狗定时器寄存器 */ +#define FGMAC_DMA_AXI_BUS_MOD_OFFSET 0x1028U /* AXI 总线模式寄存器*/ +#define FGMAC_DMA_AXI_BUS_STATUS_OFFSET 0x102CU /* AXI 状态寄存器 */ +#define FGMAC_DMA_HOST_TX_DESC_OFFSET 0x1048U /* 当前主机发送描述符寄存器 */ +#define FGMAC_DMA_HOST_RX_DESC_OFFSET 0x104CU /* 当前主机接收描述符寄存器 */ +#define FGMAC_DMA_HOST_TX_BUF_ADDR_OFFSET 0x1050U /* 当前主机发送缓冲地址寄存器 */ +#define FGMAC_DMA_HOST_RX_BUF_ADDR_OFFSET 0x1054U /* 当前主机接收缓冲地址寄存器 */ +#define FGMAC_DMA_HW_FUNC_OFFSET 0x1058U /* 硬件功能寄存器 */ + +/** @name FGMAC_CONF_OFFSET Register + */ +#define FGMAC_CONF_RX_EN BIT(2) /* 接收器启用 */ +#define FGMAC_CONF_TX_EN BIT(3) /* 发送器启用 */ +#define FGMAC_CONF_DC BIT(4) /* 延期检查 */ +#define FGMAC_CONF_BL_MASK GENMASK(6, 5) /* 后退限制 */ +#define FGMAC_CONF_BL(x) (FGMAC_CONF_BL_MASK & ((x) << 5)) +#define FGMAC_CONF_ACS BIT(7) /* 自动 PAD/ CRC 剥线 */ +#define FGMAC_CONF_LINK_UPDOWN BIT(8) /* 链接 up/down */ +#define FGMAC_CONF_DISABLE_RETRY BIT(9) /* 禁用重试 */ +#define FGMAC_CONF_IPC BIT(10) /* 校验和卸载 */ +#define FGMAC_CONF_DUPLEX_MODE BIT(11) /* 双工模式 */ +#define FGMAC_CONF_LOOPBACK_MODE BIT(12) /* 环回模式 */ +#define FGMAC_CONF_DO BIT(13) /* 不能自接收 */ +#define FGMAC_CONF_FES BIT(14) /* 速度选择 0: 10Mbps, 1: 100Mbps d2000 ft2004手册有误*/ +#define FGMAC_CONF_PORTSELECT BIT(15) /* 端口选择 0: GMII(1000Mbps)1: MII(10/100Mbps) */ +#define FGMAC_CONF_DCRS BIT(16) /* 传输过程中禁用载波侦听 */ +#define FGMAC_CONF_IFG_MASK GENMASK(19, 17) /* 帧内间隔 */ +#define FGMAC_CONF_IFG(x) (FGMAC_CONF_IFG_MASK & ((x) << 17)) +#define FGMAC_CONF_JE BIT(20) /* 使用Jumbo帧 */ +#define FGMAC_CONF_BE BIT(21) /* 帧突发启用 */ +#define FGMAC_CONF_JD BIT(22) /* Jabber 禁用 */ +#define FGMAC_CONF_WD BIT(23) /* 看门狗禁用 */ +#define FGMAC_CONF_TC BIT(24) /* 在 RGMII 中传输配置 */ +#define FGMAC_CONF_CST BIT(25) /* 类型帧的 CRC 剥离 */ + +/* 使能类型帧的CRC剥离、禁用看门狗WD、禁用Jabber JD、帧突发启用BE、不能自接收DO(全双工保留)*/ +#define FGMAC_CONF_INIT (FGMAC_CONF_CST| FGMAC_CONF_WD| FGMAC_CONF_JD| FGMAC_CONF_BE| FGMAC_CONF_DO) + +/** @name FGMAC_FRAME_FILTER_OFFSET Register + */ +#define FGMAC_FRAME_FILTER_PR BIT(0) +#define FGMAC_FRAME_FILTER_HUC BIT(1) /* 哈希单播 */ +#define FGMAC_FRAME_FILTER_HMC BIT(2) /* 哈希多播 */ +#define FGMAC_FRAME_FILTER_DAIF BIT(3) /* 目的地址反向过滤 */ +#define FGMAC_FRAME_FILTER_PM BIT(4) /* 通过所有多播 */ +#define FGMAC_FRAME_FILTER_DBF BIT(5) /* 禁用广播帧 */ +#define FGMAC_FRAME_FILTER_PCF_MASK (GENMASK(7, 6)) /* 通过控制帧 */ +#define FGMAC_FRAME_FILTER_PCF(x) ((x) << 6) +#define FGMAC_FRAME_FILTER_SAIF BIT(8) /* 源地址反相过滤 */ +#define FGMAC_FRAME_FILTER_SAF BIT(9) /* 源地址过滤使能 */ +#define FGMAC_FRAME_FILTER_HPF BIT(10) /* hash 或 perfect 过滤器 */ +#define FGMAC_FRAME_FILTER_RA BIT(31) /* 全部接收 */ + +/** @name FGMAC_HASH_HIGH_OFFSET Register + */ +#define FGMAC_HASH_HIGH_HTH_MASK GENMASK(31, 0) /* 该字段包含 Hash 表的高 32 位。 */ + +/** @name FGMAC_HASH_LOW_OFFSET Register + */ +#define FGMAC_HASH_LOW_HTH_MASK GENMASK(31, 0) /* 该字段包含 Hash 表的低 32 位。 */ + +/** @name FGMAC_GMII_ADDR_OFFSET Register + */ +#define FGMAC_MII_ADDR_GB BIT(0) /* GMII 忙 */ +#define FGMAC_MII_ADDR_GW BIT(1) /* GMII 写 */ +#define FGMAC_MII_ADDR_CR_MASK GENMASK(5, 2) /* CSR 时钟范围 */ +#define FGMAC_MII_ADDR_CR(x) (FGMAC_MII_ADDR_CR_MASK & ((x) << 2)) +#define FGMAC_MII_ADDR_GR_MASK GENMASK(10, 6) /* GMII 寄存器 */ +#define FGMAC_MII_ADDR_GR(x) (FGMAC_MII_ADDR_GR_MASK & ((x) << 6)) +#define FGMAC_MII_ADDR_PA_MASK GENMASK(15, 11) /* 物理层地址 */ +#define FGMAC_MII_ADDR_PA(x) (FGMAC_MII_ADDR_PA_MASK & ((x) << 11)) + +/** @name FGMAC_GMII_DATA_OFFSET Register + */ +#define FGMAC_MII_DATA_GD_MASK GENMASK(15, 0) + +/** @name FGMAC_FLOW_CTRL_OFFSET Register + */ +#define FGMAC_FLOW_FCB BIT(0) +#define FGMAC_FLOW_BPA BIT(0) +#define FGMAC_FLOW_TFE BIT(1) +#define FGMAC_FLOW_RFE BIT(2) /* 接收流控制启用 */ +#define FGMAC_FLOW_UP BIT(3) /* 单播暂停帧检测 */ +#define FGMAC_FLOW_PLT_MASK GENMASK(5, 4) /* 暂停低阈值 */ +#define FGMAC_FLOW_PLT(x) ((x) << 3) +#define FGMAC_FLOW_DZPQ BIT(7) +#define FGMAC_FLOW_PT_MASK GENMASK(31, 16) /* 暂停时间 */ + +/** @name FGMAC_VLAN_TAG_OFFSET Register + */ +#define FGMAC_VLAN_TAG_VL_MASK GENMASK(15, 0) /* 启用 12 位 VLAN 标记比较 */ +#define FGMAC_VLAN_TAG_VL(x) (FGMAC_VLAN_TAG_VL_MASK & ((x) << 15)) +#define FGMAC_VLAN_TAG_ETV BIT(16) /* 接收帧的 VLAN 标记标识符 */ + +/** @name FGMAC_VERSION_OFFSET Register + */ +#define FGMAC_VERSION_UDV_MASK GENMASK(15, 8) /* 用户定义版本号 */ +#define FGMAC_VERSION_SDV_MASK GENMASK(7, 0) /* 硬件定议版本号 */ + +/** @name FGMAC_LPI_CTRL_STATUS_OFFSET Register + */ +#define FGMAC_LPI_CTRL_STATS_TLPIEN BIT(0) /* 发送 LPI 进入 */ +#define FGMAC_LPI_CTRL_STATS_TLPIEX BIT(1) /* 发送 LPI 退出 */ +#define FGMAC_LPI_CTRL_STATS_RLPIEN BIT(2) /* 接收 LPI 进入 */ +#define FGMAC_LPI_CTRL_STATS_RLPIEX BIT(3) /* 接收 LPI 退出 */ +#define FGMAC_LPI_CTRL_STATS_TLPIST BIT(8) /* 发送 LPI 状态 */ +#define FGMAC_LPI_CTRL_STATS_RLPIST BIT(9) /* 接收 LPI 状态 */ +#define FGMAC_LPI_CTRL_STATS_LPIEN BIT(16) /* LPI 使能 */ +#define FGMAC_LPI_CTRL_STATS_PLS BIT(17) /* PHY 链路状态 */ +#define FGMAC_LPI_CTRL_STATS_PLSEN BIT(18) /* 物理链路状态使能 */ +#define FGMAC_LPI_CTRL_STATS_LPITXA BIT(19) /* LPI 发送自动化 */ + +/** @name FGMAC_LPI_TIMER_CTRL_OFFSET Register + */ +#define FGMAC_LPI_TIMER_TWT_MASK GENMASK(15, 0) +#define FGMAC_LPI_TIMER_LIT_MASK GENMASK(25, 16) + +/** @name FGMAC_INTR_STATUS_OFFSET Register + */ +#define FGMAC_ISR_STATUS_RSIS BIT(0) /* RGMII/SMII Interrupt Status */ +#define FGMAC_ISR_STATUS_PCSLSC BIT(1) /* PCS 链路状态改变 */ +#define FGMAC_ISR_STATUS_PCSANC BIT(2) /* PCS 自协商完成 */ +#define FGMAC_ISR_STATUS_PMTIS BIT(3) +#define FGMAC_ISR_STATUS_MMCIS BIT(4) +#define FGMAC_ISR_STATUS_MMCRIS BIT(5) /* MMC 接收中断状态 */ +#define FGMAC_ISR_STATUS_MMCTIS BIT(6) /* MMC 发送中断状态 */ +#define FGMAC_ISR_STATUS_MMCRCOIS BIT(7) /* 接收校验和卸载中断状态 */ +#define FGMAC_ISR_STATUS_TIS BIT(9) /* 时间戳中断状态 */ +#define FGMAC_ISR_STATUS_LPIIS BIT(10) /* LPI 中断状态 */ +#define FGMAC_ISR_STATUS_ALL_MASK GENMASK(10, 0) + +/** @name FGMAC_INTR_MASK_OFFSET Register + */ +#define FGMAC_ISR_MASK_RSIM BIT(0) /* RGMII/SMII 中断屏蔽 */ +#define FGMAC_ISR_MASK_PCSLSIM BIT(1) /* PCS 链路状态中断屏蔽 */ +#define FGMAC_ISR_MASK_PCSANCIM BIT(2) /* PCS AN 完成中断屏蔽 */ +#define FGMAC_ISR_MASK_PMTIM BIT(3) /* PMT 中断屏蔽 */ +#define FGMAC_ISR_MASK_TIM BIT(9) /* 时间戳中断屏蔽 */ +#define FGMAC_ISR_MASK_LPIIM BIT(10) /* LPI 中断屏蔽 */ +#define FGMAC_ISR_MASK_ALL_BITS (GENMASK(3, 0) | GENMASK(10, 9)) + +#define FGMAC_8BIT_ADDR GENMASK(7, 0) + +/** @name FGMAC_MAC_ADDR0_UPPER16BIT_OFFSET Register + */ +#define FGMAC_MAC_ADDR0_UPPER16BIT_A GENMASK(15, 0) /* MAC 地址 0[47:32] */ + +/** @name FGMAC_MAC_ADDR0_LOWER32BIT_OFFSET Register + */ +#define FGMAC_MAC_ADDR0_LOWER32BIT_A GENMASK(31, 0) /* MAC 地址 0[31:0] */ + +/** @name FGMAC_MAC_ADDR1_UPPER16BIT_OFFSET Register + */ +#define FGMAC_MAC_ADDR1_UPPER16BIT_A GENMASK(15, 0) /* MAC 地址 1[47:32] */ +#define FGMAC_MAC_ADDR1_UPPER16BIT_MBC GENMASK(29, 24) +#define FGMAC_MAC_ADDR1_UPPER16BIT_SA BIT(30) +#define FGMAC_MAC_ADDR1_UPPER16BIT_AE BIT(31) + +/** @name FGMAC_MAC_ADDR1_LOWER32BIT_OFFSET Register + */ +#define FGMAC_MAC_ADDR1_LOWER16BIT_A GENMASK(31, 0) /* MAC 地址 1[31:0] */ + +/** @name FGMAC_MAC_PHY_STATUS Register + */ +#define FGMAC_RGSMIIIS_LNKMODE BIT(0) /* 指示链路的当前操作模式 */ +#define FGMAC_RGSMIIIS_LNKMODE_HALF (0b0 << 0) +#define FGMAC_RGSMIIIS_LNKMODE_FULL (0b1 << 0) +#define FGMAC_RGSMIIIS_SPEED GENMASK(2, 1) +#define FGMAC_RGSMIIIS_SPEED_2_5MHZ (0b00 << 1) /* 链路速度 2.5MHz */ +#define FGMAC_RGSMIIIS_SPEED_25MHZ (0b01 << 1) /* 25MHz */ +#define FGMAC_RGSMIIIS_SPEED_125MHZ (0b10 << 1) /* 125MHz */ +#define FGMAC_RGSMIIIS_LNKSTS BIT(3) +#define FGMAC_RGSMIIIS_LNKSTS_UP (0b1 << 3) +#define FGMAC_RGSMIIIS_LNKSTS_DOWN (0b0 << 3) +#define FGMAC_RGSMIIIS_JAB_TIMEOUT BIT(4) +#define FGMAC_RGSMIIIS_FALSECARDET BIT(5) + +/****************FGMAC DMA Register*******************/ +/* Bus mode register definitions */ +/** @name FGMAC_DMA_BUS_MODE_OFFSET Register + */ +#define FGMAC_DMA_BUS_SWR BIT(0) /* 软件复位 */ +#define FGMAC_DMA_BUS_DA BIT(1) /* 设置 8xPBL 模式 */ +#define FGMAC_DMA_BUS_DSL_MASK GENMASK(6, 2) /* 描述符跳跃长度 */ +#define FGMAC_DMA_BUS_ATDS BIT(7) +#define FGMAC_DMA_BUS_PBL_MASK GENMASK(13, 8) /* 可编程突发长度 */ +#define FGMAC_DMA_BUS_PBL(x) ((x) << 8) +enum +{ + FGMAC_DMA_BUS_PBL_1 = 1, + FGMAC_DMA_BUS_PBL_2 = 2, + FGMAC_DMA_BUS_PBL_4 = 4, + FGMAC_DMA_BUS_PBL_8 = 8, + FGMAC_DMA_BUS_PBL_16 = 16, + FGMAC_DMA_BUS_PBL_32 = 32 +}; +#define FGMAC_DMA_BUS_PR_MASK GENMASK(15, 14) /* 加权循环仲裁中的优先级比率 */ +#define FGMAC_DMA_BUS_PR(x) ((x) << 14) +#define FGMAC_DMA_BUS_FB BIT(16) /* 固定突发 */ +#define FGMAC_DMA_BUS_RPBL_MASK GENMASK(22, 17) /* RxDMA 事务中要传输的最大节拍数 */ +#define FGMAC_DMA_BUS_RPBL(x) ((x) << 17) +enum +{ + FGMAC_DMA_BUS_RPBL_1 = 1, + FGMAC_DMA_BUS_RPBL_2 = 2, + FGMAC_DMA_BUS_RPBL_4 = 4, + FGMAC_DMA_BUS_RPBL_16 = 16, + FGMAC_DMA_BUS_RPBL_32 = 32 +}; +#define FGMAC_DMA_BUS_USP BIT(23) +#define FGMAC_DMA_BUS_8XPBL BIT(24) +#define FGMAC_DMA_BUS_AAL BIT(25) +#define FGMAC_DMA_BUS_MB BIT(26) /* 混合突发 */ +#define FGMAC_DMA_BUS_TXPR BIT(27) /* 发送优先级 */ +#define FGMAC_DMA_BUS_PRWG GENMASK(29, 18) /* 通道优先权重 */ + +#define FGMAC_DMA_BUS_INIT (FGMAC_DMA_BUS_FB | FGMAC_DMA_BUS_PBL(16) | FGMAC_DMA_BUS_RPBL(16)) + +/* 这些位控制 RxDMA 和 TxDMA 之间的加权循环仲裁中的优先级比率, + FGMAC_DMA_BUS_DA=1时有效 */ +#define FGMAC_DMA_BUS_PRIORXTX_41 (3 << 14) /* 4:1 */ +#define FGMAC_DMA_BUS_PRIORXTX_31 (2 << 14) /* 3:1 */ +#define FGMAC_DMA_BUS_PRIORXTX_21 (1 << 14) /* 2:1 */ +#define FGMAC_DMA_BUS_PRIORXTX_11 (0 << 14) /* 1:1 */ + +/** @name FGMAC_DMA_TX_POLL_REQ_OFFSET Register + */ +#define FGMAC_DMA_XMT_POLL_DEMAND_TPD GENMASK(31, 0) + +/** @name FGMAC_DMA_RX_POLL_REQ_OFFSET Register + */ +#define FGMAC_DMA_RCV_POLL_DEMAND_RPD GENMASK(31, 0) + +/** @name FGMAC_DMA_RX_LIST_BASE_OFFSET Register + */ +#define FGMAC_DMA_RCV_BASE_ADDR_START_REC_LIST GENMASK(31, 4) + +/** @name FGMAC_DMA_TX_LIST_BASE_OFFSET Register + */ +#define FGMAC_DMA_TX_BASE_ADDR_START_TRA_LIST GENMASK(31, 4) + +/** @name FGMAC_DMA_STATUS_OFFSET Register + */ +#define FGMAC_DMA_STATUS_GLPII BIT(30) /* FGMAC LPI interrupt */ +#define FGMAC_DMA_STATUS_TTI BIT(29) /* 时间戳触发中断 */ +#define FGMAC_DMA_STATUS_GPI BIT(28) /* PMT interrupt */ +#define FGMAC_DMA_STATUS_GMI BIT(27) /* MMC interrupt */ +#define FGMAC_DMA_STATUS_GLI BIT(26) /* FGMAC Line interface int */ +#define FGMAC_DMA_STATUS_EB_MASK GENMASK(25, 23) /* Error Bits Mask */ +#define FGMAC_DMA_STATUS_TS_MASK GENMASK(22, 20) /* Transmit Process State */ +#define FGMAC_DMA_STATUS_TS_STOPPED (0b000 << 20) +#define FGMAC_DMA_STATUS_TS_GET_DESC (0b001 << 20) +#define FGMAC_DMA_STATUS_TS_WAIT (0b010 << 20) +#define FGMAC_DMA_STATUS_TS_QUEUE (0b011 << 20) +#define FGMAC_DMA_STATUS_TS_PAUSE (0b110 << 20) +#define FGMAC_DMA_STATUS_TS_CLOSE_DESC (0b111 << 20) +#define FGMAC_DMA_STATUS_RS_MASK GENMASK(19, 17) /* Receive Process State */ +#define FGMAC_DMA_STATUS_NIS BIT(16) /* Normal Interrupt Summary */ +#define FGMAC_DMA_STATUS_AIS BIT(15) /* Abnormal Interrupt Summary */ +#define FGMAC_DMA_STATUS_ERI BIT(14) /* Early Receive Interrupt */ +#define FGMAC_DMA_STATUS_FBI BIT(13) /* Fatal Bus Error Interrupt */ +#define FGMAC_DMA_STATUS_ETI BIT(10) /* Early Transmit Interrupt */ +#define FGMAC_DMA_STATUS_RWT BIT(9) /* Receive Watchdog Timeout */ +#define FGMAC_DMA_STATUS_RPS BIT(8) /* Receive Process Stopped */ +#define FGMAC_DMA_STATUS_RU BIT(7) /* Receive Buffer Unavailable */ +#define FGMAC_DMA_STATUS_RI BIT(6) /* Receive Interrupt */ +#define FGMAC_DMA_STATUS_UNF BIT(5) /* Transmit Underflow */ +#define FGMAC_DMA_STATUS_OVF BIT(4) /* Receive Overflow */ +#define FGMAC_DMA_STATUS_TJT BIT(3) /* Transmit Jabber Timeout */ +#define FGMAC_DMA_STATUS_TU BIT(2) /* Transmit Buffer Unavailable */ +#define FGMAC_DMA_STATUS_TPS BIT(1) /* Transmit Process Stopped */ +#define FGMAC_DMA_STATUS_TI BIT(0) /* Transmit Interrupt */ + +#define FGMAC_DMA_STATUS_CLR_ABLE (GENMASK(5, 0) | GENMASK(10, 7)| FGMAC_DMA_STATUS_FBI | FGMAC_DMA_STATUS_AIS) /* BIT [16 : 0] write 1 to clear */ + +/** @name FGMAC_DMA_OP_OFFSET Register + */ +#define FGMAC_DMA_OP_DT BIT(26) /* No Dropping of TCP/IP csum Err Frame */ +#define FGMAC_DMA_OP_RSF BIT(25) /* Rx Store and Forward */ +#define FGMAC_DMA_OP_DFF BIT(24) /* */ +#define FGMAC_DMA_OP_RFA_2 BIT(23) +#define FGMAC_DMA_OP_RFD_2 BIT(22) +#define FGMAC_DMA_OP_TSF BIT(21) /* Tx Store and Forward */ +#define FGMAC_DMA_OP_FTF BIT(20) /* Flush Tx FIFO */ +#define FGMAC_DMA_OP_TTC_MASK GENMASK(16, 14) +#define FGMAC_DMA_OP_TTC(x) ((x) << 14) /* Tx Threshold Control */ +enum +{ + FGMAC_DMA_OP_TTC_64 = 0b000, + FGMAC_DMA_OP_TTC_128 = 0b001, + FGMAC_DMA_OP_TTC_192 = 0b010, + FGMAC_DMA_OP_TTC_256 = 0b011, + FGMAC_DMA_OP_TTC_40 = 0b100, + FGMAC_DMA_OP_TTC_32 = 0b101, + FGMAC_DMA_OP_TTC_24 = 0b110, + FGMAC_DMA_OP_TTC_16 = 0b111 +}; + +#define FGMAC_DMA_OP_ST BIT(13) /* Start/Stop Tx */ +#define FGMAC_DMA_OP_RFD_MASK GENMASK(12, 11) +#define FGMAC_DMA_OP_RFD(x) ((x) << 11) /* Threshold for DeActive Flow Control */ +#define FGMAC_DMA_OP_RFA_MASK GENMASK(10, 9) /* Threshold for Active Flow Control */ +#define FGMAC_DMA_OP_EFC BIT(8) /* Enable HW Flow control */ +#define FGMAC_DMA_OP_FEF BIT(7) /* Forward Error Frame */ +#define FGMAC_DMA_OP_FUF BIT(6) /* Forward Undersize Good Frame */ +#define FGMAC_DMA_OP_RTC_MASK GENMASK(4, 3) /* Rx Threshold Control */ +#define FGMAC_DMA_OP_OSF BIT(2) /* Operate On Second Mode */ +#define FGMAC_DMA_OP_SR BIT(1) /* Start/Stop Rx */ +#define FGMAC_DMA_OP_CLEAR_MASK GENMASK(31, 0) +#define FGMAC_DMA_OP_INIT (FGMAC_DMA_OP_SR | FGMAC_DMA_OP_RSF) + +/** @name FGMAC_DMA_INTR_OFFSET Register + */ +#define FGMAC_DMA_INTR_ENA_TIE BIT(0) /* Transmit Interrupt */ +#define FGMAC_DMA_INTR_ENA_TSE BIT(1) /* 传输停止启用 */ +#define FGMAC_DMA_INTR_ENA_TUE BIT(2) /* Transmit Buffer Unavailable */ +#define FGMAC_DMA_INTR_ENA_THE BIT(3) /* 发送 Jabber 超时启用 */ +#define FGMAC_DMA_INTR_ENA_OVE BIT(4) /* 溢出中断使能 */ +#define FGMAC_DMA_INTR_ENA_UNE BIT(5) /* 下溢中断使能 */ +#define FGMAC_DMA_INTR_ENA_RIE BIT(6) /* Receive Interrupt */ +#define FGMAC_DMA_INTR_ENA_RUE BIT(7) /* 接收缓冲区不可用启用 */ +#define FGMAC_DMA_INTR_ENA_RSE BIT(8) /* 接收已停止启用 */ +#define FGMAC_DMA_INTR_ENA_RWE BIT(9) /* 接收看门狗超时使能 */ +#define FGMAC_DMA_INTR_ENA_ETE BIT(10) /* 早期发送中断使能 */ +#define FGMAC_DMA_INTR_ENA_FBE BIT(13) /* Fatal Bus Error */ +#define FGMAC_DMA_INTR_ENA_ERE BIT(14) /* Early Receive */ +#define FGMAC_DMA_INTR_ENA_AIE BIT(15) /* Abnormal Summary */ +#define FGMAC_DMA_INTR_ENA_NIE BIT(16) /* Normal Summary */ +#define FGMAC_DMA_INTR_ENA_ALL_MASK (GENMASK(10, 0) | GENMASK(16, 13)) + +/** @name FGMAC_DMA_MISSED_FRAME_CNT_OFFSET Register + */ +#define FGMAC_DMA_MISSED_FRAME_CTR_CMIS GENMASK(15, 0) /* 由于主机接收缓冲区不可用而导致控制器丢失的帧数 */ +#define FGMAC_DMA_MISSED_FRAME_CTR_OVMIS BIT(16) +#define FGMAC_DMA_MISSED_FRAME_CTR_CFIFO GENMASK(27, 17) +#define FGMAC_DMA_MISSED_FRAME_CTR_OVFIFO BIT(28) + +/** @name FGMAC_DMA_RX_WATCHDOG_OFFSET Register + */ +#define FGMAC_DMA_RX_WATCHDOG_RIWT GENMASK(7, 0) + +/** @name FGMAC_DMA_AXI_BUS_MOD_OFFSET Register + */ +#define FGMAC_DMA_AXI_BUS_MOD_UNDEF BIT(0) /* AXI 未定义的突发长度 */ +#define FGMAC_DMA_AXI_BUS_MOD_BLEN4 BIT(1) /* AXI 突发长度 4 */ +#define FGMAC_DMA_AXI_BUS_MOD_BLEN8 BIT(2) /* AXI 突发长度 8 */ +#define FGMAC_DMA_AXI_BUS_MOD_BLEN16 BIT(3) /* AXI 突发长度 16 */ +#define FGMAC_DMA_AXI_BUS_MOD_BLEN32 BIT(4) /* AXI 突发长度 32 */ +#define FGMAC_DMA_AXI_BUS_MOD_BLEN64 BIT(5) /* AXI 突发长度 64 */ +#define FGMAC_DMA_AXI_BUS_MOD_BLEN128 BIT(6) /* AXI 突发长度 128 */ +#define FGMAC_DMA_AXI_BUS_MOD_BLEN256 BIT(7) /* AXI 突发长度 256 */ +#define FGMAC_DMA_AXI_BUS_MOD_AXI_AAL BIT(12) /* 地址对齐的节拍 */ +#define FGMAC_DMA_AXI_BUS_MOD_RD_OSR_LMT_MASK GENMASK(19, 16) +#define FGMAC_DMA_AXI_BUS_MOD_RD_OSR_LMT(x) ((x) << 16) /* XI 最大读取未决请求限制此值限 制 AXI 读取接口上的最大未完成请求。 */ +#define FGMAC_DMA_AXI_BUS_MOD_WR_OSR_LMT_MASK GENMASK(23, 20) +#define FGMAC_DMA_AXI_BUS_MOD_WR_OSR_LMT(x) ((x) << 20) /* AXI 最大写入未决请求限制此值 限制 AXI 写入接口上的最大未完成请求。 */ +#define FGMAC_DMA_AXI_BUS_MOD_UNLCK_ON_MGK_RWK BIT(30) +#define FGMAC_DMA_AXI_BUS_MOD_EN_LPI BIT(31) + +#define FGMAC_DMA_DESC_ADDR_MASK GENMASK(31, 4) + +#define FGMAC_MAC_ADDR_LEN 6 +#define FGMAC_RETRY_TIMES 500 +#define FGMAC_DELAY_US 100 +/**************************** Type Definitions *******************************/ + +typedef u8 FGmacMacAddr[FGMAC_MAC_ADDR_LEN]; + +enum +{ + FGMAC_CTRL_INTR = 0, + FGMAC_DMA_INTR, + + FGMAC_MAX_INTR_TYPE +}; + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +/* 读FGMAC控制器寄存器,以u32返回整个寄存器值 */ +#define FGMAC_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) + +/* 写FGMAC控制器寄存器,以u32覆盖写入整个寄存器值 */ +#define FGMAC_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)(reg_offset), (u32)(reg_value)) + +/* 将FGMAC控制器寄存器的特定位置为1, 不改变其它位 */ +#define FGMAC_SET_REG32(addr, reg_offset, set_bits) FtSetBit32((addr) + (u32)(reg_offset), (u32)(set_bits)) + +/* 将FGMAC控制器寄存器的特定位置为0, 不改变其它位 */ +#define FGMAC_CLR_REG32(addr, reg_offset, clr_bits) FtClearBit32((addr) + (u32)(reg_offset), (u32)(clr_bits)) + +/* 在一个总长度为num的环内将索引idx增加1 */ +#define FGMAC_DMA_INC_DESC(idx, num) (idx) = (((idx) + 1) % (num)) + +static inline void FGmacResumeDmaSend(uintptr base_addr) +{ + if (FGMAC_READ_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET) & FGMAC_DMA_STATUS_TU) + { + FGMAC_SET_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET, FGMAC_DMA_STATUS_TU); /* clear TBUS GMAC DMA flag */ + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_TX_POLL_REQ_OFFSET, 0xff); /* resume DMA transmission */ + } + else + { + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_TX_POLL_REQ_OFFSET, 0xff); /* resume DMA transmission */ + } +} + +static inline void FGmacResumeDmaRecv(uintptr base_addr) +{ + if (FGMAC_READ_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET) & FGMAC_DMA_STATUS_RU) + { + FGMAC_SET_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET, FGMAC_DMA_STATUS_RU); /* Clear RBUS GMAC DMA flag */ + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_RX_POLL_REQ_OFFSET, 0xff); /* Resume DMA transmission*/ + } + else + { + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_RX_POLL_REQ_OFFSET, 0xff); + } +} + +static inline void FGmacStartDmaTrans(uintptr base_addr) +{ + FGMAC_SET_REG32(base_addr, FGMAC_DMA_OP_OFFSET, (FGMAC_DMA_OP_SR | FGMAC_DMA_OP_ST)); /* enable dma tx and rx */ + FGMAC_SET_REG32(base_addr, FGMAC_CONF_OFFSET, (FGMAC_CONF_RX_EN | FGMAC_CONF_TX_EN)); /* enable gmac tx and rx */ + + /* clear Tx and Rx process stopped flags */ + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_INTR_OFFSET, + (FGMAC_DMA_INTR_ENA_RIE | FGMAC_DMA_INTR_ENA_AIE | FGMAC_DMA_INTR_ENA_NIE)); +} + +static inline void FGmacStopDmaTrans(uintptr base_addr) +{ + FGMAC_CLR_REG32(base_addr, FGMAC_DMA_OP_OFFSET, (FGMAC_DMA_OP_SR | FGMAC_DMA_OP_ST)); /* disable dma tx and rx */ + FGMAC_CLR_REG32(base_addr, FGMAC_CONF_OFFSET, (FGMAC_CONF_RX_EN | FGMAC_CONF_TX_EN)); /* disable gmac tx and rx */ +} + +static inline void FGmacResmuDmaUnderflow(uintptr base_addr) +{ + if (FGMAC_DMA_STATUS_UNF & FGMAC_READ_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET)) + { + FGMAC_SET_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET, FGMAC_DMA_STATUS_UNF); /* clear TBUS GMAC DMA flag */ + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_TX_POLL_REQ_OFFSET, 0xff); /* resume DMA transmission*/ + } +} + +/************************** Function Prototypes ******************************/ +/* 获取FGMAC控制器配置的MAC地址 */ +void FGmacGetMacAddr(uintptr base_addr, FGmacMacAddr mac_addr); + +/* 设置FGMAC控制器的MAC地址 */ +void FGmacSetMacAddr(uintptr base_addr, const FGmacMacAddr mac_addr); + +/* 触发FGMAC控制器软件复位 */ +FError FGmacSoftwareReset(uintptr base_addr, int timeout); + +FError FGmacFlushTxFifo(uintptr base_addr, int timeout); + +void FGmacStopDmaTrans(uintptr base_addr); + +/* wait fgmac mii not busy */ +FError FGmacPhyWaitBusBusy(uintptr base_addr, int timeout); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_intr.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_intr.c new file mode 100644 index 0000000000..e23aabfb44 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_intr.c @@ -0,0 +1,177 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_intr.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fgmac.h" +#include "fgmac_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGMAC_CALL_EVT_HANDLER(instance_p, evt) \ + {\ + if (NULL != (instance_p)->evt_handler[(evt)]) \ + { \ + (instance_p)->evt_handler[evt]((void *)(instance_p)); \ + }\ + } + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + +/** + * @name: FGmacInterruptHandler + * @msg: FGMAC中断处理函数 + * @return {*} + * @param {s32} vector, 中断向量号,此处没有用到 + {void} *param, 中断输入参数,此处传入的是FGMAC的驱动控制数据 + * @note 此函数运行在中断上下文 + */ +void FGmacInterruptHandler(s32 vector, void *param) +{ + FASSERT(param); + FGmac *instance_p = (FGmac *)param; + uintptr base_addr = instance_p->config.base_addr; + u32 status = 0; + + /* dma interrupt */ + status = FGMAC_READ_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET); + + if (FGMAC_DMA_STATUS_GLI & status) + { + FGMAC_CALL_EVT_HANDLER(instance_p, FGMAC_PHY_STATUS_EVT); + } + + if (FGMAC_DMA_STATUS_RI & status) + { + FGMAC_CALL_EVT_HANDLER(instance_p, FGMAC_RX_COMPLETE_EVT); + FGMAC_SET_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET, FGMAC_DMA_STATUS_RI); /* write to clear */ + } + + if (FGMAC_DMA_STATUS_TI & status) + { + FGMAC_CALL_EVT_HANDLER(instance_p, FGMAC_TX_COMPLETE_EVT); + FGMAC_SET_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET, FGMAC_DMA_STATUS_TI); /* write to clear */ + } + + if (FGMAC_DMA_STATUS_AIS & status) + { + FGMAC_CALL_EVT_HANDLER(instance_p, FGMAC_DMA_ERR_EVT); + FGMAC_SET_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET, FGMAC_DMA_STATUS_CLR_ABLE); + } + + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_STATUS_OFFSET, status); /* write to clear */ + + /* RGMII/SGMII Interrupt */ + status = FGMAC_READ_REG32(base_addr, FGMAC_INTR_STATUS_OFFSET); + if (status & FGMAC_ISR_STATUS_RSIS) + { + /* status changed, read SGMII register to clear */ + FGMAC_READ_REG32(base_addr, FGMAC_MAC_PHY_STATUS); + } + + return; +} + +/** + * @name: FGmacRegisterEvtHandler + * @msg: 注册FGMAC中断事件响应函数 + * @return {*} + * @param {FGmac} *instance_p 驱动控制数据 + * @param {u32} evt 中断事件类型 + * @param {FGmacEvtHandler} handler 中断事件响应函数 + * @note 注册的函数handler会在中断上下文执行 + */ +void FGmacRegisterEvtHandler(FGmac *instance_p, u32 evt, FGmacEvtHandler handler) +{ + FASSERT((NULL != instance_p) && (FGMAC_INTR_EVT_NUM > evt)); + instance_p->evt_handler[evt] = handler; +} + +/** + * @name: FGmacSetInterruptMask + * @msg: 屏蔽FGMAC中断 + * @return {*} + * @param {FGmac} *instance_p 驱动控制数据 + * @param {u32} intr_type 中断类型 GMAC中断/DMA中断 + * @param {u32} mask 中断屏蔽位 + * @note 在FGMAC驱动初始化成功后调用此函数 + */ +void FGmacSetInterruptMask(FGmac *instance_p, u32 intr_type, u32 mask) +{ + FASSERT(instance_p); + FASSERT(FGMAC_MAX_INTR_TYPE > intr_type); + u32 cur_mask = 0; + uintptr base_addr = instance_p->config.base_addr; + + if (FGMAC_CTRL_INTR == intr_type) + { + cur_mask = FGMAC_READ_REG32(base_addr, FGMAC_INTR_MASK_OFFSET); + cur_mask |= mask; + FGMAC_WRITE_REG32(base_addr, FGMAC_INTR_MASK_OFFSET, cur_mask); + } + else + { + cur_mask = FGMAC_READ_REG32(base_addr, FGMAC_DMA_INTR_OFFSET); + cur_mask &= (~mask); + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_INTR_OFFSET, cur_mask); + } + + return; +} + +/** + * @name: FGmacSetInterruptUmask + * @msg: 使能FGMAC中断 + * @return {*} + * @param {FGmac} *instance_p 驱动控制数据 + * @param {u32} intr_type 中断类型 GMAC中断/DMA中断 + * @param {u32} mask 中断使能标志位 + * @note 在FGMAC驱动初始化成功后调用此函数 + */ +void FGmacSetInterruptUmask(FGmac *instance_p, u32 intr_type, u32 mask) +{ + FASSERT(instance_p); + FASSERT(FGMAC_MAX_INTR_TYPE > intr_type); + u32 cur_mask = 0; + uintptr base_addr = instance_p->config.base_addr; + + if (FGMAC_CTRL_INTR == intr_type) + { + cur_mask = FGMAC_READ_REG32(base_addr, FGMAC_INTR_MASK_OFFSET); + cur_mask &= (~mask); + FGMAC_WRITE_REG32(base_addr, FGMAC_INTR_MASK_OFFSET, cur_mask); + } + else + { + cur_mask = FGMAC_READ_REG32(base_addr, FGMAC_DMA_INTR_OFFSET); + cur_mask |= mask; + FGMAC_WRITE_REG32(base_addr, FGMAC_DMA_INTR_OFFSET, cur_mask); + } + + return; +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_sinit.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_sinit.c new file mode 100644 index 0000000000..87822e48b0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/fgmac_sinit.c @@ -0,0 +1,68 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_sinit.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/* - This file contains the implementation of driver's static initialization functionality. +- 驱动静态初始化 */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fgmac.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +extern const FGmacConfig FGMAC_CONFIG_TBL[GMAC_INSTANCE_NUM]; + +/************************** Function Prototypes ******************************/ +/** + * @name: FGmacLookupConfig + * @msg: 获取FGMAC驱动的默认配置参数 + * @return {const FGmacConfig *}, 驱动默认配置 + * @param {u32} instance_id, 驱动控制器号 + * @note 返回FGMAC的默认配置,复制后修改配置 + * 需要确认当前平台支持输入的instance_id + */ +const FGmacConfig *FGmacLookupConfig(u32 instance_id) +{ + const FGmacConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)GMAC_INSTANCE_NUM; index++) + { + if (FGMAC_CONFIG_TBL[index].instance_id == instance_id) + { + ptr = &FGMAC_CONFIG_TBL[index]; + break; + } + } + + return (const FGmacConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/ar803x/fgmac_ar803x.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/ar803x/fgmac_ar803x.c new file mode 100644 index 0000000000..038afa1ede --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/ar803x/fgmac_ar803x.c @@ -0,0 +1,198 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_ar803x.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" + +#include "fgmac_hw.h" +#include "fgmac.h" +#include "fgmac_ar803x.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGMAC_DEBUG_TAG "FGMAC-AR803X" +#define FGMAC_ERROR(format, ...) FT_DEBUG_PRINT_E(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_WARN(format, ...) FT_DEBUG_PRINT_W(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_INFO(format, ...) FT_DEBUG_PRINT_I(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +/* write phy register */ +extern FError FGmacWritePhyReg(FGmac *instance_p, u32 phy_address, u16 phy_reg, u16 phy_reg_val); +/* read phy register */ +extern FError FGmacReadPhyReg(FGmac *instance_p, u32 phy_address, u16 phy_reg, u16 *phy_reg_val_p); + + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/* 此文件主要为了完成用户对外接口,用户可以使用这些接口直接开始工作 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + + +/** + * @name: FGmacAr803xDebugRegRead + * @msg: read phy debug register value + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @param {u16} debug_reg, phy debug register offset to read + * @param {u16} *reg_data_p, phy register value pointer + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +static FError FGmacAr803xDebugRegRead(FGmac *instance_p, u32 phy_address, u16 debug_reg, u16 *reg_data_p) +{ + FASSERT(instance_p && reg_data_p); + FError ret = FGMAC_SUCCESS; + + ret = FGmacWritePhyReg(instance_p, phy_address, FGMAC_AR803X_DEBUG_ADDR, debug_reg & FGMAC_AR803X_DEBUG_DATA_MASK); + if (FGMAC_SUCCESS != ret) + return ret; + + ret = FGmacReadPhyReg(instance_p, phy_address, FGMAC_AR803X_DEBUG_DATA, reg_data_p); + return ret; +} + +static FError FGmacAr803xMaskReg(FGmac *instance_p, u32 phy_address, u16 reg, u32 clear, u32 set) +{ + FASSERT(instance_p); + FError ret = FGMAC_SUCCESS; + u16 val = 0; + + ret = FGmacReadPhyReg(instance_p, phy_address, reg, &val); + if (FGMAC_SUCCESS != ret) + return ret; + + val &= ~clear; + val |= set; + + ret = FGmacWritePhyReg(instance_p, phy_address, FGMAC_AR803X_DEBUG_DATA, val); + return ret; +} + +/** + * @name: FGmacAr803xDisableHibernate + * @msg: disable phy Power hibernate control + * @param {FGmac} *instance_p, instance of FGmac controller + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacAr803xDisableHibernate(FGmac *instance_p) +{ + FASSERT(instance_p); + u32 ret = FGMAC_SUCCESS; + u16 reg_val = 0; + + ret = FGmacAr803xDebugRegRead(instance_p, instance_p->phy_addr, FGMAC_AR803X_DEBUG_HIB_CTRL_REG, ®_val); + if (FGMAC_SUCCESS != ret) + return ret; + + reg_val &= ~FGMAC_AR803X_PS_HIB_EN; + ret = FGmacWritePhyReg(instance_p, instance_p->phy_addr, FGMAC_AR803X_DEBUG_DATA, reg_val); + + reg_val = 0; + FGmacAr803xDebugRegRead(instance_p, instance_p->phy_addr, FGMAC_AR803X_DEBUG_HIB_CTRL_REG, ®_val); + FGMAC_INFO("debug reg: 0x%lx, ret: 0x%lx", reg_val, ret); + + return ret; +} + +/** + * @name: FFmacAr803xRxClockDelayControl + * @msg: control phy debug register0 for rx clock delay + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} enable_setting, 1-enable, else disable + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FFmacAr803xRxClockDelayControl(FGmac *instance_p, u32 enable_setting) +{ + FASSERT(instance_p); + u32 ret = FGMAC_SUCCESS; + u16 reg_val = 0; + + ret = FGmacAr803xDebugRegRead(instance_p, instance_p->phy_addr, FGMAC_AR803X_RX_CLOCK_CTRL_REG, ®_val); + if (FGMAC_SUCCESS != ret) + return ret; + + if (enable_setting == FGMAC_RX_CLOCK_ENABLE) + { + reg_val |= FGMAC_AR803X_RX_CLOCK_DELAY; + } + else + { + reg_val &= ~FGMAC_AR803X_RX_CLOCK_DELAY; + } + + ret = FGmacWritePhyReg(instance_p, instance_p->phy_addr, FGMAC_AR803X_DEBUG_DATA, reg_val); + + reg_val = 0; + FGmacAr803xDebugRegRead(instance_p, instance_p->phy_addr, FGMAC_AR803X_RX_CLOCK_CTRL_REG, ®_val); + FGMAC_INFO("debug reg: 0x%lx, ret: 0x%lx", reg_val, ret); + + return ret; +} + +/** + * @name: FFmacAr803xTxClockDelayControl + * @msg: control phy debug register5 for tx clock delay + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} enable_setting, 1-enable, else disable + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FFmacAr803xTxClockDelayControl(FGmac *instance_p, u32 enable_setting) +{ + FASSERT(instance_p); + u32 ret = FGMAC_SUCCESS; + u16 reg_val = 0; + + ret = FGmacAr803xDebugRegRead(instance_p, instance_p->phy_addr, FGMAC_AR803X_TX_CLOCK_CTRL_REG, ®_val); + if (FGMAC_SUCCESS != ret) + return ret; + + if (enable_setting == FGMAC_TX_CLOCK_ENABLE) + { + reg_val |= FGMAC_AR803X_TX_CLOCK_DELAY; + } + else + { + reg_val &= ~FGMAC_AR803X_TX_CLOCK_DELAY; + } + + ret = FGmacWritePhyReg(instance_p, instance_p->phy_addr, FGMAC_AR803X_DEBUG_DATA, reg_val); + + reg_val = 0; + FGmacAr803xDebugRegRead(instance_p, instance_p->phy_addr, FGMAC_AR803X_TX_CLOCK_CTRL_REG, ®_val); + FGMAC_INFO("debug reg: 0x%lx, ret: 0x%lx", reg_val, ret); + + return ret; +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/ar803x/fgmac_ar803x.h b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/ar803x/fgmac_ar803x.h new file mode 100644 index 0000000000..324583dca3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/ar803x/fgmac_ar803x.h @@ -0,0 +1,93 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_ar803x.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_FGMAC_PHY_AR803X_H +#define DRIVERS_FGMAC_PHY_AR803X_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" + +#include "fgmac_phy.h" + +/************************** Constant Definitions *****************************/ + +/* phy id */ +#define FGMAC_AR803X_PHY_ID1 0x4D /*803xPhy芯片 id1值为4d 8035芯片 id1 为0x004d id2 为0xd072 */ +#define FGMAC_AR803X_PHY_ID2 0x4D + +/* address and data port */ +#define FGMAC_AR803X_DEBUG_ADDR 0x1DU +#define FGMAC_AR803X_DEBUG_DATA 0x1EU + +/* debug register offset */ +#define FGMAC_AR803X_DEBUG_HIB_CTRL_REG 0xBU +#define FGMAC_AR803X_RX_CLOCK_CTRL_REG 0x0U +#define FGMAC_AR803X_TX_CLOCK_CTRL_REG 0x5U + +#define FGMAC_AR803X_DEBUG_DATA_MASK GENMASK(5, 0) + +/* rx clock delay setting */ +#define FGMAC_RX_CLOCK_ENABLE 1 +#define FGMAC_RX_CLOCK_DISABLE 0 + +/* tx clock delay setting */ +#define FGMAC_TX_CLOCK_ENABLE 1 +#define FGMAC_TX_CLOCK_DISABLE 0 + +/* hib ctrl and auto-negotiation register */ +#define FGMAC_AR803X_PS_HIB_EN BIT(15) + +#define FGMAC_AR803X_RX_CLOCK_DELAY BIT(15) +#define FGMAC_AR803X_TX_CLOCK_DELAY BIT(8) + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/* disable phy Power hibernate control */ +FError FGmacAr803xDisableHibernate(FGmac *instance_p); + +/* control phy debug register0 for rx clock delay */ +FError FFmacAr803xRxClockDelayControl(FGmac *instance_p, u32 enable_setting); + +/* control phy debug register5 for tx clock delay */ +FError FFmacAr803xTxClockDelayControl(FGmac *instance_p, u32 enable_setting); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/fgmac_phy.c b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/fgmac_phy.c new file mode 100644 index 0000000000..53b0d65ada --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/fgmac_phy.c @@ -0,0 +1,523 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_phy.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:53 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fassert.h" +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" + +#include "fparameters.h" + +#include "fgmac_hw.h" +#include "fgmac_phy.h" +#include "fgmac.h" +#ifdef CONFIG_FGMAC_PHY_AR803X + #include "fgmac_ar803x.h" +#endif +#include "fsleep.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGMAC_DEBUG_TAG "FGMAC-PHY" +#define FGMAC_ERROR(format, ...) FT_DEBUG_PRINT_E(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_WARN(format, ...) FT_DEBUG_PRINT_W(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_INFO(format, ...) FT_DEBUG_PRINT_I(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGMAC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGMAC_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/* 此文件主要为了完成用户对外接口,用户可以使用这些接口直接开始工作 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/** + * @name: FGmacWaitPhyAutoNegotiationEnd + * @msg: wait fgmac phy auto negotiation complete + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +static FError FGmacWaitPhyAutoNegotiationEnd(FGmac *instance_p, u32 phy_address) +{ + u16 reg_val; + FError ret = FGMAC_SUCCESS; + int timeout = FGMAC_RETRY_TIMES; + do + { + reg_val = 0; + ret = FGmacReadPhyReg(instance_p, phy_address, FGMAC_PHY_MII_STATUS_REG, ®_val); + if (FGMAC_SUCCESS != ret) + break; + fsleep_millisec(20); + } + while ((FGMAC_PHY_MII_SR_AUTO_NEGOT_COMPLETE != (FGMAC_PHY_MII_SR_AUTO_NEGOT_COMPLETE & reg_val)) && + (0 < --timeout)); + + if (FGMAC_SUCCESS != ret) + return ret; + + if (0 >= timeout) + { + FGMAC_ERROR("auto negotiation timeout, reg_val: %#x", reg_val); + ret = FGmacReadPhyReg(instance_p, phy_address, FGMAC_PHY_MII_CTRL_REG, ®_val); + FGMAC_ERROR("auto negotiation timeout, FGMAC_PHY_MII_CTRL_REG reg_val: %#x", reg_val); + ret = FGMAC_ERR_TIMEOUT; + } + + return ret; +} + +/** + * @name: FGmacPhyAutoNegotiation + * @msg: fgmac phy auto negotiation configuration + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +static FError FGmacPhyAutoNegotiation(FGmac *instance_p, u32 phy_address) +{ + FASSERT(instance_p); + u16 reg_val; + FError ret = FGMAC_SUCCESS; + int timeout = FGMAC_RETRY_TIMES; + /* check link state */ + do + { + reg_val = 0; + ret = FGmacReadPhyReg(instance_p, phy_address, FGMAC_PHY_MII_STATUS_REG, ®_val); + if (FGMAC_SUCCESS != ret) + break; + fsleep_millisec(20); + + } + while (!(reg_val & FGMAC_PHY_MII_SR_LSTATUS) && (0 <= --timeout)); + + if (0 >= timeout) + { + FGMAC_ERROR("timeout when wait phy auto negotiation "); + return FGMAC_ERR_TIMEOUT; + } + + if (FGMAC_SUCCESS != ret) + return ret; + + ret = FGmacReadPhyReg(instance_p, phy_address, FGMAC_PHY_MII_CTRL_REG, ®_val); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("auto negotiation failed"); + return ret; + } + + reg_val |= FGMAC_PHY_MII_CR_AUTO_NEGOT; + + ret = FGmacWritePhyReg(instance_p, phy_address, FGMAC_PHY_MII_CTRL_REG, reg_val); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("auto negotiation failed"); + return ret; + } + + ret = FGmacWaitPhyAutoNegotiationEnd(instance_p, phy_address); + if (FGMAC_SUCCESS != ret) + return ret; + + return ret; +} + +/** + * @name: FGmacPhyNoneNegotiation + * @msg: fgmac phy not negotiation configuration + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +static FError FGmacPhyNoneNegotiation(FGmac *instance_p, u32 phy_address) +{ + FASSERT(instance_p); + u16 control_reg = 0; + FError ret = FGMAC_SUCCESS; + + /* read phy control register */ + ret = FGmacReadPhyReg(instance_p, phy_address, FGMAC_PHY_MII_CTRL_REG, &control_reg); + if (FGMAC_SUCCESS != ret) + return ret; + + /* 设置半双工模式 */ + if (FGMAC_PHY_MODE_FULLDUPLEX == instance_p->config.duplex_mode) + control_reg |= FGMAC_PHY_MII_CR_DUPLEX_MODE; + else + control_reg &= ~(FGMAC_PHY_MII_CR_DUPLEX_MODE); + + /* 设置速度bit6|bit13, 10b-1000M, 01b-100M, 00b-10M */ + switch (instance_p->config.speed) + { + case FGMAC_PHY_SPEED_1000: + control_reg |= FGMAC_PHY_MII_CR_SPEED_SEL_MSB; + control_reg &= ~(FGMAC_PHY_MII_CR_SPEED_SEL_LSB); + break; + case FGMAC_PHY_SPEED_100: + control_reg &= ~(FGMAC_PHY_MII_CR_SPEED_SEL_MSB); + control_reg |= FGMAC_PHY_MII_CR_SPEED_SEL_LSB; + break; + case FGMAC_PHY_SPEED_10: + control_reg &= ~(FGMAC_PHY_MII_CR_SPEED_SEL_MSB); + control_reg &= ~(FGMAC_PHY_MII_CR_SPEED_SEL_LSB); + break; + default: + FASSERT(0); + break; + } + + /* disable auto-negotiation */ + control_reg &= ~(FGMAC_PHY_MII_CR_AUTO_NEGOT); + control_reg &= ~(FGMAC_PHY_MII_CR_RESTART_AUTO_NEGO); + + /* write phy control register */ + ret = FGmacWritePhyReg(instance_p, phy_address, FGMAC_PHY_MII_CTRL_REG, control_reg); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("disable auto-negotiation failed"); + return ret; + } + + return ret; +} + +/** + * @name: FGmacWritePhyReg + * @msg: write phy register value + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @param {u16} phy_reg, phy register offset to write + * @param {u16} phy_reg_val, value write to phy register + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacWritePhyReg(FGmac *instance_p, u32 phy_address, u16 phy_reg, u16 phy_reg_val) +{ + FASSERT(instance_p); + u32 cmd_reg_val; + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGMAC_SUCCESS; + + cmd_reg_val = FGMAC_MII_ADDR_CR(instance_p->config.mdc_clk_hz); + cmd_reg_val |= FGMAC_MII_ADDR_PA(phy_address); + cmd_reg_val |= FGMAC_MII_ADDR_GR(phy_reg); + cmd_reg_val |= FGMAC_MII_ADDR_GW; + cmd_reg_val |= FGMAC_MII_ADDR_GB; + + FGMAC_WRITE_REG32(base_addr, FGMAC_GMII_DATA_OFFSET, phy_reg_val); + FGMAC_WRITE_REG32(base_addr, FGMAC_GMII_ADDR_OFFSET, cmd_reg_val); + + ret = FGmacPhyWaitBusBusy(base_addr, FGMAC_RETRY_TIMES); + return ret; +} + +/** + * @name: FGmacReadPhyReg + * @msg: read phy register value + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @param {u16} phy_reg, phy register offset to read + * @param {u16} *phy_reg_val_p, phy register value pointer + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacReadPhyReg(FGmac *instance_p, u32 phy_address, u16 phy_reg, u16 *phy_reg_val_p) +{ + FASSERT(instance_p && phy_reg_val_p); + u32 cmd_reg_val; + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGMAC_SUCCESS; + + cmd_reg_val = FGMAC_MII_ADDR_CR(instance_p->config.mdc_clk_hz); + cmd_reg_val |= FGMAC_MII_ADDR_PA(phy_address); + cmd_reg_val |= FGMAC_MII_ADDR_GR(phy_reg); + cmd_reg_val &= ~FGMAC_MII_ADDR_GW; + cmd_reg_val |= FGMAC_MII_ADDR_GB; + + ret = FGmacPhyWaitBusBusy(base_addr, FGMAC_RETRY_TIMES); + if (FGMAC_SUCCESS != ret) + return ret; + + FGMAC_WRITE_REG32(base_addr, FGMAC_GMII_ADDR_OFFSET, cmd_reg_val); + + ret = FGmacPhyWaitBusBusy(base_addr, FGMAC_RETRY_TIMES); + if (FGMAC_SUCCESS != ret) + return ret; + + *phy_reg_val_p = FGMAC_MII_DATA_GD_MASK & FGMAC_READ_REG32(base_addr, FGMAC_GMII_DATA_OFFSET); + return ret; +} + +/** + * @name: FGmacPhyDetect + * @msg: detect fgmac phy, and get phy addr + * @param {FGmac} *instance_p, instance of FGmac controller + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacPhyDetect(FGmac *instance_p) +{ + u32 phy_addr = 0; + u16 phy_reg = 0, phy_id1_reg, phy_id2_reg; + FError ret = FGMAC_SUCCESS; + u32 invalid_count = 0; + + for (phy_addr = 0; phy_addr < FGMAC_PHY_MAX_NUM; phy_addr++) + { + ret = FGmacReadPhyReg(instance_p, phy_addr, FGMAC_PHY_MII_STATUS_REG, &phy_reg); + if (ret != FGMAC_SUCCESS) + { + FGMAC_ERROR("%s, PHY operation is busy", __func__); + return ret; + } + + if (phy_reg != 0xffff) + { + ret = FGmacReadPhyReg(instance_p, phy_addr, FGMAC_PHY_MII_PHYSID1_REG, &phy_id1_reg); + ret |= FGmacReadPhyReg(instance_p, phy_addr, FGMAC_PHY_MII_PHYSID2_REG, &phy_id2_reg); + + if ((ret == FGMAC_SUCCESS) && (phy_id1_reg != 0xffff) && (phy_id2_reg != 0xffff)) + { + /* assign the max valid phy address to instance_p->phy_addr */ + instance_p->phy_addr = phy_addr; + instance_p->phy_valid_mask |= (1 << phy_addr); + instance_p->phy_id1 = phy_id1_reg; + + FGMAC_INFO("phy_addr: [%d], phy_valid_mask: 0x%x, phy id: [0x%08x][0x%08x], phy_reg:0x%x", + phy_addr, instance_p->phy_valid_mask, phy_id1_reg, phy_id2_reg, phy_reg); + + return ret; + } + } + else + { + invalid_count++; + } + } + + if (invalid_count == FGMAC_PHY_MAX_NUM) + { + FGMAC_ERROR("phy detect failed, phy address is not found!"); + return FGMAC_ERR_PHY_IS_NOT_FOUND; + } + + return FGMAC_SUCCESS; +} + +/** + * @name: FGmacPhyReset + * @msg: detect fgmac phy, and get phy addr + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacPhyReset(FGmac *instance_p, u32 phy_address) +{ + FError ret = FGMAC_ERR_PHY_NOT_SUPPORT; + uintptr base_addr = instance_p->config.base_addr; + ret = FGmacWritePhyReg(instance_p, phy_address, FGMAC_PHY_MII_CTRL_REG, FGMAC_PHY_MII_CR_RESET); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("reset phy failed"); + return ret; + } + return FGMAC_SUCCESS; +} + +/** + * @name: FGmacGetPhySpecialStatus + * @msg: read phy special status register to get speed and duplex mode + * @param {FGmac} *instance_p, instance of FGmac controller + * @param {u32} phy_address, phy address connect to fgmac + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +static FError FGmacGetPhySpecialStatus(FGmac *instance_p, u32 phy_address) +{ + u16 phy_special_status = 0; + u32 ret = FGMAC_SUCCESS; + + ret = FGmacReadPhyReg(instance_p, phy_address, FGMAC_PHY_MII_PHY_SPECIAL_REG, &phy_special_status); + if (FGMAC_SUCCESS != ret) + { + return ret; + } + + switch (phy_special_status & FGMAC_PHY_SPECIFIC_STATUS_SPEED_MASK) + { + case FGMAC_PHY_SPECIFIC_STATUS_SPEED_1000M: + instance_p->config.speed = FGMAC_PHY_SPEED_1000; + break; + case FGMAC_PHY_SPECIFIC_STATUS_SPEED_100M: + instance_p->config.speed = FGMAC_PHY_SPEED_100; + break; + case FGMAC_PHY_SPECIFIC_STATUS_SPEED_10M: + instance_p->config.speed = FGMAC_PHY_SPEED_10; + break; + default: + break; + } + + if (phy_special_status & FGMAC_PHY_SPECIFIC_STATUS_DUPLEX_MASK) + instance_p->config.duplex_mode = FGMAC_PHY_MODE_FULLDUPLEX; + else + instance_p->config.duplex_mode = FGMAC_PHY_MODE_HALFDUPLEX; + + return ret; +} + +/** + * @name: FGmacPhyCfgInitialize + * @msg: fgmac phy configuration + * @param {FGmac} *instance_p, instance of FGmac controller + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacPhyCfgInitialize(FGmac *instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGMAC_SUCCESS; + u32 phy_addr; + + /* detect phy address, and assigned the minimum valid address to phy_addr */ + ret = FGmacPhyDetect(instance_p); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("phy detect failed!"); + return ret; + } + + for (phy_addr = 0; phy_addr <= instance_p->phy_addr; phy_addr++) + { + /* 计算出当前位置 */ + if (instance_p->phy_valid_mask & (1 << phy_addr)) + { + /* set phy power down and set phy Normal operation */ + FGmacPhyReset(instance_p, phy_addr); + + /* auto negotiation */ + if (instance_p->config.en_auto_negtiation) + { + ret = FGmacPhyAutoNegotiation(instance_p, phy_addr); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("auto negotiation phy failed"); + return ret; + } + } + else + { + /* if gmac is disable auto negotiation, we need set speed */ + ret = FGmacPhyNoneNegotiation(instance_p, phy_addr); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("negotiation phy failed"); + return ret; + } + } + + /* read phy special status register to get speed and duplex mode */ + ret = FGmacGetPhySpecialStatus(instance_p, phy_addr); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("get phy special status failed"); + return ret; + } + + FGMAC_DEBUG("instance_p->config.speed: %d", instance_p->config.speed); + FGMAC_DEBUG("instance_p->config.duplex_mode: 0x%x", instance_p->config.duplex_mode); + /* update mac controller speed setting */ + FGmacControllerSpeedConfig(instance_p, instance_p->config.speed); + + /* update mac controller duplex mode setting */ + FGmacControllerDuplexConfig(instance_p, instance_p->config.duplex_mode); + } + } + return ret; +} + +FError FGmacPhyCfgDeInitialize(FGmac *instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FGMAC_SUCCESS; + u32 phy_addr; + + for (phy_addr = 0; phy_addr <= instance_p->phy_addr; phy_addr++) + { + /* 计算出当前位置 */ + if (instance_p->phy_valid_mask & (1 << phy_addr)) + { + /* set phy power down and set phy Normal operation */ + FGmacPhyReset(instance_p, phy_addr); + } + } + return ret; +} + +/** + * @name: FGmacPhyAwaken + * @msg: fgmac phy awaken + * @param {FGmac} *instance_p, instance of FGmac controller + * @return err code information, FGMAC_SUCCESS indicates success,others indicates failed + */ +FError FGmacPhyAwaken(FGmac *instance_p) +{ + + FError ret = FGMAC_SUCCESS; + +#ifdef CONFIG_FGMAC_PHY_AR803X + ret = FGmacPhyDetect(instance_p); + if (FGMAC_SUCCESS != ret) + { + FGMAC_ERROR("phy detect failed!"); + return ret; + } + + u16 phy_id1; + phy_id1 = instance_p->phy_id1; + + if (phy_id1 == FGMAC_AR803X_PHY_ID1) + { + + ret = FGmacAr803xDisableHibernate(instance_p); + + } +#endif + return ret; +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/fgmac_phy.h b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/fgmac_phy.h new file mode 100644 index 0000000000..6287745cf3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fgmac/phy/fgmac_phy.h @@ -0,0 +1,213 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgmac_phy.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_ETH_FGMAC_PHY_H +#define DRIVERS_ETH_FGMAC_PHY_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" +#include "fkernel.h" +#include "fgmac.h" + +/************************** Constant Definitions *****************************/ +#define FGMAC_PHY_MAX_NUM 32U + +/* Generic MII registers. */ +#define FGMAC_PHY_MII_CTRL_REG 0x00 /* Basic mode control register */ +#define FGMAC_PHY_MII_STATUS_REG 0x01 /* Basic mode status register */ +#define FGMAC_PHY_MII_PHYSID1_REG 0x02 /* PHYS ID 1 */ +#define FGMAC_PHY_MII_PHYSID2_REG 0x03 /* PHYS ID 2 */ +#define FGMAC_PHY_MII_AUTONEG_REG 0x04 /* Advertisement control reg */ +#define FGMAC_PHY_MII_LP_REG 0x05 /* Link partner ability reg */ +#define FGMAC_PHY_MII_AUTONEG_EX_REG 0x06 /* Expansion register */ +#define FGMAC_PHY_MII_NEXT_PAGE_REG 0x07 /* Next Page Transmit Register */ +#define FGMAC_PHY_MII_LP_NEXT_PAGE_REG 0x08 /* Link Partner Next Page Register */ +#define FGMAC_PHY_MII_CTRL1000_REG 0x09 /* 1000BASE-T control */ +#define FGMAC_PHY_MII_STAT1000_REG 0x0a /* 1000BASE-T status */ +#define FGMAC_PHY_MII_MMD_CTRL_REG 0x0d /* MMD Access Control Register */ +#define FGMAC_PHY_MII_MMD_DATA_REG 0x0e /* MMD Access Data Register */ +#define FGMAC_PHY_MII_ESTATUS_REG 0x0f /* Extended Status */ +#define FGMAC_PHY_MII_FUNC_CONTROL_REG 0x10 /* Function control */ +#define FGMAC_PHY_MII_PHY_SPECIAL_REG 0x11 /* PHY-specific status */ +#define FGMAC_PHY_MII_DCOUNTER_REG 0x12 /* Disconnect counter */ +#define FGMAC_PHY_MII_FCSCOUNTER_REG 0x13 /* False carrier counter */ +#define FGMAC_PHY_MII_NWAYTEST_REG 0x14 /* N-way auto-neg test reg */ +#define FGMAC_PHY_MII_RERRCOUNTER_REG 0x15 /* Receive error counter */ +#define FGMAC_PHY_MII_SREVISION_REG 0x16 /* Silicon revision */ +#define FGMAC_PHY_MII_RESV1_REG 0x17 /* Reserved... */ +#define FGMAC_PHY_MII_LBRERROR_REG 0x18 /* Lpback, rx, bypass error */ +#define FGMAC_PHY_MII_PHYADDR_REG 0x19 /* PHY address */ +#define FGMAC_PHY_MII_RESV2_REG 0x1a /* Reserved... */ +#define FGMAC_PHY_MII_TPISTATUS_REG 0x1b /* TPI status for 10mbps */ +#define FGMAC_PHY_MII_NCONFIG_REG 0x1c /* Network interface config */ + +#define FGMAC_PHY_ID1 (0xffff) +#define FGMAC_PHY_ID2 (0xffff) + +/* Basic mode control register */ +#define FGMAC_PHY_MII_CR_RES GENMASK(5, 0) /* Unused... */ +#define FGMAC_PHY_MII_CR_SPEED_SEL_MSB BIT(6) /* MSB of Speed (1000) */ +#define FGMAC_PHY_MII_CR_COLLISION_TEST BIT(7) /* Collision test */ +#define FGMAC_PHY_MII_CR_DUPLEX_MODE BIT(8) /* Full duplex */ +#define FGMAC_PHY_MII_CR_RESTART_AUTO_NEGO BIT(9) /* Auto negotiation restart */ +#define FGMAC_PHY_MII_CR_ISOLATE BIT(10) /* Isolate data paths from MII */ +#define FGMAC_PHY_MII_CR_POWER_DOWN BIT(11) /* Enable low power state */ +#define FGMAC_PHY_MII_CR_AUTO_NEGOT BIT(12) /* Enable auto negotiation */ +#define FGMAC_PHY_MII_CR_SPEED_SEL_LSB BIT(13) /* Select 100Mbps */ +#define FGMAC_PHY_MII_CR_LOOPBACK BIT(14) /* TXD loopback bits */ +#define FGMAC_PHY_MII_CR_RESET BIT(15) /* Reset to default state */ + +#define FGMAC_PHY_MII_CR_FULLDUPLEX_1000M ((u16)0x2140U) /* Set the full-duplex mode at 1000 Mb/s */ +#define FGMAC_PHY_MII_CR_HALFDUPLEX_1000M ((u16)0x2040U) /* Set the half-duplex mode at 1000 Mb/s */ +#define FGMAC_PHY_MII_CR_FULLDUPLEX_100M ((u16)0x2100U) /* Set the full-duplex mode at 100 Mb/s */ +#define FGMAC_PHY_MII_CR_HALFDUPLEX_100M ((u16)0x2000U) /* Set the half-duplex mode at 100 Mb/s */ +#define FGMAC_PHY_MII_CR_FULLDUPLEX_10M ((u16)0x0100U) /* Set the full-duplex mode at 10 Mb/s */ +#define FGMAC_PHY_MII_CR_HALFDUPLEX_10M ((u16)0x0000U) /* Set the half-duplex mode at 10 Mb/s */ + +/* Basic mode status register. */ +#define FGMAC_PHY_MII_SR_EXT_CAP BIT(0) /* Ext-reg capability */ +#define FGMAC_PHY_MII_SR_JCD BIT(1) /* Jabber detected */ +#define FGMAC_PHY_MII_SR_LSTATUS BIT(2) /* Link status */ +#define FGMAC_PHY_MII_SR_AUTO_NEGOT BIT(3) /* Able to do auto-negotiation */ +#define FGMAC_PHY_MII_SR_REMOTE_FAULT BIT(4) /* Remote fault detected */ +#define FGMAC_PHY_MII_SR_AUTO_NEGOT_COMPLETE BIT(5) /* Auto-negotiation complete */ +#define FGMAC_PHY_MII_SR_MF_PREAM BIT(6) /* MF Preamble Suppression */ +#define FGMAC_PHY_MII_SR_EXT_STATUS BIT(8) /* Extended Status in R15 */ +#define FGMAC_PHY_MII_SR_100HALF2 BIT(9) /* Can do 100BASE-T2 HDX */ +#define FGMAC_PHY_MII_SR_100FULL2 BIT(10) /* Can do 100BASE-T2 FDX */ +#define FGMAC_PHY_MII_SR_10HALF BIT(11) /* Can do 10mbps, half-duplex */ +#define FGMAC_PHY_MII_SR_10FULL BIT(12) /* Can do 10mbps, full-duplex */ +#define FGMAC_PHY_MII_SR_100HALF BIT(13) /* Can do 100mbps, half-duplex */ +#define FGMAC_PHY_MII_SR_100FULL BIT(14) /* Can do 100mbps, full-duplex */ +#define FGMAC_PHY_MII_SR_100BASE4 BIT(15) /* Can do 100mbps, 4k packets */ + +/* MII_STAT1000 masks */ +#define FGMAC_PHY_MII_1000BTSR_MSCF BIT(15) /* Master/Slave Configuration Fault */ +#define FGMAC_PHY_MII_1000BTSR_MSCR BIT(14) /* Master/Slave Configuration Resolution */ +#define FGMAC_PHY_MII_1000BTSR_LRS BIT(13) /* Local Receiver Status */ +#define FGMAC_PHY_MII_1000BTSR_RRS BIT(12) /* Remote Receiver Status */ +#define FGMAC_PHY_MII_1000BTSR_1000FD BIT(11) /* Full Duplex Capability */ +#define FGMAC_PHY_MII_1000BTSR_1000HD BIT(10) /* Half Duplex Capability */ +#define FGMAC_PHY_MII_1000BTSR_IDLE_ERR_CNT GENMASK(7, 0) /* MSB of Idle Error Counter */ + +/* Link partner ability register. */ +#define FGMAC_PHY_MII_LPA_SELECT GENMASK(4, 0) /* Selector Field */ +#define FGMAC_PHY_MII_LPA_10HALF BIT(5) /* 10BASE-T half-duplex capable */ +#define FGMAC_PHY_MII_LPA_10FULL BIT(6) /* 10BASE-T full-duplex capable */ +#define FGMAC_PHY_MII_LPA_1000TXHALF BIT(7) /* 100BASE-TX half-duplex capable */ +#define FGMAC_PHY_MII_LPA_1000TXFULL BIT(8) /* 100BASE-TX full-duplex capable */ +#define FGMAC_PHY_MII_LPA_T4 BIT(9) /* 100BASE-T4 capable */ +#define FGMAC_PHY_MII_LPA_PAUSE BIT(10) /* capable of pause operation */ +#define FGMAC_PHY_MII_LPA_ASY_PAUSE BIT(11) /* asymmetric pause */ +#define FGMAC_PHY_MII_LPA_REMOTE_FAULT BIT(13) /* Remote Fault */ +#define FGMAC_PHY_MII_LPA_ACK BIT(14) /* Acknowledge */ +#define FGMAC_PHY_MII_LPA_NEXT_PAGE BIT(15) /* capable of next page */ + +/* Expansion register for auto-negotiation. */ +#define FGMAC_PHY_MII_ESTATUS_1000_XFULL BIT(15) /* Can do 1000BX Full */ +#define FGMAC_PHY_MII_ESTATUS_1000_XHALF BIT(14) /* Can do 1000BX Half */ +#define FGMAC_PHY_MII_ESTATUS_1000_TFULL BIT(13) /* Can do 1000BT Full */ +#define FGMAC_PHY_MII_ESTATUS_1000_THALF BIT(12) /* Can do 1000BT Half */ +#define FGMAC_PHY_MII_ESTATUS_MASK (FGMAC_PHY_MII_ESTATUS_1000_XFULL | FGMAC_PHY_MII_ESTATUS_1000_XHALF | \ + FGMAC_PHY_MII_ESTATUS_1000_TFULL | FGMAC_PHY_MII_ESTATUS_1000_THALF) +#define FGMAC_PHY_MII_ESTATUS_FULL_MASK (FGMAC_PHY_MII_ESTATUS_1000_XFULL | FGMAC_PHY_MII_ESTATUS_1000_TFULL) + + +#define FGMAC_PHY_SPECIFIC_STATUS_SPEED_MASK GENMASK(15, 14) + +#define FGMAC_PHY_SPECIFIC_STATUS_SPEED_1000M (2L << 14) +#define FGMAC_PHY_SPECIFIC_STATUS_SPEED_100M (1L << 14) +#define FGMAC_PHY_SPECIFIC_STATUS_SPEED_10M (0L << 14) + +#define FGMAC_PHY_SPECIFIC_STATUS_DUPLEX_MASK BIT(13) + +enum +{ + FGMAC_PHY_AUTONEGOTIATION_DISABLE = 0, + FGMAC_PHY_AUTONEGOTIATION_ENABLE +}; + +enum +{ + FGMAC_PHY_MODE_HALFDUPLEX = 0, + FGMAC_PHY_MODE_FULLDUPLEX = 1 +}; + +/* The forced speed, 10Mb, 100Mb, gigabit, 2.5Gb, 10GbE. */ +enum +{ + FGMAC_PHY_SPEED_10 = 10, + FGMAC_PHY_SPEED_100 = 100, + FGMAC_PHY_SPEED_1000 = 1000, + FGMAC_PHY_SPEED_2500 = 2500, + FGMAC_PHY_SPEED_10000 = 10000 +}; + +enum +{ + FGMAC_PHY_MII_ADDR_CR_60_100MHZ = (0b0000), + FGMAC_PHY_MII_ADDR_CR_100_150MHZ = (0b0001), + FGMAC_PHY_MII_ADDR_CR_23_35MHZ = (0b0010), + FGMAC_PHY_MII_ADDR_CR_35_60MHZ = (0b0011), + FGMAC_PHY_MII_ADDR_CR_150_250MHZ = (0b0100), + FGMAC_PHY_MII_ADDR_CR_250_300MHZ = (0b0101) +}; + +/**************************** Type Definitions *******************************/ +/** + * This typedef contains driver instance data. The user is required to allocate a + * variable of this type for every device in the system. A pointer + * to a variable of this type is then passed to the driver API functions. + */ + + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/* init phy device */ +FError FGmacPhyCfgInitialize(FGmac *instance_p); +/* write phy register */ +FError FGmacWritePhyReg(FGmac *instance_p, u32 phy_address, u16 phy_reg, u16 phy_reg_val); +/* read phy register */ +FError FGmacReadPhyReg(FGmac *instance_p, u32 phy_address, u16 phy_reg, u16 *phy_reg_val_p); + +FError FGmacPhyCfgDeInitialize(FGmac *instance_p); + +FError FGmacPhyAwaken(FGmac *instance_p); +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/Kconfig b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/Kconfig new file mode 100644 index 0000000000..90655a6e74 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/Kconfig @@ -0,0 +1,13 @@ +choice FXMAC_PHY_TYPE + prompt "PHY Type" + default FXMAC_PHY_COMMON + help + Select PHY for FGMAC + + config FXMAC_PHY_COMMON + bool "Common" + config FXMAC_PHY_YT + bool "YT" + +endchoice # FXMAC_PHY_TYPE + diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac.c new file mode 100644 index 0000000000..ffdca1ffbf --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac.c @@ -0,0 +1,874 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fxmac.h" +#include "ftypes.h" +#include "fxmac_hw.h" +#include "stdio.h" + +#include "fdebug.h" + + +#define FXMAC_DEBUG_TAG "FXMAC" +#define FXMAC_PRINT_E(format, ...) FT_DEBUG_PRINT_E(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FXMAC_PRINT_I(format, ...) FT_DEBUG_PRINT_I(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FXMAC_PRINT_D(format, ...) FT_DEBUG_PRINT_D(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FXMAC_PRINT_W(format, ...) FT_DEBUG_PRINT_W(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) + + +static void FXmacReset(FXmac *instance_p); +extern FError FXmacSetTypeIdCheck(FXmac *instance_p, u32 id_check, u8 index); + +/** + * @name: FXmacSelectClk + * @msg: Determine the driver clock configuration based on the media independent interface + * @param {FXmac} *instance_p is a pointer to the instance to be worked on. + * @param {u32} speed interface speed + * @return {*} + */ +void FXmacSelectClk(FXmac *instance_p) +{ + u32 reg_value; + s32 set_speed = 0; + u32 speed = instance_p->config.speed; + FASSERT(instance_p != NULL); + FASSERT((speed == FXMAC_SPEED_10) || (speed == FXMAC_SPEED_100) || (speed == FXMAC_SPEED_1000) || (speed == FXMAC_SPEED_2500) || (speed == FXMAC_SPEED_10000)); + + if ((instance_p->config.interface == FXMAC_PHY_INTERFACE_MODE_USXGMII) || (instance_p->config.interface == FXMAC_PHY_INTERFACE_MODE_XGMII)) + { + if (speed == FXMAC_SPEED_10000) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_SRC_SEL_LN, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL0_LN, 0x4); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL1_LN, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_PMA_XCVR_POWER_STATE, 0x1); + } + } + else if (instance_p->config.interface == FXMAC_PHY_INTERFACE_MODE_SGMII) + { + FXMAC_PRINT_I("FXMAC_PHY_INTERFACE_MODE_SGMII init"); + if (speed == FXMAC_SPEED_2500) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_SRC_SEL_LN, 0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL0_LN, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL1_LN, 0x2); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_PMA_XCVR_POWER_STATE, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL0, 0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL1, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL2, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL0, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL1, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3_0, 0x0); /*0x1c70*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL4_0, 0x0); /*0x1c74*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL3_0, 0x0); /*0x1c78*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL4_0, 0x0); /*0x1c7c*/ + } + else if (speed == FXMAC_SPEED_1000) + { + FXMAC_PRINT_I("sgmii FXMAC_SPEED_1000 \r\n "); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_SRC_SEL_LN, 1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL0_LN, 0x4); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL1_LN, 0x8); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_PMA_XCVR_POWER_STATE, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL0, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL1, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL2, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL0, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL1, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3_0, 0x0); /*0x1c70*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL4_0, 0x0); /*0x1c74*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL3_0, 0x0); /*0x1c78*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL4_0, 0x0); /*0x1c7c*/ + } + else if ((speed == FXMAC_SPEED_100) || (speed == FXMAC_SPEED_10)) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL0_LN, 0x4); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_DIV_SEL1_LN, 0x8); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_PMA_XCVR_POWER_STATE, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL0, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL1, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL2, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL0, 0x1); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL1, 0x0); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3_0, 0x1); /*0x1c70*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL4_0, 0x0); /*0x1c74*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL3_0, 0x0); /*0x1c78*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL4_0, 0x1); /*0x1c7c*/ + } + } + else if (instance_p->config.interface == FXMAC_PHY_INTERFACE_MODE_RGMII) + { + FXMAC_PRINT_I("FXMAC_PHY_INTERFACE_MODE_RGMII init"); + if (speed == FXMAC_SPEED_1000) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_MII_SELECT, 0x1); /*0x1c18*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_SEL_MII_ON_RGMII, 0x0); /*0x1c1c*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL0, 0x0); /*0x1c20*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL1, 0x1); /*0x1c24*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL2, 0x0); /*0x1c28*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3, 0x0); /*0x1c2c*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL0, 0x0); /*0x1c30*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL1, 0x1); /*0x1c34*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_CLK_250M_DIV10_DIV100_SEL, + 0x0); /*0x1c38*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL5, 0x1); /*0x1c48*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RGMII_TX_CLK_SEL0, 0x1); /*0x1c80*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RGMII_TX_CLK_SEL1, 0x0); /*0x1c84*/ + } + else if (speed == FXMAC_SPEED_100) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_SEL_MII_ON_RGMII, 0x0); /*0x1c1c*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL0, 0x0); /*0x1c20*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL1, 0x1); /*0x1c24*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL2, 0x0); /*0x1c28*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3, 0x0); /*0x1c2c*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL0, 0x0); /*0x1c30*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL1, 0x1); /*0x1c34*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_CLK_250M_DIV10_DIV100_SEL, + 0x0); /*0x1c38*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL5, 0x1); /*0x1c48*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RGMII_TX_CLK_SEL0, 0x0); /*0x1c80*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RGMII_TX_CLK_SEL1, 0x0); /*0x1c84*/ + } + else + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_SEL_MII_ON_RGMII, 0x0); /*0x1c1c*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL0, 0x0); /*0x1c20*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL1, 0x1); /*0x1c24*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL2, 0x0); /*0x1c28*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_TX_CLK_SEL3, 0x0); /*0x1c2c*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL0, 0x0); /*0x1c30*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL1, 0x1); /*0x1c34*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_CLK_250M_DIV10_DIV100_SEL, + 0x1); /*0x1c38*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL5, 0x1); /*0x1c48*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RGMII_TX_CLK_SEL0, 0x0); /*0x1c80*/ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RGMII_TX_CLK_SEL1, 0x0); /*0x1c84*/ + } + } + else if (instance_p->config.interface == FXMAC_PHY_INTERFACE_MODE_RMII) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_RX_CLK_SEL5, 0x1); /*0x1c48*/ + } + + + switch (speed) + { + case FXMAC_SPEED_25000: + set_speed = 2; + break; + case FXMAC_SPEED_10000: + set_speed = 4; + break; + case FXMAC_SPEED_5000: + set_speed = 3; + break; + case FXMAC_SPEED_2500: + set_speed = 2; + break; + case FXMAC_SPEED_1000: + set_speed = 1; + break; + default: + set_speed = 0; + break; + } + /*GEM_HSMAC(0x0050) provide rate to the external*/ + reg_value = FXMAC_READREG32(instance_p->config.base_address, FXMAC_GEM_HSMAC); + reg_value &= ~FXMAC_GEM_HSMACSPEED_MASK; + reg_value |= (set_speed) &FXMAC_GEM_HSMACSPEED_MASK; + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_GEM_HSMAC, reg_value); + + reg_value = FXMAC_READREG32(instance_p->config.base_address, FXMAC_GEM_HSMAC); + + FXMAC_PRINT_I("FXMAC_GEM_HSMAC is %x \r\n ", reg_value); +} + +/** + * Start the Ethernet controller as follows: + * - Enable transmitter if FXMAC_TRANSMIT_ENABLE_OPTION is set + * - Enable receiver if FXMAC_RECEIVER_ENABLE_OPTION is set + * - Start the SG DMA send and receive channels and enable the device + * interrupt + * + * @param instance_p is a pointer to the instance to be worked on. + * + * @return N/A + * + * @note + * Hardware is configured with scatter-gather DMA, the driver expects to start + * the scatter-gather channels and expects that the user has previously set up + * the buffer descriptor lists. + * + * This function makes use of internal resources that are shared between the + * Start, Stop, and Set/ClearOptions functions. So if one task might be setting + * device options while another is trying to start the device, the user is + * required to provide protection of this shared data (typically using a + * semaphore). + * + * This function must not be preempted by an interrupt that may service the + * device. + * + */ +void FXmacStart(FXmac *instance_p) +{ + u32 reg_val; + u32 reg = 0; + + /* Assert bad arguments and conditions */ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + + /* Start DMA */ + /* When starting the DMA channels, both transmit and receive sides + * need an initialized BD list. + */ + + FASSERT(instance_p->rx_bd_queue.bdring.base_bd_addr != 0); + + reg = FXMAC_READREG32(instance_p->config.base_address, FXMAC_RXQBASE_OFFSET); + reg = FXMAC_READREG32(instance_p->config.base_address, FXMAC_TXQBASE_OFFSET); + + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_RXQBASE_OFFSET, + instance_p->rx_bd_queue.bdring.base_bd_addr); + + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_TXQBASE_OFFSET, + instance_p->tx_bd_queue.bdring.base_bd_addr); + + reg = FXMAC_READREG32(instance_p->config.base_address, FXMAC_RXQBASE_OFFSET); + reg = FXMAC_READREG32(instance_p->config.base_address, FXMAC_TXQBASE_OFFSET); + + /* clear any existed int status */ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, + FXMAC_IXR_ALL_MASK); + + /* Enable transmitter if not already enabled */ + if ((instance_p->config.network_default_config & (u32)FXMAC_TRANSMITTER_ENABLE_OPTION) != 0x00000000U) + { + reg_val = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + if ((!(reg_val & FXMAC_NWCTRL_TXEN_MASK)) == TRUE) + { + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, + reg_val | (u32)FXMAC_NWCTRL_TXEN_MASK); + } + } + + /* Enable receiver if not already enabled */ + if ((instance_p->config.network_default_config & FXMAC_RECEIVER_ENABLE_OPTION) != 0x00000000U) + { + + reg_val = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + FXMAC_PRINT_I("endable receiver 0x%x \r\n ", reg_val); + if ((!(reg_val & FXMAC_NWCTRL_RXEN_MASK)) == TRUE) + { + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, + reg_val | (u32)FXMAC_NWCTRL_RXEN_MASK); + } + } + FXMAC_PRINT_I("FXMAC_NWCTRL_OFFSET is 0x%x \r\n", FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET)); + + /* Enable TX and RX interrupt */ + FXMAC_INT_ENABLE(instance_p, FXMAC_IXR_LINKCHANGE_MASK | FXMAC_IXR_TX_ERR_MASK | FXMAC_IXR_RX_ERR_MASK | FXMAC_IXR_RXCOMPL_MASK | FXMAC_IXR_TXCOMPL_MASK); + + /* Mark as started */ + instance_p->is_started = FT_COMPONENT_IS_STARTED; + + return; +} + + +/** + * Gracefully stop the Ethernet MAC as follows: + * - Disable all interrupts from this device + * - Stop DMA channels + * - Disable the tansmitter and receiver + * + * Device options currently in effect are not changed. + * + * This function will disable all interrupts. Default interrupts settings that + * had been enabled will be restored when FXmacStart() is called. + * + * @param instance_p is a pointer to the instance to be worked on. + * + * @note + * This function makes use of internal resources that are shared between the + * Start, Stop, Setoptions, and Clearoptions functions. So if one task might be + * setting device options while another is trying to start the device, the user + * is required to provide protection of this shared data (typically using a + * semaphore). + * + * Stopping the DMA channels causes this function to block until the DMA + * operation is complete. + * + */ +void FXmacStop(FXmac *instance_p) +{ + u32 reg_val; + + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + + /* Disable all interrupts */ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_IDR_OFFSET, + FXMAC_IXR_ALL_MASK); + + + + /* Disable the receiver & transmitter */ + reg_val = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + reg_val &= (u32)(~FXMAC_NWCTRL_RXEN_MASK); + reg_val &= (u32)(~FXMAC_NWCTRL_TXEN_MASK); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, reg_val); + + /* Mark as stopped */ + instance_p->is_started = 0U; +} + +static u32 FXmacClkDivGet(FXmac *instance_p) +{ + FXmacConfig *config_p; + + config_p = &instance_p->config; + + if (config_p->pclk_hz <= 20000000) + { + return FXMAC_NWCFG_CLOCK_DIV8_MASK; + } + else if (config_p->pclk_hz <= 40000000) + { + return FXMAC_NWCFG_CLOCK_DIV16_MASK; + } + else if (config_p->pclk_hz <= 80000000) + { + return FXMAC_NWCFG_CLOCK_DIV32_MASK; + } + else if (instance_p->moudle_id >= 2) + { + if (config_p->pclk_hz <= 120000000) + { + return FXMAC_NWCFG_CLOCK_DIV48_MASK; + } + else if (config_p->pclk_hz <= 160000000) + { + return FXMAC_NWCFG_CLOCK_DIV64_MASK; + } + else if (config_p->pclk_hz <= 240000000) + { + return FXMAC_NWCFG_CLOCK_DIV96_MASK; + } + else if (config_p->pclk_hz <= 320000000) + { + return FXMAC_NWCFG_CLOCK_DIV128_MASK; + } + else + { + return FXMAC_NWCFG_CLOCK_DIV224_MASK; + } + } + else + { + return FXMAC_NWCFG_CLOCK_DIV64_MASK; + } +} + +static u32 FXmacDmaWidth(FXmac *instance_p) +{ + u32 read_regs = 0; + FXmacConfig *config_p; + config_p = &instance_p->config; + + if (instance_p->moudle_id < 2) + { + return FXMAC_NWCFG_BUS_WIDTH_32_MASK; + } + + read_regs = FXMAC_READREG32(config_p->base_address, FXMAC_DESIGNCFG_DEBUG1_OFFSET); + + switch ((read_regs & FXMAC_DESIGNCFG_DEBUG1_BUS_WIDTH_MASK) >> 25) + { + case 4: + FXMAC_PRINT_I("bus width is 128"); + return FXMAC_NWCFG_BUS_WIDTH_128_MASK; + case 2: + FXMAC_PRINT_I("bus width is 64"); + return FXMAC_NWCFG_BUS_WIDTH_64_MASK; + default: + FXMAC_PRINT_I("bus width is 32"); + return FXMAC_NWCFG_BUS_WIDTH_32_MASK; + } +} + +static void FXmacDmaReset(FXmac *instance_p) +{ + u32 queue = 0; + FXmacConfig *config_p; + config_p = &instance_p->config; + u32 dmacfg = 0; + u32 rx_buf_size = 0; + + rx_buf_size = instance_p->max_frame_size / FXMAC_RX_BUF_UNIT; + rx_buf_size += ((instance_p->max_frame_size % FXMAC_RX_BUF_UNIT) != 0) ? 1 : 0; /* roundup */ + + if (instance_p->moudle_id >= 2) + { + for (queue = 0; queue < config_p->max_queue_num; queue++) + { + dmacfg = 0; + FXmacSetQueuePtr(instance_p, (uintptr)NULL, queue, (u16)FXMAC_SEND); + FXmacSetQueuePtr(instance_p, (uintptr)NULL, queue, (u16)FXMAC_RECV); + + if (queue) + { + FXMAC_WRITEREG32(config_p->base_address, FXMAC_RXBUFQX_SIZE_OFFSET(queue), rx_buf_size); + } + else /* queue is 0 */ + { + dmacfg |= ((u32)FXMAC_DMACR_RXBUF_MASK & (rx_buf_size << FXMAC_DMACR_RXBUF_SHIFT)); + } + } + + dmacfg |= (config_p->dma_brust_length & FXMAC_DMACR_BLENGTH_MASK); + + dmacfg &= ~FXMAC_DMACR_ENDIAN_MASK; + dmacfg &= ~FXMAC_DMACR_SWAP_MANAGEMENT_MASK; /* 选择小端 */ + + dmacfg &= ~FXMAC_DMACR_TCPCKSUM_MASK; /* close transmitter checksum generation engine */ + + dmacfg &= ~FXMAC_DMACR_ADDR_WIDTH_64; + dmacfg |= FXMAC_DMACR_RXSIZE_MASK | FXMAC_DMACR_TXSIZE_MASK; +#if defined(__aarch64__) || defined(__arch64__) + dmacfg |= FXMAC_DMACR_ADDR_WIDTH_64; +#endif + } + else + { + FXmacSetQueuePtr(instance_p, (uintptr)NULL, 0, (u16)FXMAC_SEND); + FXmacSetQueuePtr(instance_p, (uintptr)NULL, 0, (u16)FXMAC_RECV); + dmacfg |= ((u32)FXMAC_DMACR_RXBUF_MASK & (rx_buf_size << FXMAC_DMACR_RXBUF_SHIFT)); + dmacfg |= (config_p->dma_brust_length & FXMAC_DMACR_BLENGTH_MASK); + + dmacfg &= ~FXMAC_DMACR_ENDIAN_MASK; + dmacfg &= ~FXMAC_DMACR_SWAP_MANAGEMENT_MASK; /* 选择小端 */ + + dmacfg &= ~FXMAC_DMACR_TCPCKSUM_MASK; /* close transmitter checksum generation engine */ + + dmacfg &= ~FXMAC_DMACR_ADDR_WIDTH_64; + dmacfg |= FXMAC_DMACR_RXSIZE_MASK | FXMAC_DMACR_TXSIZE_MASK; +#if defined(__aarch64__) || defined(__arch64__) + dmacfg |= FXMAC_DMACR_ADDR_WIDTH_64; +#endif + } + + FXMAC_WRITEREG32(config_p->base_address, FXMAC_DMACR_OFFSET, dmacfg); +} + + +/** + * Perform a graceful reset of the Ethernet MAC. Resets the DMA channels, the + * transmitter, and the receiver. + * + * Steps to reset + * - Stops transmit and receive channels + * - Stops DMA + * - Configure transmit and receive buffer size to default + * - Clear transmit and receive status register and counters + * - Clear all interrupt sources + * - Clear phy (if there is any previously detected) address + * - Clear MAC addresses (1-4) as well as Type IDs and hash value + * + * All options are placed in their default state. Any frames in the + * descriptor lists will remain in the lists. The side effect of doing + * this is that after a reset and following a restart of the device, frames + * were in the list before the reset may be transmitted or received. + * + * The upper layer software is responsible for re-configuring (if necessary) + * and restarting the MAC after the reset. Note also that driver statistics + * are not cleared on reset. It is up to the upper layer software to clear the + * statistics if needed. + * + * When a reset is required, the driver notifies the upper layer software of + * this need through the ErrorHandler callback and specific status codes. + * The upper layer software is responsible for calling this Reset function + * and then re-configuring the device. + * + * @param instance_p is a pointer to the instance to be worked on. + * + */ +static void FXmacReset(FXmac *instance_p) +{ + u32 reg_val, write_reg = 0; + u8 i; + s8 mac_addr[6] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; + u32 rx_buf_num; + + FASSERT(instance_p != NULL); + + /* Stop the device and reset hardware */ + FXmacStop(instance_p); + + instance_p->moudle_id = (FXMAC_READREG32(instance_p->config.base_address, FXMAC_REVISION_REG_OFFSET) & FXMAC_IDENTIFICATION_MASK) >> 16; + FXMAC_PRINT_I("instance_p->moudle_id is %d \r\n", instance_p->moudle_id); + instance_p->max_mtu_size = FXMAC_MTU; + instance_p->max_frame_size = FXMAC_MTU + FXMAC_HDR_SIZE + FXMAC_TRL_SIZE; + + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, + ((FXMAC_NWCTRL_STATCLR_MASK) & (u32)(~FXMAC_NWCTRL_LOOPEN_MASK)) | FXMAC_NWCTRL_MDEN_MASK); + + write_reg = FXmacClkDivGet(instance_p); /* mdio clock division */ + write_reg |= FXmacDmaWidth(instance_p); /* 位宽 */ + + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_NWCFG_OFFSET, write_reg); + + FXmacDmaReset(instance_p); + + /* This register, when read provides details of the status of the receive path. */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_RXSR_OFFSET, FXMAC_SR_ALL_MASK); + + /* write 1 ro the relavant bit location disable that particular interrupt */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_IDR_OFFSET, FXMAC_IXR_ALL_MASK); + + reg_val = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_ISR_OFFSET); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, + reg_val); + + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_TXSR_OFFSET, FXMAC_SR_ALL_MASK); + + FXmacClearHash(instance_p); + + /* set default mac address */ + for (i = 0U; i < 4U; i++) + { + (void)FXmacSetMacAddress(instance_p, mac_addr, i); + (void)FXmacGetMacAddress(instance_p, mac_addr, i); + (void)FXmacSetTypeIdCheck(instance_p, 0x00000000U, i); + } + + /* clear all counters */ + for (i = 0U; i < (u8)((FXMAC_LAST_OFFSET - FXMAC_OCTTXL_OFFSET) / 4U); + i++) + { + (void)FXMAC_READREG32(instance_p->config.base_address, + FXMAC_OCTTXL_OFFSET + (u32)(((u32)i) * ((u32)4))); + } + + /* Sync default options with hardware but leave receiver and + * transmitter disabled. They get enabled with FXmacStart() if + * FXMAC_TRANSMITTER_ENABLE_OPTION and + * FXMAC_RECEIVER_ENABLE_OPTION are set. + */ + FXmacSetOptions(instance_p, instance_p->config.network_default_config & ~((u32)FXMAC_TRANSMITTER_ENABLE_OPTION | (u32)FXMAC_RECEIVER_ENABLE_OPTION), 0); + FXmacClearOptions(instance_p, ~instance_p->config.network_default_config, 0); +} + +/** + * @name: FXmacInitInterface + * @msg: Initialize the MAC controller configuration based on the PHY interface type + * @note: + * @param {FXmac} *instance_p is a pointer to the instance to be worked on. + */ +void FXmacInitInterface(FXmac *instance_p) +{ + u32 config, control; + FXmacConfig *config_p; + config_p = &instance_p->config; + + if (config_p->interface == FXMAC_PHY_INTERFACE_MODE_XGMII) + { + config = FXMAC_READREG32(config_p->base_address, FXMAC_NWCFG_OFFSET); + config &= ~FXMAC_NWCFG_PCSSEL_MASK; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCFG_OFFSET, config); + + control = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + control |= FXMAC_NWCTRL_ENABLE_HS_MAC_MASK; /* Use high speed MAC */ + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, control); + + config_p->duplex = 1; + } + else if (config_p->interface == FXMAC_PHY_INTERFACE_MODE_USXGMII) + { + config = FXMAC_READREG32(config_p->base_address, FXMAC_NWCFG_OFFSET); + config |= FXMAC_NWCFG_PCSSEL_MASK; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCFG_OFFSET, config); + + control = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + control |= FXMAC_NWCTRL_ENABLE_HS_MAC_MASK; /* Use high speed MAC */ + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, control); + + control = FXMAC_READREG32(config_p->base_address, FXMAC_GEM_USX_CONTROL_OFFSET); + control &= ~(FXMAC_GEM_USX_TX_SCR_BYPASS | FXMAC_GEM_USX_RX_SCR_BYPASS); + control |= FXMAC_GEM_USX_RX_SYNC_RESET; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_GEM_USX_CONTROL_OFFSET, control); + + control = FXMAC_READREG32(config_p->base_address, FXMAC_GEM_USX_CONTROL_OFFSET); + control &= ~FXMAC_GEM_USX_RX_SYNC_RESET; + control |= FXMAC_GEM_USX_TX_DATAPATH_EN; + control |= FXMAC_GEM_USX_SIGNAL_OK; + + if (config_p->speed == FXMAC_SPEED_10000) + { + control |= FXMAC_GEM_USX_HS_MAC_SPEED_10G; + } + else if (config_p->speed == FXMAC_SPEED_25000) + { + control |= FXMAC_GEM_USX_HS_MAC_SPEED_2_5G; + } + else if (config_p->speed == FXMAC_SPEED_1000) + { + control |= FXMAC_GEM_USX_HS_MAC_SPEED_1G; + } + else if (config_p->speed == FXMAC_SPEED_100) + { + control |= FXMAC_GEM_USX_HS_MAC_SPEED_100M; + } + + FXMAC_WRITEREG32(config_p->base_address, FXMAC_GEM_USX_CONTROL_OFFSET, control); + config_p->duplex = 1; + } + else if (config_p->interface == FXMAC_PHY_INTERFACE_MODE_SGMII) + { + config = FXMAC_READREG32(config_p->base_address, FXMAC_NWCFG_OFFSET); + config |= FXMAC_NWCFG_PCSSEL_MASK | FXMAC_NWCFG_SGMII_MODE_ENABLE_MASK; + + config &= ~(FXMAC_NWCFG_100_MASK | FXMAC_NWCFG_FDEN_MASK); + + if (instance_p->moudle_id >= 2) + { + config &= ~FXMAC_NWCFG_1000_MASK; + } + + if (config_p->duplex) + { + config |= FXMAC_NWCFG_FDEN_MASK; + } + + if (config_p->speed == FXMAC_SPEED_100) + { + config |= FXMAC_NWCFG_100_MASK; + } + else if (config_p->speed == FXMAC_SPEED_1000) + { + config |= FXMAC_NWCFG_1000_MASK; + } + + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCFG_OFFSET, config); + + if (config_p->speed == FXMAC_SPEED_2500) + { + control = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + control |= FXMAC_NWCTRL_TWO_PT_FIVE_GIG_MASK; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, control); + } + else + { + control = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + control &= ~FXMAC_NWCTRL_TWO_PT_FIVE_GIG_MASK; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, control); + } + + control = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + control &= ~FXMAC_NWCTRL_ENABLE_HS_MAC_MASK; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, control); + + control = FXMAC_READREG32(config_p->base_address, FXMAC_PCS_CONTROL_OFFSET); + control |= FXMAC_PCS_CONTROL_ENABLE_AUTO_NEG; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_PCS_CONTROL_OFFSET, control); + } + else + { + config = FXMAC_READREG32(config_p->base_address, FXMAC_NWCFG_OFFSET); + + FXMAC_PRINT_I("select rgmii \r\n"); + + config &= ~FXMAC_NWCFG_PCSSEL_MASK; + config &= ~(FXMAC_NWCFG_100_MASK | FXMAC_NWCFG_FDEN_MASK); + + if (instance_p->moudle_id >= 2) + { + config &= ~FXMAC_NWCFG_1000_MASK; + } + + if (config_p->duplex) + { + config |= FXMAC_NWCFG_FDEN_MASK; + } + + if (config_p->speed == FXMAC_SPEED_100) + { + config |= FXMAC_NWCFG_100_MASK; + } + else if (config_p->speed == FXMAC_SPEED_1000) + { + config |= FXMAC_NWCFG_1000_MASK; + } + + if (config_p->duplex) + { + config |= FXMAC_NWCFG_FDEN_MASK; + } + + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCFG_OFFSET, config); + + control = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + control &= ~FXMAC_NWCTRL_ENABLE_HS_MAC_MASK; /* Use high speed MAC */ + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, control); + } +} + + +static void FXmacIrqStubHandler(void) +{ + FASSERT_MSG(0, "Please register the interrupt callback function"); +} + +/** + * @name: FXmacCfgInitialize + * @msg: Initialize a specific fxmac instance/driver. + * @note: + * @param {FXmac} *instance_p is a pointer to the instance to be worked on. + * @param {FXmacConfig} *config_p is the device configuration structure containing required +* hardware build data. + * @return {FT_SUCCESS} if initialization was successful + */ +FError FXmacCfgInitialize(FXmac *instance_p, const FXmacConfig *config_p) +{ + /* Verify arguments */ + FASSERT(instance_p != NULL); + FASSERT(config_p != NULL); + + instance_p->config = *config_p; + instance_p->link_status = FXMAC_LINKDOWN; + /* Reset the hardware and set default options */ + instance_p->is_ready = FT_COMPONENT_IS_READY; + FXmacReset(instance_p); + + instance_p->send_irq_handler = (FXmacIrqHandler)FXmacIrqStubHandler; + instance_p->send_args = NULL; + + instance_p->recv_irq_handler = (FXmacIrqHandler)FXmacIrqStubHandler; + instance_p->recv_args = NULL; + + instance_p->error_irq_handler = (FXmacErrorIrqHandler)FXmacIrqStubHandler; + instance_p->error_args = NULL; + + instance_p->link_change_handler = (FXmacIrqHandler)FXmacIrqStubHandler; + instance_p->link_change_args = NULL; + + instance_p->restart_handler = (FXmacIrqHandler)FXmacIrqStubHandler; + instance_p->restart_args = NULL; + + return FT_SUCCESS; +} + + +/** + * This function sets the start address of the transmit/receive buffer queue. + * + * @param instance_p is a pointer to the instance to be worked on. + * @param queue_p is the address of the Queue to be written + * @param queue_num is the Buffer Queue Index + * @param direction indicates Transmit/Receive + * + * @note + * The buffer queue addresses has to be set before starting the transfer, so + * this function has to be called in prior to FXmacStart() + * + */ +void FXmacSetQueuePtr(FXmac *instance_p, uintptr queue_p, u8 queue_num, + u32 direction) +{ + /* Assert bad arguments and conditions */ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + + /* If already started, then there is nothing to do */ + if (instance_p->is_started == (u32)FT_COMPONENT_IS_STARTED) + { + return; + } + + if (queue_num == 0x00U) + { + if (direction == FXMAC_SEND) + { + /* set base start address of TX buffer queue (tx buffer descriptor list) */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_TXQBASE_OFFSET, + (queue_p & ULONG64_LO_MASK) | (((queue_p == (uintptr)0)) ? 1 : 0)); + } + else + { + /* set base start address of RX buffer queue (rx buffer descriptor list) */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_RXQBASE_OFFSET, + (queue_p & ULONG64_LO_MASK) | (((queue_p == (uintptr)0)) ? 1 : 0)); + } + } + else + { + if (direction == FXMAC_SEND) + { + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_TXQ1BASE_OFFSET, queue_num), + (queue_p & ULONG64_LO_MASK) | (((queue_p == (uintptr)0)) ? 1 : 0)); + } + else + { + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_TXQ1BASE_OFFSET, queue_num), + (queue_p & ULONG64_LO_MASK) | (((queue_p == (uintptr)0)) ? 1 : 0)); + } + } +#ifdef __aarch64__ + if (direction == FXMAC_SEND) + { + /* Set the MSB of TX Queue start address */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_MSBBUF_TXQBASE_OFFSET, + (u32)((queue_p & ULONG64_HI_MASK) >> 32U)); + } + else + { + /* Set the MSB of RX Queue start address */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_MSBBUF_RXQBASE_OFFSET, + (u32)((queue_p & ULONG64_HI_MASK) >> 32U)); + } +#endif +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac.h b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac.h new file mode 100644 index 0000000000..19678d929c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac.h @@ -0,0 +1,332 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_ETH_F_XMAC_H +#define DRIVERS_ETH_F_XMAC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fassert.h" +#include "ferror_code.h" + +#include "fxmac_hw.h" +#include "fxmac_bdring.h" +#include "fparameters.h" + +#define FXMAC_ERR_INVALID_PARAM FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x1u) +#define FXMAC_ERR_SG_LIST FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x2u) +#define FXMAC_ERR_GENERAL FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x4u) +#define FXMAC_ERR_SG_NO_LIST FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x5u) +#define FXMAC_ERR_PHY_BUSY FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x6u) +#define FXMAC_PHY_IS_NOT_FOUND FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x7u) +#define FXMAC_PHY_AUTO_AUTONEGOTIATION_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x8u) +#define FXMAC_ERR_MAC_IS_PROCESSING FT_MAKE_ERRCODE(ErrModBsp, ErrBspEth, 0x9u) + +/** @name Configuration options + * + * Device configuration options. See the FXMAC_SetOptions(), + * FXMACClearOptions() and FXMAC_GetOptions() for information on how to + * use options. + * + * The default state of the options are noted and are what the device and + * driver will be set to after calling FXMAC_Reset() or + * FXMAC_Initialize(). + * + * @{ + */ + +#define FXMAC_PROMISC_OPTION 0x00000001U +/* Accept all incoming packets. + * This option defaults to disabled (cleared) */ + +#define FXMAC_FRAME1536_OPTION 0x00000002U +/* Frame larger than 1516 support for Tx & Rx.x + * This option defaults to disabled (cleared) */ + +#define FXMAC_VLAN_OPTION 0x00000004U +/* VLAN Rx & Tx frame support. + * This option defaults to disabled (cleared) */ + +#define FXMAC_FLOW_CONTROL_OPTION 0x00000010U +/* Enable recognition of flow control frames on Rx + * This option defaults to enabled (set) */ + +#define FXMAC_FCS_STRIP_OPTION 0x00000020U +/* Strip FCS and PAD from incoming frames. Note: PAD from VLAN frames is not + * stripped. + * This option defaults to enabled (set) */ + +#define FXMAC_FCS_INSERT_OPTION 0x00000040U +/* Generate FCS field and add PAD automatically for outgoing frames. + * This option defaults to disabled (cleared) */ + +#define FXMAC_LENTYPE_ERR_OPTION 0x00000080U +/* Enable Length/Type error checking for incoming frames. When this option is + * set, the MAC will filter frames that have a mismatched type/length field + * and if FXMAC_REPORT_RXERR_OPTION is set, the user is notified when these + * types of frames are encountered. When this option is cleared, the MAC will + * allow these types of frames to be received. + * + * This option defaults to disabled (cleared) */ + +#define FXMAC_TRANSMITTER_ENABLE_OPTION 0x00000100U +/* Enable the transmitter. + * This option defaults to enabled (set) */ + +#define FXMAC_RECEIVER_ENABLE_OPTION 0x00000200U +/* Enable the receiver + * This option defaults to enabled (set) */ + +#define FXMAC_BROADCAST_OPTION 0x00000400U +/* Allow reception of the broadcast address + * This option defaults to enabled (set) */ + +#define FXMAC_MULTICAST_OPTION 0x00000800U +/* Allows reception of multicast addresses programmed into hash + * This option defaults to disabled (clear) */ + +#define FXMAC_RX_CHKSUM_ENABLE_OPTION 0x00001000U +/* Enable the RX checksum offload + * This option defaults to enabled (set) */ + +#define FXMAC_TX_CHKSUM_ENABLE_OPTION 0x00002000U +/* Enable the TX checksum offload + * This option defaults to enabled (set) */ + +#define FXMAC_JUMBO_ENABLE_OPTION 0x00004000U +#define FXMAC_SGMII_ENABLE_OPTION 0x00008000U + +#define FXMAC_LOOPBACK_NO_MII_OPTION 0x00010000U +#define FXMAC_LOOPBACK_USXGMII_OPTION 0x00020000U + +#define FXMAC_GET_TXRING(instance) (instance.tx_bd_queue.bdring) +#define FXMAC_GET_RXRING(instance) (instance.rx_bd_queue.bdring) + +#define FXMAC_DEFAULT_OPTIONS \ + ((u32)FXMAC_FLOW_CONTROL_OPTION | \ + (u32)FXMAC_FCS_INSERT_OPTION | \ + (u32)FXMAC_FCS_STRIP_OPTION | \ + (u32)FXMAC_BROADCAST_OPTION | \ + (u32)FXMAC_LENTYPE_ERR_OPTION | \ + (u32)FXMAC_TRANSMITTER_ENABLE_OPTION | \ + (u32)FXMAC_RECEIVER_ENABLE_OPTION | \ + (u32)FXMAC_RX_CHKSUM_ENABLE_OPTION | \ + (u32)FXMAC_TX_CHKSUM_ENABLE_OPTION) + +typedef enum +{ + FXMAC_LINKDOWN = 0, + FXMAC_LINKUP = 1, + FXMAC_NEGOTIATING = 2 +} FXmacLinkStatus; + +/* The next few constants help upper layers determine the size of memory + * pools used for Ethernet buffers and descriptor lists. + */ +#define FXMAC_MAC_ADDR_SIZE 6U /* size of Ethernet header */ + +#define FXMAC_MTU 1500U /* max MTU size of Ethernet frame */ +#define FXMAC_MTU_JUMBO 10240U /* max MTU size of jumbo frame */ +#define FXMAC_HDR_SIZE 14U /* size of Ethernet header , DA + SA + TYPE*/ +#define FXMAC_HDR_VLAN_SIZE 18U /* size of Ethernet header with VLAN */ +#define FXMAC_TRL_SIZE 4U /* size of Ethernet trailer (FCS) */ +#define FXMAC_MAX_FRAME_SIZE (FXMAC_MTU + FXMAC_HDR_SIZE + \ + FXMAC_TRL_SIZE) +#define FXMAC_MAX_VLAN_FRAME_SIZE (FXMAC_MTU + FXMAC_HDR_SIZE + \ + FXMAC_HDR_VLAN_SIZE + FXMAC_TRL_SIZE) +#define FXMAC_MAX_VLAN_FRAME_SIZE_JUMBO (FXMAC_MTU_JUMBO + FXMAC_HDR_SIZE + \ + FXMAC_HDR_VLAN_SIZE + FXMAC_TRL_SIZE) + +#define FXMAC_MAX_FRAME_SIZE_JUMBO (FXMAC_MTU_JUMBO + FXMAC_HDR_SIZE + FXMAC_TRL_SIZE) + +/** @name Callback identifiers + * + * These constants are used as parameters to FXMAC_SetHandler() + * @{ + */ +#define FXMAC_HANDLER_DMASEND 1U /* 发送中断 */ +#define FXMAC_HANDLER_DMARECV 2U /* 接收中断 */ +#define FXMAC_HANDLER_ERROR 3U /* 异常中断 */ +#define FXMAC_HANDLER_LINKCHANGE 4U /* 连接状态 */ +#define FXMAC_HANDLER_RESTART 5U /* 发送描述符队列发生异常 */ +/*@}*/ + +#define FXMAC_DMA_SG_IS_STARTED 0 +#define FXMAC_DMA_SG_IS_STOPED 1 + +#define FXMAC_SPEED_10 10U +#define FXMAC_SPEED_100 100U +#define FXMAC_SPEED_1000 1000U +#define FXMAC_SPEED_2500 2500U +#define FXMAC_SPEED_5000 5000U +#define FXMAC_SPEED_10000 10000U +#define FXMAC_SPEED_25000 25000U + +/** @name Direction identifiers + * + * These are used by several functions and callbacks that need + * to specify whether an operation specifies a send or receive channel. + * @{ + */ +#define FXMAC_SEND 1U /* send direction */ +#define FXMAC_RECV 2U /* receive direction */ + +/****************************************************************************/ +/** + * + * This macro triggers trasmit circuit to send data currently in TX buffer(s). + * + * @param instance_p is a pointer to the FXmac instance to be worked on. + * + * @return + * + * @note + * + * Signature: void FXmacTransmit(FXmac *instance_p) + * + *****************************************************************************/ +#define FXmacTransmit(instance_p) \ + FXMAC_WRITEREG32((instance_p)->config.base_address, \ + FXMAC_NWCTRL_OFFSET, \ + (FXMAC_READREG32((instance_p)->config.base_address, \ + FXMAC_NWCTRL_OFFSET) | \ + FXMAC_NWCTRL_STARTTX_MASK)) + +typedef void (*FXmacIrqHandler)(void *args); +typedef void (*FXmacErrorIrqHandler)(void *args, u32 direction, u32 error_word); +/* Interface Mode definitions */ +typedef enum +{ + FXMAC_PHY_INTERFACE_MODE_SGMII, + FXMAC_PHY_INTERFACE_MODE_RMII, + FXMAC_PHY_INTERFACE_MODE_RGMII, + FXMAC_PHY_INTERFACE_MODE_XGMII, + FXMAC_PHY_INTERFACE_MODE_USXGMII, +} FXmacPhyInterface; + +typedef struct +{ + u32 instance_id; /* Id of device*/ + volatile uintptr_t base_address; + volatile uintptr_t extral_mode_base; + volatile uintptr_t extral_loopback_base; + FXmacPhyInterface interface; + u32 speed; /* FXMAC_SPEED_XXX */ + u32 duplex; /* 1 is full-duplex , 0 is half-duplex */ + u32 auto_neg; /* Enable auto-negotiation - when set active high, autonegotiation operation is enabled. */ + u32 pclk_hz; + u32 max_queue_num; /* Number of Xmac Controller Queues */ + u32 tx_queue_id; /* 0 ~ FT_XMAC_QUEUE_MAX_NUM ,Index queue number */ + u32 rx_queue_id; /* 0 ~ FT_XMAC_QUEUE_MAX_NUM ,Index queue number */ + u32 hotplug_irq_num; + u32 dma_brust_length; /* burst length */ + u32 network_default_config; + u32 queue_irq_num[FT_XMAC_QUEUE_MAX_NUM]; /* mac0 8个 ,其他的 4个 */ +} FXmacConfig; + +typedef struct +{ + u32 queue_id; + FXmacBdRing bdring; +} FXmacQueue; + +typedef struct +{ + FXmacConfig config; + u32 is_ready; /* Device is ininitialized and ready*/ + u32 is_started; + u32 link_status; /* indicates link status ,FXMAC_LINKUP is link up ,FXMAC_LINKDOWN is link down,FXMAC_NEGOTIATING is need to negotiating*/ + u32 options; + + FXmacQueue tx_bd_queue; /* Transmit Queue */ + FXmacQueue rx_bd_queue; /* Receive Queue */ + + FXmacIrqHandler send_irq_handler; + void *send_args; + + FXmacIrqHandler recv_irq_handler; + void *recv_args; + + FXmacErrorIrqHandler error_irq_handler; + void *error_args; + + FXmacIrqHandler link_change_handler; + void *link_change_args; + + FXmacIrqHandler restart_handler; + void *restart_args; + + u32 moudle_id; /* Module identification number */ + u32 max_mtu_size; + u32 max_frame_size; + + u32 phy_address; /* phy address */ + u32 rxbuf_mask; /* 1000,100,10 */ + +} FXmac; + +/* fxmac_sinit.c */ +const FXmacConfig *FXmacLookupConfig(u32 instance_id); + +/* fgmac.c */ +FError FXmacCfgInitialize(FXmac *instance_p, const FXmacConfig *config_p); + +void FXmacInitInterface(FXmac *instance_p); + +void FXmacGetMacAddress(FXmac *instance_p, u8 *address_ptr, u8 index); +FError FXmacSetMacAddress(FXmac *instance_p, u8 *address_ptr, u8 index); + +FError FXmacSetOptions(FXmac *instance_p, u32 options, u32 queue_num); +FError FXmacClearOptions(FXmac *instance_p, u32 options, u32 queue_num); + +void FXmacStart(FXmac *instance_p); +void FXmacStop(FXmac *instance_p); +void FXmacSetQueuePtr(FXmac *instance_p, uintptr QPtr, u8 QueueNum, + u32 direction); + +/* phy interface */ +FError FXmacPhyWrite(FXmac *instance_p, u32 phy_address, + u32 register_num, u16 phy_data); + +FError FXmacPhyRead(FXmac *instance_p, u32 phy_address, + u32 register_num, u16 *phydat_aptr); + +FError FXmacPhyInit(FXmac *instance_p, u32 speed, u32 duplex_mode, u32 autonegotiation_en); + +void FXmacSelectClk(FXmac *instance_p); + +FError FXmacSetHandler(FXmac *instance_p, u32 handler_type, void *func_pointer, void *call_back_ref); +/* interrupt */ +void FXmacIntrHandler(s32 vector, void *args); + +void FXmacClearHash(FXmac *instance_p); + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bd.h b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bd.h new file mode 100644 index 0000000000..bbe982340d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bd.h @@ -0,0 +1,272 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_bd.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_ETH_F_XMAC_BD_H +#define DRIVERS_ETH_F_XMAC_BD_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "string.h" + + +/** + * @name: FXMAC_BD_READ + * @msg: Read the given Buffer Descriptor word. + * @param bd_ptr is the base address of the BD to read + * @param offset is the word offset to be read + * @return The 32-bit value of the field + */ +#define FXMAC_BD_READ(bd_ptr, offset) \ + (*(u32 *)((uintptr)((void *)(bd_ptr)) + (u32)(offset))) + + +/** + * @name: FXMAC_BD_WRITE + * @msg: Write the given Buffer Descriptor word. + * @param bd_ptr is the base address of the BD to write + * @param Offset is the word offset to be written + * @param data is the 32-bit value to write to the field + * @return {*} + */ +#define FXMAC_BD_WRITE(bd_ptr, Offset, data) \ + (*(u32 *)((uintptr)(void *)(bd_ptr) + (u32)(Offset)) = (u32)(data)) + + +/** + * @name: FXMAC_BD_SET_STATUS + * @msg: Set the BD's Status field (word 1). + * @param bd_ptr is the BD pointer to operate on + * @param data is the value to write to BD's status field. + */ +#define FXMAC_BD_SET_STATUS(bd_ptr, data) \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_STAT_OFFSET, \ + FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) | (data)) + + +/** + * @name: FXMAC_BD_IS_RX_NEW + * @msg: Determine the new bit of the receive BD. + * @param bd_ptr is the BD pointer to operate on + */ +#define FXMAC_BD_IS_RX_NEW(bd_ptr) \ + ((FXMAC_BD_READ((bd_ptr), FXMAC_BD_ADDR_OFFSET) & \ + FXMAC_RXBUF_NEW_MASK) != 0U \ + ? TRUE \ + : FALSE) + + +/** + * @name: FXMAC_BD_IS_TX_WRAP + * @msg: Determine the wrap bit of the transmit BD which indicates end of the + * BD list. + * @param bd_ptr is the BD pointer to operate on + */ +#define FXMAC_BD_IS_TX_WRAP(bd_ptr) \ + ((FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) & \ + FXMAC_TXBUF_WRAP_MASK) != 0U \ + ? TRUE \ + : FALSE) + + +/** + * @name: FXMAC_BD_IS_RX_WRAP + * @msg: Determine the wrap bit of the receive BD which indicates end of the + * BD list. + * @param: bd_ptr is the BD pointer to operate on + */ +#define FXMAC_BD_IS_RX_WRAP(bd_ptr) \ + ((FXMAC_BD_READ((bd_ptr), FXMAC_BD_ADDR_OFFSET) & \ + FXMAC_RXBUF_WRAP_MASK) != 0U \ + ? TRUE \ + : FALSE) + + + +/** + * @name: FXMAC_BD_SET_ADDRESS_TX + * @msg: Set the BD's address field (word 0). + * @param: bd_ptr is the BD pointer to operate on + * @param: addr is the value to write to BD's status field. + */ +#if defined(__aarch64__) || defined(__arch64__) +#define FXMAC_BD_SET_ADDRESS_TX(bd_ptr, addr) \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_ADDR_OFFSET, \ + (u32)((addr)&ULONG64_LO_MASK)); \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_ADDR_HI_OFFSET, \ + (u32)(((addr)&ULONG64_HI_MASK) >> 32U)); +#else +#define FXMAC_BD_SET_ADDRESS_TX(bd_ptr, addr) \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_ADDR_OFFSET, (u32)(addr)) +#endif + + +/** + * @name: FXMAC_BD_SET_ADDRESS_RX + * @msg: Set the BD's address field (word 0). + * @param: bd_ptr is the BD pointer to operate on + * @param: addr is the value to write to BD's status field. + * @return {*} + */ +#ifdef __aarch64__ +#define FXMAC_BD_SET_ADDRESS_RX(bd_ptr, addr) \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_ADDR_OFFSET, \ + ((FXMAC_BD_READ((bd_ptr), FXMAC_BD_ADDR_OFFSET) & \ + ~FXMAC_RXBUF_ADD_MASK) | \ + ((u32)((addr)&ULONG64_LO_MASK)))); \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_ADDR_HI_OFFSET, \ + (u32)(((addr)&ULONG64_HI_MASK) >> 32U)); +#else +#define FXMAC_BD_SET_ADDRESS_RX(bd_ptr, addr) \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_ADDR_OFFSET, \ + ((FXMAC_BD_READ((bd_ptr), FXMAC_BD_ADDR_OFFSET) & \ + ~FXMAC_RXBUF_ADD_MASK) | \ + (u32)(addr))) +#endif + + +/** + * @name: FXMAC_BD_SET_LENGTH + * @msg: Set transfer length in bytes for the given BD. The length must be set each + * time a BD is submitted to hardware. + * @param: bd_ptr is the BD pointer to operate on + * @param: len_bytes is the number of bytes to transfer. + * @return {*} + */ +#define FXMAC_BD_SET_LENGTH(bd_ptr, len_bytes) \ + FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_STAT_OFFSET, \ + ((FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) & \ + ~FXMAC_TXBUF_LEN_MASK) | \ + (len_bytes))) + + +/** + * @name: FXMAC_BD_GET_LENGTH + * @msg: For Tx channels, the returned value is the same as that written with + * FXMAC_BD_SET_LENGTH(). For Rx channels, the returned value is the size of the received packet. + * @param: bd_ptr is the BD pointer to operate on + * @return {*} + */ +#define FXMAC_BD_GET_LENGTH(bd_ptr) \ + (FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) & \ + FXMAC_RXBUF_LEN_MASK) + + +/** + * @name: FXMAC_GET_RX_FRAME_SIZE + * @msg: The returned value is the size of the received packet. + * This API supports jumbo frame sizes if enabled. + * @param instance_p is the pointer to xmac instance + * @param bd_ptr is the BD pointer to operate on + * + * @return Length field processed by hardware or set by + * FXMAC_BD_SET_LENGTH(). + */ + +#define FXMAC_BD_JUMBO_LENGTH_MASK + +#define FXMAC_GET_RX_FRAME_SIZE(instance_p, bd_ptr) \ + (FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) & \ + 0x00003FFFU) + + + +/** + * @name: FXMAC_BD_CLEAR_TX_USED + * @msg: Software clears this bit to enable the buffer to be read by the hardware. + * Hardware sets this bit for the first buffer of a frame once it has been + * successfully transmitted. This macro clears this bit of transmit BD. + * @param: bd_ptr is the BD pointer to operate on + * @return {*} + */ +#define FXMAC_BD_CLEAR_TX_USED(bd_ptr) \ + (FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_STAT_OFFSET, \ + FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) & \ + (~FXMAC_TXBUF_USED_MASK))) + +#define FXMAC_BD_SET_CRC(bd_ptr) \ + (FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_STAT_OFFSET, \ + FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) & \ + (~FXMAC_TXBUF_NOCRC_MASK))) + + +/** + * @name: FXMAC_BD_SET_LAST + * @msg: Tell the DMA engine that the given transmit BD marks the end of the current + * packet to be processed. + * @param bd_ptr is the BD pointer to operate on + * @return {*} + */ +#define FXMAC_BD_SET_LAST(bd_ptr) \ + (FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_STAT_OFFSET, \ + FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) | \ + FXMAC_TXBUF_LAST_MASK)) + + +/** + * @name: FXMAC_BD_CLEAR_LAST + * @msg: Tell the DMA engine that the current packet does not end with the given + * BD. + * @param bd_ptr is the BD pointer to operate on + * @return {*} + */ +#define FXMAC_BD_CLEAR_LAST(bd_ptr) \ + (FXMAC_BD_WRITE((bd_ptr), FXMAC_BD_STAT_OFFSET, \ + FXMAC_BD_READ((bd_ptr), FXMAC_BD_STAT_OFFSET) & \ + ~FXMAC_TXBUF_LAST_MASK)) + +/** + * @name: FXMAC_BD_CLEAR + * @msg: Zero out BD fields + * @param bd_ptr is the BD pointer to operate on + * @return {*} + */ +#define FXMAC_BD_CLEAR(bd_ptr) \ + memset((bd_ptr), 0, sizeof(FXmacBd)) + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ +#ifdef __aarch64__ +/* Minimum BD alignment */ +#define FXMAC_DMABD_MINIMUM_ALIGNMENT 64U +#define FXMAC_BD_NUM_WORDS 4U +#else +/* Minimum BD alignment */ +#define FXMAC_DMABD_MINIMUM_ALIGNMENT 4U +#define FXMAC_BD_NUM_WORDS 2U +#endif + +/** + * The FXMAC_Bd is the type for buffer descriptors (BDs). + */ +typedef u32 FXmacBd[FXMAC_BD_NUM_WORDS]; + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bdring.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bdring.c new file mode 100644 index 0000000000..5459203c18 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bdring.c @@ -0,0 +1,964 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_bdring.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fxmac_hw.h" +#include "fxmac.h" +#include "fxmac_bdring.h" +#include "fxmac_bd.h" +#include "ftypes.h" +#include "fxmac.h" +#include "string.h" +#include "fprintk.h" +#include "fdebug.h" + +static void FXmacBdSetRxWrap(uintptr bdptr); +static void FXmacBdSetTxWrap(uintptr bdptr); + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/** + * @name: FXMAC_RING_SEEKAHEAD + * @msg: Move the bdptr argument ahead an arbitrary number of BDs wrapping around + * to the beginning of the ring if needed. + * @param ring_ptr is the ring bdptr appears in + * @param bdptr on input is the starting BD position and on output is the final BD position + * @param num_bd is the number of BD spaces to increment + */ +#define FXMAC_RING_SEEKAHEAD(ring_ptr, bdptr, num_bd) \ + { \ + uintptr addr = (uintptr)(void *)(bdptr); \ + \ + addr += ((ring_ptr)->separation * (num_bd)); \ + if ((addr > (ring_ptr)->high_bd_addr) || ((uintptr)(void *)(bdptr) > addr)) \ + { \ + addr -= (ring_ptr)->length; \ + } \ + \ + (bdptr) = (FXmacBd *)(void *)addr; \ + } + +/** + * @name: FXMAC_RING_SEEKBACK + * @msg: Move the bdptr argument backwards an arbitrary number of BDs wrapping + * around to the end of the ring if needed. + * @param ring_ptr is the ring bdptr appears in + * @param bdptr on input is the starting BD position and on output is the + * final BD position + * @param num_bd is the number of BD spaces to increment + * @return {*} + */ +#define FXMAC_RING_SEEKBACK(ring_ptr, bdptr, num_bd) \ + { \ + uintptr addr = (uintptr)(void *)(bdptr); \ + \ + addr -= ((ring_ptr)->separation * (num_bd)); \ + if ((addr < (ring_ptr)->base_bd_addr) || ((uintptr)(void *)(bdptr) < addr)) \ + { \ + addr += (ring_ptr)->length; \ + } \ + \ + (bdptr) = (FXmacBd *)(void *)addr; \ + } + + + +/** + * @name: FXmacBdRingCreate + * @msg: Using a memory segment allocated by the caller, create and setup the BD list + * for the given DMA channel. + * @param ring_ptr is the instance to be worked on. + * @param Physaddr is the physical base address of user memory region. + * @param Virtaddr is the virtual base address of the user memory region. If + * address translation is not being utilized, then Virtaddr should be + * equivalent to Physaddr. + * @param Alignment governs the byte alignment of individual BDs. This function + * will enforce a minimum alignment of 4 bytes with no maximum as long + * as it is specified as a power of 2. + * @param bd_count is the number of BDs to setup in the user memory region. It + * is assumed the region is large enough to contain the BDs. + * @return + * FT_SUCCESS if initialization was successful + * FXMAC_ERR_INVALID_PARAM under any of the following conditions: + * 1) Physaddr and/or Virtaddr are not aligned to the given Alignment + * parameter. + * 2) Alignment parameter does not meet minimum requirements or is not a + * power of 2 value. + * 3) bd_count is 0. + */ +FError FXmacBdRingCreate(FXmacBdRing *ring_ptr, uintptr phys_addr, + uintptr virt_addr, u32 alignment, u32 bd_count) +{ + u32 i; + uintptr bd_virt_addr; + uintptr bd_phy_addr; + uintptr virt_addr_loc = virt_addr; + + /* In case there is a failure prior to creating list, make sure the + * following attributes are 0 to prevent calls to other functions + * from doing anything. + */ + ring_ptr->all_cnt = 0U; + ring_ptr->free_cnt = 0U; + ring_ptr->hw_cnt = 0U; + ring_ptr->pre_cnt = 0U; + ring_ptr->post_cnt = 0U; + + /* Make sure alignment parameter meets minimum requirements */ + if (alignment < (u32)FXMAC_DMABD_MINIMUM_ALIGNMENT) + { + return (FError)(FXMAC_ERR_INVALID_PARAM); + } + + /* Make sure alignment is a power of 2 */ + if (((alignment - 0x00000001U) & alignment) != 0x00000000U) + { + return (FError)(FXMAC_ERR_INVALID_PARAM); + } + + /* Make sure phys_addr and virt_addr are on same alignment */ + if (((phys_addr % alignment) != (u32)0) || ((virt_addr_loc % alignment) != (u32)0)) + { + return (FError)(FXMAC_ERR_INVALID_PARAM); + } + + /* Is bd_count reasonable? */ + if (bd_count == 0x00000000U) + { + return (FError)(FXMAC_ERR_INVALID_PARAM); + } + + /* Figure out how many bytes will be between the start of adjacent BDs */ + ring_ptr->separation = ((u32)sizeof(FXmacBd)); + + /* Must make sure the ring doesn't span address 0x00000000. If it does, + * then the next/prev BD traversal macros will fail. + */ + if (virt_addr_loc > ((virt_addr_loc + (ring_ptr->separation * bd_count)) - (u32)1)) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + /* Initial ring setup: + * - Clear the entire space + * - Setup each BD's BDA field with the physical address of the next BD + */ + (void)memset((void *)virt_addr_loc, 0, (ring_ptr->separation * bd_count)); + + bd_virt_addr = virt_addr_loc; + bd_phy_addr = phys_addr + ring_ptr->separation; + for (i = 1U; i < bd_count; i++) + { + bd_virt_addr += ring_ptr->separation; + bd_phy_addr += ring_ptr->separation; + } + + /* Setup and initialize pointers and counters */ + ring_ptr->run_state = (u32)(FXMAC_DMA_SG_IS_STOPED); + ring_ptr->base_bd_addr = virt_addr_loc; + ring_ptr->phys_base_addr = phys_addr; + ring_ptr->high_bd_addr = bd_virt_addr; + ring_ptr->length = + ((ring_ptr->high_bd_addr - ring_ptr->base_bd_addr) + ring_ptr->separation); + ring_ptr->all_cnt = (u32)bd_count; + ring_ptr->free_cnt = (u32)bd_count; + ring_ptr->free_head = (FXmacBd *)(void *)virt_addr_loc; + ring_ptr->pre_head = (FXmacBd *)virt_addr_loc; + ring_ptr->hw_head = (FXmacBd *)virt_addr_loc; + ring_ptr->hw_tail = (FXmacBd *)virt_addr_loc; + ring_ptr->post_head = (FXmacBd *)virt_addr_loc; + ring_ptr->bda_restart = (FXmacBd *)(void *)phys_addr; + + return (FError)(FT_SUCCESS); +} + +/** + * @name: FXmacBdRingClone + * @msg: Clone the given BD into every BD in the list. + * every field of the source BD is replicated in every BD of the list. + * @param ring_ptr is the instance to be worked on. + * @param src_bd_ptr is the source BD template to be cloned into the list. This + * BD will be modified. + * @param direction is either FXMAC_SEND or FXMAC_RECV that indicates + * which direction. + * @return {*} + */ +FError FXmacBdRingClone(FXmacBdRing *ring_ptr, FXmacBd *src_bd_ptr, + u8 direction) +{ + u32 i; + uintptr cur_bd; + + /* Can't do this function if there isn't a ring */ + if (ring_ptr->all_cnt == 0x00000000U) + { + return (FError)(FXMAC_ERR_SG_NO_LIST); + } + + /* Can't do this function with the channel running */ + if (ring_ptr->run_state == (u32)FXMAC_DMA_SG_IS_STARTED) + { + return (FError)(FT_COMPONENT_IS_STARTED); + } + + /* Can't do this function with some of the BDs in use */ + if (ring_ptr->free_cnt != ring_ptr->all_cnt) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + if ((direction != (u8)FXMAC_SEND) && (direction != (u8)FXMAC_RECV)) + { + return (FError)(FXMAC_ERR_INVALID_PARAM); + } + + /* Starting from the top of the ring, save bd.next, overwrite the entire + * BD with the template, then restore bd.next + */ + cur_bd = ring_ptr->base_bd_addr; + for (i = 0U; i < ring_ptr->all_cnt; i++) + { + memcpy((void *)cur_bd, src_bd_ptr, sizeof(FXmacBd)); + cur_bd += ring_ptr->separation; + } + + cur_bd -= ring_ptr->separation; + + if (direction == FXMAC_RECV) + { + FXmacBdSetRxWrap(cur_bd); + } + else + { + FXmacBdSetTxWrap(cur_bd); + } + + return (FError)(FT_SUCCESS); +} + + +/** + * @name: FXmacBdRingAlloc + * @msg: Reserve locations in the BD list. The set of returned BDs may be modified + * in preparation for future DMA transaction(s). Once the BDs are ready to be + * submitted to hardware, the user must call FXmacBdRingToHw() in the same + * order which they were allocated here. + * @param ring_ptr is a pointer to the BD ring instance to be worked on. + * @param num_bd is the number of BDs to allocate + * @param bd_set_ptr is an output parameter, it points to the first BD available + * for modification. + * @return FT_SUCCESS if the requested number of BDs was returned in the bd_set_ptr + * parameter. + * - FXMAC_ERR_GENERAL if there were not enough free BDs to satisfy the request. + */ +FError FXmacBdRingAlloc(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd **bd_set_ptr) +{ + FError status; + /* Enough free BDs available for the request? */ + if (ring_ptr->free_cnt < num_bd) + { + status = (FError)(FXMAC_ERR_GENERAL); + } + else + { + /* Set the return argument and move free_head forward */ + *bd_set_ptr = ring_ptr->free_head; + FXMAC_RING_SEEKAHEAD(ring_ptr, ring_ptr->free_head, num_bd); + ring_ptr->free_cnt -= num_bd; + ring_ptr->pre_cnt += num_bd; + status = (FError)(FT_SUCCESS); + } + return status; +} + + +/** + * @name: FXmacBdRingUnAlloc + * @msg: * Fully or partially undo an FXmacBdRingAlloc() operation. Use this + * function if all the BDs allocated by FXmacBdRingAlloc() could not be + * transferred to hardware with FXmacBdRingToHw(). + * + * This function helps out in situations when an unrelated error occurs after + * BDs have been allocated but before they have been given to hardware. + * An example of this type of error would be an OS running out of resources. + * + * This function is not the same as FXmacBdRingFree(). The Free function + * returns BDs to the free list after they have been processed by hardware, + * while UnAlloc returns them before being processed by hardware. + * + * There are two scenarios where this function can be used. Full UnAlloc or + * Partial UnAlloc. A Full UnAlloc means all the BDs Alloc'd will be returned: + * + *
+ *    status = FXmacBdRingAlloc(Myring_ptr, 10, &bdptr),
+ *        ...
+ *    if (Error)
+ *    {
+ *        status = FXmacBdRingUnAlloc(Myring_ptr, 10, &bdptr),
+ *    }
+ * 
+ * + * A partial UnAlloc means some of the BDs Alloc'd will be returned: + * + *
+ *    status = FXmacBdRingAlloc(Myring_ptr, 10, &bdptr),
+ *    BdsLeft = 10,
+ *    cur_bd_ptr = bdptr,
+ *
+ *    while (BdsLeft)
+ *    {
+ *       if (Error)
+ *       {
+ *          status = FXmacBdRingUnAlloc(Myring_ptr, BdsLeft, cur_bd_ptr),
+ *       }
+ *
+ *       cur_bd_ptr = FXMAC_BD_RING_NEXT(Myring_ptr, cur_bd_ptr),
+ *       BdsLeft--,
+ *    }
+ * 
+ * + * A partial UnAlloc must include the last BD in the list that was Alloc'd. + * + * @param ring_ptr is a pointer to the instance to be worked on. + * @param num_bd is the number of BDs to allocate + * @param bd_set_ptr is an output parameter, it points to the first BD available + * for modification. + * + * @return + * - FT_SUCCESS if the BDs were unallocated. + * - FXMAC_ERR_GENERAL if num_bd parameter was greater that the number of BDs in + * the preprocessing state. + * + * @return {*} + */ +FError FXmacBdRingUnAlloc(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd *bd_set_ptr) +{ + FError status; + (void)bd_set_ptr; + FASSERT(ring_ptr != NULL); + FASSERT(bd_set_ptr != NULL); + + /* Enough BDs in the free state for the request? */ + if (ring_ptr->pre_cnt < num_bd) + { + status = (FError)(FXMAC_ERR_GENERAL); + } + else + { + /* Set the return argument and move free_head backward */ + FXMAC_RING_SEEKBACK(ring_ptr, (ring_ptr->free_head), num_bd); + ring_ptr->free_cnt += num_bd; + ring_ptr->pre_cnt -= num_bd; + status = (FError)(FT_SUCCESS); + } + return status; +} + + +/** + * @name: FXmacBdRingToHw + * @msg: Enqueue a set of BDs to hardware that were previously allocated by + * FXmacBdRingAlloc(). Once this function returns, the argument BD set goes + * under hardware control. Any changes made to these BDs after this point will + * corrupt the BD list leading to data corruption and system instability. + * + * @param ring_ptr is a pointer to the instance to be worked on. + * @param num_bd is the number of BDs in the set. + * @param bd_set_ptr is the first BD of the set to commit to hardware. + * @return FT_SUCCESS if the set of BDs was accepted and enqueued to hardware. + * XST_FAILURE if the set of BDs was rejected because the last BD of the set + * did not have its "last" bit set. + * FXMAC_ERR_SG_LIST if this function was called out of sequence with + * FXmacBdRingAlloc(). + */ +FError FXmacBdRingToHw(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd *bd_set_ptr) +{ + FXmacBd *cur_bd_ptr; + u32 i; + FError status; + /* if no bds to process, simply return. */ + if (0U == num_bd) + { + status = (FError)(FT_SUCCESS); + } + else + { + /* Make sure we are in sync with FXmacBdRingAlloc() */ + if ((ring_ptr->pre_cnt < num_bd) || (ring_ptr->pre_head != bd_set_ptr)) + { + status = (FError)(FXMAC_ERR_SG_LIST); + } + else + { + cur_bd_ptr = bd_set_ptr; + for (i = 0U; i < num_bd; i++) + { + cur_bd_ptr = (FXmacBd *)((void *)FXMAC_BD_RING_NEXT(ring_ptr, cur_bd_ptr)); + } + /* Adjust ring pointers & counters */ + FXMAC_RING_SEEKAHEAD(ring_ptr, ring_ptr->pre_head, num_bd); + ring_ptr->pre_cnt -= num_bd; + ring_ptr->hw_tail = cur_bd_ptr; + ring_ptr->hw_cnt += num_bd; + + status = (FError)(FT_SUCCESS); + } + } + return status; +} + + +/** + * @name: FXmacBdRingFromHwTx + * @msg: Returns a set of BD(s) that have been processed by hardware. The returned + * BDs may be examined to determine the outcome of the DMA transaction(s). + * Once the BDs have been examined, the user must call FXmacBdRingFree() + * in the same order which they were retrieved here. Example: + * + *
+ *        num_bd = FXmacBdRingFromHwTx(Myring_ptr, MaxBd, &MyBdSet),
+ *        if (num_bd == 0)
+ *        {
+ *           * hardware has nothing ready for us yet*
+ *        }
+ *
+ *        cur_bd = MyBdSet,
+ *        for (i=0; i
+ *
+ * A more advanced use of this function may allocate multiple sets of BDs.
+ * They must be retrieved from hardware and freed in the correct sequence:
+ * 
+ *        * Legal *
+ *        FXmacBdRingFromHwTx(Myring_ptr, num_bd1, &MySet1),
+ *        FXmacBdRingFree(Myring_ptr, num_bd1, MySet1),
+ *
+ *        * Legal *
+ *        FXmacBdRingFromHwTx(Myring_ptr, num_bd1, &MySet1),
+ *        FXmacBdRingFromHwTx(Myring_ptr, num_bd2, &MySet2),
+ *        FXmacBdRingFree(Myring_ptr, num_bd1, MySet1),
+ *        FXmacBdRingFree(Myring_ptr, num_bd2, MySet2),
+ *
+ *        * Not legal *
+ *        FXmacBdRingFromHwTx(Myring_ptr, num_bd1, &MySet1),
+ *        FXmacBdRingFromHwTx(Myring_ptr, num_bd2, &MySet2),
+ *        FXmacBdRingFree(Myring_ptr, num_bd2, MySet2),
+ *        FXmacBdRingFree(Myring_ptr, num_bd1, MySet1),
+ * 
+ * + * If hardware has only partially completed a packet spanning multiple BDs, + * then none of the BDs for that packet will be included in the results. + * + * @param ring_ptr is a pointer to the instance to be worked on. + * @param bd_limit is the maximum number of BDs to return in the set. + * @param bd_set_ptr is an output parameter, it points to the first BD available + * for examination. + * +* @return + * The number of BDs processed by hardware. A value of 0 indicates that no + * data is available. No more than bd_limit BDs will be returned. + * + * @return + * The number of BDs processed by hardware. A value of 0 indicates that no + * data is available. No more than bd_limit BDs will be returned. + */ +u32 FXmacBdRingFromHwTx(FXmacBdRing *ring_ptr, u32 bd_limit, + FXmacBd **bd_set_ptr) +{ + FXmacBd *cur_bd_ptr; + u32 bd_str = 0U; + u32 bd_count; + u32 bd_partial_count; + u32 Sop = 0U; + u32 status; + u32 bd_limitLoc = bd_limit; + cur_bd_ptr = ring_ptr->hw_head; + bd_count = 0U; + bd_partial_count = 0U; + + /* If no BDs in work group, then there's nothing to search */ + if (ring_ptr->hw_cnt == 0x00000000U) + { + *bd_set_ptr = NULL; + status = 0U; + } + else + { + + if (bd_limitLoc > ring_ptr->hw_cnt) + { + bd_limitLoc = ring_ptr->hw_cnt; + } + /* Starting at hw_head, keep moving forward in the list until: + * - A BD is encountered with its new/used bit set which means + * hardware has not completed processing of that BD. + * - ring_ptr->hw_tail is reached and ring_ptr->hw_cnt is reached. + * - The number of requested BDs has been processed + */ + while (bd_count < bd_limitLoc) + { + /* Read the status */ + if (cur_bd_ptr != NULL) + { + bd_str = FXMAC_BD_READ(cur_bd_ptr, FXMAC_BD_STAT_OFFSET); + } + + if ((Sop == 0x00000000U) && ((bd_str & FXMAC_TXBUF_USED_MASK) != 0x00000000U)) + { + Sop = 1U; + } + if (Sop == 0x00000001U) + { + bd_count++; + bd_partial_count++; + } + + /* hardware has processed this BD so check the "last" bit. + * If it is clear, then there are more BDs for the current + * packet. Keep a count of these partial packet BDs. + */ + if ((Sop == 0x00000001U) && ((bd_str & FXMAC_TXBUF_LAST_MASK) != 0x00000000U)) + { + Sop = 0U; + bd_partial_count = 0U; + } + + /* Move on to next BD in work group */ + cur_bd_ptr = FXMAC_BD_RING_NEXT(ring_ptr, cur_bd_ptr); + } + + /* Subtract off any partial packet BDs found */ + bd_count -= bd_partial_count; + + /* If bd_count is non-zero then BDs were found to return. Set return + * parameters, update pointers and counters, return success + */ + if (bd_count > 0x00000000U) + { + *bd_set_ptr = ring_ptr->hw_head; + ring_ptr->hw_cnt -= bd_count; + ring_ptr->post_cnt += bd_count; + FXMAC_RING_SEEKAHEAD(ring_ptr, ring_ptr->hw_head, bd_count); + status = (bd_count); + } + else + { + *bd_set_ptr = NULL; + status = 0U; + } + } + return status; +} + +/** + * @name: FXmacBdRingFromHwRx + * @msg: Returns a set of BD(s) that have been processed by hardware. The returned + * BDs may be examined to determine the outcome of the DMA transaction(s). + * Once the BDs have been examined, the user must call FXmacBdRingFree() + * in the same order which they were retrieved here. Example: + * + *
+ *        num_bd = FXmacBdRingFromHwRx(Myring_ptr, MaxBd, &MyBdSet),
+ *
+ *        if (num_bd == 0)
+ *        {
+ *           *hardware has nothing ready for us yet*
+ *        }
+ *
+ *        cur_bd = MyBdSet,
+ *        for (i=0; i
+ *
+ * A more advanced use of this function may allocate multiple sets of BDs.
+ * They must be retrieved from hardware and freed in the correct sequence:
+ * 
+ *        * Legal *
+ *        FXmacBdRingFromHwRx(Myring_ptr, num_bd1, &MySet1),
+ *        FXmacBdRingFree(Myring_ptr, num_bd1, MySet1),
+ *
+ *        * Legal *
+ *        FXmacBdRingFromHwRx(Myring_ptr, num_bd1, &MySet1),
+ *        FXmacBdRingFromHwRx(Myring_ptr, num_bd2, &MySet2),
+ *        FXmacBdRingFree(Myring_ptr, num_bd1, MySet1),
+ *        FXmacBdRingFree(Myring_ptr, num_bd2, MySet2),
+ *
+ *        * Not legal *
+ *        FXmacBdRingFromHwRx(Myring_ptr, num_bd1, &MySet1),
+ *        FXmacBdRingFromHwRx(Myring_ptr, num_bd2, &MySet2),
+ *        FXmacBdRingFree(Myring_ptr, num_bd2, MySet2),
+ *        FXmacBdRingFree(Myring_ptr, num_bd1, MySet1),
+ * 
+ * + * If hardware has only partially completed a packet spanning multiple BDs, + * then none of the BDs for that packet will be included in the results. + * + * @param ring_ptr is a pointer to the instance to be worked on. + * @param bd_limit is the maximum number of BDs to return in the set. + * @param bd_set_ptr is an output parameter, it points to the first BD available + * for examination. + * + * @return + * The number of BDs processed by hardware. A value of 0 indicates that no + * data is available. No more than bd_limit BDs will be returned. + */ +u32 FXmacBdRingFromHwRx(FXmacBdRing *ring_ptr, u32 bd_limit, + FXmacBd **bd_set_ptr) +{ + FXmacBd *cur_bd_ptr; + u32 bd_str = 0U; + u32 bd_count; + u32 bd_partial_count; + u32 status; + + cur_bd_ptr = ring_ptr->hw_head; + bd_count = 0U; + bd_partial_count = 0U; + + /* If no BDs in work group, then there's nothing to search */ + if (ring_ptr->hw_cnt == 0x00000000U) + { + *bd_set_ptr = NULL; + status = 0U; + } + else + { + /* Starting at hw_head, keep moving forward in the list until: + * - A BD is encountered with its new/used bit set which means + * hardware has completed processing of that BD. + * - ring_ptr->hw_tail is reached and ring_ptr->hw_cnt is reached. + * - The number of requested BDs has been processed + */ + while (bd_count < bd_limit) + { + + /* Read the status */ + if (cur_bd_ptr != NULL) + { + bd_str = FXMAC_BD_READ(cur_bd_ptr, FXMAC_BD_STAT_OFFSET); + } + if ((!(FXMAC_BD_IS_RX_NEW(cur_bd_ptr))) == TRUE) + { + break; + } + + bd_count++; + + /* hardware has processed this BD so check the "last" bit. If + * it is clear, then there are more BDs for the current packet. + * Keep a count of these partial packet BDs. + */ + if ((bd_str & FXMAC_RXBUF_EOF_MASK) != 0x00000000U) + { + bd_partial_count = 0U; + } + else + { + bd_partial_count++; + } + + /* Move on to next BD in work group */ + cur_bd_ptr = FXMAC_BD_RING_NEXT(ring_ptr, cur_bd_ptr); + // if((bd_str & FXMAC_RXBUF_EOF_MASK) != 0x00000000U) + // { + // if(bd_str &FXMAC_RXBUF_FCS_STATUS_MASK) + // { + // f_printk("********** error fcs data is appear ************* \r\n"); + // FtDumpHexWord(FXMAC_BD_READ(cur_bd_ptr,0) &(0xfffffff8),bd_str&FXMAC_RXBUF_LEN_MASK); + // f_printk("********** end ************* \r\n"); + // } + // } + } + + /* Subtract off any partial packet BDs found */ + bd_count -= bd_partial_count; + + /* If bd_count is non-zero then BDs were found to return. Set return + * parameters, update pointers and counters, return success + */ + if (bd_count > 0x00000000U) + { + *bd_set_ptr = ring_ptr->hw_head; + ring_ptr->hw_cnt -= bd_count; + ring_ptr->post_cnt += bd_count; + FXMAC_RING_SEEKAHEAD(ring_ptr, ring_ptr->hw_head, bd_count); + status = (bd_count); + } + else + { + *bd_set_ptr = NULL; + status = 0U; + } + } + return status; +} + +/** + * @name: FXmacBdRingFree + * @msg: Frees a set of BDs that had been previously retrieved with + * FXmacBdRingFromHw(). + * + * @param ring_ptr is a pointer to the instance to be worked on. + * @param num_bd is the number of BDs to free. + * @param bd_set_ptr is the head of a list of BDs returned by + * FXmacBdRingFromHw(). + * + * @return + * FT_SUCCESS if the set of BDs was freed. + * FXMAC_ERR_SG_LIST if this function was called out of sequence with + * FXmacBdRingFromHw(). + */ +FError FXmacBdRingFree(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd *bd_set_ptr) +{ + FError status; + /* if no bds to process, simply return. */ + if (0x00000000U == num_bd) + { + status = (FError)(FT_SUCCESS); + } + else + { + /* Make sure we are in sync with FXmacBdRingFromHw() */ + if ((ring_ptr->post_cnt < num_bd) || (ring_ptr->post_head != bd_set_ptr)) + { + status = (FError)(FXMAC_ERR_SG_LIST); + } + else + { + /* Update pointers and counters */ + ring_ptr->free_cnt += num_bd; + ring_ptr->post_cnt -= num_bd; + FXMAC_RING_SEEKAHEAD(ring_ptr, ring_ptr->post_head, num_bd); + status = (FError)(FT_SUCCESS); + } + } + return status; +} + +/** + * @name: FXmacBdRingCheck + * @msg: Check the internal data structures of the BD ring for the provided channel. + * The following checks are made: + * + * - Is the BD ring linked correctly in physical address space. + * - Do the internal pointers point to BDs in the ring. + * - Do the internal counters add up. + * + * The channel should be stopped prior to calling this function. + * + * @param {FXmacBdRing} ring_ptr is a pointer to the instance to be worked on. + * @param {u8} direction is either FXMAC_SEND or FXMAC_RECV that indicates + * which direction. + * @return {*} + * FT_SUCCESS if the set of BDs was freed. + * XST_DMA_SG_NO_LIST if the list has not been created. + * FT_COMPONENT_IS_STARTED if the channel is not stopped. + * FXMAC_ERR_SG_LIST if a problem is found with the internal data + * structures. If this value is returned, the channel should be reset to + * avoid data corruption or system instability. + */ +FError FXmacBdRingCheck(FXmacBdRing *ring_ptr, u8 direction) +{ + uintptr addr_v, addr_p; + u32 i; + + if ((direction != (u8)FXMAC_SEND) && (direction != (u8)FXMAC_RECV)) + { + return (FError)(FXMAC_ERR_INVALID_PARAM); + } + + /* Is the list created */ + if (ring_ptr->all_cnt == 0x00000000U) + { + return (FError)(FXMAC_ERR_SG_NO_LIST); + } + + /* Can't check if channel is running */ + if (ring_ptr->run_state == (u32)FXMAC_DMA_SG_IS_STARTED) + { + return (FError)(FT_COMPONENT_IS_STARTED); + } + + /* run_state doesn't make sense */ + if (ring_ptr->run_state != (u32)FXMAC_DMA_SG_IS_STOPED) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + /* Verify internal pointers point to correct memory space */ + addr_v = (uintptr)ring_ptr->free_head; + if ((addr_v < ring_ptr->base_bd_addr) || (addr_v > ring_ptr->high_bd_addr)) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + addr_v = (uintptr)ring_ptr->pre_head; + if ((addr_v < ring_ptr->base_bd_addr) || (addr_v > ring_ptr->high_bd_addr)) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + addr_v = (uintptr)ring_ptr->hw_head; + if ((addr_v < ring_ptr->base_bd_addr) || (addr_v > ring_ptr->high_bd_addr)) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + addr_v = (uintptr)ring_ptr->hw_tail; + if ((addr_v < ring_ptr->base_bd_addr) || (addr_v > ring_ptr->high_bd_addr)) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + addr_v = (uintptr)ring_ptr->post_head; + if ((addr_v < ring_ptr->base_bd_addr) || (addr_v > ring_ptr->high_bd_addr)) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + /* Verify internal counters add up */ + if ((ring_ptr->hw_cnt + ring_ptr->pre_cnt + ring_ptr->free_cnt + + ring_ptr->post_cnt) != ring_ptr->all_cnt) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + /* Verify BDs are linked correctly */ + addr_v = ring_ptr->base_bd_addr; + addr_p = ring_ptr->phys_base_addr + ring_ptr->separation; + + for (i = 1U; i < ring_ptr->all_cnt; i++) + { + /* Check BDA for this BD. It should point to next physical addr */ + if (FXMAC_BD_READ(addr_v, FXMAC_BD_ADDR_OFFSET) != addr_p) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + + /* Move on to next BD */ + addr_v += ring_ptr->separation; + addr_p += ring_ptr->separation; + } + + /* Last BD should have wrap bit set */ + if (FXMAC_SEND == direction) + { + if ((!FXMAC_BD_IS_TX_WRAP(addr_v)) == TRUE) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + } + else + { + /* FXMAC_RECV */ + if ((!FXMAC_BD_IS_RX_WRAP(addr_v)) == TRUE) + { + return (FError)(FXMAC_ERR_SG_LIST); + } + } + + /* No problems found */ + return (FError)(FT_SUCCESS); +} + + +/** + * @name: FXmacBdSetRxWrap + * @msg: Set this bit to mark the last descriptor in the receive buffer descriptor + * list. + * @param {uintptr} bdptr is the BD pointer to operate on + */ +static void FXmacBdSetRxWrap(uintptr bdptr) +{ + u32 data_value_rx; + u32 *temp_ptr; + + bdptr += (u32)(FXMAC_BD_ADDR_OFFSET); + temp_ptr = (u32 *)bdptr; + if (temp_ptr != NULL) + { + data_value_rx = *temp_ptr; + data_value_rx |= FXMAC_RXBUF_WRAP_MASK; + *temp_ptr = data_value_rx; + } +} + +/** + * @name: FXmacBdSetTxWrap + * @msg: Sets this bit to mark the last descriptor in the transmit buffer + * descriptor list. + * @param {uintptr} bdptr is the BD pointer to operate on + */ +static void FXmacBdSetTxWrap(uintptr bdptr) +{ + u32 data_value_tx; + u32 *temp_ptr; + + bdptr += (u32)(FXMAC_BD_STAT_OFFSET); + temp_ptr = (u32 *)bdptr; + if (temp_ptr != NULL) + { + data_value_tx = *temp_ptr; + data_value_tx |= FXMAC_TXBUF_WRAP_MASK; + *temp_ptr = data_value_tx; + } +} + + +/** + * @name: FXmacBdringPtrReset + * @msg: Reset BD ring head and tail pointers. + * @return {*} + * @param {FXmacBdRing} *ring_ptr is the instance to be worked on. + * @param {void} *virtaddrloc is the virtual base address of the user memory region. + */ +void FXmacBdringPtrReset(FXmacBdRing *ring_ptr, void *virtaddrloc) +{ + ring_ptr->free_head = virtaddrloc; + ring_ptr->pre_head = virtaddrloc; + ring_ptr->hw_head = virtaddrloc; + ring_ptr->hw_tail = virtaddrloc; + ring_ptr->post_head = virtaddrloc; +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bdring.h b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bdring.h new file mode 100644 index 0000000000..b03269e3f4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_bdring.h @@ -0,0 +1,160 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_bdring.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_ETH_F_XMAC_BDRING_H +#define DRIVERS_ETH_F_XMAC_BDRING_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fxmac_bd.h" +#include "ftypes.h" + +/**************************** Type Definitions *******************************/ + +/** This is an internal structure used to maintain the DMA list */ +typedef struct +{ + uintptr phys_base_addr; /* Physical address of 1st BD in list */ + uintptr base_bd_addr; /* Virtual address of 1st BD in list */ + uintptr high_bd_addr; /* Virtual address of last BD in the list */ + u32 length; /* Total size of ring in bytes */ + u32 run_state; /* Flag to indicate DMA is started */ + u32 separation; /* Number of bytes between the starting address + of adjacent BDs */ + FXmacBd *free_head; + /* First BD in the free group */ + FXmacBd *pre_head; /* First BD in the pre-work group */ + FXmacBd *hw_head; /* First BD in the work group */ + FXmacBd *hw_tail; /* Last BD in the work group */ + FXmacBd *post_head; + /* First BD in the post-work group */ + FXmacBd *bda_restart; + /* BDA to load when channel is started */ + + volatile u32 hw_cnt; /* Number of BDs in work group */ + u32 pre_cnt; /* Number of BDs in pre-work group */ + u32 free_cnt; /* Number of allocatable BDs in the free group */ + u32 post_cnt; /* Number of BDs in post-work group */ + u32 all_cnt; /* Total Number of BDs for channel */ +} FXmacBdRing; + +/** + * @name: FXMAC_BD_RING_NEXT + * @msg: Return the next BD from bd_ptr in a list. + * + * @param ring_ptr is the DMA channel to operate on. + * @param bd_ptr is the BD to operate on. + * @return The next BD in the list relative to the bd_ptr parameter. + */ +#define FXMAC_BD_RING_NEXT(ring_ptr, bd_ptr) \ + (((uintptr)((void *)(bd_ptr)) >= (ring_ptr)->high_bd_addr) ? (FXmacBd *)((void *)(ring_ptr)->base_bd_addr) : (FXmacBd *)((uintptr)((void *)(bd_ptr)) + (ring_ptr)->separation)) + +/** + * @name: FXMAC_BD_RING_CNT_CALC + * @msg: Use this macro at initialization time to determine how many BDs will fit + * in a BD list within the given memory constraints. + * + * @param alignment specifies what byte alignment the BDs must fall on and + * must be a power of 2 to get an accurate calculation (32, 64, 128,...) + * @param Bytes is the number of bytes to be used to store BDs. + * @return Number of BDs that can fit in the given memory area + */ +#define FXMAC_BD_RING_CNT_CALC(alignment, Bytes) \ + (u32)((Bytes) / (sizeof(FXmacBd))) + +/** + * @name: FXMAC_BD_RING_MEM_CALC + * @msg: Use this macro at initialization time to determine how many bytes of memory + * is required to contain a given number of BDs at a given alignment. + * @param alignment specifies what byte alignment the BDs must fall on. This + * parameter must be a power of 2 to get an accurate calculation (32, 64, + * 128,...) + * @param num_bd is the number of BDs to calculate memory size requirements for + * @return The number of bytes of memory required to create a BD list with the + * given memory constraints. + */ +#define FXMAC_BD_RING_MEM_CALC(alignment, num_bd) \ + (u32)(sizeof(FXmacBd) * (num_bd)) + +/** + * @name: FXMAC_BD_RING_GET_CNT + * @msg: Return the total number of BDs allocated by this channel with + * FXmacBdRingCreate(). + * @param ring_ptr is the DMA channel to operate on. + * @return The total number of BDs allocated for this channel. + */ +#define FXMAC_BD_RING_GET_CNT(ring_ptr) ((ring_ptr)->all_cnt) + +/** + * @name: FXMAC_BD_RING_GET_FREE_CNT + * @msg: Return the number of BDs allocatable with FXmacBdRingAlloc() for pre- + * processing. + * + * @param ring_ptr is the DMA channel to operate on. + * @return The number of BDs currently allocatable. + */ +#define FXMAC_BD_RING_GET_FREE_CNT(ring_ptr) ((ring_ptr)->free_cnt) + +/** + * @name: FXMAC_BD_RING_PREV + * @msg: Return the previous BD from bd_ptr in the list. + * @param ring_ptr is the DMA channel to operate on. + * @param bd_ptr is the BD to operate on + * @return The previous BD in the list relative to the bd_ptr parameter. + */ +#define FXMAC_BD_RING_PREV(ring_ptr, bd_ptr) \ + (((uintptr)(bd_ptr) <= (ring_ptr)->base_bd_addr) ? (FXmacBd *)(ring_ptr)->high_bd_addr : (FXmacBd *)((uintptr)(bd_ptr) - (ring_ptr)->separation)) + +/************************** Function Prototypes ******************************/ + +/* + * Scatter gather DMA related functions in FXmacbdring.c + */ +FError FXmacBdRingCreate(FXmacBdRing *ring_ptr, uintptr phys_addr, + uintptr virt_addr, u32 alignment, u32 bd_count); +FError FXmacBdRingClone(FXmacBdRing *ring_ptr, FXmacBd *src_bd_ptr, + u8 direction); +FError FXmacBdRingAlloc(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd **bd_set_ptr); +FError FXmacBdRingUnAlloc(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd *bd_set_ptr); +FError FXmacBdRingToHw(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd *bd_set_ptr); +FError FXmacBdRingFree(FXmacBdRing *ring_ptr, u32 num_bd, + FXmacBd *bd_set_ptr); +u32 FXmacBdRingFromHwTx(FXmacBdRing *ring_ptr, u32 bd_limit, + FXmacBd **bd_set_ptr); +u32 FXmacBdRingFromHwRx(FXmacBdRing *ring_ptr, u32 bd_limit, + FXmacBd **bd_set_ptr); +FError FXmacBdRingCheck(FXmacBdRing *ring_ptr, u8 direction); + +void FXmacBdringPtrReset(FXmacBdRing *ring_ptr, void *virt_addrloc); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_g.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_g.c new file mode 100644 index 0000000000..b8f1b053f3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_g.c @@ -0,0 +1,152 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_g.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fxmac.h" +#include "fparameters.h" +#include "ftypes.h" +/************************** Constant Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Prototypes ******************************/ + +/* + * The configuration table for emacps device + */ + +const FXmacConfig fxmac_cfg_tbl[FT_XMAC_NUM] = +{ + [FT_XMAC0_ID] = + { + .instance_id = (u32)FT_XMAC0_ID, /* Device ID */ + .base_address = (uintptr)FT_XMAC0_BASEADDRESS, /* Device base address */ + .extral_mode_base = FT_XMAC0_MODE_SEL_BASEADDRESS, + .extral_loopback_base = FT_XMAC0_LOOPBACK_SEL_BASEADDRESS, + .interface = FXMAC_PHY_INTERFACE_MODE_SGMII, + .speed = 1000, + .duplex = 1, + .auto_neg = 1, + .pclk_hz = FT_XMAC0_PCLK, + .max_queue_num = 16, + .tx_queue_id = 0, + .rx_queue_id = 0, + .hotplug_irq_num = FT_XMAC0_HOTPLUG_IRQ_NUM, + .dma_brust_length = 16, + .network_default_config = FXMAC_DEFAULT_OPTIONS, + .queue_irq_num = + { + FT_XMAC0_QUEUE0_IRQ_NUM, + FT_XMAC0_QUEUE1_IRQ_NUM, + FT_XMAC0_QUEUE2_IRQ_NUM, + FT_XMAC0_QUEUE3_IRQ_NUM, + FT_XMAC0_QUEUE4_IRQ_NUM, + FT_XMAC0_QUEUE5_IRQ_NUM, + FT_XMAC0_QUEUE6_IRQ_NUM, + FT_XMAC0_QUEUE7_IRQ_NUM + } + }, +#ifdef FT_XMAC1_ID + [FT_XMAC1_ID] = + { + .instance_id = (u32)FT_XMAC1_ID, /* Device ID */ + .base_address = (uintptr)FT_XMAC1_BASEADDRESS, /* Device base address */ + .extral_mode_base = FT_XMAC1_MODE_SEL_BASEADDRESS, + .extral_loopback_base = FT_XMAC1_LOOPBACK_SEL_BASEADDRESS, + .interface = FXMAC_PHY_INTERFACE_MODE_SGMII, + .speed = 1000, + .duplex = 1, + .auto_neg = 1, + .pclk_hz = FT_XMAC1_PCLK, + .max_queue_num = 4, + .tx_queue_id = 0, + .rx_queue_id = 0, + .hotplug_irq_num = FT_XMAC1_HOTPLUG_IRQ_NUM, + .dma_brust_length = 16, + .network_default_config = FXMAC_DEFAULT_OPTIONS, + .queue_irq_num = + { + FT_XMAC1_QUEUE0_IRQ_NUM, + FT_XMAC1_QUEUE1_IRQ_NUM, + FT_XMAC1_QUEUE2_IRQ_NUM, + FT_XMAC1_QUEUE3_IRQ_NUM + } + }, +#endif +#ifdef FT_XMAC2_ID + [FT_XMAC2_ID] = + { + .instance_id = (u32)FT_XMAC2_ID, /* Device ID */ + .base_address = (uintptr)FT_XMAC2_BASEADDRESS, /* Device base address */ + .extral_mode_base = FT_XMAC2_MODE_SEL_BASEADDRESS, + .extral_loopback_base = FT_XMAC2_LOOPBACK_SEL_BASEADDRESS, + .interface = FXMAC_PHY_INTERFACE_MODE_RGMII, + .speed = 1000, + .duplex = 1, + .auto_neg = 1, + .pclk_hz = FT_XMAC2_PCLK, + .max_queue_num = 4, + .tx_queue_id = 0, + .rx_queue_id = 0, + .hotplug_irq_num = FT_XMAC2_HOTPLUG_IRQ_NUM, + .dma_brust_length = 16, + .network_default_config = FXMAC_DEFAULT_OPTIONS, + .queue_irq_num = + { + FT_XMAC2_QUEUE0_IRQ_NUM, + FT_XMAC2_QUEUE1_IRQ_NUM, + FT_XMAC2_QUEUE2_IRQ_NUM, + FT_XMAC2_QUEUE3_IRQ_NUM + } + }, +#endif +#ifdef FT_XMAC3_ID + [FT_XMAC3_ID] = + { + .instance_id = (u32)FT_XMAC3_ID, /* Device ID */ + .base_address = (uintptr)FT_XMAC3_BASEADDRESS, /* Device base address */ + .extral_mode_base = FT_XMAC3_MODE_SEL_BASEADDRESS, + .extral_loopback_base = FT_XMAC3_LOOPBACK_SEL_BASEADDRESS, + .interface = FXMAC_PHY_INTERFACE_MODE_RGMII, + .speed = 1000, + .duplex = 1, + .auto_neg = 1, + .pclk_hz = FT_XMAC3_PCLK, + .max_queue_num = 4, + .tx_queue_id = 0, + .rx_queue_id = 0, + .hotplug_irq_num = FT_XMAC3_HOTPLUG_IRQ_NUM, + .dma_brust_length = 16, + .network_default_config = FXMAC_DEFAULT_OPTIONS, + .queue_irq_num = + { + FT_XMAC3_QUEUE0_IRQ_NUM, + FT_XMAC3_QUEUE1_IRQ_NUM, + FT_XMAC3_QUEUE2_IRQ_NUM, + FT_XMAC3_QUEUE3_IRQ_NUM + } + } +#endif +}; +/** @} */ diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_hw.h b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_hw.h new file mode 100644 index 0000000000..f3814bd897 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_hw.h @@ -0,0 +1,701 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_hw.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_ETH_FMAC_HW_H +#define BSP_DRIVERS_ETH_FMAC_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fparameters.h" +#include "fio.h" +#include "ftypes.h" +#include "fkernel.h" + +#define FXMAC_RX_BUF_SIZE 1536U /* Specify the receive buffer size in \ + bytes, 64, 128, ... 10240 */ +#define FXMAC_RX_BUF_SIZE_JUMBO 10240U + +#define FXMAC_RX_BUF_UNIT 64U /* Number of receive buffer bytes as a \ + unit, this is HW setup */ + +#define FXMAC_MAX_RXBD 128U /* Size of RX buffer descriptor queues */ +#define FXMAC_MAX_TXBD 128U /* Size of TX buffer descriptor queues */ + +#define FXMAC_MAX_HASH_BITS 64U /* Maximum value for hash bits. 2**6 */ + +/************************** Constant Definitions *****************************/ + +#define FXMAC_MAX_MAC_ADDR 4U /* Maxmum number of mac address \ + supported */ +#define FXMAC_MAX_TYPE_ID 4U /* Maxmum number of type id supported */ + +#ifdef __aarch64__ +#define FXMAC_BD_ALIGNMENT 64U /* Minimum buffer descriptor alignment \ + on the local bus */ +#else + +#define FXMAC_BD_ALIGNMENT 4U /* Minimum buffer descriptor alignment \ + on the local bus */ +#endif +#define FXMAC_RX_BUF_ALIGNMENT 4U /* Minimum buffer alignment when using \ + options that impose alignment \ + restrictions on the buffer data on \ + the local bus */ + +#define FXMAC_NWCTRL_OFFSET 0x00000000U /* Network Control reg */ +#define FXMAC_NWCFG_OFFSET 0x00000004U /* Network Config reg */ +#define FXMAC_NWSR_OFFSET 0x00000008U /* Network Status reg */ +#define FXMAC_DMACR_OFFSET 0x00000010U /* DMA Control reg */ +#define FXMAC_TXSR_OFFSET 0x00000014U /* TX Status reg */ +#define FXMAC_RXQBASE_OFFSET 0x00000018U /* RX Q Base address reg */ +#define FXMAC_TXQBASE_OFFSET 0x0000001CU /* TX Q Base address reg */ +#define FXMAC_RXSR_OFFSET 0x00000020U /* RX Status reg */ + +#define FXMAC_ISR_OFFSET 0x00000024U /* Interrupt Status reg */ +#define FXMAC_IER_OFFSET 0x00000028U /* Interrupt Enable reg */ +#define FXMAC_IDR_OFFSET 0x0000002CU /* Interrupt Disable reg */ +#define FXMAC_IMR_OFFSET 0x00000030U /* Interrupt Mask reg */ + +#define FXMAC_PHYMNTNC_OFFSET 0x00000034U /* Phy Maintaince reg */ +#define FXMAC_RXPAUSE_OFFSET 0x00000038U /* RX Pause Time reg */ +#define FXMAC_TXPAUSE_OFFSET 0x0000003CU /* TX Pause Time reg */ + +#define FXMAC_JUMBOMAXLEN_OFFSET 0x00000048U /* Jumbo max length reg */ +#define FXMAC_GEM_HSMAC 0x0050 /* Hs mac config register*/ +#define FXMAC_RXWATERMARK_OFFSET 0x0000007CU /* RX watermark reg */ + +#define FXMAC_HASHL_OFFSET 0x00000080U /* Hash Low address reg */ +#define FXMAC_HASHH_OFFSET 0x00000084U /* Hash High address reg */ + +#define FXMAC_GEM_SA1B 0x0088 /* Specific1 Bottom */ +#define FXMAC_GEM_SA1T 0x008C /* Specific1 Top */ +#define FXMAC_GEM_SA2B 0x0090 /* Specific2 Bottom */ +#define FXMAC_GEM_SA2T 0x0094 /* Specific2 Top */ +#define FXMAC_GEM_SA3B 0x0098 /* Specific3 Bottom */ +#define FXMAC_GEM_SA3T 0x009C /* Specific3 Top */ +#define FXMAC_GEM_SA4B 0x00A0 /* Specific4 Bottom */ +#define FXMAC_GEM_SA4T 0x00A4 /* Specific4 Top */ + +#define FXMAC_MATCH1_OFFSET 0x000000A8U /* Type ID1 Match reg */ +#define FXMAC_MATCH2_OFFSET 0x000000ACU /* Type ID2 Match reg */ +#define FXMAC_MATCH3_OFFSET 0x000000B0U /* Type ID3 Match reg */ +#define FXMAC_MATCH4_OFFSET 0x000000B4U /* Type ID4 Match reg */ + +#define FXMAC_STRETCH_OFFSET 0x000000BCU /* IPG Stretch reg */ +#define FXMAC_REVISION_REG_OFFSET 0x000000FCU /* identification number and module revision */ + +#define FXMAC_OCTTXL_OFFSET 0x00000100U /* Octects transmitted Low \ + reg */ +#define FXMAC_OCTTXH_OFFSET 0x00000104U /* Octects transmitted High \ + reg */ + +#define FXMAC_TXCNT_OFFSET 0x00000108U /* Error-free Frmaes \ + transmitted counter */ +#define FXMAC_TXBCCNT_OFFSET 0x0000010CU /* Error-free Broadcast \ + Frames counter*/ +#define FXMAC_TXMCCNT_OFFSET 0x00000110U /* Error-free Multicast \ + Frame counter */ +#define FXMAC_TXPAUSECNT_OFFSET 0x00000114U /* Pause Frames Transmitted \ + Counter */ +#define FXMAC_TX64CNT_OFFSET 0x00000118U /* Error-free 64 byte Frames \ + Transmitted counter */ +#define FXMAC_TX65CNT_OFFSET 0x0000011CU /* Error-free 65-127 byte \ + Frames Transmitted \ + counter */ +#define FXMAC_TX128CNT_OFFSET 0x00000120U /* Error-free 128-255 byte \ + Frames Transmitted \ + counter*/ +#define FXMAC_TX256CNT_OFFSET 0x00000124U /* Error-free 256-511 byte \ + Frames transmitted \ + counter */ +#define FXMAC_TX512CNT_OFFSET 0x00000128U /* Error-free 512-1023 byte \ + Frames transmitted \ + counter */ +#define FXMAC_TX1024CNT_OFFSET 0x0000012CU /* Error-free 1024-1518 byte \ + Frames transmitted \ + counter */ +#define FXMAC_TX1519CNT_OFFSET 0x00000130U /* Error-free larger than \ + 1519 byte Frames \ + transmitted counter */ +#define FXMAC_TXURUNCNT_OFFSET 0x00000134U /* TX under run error \ + counter */ + +#define FXMAC_SNGLCOLLCNT_OFFSET 0x00000138U /* Single Collision Frame \ + Counter */ +#define FXMAC_MULTICOLLCNT_OFFSET 0x0000013CU /* Multiple Collision Frame \ + Counter */ +#define FXMAC_EXCESSCOLLCNT_OFFSET 0x00000140U /* Excessive Collision Frame \ + Counter */ +#define FXMAC_LATECOLLCNT_OFFSET 0x00000144U /* Late Collision Frame \ + Counter */ +#define FXMAC_TXDEFERCNT_OFFSET 0x00000148U /* Deferred Transmission \ + Frame Counter */ +#define FXMAC_TXCSENSECNT_OFFSET 0x0000014CU /* Transmit Carrier Sense \ + Error Counter */ + +#define FXMAC_OCTRXL_OFFSET 0x00000150U /* Octects Received register \ + Low */ +#define FXMAC_OCTRXH_OFFSET 0x00000154U /* Octects Received register \ + High */ + +#define FXMAC_RXCNT_OFFSET 0x00000158U /* Error-free Frames \ + Received Counter */ +#define FXMAC_RXBROADCNT_OFFSET 0x0000015CU /* Error-free Broadcast \ + Frames Received Counter */ +#define FXMAC_RXMULTICNT_OFFSET 0x00000160U /* Error-free Multicast \ + Frames Received Counter */ +#define FXMAC_RXPAUSECNT_OFFSET 0x00000164U /* Pause Frames \ + Received Counter */ +#define FXMAC_RX64CNT_OFFSET 0x00000168U /* Error-free 64 byte Frames \ + Received Counter */ +#define FXMAC_RX65CNT_OFFSET 0x0000016CU /* Error-free 65-127 byte \ + Frames Received Counter */ +#define FXMAC_RX128CNT_OFFSET 0x00000170U /* Error-free 128-255 byte \ + Frames Received Counter */ +#define FXMAC_RX256CNT_OFFSET 0x00000174U /* Error-free 256-512 byte \ + Frames Received Counter */ +#define FXMAC_RX512CNT_OFFSET 0x00000178U /* Error-free 512-1023 byte \ + Frames Received Counter */ +#define FXMAC_RX1024CNT_OFFSET 0x0000017CU /* Error-free 1024-1518 byte \ + Frames Received Counter */ +#define FXMAC_RX1519CNT_OFFSET 0x00000180U /* Error-free 1519-max byte \ + Frames Received Counter */ +#define FXMAC_RXUNDRCNT_OFFSET 0x00000184U /* Undersize Frames Received \ + Counter */ +#define FXMAC_RXOVRCNT_OFFSET 0x00000188U /* Oversize Frames Received \ + Counter */ +#define FXMAC_RXJABCNT_OFFSET 0x0000018CU /* Jabbers Received \ + Counter */ +#define FXMAC_RXFCSCNT_OFFSET 0x00000190U /* Frame Check Sequence \ + Error Counter */ +#define FXMAC_RXLENGTHCNT_OFFSET 0x00000194U /* Length Field Error \ + Counter */ +#define FXMAC_RXSYMBCNT_OFFSET 0x00000198U /* Symbol Error Counter */ +#define FXMAC_RXALIGNCNT_OFFSET 0x0000019CU /* Alignment Error Counter */ +#define FXMAC_RXRESERRCNT_OFFSET 0x000001A0U /* Receive Resource Error \ + Counter */ +#define FXMAC_RXORCNT_OFFSET 0x000001A4U /* Receive Overrun Counter */ +#define FXMAC_RXIPCCNT_OFFSET 0x000001A8U /* IP header Checksum Error \ + Counter */ +#define FXMAC_RXTCPCCNT_OFFSET 0x000001ACU /* TCP Checksum Error \ + Counter */ +#define FXMAC_RXUDPCCNT_OFFSET 0x000001B0U /* UDP Checksum Error \ + Counter */ +#define FXMAC_LAST_OFFSET 0x000001B4U /* Last statistic counter \ + offset, for clearing */ + +#define FXMAC_1588_SEC_OFFSET 0x000001D0U /* 1588 second counter */ +#define FXMAC_1588_NANOSEC_OFFSET 0x000001D4U /* 1588 nanosecond counter */ +#define FXMAC_1588_ADJ_OFFSET 0x000001D8U /* 1588 nanosecond \ + adjustment counter */ +#define FXMAC_1588_INC_OFFSET 0x000001DCU /* 1588 nanosecond \ + increment counter */ +#define FXMAC_PTP_TXSEC_OFFSET 0x000001E0U /* 1588 PTP transmit second \ + counter */ +#define FXMAC_PTP_TXNANOSEC_OFFSET 0x000001E4U /* 1588 PTP transmit \ + nanosecond counter */ +#define FXMAC_PTP_RXSEC_OFFSET 0x000001E8U /* 1588 PTP receive second \ + counter */ +#define FXMAC_PTP_RXNANOSEC_OFFSET 0x000001ECU /* 1588 PTP receive \ + nanosecond counter */ +#define FXMAC_PTPP_TXSEC_OFFSET 0x000001F0U /* 1588 PTP peer transmit \ + second counter */ +#define FXMAC_PTPP_TXNANOSEC_OFFSET 0x000001F4U /* 1588 PTP peer transmit \ + nanosecond counter */ +#define FXMAC_PTPP_RXSEC_OFFSET 0x000001F8U /* 1588 PTP peer receive \ + second counter */ +#define FXMAC_PTPP_RXNANOSEC_OFFSET 0x000001FCU /* 1588 PTP peer receive \ + nanosecond counter */ + +#define FXMAC_PCS_CONTROL_OFFSET 0x00000200U /* All PCS registers */ + +#define FXMAC_PCS_STATUS_OFFSET 0x00000204U /* All PCS status */ + +#define FXMAC_PCS_AN_LP_OFFSET 0x00000214U /* All PCS link partner's base page */ + +#define FXMAC_DESIGNCFG_DEBUG1_OFFSET 0x00000280U /* Design Configuration Register 1 */ + +#define FXMAC_DESIGNCFG_DEBUG2_OFFSET 0x00000284U /* Design Configuration Register 2 */ + +#define FXMAC_INTQ1_STS_OFFSET 0x00000400U /* Interrupt Q1 Status reg */ + +#define FXMAC_TXQ1BASE_OFFSET 0x00000440U /* TX Q1 Base address \ + reg */ +#define FXMAC_RXQ1BASE_OFFSET 0x00000480U /* RX Q1 Base address \ + reg */ + +#define FXMAC_RXBUFQ1_SIZE_OFFSET 0x000004a0U /* Receive Buffer Size */ +#define FXMAC_RXBUFQX_SIZE_OFFSET(x) (FXMAC_RXBUFQ1_SIZE_OFFSET + (x << 2)) +#define FXMAC_RXBUFQX_SIZE_MASK GENMASK(7, 0) + +#define FXMAC_MSBBUF_TXQBASE_OFFSET 0x000004C8U /* MSB Buffer TX Q Base reg */ +#define FXMAC_MSBBUF_RXQBASE_OFFSET 0x000004D4U /* MSB Buffer RX Q Base \ + reg */ +#define FXMAC_INTQ1_IER_OFFSET 0x00000600U /* Interrupt Q1 Enable reg */ +#define FXMAC_INTQX_IER_SIZE_OFFSET(x) (FXMAC_INTQ1_IER_OFFSET + (x << 2)) + +#define FXMAC_INTQ1_IDR_OFFSET 0x00000620U /* Interrupt Q1 Disable reg */ +#define FXMAC_INTQX_IDR_SIZE_OFFSET(x) (FXMAC_INTQ1_IDR_OFFSET + (x << 2)) + +#define FXMAC_INTQ1_IMR_OFFSET 0x00000640U /* Interrupt Q1 Mask \ + reg */ + +#define FXMAC_GEM_USX_CONTROL_OFFSET 0x0A80 /* High speed PCS control register */ +#define FXMAC_TEST_CONTROL_OFFSET 0X0A84 /* USXGMII Test Control Register */ + +#define FXMAC_GEM_SRC_SEL_LN 0x1C04 +#define FXMAC_GEM_DIV_SEL0_LN 0x1C08 +#define FXMAC_GEM_DIV_SEL1_LN 0x1C0C +#define FXMAC_GEM_PMA_XCVR_POWER_STATE 0x1C10 +#define FXMAC_GEM_SPEED_MODE 0x1C14 +#define FXMAC_GEM_MII_SELECT 0x1C18 +#define FXMAC_GEM_SEL_MII_ON_RGMII 0x1C1C +#define FXMAC_GEM_TX_CLK_SEL0 0x1C20 +#define FXMAC_GEM_TX_CLK_SEL1 0x1C24 +#define FXMAC_GEM_TX_CLK_SEL2 0x1C28 +#define FXMAC_GEM_TX_CLK_SEL3 0x1C2C +#define FXMAC_GEM_RX_CLK_SEL0 0x1C30 +#define FXMAC_GEM_RX_CLK_SEL1 0x1C34 +#define FXMAC_GEM_CLK_250M_DIV10_DIV100_SEL 0x1C38 +#define FXMAC_GEM_TX_CLK_SEL5 0x1C3C +#define FXMAC_GEM_TX_CLK_SEL6 0x1C40 +#define FXMAC_GEM_RX_CLK_SEL4 0x1C44 +#define FXMAC_GEM_RX_CLK_SEL5 0x1C48 +#define FXMAC_GEM_TX_CLK_SEL3_0 0x1C70 +#define FXMAC_GEM_TX_CLK_SEL4_0 0x1C74 +#define FXMAC_GEM_RX_CLK_SEL3_0 0x1C78 +#define FXMAC_GEM_RX_CLK_SEL4_0 0x1C7C +#define FXMAC_GEM_RGMII_TX_CLK_SEL0 0x1C80 +#define FXMAC_GEM_RGMII_TX_CLK_SEL1 0x1C84 +#define FXMAC_GEM_MODE_SEL_OFFSET 0xDC00 +#define FXMAC_LOOPBACK_SEL_OFFSET 0xDC04 + +/** + * @name interrupts bit definitions + * Bits definitions are same in FXMAC_ISR_OFFSET, + * FXMAC_IER_OFFSET, FXMAC_IDR_OFFSET, and FXMAC_IMR_OFFSET + * @{ + */ +#define FXMAC_IXR_PTPPSTX_MASK BIT(25) /* PTP Pdelay_resp TXed */ +#define FXMAC_IXR_PTPPDRTX_MASK BIT(24) /* PTP Pdelay_req TXed */ +#define FXMAC_IXR_PTPPSRX_MASK BIT(23) /* PTP Pdelay_resp RXed */ +#define FXMAC_IXR_PTPPDRRX_MASK BIT(22) /* PTP Pdelay_req RXed */ + +#define FXMAC_IXR_PTPSTX_MASK BIT(21) /* PTP Sync TXed */ +#define FXMAC_IXR_PTPDRTX_MASK BIT(20) /* PTP Delay_req TXed */ +#define FXMAC_IXR_PTPSRX_MASK BIT(19) /* PTP Sync RXed */ +#define FXMAC_IXR_PTPDRRX_MASK BIT(18) /* PTP Delay_req RXed */ + +#define FXMAC_IXR_PAUSETX_MASK BIT(14) /* Pause frame transmitted */ +#define FXMAC_IXR_PAUSEZERO_MASK BIT(13) /* Pause time has reached zero */ +#define FXMAC_IXR_PAUSENZERO_MASK BIT(12) /* Pause frame received */ +#define FXMAC_IXR_HRESPNOK_MASK BIT(11) /* hresp not ok */ +#define FXMAC_IXR_RXOVR_MASK BIT(10) /* Receive overrun occurred */ +#define FXMAC_IXR_LINKCHANGE_MASK BIT(9) /* link status change */ +#define FXMAC_IXR_TXCOMPL_MASK BIT(7) /* Frame transmitted ok */ +#define FXMAC_IXR_TXEXH_MASK BIT(6) /* Transmit err occurred or \ + no buffers*/ +#define FXMAC_IXR_RETRY_MASK BIT(5) /* Retry limit exceeded */ +#define FXMAC_IXR_URUN_MASK BIT(4) /* Transmit underrun */ +#define FXMAC_IXR_TXUSED_MASK BIT(3) /* Tx buffer used bit read */ +#define FXMAC_IXR_RXUSED_MASK BIT(2) /* Rx buffer used bit read */ +#define FXMAC_IXR_RXCOMPL_MASK BIT(1) /* Frame received ok */ +#define FXMAC_IXR_MGMNT_MASK BIT(0) /* PHY management complete */ +#define FXMAC_IXR_ALL_MASK GENMASK(14, 0) /* Everything! */ + +#define FXMAC_IXR_TX_ERR_MASK ((u32)FXMAC_IXR_TXEXH_MASK | \ + (u32)FXMAC_IXR_RETRY_MASK | \ + (u32)FXMAC_IXR_URUN_MASK) + +#define FXMAC_IXR_RX_ERR_MASK ((u32)FXMAC_IXR_HRESPNOK_MASK | \ + (u32)FXMAC_IXR_RXUSED_MASK | \ + (u32)FXMAC_IXR_RXOVR_MASK) + +/** @name network control register bit definitions + * @{ + */ +#define FXMAC_NWCTRL_ENABLE_HS_MAC_MASK BIT(31) + +#define FXMAC_NWCTRL_TWO_PT_FIVE_GIG_MASK BIT(29) /* 2.5G operation selected */ + +#define FXMAC_NWCTRL_FLUSH_DPRAM_MASK BIT(18) /* Flush a packet from \ + Rx SRAM */ +#define FXMAC_NWCTRL_ZEROPAUSETX_MASK BIT(11) /* Transmit zero quantum \ + pause frame */ +#define FXMAC_NWCTRL_PAUSETX_MASK BIT(11) /* Transmit pause frame */ +#define FXMAC_NWCTRL_HALTTX_MASK BIT(10) /* Halt transmission \ + after current frame */ +#define FXMAC_NWCTRL_STARTTX_MASK BIT(9) /* Start tx (tx_go) */ + +#define FXMAC_NWCTRL_STATWEN_MASK BIT(7) /* Enable writing to \ + stat counters */ +#define FXMAC_NWCTRL_STATINC_MASK BIT(6) /* Increment statistic \ + registers */ +#define FXMAC_NWCTRL_STATCLR_MASK BIT(5) /* Clear statistic \ + registers */ +#define FXMAC_NWCTRL_MDEN_MASK BIT(4) /* Enable MDIO port */ +#define FXMAC_NWCTRL_TXEN_MASK BIT(3) /* Enable transmit */ +#define FXMAC_NWCTRL_RXEN_MASK BIT(2) /* Enable receive */ +#define FXMAC_NWCTRL_LOOPEN_MASK BIT(1) /* local loopback */ + +/* External address match enable */ + +#define FXMAC_NWCFG_SGMII_MODE_ENABLE_MASK BIT(27) /* SGMII mode enable */ + +#define FXMAC_NWCFG_BUS_WIDTH_32_MASK (0U << 21) +#define FXMAC_NWCFG_BUS_WIDTH_64_MASK (1U << 21) +#define FXMAC_NWCFG_BUS_WIDTH_128_MASK (2U << 21) + +#define FXMAC_NWCFG_CLOCK_DIV224_MASK (7U << 18) +#define FXMAC_NWCFG_CLOCK_DIV128_MASK (6U << 18) +#define FXMAC_NWCFG_CLOCK_DIV96_MASK (5U << 18) +#define FXMAC_NWCFG_CLOCK_DIV64_MASK (4U << 18) +#define FXMAC_NWCFG_CLOCK_DIV48_MASK (3U << 18) +#define FXMAC_NWCFG_CLOCK_DIV32_MASK (2U << 18) +#define FXMAC_NWCFG_CLOCK_DIV16_MASK (1U << 18) +#define FXMAC_NWCFG_CLOCK_DIV8_MASK (0U << 18) + +#define FXMAC_NWCFG_FCS_REMOVE BIT(17) /* FCS remove - setting this bit will cause received frames to be written to memory without their frame check sequence (last 4 bytes). */ +#define FXMAC_NWCFG_PAUSE_ENABLE BIT(13) /* Pause enable - when set, transmission will pause if a non-zero 802.3 classic pause frame is received and PFC has not been negotiated. */ +#define FXMAC_NWCFG_PCSSEL_MASK BIT(11) /* PCS Select */ +#define FXMAC_NWCFG_1000_MASK BIT(10) /* Gigabit mode enable */ +#define FXMAC_NWCFG_1536RXEN_MASK BIT(8) /* Enable 1536 byte \ + frames reception */ +#define FXMAC_NWCFG_UCASTHASHEN_MASK BIT(7) /* Receive unicast hash \ + frames */ +#define FXMAC_NWCFG_MCASTHASHEN_MASK BIT(6) /* Receive multicast hash \ + frames */ +#define FXMAC_NWCFG_BCASTDI_MASK BIT(5) /* Do not receive \ + broadcast frames */ +#define FXMAC_NWCFG_COPYALLEN_MASK BIT(4) /* Copy all frames */ +#define FXMAC_NWCFG_JUMBO_MASK BIT(3) /* Jumbo frames */ +#define FXMAC_NWCFG_NVLANDISC_MASK BIT(2) /* Receive only VLAN \ + frames */ +#define FXMAC_NWCFG_FDEN_MASK BIT(1) /* full duplex */ +#define FXMAC_NWCFG_100_MASK BIT(0) /* 100 Mbps */ +#define FXMAC_NWCFG_RESET_MASK BIT(19) /* reset value */ + +/* Receive buffer descriptor status words bit positions. + * Receive buffer descriptor consists of two 32-bit registers, + * the first - word0 contains a 32-bit word aligned address pointing to the + * address of the buffer. The lower two bits make up the wrap bit indicating + * the last descriptor and the ownership bit to indicate it has been used by + * the xmac. + * The following register - word1, contains status information regarding why + * the frame was received (the filter match condition) as well as other + * useful info. + * @{ + */ +#define FXMAC_RXBUF_BCAST_MASK BIT(31) /* Broadcast frame */ +#define FXMAC_RXBUF_MULTIHASH_MASK BIT(30) /* Multicast hashed frame */ +#define FXMAC_RXBUF_UNIHASH_MASK BIT(29) /* Unicast hashed frame */ +#define FXMAC_RXBUF_EXH_MASK BIT(27) /* buffer exhausted */ +#define FXMAC_RXBUF_AMATCH_MASK GENMASK(26, 25) /* Specific address \ + matched */ +#define FXMAC_RXBUF_IDFOUND_MASK BIT(24) /* Type ID matched */ +#define FXMAC_RXBUF_IDMATCH_MASK GENMASK(23, 22) /* ID matched mask */ +#define FXMAC_RXBUF_VLAN_MASK BIT(21) /* VLAN tagged */ +#define FXMAC_RXBUF_PRI_MASK BIT(20) /* Priority tagged */ +#define FXMAC_RXBUF_VPRI_MASK GENMASK(19, 17) /* Vlan priority */ +#define FXMAC_RXBUF_CFI_MASK BIT(16) /* CFI frame */ +#define FXMAC_RXBUF_EOF_MASK BIT(15) /* End of frame. */ +#define FXMAC_RXBUF_SOF_MASK BIT(14) /* Start of frame. */ +#define FXMAC_RXBUF_FCS_STATUS_MASK BIT(13) /* Status of fcs. */ +#define FXMAC_RXBUF_LEN_MASK GENMASK(12, 0) /* Mask for length field */ +#define FXMAC_RXBUF_LEN_JUMBO_MASK GENMASK(13, 0) /* Mask for jumbo length */ + +#define FXMAC_RXBUF_WRAP_MASK BIT(1) /* Wrap bit, last BD */ +#define FXMAC_RXBUF_NEW_MASK BIT(0) /* Used bit.. */ +#define FXMAC_RXBUF_ADD_MASK GENMASK(31, 2) /* Mask for address */ +/* + * @} + */ + +/* Transmit buffer descriptor status words bit positions. + * Transmit buffer descriptor consists of two 32-bit registers, + * the first - word0 contains a 32-bit address pointing to the location of + * the transmit data. + * The following register - word1, consists of various information to control + * the xmac transmit process. After transmit, this is updated with status + * information, whether the frame was transmitted OK or why it had failed. + * @{ + */ +#define FXMAC_TXBUF_USED_MASK BIT(31) /* Used bit. */ +#define FXMAC_TXBUF_WRAP_MASK BIT(30) /* Wrap bit, last descriptor */ +#define FXMAC_TXBUF_RETRY_MASK BIT(29) /* Retry limit exceeded */ +#define FXMAC_TXBUF_URUN_MASK BIT(28) /* Transmit underrun occurred */ +#define FXMAC_TXBUF_EXH_MASK BIT(27) /* Buffers exhausted */ +#define FXMAC_TXBUF_TCP_MASK BIT(26) /* Late collision. */ +#define FXMAC_TXBUF_NOCRC_MASK BIT(16) /* No CRC */ +#define FXMAC_TXBUF_LAST_MASK BIT(15) /* Last buffer */ +#define FXMAC_TXBUF_LEN_MASK GENMASK(13, 0) /* Mask for length field */ +/* + * @} + */ + +/** @name network configuration register bit definitions + * @{ + */ +#define FXMAC_NWCFG_BADPREAMBEN_MASK BIT(29) /* disable rejection of \ + non-standard preamble */ +#define FXMAC_NWCFG_IPDSTRETCH_MASK BIT(28) /* enable transmit IPG */ +#define FXMAC_NWCFG_SGMIIEN_MASK BIT(27) /* SGMII Enable */ +#define FXMAC_NWCFG_FCSIGNORE_MASK BIT(26) /* disable rejection of \ + FCS error */ +#define FXMAC_NWCFG_HDRXEN_MASK BIT(25) /* RX half duplex */ +#define FXMAC_NWCFG_RXCHKSUMEN_MASK BIT(24) /* enable RX checksum \ + offload */ +#define FXMAC_NWCFG_PAUSECOPYDI_MASK BIT(23) /* Do not copy pause \ + Frames to memory */ +#define FXMAC_NWCFG_DWIDTH_64_MASK BIT(21) /* 64 bit Data bus width */ +#define FXMAC_NWCFG_MDC_SHIFT_MASK 18U /* shift bits for MDC */ +#define FXMAC_NWCFG_MDCCLKDIV_MASK GENMASK(20, 18) /* MDC Mask PCLK divisor */ +#define FXMAC_NWCFG_FCSREM_MASK BIT(17) /* Discard FCS from \ + received frames */ +#define FXMAC_NWCFG_LENERRDSCRD_MASK BIT(16) +/* RX length error discard */ +#define FXMAC_NWCFG_RXOFFS_MASK GENMASK(15) /* RX buffer offset */ +#define FXMAC_NWCFG_PAUSEEN_MASK BIT(13) /* Enable pause RX */ +#define FXMAC_NWCFG_RETRYTESTEN_MASK BIT(12) /* Retry test */ +#define FXMAC_NWCFG_XTADDMACHEN_MASK BIT(9) +#define FXMAC_NWCFG_LOOPBACK_LOCAL_MASK BIT(1) /* Loopback local */ + +/* External address match enable */ + +/** + * @name receive status register bit definitions + * @{ + */ +#define FXMAC_RXSR_HRESPNOK_MASK BIT(3) /* Receive hresp not OK */ +#define FXMAC_RXSR_RXOVR_MASK BIT(2) /* Receive overrun */ +#define FXMAC_RXSR_FRAMERX_MASK BIT(1) /* Frame received OK */ +#define FXMAC_RXSR_BUFFNA_MASK BIT(0) /* RX buffer used bit set */ + +#define FXMAC_RXSR_ERROR_MASK ((u32)FXMAC_RXSR_HRESPNOK_MASK | \ + (u32)FXMAC_RXSR_RXOVR_MASK | \ + (u32)FXMAC_RXSR_BUFFNA_MASK) + +#define FXMAC_SR_ALL_MASK GENMASK(31, 0) /* Mask for full register */ + +/** @name DMA control register bit definitions + * @{ + */ +#define FXMAC_DMACR_ADDR_WIDTH_64 BIT(30) /* 64 bit address bus */ +#define FXMAC_DMACR_TXEXTEND_MASK BIT(29) /* Tx Extended desc mode */ +#define FXMAC_DMACR_RXEXTEND_MASK BIT(28) /* Rx Extended desc mode */ +#define FXMAC_DMACR_ORCE_DISCARD_ON_ERR_MASK BIT(24) /* Auto Discard RX frames during lack of resource. */ +#define FXMAC_DMACR_RXBUF_MASK GENMASK(23, 16) /* Mask bit for RX buffer \ + size */ +#define FXMAC_DMACR_RXBUF_SHIFT 16U /* Shift bit for RX buffer \ + size */ +#define FXMAC_DMACR_TCPCKSUM_MASK BIT(11) /* enable/disable TX \ + checksum offload */ +#define FXMAC_DMACR_TXSIZE_MASK BIT(10) /* TX buffer memory size bit[10] */ +#define FXMAC_DMACR_RXSIZE_MASK GENMASK(9, 8) /* RX buffer memory size bit[9:8] */ +#define FXMAC_DMACR_ENDIAN_MASK BIT(7) /* endian configuration */ +#define FXMAC_DMACR_SWAP_MANAGEMENT_MASK BIT(6) /* When clear, selects little endian mode */ +#define FXMAC_DMACR_BLENGTH_MASK GENMASK(4, 0) /* buffer burst length */ +#define FXMAC_DMACR_SINGLE_AHB_AXI_BURST BIT(0) /* single AHB_AXI bursts */ +#define FXMAC_DMACR_INCR4_AHB_AXI_BURST BIT(2) /* 4 bytes AHB_AXI bursts */ +#define FXMAC_DMACR_INCR8_AHB_AXI_BURST BIT(3) /* 8 bytes AHB_AXI bursts */ +#define FXMAC_DMACR_INCR16_AHB_AXI_BURST BIT(4) /* 16 bytes AHB_AXI bursts */ + +/* This register indicates module identification number and module revision. */ + +#define FXMAC_REVISION_MODULE_MASK GENMASK(15, 0) /* Module revision */ +#define FXMAC_IDENTIFICATION_MASK GENMASK(27, 16) /* Module identification number */ +#define FXMAC_FIX_NUM_MASK GENMASK(31, 28) /* Fix number - incremented for fix releases */ + +/** @name network status register bit definitaions + * @{ + */ +#define FXMAC_NWSR_MDIOIDLE_MASK BIT(2) /* PHY management idle */ +#define FXMAC_NWSR_MDIO_MASK BIT(1) /* Status of mdio_in */ +#define FXMAC_NWSR_PCS_LINK_STATE_MASK BIT(0) + +/** @name PHY Maintenance bit definitions + * @{ + */ +#define FXMAC_PHYMNTNC_OP_MASK (BIT(17) | BIT(30)) /* operation mask bits */ +#define FXMAC_PHYMNTNC_OP_R_MASK BIT(29) /* read operation */ +#define FXMAC_PHYMNTNC_OP_W_MASK BIT(28) /* write operation */ +#define FXMAC_PHYMNTNC_ADDR_MASK GENMASK(27, 23) /* Address bits */ +#define FXMAC_PHYMNTNC_REG_MASK GENMASK(22, 18) /* register bits */ +#define FXMAC_PHYMNTNC_DATA_MASK GENMASK(11, 0) /* data bits */ +#define FXMAC_PHYMNTNC_PHAD_SHFT_MSK 23U /* Shift bits for PHYAD */ +#define FXMAC_PHYMNTNC_PREG_SHFT_MSK 18U /* Shift bits for PHREG */ + +/** @name transmit status register bit definitions + * @{ + */ +#define FXMAC_TXSR_HRESPNOK_MASK BIT(8) /* Transmit hresp not OK */ +#define FXMAC_TXSR_URUN_MASK BIT(6) /* Transmit underrun */ +#define FXMAC_TXSR_TXCOMPL_MASK BIT(5) /* Transmit completed OK */ +#define FXMAC_TXSR_BUFEXH_MASK BIT(4) /* Transmit buffs exhausted \ + mid frame */ +#define FXMAC_TXSR_TXGO_MASK BIT(3) /* Status of go flag */ +#define FXMAC_TXSR_RXOVR_MASK BIT(2) /* Retry limit exceeded */ +#define FXMAC_TXSR_FRAMERX_MASK BIT(1) /* Collision tx frame */ +#define FXMAC_TXSR_USEDREAD_MASK BIT(0) /* TX buffer used bit set */ + +#define FXMAC_TXSR_ERROR_MASK ((u32)FXMAC_TXSR_HRESPNOK_MASK | \ + (u32)FXMAC_TXSR_URUN_MASK | \ + (u32)FXMAC_TXSR_BUFEXH_MASK | \ + (u32)FXMAC_TXSR_RXOVR_MASK | \ + (u32)FXMAC_TXSR_FRAMERX_MASK | \ + (u32)FXMAC_TXSR_USEDREAD_MASK) + +/** + * @name Interrupt Q1 status register bit definitions + * @{ + */ +#define FXMAC_INTQ1SR_TXCOMPL_MASK BIT(7) /* Transmit completed OK */ +#define FXMAC_INTQ1SR_TXERR_MASK BIT(6) /* Transmit AMBA Error */ + +#define FXMAC_INTQ1_IXR_ALL_MASK ((u32)FXMAC_INTQ1SR_TXCOMPL_MASK | \ + (u32)FXMAC_INTQ1SR_TXERR_MASK) + +/** + * @name Interrupt QUEUE status register bit definitions + * @{ + */ +#define FXMAC_INTQUESR_TXCOMPL_MASK BIT(7) /* Transmit completed OK */ +#define FXMAC_INTQUESR_TXERR_MASK BIT(6) /* Transmit AMBA Error */ +#define FXMAC_INTQUESR_RCOMP_MASK BIT(1) +#define FXMAC_INTQUESR_RXUBR_MASK BIT(2) + +#define FXMAC_INTQUE_IXR_ALL_MASK ((u32)FXMAC_INTQUESR_TXCOMPL_MASK | \ + (u32)FXMAC_INTQUESR_TXERR_MASK) + +#define FXMAC_QUEUE_REGISTER_OFFSET(base_addr, queue_id) ((u32)base_addr + (queue_id - 1) * 4) + +/* Design Configuration Register 1 - The GEM has many parameterisation options to configure the IP during compilation stage. */ + +#define FXMAC_DESIGNCFG_DEBUG1_BUS_WIDTH_MASK GENMASK(27, 25) + +/*GEM hs mac config register bitfields*/ +#define FXMAC_GEM_HSMACSPEED_OFFSET 0 +#define FXMAC_GEM_HSMACSPEED_SIZE 3 +#define FXMAC_GEM_HSMACSPEED_MASK 0x7 + +/* Transmit buffer descriptor status words offset + * @{ + */ +#define FXMAC_BD_ADDR_OFFSET 0x00000000U /* word 0/addr of BDs */ +#define FXMAC_BD_STAT_OFFSET 4 /* word 1/status of BDs, 4 bytes */ +#define FXMAC_BD_ADDR_HI_OFFSET BIT(3) /* word 2/addr of BDs */ + +/** @name MAC address register word 1 mask + * @{ + */ +#define FXMAC_GEM_SAB_MASK GENMASK(15, 0) /* Address bits[47:32] \ + bit[31:0] are in BOTTOM */ + +/* USXGMII control register */ +#define FXMAC_GEM_USX_HS_MAC_SPEED_100M (0x0 << 14) /* 100M operation */ +#define FXMAC_GEM_USX_HS_MAC_SPEED_1G (0x1 << 14) /* 1G operation */ +#define FXMAC_GEM_USX_HS_MAC_SPEED_2_5G (0x2 << 14) /* 2.5G operation */ +#define FXMAC_GEM_USX_HS_MAC_SPEED_10G (0x4 << 14) /* 10G operation */ +#define FXMAC_GEM_USX_TX_SCR_BYPASS BIT(8) /* RX Scrambler Bypass. Set high to bypass the receive descrambler. */ +#define FXMAC_GEM_USX_RX_SCR_BYPASS BIT(9) /* TX Scrambler Bypass. Set high to bypass the transmit scrambler. */ +#define FXMAC_GEM_USX_RX_SYNC_RESET BIT(2) /* RX Reset. Set high to reset the receive datapath. When low the receive datapath is enabled. */ +#define FXMAC_GEM_USX_TX_DATAPATH_EN BIT(1) /* TX Datapath Enable. */ +#define FXMAC_GEM_USX_SIGNAL_OK BIT(0) /* Enable the USXGMII/BASE-R receive PCS. */ + +/* All PCS registers */ + +#define FXMAC_PCS_CONTROL_ENABLE_AUTO_NEG BIT(12) /* Enable auto-negotiation - when set active high, autonegotiation operation is enabled. */ + + +/* FXMAC_PCS_STATUS_OFFSET */ +#define FXMAC_PCS_STATUS_LINK_STATUS_OFFSET 2 +#define FXMAC_PCS_STATUS_LINK_STATUS BIT(FXMAC_PCS_STATUS_LINK_STATUS_OFFSET) /* Link status - indicates the status of the physical connection to the link partner. When set to logic 1 the link is up, and when set to logic 0, the link is down. */ + +/* FXMAC_PCS_AN_LP_OFFSET */ + +#define FXMAC_PCS_AN_LP_SPEED_OFFSET 10 +#define FXMAC_PCS_AN_LP_SPEED (0x3U << FXMAC_PCS_AN_LP_SPEED_OFFSET) /* SGMII 11 : Reserved 10 : 1000 Mbps 01 : 100Mbps 00 : 10 Mbps */ +#define FXMAC_PCS_AN_LP_DUPLEX_OFFSET 12 +#define FXMAC_PCS_AN_LP_DUPLEX (0x3U << FXMAC_PCS_AN_LP_DUPLEX_OFFSET) /* SGMII Bit 13: Reserved. read as 0. Bit 12 : 0 : half-duplex. 1: Full Duplex." */ +#define FXMAC_PCS_LINK_PARTNER_NEXT_PAGE_STATUS (1U<<15) /* In sgmii mode, 0 is link down . 1 is link up */ + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FXMAC_READREG32(addr, reg_offset) FtIn32(addr + (u32)reg_offset) +#define FXMAC_WRITEREG32(addr, reg_offset, reg_value) FtOut32(addr + (u32)reg_offset, (u32)reg_value) + + +#define FXMAC_SetBit32(addr, reg_offset, reg_value) FtSetBit32(addr + (u32)reg_offset, (u32)reg_value) +#define FXMAC_ClearBit32(addr, reg_offset, reg_value) FtClearBit32(addr + (u32)reg_offset, (u32)reg_value) + +/****************************************************************************/ +/** + * + * Enable interrupts specified in Mask. The corresponding interrupt for + * each bit set to 1 in Mask, will be enabled. + * + * @param instance_p is a pointer to the instance to be worked on. + * @param Mask contains a bit mask of interrupts to enable. The mask can + * be formed using a set of bitwise or'd values. + * + * @note + * The state of the transmitter and receiver are not modified by this function. + * C-style signature + * void FXMAC_INT_ENABLE(FXmac *instance_p, u32 Mask) + * + *****************************************************************************/ +#define FXMAC_INT_ENABLE(instance_p, Mask) \ + FXMAC_WRITEREG32((instance_p)->config.base_address, \ + FXMAC_IER_OFFSET, \ + ((Mask)&FXMAC_IXR_ALL_MASK)); + +/****************************************************************************/ +/** + * + * Enable interrupts specified in Mask. The corresponding interrupt for + * each bit set to 1 in Mask, will be enabled. + * + * @param instance_p is a pointer to the instance to be worked on. + * @param Mask contains a bit mask of interrupts to enable. The mask can + * be formed using a set of bitwise or'd values. + * + * @note + * The state of the transmitter and receiver are not modified by this function. + * C-style signature + * void FXMAC_INT_Q1ENABLE(FXmac *instance_p, u32 Mask) + * + *****************************************************************************/ +#define FXMAC_INT_Q1ENABLE(instance_p, Mask) \ + FXMAC_WRITEREG32((instance_p)->config.base_address, \ + FXMAC_INTQ1_IER_OFFSET, \ + ((Mask)&FXMAC_INTQ1_IXR_ALL_MASK)); + + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_intr.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_intr.c new file mode 100644 index 0000000000..08c226740c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_intr.c @@ -0,0 +1,403 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_intr.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fxmac.h" +#include "fxmac_hw.h" +#include "fassert.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + + +/** + * @name: FXmacSetHandler + * @msg: Install an asynchronous handler function for the given handler_type: + * + * @param instance_p is a pointer to the instance to be worked on. + * @param handler_type indicates what interrupt handler type is. + * FXMAC_HANDLER_DMASEND, FXMAC_HANDLER_DMARECV and + * FXMAC_HANDLER_ERROR. + * @param func_pointer is the pointer to the callback function + * @param call_back_ref is the upper layer callback reference passed back when + * when the callback function is invoked. + * + * @return {FError} FT_SUCCESS set is ok + */ +FError FXmacSetHandler(FXmac *instance_p, u32 handler_type, + void *func_pointer, void *call_back_ref) +{ + FError status; + FASSERT(instance_p != NULL); + FASSERT(func_pointer != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + status = (FError)(FT_SUCCESS); + + switch (handler_type) + { + case FXMAC_HANDLER_DMASEND: + instance_p->send_irq_handler = ((FXmacIrqHandler)(void *)func_pointer); + instance_p->send_args = call_back_ref; + break; + case FXMAC_HANDLER_DMARECV: + instance_p->recv_irq_handler = ((FXmacIrqHandler)(void *)func_pointer); + instance_p->recv_args = call_back_ref; + break; + case FXMAC_HANDLER_ERROR: + instance_p->error_irq_handler = ((FXmacErrorIrqHandler)(void *)func_pointer); + instance_p->error_args = call_back_ref; + break; + case FXMAC_HANDLER_LINKCHANGE: + instance_p->link_change_handler = ((FXmacIrqHandler)(void *)func_pointer); + instance_p->link_change_args = call_back_ref; + break; + case FXMAC_HANDLER_RESTART: + instance_p->restart_handler = ((FXmacIrqHandler)(void *)func_pointer); + instance_p->restart_args = call_back_ref; + break; + default: + status = (FError)(FXMAC_ERR_INVALID_PARAM); + break; + } + return status; +} + + +/** + * @name: FXmacIntrHandler + * @msg: 中断处理函数 + * @param {s32} vector is interrrupt num + * @param {void} *args is a arguments variables + * @return {*} + * @note 目前中断只支持单queue的情况 + */ +void FXmacIntrHandler(s32 vector, void *args) +{ + u32 reg_isr; + u32 reg_qx_isr; + u32 reg_temp; + u32 reg_ctrl; + u32 tx_queue_id; /* 0 ~ FT_XMAC_QUEUE_MAX_NUM ,Index queue number */ + u32 rx_queue_id; /* 0 ~ FT_XMAC_QUEUE_MAX_NUM ,Index queue number */ + FXmac *instance_p = (FXmac *)args; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + + tx_queue_id = instance_p->tx_bd_queue.queue_id; + rx_queue_id = instance_p->rx_bd_queue.queue_id; + FASSERT((rx_queue_id < FT_XMAC_QUEUE_MAX_NUM) && (tx_queue_id < FT_XMAC_QUEUE_MAX_NUM)) + + /* This ISR will try to handle as many interrupts as it can in a single + * call. However, in most of the places where the user's error handler + * is called, this ISR exits because it is expected that the user will + * reset the device in nearly all instances. + */ + + if ((u32)vector == instance_p->config.queue_irq_num[tx_queue_id]) + { + if (tx_queue_id == 0) + { + reg_isr = FXMAC_READREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET); + + if ((reg_isr & FXMAC_IXR_TXCOMPL_MASK) != 0x00000000U) + { + /* Clear TX status register TX complete indication but preserve + * error bits if there is any */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_TXSR_OFFSET, + ((u32)FXMAC_TXSR_TXCOMPL_MASK | + (u32)FXMAC_TXSR_USEDREAD_MASK)); + + if (instance_p->send_irq_handler) + { + /* code */ + instance_p->send_irq_handler(instance_p->send_args); + } + + /* add */ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, FXMAC_IXR_TXCOMPL_MASK); + } + + /* Transmit error conditions interrupt */ + if (((reg_isr & FXMAC_IXR_TX_ERR_MASK) != 0x00000000U) && + (!(reg_isr & FXMAC_IXR_TXCOMPL_MASK) != 0x00000000U)) + { + /* Clear TX status register */ + reg_temp = FXMAC_READREG32(instance_p->config.base_address, FXMAC_TXSR_OFFSET); + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_TXSR_OFFSET, reg_temp); + if (instance_p->error_irq_handler) + { + instance_p->error_irq_handler(instance_p->error_args, FXMAC_SEND, reg_temp); + } + /* add */ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, FXMAC_IXR_TX_ERR_MASK); + } + + /* add restart */ + if ((reg_isr & FXMAC_IXR_TXUSED_MASK) != 0x00000000U) + { + /* add */ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, FXMAC_IXR_TXUSED_MASK); + + if (instance_p->restart_handler) + { + instance_p->restart_handler(instance_p->restart_args); + } + } + + /* link chaged */ + if ((reg_isr & FXMAC_IXR_LINKCHANGE_MASK) != 0x00000000U) + { + if (instance_p->link_change_handler) + { + instance_p->link_change_handler(instance_p->link_change_args); + } + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, FXMAC_IXR_LINKCHANGE_MASK); + } + } + else /* use queue number more than 0 */ + { + reg_isr = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_INTQ1_STS_OFFSET, tx_queue_id)); + + /* Transmit Q1 complete interrupt */ + if (((reg_isr & FXMAC_INTQUESR_TXCOMPL_MASK) != 0x00000000U)) + { + /* Clear TX status register TX complete indication but preserve + * error bits if there is any */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_INTQ1_STS_OFFSET, tx_queue_id), + FXMAC_INTQUESR_TXCOMPL_MASK); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_TXSR_OFFSET, + ((u32)FXMAC_TXSR_TXCOMPL_MASK | + (u32)FXMAC_TXSR_USEDREAD_MASK)); + instance_p->send_irq_handler(instance_p->send_args); + } + + /* Transmit Q1 error conditions interrupt */ + if (((reg_isr & FXMAC_INTQ1SR_TXERR_MASK) != 0x00000000U) && + ((reg_isr & FXMAC_INTQ1SR_TXCOMPL_MASK) != 0x00000000U)) + { + /* Clear Interrupt Q1 status register */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_INTQ1_STS_OFFSET, tx_queue_id), reg_isr); + instance_p->error_irq_handler(instance_p->error_args, FXMAC_SEND, + reg_isr); + } + } + } + + if ((u32)vector == instance_p->config.queue_irq_num[rx_queue_id]) + { + if (rx_queue_id == 0) + { + reg_isr = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_ISR_OFFSET); + + /* Receive complete interrupt */ + if ((reg_isr & FXMAC_IXR_RXCOMPL_MASK) != 0x00000000U) + { + /* Clear RX status register RX complete indication but preserve + * error bits if there is any */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_RXSR_OFFSET, + ((u32)FXMAC_RXSR_FRAMERX_MASK | + (u32)FXMAC_RXSR_BUFFNA_MASK)); + instance_p->recv_irq_handler(instance_p->recv_args); + + /* add */ + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, FXMAC_IXR_RXCOMPL_MASK); + + } + + /* Receive error conditions interrupt */ + if ((reg_isr & FXMAC_IXR_RX_ERR_MASK) != 0x00000000U) + { + /* Clear RX status register */ + reg_temp = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_RXSR_OFFSET); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_RXSR_OFFSET, reg_temp); + + /* Fix for CR # 692702. Write to bit 18 of net_ctrl + * register to flush a packet out of Rx SRAM upon + * an error for receive buffer not available. */ + if ((reg_isr & FXMAC_IXR_RXUSED_MASK) != 0x00000000U) + { + reg_ctrl = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + reg_ctrl |= (u32)FXMAC_NWCTRL_FLUSH_DPRAM_MASK; + + /* add */ + reg_ctrl &= (u32)(~FXMAC_NWCTRL_RXEN_MASK); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, reg_ctrl); + + /* add */ + reg_ctrl |= (u32)FXMAC_NWCTRL_RXEN_MASK; + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, reg_ctrl); + } + + /* add */ + if ((reg_isr & FXMAC_IXR_RXOVR_MASK) != 0x00000000U) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, FXMAC_IXR_RXOVR_MASK); + } + + /* add */ + if ((reg_isr & FXMAC_IXR_HRESPNOK_MASK) != 0x00000000U) + { + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_ISR_OFFSET, FXMAC_IXR_HRESPNOK_MASK); + } + + if (reg_temp != 0) + { + instance_p->error_irq_handler(instance_p->error_args, + FXMAC_RECV, reg_temp); + } + } + } + else /* use queue number more than 0 */ + { + reg_isr = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_INTQ1_STS_OFFSET, rx_queue_id)); + + /* Receive complete interrupt */ + if ((reg_isr & FXMAC_INTQUESR_RCOMP_MASK) != 0x00000000U) + { + /* Clear RX status register RX complete indication but preserve + * error bits if there is any */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_INTQ1_STS_OFFSET, rx_queue_id), + FXMAC_INTQUESR_RCOMP_MASK); + instance_p->recv_irq_handler(instance_p->recv_args); + } + + /* Receive error conditions interrupt */ + if ((reg_isr & FXMAC_IXR_RX_ERR_MASK) != 0x00000000U) + { + + reg_ctrl = + FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + reg_ctrl &= ~(u32)FXMAC_NWCTRL_RXEN_MASK; + + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, reg_ctrl); + + /* Clear RX status register */ + reg_temp = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_RXSR_OFFSET); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_RXSR_OFFSET, reg_temp); + + /* Fix for CR # 692702. Write to bit 18 of net_ctrl + * register to flush a packet out of Rx SRAM upon + * an error for receive buffer not available. */ + if ((reg_isr & FXMAC_IXR_RXUSED_MASK) != 0x00000000U) + { + reg_ctrl = + FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + reg_ctrl |= (u32)FXMAC_NWCTRL_FLUSH_DPRAM_MASK; + + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, reg_ctrl); + } + + /* Clear RX status register RX complete indication but preserve + * error bits if there is any */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_QUEUE_REGISTER_OFFSET(FXMAC_INTQ1_STS_OFFSET, rx_queue_id), + FXMAC_INTQUESR_RXUBR_MASK); + instance_p->recv_irq_handler(instance_p->recv_args); + + if (reg_temp != 0) + { + instance_p->error_irq_handler(instance_p->error_args, + FXMAC_RECV, reg_temp); + } + } + } + } + +} + + +/** + * @name: FXmacQueueIrqDisable + * @msg: Disable queue irq + * @param {FXmac} *instance_p a pointer to the instance to be worked on. + * @param {u32} queue_num queue number + * @param {u32} mask is interrupt disable value mask + */ +void FXmacQueueIrqDisable(FXmac *instance_p, u32 queue_num, u32 mask) +{ + FXmacConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + FASSERT(instance_p->config.max_queue_num > queue_num); + config_p = &instance_p->config; + + if (queue_num == 0) + { + FXMAC_WRITEREG32(config_p->base_address, FXMAC_IDR_OFFSET, mask & FXMAC_IXR_ALL_MASK); + } + else + { + FXMAC_WRITEREG32(config_p->base_address, FXMAC_INTQX_IDR_SIZE_OFFSET(queue_num), mask & FXMAC_IXR_ALL_MASK); + } +} + +/** + * @name: FXmacQueueIrqEnable + * @msg: Enable queue irq + * @param {FXmac} *instance_p a pointer to the instance to be worked on. + * @param {u32} queue_num is queue number + * @param {u32} mask is interrupt Enable value mask + */ +void FXmacQueueIrqEnable(FXmac *instance_p, u32 queue_num, u32 mask) +{ + FXmacConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + FASSERT(instance_p->config.max_queue_num > queue_num); + config_p = &instance_p->config; + + if (queue_num == 0) + { + FXMAC_WRITEREG32(config_p->base_address, FXMAC_IER_OFFSET, mask & FXMAC_IXR_ALL_MASK); + } + else + { + FXMAC_WRITEREG32(config_p->base_address, FXMAC_INTQX_IER_SIZE_OFFSET(queue_num), mask & FXMAC_IXR_ALL_MASK); + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_options.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_options.c new file mode 100644 index 0000000000..c4e4b0d570 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_options.c @@ -0,0 +1,745 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_options.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fxmac_hw.h" +#include "fxmac.h" +#include "fassert.h" + + +/** + * @name: FXmacSetMacAddress + * + * @msg: Set the MAC address for this driver/device. The address is a 48-bit value. + * The device must be stopped before calling this function. + * + * @param {FXmac *}: instance_p is a pointer to the instance to be worked on. + * @param address_ptr is a pointer to a 6-byte MAC address. + * @param index plus 1 is a index to which MAC (1-4) address. + * + * @return + * - FT_SUCCESS if the MAC address was set successfully + * - FXMAC_ERR_MAC_IS_PROCESSING if the device has not yet been stopped + * + */ +FError FXmacSetMacAddress(FXmac *instance_p, u8 *address_ptr, u8 index) +{ + u32 mac_addr; + u8 *aptr = (u8 *)(void *)address_ptr; + u8 index_loc = index; + FError status; + FASSERT(instance_p != NULL); + FASSERT(aptr != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + FASSERT((index_loc < (u8)FXMAC_MAX_MAC_ADDR)); + + /* Be sure device has been stopped */ + if (instance_p->is_started == (u32)FT_COMPONENT_IS_STARTED) + { + status = (FError)(FXMAC_ERR_MAC_IS_PROCESSING); + } + else + { + /* Set the MAC bits [31:0] in BOT */ + mac_addr = *(aptr); + mac_addr |= ((u32)(*(aptr + 1)) << 8U); + mac_addr |= ((u32)(*(aptr + 2)) << 16U); + mac_addr |= ((u32)(*(aptr + 3)) << 24U); + FXMAC_WRITEREG32(instance_p->config.base_address, + ((u32)FXMAC_GEM_SA1B + ((u32)index_loc * (u32)8)), mac_addr); + + /* There are reserved bits in TOP so don't affect them */ + mac_addr = FXMAC_READREG32(instance_p->config.base_address, + ((u32)FXMAC_GEM_SA1T + ((u32)index_loc * (u32)8))); + + mac_addr &= (u32)(~FXMAC_GEM_SAB_MASK); + + /* Set MAC bits [47:32] in TOP */ + mac_addr |= (u32)(*(aptr + 4)); + mac_addr |= (u32)(*(aptr + 5)) << 8U; + + FXMAC_WRITEREG32(instance_p->config.base_address, + ((u32)FXMAC_GEM_SA1T + ((u32)index_loc * (u32)8)), mac_addr); + + status = (FError)(FT_SUCCESS); + } + return status; +} + +/** + * @name: FXmacGetMacAddress + * @msg: Set the MAC address according to index + * @param {FXmac} *mac is a pointer to the instance to be worked on. + * @param {void} *address_ptr is an output parameter, and is a pointer to a buffer into + * which the current MAC address will be copied. + * @param {u8} index is a index to which MAC (0-3) address. + */ +void FXmacGetMacAddress(FXmac *instance_p, u8 *address_ptr, u8 index) +{ + u32 reg_value; + u8 *ptr = (u8 *)address_ptr; + FASSERT(instance_p != NULL); + FASSERT(ptr != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT((index < FXMAC_MAX_MAC_ADDR)); + + reg_value = FXMAC_READREG32(instance_p->config.base_address, FXMAC_GEM_SA1B + ((u32)index * (u32)8)); + *ptr = (u8)reg_value; + *(ptr + 1) = (u8)(reg_value >> 8U); + *(ptr + 2) = (u8)(reg_value >> 16U); + *(ptr + 3) = (u8)(reg_value >> 24U); + + reg_value = FXMAC_READREG32(instance_p->config.base_address, FXMAC_GEM_SA1T + ((u32)index * (u32)8)); + *(ptr + 4) = (u8)(reg_value); + *(ptr + 5) = (u8)(reg_value >> 8U); +} + + +/** + * Set the Type ID match for this driver/device. The register is a 32-bit + * value. The device must be stopped before calling this function. + * + * @param instance_p is a pointer to the instance to be worked on. + * @param id_check is type ID to be configured. + * @param index plus 1 is a index to which Type ID (1-4). + * + * @return + * - FT_SUCCESS if the MAC address was set successfully + * - FXMAC_ERR_MAC_IS_PROCESSING if the device has not yet been stopped + * + */ +FError FXmacSetTypeIdCheck(FXmac *instance_p, u32 id_check, u8 index) +{ + u8 index_loc = index; + FError status; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT((index_loc < (u8)FXMAC_MAX_TYPE_ID)); + + /* Be sure device has been stopped */ + if (instance_p->is_started == (u32)FT_COMPONENT_IS_STARTED) + { + status = (FError)(FXMAC_ERR_MAC_IS_PROCESSING); + } + else + { + + /* Set the ID bits in MATCHx register */ + FXMAC_WRITEREG32(instance_p->config.base_address, + ((u32)FXMAC_MATCH1_OFFSET + ((u32)index_loc * (u32)4)), id_check); + + status = (FError)(FT_SUCCESS); + } + return status; +} + + +/** + * Set options for the driver/device. The driver should be stopped with + * FXmacStop() before changing options. + * + * @param instance_p is a pointer to the instance to be worked on. + * @param options are the options to set. Multiple options can be set by OR'ing + * FXMAC_*_OPTIONS constants together. options not specified are not + * affected. + * @param queue_num is the Buffer Queue Index ,Used for jumbo frames only + * + * @return + * - FT_SUCCESS if the options were set successfully + * - FXMAC_ERR_MAC_IS_PROCESSING if the device has not yet been stopped + * + * @note + * See fxmac.h for a description of the available options. + * + */ +FError FXmacSetOptions(FXmac *instance_p, u32 options, u32 queue_num) +{ + u32 reg; /* Generic register contents */ + u32 reg_netcfg; /* Reflects original contents of NET_CONFIG */ + u32 reg_new_netcfg; /* Reflects new contents of NET_CONFIG */ + FError status; + FXmacConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + /* Be sure device has been stopped */ + if (instance_p->is_started == (u32)FT_COMPONENT_IS_STARTED) + { + status = (FError)(FXMAC_ERR_MAC_IS_PROCESSING); + } + else + { + + /* Many of these options will change the NET_CONFIG registers. + * To reduce the amount of IO to the device, group these options here + * and change them all at once. + */ + + /* Grab current register contents */ + reg_netcfg = FXMAC_READREG32(config_p->base_address, + FXMAC_NWCFG_OFFSET); + reg_new_netcfg = reg_netcfg; + + /* + * It is configured to max 1536. + */ + if ((options & FXMAC_FRAME1536_OPTION) != 0x00000000U) + { + reg_new_netcfg |= (FXMAC_NWCFG_1536RXEN_MASK); + } + + /* Turn on VLAN packet only, only VLAN tagged will be accepted */ + if ((options & FXMAC_VLAN_OPTION) != 0x00000000U) + { + reg_new_netcfg |= FXMAC_NWCFG_NVLANDISC_MASK; + } + + /* Turn on FCS stripping on receive packets */ + if ((options & FXMAC_FCS_STRIP_OPTION) != 0x00000000U) + { + reg_new_netcfg |= FXMAC_NWCFG_FCSREM_MASK; + } + + /* Turn on length/type field checking on receive packets */ + if ((options & FXMAC_LENTYPE_ERR_OPTION) != 0x00000000U) + { + reg_new_netcfg |= FXMAC_NWCFG_LENERRDSCRD_MASK; + } + + /* Turn on flow control */ + if ((options & FXMAC_FLOW_CONTROL_OPTION) != 0x00000000U) + { + reg_new_netcfg |= FXMAC_NWCFG_PAUSEEN_MASK; + } + + /* Turn on promiscuous frame filtering (all frames are received) */ + if ((options & FXMAC_PROMISC_OPTION) != 0x00000000U) + { + reg_new_netcfg |= FXMAC_NWCFG_COPYALLEN_MASK; + } + + /* Allow broadcast address reception */ + if ((options & FXMAC_BROADCAST_OPTION) != 0x00000000U) + { + reg_new_netcfg &= (u32)(~FXMAC_NWCFG_BCASTDI_MASK); + } + + /* Allow multicast address filtering */ + if ((options & FXMAC_MULTICAST_OPTION) != 0x00000000U) + { + reg_new_netcfg |= FXMAC_NWCFG_MCASTHASHEN_MASK; + } + + /* enable RX checksum offload */ + if ((options & FXMAC_RX_CHKSUM_ENABLE_OPTION) != 0x00000000U) + { + reg_new_netcfg |= FXMAC_NWCFG_RXCHKSUMEN_MASK; + } + + /* Enable jumbo frames */ + if ((options & FXMAC_JUMBO_ENABLE_OPTION) != 0x00000000U) + { + instance_p->max_mtu_size = FXMAC_MTU_JUMBO; + instance_p->max_frame_size = FXMAC_MTU_JUMBO + + FXMAC_HDR_SIZE + FXMAC_TRL_SIZE; + + reg_new_netcfg |= FXMAC_NWCFG_JUMBO_MASK; + FXMAC_WRITEREG32(config_p->base_address, + FXMAC_JUMBOMAXLEN_OFFSET, FXMAC_MTU_JUMBO); + + if (queue_num == 0) + { + u32 rx_buf_size = 0; + reg = FXMAC_READREG32(config_p->base_address, + FXMAC_DMACR_OFFSET); + reg &= ~FXMAC_DMACR_RXBUF_MASK; + + rx_buf_size = ((u32)instance_p->max_mtu_size / (u32)FXMAC_RX_BUF_UNIT); + rx_buf_size += (((u32)instance_p->max_mtu_size % (u32)FXMAC_RX_BUF_UNIT) != (u32)0) ? 1U : 0U; + + reg |= ((rx_buf_size << (u32)(FXMAC_DMACR_RXBUF_SHIFT)) & + (u32)(FXMAC_DMACR_RXBUF_MASK)); + FXMAC_WRITEREG32(config_p->base_address, + FXMAC_DMACR_OFFSET, reg); + } + else if (queue_num < instance_p->config.max_queue_num) + { + u32 rx_buf_size = 0; + rx_buf_size = ((u32)instance_p->max_mtu_size / (u32)FXMAC_RX_BUF_UNIT); + rx_buf_size += (((u32)instance_p->max_mtu_size % (u32)FXMAC_RX_BUF_UNIT) != (u32)0) ? 1U : 0U; + + FXMAC_WRITEREG32(config_p->base_address, FXMAC_RXBUFQX_SIZE_OFFSET(queue_num), rx_buf_size & FXMAC_RXBUFQX_SIZE_MASK); + } + } + + if (((options & FXMAC_SGMII_ENABLE_OPTION) != 0x00000000U)) + { + reg_new_netcfg |= (FXMAC_NWCFG_SGMIIEN_MASK | + FXMAC_NWCFG_PCSSEL_MASK); + } + + if ((options & FXMAC_LOOPBACK_NO_MII_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + reg |= FXMAC_NWCFG_LOOPBACK_LOCAL_MASK; + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, reg); + } + + if ((options & FXMAC_LOOPBACK_USXGMII_OPTION) != 0x00000000U) + { + FXMAC_WRITEREG32(config_p->base_address, FXMAC_TEST_CONTROL_OFFSET, 2); + } + + /* Officially change the NET_CONFIG registers if it needs to be + * modified. + */ + if (reg_netcfg != reg_new_netcfg) + { + FXMAC_WRITEREG32(config_p->base_address, + FXMAC_NWCFG_OFFSET, reg_new_netcfg); + } + + /* Enable TX checksum offload */ + if ((options & FXMAC_TX_CHKSUM_ENABLE_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(config_p->base_address, + FXMAC_DMACR_OFFSET); + reg |= FXMAC_DMACR_TCPCKSUM_MASK; + FXMAC_WRITEREG32(config_p->base_address, + FXMAC_DMACR_OFFSET, reg); + } + + /* Enable transmitter */ + if ((options & FXMAC_TRANSMITTER_ENABLE_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(config_p->base_address, + FXMAC_NWCTRL_OFFSET); + reg |= FXMAC_NWCTRL_TXEN_MASK; + FXMAC_WRITEREG32(config_p->base_address, + FXMAC_NWCTRL_OFFSET, reg); + } + + /* Enable receiver */ + if ((options & FXMAC_RECEIVER_ENABLE_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(config_p->base_address, + FXMAC_NWCTRL_OFFSET); + reg |= FXMAC_NWCTRL_RXEN_MASK; + FXMAC_WRITEREG32(config_p->base_address, + FXMAC_NWCTRL_OFFSET, reg); + } + + /* The remaining options not handled here are managed elsewhere in the + * driver. No register modifications are needed at this time. Reflecting + * the option in instance_p->options is good enough for now. + */ + + /* Set options word to its new value */ + instance_p->options |= options; + + status = (FError)(FT_SUCCESS); + } + return status; +} + + +/** + * Clear options for the driver/device + * + * @param instance_p is a pointer to the instance to be worked on. + * @param options are the options to clear. Multiple options can be cleared by + * OR'ing FXMAC_*_options constants together. options not specified + * are not affected. + * @param queue_num is the Buffer Queue Index ,Used for jumbo frames only + * @return + * - FT_SUCCESS if the options were set successfully + * - FXMAC_ERR_MAC_IS_PROCESSING if the device has not yet been stopped + * + * @note + * See fxmac.h for a description of the available options. + */ +FError FXmacClearOptions(FXmac *instance_p, u32 options, u32 queue_num) +{ + u32 reg; /* Generic */ + u32 reg_net_cfg; /* Reflects original contents of NET_CONFIG */ + u32 reg_new_net_cfg; /* Reflects new contents of NET_CONFIG */ + FError status; + FXmacConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + /* Be sure device has been stopped */ + if (instance_p->is_started == (u32)FT_COMPONENT_IS_STARTED) + { + status = (FError)(FXMAC_ERR_MAC_IS_PROCESSING); + } + else + { + /* Many of these options will change the NET_CONFIG registers. + * To reduce the amount of IO to the device, group these options here + * and change them all at once. + */ + /* Grab current register contents */ + reg_net_cfg = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCFG_OFFSET); + reg_new_net_cfg = reg_net_cfg; + /* There is only RX configuration!? + * It is configured in two different length, up to 1536 and 10240 bytes + */ + if ((options & FXMAC_FRAME1536_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_1536RXEN_MASK); + } + + /* Turn off VLAN packet only */ + if ((options & FXMAC_VLAN_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_NVLANDISC_MASK); + } + + /* Turn off FCS stripping on receive packets */ + if ((options & FXMAC_FCS_STRIP_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_FCSREM_MASK); + } + + /* Turn off length/type field checking on receive packets */ + if ((options & FXMAC_LENTYPE_ERR_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_LENERRDSCRD_MASK); + } + + /* Turn off flow control */ + if ((options & FXMAC_FLOW_CONTROL_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_PAUSEEN_MASK); + } + + /* Turn off promiscuous frame filtering (all frames are received) */ + if ((options & FXMAC_PROMISC_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_COPYALLEN_MASK); + } + + /* Disallow broadcast address filtering => broadcast reception */ + if ((options & FXMAC_BROADCAST_OPTION) != 0x00000000U) + { + reg_new_net_cfg |= FXMAC_NWCFG_BCASTDI_MASK; + } + + /* Disallow multicast address filtering */ + if ((options & FXMAC_MULTICAST_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_MCASTHASHEN_MASK); + } + + /* Disable RX checksum offload */ + if ((options & FXMAC_RX_CHKSUM_ENABLE_OPTION) != 0x00000000U) + { + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_RXCHKSUMEN_MASK); + } + + /* Disable jumbo frames */ + if (((options & FXMAC_JUMBO_ENABLE_OPTION) != 0x00000000U)) /* 恢复之前buffer 容量 */ + { + + instance_p->max_mtu_size = FXMAC_MTU; + instance_p->max_frame_size = FXMAC_MTU + FXMAC_HDR_SIZE + FXMAC_TRL_SIZE; + + reg_new_net_cfg &= (u32)(~FXMAC_NWCFG_JUMBO_MASK); + reg = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_DMACR_OFFSET); + reg &= ~FXMAC_DMACR_RXBUF_MASK; + + if (queue_num == 0) + { + u32 rx_buf_size = 0; + + reg = FXMAC_READREG32(instance_p->config.base_address, FXMAC_DMACR_OFFSET); + reg &= ~FXMAC_DMACR_RXBUF_MASK; + + rx_buf_size = ((u32)instance_p->max_mtu_size / (u32)FXMAC_RX_BUF_UNIT); + rx_buf_size += ((u32)instance_p->max_mtu_size % ((u32)FXMAC_RX_BUF_UNIT) != (u32)0) ? 1U : 0U; + + reg |= ((rx_buf_size << (u32)(FXMAC_DMACR_RXBUF_SHIFT)) & (u32)(FXMAC_DMACR_RXBUF_MASK)); + + FXMAC_WRITEREG32(instance_p->config.base_address, FXMAC_DMACR_OFFSET, reg); + } + else if (queue_num < instance_p->config.max_queue_num) + { + u32 rx_buf_size = 0; + rx_buf_size = ((u32)instance_p->max_mtu_size / (u32)FXMAC_RX_BUF_UNIT); + rx_buf_size += (((u32)instance_p->max_mtu_size % (u32)FXMAC_RX_BUF_UNIT) != (u32)0) ? 1U : 0U; + + FXMAC_WRITEREG32(config_p->base_address, FXMAC_RXBUFQX_SIZE_OFFSET(queue_num), rx_buf_size & FXMAC_RXBUFQX_SIZE_MASK); + } + } + + if (((options & FXMAC_SGMII_ENABLE_OPTION) != 0x00000000U)) + { + reg_new_net_cfg &= (u32)(~(FXMAC_NWCFG_SGMIIEN_MASK | + FXMAC_NWCFG_PCSSEL_MASK)); + } + + if ((options & FXMAC_LOOPBACK_NO_MII_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET); + reg &= (u32)(~FXMAC_NWCFG_LOOPBACK_LOCAL_MASK); + FXMAC_WRITEREG32(config_p->base_address, FXMAC_NWCTRL_OFFSET, reg); + } + + if ((options & FXMAC_LOOPBACK_USXGMII_OPTION) != 0x00000000U) + { + FXMAC_WRITEREG32(config_p->base_address, FXMAC_TEST_CONTROL_OFFSET, (FXMAC_READREG32(config_p->base_address, FXMAC_TEST_CONTROL_OFFSET) & ~2)); + } + + /* Officially change the NET_CONFIG registers if it needs to be + * modified. + */ + if (reg_net_cfg != reg_new_net_cfg) + { + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCFG_OFFSET, reg_new_net_cfg); + } + + /* Disable TX checksum offload */ + if ((options & FXMAC_TX_CHKSUM_ENABLE_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_DMACR_OFFSET); + reg &= (u32)(~FXMAC_DMACR_TCPCKSUM_MASK); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_DMACR_OFFSET, reg); + } + + /* Disable transmitter */ + if ((options & FXMAC_TRANSMITTER_ENABLE_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + reg &= (u32)(~FXMAC_NWCTRL_TXEN_MASK); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, reg); + } + + /* Disable receiver */ + if ((options & FXMAC_RECEIVER_ENABLE_OPTION) != 0x00000000U) + { + reg = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET); + reg &= (u32)(~FXMAC_NWCTRL_RXEN_MASK); + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_NWCTRL_OFFSET, reg); + } + + /* The remaining options not handled here are managed elsewhere in the + * driver. No register modifications are needed at this time. Reflecting + * option in instance_p->options is good enough for now. + */ + + /* Set options word to its new value */ + instance_p->options &= ~options; + + status = (FError)(FT_SUCCESS); + } + return status; +} + + +/** + * Clear the Hash registers for the mac address pointed by address_ptr. + * + * @param instance_p is a pointer to the instance to be worked on. + * + */ +void FXmacClearHash(FXmac *instance_p) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_HASHL_OFFSET, 0x0U); + + /* write bits [63:32] in TOP */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_HASHH_OFFSET, 0x0U); +} + + +/** + * Write data to the specified PHY register. The Ethernet driver does not + * require the device to be stopped before writing to the PHY. Although it is + * probably a good idea to stop the device, it is the responsibility of the + * application to deem this necessary. The MAC provides the driver with the + * ability to talk to a PHY that adheres to the Media Independent Interface + * (MII) as defined in the IEEE 802.3 standard. + * + * Prior to PHY access with this function, the user should have setup the MDIO + * clock with FXmacSetMdioDivisor(). + * + * @param instance_p is a pointer to the FXmac instance to be worked on. + * @param phy_address is the address of the PHY to be written (supports multiple + * PHYs) + * @param register_num is the register number, 0-31, of the specific PHY register + * to write + * @param phy_data is the 16-bit value that will be written to the register + * + * @return + * + * - FT_SUCCESS if the PHY was written to successfully. Since there is no error + * status from the MAC on a write, the user should read the PHY to verify the + * write was successful. + * - FXMAC_ERR_PHY_BUSY if there is another PHY operation in progress + * + * @note + * + * This function is not thread-safe. The user must provide mutually exclusive + * access to this function if there are to be multiple threads that can call it. + * + * There is the possibility that this function will not return if the hardware + * is broken (i.e., it never sets the status bit indicating that the write is + * done). If this is of concern to the user, the user should provide a mechanism + * suitable to their needs for recovery. + * + * For the duration of this function, all host interface reads and writes are + * blocked to the current FXmac instance. + * + ******************************************************************************/ +FError FXmacPhyWrite(FXmac *instance_p, u32 phy_address, + u32 register_num, u16 phy_data) +{ + u32 mgtcr; + volatile u32 ipisr; + u32 ip_write_temp; + FError status; + + FASSERT(instance_p != NULL); + + /* Make sure no other PHY operation is currently in progress */ + if ((!(FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWSR_OFFSET) & + FXMAC_NWSR_MDIOIDLE_MASK)) == TRUE) + { + status = (FError)(FXMAC_ERR_PHY_BUSY); + } + else + { + /* Construct mgtcr mask for the operation */ + mgtcr = FXMAC_PHYMNTNC_OP_MASK | FXMAC_PHYMNTNC_OP_W_MASK | + (phy_address << FXMAC_PHYMNTNC_PHAD_SHFT_MSK) | + (register_num << FXMAC_PHYMNTNC_PREG_SHFT_MSK) | (u32)phy_data; + + /* Write mgtcr and wait for completion */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_PHYMNTNC_OFFSET, mgtcr); + + do + { + ipisr = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWSR_OFFSET); + ip_write_temp = ipisr; + } + while ((ip_write_temp & FXMAC_NWSR_MDIOIDLE_MASK) == 0x00000000U); + + status = (FError)(FT_SUCCESS); + } + return status; +} + + +/** + * Read the current value of the PHY register indicated by the phy_address and + * the register_num parameters. The MAC provides the driver with the ability to + * talk to a PHY that adheres to the Media Independent Interface (MII) as + * defined in the IEEE 802.3 standard. + * + * + * @param instance_p is a pointer to the FXmac instance to be worked on. + * @param phy_address is the address of the PHY to be read (supports multiple + * PHYs) + * @param register_num is the register number, 0-31, of the specific PHY register + * to read + * @param phydat_aptr is an output parameter, and points to a 16-bit buffer into + * which the current value of the register will be copied. + * + * @return + * + * - FT_SUCCESS if the PHY was read from successfully + * - FXMAC_ERR_PHY_BUSY if there is another PHY operation in progress + * + * @note + * + * This function is not thread-safe. The user must provide mutually exclusive + * access to this function if there are to be multiple threads that can call it. + * + * There is the possibility that this function will not return if the hardware + * is broken (i.e., it never sets the status bit indicating that the read is + * done). If this is of concern to the user, the user should provide a mechanism + * suitable to their needs for recovery. + * + * For the duration of this function, all host interface reads and writes are + * blocked to the current FXmac instance. + * + ******************************************************************************/ +FError FXmacPhyRead(FXmac *instance_p, u32 phy_address, + u32 register_num, u16 *phydat_aptr) +{ + u32 mgtcr; + volatile u32 ipisr; + u32 IpReadTemp; + FError status; + + FASSERT(instance_p != NULL); + + /* Make sure no other PHY operation is currently in progress */ + if ((!(FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWSR_OFFSET) & + FXMAC_NWSR_MDIOIDLE_MASK)) == TRUE) + { + status = (FError)(FXMAC_ERR_PHY_BUSY); + } + else + { + /* Construct mgtcr mask for the operation */ + mgtcr = FXMAC_PHYMNTNC_OP_MASK | FXMAC_PHYMNTNC_OP_R_MASK | + (phy_address << FXMAC_PHYMNTNC_PHAD_SHFT_MSK) | + (register_num << FXMAC_PHYMNTNC_PREG_SHFT_MSK); + + /* Write mgtcr and wait for completion */ + FXMAC_WRITEREG32(instance_p->config.base_address, + FXMAC_PHYMNTNC_OFFSET, mgtcr); + + do + { + ipisr = FXMAC_READREG32(instance_p->config.base_address, + FXMAC_NWSR_OFFSET); + IpReadTemp = ipisr; + } + while ((IpReadTemp & FXMAC_NWSR_MDIOIDLE_MASK) == 0x00000000U); + + /* Read data */ + *phydat_aptr = (u16)FXMAC_READREG32(instance_p->config.base_address, + FXMAC_PHYMNTNC_OFFSET); + status = (FError)(FT_SUCCESS); + } + return status; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_phy.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_phy.c new file mode 100644 index 0000000000..4af6752555 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_phy.c @@ -0,0 +1,371 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_phy.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fxmac.h" +#include "eth_ieee_reg.h" +#include "fdebug.h" + +#if defined(CONFIG_FXMAC_PHY_YT) + #include "phy_yt.h" +#endif + + +#define FXMAC_DEBUG_TAG "FXMAC_PHY" +#define FXMAC_ERROR(format, ...) FT_DEBUG_PRINT_E(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FXMAC_INFO(format, ...) FT_DEBUG_PRINT_I(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FXMAC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FXMAC_WARN(format, ...) FT_DEBUG_PRINT_W(FXMAC_DEBUG_TAG, format, ##__VA_ARGS__) + +static FXmac *instance_b; +static u32 phy_addr_b; + +static FError FXmacDetect(FXmac *instance_p, u32 *phy_addr_p) +{ + u32 phy_addr = 0, i = 0, index; + u16 phy_reg = 0, phy_id1_reg, phy_id2_reg; + FError ret; + instance_b = instance_p; + + for (phy_addr = 0; phy_addr < FT_XMAC_PHY_MAX_NUM; phy_addr++) + { + ret = FXmacPhyRead(instance_p, phy_addr, PHY_STATUS_REG_OFFSET, &phy_reg); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s, PHY operation is busy", __func__); + return ret; + } + FXMAC_INFO("PHY_STATUS_REG_OFFSET is %x \r\n", phy_reg); + if (phy_reg != 0xffff) + { + ret = FXmacPhyRead(instance_p, phy_addr, PHY_IDENTIFIER_1_REG, &phy_id1_reg); + ret |= FXmacPhyRead(instance_p, phy_addr, PHY_IDENTIFIER_2_REG, &phy_id2_reg); + FXMAC_INFO("phy_id1_reg is 0x%x \r\n", phy_id1_reg); + FXMAC_INFO("phy_id2_reg is 0x%x \r\n", phy_id2_reg); + if ((ret == FT_SUCCESS) && (phy_id2_reg != 0) && (phy_id1_reg != 0xffff) && (phy_id1_reg != 0xffff)) + { + *phy_addr_p = phy_addr; + phy_addr_b = phy_addr; + FXMAC_INFO("phy_addr is 0x%x \r\n", phy_addr); + return FT_SUCCESS; + } + } + } + + return FT_SUCCESS; +} + +static FError FXmacGetIeeePhySpeed(FXmac *instance_p, u32 phy_addr) +{ + u16 temp, temp2; + u16 control; + u16 status; + u16 partner_capabilities; + u32 negotitation_timeout_cnt = 0; + FError ret; + volatile s32 wait; + + FXMAC_INFO("Start PHY autonegotiation "); + + ret = FXmacPhyRead(instance_p, phy_addr, PHY_CONTROL_REG_OFFSET, &control); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_CONTROL_REG_OFFSET is error", __func__, __LINE__); + return ret; + } + control |= PHY_CONTROL_RESET_MASK; + + ret = FXmacPhyWrite(instance_p, phy_addr, PHY_CONTROL_REG_OFFSET, control); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,write PHY_CONTROL_REG_OFFSET is error", __func__, __LINE__); + return ret; + } + for (wait = 0; wait < 100000; wait++) + ; + FXMAC_INFO(" PHY reset end "); + ret = FXmacPhyRead(instance_p, phy_addr, PHY_CONTROL_REG_OFFSET, &control); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_CONTROL_REG_OFFSET is error", __func__, __LINE__); + return ret; + } + + control |= PHY_CONTROL_AUTONEGOTIATE_ENABLE; + control |= PHY_CONTROL_AUTONEGOTIATE_RESTART; + ret = FXmacPhyWrite(instance_p, phy_addr, PHY_CONTROL_REG_OFFSET, control); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,write PHY_CONTROL_REG_OFFSET is error", __func__, __LINE__); + return ret; + } + + FXMAC_INFO("Waiting for PHY to complete autonegotiation."); + + ret = FXmacPhyRead(instance_p, phy_addr, PHY_STATUS_REG_OFFSET, &status); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_CONTROL_REG_OFFSET is error", __func__, __LINE__); + return ret; + } + + + while (!(status & PHY_STATUS_AUTONEGOTIATE_COMPLETE)) + { + for (wait = 0; wait < 1000000; wait++) + ; + ret = FXmacPhyRead(instance_p, phy_addr, PHY_STATUS_REG_OFFSET, &status); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_STATUS_REG_OFFSET is error", __func__, __LINE__); + return ret; + } + + + if (negotitation_timeout_cnt++ >= 0xfff) + { + FXMAC_ERROR("autonegotiation is error "); + return FXMAC_PHY_AUTO_AUTONEGOTIATION_FAILED; + } + } + FXMAC_INFO("autonegotiation complete "); + + ret = FXmacPhyRead(instance_p, phy_addr, PHY_SPECIFIC_STATUS_REG, &temp); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_SPECIFIC_STATUS_REG is error", __func__, __LINE__); + return ret; + } + + FXMAC_INFO("temp is %x \r\n", temp); + ret = FXmacPhyRead(instance_p, phy_addr, PHY_STATUS_REG_OFFSET, &temp2); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_STATUS_REG_OFFSET is error", __func__, __LINE__); + return ret; + } + + FXMAC_INFO("temp2 is %x \r\n", temp2); + + if (temp & (1 << 13)) + { + FXMAC_INFO("duplex is full \r\n"); + instance_p->config.duplex = 1; + } + else + { + FXMAC_INFO("duplex is half \r\n"); + instance_p->config.duplex = 0; + } + + if ((temp & 0xC000) == PHY_SPECIFIC_STATUS_SPEED_1000M) + { + FXMAC_INFO("speed is 1000\r\n"); + instance_p->config.speed = 1000; + } + else if ((temp & 0xC000) == PHY_SPECIFIC_STATUS_SPEED_100M) + { + FXMAC_INFO("speed is 100\r\n"); + instance_p->config.speed = 100; + } + else + { + FXMAC_INFO("speed is 10\r\n"); + instance_p->config.speed = 10; + } + + return FT_SUCCESS; +} + +void FxmaxLinkupCheck(void) +{ + u16 temp; + FXmacPhyRead(instance_b, phy_addr_b, PHY_SPECIFIC_STATUS_REG, &temp); + FXMAC_INFO("0x17 value is %x \r\n", temp); + FXMAC_INFO("linkup status is %x \r\n", temp & (1 << 10)); +} + + +static FError FXmacConfigureIeeePhySpeed(FXmac *instance_p, u32 phy_addr, u32 speed, u32 duplex_mode) +{ + u16 control; + u16 autonereg; + volatile s32 wait; + FError ret; + u16 specific_reg = 0; + + FXMAC_INFO("manual setting ,phy_addr is %d,speed %d, duplex_mode is %d \r\n", phy_addr, speed, duplex_mode); + + ret = FXmacPhyRead(instance_p, phy_addr, PHY_AUTONEGO_ADVERTISE_REG, &autonereg); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_AUTONEGO_ADVERTISE_REG is error", __func__, __LINE__); + return ret; + } + + autonereg |= PHY_AUTOADVERTISE_ASYMMETRIC_PAUSE_MASK; + autonereg |= PHY_AUTOADVERTISE_PAUSE_MASK; + ret = FXmacPhyWrite(instance_p, phy_addr, PHY_AUTONEGO_ADVERTISE_REG, autonereg); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,write PHY_AUTONEGO_ADVERTISE_REG is error", __func__, __LINE__); + return ret; + } + + + ret = FXmacPhyRead(instance_p, phy_addr, PHY_CONTROL_REG_OFFSET, &control); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_AUTONEGO_ADVERTISE_REG is error", __func__, __LINE__); + return ret; + } + FXMAC_INFO("PHY_CONTROL_REG_OFFSET is %x \r\n", control); + + + control &= ~PHY_CONTROL_LINKSPEED_1000M; + control &= ~PHY_CONTROL_LINKSPEED_100M; + control &= ~PHY_CONTROL_LINKSPEED_10M; + + if (speed == 1000) + { + control |= PHY_CONTROL_LINKSPEED_1000M; + } + else if (speed == 100) + { + control |= PHY_CONTROL_LINKSPEED_100M; + } + else if (speed == 10) + { + control |= PHY_CONTROL_LINKSPEED_10M; + } + + if (duplex_mode == 1) + { + control |= PHY_CONTROL_FULL_DUPLEX_MASK; + } + else + { + control &= ~PHY_CONTROL_FULL_DUPLEX_MASK; + } + + /* disable auto-negotiation */ + control &= ~(PHY_CONTROL_AUTONEGOTIATE_ENABLE); + control &= ~(PHY_CONTROL_AUTONEGOTIATE_RESTART); + + ret = FXmacPhyWrite(instance_p, phy_addr, PHY_CONTROL_REG_OFFSET, control); /* Technology Ability Field */ + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,write PHY_AUTONEGO_ADVERTISE_REG is error", __func__, __LINE__); + return ret; + } + + for (wait = 0; wait < 100000; wait++) + ; + + FXMAC_INFO("Manual selection completed \r\n"); + + ret = FXmacPhyRead(instance_p, phy_addr, PHY_SPECIFIC_STATUS_REG, &specific_reg); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("%s line is %d,read PHY_SPECIFIC_STATUS_REG is error", __func__, __LINE__); + return ret; + } + + FXMAC_INFO("specific_reg is %x \r\n", specific_reg); + + if (specific_reg & (1 << 13)) + { + FXMAC_INFO("duplex is full \r\n"); + instance_p->config.duplex = 1; + } + else + { + FXMAC_INFO("duplex is half \r\n"); + instance_p->config.duplex = 0; + } + + if ((specific_reg & 0xC000) == PHY_SPECIFIC_STATUS_SPEED_1000M) + { + FXMAC_INFO("speed is 1000\r\n"); + instance_p->config.speed = 1000; + } + else if ((specific_reg & 0xC000) == PHY_SPECIFIC_STATUS_SPEED_100M) + { + FXMAC_INFO("speed is 100\r\n"); + instance_p->config.speed = 100; + } + else + { + FXMAC_INFO("speed is 10\r\n"); + instance_p->config.speed = 10; + } + + return FT_SUCCESS; +} + +/** + * @name: FXmacPhyInit + * @msg: setup the PHYs for proper speed setting. + * @param {FXmac} *instance_p is a pointer to the instance to be worked on. + * @param {u32} speed is phy operating speed + * @param {u32} phy_addr is the address of the PHY to be read (supports multiple PHYs) + * @param {u32} duplex_mode is The duplex mode can be selected via either the Auto-Negotiation process or manual duplex selection. + * @param {u32} autonegotiation_en is an auto-negotiated flag . 1 is enable auto ,0 is manual + * @return {FError} + */ +FError FXmacPhyInit(FXmac *instance_p, u32 speed, u32 duplex_mode, u32 autonegotiation_en) +{ + FError ret; + u32 index = 0, phy_mask; + u16 phy_identity; + u32 phy_addr; + + if (FXmacDetect(instance_p, &phy_addr) != FT_SUCCESS) + { + FXMAC_ERROR("phy is not found"); + return FXMAC_PHY_IS_NOT_FOUND; + } + FXMAC_INFO("settings phy_addr is %d\n", phy_addr); + instance_p->phy_address = phy_addr; + if (autonegotiation_en) + { + ret = FXmacGetIeeePhySpeed(instance_p, phy_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + } + else + { + FXMAC_INFO("Set the communication speed manually"); + ret = FXmacConfigureIeeePhySpeed(instance_p, phy_addr, speed, duplex_mode); + if (ret != FT_SUCCESS) + { + FXMAC_ERROR("Failed to manually set the PHY"); + return ret; + } + + } + + instance_p->link_status = FXMAC_LINKUP; + return FT_SUCCESS; +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_phy.h b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_phy.h new file mode 100644 index 0000000000..49c1e1de38 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_phy.h @@ -0,0 +1,36 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_phy.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_ETH_FXMAC_PHY_H +#define DRIVERS_ETH_FXMAC_PHY_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_sinit.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_sinit.c new file mode 100644 index 0000000000..13a8592036 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/fxmac_sinit.c @@ -0,0 +1,44 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxmac_sinit.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fxmac.h" +#include "fparameters.h" + +extern const FXmacConfig fxmac_cfg_tbl[FT_XMAC_NUM]; + +const FXmacConfig *FXmacLookupConfig(u32 instance_id) +{ + const FXmacConfig *cfg_ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FT_XMAC_NUM; index++) + { + if (fxmac_cfg_tbl[index].instance_id == instance_id) + { + cfg_ptr = &fxmac_cfg_tbl[index]; + break; + } + } + + return (const FXmacConfig *)cfg_ptr; +} diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/eth_ieee_reg.h b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/eth_ieee_reg.h new file mode 100644 index 0000000000..02ddcee2c0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/eth_ieee_reg.h @@ -0,0 +1,104 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: eth_ieee_reg.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_ETH_PHY_IEEE_REG_H +#define DRIVERS_ETH_PHY_IEEE_REG_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "ferror_code.h" + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define PHY_CONTROL_REG_OFFSET 0 +#define PHY_STATUS_REG_OFFSET 1 +#define PHY_IDENTIFIER_1_REG 2 +#define PHY_IDENTIFIER_2_REG 3 +#define PHY_AUTONEGO_ADVERTISE_REG 4 +#define PHY_PARTNER_ABILITIES_1_REG_OFFSET 5 +#define PHY_PARTNER_ABILITIES_2_REG_OFFSET 8 +#define PHY_PARTNER_ABILITIES_3_REG_OFFSET 10 +#define PHY_1000_ADVERTISE_REG_OFFSET 9 +#define PHY_MMD_ACCESS_CONTROL_REG 13 +#define PHY_MMD_ACCESS_ADDRESS_DATA_REG 14 +#define PHY_SPECIFIC_STATUS_REG 17 + +#define PHY_CONTROL_FULL_DUPLEX_MASK 0x0100 +#define PHY_CONTROL_LINKSPEED_MASK 0x0040 +#define PHY_CONTROL_LINKSPEED_1000M 0x0040 +#define PHY_CONTROL_LINKSPEED_100M 0x2000 +#define PHY_CONTROL_LINKSPEED_10M 0x0000 +#define PHY_CONTROL_RESET_MASK 0x8000 + +#define PHY_CONTROL_AUTONEGOTIATE_ENABLE 0x1000 +#define PHY_CONTROL_AUTONEGOTIATE_RESTART 0x0200 + +#define PHY_STATUS_AUTONEGOTIATE_COMPLETE 0x0020 +#define PHY_STAT_LINK_STATUS 0x0004 + +#define PHY_AUTOADVERTISE_ASYMMETRIC_PAUSE_MASK 0x0800 +#define PHY_AUTOADVERTISE_PAUSE_MASK 0x0400 +#define PHY_AUTOADVERTISE_AUTONEG_ERROR_MASK 0x8000 + +/* Advertisement control register. */ +#define PHY_AUTOADVERTISE_10HALF 0x0020 /* Try for 10mbps half-duplex */ +#define PHY_AUTOADVERTISE_1000XFULL 0x0020 /* Try for 1000BASE-X full-duplex */ +#define PHY_AUTOADVERTISE_10FULL 0x0040 /* Try for 10mbps full-duplex */ +#define PHY_AUTOADVERTISE_1000XHALF 0x0040 /* Try for 1000BASE-X half-duplex */ +#define PHY_AUTOADVERTISE_100HALF 0x0080 /* Try for 100mbps half-duplex */ +#define PHY_AUTOADVERTISE_1000XPAUSE 0x0080 /* Try for 1000BASE-X pause */ +#define PHY_AUTOADVERTISE_100FULL 0x0100 /* Try for 100mbps full-duplex */ +#define PHY_AUTOADVERTISE_1000XPSE_ASYM 0x0100 /* Try for 1000BASE-X asym pause */ +#define PHY_AUTOADVERTISE_100BASE4 0x0200 /* Try for 100mbps 4k packets */ + +#define PHY_AUTOADVERTISE_100_AND_10 (PHY_AUTOADVERTISE_10FULL | PHY_AUTOADVERTISE_100FULL | \ + PHY_AUTOADVERTISE_10HALF | PHY_AUTOADVERTISE_100HALF) +#define PHY_AUTOADVERTISE_100 (PHY_AUTOADVERTISE_100FULL | PHY_AUTOADVERTISE_100HALF) +#define PHY_AUTOADVERTISE_10 (PHY_AUTOADVERTISE_10FULL | PHY_AUTOADVERTISE_10HALF) + +#define PHY_AUTOADVERTISE_1000 0x0300 + +#define PHY_SPECIFIC_STATUS_SPEED_1000M (2L << 14) +#define PHY_SPECIFIC_STATUS_SPEED_100M (1L << 14) +#define PHY_SPECIFIC_STATUS_SPEED_0M (0L << 14) + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +typedef FError(*EthPhyWrite)(void *instance_p, u32 phy_address, u32 phy_reg_offset, u16 phy_data); +typedef FError(*EthPhyRead)(void *instance_p, u32 phy_address, u32 phy_reg_offset, u16 *phy_data_p); + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/yt/phy_yt.c b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/yt/phy_yt.c new file mode 100644 index 0000000000..9aeae51ed3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/yt/phy_yt.c @@ -0,0 +1,224 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: phy_yt.c + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "phy_yt.h" +#include "fdebug.h" + +#define PHY_YT_DEBUG_TAG "PHY_YT" +#define PHY_YT_ERROR(format, ...) FT_DEBUG_PRINT_E(PHY_YT_DEBUG_TAG, format, ##__VA_ARGS__) +#define PHY_YT_INFO(format, ...) FT_DEBUG_PRINT_I(PHY_YT_DEBUG_TAG, format, ##__VA_ARGS__) +#define PHY_YT_DEBUG(format, ...) FT_DEBUG_PRINT_D(PHY_YT_DEBUG_TAG, format, ##__VA_ARGS__) +#define PHY_YT_WARN(format, ...) FT_DEBUG_PRINT_W(PHY_YT_DEBUG_TAG, format, ##__VA_ARGS__) + +#define PHY_YT_REG0_LOOPBACK 0x4000 + + +FError PhyYtCheckConnectStatus(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p) +{ + u16 phy_reg0 = 0; + FError status; + /* It's the address offset of the extended register + that will be Write or Read */ + status = write_p(instance_p, phy_addr, 0x1e, 0xa001); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + status = read_p(instance_p, phy_addr, 0x1f, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("read_p 0x1f failed"); + return FETH_PHY_ERR_READ; + } + + PHY_YT_INFO("phy_reg0 status is 0x%x", phy_reg0); + + return FT_SUCCESS; +} + +FError PhyYtSetLoopBack(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p) +{ + FError status; + u16 phy_reg0 = 0; + + status = read_p(instance_p, phy_addr, 0, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("Error setup phy loopback"); + return FETH_PHY_ERR_READ; + } + PHY_YT_INFO("0 phy_reg0 is 0x%x \r\n", phy_reg0); + /* + * Enable loopback + */ + phy_reg0 |= PHY_YT_REG0_LOOPBACK; + status = write_p(instance_p, phy_addr, 0, phy_reg0); + + status = read_p(instance_p, phy_addr, 0, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("Error setup phy loopback"); + return FETH_PHY_ERR_READ; + } + + status = read_p(instance_p, phy_addr, 0, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("Error setup phy loopback"); + return FETH_PHY_ERR_READ; + } + PHY_YT_INFO("after 0 phy_reg0 is 0x%x \r\n", phy_reg0); + + return FT_SUCCESS; +} + + +FError PhyChangeModeToSgmii(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p) +{ + FError status; + u16 phy_reg0 = 0; + + /* read default mode */ + status = write_p(instance_p, phy_addr, 0x1e, 0xa001); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + + status = read_p(instance_p, phy_addr, 0x1f, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("read_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + PHY_YT_INFO("default 0xa001 status is 0x%x \r\n", phy_reg0); + + /* change mode to sds */ + status = write_p(instance_p, phy_addr, 0x1e, 0xa001); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + status = write_p(instance_p, phy_addr, 0x1f, 0x8063); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + + /* read changged mode */ + status = write_p(instance_p, phy_addr, 0x1e, 0xa001); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa000 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + + status = read_p(instance_p, phy_addr, 0x1f, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("read_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + PHY_YT_INFO("changged 0xa001 status is 0x%x \r\n", phy_reg0); + + + + return FT_SUCCESS; +} + +FError PhyChangeModeToSds(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p) +{ + FError status; + u16 phy_reg0 = 0; + + + /* read default mode */ + status = write_p(instance_p, phy_addr, 0x1e, 0xa000); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa000 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + + status = read_p(instance_p, phy_addr, 0x1f, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("read_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + PHY_YT_INFO("default status is 0x%x \r\n", phy_reg0); + + /* change mode to sds */ + status = write_p(instance_p, phy_addr, 0x1e, 0xa000); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + status = write_p(instance_p, phy_addr, 0x1f, 0x2); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + + /* read changged mode */ + status = write_p(instance_p, phy_addr, 0x1e, 0xa000); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("write_p 0xa000 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + + status = read_p(instance_p, phy_addr, 0x1f, &phy_reg0); + if (status != FT_SUCCESS) + { + PHY_YT_ERROR("read_p 0xa001 to 0x1e failed"); + return FETH_PHY_ERR_READ; + } + + PHY_YT_INFO("changged status is 0x%x \r\n", phy_reg0); + + + + return FT_SUCCESS; +} + + + diff --git a/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/yt/phy_yt.h b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/yt/phy_yt.h new file mode 100644 index 0000000000..4640db8511 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/eth/fxmac/phy/yt/phy_yt.h @@ -0,0 +1,45 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: phy_yt.h + * Date: 2022-04-06 14:46:52 + * LastEditTime: 2022-04-06 14:46:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef PHY_YT_H +#define PHY_YT_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ferror_code.h" +#include "eth_ieee_reg.h" + +#define FETH_PHY_ERR_READ FT_MAKE_ERRCODE(ErrModBsp, ErrEthPhy, 0x1u) + +FError PhyYtSetLoopBack(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p); +FError PhyYtCheckConnectStatus(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p); +FError PhyChangeModeToSds(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p); +FError PhyChangeModeToSgmii(void *instance_p, u32 phy_addr, EthPhyWrite write_p, EthPhyRead read_p); +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/gic/Kconfig b/bsp/phytium/libraries/standalone/drivers/gic/Kconfig new file mode 100644 index 0000000000..9946994e6d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/Kconfig @@ -0,0 +1,6 @@ + config ENABLE_GICV3 + bool + prompt "Use Generic Interrupt Controller v3" + default y + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic.c b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic.c new file mode 100644 index 0000000000..b1fa4fb582 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic.c @@ -0,0 +1,674 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic.c + * Date: 2022-03-28 09:30:23 + * LastEditTime: 2022-03-28 09:30:24 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fgic.h" +#include "fgic_distributor.h" +#include "fgic_cpu_interface.h" +#include "fgic_redistributor.h" +#include "fgic_hw.h" +#include "ftypes.h" +#include "fkernel.h" +#include "fassert.h" +#include "fdebug.h" + + +#define FGIC_DEBUG_TAG "FGIC" +#define FGIC_ERROR(format, ...) FT_DEBUG_PRINT_E(FGIC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGIC_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FGIC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGIC_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FGIC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGIC_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FGIC_DEBUG_TAG, format, ##__VA_ARGS__) + + +#define FGIC_SPI_START_ID 32 +#define FGIC_PPI_END_ID 31 +#define FGIC_SGI_END_ID 15 + +#define FGIC_GICD_32_PER_REG 32 +#define FGIC_GICD_16_PER_REG 16 +#define FGIC_GICD_4_PER_REG 4 + +#define FGIC_INT_DEFAULT_PRI_X4 0xa0a0a0a0 /* 考虑到当前一般程序工作于EL1,对于NS 或 S 安全状态 ,0x80 - 0xff 的优先级都有存在的可能性 */ +#define FGIC_CPU_INTERFACE_DEFAULT_FLITER 0xFF + +typedef enum +{ + GICD_CTLR_RWP_WAIT = 0, /* Use GICD_CTLR for test */ + GICR_CTLR_RWP_WAIT, /* Use GICR_CTLR for test */ +} WAIT_RWP_MODE; + +/** + * @name: FGicWaitRwp + * @msg: Wait for register write pending + * @param {uintptr} ctrl_base is a GICD_CTLR address + * @param {WAIT_RWP_MODE} wait_mode + * @return {*} + */ +static FError FGicWaitRwp(uintptr ctrl_base, WAIT_RWP_MODE wait_mode) +{ + u32 rwp_mask; + u32 timeout_cnt = 0; + if (GICD_CTLR_RWP_WAIT == wait_mode) + { + rwp_mask = FGIC_GICD_CTLR_RWP_MASK; + } + else if (GICR_CTLR_RWP_WAIT == wait_mode) + { + rwp_mask = FGIC_GICR_CTLR_RWP_MASK; + } + else + { + FGIC_DEBUG_E(" wait_mode not in WAIT_RWP_MODE "); + return FGIC_CTLR_ERR_TYPE; + } + + while (FGIC_READREG32(ctrl_base, 0) & rwp_mask) + { + if (timeout_cnt ++ >= 0xffffff) + { + FGIC_DEBUG_E(" wait rwp timeout "); + return FGIC_CTLR_ERR_IN_GET; + } + } + + return FGIC_SUCCESS; +} + +/** + * @name: void FGicDistrubutiorInit(FGic *instance_p) + * @msg: Initialize Distrubutior + * @param {FGic} *instance_p is a pointer to the FGic instance. + */ +void FGicDistrubutiorInit(FGic *instance_p) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + u32 max_ints_mun, int_id, int_index; + uintptr dis_base = instance_p->config.dis_base; + max_ints_mun = instance_p->max_spi_num; + /* Disable the distributor */ + FGIC_WRITEREG32(dis_base, FGIC_GICD_CTLR_OFFSET, 0); + FASSERT(FGicWaitRwp(dis_base + FGIC_GICD_CTLR_OFFSET, GICD_CTLR_RWP_WAIT) == FGIC_SUCCESS); + + if (instance_p->security == ONE_NS_SECURITY_STATE) + { + /* Make GICD_CTLR.DS = 1 ,Non-secure accesses are permitted to access and modify registers that control Group 0 interrupts */ + FGIC_SETBIT(dis_base, FGIC_GICD_CTLR_OFFSET, FGIC_GICD_CTLR_DS_MASK); + FASSERT(FGIC_READREG32(dis_base, FGIC_GICD_CTLR_OFFSET) & FGIC_GICD_CTLR_DS_MASK); + } + + /* 关闭所有中断,并将中断分组默认为group 1 */ + for (int_id = FGIC_SPI_START_ID; int_id < max_ints_mun; int_id += FGIC_GICD_32_PER_REG) + { + int_index = int_id / FGIC_GICD_32_PER_REG; + /* Disables forwarding of the corresponding interrupt. */ + FGIC_GICD_ICENABLER_WRITE_N_MASK(dis_base, int_id, FGIC_GICD_ICENABLER_DEFAULT_MASK); + /* Changes the state of the corresponding interrupt from pending to inactive, or from active and pending to active. */ + FGIC_GICD_ICPENDR_WRITE_N_MASK(dis_base, int_id, FGIC_GICD_ICPENDR_DEFAULT_MASK); + + if (instance_p->security == ONE_NS_SECURITY_STATE) + { + FGIC_GICD_IGROUPR_WRITE_N_MASK(dis_base, int_id, FGIC_GICD_ICPENDR_DEFAULT_MASK); + } + else + { + FGIC_GICD_IGROUPR_WRITE_N_MASK(dis_base, int_id, FGIC_GICD_ICPENDR_DEFAULT_MASK); + } + FGIC_GICD_IGRPMODR_WRITE_N_MASK(dis_base, int_id, FGIC_GICD_IGRPMODR_DEFAULT_MASK); + } + + FASSERT(FGicWaitRwp(dis_base + FGIC_GICD_CTLR_OFFSET, GICD_CTLR_RWP_WAIT) == FGIC_SUCCESS); + + for (int_id = FGIC_SPI_START_ID; int_id < max_ints_mun; int_id += FGIC_GICD_4_PER_REG) + { + FGIC_GICD_IPRIORITYR_WRITE_N_MASK(dis_base, int_id, FGIC_INT_DEFAULT_PRI_X4); + } + + for (int_id = FGIC_SPI_START_ID; int_id < max_ints_mun; int_id += FGIC_GICD_16_PER_REG) + { + FGIC_GICD_ICFGR_WRITE_N_MASK(dis_base, int_id, 0); /* level-sensitive */ + } + + if (instance_p->security == ONE_NS_SECURITY_STATE) + { + FGIC_GICD_CTLR_WRITE(dis_base, GICD_CTLR_BIT_ARE_S | GICD_CTLR_ENABLE_GRP1_NS); + } + else + { + FGIC_GICD_CTLR_WRITE(dis_base, GICD_CTLR_BIT_ARE_NS | GICD_CTLR_ENABLE_GRP1_NS); + } + + + +} + +/** + * @name: FError FGicRedistrubutiorInit(FGic *instance_p) + * @msg: Initialize Redistrubutior + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @return {FError} FGIC_SUCCESS is success ,FGIC_ERR_IN_TIMEOUT is timeout + */ +FError FGicRedistrubutiorInit(FGic *instance_p) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + s32 int_id ; + u32 timeout = 0; + uintptr redis_base = instance_p->redis_base; + uintptr sgi_base = instance_p->redis_base + FGIC_GICR_SGI_BASE_OFFSET; + + /* Clear processor sleep and wait till childasleep is cleard */ + + FGIC_GICR_WAKER_CLEAR_BIT(redis_base, FGIC_GICR_WAKER_PROCESSOR_SLEEP_MASK); + while (FGIC_GICR_WAKER_READ(redis_base) & FGIC_GICR_WAKER_CHILDREN_ASLEEP_MASK) + { + timeout++; + if (timeout >= 0xfffffff) + { + return FGIC_ERR_IN_TIMEOUT; + } + } + + FASSERT(FGicWaitRwp(redis_base, GICR_CTLR_RWP_WAIT) == FGIC_SUCCESS); + FGIC_GICR_ICENABLER0_WRITE(sgi_base, FGIC_GICR_ICENABLER0_DEFAULT_MASK); /* Disable all sgi ppi */ + + /* Clear pending */ + FGIC_GICR_ICPENDR0_WRITE(sgi_base, FGIC_GICR_ICPENDR0_DEFAULT_MASK); + + /* Set sgi ppi route to different security group */ + + if (instance_p->security == ONE_NS_SECURITY_STATE) + { + FGIC_GICR_IGROUPR0_WRITE(sgi_base, FGIC_GICR_IGROUPR0_DEFAULT_MASK); + } + else + { + FGIC_GICR_IGROUPR0_WRITE(sgi_base, FGIC_GICR_IGROUPR0_DEFAULT_MASK); + } + FGIC_GICR_IGRPMODR0_WRITE(sgi_base, FGIC_GICR_IGRPMODR0_DEFAULT_MASK); + + /* 默认所有优先级为0xa0 */ + for (int_id = 0; int_id < FGIC_SPI_START_ID; int_id += FGIC_GICD_4_PER_REG) + { + FGIC_GICR_IPRIORITYR_WRITE(sgi_base, int_id, FGIC_INT_DEFAULT_PRI_X4); + } + + FGIC_GICR_ICFGR0_WRITE(sgi_base, 0); /* set level-sensitive */ + FGIC_GICR_ICFGR1_WRITE(sgi_base, 0); + + return FGIC_SUCCESS; +} + +/** + * @name: void FGicCpuInterfaceInit(void) + * @msg: Initialize Cpu interface of current core + */ +void FGicCpuInterfaceInit(void) +{ + u32 reg; + reg = FGicGetICC_SRE_EL1(); + + if (!(reg & GICC_SRE_SRE)) + { + reg |= (GICC_SRE_SRE | GICC_SRE_DFB | GICC_SRE_DIB); + FGicSetICC_SRE_EL1(reg); + reg = FGicGetICC_SRE_EL1(); + FASSERT(reg & GICC_SRE_SRE); + } + + FGicSetICC_PMR(FGIC_CPU_INTERFACE_DEFAULT_FLITER); + + FGicEnableGroup1_EL1(); + + FGicSetICC_CTLR_EL1(GICC_CTLR_CBPR); /* ICC_BPR0_EL1 determines the preemption group for both Group 0 and Group 1 interrupts. */ +} + +/** + * @name: FError FGicCfgInitialize(FGic *instance_p, const FGicConfig *input_config_p , uintptr redis_base) + * @msg: Initialize the GIC driver instance based on the incoming configuration + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {FGicConfig} *input_config_p Configuration items that need to be applied in the instance + * @param {uintptr} redis_base is the redistributor adress of current core + * @return {*} + */ +FError FGicCfgInitialize(FGic *instance_p, const FGicConfig *input_config_p, uintptr redis_base) +{ + u32 max_ints_mun; + uintptr dis_base; + + FASSERT(instance_p && input_config_p); + + instance_p->config = *input_config_p; + instance_p->redis_base = redis_base ; + instance_p->is_ready = FT_COMPONENT_IS_READY; + + dis_base = instance_p->config.dis_base; + + max_ints_mun = FGIC_READREG32(dis_base, FGIC_GICD_TYPER_OFFSET); + max_ints_mun &= FGIC_GICD_TYPER_ITLINESNUMBER_MASK ; + max_ints_mun = ((max_ints_mun + 1) << 5) - 1; /* If the value of this field is N, the maximum SPI INTID is 32(N+1) minus 1. */ + instance_p->max_spi_num = max_ints_mun; + + return FGIC_SUCCESS; +} + +/** + * @name: FError FGicIntEnable(FGic *instance_p,s32 int_id) + * @msg: Enables the interrupt function based on the interrupt number + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {s32} int_id is interrupt id + * @return {*} + */ +FError FGicIntEnable(FGic *instance_p, s32 int_id) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + if (int_id > instance_p->max_spi_num) + { + FGIC_DEBUG_E("int_id is over max spi num for FGicIntEnable"); + return FGIC_CTLR_ERR_NUM; + } + + if (int_id <= FGIC_PPI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + FGicEnablePrivateInt(redis_base, int_id); + } + else + { + uintptr dis_base = instance_p->config.dis_base; + FGicEnableSPI(dis_base, int_id); + } + + return FGIC_SUCCESS ; +} + + +/** + * @name: FError FGicIntEnable(FGic *instance_p,s32 int_id) + * @msg: Disable the interrupt function based on the interrupt number + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {s32} int_id is interrupt id + */ +FError FGicIntDisable(FGic *instance_p, s32 int_id) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + + if (int_id > instance_p->max_spi_num) + { + FGIC_DEBUG_E("int_id is over max spi num for FGicIntDisable"); + return FGIC_CTLR_ERR_NUM; + } + + if (int_id <= FGIC_PPI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + FGicDisablePrivateInt(redis_base, int_id); + } + else + { + uintptr dis_base = instance_p->config.dis_base; + FGicDisableSPI(dis_base, int_id); + } + + return FGIC_SUCCESS ; +} + + +/** + * @name: FError FGicSetPriority(FGic *instance_p,s32 int_id,u32 priority) + * @msg: Sets the current interrupt priority value based on the interrupt number + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {s32} int_id is interrupt id + * @param {u32} priority is priority value ,valid bit is bit[0:7] + * @return {*} + */ +FError FGicSetPriority(FGic *instance_p, s32 int_id, u32 priority) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + + if (int_id > instance_p->max_spi_num) + { + FGIC_DEBUG_E("int_id is over max spi num for FGicSetPriority"); + return FGIC_CTLR_ERR_IN_GET; + } + + if (int_id <= FGIC_PPI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + FGicSetPrivatePriority(redis_base, int_id, priority); + } + else + { + uintptr dis_base = instance_p->config.dis_base; + FGicSetSpiPriority(dis_base, int_id, priority); + } + + return FGIC_SUCCESS ; +} + +/** + * @name: u32 FGicGetPriority(FGic *instance_p,s32 int_id) + * @msg: Gets the current interrupt priority value based on the interrupt number + * @param {FGic} *instance_p is a pointer to the FGic instance + * @param {s32} int_id is interrupt id + * @return {u32} priority value ,valid bit is bit[0:7] + */ +u32 FGicGetPriority(FGic *instance_p, s32 int_id) +{ + u32 priority; + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + + if (int_id > instance_p->max_spi_num) + { + FGIC_DEBUG_E("int_id is over max spi num for FGicGetPriority"); + return (u32)FGIC_CTLR_ERR_IN_GET; + } + + if (int_id <= FGIC_PPI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + priority = FGicGetPrivatePriority(redis_base, int_id); + } + else + { + uintptr dis_base = instance_p->config.dis_base; + priority = FGicGetSpiPriority(dis_base, int_id); + } + + return priority ; +} + +/** + * @name: FError FGicSetTriggerLevel(FGic *instance_p,s32 int_id,TRIGGER_LEVEL trigger_way) + * @msg: Sets the interrupt triggering mode based on the current interrupt number + * @param {FGic} *instance_p is a pointer to the FGic instance + * @param {s32} int_id is interrupt id + * @param {TRIGGER_LEVEL} trigger_way is trigger mode + * @return {*} + */ +FError FGicSetTriggerLevel(FGic *instance_p, s32 int_id, TRIGGER_LEVEL trigger_way) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + if (int_id > instance_p->max_spi_num) + { + FGIC_DEBUG_E("int_id is over max spi num for FGicSetTriggerLevel"); + return FGIC_CTLR_ERR_IN_SET; + } + + if (int_id <= FGIC_SGI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + FGicSetSgiLevel(redis_base, int_id, trigger_way); + } + else if (int_id <= FGIC_PPI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + FGicSetPpiLevel(redis_base, int_id, trigger_way); + } + else + { + uintptr dis_base = instance_p->config.dis_base; + FGicSetSpiLevel(dis_base, int_id, trigger_way); + } + + return FGIC_SUCCESS ; +} + +/** + * @name: u32 FGicGetTriggerLevel(FGic *instance_p,s32 int_id) + * @msg: Gets the interrupt triggering mode based on the current interrupt number + * @param {FGic} *instance_p is a pointer to the FGic instance + * @param {s32} int_id is interrupt id + * @return {u32} triggering mode + */ +u32 FGicGetTriggerLevel(FGic *instance_p, s32 int_id) +{ + u32 trigger_way; + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + + if (int_id > instance_p->max_spi_num) + { + FGIC_DEBUG_E("int_id is over max spi num for FGicGetTriggerLevel"); + return (u32)FGIC_CTLR_ERR_IN_GET; + } + + if (int_id <= FGIC_SGI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + trigger_way = FGicGetSgiLevel(redis_base, int_id); + } + else if (int_id <= FGIC_PPI_END_ID) + { + uintptr redis_base = instance_p->redis_base; + trigger_way = FGicGetPpiLevel(redis_base, int_id); + } + else + { + uintptr dis_base = instance_p->config.dis_base; + trigger_way = FGicGetSpiLevel(dis_base, int_id); + } + + return trigger_way ; +} + +/** + * @name: FGicSetSpiAffinityRouting + * @msg: Set intermediate routing information for a specific SPI interrupt + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {u32} int_id is interrupt vector for spi + * @param {SPI_ROUTING_MODE} route_mode is the interrupt routing mode. + * @param {u64} affinity is the affinity level ,format is + * |--------[bit39-32]-------[bit23-16]-------------[bit15-8]--------[bit7-0] + * |--------Affinity level3-----Affinity level2-----Affinity level1---Affinity level0 + * @return {*} + */ +FError FGicSetSpiAffinityRouting(FGic *instance_p, s32 int_id, SPI_ROUTING_MODE route_mode, u64 affinity) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + uintptr dis_base = instance_p->config.dis_base; + + if ((int_id > instance_p->max_spi_num) || (int_id <= FGIC_PPI_END_ID)) + { + FGIC_DEBUG_E("int_id %d is out of range ", int_id); + return FGIC_CTLR_ERR_IN_SET; + } + + FGicSetSpiRoute(dis_base, int_id, route_mode, affinity); + return FGIC_SUCCESS; +} + + +/** + * @name: FGicGetAffinityRouting + * @msg: Get intermediate routing information for a specific SPI interrupt + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {u32} int_id is interrupt vector for spi + * @param {SPI_ROUTING_MODE} *route_mode_p is a pointer to get interrupt routing mode. + * @param {u64} *affinity_p is pointer to get affinity level ,format is + * |--------[bit39-32]-------[bit23-16]-------------[bit15-8]--------[bit7-0] + * |--------Affinity level3-----Affinity level2-----Affinity level1---Affinity level0 + * @return {FError} + */ +FError FGicGetAffinityRouting(FGic *instance_p, s32 int_id, SPI_ROUTING_MODE *route_mode_p, u64 *affinity_p) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(route_mode_p != NULL); + FASSERT(affinity_p != NULL); + uintptr dis_base = instance_p->config.dis_base; + u64 reg; + + if ((int_id > instance_p->max_spi_num) || (int_id <= FGIC_PPI_END_ID)) + { + FGIC_DEBUG_E("int_id %d is out of range ", int_id); + return (u32)FGIC_CTLR_ERR_IN_GET; + } + + reg = FGicGetSpiRoute(dis_base, int_id); + *route_mode_p = reg & SPI_ROUTING_TO_ANY; + *affinity_p = reg & FGIC_GICD_IROUTER_AFFINITY_MASK; + return FGIC_SUCCESS; +} + + +/** + * @name: FGicGenerateSgi + * @msg: This interface is used for software generated interrupts + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {u32} int_id is interrupt vector for spi + * @param {u32} target_list is the set of PEs for which SGI interrupts will be generated. Each bit corresponds to the PE within a cluster with an Affinity 0 value equal to the bit number. + * @param {SGI_ROUTING_MODE} routing_mode is Interrupt Routing Mode. + * @param {u64} affinity is the affinity level ,format is + * |--------[bit55-48]-------[bit39-32]-------------[bit23-16] + * |--------Affinity level3-----Affinity level2-----Affinity level1 + * @return {*} + */ +FError FGicGenerateSgi(FGic *instance_p, s32 int_id, u32 target_list, SGI_ROUTING_MODE routing_mode, u64 affinity) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + if (int_id > FGIC_SGI_END_ID) + { + FGIC_DEBUG_E("int_id %d is out of range ", int_id); + return FGIC_CTLR_ERR_IN_SET; + } + + FGicSetICC_SGI1R((int_id & FGIC_ICC_SGI1R_INTID_MASK) << 24, target_list, routing_mode, affinity); + return FGIC_SUCCESS; +} + +/** + * @name: FGicDeactionInterrupt + * @msg: Deactive Interruption of the current active state + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {s32} int_id is interrupt id + */ +void FGicDeactionInterrupt(FGic *instance_p, s32 int_id) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FGicSetICC_EOIR1(int_id); +} + +/** + * @name: FGicAcknowledgeInt + * @msg: Acknowledge pending interrupt + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @return {s32} interrupt id + */ +s32 FGicAcknowledgeInt(FGic *instance_p) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + return FGicGetICC_APR1(); +} + + +/** + * @name: FGicSetPriorityFilter + * @msg: By setting the parameter of ICC_PMR, the interrupt range that the interrupt controller can respond to is determined + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {u32} priority_mask . If the priority of an interrupt is lower than the value indicated by this field, the interface signals the interrupt to the PE. + * The reference values of priority_mask are as follows + * |priority_mask---------------256-------254--------252------248-------240 + * |Implemented priority bits---[7:0]----[7:1]------[7:2]-----[7:3]-----[7:4] + * |priority the growing steps--any-----even value----4---------8--------16 + */ +void FGicSetPriorityFilter(FGic *instance_p, u32 priority_mask) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + FGicSetICC_PMR(priority_mask); +} + + +/** + * @name: FGicGetPriorityFilter + * @msg: Gets the current priority filtering value + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @return {u32} Priority Mask for the CPU interface . If the priority of an interrupt is lower than the value + * indicated by this field, the interface signals the interrupt to the PE. + * The reference values of priority_mask are as follows + * |return value----------------256-------254--------252------248-------240 + * |Implemented priority bits---[7:0]----[7:1]------[7:2]-----[7:3]-----[7:4] + * |priority the growing steps--any-----even value----4---------8--------16 + */ +u32 FGicGetPriorityFilter(FGic *instance_p) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + return FGicGetICC_PMR(); +} + + +/** + * @name: FGicGetPriorityGroup + * @msg: Get Binary point value + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @return {u32} The relationship between Binary point value and grouping is as follows + * |return value----------------0-------1--------2------3-------4------5------6-------7 + * |Group priority field------[---]----[7:1]---[7:2]--[7:3]---[7:4]---[7:5]---[7:6]---[7] + * |Subpriority field---------[---]-----[0]----[1:0]--[2:0]---[3:0]---[4:0]---[5:0]---[6:0] + */ +u32 FGicGetPriorityGroup(FGic *instance_p) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + return FGicGetICC_BPR1(); +} + +/** + * @name: FGicSetPriorityGroup + * @msg: Sets the value of the current group priority + * @param {FGic} *instance_p is a pointer to the FGic instance. + * @param {u32} binary_point : The value of this field controls how the 8-bit interrupt priority field is split into a group priority field + * The relationship between binary_point value and grouping is as follows + * |binary_point----------------0-------1--------2------3-------4------5------6-------7 + * |Group priority field------[---]----[7:1]---[7:2]--[7:3]---[7:4]---[7:5]---[7:6]---[7] + * |Subpriority field---------[---]-----[0]----[1:0]--[2:0]---[3:0]---[4:0]---[5:0]---[6:0] + */ +void FGicSetPriorityGroup(FGic *instance_p, u32 binary_point) +{ + FASSERT(instance_p); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + FGicSetICC_BPR1(binary_point); +} + + diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic.h b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic.h new file mode 100644 index 0000000000..e08236e916 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic.h @@ -0,0 +1,109 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic.h + * Date: 2022-03-28 09:30:29 + * LastEditTime: 2022-03-28 09:30:29 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_GIC_FGIC_H +#define DRIVERS_GIC_FGIC_H + +#include "ftypes.h" +#include "ferror_code.h" +#include "fparameters.h" + + +#define FGIC_RSGI_AFF1_OFFSET 16 +#define FGIC_RSGI_AFF2_OFFSET 32 +#define FGIC_RSGI_AFF3_OFFSET 48 + +#define FGIC_SUCCESS FT_SUCCESS +#define FGIC_CTLR_ERR_TYPE FT_MAKE_ERRCODE(ErrModBsp, ErrGic, 1) /* 错误选择CTLR 寄存器 */ +#define FGIC_CTLR_ERR_NUM FT_MAKE_ERRCODE(ErrModBsp, ErrGic, 2) /* 当前控制器不支持此中断id */ +#define FGIC_CTLR_ERR_IN_SET FT_MAKE_ERRCODE(ErrModBsp, ErrGic, 3) /* 在设置过程中出现的异常 */ +#define FGIC_CTLR_ERR_IN_GET FT_MAKE_ERRCODE(ErrModBsp, ErrGic, 4) /* 在获取过程中出现的异常 */ +#define FGIC_ERR_IN_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrGic, 5) /* 超时退出 */ + + +typedef enum +{ + TRIGGER_BY_LEVEL_SENSITIVE = 0, /* Corresponding interrupt is level-sensitive. */ + TRIGGER_BY_LEVEL_EDGE, /* Corresponding interrupt is edge-triggered. */ +} TRIGGER_LEVEL; + +typedef enum +{ + TWO_SECURITY_STATE = 0, /* */ + ONE_NS_SECURITY_STATE, /* */ +} SECURITY_STATE; + +/* Interrupt Routing Mode. */ +typedef enum +{ + SGI_ROUTING_TO_SPECIFIC = 0, /* sgi interrupts routed to the PEs specified by affinity level. */ + SGI_ROUTING_TO_ANY = (1ULL << 40) /* sgi interrupts routed to all PEs in the system, excluding "self". */ +} SGI_ROUTING_MODE; + +typedef enum +{ + SPI_ROUTING_TO_SPECIFIC = 0, /* spi interrupts routed to the PE specified by affinity level. */ + SPI_ROUTING_TO_ANY = (1U << 31) /* spi interrupts routed to any PE defined as a participating node. */ +} SPI_ROUTING_MODE; + +typedef struct +{ + u32 instance_id; /* Id of device*/ + uintptr dis_base; /* Distributor base address */ + +} FGicConfig; + +typedef struct +{ + FGicConfig config; /* Configuration data structure */ + u32 is_ready; /* Device is ininitialized and ready*/ + uintptr redis_base; /* Redistributor base address for each core */ + SECURITY_STATE security ; + s32 max_spi_num; /* Max value of spi priority */ +} FGic; + +/* Initialization */ +FGicConfig *FGicLookupConfig(u32 instance_id); +FError FGicCfgInitialize(FGic *instance_p, const FGicConfig *input_config_p, uintptr redis_base); +void FGicDistrubutiorInit(FGic *instance_p); +FError FGicRedistrubutiorInit(FGic *instance_p); +void FGicCpuInterfaceInit(void); + +/* Operation interface */ +FError FGicIntEnable(FGic *instance_p, s32 int_id); +FError FGicIntDisable(FGic *instance_p, s32 int_id); +FError FGicSetPriority(FGic *instance_p, s32 int_id, u32 priority); +u32 FGicGetPriority(FGic *instance_p, s32 int_id); +FError FGicSetTriggerLevel(FGic *instance_p, s32 int_id, TRIGGER_LEVEL trigger_way); +u32 FGicGetTriggerLevel(FGic *instance_p, s32 int_id); +FError FGicSetSpiAffinityRouting(FGic *instance_p, s32 int_id, SPI_ROUTING_MODE route_mode, u64 affinity); +FError FGicGetAffinityRouting(FGic *instance_p, s32 int_id, SPI_ROUTING_MODE *route_mode_p, u64 *affinity_p); +FError FGicGenerateSgi(FGic *instance_p, s32 int_id, u32 target_list, SGI_ROUTING_MODE routing_mode, u64 affinity); +void FGicDeactionInterrupt(FGic *instance_p, s32 int_id); +s32 FGicAcknowledgeInt(FGic *instance_p); +void FGicSetPriorityFilter(FGic *instance_p, u32 priority_mask); +void FGicSetPriorityGroup(FGic *instance_p, u32 binary_point); +u32 FGicGetPriorityFilter(FGic *instance_p); +u32 FGicGetPriorityGroup(FGic *instance_p); + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_cpu_interface.S b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_cpu_interface.S new file mode 100644 index 0000000000..2cc1d927a3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_cpu_interface.S @@ -0,0 +1,494 @@ +/* + * @Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * @FilePath: fgic_cpu_interface.S + * @Date: 2022-03-29 18:04:23 + * @LastEditTime: 2022-03-29 18:04:27 + * @Description:  This file is for + * + * @Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + + +#ifdef __aarch64__ + +/* + * Mapping of MSR and MRS to physical and virtual CPU interface registers + * + * ARM Generic Interrupt Controller Architecture Specification + * GIC architecture version 3.0 and version 4.0 + * Table 8-5 + */ +#define ICC_AP0R0_EL1 S3_0_C12_C8_4 +#define ICC_AP0R1_EL1 S3_0_C12_C8_5 +#define ICC_AP0R2_EL1 S3_0_C12_C8_6 +#define ICC_AP0R3_EL1 S3_0_C12_C8_7 + +#define ICC_AP1R0_EL1 S3_0_C12_C9_0 +#define ICC_AP1R1_EL1 S3_0_C12_C9_1 +#define ICC_AP1R2_EL1 S3_0_C12_C9_2 +#define ICC_AP1R3_EL1 S3_0_C12_C9_3 + +#define ICC_ASGI1R_EL1 S3_0_C12_C11_6 + +#define ICC_BPR0_EL1 S3_0_C12_C8_3 +#define ICC_BPR1_EL1 S3_0_C12_C12_3 + +#define ICC_CTLR_EL1 S3_0_C12_C12_4 +#define ICC_CTLR_EL3 S3_6_C12_C12_4 + +#define ICC_DIR_EL1 S3_0_C12_C11_1 + +#define ICC_EOIR0_EL1 S3_0_C12_C8_1 +#define ICC_EOIR1_EL1 S3_0_C12_C12_1 + +#define ICC_HPPIR0_EL1 S3_0_C12_C8_2 +#define ICC_HPPIR1_EL1 S3_0_C12_C12_2 + +#define ICC_IAR0_EL1 S3_0_C12_C8_0 +#define ICC_IAR1_EL1 S3_0_C12_C12_0 + +#define ICC_IGRPEN0_EL1 S3_0_C12_C12_6 +#define ICC_IGRPEN1_EL1 S3_0_C12_C12_7 +#define ICC_IGRPEN1_EL3 S3_6_C12_C12_7 + +#define ICC_PMR_EL1 S3_0_C4_C6_0 +#define ICC_RPR_EL1 S3_0_C12_C11_3 + +#define ICC_SGI0R_EL1 S3_0_C12_C11_7 +#define ICC_SGI1R_EL1 S3_0_C12_C11_5 + +#define ICC_SRE_EL1 S3_0_C12_C12_5 +#define ICC_SRE_EL2 S3_4_C12_C9_5 +#define ICC_SRE_EL3 S3_6_C12_C12_5 + +/* + * Mapping of MSR and MRS to virtual interface control registers + * + * ARM Generic Interrupt Controller Architecture Specification + * GIC architecture version 3.0 and version 4.0 + * Table 8-6 + */ +#define ICH_AP0R0_EL2 S3_4_C12_C8_0 +#define ICH_AP0R1_EL2 S3_4_C12_C8_1 +#define ICH_AP0R2_EL2 S3_4_C12_C8_2 +#define ICH_AP0R3_EL2 S3_4_C12_C8_3 + +#define ICH_AP1R0_EL2 S3_4_C12_C9_0 +#define ICH_AP1R1_EL2 S3_4_C12_C9_1 +#define ICH_AP1R2_EL2 S3_4_C12_C9_2 +#define ICH_AP1R3_EL2 S3_4_C12_C9_3 + +#define ICH_HCR_EL2 S3_4_C12_C11_0 + +#define ICH_VTR_EL2 S3_4_C12_C11_1 + +#define ICH_MISR_EL2 S3_4_C12_C11_2 + +#define ICH_EISR_EL2 S3_4_C12_C11_3 + +#define ICH_ELRSR_EL2 S3_4_C12_C11_5 + +#define ICH_VMCR_EL2 S3_4_C12_C11_7 + +#define ICH_LR0_EL2 S3_4_C12_C12_0 +#define ICH_LR1_EL2 S3_4_C12_C12_1 +#define ICH_LR2_EL2 S3_4_C12_C12_2 +#define ICH_LR3_EL2 S3_4_C12_C12_3 +#define ICH_LR4_EL2 S3_4_C12_C12_4 +#define ICH_LR5_EL2 S3_4_C12_C12_5 +#define ICH_LR6_EL2 S3_4_C12_C12_6 +#define ICH_LR7_EL2 S3_4_C12_C12_7 +#define ICH_LR8_EL2 S3_4_C12_C13_0 +#define ICH_LR9_EL2 S3_4_C12_C13_1 +#define ICH_LR10_EL2 S3_4_C12_C13_2 +#define ICH_LR11_EL2 S3_4_C12_C13_3 +#define ICH_LR12_EL2 S3_4_C12_C13_4 +#define ICH_LR13_EL2 S3_4_C12_C13_5 +#define ICH_LR14_EL2 S3_4_C12_C13_6 +#define ICH_LR15_EL2 S3_4_C12_C13_7 + +#define FUNC_DEFINE(name) .global name ;\ + .type name, @function ;\ + name: + + +/** + * @name: + * @msg: void FGicSetICC_SRE_EL3(GICC_SRE_BITS bits) --- Interrupt Controller System Register Enable + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_SRE_EL3) + MSR ICC_SRE_EL3, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_SRE_EL2(GICC_SRE_BITS bits) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_SRE_EL2) + MSR ICC_SRE_EL2, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_SRE_EL1(GICC_SRE_BITS bits) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_SRE_EL1) + MSR ICC_SRE_EL1, x0 + ISB + RET + + + +/** + * @name: + * @msg: u32 FGicGetICC_SRE_EL3(void) -- Interrupt Controller System Register Enable + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_SRE_EL3) + MRS x0, ICC_SRE_EL3 + RET + +/** + * @name: + * @msg: u32 FGicGetICC_SRE_EL2(void) + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_SRE_EL2) + MRS x0, ICC_SRE_EL2 + RET + +/** + * @name: + * @msg: u32 FGicGetICC_SRE_EL1(void) + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_SRE_EL1) + MRS x0, ICC_SRE_EL1 + RET + + +/** + * @name: + * @msg: void FGicEnableGroup0(void) + * @return {*} + */ +FUNC_DEFINE(FGicEnableGroup0) + MOV w0, #1 + MSR ICC_IGRPEN0_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicDisableGroup0(void) + * @return {*} + */ +FUNC_DEFINE(FGicDisableGroup0) + MOV w0, #0 + MSR ICC_IGRPEN0_EL1, x0 + ISB + RET + + +/** + * @name: + * @msg: + * @return {*} + */ +FUNC_DEFINE(FGicEnableGroup1_EL3) + MOV w0, #1 + MSR ICC_IGRPEN1_EL3, x0 + ISB + RET + +/** + * @name: + * @msg: + * @return {*} + */ +FUNC_DEFINE(FGicEnableGroup1_EL1) + MOV w0, #1 + MSR ICC_IGRPEN1_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicDisableGroup1_EL1(void) + * @return {*} + */ +FUNC_DEFINE(FGicDisableGroup1_EL1) + MOV w0, #0 + MSR ICC_IGRPEN1_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicDisableGroup1_EL3(void) + * @return {*} + */ +FUNC_DEFINE(FGicDisableGroup1_EL3) + MOV w0, #0 + MSR ICC_IGRPEN1_EL3, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_CTLR_EL3(GICC_CTLR_BITS reg_bits) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_CTLR_EL3) + MSR ICC_CTLR_EL3, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_CTLR_EL1(GICC_CTLR_BITS reg_bits) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_CTLR_EL1) + MSR ICC_CTLR_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: u32 FGicGetICC_CTLR_EL3(void) -- Controls aspects of the behavior of the GIC CPU interface and provides information about the features implemented. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_CTLR_EL3) + MRS x0, ICC_CTLR_EL3 + RET + +/** + * @name: + * @msg: u32 FGicGetICC_CTLR_EL1(void) -- Controls aspects of the behavior of the GIC CPU interface and provides information about the features implemented. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_CTLR_EL1) + MRS x0, ICC_CTLR_EL1 + RET + +/** + * @name: + * @msg: u32 FGicWriteICC_APR0(void) -- The PE reads this register to obtain the INTID of the signaled Group 0 interrupt. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_APR0) + MRS x0, ICC_IAR0_EL1 + RET + +/** + * @name: + * @msg: u32 FGicGetICC_APR1(void) -- The PE reads this register to obtain the INTID of the signaled Group 1 interrupt. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_APR1) + MRS x0, ICC_IAR1_EL1 + RET + +/** + * @name: + * @msg: void FGicSetICC_EOIR0(u32 intnum) -- /* A PE writes to this register to inform the CPU interface that it has completed the processing of the specified Group 0 interrupt + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_EOIR0) + MSR ICC_EOIR0_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_EOIR1(u32 intnum) -- /* A PE writes to this register to inform the CPU interface that it has completed the processing of the specified Group 1 interrupt + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_EOIR1) + MSR ICC_EOIR1_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_DIR(u32 intnum) -- When interrupt priority drop is separated from interrupt deactivation, a write to this register deactivates the specified interrupt. + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_DIR) + MSR ICC_DIR_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_PMR(u32 priority_mask) -- Provides an interrupt priority filter. + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_PMR) + MSR ICC_PMR_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: u32 FGicGetICC_PMR(void) + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_PMR) + MRS x0,ICC_PMR_EL1 + RET + +/** + * @name: + * @msg: u32 FGicGetICC_BPR1(void) --- Defines the point at which the priority value fields split into two parts, the group priority field and the subpriority field. The group priority field determines Group 1 interrupt preemption. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_BPR1) + MRS x0,ICC_BPR1_EL1 + RET + +/** + * @name: + * @msg: void FGicSetICC_BPR1(u32 binary_point) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_BPR1) + MSR ICC_BPR1_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: u32 FGicGetICC_BPR0(void) --- Defines the point at which the priority value fields split into two parts, the group priority field and the subpriority field. The group priority field determines Group 0 interrupt preemption. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_BPR0) + MRS x0,ICC_BPR0_EL1 + RET + +/** + * @name: + * @msg: void FGicSetICC_BPR0(u32 binary_point) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_BPR0) + MSR ICC_BPR0_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: u32 FGicGetICC_HPPIR1(void) --- Indicates the highest priority pending Group 1 interrupt on the CPU interface. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_HPPIR1) + MRS x0,ICC_HPPIR1_EL1 + RET + +/** + * @name: + * @msg: void FGicSetICC_HPPIR1(u32 binary_point) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_HPPIR1) + MSR ICC_HPPIR1_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: u32 FGicGetICC_HPPIR0(void) --- Indicates the highest priority pending Group 0 interrupt on the CPU interface. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_HPPIR0) + MRS x0,ICC_HPPIR0_EL1 + RET + +/** + * @name: + * @msg: void FGicSetICC_HPPIR0(u32 binary_point) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_HPPIR0) + MSR ICC_HPPIR0_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: u32 FGicGetICC_RPR(void) --- Indicates the Running priority of the CPU interface. + * @return {*} + */ +FUNC_DEFINE(FGicGetICC_RPR) + MRS x0,ICC_RPR_EL1 + RET + +/* SGI interface */ +/** + * @name: + * @msg: void FGicSetICC_SGI0R(u32 intnum,u32 target_list,GICC_SGIR_IRM_BITS mode,u64 affinity_list) --- Generates Secure Group 0 SGIs + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_SGI0R) + ORR x0, x0, x1 + ORR x0, x0, x2 + ORR x0, x0, x3 + MSR ICC_SGI0R_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_SGI1R(u32 intnum,u32 target_list,GICC_SGIR_IRM_BITS mode,u64 affinity_list) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_SGI1R) + ORR x0, x0, x1 + ORR x0, x0, x2 + ORR x0, x0, x3 + MSR ICC_SGI1R_EL1, x0 + ISB + RET + +/** + * @name: + * @msg: void FGicSetICC_ASGI1R(u32 intnum,u32 target_list,GICC_SGIR_IRM_BITS mode,u64 affinity_list) + * @return {*} + */ +FUNC_DEFINE(FGicSetICC_ASGI1R) + ORR x0, x0, x1 + ORR x0, x0, x2 + ORR x0, x0, x3 + MSR ICC_ASGI1R_EL1, x0 + ISB + RET + + +#else + + + + +#endif + + diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_cpu_interface.h b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_cpu_interface.h new file mode 100644 index 0000000000..9bcdd84c7d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_cpu_interface.h @@ -0,0 +1,547 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic_cpu_interface.h + * Date: 2022-03-28 14:55:27 + * LastEditTime: 2022-03-28 14:55:27 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_CPU_INTERFACE_H +#define DRIVERS_CPU_INTERFACE_H +#include "ftypes.h" + + +#define FGIC_ICC_SGI1R_INTID_MASK 0xFULL /* The INTID of the SGI. */ + +#define GICC_SGIR_IRM_BITS SGI_ROUTING_MODE + +typedef enum +{ + GICC_SRE_SRE = (1 << 0), + GICC_SRE_DFB = (1 << 1), + GICC_SRE_DIB = (1 << 2), + GICC_SRE_ENABLE = (1 << 3) +} GICC_SRE_BITS; + +typedef enum +{ + GICC_CTLR_CBPR = (1 << 0), + GICC_CTLR_CBPR_EL1S = (1 << 0), + GICC_CTLR_EOIMODE = (1 << 1), + GICC_CTLR_CBPR_EL1NS = (1 << 1), + GICC_CTLR_EOIMODE_EL3 = (1 << 2), + GICC_CTLR_EOIMODE_EL1S = (1 << 3), + GICC_CTLR_EOIMODE_EL1NS = (1 << 4), /* GICC_EOIR and GICC_AEOIR provide priority drop functionality only. GICC_DIR provides interrupt deactivation functionality. */ + GICC_CTLR_RM = (1 << 5), + GICC_CTLR_PMHE = (1 << 6) +} GICC_CTLR_BITS; + + +#ifdef __aarch64__ + +void FGicSetICC_SRE_EL3(GICC_SRE_BITS bits); +void FGicSetICC_SRE_EL2(GICC_SRE_BITS bits); +void FGicSetICC_SRE_EL1(GICC_SRE_BITS bits); +u32 FGicGetICC_SRE_EL3(void); +u32 FGicGetICC_SRE_EL2(void); +u32 FGicGetICC_SRE_EL1(void); +void FGicEnableGroup0(void); +void FGicDisableGroup0(void); +void FGicEnableGroup1_EL1(void); +void FGicEnableGroup1_EL3(void); +void FGicDisableGroup1_EL1(void); +void FGicDisableGroup1_EL3(void); +void FGicSetICC_CTLR_EL3(GICC_CTLR_BITS reg_bits); +void FGicSetICC_CTLR_EL1(GICC_CTLR_BITS reg_bits); +u32 FGicGetICC_CTLR_EL3(void); +u32 FGicGetICC_CTLR_EL1(void); +u32 FGicWriteICC_APR0(void); +s32 FGicGetICC_APR1(void); +void FGicSetICC_EOIR0(u32 intnum); +void FGicSetICC_EOIR1(u32 intnum); +void FGicSetICC_DIR(u32 intnum); +void FGicSetICC_PMR(u32 priority_mask); +u32 FGicGetICC_PMR(void); +u32 FGicGetICC_BPR1(void); +void FGicSetICC_BPR1(u32 binary_point); +u32 FGicGetICC_BPR0(void); +void FGicSetICC_BPR0(u32 binary_point); +u32 FGicGetICC_HPPIR1(void); +void FGicSetICC_HPPIR1(u32 binary_point); +u32 FGicGetICC_HPPIR0(void); +void FGicSetICC_HPPIR0(u32 binary_point); +u32 FGicGetICC_RPR(void); +/* SGI interface */ +void FGicSetICC_SGI0R(u32 intnum, u32 target_list, GICC_SGIR_IRM_BITS mode, u64 affinity_list); +void FGicSetICC_SGI1R(u32 intnum, u32 target_list, GICC_SGIR_IRM_BITS mode, u64 affinity_list); +void FGicSetICC_ASGI1R(u32 intnum, u32 target_list, GICC_SGIR_IRM_BITS mode, u64 affinity_list); + + + +#else /* aarch32 */ + + + +/* For AArch32 state, accesses to GIC registers that are visible in the System register */ +#define FGIC_SYS_READ32(CR, Rt) __asm__ volatile("MRC " CR \ + : "=r"(Rt) \ + : \ + : "memory") +#define FGIC_SYS_WRITE32(CR, Rt) __asm__ volatile("MCR " CR \ + : \ + : "r"(Rt) \ + : "memory") + +#define FGIC_SYS_WRITE64(cp, op1, Rt, CRm) __asm__ volatile("MCRR p" #cp ", " #op1 ", %Q0, %R0, c" #CRm \ + : \ + : "r"(Rt) \ + : "memory") + + +#define ICC_IAR0 "p15, 0, %0, c12, c8, 0" +#define ICC_IAR1 "p15, 0, %0, c12, c12, 0" +/* writes to this register to inform the CPU interface +that it has completed the processing */ +#define ICC_EOIR0 "p15, 0, %0, c12, c8, 1" +#define ICC_EOIR1 "p15, 0, %0, c12, c12, 1" +/* GET the INTID of highest priority pending interrupt */ +#define ICC_HPPIR0 "p15, 0, %0, c12, c8, 2" +#define ICC_HPPIR1 "p15, 0, %0, c12, c12, 2" +#define ICC_BPR0 "p15, 0, %0, c12, c8, 3" +#define ICC_BPR1 "p15, 0, %0, c12, c12, 3" +#define ICC_DIR "p15, 0, %0, c12, c11, 1" +#define ICC_PMR "p15, 0, %0, c4, c6, 0" +#define ICC_RPR "p15, 0, %0, c12, c11, 3" +#define ICC_CTLR "p15, 0, %0, c12, c12, 4" +#define ICC_MCTLR "p15, 6, %0, c12, c12, 4" +#define ICC_SRE "p15, 0, %0, c12, c12, 5" +#define ICC_HSRE "p15, 4, %0, c12, c9, 5" +#define ICC_MSRE "p15, 6, %0, c12, c12, 5" +#define ICC_IGRPEN0 "p15, 0, %0, c12, c12, 6" +#define ICC_IGRPEN1 "p15, 0, %0, c12, c12, 7" +#define ICC_MGRPEN1 "p15, 6, %0, c12, c12, 7" + +#define FGicSetICC_SRE_EL1 FGicSetICC_SRE +#define FGicSetICC_SRE_EL2 FGicSetICC_SRE +#define FGicSetICC_SRE_EL3 FGicSetICC_SRE + +/** + * @name: + * @msg: void FGicSetICC_SRE(GICC_SRE_BITS bits) --- Interrupt Controller System Register Enable + * @return {*} + */ +static inline void FGicSetICC_SRE(GICC_SRE_BITS bits) +{ + FGIC_SYS_WRITE32(ICC_SRE, (u32)bits); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + + +#define FGicGetICC_SRE_EL3 FGicGetICC_SRE +#define FGicGetICC_SRE_EL2 FGicGetICC_SRE +#define FGicGetICC_SRE_EL1 FGicGetICC_SRE + +/** + * @name: + * @msg: u32 FGicGetICC_SRE(void) -- Interrupt Controller System Register Enable + * @return {*} + */ +static inline u32 FGicGetICC_SRE(void) +{ + u32 value; + + FGIC_SYS_READ32(ICC_SRE, value); + return value; +} + + +/** + * @name: + * @msg: void FGicEnableGroup0(void) + * @return {*} + */ +static inline void FGicEnableGroup0(void) +{ + u32 value = 1; + FGIC_SYS_WRITE32(ICC_IGRPEN0, value); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: void FGicDisableGroup0(void) + * @return {*} + */ +static inline void FGicDisableGroup0(void) +{ + u32 value = 0; + FGIC_SYS_WRITE32(ICC_IGRPEN0, value); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + + +#define FGicEnableGroup1_EL3 FGicEnableGroup1 +#define FGicEnableGroup1_EL1 FGicEnableGroup1 + +/** + * @name: + * @msg: + * @return {*} + */ +static inline void FGicEnableGroup1(void) +{ + u32 value = 1; + FGIC_SYS_WRITE32(ICC_IGRPEN1, value); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + + + +#define FGicDisableGroup1_EL3 FGicDisableGroup1 +#define FGicDisableGroup1_EL1 FGicDisableGroup1 + +/** + * @name: + * @msg: void FGicDisableGroup1(void) + * @return {*} + */ +static inline void FGicDisableGroup1(void) +{ + u32 value = 0; + FGIC_SYS_WRITE32(ICC_IGRPEN1, value); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +#define FGicSetICC_CTLR_EL3 FGicSetICC_CTLR +#define FGicSetICC_CTLR_EL1 FGicSetICC_CTLR + +/** + * @name: + * @msg: void FGicSetICC_CTLR(GICC_CTLR_BITS reg_bits) + * @return {*} + */ +static inline void FGicSetICC_CTLR(GICC_CTLR_BITS bits) +{ + FGIC_SYS_WRITE32(ICC_CTLR, bits); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +#define FGicGetICC_CTLR_EL3 FGicGetICC_CTLR +#define FGicGetICC_CTLR_EL1 FGicGetICC_CTLR + +/** + * @name: + * @msg: static inline u32 FGicGetICC_CTLR(void) -- Controls aspects of the behavior of the GIC CPU interface and provides information about the features implemented. + * @return {*} + */ +static inline u32 FGicGetICC_CTLR(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_CTLR, reg); + return reg; +} + +/** + * @name: + * @msg: static inline u32 FGicWriteICC_APR0(void) -- The PE reads this register to obtain the INTID of the signaled Group 0 interrupt. + * @return {*} + */ +static inline u32 FGicWriteICC_APR0(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_IAR0, reg); + return reg; +} + + +/** + * @name: + * @msg: static inline s32 FGicGetICC_APR1(void) -- The PE reads this register to obtain the INTID of the signaled Group 1 interrupt. + * @return {*} + */ +static inline s32 FGicGetICC_APR1(void) +{ + s32 reg; + FGIC_SYS_READ32(ICC_IAR1, reg); + return reg; +} + + +/** + * @name: + * @msg: static inline void FGicSetICC_EOIR0(u32 intnum) -- /* A PE writes to this register to inform the CPU interface that it has completed the processing of the specified Group 0 interrupt + * @return {*} + * @param {u32} intnum + */ +static inline void FGicSetICC_EOIR0(u32 intnum) +{ + FGIC_SYS_WRITE32(ICC_EOIR0, intnum); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + + +/** + * @name: + * @msg: static inline void FGicSetICC_EOIR1(u32 intnum) -- /* A PE writes to this register to inform the CPU interface that it has completed the processing of the specified Group 1 interrupt + * @return {*} + */ +static inline void FGicSetICC_EOIR1(u32 intnum) +{ + FGIC_SYS_WRITE32(ICC_EOIR1, intnum); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: static inline void FGicSetICC_DIR(u32 intnum) -- When interrupt priority drop is separated from interrupt deactivation, a write to this register deactivates the specified interrupt. + * @return {*} + */ +static inline void FGicSetICC_DIR(u32 intnum) +{ + FGIC_SYS_WRITE32(ICC_DIR, intnum); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: static inline void FGicSetICC_PMR(u32 priority_mask) -- Provides an interrupt priority filter. + * @return {*} + */ +/** + * @name: + * @msg: + * @param {u32} priority_mask is level for the CPU interface. If the priority of an interrupt is higher than the value + * indicated by this field, the interface signals the interrupt to the PE. + */ +static inline void FGicSetICC_PMR(u32 priority_mask) +{ + FGIC_SYS_WRITE32(ICC_PMR, priority_mask); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + + +/** + * @name: + * @msg: static inline u32 FGicGetICC_PMR(void) + * @return {*} + */ +static inline u32 FGicGetICC_PMR(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_PMR, reg); + return reg; +} + + +/** + * @name: + * @msg: static inline u32 FGicGetICC_BPR1(void) --- Defines the point at which the priority value fields split into two parts, the group priority field and the subpriority field. The group priority field determines Group 1 interrupt preemption. + * @return {*} + */ +static inline u32 FGicGetICC_BPR1(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_BPR1, reg); + return reg; +} + +/** + * @name: + * @msg: static inline void FGicSetICC_BPR1(u32 binary_point) + * @return {*} + */ +static inline void FGicSetICC_BPR1(u32 binary_point) +{ + FGIC_SYS_WRITE32(ICC_BPR1, binary_point); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: static inline u32 FGicGetICC_BPR0(void) --- Defines the point at which the priority value fields split into two parts, the group priority field and the subpriority field. The group priority field determines Group 0 interrupt preemption. + * @return {*} + */ +static inline u32 FGicGetICC_BPR0(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_BPR0, reg); + return reg; +} + + +/** + * @name: + * @msg: static inline void FGicSetICC_BPR0(u32 binary_point) + * @return {*} + */ +static inline void FGicSetICC_BPR0(u32 binary_point) +{ + FGIC_SYS_WRITE32(ICC_BPR0, binary_point); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: static inline u32 FGicGetICC_HPPIR1(void) --- Indicates the highest priority pending Group 1 interrupt on the CPU interface. + * @return {*} + */ +static inline u32 FGicGetICC_HPPIR1(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_HPPIR1, reg); + return reg; +} + + +/** + * @name: + * @msg: static inline void FGicSetICC_HPPIR1(u32 binary_point) + * @return {*} + */ +static inline void FGicSetICC_HPPIR1(u32 binary_point) +{ + FGIC_SYS_WRITE32(ICC_HPPIR1, binary_point); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: static inline u32 FGicGetICC_HPPIR0(void) --- Indicates the highest priority pending Group 0 interrupt on the CPU interface. + * @return {*} + */ +static inline u32 FGicGetICC_HPPIR0(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_HPPIR0, reg); + return reg; +} + + +/** + * @name: + * @msg: static inline void FGicSetICC_HPPIR0(u32 binary_point) + * @return {*} + */ +static inline void FGicSetICC_HPPIR0(u32 binary_point) +{ + FGIC_SYS_WRITE32(ICC_HPPIR0, binary_point); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: static inline u32 FGicGetICC_RPR(void) --- Indicates the Running priority of the CPU interface. + * @return {*} + */ +static inline u32 FGicGetICC_RPR(void) +{ + u32 reg; + FGIC_SYS_READ32(ICC_RPR, reg); + return reg; +} +/* SGI interface */ + +/** + * @name: + * @msg: static inline void FGicSetICC_SGI0R(u32 intnum,u32 target_list,GICC_SGIR_IRM_BITS mode,u64 affinity_list) --- Generates Secure Group 0 SGIs + * @return {*} + */ +/** + * @name: + * @msg: + * @return {*} + * @param {u32} intnum_bit + * @param {u32} target_list + * @param {GICC_SGIR_IRM_BITS} irm_bit + * @param {u64} affinity_list + */ +static inline void FGicSetICC_SGI0R(u32 intnum_bit, u32 target_list, GICC_SGIR_IRM_BITS irm_bit, u64 affinity_list) +{ + u64 sgi_val; + sgi_val = intnum_bit; /* The INTID of the SGI. */ + sgi_val |= affinity_list ; /* Aff3.Aff2.Aff1 */ + sgi_val |= irm_bit ; /* Interrupt Routing Mode. */ + sgi_val |= target_list; /* Target List. The set of PEs for which SGI interrupts will be generated. */ + + __asm__ volatile("dsb 0xF" :: + : "memory"); + FGIC_SYS_WRITE64(15, 2, sgi_val, 12); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + +/** + * @name: + * @msg: static inline void FGicSetICC_SGI1R(u32 intnum,u32 target_list,GICC_SGIR_IRM_BITS mode,u64 affinity_list) + * @return {*} + */ +static inline void FGicSetICC_SGI1R(u32 intnum_bit, u32 target_list, GICC_SGIR_IRM_BITS irm_bit, u64 affinity_list) +{ + u64 sgi_val; + sgi_val = intnum_bit; /* The INTID of the SGI. */ + sgi_val |= affinity_list ; /* Aff3.Aff2.Aff1 */ + sgi_val |= irm_bit ; /* Interrupt Routing Mode. */ + sgi_val |= target_list; /* Target List. The set of PEs for which SGI interrupts will be generated. */ + + __asm__ volatile("dsb 0xF" :: + : "memory"); + FGIC_SYS_WRITE64(15, 0, sgi_val, 12); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + + +/** + * @name: + * @msg: static inline void FGicSetICC_ASGI1R(u32 intnum,u32 target_list,GICC_SGIR_IRM_BITS mode,u64 affinity_list) + * @return {*} + */ +static inline void FGicSetICC_ASGI1R(u32 intnum_bit, u32 target_list, GICC_SGIR_IRM_BITS irm_bit, u64 affinity_list) +{ + u64 sgi_val; + sgi_val = intnum_bit; /* The INTID of the SGI. */ + sgi_val |= affinity_list ; /* Aff3.Aff2.Aff1 */ + sgi_val |= irm_bit ; /* Interrupt Routing Mode. */ + sgi_val |= target_list; /* Target List. The set of PEs for which SGI interrupts will be generated. */ + + __asm__ volatile("dsb 0xF" :: + : "memory"); + FGIC_SYS_WRITE64(15, 1, sgi_val, 12); + __asm__ volatile("isb 0xF" :: + : "memory"); +} + + +#endif + +#endif + diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_distributor.h b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_distributor.h new file mode 100644 index 0000000000..1c163dd1fb --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_distributor.h @@ -0,0 +1,165 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic_distributor.h + * Date: 2022-03-28 15:18:56 + * LastEditTime: 2022-03-28 15:18:56 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#ifndef DRIVERS_GIC_FGIC_DISTRIBUTOR_H +#define DRIVERS_GIC_FGIC_DISTRIBUTOR_H + +#include "fgic.h" +#include "fgic_hw.h" +#include "ftypes.h" + +#define GICD_ICFGR_MODE TRIGGER_LEVEL +#define GICD_IRPITER_MODE SPI_ROUTING_MODE + +typedef enum +{ + GICD_CTLR_ENABLE_GRP0 = (1 << 0), + GICD_CTLR_ENABLE_GRP1_NS = (1 << 1), + GICD_CTLR_ENABLE_GRP1A = (1 << 1), + GICD_CTLR_ENABLE_GRP1S = (1 << 2), + GICD_CTLR_ENABLE_ALL = (1 << 2) | (1 << 1) | (1 << 0), + GICD_CTLR_BIT_ARE_S = (1 << 4), /* Enable Secure state affinity routing , for single Security state ,this bit is */ + GICD_CTLR_BIT_ARE_NS = (1 << 5), /* Enable Non-Secure state affinity routing */ + GICD_CTLR_BIT_DS = (1 << 6), /* Disable Security support */ + GICD_CTLR_BIT_E1NWF = (1 << 7) /* Enable "1-of-N" wakeup model */ +} GICD_CTLR_VALUE; + +typedef enum +{ + GICD_GROUP_G0S = 0, + GICD_GROUP_G1NS = (1 << 0), + GICD_GROUP_G1S = (1 << 2), +} GICD_GROUP_SECURE_MODE; + +static inline void FGicSetGicd(uintptr dist_base, GICD_CTLR_VALUE ctrl_value) +{ + FGIC_GICD_CTLR_WRITE(dist_base, ctrl_value); +} + +/** + * @name: FGicEnableSPI + * @msg: configure the priority for a shared peripheral interrupt + * @param {FGic} *gic_p is a pointer to the FGic instance. + * @param {u32} spi_id spi interrupt identifier ,value range 32-1019 + */ +static inline void FGicEnableSPI(uintptr dist_base, u32 spi_id) +{ + FGIC_GICD_ISENABLER_WRITE_N_MASK(dist_base, spi_id, (1U << (spi_id % 32))); +} + +static inline void FGicDisableSPI(uintptr dist_base, u32 spi_id) +{ + FGIC_GICD_ICENABLER_WRITE_N_MASK(dist_base, spi_id, (1U << (spi_id % 32))); +} + +static inline void FGicSetSpiPriority(uintptr dist_base, u32 spi_id, u32 priority) +{ + u32 mask; + + /* For SPIs , has one byte-wide entry per interrupt */ + mask = FGIC_GICD_IPRIORITYR_READ_N_MASK(dist_base, spi_id); + mask &= ~FGIC_GICD_IPRIORITYR_VALUE_MASK(spi_id); + mask |= ((priority & 0xffU) << (spi_id % 4) * 8U); + FGIC_GICD_IPRIORITYR_WRITE_N_MASK(dist_base, spi_id, mask); +} + +static inline u32 FGicGetSpiPriority(uintptr dist_base, u32 spi_id) +{ + u32 mask; + + /* For SPIs , has one byte-wide entry per interrupt */ + mask = FGIC_GICD_IPRIORITYR_READ_N_MASK(dist_base, spi_id); + + return (mask >> ((spi_id % 4U) * 8U)) & 0xFFU ; +} + +static inline void FGicSetSpiRoute(uintptr dist_base, u32 spi_id, GICD_IRPITER_MODE route_mode, u64 affinity) +{ + u32 bank; + + /* For SPIs ,has one doubleword-wide entry per interrupt */ + bank = spi_id & FGIC_GICD_IROUTER_RANGE_LIMIT; + __asm__ volatile("dsb 0xF" ::: "memory"); + FGIC_GICD_IROUTER_WRITE(dist_base, bank, affinity | route_mode); + __asm__ volatile("isb 0xF" ::: "memory"); +} + +static inline u64 FGicGetSpiRoute(uintptr dist_base, u32 spi_id) +{ + u32 bank; + /* For SPIs ,has one doubleword-wide entry per interrupt */ + bank = spi_id & FGIC_GICD_IROUTER_RANGE_LIMIT; + return FGIC_GICD_IROUTER_READ(dist_base, bank); +} + +static inline void FGicSetSpiLevel(uintptr dist_base, u32 spi_id, GICD_ICFGR_MODE mode) +{ + u32 mask ; + mask = FGIC_GICD_ICFGR_READ_N_MASK(dist_base, spi_id); + mask &= ~FGIC_GICD_ICFGR_VALUE_MASK(spi_id); + mask |= (mode << FGIC_GICD_ICFGR_VALUE_OFFSET(spi_id)); + FGIC_GICD_ICFGR_WRITE_N_MASK(dist_base, spi_id, mask); +} + +static inline u32 FGicGetSpiLevel(uintptr dist_base, u32 spi_id) +{ + u32 mask ; + mask = FGIC_GICD_ICFGR_READ_N_MASK(dist_base, spi_id); + return (mask >> ((spi_id % 16U) >> 1U)) ; +} + +static inline void FGicSetSpiSecurity(uintptr dist_base, u32 spi_id, GICD_GROUP_SECURE_MODE mode) +{ + u32 mask ; + /* Group status */ + mask = FGIC_GICD_IGROUPR_READ_N_MASK(dist_base, spi_id); + mask &= ~FGIC_GICD_IGROUPR_VALUE_MASK(spi_id); + + mask |= ((mode & 0x1) << (spi_id % 32)); + FGIC_GICD_IGROUPR_WRITE_N_MASK(dist_base, spi_id, mask); + + /* Group modifier */ + mask = FGIC_GICD_IGRPMODR_READ_N_MASK(dist_base, spi_id); + mask &= ~FGIC_GICD_IGRPMODR_VALUE_MASK(spi_id); + + mask |= (((mode & 0x2) >> 1) << (spi_id % 32)); + FGIC_GICD_IGRPMODR_WRITE_N_MASK(dist_base, spi_id, mask); +} + +static inline u32 FGicGetSpiSecurity(uintptr dist_base, u32 spi_id) +{ + u32 mask ; + u32 group_status, group_modifier; + /* Group status */ + mask = FGIC_GICD_IGROUPR_READ_N_MASK(dist_base, spi_id); + mask &= FGIC_GICD_IGROUPR_VALUE_MASK(spi_id); + group_status = (mask >> (spi_id % 32)); + + /* Group modifier */ + mask = FGIC_GICD_IGRPMODR_READ_N_MASK(dist_base, spi_id); + mask &= FGIC_GICD_IGRPMODR_VALUE_MASK(spi_id); + group_modifier = (mask >> (spi_id % 32)); + + return ((group_modifier << 1) | group_status); +} + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_g.c b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_g.c new file mode 100644 index 0000000000..3f40151fc7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_g.c @@ -0,0 +1,32 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic_g.c + * Date: 2022-03-30 14:57:43 + * LastEditTime: 2022-03-30 14:57:43 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "fparameters.h" +#include "fgic.h" + +FGicConfig fgic_config[FGIC_NUM] = +{ + { + .instance_id = 0, /* Id of device */ + .dis_base = GICV3_DISTRIBUTOR_BASEADDRESS, /* Distributor base address */ + } +}; \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_hw.h b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_hw.h new file mode 100644 index 0000000000..a8947ebbef --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_hw.h @@ -0,0 +1,315 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic_hw.h + * Date: 2022-03-24 11:44:48 + * LastEditTime: 2022-03-24 11:44:48 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_GIC_FGIC_HW_H +#define DRIVERS_GIC_FGIC_HW_H + +#include "ftypes.h" +#include "fio.h" +#include "fkernel.h" + +/* Distributor */ +#define FGIC_GICD_CTLR_OFFSET 0x00000000U /* Distributor Control Register ,RW */ +#define FGIC_GICD_TYPER_OFFSET 0x00000004U /* Interrupt Controller Type Register ,RO */ +#define FGIC_GICD_IIDR_OFFSET 0x00000008U /* Distributor Implementer Identification Register ,RO */ +#define FGIC_GICD_TYPER2_OFFSET 0x0000000CU /* Interrupt controller Type Register 2,RO */ +#define FGIC_GICD_STATUSR_OFFSET 0x00000010U /* Error Reporting Status Register, optional ,RW */ +#define FGIC_GICD_SETSPI_NSR_OFFSET 0x00000040U /* Set SPI Register ,WO */ +#define FGIC_GICD_CLRSPI_NSR_OFFSET 0x00000048U /* Clear SPI Register ,WO */ +#define FGIC_GICD_SETSPI_SR_OFFSET 0x00000050U /* Set SPI, Secure Register ,WO */ +#define FGIC_GICD_CLRSPI_SR_OFFSET 0x00000058U /* Clear SPI, Secure Register ,WO */ +#define FGIC_GICD_IGROUPR_OFFSET 0x00000080U /* Interrupt Group Registers ,RW */ + +#define FGIC_GICD_ISENABLER_OFFSET 0x00000100U /* Interrupt Set-Enable Registers ,RW */ +#define FGIC_GICD_ICENABLER_OFFSET 0x00000180U /* Interrupt Clear-Enable Registers ,RW */ +#define FGIC_GICD_ISPENDR_OFFSET 0x00000200U /* Interrupt Set-Pending Registers ,RW */ +#define FGIC_GICD_ICPENDR_OFFSET 0x00000280U /* Interrupt Clear-Pending Registers ,RW */ +#define FGIC_GICD_ISACTIVER_OFFSET 0x00000300U /* Interrupt Set-Active Registers ,RW */ +#define FGIC_GICD_ICACTIVER_OFFSET 0x00000380U /* Interrupt Clear-Active Registers ,RW */ +#define FGIC_GICD_IPRIORITYR_OFFSET 0x00000400U /* Interrupt Priority Registers ,RW */ +#define FGIC_GICD_ITARGETSR_OFFSET 0x00000800U /* Interrupt Processor Targets Registers ,RO */ + +#define FGIC_GICD_ICFGR_OFFSET 0x00000C00U /* Interrupt Configuration Registers ,RW */ +#define FGIC_GICD_IGRPMODR_OFFSET 0x00000D00U /* Interrupt Group Modifier Registers */ + +#define FGIC_GICD_NSACR_OFFSET 0x00000E00U /* Non-secure Access Control ,RW */ +#define FGIC_GICD_SGIR_OFFSET 0x00000F00U /* Software Generated Interrupt Register ,WO */ +#define FGIC_GICD_CPENDSGIR_OFFSET 0x00000F10U /* SGI Clear-Pending Registers ,RW */ +#define FGIC_GICD_SPENDSGIR_OFFSET 0x00000F20U /* SGI Set-Pending Registers ,RW */ + +#define FGIC_GICD_IGROUPR_E_OFFSET 0x00001000U /* Interrupt Group Registers for extended SPI ,RW */ + +#define FGIC_GICD_ISENABLER_E_OFFSET 0x00001200U /* Interrupt Set-Enable for extended SPI ,RW */ + +#define FGIC_GICD_ICENABLER_E_OFFSET 0x00001400U /* Interrupt Clear-Enable for extended SPI ,RW */ + +#define FGIC_GICD_ISPENDR_E_OFFSET 0x00001600U /* Interrupt Set-Pend for extended SPI range ,RW */ +#define FGIC_GICD_ICPENDR_E_OFFSET 0x00001800U /* Interrupt Clear-Pend for extended SPI ,RW */ + +#define FGIC_GICD_ISACTIVER_E_OFFSET 0x00001A00U /* Interrupt Set-Active for extended SPI ,RW */ + +#define FGIC_GICD_ICACTIVER_E_OFFSET 0x00001C00U /* Interrupt Clear-Active for extended SPI ,RW */ + +#define FGIC_GICD_IPRIORITYR_E_OFFSET 0x00002000U /* Interrupt Priority for extended SPI range ,RW */ +#define FGIC_GICD_ICFGR_E_OFFSET 0x00003000U /* Extended SPI Configuration Register ,RW */ +#define FGIC_GICD_IGRPMODR_E_OFFSET 0x00003400U /* Interrupt Group Modifier for extended SPI ,RW */ +#define FGIC_GICD_NSACR_E_OFFSET 0x00003600U /* Non-secure Access Control Registers for extended SPI range ,RW */ + +#define FGIC_GICD_IROUTER_OFFSET 0x00006000U /* Interrupt Routing Registers ,RW ,The offset of the GICD_IROUTER register is 0x6000 + 8n. */ +#define FGIC_GICD_IROUTER_E_OFFSET 0x00008000U /* Interrupt Routing Registers for extended SPI range ,RW */ + +/* Redistributor - RD_BASE */ +/* Each Redistributor defines two 64KB frames in the physical address map */ +#define FGIC_GICR_CTLR_OFFSET 0x00000000U /* See the register description Redistributor Control Register ,RW */ +#define FGIC_GICR_IIDR_OFFSET 0x00000004U /* Implementer Identification Register ,RO */ +#define FGIC_GICR_TYPER_OFFSET 0x00000008U /* Redistributor Type Register ,RO */ +#define FGIC_GICR_STATUSR_OFFSET 0x00000010U /* Error Reporting Status Register, optional ,RW */ +#define FGIC_GICR_WAKER_OFFSET 0x00000014U /* See the register description Redistributor Wake Register ,RW */ +#define FGIC_GICR_MPAMIDR_OFFSET 0x00000018U /* Report maximum PARTID and PMG Register ,RO */ +#define FGIC_GICR_PARTIDR_OFFSET 0x0000001CU /* Set PARTID and PMG Register ,RW */ + +#define FGIC_GICR_SETLPIR_OFFSET 0x00000040U /* Set LPI Pending Register ,WO */ +#define FGIC_GICR_CLRLPIR_OFFSET 0x00000048U /* Clear LPI Pending Register ,WO */ + +#define FGIC_GICR_PROPBASER_OFFSET 0x00000070U /* Redistributor Properties Base Address Register ,RW */ +#define FGIC_GICR_PENDBASER_OFFSET 0x00000078U /* Redistributor LPI Pending Table Base Address Register ,RW */ + +/* Redistributor - SGI_BASE */ + +#define FGIC_GICR_SGI_BASE_OFFSET 0x10000U /* 64KB frames */ + +#define FGIC_GICR_IGROUPR0_OFFSET 0x00000080U /* Interrupt Group Register 0 ,RW */ +#define FGIC_GICR_IGROUPR_E_OFFSET 0x00000084U /* Interrupt Group Registers for extended PPI range ,RW */ + +#define FGIC_GICR_ISENABLER0_OFFSET 0x00000100U /* Interrupt Set-Enable Register 0 ,RW */ +#define FGIC_GICR_ISENABLER_E_OFFSET 0x00000104U /* Interrupt Set-Enable for extended PPI range ,RW */ + +#define FGIC_GICR_ICENABLER0_OFFSET 0x00000180U /* Interrupt Clear-Enable Register 0 ,RW */ +#define FGIC_GICR_ICENABLER_E_OFFSET 0x00000184U /* Interrupt Clear-Enable for extended PPI range ,RW */ + + +#define FGIC_GICR_ISPENDR0_OFFSET 0x00000200U /* Interrupt Set-Pend Register 0 ,RW */ +#define FGIC_GICR_ISPENDR_E_OFFSET 0x00000204U /* Interrupt Set-Pend for extended PPI range ,RW */ + +#define FGIC_GICR_ICPENDR0_OFFSET 0x00000280U /* Interrupt Clear-Pend Register 0 ,RW */ + +#define FGIC_GICR_ICPENDR_E_OFFSET 0x00000284U /* Interrupt Clear-Pend for extended PPI range ,RW */ + +#define FGIC_GICR_ISACTIVER0_OFFSET 0x00000300U /* Interrupt Set-Active Register 0 ,RW */ +#define FGIC_GICR_ISACTIVER_E_OFFSET 0x00000304U /* Interrupt Set-Active for extended PPI range ,RW */ + +#define FGIC_GICR_ICACTIVER0_OFFSET 0x00000380U /* Interrupt Clear-Active Register 0 ,RW */ +#define FGIC_GICR_ICACTIVER_E_OFFSET 0x00000384U /* Interrput Clear-Active for extended PPI range ,RW */ + +#define FGIC_GICR_IPRIORITYR_OFFSET 0x00000400U /* Interrupt Priority Registers ,RW */ +#define FGIC_GICR_IPRIORITYR_E_OFFSET 0x00000420U /* Interrupt Priority for extended PPI range ,RW */ + +#define FGIC_GICR_ICFGR0_OFFSET 0x00000C00U /* SGI Configuration Register ,RW*/ +#define FGIC_GICR_ICFGR1_OFFSET 0x00000C04U /* PPI Configuration Register ,RW*/ + +#define FGIC_GICR_ICFGR_E_OFFSET 0x00000C08U /* Extended PPI Configuration Register ,RW */ +#define FGIC_GICR_IGRPMODR0_OFFSET 0x00000D00U /* Interrupt Group Modifier Register 0 ,RW */ + +#define FGIC_GICR_IGRPMODR_E_OFFSET 0x00000D04U /* Interrupt Group Modifier for extended PPI range ,RW */ + +#define FGIC_GICR_NSACR_OFFSET 0x00000E00U /* Non-Secure Access Control Register ,RW */ + +#define FGIC_READREG8(addr, reg_offset) FtIn8(addr + (u8)reg_offset) +#define FGIC_WRITEREG8(addr, reg_offset, reg_value) FtOut8(addr + (u8)reg_offset, (u8)reg_value) + +#define FGIC_READREG32(addr, reg_offset) FtIn32(addr + (u32)reg_offset) +#define FGIC_WRITEREG32(addr, reg_offset, reg_value) FtOut32(addr + (u32)reg_offset, (u32)reg_value) + +#define FGIC_READREG64(addr, reg_offset) FtIn64(addr + (u64)reg_offset) +#define FGIC_WRITEREG64(addr, reg_offset, reg_value) FtOut64(addr +(u64)reg_offset, (u64)reg_value) + + +#define FGIC_SETBIT(base_addr, reg_offset, data) \ + FtSetBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FGIC_CLEARBIT(base_addr, reg_offset, data) \ + FtClearBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +/* FGIC_GICD_CTLR_OFFSET --- Distributor switch */ +#define FGIC_GICD_CTLR_RWP_MASK BIT(31) +#define FGIC_GICD_CTLR_DS_MASK BIT(6) + +/* Need check system whether support Security states */ + +#define FGIC_GICD_CTLR_WRITE(gicd_base, reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_CTLR_OFFSET, reg) +#define FGIC_GICD_CTLR_READ(gicd_base) FGIC_READREG32(gicd_base , FGIC_GICD_CTLR_OFFSET) + +/* FGIC_GICD_ISENABLER_OFFSET --- SPI Open */ +#define FGIC_GICD_ISENABLER_VALUE_OFFSET(itnum) ((itnum % 32U)) +#define FGIC_GICD_ISENABLER_VALUE_MASK(itnum) (0x1U << FGIC_GICD_ISENABLER_VALUE_OFFSET(itnum)) +#define FGIC_GICD_ISENABLER_READ_N_MASK(gicd_base,itnum) FGIC_READREG32(gicd_base , FGIC_GICD_ISENABLER_OFFSET + ((itnum >> 5)<<2) ) +#define FGIC_GICD_ISENABLER_WRITE_N_MASK(gicd_base,itnum,reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_ISENABLER_OFFSET + ((itnum >> 5)<<2), reg) + +/* FGIC_GICD_TYPER_OFFSET --- Provides information about what features the GIC implementation supports. */ +#define FGIC_GICD_TYPER_ITLINESNUMBER_MASK 0x1f + + +/* FGIC_GICD_ICENABLER_OFFSET --- SPI close */ +#define FGIC_GICD_ICENABLER_DEFAULT_MASK BIT_MASK(32) +#define FGIC_GICD_ICENABLER_VALUE_OFFSET(itnum) ((itnum % 32U)) +#define FGIC_GICD_ICENABLER_VALUE_MASK(itnum) (0x1U << FGIC_GICD_ICENABLER_VALUE_OFFSET(itnum)) +#define FGIC_GICD_ICENABLER_READ_N_MASK(gicd_base,itnum) FGIC_READREG32(gicd_base , FGIC_GICD_ICENABLER_OFFSET + ((itnum >> 5)<<2) ) +#define FGIC_GICD_ICENABLER_WRITE_N_MASK(gicd_base,itnum,reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_ICENABLER_OFFSET + ((itnum >> 5)<<2), reg) + + +/* FGIC_GICD_IPRIORITYR_OFFSET --- SPI priority */ +#define FGIC_GICD_IPRIORITYR_VALUE_MASK(itnum) (0xFFU << ((itnum % 4U) << 3)) +#define FGIC_GICD_IPRIORITYR_READ_N_MASK(gicd_base,itnum) FGIC_READREG32(gicd_base , FGIC_GICD_IPRIORITYR_OFFSET + ((itnum >> 2)<<2) ) +#define FGIC_GICD_IPRIORITYR_WRITE_N_MASK(gicd_base,itnum,reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_IPRIORITYR_OFFSET + ((itnum >> 2)<<2), reg) + +/* FGIC_GICD_IROUTER_OFFSET --- SPI Routing */ +#define FGIC_GICD_IROUTER_AFFINITY_MASK (((0xFFULL) <<32)|((0xFFULL) <<16)|((0xFFULL)<<8)|(0xFFULL)) /* affinity mask */ +#define FGIC_GICD_IROUTER_RANGE_LIMIT (1023) /* GICD_IROUTER, Interrupt Routing Registers, n = 0 - 1019 */ +#define FGIC_GICD_IROUTER_BYTE_WIDTH 8 +#define FGIC_GICD_IROUTER_WRITE(gicd_base, bank, reg) FGIC_WRITEREG64(gicd_base , FGIC_GICD_IROUTER_OFFSET + (bank * FGIC_GICD_IROUTER_BYTE_WIDTH), reg) +#define FGIC_GICD_IROUTER_READ(gicd_base, bank) FGIC_READREG64(gicd_base , FGIC_GICD_IROUTER_OFFSET + (bank * FGIC_GICD_IROUTER_BYTE_WIDTH)) + +/* FGIC_GICD_ITARGETSR_OFFSET --- legacy operation ( affinity routing is not enabled) */ +#define FGIC_GICD_ITARGETSR_BYTE_WIDTH 4 +#define FGIC_GICD_ITARGETSR_WRITE(gicd_base, bank, reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_ITARGETSR_OFFSET + (bank * FGIC_GICD_ITARGETSR_BYTE_WIDTH), reg) +#define FGIC_GICD_ITARGETSR_READ(gicd_base, bank) FGIC_READREG32(gicd_base , FGIC_GICD_ITARGETSR_OFFSET + (bank * FGIC_GICD_ITARGETSR_BYTE_WIDTH)) + +/* FGIC_GICD_ICFGR_OFFSET --- edge-triggered or level-sensitive */ +#define FGIC_GICD_ICFGR_VALUE_OFFSET(itnum) ((itnum % 16U) << 1) +#define FGIC_GICD_ICFGR_VALUE_MASK(itnum) (0x3U << FGIC_GICD_ICFGR_VALUE_OFFSET(itnum)) +#define FGIC_GICD_ICFGR_READ_N_MASK(gicd_base,itnum) FGIC_READREG32(gicd_base , FGIC_GICD_ICFGR_OFFSET + ((itnum >> 4)<<2) ) +#define FGIC_GICD_ICFGR_WRITE_N_MASK(gicd_base,itnum,reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_ICFGR_OFFSET + ((itnum >> 4)<<2), reg) + + +/* FGIC_GICD_ISPENDR_OFFSET --- about spi pending */ +#define FGIC_GICD_ISPENDR_BYTE_WIDTH 4 +#define FGIC_GICD_ISPENDR_WRITE(gicd_base, bank, reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_ISPENDR_OFFSET + (bank * FGIC_GICD_ISPENDR_BYTE_WIDTH), reg) +#define FGIC_GICD_ISPENDR_READ(gicd_base, bank) FGIC_READREG32(gicd_base , FGIC_GICD_ISPENDR_OFFSET + (bank * FGIC_GICD_ISPENDR_BYTE_WIDTH)) + + +/* FGIC_GICD_ICPENDR_OFFSET --- about spi pending */ +#define FGIC_GICD_ICPENDR_DEFAULT_MASK BIT_MASK(32) +#define FGIC_GICD_ICPENDR_VALUE_OFFSET(itnum) ((itnum % 32U)) +#define FGIC_GICD_ICPENDR_VALUE_MASK(itnum) (0x1U << FGIC_GICD_ICPENDR_VALUE_OFFSET(itnum)) +#define FGIC_GICD_ICPENDR_READ_N_MASK(gicd_base,itnum) FGIC_READREG32(gicd_base , FGIC_GICD_ICPENDR_OFFSET + ((itnum >> 5)<<2) ) +#define FGIC_GICD_ICPENDR_WRITE_N_MASK(gicd_base,itnum,reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_ICPENDR_OFFSET + ((itnum >> 5)<<2), reg) + + + + +/* FGIC_GICD_IGROUPR_OFFSET --- */ +#define FGIC_GICD_IGROUPR_VALUE_OFFSET(itnum) ((itnum % 32U)) +#define FGIC_GICD_IGROUPR_VALUE_MASK(itnum) (0x1U << FGIC_GICD_IGROUPR_VALUE_OFFSET(itnum)) +#define FGIC_GICD_IGROUPR_READ_N_MASK(gicd_base,itnum) FGIC_READREG32(gicd_base , FGIC_GICD_IGROUPR_OFFSET + ((itnum >> 5)<<2) ) +#define FGIC_GICD_IGROUPR_WRITE_N_MASK(gicd_base,itnum,reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_IGROUPR_OFFSET + ((itnum >> 5)<<2), reg) + + +/* FGIC_GICD_IGRPMODR_OFFSET --- Controls whether the corresponding interrupt is in Secure Group 0、Non-secure Group 1、 Secure Group 1 */ +#define FGIC_GICD_IGRPMODR_DEFAULT_MASK BIT_MASK(32) +#define FGIC_GICD_IGRPMODR_VALUE_OFFSET(itnum) ((itnum % 32U)) +#define FGIC_GICD_IGRPMODR_VALUE_MASK(itnum) (0x1U << FGIC_GICD_IGRPMODR_VALUE_OFFSET(itnum)) +#define FGIC_GICD_IGRPMODR_READ_N_MASK(gicd_base,itnum) FGIC_READREG32(gicd_base , FGIC_GICD_IGRPMODR_OFFSET + ((itnum >> 5)<<2) ) +#define FGIC_GICD_IGRPMODR_WRITE_N_MASK(gicd_base,itnum,reg) FGIC_WRITEREG32(gicd_base , FGIC_GICD_IGRPMODR_OFFSET + ((itnum >> 5)<<2), reg) + + +/* FGIC_GICR_TYPER_OFFSET --- Provides information about the configuration of this Redistributor. */ +#define FGIC_GICR_TYPER_BYTE_WIDTH 4 +#define FGIC_GICR_TYPER_L_READ(redis_base) FGIC_READREG32(redis_base , FGIC_GICR_TYPER_OFFSET) +#define FGIC_GICR_TYPER_H_READ(redis_base) FGIC_READREG32(redis_base , FGIC_GICR_TYPER_OFFSET + FGIC_GICR_TYPER_BYTE_WIDTH) + +/* FGIC_GICR_WAKER_OFFSET --- Permits software to control the behavior of the WakeRequest power management signal corresponding to the Redistributor */ +#define FGIC_GICR_WAKER_PROCESSOR_SLEEP_MASK BIT(1) +#define FGIC_GICR_WAKER_CHILDREN_ASLEEP_MASK BIT(2) +#define FGIC_GICR_WAKER_CLEAR_BIT(redis_base, bit) FGIC_CLEARBIT(redis_base,FGIC_GICR_WAKER_OFFSET,bit) +#define FGIC_GICR_WAKER_WRITE(redis_base, reg) FGIC_WRITEREG32(redis_base , FGIC_GICR_WAKER_OFFSET, reg) +#define FGIC_GICR_WAKER_READ(redis_base) FGIC_READREG32(redis_base , FGIC_GICR_WAKER_OFFSET) + +/* FGIC_GICR_IPRIORITYR_OFFSET --- Enables forwarding of the corresponding SGI or PPI to the CPU interfaces*/ +#define FGIC_GICR_IPRIORITYR_VALUE_MASK(itnum) (0xFFU << ((itnum % 4U) << 3)) +#define FGIC_GICR_IPRIORITYR_READ(sgi_base,itnum) FGIC_READREG32(sgi_base , FGIC_GICR_IPRIORITYR_OFFSET + ((itnum >> 2)<<2) ) +#define FGIC_GICR_IPRIORITYR_WRITE(sgi_base,itnum,reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_IPRIORITYR_OFFSET + ((itnum >> 2)<<2), reg) + +/* FGIC_GICR_ISPENDR0_OFFSET --- Adds the pending state to the corresponding SGI or PPI. */ +#define FGIC_GICR_ISPENDR0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ISPENDR0_OFFSET, reg) +#define FGIC_GICR_ISPENDR0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ISPENDR0_OFFSET) + +/* FGIC_GICR_ICPENDR0_OFFSET --- Removes the pending state from the corresponding SGI or PPI. */ +#define FGIC_GICR_ICPENDR0_DEFAULT_MASK BIT_MASK(32) +#define FGIC_GICR_ICPENDR0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ICPENDR0_OFFSET, reg) +#define FGIC_GICR_ICPENDR0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ICPENDR0_OFFSET) + +/* FGIC_GICR_ISACTIVER0_OFFSET --- Activates the corresponding SGI or PPI. These registers are used when saving and restoring GIC state. */ + +#define FGIC_GICR_ISACTIVER0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ISACTIVER0_OFFSET, reg) +#define FGIC_GICR_ISACTIVER0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ISACTIVER0_OFFSET) + +/* FGIC_GICR_ICACTIVER0_OFFSET --- Deactivates the corresponding SGI or PPI. These registers are used when saving and restoring GIC state.*/ +#define FGIC_GICR_ICACTIVER0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ICACTIVER0_OFFSET, reg) +#define FGIC_GICR_ICACTIVER0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ICACTIVER0_OFFSET) + +/* FGIC_GICR_IGROUPR0_OFFSET --- Controls whether the corresponding SGI or PPI is in Group 0 or Group 1. */ +#define FGIC_GICR_IGROUPR0_DEFAULT_MASK BIT_MASK(32) +#define FGIC_GICR_IGROUPR0_VALUE_OFFSET(itnum) ((itnum % 32U)) +#define FGIC_GICR_IGROUPR0_VALUE_MASK(itnum) (0x1U << FGIC_GICR_IGROUPR0_VALUE_OFFSET(itnum)) +#define FGIC_GICR_IGROUPR0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_IGROUPR0_OFFSET, reg) +#define FGIC_GICR_IGROUPR0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_IGROUPR0_OFFSET) + +/* FGIC_GICR_IGRPMODR0_OFFSET --- controls whether the corresponding interrupt is in: • Secure Group 0.• Non-secure Group 1.• When System register access is enabled, Secure Group 1. */ +#define FGIC_GICR_IGRPMODR0_DEFAULT_MASK BIT_MASK(32) +#define FGIC_GICR_IGRPMODR0_VALUE_OFFSET(itnum) ((itnum % 32U)) +#define FGIC_GICR_IGRPMODR0_VALUE_MASK(itnum) (0x1U << FGIC_GICR_IGRPMODR0_VALUE_OFFSET(itnum)) +#define FGIC_GICR_IGRPMODR0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_IGRPMODR0_OFFSET, reg) +#define FGIC_GICR_IGRPMODR0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_IGRPMODR0_OFFSET) + +/* FGIC_GICR_ISENABLER0_OFFSET --- Enables forwarding of the corresponding interrupt to the CPU interfaces. */ +#define FGIC_GICR_ISENABLER0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ISENABLER0_OFFSET, reg) +#define FGIC_GICR_ISENABLER0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ISENABLER0_OFFSET) + +/* FGIC_GICR_ICENABLER0_OFFSET --- Disables forwarding of the corresponding interrupt to the CPU interfaces. */ +#define FGIC_GICR_ICENABLER0_DEFAULT_MASK BIT_MASK(32) +#define FGIC_GICR_ICENABLER0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ICENABLER0_OFFSET, reg) +#define FGIC_GICR_ICENABLER0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ICENABLER0_OFFSET) + +/* FGIC_GICR_ICFGR0_OFFSET */ +#define FGIC_GICR_ICFGR0_DEFAULT_MASK 0 +#define FGIC_GICR_ICFGR0_VALUE_OFFSET(itnum) ((itnum % 16U) << 1) +#define FGIC_GICR_ICFGR0_VALUE_MASK(itnum) (0x3U << FGIC_GICR_ICFGR0_VALUE_OFFSET(itnum)) +#define FGIC_GICR_ICFGR0_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ICFGR0_OFFSET, reg) +#define FGIC_GICR_ICFGR0_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ICFGR0_OFFSET) + +/* FGIC_GICR_ICFGR1_OFFSET */ +#define FGIC_GICR_ICFGR1_VALUE_OFFSET(itnum) ((itnum % 16U) << 1) +#define FGIC_GICR_ICFGR1_VALUE_MASK(itnum) (0x3U << FGIC_GICR_ICFGR1_VALUE_OFFSET(itnum)) +#define FGIC_GICR_ICFGR1_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_ICFGR1_OFFSET, reg) +#define FGIC_GICR_ICFGR1_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_ICFGR1_OFFSET) + +/* FGIC_GICR_CTLR_OFFSET */ + +#define FGIC_GICR_CTLR_RWP_MASK BIT(2) + +/* FGIC_GICR_NSACR_OFFSET */ + +#define FGIC_GICR_NSACR_WRITE(sgi_base, reg) FGIC_WRITEREG32(sgi_base , FGIC_GICR_NSACR_OFFSET, reg) +#define FGIC_GICR_NSACR_READ(sgi_base) FGIC_READREG32(sgi_base , FGIC_GICR_NSACR_OFFSET) + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_redistributor.h b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_redistributor.h new file mode 100644 index 0000000000..23f3bf147f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_redistributor.h @@ -0,0 +1,173 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic_redistributor.h + * Date: 2022-03-28 14:57:01 + * LastEditTime: 2022-03-28 14:57:01 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#ifndef DRIVERS_GIC_FGIC_REDISTRIBUTOR_H +#define DRIVERS_GIC_FGIC_REDISTRIBUTOR_H + +#include "fgic.h" +#include "fgic_hw.h" +#include "ftypes.h" + + +typedef enum +{ + GICR_GROUP_G0S = 0, + GICR_GROUP_G1NS = (1 << 0), + GICR_GROUP_G1S = (1 << 2), +} GICR_GROUP_SECURE_MODE; + +typedef enum +{ + GICR_WAKER_PROCESSOR_SLEEP = (1 << 1), + GICR_WAKER_CHILDREN_ASLEEP = (1 << 2) +} GICR_WAKER_MODE; + +static inline u32 FGicGetGicrAffinity(uintptr redis_base) +{ + return FGIC_GICR_TYPER_H_READ(redis_base); +} + + +static inline void FGicWakeGicr(uintptr redis_base) +{ + u32 mask ; + mask = FGIC_GICR_WAKER_READ(redis_base); + mask &= ~GICR_WAKER_PROCESSOR_SLEEP ; + FGIC_GICR_WAKER_WRITE(redis_base, mask); + + do + { + mask = FGIC_GICR_WAKER_READ(redis_base); + + } + while ((mask & GICR_WAKER_CHILDREN_ASLEEP) != 0); /* This PE is not in, and is not entering, a low power state. */ +} + + +static inline void FGicEnablePrivateInt(uintptr redis_base, s32 int_id) +{ + FGIC_GICR_ISENABLER0_WRITE(redis_base + FGIC_GICR_SGI_BASE_OFFSET, (1U << (int_id % 32))); +} + +static inline void FGicDisablePrivateInt(uintptr redis_base, s32 int_id) +{ + FGIC_GICR_ICENABLER0_WRITE(redis_base + FGIC_GICR_SGI_BASE_OFFSET, (1U << (int_id % 32))); +} + +static inline void FGicSetPrivatePriority(uintptr redis_base, s32 spi_id, u32 priority) +{ + u32 mask; + + /* For SPIs , has one byte-wide entry per interrupt */ + mask = FGIC_GICR_IPRIORITYR_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET, spi_id); + mask &= ~FGIC_GICR_IPRIORITYR_VALUE_MASK(spi_id); + mask |= ((priority & 0xffU) << (spi_id % 4) * 8U); + FGIC_GICR_IPRIORITYR_WRITE(redis_base + FGIC_GICR_SGI_BASE_OFFSET, spi_id, mask); +} + +static inline u32 FGicGetPrivatePriority(uintptr redis_base, s32 spi_id) +{ + u32 mask; + /* For SPIs , has one byte-wide entry per interrupt */ + mask = FGIC_GICR_IPRIORITYR_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET, spi_id); + + return (mask >> ((spi_id % 4U) * 8U)) & 0xFFU; +} + +static inline void FGicSetSgiLevel(uintptr redis_base, s32 spi_id, GICD_ICFGR_MODE mode) +{ + u32 mask ; + mask = FGIC_GICR_ICFGR0_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + mask &= ~FGIC_GICR_ICFGR0_VALUE_OFFSET(spi_id); + mask |= (mode << FGIC_GICR_ICFGR0_VALUE_OFFSET(spi_id)); + FGIC_GICR_ICFGR0_WRITE(redis_base, mask); +} + +static inline u32 FGicGetSgiLevel(uintptr redis_base, s32 spi_id) +{ + u32 mask ; + mask = FGIC_GICR_ICFGR0_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + return (mask >> ((spi_id % 16U) >> 1U)) ; +} + + +static inline void FGicSetPpiLevel(uintptr redis_base, s32 spi_id, GICD_ICFGR_MODE mode) +{ + u32 mask ; + mask = FGIC_GICR_ICFGR1_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + mask &= ~FGIC_GICR_ICFGR1_VALUE_OFFSET(spi_id); + mask |= (mode << FGIC_GICR_ICFGR1_VALUE_OFFSET(spi_id)); + FGIC_GICR_ICFGR1_WRITE(redis_base, mask); +} + + +static inline u32 FGicGetPpiLevel(uintptr redis_base, s32 spi_id) +{ + u32 mask ; + mask = FGIC_GICR_ICFGR1_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + return (mask >> ((spi_id % 16U) >> 1U)) ; +} + +static inline void FGicSetPrivateSecurity(uintptr redis_base, s32 spi_id, GICD_GROUP_SECURE_MODE mode) +{ + u32 mask ; + /* Group status */ + mask = FGIC_GICR_IGROUPR0_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + mask &= ~FGIC_GICR_IGROUPR0_VALUE_MASK(spi_id); + + mask |= ((mode & 0x1) << (spi_id % 32)); + FGIC_GICR_IGROUPR0_WRITE(redis_base + FGIC_GICR_SGI_BASE_OFFSET, mask); + + /* Group modifier */ + mask = FGIC_GICR_IGRPMODR0_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + mask &= ~FGIC_GICR_IGRPMODR0_VALUE_MASK(spi_id); + + mask |= (((mode & 0x2) >> 1) << (spi_id % 32)); + FGIC_GICR_IGRPMODR0_WRITE(redis_base + FGIC_GICR_SGI_BASE_OFFSET, mask); +} + + +static inline u32 FGicGetPrivateSecurity(uintptr redis_base, s32 spi_id) +{ + u32 mask ; + u32 group_status, group_modifier; + /* Group status */ + mask = FGIC_GICR_IGROUPR0_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + mask &= FGIC_GICR_IGROUPR0_VALUE_MASK(spi_id); + group_status = (mask >> (spi_id % 32)); + + /* Group modifier */ + mask = FGIC_GICR_IGRPMODR0_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); + mask &= FGIC_GICR_IGRPMODR0_VALUE_MASK(spi_id); + group_modifier = (mask >> (spi_id % 32)); + + return ((group_modifier << 1) | group_status); +} + + +static inline u32 FGicNonSecureAccessRead(uintptr redis_base) +{ + return FGIC_GICR_NSACR_READ(redis_base + FGIC_GICR_SGI_BASE_OFFSET); +} + +#endif + diff --git a/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_sinit.c b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_sinit.c new file mode 100644 index 0000000000..28b9ce2b29 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/gic/fgic/fgic_sinit.c @@ -0,0 +1,49 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgic_sinit.c + * Date: 2022-03-30 15:00:29 + * LastEditTime: 2022-03-30 15:00:29 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "fgic.h" + +extern FGicConfig fgic_config[FGIC_NUM]; + + +/** + * @name: FGicLookupConfig + * @msg: Gets the default configuration parameters in the current GIC + * @param {u32} instance_id + * @return {*} + */ +FGicConfig *FGicLookupConfig(u32 instance_id) +{ + FGicConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FGIC_NUM; index++) + { + if (fgic_config[index].instance_id == instance_id) + { + ptr = &fgic_config[index]; + break; + } + } + + return (FGicConfig *)ptr; +} diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/Kconfig b/bsp/phytium/libraries/standalone/drivers/i2c/Kconfig new file mode 100644 index 0000000000..1195673525 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/Kconfig @@ -0,0 +1,8 @@ +config USE_FI2C + bool + prompt "Use FI2C" + default n + help + Include FI2C driver component + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c.c b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c.c new file mode 100644 index 0000000000..43899808a8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c.c @@ -0,0 +1,198 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:36:58 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ +#include +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" +#include "fi2c_hw.h" +#include "fi2c.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FI2C_DEBUG_TAG "I2C" +#define FI2C_ERROR(format, ...) FT_DEBUG_PRINT_E(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_INFO(format, ...) FT_DEBUG_PRINT_I(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_DEBUG(format, ...) FT_DEBUG_PRINT_D(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +static FError FI2cReset(FI2c *instance_p); + +/************************** Variable Definitions *****************************/ +static const char *FI2C_ERROR_CODE_MSG[FI2C_NUM_OF_ERR_CODE] = +{ + "FI2C_SUCCESS : fi2c success", + "FI2C_ERR_INVAL_PARM : fi2c invalid input parameters", + "FI2C_ERR_NOT_READY : fi2c driver not ready", + "FI2C_ERR_TIMEOUT : fi2c wait timeout", + "FI2C_ERR_NOT_SUPPORT : fi2c non support operation", + "FI2C_ERR_INVAL_STATE : fi2c invalid state" +}; + +/*****************************************************************************/ + +/* 此文件主要为了完成用户对外接口,用户可以使用这些接口直接开始工作 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/** + * @name: FI2cCfgInitialize + * @msg: 完成I2C驱动实例的初始化,使之可以使用 + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {FI2cConfig} *cofig_p I2C驱动配置数据 + * @return SUCCESS if initialization was successful + * ERROR + */ +FError FI2cCfgInitialize(FI2c *instance_p, const FI2cConfig *input_config_p) +{ + FASSERT(instance_p && input_config_p); + + FError ret = FI2C_SUCCESS; + + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FI2C_ERROR("device is already initialized!!!"); + return FI2C_ERR_INVAL_STATE; + } + + /* + * Set default values and configuration data, including setting the + * callback handlers to stubs so the system will not crash should the + * application not assign its own callbacks. + */ + FI2cDeInitialize(instance_p); + instance_p->config = *input_config_p; + + /* + * Reset the device. + */ + ret = FI2cReset(instance_p); + if (FI2C_SUCCESS == ret) + { + instance_p->is_ready = FT_COMPONENT_IS_READY; + } + + return ret; +} + +/** + * @name: FI2cDeInitialize + * @msg: 完成I2C驱动实例去使能,清零实例数据 + * @return {*} + * @param {FI2c} *instance_p + */ +void FI2cDeInitialize(FI2c *instance_p) +{ + FASSERT(instance_p); + instance_p->is_ready = 0; + + memset(instance_p, 0, sizeof(*instance_p)); +} + +/** + * @name: FI2cReset + * @msg: 重置I2C控制器 + * @return {*} + * @param {FI2c} *instance_p, I2C驱动实例数据 + */ +static FError FI2cReset(FI2c *instance_p) +{ + FASSERT(instance_p); + + FError ret = FI2C_SUCCESS; + FI2cConfig *config_p = &instance_p->config; + uintptr base_addr = config_p->base_addr; + u32 reg_val = 0; + + ret = FI2cSetEnable(base_addr, FALSE); /* disable i2c ctrl */ + + if (FI2C_MASTER == config_p->work_mode) + { + reg_val |= (config_p->use_7bit_addr) ? FI2C_CON_MASTER_ADR_7BIT : FI2C_CON_MASTER_ADR_10BIT ; + reg_val |= FI2C_CON_SLAVE_DISABLE; + reg_val |= FI2C_CON_MASTER_MODE; + reg_val |= FI2C_CON_RESTART_EN; + } + else + { + reg_val |= (config_p->use_7bit_addr) ? FI2C_CON_SLAVE_ADR_7BIT : FI2C_CON_SLAVE_ADR_10BIT; + reg_val &= (~FI2C_CON_MASTER_MODE); + reg_val |= FI2C_CON_SLAVE_MODE; + } + reg_val |= FI2C_CON_STD_SPEED; + + FI2C_WRITE_REG32(base_addr, FI2C_CON_OFFSET, reg_val); + FI2C_WRITE_REG32(base_addr, FI2C_RX_TL_OFFSET, 0); + FI2C_WRITE_REG32(base_addr, FI2C_TX_TL_OFFSET, 0); + FI2C_SET_INTRRUPT_MASK(base_addr, 0); /* disable all intr */ + + ret = FI2cSetSpeed(base_addr, config_p->speed_rate); + + if (FI2C_SUCCESS == ret) + ret = FI2cSetEnable(base_addr, TRUE); /* enable i2c ctrl */ + + /* if init successed, and i2c is in slave mode, set slave address */ + if ((FI2C_SUCCESS == ret) && (FI2C_SLAVE == config_p->work_mode)) + ret = FI2cSetSar(base_addr, config_p->slave_addr); + + return ret; +} + +/** + * @name: FI2cErrorToMessage + * @msg: 获取I2C模块错误码对应的错误信息 + * @return {const char *}, 错误码信息,NULL表示失败 + * @param {FError} error, I2C输入错误码 + */ +const char *FI2cErrorToMessage(FError error) +{ + const char *msg = NULL; + if (FI2C_SUCCESS != error && (FI2C_ERR_CODE_PREFIX != error & (FT_ERRCODE_SYS_MODULE_MASK | FT_ERRCODE_SUB_MODULE_MASK))) + { + /* if input error do not belong to this module */ + return msg; + } + u32 index = error & FT_ERRCODE_TAIL_VALUE_MASK; + + if (index < FI2C_NUM_OF_ERR_CODE) + { + msg = FI2C_ERROR_CODE_MSG[index]; + } + + return msg; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c.h b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c.h new file mode 100644 index 0000000000..505b310f85 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c.h @@ -0,0 +1,201 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:37:04 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + + +#ifndef DRIVERS_I2C_FI2C_H +#define DRIVERS_I2C_FI2C_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" +#include "ferror_code.h" +#include "sdkconfig.h" +/************************** Constant Definitions *****************************/ +#define FI2C_SUCCESS FT_SUCCESS +#define FI2C_ERR_INVAL_PARM FT_MAKE_ERRCODE(ErrModBsp, ErrBspI2c, 1) +#define FI2C_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspI2c, 2) +#define FI2C_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspI2c, 3) +#define FI2C_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspI2c, 4) +#define FI2C_ERR_INVAL_STATE FT_MAKE_ERRCODE(ErrModBsp, ErrBspI2c, 5) + +/* add up new error code above and plust FI2C_ERR_CODE_MAX by ONE*/ +#define FI2C_ERR_CODE_MAX FT_MAKE_ERRCODE(ErrModBsp, ErrBspI2c, 6) +#define FI2C_ERR_CODE_PREFIX FI2C_ERR_CODE_MAX & (FT_ERRCODE_SYS_MODULE_MASK | FT_ERRCODE_SUB_MODULE_MASK) +#define FI2C_NUM_OF_ERR_CODE FI2C_ERR_CODE_MAX & FT_ERRCODE_TAIL_VALUE_MASK + +/* + * status codes + */ +#define STATUS_IDLE 0x0 +#define STATUS_WRITE_IN_PROGRESS 0x1 +#define STATUS_READ_IN_PROGRESS 0x2 + +enum +{ + FI2C_MASTER = 0, /* i2c主设备 */ + FI2C_SLAVE /* i2c从设备 */ +}; + +enum +{ + FI2C_SPEED_STANDARD_RATE = 100000, /* 100kb/s */ + FI2C_SPEED_FAST_RATE = 400000 /* 400kb/s */ +}; + +enum +{ + FI2C_EVT_MASTER_TRANS_ABORTED = 0,/*master模式传输出错回调函数事件值*/ + FI2C_EVT_MASTER_READ_DONE, /*master模式接收完成回调函数事件值*/ + FI2C_EVT_MASTER_WRITE_DONE, /*master模式发送完成回调函数事件值*/ + + FI2C_MASTER_INTR_EVT_NUM +}; /* master mode evt */ + +enum/*slave模式回调函数事件值*/ +{ + FI2C_EVT_SLAVE_READ_REQUESTED = 0, /*slave收到主机读取内容的请求*/ + FI2C_EVT_SLAVE_WRITE_REQUESTED, /*slave收到主机发送的写请求*/ + FI2C_EVT_SLAVE_READ_PROCESSED, /*在Slave发送模式下,发送完数据的最后一个字节后,在规定时间内没有收到 Master 端的回应*/ + FI2C_EVT_SLAVE_WRITE_RECEIVED, /*Slave收到主机发送的数据,需要存下*/ + FI2C_EVT_SLAVE_STOP, /*I2C总线接口上是否产生了STOP。与控制器工作在Master模式还是 Slave 模式无关。*/ + + FI2C_SLAVE_INTR_EVT_NUM +}; /* slave mode evt */ + +/**************************** Type Definitions *******************************/ + +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num; /* Device intrrupt id */ + u32 irq_prority; /* Device intrrupt priority */ + u32 ref_clk_hz; /* Input reference clock frequency in Hz */ + u32 work_mode; /* Device work mode Slave or Master */ + u32 slave_addr; /*Master mode Slave Address writing/reading to/from ,Slave mode set local address*/ + boolean use_7bit_addr; /* Slave in-chip address offset in 7bit or 10bit */ + u32 speed_rate; /* I2C speed rate */ +} FI2cConfig; /* Device configure setting */ + +typedef void (*FI2cEvtHandler)(void *instance_p, void *param); + +typedef struct +{ + /* data */ + const void *data_buff; + u32 tx_total_num; + volatile u32 tx_cnt; + u32 flag;/* CMD BIT(8), STOP BIT(9) and RESTART BIT(10) Generation */ +} FI2cFrameTX; + +typedef struct +{ + /* data */ + void *data_buff; + u32 rx_total_num; + volatile u32 rx_cnt; +} FI2cFrameRX; + +typedef struct +{ + FI2cConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + volatile u32 status; + FI2cFrameTX txframe; + FI2cFrameRX rxframe; + /** only apply to master device **/ + /* Master intrrupt handler */ + FI2cEvtHandler master_evt_handlers[FI2C_MASTER_INTR_EVT_NUM]; + + /** only apply to slave device **/ + /* Slave intrrupt handler */ + FI2cEvtHandler slave_evt_handlers[FI2C_SLAVE_INTR_EVT_NUM]; + +} FI2c; /* Device instance */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/* fi2c_sinit.c */ +/* 获取I2C驱动的默认配置参数 */ +const FI2cConfig *FI2cLookupConfig(u32 instance_id); + +/* fi2c.c */ +/* 完成I2C驱动实例的初始化,使之可以使用*/ +FError FI2cCfgInitialize(FI2c *instance_p, const FI2cConfig *cofig_p); + +/* 完成I2C驱动实例去使能,清零实例数据 */ +void FI2cDeInitialize(FI2c *instance_p); + +/* 获取I2C模块错误码对应的错误信息 */ +const char *FI2cErrorToMessage(FError error); + +/* fi2c_master.c */ +/* I2C主机读,阻塞直到完成读操作或失败 */ +FError FI2cMasterReadPoll(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, u8 *buf_p, u32 buf_len); + +/*I2C主机读,接收中断读操作或者失败 */ +FError FI2cMasterReadIntr(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, u8 *buf_p, u32 buf_len); + +/* I2C主机写,中断发送直到完成写操作或失败 */ +FError FI2cMasterWriteIntr(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, const u8 *buf_p, u32 buf_len); + +/* I2C主机写,阻塞直到完成写操作或失败 */ +FError FI2cMasterWritePoll(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, const u8 *buf_p, u32 buf_len); + +/* 获取I2C的中断值*/ +u32 FI2cGetIntr(FI2c *instance_p); + +/* 设置I2C主机的中断 */ +FError FI2cMasterSetupIntr(FI2c *instance_p, u32 mask); + +/* 主机模式中断服务函数 */ +void FI2cMasterIntrHandler(s32 vector, void *param); + +/* 注册I2C主机中断事件函数 */ +void FI2cMasterRegisterIntrHandler(FI2c *instance_p, u32 evt, FI2cEvtHandler handler); + +/* 设置I2C从机的中断 */ +FError FI2cSlaveSetupIntr(FI2c *instance_p); + +/* 从机模式中断服务函数 */ +void FI2cSlaveIntrHandler(s32 vector, void *param); + +/* 注册I2C从机中断事件函数 */ +void FI2cSlaveRegisterIntrHandler(FI2c *instance_p, u32 evt, FI2cEvtHandler handler); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_g.c b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_g.c new file mode 100644 index 0000000000..92e122f0ad --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_g.c @@ -0,0 +1,143 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:36:14 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/* - This file contains a configuration table that specifies the configuration +- 驱动全局变量定义,包括静态配置参数 */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fi2c.h" +#include "sdkconfig.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ +/** + * @name: FI2C_CONFIG_TBL + * @msg: I2C驱动的默认配置参数 + */ +#if defined(CONFIG_TARGET_E2000) +const FI2cConfig FI2C_CONFIG_TBL[I2C_INSTANCE_NUM] = +{ + [I2C_INSTANCE_0] = + { + .instance_id = I2C_INSTANCE_0, + .base_addr = I2C_0_BASEADDR, + .irq_num = I2C_0_INTR_IRQ, + .irq_prority = 0, + .ref_clk_hz = I2C_REF_CLK_HZ, + .work_mode = FI2C_MASTER, + .slave_addr = 0, + .use_7bit_addr = TRUE, + .speed_rate = FI2C_SPEED_STANDARD_RATE + }, + [I2C_INSTANCE_1] = + { + .instance_id = I2C_INSTANCE_1, + .base_addr = I2C_1_BASEADDR, + .irq_num = I2C_1_INTR_IRQ, + .irq_prority = 0, + .ref_clk_hz = I2C_REF_CLK_HZ, + .work_mode = FI2C_MASTER, + .slave_addr = 0, + .use_7bit_addr = TRUE, + .speed_rate = FI2C_SPEED_STANDARD_RATE + }, + + [I2C_INSTANCE_2] = + { + .instance_id = I2C_INSTANCE_2, + .base_addr = I2C_2_BASEADDR, + .irq_num = I2C_2_INTR_IRQ, + .irq_prority = 0, + .ref_clk_hz = I2C_REF_CLK_HZ, + .work_mode = FI2C_MASTER, + .slave_addr = 0, + .use_7bit_addr = TRUE, + .speed_rate = FI2C_SPEED_STANDARD_RATE + } +}; +#endif + +#if defined(CONFIG_TARGET_D2000) || defined(CONFIG_TARGET_F2000_4) +const FI2cConfig FI2C_CONFIG_TBL[I2C_INSTANCE_NUM] = +{ + [I2C_INSTANCE_0] = + { + .instance_id = I2C_INSTANCE_0, + .base_addr = I2C_0_BASEADDR, + .irq_num = I2C_0_INTR_IRQ, + .irq_prority = 0, + .ref_clk_hz = I2C_REF_CLK_HZ, + .work_mode = FI2C_MASTER, + .slave_addr = 0, + .use_7bit_addr = TRUE, + .speed_rate = FI2C_SPEED_STANDARD_RATE + }, + [I2C_INSTANCE_1] = + { + .instance_id = I2C_INSTANCE_1, + .base_addr = I2C_1_BASEADDR, + .irq_num = I2C_1_INTR_IRQ, + .irq_prority = 0, + .ref_clk_hz = I2C_REF_CLK_HZ, + .work_mode = FI2C_MASTER, + .slave_addr = 0, + .use_7bit_addr = TRUE, + .speed_rate = FI2C_SPEED_STANDARD_RATE + }, + + [I2C_INSTANCE_2] = + { + .instance_id = I2C_INSTANCE_2, + .base_addr = I2C_2_BASEADDR, + .irq_num = I2C_2_INTR_IRQ, + .irq_prority = 0, + .ref_clk_hz = I2C_REF_CLK_HZ, + .work_mode = FI2C_MASTER, + .slave_addr = 0, + .use_7bit_addr = TRUE, + .speed_rate = FI2C_SPEED_STANDARD_RATE + }, + [I2C_INSTANCE_3] = + { + .instance_id = I2C_INSTANCE_3, + .base_addr = I2C_3_BASEADDR, + .irq_num = I2C_3_INTR_IRQ, + .irq_prority = 0, + .ref_clk_hz = I2C_REF_CLK_HZ, + .work_mode = FI2C_MASTER, + .slave_addr = 0, + .use_7bit_addr = TRUE, + .speed_rate = FI2C_SPEED_STANDARD_RATE + } +}; +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_hw.c b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_hw.c new file mode 100644 index 0000000000..6ce4679b14 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_hw.c @@ -0,0 +1,433 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:36:22 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ +#include +#include "fsleep.h" +#include "fdebug.h" +#include "ferror_code.h" +#include "fassert.h" +#include "fi2c_hw.h" +#include "fi2c.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +typedef struct +{ + u32 speed_mode; + u32 scl_lcnt; + u32 scl_hcnt; + u32 sda_hold; +} FI2cSpeedCfg; /* speed related configs */ + +typedef struct +{ + u32 speed; + u32 min_scl_hightime_ns; + u32 min_scl_lowtime_ns; + u32 def_risetime_ns; + u32 def_falltime_ns; +} FI2cSpeedModeInfo; /* speed calculation related configs */ + +/************************** Variable Definitions *****************************/ +static const FI2cSpeedModeInfo I2C_SPEED_CFG[FI2C_SPEED_MODE_MAX] = +{ + [FI2C_STANDARD_SPEED] = { + FI2C_SPEED_STANDARD_RATE, + 4000, + 4700, + 1000, + 300, + }, + [FI2C_FAST_SPEED] = { + FI2C_SPEED_FAST_RATE, + 1000, + 1300, + 300, + 300, + } +}; + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FI2C_DEBUG_TAG "I2C_HW" +#define FI2C_ERROR(format, ...) FT_DEBUG_PRINT_E(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_INFO(format, ...) FT_DEBUG_PRINT_I(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_DEBUG(format, ...) FT_DEBUG_PRINT_D(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FI2C_TIMEOUT 500 + +/************************** Function Prototypes ******************************/ +/** + * @name: FI2cSetEnable + * @msg: 设置I2C控制器的使能状态 + * @return {*} + * @param {uintptr} addr, I2c控制器基地址 + * @param {boolean} enable, TRUE: 使能,FALSE: 去使能 + */ +FError FI2cSetEnable(uintptr addr, boolean enable) +{ + u32 status = enable ? FI2C_IC_ENABLE : FI2C_IC_DISABLE; + u32 timeout = FI2C_TIMEOUT; + + do + { + FI2C_WRITE_REG32(addr, FI2C_ENABLE_OFFSET, status); + if (((FI2C_READ_REG32(addr, FI2C_ENABLE_STATUS_OFFSET)) & FI2C_IC_ENABLE_MASK) == status) + { + return FI2C_SUCCESS; + } + + } + while (0 != timeout--); + + FI2C_ERROR("timeout in %sabling I2C ctrl", enable ? "en" : "dis"); + return FI2C_ERR_TIMEOUT; +} + +/** + * @name: FI2cCalcTiming + * @msg: 计算I2C的上升沿下降沿配置 + * @return {*} + * @param {u32} bus_clk_hz, I2C总线时钟速度 Hz,默认48MHz + * @param {u32} spk_cnt, spk数目 + * @param {FI2cSpeedCfg} *speed_cfg_p,速度配置 + */ +static FError FI2cCalcTiming(u32 bus_clk_hz, u32 spk_cnt, FI2cSpeedCfg *speed_cfg_p) +{ + FASSERT(speed_cfg_p); + u32 speed_mode = speed_cfg_p->speed_mode; + const FI2cSpeedModeInfo *info_p = &I2C_SPEED_CFG[speed_mode]; + int fall_cnt, rise_cnt, min_t_low_cnt, min_t_high_cnt; + int hcnt, lcnt, period_cnt, diff, tot; + int sda_hold_time_ns, scl_rise_time_ns, scl_fall_time_ns; + + period_cnt = bus_clk_hz / info_p->speed; + scl_rise_time_ns = info_p->def_risetime_ns; + scl_fall_time_ns = info_p->def_falltime_ns; + + /* convert a period to a number of IC clk cycles */ + rise_cnt = DIV_ROUND_UP(bus_clk_hz / 1000 * scl_rise_time_ns, NANO_TO_KILO); + fall_cnt = DIV_ROUND_UP(bus_clk_hz / 1000 * scl_fall_time_ns, NANO_TO_KILO); + min_t_low_cnt = DIV_ROUND_UP(bus_clk_hz / 1000 * info_p->min_scl_lowtime_ns, NANO_TO_KILO); + min_t_high_cnt = DIV_ROUND_UP(bus_clk_hz / 1000 * info_p->min_scl_hightime_ns, NANO_TO_KILO); + + FI2C_INFO("i2c: mode %d, bus_clk %d, speed %d, period %d rise %d fall %d tlow %d thigh %d spk %d\n", + speed_mode, bus_clk_hz, info_p->speed, period_cnt, rise_cnt, fall_cnt, + min_t_low_cnt, min_t_high_cnt, spk_cnt); + + /* + * Back-solve for hcnt and lcnt according to the following equations: + * SCL_High_time = [(HCNT + IC_*_SPKLEN + 7) * icClk] + SCL_Fall_time + * SCL_Low_time = [(LCNT + 1) * icClk] - SCL_Fall_time + SCL_Rise_time + */ + hcnt = min_t_high_cnt - fall_cnt - 7 - spk_cnt; + lcnt = min_t_low_cnt - rise_cnt + fall_cnt - 1; + + if (hcnt < 0 || lcnt < 0) + { + FI2C_ERROR("i2c: bad counts. hcnt = %d lcnt = %d\n", hcnt, lcnt); + return FI2C_ERR_INVAL_PARM; + } + + /* + * Now add things back up to ensure the period is hit. If it is off, + * split the difference and bias to lcnt for remainder + */ + tot = hcnt + lcnt + 7 + spk_cnt + rise_cnt + 1; + + if (tot < period_cnt) + { + diff = (period_cnt - tot) / 2; + hcnt += diff; + lcnt += diff; + tot = hcnt + lcnt + 7 + spk_cnt + rise_cnt + 1; + lcnt += period_cnt - tot; + } + + speed_cfg_p->scl_lcnt = lcnt; + speed_cfg_p->scl_hcnt = hcnt; + speed_cfg_p->sda_hold = DIV_ROUND_UP(bus_clk_hz / 1000 * 300, NANO_TO_KILO); /* Use internal default unless other value is specified */ + + FI2C_INFO("i2c: hcnt = %d lcnt = %d sda hold = %d\n", + speed_cfg_p->scl_hcnt, + speed_cfg_p->scl_lcnt, + speed_cfg_p->sda_hold); + + return FI2C_SUCCESS; +} + +/** + * @name: FI2cCalcSpeedCfg + * @msg: 计算I2C的速度配置 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + * @param {u32} speed, I2C传输速率 + * @param {u32} bus_clk_hz, I2C时钟频率 + * @param {FI2cSpeedCfg} *speed_cfg_p, I2C速度配置 + */ +static FError FI2cCalcSpeedCfg(uintptr addr, u32 speed, u32 bus_clk_hz, FI2cSpeedCfg *speed_cfg_p) +{ + FASSERT(speed_cfg_p); + u32 spk_cnt = 0; + + if (FI2C_SPEED_FAST_RATE <= speed) + speed_cfg_p->speed_mode = FI2C_FAST_SPEED; + else if (FI2C_SPEED_STANDARD_RATE <= speed) + speed_cfg_p->speed_mode = FI2C_STANDARD_SPEED; + else + return FI2C_ERR_INVAL_PARM; + + spk_cnt = FI2C_READ_REG32(addr, FI2C_FS_SPKLEN_OFFSET); + return FI2cCalcTiming(bus_clk_hz, spk_cnt, speed_cfg_p); +} + +/** + * @name: FI2cSetSpeed + * @msg: 设置I2C控制器的速率 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + * @param {u32} speed_rate, I2C传输速率 + */ +FError FI2cSetSpeed(uintptr addr, u32 speed_rate) +{ + FError ret = FI2C_SUCCESS; + FI2cSpeedCfg speed_cfg; + u32 enable_status; + u32 reg_val; + + memset(&speed_cfg, 0, sizeof(speed_cfg)); + ret = FI2cCalcSpeedCfg(addr, speed_rate, I2C_REF_CLK_HZ, &speed_cfg); + if (FI2C_SUCCESS != ret) + return ret; + + /* get enable setting for restore later */ + enable_status = FI2cGetEnable(addr); + + /* reset speed mode bits */ + reg_val = ((FI2C_READ_REG32(addr, FI2C_CON_OFFSET)) & (~FI2C_CON_SPEED_MASK)); + switch (speed_cfg.speed_mode) + { + case FI2C_STANDARD_SPEED: + reg_val |= FI2C_CON_STD_SPEED; + FI2C_WRITE_REG32(addr, FI2C_SS_SCL_HCNT_OFFSET, speed_cfg.scl_hcnt); + FI2C_WRITE_REG32(addr, FI2C_SS_SCL_LCNT_OFFSET, speed_cfg.scl_lcnt); + break; + case FI2C_FAST_SPEED: + reg_val |= FI2C_CON_FAST_SPEED; + FI2C_WRITE_REG32(addr, FI2C_FS_SCL_HCNT_OFFSET, speed_cfg.scl_hcnt); + FI2C_WRITE_REG32(addr, FI2C_FS_SCL_LCNT_OFFSET, speed_cfg.scl_lcnt); + break; + default: + ret |= FI2C_ERR_INVAL_PARM; + break; + } + + FI2C_WRITE_REG32(addr, FI2C_CON_OFFSET, reg_val); + + /* Configure SDA Hold Time if required */ + if (0 != speed_cfg.sda_hold) + FI2C_WRITE_REG32(addr, FI2C_SDA_HOLD_OFFSET, speed_cfg.sda_hold); + + /* Restore back i2c now speed set */ + if (FI2C_IC_ENABLE == enable_status) + { + ret |= FI2cSetEnable(addr, TRUE); + } + + return ret; +} + +/** + * @name: FI2cWaitStatus + * @msg: 等待特定的I2C状态位直到状态不存在或者超时 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + * @param {u32} stat_bit, I2C状态位 + */ +FError FI2cWaitStatus(uintptr addr, u32 stat_bit) +{ + u32 timeout = 0; + + /* wait until statbit was set or timeout */ + do + { + fsleep_millisec(2); /*wait 2 ms*/ + } + while (!((FI2C_READ_REG32(addr, FI2C_STATUS_OFFSET)) & stat_bit) && (FI2C_TIMEOUT > ++timeout)); + + if (FI2C_TIMEOUT <= timeout) + { + FI2C_ERROR("timeout when wait status: 0x%x", stat_bit); + return FI2C_ERR_TIMEOUT; + } + + return FI2C_SUCCESS; +} + +/** + * @name: FI2cWaitBusBusy + * @msg: 等待I2C总线忙 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + */ +FError FI2cWaitBusBusy(uintptr addr) +{ + u32 timeout = FI2C_TIMEOUT; + u32 ret = FI2C_SUCCESS; + + if (((FI2C_READ_REG32(addr, FI2C_STATUS_OFFSET)) & FI2C_STATUS_MST_ACTIVITY) && + (FI2C_SUCCESS != FI2cWaitStatus(addr, FI2C_STATUS_TFE))) + { + ret = FI2C_ERR_TIMEOUT; + FI2C_ERROR("timeout when wait i2c bus busy"); + } + + return ret; +} + +/** + * @name: FI2cSetTar + * @msg: 设置与I2C主机通信的从机地址 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + * @param {u32} tar_addr, I2C从机地址 + */ +FError FI2cSetTar(uintptr addr, u32 tar_addr) +{ + u32 enable_status = FI2cGetEnable(addr); + u32 ret = FI2C_SUCCESS; + u32 reg_val = 0; + + if (FI2C_IC_ENABLE == enable_status) + ret = FI2cSetEnable(addr, FALSE); + + if (FI2C_SUCCESS == ret) + FI2C_WRITE_REG32(addr, FI2C_TAR_OFFSET, (tar_addr & FI2C_IC_TAR_MASK)); + + if (FI2C_IC_ENABLE == enable_status) + ret = FI2cSetEnable(addr, TRUE); + + return ret; +} + +/** + * @name: FI2cSetSar + * @msg: 从机模式下,设置I2C地址 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + * @param {u32} sar_addr, 作为从机的地址 + */ +FError FI2cSetSar(uintptr addr, u32 sar_addr) +{ + u32 enable_status = FI2cGetEnable(addr); + u32 ret = FI2C_SUCCESS; + u32 reg_val = 0; + + if (FI2C_IC_ENABLE == enable_status) + ret = FI2cSetEnable(addr, FALSE); + + if (FI2C_SUCCESS == ret) + FI2C_WRITE_REG32(addr, FI2C_SAR_OFFSET, (sar_addr & FI2C_IC_SAR_MASK)); + + if (FI2C_IC_ENABLE == enable_status) + ret = FI2cSetEnable(addr, TRUE); + + return ret; +} + +/** + * @name: FI2cFlushRxFifo + * @msg: 等待接收Fifo传输完成 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + */ +FError FI2cFlushRxFifo(uintptr addr) +{ + u8 data; + int timeout = 0; + FError ret = FI2C_SUCCESS; + + /* read data to trigger trans until fifo empty */ + while (FI2C_GET_STATUS(addr) & FI2C_STATUS_RFNE) + { + data = FI2C_READ_DATA(addr); + + if (FI2C_TIMEOUT < ++timeout) + { + ret = FI2C_TIMEOUT; + FI2C_ERROR("timeout when flush fifo"); + break; + } + } + + return ret; +} + +/** + * @name: FI2cClearIntrBits + * @msg: 清除中断状态位,返回清除前的中断状态 + * @return {*} + * @param {uintptr} addr, I2C控制器基地址 + * @param {u32} *last_err_p, Abort错误 + */ +u32 FI2cClearIntrBits(uintptr addr, u32 *last_err_p) +{ + FASSERT(last_err_p); + + const u32 stat = FI2C_READ_INTR_STAT(addr); + + /* read to clr intrrupt status bits */ + if (stat & FI2C_INTR_TX_ABRT) + { + *last_err_p = FI2C_READ_REG32(addr, FI2C_TX_ABRT_SOURCE_OFFSET); /* read out abort sources */ + FI2C_READ_REG32(addr, FI2C_CLR_TX_ABRT_OFFSET); + } + + if (stat & FI2C_INTR_RX_UNDER) + FI2C_READ_REG32(addr, FI2C_CLR_RX_UNDER_OFFSET); + + if (stat & FI2C_INTR_RX_OVER) + FI2C_READ_REG32(addr, FI2C_CLR_RX_OVER_OFFSET); + + if (stat & FI2C_INTR_TX_OVER) + FI2C_READ_REG32(addr, FI2C_CLR_TX_OVER_OFFSET); + + if (stat & FI2C_INTR_RX_DONE) + FI2C_READ_REG32(addr, FI2C_CLR_RX_DONE_OFFSET); + + if (stat & FI2C_INTR_ACTIVITY) + FI2C_READ_REG32(addr, FI2C_CLR_ACTIVITY_OFFSET); + + if (stat & FI2C_INTR_STOP_DET) + FI2C_READ_REG32(addr, FI2C_CLR_STOP_DET_OFFSET); + + if (stat & FI2C_INTR_START_DET) + FI2C_READ_REG32(addr, FI2C_CLR_START_DET_OFFSET); + + if (stat & FI2C_INTR_GEN_CALL) + FI2C_READ_REG32(addr, FI2C_CLR_GEN_CALL_OFFSET); + + return stat; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_hw.h b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_hw.h new file mode 100644 index 0000000000..1a39e67968 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_hw.h @@ -0,0 +1,271 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:36:32 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_I2C_FI2C_HW_H +#define DRIVERS_I2C_FI2C_HW_H + +/* - 传入模块基地址,不能复杂结构体 +- hardware interface of device || low-level driver function prototypes + +- 包括驱动寄存器参数和low-level操作定义 +1. 定义寄存器偏移 +2. 对上提供该模块寄存器操作的接口 +3. 一些简单外设提供直接操作接口 +4. 可以定义一些状态的接口,用于响应驱动状态的变化 */ + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fparameters.h" +#include "fio.h" +#include "ferror_code.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ + +/** @name Register Map + * + * Register offsets from the base address of an I2C device. + * @{ + */ +#define FI2C_CON_OFFSET 0x00 +#define FI2C_TAR_OFFSET 0x04 +#define FI2C_SAR_OFFSET 0x08 +#define FI2C_HS_MADDR_OFFSET 0x0C +#define FI2C_DATA_CMD_OFFSET 0x10 +#define FI2C_SS_SCL_HCNT_OFFSET 0x14 +#define FI2C_SS_SCL_LCNT_OFFSET 0x18 +#define FI2C_FS_SCL_HCNT_OFFSET 0x1C +#define FI2C_FS_SCL_LCNT_OFFSET 0x20 +#define FI2C_HS_SCL_HCNT_OFFSET 0x24 +#define FI2C_HS_SCL_LCNT_OFFSET 0x28 +#define FI2C_INTR_STAT_OFFSET 0x2C +#define FI2C_INTR_MASK_OFFSET 0x30 +#define FI2C_RAW_INTR_STAT_OFFSET 0x34 +#define FI2C_RX_TL_OFFSET 0x38 +#define FI2C_TX_TL_OFFSET 0x3C +#define FI2C_CLR_INTR_OFFSET 0x40 +#define FI2C_CLR_RX_UNDER_OFFSET 0x44 +#define FI2C_CLR_RX_OVER_OFFSET 0x48 +#define FI2C_CLR_TX_OVER_OFFSET 0x4C +#define FI2C_CLR_RD_REQ_OFFSET 0x50 +#define FI2C_CLR_TX_ABRT_OFFSET 0x54 +#define FI2C_CLR_RX_DONE_OFFSET 0x58 +#define FI2C_CLR_ACTIVITY_OFFSET 0x5c +#define FI2C_CLR_STOP_DET_OFFSET 0x60 +#define FI2C_CLR_START_DET_OFFSET 0x64 +#define FI2C_CLR_GEN_CALL_OFFSET 0x68 +#define FI2C_ENABLE_OFFSET 0x6C +#define FI2C_STATUS_OFFSET 0x70 +#define FI2C_TXFLR_OFFSET 0x74 +#define FI2C_RXFLR_OFFSET 0x78 +#define FI2C_SDA_HOLD_OFFSET 0x7c +#define FI2C_TX_ABRT_SOURCE_OFFSET 0x80 +#define FI2C_SLV_DATA_NACK_ONLY_OFFSET 0x84 +#define FI2C_DMA_CR_OFFSET 0x88 +#define FI2C_DMA_TDLR_OFFSET 0x8c +#define FI2C_DMA_RDLR_OFFSET 0x90 +#define FI2C_SDA_SETUP_OFFSET 0x94 +#define FI2C_ACK_GENERAL_CALL_OFFSET 0x98 +#define FI2C_ENABLE_STATUS_OFFSET 0x9C +#define FI2C_FS_SPKLEN_OFFSET 0xa0 +#define FI2C_HS_SPKLEN_OFFSET 0xa4 +#define FI2C_COMP_PARAM_1_OFFSET 0xf4 +#define FI2C_COMP_VERSION_OFFSET 0xf8 +#define FI2C_COMP_TYPE_OFFSET 0xfc + +/** @name FI2C_CON_OFFSET Register + */ +#define FI2C_CON_MASTER_MODE (0x1 << 0) +#define FI2C_CON_SLAVE_MODE (0x0 << 0) + +#define FI2C_CON_SPEED_MASK GENMASK(2, 1) +#define FI2C_CON_STD_SPEED (0x1 << 1) +#define FI2C_CON_FAST_SPEED (0x2 << 1) +#define FI2C_CON_HIGH_SPEED (0x3 << 1) + +/* for slave mode */ +#define FI2C_CON_SLAVE_ADR_7BIT (0x0 << 3) +#define FI2C_CON_SLAVE_ADR_10BIT (0x1 << 3) + +/* for master mode */ +#define FI2C_CON_MASTER_ADR_7BIT (0x0 << 4) +#define FI2C_CON_MASTER_ADR_10BIT (0x1 << 4) + +#define FI2C_CON_RESTART_EN (0x1 << 5) +#define FI2C_CON_SLAVE_DISABLE (0x1 << 6) + +/** @name FI2C_TAR_OFFSET Register + */ +#define FI2C_IC_TAR_MASK GENMASK(9, 0) +#define FI2C_GC_OR_START (0x1 << 10) +#define FI2C_SPECIAL (0x1 << 11) +#define FI2C_TAR_ADR_7BIT (0x0 << 12) +#define FI2C_TAR_ADR_10BIT (0x1 << 12) + +/** @name FI2C_SAR_OFFSET Register + */ +#define FI2C_IC_SAR_MASK GENMASK(9, 0) //Slave addr when in slave mode + +/** @name FI2C_HS_MADDR_OFFSET Register + */ +#define FI2C_IC_HS_MAR GENMASK(2, 0) //I2C High Speed模式主机编码 + +/** @name FI2C_DATA_CMD_OFFSET Register + */ +#define FI2C_DATA_MASK GENMASK(7, 0) +#define FI2C_DATA_CMD_READ (0x1 << 8) +#define FI2C_DATA_CMD_WRITE (0x0 << 8) +#define FI2C_DATA_CMD_STOP (0x1 << 9) +#define FI2C_DATA_CMD_RESTART (0x1 << 10) + +/** @name FI2C_INTR_STAT_OFFSET Register + * @name FI2C_INTR_MASK_OFFSET Register + * @name FI2C_RAW_INTR_STAT_OFFSET Register + */ +#define FI2C_INTR_RX_UNDER (0x1 << 0) /* 接收缓冲区为空 */ +#define FI2C_INTR_RX_OVER (0x1 << 1) /* 接收缓冲区大小达到 IC_RX_BUFFER_DEPTH ,且还继续从外部接收数据 */ +#define FI2C_INTR_RX_FULL (0x1 << 2) /* 接收缓冲区大于等于 IC_RX_TL 中设定的门限值(RX_TL) */ +#define FI2C_INTR_TX_OVER (0x1 << 3) /* 发送缓冲区大小达到 IC_TX_BUFFER_DEPTH,并且还在尝试写数据 */ +#define FI2C_INTR_TX_EMPTY (0x1 << 4) /* 发送缓冲区小于等于 IC_TX_TL 寄存器中设定的门限值 */ +#define FI2C_INTR_RD_REQ (0x1 << 5) /* 读请求标志 */ +#define FI2C_INTR_TX_ABRT (0x1 << 6) /* I2C 不能完成FIFO内容的传输 */ +#define FI2C_INTR_RX_DONE (0x1 << 7) /* Slave工作模式下,规定时间内没有Master的回应,通信结束 */ +#define FI2C_INTR_ACTIVITY (0x1 << 8) /* I2C 控制器的活动状态 */ +#define FI2C_INTR_STOP_DET (0x1 << 9) /* I2C 总线接口上是否产生了 STOP */ +#define FI2C_INTR_START_DET (0x1 << 10) /* I2C 总线接口上是否产生了 START 或 RESTART */ +#define FI2C_INTR_GEN_CALL (0x1 << 11) /* I2C 总线接口上接收并识别到General Call格式 */ + +#define FI2C_INTR_ALL_MASK 0x8FF + +#define FI2C_INTR_MASTER_WR_MASK (FI2C_INTR_TX_EMPTY | FI2C_INTR_TX_ABRT) +#define FI2C_INTR_MASTER_RD_MASK (FI2C_INTR_MASTER_WR_MASK | FI2C_INTR_RX_FULL) + +#define FI2C_INTR_SLAVE_DEF_MASK (FI2C_INTR_RX_FULL | FI2C_INTR_STOP_DET | \ + FI2C_INTR_RD_REQ | FI2C_INTR_RX_DONE | \ + FI2C_INTR_RX_UNDER | FI2C_INTR_TX_ABRT |\ + FI2C_INTR_START_DET) + +/** @name FI2C_RX_TL_OFFSET Register + */ +#define FI2C_RX_TL_MASK GENMASK(7, 0) + +/** @name FI2C_TX_TL_OFFSET Register + */ +#define FI2C_TX_TL_MASK GENMASK(7, 0) + +/** @name FI2C_IC_ENABLE_OFFSET Register + */ +#define FI2C_ENABLE_CONTROLLER (0x1 << 0) +#define FI2C_DISABLE_CONTROLLER (0x0 << 0) + +/** @name FI2C_STATUS_OFFSET Register + */ +#define FI2C_STATUS_ACTIVITY (0x1 << 0) +#define FI2C_STATUS_TFNF (0x1 << 1) +#define FI2C_STATUS_TFE (0x1 << 2) +#define FI2C_STATUS_RFNE (0x1 << 3) +#define FI2C_STATUS_RFF (0x1 << 4) +#define FI2C_STATUS_MST_ACTIVITY (0x1 << 5) +#define FI2C_STATUS_SLV_ACTIVITY (0x1 << 6) + +/** @name FI2C_ENABLE_OFFSET Register + */ +#define FI2C_IC_ENABLE (0x1 << 0) +#define FI2C_IC_DISABLE (0x0 << 0) +#define FI2C_IC_ENABLE_MASK (0x1 << 0) + +#define FI2C_SLV_DISABLED_WHILE_BUSY (0x1 << 1) +#define FI2C_SLV_RX_DATA_LOST (0x1 << 2) + +/* High and low times in different speed modes (in ns) */ +#define FI2C_MIN_SS_SCL_HIGHTIME 4000 +#define FI2C_MIN_SS_SCL_LOWTIME 4700 +#define FI2C_MIN_FS_SCL_HIGHTIME 600 +#define FI2C_MIN_FS_SCL_LOWTIME 1300 +#define FI2C_MIN_FP_SCL_HIGHTIME 500 +#define FI2C_MIN_FP_SCL_LOWTIME 500 +#define FI2C_MIN_HS_SCL_HIGHTIME 60 +#define FI2C_MIN_HS_SCL_LOWTIME 160 +#define FI2C_DEFAULT_SDA_HOLD_TIME 300 + +#define FI2C_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) +#define FI2C_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)(reg_offset), (u32)(reg_value)) + +#define FI2C_IIC_FIFO_MAX_LV 8 + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ +enum +{ + FI2C_STANDARD_SPEED = 0, + FI2C_FAST_SPEED, + + FI2C_SPEED_MODE_MAX +}; +/***************** Macros (Inline Functions) Definitions *********************/ +#define FI2C_GET_INTRRUPT_MASK(addr) FI2C_READ_REG32((addr), FI2C_INTR_MASK_OFFSET) + +#define FI2C_SET_INTRRUPT_MASK(addr, mask) FI2C_WRITE_REG32((addr), FI2C_INTR_MASK_OFFSET, (mask)) + +#define FI2C_CLEAR_INTR_STATUS(addr) FI2C_READ_REG32((addr), FI2C_CLR_INTR_OFFSET) + +#define FI2C_GET_STATUS(addr) FI2C_READ_REG32((addr), FI2C_STATUS_OFFSET) + +#define FI2C_READ_DATA(addr) (u8)(FI2C_DATA_MASK & FI2C_READ_REG32(addr, FI2C_DATA_CMD_OFFSET)) + +#define FI2C_WRITE_DATA(addr, dat) FI2C_WRITE_REG32((addr), FI2C_DATA_CMD_OFFSET, (dat)) + +#define FI2C_SET_RX_TL(addr, level) FI2C_WRITE_REG32((addr), FI2C_RX_TL_OFFSET, (level)) + +#define FI2C_SET_TX_TL(addr, level) FI2C_WRITE_REG32((addr), FI2C_TX_TL_OFFSET, (level)) + +#define FI2C_READ_INTR_STAT(addr) FI2C_READ_REG32((addr), FI2C_INTR_STAT_OFFSET) + +#define FI2C_READ_RAW_INTR_STAT(addr) FI2C_READ_REG32((addr), FI2C_RAW_INTR_STAT_OFFSET) + +inline static u32 FI2cGetEnable(uintptr addr) +{ + return FI2C_READ_REG32(addr, FI2C_ENABLE_STATUS_OFFSET); +} + +/************************** Function Prototypes ******************************/ +FError FI2cSetEnable(uintptr addr, boolean enable); +FError FI2cSetSpeed(uintptr addr, u32 speed_rate); +FError FI2cWaitStatus(uintptr addr, u32 stat_bit); +FError FI2cWaitBusBusy(uintptr addr); +FError FI2cSetTar(uintptr addr, u32 tar_addr); +FError FI2cSetSar(uintptr addr, u32 sar_addr); +FError FI2cFlushRxFifo(uintptr addr); +u32 FI2cClearIntrBits(uintptr addr, u32 *last_err_p); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_intr.c b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_intr.c new file mode 100644 index 0000000000..85ebbd2af1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_intr.c @@ -0,0 +1,448 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:36:38 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ +#include +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" +#include "fi2c_hw.h" +#include "fi2c.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FI2C_DEBUG_TAG "I2C" +#define FI2C_ERROR(format, ...) FT_DEBUG_PRINT_E(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_INFO(format, ...) FT_DEBUG_PRINT_I(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_DEBUG(format, ...) FT_DEBUG_PRINT_D(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/************************** Function Prototypes ******************************/ +static inline void FI2cMasterCallEvtHandler(FI2c *instance_p, u32 evt, void *para) +{ + FASSERT(instance_p); + FASSERT(evt < FI2C_MASTER_INTR_EVT_NUM); + + if (instance_p->master_evt_handlers[evt]) + { + instance_p->master_evt_handlers[evt](instance_p, para); + } +} + +static inline void FI2cSlaveCallEvtHandler(FI2c *instance_p, u32 evt, void *para) +{ + FASSERT(instance_p); + FASSERT(evt < FI2C_SLAVE_INTR_EVT_NUM); + FASSERT(para); + + if (instance_p->slave_evt_handlers[evt]) + { + instance_p->slave_evt_handlers[evt](instance_p, para); + } +} + +/** + * @name: FI2cStubHandler + * @msg: 主机模式下的I2C中断默认回调函数 + * @return {*} + * @param {void} *instance_p I2C驱动实例数据 + * @param {void} *param, 中断输入参数 + */ +static void FI2cStubHandler(void *instance_p, void *param) +{ + FASSERT(instance_p); + FI2c *instance = (FI2c *)(instance_p); + uintptr base_addr = instance->config.base_addr; + + FI2C_INFO("id: %d ,intr cause: 0x%x", + instance->config.instance_id, + FI2C_READ_INTR_STAT(base_addr)); +} + +/** + * @name: FI2cMasterIntrTxEmptyHandler + * @msg: 主机模式下的I2C TX_FIFO空中断处理函数 + * @return {*} + * @param {void} *instance_p I2C驱动实例数据 + */ +static void FI2cMasterIntrTxEmptyHandler(FI2c *instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + const u8 *buf_p = instance_p->txframe.data_buff; + + u32 intr_mask; + u32 buf_len; + u32 reg_val; + u32 rx_limit, tx_limit; + + buf_len = instance_p->txframe.tx_total_num - instance_p->txframe.tx_cnt; + + rx_limit = FI2C_IIC_FIFO_MAX_LV - FI2C_READ_REG32(base_addr, FI2C_RXFLR_OFFSET); + tx_limit = FI2C_IIC_FIFO_MAX_LV - FI2C_READ_REG32(base_addr, FI2C_TXFLR_OFFSET); + while (buf_len > 0 & rx_limit > 0 & tx_limit > 0) + { + if (1 == buf_len) + { + if (instance_p->status == STATUS_WRITE_IN_PROGRESS) + { + reg_val = (FI2C_DATA_MASK & *((u8 *)(instance_p->txframe.data_buff))) | + FI2C_DATA_CMD_WRITE | + FI2C_DATA_CMD_STOP; + instance_p->txframe.data_buff++; + FI2C_INFO("Write Stop Singal"); + } + else if (instance_p->status == STATUS_READ_IN_PROGRESS) + { + reg_val = FI2C_DATA_CMD_READ | FI2C_DATA_CMD_STOP; + } + } + else + { + if (instance_p->status == STATUS_WRITE_IN_PROGRESS) + { + reg_val = (FI2C_DATA_MASK & *((u8 *)(instance_p->txframe.data_buff))) | + FI2C_DATA_CMD_WRITE; + instance_p->txframe.data_buff++; + } + else if (instance_p->status == STATUS_READ_IN_PROGRESS) + { + reg_val = FI2C_DATA_CMD_READ; + } + } + FI2C_WRITE_REG32(base_addr, FI2C_DATA_CMD_OFFSET, reg_val); + rx_limit--; + tx_limit--; + buf_len--; + } + instance_p->txframe.tx_cnt = instance_p->txframe.tx_total_num - buf_len; + /*tx over.*/ + if (instance_p->txframe.tx_cnt == instance_p->txframe.tx_total_num) + { + instance_p->txframe.tx_cnt = 0; + if (instance_p->status == STATUS_WRITE_IN_PROGRESS) + { + instance_p->status = STATUS_IDLE; + } + intr_mask = FI2C_GET_INTRRUPT_MASK(instance_p->config.base_addr); + intr_mask &= ~(FI2C_INTR_TX_EMPTY); + FI2C_SET_INTRRUPT_MASK(instance_p->config.base_addr, intr_mask); + } +} + +/** + * @name: FI2cMasterIntrRxFullHandler + * @msg: 主机模式下的I2C RX_FIFO满处理函数,可通过FI2C_SET_RX_TL(address,level);设置触发level + * @return {*} + * @param {void} *instance_p I2C驱动实例数据 + */ +static void FI2cMasterIntrRxFullHandler(FI2c *instance_p) +{ + FASSERT(instance_p); + u32 intr_mask; + uintptr base_addr = instance_p->config.base_addr; + u8 emptyfifo = FI2C_READ_REG32(base_addr, FI2C_RXFLR_OFFSET); + u32 i = 0u; + u32 reg_val; + for (i = 0; i < emptyfifo; i++) + { + *((u8 *)(instance_p->rxframe.data_buff++)) = FI2C_READ_DATA(base_addr); + } + instance_p->rxframe.rx_cnt += emptyfifo; + if (instance_p->rxframe.rx_cnt >= instance_p->rxframe.rx_total_num) + { + instance_p->rxframe.rx_cnt = 0; + instance_p->status = STATUS_IDLE; + intr_mask = FI2C_GET_INTRRUPT_MASK(base_addr); + intr_mask &= ~(FI2C_INTR_RX_FULL); + FI2C_SET_INTRRUPT_MASK(base_addr, intr_mask); + FI2cFlushRxFifo(base_addr); + } +} + +/** + * @name: FI2cMasterIntrHandler + * @msg: 主机模式下的I2C中断响应函数 + * @return {*} + * @param {s32} vector + * @param {void} *param, 中断输入参数 + */ +void FI2cMasterIntrHandler(s32 vector, void *param) +{ + FASSERT(param); + FI2c *instance_p = (FI2c *)param; + uintptr base_addr = instance_p->config.base_addr; + u32 last_err = 0; + u32 stat = FI2cClearIntrBits(base_addr, &last_err); + u32 raw_stat = FI2C_READ_RAW_INTR_STAT(base_addr); + u32 enabled = FI2C_READ_REG32(base_addr, FI2C_ENABLE_OFFSET); + u32 val = 0; + FASSERT(FI2C_MASTER == instance_p->config.work_mode); + if (!(enabled & FI2C_IC_ENABLE) || !(raw_stat & ~FI2C_INTR_ACTIVITY)) + { + return; + } + + if (stat & FI2C_INTR_TX_ABRT) /* trans abort error */ + { + FI2C_ERROR("last error: 0x%x", last_err); + FI2C_ERROR("abort source: 0x%x", FI2C_READ_REG32(base_addr, FI2C_TX_ABRT_SOURCE_OFFSET)); + instance_p->status = STATUS_IDLE; + FI2C_SET_INTRRUPT_MASK(base_addr, 0); /* disable all intr */ + FI2C_READ_REG32(base_addr, FI2C_CLR_TX_ABRT_OFFSET); + FI2C_WRITE_REG32(base_addr, FI2C_ENABLE_OFFSET, 1); + FI2cMasterCallEvtHandler(instance_p, FI2C_EVT_MASTER_TRANS_ABORTED, &val); + return; + } + + if (stat & FI2C_INTR_RX_FULL) /* rx complete */ + { + FI2cMasterIntrRxFullHandler(instance_p); + FI2cMasterCallEvtHandler(instance_p, FI2C_EVT_MASTER_READ_DONE, &val); + return; + } + + if (stat & FI2C_INTR_TX_EMPTY) /* tx complete */ + { + FI2cMasterIntrTxEmptyHandler(instance_p); + FI2cMasterCallEvtHandler(instance_p, FI2C_EVT_MASTER_WRITE_DONE, &val); + return; + } + return; +} +/** + * @name: FI2cMasterRegisterIntrHandler + * @msg: 注册I2C主机中断事件函数 + * @return {*} + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {u32} evt 中断事件,参考 FI2C_MASTER_INTR_EVT_NUM + * @param {FI2cEvtHandler} handler 中断事件回调函数 + */ +void FI2cMasterRegisterIntrHandler(FI2c *instance_p, u32 evt, FI2cEvtHandler handler) +{ + FASSERT(instance_p && evt < FI2C_MASTER_INTR_EVT_NUM); + instance_p->master_evt_handlers[evt] = handler; +} + +/** + * @name: FI2cMasterGetIntr + * @msg: 获取I2C主机的中断 + * @return {u32 } 返回中断寄存器值 + * @param {FI2c} *instance_p I2C驱动实例数据 + */ +u32 FI2cGetIntr(FI2c *instance_p) +{ + FASSERT(instance_p); + FI2cConfig *config_p = &instance_p->config; + uintptr base_addr = config_p->base_addr; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FI2C_ERROR("i2c driver not ready"); + return FI2C_ERR_NOT_READY; + } + + return FI2C_GET_INTRRUPT_MASK(base_addr); +} +/** + * @name: FI2cMasterSetupIntr + * @msg: 设置I2C主机的中断 + * @return {FError *} 返回错误码 + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {u32} mask 需要操作的中断寄存器位 + */ +FError FI2cMasterSetupIntr(FI2c *instance_p, u32 mask) +{ + FASSERT(instance_p); + FI2cConfig *config_p = &instance_p->config; + uintptr base_addr = config_p->base_addr; + u32 evt; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FI2C_ERROR("i2c driver not ready"); + return FI2C_ERR_NOT_READY; + } + + if (FI2C_MASTER != instance_p->config.work_mode) + { + FI2C_ERROR("i2c work mode shall be master"); + return FI2C_ERR_INVAL_STATE; + } + + /* disable all i2c irq */ + FI2C_CLEAR_INTR_STATUS(base_addr); + + for (evt = FI2C_EVT_MASTER_TRANS_ABORTED; evt < FI2C_MASTER_INTR_EVT_NUM; evt++) + { + if (instance_p->master_evt_handlers[evt] == NULL) + { + FI2cMasterRegisterIntrHandler(instance_p, evt, FI2cStubHandler); + FI2C_INFO("evt :%d.is default.\r\n", evt); + } + } + FI2C_SET_INTRRUPT_MASK(base_addr, mask); + + return FI2C_SUCCESS; +} + +/** + * @name: FI2cSlaveIntrHandler + * @msg: I2C从机的中断响应函数 + * @return {*} + * @param {s32} vector + * @param {void} *param, 输入参数 + */ +void FI2cSlaveIntrHandler(s32 vector, void *param) +{ + FASSERT(param); + FI2c *instance_p = (FI2c *)param; + uintptr base_addr = instance_p->config.base_addr; + u32 last_err = 0; + + u32 stat = FI2C_READ_INTR_STAT(base_addr); + u32 raw_stat = FI2C_READ_RAW_INTR_STAT(base_addr); + u32 enabled = FI2C_READ_REG32(base_addr, FI2C_ENABLE_OFFSET); + boolean slave_active = (FI2C_GET_STATUS(base_addr) & FI2C_STATUS_SLV_ACTIVITY) ? TRUE : FALSE; + u8 val = 0; + u32 reg_val; + + FASSERT(FI2C_SLAVE == instance_p->config.work_mode); + + if (!(enabled & FI2C_IC_ENABLE) || !(raw_stat & ~FI2C_INTR_ACTIVITY)) + { + return; + } + stat = FI2cClearIntrBits(base_addr, &last_err); + + if (stat & FI2C_INTR_RX_FULL) + { + if (instance_p->status != STATUS_WRITE_IN_PROGRESS) + { + /* code */ + instance_p->status = STATUS_WRITE_IN_PROGRESS; + FI2cSlaveCallEvtHandler(instance_p, FI2C_EVT_SLAVE_WRITE_REQUESTED, &val); + } + val = FI2C_READ_DATA(base_addr); + FI2cSlaveCallEvtHandler(instance_p, FI2C_EVT_SLAVE_WRITE_RECEIVED, &val); + } + if (stat & FI2C_INTR_RD_REQ) + { + if (slave_active) + { + FI2C_READ_REG32(base_addr, FI2C_CLR_RD_REQ_OFFSET); + instance_p->status = STATUS_WRITE_IN_PROGRESS; + FI2cSlaveCallEvtHandler(instance_p, FI2C_EVT_SLAVE_READ_REQUESTED, &val); + reg_val = val; + FI2C_WRITE_DATA(base_addr, reg_val); + } + } + + if (stat & FI2C_INTR_RX_DONE) + { + FI2cSlaveCallEvtHandler(instance_p, FI2C_EVT_SLAVE_READ_PROCESSED, &val); + FI2C_READ_REG32(base_addr, FI2C_CLR_RX_DONE_OFFSET); + return; + } + + if (stat & FI2C_INTR_STOP_DET) + { + instance_p->status = STATUS_IDLE; + FI2cSlaveCallEvtHandler(instance_p, FI2C_EVT_SLAVE_STOP, &val); + } + + if (stat & FI2C_INTR_TX_ABRT) /* trans abort error */ + { + FI2C_ERROR("last error: 0x%x", last_err); + FI2C_ERROR("abort source: 0x%x", FI2C_READ_REG32(base_addr, FI2C_TX_ABRT_SOURCE_OFFSET)); + } + + return; +} + +/** + * @name: FI2cSlaveRegisterIntrHandler + * @msg: 注册I2C从机中断事件函数 + * @return {*} + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {u32} evt 中断事件,参考 FI2C_SLAVE_INTR_EVT_NUM + * @param {FI2cEvtHandler} handler 中断事件回调函数 + */ +void FI2cSlaveRegisterIntrHandler(FI2c *instance_p, u32 evt, FI2cEvtHandler handler) +{ + FASSERT(instance_p && evt < FI2C_SLAVE_INTR_EVT_NUM); + instance_p->slave_evt_handlers[evt] = handler; +} + +/** + * @name: FI2cSlaveSetupIntr + * @msg: 设置I2C从机的中断 + * @return {FError *} 返回错误码 + * @param {FI2c} *instance_p + */ +FError FI2cSlaveSetupIntr(FI2c *instance_p) +{ + FASSERT(instance_p); + FI2cConfig *config_p = &instance_p->config; + uintptr base_addr = config_p->base_addr; + u32 evt; + u32 mask; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FI2C_ERROR("i2c driver not ready"); + return FI2C_ERR_NOT_READY; + } + + if (FI2C_SLAVE != instance_p->config.work_mode) + { + FI2C_ERROR("i2c work mode shall be slave"); + return FI2C_ERR_INVAL_STATE; + } + + /* disable all i2c irq */ + FI2C_CLEAR_INTR_STATUS(base_addr); + + for (evt = FI2C_EVT_SLAVE_READ_REQUESTED; evt < FI2C_SLAVE_INTR_EVT_NUM; evt++) + { + if (instance_p->slave_evt_handlers[evt] == NULL) + { + FI2cSlaveRegisterIntrHandler(instance_p, evt, FI2cStubHandler); + FI2C_INFO("evt :%d.is default.\r\n", evt); + } + } + FI2C_SET_RX_TL(instance_p->config.base_addr, 0);/* 0 表示接收缓冲区大于等于 1 时触发中断 */ + FI2C_SET_TX_TL(instance_p->config.base_addr, 0);/* 0 表示发送缓冲区大于等于 1 时触发中断 */ + mask = FI2C_GET_INTRRUPT_MASK(base_addr); + mask |= (FI2C_INTR_SLAVE_DEF_MASK); + FI2C_SET_INTRRUPT_MASK(base_addr, mask); + + return FI2C_SUCCESS; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_master.c b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_master.c new file mode 100644 index 0000000000..49afc9cbc3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_master.c @@ -0,0 +1,411 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c_master.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:36:46 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/* + - 一些驱动模块,直接操作硬件的I/O接口,无法实现有意义的操作,此时需要针对中间件或者用户使用习惯设计此模块 (i2c,nand,eth) + - 部分场景适用, 分角色的 I/O 操作 + - 此模块的函数原型,在fooxx.h 中声明一次,方便用户或者中间件层调用 + +*/ + +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "fsleep.h" +#include "fdebug.h" +#include "fi2c_hw.h" +#include "fi2c.h" +#include "finterrupt.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FI2C_DEBUG_TAG "I2C_MASTER" +#define FI2C_ERROR(format, ...) FT_DEBUG_PRINT_E(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_INFO(format, ...) FT_DEBUG_PRINT_I(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) +#define FI2C_DEBUG(format, ...) FT_DEBUG_PRINT_D(FI2C_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FI2C_TIMEOUT 500 + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +/** + * @name: FI2cMasterStartTrans + * @msg: I2C主机开始传输 + * @return {*} + * @param {FI2c} *instance_p, I2C驱动实例数据 + * @param {u32} mem_addr, 从机的片内偏移 + * @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + * @param {u8} flag ,for cmd reg STOP,RESTART. + */ +static FError FI2cMasterStartTrans(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, u16 flag) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FI2C_SUCCESS; + u32 addr_len = mem_byte_len; + + ret = FI2cWaitBusBusy(base_addr); + if (FI2C_SUCCESS != ret) + return ret; + ret = FI2cSetTar(base_addr, instance_p->config.slave_addr); /* 设备地址 */ + if (FI2C_SUCCESS != ret) + return ret; + while (addr_len) + { + ret = FI2cWaitStatus(base_addr, FI2C_STATUS_TFNF); + if (FI2C_SUCCESS != ret) + break; + if (FI2C_GET_STATUS(base_addr) & FI2C_STATUS_TFNF) + { + addr_len--; + if (addr_len != 0) + { + FI2C_WRITE_REG32(base_addr, FI2C_DATA_CMD_OFFSET, + (mem_addr >> (addr_len * BITS_PER_BYTE)) & FI2C_DATA_MASK); /* word address */ + } + else + { + FI2C_WRITE_REG32(base_addr, FI2C_DATA_CMD_OFFSET, + ((mem_addr >> (addr_len * BITS_PER_BYTE)) & FI2C_DATA_MASK) + flag); /* word address */ + } + } + } + return ret; +} + +/** + * @name: FI2cMasterStopTrans + * @msg: I2C主机结束传输 + * @return {*} + * @param {FI2c} *instance_p, I2C驱动实例数据 + */ +static FError FI2cMasterStopTrans(FI2c *instance_p) +{ + FASSERT(instance_p); + FError ret = FI2C_SUCCESS; + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + u32 timeout = 0; + + FI2C_INFO("GET MASTER STOP, stat: 0x%x, 0x%x", FI2C_READ_INTR_STAT(base_addr), + FI2C_READ_RAW_INTR_STAT(base_addr)); + + while (TRUE) + { + if (FI2C_READ_RAW_INTR_STAT(base_addr) & FI2C_INTR_STOP_DET) + { + reg_val = FI2C_READ_REG32(base_addr, FI2C_CLR_STOP_DET_OFFSET); /* read to clr intr status */ + break; + } + else if (FI2C_TIMEOUT < ++timeout) + { + break; /* wait timeout, but no error code ret */ + } + } + + ret = FI2cWaitBusBusy(base_addr); + if (FI2C_SUCCESS == ret) + ret = FI2cFlushRxFifo(base_addr); + + return ret; +} + +/** + * @name: FI2cMasterReadPoll + * @msg: I2C主机读,阻塞直到完成读操作或失败 + * @return {FError *} 返回错误码 + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {u32} mem_addr 从机的内部偏移地址 + * @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + * @param {u8} *buf_p 读目的缓冲区 + * @param {int} buf_len 读目的缓冲区长度 + */ +FError FI2cMasterReadPoll(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, u8 *buf_p, u32 buf_len) +{ + FError ret = FI2C_SUCCESS; + FASSERT(instance_p); + u32 mask; + u32 reg_val; + u32 tx_len = buf_len; + u32 rx_len = buf_len; + u32 rx_limit, tx_limit; + u32 trans_timeout = 0; + uintptr base_addr = instance_p->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FI2C_ERROR("i2c driver not ready"); + return FI2C_ERR_NOT_READY; + } + + if (FI2C_MASTER != instance_p->config.work_mode) + { + FI2C_ERROR("i2c work mode shall be master"); + return FI2C_ERR_INVAL_STATE; + } + + ret = FI2cMasterStartTrans(instance_p, mem_addr, mem_byte_len, FI2C_DATA_CMD_WRITE); + if (FI2C_SUCCESS != ret) + return ret; + /*for trigger rx intr*/ + while (tx_len > 0 || rx_len > 0) + { + /* code */ + rx_limit = FI2C_IIC_FIFO_MAX_LV - FI2C_READ_REG32(base_addr, FI2C_RXFLR_OFFSET); + tx_limit = FI2C_IIC_FIFO_MAX_LV - FI2C_READ_REG32(base_addr, FI2C_TXFLR_OFFSET); + + while (tx_len > 0 & rx_limit > 0 & tx_limit > 0) + { + /* code */ + if (tx_len == 1) + { + + reg_val = FI2C_DATA_CMD_READ | FI2C_DATA_CMD_STOP; + FI2C_WRITE_REG32(instance_p->config.base_addr, FI2C_DATA_CMD_OFFSET, reg_val); + } + else + { + reg_val = FI2C_DATA_CMD_READ; + FI2C_WRITE_REG32(instance_p->config.base_addr, FI2C_DATA_CMD_OFFSET, reg_val); + } + tx_len--; + rx_limit--; + tx_limit--; + } + + u8 rx_tem = FI2C_READ_REG32(base_addr, FI2C_RXFLR_OFFSET); + while (rx_tem > 0 & rx_len > 0) + { + /* code */ + if (FI2C_GET_STATUS(base_addr) & FI2C_STATUS_RFNE) + { + /* trans one byte */ + *buf_p++ = FI2C_READ_DATA(base_addr); + rx_len--; + rx_tem--; + trans_timeout = 0; + } + else if (FI2C_TIMEOUT < (++trans_timeout)) + { + ret = FI2C_ERR_TIMEOUT; + FI2C_ERROR("timeout in i2c master read"); + break; + } + } + } + if (FI2C_SUCCESS == ret) + { + ret = FI2cMasterStopTrans(instance_p); + } + return ret; +} + +/** + * @name: FI2cMasterWritePoll + * @msg: I2C主机写,阻塞直到完成写操作或失败 + * @return {FError *} 返回错误码 + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {u32} mem_addr 从机的内部偏移地址 + * @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + * @param {u8} *buf_p 写源缓冲区 + * @param {size_t} buf_len 写源缓冲区长度 + */ +FError FI2cMasterWritePoll(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, const u8 *buf_p, u32 buf_len) +{ + FASSERT(instance_p && buf_p); + FError ret = FI2C_SUCCESS; + u32 buf_idx = buf_len; + u32 tx_limit; + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + u32 trans_timeout = 0; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FI2C_ERROR("i2c driver not ready"); + return FI2C_ERR_NOT_READY; + } + if (FI2C_MASTER != instance_p->config.work_mode) + { + FI2C_ERROR("i2c work mode shall be master"); + return FI2C_ERR_INVAL_STATE; + } + + ret = FI2cMasterStartTrans(instance_p, mem_addr, mem_byte_len, FI2C_DATA_CMD_WRITE); + if (FI2C_SUCCESS != ret) + return ret; + while (buf_idx) + { + tx_limit = FI2C_IIC_FIFO_MAX_LV - FI2C_READ_REG32(base_addr, FI2C_TXFLR_OFFSET); + while (tx_limit > 0 & buf_idx > 0) + { + if (FI2C_GET_STATUS(base_addr) & FI2C_STATUS_TFNF) + { + if (1 == buf_idx) + { + reg_val = (FI2C_DATA_MASK & *buf_p) | + FI2C_DATA_CMD_WRITE | + FI2C_DATA_CMD_STOP; + FI2C_INFO("Write Stop Singal"); + } + else + { + reg_val = (FI2C_DATA_MASK & *buf_p) | + FI2C_DATA_CMD_WRITE; + } + buf_idx--; + tx_limit--; + FI2C_WRITE_REG32(base_addr, FI2C_DATA_CMD_OFFSET, reg_val); + buf_p++; + trans_timeout = 0; + } + else if (FI2C_TIMEOUT < ++trans_timeout) + { + ret = FI2C_ERR_TIMEOUT; + FI2C_ERROR("timeout in i2c master write"); + break; + } + } + } + if (FI2C_SUCCESS == ret) + { + ret = FI2cMasterStopTrans(instance_p); + } + return ret; +} + +/** + * @name: FI2cMasterReadIntr + * @msg: I2C主机读,中断完成读操作或失败 + * @return {FError *} 返回错误码 + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {u32} mem_addr 从机的内部偏移地址 + * @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + * @param {u8} *buf_p 读目的缓冲区 + * @param {int} buf_len 读目的缓冲区长度 + */ +FError FI2cMasterReadIntr(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, u8 *buf_p, u32 buf_len) +{ + FError ret = FI2C_SUCCESS; + FASSERT(instance_p); + u32 mask; + u32 reg_val; + u32 trans_timeout; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FI2C_ERROR("i2c driver not ready"); + return FI2C_ERR_NOT_READY; + } + if (FI2C_MASTER != instance_p->config.work_mode) + { + FI2C_ERROR("i2c work mode shall be master"); + return FI2C_ERR_INVAL_STATE; + } + + while (instance_p->status != STATUS_IDLE) + { + /* code */ + fsleep_millisec(1); + if (FI2C_TIMEOUT < (++trans_timeout)) + { + ret = FI2C_ERR_TIMEOUT; + FI2C_ERROR("timeout in i2c master read intr."); + break; + } + } + instance_p->rxframe.data_buff = buf_p; + instance_p->rxframe.rx_total_num = buf_len; + instance_p->txframe.tx_total_num = buf_len; + instance_p->rxframe.rx_cnt = 0; + FI2C_SET_RX_TL(instance_p->config.base_addr, 0);/* 0 表示接收缓冲区大于等于 1 时触发中断 */ + ret = FI2cMasterStartTrans(instance_p, mem_addr, mem_byte_len, FI2C_DATA_CMD_WRITE); + instance_p->status = STATUS_READ_IN_PROGRESS; + if (FI2C_SUCCESS != ret) + return ret; + mask = FI2C_GET_INTRRUPT_MASK(instance_p->config.base_addr); + mask |= FI2C_INTR_MASTER_RD_MASK; + ret = FI2cMasterSetupIntr(instance_p, mask); + if (FI2C_SUCCESS != ret) + return ret; + return ret; +} + +/** + * @name: FI2cMasterWriteIntr + * @msg: I2C主机写,中断写操作或失败 + * @return {FError *} 返回错误码 + * @param {FI2c} *instance_p I2C驱动实例数据 + * @param {u32} mem_addr 从机的内部偏移地址 + * @param {u8} mem_byte_len, Size of internal memory address 1->8bit ~ 4->32bit + * @param {u8} *buf_p 写源缓冲区 + * @param {size_t} buf_len 写源缓冲区长度 + */ +FError FI2cMasterWriteIntr(FI2c *instance_p, u32 mem_addr, u8 mem_byte_len, const u8 *buf_p, u32 buf_len) +{ + FError ret = FI2C_SUCCESS; + FASSERT(instance_p); + u32 mask; + u32 trans_timeout = 0; + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FI2C_ERROR("i2c driver not ready"); + return FI2C_ERR_NOT_READY; + } + + if (FI2C_MASTER != instance_p->config.work_mode) + { + FI2C_ERROR("i2c work mode shall be master"); + return FI2C_ERR_INVAL_STATE; + } + while (instance_p->status != STATUS_IDLE) + { + /* code */ + fsleep_millisec(1); + if (FI2C_TIMEOUT < (++trans_timeout)) + { + ret = FI2C_ERR_TIMEOUT; + FI2C_ERROR("timeout in i2c master write intr."); + break; + } + } + instance_p->txframe.data_buff = buf_p; + instance_p->txframe.tx_total_num = buf_len; + instance_p->txframe.tx_cnt = 0; + ret = FI2cMasterStartTrans(instance_p, mem_addr, mem_byte_len, FI2C_DATA_CMD_WRITE); + if (FI2C_SUCCESS != ret) + return ret; + instance_p->status = STATUS_WRITE_IN_PROGRESS; + mask = FI2C_GET_INTRRUPT_MASK(instance_p->config.base_addr); + mask |= FI2C_INTR_MASTER_WR_MASK; + ret = FI2cMasterSetupIntr(instance_p, mask); + if (FI2C_SUCCESS != ret) + return ret; + return ret; +} diff --git a/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_sinit.c b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_sinit.c new file mode 100644 index 0000000000..8ea6a12dec --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/i2c/fi2c/fi2c_sinit.c @@ -0,0 +1,66 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fi2c_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:36:52 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + + +/* - This file contains the implementation of driver's static initialization functionality. +- 驱动静态初始化 */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fi2c.h" +#include "sdkconfig.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +extern const FI2cConfig FI2C_CONFIG_TBL[I2C_INSTANCE_NUM]; +/************************** Function Prototypes ******************************/ +/** + * @name: FI2cLookupConfig + * @msg: 获取I2C驱动的默认配置参数 + * @return {const FI2cConfig*} 驱动默认参数 + * @param {u32} instance_id, 当前控制的I2C控制器实例号 + */ +const FI2cConfig *FI2cLookupConfig(u32 instance_id) +{ + const FI2cConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)I2C_INSTANCE_NUM; index++) + { + if (FI2C_CONFIG_TBL[index].instance_id == instance_id) + { + ptr = &FI2C_CONFIG_TBL[index]; + break; + } + } + + return (const FI2cConfig *)ptr; +} diff --git a/bsp/phytium/libraries/standalone/drivers/ipc/Kconfig b/bsp/phytium/libraries/standalone/drivers/ipc/Kconfig new file mode 100644 index 0000000000..2012b165d2 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/ipc/Kconfig @@ -0,0 +1,9 @@ +config ENABLE_FSEMAPHORE + bool + prompt "Use FSemaphore" + default n + depends on TARGET_E2000S || TARGET_E2000D || TARGET_E2000Q + help + Select FSemaphore driver component + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore.c b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore.c new file mode 100644 index 0000000000..6409551a3a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore.c @@ -0,0 +1,337 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsemaphore.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for semaphore user api implmentation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022/5/23 init commit + */ + + +/***************************** Include Files *********************************/ +#include + +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" +#include "fassert.h" + +#include "fsemaphore_hw.h" +#include "fsemaphore.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSEMA_DEBUG_TAG "SEMA" +#define FSEMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FSEMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSEMA_WARN(format, ...) FT_DEBUG_PRINT_W(FSEMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSEMA_INFO(format, ...) FT_DEBUG_PRINT_I(FSEMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSEMA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSEMA_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +/** + * @name: FSemaCfgInitialize + * @msg: 初始化Semaphore控制器 + * @return {FError} FSEMA_SUCCESS 表示初始化成功 + * @param {FSema} *instance, Semaphore控制器实例 + * @param {FSemaConfig} *input_config, Semaphore控制器配置 + */ +FError FSemaCfgInitialize(FSema *const instance, const FSemaConfig *input_config) +{ + FASSERT(instance && input_config); + uintptr base_addr = input_config->base_addr; + FASSERT_MSG((0 != base_addr), "invalid base addr"); + FError ret = FSEMA_SUCCESS; + + if (FT_COMPONENT_IS_READY == instance->is_ready) + { + FSEMA_WARN("device is already initialized!!!"); + } + + if (&instance->config != input_config) + instance->config = *input_config; + + FSemaHwResetAll(base_addr); /* 重置所有的锁 */ + + if (FSEMA_SUCCESS == ret) + instance->is_ready = FT_COMPONENT_IS_READY; + + return ret; +} + +/** + * @name: FSemaDeInitialize + * @msg: 去初始化Semaphore控制器 + * @return {void} 无 + * @param {FSema} *instance, Semaphore控制器实例 + */ +void FSemaDeInitialize(FSema *const instance) +{ + FASSERT(instance); + u32 loop; + uintptr base_addr = instance->config.base_addr; + + for (loop = 0; loop < FSEMA_NUM_OF_LOCKER; loop++) + { + if (NULL != instance->locker[loop]) + { + FSEMA_WARN("locker %d @%p is not yet deleted !!!", loop, instance->locker[loop]); + memset(instance->locker[loop], 0, sizeof(*instance->locker[loop])); + } + + } + + if (0 != base_addr) /* 如果base addr为0,实例可能还没有初始化 */ + { + FSemaHwResetAll(base_addr); + } + + memset(instance, 0, sizeof(*instance)); + + return; +} + +/** + * @name: FSemaCreateLocker + * @msg: 分配和创建Semaphore锁 + * @return {FError} FSEMA_SUCCESS 表示分配成功 + * @param {FSema} *instance, Semaphore控制器实例 + * @param {FSemaLocker} *locker, Semaphore锁的实例 + */ +FError FSemaCreateLocker(FSema *const instance, FSemaLocker *const locker) +{ + FASSERT(instance && locker); + u32 locker_idx; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FSEMA_ERROR("device@%p not yet inited !!!", instance->config.base_addr); + return FSEMA_ERR_NOT_INIT; + } + + for (locker_idx = 0; locker_idx < FSEMA_NUM_OF_LOCKER; locker_idx++) + { + /* 分配一把未创建的锁 */ + if (NULL == instance->locker[locker_idx]) + { + FSEMA_INFO("allocate locker %d", locker_idx); + break; + } + } + + if (locker_idx >= FSEMA_NUM_OF_LOCKER) + { + FSEMA_ERROR("no locker available !!!"); + return FSEMA_ERR_NO_AVAILABLE_LOCKER; /* 所有的锁都已经分配创建 */ + } + + instance->locker[locker_idx] = locker; + locker->index = locker_idx; /* 分配锁,将锁的实例挂在控制器实例上 */ + + locker->owner = FSEMA_OWNER_NONE; /* 当前锁还没有owner */ + locker->name[0] = '\0'; + locker->sema = instance; + + return FSEMA_SUCCESS; +} + +/** + * @name: FSemaTryLock + * @msg: 尝试获取Semaphore锁 + * @return {FError} FSEMA_SUCCESS 表示成功获取锁,FSEMA_ERR_LOCK_TIMEOUT 表示锁已经被占用 + * @param {FSemaLocker} *locker, Semaphore锁的实例 + * @param {u32} owner, 当前尝试获取锁的是谁 + * @param {u32} try_times, 尝试获取的次数 + * @param {FSemaRelaxHandler} relax_handler, 每次尝试获取锁失败后的relax函数 + */ +FError FSemaTryLock(FSemaLocker *const locker, u32 owner, u32 try_times, FSemaRelaxHandler relax_handler) +{ + FASSERT(locker && locker->sema); + FSema *const instance = locker->sema; + uintptr base_addr = instance->config.base_addr; + boolean lock_success = FALSE; + FError ret = FSEMA_SUCCESS; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FSEMA_ERROR("device@%p not yet inited !!!", instance->config.base_addr); + return FSEMA_ERR_NOT_INIT; + } + + while (try_times > 0) + { + /* 尝试获取锁 */ + lock_success = FSemaTryLockOnce(base_addr, locker->index); + if (TRUE == lock_success) + break; + + if (relax_handler) + relax_handler(instance); + + try_times--; + } + + if (FALSE == lock_success) + { + ret = FSEMA_ERR_LOCK_TIMEOUT; + FSEMA_ERROR("locker-%d has been taken by owner 0x%x", locker->index, locker->owner); + } + else + { + locker->owner = owner; /* 记录当前locker的owner */ + FSEMA_INFO("locker-%d taken success by owner 0x%x", locker->index, owner); + } + + return ret; +} + +/** + * @name: FSemaUnlock + * @msg: 尝试释放Semaphore锁 + * @return {FError} FSEMA_SUCCESS释放锁成功 + * @param {FSemaLocker} *locker, Semaphore锁实例 + * @param {u32} owner, 当前尝试释放锁的身份 + */ +FError FSemaUnlock(FSemaLocker *const locker, u32 owner) +{ + FASSERT(locker && locker->sema); + FSema *const instance = locker->sema; + uintptr base_addr = instance->config.base_addr; + FError ret = FSEMA_SUCCESS; + u32 reg_val; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FSEMA_ERROR("device@%p not yet inited !!!", instance->config.base_addr); + return FSEMA_ERR_NOT_INIT; + } + + if (locker->owner != owner) + { + FSEMA_ERROR("locker is owned by 0x%x, 0x%x has no premission to unlock it !!!", + locker->owner, owner); + return FSEMA_ERR_NO_PERMISSION; + } + + if (FALSE == FSemaHwGetStatus(base_addr, locker->index)) + { + FSEMA_INFO("locker-%d is not in locked status 0x%x!!!", + locker->index, FSemaReadReg(base_addr, FSEMA_STATE_REG_OFFSET)); + return ret; + } + + reg_val = FSEMA_RLOCK_X_UNLOCK; + FSemaWriteReg(base_addr, FSEMA_RLOCK_X_REG_OFFSET(locker->index), reg_val); /* 写0解锁信号量 */ + locker->owner = FSEMA_OWNER_NONE; /* 解锁成功,当前锁持有者为None */ + + return ret; +} + +/** + * @name: FSemaUnlockAll + * @msg: 强制解除所有Semaphore锁 + * @return {FError} FSEMA_SUCCESS表示强制解锁成功 + * @param {FSema} *instance, Semaphore控制器实例 + */ +FError FSemaUnlockAll(FSema *const instance) +{ + FASSERT(instance); + uintptr base_addr = instance->config.base_addr; + u32 loop; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FSEMA_ERROR("device@%p not yet inited !!!", instance->config.base_addr); + return FSEMA_ERR_NOT_INIT; + } + + FSemaHwResetAll(base_addr); + + for (loop = 0; loop < FSEMA_NUM_OF_LOCKER; loop++) + { + if (NULL != instance->locker[loop]) + { + instance->locker[loop]->owner = FSEMA_OWNER_NONE; /* 解锁成功,当前锁持有者为None */ + } + } + + return FSEMA_SUCCESS; +} + +/** + * @name: FSemaDeleteLocker + * @msg: 强制解除Semaphore锁并删除锁实例 + * @return {FError} FSEMA_SUCCESS 表示删除锁成功 + * @param {FSemaLocker} *locker, Semaphore锁实例 + */ +FError FSemaDeleteLocker(FSemaLocker *const locker) +{ + FASSERT(locker && locker->sema); + FSema *const instance = locker->sema; + uintptr base_addr = instance->config.base_addr; + u32 locker_idx = locker->index; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FSEMA_ERROR("device@%p not yet inited !!!", instance->config.base_addr); + return FSEMA_ERR_NOT_INIT; + } + + if (TRUE == FSemaHwGetStatus(base_addr, locker_idx)) + { + FSEMA_WARN("caution, locker-%d has been taken by 0x%x !!!", + locker_idx, locker->owner); + } + + FASSERT_MSG((instance->locker[locker_idx] == locker), "invalid locker index %d", locker_idx); + + FSemaWriteReg(base_addr, FSEMA_RLOCK_X_REG_OFFSET(locker->index), FSEMA_RLOCK_X_UNLOCK); /* 写0解锁信号量 */ + + instance->locker[locker_idx] = NULL; + memset(locker, 0, sizeof(*locker)); + + return FSEMA_SUCCESS; +} + +/** + * @name: FSemaIsLocked + * @msg: 检查指定Semaphore锁是否处于锁定状态 + * @return {boolean} TRUE: 处于锁定状态 + * @param {FSemaLocker} *locker, Semaphore锁实例 + */ +boolean FSemaIsLocked(FSemaLocker *locker) +{ + FASSERT(locker && locker->sema); + FSema *const instance = locker->sema; + uintptr base_addr = instance->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FSEMA_ERROR("device@%p not yet inited !!!", instance->config.base_addr); + return FSEMA_ERR_NOT_INIT; + } + + return FSemaHwGetStatus(base_addr, locker->index); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore.h b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore.h new file mode 100644 index 0000000000..361234d1e5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore.h @@ -0,0 +1,109 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsemaphore.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:35 + * Description:  This files is for semaphore user api definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022/5/23 init commit + */ + + +#ifndef DRIVERS_IPC_FSEMAPHORE_H +#define DRIVERS_IPC_FSEMAPHORE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "ftypes.h" +#include "ferror_code.h" + +/************************** Constant Definitions *****************************/ +#define FSEMA_NUM_OF_LOCKER 32U +#define FSEMA_OWNER_NONE 0U + +#define FSEMA_SUCCESS FT_SUCCESS +#define FSEMA_ERR_NOT_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrSema, 0U) +#define FSEMA_ERR_NO_AVAILABLE_LOCKER FT_MAKE_ERRCODE(ErrModBsp, ErrSema, 1U) +#define FSEMA_ERR_LOCK_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrSema, 2U) +#define FSEMA_ERR_NO_PERMISSION FT_MAKE_ERRCODE(ErrModBsp, ErrSema, 3U) +/**************************** Type Definitions *******************************/ +typedef struct +{ + u32 id; /* Semaphore控制器id */ + uintptr base_addr; /* Semaphore控制器基地址 */ +} FSemaConfig; /* Semaphore控制器配置 */ + +typedef struct _FSema FSema; + +typedef struct +{ + u32 index; /* Semaphore锁id */ +#define FSEMA_LOCKER_NAME_LEN 32U + char name[FSEMA_LOCKER_NAME_LEN]; /* Semaphore锁的名字 */ + u32 owner; /* Semaphore锁的拥有者, 当前持有锁的人, 如果没有上锁就标记FSEMA_OWNER_NONE */ + FSema *sema; /* Semaphore控制器实例 */ +} FSemaLocker; /* Semaphore锁实例 */ + +typedef struct _FSema +{ + FSemaConfig config; /* Semaphore控制器配置 */ + u32 is_ready; /* Semaphore控制器初始化是否完成 */ + FSemaLocker *locker[FSEMA_NUM_OF_LOCKER]; /* Semaphore锁实例,locker[i] == NULL 表示锁尚未分配 */ +} FSema; /* Semaphore控制器实例 */ + +typedef void (*FSemaRelaxHandler)(FSema *const instance); /* 等待下一次上锁的relax函数 */ +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/* 获取Semaphore的默认配置 */ +const FSemaConfig *FSemaLoopkupConfig(u32 instance_id); + +/* 初始化Semaphore控制器 */ +FError FSemaCfgInitialize(FSema *const instance, const FSemaConfig *config); + +/* 去初始化Semaphore控制器 */ +void FSemaDeInitialize(FSema *const instance); + +/* 分配和创建Semaphore锁 */ +FError FSemaCreateLocker(FSema *const instance, FSemaLocker *const locker); + +/* 强制解除Semaphore锁并删除锁实例 */ +FError FSemaDeleteLocker(FSemaLocker *const locker); + +/* 尝试获取指定Semaphore锁 */ +FError FSemaTryLock(FSemaLocker *const locker, u32 owner, u32 try_times, FSemaRelaxHandler relax_handler); + +/* 尝试释放指定Semaphore锁 */ +FError FSemaUnlock(FSemaLocker *const locker, u32 owner); + +/* 强制解除所有Semaphore锁 */ +FError FSemaUnlockAll(FSema *const instance); + +/* 检查指定Semaphore锁是否处于锁定状态 */ +boolean FSemaIsLocked(FSemaLocker *locker); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_g.c b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_g.c new file mode 100644 index 0000000000..1ee775f7d1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_g.c @@ -0,0 +1,50 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsemaphore_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:09 + * Description:  This files is for semaphore static variables + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022/5/23 init commit + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fsemaphore.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +const FSemaConfig fsema_cfg_tbl[FSEMA_INSTANCE_NUM] = +{ + [FSEMA0_ID] = + { + .id = FSEMA0_ID, + .base_addr = FSEMA0_BASE_ADDR + } +}; + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_hw.h b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_hw.h new file mode 100644 index 0000000000..d70e93ebf5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_hw.h @@ -0,0 +1,153 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsemaphore_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:24:52 + * Description:  This files is for semaphore register definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022/5/23 init commit + */ + + +#ifndef DRIVERS_IPC_FSEMAPHORE_HW_H +#define DRIVERS_IPC_FSEMAPHORE_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fparameters.h" +#include "ftypes.h" +#include "fio.h" +#include "fassert.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ +/** @name Register Map + * + * Register offsets from the base address of an Semaphore. + * @{ + */ +#define FSEMA_RST_REG_OFFSET 0x0U /* 写 1 复位所有信号量 */ +#define FSEMA_IND_RST_REG_OFFSET 0x4U /* 写信号量独热码为 1,复位对应信号量 */ +#define FSEMA_STATE_REG_OFFSET 0x8U /* 信号量 0 ~ 31的状态 */ +#define FSEMA_RLOCK_X_REG_OFFSET(x) (0x10U + (x) * 4) /* 信号量 X 读锁定寄存器 */ + +/** @name FSEMA_RST_REG_OFFSET Register + */ +#define FSEMA_RST_ALL BIT(0) /* 写 1 复位所有信号量 */ + +/** @name FSEMA_IND_RST_REG_OFFSET Register + */ +#define FSEMA_IND_RSET(locker_idx) BIT(locker_idx) /* 写信号量独热码为 1,复位对应信号量 */ + +/** @name FSEMA_STATE_REG_OFFSET Register + */ +#define FSEMA_LOCKER_STATE(locker_idx) BIT(locker_idx) /* 状态:0 表示解锁,1 表示锁定 */ + +/** @name FSEMA_RLOCK_X_REG_OFFSET Register + */ +#define FSEMA_RLOCK_X_UNLOCK 0 /* 写 0:信号量被解锁 */ +/* 读返回 0:信号量当前未被锁定,读后被锁定 + 读返回 1:信号量当前已经被锁定,锁定失败 */ +#define FSEMA_RLOCK_X_IS_LOCKED 1 +#define FSEMA_RLOCK_X_TAKE_LOCKER 0 + +#define FSEMA_MIN_LOCKER_IDX 0 +#define FSEMA_MAX_LOCKER_IDX 31 + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +static u32 FSemaReadReg(uintptr base_addr, u32 reg_off) +{ + return FtIn32(base_addr + reg_off); +} + +static inline void FSemaWriteReg(uintptr base_addr, u32 reg_off, u32 reg_val) +{ + FtOut32(base_addr + reg_off, reg_val); + return; +} + +/** + * @name: FSemaHwResetAll + * @msg: 强制解除所有锁定 + * @return {void} 无 + * @param {uintptr} base_addr, Semaphore 控制器基地址 + */ +static inline void FSemaHwResetAll(uintptr base_addr) +{ + FSemaWriteReg(base_addr, FSEMA_RST_REG_OFFSET, FSEMA_RST_ALL); +} + +/** + * @name: FSemaHwResetLocker + * @msg: 强制解除指定锁定 + * @return {void} 无 + * @param {uintptr} base_addr, Semaphore 控制器基地址 + * @param {u32} locker_idx, Semaphore锁id + */ +static inline void FSemaHwResetLocker(uintptr base_addr, u32 locker_idx) +{ + u32 reg_val = FSemaReadReg(base_addr, FSEMA_IND_RST_REG_OFFSET); + reg_val |= FSEMA_IND_RSET(locker_idx); + FSemaWriteReg(base_addr, FSEMA_IND_RST_REG_OFFSET, reg_val); + return; +} + +/** + * @name: FSemaHwGetStatus + * @msg: 获取锁定状态 + * @return {boolean} TRUE: 被锁定, FALSE: 未被锁定 + * @param {uintptr} base_addr, Semaphore 控制器基地址 + * @param {u32} locker_idx, Semaphore锁id + */ +static inline boolean FSemaHwGetStatus(uintptr base_addr, u32 locker_idx) +{ + u32 reg_val = FSemaReadReg(base_addr, FSEMA_STATE_REG_OFFSET); + return (reg_val & FSEMA_LOCKER_STATE(locker_idx)) ? TRUE : FALSE; +} + +/** + * @name: FSemaTryLockOnce + * @msg: 尝试锁定 + * @return {boolean} TRUE: 锁定成功 + * @param {uintptr} base_addr, Semaphore 控制器基地址 + * @param {u32} locker_idx, Semaphore锁id + */ +static inline boolean FSemaTryLockOnce(uintptr base_addr, u32 locker_idx) +{ + boolean lock_success = FALSE; + u32 reg_val = FSemaReadReg(base_addr, FSEMA_RLOCK_X_REG_OFFSET(locker_idx)); /* 读寄存器,尝试上锁 */ + + /* 读返回 1:信号量之前已经被锁定,本次锁定失败 + 读返回 0:信号量之前未被锁定,本次锁定成功 */ + return (FSEMA_RLOCK_X_IS_LOCKED & reg_val) ? FALSE : TRUE; +} + +/************************** Function Prototypes ******************************/ + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_sinit.c b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_sinit.c new file mode 100644 index 0000000000..4e52d6fd1a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/ipc/fsemaphore/fsemaphore_sinit.c @@ -0,0 +1,63 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsemaphore_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:15 + * Description:  This files is for semaphore static init + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022/5/23 init commit + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fsemaphore.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +extern const FSemaConfig fsema_cfg_tbl[FSEMA_INSTANCE_NUM]; + +/************************** Function Prototypes ******************************/ +/** + * @name: FSemaLoopkupConfig + * @msg: 获取Semaphore的默认配置 + * @return {const FSemaConfig *} Semaphore的默认配置 + * @param {u32} instance_id, Semaphore的实例id + */ +const FSemaConfig *FSemaLoopkupConfig(u32 instance_id) +{ + const FSemaConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FSEMA_INSTANCE_NUM; index++) + { + if (fsema_cfg_tbl[index].id == instance_id) + { + ptr = &fsema_cfg_tbl[index]; + break; + } + } + + return (const FSemaConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mio/Kconfig b/bsp/phytium/libraries/standalone/drivers/mio/Kconfig new file mode 100644 index 0000000000..018035d6e8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mio/Kconfig @@ -0,0 +1,9 @@ +menu "Hardware Mio Configuration" + config ENABLE_MIO + bool + prompt "Use Mio" + depends on TARGET_E2000S || TARGET_E2000D || TARGET_E2000Q + + default n +endmenu + diff --git a/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio.c b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio.c new file mode 100644 index 0000000000..ab35e436aa --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio.c @@ -0,0 +1,137 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fmio.c + * Date: 2022-07-06 15:01:30 + * LastEditTime: 2022-07-06 15:01:30 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include +#include "fmio_hw.h" +#include "fmio.h" + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FMIO_DEBUG_TAG "MIO" +#define FMIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FMIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FMIO_INFO(format, ...) FT_DEBUG_PRINT_I(FMIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FMIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FMIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/** + * @name: FMioFuncInit + * @msg: 初始化 + * @return {*} + * @param {FMioCtrl} *instance_p + * @param {u32} mio_type + */ +FError FMioFuncInit(FMioCtrl *instance_p, u32 mio_type) +{ + FASSERT(instance_p); + + FError ret = FMIO_SUCCESS; + + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FMIO_ERROR("device is already initialized!!!"); + return FMIO_ERR_INVAL_STATE; + } + + ret = FMioSelectFunc(instance_p->config.mio_base_addr, mio_type); + if (FMIO_SUCCESS == ret) + { + instance_p->is_ready = FT_COMPONENT_IS_READY; + } + return ret; +} + +/** + * @name: FMioFuncDeinit + * @msg: 去初始化 + * @return {*} + * @param {FMioCtrl} *instance_p + */ +FError FMioFuncDeinit(FMioCtrl *instance_p) +{ + FASSERT(instance_p); + FError ret = FMIO_SUCCESS; + + instance_p->is_ready = 0; + + /* 重新配置成默认IIC模式 */ + ret = FMioSelectFunc(instance_p->config.mio_base_addr, FMIO_FUNC_SET_I2C); + + memset(instance_p, 0, sizeof(*instance_p)); + + return ret; +} + +/** + * @name: FMioFuncGetAddress + * @msg: 获取功能设置的基地址 + * @return {uintptr} + * @param {FMioCtrl} *instance_p + */ +uintptr FMioFuncGetAddress(FMioCtrl *instance_p, u32 mio_type) +{ + FASSERT(instance_p); + FError ret = FMIO_SUCCESS; + + if (instance_p->is_ready != FT_COMPONENT_IS_READY) + { + FMIO_ERROR("Mio instance_id: %d ,not init.", instance_p->config.instance_id); + return FMIO_ERR_NOT_READY; + } + + if (FMioGetFunc(instance_p->config.mio_base_addr) != mio_type) + { + FMIO_ERROR("Mio instance_id: %d ,mio_type error,please init type first.", instance_p->config.instance_id); + return FMIO_ERR_INVAL_STATE; + } + + return instance_p->config.func_base_addr; +} + +/** + * @name: FMioFuncGetIrqNum + * @msg: 获取MIO的中断号 + * @return {u32}中断号 + * @param {FMioCtrl} *instance_p + */ +u32 FMioFuncGetIrqNum(FMioCtrl *instance_p, u32 mio_type) +{ + FASSERT(instance_p); + FError ret = FMIO_SUCCESS; + + if (instance_p->is_ready != FT_COMPONENT_IS_READY) + { + FMIO_ERROR("Mio instance_id: %d ,not init.", instance_p->config.instance_id); + return FMIO_ERR_NOT_READY; + } + + if (FMioGetFunc(instance_p->config.mio_base_addr) != mio_type) + { + FMIO_ERROR("Mio instance_id: %d ,mio_type error,please init type first.", instance_p->config.instance_id); + return FMIO_ERR_INVAL_STATE; + } + + return instance_p->config.irq_num; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio.h b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio.h new file mode 100644 index 0000000000..5343130add --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio.h @@ -0,0 +1,82 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fmio.h + * Date: 2022-06-21 15:40:06 + * LastEditTime: 2022-06-21 15:40:06 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_MIO_FMIO_H +#define DRIVERS_MIO_FMIO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "ferror_code.h" +#include "fassert.h" + +/************************** Constant Definitions *****************************/ +#define FMIO_SUCCESS FT_SUCCESS +#define FMIO_ERR_INVAL_PARM FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 1) +#define FMIO_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 2) +#define FMIO_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 3) +#define FMIO_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 4) +#define FMIO_ERR_INVAL_STATE FT_MAKE_ERRCODE(ErrModBsp, ErrBspMio, 5) + +/**************************** Type Definitions *******************************/ + +typedef struct +{ + u32 instance_id; /*mio id*/ + uintptr func_base_addr; /*I2C or UART function address*/ + u32 irq_num; /* Device intrrupt id */ + uintptr mio_base_addr; /*MIO control address*/ +} FMioConfig; /*mio configs*/ + +typedef struct +{ + FMioConfig config; /* mio config */ + u32 is_ready; /* mio initialize the complete flag */ +} FMioCtrl; + +/************************** Function Prototypes ******************************/ +/*获取MIO的配置信息*/ +const FMioConfig *FMioLookupConfig(u32 instance_id); + +/*初始化MIO的功能*/ +FError FMioFuncInit(FMioCtrl *instance_p, u32 mio_type); + +/*去初始化*/ +FError FMioFuncDeinit(FMioCtrl *instance_p); + +/*获取功能配置的基地址*/ +uintptr FMioFuncGetAddress(FMioCtrl *instance_p, u32 mio_type); + +/*获取功能的中断号*/ +u32 FMioFuncGetIrqNum(FMioCtrl *instance_p, u32 mio_type); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_g.c b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_g.c new file mode 100644 index 0000000000..e018aa6452 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_g.c @@ -0,0 +1,130 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fmio_g.c + * Date: 2022-06-20 21:05:07 + * LastEditTime: 2022-06-20 21:05:07 + * Description:  This file is for mio + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 0.1.0 liu 2022.06.20 init + */ + +/***************************** Include Files *********************************/ +#include "fparameters.h" +#include "fmio_hw.h" +#include "fmio.h" + +/************************** Constant Definitions *****************************/ + +const FMioConfig FMioConfigTbl[MIO_INSTANCE_NUM] = +{ + { + .instance_id = MIO_INSTANCE_0, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_0), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_0), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_0) + }, + { + .instance_id = MIO_INSTANCE_1, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_1), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_1), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_1) + }, + { + .instance_id = MIO_INSTANCE_2, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_2), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_2), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_2) + }, + { + .instance_id = MIO_INSTANCE_3, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_3), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_3), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_3) + }, + { + .instance_id = MIO_INSTANCE_4, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_4), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_4), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_4) + }, + { + .instance_id = MIO_INSTANCE_5, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_5), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_5), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_5) + }, + { + .instance_id = MIO_INSTANCE_6, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_6), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_6), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_6) + }, + { + .instance_id = MIO_INSTANCE_7, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_7), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_7), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_7) + }, + { + .instance_id = MIO_INSTANCE_8, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_8), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_8), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_8) + }, + { + .instance_id = MIO_INSTANCE_9, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_9), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_9), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_9) + }, + { + .instance_id = MIO_INSTANCE_10, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_10), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_10), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_10) + }, + { + .instance_id = MIO_INSTANCE_11, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_11), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_11), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_11) + }, + { + .instance_id = MIO_INSTANCE_12, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_12), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_12), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_12) + }, + { + .instance_id = MIO_INSTANCE_13, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_13), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_13), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_13) + }, + { + .instance_id = MIO_INSTANCE_14, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_14), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_14), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_14) + }, + { + .instance_id = MIO_INSTANCE_15, + .func_base_addr = FMIO_BASE_ADDR(MIO_INSTANCE_15), + .irq_num = FMIO_IRQ_NUM(MIO_INSTANCE_15), + .mio_base_addr = FMIO_BASE_SET_ADDR(MIO_INSTANCE_15) + } +}; diff --git a/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_hw.c b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_hw.c new file mode 100644 index 0000000000..336d93c52e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_hw.c @@ -0,0 +1,89 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fmio_hw.c + * Date: 2022-06-20 21:05:23 + * LastEditTime: 2022-06-20 21:05:23 + * Description:  This file is for mio + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 0.1.0 liushengming 2022.06.20 init + */ + +/***************************** Include Files *********************************/ + +#include "fmio_hw.h" +#include "ftypes.h" +#include "fassert.h" +#include "fmio.h" +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FMIO_DEBUG_TAG "MIO-HW" +#define FMIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FMIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FMIO_INFO(format, ...) FT_DEBUG_PRINT_I(FMIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FMIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FMIO_DEBUG_TAG, format, ##__VA_ARGS__) +/************************** Function Prototypes ******************************/ + +/** + * @name: FMioSelectFunc + * @msg: 设置Mio功能 + * @return {*} + * @param {uintptr} addr + * @param {u32} mio_type + */ +FError FMioSelectFunc(uintptr addr, u32 mio_type) +{ + FASSERT(mio_type < FMIO_NUM_OF_MIO_FUNC); + FASSERT(addr); + + u32 reg_val; + + reg_val = FMioReadStatus(addr); + + if (mio_type == reg_val) + { + return FMIO_SUCCESS; + } + + FMioWriteFunc(addr, mio_type); + + return FMIO_SUCCESS; +} + +/** + * @name: FMioGetMioFunc + * @msg: 获取Mio状态 + * @return {*} + * @param {uintptr} addr + */ +u32 FMioGetFunc(uintptr addr) +{ + FASSERT(addr); + + return FMioReadStatus(addr); +} + +/** + * @name: FMioGetVersion + * @msg: 获取版本信息,默认32'h1 + * @return {*} + * @param {uintptr} addr + */ +u32 FMioGetVersion(uintptr addr) +{ + FASSERT(addr); + + return FMioReadVersion(addr); +} diff --git a/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_hw.h b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_hw.h new file mode 100644 index 0000000000..acc1699fae --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_hw.h @@ -0,0 +1,134 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fmio_hw.h + * Date: 2022-06-20 21:05:34 + * LastEditTime: 2022-06-20 21:05:34 + * Description:  This file is for mio + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 0.1.0 liushengming 2022.06.20 init + */ +#ifndef DRIVERS_MIO_FMIO_HW_H +#define DRIVERS_MIO_FMIO_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fparameters.h" +#include "fio.h" +#include "fkernel.h" +#include "fdebug.h" +#include "ferror_code.h" + + +/************************** Constant Definitions *****************************/ + +/** @name Register Map + * + * Register offsets from the base address of MIO device. + * + */ +#define FMIO_BASE_SET_ADDR(x) FMIO_BASE_ADDR(x)+0x1000 + +#define FMIO_FUNC_OFFSET 0x00 +#define FMIO_SEL_STATE_OFFSET 0x04 +#define FMIO_VER_OFFSET 0x100 + +/* creg_mio_func_sel */ +#define FMIO_FUNC_SEL_MASK GENMASK(1,0) +#define FMIO_FUNC_SET(n) (FMIO_FUNC_SEL_MASK & (n)) +enum +{ + FMIO_FUNC_SET_I2C = 0b00, + FMIO_FUNC_SET_UART = 0b01, + + FMIO_NUM_OF_MIO_FUNC +}; + +#define FMIO_FUNC_STATE_MASK GENMASK(1, 0) +#define FMIO_VERSION_MASK GENMASK(31, 0) + +/***************** Macros (Inline Functions) Definitions *********************/ +/** + * @name: FMIO_READ_REG32 + * @msg: 读取MIO寄存器 + * @param {u32} addr MIO的基地址 + * @param {u32} reg_offset MIO的寄存器的偏移 + * @return {u32} 寄存器参数 + */ +#define FMIO_READ_REG32(addr, reg_offset) FtIn32(addr + (u32)reg_offset) + +/** + * @name: FMIO_WRITE_REG32 + * @msg: 写入MIO寄存器 + * @param {u32} addr MIO的基地址 + * @param {u32} reg_offset MIO的寄存器的偏移 + * @param {u32} reg_value 写入寄存器参数 + * @return {void} + */ +#define FMIO_WRITE_REG32(addr, reg_offset, reg_value) FtOut32(addr + (u32)reg_offset, (u32)reg_value) + +/** + * @name: FMioWriteFunc + * @msg: 设置MIO的功能 + * @return {*} + * @param {uintptr} addr + * @param {u32} val + */ +static inline void FMioWriteFunc(uintptr addr, u32 val) +{ + FMIO_WRITE_REG32(addr, FMIO_FUNC_OFFSET, val); +} + +/** + * @name: FMioReadStatus + * @msg: 获取MIO的设置 + * @return {u32} register value + * @param {uintptr} addr + */ +static inline u32 FMioReadStatus(uintptr addr) +{ + return FMIO_READ_REG32(addr, FMIO_SEL_STATE_OFFSET) & FMIO_FUNC_STATE_MASK; +} + +/** + * @name: FMioReadVersion + * @msg: 获取MIO的版本信息 + * @return {u32} register value + * @param {uintptr} addr + */ +static inline u32 FMioReadVersion(uintptr addr) +{ + return FMIO_READ_REG32(addr, FMIO_VER_OFFSET) & FMIO_VERSION_MASK; +} + +/************************** Function Prototypes ******************************/ +/*设置Mio功能*/ +FError FMioSelectFunc(uintptr addr, u32 mio_type); + +/*获取Mio状态*/ +u32 FMioGetFunc(uintptr addr); + +/*获取版本信息,默认32'h1*/ +u32 FMioGetVersion(uintptr addr); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_sinit.c b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_sinit.c new file mode 100644 index 0000000000..a971924e37 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mio/fmio/fmio_sinit.c @@ -0,0 +1,60 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fmio_sinit.c + * Date: 2022-06-20 20:33:25 + * LastEditTime: 2022-06-20 20:33:25 + * Description:  This file is for mio + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 0.1.0 liushengming 2022.06.20 init + */ +#include "ftypes.h" +#include "fparameters.h" +#include "fassert.h" +#include "fmio.h" +#include "fmio_hw.h" + + +extern FMioConfig FMioConfigTbl[MIO_INSTANCE_NUM]; + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FMIO_DEBUG_TAG "MIO" +#define FMIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FMIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/** + * @name: FMioLookupConfig + * @msg: get mio configs by id + * @param {u32} instance_id, id of mio ctrl + * @return {FMioConfig *}, mio config address + */ +const FMioConfig *FMioLookupConfig(u32 instance_id) +{ + FASSERT(instance_id < MIO_INSTANCE_NUM); + const FMioConfig *pconfig = NULL; + u32 index; + + for (index = 0; index < (u32)MIO_INSTANCE_NUM; index++) + { + if (FMioConfigTbl[index].instance_id == instance_id) + { + pconfig = &FMioConfigTbl[index]; + break; + } + } + return (const FMioConfig *)pconfig; +} diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/Kconfig b/bsp/phytium/libraries/standalone/drivers/mmc/Kconfig new file mode 100644 index 0000000000..4bf40f4a68 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/Kconfig @@ -0,0 +1,19 @@ +config ENABLE_FSDMMC + bool + prompt "Use FSdmmc" + default n + depends on USE_SDMMC + depends on TARGET_F2000_4 || TARGET_D2000 + help + Select FSdmmc driver component + +config ENABLE_FSDIO + bool + prompt "Use FSdio" + default n + depends on USE_SDMMC + depends on TARGET_E2000S || TARGET_E2000D || TARGET_E2000Q + help + Select FSdio driver component + + \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio.c new file mode 100644 index 0000000000..771e4ff9ca --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio.c @@ -0,0 +1,482 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio.c + * Date: 2022-05-26 16:27:54 + * LastEditTime: 2022-05-26 16:27:54 + * Description:  This files is for SDIO user function implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ + +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "fdebug.h" +#include "fassert.h" +#include "ftypes.h" +#include "fsleep.h" + +#include "fcache.h" + +#include "fsdio_hw.h" +#include "fsdio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDIO_DEBUG_TAG "FSDIO" +#define FSDIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_WARN(format, ...) FT_DEBUG_PRINT_W(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_INFO(format, ...) FT_DEBUG_PRINT_I(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +static FError FSdioReset(FSdio *const instance_p); +static FError FSdioUpdateExternalClk(uintptr base_addr, u32 uhs_reg_val); + +/*****************************************************************************/ +/** + * @name: FSdioCfgInitialize + * @msg: initialization SDIO controller instance + * @return {FError} FSDIO_SUCCESS if initialization success, otherwise failed + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioConfig} *input_config_p, SDIO controller configure + * @note get into card-detect mode after initialization, bus width = 1, card freq = 400kHz + */ +FError FSdioCfgInitialize(FSdio *const instance_p, const FSdioConfig *input_config_p) +{ + FASSERT(instance_p && input_config_p); + FError ret = FSDIO_SUCCESS; + + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FSDIO_WARN("device is already initialized!!!"); + } + + if (&instance_p->config != input_config_p) + instance_p->config = *input_config_p; + + ret = FSdioReset(instance_p); /* reset the device */ + + if (FSDIO_SUCCESS == ret) + { + instance_p->is_ready = FT_COMPONENT_IS_READY; + FSDIO_INFO("device initialize success !!!"); + } + + return ret; +} + +/** + * @name: FSdioDeInitialize + * @msg: deinitialization SDIO controller instance + * @return {NONE} + * @param {FSdio} *instance_p, SDIO controller instance + */ +void FSdioDeInitialize(FSdio *const instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + + FSdioSetInterruptMask(instance_p, FSDIO_GENERAL_INTR, FSDIO_INT_ALL_BITS, FALSE); /* 关闭控制器中断位 */ + FSdioSetInterruptMask(instance_p, FSDIO_IDMA_INTR, FSDIO_DMAC_INT_ENA_ALL, FALSE); /* 关闭DMA中断位 */ + + FSdioClearRawStatus(base_addr); /* 清除中断状态 */ + FSdioClearDMAStatus(base_addr); + + FSdioSetPower(base_addr, FALSE); /* 关闭电源 */ + FSdioSetClock(base_addr, FALSE); /* 关闭卡时钟 */ + FSDIO_CLR_BIT(base_addr, FSDIO_UHS_REG_EXT_OFFSET, FSDIO_UHS_EXT_CLK_ENA); /* 关闭外部时钟 */ + FSDIO_CLR_BIT(base_addr, FSDIO_UHS_REG_OFFSET, FSDIO_UHS_REG_VOLT_180); /* 恢复为3.3v默认电压 */ + + instance_p->is_ready = 0; +} + +/** + * @name: FSdioSetClkFreq + * @msg: Set the Card clock freqency + * @return {None} + * @param {FSdio} *instance_p, SDIO controller instance + * @param {u32} input_clk_hz, Card clock freqency in Hz + */ +FError FSdioSetClkFreq(FSdio *const instance_p, u32 input_clk_hz) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + u32 div = 0xff, drv = 0, sample = 0; + u32 first_uhs_div, tmp_ext_reg, div_reg; + FError ret = FSDIO_SUCCESS; + + FSDIO_INFO("set clk as %ld", input_clk_hz); + + /* must set 2nd stage clcok first then set 1st stage clock */ + /* experimental uhs setting --> 2nd stage clock, below setting parameters get from + experiment, for better sample timing */ + if (input_clk_hz >= FSDIO_SD_25_MHZ) /* e.g. 25MHz or 50MHz */ + { + tmp_ext_reg = FSDIO_UHS_REG(0U, 0U, 0x2U) | FSDIO_UHS_EXT_CLK_ENA; + FASSERT(tmp_ext_reg == 0x202); + } + else if (input_clk_hz == FSDIO_SD_400KHZ) /* 400kHz */ + { + tmp_ext_reg = FSDIO_UHS_REG(0U, 0U, 0x5U) | FSDIO_UHS_EXT_CLK_ENA; + FASSERT(tmp_ext_reg == 0x502); + } + else /* e.g. 20MHz */ + { + tmp_ext_reg = FSDIO_UHS_REG(0U, 0U, 0x3U) | FSDIO_UHS_EXT_CLK_ENA; + FASSERT(tmp_ext_reg == 0x302); + } + + /* update uhs setting */ + ret = FSdioUpdateExternalClk(base_addr, tmp_ext_reg); + if (FSDIO_SUCCESS != ret) + return ret; + + FSdioSetClock(base_addr, FALSE); /* disable clock */ + + /* send private cmd to update clock */ + ret = FSdioSendPrivateCmd(base_addr, FSDIO_CMD_UPD_CLK, 0U); + if (FSDIO_SUCCESS != ret) + return ret; + + /* experimental clk divide setting -- 1st stage clock */ + first_uhs_div = 1 + FSDIO_UHS_CLK_DIV_GET(tmp_ext_reg); + div = FSDIO_CLK_RATE_HZ / (2 * first_uhs_div * input_clk_hz); + if (div > 2) + { + sample = div / 2 + 1; + drv = sample - 1; + } + else if (div == 2) + { + drv = 0; + sample = 1; + } + + div_reg = FSDIO_CLK_DIV(sample, drv, div); + FSDIO_WRITE_REG(base_addr, FSDIO_CLKDIV_OFFSET, div_reg); + + FSDIO_INFO("UHS_REG_EXT: %x, CLKDIV: %x", + FSDIO_READ_REG(base_addr, FSDIO_UHS_REG_EXT_OFFSET), + FSDIO_READ_REG(base_addr, FSDIO_CLKDIV_OFFSET)); + + FSDIO_INFO("UHS_REG_EXT ext: 0x%x, CLKDIV: 0x%x", + FSDIO_READ_REG(base_addr, FSDIO_UHS_REG_EXT_OFFSET), + FSDIO_READ_REG(base_addr, FSDIO_CLKDIV_OFFSET)); + + FSdioSetClock(base_addr, TRUE); /* enable clock */ + + /* update clock for 1 stage clock */ + ret = FSdioSendPrivateCmd(base_addr, FSDIO_CMD_UPD_CLK, 0U); + if (FSDIO_SUCCESS != ret) + return ret; + + return ret; +} + +/** + * @name: FSdioWaitClkReady + * @msg: Wait clock ready after modify clock setting + * @return {FError} FSDIO_SUCCESS if wait success, FSDIO_ERR_TIMEOUT if wait timeout + * @param {uintptr} base_addr, base address of SDIO controller + * @param {int} retries, retry times in waiting + */ +static FError FSdioWaitClkReady(uintptr base_addr, int retries) +{ + FASSERT(retries > 1); + u32 reg_val = 0; + + do + { + reg_val = FSDIO_READ_REG(base_addr, FSDIO_GPIO_OFFSET); + } + while (!(reg_val & FSDIO_CLK_READY) && (retries-- > 0)); + + if (!(reg_val & FSDIO_CLK_READY) && (retries <= 0)) + { + FSDIO_ERROR("wait clk ready timeout !!! status: 0x%x", + reg_val); + return FSDIO_ERR_TIMEOUT; + } + + return FSDIO_SUCCESS; +} + +/** + * @name: FSdioUpdateExternalClk + * @msg: update uhs clock value and wait clock ready + * @return {FError} + * @param {uintptr} base_addr + * @param {u32} uhs_reg_val + */ +static FError FSdioUpdateExternalClk(uintptr base_addr, u32 uhs_reg_val) +{ + u32 reg_val; + int retries = FSDIO_TIMEOUT; + FSDIO_WRITE_REG(base_addr, FSDIO_UHS_REG_EXT_OFFSET, 0U); + FSDIO_WRITE_REG(base_addr, FSDIO_UHS_REG_EXT_OFFSET, uhs_reg_val); + + do + { + reg_val = FSDIO_READ_REG(base_addr, FSDIO_GPIO_OFFSET); + if (--retries <= 0) + break; + } + while (!(reg_val & FSDIO_CLK_READY)); + + return (retries <= 0) ? FSDIO_ERR_TIMEOUT : FSDIO_SUCCESS; +} + +/** + * @name: FSdioResetCtrl + * @msg: Reset fifo/DMA in cntrl register + * @return {FError} FSDIO_SUCCESS if reset success + * @param {uintptr} base_addr, base address of SDIO controller + * @param {u32} reset_bits, bits to be reset + */ +FError FSdioResetCtrl(uintptr base_addr, u32 reset_bits) +{ + u32 reg_val; + int retries = FSDIO_TIMEOUT; + FSDIO_SET_BIT(base_addr, FSDIO_CNTRL_OFFSET, reset_bits); + + do + { + reg_val = FSDIO_READ_REG(base_addr, FSDIO_CNTRL_OFFSET); + if (--retries <= 0) + break; + } + while (reset_bits & reg_val); + + if (retries <= 0) + return FSDIO_ERR_TIMEOUT; + + return FSDIO_SUCCESS; +} + +/** + * @name: FSdioResetBusyCard + * @msg: reset controller from card busy state + * @return {FError} FSDIO_SUCCESS if reset success + * @param {uintptr} base_addr, base address of controller + */ +FError FSdioResetBusyCard(uintptr base_addr) +{ + u32 reg_val; + int retries = FSDIO_TIMEOUT; + FSDIO_SET_BIT(base_addr, FSDIO_CNTRL_OFFSET, FSDIO_CNTRL_CONTROLLER_RESET); + + do + { + FSDIO_SET_BIT(base_addr, FSDIO_CNTRL_OFFSET, FSDIO_CNTRL_CONTROLLER_RESET); + reg_val = FSDIO_READ_REG(base_addr, FSDIO_STATUS_OFFSET); + if (--retries <= 0) + break; + } + while (reg_val & FSDIO_STATUS_DATA_BUSY); + + return (retries <= 0) ? FSDIO_ERR_BUSY : FSDIO_SUCCESS; +} + +/** + * @name: FSdioRestartClk + * @msg: restart controller clock from error status + * @return {FError} FSDIO_SUCCESS if reset success + * @param {uintptr} base_addr, base address of controller + */ +FError FSdioRestartClk(uintptr base_addr) +{ + u32 clk_div, uhs; + int retries = FSDIO_TIMEOUT; + u32 reg_val; + FError ret = FSDIO_SUCCESS; + + /* wait command finish if previous command is in error state */ + do + { + reg_val = FSDIO_READ_REG(base_addr, FSDIO_CMD_OFFSET); + if (--retries <= 0) + break; + } + while (reg_val & FSDIO_CMD_START); + + if (retries <= 0) + return FSDIO_ERR_TIMEOUT; + + /* update clock */ + FSdioSetClock(base_addr, FALSE); + + clk_div = FSDIO_READ_REG(base_addr, FSDIO_CLKDIV_OFFSET); + uhs = FSDIO_READ_REG(base_addr, FSDIO_UHS_REG_EXT_OFFSET); + + ret = FSdioUpdateExternalClk(base_addr, uhs); + if (FSDIO_SUCCESS != ret) + return ret; + + FSDIO_WRITE_REG(base_addr, FSDIO_CLKDIV_OFFSET, clk_div); + + FSdioSetClock(base_addr, TRUE); + + ret = FSdioSendPrivateCmd(base_addr, FSDIO_CMD_UPD_CLK, 0U); + + return ret; +} + +/** + * @name: FSdioReset + * @msg: Reset SDIO controller instance + * @return {FError} FSDIO_SUCCESS if reset success + * @param {FSdio} *instance_p, SDIO controller instance + */ +static FError FSdioReset(FSdio *const instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + FError ret = FSDIO_SUCCESS; + + /* set creg_nand_mmcsd DMA path */ + FSDIO_INFO("Prev LSD CFG: 0x%x", FtIn32(FLSD_CONFIG_BASE + FLSD_NAND_MMCSD_HADDR)); + FtOut32(FLSD_CONFIG_BASE + FLSD_NAND_MMCSD_HADDR, 0x0U); + FSDIO_INFO("Curr LSD CFG: 0x%x", FtIn32(FLSD_CONFIG_BASE + FLSD_NAND_MMCSD_HADDR)); + + /* set fifo */ + reg_val = FSDIO_FIFOTH(FSDIO_FIFOTH_DMA_TRANS_8, FSDIO_RX_WMARK, FSDIO_TX_WMARK); + FSDIO_WRITE_REG(base_addr, FSDIO_FIFOTH_OFFSET, reg_val); + + /* set card threshold */ + reg_val = FSDIO_CARD_THRCTL_THRESHOLD(FSDIO_FIFO_DEPTH_8) | FSDIO_CARD_THRCTL_CARDRD; + FSDIO_WRITE_REG(base_addr, FSDIO_CARD_THRCTL_OFFSET, reg_val); + + /* disable clock and update ext clk */ + FSdioSetClock(base_addr, FALSE); + + /* set 1st clock */ + reg_val = FSDIO_UHS_REG(0U, 0U, 0x5U) | FSDIO_UHS_EXT_CLK_ENA; + FASSERT_MSG(0x502 == reg_val, "invalid uhs config"); + ret = FSdioUpdateExternalClk(base_addr, reg_val); + if (FSDIO_SUCCESS != ret) + { + FSDIO_ERROR("update extern clock failed !!!"); + return ret; + } + + /* power on */ + FSdioSetPower(base_addr, TRUE); + FSdioSetClock(base_addr, TRUE); + FSdioSetExtClock(base_addr, TRUE); + + /* set voltage as 3.3v */ + if (FSDIO_SD_1_8V_VOLTAGE == instance_p->config.voltage) + FSdioSetVoltage1_8V(base_addr, TRUE); + else + FSdioSetVoltage1_8V(base_addr, FALSE); + + /* reset controller and card */ + ret = FSdioResetCtrl(base_addr, FSDIO_CNTRL_FIFO_RESET | FSDIO_CNTRL_DMA_RESET); + if (FSDIO_SUCCESS != ret) + { + FSDIO_ERROR("reset controller failed !!!"); + return ret; + } + + /* send private command to update clock */ + ret = FSdioSendPrivateCmd(base_addr, FSDIO_CMD_UPD_CLK, 0U); + if (FSDIO_SUCCESS != ret) + { + FSDIO_ERROR("update clock failed !!!"); + return ret; + } + + /* reset card for no-removeable media, e.g. eMMC */ + if (TRUE == instance_p->config.non_removable) + FSDIO_SET_BIT(base_addr, FSDIO_CARD_RESET_OFFSET, FSDIO_CARD_RESET_ENABLE); + else + FSDIO_CLR_BIT(base_addr, FSDIO_CARD_RESET_OFFSET, FSDIO_CARD_RESET_ENABLE); + + /* clear interrupt status */ + FSDIO_WRITE_REG(base_addr, FSDIO_INT_MASK_OFFSET, 0U); + reg_val = FSDIO_READ_REG(base_addr, FSDIO_RAW_INTS_OFFSET); + FSDIO_WRITE_REG(base_addr, FSDIO_RAW_INTS_OFFSET, reg_val); + + FSDIO_WRITE_REG(base_addr, FSDIO_DMAC_INT_EN_OFFSET, 0U); + reg_val = FSDIO_READ_REG(base_addr, FSDIO_DMAC_STATUS_OFFSET); + FSDIO_WRITE_REG(base_addr, FSDIO_DMAC_STATUS_OFFSET, reg_val); + + /* enable card detect interrupt */ + if (FALSE == instance_p->config.non_removable) + FSDIO_SET_BIT(base_addr, FSDIO_INT_MASK_OFFSET, FSDIO_INT_CD_BIT); + + /* enable controller and internal DMA */ + FSDIO_SET_BIT(base_addr, FSDIO_CNTRL_OFFSET, FSDIO_CNTRL_INT_ENABLE | FSDIO_CNTRL_USE_INTERNAL_DMAC); + + /* set data and resp timeout */ + FSDIO_WRITE_REG(base_addr, FSDIO_TMOUT_OFFSET, + FSDIO_TIMEOUT_DATA(FSDIO_MAX_DATA_TIMEOUT, FSDIO_MAX_RESP_TIMEOUT)); + + /* reset descriptors and dma */ + FSdioSetDescriptor(base_addr, (uintptr)NULL); /* set decriptor list as NULL */ + FSdioResetIDMA(base_addr); + + FSDIO_INFO("init hardware done !!!"); + return ret; +} + +/** + * @name: FSdioRestart + * @msg: reset controller from error state + * @return {FError} FSDIO_SUCCESS if restart success + * @param {FSdio} *instance_p, instance of controller + */ +FError FSdioRestart(FSdio *const instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 reg_val; + FError ret = FSDIO_SUCCESS; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return FSDIO_ERR_NOT_INIT; + } + + /* reset controller */ + ret = FSdioResetCtrl(base_addr, FSDIO_CNTRL_FIFO_RESET); + if (FSDIO_SUCCESS != ret) + return ret; + + /* reset controller if in busy state */ + ret = FSdioResetBusyCard(base_addr); + if (FSDIO_SUCCESS != ret) + return ret; + + /* reset clock */ + ret = FSdioRestartClk(base_addr); + if (FSDIO_SUCCESS != ret) + return ret; + + /* reset internal DMA */ + FSdioResetIDMA(base_addr); + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio.h b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio.h new file mode 100644 index 0000000000..6d1f0ba4b9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio.h @@ -0,0 +1,227 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio.h + * Date: 2022-05-26 16:20:52 + * LastEditTime: 2022-05-26 16:20:53 + * Description:  This files is for sdio user interface definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + * 1.2 zhugengyu 2022/7/15 adopt to e2000 + */ + +#ifndef DRIVERS_FSDIO_H +#define DRIVERS_FSDIO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "ferror_code.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ + +/* SDIO driver error code */ +#define FSDIO_SUCCESS FT_SUCCESS +#define FSDIO_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 1) +#define FSDIO_ERR_NOT_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 2) +#define FSDIO_ERR_SHORT_BUF FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 3) +#define FSDIO_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 4) +#define FSDIO_ERR_INVALID_STATE FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 5) +#define FSDIO_ERR_TRANS_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 6) +#define FSDIO_ERR_CMD_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 7) +#define FSDIO_ERR_NO_CARD FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 8) +#define FSDIO_ERR_BUSY FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 9) + +typedef enum +{ + FSDIO_IDMA_TRANS_MODE, /* DMA trans mode */ + FSDIO_PIO_TRANS_MODE, /* NO-DMA trans by read/write Fifo */ +} FSdioTransMode; /* SDIO trans mode */ + +typedef enum +{ + FSDIO_GENERAL_INTR, /* interrupt status belongs to controller */ + FSDIO_IDMA_INTR, /* interrupt status belongs to DMA */ +} FSdioIntrType; /* SDIO interrupt status type */ + +typedef enum +{ + FSDIO_SD_3_3V_VOLTAGE = 0, /* 3.3v */ + FSDIO_SD_1_8V_VOLTAGE /* 1.8v */ +} FSdioVoltageType; /* SDIO card voltage type */ + +typedef enum +{ + FSDIO_EVT_CARD_DETECTED = 0, /* card detected event */ + FSDIO_EVT_CMD_DONE, /* cmd transfer finish event */ + FSDIO_EVT_DATA_DONE, /* cmd with data transfer finish event */ + FSDIO_EVT_ERR_OCCURE, /* error occurred in transfer */ + + FSDIO_NUM_OF_EVT +} FSdioEvtType; /* SDIO event type */ + +#define FSDIO_DEFAULT_BLOCK_SZ 512U +#define FSDIO_SD_400KHZ 400000U +#define FSDIO_SD_25_MHZ 25000000U +#define FSDIO_SD_50_MHZ 50000000U +/**************************** Type Definitions *******************************/ +typedef struct _FSdio FSdio; + +typedef void (*FSdioRelaxHandler)(void); +typedef void (*FSdioEvtHandler)(FSdio *const instance_p, void *args); + +typedef struct +{ + u32 attribute; /* ds0 */ +#define FSDIO_IDMAC_DES0_DIC BIT(1)/* 内部描述表不触发TI/RI中断 */ +#define FSDIO_IDMAC_DES0_LD BIT(2)/* 数据的最后一个描述符 */ +#define FSDIO_IDMAC_DES0_FD BIT(3)/* 数据的第一个描述符 */ +#define FSDIO_IDMAC_DES0_CH BIT(4)/* 链接下一个描述符地址 */ +#define FSDIO_IDMAC_DES0_ER BIT(5)/* 链表已经到达最后一个链表 */ +#define FSDIO_IDMAC_DES0_CES BIT(30)/* RINTSTS寄存器错误汇总 */ +#define FSDIO_IDMAC_DES0_OWN BIT(31)/* 描述符关联DMA,完成传输后该位置置0 */ + u32 non1; /* ds1 --> unused */ + u32 len; /* ds2 bit[25:13] buffer2 size,bit[12:0] buffer1 size*/ +#define FSDIO_IDMAC_DES2_BUF1_MASK GENMASK(12, 0) +#define FSDIO_IDMAC_DES2_BUF1_SIZE(x) (FSDIO_IDMAC_DES2_BUF1_MASK & (x)) +#define FSDIO_IDMAC_DES2_BUF2_MASK GENMASK(25, 13) +#define FSDIO_IDMAC_DES2_BUF2_SIZE(x) (FSDIO_IDMAC_DES2_BUF2_MASK & (x << 13)) + u32 non2; /* ds3 --> unused */ + u32 addr_lo; /* ds4 Lower 32-bits of Buffer Address Pointer 1 --> buffer 1 */ + u32 addr_hi; /* ds5 Upper 32-bits of Buffer Address Pointer 1 */ + u32 desc_lo; /* ds6 Lower 32-bits of Next Descriptor Address --> buffer 2 */ + u32 desc_hi; /* ds7 Upper 32-bits of Next Descriptor Address */ +} __attribute__((packed)) __attribute((aligned(4))) FSdioIDmaDesc; /* SDIO DMA descriptr */ + +typedef struct +{ + volatile FSdioIDmaDesc *first_desc; /* first descriptor in the list */ + u32 desc_num; /* num of descriptors in the list */ +} FSdioIDmaDescList; /* SDIO DMA descriptors list */ + +typedef struct +{ + u8 *buf; /* trans buffer */ + u32 blksz; /* card block size */ + u32 blkcnt; /* num of block in trans */ + u32 datalen; /* bytes in trans */ +} FSdioData; /* SDIO trans data */ + +typedef struct +{ + u32 cmdidx; /* command index */ + u32 cmdarg; /* command argument */ + u32 response[4]; /* command response buffer */ + u32 flag; /* command flags */ +#define FSDIO_CMD_FLAG_NEED_INIT BIT(1) /* need initialization */ +#define FSDIO_CMD_FLAG_EXP_RESP BIT(2) /* need reply */ +#define FSDIO_CMD_FLAG_EXP_LONG_RESP BIT(3) /* need 136 bits long reply */ +#define FSDIO_CMD_FLAG_NEED_RESP_CRC BIT(4) /* need CRC */ +#define FSDIO_CMD_FLAG_EXP_DATA BIT(5) /* need trans data */ +#define FSDIO_CMD_FLAG_WRITE_DATA BIT(6) /* need trans data to write card */ +#define FSDIO_CMD_FLAG_READ_DATA BIT(7) /* need trans data to read card */ +#define FSDIO_CMD_FLAG_NEED_AUTO_STOP BIT(8) /* need auto stop after command */ +#define FSDIO_CMD_FLAG_ADTC BIT(9) /* need ADTC */ +#define FSDIO_CMD_FLAG_SWITCH_VOLTAGE BIT(10) /* need switch voltage */ + FSdioData *data_p; /* SDIO trans data */ + volatile boolean success; /* TRUE: comand and data transfer success */ +} FSdioCmdData; /* SDIO trans command and data */ + +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num; /* Interrupt num */ + FSdioTransMode trans_mode; /* Trans mode, PIO/DMA */ + FSdioVoltageType voltage; /* Card voltage type */ + boolean non_removable; /* No removeable media, e.g eMMC */ +} FSdioConfig; /* SDIO intance configuration */ + +typedef struct _FSdio +{ + FSdioConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + FSdioIDmaDescList desc_list; /* DMA descriptor list, valid in DMA trans mode */ + FSdioEvtHandler evt_handlers[FSDIO_NUM_OF_EVT]; /* call-backs for interrupt event */ + void *evt_args[FSDIO_NUM_OF_EVT]; /* arguments for event call-backs */ +} FSdio; /* SDIO intance */ +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/* Get the device instance default configure */ +const FSdioConfig *FSdioLookupConfig(u32 instance_id); + +/* initialization SDIO controller instance */ +FError FSdioCfgInitialize(FSdio *const instance_p, const FSdioConfig *cofig_p); + +/* deinitialization SDIO controller instance */ +void FSdioDeInitialize(FSdio *const instance_p); + +/* Setup DMA descriptor for SDIO controller instance */ +FError FSdioSetIDMAList(FSdio *const instance_p, volatile FSdioIDmaDesc *desc, u32 desc_num); + +/* Set the Card clock freqency */ +FError FSdioSetClkFreq(FSdio *const instance_p, u32 input_clk_hz); + +/* Start command and data transfer in DMA mode */ +FError FSdioDMATransfer(FSdio *const instance_p, FSdioCmdData *const cmd_data_p); + +/* Wait DMA transfer finished by poll */ +FError FSdioPollWaitDMAEnd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p, FSdioRelaxHandler relax); + +/* Start command and data transfer in PIO mode */ +FError FSdioPIOTransfer(FSdio *const instance_p, FSdioCmdData *const cmd_data_p); + +/* Wait PIO transfer finished by poll */ +FError FSdioPollWaitPIOEnd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p, FSdioRelaxHandler relax); + +/* Get cmd response and received data after wait poll status or interrupt signal */ +FError FSdioGetCmdResponse(FSdio *const instance_p, FSdioCmdData *const cmd_data_p); + +/* Get SDIO controller interrupt mask */ +u32 FSdioGetInterruptMask(FSdio *const instance_p, FSdioIntrType intr_type); + +/* Enable/Disable SDIO controller interrupt */ +void FSdioSetInterruptMask(FSdio *const instance_p, FSdioIntrType type, u32 set_mask, boolean enable); + +/* Interrupt handler for SDIO instance */ +void FSdioInterruptHandler(s32 vector, void *param); + +/* Reset controller from error state */ +FError FSdioRestart(FSdio *const instance_p); + +/* Register event call-back function as handler for interrupt events */ +void FSdioRegisterEvtHandler(FSdio *const instance_p, FSdioEvtType evt, FSdioEvtHandler handler, void *handler_arg); + +/* Dump all register value of SDIO instance */ +void FSdioDumpRegister(uintptr base_addr); + +#ifdef __cplusplus +} +#endif + + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_cmd.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_cmd.c new file mode 100644 index 0000000000..0bcd30d960 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_cmd.c @@ -0,0 +1,210 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_cmd.c + * Date: 2022-06-01 14:23:59 + * LastEditTime: 2022-06-01 14:24:00 + * Description:  This files is for SDIO command related function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "fdebug.h" +#include "fassert.h" +#include "ftypes.h" + +#include "fcache.h" + +#include "fsdio_hw.h" +#include "fsdio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDIO_DEBUG_TAG "FSDIO-CMD" +#define FSDIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_WARN(format, ...) FT_DEBUG_PRINT_W(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_INFO(format, ...) FT_DEBUG_PRINT_I(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +extern FError FSdioPIOReadData(FSdio *const instance_p, FSdioData *data_p); + +/*****************************************************************************/ +FError FSdioSendPrivateCmd(uintptr base_addr, u32 cmd, u32 arg) +{ + u32 reg_val; + int retries = FSDIO_TIMEOUT; + + do + { + reg_val = FSDIO_READ_REG(base_addr, FSDIO_STATUS_OFFSET); + if (--retries <= 0) + break; + } + while (FSDIO_STATUS_DATA_BUSY & reg_val); + + if (retries <= 0) + return FSDIO_ERR_BUSY; + + FSDIO_WRITE_REG(base_addr, FSDIO_CMD_ARG_OFFSET, arg); + FSDIO_WRITE_REG(base_addr, FSDIO_CMD_OFFSET, FSDIO_CMD_START | cmd); + + retries = FSDIO_TIMEOUT; + do + { + reg_val = FSDIO_READ_REG(base_addr, FSDIO_CMD_OFFSET); + if (--retries <= 0) + break; + } + while (FSDIO_CMD_START & reg_val); + + return (retries <= 0) ? FSDIO_ERR_TIMEOUT : FSDIO_SUCCESS; +} + +/** + * @name: FSdioTransferCmd + * @msg: pack and transfer command + * @return {FError} FSDIO_SUCCESS if transfer success + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioCmdData} *cmd_data_p, contents of transfer command and data + */ +FError FSdioTransferCmd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p) +{ + FASSERT(cmd_data_p); + FError ret = FSDIO_SUCCESS; + uintptr base_addr = instance_p->config.base_addr; + u32 cmd_flag = cmd_data_p->flag; + u32 raw_cmd = FSDIO_CMD_USE_HOLD_REG; /* USE_HOLD_REG必须为1 */ + + /* 命令需要进行卡初始化,如CMD-0 */ + if (FSDIO_CMD_FLAG_NEED_INIT & cmd_flag) + { + raw_cmd |= FSDIO_CMD_INIT; + } + + /* 命令涉及电压切换 */ + if (FSDIO_CMD_FLAG_SWITCH_VOLTAGE & cmd_flag) + { + raw_cmd |= FSDIO_CMD_VOLT_SWITCH; + } + + /* 命令传输过程伴随数据传输 */ + if (FSDIO_CMD_FLAG_EXP_DATA & cmd_flag) + { + raw_cmd |= FSDIO_CMD_DAT_EXP; + + if (FSDIO_CMD_FLAG_WRITE_DATA & cmd_flag) /* 写卡 */ + { + raw_cmd |= FSDIO_CMD_DAT_WRITE; + } + } + + /* 命令需要进行CRC校验 */ + if (FSDIO_CMD_FLAG_NEED_RESP_CRC & cmd_flag) + { + raw_cmd |= FSDIO_CMD_RESP_CRC; + } + + /* 命令需要响应回复 */ + if (FSDIO_CMD_FLAG_EXP_RESP & cmd_flag) + { + raw_cmd |= FSDIO_CMD_RESP_EXP; + + if (FSDIO_CMD_FLAG_EXP_LONG_RESP & cmd_flag) /* 命令需要136字节长回复 */ + { + raw_cmd |= FSDIO_CMD_RESP_LONG; + } + } + + raw_cmd |= FSDIO_CMD_INDX_SET(cmd_data_p->cmdidx); + + FSDIO_DEBUG("============[CMD-%d]@0x%x begin ============", cmd_data_p->cmdidx, base_addr); + FSDIO_DEBUG(" cmd: 0x%x", raw_cmd); + FSDIO_DEBUG(" arg: 0x%x", cmd_data_p->cmdarg); + + /* enable related interrupt */ + FSdioSetInterruptMask(instance_p, FSDIO_GENERAL_INTR, + FSDIO_INTS_CMD_MASK, TRUE); + + FSdioSendPrivateCmd(base_addr, raw_cmd, cmd_data_p->cmdarg); + FSDIO_INFO("cmd send done ..."); + return ret; +} + +/** + * @name: FSdioGetCmdResponse + * @msg: Get cmd response and received data after wait poll status or interrupt signal + * @return {FError} FSDIO_SUCCESS if get success + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioCmdData} *cmd_data_p, contents of transfer command and data + */ +FError FSdioGetCmdResponse(FSdio *const instance_p, FSdioCmdData *const cmd_data_p) +{ + FASSERT(instance_p); + FASSERT(cmd_data_p); + FError ret = FSDIO_SUCCESS; + u32 reg_val; + const boolean read = cmd_data_p->flag & FSDIO_CMD_FLAG_READ_DATA; + uintptr base_addr = instance_p->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return FSDIO_ERR_NOT_INIT; + } + + if ((NULL != cmd_data_p->data_p) && (read)) + { + if (FSDIO_PIO_TRANS_MODE == instance_p->config.trans_mode) + { + ret = FSdioPIOReadData(instance_p, cmd_data_p->data_p); + } + } + + /* check response of cmd */ + if (FSDIO_CMD_FLAG_EXP_RESP & cmd_data_p->flag) + { + if (FSDIO_CMD_FLAG_EXP_LONG_RESP & cmd_data_p->flag) + { + cmd_data_p->response[0] = FSDIO_READ_REG(base_addr, FSDIO_RESP0_OFFSET); + cmd_data_p->response[1] = FSDIO_READ_REG(base_addr, FSDIO_RESP1_OFFSET); + cmd_data_p->response[2] = FSDIO_READ_REG(base_addr, FSDIO_RESP2_OFFSET); + cmd_data_p->response[3] = FSDIO_READ_REG(base_addr, FSDIO_RESP3_OFFSET); + FSDIO_DEBUG(" resp: 0x%x-0x%x-0x%x-0x%x", + cmd_data_p->response[0], cmd_data_p->response[1], + cmd_data_p->response[2], cmd_data_p->response[3]); + } + else + { + cmd_data_p->response[0] = FSDIO_READ_REG(base_addr, FSDIO_RESP0_OFFSET); + FSDIO_DEBUG(" resp: 0x%x", cmd_data_p->response[0]); + } + } + + cmd_data_p->success = TRUE; /* cmd / data transfer finished successful */ + FSDIO_DEBUG("============[CMD-%d]@0x%x end ============", cmd_data_p->cmdidx, base_addr); + + /* disable related interrupt */ + FSdioSetInterruptMask(instance_p, FSDIO_GENERAL_INTR, FSDIO_INTS_CMD_MASK | FSDIO_INTS_DATA_MASK, FALSE); + FSdioSetInterruptMask(instance_p, FSDIO_IDMA_INTR, FSDIO_DMAC_INTS_MASK, FALSE); + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_dma.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_dma.c new file mode 100644 index 0000000000..9fc1507d39 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_dma.c @@ -0,0 +1,365 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_dma.c + * Date: 2022-06-01 14:21:41 + * LastEditTime: 2022-06-01 14:21:42 + * Description:  This files is for DMA related function implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ +/***************************** Include Files *********************************/ +#include + +#include "fio.h" +#include "fdebug.h" +#include "fassert.h" +#include "ftypes.h" + +#include "fcache.h" + +#include "fsdio_hw.h" +#include "fsdio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDIO_DEBUG_TAG "FSDIO-DMA" +#define FSDIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_WARN(format, ...) FT_DEBUG_PRINT_W(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_INFO(format, ...) FT_DEBUG_PRINT_I(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +extern FError FSdioTransferCmd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p); + +/*****************************************************************************/ +/** + * @name: FSdioDumpDMADescriptor + * @msg: dump DMA descriptor list + * @return {*} + * @param {FSdio} *instance_p, instance of controller + * @param {u32} desc_in_use, max index of descriptor in use + */ +static void FSdioDumpDMADescriptor(FSdio *const instance_p, u32 desc_in_use) +{ + u32 loop; + volatile FSdioIDmaDesc *cur_desc = NULL; + + if (instance_p->desc_list.first_desc) + { + for (loop = 0; loop < desc_in_use; loop++) + { + cur_desc = &(instance_p->desc_list.first_desc[loop]); + FSDIO_DEBUG("descriptor@%p", cur_desc); + FSDIO_DEBUG("\tattribute: 0x%x", cur_desc->attribute); + FSDIO_DEBUG("\tnon1: 0x%x", cur_desc->non1); + FSDIO_DEBUG("\tlen: 0x%x", cur_desc->len); + FSDIO_DEBUG("\tnon2: 0x%x", cur_desc->non2); + FSDIO_DEBUG("\taddr_lo: 0x%x", cur_desc->addr_lo); + FSDIO_DEBUG("\taddr_hi: 0x%x", cur_desc->addr_hi); + FSDIO_DEBUG("\tdesc_lo: 0x%x", cur_desc->desc_lo); + FSDIO_DEBUG("\tdesc_hi: 0x%x", cur_desc->desc_hi); + } + } +} + +/** + * @name: FSdioSetupDMADescriptor + * @msg: setup DMA descriptor list before do transcation + * @return {FError} FSDIO_SUCCESS if setup success + * @param {FSdio} *instance_p, instance of controller + * @param {FSdioData} *data_p, data in transcation + */ +static FError FSdioSetupDMADescriptor(FSdio *const instance_p, FSdioData *data_p) +{ + FASSERT(data_p); + FASSERT(instance_p->desc_list.first_desc); + u32 loop; + u32 buf_num = data_p->datalen / data_p->blksz + + ((data_p->datalen % data_p->blksz) ? 1U : 0U); + volatile FSdioIDmaDesc *cur_desc = NULL; + uintptr buff_addr = 0U; + uintptr desc_addr = 0U; + boolean is_first = TRUE; + boolean is_last = FALSE; + + if (buf_num > instance_p->desc_list.desc_num) + { + FSDIO_ERROR("descriptor is short for transfer %d < %d", + instance_p->desc_list.desc_num, buf_num); + return FSDIO_ERR_SHORT_BUF; + } + + memset((void *)instance_p->desc_list.first_desc, 0, + sizeof(FSdioIDmaDesc) * instance_p->desc_list.desc_num); + + FSDIO_INFO("%d of descriptor in use", buf_num); + for (loop = 0U; loop < buf_num; loop++) + { + cur_desc = &(instance_p->desc_list.first_desc[loop]); + is_first = (0U == loop) ? TRUE : FALSE; + is_last = ((buf_num - 1U) == loop) ? TRUE : FALSE; + + /* set properity of descriptor entry */ + cur_desc->attribute = FSDIO_IDMAC_DES0_CH | FSDIO_IDMAC_DES0_OWN; /* descriptor list in chain, and set OWN bit */ + cur_desc->attribute |= (is_first) ? FSDIO_IDMAC_DES0_FD : 0; /* is it the first entry ? */ + cur_desc->attribute |= (is_last) ? (FSDIO_IDMAC_DES0_LD | FSDIO_IDMAC_DES0_ER) : 0; /* is it the last entry ? */ + + /* set data length in transfer */ + cur_desc->non1 = 0U; + cur_desc->len = FSDIO_IDMAC_DES2_BUF1_SIZE(data_p->blksz) | FSDIO_IDMAC_DES2_BUF2_SIZE(0U); + + /* set data buffer for transfer */ + buff_addr = (uintptr)data_p->buf + (uintptr)(loop * data_p->blksz); +#ifdef __aarch64__ + cur_desc->addr_hi = UPPER_32_BITS(buff_addr); + cur_desc->addr_lo = LOWER_32_BITS(buff_addr); +#else + cur_desc->addr_hi = 0U; + cur_desc->addr_lo = (u32)(buff_addr); +#endif + + /* set address of next descriptor entry, NULL for last entry */ + desc_addr = is_last ? 0U : (uintptr)&instance_p->desc_list.first_desc[loop + 1]; +#ifdef __aarch64__ + cur_desc->desc_hi = UPPER_32_BITS(desc_addr); + cur_desc->desc_lo = LOWER_32_BITS(desc_addr); +#else + cur_desc->desc_hi = 0U; + cur_desc->desc_lo = (u32)(desc_addr); +#endif + } + + /* flush cache of descripor list and transfer buffer */ + FCacheDCacheFlushRange((uintptr)instance_p->desc_list.first_desc, sizeof(FSdioIDmaDesc) * instance_p->desc_list.desc_num); + FCacheDCacheFlushRange((uintptr)data_p->buf, data_p->datalen); + + FSdioDumpDMADescriptor(instance_p, buf_num); + return FSDIO_SUCCESS; +} + +/** + * @name: FSdioDMATransferData + * @msg: + * @return {*} + * @param {FSdio} *instance_p + * @param {FSdioData} *data_p + */ +static FError FSdioDMATransferData(FSdio *const instance_p, FSdioData *data_p) +{ + FASSERT(data_p); + FError ret = FSDIO_SUCCESS; + uintptr base_addr = instance_p->config.base_addr; + + /* enable related interrupt */ + FSdioSetInterruptMask(instance_p, FSDIO_GENERAL_INTR, FSDIO_INTS_DATA_MASK, TRUE); + FSdioSetInterruptMask(instance_p, FSDIO_IDMA_INTR, FSDIO_DMAC_INTS_MASK, TRUE); + + /* fill transfer buffer to DMA descriptor */ + ret = FSdioSetupDMADescriptor(instance_p, data_p); + if (FSDIO_SUCCESS != ret) + return ret; + + FSDIO_INFO("descriptor@%p, trans bytes: %d, block size: %d", + instance_p->desc_list.first_desc, + data_p->datalen, + data_p->blksz); + + /* set transfer info to register */ + FSdioSetDescriptor(base_addr, (uintptr)(instance_p->desc_list.first_desc)); + FSdioSetTransBytes(base_addr, data_p->datalen); + FSdioSetBlockSize(base_addr, data_p->blksz); + + return ret; +} + +/** + * @name: FSdioDMATransfer + * @msg: Start command and data transfer in DMA mode + * @return {FError} FSDIO_SUCCESS if transfer success, otherwise failed + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioCmdData} *cmd_data_p, contents of transfer command and data + */ +FError FSdioDMATransfer(FSdio *const instance_p, FSdioCmdData *const cmd_data_p) +{ + FASSERT(instance_p); + FASSERT(cmd_data_p); + FError ret = FSDIO_SUCCESS; + uintptr base_addr = instance_p->config.base_addr; + + cmd_data_p->success = FALSE; /* reset cmd transfer status */ + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return FSDIO_ERR_NOT_INIT; + } + + if (FSDIO_IDMA_TRANS_MODE != instance_p->config.trans_mode) + { + FSDIO_ERROR("device is not configure in DMA transfer mode"); + return FSDIO_ERR_INVALID_STATE; + } + + /* for removable media, check if card exists */ + if ((FALSE == instance_p->config.non_removable) && + (FALSE == FSdioCheckIfCardExists(base_addr))) + { + FSDIO_ERROR("card not detected !!!"); + return FSDIO_ERR_NO_CARD; + } + + /* reset fifo and DMA before transfer */ + FSDIO_SET_BIT(base_addr, FSDIO_CNTRL_OFFSET, FSDIO_CNTRL_FIFO_RESET | FSDIO_CNTRL_DMA_RESET); + ret = FSdioResetCtrl(base_addr, FSDIO_CNTRL_FIFO_RESET | FSDIO_CNTRL_DMA_RESET); + if (FSDIO_SUCCESS != ret) + return ret; + + /* enable use of DMA */ + FSDIO_SET_BIT(base_addr, FSDIO_CNTRL_OFFSET, FSDIO_CNTRL_USE_INTERNAL_DMAC); + FSDIO_SET_BIT(base_addr, FSDIO_BUS_MODE_OFFSET, FSDIO_BUS_MODE_DE); + + if (NULL != cmd_data_p->data_p) /* transfer data */ + { + ret = FSdioDMATransferData(instance_p, + cmd_data_p->data_p); + } + + if (FSDIO_SUCCESS == ret) /* transfer command */ + { + ret = FSdioTransferCmd(instance_p, cmd_data_p); + } + + return ret; +} + +/** + * @name: FSdioPollWaitDMAEnd + * @msg: Wait DMA transfer finished by poll + * @return {FError} FSDIO_SUCCESS if wait success, otherwise wait failed + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioCmdData} *cmd_data_p, contents of transfer command and data + * @param {FSdioRelaxHandler} relax, handler of relax when wait busy + */ +FError FSdioPollWaitDMAEnd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p, FSdioRelaxHandler relax) +{ + FASSERT(instance_p); + FASSERT(cmd_data_p); + FError ret = FSDIO_SUCCESS; + u32 reg_val; + int delay; + const boolean read = cmd_data_p->flag & FSDIO_CMD_FLAG_READ_DATA; + uintptr base_addr = instance_p->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return FSDIO_ERR_NOT_INIT; + } + + if (FSDIO_IDMA_TRANS_MODE != instance_p->config.trans_mode) + { + FSDIO_ERROR("device is not configure in DMA transfer mode"); + return FSDIO_ERR_INVALID_STATE; + } + + /* wait command done or timeout */ + delay = FSDIO_TIMEOUT; + do + { + reg_val = FSdioGetRawStatus(base_addr); + if (relax) + relax(); + } + while (!(FSDIO_INT_CMD_BIT & reg_val) && (--delay > 0)); + + if (!(FSDIO_INT_CMD_BIT & reg_val) && (delay <= 0)) + { + FSDIO_ERROR("wait cmd done timeout, raw ints: 0x%x", reg_val); + return FSDIO_ERR_CMD_TIMEOUT; + } + + if (NULL != cmd_data_p->data_p) /* wait data transfer done or timeout */ + { + delay = FSDIO_TIMEOUT; + do + { + reg_val = FSDIO_READ_REG(base_addr, FSDIO_RAW_INTS_OFFSET); + if (relax) + relax(); + } + while (!(FSDIO_INT_DTO_BIT & reg_val) && (--delay > 0)); + + /* clear status to ack data done */ + FSdioClearRawStatus(base_addr); + + if (!(FSDIO_INT_DTO_BIT & reg_val) && (delay <= 0)) + { + FSDIO_ERROR("wait DMA transfer timeout, raw ints: 0x%x", reg_val); + return FSDIO_ERR_TRANS_TIMEOUT; + } + + /* invalidate cache of transfer buffer */ + if (read) + { + FCacheDCacheInvalidateRange((uintptr)cmd_data_p->data_p, cmd_data_p->data_p->datalen); + } + } + + /* clear status to ack cmd done */ + FSdioClearRawStatus(base_addr); + + if (FSDIO_SUCCESS == ret) + { + ret = FSdioGetCmdResponse(instance_p, cmd_data_p); + } + + return ret; +} + +/** + * @name: FSdioSetIDMAList + * @msg: Setup DMA descriptor for SDIO controller instance + * @return {FError} FSDIO_SUCCESS if setup done, otherwise failed + * @param {FSdio} *instance_p, SDIO controller instance + * @param {volatile FSdioIDmaDesc} *desc, first item in DMA descriptor lists + * @param {u32} desc_num, number of items in DMA descriptor lists + */ +FError FSdioSetIDMAList(FSdio *const instance_p, volatile FSdioIDmaDesc *desc, u32 desc_num) +{ + FASSERT(instance_p); + FError ret = FSDIO_SUCCESS; + uintptr base_addr = instance_p->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return FSDIO_ERR_NOT_INIT; + } + + if (FSDIO_IDMA_TRANS_MODE != instance_p->config.trans_mode) + { + FSDIO_ERROR("device is not configure in DMA transfer mode"); + return FSDIO_ERR_INVALID_STATE; + } + + instance_p->desc_list.first_desc = desc; + instance_p->desc_list.desc_num = desc_num; + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_g.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_g.c new file mode 100644 index 0000000000..78b00cc0e1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_g.c @@ -0,0 +1,67 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:37:44 + * Description:  This files is for static init + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fsdio.h" +#include "fsdio_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +const FSdioConfig FSDIO_CONFIG_TBL[FSDIO_HOST_INSTANCE_NUM] = +{ + [FSDIO_HOST_INSTANCE_0] = + { + .instance_id = FSDIO_HOST_INSTANCE_0, + .base_addr = FSDIO_HOST_0_BASE_ADDR, + .irq_num = FSDIO_HOST_0_IRQ_NUM, + .trans_mode = FSDIO_IDMA_TRANS_MODE, + .voltage = FSDIO_SD_3_3V_VOLTAGE, + .non_removable = FALSE + }, + + [FSDIO_HOST_INSTANCE_1] = + { + .instance_id = FSDIO_HOST_INSTANCE_1, + .base_addr = FSDIO_HOST_1_BASE_ADDR, + .irq_num = FSDIO_HOST_1_IRQ_NUM, + .trans_mode = FSDIO_IDMA_TRANS_MODE, + .voltage = FSDIO_SD_3_3V_VOLTAGE, + .non_removable = FALSE + } +}; + + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_hw.h b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_hw.h new file mode 100644 index 0000000000..a0a1a0b1b6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_hw.h @@ -0,0 +1,625 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_hw.h + * Date: 2022-05-26 15:32:34 + * LastEditTime: 2022-05-26 15:32:35 + * Description:  This files is for SDIO register function definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + * 1.1 zhugengyu 2022/5/26 modify according to tech manual. + */ + +#ifndef DRIVERS_FSDIO_HW_H +#define DRIVERS_FSDIO_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ +#include "fparameters.h" +#include "fio.h" +#include "ftypes.h" +#include "fassert.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ + +/** @name Register Map + * + * Register offsets from the base address of an SD device. + * @{ + */ +#define FSDIO_CNTRL_OFFSET 0x00U /* the controller config reg */ +#define FSDIO_PWREN_OFFSET 0x04U /* the power enable reg */ +#define FSDIO_CLKDIV_OFFSET 0x08U /* the clock divider reg */ +#define FSDIO_CLKENA_OFFSET 0x10U /* the clock enable reg */ +#define FSDIO_TMOUT_OFFSET 0x14U /* the timeout reg */ +#define FSDIO_CTYPE_OFFSET 0x18U /* the card type reg */ +#define FSDIO_BLK_SIZ_OFFSET 0x1CU /* the block size reg */ +#define FSDIO_BYT_CNT_OFFSET 0x20U /* the byte count reg */ +#define FSDIO_INT_MASK_OFFSET 0x24U /* the interrupt mask reg */ +#define FSDIO_CMD_ARG_OFFSET 0x28U /* the command argument reg */ +#define FSDIO_CMD_OFFSET 0x2CU /* the command reg */ +#define FSDIO_RESP0_OFFSET 0x30U /* the response reg0 */ +#define FSDIO_RESP1_OFFSET 0x34U /* the response reg1 */ +#define FSDIO_RESP2_OFFSET 0x38U /* the response reg2 */ +#define FSDIO_RESP3_OFFSET 0x3CU /* the response reg3 */ +#define FSDIO_MASKED_INTS_OFFSET 0x40U /* the masked interrupt status reg */ +#define FSDIO_RAW_INTS_OFFSET 0x44U /* the raw interrupt status reg */ +#define FSDIO_STATUS_OFFSET 0x48U /* the status reg */ +#define FSDIO_FIFOTH_OFFSET 0x4CU /* the FIFO threshold watermark reg */ +#define FSDIO_CARD_DETECT_OFFSET 0x50U /* the card detect reg */ +#define FSDIO_CARD_WRTPRT_OFFSET 0x54U /* the card write protect reg */ +#define FSDIO_GPIO_OFFSET 0x58U /* the ciu ready */ +#define FSDIO_TRAN_CARD_CNT_OFFSET 0x5CU /* the transferred CIU card byte count reg */ +#define FSDIO_TRAN_FIFO_CNT_OFFSET 0x60U /* the transferred host to FIFO byte count reg */ +#define FSDIO_DEBNCE_OFFSET 0x64U /* the debounce count reg */ +#define FSDIO_UID_OFFSET 0x68U /* the user ID reg */ +#define FSDIO_VID_OFFSET 0x6CU /* the controller version ID reg */ +#define FSDIO_HWCONF_OFFSET 0x70U /* the hardware configuration reg */ +#define FSDIO_UHS_REG_OFFSET 0x74U /* the UHS-I reg */ +#define FSDIO_CARD_RESET_OFFSET 0x78U /* the card reset reg */ +#define FSDIO_BUS_MODE_OFFSET 0x80U /* the bus mode reg */ +#define FSDIO_DESC_LIST_ADDRL_OFFSET 0x88U /* the descriptor list low base address reg */ +#define FSDIO_DESC_LIST_ADDRH_OFFSET 0x8CU /* the descriptor list high base address reg */ +#define FSDIO_DMAC_STATUS_OFFSET 0x90U /* the internal DMAC status reg */ +#define FSDIO_DMAC_INT_EN_OFFSET 0x94U /* the internal DMAC interrupt enable reg */ +#define FSDIO_CUR_DESC_ADDRL_OFFSET 0x98U /* the current host descriptor low address reg */ +#define FSDIO_CUR_DESC_ADDRH_OFFSET 0x9CU /* the current host descriptor high address reg */ +#define FSDIO_CUR_BUF_ADDRL_OFFSET 0xA0U /* the current buffer low address reg */ +#define FSDIO_CUR_BUF_ADDRH_OFFSET 0xA4U /* the current buffer high address reg */ +#define FSDIO_CARD_THRCTL_OFFSET 0x100U /* the card threshold control reg */ +#define FSDIO_UHS_REG_EXT_OFFSET 0x108U /* the UHS register extension */ +#define FSDIO_EMMC_DDR_REG_OFFSET 0x10CU /* the EMMC DDR reg */ +#define FSDIO_ENABLE_SHIFT_OFFSET 0x110U /* the enable phase shift reg */ +#define FSDIO_DATA_OFFSET 0x200U /* the data FIFO access */ + +/** @name FSDIO_CNTRL_OFFSET x0 Register + */ +#define FSDIO_CNTRL_CONTROLLER_RESET BIT(0) /* RW 复位控制器,除 DMA,FIFO */ +#define FSDIO_CNTRL_FIFO_RESET BIT(1) /* RW 复位 FIFO, 1 有效 */ +#define FSDIO_CNTRL_DMA_RESET BIT(2) /* RW 复位内部 DMA, 1 有效 */ +#define FSDIO_CNTRL_INT_ENABLE BIT(4) /* RW 全局中断使能配置, 1 使能 */ +#define FSDIO_CNTRL_DMA_ENABLE BIT(5) /* RW 外部 DMA 模式使能 */ +#define FSDIO_CNTRL_READ_WAIT BIT(6) /* RW SDIO 读等待 1 有效 */ +#define FSDIO_CNTRL_SEND_IRQ_RESPONSE BIT(7) /* RW MMC 中断自动响应配置 1 有效 */ +#define FSDIO_CNTRL_ABORT_READ_DATA BIT(8) /* RW 读暂停异常清除 */ +#define FSDIO_CNTRL_SEND_CCSD BIT(9) /* RW 发送CCD (NOT USED) */ +#define FSDIO_CNTRL_SEND_AUTO_STOP_CCSD BIT(10) /* RW 发送CCD,自动STOP (NOT USED) */ +#define FSDIO_CNTRL_ENDIAN BIT(11) /* RW 0:小端,1:大端 */ +#define FSDIO_CNTRL_CARD_VOLTAGE_A_MASK GENMASK(19, 16) /* RW A电压选择 */ +#define FSDIO_CNTRL_CARD_VOLTAGE_B_MASK GENMASK(23, 20) /* RW B电压选择 */ +#define FSDIO_CNTRL_ENABLE_OD_PULLUP BIT(24) /* RW 外部开漏输出 */ +#define FSDIO_CNTRL_USE_INTERNAL_DMAC BIT(25) /* RW 使用内部DMA */ + +/** @name FSDIO_PWREN_OFFSET 0x4 Register + */ +#define FSDIO_PWREN_ENABLE BIT(0) /* RW 卡供电开关, 0:关;1:开*/ + +/** @name FSDIO_CLKDIV_OFFSET 0x8 Register + */ +/* CLK_SAMPLE 和 CLK_SAMPLE 必须小于 CLK_DIVIDER */ +#define FSDIO_CLK_SAMPLE_SET(x) SET_REG32_BITS((x), 23, 16) +#define FSDIO_CLK_DRV_SET(x) SET_REG32_BITS((x), 15, 8) +#define FSDIO_CLK_DIVIDER_SET(x) SET_REG32_BITS((x), 7, 0) /* 分频系数 = 2 * bit[7:0] */ +#define FSDIO_CLK_DIV(samp, drv, div) FSDIO_CLK_SAMPLE_SET(samp) | \ + FSDIO_CLK_DRV_SET(drv) | \ + FSDIO_CLK_DIVIDER_SET(div) + +/** @name FSDIO_CLKENA_OFFSET Register + */ +#define FSDIO_CLKENA_CCLK_ENABLE BIT(0) /* RW 0:Clock disabled;1:Clock enabled */ +#define FSDIO_CLKENA_CCLK_LOW_POWER BIT(16) /* RW 0x0:非低功耗;0x1:低功耗 */ + +/** @name FSDIO_TMOUT_OFFSET Register + */ +#define FSDIO_MAX_DATA_TIMEOUT 0xffffff /* RW 读卡超时(以卡时钟为单位) */ +#define FSDIO_MAX_RESP_TIMEOUT 0xff /* RW 响应超时(以卡时钟为单位) */ +#define FSDIO_TIMEOUT_DATA(data_timeout, resp_timeout) \ + ((GENMASK(31, 8) & ((data_timeout) << 8)) | \ + (GENMASK(7, 0) & ((resp_timeout)))) + +/** @name FSDIO_CTYPE_OFFSET Register + */ +#define FSDIO_CARD0_WIDTH1_8BIT BIT(16) /* 1: 8-bit mode */ +#define FSDIO_CARD0_WIDTH2_4BIT BIT(0) /* 1: 4-bit mode */ +#define FSDIO_CARD0_WIDTH2_1BIT 0x0U /* 0: 1-bit mode */ + +/** @name FSDIO_INT_MASK_OFFSET Register + * @name FSDIO_MASKED_INTS_OFFSET Register + * @name FSDIO_RAW_INTS_OFFSET Register + */ +#define FSDIO_INT_CD_BIT BIT(0) /* RW Card detect (CD) */ +#define FSDIO_INT_RE_BIT BIT(1) /* RW Response error (RE) */ +#define FSDIO_INT_CMD_BIT BIT(2) /* RW Command done (CD) */ +#define FSDIO_INT_DTO_BIT BIT(3) /* RW Data transfer over (DTO) */ +#define FSDIO_INT_TXDR_BIT BIT(4) /* RW Transmit FIFO data request (TXDR) */ +#define FSDIO_INT_RXDR_BIT BIT(5) /* RW Receive FIFO data request (RXDR) */ +#define FSDIO_INT_RCRC_BIT BIT(6) /* RW Response CRC error (RCRC) */ +#define FSDIO_INT_DCRC_BIT BIT(7) /* RW Data CRC error (DCRC) */ +#define FSDIO_INT_RTO_BIT BIT(8) /* RW Response timeout (RTO) */ +#define FSDIO_INT_DRTO_BIT BIT(9) /* RW Data read timeout (DRTO) */ +#define FSDIO_INT_HTO_BIT BIT(10) /* RW Data starvation-by-host timeout (HTO) */ +#define FSDIO_INT_FRUN_BIT BIT(11) /* RW FIFO underrun/overrun error (FRUN) */ +#define FSDIO_INT_HLE_BIT BIT(12) /* RW Hardware locked write error (HLE) */ +#define FSDIO_INT_SBE_BCI_BIT BIT(13) /* RW Start-bit error (SBE) */ +#define FSDIO_INT_ACD_BIT BIT(14) /* RW Auto command done (ACD) */ +#define FSDIO_INT_EBE_BIT BIT(15) /* RW End-bit error (read)/Write no CRC (EBE) */ +#define FSDIO_INT_SDIO_BIT BIT(16) /* RW SDIO interrupt for card */ + +#define FSDIO_INT_ALL_BITS GENMASK(16, 0) +#define FSDIO_INTS_CMD_MASK (FSDIO_INT_RE_BIT | FSDIO_INT_CMD_BIT | FSDIO_INT_RCRC_BIT | \ + FSDIO_INT_RTO_BIT | FSDIO_INT_HTO_BIT | FSDIO_INT_HLE_BIT) + +#define FSDIO_INTS_DATA_MASK (FSDIO_INT_DTO_BIT | FSDIO_INT_DCRC_BIT | FSDIO_INT_DRTO_BIT | \ + FSDIO_INT_SBE_BCI_BIT) + +/** @name FSDIO_CMD_OFFSET Register + */ +#define FSDIO_CMD_START BIT(31) /* 启动命令 */ +#define FSDIO_CMD_USE_HOLD_REG BIT(29) /* 0: 旁路HOLD寄存器,1: 使能HOLD寄存器 */ +#define FSDIO_CMD_VOLT_SWITCH BIT(28) /* 0: 无电压转换,1: 有电压转换 */ +#define FSDIO_CMD_BOOT_MODE BIT(27) /* 0: Mandatory boot, 1: Alternate boot */ +#define FSDIO_CMD_DISABLE_BOOT BIT(26) /* 中止boot进程 */ +#define FSDIO_CMD_EXPECT_BOOT_ACK BIT(25) /* 1: Expect book ack */ +#define FSDIO_CMD_ENABLE_BOOT BIT(24) /* 1: 使能 boot for mandatory */ +#define FSDIO_CMD_UPD_CLK BIT(21) /* 1:不发送指令,仅更新时钟寄存器的值到卡时钟域内 */ +#define FSDIO_CMD_CARD_NUM_SET(num) SET_REG32_BITS((num), 20, 16) +#define FSDIO_CMD_INIT BIT(15) /* 0:在发送指令前不发送初始化序列(80 个周期) 1: 发送 */ +#define FSDIO_CMD_STOP_ABORT BIT(14) /* 1:停止或中止命令,用于停止当前的数据传输 */ +#define FSDIO_CMD_WAIT_PRVDATA_COMPLETE BIT(13) /* 1:等待前面的数据传输完成后再发送指令 0: 立即发送命令 */ +#define FSDIO_CMD_SEND_AUTO_STOP BIT(12) /* 1:在数据传送结束时发送停止命令 */ +#define FSDIO_CMD_TRANSF_MODE_SET(mode) SET_REG32_BITS((mode), 12, 11) /* 1: 流数据传输指令 */ +#define FSDIO_CMD_DAT_WRITE BIT(10) /* 0:读卡 1:写卡 */ +#define FSDIO_CMD_DAT_EXP BIT(9) /* 0:不等待数据传输, 1:等待数据传输 */ +#define FSDIO_CMD_RESP_CRC BIT(8) /* 1:检查响应 CRC */ +#define FSDIO_CMD_RESP_LONG BIT(7) /* 0:等待卡的短响应 1:等待卡的长响应 */ +#define FSDIO_CMD_RESP_EXP BIT(6) /* 1:等待卡的响应,0:命令不需要卡响应 */ +#define FSDIO_CMD_INDX_SET(ind) SET_REG32_BITS((ind), 5, 0) /* 命令索引号 */ + +/** @name FSDIO_STATUS_OFFSET Register + */ +#define FSDIO_STATUS_FIFO_RX BIT(0) /* RO, 达到 FIFO_RX 标记 */ +#define FSDIO_STATUS_FIFO_TX BIT(1) /* RO, 达到 FIFO_TX 标记 */ +#define FSDIO_STATUS_FIFO_EMPTY BIT(2) /* RO, FIFO empty */ +#define FSDIO_STATUS_FIFO_FULL BIT(3) /* RO, FIFO full */ +#define FSDIO_STATUS_CMD_FSM_GET(reg_val) GET_REG32_BITS((reg_val), 7, 4) +#define FSDIO_STATUS_DATA3_STATUS BIT(8) /* RO DATA[3] 卡在位检测,1:在位 */ +#define FSDIO_STATUS_DATA_BUSY BIT(9) /* RO 1: 卡 busy */ +#define FSDIO_STATUS_DATA_STATE_MC_BUSY BIT(10) /* RO DATA TX|RX FSM busy */ +#define FSDIO_STATUS_RESP_INDEX_GET(reg_val) GET_REG32_BITS((reg_val), 16, 11) +#define FSDIO_STATUS_FIFO_CNT_GET(reg_val) GET_REG32_BITS((reg_val), 29, 17) /* RO: FIFO 填充计数器 */ +#define FSDIO_STATUS_DMA_ACK BIT(30) /* RO DMA 确认 */ +#define FSDIO_STATUS_DMA_REQ BIT(31) /* RO DMA 请求 */ + +/** @name FSDIO_FIFOTH_OFFSET Register + */ +enum +{ + FSDIO_FIFOTH_DMA_TRANS_1 = 0b000, + FSDIO_FIFOTH_DMA_TRANS_4 = 0b001, + FSDIO_FIFOTH_DMA_TRANS_8 = 0b010, + FSDIO_FIFOTH_DMA_TRANS_16 = 0b011, + FSDIO_FIFOTH_DMA_TRANS_32 = 0b100, + FSDIO_FIFOTH_DMA_TRANS_64 = 0b101, + FSDIO_FIFOTH_DMA_TRANS_128 = 0b110, + FSDIO_FIFOTH_DMA_TRANS_256 = 0b111 +}; + +#define FSDIO_FIFOTH_DMA_TRANS_MASK GENMASK(30, 28) /* 多次传输的突发大小 */ +#define FSDIO_FIFOTH_RX_WMARK_MASK GENMASK(27, 16) /* 当接收数据给卡时FIFO的阈值 */ +#define FSDIO_FIFOTH_TX_WMARK_MASK GENMASK(11, 0) /* 当发送数据给卡时FIFO的阈值 */ + +#define FSDIO_RX_WMARK 0x7U +#define FSDIO_TX_WMARK 0x100U + +/* + trans_size: Burst size of multiple transaction; + rx_wmark: FIFO threshold watermark level when receiving data to card. + tx_wmark: FIFO threshold watermark level when transmitting data to card +*/ +#define FSDIO_FIFOTH(trans_size, rx_wmark, tx_wmark) \ + (((FSDIO_FIFOTH_DMA_TRANS_MASK) & ((trans_size) << 28)) | \ + ((FSDIO_FIFOTH_RX_WMARK_MASK) & ((rx_wmark) << 16)) | \ + ((FSDIO_FIFOTH_TX_WMARK_MASK) & (tx_wmark))) + +#define FSDIO_DMA_TRANS_SIZE_SET(x) SET_REG32_BITS((x), 30, 28) +#define FSDIO_RX_MARK_SIZE_SET(x) SET_REG32_BITS((x), 27, 16) +#define FSDIO_TX_MARK_SIZE_SET(x) SET_REG32_BITS((x), 11, 0) + +/** @name FSDIO_CARD_DETECT_OFFSET Register + */ +#define FSDIO_CARD_DETECTED BIT(0) /* 1:卡不在位;0:卡在位 */ + +/** @name FSDIO_CARD_WRTPRT_OFFSET Register + */ +#define FSDIO_CARD_WRITE_PROTECTED BIT(0) /* 1:写保护;0:无写保护 */ + +/** @name FSDIO_GPIO_OFFSET Register + */ +#define FSDIO_CLK_READY BIT(0) /* CIU 时钟 ready */ + +/** @name FSDIO_UHS_REG_OFFSET Register + */ +#define FSDIO_UHS_REG_VOLT_180 BIT(0) /* RW 外部调压器接口电压 0: 3.3v, 1: 1.8v */ +#define FSDIO_UHS_REG_VOLT_330 0U +#define FSDIO_UHS_REG_DDR BIT(16) /* RW DDR 模式 */ + +/** @name FSDIO_CARD_RESET_OFFSET Register + */ +#define FSDIO_CARD_RESET_ENABLE BIT(0) /* RW 1:运行;0:复位 */ + +/** @name FSDIO_BUS_MODE_OFFSET Register + */ +#define FSDIO_BUS_MODE_SWR BIT(0) /* RW 软复位,复位idma内部寄存器 */ +#define FSDIO_BUS_MODE_FB BIT(1) /* RW 固定burst */ +#define FSDIO_BUS_MODE_DE BIT(7) /* RW idma使能 */ +#define FSDIO_BUS_MODE_PBL_GET(reg_val) GET_REG32_BITS((reg_val), 10, 8) /* burst LEN */ + +/** @name FSDIO_DMAC_STATUS_OFFSET Register + */ +#define FSDIO_DMAC_STATUS_TI BIT(0) /* RW 发送中断。表示链表的数据发送完成 */ +#define FSDIO_DMAC_STATUS_RI BIT(1) /* RW 接收中断。表示链表的数据接收完成 */ +#define FSDIO_DMAC_STATUS_FBE BIT(2) /* RW 致命总线错误中断 */ +#define FSDIO_DMAC_STATUS_DU BIT(4) /* RW 链表不可用中断 */ +#define FSDIO_DMAC_STATUS_CES BIT(5) /* RW 卡错误汇总 */ +#define FSDIO_DMAC_STATUS_NIS BIT(8) /* RW 正常中断汇总 */ +#define FSDIO_DMAC_STATUS_AIS BIT(9) /* RW 异常中断汇总 */ +#define FSDIO_DMAC_STATUS_EB_GET(reg_val) GET_REG32_BITS((reg_val), 12, 10) +#define FSDIO_DMAC_STATUS_ALL_BITS GENMASK(9, 0) + +#define FSDIO_DMAC_STATUS_EB_TX 0b001 +#define FSDIO_DMAC_STATUS_EB_RX 0b010 + +/** @name FSDIO_DMAC_INT_EN_OFFSET Register + */ +#define FSDIO_DMAC_INT_ENA_TI BIT(0) /* RW 发送完成中断使能 */ +#define FSDIO_DMAC_INT_ENA_RI BIT(1) /* RW 接收完成中断使能 */ +#define FSDIO_DMAC_INT_ENA_FBE BIT(2) /* RW 总线错误中断使能 */ +#define FSDIO_DMAC_INT_ENA_DU BIT(4) /* RW 描述符不可读中断使能 */ +#define FSDIO_DMAC_INT_ENA_CES BIT(5) /* RW 卡错误中断使能 */ +#define FSDIO_DMAC_INT_ENA_NIS BIT(8) /* RW 正常中断汇总使能 */ +#define FSDIO_DMAC_INT_ENA_AIS BIT(9) /* RW 异常中断汇总使能 */ +#define FSDIO_DMAC_INT_ENA_ALL GENMASK(9, 0) + +#define FSDIO_DMAC_INTS_MASK (FSDIO_DMAC_INT_ENA_FBE | FSDIO_DMAC_INT_ENA_DU | \ + FSDIO_DMAC_INT_ENA_NIS | FSDIO_DMAC_INT_ENA_AIS) + +/** @name FSDIO_CARD_THRCTL_OFFSET Register + */ +#define FSDIO_CARD_THRCTL_CARDRD BIT(0) /* RW 读卡threshold使能 */ +#define FSDIO_CARD_THRCTL_BUSY_CLR BIT(1) /* RW busy清中断 */ +#define FSDIO_CARD_THRCTL_CARDWR BIT(2) /* RO 写卡threshold使能 */ +enum +{ + FSDIO_FIFO_DEPTH_8 = 23, + FSDIO_FIFO_DEPTH_16 = 24, + FSDIO_FIFO_DEPTH_32 = 25, + FSDIO_FIFO_DEPTH_64 = 26, + FSDIO_FIFO_DEPTH_128 = 27 +}; + +#define FSDIO_CARD_THRCTL_THRESHOLD(n) BIT(n) /* 读卡 Threshold */ + +/** @name FSDIO_UHS_REG_EXT_OFFSET Register + */ +#define FSDIO_UHS_EXT_MMC_VOLT BIT(0) /* RW 1.2V供电选择 */ +#define FSDIO_UHS_EXT_CLK_ENA BIT(1) /* RW 外部时钟,CIU时钟使能 */ +#define FSDIO_UHS_CLK_DIV_MASK GENMASK(14, 8) /* RW 分频系数,ciu_f = clk_div_ctrl + 1, min=1*/ +#define FSDIO_UHS_CLK_DIV(x) (FSDIO_UHS_CLK_DIV_MASK & ((x) << 8)) +#define FSDIO_UHS_CLK_SAMP_MASK GENMASK(22, 16) /* RW 采样相位参数,相对于ciu时钟相位点 */ +#define FSDIO_UHS_CLK_SAMP(x) (FSDIO_UHS_CLK_SAMP_MASK & ((x) << 16)) +#define FSDIO_UHS_CLK_DRV_MASK GENMASK(30, 24) /* RW 输出相位参数,相对于ciu时钟相位点 */ +#define FSDIO_UHS_CLK_DRV(x) (FSDIO_UHS_CLK_DRV_MASK & ((x) << 24)) +#define FSDIO_UHS_EXT_CLK_MUX BIT(31) + +/* FSDIO_UHS_REG_EXT_OFFSET 和 FSDIO_CLKDIV_OFFSET 两个寄存器配合完成卡时钟和驱动采样相位调整 + UHS_REG_EXT 配置一级分频,CLK_DIV 决定CARD工作时钟频率, DRV 和 SAMP 分别控制驱动相位和采样相位粗调 + 分配系数 = bit [14 : 8] + 1 + CLKDIV 配置二级分频, DIVIDER , DRV 和 SAMP 分别控制驱动相位和采样相位精调 + 分配系数 = bit [7: 0] * 2 +*/ +#define FSDIO_UHS_REG(drv_phase, samp_phase, clk_div) \ + (FSDIO_UHS_CLK_DRV(drv_phase) | \ + FSDIO_UHS_CLK_SAMP(samp_phase) | \ + FSDIO_UHS_CLK_DIV(clk_div)) + +#define FSDIO_UHS_CLK_DIV_SET(x) SET_REG32_BITS((x), 14, 8) +#define FSDIO_UHS_CLK_DIV_GET(reg_val) GET_REG32_BITS((reg_val), 14, 8) +#define FSDIO_UHS_CLK_SAMP_SET(x) SET_REG32_BITS((x), 22, 16) +#define FSDIO_UHS_CLK_DRV_SET(x) SET_REG32_BITS((x), 30, 24) + +/** @name FSDIO_REG_EMMC_DDR_REG_OFFSET Register + */ +#define FSDIO_EMMC_DDR_CYCLE BIT(0) /* RW 1: start bit小于一个周期,0:start bit 为一个周期 */ + +#define FSDIO_TIMEOUT (50000) /* timeout for retries */ +#define FSDIO_DELAY_US (5) +#define FSDIO_400_KHZ (400000UL) +#define FSDIO_25_MHZ (25000000UL) +#define FSDIO_MAX_FIFO_CNT (0x800U) + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDIO_READ_REG(addr, reg_off) FtIn32((addr) + (u32)(reg_off)) +#define FSDIO_WRITE_REG(addr, reg_off, reg_val) FtOut32((addr) + (u32)(reg_off), (u32)(reg_val)) +#define FSDIO_CLR_BIT(addr, reg_off, bits) FtClearBit32((addr) + (u32)(reg_off), bits) +#define FSDIO_SET_BIT(addr, reg_off, bits) FtSetBit32((addr) + (u32)(reg_off), bits) + +/************************** Function Prototypes ******************************/ +FError FSdioSendPrivateCmd(uintptr base_addr, u32 cmd, u32 arg); +FError FSdioResetCtrl(uintptr base_addr, u32 reset_bits); + +/*****************************************************************************/ +/** + * @name: FSdioSetClock + * @msg: Enable/Disable controller clock + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + * @param {boolean} enable, TRUE: enable clock + */ +static inline void FSdioSetClock(uintptr base_addr, boolean enable) +{ + u32 reg_val = FSDIO_READ_REG(base_addr, FSDIO_CLKENA_OFFSET); + if (enable) + reg_val |= FSDIO_CLKENA_CCLK_ENABLE; + else + reg_val &= ~FSDIO_CLKENA_CCLK_ENABLE; + FSDIO_WRITE_REG(base_addr, FSDIO_CLKENA_OFFSET, reg_val); +} + +static inline void FSdioSetPower(uintptr base_addr, boolean enable) +{ + u32 reg_val = FSDIO_READ_REG(base_addr, FSDIO_PWREN_OFFSET); + if (enable) + reg_val |= FSDIO_PWREN_ENABLE; + else + reg_val &= ~FSDIO_PWREN_ENABLE; + FSDIO_WRITE_REG(base_addr, FSDIO_PWREN_OFFSET, reg_val); +} + +static inline void FSdioSetExtClock(uintptr base_addr, boolean enable) +{ + u32 reg_val = FSDIO_READ_REG(base_addr, FSDIO_UHS_REG_EXT_OFFSET); + if (enable) + reg_val |= FSDIO_UHS_EXT_CLK_ENA; + else + reg_val &= ~FSDIO_UHS_EXT_CLK_ENA; + FSDIO_WRITE_REG(base_addr, FSDIO_UHS_REG_EXT_OFFSET, reg_val); +} + +static inline void FSdioSetVoltage1_8V(uintptr base_addr, boolean v1_8) +{ + u32 reg_val = FSDIO_READ_REG(base_addr, FSDIO_UHS_REG_OFFSET); + if (v1_8) + reg_val |= FSDIO_UHS_REG_VOLT_180; + else + reg_val &= ~FSDIO_UHS_REG_VOLT_180; /* 3.3v */ + FSDIO_WRITE_REG(base_addr, FSDIO_UHS_REG_OFFSET, reg_val); +} + +/** + * @name: FSdioGetRawStatus + * @msg: Get raw interrupt status of controller + * @return {u32} raw interrupt status + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline u32 FSdioGetRawStatus(uintptr base_addr) +{ + return FSDIO_READ_REG(base_addr, FSDIO_RAW_INTS_OFFSET); +} + +/** + * @name: FSdioClearRawStatus + * @msg: Clear raw interrupt status of controller + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline void FSdioClearRawStatus(uintptr base_addr) +{ + u32 reg_val = FSdioGetRawStatus(base_addr); + FSDIO_WRITE_REG(base_addr, FSDIO_RAW_INTS_OFFSET, reg_val); +} + +/** + * @name: FSdioGetStatus + * @msg: Get status of controller + * @return {u32} controller status + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline u32 FSdioGetStatus(uintptr base_addr) +{ + return FSDIO_READ_REG(base_addr, FSDIO_STATUS_OFFSET); +} + +/** + * @name: FSdioGetDMAStatus + * @msg: Get interrupt status of DMA + * @return {u32} DMA interrupt status + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline u32 FSdioGetDMAStatus(uintptr base_addr) +{ + return FSDIO_READ_REG(base_addr, FSDIO_DMAC_STATUS_OFFSET); +} + +/** + * @name: FSdioClearDMAStatus + * @msg: Clear interrupt status of DMA + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline void FSdioClearDMAStatus(uintptr base_addr) +{ + u32 reg_val = FSdioGetDMAStatus(base_addr); + FSDIO_WRITE_REG(base_addr, FSDIO_DMAC_STATUS_OFFSET, reg_val); +} + +/** + * @name: FSdioSetDescriptor + * @msg: Set base address of DMA descriptors + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + * @param {uintptr} descriptor, base address of DMA descriptors + */ +static inline void FSdioSetDescriptor(uintptr base_addr, uintptr descriptor) +{ +#ifdef __aarch64___ + FSDIO_WRITE_REG(base_addr, FSDIO_DESC_LIST_ADDRH_OFFSET, UPPER_32_BITS(descriptor)); + FSDIO_WRITE_REG(base_addr, FSDIO_DESC_LIST_ADDRL_OFFSET, LOWER_32_BITS(descriptor)); +#else + FSDIO_WRITE_REG(base_addr, FSDIO_DESC_LIST_ADDRH_OFFSET, 0x0U); + FSDIO_WRITE_REG(base_addr, FSDIO_DESC_LIST_ADDRL_OFFSET, (u32)(descriptor)); +#endif +} + +/** + * @name: FSdioSetTransBytes + * @msg: Set number of bytes to transfer + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + * @param {u32} bytes, number of bytes to transfer + */ +static inline void FSdioSetTransBytes(uintptr base_addr, u32 bytes) +{ + FSDIO_WRITE_REG(base_addr, FSDIO_BYT_CNT_OFFSET, bytes); +} + +/** + * @name: FSdioSetBlockSize + * @msg: Set size of blocks in card + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + * @param {u32} block_size, size of blocks in card + */ +static inline void FSdioSetBlockSize(uintptr base_addr, u32 block_size) +{ + FSDIO_WRITE_REG(base_addr, FSDIO_BLK_SIZ_OFFSET, block_size); +} + +/** + * @name: FSdioSetBusWidth + * @msg: Set bus width of card + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + * @param {u32} width, bus width of card 1-bit, 4-bit, 8-bit + */ +static inline void FSdioSetBusWidth(uintptr base_addr, u32 width) +{ + u32 reg_val; + + switch (width) + { + case 1: + reg_val = FSDIO_CARD0_WIDTH2_1BIT; + break; + case 4: + reg_val = FSDIO_CARD0_WIDTH2_4BIT; + break; + case 8: + reg_val = FSDIO_CARD0_WIDTH1_8BIT; + break; + default: + FASSERT_MSG(0, "invalid bus width %d", width); + break; + } + + FSDIO_WRITE_REG(base_addr, FSDIO_CTYPE_OFFSET, reg_val); +} + +/** + * @name: FSdioGetBusWidth + * @msg: Get bus width for card + * @return {u32} current bus width setting + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline u32 FSdioGetBusWidth(uintptr base_addr) +{ + u32 bus_width = 1; + u32 reg_val = FSDIO_READ_REG(base_addr, FSDIO_CTYPE_OFFSET); + + if (FSDIO_CARD0_WIDTH2_4BIT & reg_val) + { + bus_width = 4; + } + else if (FSDIO_CARD0_WIDTH1_8BIT & reg_val) + { + bus_width = 8; + } + + return bus_width; +} + +/** + * @name: FSdioResetIDMA + * @msg: Reset for internal DMA + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline void FSdioResetIDMA(uintptr base_addr) +{ + u32 reg_val = FSDIO_READ_REG(base_addr, FSDIO_BUS_MODE_OFFSET); + reg_val |= FSDIO_BUS_MODE_SWR; /* 写1软复位idma,复位完成后硬件自动清0 */ + FSDIO_WRITE_REG(base_addr, FSDIO_BUS_MODE_OFFSET, reg_val); +} + +/** + * @name: FSdioSetDDRMode + * @msg: Enable/Disable DDR mode + * @return {*} + * @param {uintptr} base_addr, base address of SDIO controller + * @param {boolean} enable, TRUE: enable DDR mode + */ +static inline void FSdioSetDDRMode(uintptr base_addr, boolean enable) +{ + u32 uhs_val = FSDIO_READ_REG(base_addr, FSDIO_UHS_REG_OFFSET); + u32 emmc_val = FSDIO_READ_REG(base_addr, FSDIO_EMMC_DDR_REG_OFFSET); + if (enable) + { + uhs_val |= FSDIO_UHS_REG_DDR; + emmc_val |= FSDIO_EMMC_DDR_CYCLE; + } + else + { + uhs_val &= ~FSDIO_UHS_REG_DDR; + emmc_val &= ~FSDIO_EMMC_DDR_CYCLE; + } + FSDIO_WRITE_REG(base_addr, FSDIO_UHS_REG_OFFSET, uhs_val); + FSDIO_WRITE_REG(base_addr, FSDIO_EMMC_DDR_REG_OFFSET, emmc_val); + + return; +} + +/** + * @name: FSdioCheckIfCardExists + * @msg: Check if card inserted + * @return {boolean} TRUE: inserted, FALSE: not-found + * @param {uintptr} base_addr, base address of SDIO controller + */ +static inline boolean FSdioCheckIfCardExists(uintptr base_addr) +{ + return (FSDIO_READ_REG(base_addr, FSDIO_CARD_DETECT_OFFSET) & FSDIO_CARD_DETECTED) ? + FALSE : TRUE; +} + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_intr.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_intr.c new file mode 100644 index 0000000000..333795b2db --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_intr.c @@ -0,0 +1,225 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_intr.c + * Date: 2022-06-01 15:08:58 + * LastEditTime: 2022-06-01 15:08:58 + * Description:  This files is for SDIO interrupt related function implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "fdebug.h" +#include "fassert.h" +#include "ftypes.h" + +#include "fsdio_hw.h" +#include "fsdio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDIO_DEBUG_TAG "FSDIO-INTR" +#define FSDIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_WARN(format, ...) FT_DEBUG_PRINT_W(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_INFO(format, ...) FT_DEBUG_PRINT_I(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FSDIO_CALL_EVT_HANDLER(instance_p, evt) \ + if (instance_p->evt_handlers[evt]) \ + { \ + instance_p->evt_handlers[evt](instance_p, instance_p->evt_args[evt]); \ + } + +static const u32 cmd_err_ints_mask = FSDIO_INT_RTO_BIT | FSDIO_INT_RCRC_BIT | FSDIO_INT_RE_BIT | + FSDIO_INT_DCRC_BIT | FSDIO_INT_DRTO_BIT | + FSDIO_INT_SBE_BCI_BIT | FSDIO_INT_HLE_BIT; + +static const u32 dmac_err_ints_mask = FSDIO_DMAC_INT_ENA_FBE | FSDIO_DMAC_INT_ENA_DU | + FSDIO_DMAC_INT_ENA_AIS; +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + +/** + * @name: FSdioGetInterruptMask + * @msg: Get SDIO controller interrupt mask + * @return {u32} interrupt mask bits + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioIntrType} type, Type of interrupt, controller/DMA interrupt + */ +u32 FSdioGetInterruptMask(FSdio *const instance_p, FSdioIntrType type) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 mask = 0U; + + if (0 == instance_p->config.base_addr) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return mask; + } + + if (FSDIO_GENERAL_INTR == type) + { + mask = FSDIO_READ_REG(base_addr, FSDIO_INT_MASK_OFFSET); + } + else + { + mask = FSDIO_READ_REG(base_addr, FSDIO_DMAC_INT_EN_OFFSET); + } + + return mask; +} + +/** + * @name: FSdioSetInterruptMask + * @msg: Enable/Disable SDIO controller interrupt + * @return {NONE} + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioIntrType} type, Type of interrupt, controller/DMA interrupt + * @param {u32} set_mask, interrupt mask bits + * @param {boolean} enable, TRUE: enable interrupt mask bits + */ +void FSdioSetInterruptMask(FSdio *const instance_p, FSdioIntrType type, u32 set_mask, boolean enable) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + u32 mask = 0U; + + if (0 == instance_p->config.base_addr) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return; + } + + mask = FSdioGetInterruptMask(instance_p, type); + + if (TRUE == enable) + { + mask |= set_mask; + } + else + { + mask &= ~set_mask; + } + + if (FSDIO_GENERAL_INTR == type) + { + FSDIO_WRITE_REG(base_addr, FSDIO_INT_MASK_OFFSET, mask); + } + else + { + FSDIO_WRITE_REG(base_addr, FSDIO_DMAC_INT_EN_OFFSET, mask); + } + + return; +} + +/** + * @name: FSdioInterruptHandler + * @msg: Interrupt handler for SDIO instance + * @return {NONE} + * @param {s32} vector, Interrupt id + * @param {void} *param, Interrupt params, is SDIO instance + */ +void FSdioInterruptHandler(s32 vector, void *param) +{ + FASSERT(param); + FSdio *const instance_p = (FSdio * const)param; + uintptr base_addr = instance_p->config.base_addr; + u32 events, event_mask, dmac_events, dmac_evt_mask; + + events = FSDIO_READ_REG(base_addr, FSDIO_RAW_INTS_OFFSET); + dmac_events = FSDIO_READ_REG(base_addr, FSDIO_DMAC_STATUS_OFFSET); + event_mask = FSDIO_READ_REG(base_addr, FSDIO_INT_MASK_OFFSET); + dmac_evt_mask = FSDIO_READ_REG(base_addr, FSDIO_DMAC_INT_EN_OFFSET); + + if (!(events & FSDIO_INT_ALL_BITS) && + !(dmac_events & FSDIO_DMAC_STATUS_ALL_BITS)) + { + FSDIO_DEBUG("irq exit with no action"); + return; /* no interrupt status */ + } + + FSDIO_WRITE_REG(base_addr, 0xfd0U, 0U); + + FSDIO_DEBUG("events:0x%x,mask:0x%x,dmac_events:%x,dmac_mask:0x%x", events, event_mask, dmac_events, dmac_evt_mask); + + FSDIO_WRITE_REG(base_addr, FSDIO_RAW_INTS_OFFSET, events); + FSDIO_WRITE_REG(base_addr, FSDIO_DMAC_STATUS_OFFSET, dmac_events); + + if (((events & event_mask) == 0) && + ((dmac_events & dmac_evt_mask == 0))) + { + return; /* no need to handle interrupt */ + } + + /* handle card detect event */ + if (((events & event_mask) & FSDIO_INT_CD_BIT) && (FALSE == instance_p->config.non_removable)) + { + FSDIO_DEBUG("sd status changed here ! status:[%d]", FSDIO_READ_REG(base_addr, FSDIO_CARD_DETECT_OFFSET)); + FSDIO_CALL_EVT_HANDLER(instance_p, FSDIO_EVT_CARD_DETECTED); + } + + if ((events & FSDIO_INT_DTO_BIT) && (events & FSDIO_INT_CMD_BIT)) /* handle cmd && data done */ + { + FSDIO_DEBUG("cmd and data over"); + FSDIO_CALL_EVT_HANDLER(instance_p, FSDIO_EVT_CMD_DONE); + FSDIO_CALL_EVT_HANDLER(instance_p, FSDIO_EVT_DATA_DONE); + } + else if (events & FSDIO_INT_CMD_BIT) /* handle cmd done */ + { + FSDIO_DEBUG("cmd over"); + FSDIO_CALL_EVT_HANDLER(instance_p, FSDIO_EVT_CMD_DONE); + } + else if (events & FSDIO_INT_DTO_BIT) /* handle data done */ + { + FSDIO_DEBUG("data over"); + FSDIO_CALL_EVT_HANDLER(instance_p, FSDIO_EVT_DATA_DONE); + } + + /* handle error state */ + if ((dmac_events & dmac_err_ints_mask) || (events & cmd_err_ints_mask)) + { + FSDIO_ERROR("ERR:events:0x%x,mask:0x%x,dmac_evts:0x%x,dmac_mask:0x%x", + events, event_mask, dmac_events, dmac_evt_mask); + FSDIO_CALL_EVT_HANDLER(instance_p, FSDIO_EVT_ERR_OCCURE); + } + + return; +} + +/** + * @name: FSdioRegisterEvtHandler + * @msg: Register event call-back function as handler for interrupt events + * @return {NONE} + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioEvtType} evt, interrupt event + * @param {FSdioEvtHandler} handler, event call-back function + * @param {void} *handler_arg, argument of event call-back function + */ +void FSdioRegisterEvtHandler(FSdio *const instance_p, FSdioEvtType evt, FSdioEvtHandler handler, void *handler_arg) +{ + FASSERT(instance_p); + + instance_p->evt_handlers[evt] = handler; + instance_p->evt_args[evt] = handler_arg; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_pio.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_pio.c new file mode 100644 index 0000000000..dfe4f1b5a9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_pio.c @@ -0,0 +1,266 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_pio.c + * Date: 2022-06-01 14:21:47 + * LastEditTime: 2022-06-01 14:21:47 + * Description:  This files is for PIO transfer related function implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "fdebug.h" +#include "fassert.h" +#include "ftypes.h" + +#include "fcache.h" + +#include "fsdio_hw.h" +#include "fsdio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDIO_DEBUG_TAG "FSDIO-PIO" +#define FSDIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_WARN(format, ...) FT_DEBUG_PRINT_W(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_INFO(format, ...) FT_DEBUG_PRINT_I(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +extern FError FSdioTransferCmd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p); + +/*****************************************************************************/ +/** + * @name: FSdioPIOWriteData + * @msg: Write data to fifo + * @return {FError} FSDIO_SUCCESS if write success + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioData} *data_p, contents of transfer data + */ +static FError FSdioPIOWriteData(FSdio *const instance_p, FSdioData *data_p) +{ + FASSERT(data_p); + FError ret = FSDIO_SUCCESS; + u32 loop; + uintptr base_addr = instance_p->config.base_addr; + const u32 wr_times = data_p->datalen / sizeof(u32); /* u8 --> u32 */ + u32 *wr_buf = (u32 *)data_p->buf; + + /* while in PIO mode, max data transferred is 0x800 */ + if (data_p->datalen > FSDIO_MAX_FIFO_CNT) + { + FSDIO_ERROR("Fifo do not support write more than 0x%x", FSDIO_MAX_FIFO_CNT); + return FSDIO_ERR_NOT_SUPPORT; + } + + /* write fifo data */ + FSDIO_WRITE_REG(base_addr, FSDIO_CMD_OFFSET, FSDIO_CMD_DAT_WRITE); + for (loop = 0; loop < wr_times; loop++) + { + FSDIO_WRITE_REG(base_addr, FSDIO_DATA_OFFSET, wr_buf[loop]); + } + + return ret; +} + +/** + * @name: FSdioPIOReadData + * @msg: Read data from fifo + * @return {FError} FSDIO_SUCCESS if read success + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioData} *data_p, contents of transfer data + */ +FError FSdioPIOReadData(FSdio *const instance_p, FSdioData *data_p) +{ + FASSERT(data_p); + FError ret = FSDIO_SUCCESS; + u32 loop; + uintptr base_addr = instance_p->config.base_addr; + const u32 rd_times = data_p->datalen / sizeof(u32); /* u8 --> u32 */ + u32 *rd_buf = (u32 *)data_p->buf; + + /* while in PIO mode, max data transferred is 0x800 */ + if (data_p->datalen > FSDIO_MAX_FIFO_CNT) + { + FSDIO_ERROR("Fifo do not support write more than 0x%x", FSDIO_MAX_FIFO_CNT); + return FSDIO_ERR_NOT_SUPPORT; + } + + /* read data from fifo */ + for (loop = 0; loop < rd_times; loop++) + { + rd_buf[loop] = FSDIO_READ_REG(base_addr, FSDIO_DATA_OFFSET); + } + + return ret; +} + +/** + * @name: FSdioPIOTransfer + * @msg: Start command and data transfer in PIO mode + * @return {FError} FSDIO_SUCCESS if transfer success, otherwise failed + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioCmdData} *cmd_data_p, contents of transfer command and data + */ +FError FSdioPIOTransfer(FSdio *const instance_p, FSdioCmdData *const cmd_data_p) +{ + FASSERT(instance_p); + FASSERT(cmd_data_p); + FError ret = FSDIO_SUCCESS; + const boolean read = cmd_data_p->flag & FSDIO_CMD_FLAG_READ_DATA; + uintptr base_addr = instance_p->config.base_addr; + + cmd_data_p->success = FALSE; /* reset cmd transfer status */ + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return FSDIO_ERR_NOT_INIT; + } + + if (FSDIO_PIO_TRANS_MODE != instance_p->config.trans_mode) + { + FSDIO_ERROR("device is not configure in PIO transfer mode"); + return FSDIO_ERR_INVALID_STATE; + } + + /* for removable media, check if card exists */ + if ((FALSE == instance_p->config.non_removable) && + (FALSE == FSdioCheckIfCardExists(base_addr))) + { + FSDIO_ERROR("card not detected !!!"); + return FSDIO_ERR_NO_CARD; + } + + /* reset fifo and not use DMA */ + FSDIO_CLR_BIT(base_addr, FSDIO_CNTRL_OFFSET, FSDIO_CNTRL_USE_INTERNAL_DMAC); + ret = FSdioResetCtrl(base_addr, FSDIO_CNTRL_FIFO_RESET); + if (FSDIO_SUCCESS != ret) + return ret; + FSDIO_CLR_BIT(base_addr, FSDIO_BUS_MODE_OFFSET, FSDIO_BUS_MODE_DE); + + if (NULL != cmd_data_p->data_p) + { + /* set transfer data length and block size */ + FSdioSetTransBytes(base_addr, cmd_data_p->data_p->datalen); + FSdioSetBlockSize(base_addr, cmd_data_p->data_p->blksz); + + if (FALSE == read) /* if need to write, write to fifo before send command */ + { + /* invalide buffer for data to write */ + FCacheDCacheInvalidateRange((uintptr)cmd_data_p->data_p->buf, + cmd_data_p->data_p->datalen); + + ret = FSdioPIOWriteData(instance_p, cmd_data_p->data_p); + } + } + + if (FSDIO_SUCCESS == ret) /* send command */ + { + ret = FSdioTransferCmd(instance_p, cmd_data_p); + } + + return ret; +} + +/** + * @name: FSdioPollWaitPIOEnd + * @msg: Wait PIO transfer finished by poll + * @return {FError} FSDIO_SUCCESS if wait success, otherwise wait failed + * @param {FSdio} *instance_p, SDIO controller instance + * @param {FSdioCmdData} *cmd_data_p, contents of transfer command and data + * @param {FSdioRelaxHandler} relax, handler of relax when wait busy + */ +FError FSdioPollWaitPIOEnd(FSdio *const instance_p, FSdioCmdData *const cmd_data_p, FSdioRelaxHandler relax) +{ + FASSERT(instance_p); + FASSERT(cmd_data_p); + FError ret = FSDIO_SUCCESS; + u32 loop; + u32 reg_val; + int delay; + const boolean read = cmd_data_p->flag & FSDIO_CMD_FLAG_READ_DATA; + uintptr base_addr = instance_p->config.base_addr; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSDIO_ERROR("device is not yet initialized!!!"); + return FSDIO_ERR_NOT_INIT; + } + + if (FSDIO_PIO_TRANS_MODE != instance_p->config.trans_mode) + { + FSDIO_ERROR("device is not configure in PIO transfer mode"); + return FSDIO_ERR_INVALID_STATE; + } + + FSDIO_INFO("wait for PIO cmd to finish ..."); + delay = FSDIO_TIMEOUT; + do + { + reg_val = FSdioGetRawStatus(base_addr); + if (relax) + relax(); + } + while (!(FSDIO_INT_CMD_BIT & reg_val) && (--delay > 0)); + + if (!(FSDIO_INT_CMD_BIT & reg_val) && (delay <= 0)) + { + FSDIO_ERROR("wait cmd done timeout, raw ints: 0x%x", reg_val); + return FSDIO_ERR_CMD_TIMEOUT; + } + + /* if need to read data, read fifo after send command */ + if ((NULL != cmd_data_p->data_p) && (read)) + { + FSDIO_INFO("wait for PIO data to read ..."); + delay = FSDIO_TIMEOUT; + do + { + reg_val = FSdioGetRawStatus(base_addr); + if (relax) + relax(); + } + while (!(FSDIO_INT_DTO_BIT & reg_val) && (--delay > 0)); + + /* clear status to ack */ + FSdioClearRawStatus(base_addr); + FSDIO_INFO("card cnt: 0x%x, fifo cnt: 0x%x", + FSDIO_READ_REG(base_addr, FSDIO_TRAN_CARD_CNT_OFFSET), + FSDIO_READ_REG(base_addr, FSDIO_TRAN_FIFO_CNT_OFFSET)); + + if (!(FSDIO_INT_DTO_BIT & reg_val) && (delay <= 0)) + { + FSDIO_ERROR("wait PIO transfer timeout, raw ints: 0x%x", reg_val); + return FSDIO_ERR_TRANS_TIMEOUT; + } + } + + /* clear status to ack cmd done */ + FSdioClearRawStatus(base_addr); + + if (FSDIO_SUCCESS == ret) + { + ret = FSdioGetCmdResponse(instance_p, cmd_data_p); + } + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_selftest.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_selftest.c new file mode 100644 index 0000000000..34e8b8520a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_selftest.c @@ -0,0 +1,103 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_selftest.c + * Date: 2022-06-02 11:49:44 + * LastEditTime: 2022-06-02 11:49:45 + * Description:  This files is for SDIO self-test function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ +/***************************** Include Files *********************************/ + +#include "fio.h" +#include "fdebug.h" +#include "fassert.h" +#include "ftypes.h" + +#include "fsdio_hw.h" +#include "fsdio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDIO_DEBUG_TAG "FSDIO-TEST" +#define FSDIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_WARN(format, ...) FT_DEBUG_PRINT_W(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_INFO(format, ...) FT_DEBUG_PRINT_I(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDIO_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FSDIO_DUMPER(base_addr, reg_off, reg_name) \ + FSDIO_DEBUG("\t\t[%s]@0x%x\t=\t0x%x", reg_name, (reg_off), FSDIO_READ_REG((base_addr), (reg_off))) +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + +/** + * @name: FSdioDumpRegister + * @msg: Dump all register value of SDIO instance + * @return {NONE} + * @param {uintptr} base_addr, base address of SDIO controller + */ +void FSdioDumpRegister(uintptr base_addr) +{ + FSDIO_DEBUG("Dump register info @0x%x", base_addr); + FSDIO_DUMPER(base_addr, FSDIO_CNTRL_OFFSET, "cntrl"); + FSDIO_DUMPER(base_addr, FSDIO_PWREN_OFFSET, "pwren"); + FSDIO_DUMPER(base_addr, FSDIO_CLKDIV_OFFSET, "clkdiv"); + FSDIO_DUMPER(base_addr, FSDIO_CLKENA_OFFSET, "clkena"); + FSDIO_DUMPER(base_addr, FSDIO_TMOUT_OFFSET, "tmout"); + FSDIO_DUMPER(base_addr, FSDIO_CTYPE_OFFSET, "ctype"); + FSDIO_DUMPER(base_addr, FSDIO_BLK_SIZ_OFFSET, "blksz"); + FSDIO_DUMPER(base_addr, FSDIO_BYT_CNT_OFFSET, "blkcnt"); + FSDIO_DUMPER(base_addr, FSDIO_INT_MASK_OFFSET, "intmask"); + FSDIO_DUMPER(base_addr, FSDIO_CMD_ARG_OFFSET, "cmdarg"); + FSDIO_DUMPER(base_addr, FSDIO_CMD_OFFSET, "cmd"); + FSDIO_DUMPER(base_addr, FSDIO_RESP0_OFFSET, "resp0"); + FSDIO_DUMPER(base_addr, FSDIO_RESP1_OFFSET, "reps1"); + FSDIO_DUMPER(base_addr, FSDIO_RESP2_OFFSET, "resp2"); + FSDIO_DUMPER(base_addr, FSDIO_RESP3_OFFSET, "resp3"); + FSDIO_DUMPER(base_addr, FSDIO_MASKED_INTS_OFFSET, "maskints"); + FSDIO_DUMPER(base_addr, FSDIO_RAW_INTS_OFFSET, "rawints"); + FSDIO_DUMPER(base_addr, FSDIO_STATUS_OFFSET, "status"); + FSDIO_DUMPER(base_addr, FSDIO_FIFOTH_OFFSET, "fifoth"); + FSDIO_DUMPER(base_addr, FSDIO_CARD_DETECT_OFFSET, "carddet"); + FSDIO_DUMPER(base_addr, FSDIO_CARD_WRTPRT_OFFSET, "wrtprt"); + FSDIO_DUMPER(base_addr, FSDIO_GPIO_OFFSET, "gpio"); + FSDIO_DUMPER(base_addr, FSDIO_TRAN_CARD_CNT_OFFSET, "trans_cardcnt"); + FSDIO_DUMPER(base_addr, FSDIO_TRAN_FIFO_CNT_OFFSET, "trans_fifocnt"); + FSDIO_DUMPER(base_addr, FSDIO_DEBNCE_OFFSET, "debnce"); + FSDIO_DUMPER(base_addr, FSDIO_UID_OFFSET, "uid"); + FSDIO_DUMPER(base_addr, FSDIO_VID_OFFSET, "vid"); + FSDIO_DUMPER(base_addr, FSDIO_HWCONF_OFFSET, "hwconf"); + FSDIO_DUMPER(base_addr, FSDIO_UHS_REG_OFFSET, "uhsreg"); + FSDIO_DUMPER(base_addr, FSDIO_CARD_RESET_OFFSET, "cardreset"); + FSDIO_DUMPER(base_addr, FSDIO_BUS_MODE_OFFSET, "busmode"); + FSDIO_DUMPER(base_addr, FSDIO_DESC_LIST_ADDRL_OFFSET, "descaddrl"); + FSDIO_DUMPER(base_addr, FSDIO_DESC_LIST_ADDRH_OFFSET, "descaddrh"); + FSDIO_DUMPER(base_addr, FSDIO_DMAC_STATUS_OFFSET, "dmacstatus"); + FSDIO_DUMPER(base_addr, FSDIO_DMAC_INT_EN_OFFSET, "dmacinten"); + FSDIO_DUMPER(base_addr, FSDIO_CUR_DESC_ADDRL_OFFSET, "curdescaddrl"); + FSDIO_DUMPER(base_addr, FSDIO_CUR_DESC_ADDRH_OFFSET, "curdescaddrh"); + FSDIO_DUMPER(base_addr, FSDIO_CUR_BUF_ADDRL_OFFSET, "curbufaddrl"); + FSDIO_DUMPER(base_addr, FSDIO_CUR_BUF_ADDRH_OFFSET, "curbufaddrh"); + FSDIO_DUMPER(base_addr, FSDIO_CARD_THRCTL_OFFSET, "card_thrctl"); + FSDIO_DUMPER(base_addr, FSDIO_UHS_REG_EXT_OFFSET, "uhsregext"); + FSDIO_DUMPER(base_addr, FSDIO_EMMC_DDR_REG_OFFSET, "emmcddr"); + FSDIO_DUMPER(base_addr, FSDIO_ENABLE_SHIFT_OFFSET, "enableshift"); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_sinit.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_sinit.c new file mode 100644 index 0000000000..3111024e72 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdio/fsdio_sinit.c @@ -0,0 +1,64 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdio_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:48:41 + * Description:  This files is for static init + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + * 1.1 zhugengyu 2022/6/6 modify according to tech manual. + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fsdio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +extern const FSdioConfig FSDIO_CONFIG_TBL[FSDIO_HOST_INSTANCE_NUM]; + +/************************** Function Prototypes ******************************/ +/** + * @name: FSdioLookupConfig + * @msg: Get the device instance default configure + * @return {const FSdioConfig *} default configure + * @param {u32} instance_id + */ +const FSdioConfig *FSdioLookupConfig(u32 instance_id) +{ + const FSdioConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FSDIO_HOST_INSTANCE_NUM; index++) + { + if (FSDIO_CONFIG_TBL[index].instance_id == instance_id) + { + ptr = &FSDIO_CONFIG_TBL[index]; + break; + } + } + + return (const FSdioConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc.c new file mode 100644 index 0000000000..cb15f01464 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc.c @@ -0,0 +1,389 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:55:23 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +/***************************** Include Files *********************************/ +#include + +#include "fassert.h" +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" + +#include "fcache.h" +#include "fsleep.h" + +#include "fsdmmc_hw.h" +#include "fsdmmc.h" +#include "fsdmmc_dma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDMMC_DEBUG_TAG "FSDMMC" +#define FSDMMC_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_WARN(format, ...) FT_DEBUG_PRINT_W(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_INFO(format, ...) FT_DEBUG_PRINT_I(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/* 此文件主要为了完成用户对外接口,用户可以使用这些接口直接开始工作 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/** + * @name: FSdmmcCfgInitialize + * @msg: 初始化FSDMMC控制器, 使之可以使用 + * @return {FError} 驱动初始化的错误码信息,FSDMMC_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FSdmmc} *instance_p FSDMMC驱动控制数据 + * @param {FSdmmcConfig} *input_config_p FSDMMC用户输入配置 + * @note 输入配置通过FSdmmcLookupConfig获取,用户按照需要修改后传入此函数 + */ +FError FSdmmcCfgInitialize(FSdmmc *instance_p, const FSdmmcConfig *input_config_p) +{ + FASSERT(instance_p && input_config_p); + uintptr base_addr; + FError ret = FSDMMC_SUCCESS; + + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FSDMMC_WARN("device is already initialized!!!"); + } + + /* + * Set default values and configuration data, including setting the + * callback handlers to stubs so the system will not crash should the + * application not assign its own callbacks. + */ + FSdmmcDeInitialize(instance_p); + + instance_p->config = *input_config_p; + base_addr = instance_p->config.base_addr; + + /* + * Check if card exists + */ + if (!FSdmmcCheckIfCardExists(base_addr)) + { + FSDMMC_ERROR("storage device not found !!! 0x%x", base_addr); + return FSDMMC_ERR_CARD_NO_FOUND; + } + + /* + * Reset the device. + */ + ret = FSdmmcReset(base_addr); + if (FSDMMC_SUCCESS == ret) + instance_p->is_ready = FT_COMPONENT_IS_READY; + + return ret; +} + +/** + * @name: FSdmmcDeInitialize + * @msg: 去使能FSDMMC控制器, 清零实例数据 + * @return {*} + * @param {FSdmmc} *instance_p FSDMMC驱动控制数据 + */ +void FSdmmcDeInitialize(FSdmmc *instance_p) +{ + FASSERT(instance_p); + + instance_p->is_ready = 0; + memset(instance_p, 0, sizeof(*instance_p)); + + return; +} + +/** + * @name: FSdmmcMakeRawCmd + * @msg: 组装生成待发送的命令 + * @return {*} + * @param {FSdmmcCmd} *cmd_p 命令控制数据 + */ +u32 FSdmmcMakeRawCmd(FSdmmcCmd *cmd_p) +{ + FASSERT(cmd_p); + u32 raw_cmd = 0; + + /* + * rawcmd : + * trty << 14 | opcode << 8 | cmdw << 6 | cice << 4 | crce << 3 | resp + */ + raw_cmd |= FSDMMC_CMD_SETTING_CMDI(cmd_p->cmdidx); + + if (cmd_p->flag & FSDMMC_CMD_FLAG_ADTC) + raw_cmd |= FSDMMC_CMD_SETTING_TRTY(0b10); /* adtc指令 */ + + if (0 == (cmd_p->flag & FSDMMC_CMD_FLAG_EXP_RESP)) + raw_cmd |= FSDMMC_CMD_NO_RESP; + else if (cmd_p->flag & FSDMMC_CMD_FLAG_EXP_LONG_RESP) + raw_cmd |= FSDMMC_CMD_RESP_136_BIT; + else + raw_cmd |= FSDMMC_CMD_RESP_48_BIT; + + return raw_cmd; +} + +/** + * @name: FSdmmcWaitCmdEnd + * @msg: 阻塞等待命令发送完成,获取命令返回的响应 + * @return {FError} FSDMMC_SUCCESS表示命令发送成功,其它表示命令发送失败 + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {FSdmmcCmd} *cmd_p 命令控制数据 + */ +static FError FSdmmcWaitCmdEnd(uintptr base_addr, FSdmmcCmd *cmd_p) +{ + FASSERT(cmd_p); + FError ret = FSDMMC_SUCCESS; + + ret = FSdmmcWaitStatus(base_addr, FSDMMC_TIMEOUT); + if (FSDMMC_SUCCESS != ret) + return ret; + + if (cmd_p->flag & FSDMMC_CMD_FLAG_EXP_RESP) + { + if (cmd_p->flag & FSDMMC_CMD_FLAG_EXP_LONG_RESP) + { + cmd_p->response[0] = FSDMMC_READ_REG(base_addr, FSDMMC_CMD_RESP_1_REG_OFFSET); + cmd_p->response[1] = FSDMMC_READ_REG(base_addr, FSDMMC_CMD_RESP_2_REG_OFFSET); + cmd_p->response[2] = FSDMMC_READ_REG(base_addr, FSDMMC_CMD_RESP_3_REG_OFFSET); + cmd_p->response[3] = FSDMMC_READ_REG(base_addr, FSDMMC_CMD_RESP_4_REG_OFFSET); + } + else + { + cmd_p->response[0] = FSDMMC_READ_REG(base_addr, FSDMMC_CMD_RESP_1_REG_OFFSET); + cmd_p->response[1] = 0; + cmd_p->response[2] = 0; + cmd_p->response[3] = 0; + } + } + + FSDMMC_INFO("get cmd resp: 0x%x:0x%x:0x%x:0x%x", + cmd_p->response[0], + cmd_p->response[1], + cmd_p->response[2], + cmd_p->response[3]); + + return FSDMMC_SUCCESS; +} + +/** + * @name: FSdmmcSendCmd + * @msg: 发送命令 + * @return {FError} FSDMMC_SUCCESS表示命令发送成功,其它表示命令发送失败 + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {FSdmmcCmd} *cmd_p 命令控制数据 + */ +void FSdmmcSendCmd(uintptr base_addr, FSdmmcCmd *cmd_p) +{ + FASSERT(cmd_p); + u32 raw_cmd = FSdmmcMakeRawCmd(cmd_p); + + FSdmmcSendPrivateCmd(base_addr, raw_cmd, cmd_p->cmdarg); +} + +/** + * @name: FSdmmcTransferCmdPoll + * @msg: 通过FSDMMC轮询方式发送命令,阻塞等待命令返回 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {FSdmmcCmd} *cmd_p 命令控制数据 + */ +static FError FSdmmcTransferCmdPoll(uintptr base_addr, FSdmmcCmd *cmd_p) +{ + FASSERT(cmd_p); + FSdmmcSendCmd(base_addr, cmd_p); + return FSdmmcWaitCmdEnd(base_addr, cmd_p); +} + +/** + * @name: FSdmmcSendAdtcCmd + * @msg: 发送ADTC命令 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {FSdmmcCmd} *cmd_p 命令控制数据 + */ +static void FSdmmcSendAdtcCmd(uintptr base_addr, FSdmmcCmd *cmd_p) +{ + FASSERT(cmd_p); + u32 raw_cmd = FSdmmcMakeRawCmd(cmd_p); + + FSdmmcClearNormalInterruptStatus(base_addr); + raw_cmd |= FSDMMC_CMD_SETTING_TRTY(0b10); /* adtc指令 */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_CMD_SETTING_REG_OFFSET, raw_cmd); + return; +} + +/** + * @name: FSdmmcSendData + * @msg: 发送数据 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {boolean} read TREU: 读数据 FALSE: 写数据 + * @param {FSdmmcCmd} *cmd_p 命令控制数据 + */ +FError FSdmmcSendData(uintptr base_addr, boolean read, FSdmmcCmd *cmd_p) +{ + FASSERT(cmd_p); + FSdmmcData *dat_p = cmd_p->data_p; + u32 card_addr; + u32 blk_cnt; + FError ret = FSDMMC_SUCCESS; + + if ((dat_p->datalen >= FSDMMC_DMA_ADDR_ALIGN) && (dat_p->datalen % FSDMMC_DMA_ADDR_ALIGN != 0)) + { + FSDMMC_ERROR("invalid size: total = %d ", dat_p->datalen); + return FSDMMC_ERR_INVALID_BUF; + } + + if (((uintptr)(dat_p->buf) % FSDMMC_DMA_ADDR_ALIGN) != 0) + { + FSDMMC_ERROR("buffer %p can not be used for DMA", dat_p->buf); + return FSDMMC_ERR_INVALID_BUF; + } + + card_addr = cmd_p->cmdarg; + blk_cnt = dat_p->datalen / dat_p->blksz; + if (dat_p->datalen % dat_p->blksz) + blk_cnt++; + + FSDMMC_INFO("data len: %d, card addr: 0x%x, blk cnt: %d, is %s", + dat_p->datalen, card_addr, blk_cnt, read ? "read" : "write"); + + if (read) + { + if ((cmd_p->flag & FSDMMC_CMD_FLAG_ADTC) && (dat_p->blksz > dat_p->datalen)) + { + FSdmmcSendAdtcCmd(base_addr, cmd_p); + } + /* read data */ + FSdmmcSetReadDMA(base_addr, (uintptr)card_addr, blk_cnt, dat_p->buf); + } + else + { + /* invalidate write buf */ + FCacheDCacheInvalidateRange((uintptr)dat_p->buf, dat_p->datalen); + + /* write data */ + FSdmmcSetWriteDMA(base_addr, (uintptr)card_addr, blk_cnt, dat_p->buf); + } + + return ret; +} + +/** + * @name: FSdmmcTransferDataPoll + * @msg: 通过FSDMMC轮询方式发送数据,阻塞等待数据返回 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {FSdmmcCmd} *cmd_p 待发送数据 + */ +static FError FSdmmcTransferDataPoll(uintptr base_addr, FSdmmcCmd *cmd_p) +{ + FASSERT(cmd_p); + FError ret = FSDMMC_SUCCESS; + FSdmmcData *dat_p = cmd_p->data_p; + const boolean read = (FSDMMC_CMD_FLAG_READ_DATA == (cmd_p->flag & FSDMMC_CMD_FLAG_READ_DATA)); + + ret = FSdmmcSendData(base_addr, read, cmd_p); + if (FSDMMC_SUCCESS != ret) + return ret; + + ret = FSdmmcWaitCmdEnd(base_addr, cmd_p); + if (FSDMMC_SUCCESS != ret) + return ret; + + ret = FSdmmcWaitDMAStatus(base_addr, read, FSDMMC_TIMEOUT); + if (FSDMMC_SUCCESS != ret) + return ret; + + FCacheDCacheInvalidateRange((uintptr)dat_p->buf, dat_p->datalen); + return ret; +} + +/** + * @name: FSdmmcPollTransfer + * @msg: 通过FSDMMC轮询方式发送/接收数据和命令 + * @return {FError} 驱动初始化的错误码信息,FSDMMC_SUCCESS 表示发送/接收成功,其它返回值表示发送/接收失败 + * @param {FSdmmc} *instance_p FSDMMC驱动控制数据 + * @param {FSdmmcCmd} *cmd_data_p FSDMMC数据和命令 + * @note FSDMMC控制器初始化后才能调用此函数 + */ +FError FSdmmcPollTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p) +{ + FASSERT(instance_p && cmd_data_p); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FSDMMC_SUCCESS; + + if (FALSE == FSdmmcCheckIfCardExists(base_addr)) + { + FSDMMC_ERROR("card not found !!! fsdio ctrl base 0x%x", base_addr); + return FSDMMC_ERR_CARD_NO_FOUND; + } + + if (cmd_data_p->flag & FSDMMC_CMD_FLAG_EXP_DATA) + { + /* transfer data */ + FSDMMC_INFO("====DATA [%d] START: buf: %p=====", cmd_data_p->cmdidx, cmd_data_p->data_p->buf); + ret = FSdmmcTransferDataPoll(base_addr, cmd_data_p); + if (FSDMMC_SUCCESS != ret) + { + FSDMMC_ERROR("trans data failed 0x%x", ret); + return ret; + } + + FSDMMC_INFO("====DATA [%d] END 0x%x=====", cmd_data_p->cmdidx, ret); + } + else + { + /* transfer command */ + FSDMMC_INFO("=====CMD [%d] START=====", cmd_data_p->cmdidx); + ret = FSdmmcTransferCmdPoll(base_addr, cmd_data_p); + if (FSDMMC_SUCCESS != ret) + { + FSDMMC_ERROR("send cmd failed 0x%x", ret); + return ret; + } + + FSDMMC_INFO("=====CMD [%d] END: 0x%x=====", cmd_data_p->cmdidx, ret); + } + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc.h b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc.h new file mode 100644 index 0000000000..25573e68af --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc.h @@ -0,0 +1,173 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:55:57 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +#ifndef DRIVERS_MMC_FSDMMC_H +#define DRIVERS_MMC_FSDMMC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "ferror_code.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ +#define FSDMMC_SUCCESS FT_SUCCESS +#define FSDMMC_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 1) +#define FSDMMC_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 2) +#define FSDMMC_ERR_CMD_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 3) +#define FSDMMC_ERR_DATA_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 4) +#define FSDMMC_ERR_CARD_NO_FOUND FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 5) +#define FSDMMC_ERR_INVALID_BUF FT_MAKE_ERRCODE(ErrModBsp, ErrBspMmc, 6) + +/**************************** Type Definitions *******************************/ +enum +{ + FSDMMC_DMA_BD_INTR = 0, + FSDMMC_CMD_INTR, + FSDMMC_ERROR_INTR, + + FSDMMC_INTR_NUM +}; /* 中断类型 */ + +enum +{ + FSDMMC_EVT_CARD_REMOVED = 0, + FSDMMC_EVT_CMD_DONE, + FSDMMC_EVT_CMD_ERROR, + FSDMMC_EVT_CMD_RESP_ERROR, + FSDMMC_EVT_DATA_ERROR, + FSDMMC_EVT_DATA_READ_DONE, + FSDMMC_EVT_DATA_WRITE_DONE, + + FSDMMC_EVT_NUM +}; /* 事件类型 */ + +/** + * This typedef contains data information for the device. + */ +typedef struct +{ + u8 *buf; + u32 blksz; + u32 blkcnt; + u32 datalen; +} FSdmmcData; + +/** + * This typedef contains command information for the device. + */ +typedef struct +{ + u32 cmdidx; + u32 cmdarg; + u32 resptype; + u32 response[4]; + u32 flag; +#define FSDMMC_CMD_FLAG_NEED_STOP BIT(0) +#define FSDMMC_CMD_FLAG_NEED_INIT BIT(1) +#define FSDMMC_CMD_FLAG_EXP_RESP BIT(2) +#define FSDMMC_CMD_FLAG_EXP_LONG_RESP BIT(3) +#define FSDMMC_CMD_FLAG_NEED_RESP_CRC BIT(4) +#define FSDMMC_CMD_FLAG_EXP_DATA BIT(5) +#define FSDMMC_CMD_FLAG_WRITE_DATA BIT(6) +#define FSDMMC_CMD_FLAG_READ_DATA BIT(7) +#define FSDMMC_CMD_FLAG_NEED_AUTO_STOP BIT(8) +#define FSDMMC_CMD_FLAG_ADTC BIT(9) + FSdmmcData *data_p; +} FSdmmcCmd; + +/** + * This typedef contains configuration information for the device. + */ +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num[FSDMMC_INTR_NUM]; +} FSdmmcConfig; + +typedef void (*FSdmmcEventHandler)(void *instance_p); + +/** + * This typedef contains driver instance data. The user is required to allocate a + * variable of this type for every device in the system. A pointer + * to a variable of this type is then passed to the driver API functions. + */ +typedef struct +{ + FSdmmcConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + FSdmmcEventHandler evt_handler[FSDMMC_EVT_NUM]; +} FSdmmc; /* Device instance */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/* 获取FSDMMC控制器默认配置 */ +const FSdmmcConfig *FSdmmcLookupConfig(u32 instance_id); + +/* 初始化FSDMMC控制器, 使之可以使用 */ +FError FSdmmcCfgInitialize(FSdmmc *instance_p, const FSdmmcConfig *cofig_p); + +/* 去使能FSDMMC控制器, 清零实例数据 */ +void FSdmmcDeInitialize(FSdmmc *instance_p); + +/* 通过FSDMMC轮询方式发送/接收数据和命令 */ +FError FSdmmcPollTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p); + +/* 通过FSDMMC中断方式发送/接收数据和命令 */ +FError FSdmmcInterruptTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p); + +/* 获取FSDMMC的中断掩码 */ +u32 FSdmmcGetInterruptMask(uintptr base_addr, u32 intr_type); + +/* 设置FSDMMC的中断掩码 */ +void FSdmmcSetInterruptMask(uintptr base_addr, u32 intr_type, u32 mask, boolean enable); + +/* 命令中断响应函数 */ +void FSdmmcCmdInterrupHandler(s32 vector, void *param); + +/* 错误中断响应函数 */ +void FSdmmcErrInterrupHandler(s32 vector, void *param); + +/* DMA中断响应函数 */ +void FSdmmcDmaInterrupHandler(s32 vector, void *param); + +/* 注册中断事件响应函数 */ +void FSdmmcRegisterInterruptHandler(FSdmmc *instance_p, u32 event, FSdmmcEventHandler handler); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_dma.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_dma.c new file mode 100644 index 0000000000..d2c4da00c4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_dma.c @@ -0,0 +1,142 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc_dma.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:49:31 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +/***************************** Include Files *********************************/ +#include "fassert.h" +#include "fio.h" +#include "fdebug.h" + +#include "fsdmmc_hw.h" +#include "fsdmmc.h" +#include "fsdmmc_dma.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDMMC_DEBUG_TAG "FSDMMC-DMA" +#define FSDMMC_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_WARN(format, ...) FT_DEBUG_PRINT_W(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_INFO(format, ...) FT_DEBUG_PRINT_I(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +/** + * @name: FSdmmcSetReadDMA + * @msg: 设置读数据DMA配置 + * @return {*} + * @param {uintptr} base_addr FSDMMC 控制器基地址 + * @param {uintptr} card_addr 读卡地址 + * @param {u32} blk_cnt 读卡的block数 + * @param {void} *buf_p 读卡的目的地址 + */ +void FSdmmcSetReadDMA(uintptr base_addr, uintptr card_addr, u32 blk_cnt, void *buf_p) +{ + FASSERT(buf_p); + + u32 dsth = UPPER_32_BITS((uintptr)buf_p); /* DMA传输目的地址--> sd read buf */ + u32 dstl = LOWER_32_BITS((uintptr)buf_p); + u32 srch = UPPER_32_BITS((uintptr)card_addr); /* DMA传输源地址 --> sd card */ + u32 srcl = LOWER_32_BITS((uintptr)card_addr); + + FSDMMC_INFO("sd card: 0x%x:0x%x ==> mem space: 0x%x:0x%x", + srch, srcl, dsth, dstl); + + FSDMMC_INFO("read %d blks from 0x%x", blk_cnt, card_addr); + + /* DMA 复位 */ + FSDMMC_SET_BIT(base_addr, FSDMMC_SOFTWARE_RESET_REG_OFFSET, FSDMMC_SOFTWARE_RESET_BDRST); + FSDMMC_CLR_BIT(base_addr, FSDMMC_SOFTWARE_RESET_REG_OFFSET, FSDMMC_SOFTWARE_RESET_BDRST); + + /* 设置传输块数目 */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_BLK_CNT_REG_OFFSET, blk_cnt); + + /* 清除状态寄存器 */ + FSdmmcClearErrorInterruptStatus(base_addr); + FSdmmcClearBDInterruptStatus(base_addr); + FSdmmcClearNormalInterruptStatus(base_addr); + + FSDMMC_INFO("base addr: 0x%x buf_p: %p", base_addr, buf_p); + + /* DMA 读卡地址配置:4 个 cycle + 系统低 4B-系统高 4B-SD 低 4B- SD 高 4B */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_RX_BD_REG_OFFSET, dstl); + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_RX_BD_REG_OFFSET, dsth); + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_RX_BD_REG_OFFSET, srcl); + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_RX_BD_REG_OFFSET, srch); + + + FSDMMC_INFO("DMA READ START!"); + return; +} + +/** + * @name: FSdmmcSetWriteDMA + * @msg: 设置写数据DMA配置 + * @return {*} + * @param {uintptr} base_addr FSDMMC 控制器基地址 + * @param {uintptr} card_addr 写卡地址 + * @param {u32} blk_cnt 写卡的block数 + * @param {void} *buf_p 写卡的源地址 + */ +void FSdmmcSetWriteDMA(uintptr base_addr, uintptr card_addr, u32 blk_cnt, const void *buf_p) +{ + FASSERT(buf_p); + u32 srch = UPPER_32_BITS((uintptr)buf_p); /* DMA传输源地址--> sd read buf */ + u32 srcl = LOWER_32_BITS((uintptr)buf_p); + u32 dsth = UPPER_32_BITS((uintptr)card_addr); /* DMA传输目的地址 --> sd card */ + u32 dstl = LOWER_32_BITS((uintptr)card_addr); + + FSDMMC_INFO("mem space: 0x%x:0x%x ==> sd card: 0x%x:0x%x", + srch, srcl, dsth, dstl); + + FSDMMC_INFO("write %d blks from 0x%x", blk_cnt, card_addr); + + /* DMA 复位 */ + FSDMMC_SET_BIT(base_addr, FSDMMC_SOFTWARE_RESET_REG_OFFSET, FSDMMC_SOFTWARE_RESET_BDRST); + FSDMMC_CLR_BIT(base_addr, FSDMMC_SOFTWARE_RESET_REG_OFFSET, FSDMMC_SOFTWARE_RESET_BDRST); + + /* 设置传输块数目 */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_BLK_CNT_REG_OFFSET, blk_cnt); + + /* 清除状态寄存器 */ + FSdmmcClearErrorInterruptStatus(base_addr); + FSdmmcClearBDInterruptStatus(base_addr); + FSdmmcClearNormalInterruptStatus(base_addr); + + /* DMA 写卡地址配置:4 个 cycle + 系统低 4B-系统高 4B-SD 低 4B- SD 高 4B */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_TX_BD_REG_OFFSET, srcl); + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_TX_BD_REG_OFFSET, srch); + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_TX_BD_REG_OFFSET, dstl); + FSDMMC_WRITE_REG(base_addr, FSDMMC_DAT_IN_M_TX_BD_REG_OFFSET, dsth); + + FSDMMC_INFO("DMA WRITE START!"); + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_dma.h b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_dma.h new file mode 100644 index 0000000000..06cff5d8f4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_dma.h @@ -0,0 +1,54 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc_dma.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:51:25 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +#ifndef DRIVERS_MMC_FSDMMC_DMA_H +#define DRIVERS_MMC_FSDMMC_DMA_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ +#include "ftypes.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/* 设置读数据DMA配置 */ +void FSdmmcSetReadDMA(uintptr base_addr, uintptr card_addr, u32 blk_cnt, void *buf_p); + +/* 设置写数据DMA配置 */ +void FSdmmcSetWriteDMA(uintptr base_addr, uintptr card_addr, u32 blk_cnt, const void *buf_p); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_g.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_g.c new file mode 100644 index 0000000000..bef9e3f28d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_g.c @@ -0,0 +1,62 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:53:31 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +/* - This file contains a configuration table that specifies the configuration +- 驱动全局变量定义,包括静态配置参数 */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" + +#include "fsdmmc.h" +#include "fsdmmc_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +const FSdmmcConfig FSDMMC_CONFIG_TBL[FSDMMC_HOST_INSTANCE_NUM] = +{ + [FSDMMC_HOST_INSTANCE_0] = + { + .instance_id = FSDMMC_HOST_INSTANCE_0, /* Id of device*/ + .base_addr = FSDMMC_HOST_0_BASEADDR, + .irq_num = + { + [FSDMMC_CMD_INTR] = FSDMMC_HOST_0_CMD_INTR_IRQ, + [FSDMMC_DMA_BD_INTR] = FSDMMC_HOST_0_DMA_INTR_IRQ, + [FSDMMC_ERROR_INTR] = FSDMMC_HOST_0_ERR_INTR_IRQ + } + } +}; + + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_hw.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_hw.c new file mode 100644 index 0000000000..155f388561 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_hw.c @@ -0,0 +1,258 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:54:02 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +/***************************** Include Files *********************************/ +#include "fassert.h" +#include "fdebug.h" + +#include "fsdmmc_hw.h" +#include "fsdmmc.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSDMMC_DEBUG_TAG "FSDMMC-HW" +#define FSDMMC_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_WARN(format, ...) FT_DEBUG_PRINT_W(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_INFO(format, ...) FT_DEBUG_PRINT_I(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +/** + * @name: FSdmmcSoftwareReset + * @msg: 完成软复位 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {int} retries 重试次数 + */ +FError FSdmmcSoftwareReset(uintptr base_addr, int retries) +{ + FASSERT(retries > 1); + u32 reg_val; + + FSDMMC_SET_BIT(base_addr, FSDMMC_SOFTWARE_RESET_REG_OFFSET, FSDMMC_SOFTWARE_RESET_SRST); + FSDMMC_CLR_BIT(base_addr, FSDMMC_SOFTWARE_RESET_REG_OFFSET, FSDMMC_SOFTWARE_RESET_SRST); + + do + { + reg_val = FSDMMC_READ_REG(base_addr, FSDMMC_STATUS_REG_OFFSET); + } + while (!(reg_val & FSDMMC_STATUS_IDIE) && + (retries-- > 0)); + + if (!(reg_val & FSDMMC_STATUS_IDIE) && (retries <= 0)) + { + FSDMMC_ERROR("software reset timeout!!! status: 0x%x", reg_val); + return FSDMMC_ERR_TIMEOUT; + } + + return FSDMMC_SUCCESS; +} + +/** + * @name: FSdmmcSetCardClk + * @msg: 设置FSDMMC的时钟 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {u32} clk_freq_hz 时钟频率,HZ + */ +FError FSdmmcSetCardClk(uintptr base_addr, u32 clk_freq_hz) +{ + FSDMMC_WRITE_REG(base_addr, FSDMMC_CLOCK_DIV_REG_OFFSET, FSDMMC_CLK_DIVIDER(clk_freq_hz)); + FSDMMC_WRITE_REG(base_addr, FSDMMC_SD_DRV_REG_OFFSET, FSDMMC_DEFAULT_DRV); + FSDMMC_WRITE_REG(base_addr, FSDMMC_SD_SAMP_REG_OFFSET, FSDMMC_DEFAULT_SAMP); + + return FSdmmcSoftwareReset(base_addr, FSDMMC_TIMEOUT); +} + +static const char *FSdmmcGetRespTypeStr(u32 hw_cmd) +{ + const char *str; + + switch (FSDMMC_CMD_RESP_MASK & hw_cmd) + { + case FSDMMC_CMD_NO_RESP: + str = "NONE"; + break; + case FSDMMC_CMD_RESP_136_BIT: + str = "LONG"; + break; + case FSDMMC_CMD_RESP_48_BIT: + str = "SHORT"; + break; + case FSDMMC_CMD_RESP_48_BIT_BUSY_CHECK: + str = "SHORT CHECK BUSY"; + break; + default: + FASSERT(0); + } + + return str; +} + +/** + * @name: FSdmmcSendPrivateCmd + * @msg: 发送命令 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {u32} cmd 待发送的命令 + * @param {u32} arg 待发送命令的参数 + */ +void FSdmmcSendPrivateCmd(uintptr base_addr, u32 cmd, u32 arg) +{ + /* 清空状态寄存器 */ + FSdmmcClearNormalInterruptStatus(base_addr); + FSdmmcClearErrorInterruptStatus(base_addr); + FSdmmcClearBDInterruptStatus(base_addr); + + /* 设置命令 */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_CMD_SETTING_REG_OFFSET, cmd); + + /* 设置参数,同时触发发送命令 */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_ARGUMENT_REG_OFFSET, FSDMMC_ARGUMENT_MASK & arg); + + FSDMMC_INFO("CMD: 0x%08x ", FSDMMC_READ_REG(base_addr, FSDMMC_CMD_SETTING_REG_OFFSET)); + FSDMMC_INFO("ARG: 0x%08x", FSDMMC_READ_REG(base_addr, FSDMMC_ARGUMENT_REG_OFFSET)); + FSDMMC_INFO("RESP: %s", FSdmmcGetRespTypeStr(cmd)); +} + +/** + * @name: FSdmmcReset + * @msg: 重置FSDMMC控制器 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + */ +FError FSdmmcReset(uintptr base_addr) +{ + u32 reg_val; + FError ret = FSDMMC_SUCCESS; + + ret = FSdmmcSoftwareReset(base_addr, FSDMMC_TIMEOUT); + if (FSDMMC_SUCCESS != ret) + return ret; + + /* set card detection */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_SD_SEN_REG_OFFSET, 0x0); + reg_val = FSDMMC_SEN_CREFR_VAL | FSDMMC_SEN_DEBNCE_VAL; + FSDMMC_WRITE_REG(base_addr, FSDMMC_SD_SEN_REG_OFFSET, reg_val); + + /* configure cmd data timeout */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_TIMEOUT_CMD_REG_OFFSET, FSDMMC_CMD_TIMEOUT); + FSDMMC_WRITE_REG(base_addr, FSDMMC_TIMEOUT_DATA_REG_OFFSET, FSDMMC_DATA_TIMEOUT); + + /* handle DMA cache */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_HDS_AXI_REG_CONF1_REG_OFFSET, FSDMMC_AXI_CONF1); + FSDMMC_WRITE_REG(base_addr, FSDMMC_HDS_AXI_REG_CONF2_REG_OFFSET, FSDMMC_AXI_CONF2); + + /* set ending */ + reg_val = FSDMMC_PERMDW_STD_END | FSDMMC_PERMDR_STD_END; + FSDMMC_WRITE_REG(base_addr, FSDMMC_CONTROLL_SETTING_REG_OFFSET, reg_val); + + /* disable interrupt */ + FSDMMC_WRITE_REG(base_addr, FSDMMC_NORMAL_INT_EN_REG_OFFSET, 0x0); + FSDMMC_WRITE_REG(base_addr, FSDMMC_ERROR_INT_EN_REG_OFFSET, 0x0); + FSDMMC_WRITE_REG(base_addr, FSDMMC_BD_ISR_EN_REG_OFFSET, 0x0); + + /* clear interrupr status */ + FSdmmcClearNormalInterruptStatus(base_addr); + FSdmmcClearErrorInterruptStatus(base_addr); + FSdmmcClearBDInterruptStatus(base_addr); + + return ret; +} + +/** + * @name: FSdmmcWaitStatus + * @msg: 等待命令完成或者命令错误状态 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {int} retries 重试次数 + */ +FError FSdmmcWaitStatus(uintptr base_addr, int retries) +{ + FASSERT(retries > 1); + const u32 status_mask = FSDMMC_NORMAL_INT_STATUS_CC | FSDMMC_NORMAL_INT_STATUS_EI; /* 等待命令完成或者发生错误 */ + u32 status; + + do + { + status = status_mask & FSDMMC_READ_REG(base_addr, FSDMMC_NORMAL_INT_STATUS_REG_OFFSET); + } + while ((!status) && (retries-- > 0)); + + if (FSDMMC_NORMAL_INT_STATUS_EI & status) + { + FSDMMC_ERROR("error status: 0x%x, remain retries: %d", status, retries); + FSdmmcReset(base_addr); + return FSDMMC_ERR_CMD_FAILED; + } + else if (0 >= retries) + { + FSDMMC_ERROR("wait timeout!!! status 0x%x", status); + return FSDMMC_ERR_TIMEOUT; + } + + return FSDMMC_SUCCESS; +} + +/** + * @name: FSdmmcWaitDMAStatus + * @msg: 等待数据传输完成或者传输错误状态 + * @return {*} + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {boolean} read TRUE: 当前是读数据 FALSE: 当前是写数据 + * @param {int} retries 重试次数 + */ +FError FSdmmcWaitDMAStatus(uintptr base_addr, boolean read, int retries) +{ + const u32 status_mask = read ? + (FSDMMC_BD_ISR_REG_RESPE | FSDMMC_BD_ISR_REG_DAIS) : /* 等待DMA传输完成或者发生错误 */ + (FSDMMC_BD_ISR_REG_TRS | FSDMMC_BD_ISR_REG_DAIS); /* 等待DMA传输完成或者发生错误 */ + u32 status; + + /* 等待DMA传输完成或者发生错误 */ + do + { + status = status_mask & FSDMMC_READ_REG(base_addr, FSDMMC_BD_ISR_REG_OFFSET); + } + while ((!status) && (retries-- > 0)); + + if (status & FSDMMC_BD_ISR_REG_DAIS) + { + FSDMMC_ERROR("BD Data error when %s blk!", read ? "read" : "write"); + FSdmmcReset(base_addr); + return FSDMMC_ERR_DATA_FAILED; + } + else if (0 >= retries) + { + FSDMMC_ERROR("BD Data timeout !!!"); + return FSDMMC_ERR_TIMEOUT; + } + + return FSDMMC_SUCCESS; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_hw.h b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_hw.h new file mode 100644 index 0000000000..623f2af31d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_hw.h @@ -0,0 +1,346 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:54:24 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +#ifndef DRIVERS_MMC_FSDMMC_HW_H +#define DRIVERS_MMC_FSDMMC_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fparameters.h" +#include "fio.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ + +/** @name Register Map + * + * Register offsets from the base address of an SD device. + * @{ + */ +#define FSDMMC_CONTROLL_SETTING_REG_OFFSET 0x00 /* Controller configuration register */ +#define FSDMMC_ARGUMENT_REG_OFFSET 0x04 /* Parameter register */ +#define FSDMMC_CMD_SETTING_REG_OFFSET 0x08 /* Command register */ +#define FSDMMC_CLOCK_DIV_REG_OFFSET 0x0C /* Clock division register */ +#define FSDMMC_SOFTWARE_RESET_REG_OFFSET 0x10 /* Reset control register */ +#define FSDMMC_POWER_CONTROLL_REG_OFFSET 0x14 /* Power control register */ +#define FSDMMC_TIMEOUT_CMD_REG_OFFSET 0x18 /* Cmd Timeout setting register */ +#define FSDMMC_TIMEOUT_DATA_REG_OFFSET 0x1C /* Data timeout setting register */ +#define FSDMMC_NORMAL_INT_EN_REG_OFFSET 0x20 /* Interrupt Enable Register */ +#define FSDMMC_ERROR_INT_EN_REG_OFFSET 0x24 /* Error Interrupt Enable Register */ +#define FSDMMC_BD_ISR_EN_REG_OFFSET 0x28 /* Data Transfer Interrupt Enable Register */ +#define FSDMMC_CAPABILIES_REG_OFFSET 0x2c /* capabilies register */ +#define FSDMMC_SD_DRV_REG_OFFSET 0x30 /* SD card driver phase register */ +#define FSDMMC_SD_SAMP_REG_OFFSET 0x34 /* SD card sampling phase register */ +#define FSDMMC_SD_SEN_REG_OFFSET 0x38 /* Card detection controller */ +#define FSDMMC_HDS_AXI_REG_CONF1_REG_OFFSET 0x3c /* AXI boundary configuration register 1 */ +#define FSDMMC_DAT_IN_M_RX_BD_REG_OFFSET 0x40 /* SD BD RX address register */ +#define FSDMMC_DAT_IN_M_TX_BD_REG_OFFSET 0x60 /* SD BD TX address register */ +#define FSDMMC_BLK_CNT_REG_OFFSET 0x80 /* Block reads and writes configuration registers */ +#define FSDMMC_HDS_AXI_REG_CONF2_REG_OFFSET 0xa8 /* AXI boundary configuration register 2 */ +#define FSDMMC_NORMAL_INT_STATUS_REG_OFFSET 0xc0 /* Interrupt status register */ +#define FSDMMC_ERROR_INT_STATUS_REG_OFFSET 0xc4 /* ERROR interrupt register */ +#define FSDMMC_BD_ISR_REG_OFFSET 0xc8 /* Data Transfer Interrupt Status Register */ +#define FSDMMC_BD_STATUS_REG_OFFSET 0xcc /* BD descriptor register */ +#define FSDMMC_STATUS_REG_OFFSET 0xd0 /* Status register */ +#define FSDMMC_BLOCK_REG_OFFSET 0xd4 /* Block length register */ +#define FSDMMC_CMD_RESP_1_REG_OFFSET 0xe0 /* Command response register 1 */ +#define FSDMMC_CMD_RESP_2_REG_OFFSET 0xe4 /* Command response register 2 */ +#define FSDMMC_CMD_RESP_3_REG_OFFSET 0xe8 /* Command response register 3 */ +#define FSDMMC_CMD_RESP_4_REG_OFFSET 0xec /* Command response register 4 */ + +/** @name FSDMMC_CONTROLL_SETTING_REG_OFFSET Register + */ +#define FSDMMC_PERMDW_MASK GENMASK(11, 10) +#define FSDMMC_PERMDW(x) (FSDMMC_PERMDW_MASK & ((x) << 10)) /* 写操作对应的大小端选择 */ +#define FSDMMC_PERMDW_LIT_END FSDMMC_PERMDW(0x0) +#define FSDMMC_PERMDW_BIG_END FSDMMC_PERMDW(0x1) +#define FSDMMC_PERMDW_STD_END FSDMMC_PERMDW(0x3) + +#define FSDMMC_PERMDR_MASK GENMASK(9, 8) +#define FSDMMC_PERMDR(x) (FSDMMC_PERMDR_MASK & ((x) << 8)) /* 读操作对应的大小端选择 */ +#define FSDMMC_PERMDR_LIT_END FSDMMC_PERMDR(0x0) +#define FSDMMC_PERMDR_BIG_END FSDMMC_PERMDR(0x1) +#define FSDMMC_PERMDR_STD_END FSDMMC_PERMDR(0x3) + +/** @name FSDMMC_ARGUMENT_REG_OFFSET Register + */ +#define FSDMMC_ARGUMENT_MASK GENMASK(31, 0) + +/** @name FSDMMC_CMD_SETTING_REG_OFFSET Register + */ +#define FSDMMC_CMD_RESP_MASK GENMASK(1, 0) +#define FSDMMC_CMD_SETTING_RTS(x) (FSDMMC_CMD_RESP_MASK & ((x) << 0)) /* 0: No response 01: Response byte length 136 10: Response byte length 48 11: Response byte length 48 */ +#define FSDMMC_CMD_NO_RESP FSDMMC_CMD_SETTING_RTS(0x0) /* 00:不响应 */ +#define FSDMMC_CMD_RESP_136_BIT FSDMMC_CMD_SETTING_RTS(0x1) /* 01:响应字节长度 136 */ +#define FSDMMC_CMD_RESP_48_BIT FSDMMC_CMD_SETTING_RTS(0x2) /* 10: 响应字节长度 48 */ +#define FSDMMC_CMD_RESP_48_BIT_BUSY_CHECK FSDMMC_CMD_SETTING_RTS(0x3) /* 11: 响应字节长度 48, check busy after resp */ + +#define FSDMMC_CMD_SETTING_CRCE BIT(3) /* 0: CRC check is not performed on CMD response 1: CRC check is performed on CMD response */ +#define FSDMMC_CMD_SETTING_CICE BIT(4) /* 0:CMD 响应时,不执行索引检查 1:CMD 响应时,执行索引检查 */ +#define FSDMMC_CMD_SETTING_CMDTP(x) (GENMASK(7, 6) & ((x) << 6)) /* 命令类型 */ +#define FSDMMC_CMD_SETTING_CMDI(x) (GENMASK(13, 8) & ((x) << 8)) /* 命令索引 */ +#define FSDMMC_CMD_SETTING_TRTY(x) (GENMASK(15, 14) & ((x) << 14)) /* 10: adtc 指令 ,其它: 读写操作 */ + + +/** @name FSDMMC_CLOCK_DIV_REG_OFFSET Register + */ +#define FSDMMC_CLK_DIVIDER(clk) (GENMASK(31, 0) & ((FSDMMC_CLK_FREQ_HZ / (2 * (clk))) - 1)) + +/** @name FSDMMC_SOFTWARE_RESET_REG_OFFSET Register + */ +#define FSDMMC_SOFTWARE_RESET_SRST BIT(0) /* 控制器软复位 */ +#define FSDMMC_SOFTWARE_RESET_BDRST BIT(2) /* DMA BD 清 0 */ +#define FSDMMC_SOFTWARE_RESET_CFCLF BIT(3) /* 卡插入拔出状态触发标志清 0 */ + +/** @name FSDMMC_TIMEOUT_CMD_REG_OFFSET Register + */ +#define FSDMMC_TIMEOUT_CMD_MASK GENMASK(31, 0) + +/** @name FSDMMC_TIMEOUT_DATA_REG_OFFSET Register + */ +#define FSDMMC_TIMEOUT_DATA_MASK GENMASK(31, 0) + +/** @name FSDMMC_NORMAL_INT_EN_REG_OFFSET Register + */ +#define FSDMMC_NORMAL_INT_EN_ECC BIT(0) /* 命令完成中断使能 */ +#define FSDMMC_NORMAL_INT_EN_ECCRCE BIT(1) /* 卡拔出中断使能 */ +#define FSDMMC_NORMAL_INT_EN_ECIE BIT(15) /* 错误中断使能 */ +#define FSDMCC_NORMAL_INT_ALL_BITS (FSDMMC_NORMAL_INT_EN_ECC | FSDMMC_NORMAL_INT_EN_ECCRCE |\ + FSDMMC_NORMAL_INT_EN_ECIE) + +/** @name FSDMMC_ERROR_INT_EN_REG_OFFSET Register + */ +#define FSDMMC_ERROR_INT_EN_CNR BIT(4) /* 命令响应错误中断 */ +#define FSDMMC_ERROR_INT_EN_CIR BIT(3) /* 命令索引错误中断使能 */ +#define FSDMMC_ERROR_INT_EN_CCRCE BIT(1) /* 命令 CRC 错误中断使能 */ +#define FSDMMC_ERROR_INT_EN_CTE BIT(0) /* 命令超时中断使能 */ +#define FSDMMC_ERROR_INT_ALL_BITS (FSDMMC_ERROR_INT_EN_CNR | FSDMMC_ERROR_INT_EN_CIR |\ + FSDMMC_ERROR_INT_EN_CCRCE | FSDMMC_ERROR_INT_EN_CTE) + +/** @name FSDMMC_BD_ISR_EN_REG_OFFSET Register + */ +#define FSDMMC_BD_ISR_EN_ETRS BIT(0) /* DMA 传输完成中断使能 */ +#define FSDMMC_BD_ISR_EN_EDTE BIT(3) /* 数据超时中断使能 */ +#define FSDMMC_BD_ISR_EN_ECMDE BIT(4) /* 命令响应错误中断使能 */ +#define FSDMMC_BD_ISR_EN_ETRE BIT(5) /* 传输错误中断使能 */ +#define FSDMMC_BD_ISR_EN_ENRCRCE BIT(6) /* CRC 校验错误中断使能 */ +#define FSDMMC_BD_ISR_EN_EDATFRAXE BIT(7) /* AXI 总线错误中断使能 */ +#define FSDMMC_BD_ISR_EN_RESPE BIT(8) /* 读 SD 卡操作,AXI BR 通道完成中断 */ +#define FSDMMC_BD_ISR_EN_EDAISE BIT(15) /* DMA 错误中断使能 */ +#define FSDMMC_BD_ISR_ALL_BITS (FSDMMC_BD_ISR_EN_ETRS | FSDMMC_BD_ISR_EN_EDTE | \ + FSDMMC_BD_ISR_EN_ECMDE | FSDMMC_BD_ISR_EN_ETRE | \ + FSDMMC_BD_ISR_EN_ENRCRCE | FSDMMC_BD_ISR_EN_EDATFRAXE | \ + FSDMMC_BD_ISR_EN_RESPE | FSDMMC_BD_ISR_EN_EDAISE) + + +/** @name FSDMMC_SD_DRV_REG_OFFSET Register + */ +#define FSDMMC_SD_DRV_MASK GENMASK(31, 0) /* 卡驱动相位配置参数 */ + +/** @name FSDMMC_SD_SAMP_REG_OFFSET Register + */ +#define FSDMMC_SD_SAMP_MASK GENMASK(31, 0) /* 卡采样相位配置参数 */ + +/** @name FSDMMC_SD_SEN_REG_OFFSET Register + */ +#define FSDMMC_SD_SEN_REG_CREFR BIT(1) /* 卡拔出时自动释放 AXI 总线选择 */ +#define FSDMMC_SD_SEN_REG_CRES BIT(2) /* CARD 在位状态标志选择 0: 卡在位-0,不在位-1 1: 卡在位-1,不在位-0 */ +#define FSDMMC_SD_SEN_REG_DEBNCE(x) ((x << 8) & GENMASK(31, 8)) /* 去抖时钟分频参数 */ + +/** @name FSDMMC_HDS_AXI_REG_CONF1_REG_OFFSET Register + */ +#define FSDMMC_HDS_AXI_CONF1_AWREGION_HDS_M GENMASK(22, 19) +#define FSDMMC_HDS_AXI_CONF1_AWSNOOP_HDS_M GENMASK(18, 16) +#define FSDMMC_HDS_AXI_CONF1_ARBAR_HDS_M GENMASK(15, 14) +#define FSDMMC_HDS_AXI_CONF1_ARDOMAIN_HDS_M GENMASK(13, 12) +#define FSDMMC_HDS_AXI_CONF1_ARREGION_HDS_M GENMASK(11, 8) +#define FSDMMC_HDS_AXI_CONF1_ARSNOOP_HDS_M GENMASK(7, 4) +#define FSDMMC_HDS_AXI_CONF1_AWBAR_HDS_M GENMASK(3, 2) +#define FSDMMC_HDS_AXI_CONF1_AWDOMAIN_HDS_M GENMASK(1, 0) + +/** @name FSDMMC_DAT_IN_M_RX_BD_REG_OFFSET Register + */ +#define FSDMMC_DAT_IN_M_RX_BD_MASK GENMASK(31, 0) + +/** @name FSDMMC_DAT_IN_M_TX_BD_REG_OFFSET Register + */ +#define FSDMMC_DAT_IN_M_TX_BD_MASK GENMASK(31, 0) + +/** @name FSDMMC_BLK_CNT_REG_OFFSET Register + */ +#define FSDMMC_BLK_CNT_MASK GENMASK(31, 0) + +/** @name FSDMMC_HDS_AXI_REG_CONF2_REG_OFFSET Register + */ +#define FSDMMC_HDS_AXI_CONF2_SD_ARPROT GENMASK(29, 27) +#define FSDMMC_HDS_AXI_CONF2_SD_AWPROT GENMASK(26, 24) +#define FSDMMC_HDS_AXI_CONF2_SD_ARCACHE_M GENMASK(23, 20) +#define FSDMMC_HDS_AXI_CONF2_SD_AWCACHE_M GENMASK(19, 16) +#define FSDMMC_HDS_AXI_CONF2_HDA_ARPRO GENMASK(13, 11) +#define FSDMMC_HDS_AXI_CONF2_HDA_AWPROT GENMASK(10, 8) +#define FSDMMC_HDS_AXI_CONF2_HDA_ARCACHE_M GENMASK(7, 4) +#define FSDMMC_HDS_AXI_CONF2_HDA_AWCACHE_M GENMASK(3, 0) + +/** @name FSDMMC_NORMAL_INT_STATUS_REG_OFFSET Register + */ +#define FSDMMC_NORMAL_INT_STATUS_EI BIT(15) /* 命令错误中断 */ +#define FSDMMC_NORMAL_INT_STATUS_CR BIT(1) /* 卡移除中断 */ +#define FSDMMC_NORMAL_INT_STATUS_CC BIT(0) /* 命令完成中断 */ +#define FSDMMC_NORMAL_INT_STATUS_ALL_MASK (FSDMMC_NORMAL_INT_STATUS_EI | FSDMMC_NORMAL_INT_STATUS_CR | FSDMMC_NORMAL_INT_STATUS_CC) + +/** @name FSDMMC_ERROR_INT_STATUS_REG_OFFSET Register + */ +#define FSDMMC_ERROR_INT_STATUS_CNR BIT(4) /* 命令响应错误中断 */ +#define FSDMMC_ERROR_INT_STATUS_CIR BIT(3) /* 命令索引错误中断 */ +#define FSDMMC_ERROR_INT_STATUS_CCRCE BIT(1) /* 命令 CRC 错误中断 */ +#define FSDMMC_ERROR_INT_STATUS_CTE BIT(0) /* 命令超时错误中断 */ +#define FSDMMC_ERROR_INT_STATUS_ALL_MASK (FSDMMC_ERROR_INT_STATUS_CNR | FSDMMC_ERROR_INT_STATUS_CIR | FSDMMC_ERROR_INT_STATUS_CCRCE | FSDMMC_ERROR_INT_STATUS_CTE) + +/** @name FSDMMC_BD_ISR_REG_OFFSET Register + */ +#define FSDMMC_BD_ISR_REG_DAIS BIT(15) /* DMA 错误中断*/ +#define FSDMMC_BD_ISR_REG_RESPE BIT(8) /* 读 SD 卡操作,AXI BR 通道完成中断*/ +#define FSDMMC_BD_ISR_REG_DATFRAX BIT(7) /* AXI 总线强制释放中断*/ +#define FSDMMC_BD_ISR_REG_NRCRC BIT(6) /* 无 CRC 响应中断*/ +#define FSDMMC_BD_ISR_REG_TRE BIT(5) /* CRC 响应错误中断*/ +#define FSDMMC_BD_ISR_REG_CMDE BIT(4) /* 命令响应错误中断*/ +#define FSDMMC_BD_ISR_REG_DTE BIT(3) /* 超时中断*/ +#define FSDMMC_BD_ISR_REG_TRS BIT(0) /* DMA 传输完成中断*/ + +/** @name FSDMMC_BD_STATUS_REG_OFFSET Register + */ +#define FSDMMC_BD_STATUS_MASK GENMASK(31, 0) /* BD 描述符 */ + +/** @name FSDMMC_STATUS_REG_OFFSET Register + */ +#define FSDMMC_STATUS_REG_DATMAST(x) (GENMASK(30, 27) & ((x) << 27)) /* data_master 状态机 */ +#define FSDMMC_STATUS_REG_CDIF BIT(26) /* 卡在位标志 */ +#define FSDMMC_STATUS_REG_CDRF BIT(25) /* 卡不在位标志 */ +#define FSDMMC_STATUS_REG_CLSL BIT(24) /* 命令闲信号 */ +#define FSDMMC_STATUS_REG_DLSL(x) (GENMASK(23, 20) & ((x) << 20)) /* 线信号 */ +#define FSDMMC_STATUS_REG_CDSL BIT(19) /* 卡检测管脚信号 */ +#define FSDMMC_STATUS_REG_CST(x) (GENMASK(15, 12) & ((x) << 12)) /* cmd_host state 状态机 */ +#define FSDMMC_STATUS_IDIE (0x1 << 12) +#define FSDMMC_STATUS_REG_CSM(x) (GENMASK(11, 7) & ((x) << 7)) +#define FSDMMC_STATUS_REG_DAT_AVA BIT(6) /* DAT_AVA 当前命令状态流程运转完 */ +#define FSDMMC_STATUS_REG_CRC_VALID BIT(5) +#define FSDMMC_STATUS_REG_CICMD BIT(0) /* RO 0x0 CMD 总线状态 */ +#define FSDMMC_STATUS_CMD_BUSY (0x0 << 0) +#define FSDMMC_STATUS_CMD_READY (0x1 << 0) + +/** @name FSDMMC_BLOCK_REG_OFFSET Register + */ +#define FSDMMC_BLOCK_MASK GENMASK(31, 0) + +/** @name FSDMMC_CMD_RESP_1_REG_OFFSET Register + */ +#define FSDMMC_CMD_RESP_1_MASK GENMASK(31, 0) + +/** @name FSDMMC_CMD_RESP_2_REG_OFFSET Register + */ +#define FSDMMC_CMD_RESP_2_MASK GENMASK(31, 0) + +/** @name FSDMMC_CMD_RESP_3_REG_OFFSET Register + */ +#define FSDMMC_CMD_RESP_3_MASK GENMASK(31, 0) + +/** @name FSDMMC_CMD_RESP_4_REG_OFFSET Register + */ +#define FSDMMC_CMD_RESP_4_MASK GENMASK(31, 0) + +#define FSDMMC_DEFAULT_DRV 1 +#define FSDMMC_DEFAULT_SAMP 5 +#define FSDMMC_SEN_CREFR_VAL (0x1 << 1) +#define FSDMMC_SEN_DEBNCE_VAL (0xB << 8) +#define FSDMMC_CMD_TIMEOUT 10000000 /* 1s */ +#define FSDMMC_DATA_TIMEOUT 40000000 /* 4s */ +#define FSDMMC_AXI_CONF1 0x1001 +#define FSDMMC_AXI_CONF2 0x12221222 +#define FSDMMC_TIMEOUT 5000000 /* timeout for retries */ +#define FSDMMC_BLOCK_SIZE 512 + +#define FSDMMC_DMA_ADDR_ALIGN 32 +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FSDMMC_READ_REG(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) +#define FSDMMC_WRITE_REG(addr, reg_offset, reg_value) FtOut32((addr) + (u32)(reg_offset), (u32)(reg_value)) +#define FSDMMC_SET_BIT(addr, reg_offset, bit) FtSetBit32((addr) + (u32)(reg_offset), (u32)(bit)) +#define FSDMMC_CLR_BIT(addr, reg_offset, bit) FtClearBit32((addr) + (u32)(reg_offset), (u32)(bit)) + +/* 检查卡检测管脚信号, 低电平表示卡在位 */ +static inline boolean FSdmmcCheckIfCardExists(uintptr base_addr) +{ + return (FSDMMC_STATUS_REG_CDSL != (FSDMMC_STATUS_REG_CDSL & FSDMMC_READ_REG(base_addr, FSDMMC_STATUS_REG_OFFSET))); +} + +/* 清除命令中断状态位 */ +static inline void FSdmmcClearNormalInterruptStatus(uintptr base_addr) +{ + FSDMMC_WRITE_REG(base_addr, FSDMMC_NORMAL_INT_STATUS_REG_OFFSET, (0x1)); +} + +/* 清除错误中断状态位 */ +static inline void FSdmmcClearErrorInterruptStatus(uintptr base_addr) +{ + FSDMMC_WRITE_REG(base_addr, FSDMMC_ERROR_INT_STATUS_REG_OFFSET, (0x1)); +} + +/* 清除DMA中断状态位 */ +static inline void FSdmmcClearBDInterruptStatus(uintptr base_addr) +{ + FSDMMC_WRITE_REG(base_addr, FSDMMC_BD_ISR_REG_OFFSET, (0x1)); +} + +/************************** Function Prototypes ******************************/ +/* 重置FSDMMC控制器 */ +FError FSdmmcReset(uintptr base_addr); + +/* 完成软复位 */ +FError FSdmmcSoftwareReset(uintptr base_addr, int retries); + +/* 设置FSDMMC的时钟 */ +FError FSdmmcSetCardClk(uintptr base_addr, u32 clk_freq_hz); + +/* 发送命令 */ +void FSdmmcSendPrivateCmd(uintptr base_addr, u32 cmd, u32 arg); + +/* 等待命令完成或者命令错误状态 */ +FError FSdmmcWaitStatus(uintptr base_addr, int retries); + +/* 等待数据传输完成或者传输错误状态 */ +FError FSdmmcWaitDMAStatus(uintptr base_addr, boolean read, int retries); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_intr.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_intr.c new file mode 100644 index 0000000000..5fa29e8737 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_intr.c @@ -0,0 +1,318 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:54:53 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + +/***************************** Include Files *********************************/ +#include "fassert.h" +#include "fio.h" +#include "fdebug.h" + +#include "fsdmmc_hw.h" +#include "fsdmmc.h" + +/************************** Constant Definitions *****************************/ +#define FSDMMC_DEBUG_TAG "FSDMMC-INTR" +#define FSDMMC_ERROR(format, ...) FT_DEBUG_PRINT_E(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_WARN(format, ...) FT_DEBUG_PRINT_W(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_INFO(format, ...) FT_DEBUG_PRINT_I(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSDMMC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSDMMC_DEBUG_TAG, format, ##__VA_ARGS__) + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +static void FSdmmcCallEvtHandler(FSdmmcEventHandler handler, FSdmmc *instance_p) +{ + if (NULL != handler) + { + handler((void *)instance_p); + } +} + +/************************** Function Prototypes ******************************/ +extern u32 FSdmmcMakeRawCmd(FSdmmcCmd *cmd_p); +extern void FSdmmcSendCmd(uintptr base_addr, FSdmmcCmd *cmd_p); +extern FError FSdmmcSendData(uintptr base_addr, boolean read, FSdmmcCmd *cmd_p); + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +/** + * @name: FSdmmcGetInterruptMask + * @msg: 获取FSDMMC的中断掩码 + * @return {u32} 中断掩码 + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {u32} intr_type FSDMMC中断类型, 参考FSDMMC_INTR_NUM + * @note FSDMMC控制器初始化后才能调用此函数 + */ +u32 FSdmmcGetInterruptMask(uintptr base_addr, u32 intr_type) +{ + u32 mask; + + switch (intr_type) + { + case FSDMMC_CMD_INTR: + mask = FSDMMC_READ_REG(base_addr, FSDMMC_NORMAL_INT_EN_REG_OFFSET); + break; + case FSDMMC_ERROR_INTR: + mask = FSDMMC_READ_REG(base_addr, FSDMMC_ERROR_INT_EN_REG_OFFSET); + break; + case FSDMMC_DMA_BD_INTR: + mask = FSDMMC_READ_REG(base_addr, FSDMMC_BD_ISR_EN_REG_OFFSET); + break; + default: + FASSERT(0); + break; + } + + return mask; +} + +/** + * @name: FSdmmcSetInterruptMask + * @msg: 设置FSDMMC的中断掩码 + * @param {uintptr} base_addr FSDMMC控制器基地址 + * @param {u32} intr_type FSDMMC中断类型, 参考FSDMMC_INTR_NUM + * @param {u32} mask 中断掩码 + * @param {boolean} enable TRUE:打开中断, FALSE:关闭中断 + * @note FSDMMC控制器初始化后才能调用此函数 + */ +void FSdmmcSetInterruptMask(uintptr base_addr, u32 intr_type, u32 mask, boolean enable) +{ + u32 old_mask = FSdmmcGetInterruptMask(base_addr, intr_type); + u32 new_mask = 0; + + if (TRUE == enable) + new_mask = old_mask | mask; + else + new_mask = old_mask & (~mask); + + switch (intr_type) + { + case FSDMMC_CMD_INTR: + FSDMMC_WRITE_REG(base_addr, FSDMMC_NORMAL_INT_EN_REG_OFFSET, new_mask); + break; + case FSDMMC_ERROR_INTR: + FSDMMC_WRITE_REG(base_addr, FSDMMC_ERROR_INT_EN_REG_OFFSET, new_mask); + break; + case FSDMMC_DMA_BD_INTR: + FSDMMC_WRITE_REG(base_addr, FSDMMC_BD_ISR_EN_REG_OFFSET, new_mask); + break; + default: + FASSERT(0); + break; + } + + return; +} + +/** + * @name: FSdmmcCmdInterrupHandler + * @msg: 命令中断响应函数 + * @return {*} 无 + * @param {s32} vector 中断向量号 + * @param {void} *param 中断响应输入参数 + * @note 此函数用于设置FSDMMC中断时注册,用户可以自定义一个中断响应函数替换此函数 + */ +void FSdmmcCmdInterrupHandler(s32 vector, void *param) +{ + FASSERT(param); + u32 status; + FSdmmc *instance_p = (FSdmmc *)param; + uintptr base_addr = instance_p->config.base_addr; + + /* clear interrupts */ + status = FSDMMC_READ_REG(base_addr, FSDMMC_NORMAL_INT_STATUS_REG_OFFSET); + + if (status & FSDMMC_NORMAL_INT_STATUS_CR) /* 卡移除中断 */ + { + FSdmmcCallEvtHandler(instance_p->evt_handler[FSDMMC_EVT_CARD_REMOVED], instance_p); + } + + if (status & FSDMMC_NORMAL_INT_STATUS_CC) /* 命令完成中断 */ + { + FSdmmcCallEvtHandler(instance_p->evt_handler[FSDMMC_EVT_CMD_DONE], instance_p); + } + + if (status & FSDMMC_NORMAL_INT_STATUS_EI) /* 命令错误中断 */ + { + FSdmmcCallEvtHandler(instance_p->evt_handler[FSDMMC_EVT_CMD_ERROR], instance_p); + } + + FSdmmcClearNormalInterruptStatus(base_addr); +} + +/** + * @name: FSdmmcDmaInterrupHandler + * @msg: DMA中断响应函数 + * @return {*} + * @param {s32} vector 中断向量号 + * @param {void} *param 中断响应输入参数 + * @note 此函数用于设置FSDMMC中断时注册,用户可以自定义一个中断响应函数替换此函数 + */ +void FSdmmcDmaInterrupHandler(s32 vector, void *param) +{ + FASSERT(param); + u32 status; + FSdmmc *instance_p = (FSdmmc *)param; + uintptr base_addr = instance_p->config.base_addr; + + /* clear interrupts */ + status = FSDMMC_READ_REG(base_addr, FSDMMC_BD_ISR_REG_OFFSET); + + if (status & FSDMMC_BD_ISR_REG_DAIS) /* DMA 错误中断 */ + { + FSdmmcCallEvtHandler(instance_p->evt_handler[FSDMMC_EVT_DATA_ERROR], instance_p); + } + + if (status & FSDMMC_BD_ISR_REG_RESPE) /* 读 SD 卡操作,AXI BR 通道完成中断 */ + { + FSdmmcCallEvtHandler(instance_p->evt_handler[FSDMMC_EVT_DATA_READ_DONE], instance_p); + } + + if (status & FSDMMC_BD_ISR_REG_DATFRAX) /* AXI 总线强制释放中断*/ + { + FSDMMC_ERROR("FSDMMC_BD_ISR_REG_DATFRAX"); + } + + if (status & FSDMMC_BD_ISR_REG_NRCRC) /* 无 CRC 响应中断*/ + { + FSDMMC_ERROR("FSDMMC_BD_ISR_REG_NRCRC"); + } + + if (status & FSDMMC_BD_ISR_REG_TRE) /* CRC 响应错误中断*/ + { + FSDMMC_ERROR("FSDMMC_BD_ISR_REG_TRE"); + } + + if (status & FSDMMC_BD_ISR_REG_CMDE) /* 命令响应错误中断*/ + { + FSDMMC_ERROR("FSDMMC_BD_ISR_REG_CMDE"); + } + + if (status & FSDMMC_BD_ISR_REG_DTE) /* 超时中断*/ + { + FSDMMC_ERROR("FSDMMC_BD_ISR_REG_DTE"); + } + + if (status & FSDMMC_BD_ISR_REG_TRS) /* DMA 传输完成中断*/ + { + FSdmmcCallEvtHandler(instance_p->evt_handler[FSDMMC_EVT_DATA_WRITE_DONE], instance_p); + } + + FSdmmcClearBDInterruptStatus(base_addr); +} + +/** + * @name: FSdmmcErrInterrupHandler + * @msg: 错误中断响应函数 + * @return {*} + * @param {s32} vector 中断向量号 + * @param {void} *param 中断响应输入参数 + * @note 此函数用于设置FSDMMC中断时注册,用户可以自定义一个中断响应函数替换此函数 + */ +void FSdmmcErrInterrupHandler(s32 vector, void *param) +{ + FASSERT(param); + u32 status; + FSdmmc *instance_p = (FSdmmc *)param; + uintptr base_addr = instance_p->config.base_addr; + + status = FSDMMC_READ_REG(base_addr, FSDMMC_ERROR_INT_STATUS_REG_OFFSET); + + if (status & FSDMMC_ERROR_INT_STATUS_CNR) /* 命令响应错误中断 */ + { + FSdmmcCallEvtHandler(instance_p->evt_handler[FSDMMC_EVT_CMD_RESP_ERROR], instance_p); + } + + if (status & FSDMMC_ERROR_INT_STATUS_CIR) /* 命令索引错误中断 */ + { + FSDMMC_ERROR("FSDMMC_ERROR_INT_STATUS_CIR"); + } + + if (status & FSDMMC_ERROR_INT_STATUS_CCRCE) /* 命令 CRC 错误中断 */ + { + FSDMMC_ERROR("FSDMMC_ERROR_INT_STATUS_CCRCE"); + } + + if (status & FSDMMC_ERROR_INT_STATUS_CTE) /* 命令超时错误中断 */ + { + FSDMMC_ERROR("FSDMMC_ERROR_INT_STATUS_CTE"); + } + + /* clear command error status */ + FSdmmcClearErrorInterruptStatus(base_addr); +} + +/** + * @name: FSdmmcRegisterInterruptHandler + * @msg: 注册中断事件响应函数 + * @return {*} + * @param {FSdmmc} *instance_p FSDMMC驱动控制数据 + * @param {u32} event FSDMMC中断事件类型,参考FSDMMC_EVT_NUM + * @param {FSdmmcEventHandler} handler, FSDMMC中断事件响应函数 + * @note 此函数用于设置FSDMMC中断时注册,被注册的函数被FSdmmcCmdInterrupHandler、FSdmmcErrInterrupHandler + * 和FSdmmcDmaInterrupHandler调用 + */ +void FSdmmcRegisterInterruptHandler(FSdmmc *instance_p, u32 event, FSdmmcEventHandler handler) +{ + FASSERT(instance_p); + instance_p->evt_handler[event] = handler; +} + +/** + * @name: FSdmmcInterruptTransfer + * @msg: 通过FSDMMC中断方式发送/接收数据和命令 + * @return {FError} 驱动初始化的错误码信息,FSDMMC_SUCCESS 表示发送/接收成功,其它返回值表示发送/接收失败 + * @param {FSdmmc} *instance_p FSDMMC驱动控制数据 + * @param {FSdmmcCmd} *cmd_data_p FSDMMC数据和命令 + * @note FSDMMC控制器初始化后才能调用此函数,使用前需要确保FSDMMC中断设置完成 + */ +FError FSdmmcInterruptTransfer(FSdmmc *instance_p, FSdmmcCmd *cmd_data_p) +{ + FASSERT(instance_p && cmd_data_p); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FSDMMC_SUCCESS; + + if (FALSE == FSdmmcCheckIfCardExists(base_addr)) + { + FSDMMC_ERROR("card not found !!! fsdio ctrl base 0x%x", base_addr); + return FSDMMC_ERR_CARD_NO_FOUND; + } + + if (cmd_data_p->flag & FSDMMC_CMD_FLAG_EXP_DATA) + { + /* transfer data */ + FSDMMC_INFO("====DATA [%d] START: buf: %p=====", cmd_data_p->cmdidx, cmd_data_p->data_p); + ret = FSdmmcSendData(base_addr, + (FSDMMC_CMD_FLAG_READ_DATA == (cmd_data_p->flag & FSDMMC_CMD_FLAG_READ_DATA)), + cmd_data_p); + } + else + { + /* transfer command */ + FSDMMC_INFO("=====CMD [%d] START=====", cmd_data_p->cmdidx); + FSdmmcSendCmd(base_addr, cmd_data_p); + } + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_sinit.c b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_sinit.c new file mode 100644 index 0000000000..96d040abe1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/mmc/fsdmmc/fsdmmc_sinit.c @@ -0,0 +1,69 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsdmmc_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:55:09 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021/12/2 init + */ + + +/* - This file contains the implementation of driver's static initialization functionality. +- 驱动静态初始化 */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" + +#include "fsdmmc.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +extern const FSdmmcConfig FSDMMC_CONFIG_TBL[FSDMMC_HOST_INSTANCE_NUM]; + +/************************** Function Prototypes ******************************/ +/** + * @name: FSdmmcLookupConfig + * @msg: 获取FSDMMC控制器默认配置 + * @return {const FSdmmcConfig *} FSDMMC默认配置,返回NULL如果找不到默认配置 + * @param {u32} instance_id 驱动控制器ID + * @note instance_id从0开始,取决于FSDMMC控制器的个数 + */ +const FSdmmcConfig *FSdmmcLookupConfig(u32 instance_id) +{ + const FSdmmcConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FSDMMC_HOST_INSTANCE_NUM; index++) + { + if (FSDMMC_CONFIG_TBL[index].instance_id == instance_id) + { + ptr = &FSDMMC_CONFIG_TBL[index]; + break; + } + } + + return (const FSdmmcConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/nand/Kconfig b/bsp/phytium/libraries/standalone/drivers/nand/Kconfig new file mode 100644 index 0000000000..4638b049f9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/Kconfig @@ -0,0 +1,34 @@ + +menu "NAND Configuration" + menu "FNAND ip config" + choice + prompt "choice fnand driver" + config ENABLE_FNAND + bool + prompt "Use FNAND" + + if ENABLE_FNAND + config FNAND_COMMON_DEBUG_EN + bool + prompt "Use FNAND common mode debug" + + config FNAND_DMA_DEBUG_EN + bool + prompt "Use FNAND DMA mode debug" + + config FNAND_TOGGLE_DEBUG_EN + bool + prompt "Use FNAND toggle mode debug" + + config FNAND_ONFI_DEBUG_EN + bool + prompt "Use FNAND onfi mode debug" + + endif + + endchoice + endmenu + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand.c new file mode 100644 index 0000000000..5396ff2600 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand.c @@ -0,0 +1,567 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand.c + * Date: 2022-05-10 14:53:42 + * LastEditTime: 2022-05-10 08:56:27 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "fnand.h" +#include "fnand_hw.h" +#include +#include +#include "fnand_id.h" +#include "fnand_common_cmd.h" +#include "fdebug.h" +#define FNAND_DEBUG_TAG "FNAND" +#define FNAND_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_DEBUG_TAG, format, ##__VA_ARGS__) + +extern void FNandHwInit(uintptr_t base_address, FNandInterMode inter_mode); +extern void FNandHwReset(uintptr_t base_address); +extern void FNandEnable(uintptr_t base_address); +extern FError FNandToggleInit(FNand *instance_p, u32 chip_addr); +extern FError FNandOnfiInit(FNand *instance_p, u32 chip_addr); +extern FError FNandTimingInterfaceUpdate(FNand *instance_p, u32 chip_addr); +extern void FNandIsrEnable(FNand *instance_p, u32 int_mask); + + +/** + * @name: FNandScan + * @msg: Nand scanning + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @return {FT_SUCCESS} Scan nand is ok + */ +FError FNandScan(FNand *instance_p) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + return FNandDetect(instance_p); + +} + +u32 FNandCheckBusy(FNand *instance_p) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FNandConfig *config_p; + config_p = &instance_p->config; + + return FNAND_READREG(config_p->base_address, FNAND_STATE_OFFSET) & FNAND_STATE_BUSY_OFFSET; +} + + +FError FNandSendCmd(FNand *instance_p, struct FNandDmaDescriptor *descriptor_p, FNandOperationType isr_type) +{ + FNandConfig *config_p; + u32 timeout_cnt = 0; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(isr_type < FNAND_TYPE_NUM); + + config_p = &instance_p->config; + + FNandHwReset(config_p->base_address); + + if (0 != FNandCheckBusy(instance_p)) + { + FNAND_DEBUG_E("Nand is busy"); + return FNAND_IS_BUSY; + } + + /* write dma addr to register */ + FNAND_WRITEREG(config_p->base_address, FNAND_MADDR0_OFFSET, ((uintptr)descriptor_p) & FNAND_MADDR0_DT_LOW_ADDR_MASK); + +#ifdef __aarch64__ + /* 将高位地址填入寄存器 */ + FNAND_CLEARBIT(config_p->base_address, FNAND_MADDR1_OFFSET, FNAND_MADDR1_DT_HIGH_8BITADDR_MASK); + FNAND_SETBIT(config_p->base_address, FNAND_MADDR1_OFFSET, ((uintptr)descriptor_p >> 32) & FNAND_MADDR1_DT_HIGH_8BITADDR_MASK); +#else + FNAND_CLEARBIT(config_p->base_address, FNAND_MADDR1_OFFSET, FNAND_MADDR1_DT_HIGH_8BITADDR_MASK); +#endif + /* 中断模式操作 */ + if (instance_p->work_mode == FNAND_WORK_MODE_ISR) + { + if (isr_type == FNAND_CMD_TYPE) + { + FNandIsrEnable(instance_p, FNAND_INTRMASK_CMD_FINISH_MASK); + } + else if (isr_type == FNAND_WRITE_PAGE_TYPE) + { + FNandIsrEnable(instance_p, FNAND_INTRMASK_PGFINISH_MASK); + } + else if (isr_type == FNAND_READ_PAGE_TYPE) + { + FNandIsrEnable(instance_p, FNAND_INTRMASK_DMA_PGFINISH_MASK); + } + else if (isr_type == FNAND_WAIT_ECC_TYPE) + { + FNandIsrEnable(instance_p, FNAND_INTRMASK_ECC_FINISH_MASK); + } + } + + FNAND_SETBIT(config_p->base_address, FNAND_MADDR1_OFFSET, FNAND_MADDR1_DMA_EN_MASK); + + if (instance_p->work_mode == FNAND_WORK_MODE_ISR && (instance_p->wait_irq_fun_p != NULL)) + { + if (instance_p->wait_irq_fun_p) + { + if (instance_p->wait_irq_fun_p(instance_p->wait_args) != FT_SUCCESS) + { + FNAND_DEBUG_E("wait_irq_fun_p is failed"); + return FNAND_ERR_IRQ_OP_FAILED; + } + } + else + { + FNAND_DEBUG_E("The lack of wait_irq_fun_p"); + FNAND_WRITEREG(config_p->base_address, FNAND_INTRMASK_OFFSET, FNAND_INTRMASK_ALL_INT_MASK); + return FNAND_ERR_IRQ_LACK_OF_CALLBACK; + } + + return FT_SUCCESS ; + } + else + { + if (isr_type == FNAND_CMD_TYPE) + { + while (0 == (FNAND_READREG(config_p->base_address, FNAND_STATE_OFFSET) & FNAND_STATE_CMD_PGFINISH_OFFSET)) + { + if (timeout_cnt++ >= 0xffffff) + { + FNAND_DEBUG_E("FNAND_CMD_TYPE is send timeout"); + return FNAND_OP_TIMEOUT; + } + } + } + else if (isr_type == FNAND_WRITE_PAGE_TYPE) + { + while (0 == (FNAND_READREG(config_p->base_address, FNAND_STATE_OFFSET) & FNAND_STATE_PG_PGFINISH_OFFSET)) + { + if (timeout_cnt++ >= 0xffffff) + { + FNAND_DEBUG_E("FNAND_CMD_TYPE is send timeout"); + return FNAND_OP_TIMEOUT; + } + } + } + else if (isr_type == FNAND_READ_PAGE_TYPE) + { + while (0 == (FNAND_READREG(config_p->base_address, FNAND_STATE_OFFSET) & FNAND_STATE_DMA_PGFINISH_OFFSET)) + { + if (timeout_cnt++ >= 0xffffff) + { + FNAND_DEBUG_E("FNAND_CMD_TYPE is send timeout"); + return FNAND_OP_TIMEOUT; + } + } + } + else if (isr_type == FNAND_WAIT_ECC_TYPE) + { + while (0 == (FNAND_READREG(config_p->base_address, FNAND_STATE_OFFSET) & FNAND_STATE_ECC_FINISH_OFFSET)) + { + if (timeout_cnt++ >= 0xffffff) + { + FNAND_DEBUG_E("FNAND_CMD_TYPE is send timeout"); + return FNAND_OP_TIMEOUT; + } + } + } + } + + return FT_SUCCESS; +} + + +/** + * @name: FNandOperationWaitIrqRegister + * @msg: When nand is sent in interrupt mode, the action that waits while the operation completes + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {FNandOperationWaitIrqCallback} wait_irq_fun_p , When the user adds this function, return FT_SUCCESS reports success, otherwise failure + * @param {void} *wait_args + * @return {*} + */ +void FNandOperationWaitIrqRegister(FNand *instance_p, FNandOperationWaitIrqCallback wait_irq_fun_p, void *wait_args) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + instance_p->wait_irq_fun_p = wait_irq_fun_p; + instance_p->wait_args = wait_args; +} + + + +/** + * @name: FNandCfgInitialize + * @msg: Initialize the NAND controller + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {FNandConfig} * points to the FNand device configuration structure. + * @return {FError} FT_SUCCESS if successful + * @note: + */ +FError FNandCfgInitialize(FNand *instance_p, + FNandConfig *config_p) +{ + u32 i; + FError ret; + /* Assert arguments */ + FASSERT(instance_p != NULL); + FASSERT(config_p != NULL); + + /* Clear instance memory and make copy of configuration */ + memset(instance_p, 0, sizeof(FNand)); + instance_p->config = *config_p; + instance_p->is_ready = FT_COMPONENT_IS_READY; + + /* lsd config */ + FNAND_CLEARBIT(FLSD_CONFIG_BASE, 0xc0, 1); + + instance_p->work_mode = FNAND_WORK_MODE_ISR ; /* 默认采用中断模式 */ + for (i = 0; i < FNAND_CONNECT_MAX_NUM; i++) + { + instance_p->inter_mode[i] = FNAND_ASYN_SDR; /* 初始化阶段以异步模式启动 */ + instance_p->timing_mode[i] = FNAND_TIMING_MODE0 ; + /* 初始化时序配置 */ + ret = FNandTimingInterfaceUpdate(instance_p, i); + if (ret != FT_SUCCESS) + { + FNAND_DEBUG_E("%s, FNandTimingInterfaceUpdate is error", __func__); + return ret; + } + } + + FNandHwInit(instance_p->config.base_address, instance_p->inter_mode[0]); + FNandHwReset(instance_p->config.base_address); + + /* init ecc strength */ + FNAND_CLEARBIT(instance_p->config.base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_CORRECT_MAKE(7UL)); /* clear all ecc_correct */ + if (instance_p->config.ecc_strength == 0x8) + { + FNAND_SETBIT(instance_p->config.base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_CORRECT_MAKE(7UL)); + } + else if (instance_p->config.ecc_strength == 0x4) + { + FNAND_SETBIT(instance_p->config.base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_CORRECT_MAKE(3UL)); + } + else if (instance_p->config.ecc_strength == 0x2) + { + FNAND_SETBIT(instance_p->config.base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_CORRECT_MAKE(1UL)); + } + else + { + FNAND_SETBIT(instance_p->config.base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_CORRECT_MAKE(0UL)); + } + + FNandEnable(instance_p->config.base_address); + + /* init bbm */ + FNandInitBbtDesc(instance_p); + return (FT_SUCCESS); +} + + +/** + * @name: FNandWritePage + * @msg: Write operations one page at a time, including writing page data and spare data + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} page_addr is the address to which the page needs to be written + * @param {u8} *buffer is page writes a pointer to the buffer + * @param {u32} page_copy_offset is the offset of the page writing , Buffer write data to 0 + page_copy_offset + * @param {u32} length is page data write length + * @param {u8} *oob_buffer is the data buffer pointer needs to be written to the spare space + * @param {u32} oob_copy_offset is the offset of the spare space writing , Buffer write data to page length + oob_copy_offset + * @param {u32} oob_length is the length to be written to the spare space + * @param {u32} chip_addr chip address + * @return {FError} FT_SUCCESS ,write page is successful + */ +FError FNandWritePage(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + FASSERT(instance_p->write_hw_ecc_p); + + FNandOpData op_data = + { + .page_addr = page_addr, + .page_buf = NULL, /* page 数据缓存空间 */ + .page_offset = 0, /* 从offset开始拷贝页数据 */ + .page_length = 0, /* 从offset开始拷贝页数据的长度 */ + .obb_required = 0, /* obb 是否读取的标志位,1 需要操作oob 区域 */ + .oob_buf = NULL, /* obb 数据缓存空间 */ + .oob_offset = 0, /* 从offset开始拷贝页数据 */ + .oob_length = 0, /* 从offset开始拷贝页数据的长度 */ + .chip_addr = chip_addr, /* 芯片地址 */ + }; + + if (buffer && (length > 0)) + { + op_data.page_buf = buffer; + op_data.page_length = length; + op_data.page_offset = page_copy_offset; + } + + if (oob_buffer && (oob_length > 0)) + { + op_data.obb_required = 1; + op_data.oob_buf = oob_buffer; + op_data.oob_length = oob_length; + op_data.oob_offset = oob_copy_offset; + } + + return instance_p->write_hw_ecc_p(instance_p, &op_data); +} + +/** + * @name: FNandWritePage + * @msg: Write operations one page at a time, including writing page data and spare data ,without hw ecc + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} page_addr is the address to which the page needs to be written + * @param {u8} *buffer is page writes a pointer to the buffer + * @param {u32} page_copy_offset is the offset of the page writing , Buffer write data to 0 + page_copy_offset + * @param {u32} length is page data write length + * @param {u8} *oob_buffer is the data buffer pointer needs to be written to the spare space + * @param {u32} oob_copy_offset is the offset of the spare space writing , Buffer write data to page length + oob_copy_offset + * @param {u32} oob_length is the length to be written to the spare space + * @param {u32} chip_addr chip address + * @return {FError} FT_SUCCESS ,write page is successful + */ +FError FNandWritePageRaw(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + FASSERT(instance_p->write_hw_ecc_p); + + FNandOpData op_data = + { + .page_addr = page_addr, + .page_buf = NULL, /* page 数据缓存空间 */ + .page_offset = 0, /* 从offset开始拷贝页数据 */ + .page_length = 0, /* 从offset开始拷贝页数据的长度 */ + .obb_required = 0, /* obb 是否读取的标志位,1 需要操作oob 区域 */ + .oob_buf = NULL, /* obb 数据缓存空间 */ + .oob_offset = 0, /* 从offset开始拷贝页数据 */ + .oob_length = 0, /* 从offset开始拷贝页数据的长度 */ + .chip_addr = chip_addr, /* 芯片地址 */ + }; + + if (buffer && (length > 0)) + { + op_data.page_buf = buffer; + op_data.page_length = length; + op_data.page_offset = page_copy_offset; + } + + if (oob_buffer && (oob_length > 0)) + { + op_data.obb_required = 1; + op_data.oob_buf = oob_buffer; + op_data.oob_length = oob_length; + op_data.oob_offset = oob_copy_offset; + } + + return instance_p->write_p(instance_p, &op_data); +} + +/** + * @name: FNandReadPage + * @msg: Read operations one page at a time, including reading page data and spare space data + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} page_addr is the address to which the page needs to be readed + * @param {u8} *buffer is the buffer used by the user to read page data + * @param {u32} page_copy_offset is the offset of the page reading , Buffer read data from 0 + page_copy_offset of per page + * @param {u32} length is page data read length + * @param {u8} *oob_buffer is buffer that read data from the spare space + * @param {u32} oob_copy_offset is the offset of the spare space reading , Buffer reads data from page length + oob_copy_offset + * @param {u32} oob_length is the length to be written to the spare space + * @param {u32} chip_addr chip address + * @return {FError} FT_SUCCESS is read successful + */ +FError FNandReadPage(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + FASSERT(instance_p->read_hw_ecc_p); + + FNandOpData op_data = + { + .page_addr = page_addr, + .page_buf = NULL, /* page 数据缓存空间 */ + .page_offset = 0, /* 从offset开始拷贝页数据 */ + .page_length = 0, /* 从offset开始拷贝页数据的长度 */ + .obb_required = 0, /* obb 是否读取的标志位,1 需要操作oob 区域 */ + .oob_buf = NULL, /* obb 数据缓存空间 */ + .oob_offset = 0, /* 从offset开始拷贝页数据 */ + .oob_length = 0, /* 从offset开始拷贝页数据的长度 */ + .chip_addr = chip_addr, /* 芯片地址 */ + }; + + /* clear buffer */ + if (buffer && (length > 0)) + { + op_data.page_buf = buffer; + op_data.page_length = length; + op_data.page_offset = page_copy_offset; + } + + if (oob_buffer && (oob_length > 0)) + { + op_data.obb_required = 1; + op_data.oob_buf = oob_buffer; + op_data.oob_length = oob_length; + op_data.oob_offset = oob_copy_offset; + } + + return instance_p->read_hw_ecc_p(instance_p, &op_data); +} + +FError FNandReadPageRaw(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + FASSERT(instance_p->read_hw_ecc_p); + + FNandOpData op_data = + { + .page_addr = page_addr, + .page_buf = NULL, /* page 数据缓存空间 */ + .page_offset = 0, /* 从offset开始拷贝页数据 */ + .page_length = 0, /* 从offset开始拷贝页数据的长度 */ + .obb_required = 0, /* obb 是否读取的标志位,1 需要操作oob 区域 */ + .oob_buf = NULL, /* obb 数据缓存空间 */ + .oob_offset = 0, /* 从offset开始拷贝页数据 */ + .oob_length = 0, /* 从offset开始拷贝页数据的长度 */ + .chip_addr = chip_addr, /* 芯片地址 */ + }; + + /* clear buffer */ + if (buffer && (length > 0)) + { + op_data.page_buf = buffer; + op_data.page_length = length; + op_data.page_offset = page_copy_offset; + } + + if (oob_buffer && (oob_length > 0)) + { + op_data.obb_required = 1; + op_data.oob_buf = oob_buffer; + op_data.oob_length = oob_length; + op_data.oob_offset = oob_copy_offset; + } + + return instance_p->read_p(instance_p, &op_data); +} + +/** + * @name: FNandEraseBlock + * @msg: erase block data + * @note: 擦除之后增加read status 命令进行检查。(70h) + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} block is block number + * @param {u32} chip_addr is chip address + * @return {FError} FT_SUCCESS is erase is successful + */ +FError FNandEraseBlock(FNand *instance_p, u32 block, u32 chip_addr) +{ + u32 page_address; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + page_address = block * instance_p->nand_geometry[chip_addr].pages_per_block; + return instance_p->erase_p(instance_p, page_address, chip_addr); +} + + + +/** + * @name: FNandReadPageOOb + * @msg: Read spare space fo per page + * @note: + * @param {FNand} *instance_p is the instance pointer + * @param {u32} page_addr is the Row Address of the spare space needs to be read + * @param {u8} *oob_buffer is the buffer used by the user to read spare space data + * @param {u32} oob_copy_offset is the offset of the spare space reading , Buffer reads data from page length + page_copy_offset + * @param {u32} oob_length is the length of data retrieved from spare space + * @param {u32} chip_addr is chip address + * @return {FError} FT_SUCCESS is read successful + */ +FError FNandReadPageOOb(FNand *instance_p, u32 page_addr, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + + FNandOpData op_data = + { + .page_addr = page_addr, + .page_buf = NULL, /* page 数据缓存空间 */ + .page_offset = 0, /* 从offset开始拷贝页数据 */ + .page_length = 0, /* 从offset开始拷贝页数据的长度 */ + .obb_required = 1, /* obb 是否读取的标志位,1 需要操作oob 区域 */ + .oob_buf = oob_buffer, /* obb 数据缓存空间 */ + .oob_offset = oob_copy_offset, /* 从offset开始拷贝页数据 */ + .oob_length = oob_length, /* 从offset开始拷贝页数据的长度 */ + .chip_addr = chip_addr, /* 芯片地址 */ + }; + + return instance_p->read_oob_p(instance_p, &op_data); +} + +/** + * @name: FNandWritePageOOb + * @msg: write data to the spare space + * @note: + * @param {FNand} *instance_p is the instance pointer + * @param {u32} page_addr is the Row Address of the spare space needs to be write + * @param {u8} *oob_buffer is buffer that writes data to the spare space + * @param {u32} page_copy_offset is the offset of the spare space writing , Buffer write data to page length + page_copy_offset + * @param {u32} oob_length is the length to be written to the spare space + * @param {u32} chip_addr is chip address + * @return {FError} FT_SUCCESS is write successful + */ +FError FNandWritePageOOb(FNand *instance_p, u32 page_addr, u8 *oob_buffer, u32 page_copy_offset, u32 oob_length, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + + FNandOpData op_data = + { + .page_addr = page_addr, + .page_buf = NULL, /* page 数据缓存空间 */ + .page_offset = 0, /* 从offset开始拷贝页数据 */ + .page_length = 0, /* 从offset开始拷贝页数据的长度 */ + .obb_required = 1, /* obb 是否读取的标志位,1 需要操作oob 区域 */ + .oob_buf = oob_buffer, /* obb 数据缓存空间 */ + .oob_offset = page_copy_offset, /* 从offset开始拷贝页数据 */ + .oob_length = oob_length, /* 从offset开始拷贝页数据的长度 */ + .chip_addr = chip_addr, /* 芯片地址 */ + }; + + return instance_p->write_oob_p(instance_p, &op_data); +} diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand.h new file mode 100644 index 0000000000..2ded2317a5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand.h @@ -0,0 +1,302 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand.h + * Date: 2022-05-07 15:40:42 + * LastEditTime: 2022-05-07 15:40:42 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#ifndef DRIVERS_NAND_FNAND_H +#define DRIVERS_NAND_FNAND_H + +#ifdef __cplusplus +extern "C" +{ +#endif + + +#include "ftypes.h" +#include "fassert.h" +#include "fnand_dma.h" +#include "fnand_timing.h" +#include "fparameters.h" +#include "fkernel.h" + +#define FNAND_ERR_OPERATION FT_CODE_ERR(ErrModBsp, ErrNand, 0x1u) +#define FNAND_ERR_INVAILD_PARAMETER FT_CODE_ERR(ErrModBsp, ErrNand, 0x2u) +#define FNAND_IS_BUSY FT_CODE_ERR(ErrModBsp, ErrNand, 0x3u) +#define FNAND_OP_TIMEOUT FT_CODE_ERR(ErrModBsp, ErrNand, 0x4u) +#define FNAND_VALUE_ERROR FT_CODE_ERR(ErrModBsp, ErrNand, 0x7u) +#define FNAND_VALUE_FAILURE FT_CODE_ERR(ErrModBsp, ErrNand, 0x8u) +#define FNAND_NOT_FET_TOGGLE_MODE FT_CODE_ERR(ErrModBsp, ErrNand, 0xCu) +#define FNAND_ERR_READ_ECC FT_CODE_ERR(ErrModBsp, ErrNand, 0xBu) +#define FNAND_ERR_IRQ_LACK_OF_CALLBACK FT_CODE_ERR(ErrModBsp, ErrNand, 0xCu) +#define FNAND_ERR_IRQ_OP_FAILED FT_CODE_ERR(ErrModBsp, ErrNand, 0xdu) +#define FNAND_ERR_NOT_MATCH FT_CODE_ERR(ErrModBsp, ErrNand, 0xEu) + + + +#define FNAND_MAX_BLOCKS 32768 /* Max number of Blocks */ +#define FNAND_MAX_PAGE_SIZE 16384 /* Max page size of NAND \ + flash */ +#define FNAND_MAX_SPARE_SIZE 1024 /* Max spare bytes of a NAND \ + flash page */ + + +/* dma */ +#define FNAND_DMA_MAX_LENGTH (32*1024) + +/* options */ +/* These constants are used as option to FNandSetOption() */ +#define FNAND_OPS_INTER_MODE_SELECT 1U /* */ + + +/* These constants are used as parameters to FNandSetIsrHandler() */ +#define FNAND_WORK_MODE_POLL 0U +#define FNAND_WORK_MODE_ISR 1U + + +/* NAND Flash Interface */ + +#define FNAND_ONFI_MODE 0U +#define FNAND_TOGGLE_MODE 1U + + +typedef enum +{ + FNAND_ASYNC_TIM_INT_MODE0 = 0, + FNAND_ASYNC_TIM_INT_MODE1, + FNAND_ASYNC_TIM_INT_MODE2, + FNAND_ASYNC_TIM_INT_MODE3, + FNAND_ASYNC_TIM_INT_MODE4, +} FNandAsyncTimint; + +typedef enum +{ + FNAND_CMD_TYPE = 0, /* 采用cmd 类型的操作类型 */ + FNAND_WRITE_PAGE_TYPE, /* PAGE program 操作 */ + FNAND_READ_PAGE_TYPE, /* PAGE read 操作 */ + FNAND_WAIT_ECC_TYPE, /* Waiting ECC FINISH 操作 */ + FNAND_TYPE_NUM +} FNandOperationType; + +/* Irq Callback events */ +typedef enum +{ + FNAND_IRQ_BUSY_EVENT = 0,/* nandflash控制器忙状态中断状态位 */ + FNAND_IRQ_DMA_BUSY_EVENT, /* dma控制器忙状态中断状态位 */ + FNAND_IRQ_DMA_PGFINISH_EVENT, /* dma页操作完成中断状态位 */ + FNAND_IRQ_DMA_FINISH_EVENT, /* dma操作完成中断完成中断状态位 */ + FNAND_IRQ_FIFO_EMP_EVENT, /* fifo为空中断状态位 */ + FNAND_IRQ_FIFO_FULL_EVENT, /* fifo为满中断状态位 */ + FNAND_IRQ_FIFO_TIMEOUT_EVENT, /* fifo超时中断状态位 */ + FNAND_IRQ_CMD_FINISH_EVENT, /* nand接口命令完成中断状态位 */ + FNAND_IRQ_PGFINISH_EVENT, /* nand接口页操作完成中断状态位 */ + FNAND_IRQ_RE_EVENT, /* re_n门控打开中断状态位 */ + FNAND_IRQ_DQS_EVENT, /* dqs门控打开中断状态位 */ + FNAND_IRQ_RB_EVENT, /* rb_n信号busy中断状态位 */ + FNAND_IRQ_ECC_FINISH_EVENT, /* ecc完成中断状态蔽位 */ + FNAND_IRQ_ECC_ERR_EVENT /* ecc正确中断状态蔽位 */ +} FNAND_CALL_BACK_EVENT; + +typedef struct +{ + u32 bytes_per_page; /* Bytes per page */ + u32 spare_bytes_per_page; /* Size of spare area in bytes */ + u32 pages_per_block; /* Pages per block */ + u32 blocks_per_lun; /* Bocks per LUN */ + u8 num_lun; /* Total number of LUN */ + u8 flash_width; /* Data width of flash device */ + u64 num_pages; /* Total number of pages in device */ + u64 num_blocks; /* Total number of blocks in device */ + u64 block_size; /* Size of a block in bytes */ + u64 device_size; /* Total device size in bytes */ + u8 rowaddr_cycles; /* Row address cycles */ + u8 coladdr_cycles; /* Column address cycles */ + u32 hw_ecc_steps; /* number of ECC steps per page */ + u32 hw_ecc_length; /* 产生硬件ecc校验参数的个数 */ + u32 ecc_offset; /* spare_bytes_per_page - hw_ecc_length = obb存放硬件ecc校验参数页位置的偏移 */ + u32 ecc_step_size; /* 进行读写操作时,单次ecc 的步骤的跨度 */ +} FNandNandGeometry; + +typedef enum +{ + FNAND_ASYN_SDR = 0, /* ONFI & Toggle async */ + FNAND_ONFI_DDR = 1, /* ONFI sync */ + FNAND_TOG_ASYN_DDR = 2 /* Toggle async */ +} FNandInterMode; + +typedef enum +{ + FNAND_TIMING_MODE0 = 0, + FNAND_TIMING_MODE1 = 1, + FNAND_TIMING_MODE2 = 2, + FNAND_TIMING_MODE3 = 3, + FNAND_TIMING_MODE4 = 4, + FNAND_TIMING_MODE5 = 5, +} FNandTimingMode; + +typedef struct +{ + u32 instance_id; /* Id of device*/ + u32 irq_num; /* Irq number */ + volatile uintptr_t base_address; + u32 ecc_strength; /* 每次ecc 步骤纠正的位数 */ + u32 ecc_step_size; /* 进行读写操作时,单次ecc 的步骤的跨度 */ +} FNandConfig; + +/** + * Bad block pattern + */ +typedef struct +{ + u32 options; /**< Options to search the bad block pattern */ + u32 offset; /**< Offset to search for specified pattern */ + u32 length; /**< Number of bytes to check the pattern */ + u8 pattern[2]; /**< Pattern format to search for */ +} FNandBadBlockPattern; + + +typedef struct +{ + u32 page_addr; + u8 *page_buf; /* page 数据缓存空间 */ + u32 page_offset; /* 从offset开始拷贝页数据 */ + u32 page_length; /* 从offset开始拷贝页数据的长度 */ + s32 obb_required; /* obb 是否读取的标志位,1 需要操作oob 区域 */ + u8 *oob_buf; /* obb 数据缓存空间 */ + u32 oob_offset; /* 从offset开始拷贝页数据 */ + u32 oob_length; /* 从offset开始拷贝页数据的长度 */ + u32 chip_addr; /* 芯片地址 */ +} FNandOpData; + +/** + * Bad block table descriptor + */ +typedef struct +{ + u32 page_offset; /* Page offset where BBT resides */ + u32 sig_offset; /* Signature offset in Spare area */ + u32 ver_offset; /* Offset of BBT version */ + u32 sig_length; /* Length of the signature */ + u32 max_blocks; /* Max blocks to search for BBT */ + char signature[4]; /* BBT signature */ + u8 version; /* BBT version */ + u32 valid; /* BBT descriptor is valid or not */ +} FNandBbtDesc; + +typedef struct +{ + u8 bbt[FNAND_MAX_BLOCKS >> 2]; + FNandBbtDesc bbt_desc; /* Bad block table descriptor */ + FNandBbtDesc bbt_mirror_desc; /* Mirror BBT descriptor */ + FNandBadBlockPattern bb_pattern; /* Bad block pattern to search */ +} FNandBadBlockManager; + +/* DMA */ + +/* DMA buffer */ +struct FNandDmaBuffer +{ + u8 data_buffer[FNAND_DMA_MAX_LENGTH]; +} __attribute__((packed)) __attribute__((aligned(128))); + +/* operation api */ +typedef struct _FNand FNand; + +typedef FError(*FNandTransferP)(FNand *instance_p, FNandOpData *op_data_p); +typedef FError(*FNandEraseP)(FNand *instance_p, u32 page_address, u32 chip_addr); + +typedef void (*FnandIrqEventHandler)(void *args, FNAND_CALL_BACK_EVENT event) ; +typedef FError(*FNandOperationWaitIrqCallback)(void *args); + + +typedef struct +{ + u8 data[8]; + u32 len; + +} FNandId; + +typedef struct _FNand +{ + u32 is_ready; /* Device is ininitialized and ready*/ + FNandConfig config; + u32 work_mode; /* NAND controler work mode */ + + /* nand flash info */ + FNandInterMode inter_mode[FNAND_CONNECT_MAX_NUM]; /* NAND controler timing work mode */ + FNandTimingMode timing_mode[FNAND_CONNECT_MAX_NUM]; + u32 nand_flash_interface[FNAND_CONNECT_MAX_NUM] ; /* Nand Flash Interface , followed by FNAND_ONFI_MODE \ FNAND_TOGGLE_MODE*/ + + struct FNandDmaBuffer dma_data_buffer; /* DMA data buffer */ + struct FNandDmaBuffer descriptor_buffer; /* DMA descriptor */ + struct FNandSdrTimings sdr_timing; /* SDR NAND chip timings */ + + /* bbm */ + FNandBadBlockManager bbt_manager[FNAND_CONNECT_MAX_NUM]; /* bad block manager handler */ + /* nand detect */ + FNandNandGeometry nand_geometry[FNAND_CONNECT_MAX_NUM]; /* nand flash infomation */ + /* dma 页操作 */ + FnandIrqEventHandler irq_event_fun_p; /* Interrupt event response function */ + void *irq_args; + + FNandOperationWaitIrqCallback wait_irq_fun_p; /* The NAND controller operates the wait function */ + void *wait_args; + + /* operations */ + FNandTransferP write_p ; /* Write page function */ + FNandTransferP read_p ; /* Read page function */ + FNandTransferP write_oob_p ; /* Write page spare space function */ + FNandTransferP read_oob_p ; /* Read page spare space function */ + FNandTransferP write_hw_ecc_p ; /* Write page with hardware function */ + FNandTransferP read_hw_ecc_p ; /* Read page with hardware function */ + FNandEraseP erase_p; /* Erase block function */ +} FNand; + +FNandConfig *FNandLookupConfig(u32 instance_id); +FError FNandCfgInitialize(FNand *instance_p, + FNandConfig *config_p); +FError FNandScan(FNand *instance_p); +FError FNandSetOption(FNand *instance_p, u32 options, u32 value); + +/* API */ +FError FNandWritePage(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr); +FError FNandWritePageRaw(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr); +FError FNandReadPage(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr); +FError FNandEraseBlock(FNand *instance_p, u32 block, u32 chip_addr); +FError FNandReadPageOOb(FNand *instance_p, u32 page_addr, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr); +FError FNandWritePageOOb(FNand *instance_p, u32 page_addr, u8 *oob_buffer, u32 page_copy_offset, u32 oob_length, u32 chip_addr); +FError FNandReadPageRaw(FNand *instance_p, u32 page_addr, u8 *buffer, u32 page_copy_offset, u32 length, u8 *oob_buffer, u32 oob_copy_offset, u32 oob_length, u32 chip_addr); +/* irq */ +void FNandSetIsrHandler(FNand *instance_p, FnandIrqEventHandler event_p, void *irq_args); +void FNandIrqHandler(s32 vector, void *param); +void FNandOperationWaitIrqRegister(FNand *instance_p, FNandOperationWaitIrqCallback wait_irq_fun_p, void *wait_args); +void FNandIrqDisable(FNand *instance_p, u32 int_mask); +void FNandIsrEnable(FNand *instance_p, u32 int_mask); +/* bbm */ +void FNandInitBbtDesc(FNand *instance_p); +FError FNandScanBbt(FNand *instance_p, u32 target_addr); +FError FNandIsBlockBad(FNand *instance_p, u32 block, u32 target_addr); +FError FNandMarkBlockBad(FNand *instance_p, u32 block, u32 chip_addr); +#ifdef __cplusplus +} +#endif + + + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_bbm.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_bbm.c new file mode 100644 index 0000000000..50bfada9de --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_bbm.c @@ -0,0 +1,882 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_bbm.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:12 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fnand_bbm.h" +#include "fnand.h" +#include "fparameters.h" + +#include +#include "fdebug.h" +#define FNAND_BBM_DEBUG_TAG "FNAND_BBM" +#define FNAND_BBM_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_BBM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_BBM_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_BBM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_BBM_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_BBM_DEBUG_TAG, format, ##__VA_ARGS__) + +static FError FNandWriteBbt(FNand *instance_p, + FNandBbtDesc *desc_p, + FNandBbtDesc *mirror_desc_p, + u32 chip_addr); + +/** + * @name: FNandInitBbtDesc + * @msg: This function initializes the Bad Block Table(BBT) descriptors with a + * predefined pattern for searching Bad Block Table(BBT) in flash. + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @return {*} + * @note: + */ +void FNandInitBbtDesc(FNand *instance_p) +{ + u32 i; + int index; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + for (i = 0; i < FNAND_CONNECT_MAX_NUM; i++) + { + /* + * Initialize primary Bad Block Table(BBT) + */ + instance_p->bbt_manager[i].bbt_desc.page_offset = FNAND_BBT_DESC_PAGE_OFFSET; + instance_p->bbt_manager[i].bbt_desc.sig_offset = FNAND_BBT_DESC_SIG_OFFSET; + instance_p->bbt_manager[i].bbt_desc.ver_offset = FNAND_BBT_DESC_VER_OFFSET; + instance_p->bbt_manager[i].bbt_desc.max_blocks = FNAND_BBT_DESC_MAX_BLOCKS; + instance_p->bbt_manager[i].bbt_desc.sig_length = FNAND_BBT_DESC_SIG_LEN; + strcpy(&instance_p->bbt_manager[i].bbt_desc.signature[0], "Bbt0"); + instance_p->bbt_manager[i].bbt_desc.version = 0; + instance_p->bbt_manager[i].bbt_desc.valid = 0; + /* + * Initialize mirror Bad Block Table(BBT) + */ + instance_p->bbt_manager[i].bbt_mirror_desc.page_offset = FNAND_BBT_DESC_PAGE_OFFSET; + instance_p->bbt_manager[i].bbt_mirror_desc.sig_offset = FNAND_BBT_DESC_SIG_OFFSET; + instance_p->bbt_manager[i].bbt_mirror_desc.ver_offset = FNAND_BBT_DESC_VER_OFFSET; + instance_p->bbt_manager[i].bbt_mirror_desc.sig_length = FNAND_BBT_DESC_SIG_LEN; + instance_p->bbt_manager[i].bbt_mirror_desc.max_blocks = FNAND_BBT_DESC_MAX_BLOCKS; + strcpy(&instance_p->bbt_manager[i].bbt_mirror_desc.signature[0], "1tbB"); + instance_p->bbt_manager[i].bbt_mirror_desc.version = 0; + instance_p->bbt_manager[i].bbt_mirror_desc.valid = 0; + + /* + * Initialize Bad block search pattern structure + */ + if (instance_p->nand_geometry[i].bytes_per_page > 512) + { + /* For flash page size > 512 bytes */ + instance_p->bbt_manager[i].bb_pattern.options = FNAND_BBT_SCAN_2ND_PAGE; + instance_p->bbt_manager[i].bb_pattern.offset = + FNAND_BB_PATTERN_OFFSET_LARGE_PAGE; + instance_p->bbt_manager[i].bb_pattern.length = + FNAND_BB_PATTERN_LENGTH_LARGE_PAGE; + } + else + { + instance_p->bbt_manager[i].bb_pattern.options = FNAND_BBT_SCAN_2ND_PAGE; + instance_p->bbt_manager[i].bb_pattern.offset = + FNAND_BB_PATTERN_OFFSET_SMALL_PAGE; + instance_p->bbt_manager[i].bb_pattern.length = + FNAND_BB_PATTERN_LENGTH_SMALL_PAGE; + } + for (index = 0; index < FNAND_BB_PATTERN_LENGTH_LARGE_PAGE; index++) + { + instance_p->bbt_manager[i].bb_pattern.pattern[index] = FNAND_BB_PATTERN; + } + } +} + +/** + * @name: FNandConvertBbt + * @msg: Convert bitmask read in flash to information stored in RAM + * @return {*} + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u8} *buf is buffer to store the bitmask + * @param {u32} chip_addr is chip address + */ +static void FNandConvertBbt(FNand *instance_p, u8 *buf, u32 chip_addr) +{ + u32 block_offset; + u32 block_shift; + u32 data; + u8 block_type; + u32 block_index; + u32 bbtlen = instance_p->nand_geometry[chip_addr].num_blocks >> + FNAND_BBT_BLOCK_SHIFT; + + for (block_offset = 0; block_offset < bbtlen; block_offset++) + { + data = buf[block_offset]; + + /* + * Clear the RAM based Bad Block Table(BBT) contents + */ + instance_p->bbt_manager[chip_addr].bbt[block_offset] = 0x0; + + /* + * Loop through the every 4 blocks in the bitmap + */ + for (block_index = 0; block_index < FNAND_BBT_ENTRY_NUM_BLOCKS; + block_index++) + { + block_shift = FNAND_BBTBLOCKSHIFT(block_index); + block_type = (data >> block_shift) & + FNAND_BLOCK_TYPE_MASK; + // FNAND_BBM_DEBUG_E("block_offset %d,block_shift %d",block_offset,block_shift); + // FNAND_BBM_DEBUG_E("block_type is %d \r\n",block_type); + switch (block_type) + { + case FNAND_FLASH_BLOCK_FACTORY_BAD: + /* Factory bad block */ + instance_p->bbt_manager[chip_addr].bbt[block_offset] |= + FNAND_BLOCK_FACTORY_BAD << block_shift; + break; + case FNAND_FLASH_BLOCK_RESERVED: + /* Reserved block */ + instance_p->bbt_manager[chip_addr].bbt[block_offset] |= + FNAND_BLOCK_RESERVED << block_shift; + break; + case FNAND_FLASH_BLOCK_BAD: + /* Bad block due to wear */ + instance_p->bbt_manager[chip_addr].bbt[block_offset] |= + FNAND_BLOCK_BAD << block_shift; + break; + default: + /* Good block */ + /* The BBT entry already defaults to + * zero */ + break; + } + } + } +} + +static FError FNandUpdateBbt(FNand *instance_p, u32 chip_addr) +{ + FError ret; + u8 version; + + /* + * Update the version number + */ + version = instance_p->bbt_manager[chip_addr].bbt_desc.version; + instance_p->bbt_manager[chip_addr].bbt_desc.version = (version + 1) % 256; + version = instance_p->bbt_manager[chip_addr].bbt_mirror_desc.version; + instance_p->bbt_manager[chip_addr].bbt_mirror_desc.version = (version + 1) % 256; + + /* + * Update the primary Bad Block Table(BBT) in flash + */ + ret = FNandWriteBbt(instance_p, + &instance_p->bbt_manager[chip_addr].bbt_desc, + &instance_p->bbt_manager[chip_addr].bbt_mirror_desc, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + + /* + * Update the mirrored Bad Block Table(BBT) in flash + */ + ret = FNandWriteBbt(instance_p, + &instance_p->bbt_manager[chip_addr].bbt_mirror_desc, + &instance_p->bbt_manager[chip_addr].bbt_desc, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + + return FT_SUCCESS; +} + +static FError FNandMarkBbt(FNand *instance_p, + FNandBbtDesc *desc_p, + u32 chip_addr) +{ + + u32 block_index; + u32 block_offset; + u8 block_shift; + u8 old_val; + u8 new_val; + FError ret; + u32 updatebbt = 0; + u32 index; + + /* + * Mark the last four blocks as Reserved + */ + block_index = instance_p->nand_geometry[chip_addr].num_blocks - desc_p->max_blocks; + + for (index = 0; index < desc_p->max_blocks; index++, block_index++) + { + block_offset = block_index >> FNAND_BBT_BLOCK_SHIFT; + block_shift = FNAND_BBTBLOCKSHIFT(block_index); + old_val = instance_p->bbt_manager[chip_addr].bbt[block_offset]; + new_val = old_val | (FNAND_BLOCK_RESERVED << block_shift); + instance_p->bbt_manager[chip_addr].bbt[block_offset] = new_val; + + if (old_val != new_val) + { + updatebbt = 1; + } + } + + /* + * Update the BBT to flash + */ + if (updatebbt) + { + ret = FNandUpdateBbt(instance_p, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + } + return FT_SUCCESS; +} + +static FError FNandWriteBbt(FNand *instance_p, + FNandBbtDesc *desc_p, + FNandBbtDesc *mirror_desc_p, + u32 chip_addr) +{ + u64 offset; + u32 block = instance_p->nand_geometry[chip_addr].num_blocks - 1; + u8 buf[FNAND_MAX_BLOCKS >> FNAND_BBT_BLOCK_SHIFT]; + u8 sparebuf[FNAND_MAX_SPARE_SIZE]; + u8 mask[4] = {0x00, 0x01, 0x02, 0x03}; + u8 Data; + u32 block_offset; + u32 block_shift; + FError ret; + u32 block_index; + u32 index; + u8 block_type; + u32 bbtlen = instance_p->nand_geometry[chip_addr].num_blocks >> + FNAND_BBT_BLOCK_SHIFT; + FNAND_BBM_DEBUG_I("FNandWriteBbt bbtlen is %d", bbtlen); + + /* + * Find a valid block to write the Bad Block Table(BBT) + */ + if (!desc_p->valid) + { + for (index = 0; index < desc_p->max_blocks; index++) + { + block = (block - index); + block_offset = block >> FNAND_BBT_BLOCK_SHIFT; + block_shift = FNAND_BBTBLOCKSHIFT(block); + block_type = (instance_p->bbt_manager[chip_addr].bbt[block_offset] >> + block_shift) & + FNAND_BLOCK_TYPE_MASK; + switch (block_type) + { + case FNAND_BLOCK_BAD: + case FNAND_BLOCK_FACTORY_BAD: + continue; + default: + /* Good Block */ + break; + } + desc_p->page_offset = block * + instance_p->nand_geometry[chip_addr].pages_per_block; + if (desc_p->page_offset != mirror_desc_p->page_offset) + { + /* Free block found */ + desc_p->valid = 1; + break; + } + } + + /* + * Block not found for writing Bad Block Table(BBT) + */ + if (index >= desc_p->max_blocks) + { + return FNAND_VALUE_FAILURE; + } + } + else + { + block = desc_p->page_offset / instance_p->nand_geometry[chip_addr].pages_per_block; + } + + /* + * Convert the memory based BBT to flash based table + */ + memset(buf, 0xff, bbtlen); + + /* + * Loop through the number of blocks + */ + for (block_offset = 0; block_offset < bbtlen; block_offset++) + { + Data = instance_p->bbt_manager[chip_addr].bbt[block_offset]; + /* + * Calculate the bit mask for 4 blocks at a time in loop + */ + for (block_index = 0; block_index < FNAND_BBT_ENTRY_NUM_BLOCKS; + block_index++) + { + block_shift = FNAND_BBTBLOCKSHIFT(block_index); + buf[block_offset] &= ~(mask[Data & + FNAND_BLOCK_TYPE_MASK] + << block_shift); + Data >>= FNAND_BBT_BLOCK_SHIFT; + } + // FNAND_BBM_DEBUG_I("buf[%d] 0x%x",block_offset,buf[block_offset]); + } + + /* + * Write the Bad Block Table(BBT) to flash + */ + // printf("erase_p is %p \r\n",instance_p->erase_p); + ret = FNandEraseBlock(instance_p, block, chip_addr); + //instance_p->erase_p(instance_p, block, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + + /* + * Write the signature and version in the spare data area + */ + memset(sparebuf, 0xff, instance_p->nand_geometry[chip_addr].spare_bytes_per_page); + memcpy(sparebuf + desc_p->sig_offset, &desc_p->signature[0], + desc_p->sig_length); + memcpy(sparebuf + desc_p->ver_offset, &desc_p->version, 1); + + /* + * Write the BBT to page offset + */ + FNandWritePage(instance_p, desc_p->page_offset, &buf[0], 0, bbtlen, sparebuf, 0, sizeof(sparebuf), chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + return FT_SUCCESS; +} + +static void FNandCreateBbt(FNand *instance_p, u32 chip_addr) +{ + u32 block_index; + u32 page_index; + u32 length; + u32 block_offset; + u32 block_shift; + u32 num_pages; + u32 page; + u8 buf[FNAND_MAX_SPARE_SIZE]; + u32 bbt_len = instance_p->nand_geometry[chip_addr].num_blocks >> + FNAND_BBT_BLOCK_SHIFT; + FError ret; + /* + * Number of pages to search for bad block pattern + */ + if (instance_p->bbt_manager[chip_addr].bb_pattern.options & FNAND_BBT_SCAN_2ND_PAGE) + { + num_pages = 2; + } + else + { + num_pages = 1; + } + + /* + * Zero the RAM based Bad Block Table(BBT) entries + */ + memset(&instance_p->bbt_manager[chip_addr].bbt[0], 0, bbt_len); + + /* + * Scan all the blocks for factory marked bad blocks + */ + for (block_index = 0; block_index < + instance_p->nand_geometry[chip_addr].num_blocks; + block_index++) + { + /* + * Block offset in Bad Block Table(BBT) entry + */ + block_offset = block_index >> FNAND_BBT_BLOCK_SHIFT; + /* + * Block shift value in the byte + */ + block_shift = FNAND_BBTBLOCKSHIFT(block_index); + page = block_index * instance_p->nand_geometry[chip_addr].pages_per_block; + + /* + * Search for the bad block pattern + */ + for (page_index = 0; page_index < num_pages; page_index++) + { + ret = FNandReadPageOOb(instance_p, page + page_index, buf, 0, sizeof(buf), chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_BBM_DEBUG_E("%s FNandReadPageOOb is error", __func__); + /* Marking as bad block */ + instance_p->bbt_manager[chip_addr].bbt[block_offset] |= + (FNAND_BLOCK_FACTORY_BAD << block_shift); + break; + } + + /* + * Read the spare bytes to check for bad block + * pattern + */ + for (length = 0; length < + instance_p->bbt_manager[chip_addr].bb_pattern.length; + length++) + { + if (buf[instance_p->bbt_manager[chip_addr].bb_pattern.offset + length] != + instance_p->bbt_manager[chip_addr].bb_pattern.pattern[length]) + { + /* Bad block found */ + instance_p->bbt_manager[chip_addr].bbt[block_offset] |= + (FNAND_BLOCK_FACTORY_BAD << block_shift); + FNAND_BBM_DEBUG_E("Bad block found block is %d", page + page_index); + break; + } + } + } + } +} + +FError FNandSearchBbt(FNand *instance_p, FNandBbtDesc *desc, u32 chip_addr) +{ + u32 start_block; + u32 sig_offset; + u32 ver_offset; + u32 max_blocks; + u32 pageoff; + u32 sig_length; + u8 buf[FNAND_MAX_SPARE_SIZE]; + u32 block; + u32 offset; + FError ret; + + start_block = instance_p->nand_geometry[chip_addr].num_blocks - 1; /* start block is last block start */ + sig_offset = desc->sig_offset; + ver_offset = desc->ver_offset; + max_blocks = desc->max_blocks; + sig_length = desc->sig_length; + FNAND_BBM_DEBUG_I("FNandSearchBbt is start 0x%x", start_block); + FNAND_BBM_DEBUG_I("pages_per_block is start %d", instance_p->nand_geometry[chip_addr].pages_per_block); + for (block = 0; block < max_blocks; block++) + { + pageoff = (start_block - block) * + instance_p->nand_geometry[chip_addr].pages_per_block; + FNAND_BBM_DEBUG_I("block 0x%x", block); + FNAND_BBM_DEBUG_I("%s, pageoff is 0x%x", __func__, pageoff); + ret = FNandReadPageOOb(instance_p, pageoff, buf, 0, sizeof(buf), chip_addr); + if (ret != FT_SUCCESS) + { + continue; + } + + /* + * Check the Bad Block Table(BBT) signature + */ + for (offset = 0; offset < sig_length; offset++) + { + if (buf[offset + sig_offset] != desc->signature[offset]) + { + break; /* Check the next blocks */ + } + } + if (offset >= sig_length) + { + /* + * Bad Block Table(BBT) found + */ + desc->page_offset = pageoff; + desc->version = buf[ver_offset]; + desc->valid = 1; + return FT_SUCCESS; + } + } + /* + * Bad Block Table(BBT) not found + */ + return FNAND_VALUE_ERROR; +} + +/** + * @name: + * @msg: + * @return {*} + * @note: + * @param {FNand} *instance_p + * @param {u32} chip_addr + */ +FError FNandReadBbt(FNand *instance_p, u32 chip_addr) +{ + u64 offset; + u8 buf[FNAND_MAX_BLOCKS >> FNAND_BBT_BLOCK_SHIFT]; + FError status1; + FError status2; + FError ret; + u32 bbtlen; + + + FNandBbtDesc *desc_p = &instance_p->bbt_manager[chip_addr].bbt_desc; + FNandBbtDesc *mirror_desc_p = &instance_p->bbt_manager[chip_addr].bbt_mirror_desc; + + bbtlen = instance_p->nand_geometry[chip_addr].num_blocks >> FNAND_BBT_BLOCK_SHIFT; /* 根据nand 介质信息获取的总块数,除以4 的含义为每字节存储4个块信息 */ + FNAND_BBM_DEBUG_I("FNandReadBbt ,bbtlen is %d", bbtlen); + + status1 = FNandSearchBbt(instance_p, desc_p, chip_addr); + status2 = FNandSearchBbt(instance_p, mirror_desc_p, chip_addr); + + if ((status1 != FT_SUCCESS) && (status2 != FT_SUCCESS)) + { + FNAND_BBM_DEBUG_E("FNandReadBbt error status1 %x, status2 %x", status1, status2); + return FNAND_VALUE_FAILURE; + } + + /* + * Bad Block Table found + */ + + if (desc_p->valid && mirror_desc_p->valid) + { + if (desc_p->version > mirror_desc_p->version) + { + /* + * Valid BBT & Mirror BBT found + */ + FNAND_BBM_DEBUG_I("desc_p->version > mirror_desc_p->version read page is %d", desc_p->page_offset); + ret = FNandReadPage(instance_p, desc_p->page_offset, buf, 0, bbtlen, NULL, 0, 0, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_BBM_DEBUG_I("desc_p->version > mirror_desc_p->version read page is error 0x%x", ret); + return ret; + } + /* + * Convert flash BBT to memory based BBT + */ + FNandConvertBbt(instance_p, &buf[0], chip_addr); + mirror_desc_p->version = desc_p->version; + + /* + * Write the BBT to Mirror BBT location in flash + */ + ret = FNandWriteBbt(instance_p, mirror_desc_p, + desc_p, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + } + else if (desc_p->version < mirror_desc_p->version) + { + FNAND_BBM_DEBUG_I("desc_p->version < mirror_desc_p->version read page is %d", mirror_desc_p->page_offset); + ret = FNandReadPage(instance_p, mirror_desc_p->page_offset, buf, 0, bbtlen, NULL, 0, 0, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_BBM_DEBUG_I("desc_p->version < mirror_desc_p->version read page is error 0x%x", ret); + return ret; + } + /* + * Convert flash BBT to memory based BBT + */ + FNandConvertBbt(instance_p, &buf[0], chip_addr); + desc_p->version = mirror_desc_p->version; + + /* + * Write the BBT to Mirror BBT location in flash + */ + ret = FNandWriteBbt(instance_p, desc_p, + mirror_desc_p, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + } + else + { + /* Both are up-to-date */ + FNAND_BBM_DEBUG_I("Both are up-to-date read page is %d", desc_p->page_offset); + + ret = FNandReadPage(instance_p, desc_p->page_offset, buf, 0, bbtlen, NULL, 0, 0, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_BBM_DEBUG_I("Both are up-to-date read page is error 0x%x", ret); + return ret; + } + + /* + * Convert flash BBT to memory based BBT + */ + FNandConvertBbt(instance_p, &buf[0], chip_addr); + } + } + else if (desc_p->valid) + { + /* + * Valid Primary BBT found + */ + + FNAND_BBM_DEBUG_I("Valid Primary BBT found is %d", desc_p->page_offset); + + ret = FNandReadPage(instance_p, desc_p->page_offset, buf, 0, bbtlen, NULL, 0, 0, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_BBM_DEBUG_I("Valid Primary BBT found is error 0x%x", ret); + return ret; + } + + + /* + * Convert flash BBT to memory based BBT + */ + FNandConvertBbt(instance_p, &buf[0], chip_addr); + desc_p->version = mirror_desc_p->version; + + /* + * Write the BBT to Mirror BBT location in flash + */ + ret = FNandWriteBbt(instance_p, mirror_desc_p, + desc_p, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + } + else + { + /* + * Valid Mirror BBT found + */ + + FNAND_BBM_DEBUG_I("Valid Mirror BBT found is %d", mirror_desc_p->page_offset); + + ret = FNandReadPage(instance_p, mirror_desc_p->page_offset, buf, 0, bbtlen, NULL, 0, 0, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_BBM_DEBUG_I("Valid Mirror BBT found is error 0x%x", ret); + return ret; + } + + /* + * Convert flash BBT to memory based BBT + */ + FNandConvertBbt(instance_p, &buf[0], chip_addr); + desc_p->version = mirror_desc_p->version; + + /* + * Write the BBT to Mirror BBT location in flash + */ + ret = FNandWriteBbt(instance_p, desc_p, + mirror_desc_p, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + } + return FT_SUCCESS; +} + + + +static void FNandBbtDumpDebug(FNand *instance_p) +{ + int i; + FNAND_BBM_DEBUG_W("/********************* master bbt descriptor **********************/"); + + FNAND_BBM_DEBUG_I("page_offset 0x%x", instance_p->bbt_manager[0].bbt_desc.page_offset); /* Page offset where BBT resides */ + FNAND_BBM_DEBUG_I("sig_offset 0x%x", instance_p->bbt_manager[0].bbt_desc.sig_offset); /* Signature offset in Spare area */ + FNAND_BBM_DEBUG_I("ver_offset 0x%x", instance_p->bbt_manager[0].bbt_desc.ver_offset); /* Offset of BBT version */ + FNAND_BBM_DEBUG_I("sig_length 0x%x", instance_p->bbt_manager[0].bbt_desc.sig_length); /* Length of the signature */ + FNAND_BBM_DEBUG_I("max_blocks 0x%x", instance_p->bbt_manager[0].bbt_desc.max_blocks); /* Max blocks to search for BBT */ + for (i = 0; i < 4; i++) + { + FNAND_BBM_DEBUG_I("signature[%d] %c", i, instance_p->bbt_manager[0].bbt_desc.signature[i]); + } + FNAND_BBM_DEBUG_I("version 0x%x", instance_p->bbt_manager[0].bbt_desc.version); /* BBT version */ + FNAND_BBM_DEBUG_I("valid 0x%x", instance_p->bbt_manager[0].bbt_desc.valid); /* BBT descriptor is valid or not */ + + FNAND_BBM_DEBUG_W("/********************* mirror bbt descriptor **********************/"); + FNAND_BBM_DEBUG_I("page_offset 0x%x", instance_p->bbt_manager[0].bbt_mirror_desc.page_offset); /* Page offset where BBT resides */ + FNAND_BBM_DEBUG_I("sig_offset 0x%x", instance_p->bbt_manager[0].bbt_mirror_desc.sig_offset); /* Signature offset in Spare area */ + FNAND_BBM_DEBUG_I("ver_offset 0x%x", instance_p->bbt_manager[0].bbt_mirror_desc.ver_offset); /* Offset of BBT version */ + FNAND_BBM_DEBUG_I("sig_length 0x%x", instance_p->bbt_manager[0].bbt_mirror_desc.sig_length); /* Length of the signature */ + FNAND_BBM_DEBUG_I("max_blocks 0x%x", instance_p->bbt_manager[0].bbt_mirror_desc.max_blocks); /* Max blocks to search for BBT */ + for (i = 0; i < 4; i++) + { + FNAND_BBM_DEBUG_I("signature[%d] %c", i, instance_p->bbt_manager[0].bbt_mirror_desc.signature[i]); + } + FNAND_BBM_DEBUG_I("version 0x%x", instance_p->bbt_manager[0].bbt_mirror_desc.version); /* BBT version */ + FNAND_BBM_DEBUG_I("valid 0x%x", instance_p->bbt_manager[0].bbt_mirror_desc.valid); /* BBT descriptor is valid or not */ + + + FNAND_BBM_DEBUG_W("/********************* bbt info **********************/"); + FtDumpHexWord((const u32 *)instance_p->bbt_manager[0].bbt, instance_p->nand_geometry[0].num_blocks >> + FNAND_BBT_BLOCK_SHIFT); +} + +/** + * @name: FNandScanBbt + * @msg: This function reads the Bad Block Table(BBT) if present in flash. + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} chip_addr is chip address + * @return {FError} + */ +FError FNandScanBbt(FNand *instance_p, u32 chip_addr) +{ + FError ret; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + if (FNandReadBbt(instance_p, chip_addr) != FT_SUCCESS) + { + /* + * Create memory based Bad Block Table(BBT) + */ + FNandCreateBbt(instance_p, chip_addr); + + /* + * Write the Bad Block Table(BBT) to the flash + */ + ret = FNandWriteBbt(instance_p, + &instance_p->bbt_manager[chip_addr].bbt_desc, + &instance_p->bbt_manager[chip_addr].bbt_mirror_desc, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + + /* + * Write the Mirror Bad Block Table(BBT) to the flash + */ + ret = FNandWriteBbt(instance_p, + &instance_p->bbt_manager[chip_addr].bbt_mirror_desc, + &instance_p->bbt_manager[chip_addr].bbt_desc, chip_addr); + if (ret != FT_SUCCESS) + { + return ret; + } + + /* + * Mark the blocks containing Bad Block Table(BBT) as Reserved + */ + FNandMarkBbt(instance_p, &instance_p->bbt_manager[chip_addr].bbt_desc, chip_addr); + FNandMarkBbt(instance_p, &instance_p->bbt_manager[chip_addr].bbt_mirror_desc, chip_addr); + + FNAND_BBM_DEBUG_I("New bbt is ready"); + + FNandBbtDumpDebug(instance_p) ; + + } + else + { + FNAND_BBM_DEBUG_I("old bbt is valid"); + FNandBbtDumpDebug(instance_p) ; + } + + return FT_SUCCESS; +} + + +/** + * @name: FNandIsBlockBad + * @msg: This function checks whether a block is bad or not. + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} block is the fnand flash block number + * @param {u32} chip_addr is chip address + * @return {FError} FT_SUCCESS if block is bad + */ +FError FNandIsBlockBad(FNand *instance_p, u32 block, u32 chip_addr) +{ + u8 data; + u8 block_shift; + u8 BlockType; + u32 BlockOffset; + + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT_MSG(block < instance_p->nand_geometry[chip_addr].num_blocks, "block is %d,num_blocks is %d", block, instance_p->nand_geometry[chip_addr].num_blocks); + + BlockOffset = block >> FNAND_BBT_BLOCK_SHIFT; + block_shift = FNAND_BBTBLOCKSHIFT(block); + data = instance_p->bbt_manager[chip_addr].bbt[BlockOffset]; /* Block information in BBT */ + BlockType = (data >> block_shift) & FNAND_BLOCK_TYPE_MASK; + + if (BlockType != FNAND_BLOCK_GOOD) + return FT_SUCCESS; + else + return FNAND_VALUE_FAILURE; +} + + + +/** + * @name: FNandMarkBlockBad + * @msg: This function marks a block as bad in the RAM based Bad Block Table(BBT). + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} block is the fnand flash block number + * @param {u32} chip_addr is chip address + * @return {*} FT_SUCCESS if successful + */ +FError FNandMarkBlockBad(FNand *instance_p, u32 block, u32 chip_addr) +{ + u8 data; + u8 block_shift; + u32 block_offset; + u8 oldval; + u8 newval; + u32 Status; + + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(block < instance_p->nand_geometry[chip_addr].num_blocks); + + block_offset = block >> FNAND_BBT_BLOCK_SHIFT; + block_shift = FNAND_BBTBLOCKSHIFT(block); + data = instance_p->bbt_manager[chip_addr].bbt[block_offset]; /* Block information in BBT */ + + /* + * Mark the block as bad in the RAM based Bad Block Table + */ + oldval = data; + data &= ~(FNAND_BLOCK_TYPE_MASK << block_shift); + data |= (FNAND_BLOCK_BAD << block_shift); + newval = data; + instance_p->bbt_manager[chip_addr].bbt[block_offset] = data; + + /* + * Update the Bad Block Table(BBT) in flash + */ + if (oldval != newval) + { + Status = FNandUpdateBbt(instance_p, chip_addr); + if (Status != FT_SUCCESS) + { + return Status; + } + } + return FT_SUCCESS; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_bbm.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_bbm.h new file mode 100644 index 0000000000..4159553147 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_bbm.h @@ -0,0 +1,106 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_bbm.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:17 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_NAND_FNAND_BBM_H +#define DRIVERS_NAND_FNAND_BBM_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fnand.h" + +/************************** Constant Definitions *****************************/ +/* + * Block definitions for RAM based Bad Block Table (BBT) + */ +#define FNAND_BLOCK_GOOD 0x0 /* Block is good */ +#define FNAND_BLOCK_BAD 0x1 /* Block is bad */ +#define FNAND_BLOCK_RESERVED 0x2 /* Reserved block */ +#define FNAND_BLOCK_FACTORY_BAD 0x3 /* Factory marked bad block */ + +/* + * Block definitions for FLASH based Bad Block Table (BBT) + */ +#define FNAND_FLASH_BLOCK_GOOD 0x3 /* Block is good */ +#define FNAND_FLASH_BLOCK_BAD 0x2 /* Block is bad */ +#define FNAND_FLASH_BLOCK_RESERVED 0x1 /* Reserved block */ +#define FNAND_FLASH_BLOCK_FACTORY_BAD 0x0 /* Factory marked bad block */ + +#define FNAND_BBT_SCAN_2ND_PAGE 0x00000001 /* Scan the \ + second page \ + for bad block \ + information \ + */ +#define FNAND_BBT_DESC_PAGE_OFFSET 0 /* Page offset of Bad \ + Block Table Desc */ +#define FNAND_BBT_DESC_SIG_OFFSET 8 /* Bad Block Table \ + signature offset */ +#define FNAND_BBT_DESC_VER_OFFSET 12 /* Bad block Table \ + version offset */ +#define FNAND_BBT_DESC_SIG_LEN 4 /* Bad block Table \ + signature length */ +#define FNAND_BBT_DESC_MAX_BLOCKS 4 /* Bad block Table \ + max blocks */ + +#define FNAND_BBT_BLOCK_SHIFT 2 /* Block shift value \ + for a block in BBT */ +#define FNAND_BBT_ENTRY_NUM_BLOCKS 4 /* Num of blocks in \ + one BBT entry */ +#define FNAND_BB_PATTERN_OFFSET_SMALL_PAGE 5 /* Bad block pattern \ + offset in a page */ +#define FNAND_BB_PATTERN_LENGTH_SMALL_PAGE 1 /* Bad block pattern \ + length */ +#define FNAND_BB_PATTERN_OFFSET_LARGE_PAGE 0 /* Bad block pattern \ + offset in a large \ + page */ +#define FNAND_BB_PATTERN_LENGTH_LARGE_PAGE 2 /* Bad block pattern \ + length */ +#define FNAND_BB_PATTERN 0xFF /* Bad block pattern \ + to search in a page \ + */ +#define FNAND_BLOCK_TYPE_MASK 0x03 /* Block type mask */ +#define FNAND_BLOCK_SHIFT_MASK 0x06 /* Block shift mask \ + for a Bad Block Table \ + entry byte */ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/****************************************************************************/ + +#define FNAND_BBTBLOCKSHIFT(block) \ + ((block * 2) & FNAND_BLOCK_SHIFT_MASK) + + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_common_cmd.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_common_cmd.c new file mode 100644 index 0000000000..00627cc2f9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_common_cmd.c @@ -0,0 +1,731 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_common_cmd.c + * Date: 2022-06-24 03:51:06 + * LastEditTime: 2022-06-24 03:51:07 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + +#include "fnand_common_cmd.h" +#include "fnand_hw.h" +#include "stdio.h" +#include "string.h" +#include "fnand_dma.h" +#include "fnand_onfi.h" +#include "fnand_timing.h" +#include "fnand_ecc.h" +#include "fcache.h" +#include "fsleep.h" +#include "fdebug.h" +#include "sdkconfig.h" + + +#define FNAND_COMMON_DEBUG_TAG "FNAND_COMMON" + + +#ifdef CONFIG_FNAND_COMMON_DEBUG_EN + #define FNAND_COMMON_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_COMMON_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_COMMON_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_COMMON_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_COMMON_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_COMMON_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_COMMON_DEBUG_D(format, ...) FT_DEBUG_PRINT_D(FNAND_COMMON_DEBUG_TAG, format, ##__VA_ARGS__) +#else + #define FNAND_COMMON_DEBUG_I(format, ...) + #define FNAND_COMMON_DEBUG_W(format, ...) + #define FNAND_COMMON_DEBUG_E(format, ...) + #define FNAND_COMMON_DEBUG_D(format, ...) +#endif + +#define FNAND_ADDR_CYCLE_NUM0 0 +#define FNAND_ADDR_CYCLE_NUM1 1 +#define FNAND_ADDR_CYCLE_NUM2 2 +#define FNAND_ADDR_CYCLE_NUM3 3 +#define FNAND_ADDR_CYCLE_NUM4 4 +#define FNAND_ADDR_CYCLE_NUM5 5 + +#define FNAND_COMMON_CRC_BASE 0x4F4E + +#define FNAND_CTRL_ECC_EN 1 +#define FNAND_CTRL_ECC_DIS 0 + +#define FNAND_CTRL_AUTO_AUTO_RS_EN 1 +#define FNAND_CTRL_AUTO_AUTO_RS_DIS 0 + +/* + * Special handling must be done for the WAITRDY timeout parameter as it usually + * is either tPROG (after a prog), tR (before a read), tRST (during a reset) or + * tBERS (during an erase) which all of them are u64 values that cannot be + * divided by usual kernel macros and must be handled with the special + * DIV_ROUND_UP_ULL() macro. + * + * Cast to type of dividend is needed here to guarantee that the result won't + * be an unsigned long long when the dividend is an unsigned long (or smaller), + * which is what the compiler does when it sees ternary operator with 2 + * different return types (picks the largest type to make sure there's no + * loss). + */ +#define __DIVIDE(dividend, divisor) ({ \ + (__typeof__(dividend))(sizeof(dividend) <= sizeof(unsigned long) ? \ + DIV_ROUND_UP(dividend, divisor) : \ + DIV_ROUND_UP_ULL(dividend, divisor)); \ + }) +#define PSEC_TO_NSEC(x) __DIVIDE(x, 1000) +#define PSEC_TO_MSEC(x) __DIVIDE(x, 1000000000) + +extern FError FNandSendCmd(FNand *instance_p, struct FNandDmaDescriptor *descriptor_p, FNandOperationType isr_type); +extern FError FNandTimingInterfaceUpdate(FNand *instance_p, u32 chip_addr); + +extern FError FNandDmaPack(FNandCmdFormat *cmd_format, + struct FNandDmaDescriptor *descriptor_p, + FNandDmaPackData *pack_data_p + ); + + + +enum CommandsEnumNew +{ + CMD_READ_OPTION_NEW = 0, + CMD_RANDOM_DATA_OUT, + CMD_PAGE_PROGRAM, + CMD_PAGE_PROGRAM_WITH_OTHER, + CMD_COPY_BACK_PROGRAM, + CMD_BLOCK_ERASE, + CMD_RESET, + CMD_READ_ID, + CMD_READ_DEVICE_TABLE, + CMD_READ_PAGE, + CMD_READ_STATUS, + CMD_INDEX_LENGTH_NEW, +}; + + +static FNandCmdFormat cmd_format[CMD_INDEX_LENGTH_NEW] = +{ + {NAND_CMD_READ1, NAND_CMD_READ2, FNAND_ADDR_CYCLE_NUM5, FNAND_CMDCTRL_TYPE_READ, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, + {NAND_CMD_CHANGE_READ_COLUMN1, NAND_CMD_CHANGE_READ_COLUMN2, FNAND_ADDR_CYCLE_NUM2, FNAND_CMDCTRL_TYPE_READ_COL, FNAND_CTRL_ECC_EN, FNAND_CTRL_AUTO_AUTO_RS_DIS}, + {NAND_CMD_PAGE_PROG1, NAND_CMD_PAGE_PROG2, FNAND_ADDR_CYCLE_NUM5, FNAND_CMDCTRL_TYPE_PAGE_PRO, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, + {NAND_CMD_PAGE_PROG1, NAND_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM5, FNAND_CMDCTRL_CH_ROW_ADDR, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_DIS}, + {NAND_CMD_CHANGE_WRITE_COLUMN, NAND_CMD_PAGE_PROG2, FNAND_ADDR_CYCLE_NUM2, FNAND_CMDCTRL_TYPE_PAGE_PRO, FNAND_CTRL_ECC_EN, FNAND_CTRL_AUTO_AUTO_RS_EN}, + {NAND_CMD_BLOCK_ERASE1, NAND_CMD_BLOCK_ERASE2, FNAND_ADDR_CYCLE_NUM3, FNAND_CMDCTRL_TYPE_ERASE, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, + {NAND_CMD_RESET, NAND_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM5, FNAND_CMDCTRL_TYPE_RESET, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, + {NAND_CMD_READ_ID, NAND_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM1, FNAND_CMDCTRL_TYPE_READ_ID, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_DIS}, + {NAND_CMD_READ_PARAM_PAGE, NAND_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM1, FNAND_CMDCTRL_READ_PARAM, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, + {NAND_CMD_READ1, NAND_CMD_READ2, FNAND_ADDR_CYCLE_NUM5, FNAND_CMDCTRL_TYPE_READ_ID, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, + {NAND_CMD_READ_STATUS, NAND_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM5, FNAND_CMDCTRL_TYPE_READ_COL, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_DIS}, +}; + + +FError FNandFlashReadId(FNand *instance_p, u8 address, u8 *id_buffer, u32 buffer_length, u32 chip_addr) +{ + FError ret; + u32 memcpy_length; + FNandDmaPackData pack_data = + { + .addr_p = &address, + .addr_length = 1, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = (buffer_length > FNAND_DMA_MAX_LENGTH) ? FNAND_DMA_MAX_LENGTH : buffer_length, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + memset((struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], 0, sizeof(struct FNandDmaDescriptor)); + FNandDmaPack(&cmd_format[CMD_READ_ID], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_CMD_TYPE); + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + if (buffer_length && id_buffer) + { + memcpy_length = (buffer_length > pack_data.phy_bytes_length) ? pack_data.phy_bytes_length : buffer_length; + FCacheDCacheFlushRange((intptr)instance_p->dma_data_buffer.data_buffer, memcpy_length); + memcpy(id_buffer, instance_p->dma_data_buffer.data_buffer, memcpy_length); + } + + return FT_SUCCESS; +} + + +static FError FNandFlashReadStatus(FNand *instance_p, u32 chip_addr) +{ + FError ret; + FASSERT(instance_p != NULL); + FNandDmaPackData pack_data = + { + .addr_p = NULL, + .addr_length = 0, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = 4, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + memset((struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], 0, sizeof(struct FNandDmaDescriptor)); + FNandDmaPack(&cmd_format[CMD_READ_STATUS], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); /* FNAND_CMDCTRL_TYPE_RESET */ + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_READ_PAGE_TYPE); + if (ret != FT_SUCCESS) + { + return ret; + } + + FNAND_COMMON_DEBUG_I("read status is 0x%x", instance_p->dma_data_buffer.data_buffer[0]); + + return (instance_p->dma_data_buffer.data_buffer[0] == 0xe0) ? FT_SUCCESS : FNAND_IS_BUSY; +} + +FError FNandFlashReset(FNand *instance_p, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FNandDmaPackData pack_data = + { + .addr_p = NULL, + .addr_length = 0, + .phy_address = (uintptr)NULL, + .phy_bytes_length = 0, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + memset((struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], 0, sizeof(struct FNandDmaDescriptor)); + FNandDmaPack(&cmd_format[CMD_RESET], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); /* FNAND_CMDCTRL_TYPE_RESET */ + return FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_CMD_TYPE); +} + + +FError FNandFlashEraseBlock(FNand *instance_p, u32 page_addr, u32 chip_addr) +{ + u8 addr_buf[3] = {0}; + FError ret; + u32 nand_state; + + while (FNandFlashReadStatus(instance_p, chip_addr) == FNAND_IS_BUSY) + ; /* wait i/o idle */ + /* read operation */ + + + addr_buf[0] = page_addr; + addr_buf[1] = page_addr >> 8; + addr_buf[2] = page_addr >> 16; + + FNandDmaPackData pack_data = + { + .addr_p = addr_buf, + .addr_length = 3, + .phy_address = (uintptr)NULL, + .phy_bytes_length = 0, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + FNandDmaPack(&cmd_format[CMD_BLOCK_ERASE], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_CMD_TYPE); + + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + nand_state = FNAND_READREG(instance_p->config.base_address, FNAND_STATE_OFFSET); + while (nand_state & FNAND_STATE_BUSY_OFFSET) /* wait busy state is over */ + { + nand_state = FNAND_READREG(instance_p->config.base_address, FNAND_STATE_OFFSET); + } + + return FT_SUCCESS; +} + +static FError FNandPageRead(FNand *instance_p, u32 page_addr, u8 *buf, u32 page_copy_offset, u32 length, u32 chip_addr) +{ + u8 addr_buf[5] = {0}; + u32 memcpy_length; + FError ret; + addr_buf[4] = (page_addr >> 16); + addr_buf[3] = (page_addr >> 8); + addr_buf[2] = (page_addr); + + FNandDmaPackData pack_data = + { + .addr_p = addr_buf, + .addr_length = 5, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = instance_p->nand_geometry[chip_addr].bytes_per_page, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + FNandDmaPack(&cmd_format[CMD_READ_OPTION_NEW], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_READ_PAGE_TYPE); + + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + if (length && buf) + { + memcpy_length = (length > (pack_data.phy_bytes_length - page_copy_offset)) ? (pack_data.phy_bytes_length - page_copy_offset) : length; + FCacheDCacheFlushRange((intptr)(instance_p->dma_data_buffer.data_buffer + page_copy_offset), memcpy_length); + memcpy(buf, instance_p->dma_data_buffer.data_buffer + page_copy_offset, memcpy_length); + } + + return FT_SUCCESS; +} + +static FError FNandPageWrite(FNand *instance_p, u32 page_addr, u8 *buf, u32 page_copy_offset, u32 length, u32 chip_addr) +{ + u8 addr_buf[5] = {0}; + FError ret; + u32 bytes_per_page = 0; + addr_buf[4] = (page_addr >> 16); + addr_buf[3] = (page_addr >> 8); + addr_buf[2] = (page_addr); + bytes_per_page = instance_p->nand_geometry[chip_addr].bytes_per_page; + FNandDmaPackData pack_data = + { + .addr_p = addr_buf, + .addr_length = 5, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = bytes_per_page, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + memcpy(instance_p->dma_data_buffer.data_buffer + page_copy_offset, buf, ((bytes_per_page - page_copy_offset) > length) ? length : (bytes_per_page - page_copy_offset)); + + FNandDmaPack(&cmd_format[CMD_PAGE_PROGRAM], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_WRITE_PAGE_TYPE); + + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + while (FNandFlashReadStatus(instance_p, chip_addr) == FNAND_IS_BUSY); + return FT_SUCCESS; +} + +static FError FNandPageWriteHwEcc(FNand *instance_p, u32 page_addr, u8 *buf, u32 page_copy_offset, u32 length, u32 chip_addr) +{ + FError ret; + u32 nand_state = 0; + u8 addr_buf[5] = {0}; + u32 ecc_offset = 0; + u32 bytes_per_page = 0; + u32 spare_bytes_per_page = 0; + /* read operation */ + addr_buf[2] = page_addr; + addr_buf[3] = page_addr >> 8; + addr_buf[4] = page_addr >> 16; + + ecc_offset = instance_p->nand_geometry[chip_addr].ecc_offset; + bytes_per_page = instance_p->nand_geometry[chip_addr].bytes_per_page; + spare_bytes_per_page = instance_p->nand_geometry[chip_addr].spare_bytes_per_page; + + FNandDmaPackData pack_data = + { + .addr_p = addr_buf, + .addr_length = 5, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = bytes_per_page, + .chip_addr = chip_addr, + .contiune_dma = 1, + }; + + memset(instance_p->dma_data_buffer.data_buffer, 0xff, FNAND_DMA_MAX_LENGTH); + memcpy(instance_p->dma_data_buffer.data_buffer + page_copy_offset, buf, ((bytes_per_page - page_copy_offset) < length) ? (bytes_per_page - page_copy_offset) : length); + + FNandDmaPack(&cmd_format[CMD_PAGE_PROGRAM_WITH_OTHER], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data) ; + /* Random Data Input */ + + /* 写入存储硬件ecc 偏移位置参数 */ + memset(addr_buf, 0, sizeof(addr_buf)); + addr_buf[0] = bytes_per_page + ecc_offset; + addr_buf[1] = (bytes_per_page + ecc_offset) >> 8; + memset((instance_p->dma_data_buffer.data_buffer + bytes_per_page), 0xff, spare_bytes_per_page); + FNandDmaPackData pack_data2 = + { + .addr_p = addr_buf, + .addr_length = 2, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer + bytes_per_page + ecc_offset, + .phy_bytes_length = instance_p->nand_geometry[chip_addr].hw_ecc_length, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + FNandDmaPack(&cmd_format[CMD_COPY_BACK_PROGRAM], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[FNAND_DESCRIPTORS_SIZE], &pack_data2) ; + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_WRITE_PAGE_TYPE); + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + nand_state = FNAND_READREG(instance_p->config.base_address, FNAND_STATE_OFFSET); + while (nand_state & FNAND_STATE_BUSY_OFFSET) /* wait busy state is over */ + { + nand_state = FNAND_READREG(instance_p->config.base_address, FNAND_STATE_OFFSET); + } + // printf("write after nand_state 0x%x \r\n",nand_state); + while (FNandFlashReadStatus(instance_p, chip_addr) == FNAND_IS_BUSY) + ; /* wait i/o idle */ + + return FT_SUCCESS; +} + +static FError FNandPageReadOOb(FNand *instance_p, u32 page_addr, u8 *buf, u32 page_copy_offset, u32 length, u32 chip_addr) +{ + FError ret; + u8 addr_buf[5] = {0}; + u32 bytes_per_page = 0; + u32 spare_bytes_per_page = 0; + u32 memcpy_length = 0; + bytes_per_page = instance_p->nand_geometry[chip_addr].bytes_per_page ; + spare_bytes_per_page = instance_p->nand_geometry[chip_addr].spare_bytes_per_page ; + + FNandDmaPackData pack_data = + { + .addr_p = addr_buf, + .addr_length = 5, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = spare_bytes_per_page, /* 读取所有的oob 数据 */ + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + addr_buf[4] = (page_addr >> 16); + addr_buf[3] = (page_addr >> 8); + addr_buf[2] = (page_addr); + addr_buf[1] = ((bytes_per_page >> 8) & 0xff); /* 从oob 位置读取 */ + addr_buf[0] = (bytes_per_page & 0xff); + + FNandDmaPack(&cmd_format[CMD_READ_OPTION_NEW], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_READ_PAGE_TYPE); + + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + if (length && buf) + { + memcpy_length = (length > (spare_bytes_per_page - page_copy_offset)) ? (spare_bytes_per_page - page_copy_offset) : length; + FCacheDCacheFlushRange((intptr)(instance_p->dma_data_buffer.data_buffer + page_copy_offset), memcpy_length); + memcpy(buf, instance_p->dma_data_buffer.data_buffer + page_copy_offset, memcpy_length); + } + + return FT_SUCCESS; +} + +static FError FNandPageWriteOOb(FNand *instance_p, u32 page_addr, u8 *buf, u32 spare_page_offset, u32 length, u32 chip_addr) +{ + FError ret; + u8 addr_buf[5] = {0}; + u32 bytes_per_page = 0; + u32 spare_bytes_per_page = 0; + + bytes_per_page = instance_p->nand_geometry[chip_addr].bytes_per_page; + spare_bytes_per_page = instance_p->nand_geometry[chip_addr].spare_bytes_per_page ; + memset(instance_p->dma_data_buffer.data_buffer, 0xff, spare_bytes_per_page); + + FNandDmaPackData pack_data = + { + .addr_p = addr_buf, + .addr_length = 5, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = (spare_bytes_per_page > length) ? length : spare_bytes_per_page, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + addr_buf[4] = (page_addr >> 16); + addr_buf[3] = (page_addr >> 8); + addr_buf[2] = (page_addr); + addr_buf[1] = ((bytes_per_page >> 8) & 0xff); + addr_buf[0] = (bytes_per_page & 0xff); + + memcpy(instance_p->dma_data_buffer.data_buffer + spare_page_offset, buf, ((spare_bytes_per_page - spare_page_offset) > length) ? length : (spare_bytes_per_page - spare_page_offset)); + + FNandDmaPack(&cmd_format[CMD_PAGE_PROGRAM], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_WRITE_PAGE_TYPE); + + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + while (FNandFlashReadStatus(instance_p, chip_addr) == FNAND_IS_BUSY); + return FT_SUCCESS ; +} + +static FError FNandPageReadHwEcc(FNand *instance_p, u32 page_addr, u8 *buf, u32 page_copy_offset, u32 length, u32 chip_addr) +{ + FError ret; + u32 nand_state = 0; + u8 addr_buf[5] = {0}; + u32 memcpy_length = 0; + volatile u32 wait_cnt; + /* read operation */ + addr_buf[2] = page_addr; + addr_buf[3] = page_addr >> 8; + addr_buf[4] = page_addr >> 16; + + FNandDmaPackData pack_data = + { + .addr_p = addr_buf, + .addr_length = 5, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = instance_p->nand_geometry[chip_addr].bytes_per_page, + .chip_addr = chip_addr, + .contiune_dma = 1, + }; + + FNandDmaPack(&cmd_format[CMD_READ_OPTION_NEW], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data) ; + + /* Random Data Output */ + memset(addr_buf, 0, sizeof(addr_buf)); + /* 读取存储硬件ecc 偏移位置参数 */ + addr_buf[0] = instance_p->nand_geometry[chip_addr].bytes_per_page + instance_p->nand_geometry[chip_addr].ecc_offset; + addr_buf[1] = (instance_p->nand_geometry[chip_addr].bytes_per_page + instance_p->nand_geometry[chip_addr].ecc_offset) >> 8; + + FNandDmaPackData pack_data2 = + { + .addr_p = addr_buf, + .addr_length = 2, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer + instance_p->nand_geometry[chip_addr].bytes_per_page, + .phy_bytes_length = instance_p->nand_geometry[chip_addr].hw_ecc_length, + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + FNandDmaPack(&cmd_format[CMD_RANDOM_DATA_OUT], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[16], &pack_data2) ; + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_WAIT_ECC_TYPE); + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + fsleep_microsec(100); + /* 增加判断bit(16) 是否ecc 正忙 */ + nand_state = FNAND_READREG(instance_p->config.base_address, FNAND_STATE_OFFSET); + + while ((nand_state & FNAND_STATE_ECC_BUSY_OFFSET) && ((nand_state & FNAND_STATE_ECC_FINISH_OFFSET) == 0)) + { + nand_state = FNAND_READREG(instance_p->config.base_address, FNAND_STATE_OFFSET); + } + + if (nand_state & FNAND_STATE_ECC_ERROVER_OFFSET) + { + FNAND_COMMON_DEBUG_E("FNAND_STATE_ECC_ERROVER %x ,page is %x \n", 0, page_addr) ; + return FNAND_ERR_READ_ECC ; + } + else if (nand_state & FNAND_STATE_ECC_ERR_OFFSET) + { + s32 correct_num; + FNAND_COMMON_DEBUG_W("FNAND ecc correct is in \r\n"); + correct_num = FNandCorrectEcc(instance_p->config.base_address, instance_p->nand_geometry[chip_addr].ecc_step_size, + instance_p->nand_geometry[chip_addr].hw_ecc_steps, instance_p->dma_data_buffer.data_buffer, + instance_p->nand_geometry[chip_addr].bytes_per_page); + + if (correct_num < 0) + { + FNAND_COMMON_DEBUG_W("CRC ECC IS ERROR \n") ; + return FNAND_ERR_READ_ECC; + } + + FNAND_COMMON_DEBUG_W("FNAND_STATE_ECC_ERR %x ,page is %x \n", correct_num, page_addr) ; + } + + if (length && buf) + { + memcpy_length = (length > (pack_data.phy_bytes_length - page_copy_offset)) ? (pack_data.phy_bytes_length - page_copy_offset) : length; + FCacheDCacheFlushRange((intptr)(instance_p->dma_data_buffer.data_buffer + page_copy_offset), memcpy_length); + memcpy(buf, instance_p->dma_data_buffer.data_buffer + page_copy_offset, memcpy_length); + } + + return FT_SUCCESS; +} + +FError FNandFlashReadPageRaw(FNand *instance_p, FNandOpData *op_data_p) +{ + FASSERT(instance_p != NULL); + FASSERT(op_data_p != NULL); + FError ret; + ret = FNandPageRead(instance_p, op_data_p->page_addr, op_data_p->page_buf, op_data_p->page_offset, op_data_p->page_length, op_data_p->chip_addr); + + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageRead is error %x", __func__, ret); + return ret; + } + + if (op_data_p->obb_required) + { + ret = FNandPageReadOOb(instance_p, op_data_p->page_addr, op_data_p->oob_buf, op_data_p->oob_offset, op_data_p->oob_length, op_data_p->chip_addr); + + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageReadOOb is error %x", __func__, ret); + return ret; + } + } + + return FT_SUCCESS; +} + +FError FNandFlashReadPageHwEcc(FNand *instance_p, FNandOpData *op_data_p) +{ + FASSERT(instance_p != NULL); + FASSERT(op_data_p != NULL); + FError ret; + FNandConfig *config_p; + config_p = &instance_p->config; + FNandFlashReadStatus(instance_p, op_data_p->chip_addr); + + FNandEnableHwEcc(config_p->base_address); + ret = FNandPageReadHwEcc(instance_p, op_data_p->page_addr, op_data_p->page_buf, op_data_p->page_offset, op_data_p->page_length, op_data_p->chip_addr); + FNandDisableHwEcc(config_p->base_address); + + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageReadHwEcc is error %x", __func__, ret); + return ret; + } + + + if (op_data_p->obb_required) + { + ret = FNandPageReadOOb(instance_p, op_data_p->page_addr, op_data_p->oob_buf, op_data_p->oob_offset, op_data_p->oob_length, op_data_p->chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageReadOOb is error %x", __func__, ret); + return ret; + } + } + + return FT_SUCCESS; +} + +FError FNandFlashWritePageRaw(FNand *instance_p, FNandOpData *op_data_p) +{ + FASSERT(instance_p != NULL); + FASSERT(op_data_p != NULL); + FError ret; + if (op_data_p->obb_required) + { + ret = FNandPageWriteOOb(instance_p, op_data_p->page_addr, op_data_p->oob_buf, op_data_p->oob_offset, op_data_p->oob_length, op_data_p->chip_addr); + + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageWriteOOb is error %x", __func__, ret); + return ret; + } + } + + ret = FNandPageWrite(instance_p, op_data_p->page_addr, op_data_p->page_buf, op_data_p->page_offset, op_data_p->page_length, op_data_p->chip_addr); + + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageWrite is error %x", __func__, ret); + return ret; + } + + return FT_SUCCESS; +} + + +FError FNandFlashWritePageRawHwEcc(FNand *instance_p, FNandOpData *op_data_p) +{ + FError ret; + FNandConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(op_data_p != NULL); + + FNandFlashReadStatus(instance_p, op_data_p->chip_addr); + + config_p = &instance_p->config; + if (op_data_p->obb_required) + { + ret = FNandPageWriteOOb(instance_p, op_data_p->page_addr, op_data_p->oob_buf, op_data_p->oob_offset, op_data_p->oob_length, op_data_p->chip_addr); + + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageWriteOOb is error %x", __func__, ret); + return ret; + } + } + FNandEnableHwEcc(config_p->base_address); + ret = FNandPageWriteHwEcc(instance_p, op_data_p->page_addr, op_data_p->page_buf, op_data_p->page_offset, op_data_p->page_length, op_data_p->chip_addr); + FNandDisableHwEcc(config_p->base_address); + + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageWrite is error %x", __func__, ret); + return ret; + } + + return FT_SUCCESS; +} + + +FError FNandFlashOObRead(FNand *instance_p, FNandOpData *op_data_p) +{ + FASSERT(instance_p != NULL); + FASSERT(op_data_p != NULL); + FError ret; + FNandConfig *config_p; + config_p = &instance_p->config; + + ret = FNandPageReadOOb(instance_p, op_data_p->page_addr, op_data_p->oob_buf, op_data_p->oob_offset, op_data_p->oob_length, op_data_p->chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageReadOOb is error %x", __func__, ret); + return ret; + } + + return FT_SUCCESS; +} + + + +FError FNandFlashOObWrite(FNand *instance_p, FNandOpData *op_data_p) +{ + + FASSERT(instance_p != NULL); + FASSERT(op_data_p != NULL); + FError ret; + + ret = FNandPageWriteOOb(instance_p, op_data_p->page_addr, op_data_p->oob_buf, op_data_p->oob_offset, op_data_p->oob_length, op_data_p->chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_COMMON_DEBUG_E("%s,FNandPageWriteOOb is error %x", __func__, ret); + return ret; + } +} + + +void FNandFlashFuncRegister(FNand *instance_p) +{ + FASSERT(instance_p != NULL); + instance_p->write_p = FNandFlashWritePageRaw ; + instance_p->read_p = FNandFlashReadPageRaw ; + instance_p->erase_p = FNandFlashEraseBlock ; + instance_p->write_hw_ecc_p = FNandFlashWritePageRawHwEcc ; + instance_p->read_hw_ecc_p = FNandFlashReadPageHwEcc ; + instance_p->write_oob_p = FNandFlashOObWrite; + instance_p->read_oob_p = FNandFlashOObRead; +} + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_common_cmd.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_common_cmd.h new file mode 100644 index 0000000000..2c2733d5bd --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_common_cmd.h @@ -0,0 +1,74 @@ +/* + * @Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_common_cmd.h + * @Date: 2022-07-05 19:01:01 + * @LastEditTime: 2022-07-05 19:01:02 + * @Description: This file is for + * + * @Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + +#ifndef DRIVERS_NAND_COMMON_CMD_H +#define DRIVERS_NAND_COMMON_CMD_H + +#include "ftypes.h" +#include "fnand.h" + +/* + * Mandatory commands + */ + +#define NAND_CMD_READ1 0x00 +#define NAND_CMD_READ2 0x30 /* READ PAGE */ + +#define NAND_CMD_CHANGE_READ_COLUMN1 0x05 /* NAND Random data Read \ + Column command (1st \ + cycle) */ +#define NAND_CMD_CHANGE_READ_COLUMN2 0xE0 /* NAND Random data Read \ + Column command (2nd \ + cycle) */ +#define NAND_CMD_BLOCK_ERASE1 0x60 /* NAND Block Erase \ + (1st cycle) */ +#define NAND_CMD_BLOCK_ERASE2 0xD0 /* NAND Block Erase \ + (2nd cycle) */ + +#define NAND_CMD_PAGE_PROG1 0x80 /* NAND Page Program \ + command (1st cycle) \ + */ +#define NAND_CMD_PAGE_PROG2 0x10 /* NAND Page Program \ + command (2nd cycle) \ + */ + +#define NAND_CMD_CHANGE_WRITE_COLUMN 0x85 /* NAND Change Write \ + Column command */ +#define NAND_CMD_READ_ID 0x90 /* NAND Read ID \ + command */ +#define NAND_CMD_READ_PARAM_PAGE 0xEC /* NAND Read \ + Parameter Page \ + command */ +#define NAND_CMD_RESET 0xFF /* NAND Reset \ + command */ + +#define NAND_END_CMD_NONE 0xfff /* No End command */ + +#define NAND_CMD_READ_STATUS 0x70 /* Read status */ + +FError FNandFlashReset(FNand *instance_p, u32 chip_addr) ; +FError FNandFlashReadId(FNand *instance_p, u8 address, u8 *id_buffer, u32 buffer_length, u32 chip_addr); +void FNandFlashFuncRegister(FNand *instance_p); + +#endif + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_dma.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_dma.c new file mode 100644 index 0000000000..0c76bce917 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_dma.c @@ -0,0 +1,153 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_dma.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:22 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fnand_dma.h" +#include "fnand.h" +#include "ferror_code.h" +#include "fdebug.h" +#include +#include +#include "fcache.h" +#include "fnand_toggle.h" +#include "sdkconfig.h" + +#ifdef CONFIG_FNAND_DMA_DEBUG_EN + #define FNAND_DMA_DEBUG_TAG "FNAND_DMA" + #define FNAND_DMA_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_DMA_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_DMA_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_DMA_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_DMA_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_DMA_DEBUG_TAG, format, ##__VA_ARGS__) +#else + #define FNAND_DMA_DEBUG_I(format, ...) + #define FNAND_DMA_DEBUG_W(format, ...) + #define FNAND_DMA_DEBUG_E(format, ...) +#endif + + +void FNandDmaDump(struct FNandDmaDescriptor *descriptor_p) +{ + FNAND_DMA_DEBUG_I("Phytium NFC cmd dump:\n"); + FNAND_DMA_DEBUG_I("cmd0:%x, cmd1:%x, ctrl:%x, page_cnt:%d\n", + descriptor_p->cmd0, descriptor_p->cmd1, descriptor_p->cmd_ctrl.ctrl, descriptor_p->page_cnt); + FNAND_DMA_DEBUG_I("mem_addr_first:%02x %02x %02x %02x %02x\n", + descriptor_p->mem_addr_first[0], descriptor_p->mem_addr_first[1], descriptor_p->mem_addr_first[2], descriptor_p->mem_addr_first[3], descriptor_p->mem_addr_first[4]); + FNAND_DMA_DEBUG_I("addr:%02x %02x %02x %02x %02x\n", + descriptor_p->addr[0], descriptor_p->addr[1], descriptor_p->addr[2], descriptor_p->addr[3], descriptor_p->addr[4]); + + FNAND_DMA_DEBUG_I(" csel : 0x%x ", descriptor_p->cmd_ctrl.nfc_ctrl.csel); + FNAND_DMA_DEBUG_I(" dbc : %d ", descriptor_p->cmd_ctrl.nfc_ctrl.dbc); + FNAND_DMA_DEBUG_I(" addr_cyc : %d ", descriptor_p->cmd_ctrl.nfc_ctrl.addr_cyc); + FNAND_DMA_DEBUG_I(" nc : %d ", descriptor_p->cmd_ctrl.nfc_ctrl.nc); + FNAND_DMA_DEBUG_I(" cmd_type : %d ", descriptor_p->cmd_ctrl.nfc_ctrl.cmd_type); + FNAND_DMA_DEBUG_I(" dc : %d ", descriptor_p->cmd_ctrl.nfc_ctrl.dc); + FNAND_DMA_DEBUG_I(" auto_rs : %d ", descriptor_p->cmd_ctrl.nfc_ctrl.auto_rs); + FNAND_DMA_DEBUG_I(" ecc_en : %d ", descriptor_p->cmd_ctrl.nfc_ctrl.ecc_en); + +} + +static void FNandAddrCorrect(struct FNandDmaDescriptor *descriptor_p, + u8 *addr_p, + u32 addr_length) +{ + int i, j; + if (addr_length == 0 || addr_p == NULL) + { + FNAND_DMA_DEBUG_I("addr_p is null ,Calibration is not required "); + return; + } + + if (addr_length >= FNAND_NFC_ADDR_MAX_LEN) + { + memcpy(descriptor_p->addr, addr_p, FNAND_NFC_ADDR_MAX_LEN); + descriptor_p->cmd_ctrl.nfc_ctrl.addr_cyc = FNAND_NFC_ADDR_MAX_LEN; + return; + } + + descriptor_p->cmd_ctrl.nfc_ctrl.addr_cyc = 0; + for (i = addr_length - 1, j = FNAND_NFC_ADDR_MAX_LEN - 1; i >= 0; i--, j--) + { + descriptor_p->addr[j] = addr_p[i]; /* data shift to high array */ + descriptor_p->addr[i] = 0; + descriptor_p->cmd_ctrl.nfc_ctrl.addr_cyc++; + } +} + +FError FNandDmaPack(FNandCmdFormat *cmd_format, + struct FNandDmaDescriptor *descriptor_p, + FNandDmaPackData *pack_data_p + ) +{ + u32 i; + FASSERT(cmd_format != NULL); + FASSERT(descriptor_p != NULL); + // printf(" descriptor_p is %p \r\n",descriptor_p); + descriptor_p->cmd_ctrl.ctrl = 0; + + /* cmd */ + if (cmd_format->end_cmd == TOGGLE_END_CMD_NONE) /* Only one cmd ,need to correct */ + { + descriptor_p->cmd1 = cmd_format->start_cmd; + descriptor_p->cmd0 = 0; + } + else + { + descriptor_p->cmd0 = cmd_format->start_cmd; + descriptor_p->cmd1 = cmd_format->end_cmd; + descriptor_p->cmd_ctrl.nfc_ctrl.dbc = 1; + } + + /* addr */ + FNandAddrCorrect(descriptor_p, pack_data_p->addr_p, pack_data_p->addr_length); + descriptor_p->cmd_ctrl.nfc_ctrl.cmd_type = cmd_format->cmd_type; /* cmd type */ + FNAND_DMA_DEBUG_I("cmd_type is %x \r\n", descriptor_p->cmd_ctrl.nfc_ctrl.cmd_type); + if (pack_data_p->contiune_dma) + { + descriptor_p->cmd_ctrl.nfc_ctrl.nc = 1; + } + + descriptor_p->cmd_ctrl.nfc_ctrl.csel = (0xf ^ (1 << pack_data_p->chip_addr)); + + if (pack_data_p->phy_address && (pack_data_p->phy_bytes_length > 0)) + { + descriptor_p->cmd_ctrl.nfc_ctrl.dc = 1; + for (i = 0; i < FNAND_NFC_ADDR_MAX_LEN; i++) + { + descriptor_p->mem_addr_first[i] = pack_data_p->phy_address >> (8 * i) & 0xff; + } + descriptor_p->page_cnt = pack_data_p->phy_bytes_length; + } + + if (cmd_format->auto_rs) + descriptor_p->cmd_ctrl.nfc_ctrl.auto_rs = 1; + + if (cmd_format->ecc_en) + descriptor_p->cmd_ctrl.nfc_ctrl.ecc_en = 1; + + /* invalid descriptor and buffer */ + FCacheDCacheInvalidateRange((intptr)descriptor_p, sizeof(struct FNandDmaDescriptor)); + FCacheDCacheInvalidateRange((intptr)pack_data_p->addr_p, pack_data_p->addr_length); + + FNandDmaDump(descriptor_p); + + return FT_SUCCESS; +} diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_dma.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_dma.h new file mode 100644 index 0000000000..4e792eaa4d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_dma.h @@ -0,0 +1,111 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_dma.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:27 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_NAND_FNAND_DMA_H +#define DRIVERS_NAND_FNAND_DMA_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" + +#define FNAND_CMDCTRL_TYPE_RESET 0x00 /* reset */ +#define FNAND_CMDCTRL_TYPE_SET_FTR 0x01 /* Set features */ +#define FNAND_CMDCTRL_TYPE_GET_FTR 0x02 /* Get features */ +#define FNAND_CMDCTRL_TYPE_READ_ID 0x03 /* Read ID */ +#define FNAND_CMDCTRL_TYPE_READ_COL 0x03 /* Read Column */ +#define FNAND_CMDCTRL_TYPE_PAGE_PRO 0x04 /* Page program */ +#define FNAND_CMDCTRL_TYPE_ERASE 0x05 /* Block Erase */ +#define FNAND_CMDCTRL_TYPE_READ 0x06 /* Read */ +#define FNAND_CMDCTRL_TYPE_TOGGLE 0x07 /* Toggle Two_plane */ + +#define FNAND_CMDCTRL_READ_PARAM 0x02 +#define FNAND_CMDCTRL_READ_STATUS 0x03 + +#define FNAND_CMDCTRL_CH_READ_COL 0x03 +#define FNAND_CMDCTRL_CH_ROW_ADDR 0x01 +#define FNAND_CMDCTRL_CH_WR_COL 0x01 + +#define FNAND_NFC_ADDR_MAX_LEN 0x5 + +#define FNAND_DESCRIPTORS_SIZE 16 + +struct CmdCtrl +{ + u16 csel : 4; /* 每一位表示选择NAND FLASH 设备 */ + u16 dbc : 1; /* 表示是否有2级命令,1表示有,只有此位为1时,描述符表的CMD1才有效 */ + u16 addr_cyc : 3; /* 表示指令有几个周期,‘b000’:表示没有周期 ‘b001’:表示1一个地址周期,一次类推 */ + u16 nc : 1; /* 表示是否有连续的下一个指令,一般多页操作需要连续发送多个指令 */ + u16 cmd_type : 4; /* 表示命令类型 */ + u16 dc : 1; /* 表示命令发送是否包含有数据周期,有数据此位为1 */ + u16 auto_rs : 1; /* 表示命令发送完成后是否检测闪存状态 */ + u16 ecc_en : 1; /* ECC 数据发送和读取使能位,位1 表示该命令仅发送或者读取ECC数据,当读命令该位使能位1后,控制器会对上一次数据进行ECC 校验,并返回结果 */ +}; + +struct FNandDmaDescriptor +{ + u8 cmd0; /* NAND FLASH 第一个命令编码 */ + u8 cmd1; /* NAND FLASH 第二个命令编码 */ + union + { + u16 ctrl; + struct CmdCtrl nfc_ctrl; + } cmd_ctrl; /* 16位命令字 */ + u8 addr[FNAND_NFC_ADDR_MAX_LEN]; + u16 page_cnt; + u8 mem_addr_first[FNAND_NFC_ADDR_MAX_LEN]; + +} __attribute__((packed)) __attribute__((aligned(128))); + + + +typedef struct +{ + u8 *addr_p; /* Address */ + u32 addr_length; + uintptr phy_address; + u32 phy_bytes_length; + u32 chip_addr; + u8 contiune_dma; /* */ +} FNandDmaPackData; + + +/* DMA format */ +typedef struct +{ + s32 start_cmd; /* Start command */ + s32 end_cmd; /* End command */ + u8 addr_cycles; /* Number of address cycles */ + u8 cmd_type; /* Presentation command type ,followed by FNAND_CMDCTRL_XXXX */ + u8 ecc_en; /* Hardware ecc open */ + u8 auto_rs; /* 表示命令发送完成后是否检测闪存状态 */ +} FNandCmdFormat; + + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_ecc.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_ecc.c new file mode 100644 index 0000000000..f76f28544c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_ecc.c @@ -0,0 +1,266 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_ecc.c + * Date: 2022-05-12 14:17:42 + * LastEditTime: 2022-05-12 15:56:27 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fnand_ecc.h" +#include "fnand.h" +#include "fnand_hw.h" +#include "fdebug.h" +#define FNAND_ECC_DEBUG_TAG "FNAND_ECC" +#define FNAND_ECC_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_ECC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_ECC_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_ECC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_ECC_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_ECC_DEBUG_TAG, format, ##__VA_ARGS__) + + +/** + * @name: FNandGetEccTotalLength + * @msg: 根据page size 与 ecc_strength(纠错个数)确定硬件ecc 产生 + * @param {u32} bytes_per_page + * @param {u32} ecc_strength + * @return {*} + * @note: + */ +u32 FNandGetEccTotalLength(u32 bytes_per_page, u32 ecc_strength) +{ + int ecc_total = 0; + switch (bytes_per_page) + { + case 0x200: + if (ecc_strength == 8) + ecc_total = 0x0D; + else if (ecc_strength == 4) + ecc_total = 7; + else if (ecc_strength == 2) + ecc_total = 4; + else + ecc_total = 0; + break; + case 0x800: + if (ecc_strength == 8) + ecc_total = 0x34; + else if (ecc_strength == 4) + ecc_total = 0x1a; + else if (ecc_strength == 2) + ecc_total = 0xd; + else + ecc_total = 0; + break; + case 0x1000: + if (ecc_strength == 8) + ecc_total = 0x68; + else if (ecc_strength == 4) + ecc_total = 0x34; + else if (ecc_strength == 2) + ecc_total = 0x1a; + else + ecc_total = 0; + break; + case 0x2000: + if (ecc_strength == 8) + ecc_total = 0xD0; + else if (ecc_strength == 4) + ecc_total = 0x68; + else if (ecc_strength == 2) + ecc_total = 0x34; + else + ecc_total = 0; + break; + case 0x4000: + if (ecc_strength == 8) + ecc_total = 0x1A0; + if (ecc_strength == 4) + ecc_total = 0xD0; + else if (ecc_strength == 2) + ecc_total = 0x68; + else + ecc_total = 0; + break; + default: + ecc_total = 0; + break; + } + + FNAND_ECC_DEBUG_I("[%s %d]writesize: 0x%x, ecc strength: %d, ecc_total: 0x%x\n", __func__, __LINE__, bytes_per_page, ecc_strength, ecc_total); + return ecc_total; +} + + +/** + * @name: FNandCorrectEcc + * @msg: + * @note: + * @return {*} + * @param {uintptr_t} base_address + * @param {u32} ecc_step_size 单次ecc 使用的步长大小 + * @param {u32} hw_ecc_steps 一页操作需要进行的ecc 次数 + * @param {u8*} buf page 页 对应的指针 + * @param {u32} length + */ +// s32 FNandCorrectEcc(uintptr_t base_address,u32 ecc_step_size,u32 hw_ecc_steps,u8* buf ,u32 length) +// { +// u32 i, j; +// u32 value, tmp; +// int stat = 0; +// if(!buf) +// { +// FNAND_ECC_DEBUG_E("page buffer is null"); +// return -1; +// } + +// /* i */ +// for (i = 0; i < hw_ecc_steps; i++) +// { +// for (j = 0; j < 2; j++) { +// value = FNAND_READREG(base_address, 0xB8 + 4 * (2 * i + j)); +// FNAND_ECC_DEBUG_W("index:%x i is %d ,j is %d ", +// 0xB8 + 4 * (2 * i + j),i,j); +// if (value) +// { +// FNAND_ECC_DEBUG_W("offset:%x value:0x%08x\n", +// 0xB8 + 4 * (2 * i + j), value); +// //phytium_nfc_data_dump2(nfc, nfc->dma_buf + (ecc_step_size * i + tmp/8)/512, 512); +// } + +// tmp = value & 0xFFFF; +// if (tmp && (tmp <= 4096)) +// { +// tmp -= 1; +// FNAND_ECC_DEBUG_W( "ECC_CORRECT %x %02x\n", +// ecc_step_size * i + tmp / 8, +// buf[ecc_step_size * i + tmp / 8]); + +// buf[ecc_step_size*i + tmp/8] ^= (0x01 << tmp%8); +// stat++; + +// FNAND_ECC_DEBUG_W( "ECC_CORRECT xor %x %02x\n", +// 0x01 << tmp % 8, +// buf[ecc_step_size * i + tmp / 8]); +// } +// else +// { +// FNAND_ECC_DEBUG_E("ECC_CORRECT offset > 4096!\n"); +// } + +// tmp = (value >> 16) & 0xFFFF; +// if (tmp && (tmp <= 4096) ) +// { +// tmp -= 1; +// FNAND_ECC_DEBUG_W( "ECC_CORRECT %x %02x\n", +// ecc_step_size * i + tmp / 8, +// buf[ecc_step_size * i + tmp / 8]); + +// buf[ecc_step_size*i + tmp/8] ^= (0x01 << tmp%8); +// stat++; + +// FNAND_ECC_DEBUG_W( "ECC_CORRECT xor %x %02x\n", +// ecc_step_size * i + tmp / 8, +// buf[ecc_step_size * i + tmp / 8]); +// } +// else +// { +// FNAND_ECC_DEBUG_E("ECC_CORRECT offset > 4096!\n"); +// } +// } +// } + +// return stat; + +// } + +// 校验offset 0xb8 + i * 0x10 +// 校验强度为 2 j = 1 +// 校验强度为 4 j = 2 +// 校验强度为 8 j = 4 + + + + +s32 FNandCorrectEcc(uintptr_t base_address, u32 ecc_step_size, u32 hw_ecc_steps, u8 *buf, u32 length) +{ + u32 i, j; + u32 value, tmp; + int stat = 0; + if (!buf) + { + FNAND_ECC_DEBUG_E("page buffer is null"); + return -1; + } + + /* i */ + for (i = 0; i < hw_ecc_steps; i++) + { + for (j = 0; j < 4; j++) + { + // value = FNAND_READREG(base_address, 0xB8 + 4 * (2 * i + j)); + value = FNAND_READREG(base_address, 0xB8 + 0x10 * i + 4 * j); + // FNAND_ECC_DEBUG_W("index:%x i is %d ,j is %d ", + // 0xB8 + 0x10 * i + 4*j,i,j); + if (value) + { + // FNAND_ECC_DEBUG_W("offset:%x value:0x%08x\n", + // 0xB8 + 0x10 * i + 4*j, value); + //phytium_nfc_data_dump2(nfc, nfc->dma_buf + (ecc_step_size * i + tmp/8)/512, 512); + } + + tmp = value & 0xFFFF; + if (tmp && (tmp <= 4096)) + { + tmp -= 1; + FNAND_ECC_DEBUG_W("ECC_CORRECT %x %02x\n", + ecc_step_size * i + tmp / 8, + buf[ecc_step_size * i + tmp / 8]); + + buf[ecc_step_size * i + tmp / 8] ^= (0x01 << tmp % 8); + stat++; + + FNAND_ECC_DEBUG_W("ECC_CORRECT xor %x %02x\n", + 0x01 << tmp % 8, + buf[ecc_step_size * i + tmp / 8]); + } + + + tmp = (value >> 16) & 0xFFFF; + if (tmp && (tmp <= 4096)) + { + tmp -= 1; + FNAND_ECC_DEBUG_W("ECC_CORRECT %x %02x\n", + ecc_step_size * i + tmp / 8, + buf[ecc_step_size * i + tmp / 8]); + + buf[ecc_step_size * i + tmp / 8] ^= (0x01 << tmp % 8); + stat++; + + FNAND_ECC_DEBUG_W("ECC_CORRECT xor %x %02x\n", + ecc_step_size * i + tmp / 8, + buf[ecc_step_size * i + tmp / 8]); + } + + } + } + + return stat; + +} + + + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_ecc.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_ecc.h new file mode 100644 index 0000000000..3c0bbe5bd9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_ecc.h @@ -0,0 +1,45 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_ecc.h + * Date: 2022-05-12 11:17:42 + * LastEditTime: 2022-05-12 13:56:27 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_NAND_FNAND_ECC_H +#define DRIVERS_NAND_FNAND_ECC_H + +#include "ftypes.h" +#include "fnand_hw.h" +#include "stdio.h" + +static inline void FNandEnableHwEcc(uintptr_t base_address) +{ + FNAND_SETBIT(base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_EN_MASK); + // printf("base_address is %p ,value is 0x%x \r\n",base_address,FNAND_READREG(base_address,FNAND_CTRL0_OFFSET)); +} + + +static inline void FNandDisableHwEcc(uintptr_t base_address) +{ + FNAND_CLEARBIT(base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_EN_MASK); +} + +u32 FNandGetEccTotalLength(u32 bytes_per_page, u32 ecc_strength); +s32 FNandCorrectEcc(uintptr_t base_address, u32 ecc_step_size, u32 hw_ecc_steps, u8 *buf, u32 length); +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_g.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_g.c new file mode 100644 index 0000000000..4686dbe832 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_g.c @@ -0,0 +1,40 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:31 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fnand.h" +#include "fnand_hw.h" +#include "fparameters.h" + + +FNandConfig FNandConfigTable[FNAND_NUM] = +{ + { + .instance_id = FNAND_INSTANCE0, /* Id of device*/ + .irq_num = FNAND_IRQ_NUM, /* Irq number */ + .base_address = FNAND_BASEADDRESS, + .ecc_strength = 8, /* 每次ecc 步骤纠正的位数 */ + .ecc_step_size = 512 /* 进行读写操作时,单次ecc 的步骤的跨度 */ + }, +}; + + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_hw.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_hw.c new file mode 100644 index 0000000000..e72a98a260 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_hw.c @@ -0,0 +1,58 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:36 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fnand_hw.h" +#include "fnand.h" + + + +void FNandEnable(uintptr_t base_address) +{ + FNAND_SETBIT(base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_EN_MASK); /* 使能控制器 */ +} + + +void FNandHwReset(uintptr_t base_address) +{ + FNAND_WRITEREG(base_address, FNAND_INTRMASK_OFFSET, FNAND_INTRMASK_ALL_INT_MASK); /* 屏蔽所有中断位 */ + FNAND_WRITEREG(base_address, FNAND_STATE_OFFSET, FNAND_STATE_ALL_BIT); /* 清空所有状态位 */ + FNAND_WRITEREG(base_address, FNAND_ERROR_CLEAR_OFFSET, FNAND_ERROR_ALL_CLEAR); /* 清除所有错误位 */ + FNAND_WRITEREG(base_address, FNAND_FIFO_FREE_OFFSET, FNAND_FIFO_FREE_MASK); /* 清空fifo */ + // FNAND_CLEARBIT(base_address,FNAND_CTRL0_OFFSET,FNAND_CTRL0_SPARE_SIZE_EN_MASK|FNAND_CTRL0_ECC_EN_MASK ); /* 关闭ECC 位、并且关闭spare size 有效位 */ +} + + +void FNandHwInit(uintptr_t base_address, FNandInterMode inter_mode) +{ + // FNAND_WRITEREG(base_address, FNAND_CTRL1_OFFSET, FNAND_CTRL1_SAMPL_PHASE_MAKE(1UL)); /* 读取数据时的采样速度 */ + FNAND_SETBIT(base_address, FNAND_CTRL1_OFFSET, FNAND_CTRL1_SAMPL_PHASE_MAKE(5UL)); + FNAND_CLEARBIT(base_address, FNAND_CTRL1_OFFSET, FNAND_CTRL1_ECC_DATA_FIRST_EN_MASK); + + // FNAND_SETBIT(base_address, FNAND_CTRL1_OFFSET, FNAND_CTRL1_ECC_DATA_FIRST_EN_MASK); /* 开启先读取ECC 数据,然后读入对应数据 */ + FNAND_WRITEREG(base_address, FNAND_INTERVAL_OFFSET, FNAND_INTERVAL_TIME_MAKE(1UL)); /* 命令 、地址、数据之间的时间间隔 */ + FNAND_WRITEREG(base_address, FNAND_FIFO_LEVEL0_FULL_OFFSET, FNAND_FIFO_LEVEL0_FULL_THRESHOLD_MASK & 4); /* 满阈值配置 1/2 full, default 0 */ + FNAND_WRITEREG(base_address, FNAND_FIFO_LEVEL1_EMPTY_OFFSET, FNAND_FIFO_LEVEL1_EMPTY_THRESHOLD_MASK & 4); /* 空阈值配置 1/2 empty, default 0 */ + FNAND_WRITEREG(base_address, FNAND_FIFO_FREE_OFFSET, FNAND_FIFO_FREE_MASK); /* 清空fifo 操作 */ + FNAND_WRITEREG(base_address, FNAND_ERROR_CLEAR_OFFSET, FNAND_ERROR_CLEAR_DSP_ERR_CLR_MASK); /* 清除所有错误 */ + FNAND_WRITEREG(base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_ECC_CORRECT_MAKE(1UL) | FNAND_CTRL0_INTER_MODE((unsigned long)(inter_mode))); /* 纠错为2位 ,使用配置的模式 */ +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_hw.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_hw.h new file mode 100644 index 0000000000..cf71a2d04c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_hw.h @@ -0,0 +1,320 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:40 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_NAND_FNAND_HW_H +#define DRIVERS_NAND_FNAND_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fkernel.h" +#include "ftypes.h" +#include "fio.h" +#include "fkernel.h" + +#define FNAND_CTRL0_OFFSET 0x00000000U +#define FNAND_CTRL1_OFFSET 0x00000004U +#define FNAND_MADDR0_OFFSET 0x00000008U +#define FNAND_MADDR1_OFFSET 0x0000000CU +/* ASY */ +#define FNAND_ASY_TIMING0_OFFSET 0x00000010U +#define FNAND_ASY_TIMING1_OFFSET 0x00000014U +#define FNAND_ASY_TIMING2_OFFSET 0x00000018U +#define FNAND_ASY_TIMING3_OFFSET 0x0000001CU +#define FNAND_ASY_TIMING4_OFFSET 0x00000020U +#define FNAND_ASY_TIMING5_OFFSET 0x00000024U +/* SYN */ +#define FNAND_SYN_TIMING6_OFFSET 0x00000028U +#define FNAND_SYN_TIMING7_OFFSET 0x0000002CU +#define FNAND_SYN_TIMING8_OFFSET 0x00000030U +#define FNAND_SYN_TIMING9_OFFSET 0x00000034U +#define FNAND_SYN_TIMING10_OFFSET 0x00000038U +#define FNAND_SYN_TIMING11_OFFSET 0x0000003CU +#define FNAND_SYN_TIMING12_OFFSET 0x00000040U +/* TOG */ +#define FNAND_TOG_TIMING13_OFFSET 0x00000044U +#define FNAND_TOG_TIMING14_OFFSET 0x00000048U +#define FNAND_TOG_TIMING15_OFFSET 0x0000004CU +#define FNAND_TOG_TIMING16_OFFSET 0x00000050U +#define FNAND_TOG_TIMING17_OFFSET 0x00000054U +#define FNAND_TOG_TIMING18_OFFSET 0x00000058U + +#define FNAND_FIFORSTA_OFFSET 0x0000005CU +#define FNAND_INTERVAL_OFFSET 0x00000060U +#define FNAND_CMDINTERVAL_OFFSET 0x00000064U +#define FNAND_FIFO_TIMEOUT_OFFSET 0x00000068U +#define FNAND_FIFO_LEVEL0_FULL_OFFSET 0x0000006CU +#define FNAND_FIFO_LEVEL1_EMPTY_OFFSET 0x00000070U +#define FNAND_WP_OFFSET 0x00000074U +#define FNAND_FIFO_FREE_OFFSET 0x00000078U +#define FNAND_STATE_OFFSET 0x0000007CU +#define FNAND_INTRMASK_OFFSET 0x00000080U +#define FNAND_INTR_OFFSET 0x00000084U +#define FNAND_ERROR_CLEAR_OFFSET 0x0000008CU +#define FNAND_ERROR_LOCATION_OFFSET 0x000000B8U + +/* FNAND_CTRL0_OFFSET */ +#define FNAND_CTRL0_EN_MASK BIT(0) +#define FNAND_CTRL0_WIDTH_MASK BIT(1) /* DQ width, only for ONFI async mode. 0: 8bits, 1: 16bits*/ +#define FNAND_CTRL0_INTER_MODE(x) (min((x), (0x3UL)) << 2) /* Nand Flash interface mode. 00: ONFI Async; 01: ONFI Sync; 10: Toggle Async*/ +#define FNAND_CTRL0_ECC_EN_MASK BIT(4) /* Nand Flash hardware ECC enable */ +#define FNAND_CTRL0_ECC_CORRECT_MAKE(x) (min((x), (0x7UL)) << 5) /* Nand Flash ECC strength. 3'h2: 2bits; 3'h4: 4bits */ +#define FNAND_CTRL0_SPARE_SIZE_EN_MASK BIT(8) /* Data with spare */ +#define FNAND_CTRL0_SPARE_SIZE_MASK GENMASK(31, 9) /* Spare size */ + +/* FNAND_CTRL1_OFFSET */ +// #define FNAND_CTRL1_SAMPL_PHASE_MASK GENMASK(15,0) /* when onfi synchronization or toggle mode, the cycle of receive data sampling phase */ +#define FNAND_CTRL1_SAMPL_PHASE_MAKE(x) (min((x), GENMASK(15, 0))) /* when onfi synchronization or toggle mode, the cycle of receive data sampling phase */ +#define FNAND_CTRL1_ECC_DATA_FIRST_EN_MASK BIT(16) /* ECC data is read first and then the corresponding data is read */ +#define FNAND_CTRL1_RB_SHARE_EN_MASK BIT(17) /* The R/B signal sharing function of four devices is enabled. Write 1 is enabled */ +#define FNAND_CTRL1_ECC_BYPASS_MASK BIT(18) /* When the received ECC encoded address data is 13'hff, the ECC verification function is bypass. 1 indicates that the function is enabled */ + +/* FNAND_MADDR0_OFFSET */ +#define FNAND_MADDR0_DT_LOW_ADDR_MASK GENMASK(31, 0) /* The lower 32 bits of the descriptor table header address in memory storage */ + +/* FNAND_MADDR1_OFFSET */ +#define FNAND_MADDR1_DT_HIGH_8BITADDR_MASK GENMASK(7, 0) /* The high 8 bits of the first address of the descriptor table stored in memory */ +#define FNAND_MADDR1_DMA_EN_MASK BIT(8) /* DMA transfer enable bit. This bit is 1 for the controller to start DMA transfers */ +#define FNAND_MADDR1_DMA_READ_LENGTH_MASK GENMASK(23, 16) /* Sets the length to which dma reads data */ +#define FNAND_MADDR1_DMA_WRITE_LENGTH_MASK GENMASK(31, 24) /* Sets the length to which dma writes data */ + +/* FNAND_ASY_TIMING0_OFFSET */ +#define FNAND_ASY_TIMING0_TCLS_TWP_MASK GENMASK(31, 16) /* tCL-tWP */ +#define FNAND_ASY_TIMING0_TCLS_TCS_MASK GENMASK(15, 0) /* tCS-tCLS */ + +/* FNAND_ASY_TIMING1_OFFSET */ +#define FNAND_ASY_TIMING1_TWH_MASK GENMASK(31, 16) /* tWH */ +#define FNAND_ASY_TIMING1_TWP_MASK GENMASK(15, 0) /* tWP */ + +/* FNAND_ASY_TIMING2_OFFSET */ +#define FNAND_ASY_TIMING2_TCLH_TWH_MASK GENMASK(31, 16) /* tCLH-tWH */ +#define FNAND_ASY_TIMING2_TCH_TCLH_MASK GENMASK(15, 0) /* tCH-tCLH */ + +/* FNAND_ASY_TIMING3_OFFSET */ +#define FNAND_ASY_TIMING3_TCH_TWH_MASK GENMASK(31, 16) /* tCH-tWH */ +#define FNAND_ASY_TIMING3_TDQ_EN_MASK GENMASK(15, 0) + +/* FNAND_ASY_TIMING4_OFFSET */ +#define FNAND_ASY_TIMING4_TREH_MASK GENMASK(31, 16) /* TREH */ +#define FNAND_ASY_TIMING4_TWHR_MASK GENMASK(15, 0) /* TWHR */ + +/* FNAND_ASY_TIMING5_OFFSET */ +#define FNAND_ASY_TIMING5_TADL_MASK GENMASK(31, 16) +#define FNAND_ASY_TIMING5_TRC_MASK GENMASK(15, 0) + +/* FNAND_SYN_TIMING6_OFFSET */ +#define FNAND_SYN_TIMING6_TCALS_TCH_MASK GENMASK(31, 16) +#define FNAND_SYN_TIMING6_TRC_MASK GENMASK(15, 0) + +/* FNAND_SYN_TIMING7_OFFSET */ +#define FNAND_SYN_TIMING7_TDQ_EN_MASK GENMASK(31, 16) +#define FNAND_SYN_TIMING7_TCK_MASK GENMASK(15, 0) + +/* FNAND_SYN_TIMING8_OFFSET */ +#define FNAND_SYN_TIMING8_TCK_MASK GENMASK(31, 16) +#define FNAND_SYN_TIMING8_TCAD_TCK_MASK GENMASK(15, 0) + +/* FNAND_SYN_TIMING9_OFFSET */ +#define FNAND_SYN_TIMING9_TCCS_MASK GENMASK(31, 16) +#define FNAND_SYN_TIMING9_TWHR_MASK GENMASK(15, 0) + +/* FNAND_SYN_TIMING10_OFFSET */ +#define FNAND_SYN_TIMING10_TCK_MASK GENMASK(31, 16) +#define FNAND_SYN_TIMING10_MTCK_MASK GENMASK(15, 0) + +/* FNAND_SYN_TIMING11_OFFSET */ +#define FNAND_SYN_TIMING11_TCK_TCALS_MASK GENMASK(15, 0) + +/* FNAND_SYN_TIMING12_OFFSET */ +#define FNAND_SYN_TIMING12_TCKWR_MASK GENMASK(31, 16) +#define FNAND_SYN_TIMING12_TWRCK_MASK GENMASK(15, 0) + +/* FNAND_TOG_TIMING13_OFFSET */ +#define FNAND_TOG_TIMING13_TWRPST_MASK GENMASK(31, 16) +#define FNAND_TOG_TIMING13_TWPRE_MASK GENMASK(15, 0) + +/* FNAND_TOG_TIMING14_OFFSET */ +#define FNAND_TOG_TIMING14_TCLS_TWP_MASK GENMASK(31, 16) +#define FNAND_TOG_TIMING14_TCS_TCLS_MASK GENMASK(15, 0) + +/* FNAND_TOG_TIMING15_OFFSET */ +#define FNAND_TOG_TIMING15_TWHR_MASK GENMASK(31, 16) +#define FNAND_TOG_TIMING15_TADL_MASK GENMASK(15, 0) + +/* FNAND_TOG_TIMING16_OFFSET */ +#define FNAND_TOG_TIMING16_TCLH_TWH_MASK GENMASK(31, 16) +#define FNAND_TOG_TIMING16_TCH_TCLH_MASK GENMASK(15, 0) + +/* FNAND_TOG_TIMING17_OFFSET */ +#define FNAND_TOG_TIMING17_TRPST_MASK GENMASK(31, 16) +#define FNAND_TOG_TIMING17_TRPRE_MASK GENMASK(15, 0) + +/* FNAND_TOG_TIMING18_OFFSET */ +#define FNAND_TOG_TIMING18_TRPSTH_MASK GENMASK(31, 16) +#define FNAND_TOG_TIMING18_DSC_MASK GENMASK(15, 0) + +/* FNAND_FIFORSTA_OFFSET */ +#define FNAND_FIFORSTA_FIFO_FULL_MASK BIT(11) +#define FNAND_FIFORSTA_FIFO_EMPTY_MASK BIT(10) +#define FNAND_FIFORSTA_FIFO_COUNT_MASK GENMASK(9, 0) + +/* FNAND_INTERVAL_OFFSET */ +// #define FNAND_INTERVAL_TIME_MASK GENMASK(15,0) /* The interval between commands, addresses, and data. The timeout increases by 2ns for every 1 increase in the write value */ +#define FNAND_INTERVAL_TIME_MAKE(x) (min((x), (0xFFUL))) + +/* FNAND_CMDINTERVAL_OFFSET */ +#define FNAND_CMDINTERVAL_MASK GENMASK(31, 0) /* The interval between requests. The timeout increases by 2ns for every 1 increase in the write value */ + +/* FNAND_FIFO_TIMEOUT_OFFSET */ +#define FNAND_FIFO_TIMEOUT_MASK GENMASK(31, 0) /* FIFO timeout counter, the timeout time increases by 2ns for each increment of the value written */ + +/* FNAND_FIFO_LEVEL0_FULL_OFFSET */ +#define FNAND_FIFO_LEVEL0_FULL_THRESHOLD_MASK GENMASK(3, 0) + +/* FNAND_FIFO_LEVEL1_EMPTY_OFFSET */ +#define FNAND_FIFO_LEVEL1_EMPTY_THRESHOLD_MASK GENMASK(3, 0) + +/* FNAND_WP_OFFSET */ +#define FNAND_WP_EN_MASK BIT(0) + +/* FNAND_FIFO_FREE_OFFSET */ +#define FNAND_FIFO_FREE_MASK BIT(0) + +/* FNAND_STATE_OFFSET */ +#define FNAND_STATE_BUSY_OFFSET BIT(0) /* nandflash控制器忙 */ +#define FNAND_STATE_DMA_BUSY_OFFSET BIT(1) /* dma控制器忙 */ +#define FNAND_STATE_DMA_PGFINISH_OFFSET BIT(2) /* dma数据操作完成 */ +#define FNAND_STATE_DMA_FINISH_OFFSET BIT(3) /* dma完成 */ +#define FNAND_STATE_FIFO_EMP_OFFSET BIT(4) +#define FNAND_STATE_FIFO_FULL_OFFSET BIT(5) +#define FNAND_STATE_FIFO_TIMEOUT_OFFSET BIT(6) +#define FNAND_STATE_CS_OFFSET GENMASK(10, 7) +#define FNAND_STATE_CMD_PGFINISH_OFFSET BIT(11) /* nand接口命令操作完成 */ +#define FNAND_STATE_PG_PGFINISH_OFFSET BIT(12) /* nand接口数据操作完成 */ +#define FNAND_STATE_RE_OFFSET BIT(13) /* re_n门控状态 */ +#define FNAND_STATE_DQS_OFFSET BIT(14) /* dqs门控状态 */ +#define FNAND_STATE_RB_OFFSET BIT(15) /* RB_N接口的状态 */ +#define FNAND_STATE_ECC_BUSY_OFFSET BIT(16) +#define FNAND_STATE_ECC_FINISH_OFFSET BIT(17) +#define FNAND_STATE_ECC_RIGHT_OFFSET BIT(18) +#define FNAND_STATE_ECC_ERR_OFFSET BIT(19) /* ECC 校验有错 */ +#define FNAND_STATE_ECC_ERROVER_OFFSET BIT(20) /* 错误超过可校验范围 */ +#define FNAND_STATE_AXI_DSP_ERR_OFFSET BIT(21) /* 描述符错误 */ +#define FNAND_STATE_AXI_RD_ERR_OFFSET BIT(22) +#define FNAND_STATE_AXI_WR_ERR_OFFSET BIT(23) +#define FNAND_STATE_RB_N_OFFSET GENMASK(27, 24) +#define FNAND_STATE_PROT_ERR_OFFSET BIT(28) +#define FNAND_STATE_ECCBYPASS_STA_OFFSET BIT(29) +#define FNAND_STATE_ALL_BIT GENMASK(29, 0) + +/* FNAND_INTRMASK_OFFSET */ +#define FNAND_INTRMASK_ALL_INT_MASK GENMASK(17, 0) +#define FNAND_INTRMASK_BUSY_MASK BIT(0) /* nandflash控制器忙状态中断屏蔽位 */ +#define FNAND_INTRMASK_DMA_BUSY_MASK BIT(1) /* dma控制器忙状态中断屏蔽位 */ +#define FNAND_INTRMASK_DMA_PGFINISH_MASK BIT(2) /* dma页操作完成中断屏蔽位 */ +#define FNAND_INTRMASK_DMA_FINISH_MASK BIT(3) /* dma操作完成中断完成中断屏蔽位 */ +#define FNAND_INTRMASK_FIFO_EMP_MASK BIT(4) /* fifo为空中断屏蔽位 */ +#define FNAND_INTRMASK_FIFO_FULL_MASK BIT(5) /* fifo为满中断屏蔽位 */ +#define FNAND_INTRMASK_FIFO_TIMEOUT_MASK BIT(6) /* fifo超时中断屏蔽位 */ +#define FNAND_INTRMASK_CMD_FINISH_MASK BIT(7) /* nand接口命令完成中断屏蔽位 */ +#define FNAND_INTRMASK_PGFINISH_MASK BIT(8) /* nand接口页操作完成中断屏蔽位 */ +#define FNAND_INTRMASK_RE_MASK BIT(9) /* re_n门控打开中断屏蔽位 */ +#define FNAND_INTRMASK_DQS_MASK BIT(10) /* dqs门控打开中断屏蔽位 */ +#define FNAND_INTRMASK_RB_MASK BIT(11) /* rb_n信号busy中断屏蔽位 */ +#define FNAND_INTRMASK_ECC_FINISH_MASK BIT(12) /* ecc完成中断屏蔽位 */ +#define FNAND_INTRMASK_ECC_ERR_MASK BIT(13) /* ecc 中断屏蔽位 */ + +/* FNAND_INTR_OFFSET */ +#define FNAND_INTR_ALL_INT_MASK GENMASK(17, 0) +#define FNAND_INTR_BUSY_MASK BIT(0) /* nandflash控制器忙状态中断状态位 */ +#define FNAND_INTR_DMA_BUSY_MASK BIT(1) /* dma控制器忙状态中断状态位 */ +#define FNAND_INTR_DMA_PGFINISH_MASK BIT(2) /* dma页操作完成中断状态位 */ +#define FNAND_INTR_DMA_FINISH_MASK BIT(3) /* dma操作完成中断完成中断状态位 */ +#define FNAND_INTR_FIFO_EMP_MASK BIT(4) /* fifo为空中断状态位 */ +#define FNAND_INTR_FIFO_FULL_MASK BIT(5) /* fifo为满中断状态位 */ +#define FNAND_INTR_FIFO_TIMEOUT_MASK BIT(6) /* fifo超时中断状态位 */ +#define FNAND_INTR_CMD_FINISH_MASK BIT(7) /* nand接口命令完成中断状态位 */ +#define FNAND_INTR_PGFINISH_MASK BIT(8) /* nand接口页操作完成中断状态位 */ +#define FNAND_INTR_RE_MASK BIT(9) /* re_n门控打开中断状态位 */ +#define FNAND_INTR_DQS_MASK BIT(10) /* dqs门控打开中断状态位 */ +#define FNAND_INTR_RB_MASK BIT(11) /* rb_n信号busy中断状态位 */ +#define FNAND_INTR_ECC_FINISH_MASK BIT(12) /* ecc完成中断状态蔽位 */ +#define FNAND_INTR_ECC_ERR_MASK BIT(13) /* ecc正确中断状态蔽位 */ + +/* FNAND_ERROR_CLEAR_OFFSET */ +#define FNAND_ERROR_CLEAR_DSP_ERR_CLR_MASK BIT(0) +#define FNAND_ERROR_CLEAR_AXI_RD_ERR_CLR_MASK BIT(1) +#define FNAND_ERROR_CLEAR_AXI_WR_ERR_CLR_MASK BIT(2) +#define FNAND_ERROR_CLEAR_ECC_ERR_CLR_MASK BIT(3) +#define FNAND_ERROR_ALL_CLEAR GENMASK(3, 0) + +#define FNAND_SELETED_MAX_NUMBER 4 + + + +/** +* +* This macro reads the given register. +* +* @param base_addr is the base address of the device. +* @param reg_offset is the register offset to be read. +* +* @return The 32-bit value of the register +* +* @note None. +* +*****************************************************************************/ +#define FNAND_READREG(base_addr, reg_offset) \ + FtIn32((base_addr) + (u32)(reg_offset)) + +/****************************************************************************/ +/** +* +* This macro writes the given register. +* +* @param base_addr is the base address of the device. +* @param reg_offset is the register offset to be written. +* @param data is the 32-bit value to write to the register. +* +* @return None. +* +* @note None. +* +*****************************************************************************/ +#define FNAND_WRITEREG(base_addr, reg_offset, data) \ + FtOut32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FNAND_SETBIT(base_addr, reg_offset, data) \ + FtSetBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FNAND_CLEARBIT(base_addr, reg_offset, data) \ + FtClearBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_id.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_id.c new file mode 100644 index 0000000000..4b6c90713f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_id.c @@ -0,0 +1,264 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_id.c + * Date: 2022-07-06 08:34:27 + * LastEditTime: 2022-07-06 08:34:27 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ +#include "fdebug.h" +#include "fnand.h" +#include "fnand_id.h" +#include "fnand_common_cmd.h" +#include "fdebug.h" +#include "fkernel.h" +#include "sdkconfig.h" + +#define CONFIG_FNAND_ID_DEBUG_EN +#define FNAND_ID_DEBUG_TAG "FNAND_ID" +#ifdef CONFIG_FNAND_ID_DEBUG_EN + + #define FNAND_ID_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_ID_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_ID_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_ID_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_ID_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_ID_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_ID_DEBUG_D(format, ...) FT_DEBUG_PRINT_D(FNAND_ID_DEBUG_TAG, format, ##__VA_ARGS__) +#else + #define FNAND_ID_DEBUG_I(format, ...) + #define FNAND_ID_DEBUG_W(format, ...) + #define FNAND_ID_DEBUG_E(format, ...) + #define FNAND_ID_DEBUG_D(format, ...) +#endif + + +/* + * NAND Flash Manufacturer ID Codes + */ +#define NAND_MFR_TOSHIBA 0x98 + + +/* Cell info constants */ +#define NAND_CI_CHIPNR_MSK 0x03 +#define NAND_CI_CELLTYPE_MSK 0x0C +#define NAND_CI_CELLTYPE_SHIFT 2 + + + +#define NAND_MAX_ID_LEN 8 + + + +extern FError FNandToggleInit(FNand *instance_p, u32 chip_addr); +extern FError FNandOnfiInit(FNand *instance_p, u32 chip_addr); +extern FError FNandTimingInterfaceUpdate(FNand *instance_p, u32 chip_addr); + +extern const struct FNandManuFacturerOps toshiba_ops; + +static const FNandManuFacturer fnand_manufacturers[] = +{ + {NAND_MFR_TOSHIBA, "Toshiba", &toshiba_ops}, +}; + +static int FnandIdHasPeriod(u8 *id_data_p, int arrlen, int period) +{ + int i, j; + for (i = 0; i < period; i++) + for (j = i + period; j < arrlen; j += period) + if (id_data_p[i] != id_data_p[j]) + return 0; + return 1; +} + +static int FNandIdLen(u8 *id_data_p, int data_length) +{ + int last_nonzero, period; + + for (last_nonzero = data_length - 1; last_nonzero >= 0; last_nonzero--) + if (id_data_p[last_nonzero]) + break; + + /* All zeros */ + if (last_nonzero < 0) + return 0; + + /* Calculate wraparound period */ + for (period = 1; period < data_length; period++) + if (FnandIdHasPeriod(id_data_p, data_length, period)) + break; + + /* There's a repeated pattern */ + if (period < data_length) + return period; + + /* There are trailing zeros */ + if (last_nonzero < data_length - 1) + return last_nonzero + 1; + + /* No pattern detected */ + return data_length; + +} + + +const FNandManuFacturer *FNandGetManuFacturer(u8 id) +{ + u32 i; + + for (i = 0; i < ARRAY_SIZE(fnand_manufacturers); i++) + { + if (fnand_manufacturers[i].id == id) + { + return &fnand_manufacturers[i]; + } + } + return NULL; +} + + +static FError FNandIdDetect(FNand *instance_p, u32 chip_addr) +{ + FError ret; + u32 i; + FNandId nand_id; + u8 *id_data = (u8 *)&nand_id.data; + u8 maf_id, dev_id; + const FNandManuFacturer *manufacturer_p ; + + + ret = FNandFlashReset(instance_p, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_E("FNandFlashReset is error"); + return ret; + } + + /* step2 read device ID */ + ret = FNandFlashReadId(instance_p, 0, id_data, 2, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_E("FNandFlashReadId is error"); + return ret; + } + + /* Read manufacturer and device IDs */ + maf_id = id_data[0]; + dev_id = id_data[1]; + + /* step 3 get entire device ID*/ + ret = FNandFlashReadId(instance_p, 0, id_data, sizeof(nand_id.data), chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_E("FNandFlashReadId is error"); + return ret; + } + /* step 5 compare ID string and device id */ + if (id_data[0] != maf_id || id_data[1] != dev_id) + { + FNAND_ID_DEBUG_E("second ID read did not match %02x,%02x against %02x,%02x\n", + maf_id, dev_id, id_data[0], id_data[1]); + return FNAND_ERR_NOT_MATCH; + } + + nand_id.len = FNandIdLen(id_data, ARRAY_SIZE(nand_id.data)); + + /* step 6 通过maf_id获取对应的参数 */ + manufacturer_p = FNandGetManuFacturer(maf_id); + + if (manufacturer_p == NULL) + { + FNAND_ID_DEBUG_E("Manufacturer not in list"); + return FNAND_ERR_NOT_MATCH; + } + + FNAND_ID_DEBUG_I("find manufacturer"); + if (manufacturer_p->ops->detect) + { + FNAND_ID_DEBUG_I("manufacturer_p->ops->detect"); + return manufacturer_p->ops->detect(instance_p, &nand_id, chip_addr); + } + else + { + FNAND_ID_DEBUG_E("manufacturer detect is empty"); + return FNAND_ERR_NOT_MATCH; + } + + return FT_SUCCESS; +} + +FError FNandDetect(FNand *instance_p) +{ + FError ret; + u32 i = 0; + + for (i = 0; i < FNAND_CONNECT_MAX_NUM; i++) + { + ret = FNandIdDetect(instance_p, i); + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_W("normal flash is not found"); + } + else + { + FNandFlashFuncRegister(instance_p) ; + FNAND_ID_DEBUG_I("Normal flash is found"); + continue; + } + + + ret = FNandToggleInit(instance_p, i); /* toggle 1.0 */ + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_W("toggle flash is not found"); + } + else + { + FNAND_ID_DEBUG_I("Scan %d nand is toggle mode", i); + instance_p->nand_flash_interface[i] = FNAND_TOGGLE_MODE; + ret = FNandTimingInterfaceUpdate(instance_p, i); + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_E("FNandTimingInterfaceUpdate is error"); + return ret; + } + /* open ecc length config */ + FNandFlashFuncRegister(instance_p) ; + FNAND_ID_DEBUG_I("Toggle flash is found"); + continue; + } + + ret = FNandOnfiInit(instance_p, i); + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_W("Onfi flash is not found"); + } + else + { + instance_p->nand_flash_interface[i] = FNAND_ONFI_MODE; + ret = FNandTimingInterfaceUpdate(instance_p, i); + if (ret != FT_SUCCESS) + { + FNAND_ID_DEBUG_E("FNandTimingInterfaceUpdate is error"); + return ret; + } + /* open ecc length config ,需要确保 ecc 校验的空间必须小于oob 的空间*/ + FNandFlashFuncRegister(instance_p) ; + FNAND_ID_DEBUG_I("Onfi flash is found"); + continue; + } + + } + return FT_SUCCESS; +} diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_id.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_id.h new file mode 100644 index 0000000000..ccc80290c2 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_id.h @@ -0,0 +1,53 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_id.h + * Date: 2022-07-06 14:19:15 + * LastEditTime: 2022-07-06 14:19:15 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + + +#ifndef DRIVERS_NAND_DRIVER_FNAND +#define DRIVERS_NAND_DRIVER_FNAND + + +#include "ftypes.h" +#include "fnand.h" + + + + +struct FNandManuFacturerOps +{ + FError(*detect)(FNand *instance_p, FNandId *id_p, u32 chip_addr); /* detect chip */ + int (*init)(FNand *instance_p, u32 chip_addr); + void (*cleanup)(FNand *instance_p, u32 chip_addr); +}; + + +typedef struct +{ + int id; + char *name; + const struct FNandManuFacturerOps *ops; +} FNandManuFacturer; + +FError FNandDetect(FNand *instance_p); + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_intr.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_intr.c new file mode 100644 index 0000000000..b4bdb48ea8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_intr.c @@ -0,0 +1,203 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:46 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fnand.h" +#include "fnand_hw.h" +#include "fassert.h" +#include "ferror_code.h" + +#include "fdebug.h" +#define FNAND_INTR_DEBUG_TAG "FNAND_INTR" +#define FNAND_INTR_ERROR(format, ...) FT_DEBUG_PRINT_E(FNAND_INTR_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_INTR_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_INTR_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_INTR_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_INTR_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_INTR_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_INTR_DEBUG_TAG, format, ##__VA_ARGS__) + + +/** + * @name: FNandIsrEnable + * @msg: Enable the corresponding interrupt based on the interrupt mask + * @return {*} + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance + * @param {u32} int_mask is interrupt mask + */ +void FNandIsrEnable(FNand *instance_p, u32 int_mask) +{ + u32 reg_value; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FNandConfig *config_p; + config_p = &instance_p->config; + + FNAND_CLEARBIT(config_p->base_address, FNAND_INTRMASK_OFFSET, int_mask); +} + +/** + * @name: FNandIrqDisable + * @msg: Disable the corresponding interrupt based on the interrupt mask + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance + * @param {u32} int_mask is interrupt mask + * @return {*} + */ +void FNandIrqDisable(FNand *instance_p, u32 int_mask) +{ + u32 reg_value; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FNandConfig *config_p; + config_p = &instance_p->config; + + FNAND_SETBIT(config_p->base_address, FNAND_INTRMASK_OFFSET, int_mask); +} + + +/** + * @name: FNandSetIsrHandler + * @msg: Initializes isr event callback function + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {FnandIrqEventHandler} event_p is callback function used to respond to the interrupt event + * @param {void} *irq_args is the arguments of event callback + * @return {*} + */ +void FNandSetIsrHandler(FNand *instance_p, FnandIrqEventHandler event_p, void *irq_args) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + instance_p->irq_event_fun_p = event_p; + instance_p->irq_args = irq_args; +} + + +/** + * @name: FNandIrqHandler + * @msg: Nand driver isr handler + * @note: + * @param {s32} vector is interrupt number + * @param {void} *param is argument + * @return {*} + */ +void FNandIrqHandler(s32 vector, void *param) +{ + FNand *instance_p = (FNand *)param; + FNandConfig *config_p; + u32 status; + u32 en_irq; + (void)vector; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + + status = FNAND_READREG(config_p->base_address, FNAND_INTR_OFFSET); + en_irq = (~FNAND_READREG(config_p->base_address, FNAND_INTRMASK_OFFSET)) & FNAND_INTRMASK_ALL_INT_MASK; + + if ((status & en_irq) == 0) + { + FNAND_INTR_DEBUG_E("No irq exit"); + return; + } + + FNandIrqDisable(instance_p, status & FNAND_INTRMASK_ALL_INT_MASK); + FNAND_WRITEREG(config_p->base_address, 0xfd0, 0); + FNAND_WRITEREG(config_p->base_address, FNAND_INTR_OFFSET, status); + + if (instance_p->irq_event_fun_p) + { + if (status & FNAND_INTR_BUSY_MASK) + { + + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_BUSY_EVENT); + } + + if (status & FNAND_INTR_DMA_BUSY_MASK) + { + + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_DMA_BUSY_EVENT); + } + + if (status & FNAND_INTR_DMA_PGFINISH_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_DMA_PGFINISH_EVENT); + } + + if (status & FNAND_INTR_DMA_FINISH_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_DMA_FINISH_EVENT); + } + + if (status & FNAND_INTR_FIFO_EMP_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_FIFO_EMP_EVENT); + } + + if (status & FNAND_INTR_FIFO_FULL_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_FIFO_FULL_EVENT); + } + + if (status & FNAND_INTR_FIFO_TIMEOUT_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_FIFO_TIMEOUT_EVENT); + } + + if (status & FNAND_INTR_CMD_FINISH_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_CMD_FINISH_EVENT); + } + + if (status & FNAND_INTR_PGFINISH_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_PGFINISH_EVENT); + } + + if (status & FNAND_INTR_RE_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_RE_EVENT); + } + + if (status & FNAND_INTR_DQS_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_DQS_EVENT); + } + + if (status & FNAND_INTR_RB_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_RB_EVENT); + } + + if (status & FNAND_INTR_ECC_FINISH_MASK) + { + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_ECC_FINISH_EVENT); + } + + if (status & FNAND_INTR_ECC_ERR_MASK) + { + FNAND_WRITEREG(config_p->base_address, FNAND_ERROR_CLEAR_OFFSET, FNAND_ERROR_CLEAR_ECC_ERR_CLR_MASK); + FNAND_WRITEREG(config_p->base_address, FNAND_FIFO_FREE_OFFSET, FNAND_FIFO_FREE_MASK); + instance_p->irq_event_fun_p(instance_p->irq_args, FNAND_IRQ_ECC_ERR_EVENT); + } + } +} diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_option.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_option.c new file mode 100644 index 0000000000..285e17e946 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_option.c @@ -0,0 +1,59 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_option.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:51 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fnand.h" +#include "fnand_hw.h" + +/** + * @name: FNandSetOption + * @msg: + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} options is configuration options ,use FNAND_OPS_INTER_MODE_SELECT to select nand flash interface + * @param {u32} value is set value + * @return {FError} FT_SUCCESS set option is ok ,FNAND_ERR_INVAILD_PARAMETER options is invalid + */ +FError FNandSetOption(FNand *instance_p, u32 options, u32 value) +{ + u32 reg_value; + FNandConfig *config_p; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &instance_p->config; + + switch (options) + { + case FNAND_OPS_INTER_MODE_SELECT: + FASSERT(FNAND_TOG_ASYN_DDR >= value) ; + FNAND_CLEARBIT(config_p->base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_INTER_MODE(3UL)) ; + FNAND_SETBIT(config_p->base_address, FNAND_CTRL0_OFFSET, FNAND_CTRL0_INTER_MODE((unsigned long)value)) ; + break; + default: + return FNAND_ERR_INVAILD_PARAMETER; + } + + return FT_SUCCESS; +} + + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_sinit.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_sinit.c new file mode 100644 index 0000000000..f6e714ece0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_sinit.c @@ -0,0 +1,51 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:56:56 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fnand.h" +#include "fparameters.h" + +extern FNandConfig FNandConfigTable[FNAND_NUM] ; + +/** + * @name: FNandLookupConfig + * @msg: This function looks up the device configuration based on the unique device ID. + * @param {u32} instance_id contains the ID of the device + * @return {FNandConfig *} - A pointer to the configuration found . - NULL if the specified device ID is not found + */ +FNandConfig *FNandLookupConfig(u32 instance_id) +{ + FNandConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FNAND_NUM; index++) + { + if (FNandConfigTable[index].instance_id == instance_id) + { + ptr = &FNandConfigTable[index]; + break; + } + } + + return (FNandConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_timing.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_timing.c new file mode 100644 index 0000000000..d8c364485a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_timing.c @@ -0,0 +1,467 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_timing.c + * Date: 2022-05-09 14:53:42 + * LastEditTime: 2022-05-09 08:56:27 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "ferror_code.h" +#include "fnand.h" +#include "fnand_hw.h" + +#include "fdebug.h" +#define FNAND_TIMING_DEBUG_TAG "FNAND_TIMING" +#define FNAND_TIMING_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_TIMING_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_TIMING_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_TIMING_DEBUG_TAG, format, ##__VA_ARGS__) +#define FNAND_TIMING_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_TIMING_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FNAND_TIMING_ASY_NUM 12 +#define FNAND_TIMING_SYN_NUM 14 +#define FNAND_TIMING_TOG_NUM 12 + +const u16 fnand_timing_asy_mode0[FNAND_TIMING_ASY_NUM] = {0x03, 0x03, 0x28, 0x28, 0x03, 0x03, 0x06, 0x06, 0x28, 0x70, 0x30, 0x50}; +const u16 fnand_timing_asy_mode1[FNAND_TIMING_ASY_NUM] = {0x03, 0x03, 0x14, 0x14, 0x03, 0x03, 0x06, 0x06, 0x14, 0x70, 0x20, 0x28}; +const u16 fnand_timing_asy_mode2[FNAND_TIMING_ASY_NUM] = {0x03, 0x03, 0x0D, 0x0D, 0x03, 0x03, 0x06, 0x06, 0x0D, 0x70, 0x20, 0x1A}; +const u16 fnand_timing_asy_mode3[FNAND_TIMING_ASY_NUM] = {0x03, 0x03, 0x0A, 0x0A, 0x03, 0x03, 0x06, 0x06, 0x0A, 0x70, 0x20, 0x14}; +const u16 fnand_timing_asy_mode4[FNAND_TIMING_ASY_NUM] = {0x03, 0x03, 0x08, 0x08, 0x03, 0x03, 0x06, 0x06, 0x08, 0x70, 0x15, 0x10}; +const u16 fnand_timing_asy_mode5[FNAND_TIMING_ASY_NUM] = {0x03, 0x03, 0x07, 0x07, 0x03, 0x03, 0x06, 0x06, 0x07, 0x20, 0x15, 0x0E}; + +const u16 fnand_timing_syn_mode0[FNAND_TIMING_SYN_NUM] = {0x20, 0x41, 0x05, 0x20, 0x10, 0x19, 0x62, 0x40, 0x38, 0x20, 0x00, 0x09, 0x50, 0x20}; +const u16 fnand_timing_syn_mode1[FNAND_TIMING_SYN_NUM] = {0x18, 0x32, 0x06, 0x18, 0x0C, 0x10, 0x76, 0x40, 0x2A, 0x18, 0x00, 0x12, 0x24, 0x18}; +const u16 fnand_timing_syn_mode2[FNAND_TIMING_SYN_NUM] = {0x10, 0x0A, 0x04, 0x10, 0x08, 0x0A, 0x6E, 0x50, 0x1D, 0x10, 0x00, 0x0C, 0x18, 0x10}; +const u16 fnand_timing_syn_mode3[FNAND_TIMING_SYN_NUM] = {0x0C, 0x1A, 0x02, 0x0C, 0x06, 0x08, 0x78, 0x7C, 0x15, 0x0C, 0x00, 0x08, 0x12, 0x0C}; +const u16 fnand_timing_syn_mode4[FNAND_TIMING_SYN_NUM] = {0x08, 0x17, 0x05, 0x08, 0x04, 0x01, 0x73, 0x40, 0x0C, 0x08, 0x00, 0x06, 0x0C, 0x10}; + +const u16 fnand_timing_tog_ddr_mode0[FNAND_TIMING_TOG_NUM] = {0x14, 0x0a, 0x08, 0x08, 0xc8, 0xc8, 0x08, 0x08, 0x14, 0x0a, 0x14, 0x08}; /* 600M clk */ + + +#define ONFI_DYN_TIMING_MAX ((u16)~0U) + +static const struct FNandSdrTimings onfi_sdr_timings[] = +{ + { + .tCCS_min = 500000, + .tR_max = 200000000, + .tADL_min = 400000, + .tALH_min = 20000, + .tALS_min = 50000, + .tAR_min = 25000, + .tCEA_max = 100000, + .tCEH_min = 20000, + .tCH_min = 20000, + .tCHZ_max = 100000, + .tCLH_min = 20000, + .tCLR_min = 20000, + .tCLS_min = 50000, + .tCOH_min = 0, + .tCS_min = 70000, + .tDH_min = 20000, + .tDS_min = 40000, + .tFEAT_max = 1000000, + .tIR_min = 10000, + .tITC_max = 1000000, + .tRC_min = 100000, + .tREA_max = 40000, + .tREH_min = 30000, + .tRHOH_min = 0, + .tRHW_min = 200000, + .tRHZ_max = 200000, + .tRLOH_min = 0, + .tRP_min = 50000, + .tRR_min = 40000, + .tRST_max = 250000000000ULL, + .tWB_max = 200000, + .tWC_min = 100000, + .tWH_min = 30000, + .tWHR_min = 120000, + .tWP_min = 50000, + .tWW_min = 100000, + }, + + /* Mode 1 */ + { + .tCCS_min = 500000, + .tR_max = 200000000, + .tADL_min = 400000, + .tALH_min = 10000, + .tALS_min = 25000, + .tAR_min = 10000, + .tCEA_max = 45000, + .tCEH_min = 20000, + .tCH_min = 10000, + .tCHZ_max = 50000, + .tCLH_min = 10000, + .tCLR_min = 10000, + .tCLS_min = 25000, + .tCOH_min = 15000, + .tCS_min = 35000, + .tDH_min = 10000, + .tDS_min = 20000, + .tFEAT_max = 1000000, + .tIR_min = 0, + .tITC_max = 1000000, + .tRC_min = 50000, + .tREA_max = 30000, + .tREH_min = 15000, + .tRHOH_min = 15000, + .tRHW_min = 100000, + .tRHZ_max = 100000, + .tRLOH_min = 0, + .tRP_min = 25000, + .tRR_min = 20000, + .tRST_max = 500000000, + .tWB_max = 100000, + .tWC_min = 45000, + .tWH_min = 15000, + .tWHR_min = 80000, + .tWP_min = 25000, + .tWW_min = 100000, + }, + + /* Mode 2 */ + { + .tCCS_min = 500000, + .tR_max = 200000000, + .tADL_min = 400000, + .tALH_min = 10000, + .tALS_min = 15000, + .tAR_min = 10000, + .tCEA_max = 30000, + .tCEH_min = 20000, + .tCH_min = 10000, + .tCHZ_max = 50000, + .tCLH_min = 10000, + .tCLR_min = 10000, + .tCLS_min = 15000, + .tCOH_min = 15000, + .tCS_min = 25000, + .tDH_min = 5000, + .tDS_min = 15000, + .tFEAT_max = 1000000, + .tIR_min = 0, + .tITC_max = 1000000, + .tRC_min = 35000, + .tREA_max = 25000, + .tREH_min = 15000, + .tRHOH_min = 15000, + .tRHW_min = 100000, + .tRHZ_max = 100000, + .tRLOH_min = 0, + .tRR_min = 20000, + .tRST_max = 500000000, + .tWB_max = 100000, + .tRP_min = 17000, + .tWC_min = 35000, + .tWH_min = 15000, + .tWHR_min = 80000, + .tWP_min = 17000, + .tWW_min = 100000, + }, + + /* Mode 3 */ + { + .tCCS_min = 500000, + .tR_max = 200000000, + .tADL_min = 400000, + .tALH_min = 5000, + .tALS_min = 10000, + .tAR_min = 10000, + .tCEA_max = 25000, + .tCEH_min = 20000, + .tCH_min = 5000, + .tCHZ_max = 50000, + .tCLH_min = 5000, + .tCLR_min = 10000, + .tCLS_min = 10000, + .tCOH_min = 15000, + .tCS_min = 25000, + .tDH_min = 5000, + .tDS_min = 10000, + .tFEAT_max = 1000000, + .tIR_min = 0, + .tITC_max = 1000000, + .tRC_min = 30000, + .tREA_max = 20000, + .tREH_min = 10000, + .tRHOH_min = 15000, + .tRHW_min = 100000, + .tRHZ_max = 100000, + .tRLOH_min = 0, + .tRP_min = 15000, + .tRR_min = 20000, + .tRST_max = 500000000, + .tWB_max = 100000, + .tWC_min = 30000, + .tWH_min = 10000, + .tWHR_min = 80000, + .tWP_min = 15000, + .tWW_min = 100000, + }, + /* Mode 4 */ + { + .tCCS_min = 500000, + .tR_max = 200000000, + .tADL_min = 400000, + .tALH_min = 5000, + .tALS_min = 10000, + .tAR_min = 10000, + .tCEA_max = 25000, + .tCEH_min = 20000, + .tCH_min = 5000, + .tCHZ_max = 30000, + .tCLH_min = 5000, + .tCLR_min = 10000, + .tCLS_min = 10000, + .tCOH_min = 15000, + .tCS_min = 20000, + .tDH_min = 5000, + .tDS_min = 10000, + .tFEAT_max = 1000000, + .tIR_min = 0, + .tITC_max = 1000000, + .tRC_min = 25000, + .tREA_max = 20000, + .tREH_min = 10000, + .tRHOH_min = 15000, + .tRHW_min = 100000, + .tRHZ_max = 100000, + .tRLOH_min = 5000, + .tRP_min = 12000, + .tRR_min = 20000, + .tRST_max = 500000000, + .tWB_max = 100000, + .tWC_min = 25000, + .tWH_min = 10000, + .tWHR_min = 80000, + .tWP_min = 12000, + .tWW_min = 100000, + }, + /* Mode 5 */ + { + .tCCS_min = 500000, + .tR_max = 200000000, + .tADL_min = 400000, + .tALH_min = 5000, + .tALS_min = 10000, + .tAR_min = 10000, + .tCEA_max = 25000, + .tCEH_min = 20000, + .tCH_min = 5000, + .tCHZ_max = 30000, + .tCLH_min = 5000, + .tCLR_min = 10000, + .tCLS_min = 10000, + .tCOH_min = 15000, + .tCS_min = 15000, + .tDH_min = 5000, + .tDS_min = 7000, + .tFEAT_max = 1000000, + .tIR_min = 0, + .tITC_max = 1000000, + .tRC_min = 20000, + .tREA_max = 16000, + .tREH_min = 7000, + .tRHOH_min = 15000, + .tRHW_min = 100000, + .tRHZ_max = 100000, + .tRLOH_min = 5000, + .tRP_min = 10000, + .tRR_min = 20000, + .tRST_max = 500000000, + .tWB_max = 100000, + .tWC_min = 20000, + .tWH_min = 7000, + .tWHR_min = 80000, + .tWP_min = 10000, + .tWW_min = 100000, + }, +}; + +static FError FNandMemcpyToReg16(FNand *instance_p, u32 reg, u32 reg_step, const u16 *buf, u32 len) +{ + u32 i; + u32 value = 0; + + if (!instance_p || !buf) + { + FNAND_TIMING_DEBUG_E("instance_p is %p ,buf is %p", instance_p, buf); + return FNAND_ERR_INVAILD_PARAMETER; + } + + for (i = 0; i < len; i++) + { + value = (value << 16) + buf[i]; + if (i % 2) + { + FNAND_WRITEREG(instance_p->config.base_address, reg, value); + value = 0; + reg += reg_step; + } + } + + return FT_SUCCESS; +} + +/** + * @name: + * @msg: 根据inter_mode 与 timing_mode + * @note: + * @return {*} + * @param {FNand} *instance_p + */ +FError FNandTimingInterfaceUpdate(FNand *instance_p, u32 chip_addr) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(chip_addr < FNAND_CONNECT_MAX_NUM); + const u16 *target_timming_data = NULL; + FNandConfig *config_p = &instance_p->config ; + u32 value = 0 ; + FError ret; + + FNandSetOption(instance_p, FNAND_OPS_INTER_MODE_SELECT, instance_p->inter_mode[chip_addr]); + + FNAND_CLEARBIT(config_p->base_address, FNAND_CTRL1_OFFSET, FNAND_CTRL1_SAMPL_PHASE_MAKE(0xffffUL)); /* clear sampl_phase */ + switch (instance_p->inter_mode[chip_addr]) + { + case FNAND_ASYN_SDR: + if (FNAND_TIMING_MODE4 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + target_timming_data = fnand_timing_asy_mode4; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(4UL) ; + } + else if (FNAND_TIMING_MODE3 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + target_timming_data = fnand_timing_asy_mode3; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(5UL) ; + } + else if (FNAND_TIMING_MODE2 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + target_timming_data = fnand_timing_asy_mode2; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(6UL) ; + } + else if (FNAND_TIMING_MODE1 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + target_timming_data = fnand_timing_asy_mode1; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(5UL) ; + } + else + { + target_timming_data = fnand_timing_asy_mode0; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(1UL) ; + } + ret = FNandMemcpyToReg16(instance_p, FNAND_ASY_TIMING0_OFFSET, 4, target_timming_data, FNAND_TIMING_ASY_NUM); + if (ret != FT_SUCCESS) + { + return ret; + } + FNAND_SETBIT(config_p->base_address, FNAND_CTRL1_OFFSET, value); + FNAND_WRITEREG(config_p->base_address, FNAND_INTERVAL_OFFSET, 1); + break; + case FNAND_ONFI_DDR: + if (FNAND_TIMING_MODE4 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + FNAND_WRITEREG(config_p->base_address, FNAND_INTERVAL_OFFSET, 0x30); + target_timming_data = fnand_timing_syn_mode4; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(0xdUL) ; + } + else if (FNAND_TIMING_MODE3 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + FNAND_WRITEREG(config_p->base_address, FNAND_INTERVAL_OFFSET, 0x18); + target_timming_data = fnand_timing_syn_mode3; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(5UL) ; + } + else if (FNAND_TIMING_MODE2 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + FNAND_WRITEREG(config_p->base_address, FNAND_INTERVAL_OFFSET, 0x20); + target_timming_data = fnand_timing_syn_mode2; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(0x8UL) ; + } + else if (FNAND_TIMING_MODE1 == (instance_p->timing_mode[chip_addr] & 0xf)) + { + FNAND_WRITEREG(config_p->base_address, FNAND_INTERVAL_OFFSET, 0x40); + target_timming_data = fnand_timing_syn_mode1; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(0x12UL) ; + } + else + { + FNAND_WRITEREG(config_p->base_address, FNAND_INTERVAL_OFFSET, 0x40); + target_timming_data = fnand_timing_syn_mode0; + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(0x12UL) ; + } + ret = FNandMemcpyToReg16(instance_p, FNAND_SYN_TIMING6_OFFSET, 4, target_timming_data, FNAND_TIMING_SYN_NUM); + if (ret != FT_SUCCESS) + { + return ret; + } + FNAND_SETBIT(config_p->base_address, FNAND_CTRL1_OFFSET, value); + break; + case FNAND_TOG_ASYN_DDR: + value = FNAND_CTRL1_SAMPL_PHASE_MAKE(8UL); + target_timming_data = fnand_timing_tog_ddr_mode0; + ret = FNandMemcpyToReg16(instance_p, FNAND_TOG_TIMING13_OFFSET, 4, target_timming_data, FNAND_TIMING_SYN_NUM); + if (ret != FT_SUCCESS) + { + return ret; + } + FNAND_WRITEREG(config_p->base_address, FNAND_INTERVAL_OFFSET, 0xc8); + FNAND_SETBIT(config_p->base_address, FNAND_CTRL1_OFFSET, value); + break; + default: + FNAND_TIMING_DEBUG_E("Error inter_mode is %x", instance_p->inter_mode[chip_addr]); + return FNAND_ERR_INVAILD_PARAMETER; + } + + return FT_SUCCESS; +} + + +const struct FNandSdrTimings *FNandAsyncTimingModeToSdrTimings(FNandAsyncTimint mode) +{ + if (mode >= FNAND_ASYNC_TIM_INT_MODE4) + { + FNAND_TIMING_DEBUG_E("FNandAsyncTimingModeToSdrTimings set is over mode range"); + return NULL; + } + + return &onfi_sdr_timings[mode]; +} + + + +/** + * @name: + * @msg: + * @return {*} + * @param {FNand} *instance_p + * @param {FNandAsyncTimint} mode + * @Note 当前只支持onfi 模式 + */ +FError FNandFillTimingModeTiming(FNand *instance_p, FNandAsyncTimint mode) +{ + struct FNandSdrTimings *sdr_timing_p = NULL; + const struct FNandSdrTimings *source_timing_p = NULL; + FASSERT(instance_p != NULL); + sdr_timing_p = &instance_p->sdr_timing; + source_timing_p = FNandAsyncTimingModeToSdrTimings(mode); + FASSERT(source_timing_p != NULL); + *sdr_timing_p = *source_timing_p; + + + return FT_SUCCESS; +} diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_timing.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_timing.h new file mode 100644 index 0000000000..8289e1cc32 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/fnand_timing.h @@ -0,0 +1,124 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_timing.h + * Date: 2022-04-28 18:53:58 + * LastEditTime: 2022-04-28 18:53:58 + * Description:  This file is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#ifndef DRIVERS_NAND_FNAND +#define DRIVERS_NAND_FNAND + +#include "ftypes.h" + +/** + * struct FNandSdrTimings - SDR NAND chip timings + * + * This struct defines the timing requirements of a SDR NAND chip. + * These information can be found in every NAND datasheets and the timings + * meaning are described in the ONFI specifications: + * www.onfi.org/~/media/ONFI/specs/onfi_3_1_spec.pdf (chapter 4.15 Timing + * Parameters) + * + * All these timings are expressed in picoseconds. + * + * @tBERS_max: Block erase time + * @tCCS_min: Change column setup time + * @tPROG_max: Page program time + * @tR_max: Page read time + * @tALH_min: ALE hold time + * @tADL_min: ALE to data loading time + * @tALS_min: ALE setup time + * @tAR_min: ALE to RE# delay + * @tCEA_max: CE# access time + * @tCEH_min: CE# high hold time + * @tCH_min: CE# hold time + * @tCHZ_max: CE# high to output hi-Z + * @tCLH_min: CLE hold time + * @tCLR_min: CLE to RE# delay + * @tCLS_min: CLE setup time + * @tCOH_min: CE# high to output hold + * @tCS_min: CE# setup time + * @tDH_min: Data hold time + * @tDS_min: Data setup time + * @tFEAT_max: Busy time for Set Features and Get Features + * @tIR_min: Output hi-Z to RE# low + * @tITC_max: Interface and Timing Mode Change time + * @tRC_min: RE# cycle time + * @tREA_max: RE# access time + * @tREH_min: RE# high hold time + * @tRHOH_min: RE# high to output hold + * @tRHW_min: RE# high to WE# low + * @tRHZ_max: RE# high to output hi-Z + * @tRLOH_min: RE# low to output hold + * @tRP_min: RE# pulse width + * @tRR_min: Ready to RE# low (data only) + * @tRST_max: Device reset time, measured from the falling edge of R/B# to the + * rising edge of R/B#. + * @tWB_max: WE# high to SR[6] low + * @tWC_min: WE# cycle time + * @tWH_min: WE# high hold time + * @tWHR_min: WE# high to RE# low + * @tWP_min: WE# pulse width + * @tWW_min: WP# transition to WE# low + */ +struct FNandSdrTimings +{ + u64 tBERS_max; + u32 tCCS_min; + u64 tPROG_max; + u64 tR_max; + u32 tALH_min; + u32 tADL_min; + u32 tALS_min; + u32 tAR_min; + u32 tCEA_max; + u32 tCEH_min; + u32 tCH_min; + u32 tCHZ_max; + u32 tCLH_min; + u32 tCLR_min; + u32 tCLS_min; + u32 tCOH_min; + u32 tCS_min; + u32 tDH_min; + u32 tDS_min; + u32 tFEAT_max; + u32 tIR_min; + u32 tITC_max; + u32 tRC_min; + u32 tREA_max; + u32 tREH_min; + u32 tRHOH_min; + u32 tRHW_min; + u32 tRHZ_max; + u32 tRLOH_min; + u32 tRP_min; + u32 tRR_min; + u64 tRST_max; + u32 tWB_max; + u32 tWC_min; + u32 tWH_min; + u32 tWHR_min; + u32 tWP_min; + u32 tWW_min; +}; + + + +#endif + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_onfi.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_onfi.c new file mode 100644 index 0000000000..4ba74b30e7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_onfi.c @@ -0,0 +1,284 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_onfi.c + * Date: 2022-07-05 19:10:40 + * LastEditTime: 2022-07-05 19:10:41 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + + +#include "fnand.h" +#include "fnand_hw.h" +#include "stdio.h" +#include "string.h" +#include "fnand_dma.h" +#include "fnand_common_cmd.h" +#include "fnand_onfi.h" +#include "fnand_timing.h" +#include "fnand_ecc.h" +#include "fcache.h" +// #include "fsleep.h" +#include "fdebug.h" +#include "sdkconfig.h" + + +#define FNAND_ONFI_DEBUG_TAG "FNAND_ONFI" + +#ifdef CONFIG_FNAND_ONFI_DEBUG_EN + + #define FNAND_ONFI_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_ONFI_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_ONFI_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_ONFI_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_ONFI_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_ONFI_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_ONFI_DEBUG_D(format, ...) FT_DEBUG_PRINT_D(FNAND_ONFI_DEBUG_TAG, format, ##__VA_ARGS__) +#else + #define FNAND_ONFI_DEBUG_I(format, ...) + #define FNAND_ONFI_DEBUG_W(format, ...) + #define FNAND_ONFI_DEBUG_E(format, ...) + #define FNAND_ONFI_DEBUG_D(format, ...) +#endif + +#define FNAND_ADDR_CYCLE_NUM0 0 +#define FNAND_ADDR_CYCLE_NUM1 1 +#define FNAND_ADDR_CYCLE_NUM2 2 +#define FNAND_ADDR_CYCLE_NUM3 3 +#define FNAND_ADDR_CYCLE_NUM4 4 +#define FNAND_ADDR_CYCLE_NUM5 5 + +#define FNAND_ONFI_CRC_BASE 0x4F4E + +#define FNAND_CTRL_ECC_EN 1 +#define FNAND_CTRL_ECC_DIS 0 + +#define FNAND_CTRL_AUTO_AUTO_RS_EN 1 +#define FNAND_CTRL_AUTO_AUTO_RS_DIS 0 + + + +/* + * Special handling must be done for the WAITRDY timeout parameter as it usually + * is either tPROG (after a prog), tR (before a read), tRST (during a reset) or + * tBERS (during an erase) which all of them are u64 values that cannot be + * divided by usual kernel macros and must be handled with the special + * DIV_ROUND_UP_ULL() macro. + * + * Cast to type of dividend is needed here to guarantee that the result won't + * be an unsigned long long when the dividend is an unsigned long (or smaller), + * which is what the compiler does when it sees ternary operator with 2 + * different return types (picks the largest type to make sure there's no + * loss). + */ +#define __DIVIDE(dividend, divisor) ({ \ + (__typeof__(dividend))(sizeof(dividend) <= sizeof(unsigned long) ? \ + DIV_ROUND_UP(dividend, divisor) : \ + DIV_ROUND_UP_ULL(dividend, divisor)); \ + }) +#define PSEC_TO_NSEC(x) __DIVIDE(x, 1000) +#define PSEC_TO_MSEC(x) __DIVIDE(x, 1000000000) + + +extern FError FNandSendCmd(FNand *instance_p, struct FNandDmaDescriptor *descriptor_p, FNandOperationType isr_type); +extern FError FNandTimingInterfaceUpdate(FNand *instance_p, u32 chip_addr); + +FError FNandDmaPack(FNandCmdFormat *cmd_format, + struct FNandDmaDescriptor *descriptor_p, + FNandDmaPackData *pack_data_p + ); + + + +enum CommandsEnum +{ + CMD_READ_ID = 0, + CMD_READ_DEVICE_TABLE, + CMD_INDEX_LENGTH_NEW, +}; + +static u16 FNandOnfiCrc16(u16 crc, u8 const *p, size_t len) +{ + int i; + while (len--) + { + crc ^= *p++ << 8; + for (i = 0; i < 8; i++) + crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0); + } + + return crc; +} + + + +/* Sanitize ONFI strings so we can safely print them */ +static void FNandSanitizeString(u8 *s, fsize_t len) +{ + fsize_t i; + + /* Null terminate */ + s[len - 1] = 0; + + /* Remove non printable chars */ + for (i = 0; i < len - 1; i++) + { + if (s[i] < ' ' || s[i] > 127) + s[i] = '?'; + } + +} + + + +static FNandCmdFormat cmd_format[CMD_INDEX_LENGTH_NEW] = +{ + {ONFI_CMD_READ_ID, ONFI_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM1, FNAND_CMDCTRL_TYPE_READ_ID, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_DIS}, + {ONFI_CMD_READ_PARAM_PAGE, ONFI_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM1, FNAND_CMDCTRL_READ_PARAM, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, +}; + + +static FError FNandOnfiDetectJedec(FNand *instance_p, struct OnfiNandGeometry *onfi_geometry_p, FNandNandGeometry *geometry_p) +{ + /* 多参数页冗余检查 */ + if (FNandOnfiCrc16(FNAND_ONFI_CRC_BASE, (u8 *)onfi_geometry_p, 510) != onfi_geometry_p->crc) + { + FNAND_ONFI_DEBUG_W("Onfi error mode"); + } + + FNAND_ONFI_DEBUG_I("revision is %x", onfi_geometry_p->revision); + + FNandSanitizeString(onfi_geometry_p->manufacturer, sizeof(onfi_geometry_p->manufacturer)); + FNandSanitizeString(onfi_geometry_p->model, sizeof(onfi_geometry_p->model)); + FNAND_ONFI_DEBUG_I("manufacturer %s", onfi_geometry_p->manufacturer); + FNAND_ONFI_DEBUG_I("model %s", onfi_geometry_p->model); + + geometry_p->bytes_per_page = onfi_geometry_p->byte_per_page; + geometry_p->spare_bytes_per_page = onfi_geometry_p->spare_bytes_per_page; + geometry_p->pages_per_block = onfi_geometry_p->pages_per_block; + geometry_p->blocks_per_lun = onfi_geometry_p->blocks_per_lun ; + geometry_p->num_lun = onfi_geometry_p->lun_count; + geometry_p->num_pages = (geometry_p->num_lun * + geometry_p->blocks_per_lun * + geometry_p->pages_per_block); + geometry_p->num_blocks = (geometry_p->num_lun * geometry_p->blocks_per_lun); + geometry_p->block_size = (geometry_p->pages_per_block * geometry_p->bytes_per_page); + geometry_p->device_size = (geometry_p->num_blocks * geometry_p->block_size * geometry_p->bytes_per_page); + geometry_p->rowaddr_cycles = onfi_geometry_p->addr_cycles & 0xf; + geometry_p->coladdr_cycles = (onfi_geometry_p->addr_cycles >> 4) & 0xf ; + geometry_p->hw_ecc_length = FNandGetEccTotalLength(geometry_p->bytes_per_page, instance_p->config.ecc_strength); /* 需要增加检查oob 长度 */ + geometry_p->ecc_offset = geometry_p->spare_bytes_per_page - geometry_p->hw_ecc_length; + geometry_p->hw_ecc_steps = geometry_p->bytes_per_page / instance_p->config.ecc_step_size ; + geometry_p->ecc_step_size = instance_p->config.ecc_step_size; + FNAND_ONFI_DEBUG_D("bytes_per_page %d ", geometry_p->bytes_per_page); /* Bytes per page */ + FNAND_ONFI_DEBUG_D("spare_bytes_per_page %d ", geometry_p->spare_bytes_per_page) ; /* Size of spare area in bytes */ + FNAND_ONFI_DEBUG_D("pages_per_block %d ", geometry_p->pages_per_block) ; /* Pages per block */ + FNAND_ONFI_DEBUG_D("blocks_per_lun %d ", geometry_p->blocks_per_lun) ; /* Bocks per LUN */ + FNAND_ONFI_DEBUG_D("num_lun %d ", geometry_p->num_lun) ; /* Total number of LUN */ + FNAND_ONFI_DEBUG_D("num_pages %d ", geometry_p->num_pages) ; /* Total number of pages in device */ + FNAND_ONFI_DEBUG_D("num_blocks %d ", geometry_p->num_blocks) ; /* Total number of blocks in device */ + FNAND_ONFI_DEBUG_D("block_size %d ", geometry_p->block_size) ; /* Size of a block in bytes */ + FNAND_ONFI_DEBUG_D("device_size %d ", geometry_p->device_size) ; /* Total device size in bytes */ + FNAND_ONFI_DEBUG_D("rowaddr_cycles %d ", geometry_p->rowaddr_cycles) ; /* Row address cycles */ + FNAND_ONFI_DEBUG_D("coladdr_cycles %d ", geometry_p->coladdr_cycles) ; /* Column address cycles */ + FNAND_ONFI_DEBUG_D("hw_ecc_length %d ", geometry_p->hw_ecc_length) ; /* 产生硬件ecc校验参数的个数 */ + FNAND_ONFI_DEBUG_D("ecc_offset %d ", geometry_p->ecc_offset) ; /* obb存放硬件ecc校验参数页位置的偏移 */ + FNAND_ONFI_DEBUG_D("hw_ecc_steps %d ", geometry_p->hw_ecc_steps) ; /* number of ECC steps per page */ + FNAND_ONFI_DEBUG_D("ecc_step_size %d ", geometry_p->ecc_step_size) ; /* 进行读写操作时,单次ecc 的步骤的跨度 */ + + return FT_SUCCESS; +} + +static FError FNandOnfiReadParamPage(FNand *instance_p, u8 *id_buffer, u32 buffer_length, u32 chip_addr) +{ + FError ret; + u8 address = 0x00; + u32 memcpy_length; + FNandDmaPackData pack_data = + { + .addr_p = &address, + .addr_length = 1, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = (3 * sizeof(struct OnfiNandGeometry) > FNAND_DMA_MAX_LENGTH) ? FNAND_DMA_MAX_LENGTH : (3 * sizeof(struct OnfiNandGeometry)), + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + FNandDmaPack(&cmd_format[CMD_READ_DEVICE_TABLE], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_READ_PAGE_TYPE); + + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + if (buffer_length && id_buffer) + { + memcpy_length = (buffer_length > pack_data.phy_bytes_length) ? pack_data.phy_bytes_length : buffer_length; + FCacheDCacheFlushRange((intptr)instance_p->dma_data_buffer.data_buffer, memcpy_length); + memcpy(id_buffer, instance_p->dma_data_buffer.data_buffer, memcpy_length); + } + return FT_SUCCESS; +} + +/** + * @name: FNandOnfiInit + * @msg: Onfi mode interface initialization + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} chip_addr is chip address + * @return {FError} FT_SUCCESS 初始化成功 ,FNAND_NOT_FET_TOGGLE_MODE 初始化toggle 模式错误。 + */ +FError FNandOnfiInit(FNand *instance_p, u32 chip_addr) +{ + FError ret; + char id[5]; + FASSERT(instance_p != NULL); + struct OnfiNandGeometry *onfi_geometry_p; + /* step 1 .reset nand chip */ + + ret = FNandFlashReset(instance_p, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_ONFI_DEBUG_E("FNandFlashReset is error"); + return ret; + } + /* step 2. readid operation 20h */ + ret = FNandFlashReadId(instance_p, 0x20, id, sizeof(id), chip_addr); + if (ret != FT_SUCCESS || strncmp(id, "ONFI", sizeof(id) - 1)) + { + FNAND_ONFI_DEBUG_E("20H read id is %s ", id); + return FNAND_NOT_FET_TOGGLE_MODE; + } + + instance_p->inter_mode[chip_addr] = FNAND_ASYN_SDR; + + + FNandTimingInterfaceUpdate(instance_p, chip_addr); + /* step 3. read device id table */ + + ret = FNandOnfiReadParamPage(instance_p, NULL, 0, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_ONFI_DEBUG_E("read device id table is error"); + return FNAND_NOT_FET_TOGGLE_MODE; + } + + /* step 4. device id table parse */ + onfi_geometry_p = (struct OnfiNandGeometry *)instance_p->dma_data_buffer.data_buffer; + + return FNandOnfiDetectJedec(instance_p, onfi_geometry_p, &instance_p->nand_geometry[chip_addr]); +} + + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_onfi.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_onfi.h new file mode 100644 index 0000000000..aab8892209 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_onfi.h @@ -0,0 +1,107 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_onfi.h + * Date: 2022-07-05 19:10:47 + * LastEditTime: 2022-07-05 19:10:47 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ +#ifndef DRIVERS_NAND_FNAND_ONFI_H +#define DRIVERS_NAND_FNAND_ONFI_H + +#include "ftypes.h" +#include "fnand.h" + + +#define ONFI_CMD_READ_ID 0x90 /* ONFI Read ID \ + command */ +#define ONFI_CMD_READ_PARAM_PAGE 0xEC /* ONFI Read \ + Parameter Page \ + command */ + + +#define ONFI_END_CMD_NONE 0xfff /* No End command */ + +struct OnfiNandGeometry +{ + /* rev info and features block */ + /* 'O' 'N' 'F' 'I' */ + u8 sig[4]; + u16 revision; + u16 features; + u16 opt_cmd; + u8 reserved0[2]; + u16 ext_param_page_length; /* since ONFI 2.1 */ + u8 num_of_param_pages; /* since ONFI 2.1 */ + u8 reserved1[17]; + + /* manufacturer information block */ + char manufacturer[12]; + char model[20]; + u8 jedec_id; + u16 date_code; + u8 reserved2[13]; + + /* memory organization block */ + u32 byte_per_page; + u16 spare_bytes_per_page; + u32 data_bytes_per_ppage; + u16 spare_bytes_per_ppage; + u32 pages_per_block; + u32 blocks_per_lun; + u8 lun_count; + u8 addr_cycles; + u8 bits_per_cell; + u16 bb_per_lun; + u16 block_endurance; + u8 guaranteed_good_blocks; + u16 guaranteed_block_endurance; + u8 programs_per_page; + u8 ppage_attr; + u8 ecc_bits; + u8 interleaved_bits; + u8 interleaved_ops; + u8 reserved3[13]; + + /* electrical parameter block */ + u8 io_pin_capacitance_max; + u16 async_timing_mode; + u16 program_cache_timing_mode; + u16 t_prog; + u16 t_bers; + u16 t_r; + u16 t_ccs; + u16 src_sync_timing_mode; + u8 src_ssync_features; + u16 clk_pin_capacitance_typ; + u16 io_pin_capacitance_typ; + u16 input_pin_capacitance_typ; + u8 input_pin_capacitance_max; + u8 driver_strength_support; + u16 t_int_r; + u16 t_adl; + u8 reserved4[8]; + + /* vendor */ + u16 vendor_revision; + u8 vendor[88]; + + u16 crc; +} __attribute__((__packed__)); + + +#endif // !1 \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toggle.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toggle.c new file mode 100644 index 0000000000..af1913f036 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toggle.c @@ -0,0 +1,294 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_toggle.c + * Date: 2022-07-05 20:00:31 + * LastEditTime: 2022-07-05 20:00:31 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + +#include "fnand.h" +#include "fnand_hw.h" +#include "stdio.h" +#include "string.h" +#include "fnand_dma.h" +#include "fnand_toggle.h" +#include "fnand_timing.h" +#include "fnand_ecc.h" +#include "fnand_common_cmd.h" +#include "fcache.h" +// #include "fsleep.h" +#include "fdebug.h" +#include "sdkconfig.h" + +#define CONFIG_FNAND_TOGGLE_DEBUG_EN +#define FNAND_TOGGLE_DEBUG_TAG "FNAND_TOGGLE" +#ifdef CONFIG_FNAND_TOGGLE_DEBUG_EN + + #define FNAND_TOGGLE_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_TOGGLE_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_TOGGLE_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_TOGGLE_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_TOGGLE_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_TOGGLE_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_TOGGLE_DEBUG_D(format, ...) FT_DEBUG_PRINT_D(FNAND_TOGGLE_DEBUG_TAG, format, ##__VA_ARGS__) +#else + #define FNAND_TOGGLE_DEBUG_I(format, ...) + #define FNAND_TOGGLE_DEBUG_W(format, ...) + #define FNAND_TOGGLE_DEBUG_E(format, ...) + #define FNAND_TOGGLE_DEBUG_D(format, ...) +#endif + +#define FNAND_ADDR_CYCLE_NUM0 0 +#define FNAND_ADDR_CYCLE_NUM1 1 +#define FNAND_ADDR_CYCLE_NUM2 2 +#define FNAND_ADDR_CYCLE_NUM3 3 +#define FNAND_ADDR_CYCLE_NUM4 4 +#define FNAND_ADDR_CYCLE_NUM5 5 + +#define FNAND_TOGGLE_CRC_BASE 0x4F4E + +#define FNAND_CTRL_ECC_EN 1 +#define FNAND_CTRL_ECC_DIS 0 + +#define FNAND_CTRL_AUTO_AUTO_RS_EN 1 +#define FNAND_CTRL_AUTO_AUTO_RS_DIS 0 + +/* + * Special handling must be done for the WAITRDY timeout parameter as it usually + * is either tPROG (after a prog), tR (before a read), tRST (during a reset) or + * tBERS (during an erase) which all of them are u64 values that cannot be + * divided by usual kernel macros and must be handled with the special + * DIV_ROUND_UP_ULL() macro. + * + * Cast to type of dividend is needed here to guarantee that the result won't + * be an unsigned long long when the dividend is an unsigned long (or smaller), + * which is what the compiler does when it sees ternary operator with 2 + * different return types (picks the largest type to make sure there's no + * loss). + */ +#define __DIVIDE(dividend, divisor) ({ \ + (__typeof__(dividend))(sizeof(dividend) <= sizeof(unsigned long) ? \ + DIV_ROUND_UP(dividend, divisor) : \ + DIV_ROUND_UP_ULL(dividend, divisor)); \ + }) +#define PSEC_TO_NSEC(x) __DIVIDE(x, 1000) +#define PSEC_TO_MSEC(x) __DIVIDE(x, 1000000000) + +extern FError FNandSendCmd(FNand *instance_p, struct FNandDmaDescriptor *descriptor_p, FNandOperationType isr_type); +extern FError FNandTimingInterfaceUpdate(FNand *instance_p, u32 chip_addr); + +FError FNandDmaPack(FNandCmdFormat *cmd_format, + struct FNandDmaDescriptor *descriptor_p, + FNandDmaPackData *pack_data_p + ); + + + + + +enum CommandsEnumNew +{ + CMD_READ_ID = 0, + CMD_READ_DEVICE_TABLE, + CMD_INDEX_LENGTH_NEW, +}; + + +static FNandCmdFormat cmd_format[CMD_INDEX_LENGTH_NEW] = +{ + {TOGGLE_CMD_READ_ID, TOGGLE_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM1, FNAND_CMDCTRL_TYPE_READ_ID, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_DIS}, + {TOGGLE_CMD_READ_PARAM_PAGE, TOGGLE_END_CMD_NONE, FNAND_ADDR_CYCLE_NUM1, FNAND_CMDCTRL_READ_PARAM, FNAND_CTRL_ECC_DIS, FNAND_CTRL_AUTO_AUTO_RS_EN}, +}; + +static u16 FNandToggleCrc16(u16 crc, u8 const *p, size_t len) +{ + int i; + while (len--) + { + crc ^= *p++ << 8; + for (i = 0; i < 8; i++) + crc = (crc << 1) ^ ((crc & 0x8000) ? 0x8005 : 0); + } + + return crc; +} + + + +/* Sanitize ONFI strings so we can safely print them */ +static void FNandSanitizeString(u8 *s, fsize_t len) +{ + fsize_t i; + + /* Null terminate */ + s[len - 1] = 0; + + /* Remove non printable chars */ + for (i = 0; i < len - 1; i++) + { + if (s[i] < ' ' || s[i] > 127) + s[i] = '?'; + } + +} + + +static FError FNandToggleReadParamPage(FNand *instance_p, u8 *id_buffer, u32 buffer_length, u32 chip_addr) +{ + FError ret; + u8 address = 0x40; + u32 memcpy_length; + FNandDmaPackData pack_data = + { + .addr_p = &address, + .addr_length = 1, + .phy_address = (uintptr)instance_p->dma_data_buffer.data_buffer, + .phy_bytes_length = (3 * sizeof(struct ToggleNandGeometry) > FNAND_DMA_MAX_LENGTH) ? FNAND_DMA_MAX_LENGTH : (3 * sizeof(struct ToggleNandGeometry)), + .chip_addr = chip_addr, + .contiune_dma = 0, + }; + + FNandDmaPack(&cmd_format[CMD_READ_DEVICE_TABLE], (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], &pack_data); + ret = FNandSendCmd(instance_p, (struct FNandDmaDescriptor *)&instance_p->descriptor_buffer.data_buffer[0], FNAND_READ_PAGE_TYPE); + + + if (ret != FT_SUCCESS) + { + return FNAND_ERR_OPERATION; + } + + if (buffer_length && id_buffer) + { + memcpy_length = (buffer_length > pack_data.phy_bytes_length) ? pack_data.phy_bytes_length : buffer_length; + FCacheDCacheFlushRange((intptr)instance_p->dma_data_buffer.data_buffer, memcpy_length); + memcpy(id_buffer, instance_p->dma_data_buffer.data_buffer, memcpy_length); + } + + return FT_SUCCESS; +} + +static FError FNandToggleDetectJedec(FNand *instance_p, struct ToggleNandGeometry *toggle_geometry_p, FNandNandGeometry *geometry_p) +{ + /* 检查crc */ + if (FNandToggleCrc16(FNAND_TOGGLE_CRC_BASE, (u8 *)toggle_geometry_p, 510) != toggle_geometry_p->crc) + { + FNAND_TOGGLE_DEBUG_E("Toggle error mode"); + } + + FNAND_TOGGLE_DEBUG_I("revision is %x", toggle_geometry_p->revision); + + FNandSanitizeString(toggle_geometry_p->manufacturer, sizeof(toggle_geometry_p->manufacturer)); + FNandSanitizeString(toggle_geometry_p->model, sizeof(toggle_geometry_p->model)); + FNAND_TOGGLE_DEBUG_I("manufacturer %s", toggle_geometry_p->manufacturer); + FNAND_TOGGLE_DEBUG_I("model %s", toggle_geometry_p->model); + + geometry_p->bytes_per_page = toggle_geometry_p->byte_per_page; + geometry_p->spare_bytes_per_page = toggle_geometry_p->spare_bytes_per_page; + geometry_p->pages_per_block = toggle_geometry_p->pages_per_block; + geometry_p->blocks_per_lun = toggle_geometry_p->blocks_per_lun ; + geometry_p->num_lun = toggle_geometry_p->lun_count; + geometry_p->num_pages = (geometry_p->num_lun * + geometry_p->blocks_per_lun * + geometry_p->pages_per_block); + geometry_p->num_blocks = (geometry_p->num_lun * geometry_p->blocks_per_lun); + geometry_p->block_size = (geometry_p->pages_per_block * geometry_p->bytes_per_page); + geometry_p->device_size = (geometry_p->num_blocks * geometry_p->block_size * geometry_p->bytes_per_page); + geometry_p->rowaddr_cycles = toggle_geometry_p->addr_cycles & 0xf; + geometry_p->coladdr_cycles = (toggle_geometry_p->addr_cycles >> 4) & 0xf ; + geometry_p->hw_ecc_length = FNandGetEccTotalLength(geometry_p->bytes_per_page, instance_p->config.ecc_strength); + geometry_p->ecc_offset = geometry_p->spare_bytes_per_page - geometry_p->hw_ecc_length; + geometry_p->hw_ecc_steps = geometry_p->bytes_per_page / instance_p->config.ecc_step_size ; + geometry_p->ecc_step_size = instance_p->config.ecc_step_size; + FNAND_TOGGLE_DEBUG_D("bytes_per_page %d ", geometry_p->bytes_per_page); /* Bytes per page */ + FNAND_TOGGLE_DEBUG_D("spare_bytes_per_page %d ", geometry_p->spare_bytes_per_page) ; /* Size of spare area in bytes */ + FNAND_TOGGLE_DEBUG_D("pages_per_block %d ", geometry_p->pages_per_block) ; /* Pages per block */ + FNAND_TOGGLE_DEBUG_D("blocks_per_lun %d ", geometry_p->blocks_per_lun) ; /* Bocks per LUN */ + FNAND_TOGGLE_DEBUG_D("num_lun %d ", geometry_p->num_lun) ; /* Total number of LUN */ + FNAND_TOGGLE_DEBUG_D("num_pages %d ", geometry_p->num_pages) ; /* Total number of pages in device */ + FNAND_TOGGLE_DEBUG_D("num_blocks %d ", geometry_p->num_blocks) ; /* Total number of blocks in device */ + FNAND_TOGGLE_DEBUG_D("block_size %d ", geometry_p->block_size) ; /* Size of a block in bytes */ + FNAND_TOGGLE_DEBUG_D("device_size %d ", geometry_p->device_size) ; /* Total device size in bytes */ + FNAND_TOGGLE_DEBUG_D("rowaddr_cycles %d ", geometry_p->rowaddr_cycles) ; /* Row address cycles */ + FNAND_TOGGLE_DEBUG_D("coladdr_cycles %d ", geometry_p->coladdr_cycles) ; /* Column address cycles */ + FNAND_TOGGLE_DEBUG_D("hw_ecc_length %d ", geometry_p->hw_ecc_length) ; /* 产生硬件ecc校验参数的个数 */ + FNAND_TOGGLE_DEBUG_D("ecc_offset %d ", geometry_p->ecc_offset) ; /* obb存放硬件ecc校验参数页位置的偏移 */ + FNAND_TOGGLE_DEBUG_D("hw_ecc_steps %d ", geometry_p->hw_ecc_steps) ; /* number of ECC steps per page */ + FNAND_TOGGLE_DEBUG_D("ecc_step_size %d ", geometry_p->ecc_step_size) ; /* 进行读写操作时,单次ecc 的步骤的跨度 */ + + + + return FT_SUCCESS; +} + + +/** + * @name: FNandToggleInit + * @msg: Toggle mode interface initialization + * @note: + * @param {FNand} *instance_p is the pointer to the FNand instance. + * @param {u32} chip_addr is chip address + * @return {FError} FT_SUCCESS 初始化成功 ,FNAND_NOT_FET_TOGGLE_MODE 初始化toggle 模式错误。 + */ +FError FNandToggleInit(FNand *instance_p, u32 chip_addr) +{ + FError ret; + char id[6]; + FASSERT(instance_p != NULL); + struct ToggleNandGeometry *toggle_geometry_p; + /* step 1 .reset nand chip */ + ret = FNandFlashReset(instance_p, chip_addr) ; + if (ret != FT_SUCCESS) + { + FNAND_TOGGLE_DEBUG_E("FNandFlashReset is error"); + return ret; + } + + /* step 2. readid operation 40h */ + ret = FNandFlashReadId(instance_p, 0x40, id, sizeof(id), chip_addr); + if (ret != FT_SUCCESS || strncmp(id, "JEDEC", sizeof(id) - 1)) + { + FNAND_TOGGLE_DEBUG_E("40H read id is %s ", id); + return FNAND_NOT_FET_TOGGLE_MODE; + } + + if (id[5] == 1) + { + instance_p->inter_mode[chip_addr] = FNAND_ASYN_SDR; + } + else if (id[5] == 2) + { + instance_p->inter_mode[chip_addr] = FNAND_TOG_ASYN_DDR; + } + else if (id[5] == 4) + { + instance_p->inter_mode[chip_addr] = FNAND_ASYN_SDR; + } + + FNandTimingInterfaceUpdate(instance_p, chip_addr); + + /* step 3. read device id table */ + + ret = FNandToggleReadParamPage(instance_p, NULL, 0, chip_addr); + if (ret != FT_SUCCESS) + { + FNAND_TOGGLE_DEBUG_E("read device id table is error"); + return FNAND_NOT_FET_TOGGLE_MODE; + } + + /* step 4. device id table parse */ + toggle_geometry_p = (struct ToggleNandGeometry *)instance_p->dma_data_buffer.data_buffer; + + return FNandToggleDetectJedec(instance_p, toggle_geometry_p, &instance_p->nand_geometry[chip_addr]); +} diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toggle.h b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toggle.h new file mode 100644 index 0000000000..229a6234e6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toggle.h @@ -0,0 +1,157 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_toggle.h + * Date: 2022-07-05 20:00:45 + * LastEditTime: 2022-07-05 20:00:45 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + +#ifndef DRIVERS_NAND_FNAND_TOGGLE_H +#define DRIVERS_NAND_FNAND_TOGGLE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fnand.h" + + +/* + * Mandatory commands + */ + +#define TOGGLE_CMD_READ1 0x00 +#define TOGGLE_CMD_READ2 0x30 + +#define TOGGLE_CMD_CHANGE_READ_COLUMN1 0x05 /* TOGGLE Change Read \ + Column command (1st \ + cycle) */ +#define TOGGLE_CMD_CHANGE_READ_COLUMN2 0xE0 /* TOGGLE Change Read \ + Column command (2nd \ + cycle) */ +#define TOGGLE_CMD_BLOCK_ERASE1 0x60 /* TOGGLE Block Erase \ + (1st cycle) */ +#define TOGGLE_CMD_BLOCK_ERASE2 0xD0 /* TOGGLE Block Erase \ + (2nd cycle) */ +#define TOGGLE_CMD_READ_STATUS 0x70 /* TOGGLE Read status \ + command */ +#define TOGGLE_CMD_PAGE_PROG1 0x80 /* TOGGLE Page Program \ + command (1st cycle) \ + */ +#define TOGGLE_CMD_PAGE_PROG2 0x10 /* TOGGLE Page Program \ + command (2nd cycle) \ + */ +#define TOGGLE_CMD_CHANGE_WRITE_COLUMN 0x85 /* TOGGLE Change Write \ + Column command */ +#define TOGGLE_CMD_READ_ID 0x90 /* TOGGLE Read ID \ + command */ +#define TOGGLE_CMD_READ_PARAM_PAGE 0xEC /* TOGGLE Read \ + Parameter Page \ + command */ +#define TOGGLE_CMD_RESET 0xFF /* TOGGLE Reset \ + command */ + +#define TOGGLE_END_CMD_NONE 0xfff /* No End command */ + + +struct jedec_ecc_info +{ + u8 ecc_bits; + u8 codeword_size; + u16 bb_per_lun; + u16 block_endurance; + u8 reserved[2]; +} __attribute__((packed)); + +struct ToggleNandGeometry +{ + u8 sig[4]; /* Parameter page signature */ + u16 revision; /* Revision number */ + u16 features; /* Features supported */ + u8 opt_cmd[3]; /* Optional commands supported */ + u16 sec_cmd; + u8 num_of_param_pages; + u8 reserved0[18]; + + /* manufacturer information block */ + char manufacturer[12]; /* Device manufacturer */ + char model[20]; /* Device model */ + u8 jedec_id[6]; /* JEDEC manufacturer ID */ + u8 reserved1[10]; + + /* memory organization block */ + u32 byte_per_page; /* Number of data bytes per page */ + u16 spare_bytes_per_page; /* Number of spare bytes per page */ + u8 reserved2[6]; /* */ + u32 pages_per_block; /* Number of pages per block */ + u32 blocks_per_lun; /* Number of blocks per logical unit */ + u8 lun_count; /* Number of logical unit */ + u8 addr_cycles; + u8 bits_per_cell; + u8 programs_per_page; + u8 multi_plane_addr; + u8 multi_plane_op_attr; + u8 reserved3[38]; + + /* electrical parameter block */ + u16 async_sdr_speed_grade; + u16 toggle_ddr_speed_grade; + u16 sync_ddr_speed_grade; + u8 async_sdr_features; + u8 toggle_ddr_features; + u8 sync_ddr_features; + u16 t_prog; + u16 t_bers; + u16 t_r; + u16 t_r_multi_plane; + u16 t_ccs; + u16 io_pin_capacitance_typ; + u16 input_pin_capacitance_typ; + u16 clk_pin_capacitance_typ; + u8 driver_strength_support; + u16 t_adl; + u8 reserved4[36]; + + /* ECC and endurance block */ + u8 guaranteed_good_blocks; + u16 guaranteed_block_endurance; + struct jedec_ecc_info ecc_info[4]; + u8 reserved5[29]; + + /* reserved */ + u8 reserved6[148]; + + /* vendor */ + u16 vendor_rev_num; + u8 reserved7[88]; + + /* CRC for Parameter Page */ + u16 crc; + +} __attribute__((__packed__)); + + +#ifdef __cplusplus +} +#endif + +#endif // ! + + diff --git a/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toshiba.c b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toshiba.c new file mode 100644 index 0000000000..c6d366c3e9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/nand/fnand/manufacturer/fnand_toshiba.c @@ -0,0 +1,110 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fnand_toshiba.c + * Date: 2022-07-06 08:32:43 + * LastEditTime: 2022-07-06 08:32:44 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + + +#include "fnand.h" +#include "fnand_id.h" +#include "fnand_ecc.h" +#include "fdebug.h" +#include "sdkconfig.h" + + +#define FNAND_T_NAND_DEBUG_TAG "FNAND_T_NAND" +#define CONFIG_FNAND_T_NAND_DEBUG_EN +// #define CONFIG_FNAND_T_NAND_DEBUG_EN +#ifdef CONFIG_FNAND_T_NAND_DEBUG_EN + #define FNAND_T_NAND_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FNAND_T_NAND_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_T_NAND_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FNAND_T_NAND_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_T_NAND_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FNAND_T_NAND_DEBUG_TAG, format, ##__VA_ARGS__) + #define FNAND_T_NAND_DEBUG_D(format, ...) FT_DEBUG_PRINT_D(FNAND_T_NAND_DEBUG_TAG, format, ##__VA_ARGS__) +#else + #define FNAND_T_NAND_DEBUG_I(format, ...) + #define FNAND_T_NAND_DEBUG_W(format, ...) + #define FNAND_T_NAND_DEBUG_E(format, ...) + #define FNAND_T_NAND_DEBUG_D(format, ...) +#endif + +static FError TC58NVM9S3ETAI0_CHECK(FNand *instance_p, FNandId *id_p, u32 chip_addr) +{ + FNandNandGeometry *geometry_p = &instance_p->nand_geometry[chip_addr]; + + if (((id_p->data[3] & 0x3) == 1)) /* */ + { + FNAND_T_NAND_DEBUG_I("TC58NVM9S3ETAI0 is checked") ; + geometry_p->bytes_per_page = 2048; + geometry_p->spare_bytes_per_page = 64; + geometry_p->pages_per_block = 64; + geometry_p->blocks_per_lun = 512; + geometry_p->num_lun = 1; + geometry_p->num_pages = (geometry_p->num_lun * + geometry_p->blocks_per_lun * + geometry_p->pages_per_block); + geometry_p->num_blocks = (geometry_p->num_lun * geometry_p->blocks_per_lun); + geometry_p->block_size = (geometry_p->pages_per_block * geometry_p->bytes_per_page); + geometry_p->device_size = (geometry_p->num_blocks * geometry_p->block_size * geometry_p->bytes_per_page); + geometry_p->rowaddr_cycles = 3; + geometry_p->coladdr_cycles = 2 ; + geometry_p->hw_ecc_length = FNandGetEccTotalLength(geometry_p->bytes_per_page, instance_p->config.ecc_strength); + geometry_p->ecc_offset = geometry_p->spare_bytes_per_page - geometry_p->hw_ecc_length; + geometry_p->hw_ecc_steps = geometry_p->bytes_per_page / instance_p->config.ecc_step_size ; + geometry_p->ecc_step_size = instance_p->config.ecc_step_size; + FNAND_T_NAND_DEBUG_D("bytes_per_page %d ", geometry_p->bytes_per_page); /* Bytes per page */ + FNAND_T_NAND_DEBUG_D("spare_bytes_per_page %d ", geometry_p->spare_bytes_per_page) ; /* Size of spare area in bytes */ + FNAND_T_NAND_DEBUG_D("pages_per_block %d ", geometry_p->pages_per_block) ; /* Pages per block */ + FNAND_T_NAND_DEBUG_D("blocks_per_lun %d ", geometry_p->blocks_per_lun) ; /* Bocks per LUN */ + FNAND_T_NAND_DEBUG_D("num_lun %d ", geometry_p->num_lun) ; /* Total number of LUN */ + FNAND_T_NAND_DEBUG_D("num_pages %d ", geometry_p->num_pages) ; /* Total number of pages in device */ + FNAND_T_NAND_DEBUG_D("num_blocks %d ", geometry_p->num_blocks) ; /* Total number of blocks in device */ + FNAND_T_NAND_DEBUG_D("block_size %d ", geometry_p->block_size) ; /* Size of a block in bytes */ + FNAND_T_NAND_DEBUG_D("device_size %d ", geometry_p->device_size) ; /* Total device size in bytes */ + FNAND_T_NAND_DEBUG_D("rowaddr_cycles %d ", geometry_p->rowaddr_cycles) ; /* Row address cycles */ + FNAND_T_NAND_DEBUG_D("coladdr_cycles %d ", geometry_p->coladdr_cycles) ; /* Column address cycles */ + FNAND_T_NAND_DEBUG_D("hw_ecc_length %d ", geometry_p->hw_ecc_length) ; /* 产生硬件ecc校验参数的个数 */ + FNAND_T_NAND_DEBUG_D("ecc_offset %d ", geometry_p->ecc_offset) ; /* obb存放硬件ecc校验参数页位置的偏移 */ + FNAND_T_NAND_DEBUG_D("hw_ecc_steps %d ", geometry_p->hw_ecc_steps) ; /* number of ECC steps per page */ + FNAND_T_NAND_DEBUG_D("ecc_step_size %d ", geometry_p->ecc_step_size) ; /* 进行读写操作时,单次ecc 的步骤的跨度 */ + } + else + { + FNAND_T_NAND_DEBUG_E("TC58NVM9S3ETAI0_CHECK error"); + return FNAND_ERR_NOT_MATCH; + } + + return FT_SUCCESS; +} + +FError toshiba_nand_decode_id(FNand *instance_p, FNandId *id_p, u32 chip_addr) +{ + + switch (id_p->data[1]) + { + case 0xf0: + return TC58NVM9S3ETAI0_CHECK(instance_p, id_p, chip_addr) ; + break; + default: + FNAND_T_NAND_DEBUG_E("Driver not supported 0x%x device", id_p->data[1]) ; + return FNAND_ERR_NOT_MATCH; + } +} + +const struct FNandManuFacturerOps toshiba_ops = {.detect = toshiba_nand_decode_id}; diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/Kconfig b/bsp/phytium/libraries/standalone/drivers/pcie/Kconfig new file mode 100644 index 0000000000..c4476fa491 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/Kconfig @@ -0,0 +1,9 @@ + +menu "Pcie Configuration" + config ENABLE_F_PCIE + bool + prompt "Use F_PCIE" + default n + +endmenu + diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie.c new file mode 100644 index 0000000000..470a37fc14 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie.c @@ -0,0 +1,863 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:59:28 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ +#include "fpcie.h" +#include "fpcie_hw.h" +#include "fpcie_common.h" +#include "fparameters.h" +#include "fkernel.h" +#include +#include +#include "fdebug.h" + + +#define CONFIG_SYS_PCI_CACHE_LINE_SIZE 8 +#define upper_32_bits(n) ((u32)(((n) >> 16) >> 16)) + + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FPCIE_DEBUG_TAG "FPCIE" +#define FPCIE_ERROR(format, ...) FT_DEBUG_PRINT_E(FPCIE_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FPCIE_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FPCIE_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FPCIE_DEBUG_TAG, format, ##__VA_ARGS__) + + + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +extern int FPcieEpCleanBar(FPcie *instance_p, u32 peu_num, u32 bar_num) ; + +static void FPcieShowRegion(const char *name, struct FPcieRegion *region) +{ + FPCIE_DEBUG_I("PCI Autoconfig: Bus %s region: [%llx-%llx],\n" + "\t\tPhysical Memory [%llx-%llx]", name, + (unsigned long long)region->bus_start, + (unsigned long long)(region->bus_start + region->size - 1), + (unsigned long long)region->phys_start, + (unsigned long long)(region->phys_start + region->size - 1)); + FPCIE_DEBUG_I("bus_lower is %llx ", (unsigned long long)region->bus_lower) ; +} + +/** + * @name: FPcieRegionConfigInit + * @msg: 初始化PEU 用于分配的地址空间 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {FPcieRegion} *regs 地址空间对应的指针 + * @param {u32} regs_num 传入regs 结构体的数量 + */ +//用于资源初始化到instance_p中 +static void FPcieRegionConfigInit(FPcie *instance_p, struct FPcieRegion *regs, u32 regs_num) +{ + u32 i ; + + for (i = 0; i < regs_num; i++) + { + switch (regs[i].flags) + { + case FPCIE_REGION_IO: + memset(&instance_p->mem_io, 0, sizeof(struct FPcieRegion)) ; + memcpy(&instance_p->mem_io, regs, sizeof(struct FPcieRegion)) ; + instance_p->mem_io.exist_flg = FPCIE_REGION_EXIST_FLG ; + instance_p->mem_io.bus_lower = instance_p->mem_io.phys_start; + FPcieShowRegion("I/O", &instance_p->mem_io); + break; + case FPCIE_REGION_MEM: + memset(&instance_p->mem, 0, sizeof(struct FPcieRegion)) ; + memcpy(&instance_p->mem, regs, sizeof(struct FPcieRegion)) ; + instance_p->mem.exist_flg = FPCIE_REGION_EXIST_FLG ; + instance_p->mem.bus_lower = instance_p->mem.phys_start; + FPcieShowRegion("Memory", &instance_p->mem); + break; + case (PCI_REGION_PREFETCH|FPCIE_REGION_MEM): + memset(&instance_p->mem_prefetch, 0, sizeof(struct FPcieRegion)) ; + memcpy(&instance_p->mem_prefetch, regs, sizeof(struct FPcieRegion)) ; + instance_p->mem_prefetch.exist_flg = FPCIE_REGION_EXIST_FLG ; + instance_p->mem_prefetch.bus_lower = instance_p->mem_prefetch.phys_start; + FPcieShowRegion("Prefetchable Mem", &instance_p->mem_prefetch); + break; + default: + break; + } + } +} + +/** + * @name: FPcieCfgInitialize + * @msg: This function initializes the config space and PCIe bridge. + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {FPcieConfig} *config_p pointer to FPcieConfig instrance Pointer. + * @return FError + */ +FError FPcieCfgInitialize(FPcie *instance_p, FPcieConfig *config_p) //用于从全局配置数据中获取数据,初始化instance_p +{ + fsize_t i; + struct FPcieRegion mem_region = {0} ; + struct FPcieRegion prefetch_region = {0} ; + struct FPcieRegion io_region = {0} ; + + /* Assert arguments */ + FASSERT(instance_p != NULL); + FASSERT(config_p != NULL); + + /* Clear instance memory and make copy of configuration */ + memset(instance_p, 0, sizeof(FPcie)); + memcpy(&instance_p->config, config_p, sizeof(FPcieConfig)); + + /* 为枚举过程中,涉及的配置空间提供地址划分 */ + /* mem32 地址 */ //使用获取到的硬件信息,来初始化mem32 + mem_region.phys_start = instance_p->config.npmem_base_addr ; + mem_region.bus_start = instance_p->config.npmem_base_addr ; + mem_region.size = instance_p->config.npmem_size ; + mem_region.flags = FPCIE_REGION_MEM ; + + /* mem64 地址 */ //使用获取到的硬件信息,来初始化mem64 + prefetch_region.phys_start = instance_p->config.pmem_base_addr ; + prefetch_region.bus_start = instance_p->config.pmem_base_addr ; + prefetch_region.size = instance_p->config.pmem_size ; + prefetch_region.flags = (PCI_REGION_PREFETCH | FPCIE_REGION_MEM); + + /* memio 地址 */ //使用获取到的硬件信息,来初始化io + io_region.phys_start = instance_p->config.io_base_addr ; + io_region.bus_start = instance_p->config.io_base_addr ; + io_region.size = instance_p->config.io_size ; + io_region.flags = FPCIE_REGION_IO; + + /* scaned bdf array clean */ + instance_p->scaned_bdf_count = 0; + + FPcieRegionConfigInit(instance_p, &mem_region, 1) ; +#if defined(__aarch64__) + FPcieRegionConfigInit(instance_p, &prefetch_region, 1) ; +#endif + FPcieRegionConfigInit(instance_p, &io_region, 1) ; + + instance_p->is_ready = FT_COMPONENT_IS_READY; + + /* 关闭当前所有misc 中断 */ + // FPcieMiscIrqDisable(instance_p, FPCIE_PEU0_C0); + // FPcieMiscIrqDisable(instance_p, FPCIE_PEU0_C1); + // FPcieMiscIrqDisable(instance_p, FPCIE_PEU0_C2); + // FPcieMiscIrqDisable(instance_p, FPCIE_PEU1_C0); + // FPcieMiscIrqDisable(instance_p, FPCIE_PEU1_C1); + // FPcieMiscIrqDisable(instance_p, FPCIE_PEU1_C2); + + /* 清空ep模式下所有配置地址 */ + // for (i = 0; i <= FPCIE_PEU1_C2; i++) + // { + // /* code */ + // FPcieEpCleanBar(instance_p, i, FPCIE_BAR_0); + // FPcieEpCleanBar(instance_p, i, FPCIE_BAR_1); + // FPcieEpCleanBar(instance_p, i, FPCIE_BAR_2); + // FPcieEpCleanBar(instance_p, i, FPCIE_BAR_3); + // FPcieEpCleanBar(instance_p, i, FPCIE_BAR_4); + // FPcieEpCleanBar(instance_p, i, FPCIE_BAR_5); + // } + + return (FT_SUCCESS); +} + +u32 FPcieFindCapability(FPcie *instance_p, u32 bdf, u32 cid_type, u32 cid, u32 *cid_offset) +{ + + u32 reg_value; + u32 next_cap_offset; + //u32 ret; + + if (cid_type == PCIE_CAP) + { + + /* Serach in PCIe configuration space */ + FPcieEcamReadConfig32bit(instance_p->config.ecam, bdf, FPCIE_CAPABILITY_LIST, ®_value); + if (reg_value == 0xffffffff) + return -1; + + next_cap_offset = (reg_value & 0xff); + while (next_cap_offset) + { + FPcieEcamReadConfig32bit(instance_p->config.ecam, bdf, next_cap_offset, ®_value); + if ((reg_value & 0xff) == cid) + { + *cid_offset = next_cap_offset; + return 0; + } + next_cap_offset = ((reg_value >> 8) & 0xff); + } + } + else if (cid_type == PCIE_ECAP) + { + + /* Serach in PCIe extended configuration space */ + next_cap_offset = FPCIE_ECAP_START; + while (next_cap_offset) + { + FPcieEcamReadConfig32bit(instance_p->config.ecam, bdf, next_cap_offset, ®_value); + if ((reg_value & 0xffff) == cid) + { + *cid_offset = next_cap_offset; + return 0; + } + next_cap_offset = ((reg_value >> 20) & 0xfff); + } + } + + /* The capability was not found */ + return -1; +} + +const char *FPcieClassStr(u8 class) +{ + switch (class) + { + case FPCI_CLASS_NOT_DEFINED: + return "Build before PCI Rev2.0"; + break; + case FPCI_BASE_CLASS_STORAGE: + return "Mass storage controller"; + break; + case FPCI_BASE_CLASS_NETWORK: + return "Network controller"; + break; + case FPCI_BASE_CLASS_DISPLAY: + return "Display controller"; + break; + case FPCI_BASE_CLASS_MULTIMEDIA: + return "Multimedia device"; + break; + case FPCI_BASE_CLASS_MEMORY: + return "Memory controller"; + break; + case FPCI_BASE_CLASS_BRIDGE: + return "Bridge device"; + break; + case FPCI_BASE_CLASS_COMMUNICATION: + return "Simple comm. controller"; + break; + case FPCI_BASE_CLASS_SYSTEM: + return "Base system peripheral"; + break; + case FPCI_BASE_CLASS_INPUT: + return "Input device"; + break; + case FPCI_BASE_CLASS_DOCKING: + return "Docking station"; + break; + case FPCI_BASE_CLASS_PROCESSOR: + return "Processor"; + break; + case FPCI_BASE_CLASS_SERIAL: + return "Serial bus controller"; + break; + case FPCI_BASE_CLASS_INTELLIGENT: + return "Intelligent controller"; + break; + case FPCI_BASE_CLASS_SATELLITE: + return "Satellite controller"; + break; + case FPCI_BASE_CLASS_CRYPT: + return "Cryptographic device"; + break; + case FPCI_BASE_CLASS_SIGNAL_PROCESSING: + return "DSP"; + break; + case FPCI_CLASS_OTHERS: + return "Does not fit any class"; + break; + default: + return "???"; + break; + }; +} + + +void FPcieAutoRegionAlign(struct FPcieRegion *res, pci_size_t size) +{ + res->bus_lower = ((res->bus_lower - 1) | (size - 1)) + 1; +} + +int FPcieAutoRegionAllocate(struct FPcieRegion *res, pci_size_t size, + pci_addr_t *bar, bool supports_64bit) +{ + pci_addr_t addr; + + if (!res) + { + printf("No resource\n"); + goto error; + } + + addr = ((res->bus_lower - 1) | (size - 1)) + 1; + + if (addr - res->bus_start + size > res->size) + { + printf("No room in resource"); + goto error; + } + + if (upper_32_bits(addr) && !supports_64bit) + { + printf("Cannot assign 64-bit address to 32-bit-only resource\n"); + goto error; + } + + res->bus_lower = addr + size; + + //printf("address=0x%llx bus_lower=0x%llx\n", (unsigned long long)addr, + // (unsigned long long)res->bus_lower); + + *bar = addr; + return 0; + +error: + *bar = (pci_addr_t) -1; + return -1; +} + + + +void FPcieAutoSetupDevice(FPcie *instance_p, u32 bdf, int bars_num, + struct FPcieRegion *mem, + struct FPcieRegion *prefetch, struct FPcieRegion *io, + bool enum_only) +{ + u32 bar_response; + pci_size_t bar_size; + u16 cmdstat = 0; + int bar, bar_nr = 0; + u8 header_type; + int rom_addr; + pci_addr_t bar_value; + struct FPcieRegion *bar_res = NULL; + int found_mem64 = 0; + u16 class; + + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCIE_COMMAND_REG, &cmdstat); + cmdstat = (cmdstat & ~(FPCIE_COMMAND_IO | FPCIE_COMMAND_MEMORY)) | + FPCIE_COMMAND_MASTER; + + for (bar = FPCIE_BASE_ADDRESS_0; + bar < FPCIE_BASE_ADDRESS_0 + (bars_num * 4); bar += 4) + { + /* Tickle the BAR and get the response */ + if (!enum_only) + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, bar, 0xffffffff); + + FPcieEcamReadConfig32bit(instance_p->config.ecam, bdf, bar, &bar_response); + + /* If BAR is not implemented go to the next BAR */ + if (!bar_response) + continue; + + found_mem64 = 0; + + /* Check the BAR type and set our address mask */ + if (bar_response & FPCIE_BASE_ADDRESS_SPACE) + { + bar_size = ((~(bar_response & FPCIE_BASE_ADDRESS_IO_MASK)) + & 0xffff) + 1; + if (!enum_only) + bar_res = io; + + //printf("PCI Autoconfig: BAR %d, I/O, size=0x%llx, ", + // bar_nr, (unsigned long long)bar_size); + } + else + { + if ((bar_response & FPCIE_BASE_ADDRESS_MEM_TYPE_MASK) == + FPCIE_BASE_ADDRESS_MEM_TYPE_64) + { + u32 bar_response_upper; + u64 bar64; + + if (!enum_only) + { + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, bar + 4, 0xffffffff); + } + FPcieEcamReadConfig32bit(instance_p->config.ecam, bdf, bar + 4, &bar_response_upper); + + bar64 = ((u64)bar_response_upper << 32) | + bar_response; + + bar_size = ~(bar64 & FPCIE_BASE_ADDRESS_MEM_MASK) + + 1; + if (!enum_only) + found_mem64 = 1; + } + else + { + bar_size = (u32)(~(bar_response & + FPCIE_BASE_ADDRESS_MEM_MASK) + 1); + } + if (!enum_only) + { + if ((prefetch->exist_flg & FPCIE_REGION_EXIST_FLG) & (bar_response & + FPCIE_BASE_ADDRESS_MEM_PREFETCH)) + { + bar_res = prefetch; + } + else + { + bar_res = mem; + } + } + + //printf("PCI Autoconfig: BAR %d, %s, size=0x%llx, ", + // bar_nr, bar_res == prefetch ? "Prf" : "Mem", + // (unsigned long long)bar_size); + } + + if (!enum_only && FPcieAutoRegionAllocate(bar_res, bar_size, + &bar_value, + found_mem64) == 0) + { + /* Write it out and update our limit */ + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, bar, (u32)bar_value); + + if (found_mem64) + { + bar += 4; + +#ifdef CONFIG_SYS_PCI_64BIT + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, bar, (u32)(bar_value >> 32)); +#else + /* + * If we are a 64-bit decoder then increment to + * the upper 32 bits of the bar and force it to + * locate in the lower 4GB of memory. + */ + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, bar, 0x00000000); +#endif + } + } + + cmdstat |= (bar_response & FPCIE_BASE_ADDRESS_SPACE) ? + FPCIE_COMMAND_IO : FPCIE_COMMAND_MEMORY; + + //printf("\n"); + + bar_nr++; + } + + if (!enum_only) + { + /* Configure the expansion ROM address */ + FPcieEcamReadConfig8bit(instance_p->config.ecam, bdf, FPCIE_HEADER_TYPE_REG, &header_type); + header_type &= 0x7f; + if (header_type != FPCIE_HEADER_TYPE_CARDBUS) + { + rom_addr = (header_type == FPCIE_HEADER_TYPE_NORMAL) ? + FPCIE_ROM_ADDRESS : FPCIE_ROM_ADDRESS1; + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, rom_addr, 0xfffffffe); + FPcieEcamReadConfig32bit(instance_p->config.ecam, bdf, rom_addr, &bar_response); + if (bar_response) + { + bar_size = -(bar_response & ~1); + //printf("PCI Autoconfig: ROM, size=%#x, ", + // (unsigned int)bar_size); + if (FPcieAutoRegionAllocate(mem, bar_size, + &bar_value, + false) == 0) + { + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, rom_addr, bar_value); + + } + cmdstat |= FPCIE_COMMAND_MEMORY; + //printf("\n"); + } + } + } + + /* PCI_COMMAND_IO must be set for VGA device */ + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCI_CLASS_DEVICE_REG, &class); + if (class == FPCI_CLASS_DISPLAY_VGA) + cmdstat |= FPCIE_COMMAND_IO; + + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_COMMAND_REG, cmdstat); + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_CACHE_LINE_SIZE_REG, + CONFIG_SYS_PCI_CACHE_LINE_SIZE); + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_LATENCY_TIMER_REG, 0x80); +} + +void FPcieAutoPrescanSetupBridge(FPcie *instance_p, u32 bdf, int sub_bus) +{ + struct FPcieRegion *pci_mem; + struct FPcieRegion *pci_prefetch; + struct FPcieRegion *pci_io; + u16 cmdstat, prefechable_64; + + pci_mem = &(instance_p->mem); + pci_prefetch = &(instance_p->mem_prefetch); + pci_io = &(instance_p->mem_io); + + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCIE_COMMAND_REG, &cmdstat) ; + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_MEMORY_BASE_REG, &prefechable_64) ; + prefechable_64 &= FPCIE_PREF_RANGE_TYPE_MASK; + + /* Configure bus number registers *///暂时只有一个pcie配置空间的做法,如果多个pci配置空间,则需当前bus减去该配置空间对应设备的起始bus号 + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_PRIMARY_BUS_REG, FPCIE_BUS(bdf)); + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_SECONDARY_BUS_REG, sub_bus); + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_SUBORDINATE_BUS_REG, 0xff); + + if (pci_mem->exist_flg & FPCIE_REGION_EXIST_FLG) + { + /* Round memory allocator to 1MB boundary */ + FPcieAutoRegionAlign(pci_mem, 0x100000); + + /* + * Set up memory and I/O filter limits, assume 32-bit + * I/O space + */ + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_MEMORY_BASE_REG, + (pci_mem->bus_lower & 0xfff00000) >> 16); + + cmdstat |= FPCIE_COMMAND_MEMORY; + } + + if (pci_prefetch->exist_flg & FPCIE_REGION_EXIST_FLG) + { + /* Round memory allocator to 1MB boundary */ + FPcieAutoRegionAlign(pci_prefetch, 0x100000); + + /* + * Set up memory and I/O filter limits, assume 32-bit + * I/O space + */ + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_MEMORY_BASE_REG, + (pci_prefetch->bus_lower & 0xfff00000) >> 16); + + if (prefechable_64 == FPCIE_PREF_RANGE_TYPE_64) +#ifdef CONFIG_SYS_PCI_64BIT + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, FPCIE_PREF_BASE_UPPER32_REG, + pci_prefetch->bus_lower >> 32); +#else + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, FPCIE_PREF_BASE_UPPER32_REG, + 0x0); +#endif + + cmdstat |= FPCIE_COMMAND_MEMORY; + } + else + { + /* We don't support prefetchable memory for now, so disable */ + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_MEMORY_BASE_REG, 0x1000); + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_MEMORY_LIMIT_REG, 0x0); + if (prefechable_64 == FPCIE_PREF_RANGE_TYPE_64) + { + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_BASE_UPPER32_REG, 0x0); + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_LIMIT_UPPER32_REG, 0x0); + } + } + + if (pci_io->exist_flg & FPCIE_REGION_EXIST_FLG) + { + /* Round I/O allocator to 4KB boundary */ + FPcieAutoRegionAlign(pci_io, 0x1000); + + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_IO_BASE_REG, + (pci_io->bus_lower & 0x0000f000) >> 8); + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_IO_BASE_UPPER16_REG, + (pci_io->bus_lower & 0xffff0000) >> 16); + + cmdstat |= FPCIE_COMMAND_IO; + } + + /* Enable memory and I/O accesses, enable bus master */ + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_COMMAND_REG, cmdstat | FPCIE_COMMAND_MASTER); +} + + +void FPcieAutoPostscanSetupBridge(FPcie *instance_p, u32 bdf, int sub_bus) +{ + struct FPcieRegion *pci_mem; + struct FPcieRegion *pci_prefetch; + struct FPcieRegion *pci_io; + + pci_mem = &(instance_p->mem); + pci_prefetch = &(instance_p->mem_prefetch); + pci_io = &(instance_p->mem_io); + + /* Configure bus number registers */ + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_SUBORDINATE_BUS_REG, sub_bus);//配置一下subordinate-bus,可能在固件下不一定必须用 + + if (pci_mem->exist_flg & FPCIE_REGION_EXIST_FLG) + { + /* Round memory allocator to 1MB boundary */ + FPcieAutoRegionAlign(pci_mem, 0x100000); + + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_MEMORY_LIMIT_REG, (pci_mem->bus_lower - 1) >> 16); + } + + if (pci_prefetch->exist_flg & FPCIE_REGION_EXIST_FLG) + { + u16 prefechable_64; + + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_MEMORY_LIMIT_REG, &prefechable_64); + prefechable_64 &= FPCIE_PREF_RANGE_TYPE_MASK; + + /* Round memory allocator to 1MB boundary */ + FPcieAutoRegionAlign(pci_prefetch, 0x100000); + + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_PREF_MEMORY_LIMIT_REG, (pci_prefetch->bus_lower - 1) >> 16); + if (prefechable_64 == FPCIE_PREF_RANGE_TYPE_64) +#ifdef CONFIG_SYS_PCI_64BIT + + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, FPCIE_PREF_LIMIT_UPPER32_REG, + (pci_prefetch->bus_lower - 1) >> 32); +#else + FPcieEcamWriteConfig32bit(instance_p->config.ecam, bdf, FPCIE_PREF_LIMIT_UPPER32_REG, 0x0); +#endif + } + + if (pci_io->exist_flg & FPCIE_REGION_EXIST_FLG) + { + /* Round I/O allocator to 4KB boundary */ + FPcieAutoRegionAlign(pci_io, 0x1000); + + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_IO_LIMIT_REG, + ((pci_io->bus_lower - 1) & 0x0000f000) >> 8); + FPcieEcamWriteConfig16bit(instance_p->config.ecam, bdf, FPCIE_IO_LIMIT_UPPER16_REG, + ((pci_io->bus_lower - 1) & 0xffff0000) >> 16); + } +} + + +int FPcieHoseProbeBus(FPcie *instance_p, u32 bdf) +{ + int sub_bus; + int ret; + + instance_p->bus_max = instance_p->bus_max + 1; + + sub_bus = instance_p->bus_max; + + FPcieAutoPrescanSetupBridge(instance_p, bdf, sub_bus); + + FPcieScanBus(instance_p, sub_bus, bdf); + + sub_bus = instance_p->bus_max; + FPcieAutoPostscanSetupBridge(instance_p, bdf, sub_bus); + + return sub_bus; +} + +/* + * HJF: Changed this to return int. I think this is required + * to get the correct result when scanning bridges + */ +int FPcieAutoConfigDevice(FPcie *instance_p, u32 bdf) +{ + u16 class = 0; + + struct FPcieRegion *pci_mem; + struct FPcieRegion *pci_prefetch; + struct FPcieRegion *pci_io; + + bool enum_only = false; + + int n; + +#ifdef CONFIG_PCI_ENUM_ONLY + enum_only = true; +#endif + + pci_mem = &(instance_p->mem); + pci_prefetch = &(instance_p->mem_prefetch); + pci_io = &(instance_p->mem_io); + + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCIE_CLASS_DEVICE_REG, &class) ;//读取classcode编号 + + switch (class) + { + case FPCI_CLASS_BRIDGE_PCI: + FPcieAutoSetupDevice(instance_p, bdf, 2, pci_mem, pci_prefetch, pci_io, + enum_only); + + n = FPcieHoseProbeBus(instance_p, bdf); + if (n < 0) + return n; + break; + + case FPCI_CLASS_BRIDGE_CARDBUS: + /* + * just do a minimal setup of the bridge, + * let the OS take care of the rest + */ + FPcieAutoSetupDevice(instance_p, bdf, 0, pci_mem, pci_prefetch, pci_io, + enum_only); + + printf("PCI Autoconfig: Found P2CardBus bridge, device %d\n", FPCIE_DEV(bdf)); + + break; + + case FPCI_CLASS_PROCESSOR_POWERPC: /* an agent or end-point */ + printf("PCI AutoConfig: Found PowerPC device\n"); + /* fall through */ + + default: + FPcieAutoSetupDevice(instance_p, bdf, 6, pci_mem, pci_prefetch, pci_io, + enum_only); + break; + } + + return FT_SUCCESS; +} + + +FError FPcieBindBusDevices(FPcie *instance_p, u32 bus_num, u32 parent_bdf, struct FPcieBus *bus) +{ + int dev_count = 0; + u16 vendor, device; + u8 header_type; + s32 bdf, end; + bool found_multi; + FError ret; + u8 class_show; + u32 dev_exp_cap, bus_exp_cap, dev_ext_ari_cap; + u32 data; + char buf_bdf_print[20]; + found_multi = false; + end = FPCIE_BDF(bus_num, FT_PCIE_CFG_MAX_NUM_OF_DEV - 1, + FT_PCIE_CFG_MAX_NUM_OF_FUN - 1); + for (bdf = FPCIE_BDF(bus_num, 0, 0); bdf <= end; //使用bus的seq成员来进行扫描,其实相当于secondory_bus号 + bdf += FPCIE_BDF(0, 0, 1)) + { + u32 class; + + /* phytium old pci ip version, need skip in some bus */ + if (instance_p->config.need_skip) + { + if (FPcieSkipDevice(instance_p->config.ecam, parent_bdf) == FPCIE_NEED_SKIP) + { + continue; + } + } + + if (!FPCIE_FUNC(bdf)) + found_multi = false; + if (FPCIE_FUNC(bdf) && !found_multi) + continue; + + /* Check only the first access, we don't expect problems */ + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCIE_VENDOR_REG, &vendor) ; + + if (vendor == 0xffff || vendor == 0x0000) + continue; + + FPcieEcamReadConfig8bit(instance_p->config.ecam, bdf, FPCIE_HEADER_TYPE_REG, &header_type) ; + + if (!FPCIE_FUNC(bdf)) + found_multi = header_type & 0x80; + + FPcieEcamReadConfig16bit(instance_p->config.ecam, bdf, FPCIE_DEVICE_ID_REG, &device) ; //读取deviceid + FPcieEcamReadConfig32bit(instance_p->config.ecam, bdf, FPCI_CLASS_REVISION, &class) ; //读取classcode + class >>= 8; + + FPcieEcamReadConfig8bit(instance_p->config.ecam, bdf, FPCIE_CLASS_CODE_REG, &class_show) ; + + if (parent_bdf == 0xffffffff) + { + strcpy(buf_bdf_print, "root-controller"); + } + else + { + sprintf(buf_bdf_print, "pci_%x:%x:%x", + FPCIE_BUS(parent_bdf), FPCIE_DEV(parent_bdf), FPCIE_FUNC(parent_bdf)); + } + printf(" %02x:%02x.%02x - %04lx:%04lx %s", + FPCIE_BUS(bdf), FPCIE_DEV(bdf), FPCIE_FUNC(bdf), vendor, device, + buf_bdf_print); + printf(" 0x%.2x (%s)\n", (int)class_show, FPcieClassStr(class_show)); + + /* ARI function handle */ + /* step 1: detect if PCI Express Device */ + ret = FPcieFindCapability(instance_p, bdf, PCIE_CAP, FPCI_CAP_ID_EXP, &dev_exp_cap); + if (ret == 0 && dev_exp_cap > 0) + { + /* step2: check if the device is an ARI device */ + ret = FPcieFindCapability(instance_p, bdf, PCIE_ECAP, FPCI_EXT_CAP_ID_ARI, &dev_ext_ari_cap); + if (ret == 0 && dev_ext_ari_cap > 0) + { + /* step3: check if its parent supports ARI forwarding */ + ret = FPcieFindCapability(instance_p, parent_bdf, PCIE_CAP, FPCI_CAP_ID_EXP, &bus_exp_cap); + /* config bus ARI forwarding */ + if (ret == 0 && bus_exp_cap > 0) + { + FPcieEcamReadConfig32bit(instance_p->config.ecam, parent_bdf, + bus_exp_cap + FPCIE_CAPABILITY_DEVICE_CAPABILITIES_2_OFFSET, &data); + if ((data & FPCIE_CAPABILITY_DEVICE_CAPABILITIES_2_ARI_FORWARDING) != 0) + { + /* step4: ARI forwarding support in bridge, so enable it */ + FPcieEcamReadConfig32bit(instance_p->config.ecam, parent_bdf, + bus_exp_cap + FPCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET, &data); + if (data & FPCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING == 0) + { + data |= FPCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING; + FPcieEcamWriteConfig32bit(instance_p->config.ecam, parent_bdf, + bus_exp_cap + FPCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET, data); + } + } + } + } + } + + bus->ChildN[dev_count] = bdf; + dev_count++; + + //这里可以将当前的device,保存到全局变量中,供别的驱动来查询。 + instance_p->scaned_bdf_array[instance_p->scaned_bdf_count] = bdf; + (instance_p->scaned_bdf_count)++; + + } + bus->ChildCount = dev_count; + + return FT_SUCCESS; + +} + +FError FPcieScanBus(FPcie *instance_p, u32 bus_num, u32 parent_bdf) +{ + int i = 0; + s32 bdf; + struct FPcieBus bus; + bus.ChildCount = 0; + + /* scan bus 0 device */ + FPcieBindBusDevices(instance_p, bus_num, parent_bdf, &bus); + + if (bus.ChildCount > 0) + { + for (i = 0; i < bus.ChildCount; i++) + { + bdf = bus.ChildN[i]; + FPcieAutoConfigDevice(instance_p, bdf); + } + } + instance_p->is_scaned = 1; //表示已经扫描完成 +} + diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie.h b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie.h new file mode 100644 index 0000000000..c8ca7077dc --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie.h @@ -0,0 +1,303 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie.h + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:59:37 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_FPCIE_H +#define DRIVERS_FPCIE_H + + + + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" +#include "fpcie_dma.h" +#include "fparameters.h" + +#ifdef __aarch64__ +#define CONFIG_SYS_PCI_64BIT 1 +#endif + + +#ifdef CONFIG_SYS_PCI_64BIT +typedef u64 pci_addr_t; +typedef u64 pci_size_t; +#else +typedef u32 pci_addr_t; +typedef u32 pci_size_t; +#endif + +typedef boolean bool; +#define true TRUE +#define false FALSE + + +/* Access sizes for PCI reads and writes */ +enum pci_size_t +{ + PCI_SIZE_8, + PCI_SIZE_16, + PCI_SIZE_32, +}; + + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FPCIE_ERR_INVALID_PARAM FT_CODE_ERR(ErrModBsp, ErrPcie, 0x1u) +#define FPCIE_ERR_OUTOF_BUS FT_CODE_ERR(ErrModBsp, ErrPcie, 0x2u) +#define FPCIE_ERR_CONFIG_WRITE FT_CODE_ERR(ErrModBsp, ErrPcie, 0x3u) +#define FPCIE_ERR_TYPE0 FT_CODE_ERR(ErrModBsp, ErrPcie, 0x4u) +#define FPCIE_ERR_TIMEOUT FT_CODE_ERR(ErrModBsp, ErrPcie, 0x5u) +#define FPCIE_NEED_SKIP FT_CODE_ERR(ErrModBsp, ErrPcie, 0x6u) +#define FPCIE_NOT_FOUND FT_CODE_ERR(ErrModBsp, ErrPcie, 0x7u) + + +#define FPCIE_REGION_MEM 0x00000000 /* PCI memory space */ +#define FPCIE_REGION_IO 0x00000001 /* PCI IO space */ +#define PCI_REGION_PREFETCH 0x00000008 /* prefetchable PCI memory */ + + +#define FPCIE_BAR_0 0 +#define FPCIE_BAR_1 1 +#define FPCIE_BAR_2 2 +#define FPCIE_BAR_3 3 +#define FPCIE_BAR_4 4 +#define FPCIE_BAR_5 5 + +/* PCI-E Unit controller selection */ +#define FPCIE_PEU0_C0 0 /* pcie 0 0号控制器 */ +#define FPCIE_PEU0_C1 1 /* pcie 0 1号控制器 */ +#define FPCIE_PEU0_C2 2 /* pcie 0 2号控制器 */ +#define FPCIE_PEU1_C0 3 /* pcie 1 0号控制器 */ +#define FPCIE_PEU1_C1 4 /* pcie 1 1号控制器 */ +#define FPCIE_PEU1_C2 5 /* pcie 1 2号控制器 */ + + +#define FPCIE_REGION_EXIST_FLG 1 + +/** @name Callback identifiers + * + * These constants are used as parameters to FPcieMiscSetHandler() + * @{ + */ +#define FPCIE_HANDLER_DMASEND 1U +#define FPCIE_HANDLER_DMARECV 2U +#define FPCIE_HANDLER_DMASEND_ERROR 3U +#define FPCIE_HANDLER_DMARECV_ERROR 4U +/*@}*/ + +typedef void (*FPcieIrqCallBack)(void *args); + +#if defined(__aarch64__) +typedef u64 FPcieAddr; +typedef u64 FPcieSize; +typedef u64 FPciePhysAddr; +#else +typedef u32 FPcieAddr; +typedef u32 FPcieSize; +typedef u32 FPciePhysAddr; +#endif + + +typedef struct +{ + u16 vender_id ; + u16 device_id ; + u32 bus_num ; + u32 dev_num ; + u32 fun_num ; + u32 class_code ; +} FPcieSearchFunNode; + + +typedef struct +{ + void (*IntxCallBack)(void *args) ; + void *args ; + s32 bdf ; +} FPcieIntxFun; + +struct FPcieRegion +{ + FPcieAddr bus_start; /* Start on the bus */ + FPciePhysAddr phys_start; /* Start in physical address space */ + FPcieSize size; /* Size */ + unsigned long flags; /* Resource flags */ + FPcieAddr bus_lower; + u32 exist_flg; /* exist flg */ +}; + +typedef struct +{ + u16 vendor, device; +} FpcieId; + +typedef struct +{ + u32 instance_id; /* Id of device*/ + u32 irq_num; /* Irq number */ + uintptr_t ecam; /* The Memory way */ + uintptr_t peu0_config_address; + uintptr_t peu1_config_address; + + uintptr_t control_c0_address; //0x29900000 + uintptr_t control_c1_address; //0x29910000 + uintptr_t control_c2_address; + uintptr_t control_c3_address; + uintptr_t control_c4_address; + uintptr_t control_c5_address; + +#ifdef FT_PCI_INTX_EOI + uintptr_t intx_peux_stat_address[FT_PCI_INTX_SATA_NUM] ; + uintptr_t intx_control_eux_cx_address[FT_PCI_INTX_CONTROL_NUM] ; +#endif + + u32 io_base_addr; + u32 io_size ; + u32 npmem_base_addr; + u32 npmem_size; + u64 pmem_base_addr; /* Prefetchable memory */ + u64 pmem_size; + + u8 inta_irq_num ; + u8 intb_irq_num ; + u8 intc_irq_num ; + u8 intd_irq_num ; + u8 need_skip ; + +} FPcieConfig; + +typedef struct +{ + u32 is_ready; /* Device is ininitialized and ready*/ + FPcieConfig config; + + struct FPcieRegion mem; + struct FPcieRegion mem_prefetch; + struct FPcieRegion mem_io; + + s32 bus_max; /* 当前最大bus num */ + + FPcieIrqCallBack fpcie_dma_rx_cb; + void *dma_rx_args; + + FPcieIrqCallBack fpcie_dma_tx_cb; + void *dma_tx_args; + + FPcieIrqCallBack fpcie_dma_rx_error_cb; + void *dma_rx_error_args; + + FPcieIrqCallBack fpcie_dma_tx_error_cb; + void *dma_tx_error_args; + + FPcieIntxFun inta_fun[128]; //假设最高支持128个pcie 节点 + + FPcieIntxFun intb_fun[128]; + + FPcieIntxFun intc_fun[128]; + + FPcieIntxFun intd_fun[128]; + + s32 scaned_bdf_array[128]; + s32 scaned_bdf_count; + + u32 is_scaned; /* Device is ininitialized and ready*/ + +} FPcie; + +FPcieConfig *FPcieLookupConfig(u32 instance_id); + +FError FPcieCfgInitialize(FPcie *instance_p, FPcieConfig *config_p); + +/* dma */ +FError FPcieDmaDescSet(uintptr axi_addr, + uintptr pcie_addr, + u32 length, + struct FPcieDmaDescriptor *desc, + struct FPcieDmaDescriptor *next_desc); + + +void FPcieDmaRead(uintptr cintrol_address, struct FPcieDmaDescriptor *desc); + +void FPcieDmaWrite(uintptr cintrol_address, struct FPcieDmaDescriptor *desc); + +FError FPcieDmaPollDone(struct FPcieDmaDescriptor *desc, u32 wait_cnt); + +/* Intx Interrupt */ +void FPcieIntxIrqHandler(s32 vector, void *args) ; + +FError FPcieIntxRegiterIrqHandler(FPcie *instance_p, + u32 bdf, + FPcieIntxFun *intx_fun_p) ; + +void FPcieMiscIrqDisable(FPcie *instance_p, fsize_t peu_num) ; + +struct FPcieBus +{ + s32 ChildN[32]; + u8 ChildCount; +} ; + +typedef enum +{ + HEADER = 0, + PCIE_CAP = 1, + PCIE_ECAP = 2 +} BITFIELD_REGISTER_TYPE; + + +const char *FPcieClassStr(u8 class); +void FPcieAutoRegionAlign(struct FPcieRegion *res, pci_size_t size); +int FPcieAutoRegionAllocate(struct FPcieRegion *res, pci_size_t size, + pci_addr_t *bar, bool supports_64bit); +void FPcieAutoSetupDevice(FPcie *instance_p, u32 bdf, int bars_num, + struct FPcieRegion *mem, + struct FPcieRegion *prefetch, struct FPcieRegion *io, + bool enum_only); +void FPcieAutoPrescanSetupBridge(FPcie *instance_p, u32 bdf, int sub_bus); +void FPcieAutoPostscanSetupBridge(FPcie *instance_p, u32 bdf, int sub_bus); +int FPcieHoseProbeBus(FPcie *instance_p, u32 bdf); +int FPcieAutoConfigDevice(FPcie *instance_p, u32 bdf); +FError FPcieBindBusDevices(FPcie *instance_p, u32 bus_num, u32 parent_bdf, struct FPcieBus *bus); +FError FPcieScanBus(FPcie *instance_p, u32 bus_num, u32 parent_bdf); + + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_common.h b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_common.h new file mode 100644 index 0000000000..3b7c1efef7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_common.h @@ -0,0 +1,575 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_common.h + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:57:24 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_FPCIE_COMMON_H +#define DRIVERS_FPCIE_COMMON_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fpcie_hw.h" +#include "fkernel.h" + +/******************** Macros (Inline Functions) Definitions *******************/ + +/* Device classes and subclasses */ + +#define FPCI_CLASS_NOT_DEFINED 0x0000 +#define FPCI_CLASS_NOT_DEFINED_VGA 0x0001 + +#define FPCI_BASE_CLASS_STORAGE 0x01 +#define FPCI_CLASS_STORAGE_SCSI 0x0100 +#define FPCI_CLASS_STORAGE_IDE 0x0101 +#define FPCI_CLASS_STORAGE_FLOPPY 0x0102 +#define FPCI_CLASS_STORAGE_IPI 0x0103 +#define FPCI_CLASS_STORAGE_RAID 0x0104 +#define FPCI_CLASS_STORAGE_SATA 0x0106 +#define FPCI_CLASS_STORAGE_SATA_AHCI 0x010601 +#define FPCI_CLASS_STORAGE_SAS 0x0107 +#define FPCI_CLASS_STORAGE_EXPRESS 0x010802 +#define FPCI_CLASS_STORAGE_OTHER 0x0180 + +#define FPCI_BASE_CLASS_NETWORK 0x02 +#define FPCI_CLASS_NETWORK_ETHERNET 0x0200 +#define FPCI_CLASS_NETWORK_TOKEN_RING 0x0201 +#define FPCI_CLASS_NETWORK_FDDI 0x0202 +#define FPCI_CLASS_NETWORK_ATM 0x0203 +#define FPCI_CLASS_NETWORK_OTHER 0x0280 + +#define FPCI_BASE_CLASS_DISPLAY 0x03 +#define FPCI_CLASS_DISPLAY_VGA 0x0300 +#define FPCI_CLASS_DISPLAY_XGA 0x0301 +#define FPCI_CLASS_DISPLAY_3D 0x0302 +#define FPCI_CLASS_DISPLAY_OTHER 0x0380 + +#define FPCI_BASE_CLASS_MULTIMEDIA 0x04 +#define FPCI_CLASS_MULTIMEDIA_VIDEO 0x0400 +#define FPCI_CLASS_MULTIMEDIA_AUDIO 0x0401 +#define FPCI_CLASS_MULTIMEDIA_PHONE 0x0402 +#define FPCI_CLASS_MULTIMEDIA_HD_AUDIO 0x0403 +#define FPCI_CLASS_MULTIMEDIA_OTHER 0x0480 + +#define FPCI_BASE_CLASS_MEMORY 0x05 +#define FPCI_CLASS_MEMORY_RAM 0x0500 +#define FPCI_CLASS_MEMORY_FLASH 0x0501 +#define FPCI_CLASS_MEMORY_OTHER 0x0580 + +#define FPCI_BASE_CLASS_BRIDGE 0x06 +#define FPCI_CLASS_BRIDGE_HOST 0x0600 +#define FPCI_CLASS_BRIDGE_ISA 0x0601 +#define FPCI_CLASS_BRIDGE_EISA 0x0602 +#define FPCI_CLASS_BRIDGE_MC 0x0603 +#define FPCI_CLASS_BRIDGE_PCI 0x0604 +#define FPCI_CLASS_BRIDGE_PCMCIA 0x0605 +#define FPCI_CLASS_BRIDGE_NUBUS 0x0606 +#define FPCI_CLASS_BRIDGE_CARDBUS 0x0607 +#define FPCI_CLASS_BRIDGE_RACEWAY 0x0608 +#define FPCI_CLASS_BRIDGE_OTHER 0x0680 + +#define FPCI_BASE_CLASS_COMMUNICATION 0x07 +#define FPCI_CLASS_COMMUNICATION_SERIAL 0x0700 +#define FPCI_CLASS_COMMUNICATION_PARALLEL 0x0701 +#define FPCI_CLASS_COMMUNICATION_MULTISERIAL 0x0702 +#define FPCI_CLASS_COMMUNICATION_MODEM 0x0703 +#define FPCI_CLASS_COMMUNICATION_OTHER 0x0780 + +#define FPCI_BASE_CLASS_SYSTEM 0x08 +#define FPCI_CLASS_SYSTEM_PIC 0x0800 +#define FPCI_CLASS_SYSTEM_PIC_IOAPIC 0x080010 +#define FPCI_CLASS_SYSTEM_PIC_IOXAPIC 0x080020 +#define FPCI_CLASS_SYSTEM_DMA 0x0801 +#define FPCI_CLASS_SYSTEM_TIMER 0x0802 +#define FPCI_CLASS_SYSTEM_RTC 0x0803 +#define FPCI_CLASS_SYSTEM_PCI_HOTPLUG 0x0804 +#define FPCI_CLASS_SYSTEM_SDHCI 0x0805 +#define FPCI_CLASS_SYSTEM_OTHER 0x0880 + +#define FPCI_BASE_CLASS_INPUT 0x09 +#define FPCI_CLASS_INPUT_KEYBOARD 0x0900 +#define FPCI_CLASS_INPUT_PEN 0x0901 +#define FPCI_CLASS_INPUT_MOUSE 0x0902 +#define FPCI_CLASS_INPUT_SCANNER 0x0903 +#define FPCI_CLASS_INPUT_GAMEPORT 0x0904 +#define FPCI_CLASS_INPUT_OTHER 0x0980 + +#define FPCI_BASE_CLASS_DOCKING 0x0a +#define FPCI_CLASS_DOCKING_GENERIC 0x0a00 +#define FPCI_CLASS_DOCKING_OTHER 0x0a80 + +#define FPCI_BASE_CLASS_PROCESSOR 0x0b +#define FPCI_CLASS_PROCESSOR_386 0x0b00 +#define FPCI_CLASS_PROCESSOR_486 0x0b01 +#define FPCI_CLASS_PROCESSOR_PENTIUM 0x0b02 +#define FPCI_CLASS_PROCESSOR_ALPHA 0x0b10 +#define FPCI_CLASS_PROCESSOR_POWERPC 0x0b20 +#define FPCI_CLASS_PROCESSOR_MIPS 0x0b30 +#define FPCI_CLASS_PROCESSOR_CO 0x0b40 + +#define FPCI_BASE_CLASS_SERIAL 0x0c +#define FPCI_CLASS_SERIAL_FIREWIRE 0x0c00 +#define FPCI_CLASS_SERIAL_FIREWIRE_OHCI 0x0c0010 +#define FPCI_CLASS_SERIAL_ACCESS 0x0c01 +#define FPCI_CLASS_SERIAL_SSA 0x0c02 +#define FPCI_CLASS_SERIAL_USB 0x0c03 +#define FPCI_CLASS_SERIAL_USB_UHCI 0x0c0300 +#define FPCI_CLASS_SERIAL_USB_OHCI 0x0c0310 +#define FPCI_CLASS_SERIAL_USB_EHCI 0x0c0320 +#define FPCI_CLASS_SERIAL_USB_XHCI 0x0c0330 +#define FPCI_CLASS_SERIAL_FIBER 0x0c04 +#define FPCI_CLASS_SERIAL_SMBUS 0x0c05 + +#define FPCI_BASE_CLASS_WIRELESS 0x0d +#define FPCI_CLASS_WIRELESS_RF_CONTROLLER 0x0d10 +#define FPCI_CLASS_WIRELESS_WHCI 0x0d1010 + +#define FPCI_BASE_CLASS_INTELLIGENT 0x0e +#define FPCI_CLASS_INTELLIGENT_I2O 0x0e00 + +#define FPCI_BASE_CLASS_SATELLITE 0x0f +#define FPCI_CLASS_SATELLITE_TV 0x0f00 +#define FPCI_CLASS_SATELLITE_AUDIO 0x0f01 +#define FPCI_CLASS_SATELLITE_VOICE 0x0f03 +#define FPCI_CLASS_SATELLITE_DATA 0x0f04 + +#define FPCI_BASE_CLASS_CRYPT 0x10 +#define FPCI_CLASS_CRYPT_NETWORK 0x1000 +#define FPCI_CLASS_CRYPT_ENTERTAINMENT 0x1001 +#define FPCI_CLASS_CRYPT_OTHER 0x1080 + +#define FPCI_BASE_CLASS_SIGNAL_PROCESSING 0x11 +#define FPCI_CLASS_SP_DPIO 0x1100 +#define FPCI_CLASS_SP_OTHER 0x1180 + +#define FPCI_CLASS_OTHERS 0xff + + +/* Command register offsets */ + +/* PCIe Configuration registers offsets */ + +/* Vendor ID/Device ID offset */ +#define FPCIE_CFG_ID_REG 0x0000 + +/* Independent element register */ + +#define FPCIE_VENDOR_REG 0x0 +#define FPCIE_DEVICE_ID_REG 0x02 +#define FPCIE_STATUS_REG 0x06 +#define FPCI_CLASS_DEVICE_REG 0x0a /* Device class */ +#define FPCIE_CACHE_LINE_SIZE_REG 0x0c /* 8 bits */ +#define FPCIE_LATENCY_TIMER_REG 0x0d /* 8 bits */ +#define FPCIE_HEADER_TYPE_REG 0x0e /* Header Type */ +#define FPCIE_BIST_REG 0x0f /* 8 bits */ + +#define FPCIE_HEADER_TYPE_NORMAL 0 +#define FPCIE_HEADER_TYPE_BRIDGE 1 +#define FPCIE_HEADER_TYPE_CARDBUS 2 +#define FPCIE_SECONDARY_BUS_REG 0x19 /* Secondary bus number */ +#define FPCIE_SUBORDINATE_BUS_REG 0x1a /* Highest bus number behind the bridge */ +#define FPCIE_SEC_LATENCY_TIMER_REG 0x1b /* Latency timer for secondary interface */ +#define FPCIE_IO_BASE_REG 0x1c /* I/O range behind the bridge */ +#define FPCIE_IO_LIMIT_REG 0x1d +#define FPCIE_SEC_STATUS_REG 0x1e /* Secondary status register, only bit 14 used */ + +#define FPCIE_IO_LIMIT_UPPER16_REG 0x32 + +#define FPCIE_MEMORY_BASE_REG 0x20 /* Memory range behind */ +#define FPCIE_MEMORY_LIMIT_REG 0x22 +#define FPCIE_PREF_BASE_UPPER32_REG 0x28 /* Upper half of prefetchable memory range */ +#define FPCIE_PREF_LIMIT_UPPER32_REG 0x2c + +#define FPCIE_IO_BASE_UPPER16_REG 0x30 /* Upper half of I/O addresses */ +#define FPCI_CLASS_REVISION 0x08 /* High 24 bits are class, low 8 */ + +#define FPCIE_CLASS_REVISION 0x0a /* High 24 bits are class, low 8 revision */ + +#define FPCIE_INTERRUPT_PIN_REG 0x3d +#define FPCIE_INTERRUPT_LINE_REG 0x3c +#define FPCIE_MIN_GNT_REG 0x3e /* 8 bits */ +#define FPCIE_MAX_LAT_REG 0x3f /* 8 bits */ + + +#define FPCIE_COMMAND_REG 0x04 /* 16 bits */ +#define FPCIE_COMMAND_IO 0x1 /* Enable response in I/O space */ +#define FPCIE_COMMAND_MEMORY 0x2 /* Enable response in Memory space */ +#define FPCIE_COMMAND_MASTER 0x4 /* Enable bus mastering */ +#define FPCIE_COMMAND_SPECIAL 0x8 /* Enable response to special cycles */ +#define FPCIE_COMMAND_INVALIDATE 0x10 /* Use memory write and invalidate */ +#define FPCIE_COMMAND_VGA_PALETTE 0x20 /* Enable palette snooping */ +#define FPCIE_COMMAND_PARITY 0x40 /* Enable parity checking */ +#define FPCIE_COMMAND_WAIT 0x80 /* Enable address/data stepping */ +#define FPCIE_COMMAND_SERR 0x100 /* Enable SERR */ +#define FPCIE_COMMAND_FAST_BACK 0x200 /* Enable back-to-back writes */ + +#define FPCIE_HEADER_TYPE_REG 0x0e /* 8 bits */ + + +#define FPCIE_REVISION_ID_REG 0x08 /* Revision ID */ +#define FPCIE_CLASS_PROG_REG 0x09 /* Reg. Level Programming Interface */ +#define FPCIE_CLASS_DEVICE_REG 0x0a /* Device class */ +#define FPCIE_CLASS_CODE_REG 0x0b /* Device class code */ + + +#define FPCIE_PREF_MEMORY_BASE_REG 0x24 /* Prefetchable memory range behind */ +#define FPCIE_PREF_MEMORY_LIMIT_REG 0x26 +#define FPCIE_PREF_LIMIT_UPPER32_REG 0x2c +#define FPCIE_PREF_RANGE_TYPE_MASK 0x0f +#define FPCIE_PREF_RANGE_TYPE_32 0x00 +#define FPCIE_PREF_RANGE_TYPE_64 0x01 +#define FPCIE_PREF_RANGE_MASK ~0x0f + + +#define FPCI_CLASS_BRIDGE_PCI 0x0604 +#define FPCI_CLASS_BRIDGE_CARDBUS 0x0607 +#define FPCI_CLASS_PROCESSOR_POWERPC 0x0b20 +#define FPCI_CLASS_DISPLAY_VGA 0x0300 + + + +#define FPCIE_CFG_FUN_NOT_IMP_MASK 0xFFFF +#define FPCIE_CFG_HEADER_TYPE_MASK 0x007F0000 + + +/* + * Base addresses specify locations in memory or I/O space. + * Decoded size can be determined by writing a value of + * 0xffffffff to the register, and reading it back. Only + * 1 bits are decoded. + */ +#define FPCIE_BASE_ADDRESS_0 0x10 /* 32 bits */ +#define FPCIE_BASE_ADDRESS_1 0x14 /* 32 bits [htype 0,1 only] */ +#define FPCIE_BASE_ADDRESS_2 0x18 /* 32 bits [htype 0 only] */ +#define FPCIE_BASE_ADDRESS_3 0x1c /* 32 bits */ +#define FPCIE_BASE_ADDRESS_4 0x20 /* 32 bits */ +#define FPCIE_BASE_ADDRESS_5 0x24 /* 32 bits */ +#define FPCIE_BASE_ADDRESS_SPACE 0x01 /* 0 = memory, 1 = I/O */ +#define FPCIE_BASE_ADDRESS_SPACE_IO 0x01 +#define FPCIE_BASE_ADDRESS_SPACE_MEMORY 0x00 +#define FPCIE_BASE_ADDRESS_MEM_TYPE_MASK 0x06 +#define FPCIE_BASE_ADDRESS_MEM_TYPE_32 0x00 /* 32 bit address */ +#define FPCIE_BASE_ADDRESS_MEM_TYPE_1M 0x02 /* Below 1M [obsolete] */ +#define FPCIE_BASE_ADDRESS_MEM_TYPE_64 0x04 /* 64 bit address */ +#define FPCIE_BASE_ADDRESS_MEM_PREFETCH 0x08 /* prefetchable? */ +#define FPCIE_BASE_ADDRESS_MEM_MASK (~0x0fULL) +#define FPCIE_BASE_ADDRESS_IO_MASK (~0x03ULL) +#define FPCIE_EP_MIN_APERTURE 128 + +/* BAR control values applicable to both Endpoint Function and Root Complex */ +#define FPCIE_LM_BAR_CFG_CTRL_DISABLED 0x0 +#define FPCIE_LM_BAR_CFG_CTRL_IO_32BITS 0x1 +#define FPCIE_LM_BAR_CFG_CTRL_MEM_32BITS 0x4 +#define FPCIE_LM_BAR_CFG_CTRL_PREFETCH_MEM_32BITS 0x5 +#define FPCIE_LM_BAR_CFG_CTRL_MEM_64BITS 0x6 +#define FPCIE_LM_BAR_CFG_CTRL_PREFETCH_MEM_64BITS 0x7 + + +/* Header type 0 (normal devices) */ +#define FPCIE_CARDBUS_CIS 0x28 +#define FPCIE_SUBSYSTEM_VENDOR_ID 0x2c +#define FPCIE_SUBSYSTEM_ID 0x2e +#define FPCIE_ROM_ADDRESS 0x30 /* Bits 31..11 are address, 10..1 reserved */ +#define FPCIE_ROM_ADDRESS_ENABLE 0x01 +#define FPCIE_ROM_ADDRESS_MASK (~0x7ffULL) + + +#define FPCIE_BASE_CLASS_DISPLAY 0x03 +#define FPCIE_CLASS_DISPLAY_VGA 0x0300 +#define FPCIE_CLASS_DISPLAY_XGA 0x0301 +#define FPCIE_CLASS_DISPLAY_3D 0x0302 +#define FPCIE_CLASS_DISPLAY_OTHER 0x0380 + +/* 0x34 same as for htype 0 */ +#define FPCIE_CAPABILITY_LIST 0x34 /* Offset of first capability list entry */ +#define FPCIE_ECAP_START 0x100 /* offset of first extend capability list entry */ + +/* 0x35-0x3b is reserved */ +#define FPCIE_ROM_ADDRESS1 0x38 /* Same as PCI_ROM_ADDRESS, but for htype 1 */ +#define FPCIE_BRIDGE_CONTROL_REG 0x3e + + +#define FPCI_CLASS_SUB_CODE 0x0a /* Device sub-class code */ +#define FPCI_CLASS_SUB_CODE_TOO_OLD_NOTVGA 0x00 +#define FPCI_CLASS_SUB_CODE_TOO_OLD_VGA 0x01 +#define FPCI_CLASS_SUB_CODE_STORAGE_SCSI 0x00 +#define FPCI_CLASS_SUB_CODE_STORAGE_IDE 0x01 +#define FPCI_CLASS_SUB_CODE_STORAGE_FLOPPY 0x02 +#define FPCI_CLASS_SUB_CODE_STORAGE_IPIBUS 0x03 +#define FPCI_CLASS_SUB_CODE_STORAGE_RAID 0x04 +#define FPCI_CLASS_SUB_CODE_STORAGE_ATA 0x05 +#define FPCI_CLASS_SUB_CODE_STORAGE_SATA 0x06 +#define FPCI_CLASS_SUB_CODE_STORAGE_SAS 0x07 +#define FPCI_CLASS_SUB_CODE_STORAGE_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_NETWORK_ETHERNET 0x00 +#define FPCI_CLASS_SUB_CODE_NETWORK_TOKENRING 0x01 +#define FPCI_CLASS_SUB_CODE_NETWORK_FDDI 0x02 +#define FPCI_CLASS_SUB_CODE_NETWORK_ATM 0x03 +#define FPCI_CLASS_SUB_CODE_NETWORK_ISDN 0x04 +#define FPCI_CLASS_SUB_CODE_NETWORK_WORLDFIP 0x05 +#define FPCI_CLASS_SUB_CODE_NETWORK_PICMG 0x06 +#define FPCI_CLASS_SUB_CODE_NETWORK_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_DISPLAY_VGA 0x00 +#define FPCI_CLASS_SUB_CODE_DISPLAY_XGA 0x01 +#define FPCI_CLASS_SUB_CODE_DISPLAY_3D 0x02 +#define FPCI_CLASS_SUB_CODE_DISPLAY_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_MULTIMEDIA_VIDEO 0x00 +#define FPCI_CLASS_SUB_CODE_MULTIMEDIA_AUDIO 0x01 +#define FPCI_CLASS_SUB_CODE_MULTIMEDIA_PHONE 0x02 +#define FPCI_CLASS_SUB_CODE_MULTIMEDIA_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_MEMORY_RAM 0x00 +#define FPCI_CLASS_SUB_CODE_MEMORY_FLASH 0x01 +#define FPCI_CLASS_SUB_CODE_MEMORY_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_BRIDGE_HOST 0x00 +#define FPCI_CLASS_SUB_CODE_BRIDGE_ISA 0x01 +#define FPCI_CLASS_SUB_CODE_BRIDGE_EISA 0x02 +#define FPCI_CLASS_SUB_CODE_BRIDGE_MCA 0x03 +#define FPCI_CLASS_SUB_CODE_BRIDGE_PCI 0x04 +#define FPCI_CLASS_SUB_CODE_BRIDGE_PCMCIA 0x05 +#define FPCI_CLASS_SUB_CODE_BRIDGE_NUBUS 0x06 +#define FPCI_CLASS_SUB_CODE_BRIDGE_CARDBUS 0x07 +#define FPCI_CLASS_SUB_CODE_BRIDGE_RACEWAY 0x08 +#define FPCI_CLASS_SUB_CODE_BRIDGE_SEMI_PCI 0x09 +#define FPCI_CLASS_SUB_CODE_BRIDGE_INFINIBAND 0x0A +#define FPCI_CLASS_SUB_CODE_BRIDGE_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_COMM_SERIAL 0x00 +#define FPCI_CLASS_SUB_CODE_COMM_PARALLEL 0x01 +#define FPCI_CLASS_SUB_CODE_COMM_MULTIPORT 0x02 +#define FPCI_CLASS_SUB_CODE_COMM_MODEM 0x03 +#define FPCI_CLASS_SUB_CODE_COMM_GPIB 0x04 +#define FPCI_CLASS_SUB_CODE_COMM_SMARTCARD 0x05 +#define FPCI_CLASS_SUB_CODE_COMM_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_PERIPHERAL_PIC 0x00 +#define FPCI_CLASS_SUB_CODE_PERIPHERAL_DMA 0x01 +#define FPCI_CLASS_SUB_CODE_PERIPHERAL_TIMER 0x02 +#define FPCI_CLASS_SUB_CODE_PERIPHERAL_RTC 0x03 +#define FPCI_CLASS_SUB_CODE_PERIPHERAL_HOTPLUG 0x04 +#define FPCI_CLASS_SUB_CODE_PERIPHERAL_SD 0x05 +#define FPCI_CLASS_SUB_CODE_PERIPHERAL_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_INPUT_KEYBOARD 0x00 +#define FPCI_CLASS_SUB_CODE_INPUT_DIGITIZER 0x01 +#define FPCI_CLASS_SUB_CODE_INPUT_MOUSE 0x02 +#define FPCI_CLASS_SUB_CODE_INPUT_SCANNER 0x03 +#define FPCI_CLASS_SUB_CODE_INPUT_GAMEPORT 0x04 +#define FPCI_CLASS_SUB_CODE_INPUT_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_DOCKING_GENERIC 0x00 +#define FPCI_CLASS_SUB_CODE_DOCKING_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_PROCESSOR_386 0x00 +#define FPCI_CLASS_SUB_CODE_PROCESSOR_486 0x01 +#define FPCI_CLASS_SUB_CODE_PROCESSOR_PENTIUM 0x02 +#define FPCI_CLASS_SUB_CODE_PROCESSOR_ALPHA 0x10 +#define FPCI_CLASS_SUB_CODE_PROCESSOR_POWERPC 0x20 +#define FPCI_CLASS_SUB_CODE_PROCESSOR_MIPS 0x30 +#define FPCI_CLASS_SUB_CODE_PROCESSOR_COPROC 0x40 +#define FPCI_CLASS_SUB_CODE_SERIAL_1394 0x00 +#define FPCI_CLASS_SUB_CODE_SERIAL_ACCESSBUS 0x01 +#define FPCI_CLASS_SUB_CODE_SERIAL_SSA 0x02 +#define FPCI_CLASS_SUB_CODE_SERIAL_USB 0x03 +#define FPCI_CLASS_SUB_CODE_SERIAL_FIBRECHAN 0x04 +#define FPCI_CLASS_SUB_CODE_SERIAL_SMBUS 0x05 +#define FPCI_CLASS_SUB_CODE_SERIAL_INFINIBAND 0x06 +#define FPCI_CLASS_SUB_CODE_SERIAL_IPMI 0x07 +#define FPCI_CLASS_SUB_CODE_SERIAL_SERCOS 0x08 +#define FPCI_CLASS_SUB_CODE_SERIAL_CANBUS 0x09 +#define FPCI_CLASS_SUB_CODE_WIRELESS_IRDA 0x00 +#define FPCI_CLASS_SUB_CODE_WIRELESS_IR 0x01 +#define FPCI_CLASS_SUB_CODE_WIRELESS_RF 0x10 +#define FPCI_CLASS_SUB_CODE_WIRELESS_BLUETOOTH 0x11 +#define FPCI_CLASS_SUB_CODE_WIRELESS_BROADBAND 0x12 +#define FPCI_CLASS_SUB_CODE_WIRELESS_80211A 0x20 +#define FPCI_CLASS_SUB_CODE_WIRELESS_80211B 0x21 +#define FPCI_CLASS_SUB_CODE_WIRELESS_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_I2O_V1_0 0x00 +#define FPCI_CLASS_SUB_CODE_SATELLITE_TV 0x01 +#define FPCI_CLASS_SUB_CODE_SATELLITE_AUDIO 0x02 +#define FPCI_CLASS_SUB_CODE_SATELLITE_VOICE 0x03 +#define FPCI_CLASS_SUB_CODE_SATELLITE_DATA 0x04 +#define FPCI_CLASS_SUB_CODE_CRYPTO_NETWORK 0x00 +#define FPCI_CLASS_SUB_CODE_CRYPTO_ENTERTAINMENT 0x10 +#define FPCI_CLASS_SUB_CODE_CRYPTO_OTHER 0x80 +#define FPCI_CLASS_SUB_CODE_DATA_DPIO 0x00 +#define FPCI_CLASS_SUB_CODE_DATA_PERFCNTR 0x01 +#define FPCI_CLASS_SUB_CODE_DATA_COMMSYNC 0x10 +#define FPCI_CLASS_SUB_CODE_DATA_MGMT 0x20 +#define FPCI_CLASS_SUB_CODE_DATA_OTHER 0x80 + + +/* Header type 2 (CardBus bridges) */ +#define FPCI_CB_CAPABILITY_LIST 0x14 +/* 0x15 reserved */ +#define FPCI_CB_SEC_STATUS 0x16 /* Secondary status */ +#define FPCI_CB_PRIMARY_BUS 0x18 /* PCI bus number */ +#define FPCI_CB_CARD_BUS 0x19 /* CardBus bus number */ +#define FPCI_CB_SUBORDINATE_BUS 0x1a /* Subordinate bus number */ +#define FPCI_CB_LATENCY_TIMER 0x1b /* CardBus latency timer */ +#define FPCI_CB_MEMORY_BASE_0 0x1c +#define FPCI_CB_MEMORY_LIMIT_0 0x20 +#define FPCI_CB_MEMORY_BASE_1 0x24 +#define FPCI_CB_MEMORY_LIMIT_1 0x28 +#define FPCI_CB_IO_BASE_0 0x2c +#define FPCI_CB_IO_BASE_0_HI 0x2e +#define FPCI_CB_IO_LIMIT_0 0x30 +#define FPCI_CB_IO_LIMIT_0_HI 0x32 +#define FPCI_CB_IO_BASE_1 0x34 +#define FPCI_CB_IO_BASE_1_HI 0x36 +#define FPCI_CB_IO_LIMIT_1 0x38 +#define FPCI_CB_IO_LIMIT_1_HI 0x3a +#define FPCI_CB_IO_RANGE_MASK ~0x03 +/* 0x3c-0x3d are same as for htype 0 */ +#define FPCI_CB_BRIDGE_CONTROL 0x3e +#define FPCI_CB_BRIDGE_CTL_PARITY 0x01 /* Similar to standard bridge control register */ +#define FPCI_CB_BRIDGE_CTL_SERR 0x02 +#define FPCI_CB_BRIDGE_CTL_ISA 0x04 +#define FPCI_CB_BRIDGE_CTL_VGA 0x08 +#define FPCI_CB_BRIDGE_CTL_MASTER_ABORT 0x20 +#define FPCI_CB_BRIDGE_CTL_CB_RESET 0x40 /* CardBus reset */ +#define FPCI_CB_BRIDGE_CTL_16BIT_INT 0x80 /* Enable interrupt for 16-bit cards */ +#define FPCI_CB_BRIDGE_CTL_PREFETCH_MEM0 0x100 /* Prefetch enable for both memory regions */ +#define FPCI_CB_BRIDGE_CTL_PREFETCH_MEM1 0x200 +#define FPCI_CB_BRIDGE_CTL_POST_WRITES 0x400 +#define FPCI_CB_SUBSYSTEM_VENDOR_ID 0x40 +#define FPCI_CB_SUBSYSTEM_ID 0x42 +#define FPCI_CB_LEGACY_MODE_BASE 0x44 /* 16-bit PC Card legacy mode base address (ExCa) */ +/* 0x48-0x7f reserved */ + + +/* Capability lists */ + +#define FPCI_CAP_LIST_ID 0 /* Capability ID */ +#define FPCI_CAP_ID_PM 0x01 /* Power Management */ +#define FPCI_CAP_ID_AGP 0x02 /* Accelerated Graphics Port */ +#define FPCI_CAP_ID_VPD 0x03 /* Vital Product Data */ +#define FPCI_CAP_ID_SLOTID 0x04 /* Slot Identification */ +#define FPCI_CAP_ID_MSI 0x05 /* Message Signalled Interrupts */ +#define FPCI_CAP_ID_CHSWP 0x06 /* CompactPCI HotSwap */ +#define FPCI_CAP_ID_PCIX 0x07 /* PCI-X */ +#define FPCI_CAP_ID_HT 0x08 /* HyperTransport */ +#define FPCI_CAP_ID_VNDR 0x09 /* Vendor-Specific */ +#define FPCI_CAP_ID_DBG 0x0A /* Debug port */ +#define FPCI_CAP_ID_CCRC 0x0B /* CompactPCI Central Resource Control */ +#define FPCI_CAP_ID_SHPC 0x0C /* PCI Standard Hot-Plug Controller */ +#define FPCI_CAP_ID_SSVID 0x0D /* Bridge subsystem vendor/device ID */ +#define FPCI_CAP_ID_AGP3 0x0E /* AGP Target PCI-PCI bridge */ +#define FPCI_CAP_ID_SECDEV 0x0F /* Secure Device */ +#define FPCI_CAP_ID_EXP 0x10 /* PCI Express */ +#define FPCI_CAP_ID_MSIX 0x11 /* MSI-X */ +#define FPCI_CAP_ID_SATA 0x12 /* SATA Data/Index Conf. */ +#define FPCI_CAP_ID_AF 0x13 /* PCI Advanced Features */ +#define FPCI_CAP_ID_EA 0x14 /* PCI Enhanced Allocation */ +#define FPCI_CAP_ID_MAX PCI_CAP_ID_EA + +/* Extended Capabilities (PCI-X 2.0 and Express) */ +//#define PCI_EXT_CAP_ID(header) (header & 0x0000ffff) +//#define PCI_EXT_CAP_VER(header) ((header >> 16) & 0xf) +//#define PCI_EXT_CAP_NEXT(header) ((header >> 20) & 0xffc) + +#define FPCI_EXT_CAP_ID_ERR 0x01 /* Advanced Error Reporting */ +#define FPCI_EXT_CAP_ID_VC 0x02 /* Virtual Channel Capability */ +#define FPCI_EXT_CAP_ID_DSN 0x03 /* Device Serial Number */ +#define FPCI_EXT_CAP_ID_PWR 0x04 /* Power Budgeting */ +#define FPCI_EXT_CAP_ID_RCLD 0x05 /* Root Complex Link Declaration */ +#define FPCI_EXT_CAP_ID_RCILC 0x06 /* Root Complex Internal Link Control */ +#define FPCI_EXT_CAP_ID_RCEC 0x07 /* Root Complex Event Collector */ +#define FPCI_EXT_CAP_ID_MFVC 0x08 /* Multi-Function VC Capability */ +#define FPCI_EXT_CAP_ID_VC9 0x09 /* same as _VC */ +#define FPCI_EXT_CAP_ID_RCRB 0x0A /* Root Complex RB? */ +#define FPCI_EXT_CAP_ID_VNDR 0x0B /* Vendor-Specific */ +#define FPCI_EXT_CAP_ID_CAC 0x0C /* Config Access - obsolete */ +#define FPCI_EXT_CAP_ID_ACS 0x0D /* Access Control Services */ +#define FPCI_EXT_CAP_ID_ARI 0x0E /* Alternate Routing ID */ +#define FPCI_EXT_CAP_ID_ATS 0x0F /* Address Translation Services */ +#define FPCI_EXT_CAP_ID_SRIOV 0x10 /* Single Root I/O Virtualization */ +#define FPCI_EXT_CAP_ID_MRIOV 0x11 /* Multi Root I/O Virtualization */ +#define FPCI_EXT_CAP_ID_MCAST 0x12 /* Multicast */ +#define FPCI_EXT_CAP_ID_PRI 0x13 /* Page Request Interface */ +#define FPCI_EXT_CAP_ID_AMD_XXX 0x14 /* Reserved for AMD */ +#define FPCI_EXT_CAP_ID_REBAR 0x15 /* Resizable BAR */ +#define FPCI_EXT_CAP_ID_DPA 0x16 /* Dynamic Power Allocation */ +#define FPCI_EXT_CAP_ID_TPH 0x17 /* TPH Requester */ +#define FPCI_EXT_CAP_ID_LTR 0x18 /* Latency Tolerance Reporting */ +#define FPCI_EXT_CAP_ID_SECPCI 0x19 /* Secondary PCIe Capability */ +#define FPCI_EXT_CAP_ID_PMUX 0x1A /* Protocol Multiplexing */ +#define FPCI_EXT_CAP_ID_PASID 0x1B /* Process Address Space ID */ +#define FPCI_EXT_CAP_ID_DPC 0x1D /* Downstream Port Containment */ +#define FPCI_EXT_CAP_ID_L1SS 0x1E /* L1 PM Substates */ +#define FPCI_EXT_CAP_ID_PTM 0x1F /* Precision Time Measurement */ +#define FPCI_EXT_CAP_ID_MAX PCI_EXT_CAP_ID_PTM + +/* ARI capability */ +#define FPCIE_CAPABILITY_BASE_OFFSET 0x100 +#define FPCIE_CAPABILITY_ID_SRIOV_CONTROL_ARI_HIERARCHY 0x10 +#define FPCIE_CAPABILITY_DEVICE_CAPABILITIES_2_OFFSET 0x24 +#define FPCIE_CAPABILITY_DEVICE_CAPABILITIES_2_ARI_FORWARDING 0x20 +#define FPCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET 0x28 +#define FPCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING 0x20 + + + +/* + * Address Translation Registers + */ +#define FPCIE_AT_BASE FPCIE_REG_OUTBOUND_R0_PATR0_OFFSET +/* + * Local Management Registers + */ +#define FPCIE_LM_BASE 0x2000 + +#define FPCIE_CFG_HEADER_O_TYPE 0x0000 + +/* Endpoint Function BAR Inbound PCIe to AXI Address Translation Register */ +#define FPCIE_AT_IB_EP_FUNC_BAR_ADDR0(fn, bar) \ + (FPCIE_AT_BASE + 0x0840 + (fn)*0x0040 + (bar)*0x0008) +#define FPCIE_AT_IB_EP_FUNC_BAR_ADDR1(fn, bar) \ + (FPCIE_AT_BASE + 0x0844 + (fn)*0x0040 + (bar)*0x0008) + +/* Endpoint Function f BAR b Configuration Registers */ +#define FPCIE_LM_EP_FUNC_BAR_CFG0(fn) \ + (FPCIE_LM_BASE + 0x0240 + (fn)*0x0008) +#define FPCIE_LM_EP_FUNC_BAR_CFG1(fn) \ + (FPCIE_LM_BASE + 0x0244 + (fn)*0x0008) + +#define FPCIE_LM_EP_FUNC_BAR_CFG_BAR_APERTURE_MASK(b) \ + (GENMASK(4, 0) << ((b)*8)) +#define FPCIE_LM_EP_FUNC_BAR_CFG_BAR_APERTURE(b, a) \ + (((a) << ((b)*8)) & FPCIE_LM_EP_FUNC_BAR_CFG_BAR_APERTURE_MASK(b)) +#define FPCIE_LM_EP_FUNC_BAR_CFG_BAR_CTRL_MASK(b) \ + (GENMASK(7, 5) << ((b)*8)) +#define FPCIE_LM_EP_FUNC_BAR_CFG_BAR_CTRL(b, c) \ + (((c) << ((b)*8 + 5)) & FPCIE_LM_EP_FUNC_BAR_CFG_BAR_CTRL_MASK(b)) + +#define FPCIE_REG_EP_C0_PREF_BASE_LIMIT_OFFSET_GET(config_addr, peu_num) \ + (u32)(config_addr + FPCIE_REG_EP_C0_PREF_BASE_LIMIT_OFFSET + ((peu_num + 3) % 3) * 16) + +#define FPCIE_REG_EP_C0_MEM_BASE_LIMIT_OFFSET_GET(config_addr, peu_num) \ + (u32)(config_addr + FPCIE_REG_EP_C0_MEM_BASE_LIMIT_OFFSET + ((peu_num + 3) % 3) * 16) + +#define FPCIE_BAR_MEM_TYPE_64 1 +#define FPCIE_BAR_MEM_TYPE_32 0 +#define FPCIE_PRIMARY_BUS_REG 0x18 + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_config.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_config.c new file mode 100644 index 0000000000..1fc5f4ad6a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_config.c @@ -0,0 +1,98 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_config.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:57:30 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fpcie.h" +#include "fpcie_hw.h" + + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/** + * @name: FPcieMiscIrqEnable + * @msg: 开启PCIE 子系统中对应中断源的 misc 中断 + * @param {FPcie} *instance_p + * @param {fsize_t} peu_num + */ +void FPcieMiscIrqEnable(FPcie *instance_p, fsize_t peu_num) +{ + u64 config_address; + u32 reg_value; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(peu_num <= FPCIE_PEU1_C2); + + if (peu_num < FPCIE_PEU1_C0) + { + config_address = instance_p->config.peu0_config_address; + } + else + { + config_address = instance_p->config.peu1_config_address; + peu_num -= FPCIE_PEU1_C0; + } + + reg_value = FPCIE_READREG(config_address, FPCIE_REG_MISC_INT_ENALBE_OFFSET); + FPCIE_WRITEREG(config_address, FPCIE_REG_MISC_INT_ENALBE_OFFSET, (reg_value | (1 << peu_num))); +} + + + +/** + * @name: FPcieMiscIrqDisable + * @msg: 关闭PCIE 子系统中对应中断的 misc 中断 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {fsize_t} peu_num is pci-e unit controller selection + */ +void FPcieMiscIrqDisable(FPcie *instance_p, fsize_t peu_num) +{ + uintptr_t config_address; + u32 reg_value; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(peu_num <= FPCIE_PEU1_C2); + + if (peu_num < FPCIE_PEU1_C0) + { + config_address = instance_p->config.peu0_config_address; + } + else + { + config_address = instance_p->config.peu1_config_address; + peu_num -= FPCIE_PEU1_C0; + } + + reg_value = FPCIE_READREG(config_address, FPCIE_REG_MISC_INT_ENALBE_OFFSET); + FPCIE_WRITEREG(config_address, FPCIE_REG_MISC_INT_ENALBE_OFFSET, (reg_value & ~(1 << peu_num))); +} + + diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_dma.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_dma.c new file mode 100644 index 0000000000..721e8d2d25 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_dma.c @@ -0,0 +1,167 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_dma.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:57:38 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fpcie_hw.h" +#include "fpcie_dma.h" +#include "fpcie.h" +#include "ftypes.h" +#include "fcache.h" +#include "fkernel.h" + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +#include "fdebug.h" +#define FPCIE_DMA_DEBUG_TAG "FPCIE_DMA" +#define FPCIE_DMA_ERROR(format, ...) FT_DEBUG_PRINT_E(FPCIE_DMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_DMA_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FPCIE_DMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_DMA_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FPCIE_DMA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_DMA_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FPCIE_DMA_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/** + * @name: FPcieDmaDescSet + * @msg: PCIE DMA descriptor group packet + * @param {uintptr} axi_addr is memory address + * @param {uintptr} bar_addr is Base Address Register value + * @param {u32} length want to send byte length + * @param {struct FPcieDmaDescriptor *} desc Desc is the descriptor to be configured + * @param {struct FPcieDmaDescriptor *} next_desc is the next descriptor that needs to be sent + * @return {FError} + */ +FError FPcieDmaDescSet(uintptr axi_addr, + uintptr bar_addr, + u32 length, + struct FPcieDmaDescriptor *desc, + struct FPcieDmaDescriptor *next_desc) +{ + /* 设置内存地址 */ + desc->axi_base_address = axi_addr; + desc->axi_address_phase_controls = 0x00; + + /* 设置pcie空间地址 */ + desc->pcie_base_address = bar_addr; + desc->pcie_tlp_header_attributes = 0x01; + + /* 设置数据长度, 设置dma完成中断 */ + desc->transfer_control = length; + + desc->axi_bus_status = 0x00; + desc->pcie_bus_status = 0x00; + desc->channel_status = 0x00; + + if (next_desc != NULL) + { + /* 使能链表模式 */ + desc->transfer_control &= ~(BIT(24)); + desc->transfer_control |= BIT(29); + + /* 设置下一级链表地址 */ + desc->next_descriptor = (uintptr)next_desc; + } + else + { + desc->transfer_control |= BIT(24); + desc->transfer_control &= ~(BIT(29)); + desc->next_descriptor = 0; + } + + return 0; +} + +/** + * @name: FPcieDmaRead + * @msg: Pcie reads through dma + * @param {uintptr} bar_addr is Base Address Register value + * @param {FPcieDmaDescriptor} *desc is first address of the receive descriptor + */ +void FPcieDmaRead(uintptr bar_address, struct FPcieDmaDescriptor *desc) +{ + /* The enable channel is interrupted */ + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_INT_ENABLE_OFFSET, FPCIE_CTRL_DMA_INT_ENABLE_CH0_DONE_MASK | FPCIE_CTRL_DMA_INT_ENABLE_CH0_ERR_MASK); + + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH0_SP_L_OFFSET, (u32)((uintptr)desc & 0xffffffffU)); +#ifdef __aarch64__ + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH0_SP_H_OFFSET, (u32)(((uintptr)desc >> 32) & 0xffffffffU)); +#else + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH0_SP_H_OFFSET, 0); +#endif + + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH0_CTRL_OFFSET, FPCIE_CTRL_DMA_CH0_CTRL_GO_MASK); +} + +/** + * @name: FPcieDmaWrite + * @msg: Pcie writes through dma + * @param {uintptr} bar_address is Base Address Register value + * @param {FPcieDmaDescriptor} *desc is first address of the send descriptor + */ + +void FPcieDmaWrite(uintptr bar_address, struct FPcieDmaDescriptor *desc) +{ + /* The enable channel is interrupted */ + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_INT_ENABLE_OFFSET, FPCIE_CTRL_DMA_INT_ENABLE_CH1_DONE_MASK | FPCIE_CTRL_DMA_INT_ENABLE_CH1_ERR_MASK); + + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH1_SP_L_OFFSET, (u32)((uintptr)desc & 0xffffffffU)); +#ifdef __aarch64__ + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH1_SP_H_OFFSET, (u32)(((uintptr)desc >> 32) & 0xffffffffU)); +#else + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH1_SP_H_OFFSET, 0); +#endif + FPCIE_WRITEREG(bar_address, FPCIE_REG_DMA_CH1_CTRL_OFFSET, FPCIE_CTRL_DMA_CH1_CTRL_GO_MASK | FPCIE_CTRL_DMA_CH1_CTRL_OBNOTIB_MASK); +} + +/** + * @name: FPcieDmaPollDone + * @msg: Polling waits for DMA to complete + * @param {FPcieDmaDescriptor *} desc is the current need to wait for dma to complete + * @param {u32} wait_cnt is the count that needs to wait to end + * @return FError + */ +FError FPcieDmaPollDone(struct FPcieDmaDescriptor *desc, u32 wait_cnt) +{ + FPCIE_DMA_DEBUG_I("desc axi_bus_status :[0x%02x]", desc->axi_bus_status); + FPCIE_DMA_DEBUG_I("desc pcie_bus_status:[0x%02x]", desc->pcie_bus_status); + FPCIE_DMA_DEBUG_I("desc channel_status :[0x%02x]", desc->channel_status); + + while (wait_cnt > 0) + { + if (desc->channel_status == 0x1) + { + FPCIE_DMA_DEBUG_I("dma channel transfer done "); + return FT_SUCCESS; + } + wait_cnt--; + } + + return FPCIE_ERR_TIMEOUT; +} diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_dma.h b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_dma.h new file mode 100644 index 0000000000..6e0d54bdba --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_dma.h @@ -0,0 +1,77 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_dma.h + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:57:51 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef DRIVERS_FPCIE_DMA_H +#define DRIVERS_FPCIE_DMA_H + +#ifdef __cplusplus +extern "C" +{ +#endif +#include "ftypes.h" + + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define DMA_XFER_START (0x01 << 0) +#define DMA_READ (0x00 << 1) +#define DMA_WRITE (0x01 << 1) + +#define DMA_CHANNEL_READ_DONE (0x01 << 0) +#define DMA_CHANNEL_WRITE_DONE (0x01 << 1) +#define DMA_CHANNEL_READ_ERROR (0x01 << 8) +#define DMA_CHANNEL_WRITE_ERROR (0x01 << 9) + +#define DMA_CHANNEL_READ_DONE_ENABLE (0x01 << 0) +#define DMA_CHANNEL_WRITE_DONE_ENABLE (0x01 << 1) +#define DMA_CHANNEL_READ_ERROR_ENABLE (0x01 << 8) +#define DMA_CHANNEL_WRITE_ERROR_ENABLE (0x01 << 9) +/************************** Function Prototypes ******************************/ + + +/**************************** Type Definitions *******************************/ + +struct FPcieDmaDescriptor +{ + volatile u64 axi_base_address; /* 0x00 */ + volatile u32 axi_address_phase_controls; /* 0x08 */ + volatile u64 pcie_base_address; /* 0x12 */ + volatile u64 pcie_tlp_header_attributes; /* 0x20 */ + volatile u32 transfer_control; /* 0x28 */ + volatile u8 axi_bus_status; /* 0x32 */ + volatile u8 pcie_bus_status; /* 0x33 */ + volatile u8 channel_status; /* 0x34 */ + volatile u8 reserve; /* 0x35 */ + volatile u64 next_descriptor; /* 0x36 */ +} __attribute__((packed)) __attribute__((aligned(128))); + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_ep.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_ep.c new file mode 100644 index 0000000000..cad384e18c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_ep.c @@ -0,0 +1,216 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_ep.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:57:59 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fpcie.h" +#include "fpcie_hw.h" +#include "ftypes.h" +#include "fpcie_common.h" +#include +#include +#include "fkernel.h" +#include "fdebug.h" + + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FPCIE_EP_DEBUG_TAG "FPCIE_EP" +#define FPCIE_EP_ERROR(format, ...) FT_DEBUG_PRINT_E(FPCIE_EP_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_EP_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FPCIE_EP_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_EP_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FPCIE_EP_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_EP_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FPCIE_EP_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + + + +int FPcieEpSetBar(FPcie *instance_p, u32 peu_num, u32 bar_num, u64 bar_mem_addr, u64 bar_mem_size, int flags) +{ + u32 addr0, addr1, reg, cfg, b, aperture, ctrl; + u64 sz; + uintptr_t base_addr; + FASSERT(instance_p != NULL); + base_addr = *(uintptr_t *)(&instance_p->config.control_c0_address + peu_num); + + /* BAR size is 2^(aperture + 7) */ + sz = max(bar_mem_size, (u64)FPCIE_EP_MIN_APERTURE); + /* + * roundup_pow_of_two() returns an unsigned long, which is not suited + * for 64bit values. + */ + + sz = 1ULL << fls(sz - 1); + aperture = log2(sz) - 7; /* 128B -> 0, 256B -> 1, 512B -> 2, ... */ + + if ((flags & FPCIE_BASE_ADDRESS_SPACE) == FPCIE_BASE_ADDRESS_SPACE) + { + ctrl = FPCIE_LM_BAR_CFG_CTRL_IO_32BITS; + } + else + { + boolean is_prefetch = !!(flags & FPCIE_BASE_ADDRESS_MEM_PREFETCH); + boolean is_64bits = sz > SZ_2G; + + if (is_64bits && (bar_num & 1)) + return FPCIE_ERR_INVALID_PARAM; + + if (is_64bits && !(flags & FPCIE_BASE_ADDRESS_MEM_TYPE_64)) + flags |= FPCIE_BASE_ADDRESS_MEM_TYPE_64; + + if (is_64bits && is_prefetch) + ctrl = FPCIE_LM_BAR_CFG_CTRL_PREFETCH_MEM_64BITS; + else if (is_prefetch) + ctrl = FPCIE_LM_BAR_CFG_CTRL_PREFETCH_MEM_32BITS; + else if (is_64bits) + ctrl = FPCIE_LM_BAR_CFG_CTRL_MEM_64BITS; + else + ctrl = FPCIE_LM_BAR_CFG_CTRL_MEM_32BITS; + } + + addr0 = LOWER_32_BITS(bar_mem_addr); + addr1 = UPPER_32_BITS(bar_mem_addr); + + FPCIE_WRITEREG(base_addr, FPCIE_AT_IB_EP_FUNC_BAR_ADDR0(0, bar_num), addr0); + FPCIE_WRITEREG(base_addr, FPCIE_AT_IB_EP_FUNC_BAR_ADDR1(0, bar_num), addr1); + + if (bar_num < FPCIE_BAR_4) + { + reg = FPCIE_LM_EP_FUNC_BAR_CFG0(0); + b = reg; + } + else + { + reg = FPCIE_LM_EP_FUNC_BAR_CFG0(0); + b = reg - FPCIE_BAR_4; + } + + cfg = FPCIE_READREG(base_addr, reg); + cfg &= ~(FPCIE_LM_EP_FUNC_BAR_CFG_BAR_APERTURE_MASK(b) | + FPCIE_LM_EP_FUNC_BAR_CFG_BAR_CTRL_MASK(b)); + cfg |= (FPCIE_LM_EP_FUNC_BAR_CFG_BAR_APERTURE(b, aperture) | + FPCIE_LM_EP_FUNC_BAR_CFG_BAR_CTRL(b, ctrl)); + + FPCIE_WRITEREG(base_addr, reg, cfg); + + return FT_SUCCESS; +} + +int FPcieEpCleanBar(FPcie *instance_p, u32 peu_num, u32 bar_num) +{ + u32 reg, cfg, b, ctrl; + uintptr_t base_addr; + base_addr = *(uintptr_t *)(&instance_p->config.control_c0_address + peu_num); + + if (bar_num < FPCIE_BAR_4) + { + reg = FPCIE_LM_EP_FUNC_BAR_CFG0(0); + b = bar_num; + } + else + { + reg = FPCIE_LM_EP_FUNC_BAR_CFG1(0); + b = bar_num - FPCIE_BAR_4; + } + + ctrl = FPCIE_LM_BAR_CFG_CTRL_DISABLED; + cfg = FPCIE_READREG(base_addr, reg); + cfg &= ~(FPCIE_LM_EP_FUNC_BAR_CFG_BAR_APERTURE_MASK(b) | + FPCIE_LM_EP_FUNC_BAR_CFG_BAR_CTRL_MASK(b)); + cfg |= FPCIE_LM_EP_FUNC_BAR_CFG_BAR_CTRL(b, ctrl); + FPCIE_WRITEREG(base_addr, reg, cfg); + + return FT_SUCCESS; +} + +static int GetOneInData(u64 data) +{ + int n = 63; + while (!(data & GENMASK_ULL(63, 63))) + { + n--; + data <<= 1; + } + + return n; +} + +int FPcieEpMapAddr(FPcie *instance_p, u32 peu_num, u64 phy_addr, u64 pcie_addr, u64 size) +{ + u32 addr0, addr1; + u64 pcie_addr_limit; + u64 reg; + uintptr_t config_address; + uintptr_t control_address; + + FASSERT(instance_p != NULL); + + if (peu_num < FPCIE_PEU1_C0) + { + config_address = instance_p->config.peu0_config_address; + } + else + { + config_address = instance_p->config.peu1_config_address; + } + + control_address = *(uintptr_t *)(&instance_p->config.control_c0_address + peu_num); + pcie_addr_limit = pcie_addr + size; + + if (phy_addr < 0x1000000000) + { + addr0 = ((pcie_addr >> 16) & FPCIE_C0_PREF_BASE_MASK) | (pcie_addr_limit & FPCIE_C0_PREF_LIMIT_MASK); + reg = FPCIE_REG_EP_C0_PREF_BASE_LIMIT_OFFSET_GET(config_address, peu_num); + FPCIE_WRITEREG(reg, 0, addr0); + } + else + { + addr0 = (((pcie_addr & 0xFFFFFFFF) >> 15) & 0xFFF0) | (pcie_addr_limit & 0xFFF00000); + addr1 = ((pcie_addr >> 32) & 0xFF) | ((pcie_addr_limit >> 24) & 0xFF00); + reg = FPCIE_REG_EP_C0_MEM_BASE_LIMIT_OFFSET_GET(config_address, peu_num); + FPCIE_WRITEREG(reg, 0, addr0); + FPCIE_WRITEREG(reg + 4, 0, addr1); + } + + addr0 = (phy_addr & 0xFFFFFF00) | (GetOneInData(size - 1) & 0x3F); + addr1 = (phy_addr >> 32); + FPCIE_WRITEREG(control_address, FPCIE_REG_OUTBOUND_R0_PATR0_OFFSET, addr0); + FPCIE_WRITEREG(control_address, FPCIE_REG_OUTBOUND_R0_PATR1_OFFSET, addr1); + + FPCIE_WRITEREG(control_address, FPCIE_REG_OUTBOUND_R0_PHDR0_OFFSET, 2); + FPCIE_WRITEREG(control_address, FPCIE_REG_OUTBOUND_R0_PHDR1_OFFSET, 0); + FPCIE_WRITEREG(control_address, FPCIE_REG_OUTBOUND_R0_PHDR2_OFFSET, 0); + + addr0 = (pcie_addr & 0xFFFFFF00) | (GetOneInData(size - 1) & 0x3F); + addr1 = (pcie_addr >> 32); + FPCIE_WRITEREG(control_address, FPCIE_REG_OUTBOUND_R0_ARBA0_OFFSET, addr0); + FPCIE_WRITEREG(control_address, FPCIE_REG_OUTBOUND_R0_ARBA1_OFFSET, addr1); + + return FT_SUCCESS; +} diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_g.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_g.c new file mode 100644 index 0000000000..2f05d51696 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_g.c @@ -0,0 +1,74 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_g.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:58:07 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fpcie.h" +#include "fpcie_hw.h" +#include "fparameters.h" +#include "sdkconfig.h" + + +FPcieConfig FPcieConfigTable[FT_PCIE_NUM] = +{ + { + .instance_id = FT_PCIE0_ID, /* Id of device*/ + .irq_num = FT_PCIE0_MISC_IRQ_NUM, // Irq number + .ecam = FT_PCI_CONFIG_BASEADDR, /* The Memory way */ + .peu0_config_address = FT_PCI_EU0_CONFIG_BASEADDR, + .peu1_config_address = FT_PCI_EU1_CONFIG_BASEADDR, + .control_c0_address = FT_PCI_EU0_C0_CONTROL_BASEADDR, + .control_c1_address = FT_PCI_EU0_C1_CONTROL_BASEADDR, + .control_c2_address = FT_PCI_EU0_C2_CONTROL_BASEADDR, + .control_c3_address = FT_PCI_EU1_C0_CONTROL_BASEADDR, + .control_c4_address = FT_PCI_EU1_C1_CONTROL_BASEADDR, + .control_c5_address = FT_PCI_EU1_C2_CONTROL_BASEADDR, +#ifdef FT_PCI_INTX_EOI + .intx_peux_stat_address = + { + [0] = FT_PCI_INTX_PEU0_STAT, + [1] = FT_PCI_INTX_PEU1_STAT, + }, + .intx_control_eux_cx_address = + { + [0] = FT_PCI_INTX_EU0_C0_CONTROL, + [1] = FT_PCI_INTX_EU0_C1_CONTROL, + [2] = FT_PCI_INTX_EU0_C2_CONTROL, + [3] = FT_PCI_INTX_EU1_C0_CONTROL, + [4] = FT_PCI_INTX_EU1_C1_CONTROL, + [5] = FT_PCI_INTX_EU1_C2_CONTROL, + }, +#endif + .io_base_addr = FT_PCI_IO_CONFIG_BASEADDR, + .io_size = FT_PCI_IO_CONFIG_REG_LENGTH, + .npmem_base_addr = FT_PCI_MEM32_BASEADDR, + .npmem_size = FT_PCI_MEM32_REG_LENGTH, + .pmem_base_addr = FT_PCI_MEM64_BASEADDR, /* Prefetchable memory */ + .pmem_size = FT_PCI_MEM64_REG_LENGTH, + .inta_irq_num = FT_PCI_INTA_IRQ_NUM, + .intb_irq_num = FT_PCI_INTB_IRQ_NUM, + .intc_irq_num = FT_PCI_INTC_IRQ_NUM, + .intd_irq_num = FT_PCI_INTD_IRQ_NUM, + .need_skip = FT_PCI_NEED_SKIP + } +}; + diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_hw.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_hw.c new file mode 100644 index 0000000000..3850bab7c5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_hw.c @@ -0,0 +1,312 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_hw.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:58:12 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fpcie_hw.h" +#include "fpcie.h" +#include "fpcie_common.h" +#include "fparameters.h" + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ +/* Access sizes for PCI reads and writes */ +enum FPcieSize +{ + FPCIE_SIZE_8, + FPCIE_SIZE_16, + FPCIE_SIZE_32, +}; + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + + +/** + * @name: FPcieEcamConfigAddress + * @msg: 提供一个可用于ECAM 访问机制的地址 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @param {u32} offset 配置空间中的偏移量 + * @param {void **} addrp 用于存放输出有效访问空间的地址 + * @return FError + */ +static FError FPcieEcamConfigAddress(uintptr addr, s32 bdf, u32 offset, void **addrp) +{ + u32 bus_no = FPCIE_BUS(bdf); + u32 dev_no = FPCIE_DEV(bdf); + u32 vendor = 0; + s32 bdf_parent ; + uintptr ecam_addr = addr; + addr += FPCIE_BUS(bdf) << 20; + addr += FPCIE_DEV(bdf) << 15; + addr += FPCIE_FUNC(bdf) << 12; + + + bdf_parent = FPCIE_BDF(bus_no - 1, 0, 0); + vendor = FPCIE_READREG(addr, FPCIE_CFG_ID_REG) ; + + if ((bus_no > 0) && (dev_no > 0)) + { + if ((FPCIE_READREG_BYTE(addr, FPCIE_HEADER_TYPE_REG) & 0x7f) != FPCIE_HEADER_TYPE_BRIDGE) + { + if (vendor != 0x1d17) + { + return FPCIE_NEED_SKIP; + } + + if (FPcieSkipDevice(ecam_addr, bdf_parent)) + { + return FPCIE_NEED_SKIP; + } + } + } + + addr += offset ; + *addrp = (void *)addr ; + return FT_SUCCESS; +} + + + +/** + * @name: FPcieSkipDevice + * @msg: 跳过部分无效设备 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @return FError + */ +FError FPcieSkipDevice(uintptr ecam_addr, s32 bdf) +{ + u8 pos, id; + u16 capreg; + u8 port_type; + uintptr addr ; + addr = ecam_addr ; + addr += FPCIE_BUS(bdf) << 20; + addr += FPCIE_DEV(bdf) << 15; + addr += FPCIE_FUNC(bdf) << 12; + + pos = 0x34 ; /* Capabilites Pointer */ + while (1) + { + pos = FPCIE_READREG_BYTE(addr, pos) ; + if (pos < 0x40)/* 超过Capability Pointer所代表的空间offset最大范围 */ + break; + pos &= ~3 ; /* offset 第两位对齐 */ + id = FPCIE_READREG_BYTE(addr, pos) ; /* PCI Express Cap ID */ + if (id == 0xff) + { + break ; + } + + if (id == 0x10) /* 找到 PCIe设备的cap structure */ + { + capreg = FPCIE_READREG(addr, pos + 2) ; + port_type = (capreg >> 4) & 0xf ; /* Device/Port type */ + if ((port_type == 0x5) && (FPCIE_DEV(bdf) != 0)) + { + return FPCIE_NEED_SKIP ; + } + else + { + return FT_SUCCESS; + } + + } + pos + 1 ; + } + + return FT_SUCCESS; +} + + + + +static s32 FPcieGetFf(enum FPcieSize size) +{ + switch (size) + { + case FPCIE_SIZE_8: + return 0xff; + case FPCIE_SIZE_16: + return 0xffff; + default: + return 0xffffffff; + } +} + +/** + * @name: FPcieEcamReadConfig8bit + * @msg: 基于ECAM机制读取配置空间中偏移量的值 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @param {u32} offset 配置空间中的偏移量 + * @param {u8} *value_p pointer store date available in the offset + * @return FError + */ + +void FPcieEcamReadConfig8bit(uintptr ecam_addr, s32 bdf, u32 offset, u8 *value_p) +{ + uintptr addr ; + + if (FPcieEcamConfigAddress(ecam_addr, bdf, offset, (void *)&addr) != FT_SUCCESS) + { + *value_p = FPcieGetFf(FPCIE_SIZE_8) ; + return ; + } + + + *value_p = FPCIE_READREG_BYTE(addr, 0); + + return ; +} + +/** + * @name: FPcieEcamReadConfig16bit + * @msg: 基于ECAM机制读取配置空间中偏移量的值 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @param {u32} offset 配置空间中的偏移量 + * @param {u16} *value_p pointer store date available in the offset + * @return FError + */ + +void FPcieEcamReadConfig16bit(uintptr ecam_addr, s32 bdf, u32 offset, u16 *value_p) +{ + uintptr addr ; + + if (FPcieEcamConfigAddress(ecam_addr, bdf, offset, (void *)&addr) != FT_SUCCESS) + { + *value_p = FPcieGetFf(FPCIE_SIZE_16) ; + return ; + } + + + *value_p = FPCIE_READREG_SHORT(addr, 0); + + return ; +} + +/** + * @name: FPcieEcamReadConfig32bit + * @msg: 基于ECAM机制读取配置空间中偏移量的值 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @param {u32} offset 配置空间中的偏移量 + * @param {u32} *value_p pointer store date available in the offset + * @return FError + */ +void FPcieEcamReadConfig32bit(uintptr ecam_addr, s32 bdf, u32 offset, u32 *value_p) +{ + uintptr addr ; + + if (FPcieEcamConfigAddress(ecam_addr, bdf, offset, (void *)&addr) != FT_SUCCESS) + { + *value_p = FPcieGetFf(FPCIE_SIZE_32) ; + return ; + } + + + *value_p = FPCIE_READREG(addr, 0); + + return ; +} + + +/** + * @name: FPcieEcamWriteConfig8bit + * @msg: 基于ECAM机制写入配置空间中偏移量的值 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @param {u32} offset 配置空间中的偏移量 + * @param {u8} value to be written on to the offset +* @return FError + */ + +void FPcieEcamWriteConfig8bit(uintptr ecam_addr, s32 bdf, u32 offset, u8 value) +{ + uintptr addr ; + + if (FPcieEcamConfigAddress(ecam_addr, bdf, offset, (void *)&addr) != FT_SUCCESS) + { + return ; + } + + FPCIE_WRITEREG_BYTE(addr, 0, value) ; + + return ; +} + +/** + * @name: FPcieEcamWriteConfig16bit + * @msg: 基于ECAM机制写入配置空间中偏移量的值 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @param {u32} offset 配置空间中的偏移量 + * @param {u16} value to be written on to the offset +* @return FError + */ + +void FPcieEcamWriteConfig16bit(uintptr ecam_addr, s32 bdf, u32 offset, u16 value) +{ + uintptr addr ; + + if (FPcieEcamConfigAddress(ecam_addr, bdf, offset, (void *)&addr) != FT_SUCCESS) + { + return ; + } + + FPCIE_WRITEREG_SHORT(addr, 0, value) ; + + return ; +} + + +/** + * @name: FPcieEcamWriteConfig32bit + * @msg: 基于ECAM机制写入配置空间中偏移量的值 + * @param {FPcie} *instance_p is a pointer to the FPcie instance. + * @param {s32} bdf {Bus Device function} + * @param {u32} offset 配置空间中的偏移量 + * @param {u32} value to be written on to the offset +* @return FError + */ + +void FPcieEcamWriteConfig32bit(uintptr ecam_addr, s32 bdf, u32 offset, u32 value) +{ + uintptr addr ; + + if (FPcieEcamConfigAddress(ecam_addr, bdf, offset, (void *)&addr) != FT_SUCCESS) + { + return ; + } + + FPCIE_WRITEREG(addr, 0, value) ; + + return ; +} diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_hw.h b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_hw.h new file mode 100644 index 0000000000..b6c1c1906c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_hw.h @@ -0,0 +1,327 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_hw.h + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:58:22 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DRIVERS_FPCIE_HW_H +#define DRIVERS_FPCIE_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fio.h" +#include "ferror_code.h" + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/* config register */ +#define FPCIE_REG_MISC_INT_STATE_OFFSET 0x00000008U /* 杂散中断状态寄存器 */ +#define FPCIE_REG_MISC_INT_ENALBE_OFFSET 0x0000000CU /* 杂散中断是能寄存器 */ +#define FPCIE_REG_MSI_ENABLE_OFFSET 0x000000200U /* MSI 中断使能寄存器 */ +#define FPCIE_REG_MSI_UP32_ADDR_OFFSET 0x000000208U /* 匹配 MSI 的高 32 位地址寄存器 */ +#define FPCIE_REG_MSI_LOW32_ADDR_OFFSET 0x00000020CU /* 匹配 MSI 的低 32 位地址寄存器 */ +#define FPCIE_REG_MSI_SPI_ENABLE_OFFSET 0x000000608U /* MSI 转 SPI 的使能寄存器 */ +#define FPCIE_REG_MSI_SPI_DATA_OFFSET 0x00000060CU /* MSI 转 SPI 后的 ID 和数据信息寄存器 */ +#define FPCIE_REG_EP_C0_PREF_BASE_LIMIT_OFFSET 0x000000A30U /* EP 模式下 PIO 请求译码到 C0 控制器 的可预取空间的 BASE 和 LIMIT 域 */ +#define FPCIE_REG_EP_C0_PREF_BASE_LIMIT_UP32_OFFSET 0x000000A34U /* EP 模式下 PIO 请求译码到 C0 控制器的可预取空间的高 32 位 BASE 和 sLIMIT */ +#define FPCIE_REG_EP_C0_MEM_BASE_LIMIT_OFFSET 0x000000A38U /* EP 模式下 PIO 请求译码到 C1 控制器的存储空间的 BASE 和 LIMIT 域 */ +#define FPCIE_REG_EP_C1_PREF_BASE_LIMIT_OFFSET 0x000000A40U +#define FPCIE_REG_EP_C1_PREF_BASE_LIMIT_UP32_OFFSET 0x000000A44U +#define FPCIE_REG_EP_C1_MEM_BASE_LIMIT_OFFSET 0x000000A48U +#define FPCIE_REG_EP_C2_PREF_BASE_LIMIT_OFFSET 0x000000A50U +#define FPCIE_REG_EP_C2_PREF_BASE_LIMIT_UP32_OFFSET 0x000000A54U +#define FPCIE_REG_EP_C2_MEM_BASE_LIMIT_OFFSET 0x000000A58U + +/* Controler register */ +#define FPCIE_REG_MSI_LOW_ADDRESS_OFFSET 0x94U /* MSI 事务的写地址低 32 位 */ +#define FPCIE_REG_MSI_HIGH_ADDRESS_OFFSET 0x98U /* MSI 事务的写地址高 32 位 */ +#define FPCIE_REG_MSI_DATA_OFFSET 0x9CU /* MSI 事务携带的数据信息 */ +#define FPCIE_REG_OUTBOUND_R0_PATR0_OFFSET 0x8000U /* 控制器输出方向上 region 0 的转换后地址低 32 位 */ +#define FPCIE_REG_OUTBOUND_R0_PATR1_OFFSET 0x8004U /* 控制器输出方向上 region 0 的转换后地址高 32 位 */ +#define FPCIE_REG_OUTBOUND_R0_PHDR0_OFFSET 0x8008U /* 控制器输出方向上 region 0 的转换描述符[31:0]位 */ +#define FPCIE_REG_OUTBOUND_R0_PHDR1_OFFSET 0x800CU /* 控制器输出方向上 region 0 的转换描述符[63:31]位 */ +#define FPCIE_REG_OUTBOUND_R0_PHDR2_OFFSET 0x8010U /* 控制器输出方向上 region 0 的转换描述符[95:64]位 */ +#define FPCIE_REG_OUTBOUND_R0_ARBA0_OFFSET 0x8018U /* 控制器输出方向上 region 0 的转换前的地址低 32 位 */ +#define FPCIE_REG_OUTBOUND_R0_ARBA1_OFFSET 0x801CU /* 控制器输出方向上 region 0 的转换前的地址高 32 位 */ +#define FPCIE_REG_F0_B0_ATR_L_OFFSET 0x8840U /* 控制器 FUNC 0 BAR 0 地址转换寄存器低 32 位 */ +#define FPCIE_REG_F0_B0_ATR_H_OFFSET 0x8844U /* 控制器 FUNC 0 BAR 0 地址转换寄存器高 32 位 */ +#define FPCIE_REG_F0_B2_ATR_L_OFFSET 0x8850U /* 控制器 FUNC 0 BAR 2 地址转换寄存器低 32 位 */ +#define FPCIE_REG_F0_B2_ATR_H_OFFSET 0x8854U /* 控制器 FUNC 0 BAR 2 地址转换寄存器高 32 位 */ +#define FPCIE_REG_DMA_CH0_CTRL_OFFSET 0xC000U /* DMA channel 0 的控制器寄存器 */ +#define FPCIE_REG_DMA_CH0_SP_L_OFFSET 0xC004U /* DMA channel 0 描述符存储的首地址低 32 位寄存器 */ +#define FPCIE_REG_DMA_CH0_SP_H_OFFSET 0xC008U /* DMA channel 0 描述符存储的首地址高 32 位寄存器 */ +#define FPCIE_REG_DMA_CH1_CTRL_OFFSET 0xC014U /* DMA channel 1 的控制器寄存器 */ +#define FPCIE_REG_DMA_CH1_SP_L_OFFSET 0xC018U /* DMA channel 1 描述符存储的首地址低 32 位寄存器 */ +#define FPCIE_REG_DMA_CH1_SP_H_OFFSET 0xC01CU /* DMA channel 1 描述符存储的首地址高 32 位寄存器 */ +#define FPCIE_REG_DMA_INT_STATUS_OFFSET 0xC0A0U /* DMA 中断状态寄存器 */ +#define FPCIE_REG_DMA_INT_ENABLE_OFFSET 0xC0A4U /* DMA 使能寄存器 */ + +/* REG_MISC_INT_STATE */ +#define FPCIE_MISC_STATE_C0_DMA_INT_MASK 0x1U /* c0 dma 中断 */ +#define FPCIE_MISC_STATE_C0_LOCAL_INT_MASK 0x2U /* c0 本地中断 */ +#define FPCIE_MISC_STATE_C0_POWER_STATE_CHANGE_MASK 0x4U /* c0 电源状态变化 */ +#define FPCIE_MISC_STATE_C1_DMA_INT_MASK 0x100U /* c1 dma 中断 */ +#define FPCIE_MISC_STATE_C1_LOCAL_INT_MASK 0x200U /* c1 本地中断 */ +#define FPCIE_MISC_STATE_C1_POWER_STATE_CHANGE_MASK 0x400U /* c1 电源状态变化 */ +#define FPCIE_MISC_STATE_C2_DMA_INT_MASK 0x1000U /* c2 dma 中断 */ +#define FPCIE_MISC_STATE_C2_LOCAL_INT_MASK 0x2000U /* c2 本地中断 */ +#define FPCIE_MISC_STATE_C2_POWER_STATE_CHANGE_MASK 0x4000U /* c2 电源状态变化 */ + +/* REG_MISC_INT_ENALBE */ +#define FPCIE_MISC_ENALBE_C0_MISC_INT_EN_MASK 0x1U /* c0 杂散中断使能 */ +#define FPCIE_MISC_ENALBE_C1_MISC_INT_EN_MASK 0x2U /* c1 杂散中断使能 */ +#define FPCIE_MISC_ENALBE_C2_MISC_INT_EN_MASK 0x4U /* c2 杂散中断使能 */ + +/* REG_MSI_ENABLE */ +#define FPCIE_MSI_EN_MASK 0x1U /* MSI 中断使能 */ + +/* REG_MSI_UP32_ADDR */ +#define FPCIE_MSI64_HI_ADDR_OFFSET 0xFFFFFFFFU /* MSI64 高位地址 */ + +/* REG_MSI_LOW32_ADDR */ +#define FPCIE_MSI64_LO_ADDR_MASK 0xFFFF0000U /* MSI64 低位地址 */ + +/* REG_MSI_SPI_ENABLE */ +#define FPCIE_MSI_DATA_MASK 0xFFFFU /* msi 中断的数据 */ +#define FPCIE_MSI_DEVICE_ID_MASK 0xFFFF0000U /* msi 中断的设备 id */ + +/* REG_EP_C0_PREF_BASE_LIMIT */ +#define FPCIE_C0_PREF_BASE_MASK 0xfff0U /* 可预取存储空间基址低位 */ +#define FPCIE_C0_PREF_LIMIT_MASK 0xfff00000U /* 可预取存储空间上限低位 */ + +/* REG_EP_C0_PREF_BASE_LIMIT_UP32 */ +#define FPCIE_C0_PREF_BASE_UP32_MASK 0xFFU /* 可预取存储空间基址高位 */ +#define FPCIE_C0_PREF_LIMIT_UP32_MASK 0xFF00U /* 可预取存储空间上限高位 */ + +/* REG_EP_C1_PREF_BASE_LIMIT */ +#define FPCIE_C1_PREF_BASE_MASK 0xfff0U /* 可预取存储空间基址低位 */ +#define FPCIE_C1_PREF_LIMIT_MASK 0xfff00000U /* 可预取存储空间上限低位 */ + +/* REG_EP_C1_PREF_BASE_LIMIT_UP32 */ +#define FPCIE_C1_PREF_BASE_UP32_MASK 0xFFU /* 可预取存储空间基址高位 */ +#define FPCIE_C1_PREF_LIMIT_UP32_MASK 0xFF00U /* 可预取存储空间上限高位 */ + +/* Controler register */ +/* REG_MSI_LOW_ADDRESS */ +#define FPCIE_CTRL_MSI_LOW_ADDR_MASK 0xFFFFFFFCU /* MSI 事务的写地址低位 */ + +/* REG_MSI_HIGH_ADDRESS */ +#define FPCIE_CTRL_MSI_HIGH_ADDR_MASK 0xFFFFFFFFU /* MSI 事务的写地址高 32 位 */ + +/* REG_MSI_DATA */ +#define FPCIE_CTRL_MESSAGE_DATA_MASK 0xffffU /* MSI 事务携带的数据信息 */ + +/* REG_OUTBOUND_R0_PATR0 */ +#define FPCIE_CTRL_OUTBOUND_R0_PATR0_R0_NUM_BITS_MASK 0x1fU /* 配置可通过的 AXI 域地址,例如配置为 N,那么N+1 位地址可通过。 */ +#define FPCIE_CTRL_OUTBOUND_R0_PATR0_ADDR_BITS_MASK 0xffffff00U /* 控制器输出方向 region 0 转换后的地址[31:8]位 */ + +/* REG_OUTBOUND_R0_PATR1 */ +#define FPCIE_CTRL_OUTBOUND_R0_PATR1_ADDR_BITS_MASK 0xffffffffU /* 控制器输出方向 region 0 转换后的地址[63:32]位 */ + +/* REG_OUTBOUND_R0_PHDR0 */ +#define FPCIE_CTRL_OUTBOUND_R0_PHDR0_DESCRIPTOR_MASK 0xffffffffU /* 控制器输出方向 region 0 的描述符[31:0]位 */ + +/* REG_OUTBOUND_R0_PHDR1 */ +#define FPCIE_CTRL_OUTBOUND_R0_PHDR1_DESCRIPTOR_MASK 0xffffffffU /* 控制器输出方向 region 0 的描述符[63:32]位 */ + +/* REG_OUTBOUND_R0_PHDR2 */ +#define FPCIE_CTRL_OUTBOUND_R0_PHDR2_DESCRIPTOR_MASK 0x1fffU /* 控制器输出方向 region 0 的描述符[76:64]位 */ + +/* REG_OUTBOUND_R0_ARBA0 */ +#define FPCIE_CTRL_OUTBOUND_R0_ARBA0_LOWER_MASK 0x3f /* 配置AXI域匹配地址时的mask位,例如配置为M,那么 M+1 位地址在匹配时不做比较。 */ +#define FPCIE_CTRL_OUTBOUND_R0_ARBA0_ADDR_MASK 0xFFFFFFF0U /* 控制器输出方向 region 0 转换前的地址[31:8]位 */ + +/* REG_OUTBOUND_R0_ARBA1 */ +#define FPCIE_CTRL_OUTBOUND_R0_ARBA1_ADDR_MASK 0xffffffffU /* 控制器输出方向 region 0 转换前的地址[63:32]位 */ + +/* REG_F0_B0_ATR_L */ +#define FPCIE_CTRL_F0_B0_ATR_L_ADDR_MASK 0xffffffffU /* 控制器 FUNC 0 BAR 0 地址转换寄存器低 32 位 */ + +/* REG_F0_B0_ATR_H */ +#define FPCIE_CTRL_F0_B0_ATR_H_ADDR_MASK 0xffffffffU /* 控制器 FUNC 0 BAR 0 地址转换寄存器高 32 位 */ + +/* REG_F0_B2_ATR_L */ +#define FPCIE_CTRL_F0_B2_ATR_L_ADDR_MASK 0xffffffffU /* 控制器 FUNC 0 BAR 2 地址转换寄存器低 32 位 */ + +/* REG_F0_B2_ATR_H */ +#define FPCIE_CTRL_F0_B2_ATR_H_ADDR_MASK 0xffffffffU /* 控制器 FUNC 0 BAR 2 地址转换寄存器高 32 位 */ + +/* REG_DMA_CH0_CTRL */ +#define FPCIE_CTRL_DMA_CH0_CTRL_GO_MASK 0x1U /* DMA channel 0 点火位,开始传输 */ +#define FPCIE_CTRL_DMA_CH0_CTRL_OBNOTIB_MASK 0x2U /* 配置 DMA channel 0 是读操作还是写操作 */ + +/* REG_DMA_CH0_SP_L */ +#define FPCIE_CTRL_DMA_CH0_SP_L_START_MASK 0xFFFFFFFFU /* 保存 channel 0 描述符的内存地址低 32 位 */ + +/* REG_DMA_CH0_SP_H */ +#define FPCIE_CTRL_DMA_CH0_SP_H_START_MASK 0xFFFFFFFFU /* 保存 channel 0 描述符的内存地址高 32 位 */ + +/* REG_DMA_CH1_CTRL */ +#define FPCIE_CTRL_DMA_CH1_CTRL_GO_MASK 0x1U /* DMA channel 1 点火位,开始传输 */ +#define FPCIE_CTRL_DMA_CH1_CTRL_OBNOTIB_MASK 0x2U /* 配置 DMA channel 1 是读操作还是写操作 */ + +/* REG_DMA_CH1_SP_L */ +#define FPCIE_CTRL_DMA_CH1_SP_L_START_MASK 0xFFFFFFFFU /* 保存 channel 1 描述符的内存地址低 32 位 */ + +/* REG_DMA_CH1_SP_H */ +#define FPCIE_CTRL_DMA_CH1_SP_H_START_MASK 0xFFFFFFFFU /* 保存 channel 1 描述符的内存地址高 32 位 */ + +/* REG_DMA_INT_STATUS */ +#define FPCIE_CTRL_DMA_INT_STATUS_CH0_DONE_MASK 0x1U /* channel 0 传输完成中断 */ +#define FPCIE_CTRL_DMA_INT_STATUS_CH1_DONE_MASK 0x2U /* channel 1 传输完成中断 */ +#define FPCIE_CTRL_DMA_INT_STATUS_CH0_ERR_MASK 0x10U /* channel 0 传输出错中断 */ +#define FPCIE_CTRL_DMA_INT_STATUS_CH1_ERR_MASK 0x20U /* channel 1 传输出错中断 */ +#define FPCIE_CTRL_DMA_INT_STATUS_ALL_MASK (FPCIE_CTRL_DMA_INT_STATUS_CH0_DONE_MASK | FPCIE_CTRL_DMA_INT_STATUS_CH1_DONE_MASK | FPCIE_CTRL_DMA_INT_STATUS_CH0_ERR_MASK | FPCIE_CTRL_DMA_INT_STATUS_CH1_ERR_MASK) + +/* REG_DMA_INT_ENABLE */ +#define FPCIE_CTRL_DMA_INT_ENABLE_CH0_DONE_MASK 0x1U /* 使能 channel 0 传输完成后产生中断 */ +#define FPCIE_CTRL_DMA_INT_ENABLE_CH1_DONE_MASK 0x2U /* 使能 channel 1 传输完成后产生中断 */ +#define FPCIE_CTRL_DMA_INT_ENABLE_CH0_ERR_MASK 0x10U /* 使能 channel 0 传输出错后产生中断 */ +#define FPCIE_CTRL_DMA_INT_ENABLE_CH1_ERR_MASK 0x20U /* 使能 channel 1 传输出错后产生中断 */ +#define FPCIE_CTRL_DMA_INT_ENABLE_ALL_MASK (FPCIE_CTRL_DMA_INT_ENABLE_CH0_DONE_MASK | FPCIE_CTRL_DMA_INT_ENABLE_CH1_DONE_MASK | FPCIE_CTRL_DMA_INT_ENABLE_CH0_ERR_MASK | FPCIE_CTRL_DMA_INT_ENABLE_CH1_ERR_MASK) + +/** @name ECAM Address Register bitmaps and masks + * + * @{ + */ +#define FPCIE_ECAM_MASK 0x0FFFFFFF /**< Mask of all valid bits */ +#define FPCIE_ECAM_BUS_MASK 0x0FF00000 /**< Bus Number Mask */ +#define FPCIE_ECAM_DEV_MASK 0x000F8000 /**< Device Number Mask */ +#define FPCIE_ECAM_FUN_MASK 0x00007000 /**< Function Number Mask */ +#define FPCIE_ECAM_REG_MASK 0x00000FFC /**< Register Number Mask */ +#define FPCIE_ECAM_BYT_MASK 0x00000003 /**< Byte Address Mask */ + +#define FPCIE_ECAM_BUS_SHIFT 20 /**< Bus Number Shift Value */ +#define FPCIE_ECAM_DEV_SHIFT 15 /**< Device Number Shift Value */ +#define FPCIE_ECAM_FUN_SHIFT 12 /**< Function Number Shift Value */ +#define FPCIE_ECAM_REG_SHIFT 2 /**< Register Number Shift Value */ +#define FPCIE_ECAM_BYT_SHIFT 0 /**< Byte Offset Shift Value */ +/*@}*/ + + +#define FPCIE_BUS(d) (((d) >> 16) & 0xff) +/* + * Please note the difference in DEVFN usage in U-Boot vs Linux. U-Boot + * uses DEVFN in bits 15-8 but Linux instead expects DEVFN in bits 7-0. + * Please see the Linux header include/uapi/linux/pci.h for more details. + * This is relevant for the following macros: + * FPCIE_DEV, FPCIE_FUNC, FPCIE_DEVFN + * The U-Boot macro FPCIE_DEV is equivalent to the Linux FPCIE_SLOT version with + * the remark from above (input d in bits 15-8 instead of 7-0. + */ +#define FPCIE_DEV(d) (((d) >> 11) & 0x1f) +#define FPCIE_FUNC(d) (((d) >> 8) & 0x7) +#define FPCIE_DEVFN(d, f) ((d) << 11 | (f) << 8) + +#define FPCIE_MASK_BUS(bdf) ((bdf) & 0xffff) +#define FPCIE_ADD_BUS(bus, devfn) (((bus) << 16) | (devfn)) +#define FPCIE_BDF(b, d, f) ((b) << 16 | FPCIE_DEVFN(d, f)) +#define FPCIE_VENDEV(v, d) (((v) << 16) | (d)) +#define FPCIE_ANY_ID (~0) + +/** +* +* This macro reads the given register. +* +* @param base_addr is the base address of the device. +* @param reg_offset is the register offset to be read. +* +* @return The 32-bit value of the register +* +* @note None. +* +*****************************************************************************/ +#define FPCIE_READREG(base_addr, reg_offset) \ + FtIn32((base_addr) + (u32)(reg_offset)) + +/****************************************************************************/ +/** +* +* This macro writes the given register. +* +* @param base_addr is the base address of the device. +* @param reg_offset is the register offset to be written. +* @param data is the 32-bit value to write to the register. +* +* @return None. +* +* @note None. +* +*****************************************************************************/ +#define FPCIE_WRITEREG(base_addr, reg_offset, data) \ + FtOut32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FPCIE_READREG_BYTE(base_addr, reg_offset) \ + FtIn8((base_addr) + (u32)(reg_offset)) + +#define FPCIE_WRITEREG_BYTE(base_addr, reg_offset, data) \ + FtOut8((base_addr) + (u32)(reg_offset), (u8)(data)) + + +#define FPCIE_READREG_SHORT(base_addr, reg_offset) \ + FtIn16((base_addr) + (u32)(reg_offset)) + +#define FPCIE_WRITEREG_SHORT(base_addr, reg_offset, data) \ + FtOut16((base_addr) + (u32)(reg_offset), (u16)(data)) + + +#define FPCIE_SETBIT(base_addr, reg_offset, data) \ + FtSetBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FPCIE_CLEARBIT(base_addr, reg_offset, data) \ + FtClearBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + + +/************************** Function Prototypes ******************************/ + + +void FPcieEcamReadConfig8bit(uintptr ecam_addr, s32 bdf, u32 offset, u8 *value_p); + +void FPcieEcamReadConfig16bit(uintptr ecam_addr, s32 bdf, u32 offset, u16 *value_p); + +void FPcieEcamReadConfig32bit(uintptr ecam_addr, s32 bdf, u32 offset, u32 *value_p); + + +void FPcieEcamWriteConfig8bit(uintptr ecam_addr, s32 bdf, u32 offset, u8 value); + +void FPcieEcamWriteConfig16bit(uintptr ecam_addr, s32 bdf, u32 offset, u16 value); + +void FPcieEcamWriteConfig32bit(uintptr ecam_addr, s32 bdf, u32 offset, u32 value); + +FError FPcieSkipDevice(uintptr ecam_addr, s32 bdf) ; + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_misc.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_misc.c new file mode 100644 index 0000000000..77340b588a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_misc.c @@ -0,0 +1,162 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_misc.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:59:17 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fpcie.h" +#include "fpcie_hw.h" +#include "fassert.h" +#include "fdebug.h" + + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FPCIE_INTR_DEBUG_TAG "FPCIE_INTR" +#define FPCIE_INTR_ERROR(format, ...) FT_DEBUG_PRINT_E(FPCIE_INTR_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_INTR_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FPCIE_INTR_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_INTR_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FPCIE_INTR_DEBUG_TAG, format, ##__VA_ARGS__) +/************************** Function Prototypes ******************************/ + + + +FError FPcieMiscSetHandler(FPcie *instance_p, u32 handler_type, + void *func_pointer, void *call_back_ref) +{ + FError status; + FASSERT(instance_p != NULL); + FASSERT(func_pointer != NULL); + FASSERT(instance_p->is_ready == (u32)FT_COMPONENT_IS_READY); + + switch (handler_type) + { + case FPCIE_HANDLER_DMASEND: + status = FT_SUCCESS; + instance_p->fpcie_dma_tx_cb = ((FPcieIrqCallBack)(void *)func_pointer); + instance_p->dma_tx_args = call_back_ref; + break; + case FPCIE_HANDLER_DMARECV: + status = FT_SUCCESS; + instance_p->fpcie_dma_rx_cb = ((FPcieIrqCallBack)(void *)func_pointer); + instance_p->dma_rx_args = call_back_ref; + break; + case FPCIE_HANDLER_DMASEND_ERROR: + status = FT_SUCCESS; + instance_p->fpcie_dma_tx_error_cb = ((FPcieIrqCallBack)(void *)func_pointer); + instance_p->dma_tx_error_args = call_back_ref; + break; + case FPCIE_HANDLER_DMARECV_ERROR: + status = FT_SUCCESS; + instance_p->fpcie_dma_rx_error_cb = ((FPcieIrqCallBack)(void *)func_pointer); + instance_p->dma_rx_error_args = call_back_ref; + break; + default: + status = FPCIE_ERR_INVALID_PARAM; + break; + } + return status; +} + +void FPcieMiscIrq(s32 vector, void *args) +{ + FPcie *instance_p = (FPcie *)args; + uintptr_t control_address; + u32 reg_value; + (void)vector; + FASSERT(instance_p != NULL); + + if (FPCIE_READREG(instance_p->config.peu0_config_address, FPCIE_REG_MISC_INT_STATE_OFFSET) & FPCIE_MISC_STATE_C0_DMA_INT_MASK) + { + FPCIE_INTR_DEBUG_I("PEU0 C0 DMA IRQ!"); + control_address = instance_p->config.control_c0_address; + } + else if (FPCIE_READREG(instance_p->config.peu0_config_address, FPCIE_REG_MISC_INT_STATE_OFFSET) & FPCIE_MISC_STATE_C1_DMA_INT_MASK) + { + FPCIE_INTR_DEBUG_I("PEU0 C1 DMA IRQ!"); + control_address = instance_p->config.control_c1_address; + } + else if (FPCIE_READREG(instance_p->config.peu0_config_address, FPCIE_REG_MISC_INT_STATE_OFFSET) & FPCIE_MISC_STATE_C2_DMA_INT_MASK) + { + FPCIE_INTR_DEBUG_I("PEU0 C2 DMA IRQ!"); + control_address = instance_p->config.control_c2_address; + } + else if (FPCIE_READREG(instance_p->config.peu1_config_address, FPCIE_REG_MISC_INT_STATE_OFFSET) & FPCIE_MISC_STATE_C0_DMA_INT_MASK) + { + FPCIE_INTR_DEBUG_I("PEU0 C0 DMA IRQ!"); + control_address = instance_p->config.control_c3_address; + } + else if (FPCIE_READREG(instance_p->config.peu1_config_address, FPCIE_REG_MISC_INT_STATE_OFFSET) & FPCIE_MISC_STATE_C1_DMA_INT_MASK) + { + FPCIE_INTR_DEBUG_I("PEU0 C1 DMA IRQ!"); + control_address = instance_p->config.control_c4_address; + } + else if (FPCIE_READREG(instance_p->config.peu1_config_address, FPCIE_REG_MISC_INT_STATE_OFFSET) & FPCIE_MISC_STATE_C2_DMA_INT_MASK) + { + FPCIE_INTR_DEBUG_I("PEU0 C2 DMA IRQ!"); + control_address = instance_p->config.control_c5_address; + } + + FPCIE_INTR_DEBUG_I("pcie misc irq!"); + FPCIE_INTR_DEBUG_I("pcie dma irq status : 0x%08lx", FPCIE_READREG(control_address, FPCIE_REG_DMA_INT_STATUS_OFFSET)); + + reg_value = FPCIE_READREG(control_address, FPCIE_REG_DMA_INT_STATUS_OFFSET); + + if (reg_value & FPCIE_CTRL_DMA_INT_STATUS_CH0_DONE_MASK) + { + if (instance_p->fpcie_dma_rx_cb) + { + instance_p->fpcie_dma_rx_cb(instance_p->dma_rx_args); + } + } + + if (reg_value & FPCIE_CTRL_DMA_INT_STATUS_CH1_DONE_MASK) + { + if (instance_p->fpcie_dma_tx_cb) + { + instance_p->fpcie_dma_tx_cb(instance_p->dma_tx_args); + } + } + + if (reg_value & FPCIE_CTRL_DMA_INT_STATUS_CH0_ERR_MASK) + { + if (instance_p->fpcie_dma_rx_error_cb) + { + instance_p->fpcie_dma_rx_error_cb(instance_p->dma_rx_error_args); + } + } + + if (reg_value & FPCIE_CTRL_DMA_INT_STATUS_CH1_ERR_MASK) + { + if (instance_p->fpcie_dma_tx_error_cb) + { + instance_p->fpcie_dma_tx_error_cb(instance_p->dma_tx_error_args); + } + } + + FPCIE_WRITEREG(control_address, FPCIE_REG_DMA_INT_STATUS_OFFSET, FPCIE_CTRL_DMA_INT_STATUS_ALL_MASK); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_sinit.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_sinit.c new file mode 100644 index 0000000000..f972582888 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcie_sinit.c @@ -0,0 +1,46 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcie_sinit.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:59:22 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#include "fpcie.h" +#include "fparameters.h" + +extern FPcieConfig FPcieConfigTable[FT_PCIE_NUM]; + + +FPcieConfig *FPcieLookupConfig(u32 instance_id) +{ + FPcieConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FT_PCIE_NUM; index++) + { + if (FPcieConfigTable[index].instance_id == instance_id) + { + ptr = &FPcieConfigTable[index]; + break; + } + } + + return (FPcieConfig *)ptr; +} diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcir_intx.c b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcir_intx.c new file mode 100644 index 0000000000..bcf0992e11 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcir_intx.c @@ -0,0 +1,224 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcir_intx.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:59:42 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + + +/***************************** Include Files *********************************/ +#include "fpcie.h" +#include "fpcie_common.h" +#include "fpcie_hw.h" +#include "fparameters.h" +#include "fdebug.h" + + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FPCIE_INTX_DEBUG_TAG "FPCIE_INTX" +#define FPCIE_INTX_ERROR(format, ...) FT_DEBUG_PRINT_E(FPCIE_INTX_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_INTX_DEBUG_I(format, ...) FT_DEBUG_PRINT_I(FPCIE_INTX_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_INTX_DEBUG_W(format, ...) FT_DEBUG_PRINT_W(FPCIE_INTX_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPCIE_INTX_DEBUG_E(format, ...) FT_DEBUG_PRINT_E(FPCIE_INTX_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Constant Definitions *****************************/ +#define INTA 0 +#define INTB 1 +#define INTC 2 +#define INTD 3 + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + + +/** + * @name: FPcieIntxRegiterIrqHandler + * @msg: Use bus, device, and function to register interrupt response functions with INTX + * @param {FPcie *} instance_p is a pointer to the FPcie instance. + * @param {u32} bus is the number of the bus on which you want to register the funtion + * @param {u32} device is the number of the device on which you want to register the funtion + * @param {u32} function is the number of the function on which you want to register the funtion + * @param {FPcieIntxFun *} intx_fun_p is the pointer the user uses to register the callback function + * @return {FError} + */ +FError FPcieIntxRegiterIrqHandler(FPcie *instance_p, + u32 bdf, + FPcieIntxFun *intx_fun_p) +{ + int i; + u8 interrupt_pin, interrupt_line; + u8 header_type; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + /* 通过ecm 直接访问 控制寄存器 */ + FPcieEcamReadConfig8bit(instance_p->config.ecam, bdf, FPCIE_HEADER_TYPE_REG, &header_type) ; + + if (header_type == 0) + { + for (i = 0; i < instance_p->scaned_bdf_count; i++) + { + if (instance_p->scaned_bdf_array[i] == (s32)bdf) + { + break; //获取到i的值,直接跳出循环 + } + } + + /* 读出 Interrupt Pin*/ + FPcieEcamReadConfig8bit(instance_p->config.ecam, bdf, FPCIE_INTERRUPT_PIN_REG, &interrupt_pin) ; + switch (interrupt_pin) + { + case 0x1: /* INTA# */ + interrupt_line = instance_p->config.inta_irq_num ; + instance_p->inta_fun[i] = *intx_fun_p; //中断函数,写入的是pcie instance的成员,一个pcie rc只有一个中断处理函数? + instance_p->inta_fun[i].bdf = bdf; //一个中断函数对应一个bdf号 + break ; + case 0x2: /* INTB# */ + interrupt_line = instance_p->config.intb_irq_num ; + instance_p->intb_fun[i] = *intx_fun_p; + instance_p->intb_fun[i].bdf = bdf; + break ; + case 0x3: /* INTC# */ + interrupt_line = instance_p->config.intc_irq_num ; + instance_p->intc_fun[i] = *intx_fun_p; + instance_p->intc_fun[i].bdf = bdf; + break ; + case 0x4: /* INTD# */ + interrupt_line = instance_p->config.intd_irq_num ; + instance_p->intd_fun[i] = *intx_fun_p; + instance_p->intd_fun[i].bdf = bdf; + break ; + default: + FPCIE_INTX_DEBUG_E("Error interrupt pin") ; + return FPCIE_NOT_FOUND; + } + + FPcieEcamWriteConfig8bit(instance_p->config.ecam, bdf, FPCIE_INTERRUPT_LINE_REG, interrupt_line) ; + } + else + { + FPCIE_INTX_DEBUG_E("Pcie intx not match header type") ; + return FPCIE_NOT_FOUND; + } + + return FT_SUCCESS; +} + + +static void FPcieIntxCallback(FPcie *instance_p, u8 INTx_NUM) +{ + int i; + u16 status ; + /* 读取对应bdf 的status */ + for (i = 0; i < instance_p->scaned_bdf_count; i++) //轮询所有扫描到的pcie节点的interrupt status + { + FPcieEcamReadConfig16bit(instance_p->config.ecam, instance_p->scaned_bdf_array[i], FPCIE_STATUS_REG, &status) ; + if (status & 0x8) /* check intrrupt status */ + { + switch (INTx_NUM) + { + case INTA: + instance_p->inta_fun[i].IntxCallBack(instance_p->inta_fun[i].args); + break; + case INTB: + instance_p->intb_fun[i].IntxCallBack(instance_p->intb_fun[i].args); + break; + case INTC: + instance_p->intc_fun[i].IntxCallBack(instance_p->intc_fun[i].args); + break; + case INTD: + instance_p->intd_fun[i].IntxCallBack(instance_p->intd_fun[i].args); + break; + default: + printf("%s: error intx num\n", __func__); + break; + + } + } + } +} + + + +static void FPcieIntxIrqEoi(FPcie *instance_p, u32 intx_idx) +{ +#ifdef FT_PCI_INTX_EOI + u32 status = 0 ; + u32 istatus = 0, imask = 0 ; + int i ; + status = FPCIE_READREG(instance_p->config.intx_peux_stat_address[0], 0) + (FPCIE_READREG(instance_p->config.intx_peux_stat_address[1], 0) << 12); + + imask = 1 << (3 - intx_idx); + istatus = (1 << intx_idx) << 24; + for (i = 0; i < FT_PCI_INTX_CONTROL_NUM; i++, status >>= 4) + { + if (imask & status) + { + FPCIE_WRITEREG(instance_p->config.intx_control_eux_cx_address[i], 0, istatus) ; + } + } +#else + (void) instance_p; + (void) intx_idx ; +#endif + return ; + +} + +/** + * @name: FPcieIntxIrqHandler + * @msg: Intx interrupt service function of pcie + * @param {s32} vector is interrupt vector number + * @param {void} *args is Pass in a pointer to be processed + */ +void FPcieIntxIrqHandler(s32 vector, void *args) //中断响应函数 +{ + FPcie *instance_p = (FPcie *)args; + FASSERT(instance_p != NULL); + u32 *reg_data = 0; + + switch (vector) + { + case FT_PCI_INTA_IRQ_NUM: //如果响应的是INTA中断,则调用pcie_obj中INTA的中断处理函数 + FPcieIntxCallback(instance_p, INTA) ; + FPcieIntxIrqEoi(instance_p, 0) ; + break; + case FT_PCI_INTB_IRQ_NUM: + FPcieIntxCallback(instance_p, INTA) ; + FPcieIntxIrqEoi(instance_p, 1) ; + break; + case FT_PCI_INTC_IRQ_NUM: + FPcieIntxCallback(instance_p, INTA) ; + FPcieIntxIrqEoi(instance_p, 2) ; + break; + case FT_PCI_INTD_IRQ_NUM: + FPcieIntxCallback(instance_p, INTA) ; + FPcieIntxIrqEoi(instance_p, 3) ; + break; + default: + break; + } +} + + diff --git a/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcir_intx.h b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcir_intx.h new file mode 100644 index 0000000000..d2dcbc397c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pcie/fpcie/fpcir_intx.h @@ -0,0 +1,47 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpcir_intx.h + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 08:59:47 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +#ifndef DIRVERS_PCIE_FPCIE_FPCIE_INTX_H +#define DIRVERS_PCIE_FPCIE_FPCIE_INTX_H + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + +#ifdef __cplusplus +extern "C" +{ +#endif + + +#ifdef __cplusplus +} +#endif + + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/Kconfig b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/Kconfig new file mode 100644 index 0000000000..02c30d70d6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/Kconfig @@ -0,0 +1,7 @@ + +config ENABLE_FGPIO + bool + prompt "Use FGPIO" + default n + + diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio.c b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio.c new file mode 100644 index 0000000000..37b5eab09c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio.c @@ -0,0 +1,460 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgpio.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for GPIO user API implmentation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022-3-1 init commit + */ + + +/***************************** Include Files *********************************/ +#include "fdebug.h" +#include "fparameters.h" + +#include "fgpio_hw.h" +#include "fgpio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGPIO_DEBUG_TAG "FGPIO" +#define FGPIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_WARN(format, ...) FT_DEBUG_PRINT_W(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_INFO(format, ...) FT_DEBUG_PRINT_I(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +/** + * @name: FGpioCfgInitialize + * @msg: 初始化GPIO控制器实例 + * @return {FError} FGPIO_SUCCESS 表示初始化成功 + * @param {FGpio} *instance, GPIO控制器实例 + * @param {FGpioConfig} *config, GPIO控制器配置 + */ +FError FGpioCfgInitialize(FGpio *const instance, const FGpioConfig *const config) +{ + FASSERT(instance && config); + + if (0 == config->base_addr) + { + FGPIO_ERROR("invalid base address !!!"); + return FGPIO_ERR_INVALID_PARA; + } + + if (config != &instance->config) + { + instance->config = *config; + } + + instance->is_ready = FT_COMPONENT_IS_READY; + return FGPIO_SUCCESS; +} + +/** + * @name: FGpioDeInitialize + * @msg: 去初始化GPIO控制器实例 + * @return {*} + * @param {FGpio} *instance, GPIO控制器实例 + */ +void FGpioDeInitialize(FGpio *const instance) +{ + FASSERT(instance); + u32 port_id; + u32 pin_id; + FGpioPin *pin = NULL; + + for (port_id = FGPIO_PORT_A; port_id < FGPIO_PORT_NUM; port_id++) + { + for (pin_id = FGPIO_PIN_0; pin_id < FGPIO_PIN_NUM; pin_id++) + { + pin = instance->pins[port_id][pin_id]; + if (NULL != pin) + { + FGpioPinDeInitialize(pin); + } + } + } + + instance->is_ready = 0; + return; +} + +/** + * @name: FGpioPinInitialize + * @msg: 初始化GPIO引脚实例 + * @return {FError} FGPIO_SUCCESS 表示初始化成功 + * @param {FGpio} *instance, GPIO控制器实例 + * @param {FGpioPin} *pin_instance, GPIO引脚实例 + * @param {FGpioPinId} index, GPIO引脚索引 + */ +FError FGpioPinInitialize(FGpio *const instance, FGpioPin *const pin_instance, + const FGpioPinId index) +{ + FASSERT(instance && pin_instance); + FASSERT_MSG(index.port < FGPIO_PORT_NUM, "invalid gpio port %d", index); + FASSERT_MSG(index.pin < FGPIO_PIN_NUM, "invalid gpio pin %d", index); + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FGPIO_ERROR("gpio instance not yet init !!!"); + return FGPIO_ERR_NOT_INIT; + } + + if (FT_COMPONENT_IS_READY == pin_instance->is_ready) + { + FGPIO_ERROR("gpio pin already inited !!!"); + return FGPIO_ERR_ALREADY_INIT; + } + + pin_instance->index = index; + instance->pins[index.port][index.pin] = pin_instance; + pin_instance->instance = instance; + pin_instance->irq_cb = NULL; + pin_instance->irq_cb_params = NULL; + pin_instance->irq_one_time = FALSE; + pin_instance->is_ready = FT_COMPONENT_IS_READY; + + return FGPIO_SUCCESS; +} + +/** + * @name: FGpioPinDeInitialize + * @msg: 去初始化GPIO引脚实例 + * @return {NONE} + * @param {FGpioPin} *pin, GPIO引脚实例 + */ +void FGpioPinDeInitialize(FGpioPin *const pin) +{ + FASSERT(pin); + FGpio *const instance = pin->instance; + + if ((NULL == instance) || (FT_COMPONENT_IS_READY != instance->is_ready) || + (FT_COMPONENT_IS_READY != pin->is_ready)) + { + FGPIO_ERROR("gpio instance not yet init !!!"); + return; + } + + if (FGPIO_DIR_INPUT == FGpioGetDirection(pin)) + FGpioSetInterruptMask(pin, FALSE); /* 关闭引脚中断 */ + + FGpioPinId index = pin->index; + FASSERT_MSG(instance->pins[index.port][index.pin] == pin, "invalid pin instance"); + instance->pins[index.port][index.pin] = NULL; + pin->instance = NULL; + pin->is_ready = 0U; + + return; +} + +/** + * @name: FGpioGetPinIrqSourceType + * @msg: 获取引脚中断的上报方式 + * @return {FGpioIrqSourceType} 引脚中断的上报方式 + * @param {FGpioPin} *pin, GPIO引脚实例 + */ +FGpioIrqSourceType FGpioGetPinIrqSourceType(FGpioPinId pin_id) +{ +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + if (FGPIO_PORT_B == pin_id.port) + { + return FGPIO_IRQ_NOT_SUPPORT; + } +#endif + + if (FGPIO_PORT_A == pin_id.port) + { +#if defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ + if (pin_id.ctrl <= FGPIO_WITH_PIN_IRQ) /* 0 ~ 2 中断单独上报 */ + { + return FGPIO_IRQ_BY_PIN; + } +#endif + + return FGPIO_IRQ_BY_CONTROLLER; + } + + return FGPIO_IRQ_NOT_SUPPORT; +} + +/** + * @name: FGpioReadRegDir + * @msg: 从寄存器读取GPIO组的输入输出方向 + * @return {u32} GPIO组的输入输出方向, bit[8:0]有效 + * @param {uintptr} base_addr, GPIO控制器基地址 + * @param {FGpioPortIndex} port, GPIO组, A/B + */ +static u32 FGpioReadRegDir(uintptr base_addr, const FGpioPortIndex port) +{ + u32 reg_val = 0; + + if (FGPIO_PORT_A == port) + { + reg_val = FGpioReadReg32(base_addr, FGPIO_SWPORTA_DDR_OFFSET); + } +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + else if (FGPIO_PORT_B == port) + { + reg_val = FGpioReadReg32(base_addr, FGPIO_SWPORTB_DDR_OFFSET); + } +#endif + else + { + FASSERT(0); + } + + return reg_val; +} + +/** + * @name: FGpioWriteRegDir + * @msg: 向寄存器写入GPIO组的输入输出方向 + * @return {*} + * @param {uintptr} base_addr, GPIO控制器基地址 + * @param {FGpioPortIndex} port, GPIO组, A/B + * @param {u32} reg_val, GPIO组的输入输出方向, bit[8:0]有效 + */ +static void FGpioWriteRegDir(uintptr base_addr, const FGpioPortIndex port, const u32 reg_val) +{ + if (FGPIO_PORT_A == port) + { + FGpioWriteReg32(base_addr, FGPIO_SWPORTA_DDR_OFFSET, reg_val); + } +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + else if (FGPIO_PORT_B == port) + { + FGpioWriteReg32(base_addr, FGPIO_SWPORTB_DDR_OFFSET, reg_val); + } +#endif + else + { + FASSERT(0); + } + + return; +} + +/** + * @name: FGpioSetDirection + * @msg: 设置GPIO引脚的输入输出方向 + * @return {*} + * @param {FGpioPin} *instance, GPIO控制器实例 + * @param {FGpioDirection} dir, 待设置的GPIO的方向 + * @note 初始化 GPIO 实例后使用此函数 + */ +void FGpioSetDirection(FGpioPin *const pin, FGpioDirection dir) +{ + FASSERT(pin); + FGpio *const instance = pin->instance; + FASSERT(instance); + FASSERT_MSG(instance->is_ready == FT_COMPONENT_IS_READY, "gpio instance not yet init !!!"); + u32 reg_val; + FGpioPinId index = pin->index; + uintptr base_addr = instance->config.base_addr; + + reg_val = FGpioReadRegDir(base_addr, index.port); + + if (FGPIO_DIR_INPUT == dir) + { + reg_val &= ~BIT(index.pin); /* 0-Input */ + } + else if (FGPIO_DIR_OUTPUT == dir) + { + reg_val |= BIT(index.pin); /* 1-Output */ + } + else + { + FASSERT(0); + } + + FGpioWriteRegDir(base_addr, index.port, reg_val); + return; +} + +/** + * @name: FGpioGetDirection + * @msg: 获取GPIO引脚的输入输出方向 + * @return {FGpioDirection} GPIO引脚方向 + * @param {FGpioPin} *pin, GPIO引脚实例 + * @note 初始化 GPIO 实例后使用此函数 + */ +FGpioDirection FGpioGetDirection(FGpioPin *const pin) +{ + FASSERT(pin); + FGpio *const instance = pin->instance; + FASSERT(instance); + FASSERT(instance->is_ready == FT_COMPONENT_IS_READY); + + FGpioPinId index = pin->index; + uintptr base_addr = instance->config.base_addr; + u32 reg_val = FGpioReadRegDir(base_addr, index.port); + + return (BIT(index.pin) & reg_val) ? FGPIO_DIR_OUTPUT : FGPIO_DIR_INPUT; +} + +/** + * @name: FGpioReadRegVal + * @msg: 获取GPIO组的输出寄存器值 + * @return {u32} 输出寄存器值 bit[8:0]有效 + * @param {uintptr} base_addr, GPIO控制器基地址 + * @param {FGpioPortIndex} port, GPIO组 + */ +static u32 FGpioReadRegVal(uintptr base_addr, const FGpioPortIndex port) +{ + u32 reg_val = 0; + + if (FGPIO_PORT_A == port) + { + reg_val = FGpioReadReg32(base_addr, FGPIO_SWPORTA_DR_OFFSET); + } +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + else if (FGPIO_PORT_B == port) + { + reg_val = FGpioReadReg32(base_addr, FGPIO_SWPORTB_DR_OFFSET); + } +#endif + else + { + FASSERT(0); + } + + return reg_val; +} + +/** + * @name: FGpioWriteRegVal + * @msg: 设置GPIO组的输出寄存器值 + * @return {*} + * @param {uintptr} base_addr, GPIO控制器基地址 + * @param {FGpioPortIndex} port, GPIO组 + * @param {u32} reg_val, 输出寄存器值 bit[8:0]有效 + */ +void FGpioWriteRegVal(uintptr base_addr, const FGpioPortIndex port, const u32 reg_val) +{ + if (FGPIO_PORT_A == port) + { + FGpioWriteReg32(base_addr, FGPIO_SWPORTA_DR_OFFSET, reg_val); + } +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + else if (FGPIO_PORT_B == port) + { + FGpioWriteReg32(base_addr, FGPIO_SWPORTB_DR_OFFSET, reg_val); + } +#endif + else + { + FASSERT(0); + } + + return; +} + +/** + * @name: FGpioSetOutputValue + * @msg: 设置GPIO引脚的输出值 + * @return {FError} FGPIO_SUCCESS 表示设置成功 + * @param {FGpioPin} *pin, GPIO引脚实例 + * @param {FGpioPinVal} output, GPIO引脚的输出值 + * @note 初始化 GPIO 实例后使用此函数,先设置 GPIO 引脚为输出后调用此函数 + */ +FError FGpioSetOutputValue(FGpioPin *const pin, const FGpioPinVal output) +{ + FASSERT(pin); + FGpio *const instance = pin->instance; + FASSERT(instance); + FASSERT_MSG(instance->is_ready == FT_COMPONENT_IS_READY, "gpio instance not yet init !!!"); + + FGpioPinId index = pin->index; + u32 base_addr = instance->config.base_addr; + u32 reg_val; + + if (FGPIO_DIR_OUTPUT != FGpioGetDirection(pin)) + { + FGPIO_ERROR("need to set GPIO direction as OUTPUT first !!!"); + return FGPIO_ERR_INVALID_STATE; + } + + FGPIO_INFO("pin-%d at port %d", index.pin, index.port); + reg_val = FGpioReadRegVal(base_addr, index.port); + if (FGPIO_PIN_LOW == output) + { + reg_val &= ~BIT(index.pin); + } + else if (FGPIO_PIN_HIGH == output) + { + reg_val |= BIT(index.pin); + } + else + { + FASSERT(0); + } + + FGPIO_INFO("output val 0x%x", reg_val); + FGpioWriteRegVal(base_addr, index.port, reg_val); + FGPIO_INFO("output val 0x%x", FGpioReadRegVal(base_addr, index.port)); + return FGPIO_SUCCESS; +} + +/** + * @name: FGpioGetInputValue + * @msg: 获取GPIO引脚的输入值 + * @return {FGpioPinVal} 获取的输入值,高电平/低电平 + * @param {FGpioPin} *instance, GPIO引脚实例 + * @note 初始化 GPIO 实例后使用此函数,先设置 GPIO 引脚为输入后调用此函数 + */ +FGpioPinVal FGpioGetInputValue(FGpioPin *const pin) +{ + FASSERT(pin); + FGpio *const instance = pin->instance; + FASSERT(instance); + FASSERT(instance->is_ready == FT_COMPONENT_IS_READY); + FGpioPinId index = pin->index; + uintptr base_addr = instance->config.base_addr; + u32 reg_val; + + if (FGPIO_DIR_INPUT != FGpioGetDirection(pin)) + { + FGPIO_ERROR("need to set GPIO direction as INPUT first !!!"); + return FGPIO_PIN_LOW; + } + + if (FGPIO_PORT_A == index.port) + { + reg_val = FGpioReadReg32(base_addr, FGPIO_EXT_PORTA_OFFSET); + } +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + else if (FGPIO_PORT_B == index.port) + { + reg_val = FGpioReadReg32(base_addr, FGPIO_EXT_PORTB_OFFSET); + } +#endif + else + { + FASSERT(0); + } + + FGPIO_INFO("input val: 0x%x", reg_val); + return (BIT(index.pin) & reg_val) ? FGPIO_PIN_HIGH : FGPIO_PIN_LOW; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio.h b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio.h new file mode 100644 index 0000000000..f41f80aaf2 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio.h @@ -0,0 +1,239 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgpio.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:35 + * Description:  This files is for GPIO user API definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022-3-1 init commit + */ + + +#ifndef DRIVERS_FGPIO_H +#define DRIVERS_FGPIO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "ftypes.h" +#include "fassert.h" +#include "ferror_code.h" +#include "sdkconfig.h" + +/************************** Constant Definitions *****************************/ +#define FGPIO_SUCCESS FT_SUCCESS +#define FGPIO_ERR_INVALID_PARA FT_MAKE_ERRCODE(ErrModBsp, ErrBspGpio, 0x0) +#define FGPIO_ERR_INVALID_STATE FT_MAKE_ERRCODE(ErrModBsp, ErrBspGpio, 0x1) +#define FGPIO_ERR_NOT_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrBspGpio, 0x2) +#define FGPIO_ERR_ALREADY_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrBspGpio, 0x3) + +#if defined(CONFIG_TARGET_F2000_4) || defined(CONFIG_TARGET_D2000) +#define FGPIO_VERSION_1 /* 用于FT2000/4和D2000平台的GPIO 0 ~ 1 */ +#elif defined(CONFIG_TARGET_E2000) +#define FGPIO_VERSION_2 /* 用于E2000平台的GPIO 3 ~ 5 */ +#else +#error "Invalid target board !!!" +#endif + +typedef enum +{ + FGPIO_PORT_A = 0, +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + FGPIO_PORT_B, +#endif + + FGPIO_PORT_NUM +} FGpioPortIndex; /* GPIO引脚所在的组 */ + +typedef enum +{ + FGPIO_PIN_0 = 0, + FGPIO_PIN_1, + FGPIO_PIN_2, + FGPIO_PIN_3, + FGPIO_PIN_4, + FGPIO_PIN_5, + FGPIO_PIN_6, + FGPIO_PIN_7, +#if defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ + FGPIO_PIN_8, + FGPIO_PIN_9, + FGPIO_PIN_10, + FGPIO_PIN_11, + FGPIO_PIN_12, + FGPIO_PIN_13, + FGPIO_PIN_14, + FGPIO_PIN_15, +#endif + + FGPIO_PIN_NUM +} FGpioPinIndex; /* GPIO引脚号 */ + +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ +FASSERT_STATIC(8 == FGPIO_PIN_NUM); /* pin 0 ~ 7 */ +FASSERT_STATIC(2 == FGPIO_PORT_NUM); /* port a/b */ +#elif defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ +FASSERT_STATIC(16 == FGPIO_PIN_NUM); /* pin 0 ~ 15 */ +FASSERT_STATIC(1 == FGPIO_PORT_NUM); /* port a */ +#endif +typedef enum +{ + FGPIO_DIR_INPUT = 0, /* 输入 */ + FGPIO_DIR_OUTPUT /* 输出 */ +} FGpioDirection; /* GPIO引脚的输入输出方向 */ + +typedef enum +{ + FGPIO_IRQ_TYPE_EDGE_FALLING = 0, /* 上升沿中断,引脚检测到电平从低变高时触发 */ + FGPIO_IRQ_TYPE_EDGE_RISING, /* 下降沿中断,引脚检测到电平从高变低时触发 */ + FGPIO_IRQ_TYPE_LEVEL_LOW, /* 低电平中断,引脚电平为低时触发 */ + FGPIO_IRQ_TYPE_LEVEL_HIGH /* 高电平中断,引脚电平为高时触发 */ +} FGpioIrqType; /* GPIO引脚中断类型 */ + +typedef enum +{ + FGPIO_IRQ_NOT_SUPPORT, /* 不支持引脚中断 */ + FGPIO_IRQ_BY_CONTROLLER, /* 引脚中断控制器合并上报 */ +#if defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ + FGPIO_IRQ_BY_PIN, /* 引脚中断单独上报 */ +#endif +} FGpioIrqSourceType; + +typedef enum +{ + FGPIO_PIN_LOW = 0, /* 低电平 */ + FGPIO_PIN_HIGH /* 高电平 */ +} FGpioPinVal; /* GPIO引脚电平类型 */ + +/**************************** Type Definitions *******************************/ +typedef struct _FGpioPin FGpioPin; +typedef struct _FGpio FGpio; + +typedef struct +{ + u32 instance_id; /* GPIO实例ID */ + uintptr base_addr; /* GPIO控制器基地址 */ +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + u32 irq_num; /* GPIO控制器中断号 */ +#elif defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ + u32 irq_num[FGPIO_PIN_NUM]; /* GPIO各引脚的中断号 */ +#endif + u32 irq_priority; /* 中断优先级 */ +} FGpioConfig; /* GPIO控制器配置 */ + +typedef struct +{ + u32 ctrl; /* GPIO控制器号 */ + FGpioPortIndex port; /* GPIO引脚所在的组 */ + FGpioPinIndex pin; /* GPIO引脚号 */ +} FGpioPinId; /* GPIO引脚索引 */ + +typedef void (*FGpioInterruptCallback)(s32 vector, void *param); /* GPIO引脚中断回调函数类型 */ + +typedef struct _FGpioPin +{ + FGpioPinId index; /* 索引 */ + u32 is_ready; + FGpio *instance; + FGpioInterruptCallback irq_cb; /* 中断回调函数, Port-A有效 */ + void *irq_cb_params; /* 中断回调函数的入参, Port-A有效 */ + boolean irq_one_time; /* Port-A有效, TRUE: 进入中断后关闭该引脚的中断,用于电平敏感中断,防止一直进入中断 */ +} FGpioPin; /* GPIO引脚实例 */ + +typedef struct _FGpio +{ + FGpioConfig config; + u32 is_ready; + FGpioPin *pins[FGPIO_PORT_NUM][FGPIO_PIN_NUM]; +} FGpio; /* GPIO控制器实例 */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +/* 生成GPIO引脚索引 */ +#define FGPIO_PIN(port, pin) \ + (FGpioPinId) { \ + (port), (pin) \ + } + +/************************** Function Prototypes ******************************/ +/* 获取GPIO控制器的默认配置 */ +const FGpioConfig *FGpioLookupConfig(u32 instance_id); + +/* 初始化GPIO控制器实例 */ +FError FGpioCfgInitialize(FGpio *const instance, const FGpioConfig *const config); + +/* 初始化GPIO引脚实例 */ +FError FGpioPinInitialize(FGpio *const instance, FGpioPin *const pin, + const FGpioPinId pin_id); + +/* 去初始化GPIO引脚实例 */ +void FGpioPinDeInitialize(FGpioPin *const pin); + +/* 获取引脚中断的上报方式 */ +FGpioIrqSourceType FGpioGetPinIrqSourceType(FGpioPinId pin_id); + +/* 去初始化GPIO控制器实例 */ +void FGpioDeInitialize(FGpio *const instance); + +/* 设置GPIO引脚的输入输出方向 */ +void FGpioSetDirection(FGpioPin *const pin, FGpioDirection dir); + +/* 获取GPIO引脚的输入输出方向 */ +FGpioDirection FGpioGetDirection(FGpioPin *const pin); + +/* 设置GPIO引脚的输出值 */ +FError FGpioSetOutputValue(FGpioPin *const pin, const FGpioPinVal output); + +/* 获取GPIO引脚的输入值 */ +FGpioPinVal FGpioGetInputValue(FGpioPin *const pin); + +/* 获取GPIO A组引脚的中断屏蔽位 */ +void FGpioGetInterruptMask(FGpio *const instance, u32 *mask, u32 *enabled); + +/* 设置GPIO A组引脚的中断屏蔽位 */ +void FGpioSetInterruptMask(FGpioPin *const pin, boolean enable); + +/* 获取GPIO A组引脚的中断类型和中断极性 */ +void FGpioGetInterruptType(FGpio *const instance, u32 *levels, u32 *polarity); + +/* 设置GPIO A组引脚的中断类型 */ +void FGpioSetInterruptType(FGpioPin *const pin, const FGpioIrqType type); + +/* GPIO控制器中断处理函数 */ +void FGpioInterruptHandler(s32 vector, void *param); + +#if defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 2 */ +/* GPIO引脚中断处理函数 */ +void FGpioPinInterruptHandler(s32 vector, void *param); +#endif + +/* 注册GPIO A组引脚中断回调函数 */ +void FGpioRegisterInterruptCB(FGpioPin *const pin, FGpioInterruptCallback cb, + void *cb_param, boolean irq_one_time); + +/* 打印GPIO控制寄存器信息 */ +void FGpioDumpRegisters(uintptr base_addr); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_g.c b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_g.c new file mode 100644 index 0000000000..1c41a6665d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_g.c @@ -0,0 +1,101 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgpio_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for GPIO static configuration implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022-3-1 init commit + */ + + +/***************************** Include Files *********************************/ +#include "fparameters.h" + +#include "fgpio_hw.h" +#include "fgpio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ +const FGpioConfig fgpio_cfg_tbl[FGPIO_NUM] = +{ + [FGPIO_ID_0] = + { + .instance_id = FGPIO_ID_0, + .base_addr = FGPIO_0_BASE_ADDR, + .irq_num = FGPIO_0_IRQ_NUM, + .irq_priority = 0 + }, + [FGPIO_ID_1] = + { + .instance_id = FGPIO_ID_1, + .base_addr = FGPIO_1_BASE_ADDR, + .irq_num = FGPIO_1_IRQ_NUM, + .irq_priority = 0 + } +}; +#elif defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ +FGpioConfig fgpio_cfg_tbl[FGPIO_NUM] = +{ + [FGPIO_ID_0] = + { + .instance_id = FGPIO_ID_0, + .base_addr = FGPIO_0_BASE_ADDR, + .irq_priority = 0 + }, + [FGPIO_ID_1] = + { + .instance_id = FGPIO_ID_1, + .base_addr = FGPIO_1_BASE_ADDR, + .irq_priority = 0 + }, + [FGPIO_ID_2] = + { + .instance_id = FGPIO_ID_2, + .base_addr = FGPIO_2_BASE_ADDR, + .irq_priority = 0 + }, + [FGPIO_ID_3] = + { + .instance_id = FGPIO_ID_3, + .base_addr = FGPIO_3_BASE_ADDR, + .irq_priority = 0 + }, + [FGPIO_ID_4] = + { + .instance_id = FGPIO_ID_4, + .base_addr = FGPIO_4_BASE_ADDR, + .irq_priority = 0 + }, + [FGPIO_ID_5] = + { + .instance_id = FGPIO_ID_5, + .base_addr = FGPIO_5_BASE_ADDR, + .irq_priority = 0 + }, +}; +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_hw.h b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_hw.h new file mode 100644 index 0000000000..9acad53bf0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_hw.h @@ -0,0 +1,166 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgpio_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:35 + * Description:  This files is for GPIO register definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022-3-1 init commit + */ + + +#ifndef DRIVERS_FGPIO_HW_H +#define DRIVERS_FGPIO_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fio.h" +#include "fkernel.h" + +/************************** Constant Definitions *****************************/ +/** @name Register Map + * + * Register offsets from the base address of an GPIO device. + * @{ + */ +#define FGPIO_SWPORTA_DR_OFFSET 0x00 /* WR Port A Output Data Register */ +#define FGPIO_SWPORTA_DDR_OFFSET 0x04 /* WR Port A Data Direction Register */ +#define FGPIO_EXT_PORTA_OFFSET 0x08 /* RO Port A Input Data Register */ +#define FGPIO_SWPORTB_DR_OFFSET 0x0c /* WR Port B Output Data Register */ +#define FGPIO_SWPORTB_DDR_OFFSET 0x10 /* WR Port B Data Direction Register */ +#define FGPIO_EXT_PORTB_OFFSET 0x14 /* RO Port B Input Data Register */ + +#define FGPIO_INTEN_OFFSET 0x18 /* WR Port A Interrput Enable Register */ +#define FGPIO_INTMASK_OFFSET 0x1c /* WR Port A Interrupt Mask Register */ +#define FGPIO_INTTYPE_LEVEL_OFFSET 0x20 /* WR Port A Interrupt Level Register */ +#define FGPIO_INT_POLARITY_OFFSET 0x24 /* WR Port A Interrupt Polarity Register */ +#define FGPIO_INTSTATUS_OFFSET 0x28 /* RO Port A Interrupt Status Register */ +#define FGPIO_RAW_INTSTATUS_OFFSET 0x2c /* RO Port A Raw Interrupt Status Register */ +#define FGPIO_LS_SYNC_OFFSET 0x30 /* WR Level-sensitive Synchronization Enable Register */ +#define FGPIO_DEBOUNCE_OFFSET 0x34 /* WR Debounce Enable Register */ +#define FGPIO_PORTA_EOI_OFFSET 0x38 /* WO Port A Clear Interrupt Register */ + +/** @name FGPIO_SWPORTA_DR_OFFSET Register + */ +#define FGPIO_SWPORTA_DR_SET(dir) SET_REG32_BITS((dir), 7, 0) +#define FGPIO_SWPORTA_DR_GET(reg_val) GET_REG32_BITS((reg_val), 7, 0) +#define FGPIO_SWPORTA_DR_MASK GENMASK(7, 0) + +/** @name FGPIO_SWPORTA_DDR_OFFSET Register + */ +#define FGPIO_SWPORTA_DDR_SET(dir) SET_REG32_BITS((dir), 7, 0) +#define FGPIO_SWPORTA_DDR_GET(reg_val) GET_REG32_BITS((reg_val), 7, 0) +#define FGPIO_SWPORTA_DDR_MASK GENMASK(7, 0) + +/** @name FGPIO_EXT_PORTA_OFFSET Register + */ +#define FGPIO_EXT_PORTA_SET(dir) SET_REG32_BITS((dir), 7, 0) +#define FGPIO_EXT_PORTA_GET(reg_val) GET_REG32_BITS((reg_val), 7, 0) +#define FGPIO_EXT_PORTA_MASK GENMASK(7, 0) + +/** @name FGPIO_SWPORTB_DR_OFFSET Register + */ +#define FGPIO_SWPORTB_DR_SET(dir) SET_REG32_BITS((dir), 7, 0) +#define FGPIO_SWPORTB_DR_GET(reg_val) GET_REG32_BITS((reg_val), 7, 0) +#define FGPIO_SWPORTB_DR_MASK GENMASK(7, 0) + +/** @name FGPIO_SWPORTB_DDR_OFFSET Register + */ +#define FGPIO_SWPORTB_DDR_SET(dir) SET_REG32_BITS((dir), 7, 0) +#define FGPIO_SWPORTB_DDR_GET(reg_val) GET_REG32_BITS((reg_val), 7, 0) +#define FGPIO_SWPORTB_DDR_MASK GENMASK(7, 0) + +/** @name FGPIO_EXT_PORTB_OFFSET Register + */ +#define FGPIO_EXT_PORTB_SET(dir) SET_REG32_BITS((dir), 7, 0) +#define FGPIO_EXT_PORTB_GET(reg_val) GET_REG32_BITS((reg_val), 7, 0) +#define FGPIO_EXT_PORTB_MASK GENMASK(7, 0) + +/** @name FGPIO_INTEN_OFFSET Register + */ +#define FGPIO_INTR_PORTA_EN(n) BIT(n) /* 1: enable the intr of n-th port in group-a */ + +/** @name FGPIO_INTMASK_OFFSET Register + */ +#define FGPIO_INTR_PORTA_MASK(n) BIT(n) /* 1: disable the intr of n-th port in group-a */ + +/** @name FGPIO_INTTYPE_LEVEL_OFFSET Register + */ +#define FGPIO_INTR_PORTA_LEVEL(n) BIT(n) /* 1: intr by edge, 0: intr by level */ + +/** @name FGPIO_INT_POLARITY_OFFSET Register + */ +#define FGPIO_INTR_PORTA_POLARITY(n) BIT(n) /* 1: intr by rising-edge/high-level, 0: intr by falling-edge/low-level */ + +/** @name FGPIO_INTSTATUS_OFFSET Register + */ +#define FGPIO_INTR_PORTA_STATUS(n) BIT(n) /* intr status */ + +/** @name FGPIO_RAW_INTSTATUS_OFFSET Register + */ +#define FGPIO_INTR_PORTA_RAW_STATUS(n) BIT(n) /* intr status without masking */ + +/** @name FGPIO_LS_SYNC_OFFSET Register + */ +#define FGPIO_PCLK_INTR_SYNC(n) BIT(n) /* 1: sync to pclk_intr */ + +/** @name FGPIO_DEBOUNCE_OFFSET Register + */ +#define FGPIO_DEBOUNCE_CLK_CONFIG_SET(clk) SET_REG32_BITS((clk), 15, 7) +#define FGPIO_DEBOUNCE_CLK_CONFIG_GET(reg_val) GET_REG32_BITS((reg_val), 15, 7) +#define FGPIO_DEBOUNCE_CLK_CONFIG_MASK GENMASK(15, 7) +#define FGPIO_DEBOUNCE_EN(n) BIT(n) /* 1: enable debounce */ + +/** @name FGPIO_PORTA_EOI_OFFSET Register + */ +#define FGPIO_CLR_INTR_PORTA(n) BIT(n) /* 1: clear interrupt */ + + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +static inline u32 FGpioReadReg32(uintptr base_addr, uintptr reg_off) +{ + return FtIn32(base_addr + reg_off); +} + +static inline void FGpioWriteReg32(uintptr base_addr, uintptr reg_off, const u32 reg_val) +{ + FtOut32(base_addr + reg_off, reg_val); +} + +static inline void FGpioSetBit32(uintptr base_addr, uintptr reg_off, u32 bit) +{ + if (0 == bit) + FtClearBit32(base_addr + reg_off, bit); + else if (1 == bit) + FtSetBit32(base_addr + reg_off, bit); +} + +/************************** Function Prototypes ******************************/ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_intr.c b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_intr.c new file mode 100644 index 0000000000..b453ecdb7e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_intr.c @@ -0,0 +1,328 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgpio_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for GPIO interrupt function implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022-3-1 init commit + */ + + +/***************************** Include Files *********************************/ +#include "fdebug.h" +#include "fparameters.h" + +#include "fgpio_hw.h" +#include "fgpio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGPIO_DEBUG_TAG "FGPIO-INTR" +#define FGPIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_WARN(format, ...) FT_DEBUG_PRINT_W(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_INFO(format, ...) FT_DEBUG_PRINT_I(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +/** + * @name: FGpioGetInterruptMask + * @msg: 获取GPIO A组引脚的中断屏蔽位 + * @return {*} + * @param {FGpio} *instance, GPIO控制器实例 + * @param {u32} *mask, 返回的GPIO A组引脚中断屏蔽位 + * @param {u32} *enabled, 返回的GPIO A组中断使能位 + * @note 获取的是A组所有Pin的中断屏蔽位和中断使能位 + */ +void FGpioGetInterruptMask(FGpio *const instance, u32 *mask, u32 *enabled) +{ + FASSERT(instance); + FASSERT(instance->is_ready == FT_COMPONENT_IS_READY); + uintptr base_addr = instance->config.base_addr; + + if (NULL != mask) + { + *mask = FGpioReadReg32(base_addr, FGPIO_INTMASK_OFFSET); + } + + if (NULL != enabled) + { + *enabled = FGpioReadReg32(base_addr, FGPIO_INTEN_OFFSET); + } + + return; +} + +/** + * @name: FGpioSetInterruptMask + * @msg: 设置GPIO A组引脚的中断屏蔽位 + * @return {*} + * @param {FGpioPin} *pin, GPIO引脚实例 + * @param {boolean} enable, TRUE表示使能GPIO引脚中断,FALSE表示去使能GPIO引脚中断 + * @note index对应的引脚必须为A组引脚,B组引脚不支持中断 + */ +void FGpioSetInterruptMask(FGpioPin *const pin, boolean enable) +{ + FASSERT(pin); + FGpio *const instance = pin->instance; + FASSERT(instance); + FASSERT(instance->is_ready == FT_COMPONENT_IS_READY); + uintptr base_addr = instance->config.base_addr; + u32 mask_bits = 0; + u32 enable_bits = 0; + FGpioPinId index = pin->index; + +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + if (FGPIO_PORT_B == index.port) + { + FGPIO_ERROR("None interrupt support for PORT-B !!!"); + return; + } +#endif + + if (FGPIO_DIR_OUTPUT == FGpioGetDirection(pin)) + { + FGPIO_ERROR("None interrupt support for output GPIO !!!"); + return; + } + + FGpioGetInterruptMask(instance, &mask_bits, &enable_bits); + if (TRUE == enable) + { + mask_bits &= ~BIT(index.pin); /* not mask: 0 */ + enable_bits |= BIT(index.pin); /* enable pin irq: 1 */ + } + else + { + mask_bits |= BIT(index.pin); /* mask: 1 */ + enable_bits &= ~BIT(index.pin); /* disable pin irq: 0 */ + } + + FGpioWriteReg32(base_addr, FGPIO_INTMASK_OFFSET, mask_bits); + FGpioWriteReg32(base_addr, FGPIO_INTEN_OFFSET, enable_bits); + return; +} + +/** + * @name: FGpioGetInterruptType + * @msg: 获取GPIO A组引脚的中断类型和中断极性 + * @return {*} + * @param {FGpio} *instance, GPIO控制器实例 + * @param {u32} *levels, GPIO A组引脚中断电平类型 + * @param {u32} *polarity, GPIO A组引脚中断极性类型 + * @note 获取的是A组所有Pin的电平和极性 + */ +void FGpioGetInterruptType(FGpio *const instance, u32 *levels, u32 *polarity) +{ + FASSERT(instance); + FASSERT(instance->is_ready == FT_COMPONENT_IS_READY); + uintptr base_addr = instance->config.base_addr; + + if (NULL != levels) + { + *levels = FGpioReadReg32(base_addr, FGPIO_INTTYPE_LEVEL_OFFSET); + } + + if (NULL != polarity) + { + *polarity = FGpioReadReg32(base_addr, FGPIO_INTTYPE_LEVEL_OFFSET); + } + + return; +} + +/** + * @name: FGpioSetInterruptType + * @msg: 设置GPIO引脚的中断类型 + * @return {*} + * @param {FGpioPin} *pin, GPIO引脚实例 + * @param {FGpioIrqType} type, GPIO引脚中断触发类型 + * @note index对应的引脚必须为A组引脚,B组引脚不支持中断 + */ +void FGpioSetInterruptType(FGpioPin *const pin, const FGpioIrqType type) +{ + FASSERT(pin); + FGpio *const instance = pin->instance; + FASSERT(instance); + FASSERT(instance->is_ready == FT_COMPONENT_IS_READY); + uintptr base_addr = instance->config.base_addr; + u32 level = 0; + u32 polarity = 0; + FGpioPinId index = pin->index; + +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + if (FGPIO_PORT_B == index.port) + { + FGPIO_ERROR("None interrupt support for PORT-B !!!"); + return; + } +#endif + + FGpioGetInterruptType(instance, &level, &polarity); + + switch (type) + { + case FGPIO_IRQ_TYPE_EDGE_FALLING: + level |= BIT(index.pin); /* 边沿敏感型 */ + polarity &= ~BIT(index.pin); /* 下降沿或低电平 */ + break; + case FGPIO_IRQ_TYPE_EDGE_RISING: + level |= BIT(index.pin); /* 边沿敏感型 */ + polarity |= BIT(index.pin); /* 上升沿或高电平 */ + break; + case FGPIO_IRQ_TYPE_LEVEL_LOW: + level &= ~BIT(index.pin); /* 电平敏感型 */ + polarity &= ~BIT(index.pin); /* 下降沿或低电平 */ + break; + case FGPIO_IRQ_TYPE_LEVEL_HIGH: + level &= ~BIT(index.pin); /* 电平敏感型 */ + polarity |= BIT(index.pin); /* 上升沿或高电平 */ + break; + default: + break; + } + + FGpioWriteReg32(base_addr, FGPIO_INTTYPE_LEVEL_OFFSET, level); + FGpioWriteReg32(base_addr, FGPIO_INT_POLARITY_OFFSET, polarity); + + return; +} + +/** + * @name: FGpioInterruptHandler + * @msg: GPIO中断处理函数 + * @return {*} + * @param {s32} vector, 中断输入参数1 + * @param {void} *param, 中断输入参数2 + * @note 需要用户将此函数注册到Interrtup上,使能GPIO中断才能生效 + */ +void FGpioInterruptHandler(s32 vector, void *param) +{ + FGpio *const instance = (FGpio * const)param; + FGpioPin *pin = NULL; + FASSERT(instance); + int loop; + uintptr base_addr = instance->config.base_addr; + u32 status = FGpioReadReg32(base_addr, FGPIO_INTSTATUS_OFFSET); + u32 raw_status = FGpioReadReg32(base_addr, FGPIO_RAW_INTSTATUS_OFFSET); + +#if defined(FGPIO_VERSION_2) /* E2000 gpio 3 ~ 5 */ + FASSERT_MSG(FGPIO_WITH_PIN_IRQ < instance->config.instance_id, "handle interrupt through pin !!!") +#endif + + FGPIO_INFO("status: 0x%x, raw_status: 0x%x", status, raw_status); + for (loop = FGPIO_PIN_0; loop < FGPIO_PIN_NUM; loop++) + { + if (status & BIT(loop)) + { + pin = instance->pins[FGPIO_PORT_A][loop]; + if (NULL == pin) + continue; + + if (pin->irq_cb) + { + pin->irq_cb(0U, pin->irq_cb_params); + + /* disable pin interrupt after triggered */ + if (TRUE == pin->irq_one_time) + { + FGpioSetInterruptMask(pin, FALSE); + } + } + else + { + FGPIO_WARN("no irq handler callback for GPIO-%d-A-%d", + instance->config.instance_id, + loop); + } + } + } + + /* clear interrupt status */ + FGpioWriteReg32(base_addr, FGPIO_PORTA_EOI_OFFSET, status); + return; +} + +#if defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 2 */ +/** + * @name: FGpioPinInterruptHandler + * @msg: GPIO引脚中断处理函数 + * @return {NONE} + * @param {s32} vector, 中断输入参数1 + * @param {void} *param, 中断输入参数2 + */ +void FGpioPinInterruptHandler(s32 vector, void *param) +{ + FGpioPin *const pin = (FGpioPin * const)param; + FASSERT(pin); + FGpio *const instance = pin->instance; + FASSERT(instance); + uintptr base_addr = instance->config.base_addr; + + u32 status = FGpioReadReg32(base_addr, FGPIO_INTSTATUS_OFFSET); + u32 raw_status = FGpioReadReg32(base_addr, FGPIO_RAW_INTSTATUS_OFFSET); + + FGPIO_INFO("status: 0x%x, raw_status: 0x%x", status, raw_status); + if (pin->irq_cb) + { + pin->irq_cb(0U, pin->irq_cb_params); + + /* disable pin interrupt after triggered */ + if (TRUE == pin->irq_one_time) + { + FGpioSetInterruptMask(pin, FALSE); + } + } + else + { + FGPIO_WARN("no irq handler callback for GPIO-%d-A-%d", + pin->index.ctrl, + pin->index.pin); + } + + + /* clear interrupt status */ + FGpioWriteReg32(base_addr, FGPIO_PORTA_EOI_OFFSET, status); + return; +} +#endif + +/** + * @name: FGpioRegisterInterruptCB + * @msg: 注册GPIO引脚中断回调函数 + * @return {*} + * @param {FGpioPin} pin, GPIO引脚实例 + * @param {FGpioInterruptCallback} cb, GPIO引脚中断回调函数 + * @param {void} *cb_param, GPIO引脚中断回调函数输入参数 + * @param {boolean} irq_one_time, TRUE表示引脚中断触发一次后自动关闭中断,用于电平敏感中断 + * @note 注册的回调函数在FGpioInterruptHandler中被调用 + */ +void FGpioRegisterInterruptCB(FGpioPin *const pin, FGpioInterruptCallback cb, void *cb_param, boolean irq_one_time) +{ + FASSERT(pin); + pin->irq_cb = cb; + pin->irq_cb_params = cb_param; + pin->irq_one_time = irq_one_time; + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_selftest.c b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_selftest.c new file mode 100644 index 0000000000..8cc5ed81e0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_selftest.c @@ -0,0 +1,79 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgpio_selftest.c + * Date: 2022-06-17 14:32:12 + * LastEditTime: 2022-06-17 14:32:12 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +/***************************** Include Files *********************************/ +#include "fdebug.h" +#include "fassert.h" + +#include "fgpio_hw.h" +#include "fgpio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FGPIO_DEBUG_TAG "FGPIO-TEST" +#define FGPIO_ERROR(format, ...) FT_DEBUG_PRINT_E(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_WARN(format, ...) FT_DEBUG_PRINT_W(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_INFO(format, ...) FT_DEBUG_PRINT_I(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FGPIO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FGPIO_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FGPIO_DUMPER(base_addr, reg_off, reg_name) \ + FGPIO_DEBUG("\t\t[%s]@0x%x\t=\t0x%x", reg_name, (reg_off), FGpioReadReg32((base_addr), (reg_off))) +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ + +/** + * @name: FGpioDumpRegisters + * @msg: 打印GPIO控制寄存器信息 + * @return {NONE} + * @param {uintptr} base_addr, GPIO控制器基地址 + */ +void FGpioDumpRegisters(uintptr base_addr) +{ + FASSERT(0 != base_addr); + + FGPIO_DEBUG("Dump register info @0x%x", base_addr); + FGPIO_DUMPER(base_addr, FGPIO_SWPORTA_DR_OFFSET, "dr"); + FGPIO_DUMPER(base_addr, FGPIO_SWPORTA_DDR_OFFSET, "ddr"); + FGPIO_DUMPER(base_addr, FGPIO_EXT_PORTA_OFFSET, "ext_porta"); +#if defined(FGPIO_VERSION_1) /* D2000 FT2000/4 */ + FGPIO_DUMPER(base_addr, FGPIO_SWPORTB_DR_OFFSET, "portb_dr"); + FGPIO_DUMPER(base_addr, FGPIO_SWPORTB_DDR_OFFSET, "portb_ddr"); + FGPIO_DUMPER(base_addr, FGPIO_EXT_PORTB_OFFSET, "ext_portb"); +#endif + FGPIO_DUMPER(base_addr, FGPIO_INTEN_OFFSET, "inten"); + FGPIO_DUMPER(base_addr, FGPIO_INTMASK_OFFSET, "intmask"); + FGPIO_DUMPER(base_addr, FGPIO_INTTYPE_LEVEL_OFFSET, "intr_level"); + FGPIO_DUMPER(base_addr, FGPIO_INT_POLARITY_OFFSET, "intr_polarity"); + FGPIO_DUMPER(base_addr, FGPIO_INTSTATUS_OFFSET, "intr_status"); + FGPIO_DUMPER(base_addr, FGPIO_RAW_INTSTATUS_OFFSET, "raw_int_status"); + FGPIO_DUMPER(base_addr, FGPIO_LS_SYNC_OFFSET, "ls_sync"); + FGPIO_DUMPER(base_addr, FGPIO_DEBOUNCE_OFFSET, "debounce"); + FGPIO_DUMPER(base_addr, FGPIO_PORTA_EOI_OFFSET, "porta_eoi"); + + return; +} diff --git a/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_sinit.c b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_sinit.c new file mode 100644 index 0000000000..2700899002 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pin/fgpio/fgpio_sinit.c @@ -0,0 +1,150 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fgpio_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 08:25:29 + * Description:  This files is for GPIO static variables + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2022-3-1 init commit + */ + + +/***************************** Include Files *********************************/ +#include "fparameters.h" + +#include "fgpio_hw.h" +#include "fgpio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ + extern const FGpioConfig fgpio_cfg_tbl[FGPIO_NUM]; +#elif defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ + extern FGpioConfig fgpio_cfg_tbl[FGPIO_NUM]; +#endif + +/*****************************************************************************/ + +#if defined(FGPIO_VERSION_1) /* FT2000-4, D2000 */ +/** + * @name: FGpioLookupConfig + * @msg: 获取GPIO控制器的默认配置 + * @return {const FGpioConfig *} GPIO控制器的默认配置 + * @param {u32} instance_id, GPIO控制器实例号 + */ +const FGpioConfig *FGpioLookupConfig(u32 instance_id) +{ + const FGpioConfig *ptr = NULL; + u32 index; + + for (index = 0; index < FGPIO_NUM; index++) + { + if (fgpio_cfg_tbl[index].instance_id == instance_id) + { + ptr = &fgpio_cfg_tbl[index]; + break; + } + } + + return ptr; +} +#elif defined(FGPIO_VERSION_2) /* E2000 GPIO 0 ~ 5 */ +/** + * @name: FGpioSetIrqNum + * @msg: 设置GPIO控制器各引脚的中断号 + * @return {NONE} + * @param {u32} instance_id, GPIO控制器实例号 + * @param {FGpioConfig} *ptr, GPIO控制器的默认配置 + */ +static void FGpioSetIrqNum(u32 instance_id, FGpioConfig *ptr) +{ + u32 pin_id; + u32 irq_num; + + if (FGPIO_WITH_PIN_IRQ >= instance_id) /* GPIO 0 ~ 2 */ + { + /* each pin has its own interrupt id */ + for (pin_id = FGPIO_PIN_0; pin_id < FGPIO_PIN_NUM; pin_id++) + { + ptr->irq_num[pin_id] = FGPIO_PIN_IRQ_NUM_GET(instance_id, pin_id); + } + } + else + { + if (FGPIO_ID_3 == instance_id) + { + irq_num = FGPIO_3_IRQ_NUM; + } + else if (FGPIO_4_IRQ_NUM == instance_id) + { + irq_num = FGPIO_4_IRQ_NUM; + } + else if (FGPIO_5_IRQ_NUM == instance_id) + { + irq_num = FGPIO_5_IRQ_NUM; + } + + /* all pins in the controller share the same interrupt id */ + for (pin_id = FGPIO_PIN_0; pin_id < FGPIO_PIN_NUM; pin_id++) + { + ptr->irq_num[pin_id] = irq_num; + } + } + + return; +} + +/** + * @name: FGpioLookupConfig + * @msg: 获取GPIO控制器的默认配置 + * @return {const FGpioConfig *} GPIO控制器的默认配置 + * @param {u32} instance_id, GPIO控制器实例号 + */ +const FGpioConfig *FGpioLookupConfig(u32 instance_id) +{ + const FGpioConfig *ptr = NULL; + u32 index; + static boolean irq_num_set = FALSE; + + if (FALSE == irq_num_set) /* set irq num in the first time */ + { + for (index = 0; index < FGPIO_NUM; index++) + { + FGpioSetIrqNum(index, &fgpio_cfg_tbl[index]); + } + irq_num_set = TRUE; + } + + for (index = 0; index < FGPIO_NUM; index++) /* find configs of controller */ + { + if (fgpio_cfg_tbl[index].instance_id == instance_id) + { + ptr = &fgpio_cfg_tbl[index]; + break; + } + } + + return ptr; +} +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/Kconfig b/bsp/phytium/libraries/standalone/drivers/pwm/Kconfig new file mode 100644 index 0000000000..5a6185cf4e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/Kconfig @@ -0,0 +1,9 @@ +menu "FPWM Configuration" + config USE_FPWM + bool + prompt "Use FPWM" + default n + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm.c b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm.c new file mode 100644 index 0000000000..7c1dace19e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm.c @@ -0,0 +1,808 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpwm.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include +#include "fkernel.h" +#include "ftypes.h" +#include "ferror_code.h" +#include "fdebug.h" +#include "fpwm.h" +#include "fpwm_hw.h" +#include "fparameters.h" +#include "fsleep.h" + +#define FPWM_DEBUG_TAG "PWM" +#define FPWM_ERROR(format, ...) FT_DEBUG_PRINT_E(FPWM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPWM_WARN(format, ...) FT_DEBUG_PRINT_W(FPWM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPWM_INFO(format, ...) FT_DEBUG_PRINT_I(FPWM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPWM_DEBUG(format, ...) FT_DEBUG_PRINT_D(FPWM_DEBUG_TAG, format, ##__VA_ARGS__) + +/** + * @name: FPwmReset + * @msg: reset pwm + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmReset(FPwmCtrl *pctrl, u32 channel) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + + u32 reg_val = 0; + int timeout = FPWM_RESET_TIMEOUT; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + reg_val |= FPWM_TIM_CTRL_RESET; + FPWM_WRITE_REG32(base_addr, FPWM_TIM_CTRL_OFFSET, reg_val); + + /* Check for the reset complete*/ + do + { + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + } + while ((FPWM_TIM_CTRL_RESET & reg_val) && (0 <= --timeout)); + + if (0 >= timeout) + { + FPWM_ERROR("timeout when wait pwm reset complete"); + return FPWM_ERR_TIMEOUT; + } + return FPWM_SUCCESS; +} + +/** + * @name: FPwmEnable + * @msg: enable pwm + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @return + */ +void FPwmEnable(FPwmCtrl *pctrl, u32 channel) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + reg_val |= FPWM_TIM_CTRL_ENABLE; + FPWM_WRITE_REG32(base_addr, FPWM_TIM_CTRL_OFFSET, reg_val); + + pctrl->channel_ctrl_enable[channel] = TRUE; +} + +/** + * @name: FPwmDisable + * @msg: disable pwm + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @return + */ +void FPwmDisable(FPwmCtrl *pctrl, u32 channel) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + reg_val &= (~FPWM_TIM_CTRL_ENABLE); + FPWM_WRITE_REG32(base_addr, FPWM_TIM_CTRL_OFFSET, reg_val); + + pctrl->channel_ctrl_enable[channel] = FALSE; + +} + +/** + * @name: FPwmTimCtrlModeSet + * @msg: config pwm timer counter mode. + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {FPwmTimCtrlMode} mode, counter mode parameters of FPWM + * @return + */ +static void FPwmTimCtrlModeSet(FPwmCtrl *pctrl, u32 channel, FPwmTimCtrlMode mode) +{ + FASSERT(pctrl != NULL); + FASSERT(mode < FPWM_TIM_CTRL_MODE_NUM); + /* check whether the state is disabled */ + FASSERT(pctrl->channel_ctrl_enable[channel] == FALSE); + + u32 reg_val = 0; + + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + + switch (mode) + { + /* modulo */ + case FPWM_MODULO: + reg_val &= (~FPWM_TIM_CTRL_MODE_UD); + break; + /* up-and-down */ + case FPWM_UP_DOWN: + reg_val |= FPWM_TIM_CTRL_MODE_UD; + break; + default: + break; + } + + FPWM_WRITE_REG32(base_addr, FPWM_TIM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmTimInterruptEnable + * @msg: enable pwm timer global and counter-overflow interrupt + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @return + */ +static void FPwmTimInterruptEnable(FPwmCtrl *pctrl, u32 channel) +{ + FASSERT(pctrl != NULL); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + reg_val &= (~(FPWM_TIM_CTRL_OVFIF_ENABLE | FPWM_TIM_CTRL_GIE)); + reg_val |= (FPWM_TIM_CTRL_OVFIF_ENABLE | FPWM_TIM_CTRL_GIE); + + FPWM_WRITE_REG32(base_addr, FPWM_TIM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmTimInterruptDisable + * @msg: disable pwm timer global and counter-overflow interrupt + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @return + */ +static void FPwmTimInterruptDisable(FPwmCtrl *pctrl, u32 channel) +{ + FASSERT(pctrl != NULL); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + reg_val &= (~(FPWM_TIM_CTRL_OVFIF_ENABLE | FPWM_TIM_CTRL_GIE)); + + FPWM_WRITE_REG32(base_addr, FPWM_TIM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmDivSet + * @msg: config pwm div, div range:0~4095, corresponding to 1~4096 + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {u16} div, div parameters + * @return + */ +static void FPwmDivSet(FPwmCtrl *pctrl, u32 channel, u16 div) +{ + u32 reg_val = 0; + FASSERT(pctrl != NULL); + FASSERT(div < FPWM_TIM_CTRL_DIV_MAX); + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_TIM_CTRL_OFFSET); + reg_val |= (FPWM_TIM_CTRL_DIV_MASK & FPWM_TIM_CTRL_DIV(div)); + + FPWM_WRITE_REG32(base_addr, FPWM_TIM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmPeriodSet + * @msg: config pwm period, range:1~0xffff + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {u16} pwm_period, period parameters + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +static void FPwmPeriodSet(FPwmCtrl *pctrl, u32 channel, u16 pwm_period) +{ + FASSERT(pctrl != NULL); + u32 reg_val = 0; + u64 cycles = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_PERIOD_OFFSET); + reg_val &= (~FPWM_PERIOD_CCR_MASK); + reg_val |= (pwm_period & FPWM_PERIOD_CCR_MASK); + + FPWM_WRITE_REG32(base_addr, FPWM_PERIOD_OFFSET, reg_val); +} + +/** + * @name: FPwmDutySourceSet + * @msg: config pwm duty source, from pwm_ccr register or fifo + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {FPwmDutySourceMode} duty_source, duty source parameters + * @return + */ +static void FPwmDutySourceSet(FPwmCtrl *pctrl, u32 channel, FPwmDutySourceMode duty_source) +{ + FASSERT(pctrl != NULL); + FASSERT(duty_source < FPWM_DUTY_SEL_MODE_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_CTRL_OFFSET); + switch (duty_source) + { + /* duty from PWM_CCR */ + case FPWM_DUTY_CCR: + reg_val &= (~FPWM_CTRL_DUTY_SOURCE_FIFO); + break; + /* from FIFO */ + case FPWM_DUTY_FIFO: + reg_val |= FPWM_CTRL_DUTY_SOURCE_FIFO; + break; + default: + break; + } + + FPWM_WRITE_REG32(base_addr, FPWM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmPulseSet + * @msg: config pwm duty, pwm_ccr is less than pwm_period + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {u16} pwm_ccr, pwm_ccr parameters + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmPulseSet(FPwmCtrl *pctrl, u32 channel, u16 pwm_ccr) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + u32 reg_val = 0; + u64 cycles = 0; + u32 state = 0; + u16 pwm_period_ccr = 0; + + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + /* Check the pwm_ccr < pwm_period_ccr */ + pwm_period_ccr = (u16)FPWM_READ_REG32(base_addr, FPWM_PERIOD_OFFSET); + if (pwm_ccr > pwm_period_ccr) + { + FPWM_ERROR("pwm ccr is bigger than period"); + return FPWM_ERR_INVAL_PARM; + } + + reg_val = FPWM_READ_REG32(base_addr, FPWM_CTRL_OFFSET); + + /* Check the duty source */ + if (reg_val & FPWM_CTRL_DUTY_SOURCE_FIFO) + { + /* Check the duty fifo is not full */ + state = FPWM_READ_REG32(base_addr, FPWM_STATE_OFFSET); + if (state & FPWM_STATE_FIFO_FULL) + { + FPWM_ERROR("pwm state fifo full"); + return FPWM_ERR_CMD_FAILED; + } + } + + reg_val = FPWM_READ_REG32(base_addr, FPWM_CCR_OFFSET); + reg_val &= (~FPWM_CCR_MASK); + reg_val |= (pwm_ccr & FPWM_CCR_MASK); + + FPWM_WRITE_REG32(base_addr, FPWM_CCR_OFFSET, reg_val); + + return FPWM_SUCCESS; +} + +/** + * @name: FPwmCtrlModeSet + * @msg: config pwm mode, currently only support compare output + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @return + */ +static void FPwmCtrlModeSet(FPwmCtrl *pctrl, u32 channel) +{ + FASSERT(pctrl != NULL); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_CTRL_OFFSET); + + reg_val |= FPWM_CTRL_MODE_OUTPUT; + + FPWM_WRITE_REG32(base_addr, FPWM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmPolaritySet + * @msg: config pwm compare output polarity + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {FPwmPolarity} polarity, compare output polarity parameters + * @return + */ +static void FPwmPolaritySet(FPwmCtrl *pctrl, u32 channel, FPwmPolarity polarity) +{ + FASSERT(pctrl != NULL); + FASSERT(polarity < FPWM_POLARITY_NUM); + /* check whether the state is disabled */ + FASSERT(pctrl->channel_ctrl_enable[channel] == FALSE); + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + u32 reg_val = 0; + reg_val = FPWM_READ_REG32(base_addr, FPWM_CTRL_OFFSET); + reg_val &= (~FPWM_CTRL_CMP_MASK); + reg_val |= FPWM_CTRL_CMP(polarity); + FPWM_WRITE_REG32(base_addr, FPWM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmDbReset + * @msg: reset pwm db + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +static FError FPwmDbReset(FPwmCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + + u32 reg_val = 0; + int timeout = FPWM_RESET_TIMEOUT; + uintptr base_addr = pctrl->config.db_base_addr; + + reg_val = FPWM_READ_REG32(base_addr, FPWM_DB_CTRL_OFFSET); + reg_val |= FPWM_DB_CTRL_RESET; + FPWM_WRITE_REG32(base_addr, FPWM_DB_CTRL_OFFSET, reg_val); + + /* Check for the db reset complete*/ + do + { + reg_val = FPWM_READ_REG32(base_addr, FPWM_DB_CTRL_OFFSET); + } + while ((FPWM_DB_CTRL_RESET & reg_val) && (0 <= --timeout)); + + if (0 >= timeout) + { + FPWM_ERROR("timeout when wait pwm db reset complete"); + return FPWM_ERR_TIMEOUT; + } + return FPWM_SUCCESS; +} + +/** + * @name: FPwmDbPolaritySet + * @msg: config pwm db polarity + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {FPwmDbPolarity} db_polarity, db polarity parameters + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmDbPolaritySet(FPwmCtrl *pctrl, FPwmDbPolarity db_polarity) +{ + FASSERT(pctrl != NULL); + FASSERT(db_polarity < FPWM_DB_POLARITY_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.db_base_addr; + + reg_val = FPWM_READ_REG32(base_addr, FPWM_DB_CTRL_OFFSET); + reg_val &= (~FPWM_DB_CTRL_POLSEL_MASK); + reg_val |= FPWM_DB_CTRL_POLSEL(db_polarity); + FPWM_WRITE_REG32(base_addr, FPWM_DB_CTRL_OFFSET, reg_val); + + return FPWM_SUCCESS; +} + +/** + * @name: FPwmDbFallCycleSet + * @msg: config pwm db fall cycle + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u16} fall_edge_delay, db fall cycle parameters + * @return + */ +static void FPwmDbFallCycleSet(FPwmCtrl *pctrl, u16 fall_edge_delay) +{ + FASSERT(pctrl != NULL); + FASSERT(fall_edge_delay < FPWM_DB_DLY_MAX); + u32 reg_val = 0; + uintptr pwm_base_addr = pctrl->config.pwm_base_addr; + uintptr db_base_addr = pctrl->config.db_base_addr; + + u32 pwm_period = FPWM_READ_REG32(pwm_base_addr, FPWM_PERIOD_OFFSET); + + reg_val = FPWM_READ_REG32(db_base_addr, FPWM_DB_DLY_OFFSET); + reg_val &= (~FPWM_DB_DLY_FALL_MASK); + reg_val |= FPWM_DB_DLY_FALL(fall_edge_delay); + FPWM_WRITE_REG32(db_base_addr, FPWM_DB_DLY_OFFSET, reg_val); +} + +/** + * @name: FPwmDbRiseCycleSet + * @msg: config pwm db rise cycle + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u16} rise_edge_delay, db rise cycle parameters + * @return + */ +static void FPwmDbRiseCycleSet(FPwmCtrl *pctrl, u16 rise_edge_delay) +{ + FASSERT(pctrl != NULL); + FASSERT(rise_edge_delay < FPWM_DB_DLY_MAX); + u32 reg_val = 0; + uintptr pwm_base_addr = pctrl->config.pwm_base_addr; + uintptr db_base_addr = pctrl->config.db_base_addr; + + u32 pwm_period = FPWM_READ_REG32(pwm_base_addr, FPWM_PERIOD_OFFSET); + + reg_val = FPWM_READ_REG32(db_base_addr, FPWM_DB_DLY_OFFSET); + reg_val &= (~FPWM_DB_DLY_RISE_MASK); + reg_val |= (u32)(rise_edge_delay & FPWM_DB_DLY_RISE_MASK); + FPWM_WRITE_REG32(db_base_addr, FPWM_DB_DLY_OFFSET, reg_val); +} + +/** + * @name: FPwmDbInModeSet + * @msg: config pwm db in source mode, pwm0 or pwm1 + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {FPwmDbInMode} db_in_mode, db in mode parameters + * @return void + */ +static void FPwmDbInModeSet(FPwmCtrl *pctrl, FPwmDbInMode db_in_mode) +{ + FASSERT(db_in_mode < FPWM_DB_IN_MODE_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.db_base_addr; + + reg_val = FPWM_READ_REG32(base_addr, FPWM_DB_CTRL_OFFSET); + switch (db_in_mode) + { + case FPWM_DB_IN_MODE_PWM0: + reg_val &= (~FPWM_DB_CTRL_IN_MODE); + break; + case FPWM_DB_IN_MODE_PWM1: + reg_val |= FPWM_DB_CTRL_IN_MODE; + break; + default: + break; + } + + FPWM_WRITE_REG32(base_addr, FPWM_DB_CTRL_OFFSET, reg_val); +} + +static void FPwmDbOutModeSet(FPwmCtrl *pctrl, FPwmDbOutMode db_out_mode) +{ + FASSERT(db_out_mode < FPWM_DB_OUT_MODE_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.db_base_addr; + + reg_val = FPWM_READ_REG32(base_addr, FPWM_DB_CTRL_OFFSET); + reg_val &= (~FPWM_DB_CTRL_OUT_MODE_MASK); + reg_val |= FPWM_DB_CTRL_OUT_MODE(db_out_mode); + FPWM_WRITE_REG32(base_addr, FPWM_DB_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmInterruptEnable + * @msg: enable pwm compare output interrupt + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {FPwmIntrEventType} intr_type, pwm interrupt event type + * @return + */ +void FPwmInterruptEnable(FPwmCtrl *pctrl, u32 channel, FPwmIntrEventType intr_type) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_CTRL_OFFSET); + + if (intr_type == FPWM_INTR_EVENT_COUNTER) + { + reg_val &= (~FPWM_CTRL_INTR_COUNTER_ENABLE); + reg_val |= FPWM_CTRL_INTR_COUNTER_ENABLE; + } + + if (intr_type == FPWM_INTR_EVENT_FIFO_EMPTY) + { + reg_val &= (~FPWM_CTRL_INTR_FIFO_EMPTY_ENABLE); + reg_val |= FPWM_CTRL_INTR_FIFO_EMPTY_ENABLE; + } + + FPWM_WRITE_REG32(base_addr, FPWM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmInterruptDisable + * @msg: disable pwm compare output interrupt + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {FPwmIntrEventType} intr_type, pwm interrupt event type + * @return + */ +void FPwmInterruptDisable(FPwmCtrl *pctrl, u32 channel, FPwmIntrEventType intr_type) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + u32 reg_val = 0; + uintptr base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + reg_val = FPWM_READ_REG32(base_addr, FPWM_CTRL_OFFSET); + + if (intr_type == FPWM_INTR_EVENT_COUNTER) + { + reg_val &= (~FPWM_CTRL_INTR_COUNTER_ENABLE); + } + + if (intr_type == FPWM_INTR_EVENT_FIFO_EMPTY) + { + reg_val &= (~FPWM_CTRL_INTR_FIFO_EMPTY_ENABLE); + } + + FPWM_WRITE_REG32(base_addr, FPWM_CTRL_OFFSET, reg_val); +} + +/** + * @name: FPwmDbVariableSet + * @msg: set pwm db Variable config, users need call this function before + * FPwmVariableSet if you want to use deadband function. + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {FPwmDbVariableConfig} db_cfg_p, db config parameters, include mode and cycles + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmDbVariableSet(FPwmCtrl *pctrl, FPwmDbVariableConfig *db_cfg_p) +{ + FASSERT(pctrl != NULL); + FASSERT(db_cfg_p != NULL); + + FError ret = FPWM_SUCCESS; + + ret = FPwmDbReset(pctrl); + if (ret != FPWM_SUCCESS) + { + FPWM_ERROR("FPwmDbVariableSet FPwmDbReset failed"); + return FPWM_ERR_CMD_FAILED; + } + + FPwmDbRiseCycleSet(pctrl, db_cfg_p->db_rise_cycle); + + FPwmDbFallCycleSet(pctrl, db_cfg_p->db_fall_cycle); + + ret = FPwmDbPolaritySet(pctrl, db_cfg_p->db_polarity_sel); + if (ret != FPWM_SUCCESS) + { + FPWM_ERROR("FPwmDbVariableSet FPwmDbPolaritySet failed"); + return FPWM_ERR_CMD_FAILED; + } + + FPwmDbInModeSet(pctrl, db_cfg_p->db_in_mode); + + FPwmDbOutModeSet(pctrl, db_cfg_p->db_out_mode); + + return ret; +} + +/** + * @name: FPwmDbVariableGet + * @msg: get pwm deadband variable configuration. + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {FPwmDbVariableConfig} *db_cfg_p, pwm deadband config parameters + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmDbVariableGet(FPwmCtrl *pctrl, FPwmDbVariableConfig *db_cfg_p) +{ + FASSERT(pctrl != NULL); + FASSERT(db_cfg_p != NULL); + FError ret = FPWM_SUCCESS; + + uintptr db_base_addr = pctrl->config.db_base_addr; + + u32 db_ctrl = FPWM_READ_REG32(db_base_addr, FPWM_DB_CTRL_OFFSET); + /* db input source*/ + db_cfg_p->db_in_mode = + (db_ctrl & FPWM_DB_CTRL_IN_MODE) ? FPWM_DB_IN_MODE_PWM1 : FPWM_DB_IN_MODE_PWM0; + + /* db polarity select*/ + db_cfg_p->db_polarity_sel = FPWM_DB_CTRL_POLSEL_GET(db_ctrl & FPWM_DB_CTRL_POLSEL_MASK); + /* db output mode*/ + db_cfg_p->db_out_mode = FPWM_DB_CTRL_OUT_MODE_GET(db_ctrl & FPWM_DB_CTRL_OUT_MODE_MASK); + + u32 db_dly = FPWM_READ_REG32(db_base_addr, FPWM_DB_DLY_OFFSET); + /* db falling edge delay cycle */ + db_cfg_p->db_fall_cycle = FPWM_DB_DLY_FALL_GET(db_dly & FPWM_DB_DLY_FALL_MASK); + /* db rising edge delay cycle */ + db_cfg_p->db_rise_cycle = (db_dly & FPWM_DB_DLY_RISE_MASK); + + return ret; + +} + +/** + * @name: FPwmVariableSet + * @msg: set pwm channel variable configuration, users need call this function after + * FPwmDbVariableSet if you want to use deadband function. + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {FPwmVariableConfig} pwm_cfg_p, pwm config parameters, include mode and duty + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmVariableSet(FPwmCtrl *pctrl, u32 channel, FPwmVariableConfig *pwm_cfg_p) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + FASSERT(pwm_cfg_p != NULL); + FError ret = FPWM_SUCCESS; + + /* enable lsd pwm syn */ + FPwmLsdEnable(FLSD_CONFIG_BASE, pctrl->config.instance_id); + + /* bit[0]:set pwm_tim_ctrl SW_RST */ + ret = FPwmReset(pctrl, channel); + if (ret != FPWM_SUCCESS) + { + FPWM_ERROR("FPwmVariableSet FPwmReset failed"); + return FPWM_ERR_CMD_FAILED; + } + + /* pwm timer ctrl disable, before can config */ + FPwmDisable(pctrl, channel); + + /* bit[2]:set tim_ctrl Mode */ + FPwmTimCtrlModeSet(pctrl, channel, pwm_cfg_p->tim_ctrl_mode); + + /* bit[4,5]:set tim_ctrl interrput */ + FPwmTimInterruptEnable(pctrl, channel); + + /*bit[16~27]: set tim_ctrl DIV 0~4095 */ + FPwmDivSet(pctrl, channel, pwm_cfg_p->tim_ctrl_div); + + /*bit[0~15]: set pwm_period */ + FPwmPeriodSet(pctrl, channel, pwm_cfg_p->pwm_period); + + /*bit[2]:pwm control mode, input capture or output compare */ + FPwmCtrlModeSet(pctrl, channel); + + /*bit[3]:pwm control mode irq */ + FPwmInterruptEnable(pctrl, channel, FPWM_INTR_EVENT_COUNTER); + FPwmInterruptEnable(pctrl, channel, FPWM_INTR_EVENT_FIFO_EMPTY); + + /*bit[4~6]:pwm ctrl polarity config CMP:0b100*/ + FPwmPolaritySet(pctrl, channel, pwm_cfg_p->pwm_polarity); + + /*bit[8]:pwm duty source , duty from ccr or fifo */ + FPwmDutySourceSet(pctrl, channel, pwm_cfg_p->pwm_duty_source_mode); + + /*pwm pulse set, duty */ + ret = FPwmPulseSet(pctrl, channel, pwm_cfg_p->pwm_pulse); + if (ret != FPWM_SUCCESS) + { + FPWM_ERROR("FPwmVariableSet FPwmPulseSet failed"); + return FPWM_ERR_CMD_FAILED; + } + + return ret; +} + +/** + * @name: FPwmVariableGet + * @msg: get pwm channel variable configuration. + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {u32} channel, pwm module's channel, 0/1 + * @param {FPwmVariableConfig} *pwm_cfg_p, pwm config parameters, include mode and duty + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmVariableGet(FPwmCtrl *pctrl, u32 channel, FPwmVariableConfig *pwm_cfg_p) +{ + FASSERT(pctrl != NULL); + FASSERT(channel < FPWM_CHANNEL_NUM); + FASSERT(pwm_cfg_p != NULL); + FError ret = FPWM_SUCCESS; + + uintptr pwm_base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + u32 tim_ctrl = FPWM_READ_REG32(pwm_base_addr, FPWM_TIM_CTRL_OFFSET); + /* tim_ctrl mode, counter mode */ + pwm_cfg_p->tim_ctrl_mode = + (tim_ctrl & FPWM_TIM_CTRL_MODE_UD) ? FPWM_UP_DOWN : FPWM_MODULO; + /* pwm divider */ + pwm_cfg_p->tim_ctrl_div = FPWM_TIM_CTRL_DIV_GET(tim_ctrl & FPWM_TIM_CTRL_DIV_MASK); + + /* pwm period value */ + u32 pwm_period = FPWM_READ_REG32(pwm_base_addr, FPWM_PERIOD_OFFSET) ; + pwm_cfg_p->pwm_period = (u16)(pwm_period & FPWM_PERIOD_CCR_MASK); + + u32 pwm_ctrl = FPWM_READ_REG32(pwm_base_addr, FPWM_CTRL_OFFSET); + /* pwm mode, compare output */ + pwm_cfg_p->pwm_mode = + (pwm_ctrl & FPWM_CTRL_MODE_OUTPUT) ? FPWM_OUTPUT_COMPARE : FPWM_NONE_MODE; + + /* pwm compare output polarity */ + pwm_cfg_p->pwm_polarity = FPWM_CTRL_CMP_GET(pwm_ctrl & FPWM_CTRL_CMP_MASK); + + /* pwm duty value source */ + pwm_cfg_p->pwm_duty_source_mode = + (pwm_ctrl & FPWM_CTRL_DUTY_SOURCE_FIFO) ? FPWM_DUTY_FIFO : FPWM_DUTY_CCR; + + /* pwm pulse value */ + u32 pwm_ccr = FPWM_READ_REG32(pwm_base_addr, FPWM_CCR_OFFSET); + pwm_cfg_p->pwm_pulse = (u16)(pwm_ccr & FPWM_CCR_MASK); + + return ret; +} + +/** + * @name: FPwmDeInitialize + * @msg: DeInitialization function for the device instance + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @return {*} + */ +void FPwmDeInitialize(FPwmCtrl *pctrl) +{ + FASSERT(pctrl); + + pctrl->is_ready = 0; + memset(pctrl, 0, sizeof(*pctrl)); + + return; +} + +/** + * @name: FPwmCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @param {FPwmConfig} *input_config_p, Configuration parameters of FPWM + * @return err code information, FPWM_SUCCESS indicates success,others indicates failed + */ +FError FPwmCfgInitialize(FPwmCtrl *pctrl, const FPwmConfig *input_config_p) +{ + FASSERT(pctrl && input_config_p); + + FError ret = FPWM_SUCCESS; + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == pctrl->is_ready) + { + FPWM_WARN("device is already initialized!!!"); + } + + /*Set default values and configuration data */ + FPwmDeInitialize(pctrl); + + pctrl->config = *input_config_p; + + ret = FPwmDbReset(pctrl); + if (ret != FPWM_SUCCESS) + { + FPWM_ERROR("FPwmDbVariableSet FPwmDbReset failed"); + return FPWM_ERR_CMD_FAILED; + } + + pctrl->is_ready = FT_COMPONENT_IS_READY; + + return ret; +} diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm.h b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm.h new file mode 100644 index 0000000000..80e62ae896 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm.h @@ -0,0 +1,220 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpwm.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_FPWM_H +#define BSP_DRIVERS_FPWM_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fdebug.h" +#include "ferror_code.h" +#include "fkernel.h" +#include "fassert.h" +#include "fparameters.h" + +#define FPWM_SUCCESS FT_SUCCESS +#define FPWM_ERR_INVAL_PARM FT_MAKE_ERRCODE(ErrModBsp, ErrBspPwm, 1) +#define FPWM_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspPwm, 2) +#define FPWM_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspPwm, 3) +#define FPWM_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspPwm, 4) +#define FPWM_ERR_CMD_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspPwm, 5) + +typedef enum +{ + FPWM_INTR_EVENT_COUNTER = 0, /**< Handler type for counter interrupt */ + FPWM_INTR_EVENT_FIFO_EMPTY = 1, /**< Handler type for fifo empty interrupt*/ + FPWM_INTR_EVENT_NUM +} FPwmIntrEventType; + +/* duty sel */ +typedef enum +{ + FPWM_DUTY_CCR = 0, /* duty value from pwm ccr register */ + FPWM_DUTY_FIFO = 1, /* duty value from fifo */ + FPWM_DUTY_SEL_MODE_NUM +} FPwmDutySourceMode; + +/* tim_ctrl mode, counter mode */ +typedef enum +{ + FPWM_MODULO = 0, /* count from 0~period */ + FPWM_UP_DOWN = 1, /* count from 0~period~0 */ + FPWM_TIM_CTRL_MODE_NUM +} FPwmTimCtrlMode; + +/* pwm mode, only the compare output mode is supported currently*/ +typedef enum +{ + FPWM_NONE_MODE = 0,/* no mode */ + FPWM_OUTPUT_COMPARE = 1,/* compare output mode */ + FPWM_CTRL_MODE_NUM +} FPwmCtrlMode; + +/** + * enum pwm_polarity - polarity of a PWM compare signal + * @FPWM_POLARITY_NORMAL: a high signal for the duration of the duty- + * cycle, followed by a low signal for the remainder of the pulse + * period + * @FPWM_POLARITY_INVERSED: a low signal for the duration of the duty- + * cycle, followed by a high signal for the remainder of the pulse + * period + */ +typedef enum +{ + FPWM_POLARITY_OUTPUT_HIGH = 0b000, + FPWM_POLARITY_OUTPUT_LOW = 0b001, + FPWM_POLARITY_OUTPUT_FLIP = 0b010, + FPWM_POLARITY_INVERSED = 0b011, + FPWM_POLARITY_NORMAL = 0b100, + FPWM_POLARITY_CCR_LOW = 0b101, + FPWM_POLARITY_CCR_HIGH = 0b110, + FPWM_POLARITY_INIT = 0b111, + FPWM_POLARITY_NUM +} FPwmPolarity; + + +/* db polarity select */ +typedef enum +{ + FPWM_DB_AH = 0, /* no flip */ + FPWM_DB_ALC = 1,/* pwm0 flip */ + FPWM_DB_AHC, /* pwm1 flip */ + FPWM_DB_AL, /* pwm0 and pwm1 flip */ + FPWM_DB_POLARITY_NUM +} FPwmDbPolarity; + +/* db out mode */ +typedef enum +{ + FPWM_DB_OUT_MODE_BYPASS = 0b00, /* by pass */ + FPWM_DB_OUT_MODE_FORBID_RISE = 0b01,/* forbid rise delay */ + FPWM_DB_OUT_MODE_FORBID_FALL = 0b10,/* forbid fall delay */ + FPWM_DB_OUT_MODE_ENABLE_RISE_FALL = 0b11,/* enable rise and fall delay */ + FPWM_DB_OUT_MODE_NUM +} FPwmDbOutMode; + +/* db input source select, channel 0 or 1 */ +typedef enum +{ + FPWM_DB_IN_MODE_PWM0 = 0,/* db input source choose pwm0 */ + FPWM_DB_IN_MODE_PWM1 = 1,/* db input source choose pwm1 */ + FPWM_DB_IN_MODE_NUM +} FPwmDbInMode; + +typedef struct +{ + FPwmDbPolarity db_polarity_sel;/* db polarity select*/ + FPwmDbOutMode db_out_mode;/* db output mode*/ + FPwmDbInMode db_in_mode;/* db input source*/ + u16 db_fall_cycle;/* db falling edge delay cycle */ + u16 db_rise_cycle;/* db rising edge delay cycle */ +} FPwmDbVariableConfig; + +typedef struct +{ + FPwmTimCtrlMode tim_ctrl_mode;/* tim_ctrl mode, counter mode */ + u16 tim_ctrl_div;/* pwm divider */ + u16 pwm_period;/* pwm period value */ + FPwmCtrlMode pwm_mode;/* pwm mode, compare output */ + FPwmPolarity pwm_polarity;/* pwm compare output polarity */ + FPwmDutySourceMode pwm_duty_source_mode;/* pwm duty value source */ + u16 pwm_pulse;/* pwm pulse value */ + +} FPwmVariableConfig; + +typedef struct +{ + u8 instance_id;/* pwm id */ + uintptr db_base_addr; + uintptr pwm_base_addr; + + u64 base_clk; + u32 irq_num[FPWM_CHANNEL_NUM]; /* pwm irq num */ + u32 irq_prority[FPWM_CHANNEL_NUM]; /* pwm irq priority */ + const char *instance_name;/* instance name */ + +} FPwmConfig; /* Pwm配置 */ + +typedef void (*FPwmIntrEventHandler)(void *param); + +typedef struct +{ + FPwmConfig config;/* Pwm配置 */ + u32 is_ready;/* Pwm初始化完成标志 */ + + u8 channel_ctrl_enable[FPWM_CHANNEL_NUM]; /* pwm channel ctrl enable state */ + + FPwmIntrEventHandler event_handler[FPWM_INTR_EVENT_NUM]; /* event handler for interrupt */ + void *event_param[FPWM_INTR_EVENT_NUM]; /* parameters ptr of event handler */ + +} FPwmCtrl; + + +/* interrupt handler function */ +void FPwmIntrHandler(s32 vector, void *args); + +/* register the handler function */ +void FPwmRegisterInterruptHandler(FPwmCtrl *instance_p, FPwmIntrEventType event_type, FPwmIntrEventHandler handler, void *param); + +/* get pwm configs by id */ +const FPwmConfig *FPwmLookupConfig(FPwmInstance instance_id); + +/* DeInitialization function for the device instance */ +void FPwmDeInitialize(FPwmCtrl *pctrl); + +/*Initializes a specific instance such that it is ready to be used*/ +FError FPwmCfgInitialize(FPwmCtrl *pctrl, const FPwmConfig *input_config_p); + +/* set pwm db configuration */ +FError FPwmDbVariableSet(FPwmCtrl *pctrl, FPwmDbVariableConfig *db_cfg_p); + +/* get pwm db configuration */ +FError FPwmDbVariableGet(FPwmCtrl *pctrl, FPwmDbVariableConfig *db_cfg_p); + +/* set pwm channel configuration */ +FError FPwmVariableSet(FPwmCtrl *pctrl, u32 channel, FPwmVariableConfig *pwm_cfg_p); + +/* get pwm channel configuration */ +FError FPwmVariableGet(FPwmCtrl *pctrl, u32 channel, FPwmVariableConfig *pwm_cfg_p); + +/* config pwm pulse, pwm_ccr is less than pwm_period */ +FError FPwmPulseSet(FPwmCtrl *pctrl, u32 channel, u16 pwm_ccr); + +/* disable pwm */ +void FPwmDisable(FPwmCtrl *pctrl, u32 channel); + +/* enable pwm */ +void FPwmEnable(FPwmCtrl *pctrl, u32 channel); + +/* dump some pwm registers value */ +void FPwmDump(uintptr base_addr); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_g.c b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_g.c new file mode 100644 index 0000000000..b1bcc554e7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_g.c @@ -0,0 +1,129 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpwm_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fparameters.h" +#include "fpwm.h" +#include "fpwm_hw.h" + +/* default configs of pwm ctrl */ +const FPwmConfig FPwmConfigTbl[FPWM_INSTANCE_NUM] = +{ + [FPWM_INSTANCE_0] = + { + .instance_id = FPWM_INSTANCE_0, + .db_base_addr = FPWM0_BASE_ADR, + .pwm_base_addr = FPWM0_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM0_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM1_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL0", + }, + [FPWM_INSTANCE_1] = + { + .instance_id = FPWM_INSTANCE_1, + .db_base_addr = FPWM1_BASE_ADR, + .pwm_base_addr = FPWM1_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM2_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM3_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL1", + }, + [FPWM_INSTANCE_2] = + { + .instance_id = FPWM_INSTANCE_2, + .db_base_addr = FPWM2_BASE_ADR, + .pwm_base_addr = FPWM2_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM4_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM5_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL2", + }, + [FPWM_INSTANCE_3] = + { + .instance_id = FPWM_INSTANCE_3, + .db_base_addr = FPWM3_BASE_ADR, + .pwm_base_addr = FPWM3_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM6_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM7_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL3", + }, + [FPWM_INSTANCE_4] = + { + .instance_id = FPWM_INSTANCE_4, + .db_base_addr = FPWM4_BASE_ADR, + .pwm_base_addr = FPWM4_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM8_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM9_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL4", + }, + [FPWM_INSTANCE_5] = + { + .instance_id = FPWM_INSTANCE_5, + .db_base_addr = FPWM5_BASE_ADR, + .pwm_base_addr = FPWM5_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM10_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM11_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL5", + }, + [FPWM_INSTANCE_6] = + { + .instance_id = FPWM_INSTANCE_6, + .db_base_addr = FPWM6_BASE_ADR, + .pwm_base_addr = FPWM6_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM12_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM13_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL6", + }, + [FPWM_INSTANCE_7] = + { + .instance_id = FPWM_INSTANCE_7, + .db_base_addr = FPWM7_BASE_ADR, + .pwm_base_addr = FPWM7_BASE_ADR + FPWM_OFFSET, + .base_clk = FPWM_CLK, + .irq_num[FPWM_CHANNEL_0] = FPWM14_INTR_IRQ, + .irq_num[FPWM_CHANNEL_1] = FPWM15_INTR_IRQ, + .irq_prority[FPWM_CHANNEL_0] = 0, + .irq_prority[FPWM_CHANNEL_1] = 0, + .instance_name = "PWM_CTRL7", + }, + + +}; \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_hw.c b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_hw.c new file mode 100644 index 0000000000..33bce2b6c1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_hw.c @@ -0,0 +1,103 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpwm_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include +#include "fparameters.h" +#include "fpwm_hw.h" +#include "fassert.h" + +/** + * @name: FPwmLsdEnable + * @msg: enable pwm lsd syn + * @param {uintptr} lsd_addr, base address of the lsd_pwm_syn + * @param {u8} pwm_id, pwm id parameters of FPWM + * @return + */ +void FPwmLsdEnable(uintptr lsd_addr, u8 pwm_id) +{ + FASSERT(pwm_id < FPWM_INSTANCE_NUM); + u32 reg_val = 0; + + reg_val = FPWM_READ_REG32(lsd_addr, FLSD_MIO_PWM_SYN_OFFSET); + + reg_val |= (FLSD_MIO_PWM_SYN_MASK & (1 << pwm_id)); + + FPWM_WRITE_REG32(lsd_addr, FLSD_MIO_PWM_SYN_OFFSET, reg_val); +} + +/** + * @name: FPwmLsdDisable + * @msg: disable pwm lsd syn + * @param {uintptr} lsd_addr, base address of the lsd_pwm_syn + * @param {u8} pwm_id, pwm id parameters of FPWM + * @return + */ +void FPwmLsdDisable(uintptr lsd_addr, u8 pwm_id) +{ + FASSERT(pwm_id < FPWM_INSTANCE_NUM); + u32 reg_val = 0; + + reg_val = FPWM_READ_REG32(lsd_addr, FLSD_MIO_PWM_SYN_OFFSET); + + reg_val &= (~(FLSD_MIO_PWM_SYN_MASK & (1 << pwm_id))); + + FPWM_WRITE_REG32(lsd_addr, FLSD_MIO_PWM_SYN_OFFSET, reg_val); +} + + +/** + * @name: FPwmDump + * @msg: dump some pwm registers value. + * @param {FPwmCtrl} *pctrl, instance of FPWM controller + * @return + */ +void FPwmDump(uintptr base_addr) +{ + uintptr db_base_addr = base_addr; + uintptr pwm_base_addr = base_addr + FPWM_OFFSET; + + printf("Off[0x%x]: FPWM_DB_CTRL_OFFSET = 0x%08x\r\n", db_base_addr + FPWM_DB_CTRL_OFFSET, FPWM_READ_REG32(db_base_addr, FPWM_DB_CTRL_OFFSET)); + printf("Off[0x%x]: FPWM_DB_DLY_OFFSET = 0x%08x\r\n", db_base_addr + FPWM_DB_DLY_OFFSET, FPWM_READ_REG32(db_base_addr, FPWM_DB_DLY_OFFSET)); + printf("\r\n"); + printf("Off[0x%x]: FPWM_TIM_CNT_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_TIM_CNT_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_TIM_CNT_OFFSET)); + printf("Off[0x%x]: FPWM_TIM_CTRL_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_TIM_CTRL_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_TIM_CTRL_OFFSET)); + printf("Off[0x%x]: FPWM_STATE_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_STATE_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_STATE_OFFSET)); + printf("Off[0x%x]: FPWM_PERIOD_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_PERIOD_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_PERIOD_OFFSET)); + printf("Off[0x%x]: FPWM_CTRL_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_CTRL_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_CTRL_OFFSET)); + printf("Off[0x%x]: FPWM_CCR_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_CCR_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_CCR_OFFSET)); + + pwm_base_addr = pwm_base_addr + FPWM_OFFSET; + printf("\r\n"); + printf("Off[0x%x]: FPWM_TIM_CNT_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_TIM_CNT_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_TIM_CNT_OFFSET)); + printf("Off[0x%x]: FPWM_TIM_CTRL_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_TIM_CTRL_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_TIM_CTRL_OFFSET)); + printf("Off[0x%x]: FPWM_STATE_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_STATE_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_STATE_OFFSET)); + printf("Off[0x%x]: FPWM_PERIOD_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_PERIOD_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_PERIOD_OFFSET)); + printf("Off[0x%x]: FPWM_CTRL_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_CTRL_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_CTRL_OFFSET)); + printf("Off[0x%x]: FPWM_CCR_OFFSET = 0x%08x\r\n", pwm_base_addr + FPWM_CCR_OFFSET, FPWM_READ_REG32(pwm_base_addr, FPWM_CCR_OFFSET)); + + + printf("Off[0x%x]: FPWM_LSD_OFFSET = 0x%08x\r\n", FLSD_CONFIG_BASE + FLSD_MIO_PWM_SYN_OFFSET, FPWM_READ_REG32(FLSD_CONFIG_BASE, FLSD_MIO_PWM_SYN_OFFSET)); + + printf("\r\n"); + +} diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_hw.h b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_hw.h new file mode 100644 index 0000000000..c1efe992bd --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_hw.h @@ -0,0 +1,143 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpwm_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_FPWM_HW_H +#define BSP_DRIVERS_FPWM_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fkernel.h" +#include "ftypes.h" +#include "fio.h" +#include "fparameters.h" + +/* pwm register definitions */ +#define FPWM_BASE_ADR(n) ((FPWM_CONTROL_BASE)+(n<<12)) /* 0<=n<=7 */ + +#define FPWM0_BASE_ADR FPWM_BASE_ADR(0) /* PWM 0 base address */ +#define FPWM1_BASE_ADR FPWM_BASE_ADR(1) /* PWM 1 base address */ +#define FPWM2_BASE_ADR FPWM_BASE_ADR(2) +#define FPWM3_BASE_ADR FPWM_BASE_ADR(3) +#define FPWM4_BASE_ADR FPWM_BASE_ADR(4) +#define FPWM5_BASE_ADR FPWM_BASE_ADR(5) +#define FPWM6_BASE_ADR FPWM_BASE_ADR(6) +#define FPWM7_BASE_ADR FPWM_BASE_ADR(7) + +/* DB register */ +#define FPWM_DB_CTRL_OFFSET 0x00 +#define FPWM_DB_DLY_OFFSET 0x04 +#define FPWM_OFFSET 0x400 +#define FPWM_TIM_CNT_OFFSET 0x00 +#define FPWM_TIM_CTRL_OFFSET 0x04 +#define FPWM_STATE_OFFSET 0x08 +#define FPWM_PERIOD_OFFSET 0x0C +#define FPWM_CTRL_OFFSET 0x10 +#define FPWM_CCR_OFFSET 0x14 + +#define FPWM_MODE_CHANNEL 2 +#define FPWM_N(x) ((FPWM_OFFSET)*(x)) + +#define FPWM_RESET_TIMEOUT 10 + +#define NSEC_PER_SEC (1000000000ULL) + +/* pwm db_ctrl field */ +#define FPWM_DB_CTRL_RESET BIT(0) +#define FPWM_DB_CTRL_IN_MODE BIT(1) +#define FPWM_DB_CTRL_POLSEL(data) ((data) << 2) +#define FPWM_DB_CTRL_POLSEL_MASK GENMASK(3, 2) +#define FPWM_DB_CTRL_POLSEL_GET(data) ((data) >> 2) +#define FPWM_DB_CTRL_OUT_MODE(data) ((data) << 4) +#define FPWM_DB_CTRL_OUT_MODE_MASK GENMASK(5, 4) +#define FPWM_DB_CTRL_OUT_MODE_GET(data) ((data) >> 4) + +/* pwm db_ctrl field */ +#define FPWM_DB_DLY_MAX 1024 +#define FPWM_DB_DLY_RISE_MASK GENMASK(9, 0) +#define FPWM_DB_DLY_FALL_MASK GENMASK(19, 10) +#define FPWM_DB_DLY_FALL(data) ((data) << 10) +#define FPWM_DB_DLY_FALL_GET(data) ((data) >> 10) + +/* pwm tim_ctrl field */ +#define FPWM_TIM_CTRL_DIV_MAX 4096 + +#define FPWM_TIM_CTRL_RESET BIT(0) +#define FPWM_TIM_CTRL_ENABLE BIT(1) +#define FPWM_TIM_CTRL_MODE_UD BIT(2) /* mode, modulo or up-and-down */ +#define FPWM_TIM_CTRL_OVFIF_ENABLE BIT(4) /* counter-overflow intr enable */ +#define FPWM_TIM_CTRL_GIE BIT(5) /* overall intr enable */ +#define FPWM_TIM_CTRL_DIV(data) ((data) << 16) +#define FPWM_TIM_CTRL_DIV_MASK GENMASK(27, 16) +#define FPWM_TIM_CTRL_DIV_GET(data) ((data) >> 16) + +/* pwm_state field */ +#define FPWM_STATE_COUNTER_CLEAR BIT(0) +#define FPWM_STATE_OVFIF_COUNTER BIT(1) +#define FPWM_STATE_FIFO_EMPTY BIT(2) +#define FPWM_STATE_FIFO_FULL BIT(3) + +/* pwm_period field */ +#define FPWM_PERIOD_CCR_MASK GENMASK(15, 0) + +/* pwm_ctrl field */ +#define FPWM_CTRL_MODE_OUTPUT BIT(2) +#define FPWM_CTRL_INTR_COUNTER_ENABLE BIT(3) +#define FPWM_CTRL_CMP(data) ((data) << 4) +#define FPWM_CTRL_CMP_MASK GENMASK(6, 4) +#define FPWM_CTRL_CMP_GET(data) ((data) >> 4) +#define FPWM_CTRL_DUTY_SOURCE_FIFO BIT(8) +#define FPWM_CTRL_INTR_FIFO_EMPTY_ENABLE BIT(9) + +/* pwm_ccr field */ +#define FPWM_CCR_MASK GENMASK(15, 0) + +/* pwm lsd cfg, lsd pwm sync control */ +#define FLSD_MIO_PWM_SYN_OFFSET 0x20 +#define FLSD_MIO_PWM_SYN_MASK GENMASK(7, 0) + +/***************** Macros (Inline Functions) Definitions *********************/ + +/* 读FPWM寄存器 */ +#define FPWM_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)reg_offset) + +/* 写FPWM寄存器 */ +#define FPWM_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)reg_offset, (u32)reg_value) + +#define FPWM_SETBIT(base_addr, reg_offset, data) FtSetBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FPWM_CLEARBIT(base_addr, reg_offset, data) FtClearBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +/* enable pwm lsd syn */ +void FPwmLsdEnable(uintptr lsd_addr, u8 pwm_id); + +/* disable pwm lsd syn */ +void FPwmLsdDisable(uintptr lsd_addr, u8 pwm_id); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_intr.c b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_intr.c new file mode 100644 index 0000000000..2439328f5f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_intr.c @@ -0,0 +1,103 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpwm_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "fparameters.h" +#include "fassert.h" +#include "finterrupt.h" +#include "fpwm.h" +#include "fpwm_hw.h" + +#define FT_PWM_DEBUG_TAG "FT_PWM_INTR" +#define FPWM_DEBUG(format, ...) FT_DEBUG_PRINT_D(FT_PWM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPWM_INFO(format, ...) FT_DEBUG_PRINT_I(FT_PWM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPWM_WARN(format, ...) FT_DEBUG_PRINT_W(FT_PWM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FPWM_ERROR(format, ...) FT_DEBUG_PRINT_E(FT_PWM_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FPWM_CALL_INTR_EVENT_HANDLDER(instance_p, event) \ + if (instance_p->event_handler[event]) \ + instance_p->event_handler[event](instance_p->event_param[event]) + +/** + * @name: FPwmRegisterInterruptHandler + * @msg: register FPwm interrupt handler function + * @param {FPwm} *instance_p, pointer to the pwm instance + * @param {FPwmIntrEvtType} event_type, interrupt event type + * @param {FPwmEvtHandler} handler, interrupt event handler + * @param {void} *param, contains a pointer to the driver instance + * @return {*} + */ +void FPwmRegisterInterruptHandler(FPwmCtrl *instance_p, FPwmIntrEventType event_type, FPwmIntrEventHandler handler, void *param) +{ + FASSERT(instance_p); + FASSERT(event_type < FPWM_INTR_EVENT_NUM); + instance_p->event_handler[event_type] = handler; + instance_p->event_param[event_type] = param; +} + +/** + * @name: FPwmIntrHandler + * @msg: This function is the interrupt handler for the driver. + * It must be connected to an interrupt system by the application such that it + * can be called when an interrupt occurs. + * @param vector Irq num ,Don't need attention . + * @param args contains a pointer to the driver instance + */ +void FPwmIntrHandler(s32 vector, void *args) +{ + u32 status; + static int i = 0; + FPwmCtrl *pctrl = (FPwmCtrl *)args; + + FASSERT(pctrl != NULL); + FASSERT(pctrl->is_ready == FT_COMPONENT_IS_READY); + uintptr pwm_base_addr = 0; + u8 channel = 0; + + for (channel = 0; channel < FPWM_MODE_CHANNEL; channel++) + { + pwm_base_addr = pctrl->config.pwm_base_addr + FPWM_N(channel); + + status = FPWM_READ_REG32(pwm_base_addr, FPWM_CTRL_OFFSET); + if (!(status & (FPWM_CTRL_INTR_COUNTER_ENABLE | FPWM_CTRL_INTR_FIFO_EMPTY_ENABLE))) + continue; + + status = FPWM_READ_REG32(pwm_base_addr, FPWM_STATE_OFFSET); + if (0 == status) + continue; + + /* Check for the type of error interrupt and Processing it */ + if (status & FPWM_STATE_OVFIF_COUNTER) + { + status &= (~FPWM_STATE_OVFIF_COUNTER); + FPWM_SETBIT(pwm_base_addr, FPWM_STATE_OFFSET, FPWM_STATE_COUNTER_CLEAR); + FPWM_CALL_INTR_EVENT_HANDLDER(pctrl, FPWM_INTR_EVENT_COUNTER); + } + + if (status & FPWM_STATE_FIFO_EMPTY) + { + FPWM_SETBIT(pwm_base_addr, FPWM_STATE_OFFSET, FPWM_STATE_FIFO_EMPTY); + FPWM_CALL_INTR_EVENT_HANDLDER(pctrl, FPWM_INTR_EVENT_FIFO_EMPTY); + } + } + +} + diff --git a/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_sinit.c b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_sinit.c new file mode 100644 index 0000000000..a4d13ec00b --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/pwm/fpwm/fpwm_sinit.c @@ -0,0 +1,66 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpwm_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ + +#include "fpwm.h" +#include "fparameters.h" +#include "fassert.h" + +extern FPwmConfig FPwmConfigTbl[FPWM_INSTANCE_NUM]; + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + +/** + * @name: FPwmLookupConfig + * @msg: get pwm configs by id + * @return {*} + * @param {u32} instanceId, id of pwm ctrl + */ +const FPwmConfig *FPwmLookupConfig(FPwmInstance instance_id) +{ + const FPwmConfig *pconfig = NULL; + FASSERT(instance_id < FPWM_INSTANCE_NUM); + + u32 index = 0; + + for (index = 0; index < (u32)FPWM_INSTANCE_NUM; index++) + { + if (FPwmConfigTbl[index].instance_id == instance_id) + { + pconfig = &FPwmConfigTbl[index]; + break; + } + } + + return (FPwmConfig *)pconfig; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/Kconfig b/bsp/phytium/libraries/standalone/drivers/qspi/Kconfig new file mode 100644 index 0000000000..a16b375482 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/Kconfig @@ -0,0 +1,8 @@ +menu "Qspi Configuration" + config USE_FQSPI + bool + prompt "Use FQSPI" + default n + +endmenu + diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi.c b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi.c new file mode 100644 index 0000000000..fc42e8535d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi.c @@ -0,0 +1,312 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-03-28 09:00:41 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 wangxiaodong 2021.11.12 re-construct + * 1.2 wangxiaodong 2022.3.27 re-construct + */ + +#include +#include "fkernel.h" +#include "fassert.h" +#include "fqspi.h" +#include "fqspi_hw.h" +#include "fsleep.h" + +#define FQSPI_DEBUG_TAG "FQSPI" +#define FQSPI_ERROR(format, ...) FT_DEBUG_PRINT_E(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_WARN(format, ...) FT_DEBUG_PRINT_W(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_INFO(format, ...) FT_DEBUG_PRINT_I(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_DEBUG(format, ...) FT_DEBUG_PRINT_D(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) + + +/** + * @name: FQspiCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {FQspiConfig} *input_config_p, Configuration parameters of FQSPI + * @return err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiCfgInitialize(FQspiCtrl *pctrl, const FQspiConfig *input_config_p) +{ + FASSERT(pctrl && input_config_p); + + FError ret = FQSPI_SUCCESS; + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == pctrl->is_ready) + { + FQSPI_WARN("device is already initialized!!!"); + } + + /*Set default values and configuration data */ + FQspiDeInitialize(pctrl); + + pctrl->config = *input_config_p; + + pctrl->is_ready = FT_COMPONENT_IS_READY; + + return ret; +} + +/** + * @name: FQspiDeInitialize + * @msg: DeInitialization function for the device instance + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return {*} + */ +void FQspiDeInitialize(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + + pctrl->is_ready = 0; + memset(pctrl, 0, sizeof(*pctrl)); + + return; +} + +/** + * @name: FQspiSetCapacityAndNum + * @msg: Initializes the capacity and number of flash connect to specific instance. + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return void + */ +void FQspiSetCapacityAndNum(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + u32 reg_val = 0; + FQspiConfig *config_p = &pctrl->config; + uintptr base_addr = pctrl->config.base_addr; + + switch (config_p->capacity) + { + case FQSPI_FLASH_CAP_4MB: + pctrl->flash_size = SZ_4M; + break; + case FQSPI_FLASH_CAP_8MB: + pctrl->flash_size = SZ_8M; + break; + case FQSPI_FLASH_CAP_16MB: + pctrl->flash_size = SZ_16M; + break; + case FQSPI_FLASH_CAP_32MB: + pctrl->flash_size = SZ_32M; + break; + case FQSPI_FLASH_CAP_64MB: + pctrl->flash_size = SZ_64M; + break; + case FQSPI_FLASH_CAP_128MB: + pctrl->flash_size = SZ_128M; + break; + case FQSPI_FLASH_CAP_256MB: + pctrl->flash_size = SZ_256M; + break; + default: + pctrl->flash_size = SZ_4M; + break; + } + + /* Write flash capacity and numbers information to qspi Capacity register */ + reg_val = (FQSPI_CAP_FLASH_NUM_MASK & FQSPI_CAP_FLASH_NUM(config_p->dev_num)) | + (FQSPI_CAP_FLASH_CAP_MASK & FQSPI_CAP_FLASH_CAP(config_p->capacity)); + + /*write value to flash capacity register 0x00 */ + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_CAP_OFFSET, reg_val); + +} + + +/** + * @name: FQspiRdCfgConfig + * @msg: config read config register + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiRdCfgConfig(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + u32 cmd_reg = 0; + uintptr base_addr = pctrl->config.base_addr; + + FQspiRdCfgDef rd_config = pctrl->rd_cfg; + + cmd_reg |= FQSPI_RD_CFG_CMD(rd_config.rd_cmd); + cmd_reg |= FQSPI_RD_CFG_THROUGH(rd_config.rd_through); + cmd_reg |= FQSPI_RD_CFG_TRANSFER(rd_config.rd_transfer); + cmd_reg |= FQSPI_RD_CFG_ADDR_SEL(rd_config.rd_addr_sel); + cmd_reg |= FQSPI_RD_CFG_LATENCY(rd_config.rd_latency); + cmd_reg |= FQSPI_RD_CFG_MODE_BYTE(rd_config.mode_byte); + + if ((rd_config.mode_byte) || (rd_config.cmd_sign == 0)) + { + cmd_reg |= FQSPI_RD_CFG_CMD_SIGN(rd_config.cmd_sign); + } + else + { + FQSPI_ERROR("rd_cfg mode_byte disable !!!"); + return FQSPI_INVAL_PARAM; + } + + if ((rd_config.rd_latency == FQSPI_CMD_LATENCY_ENABLE) || (rd_config.dummy == 0)) + { + rd_config.dummy = rd_config.dummy ? rd_config.dummy : 1; + cmd_reg |= FQSPI_RD_CFG_DUMMY(rd_config.dummy); + } + else + { + FQSPI_ERROR("rd_cfg latency disable !!!"); + return FQSPI_INVAL_PARAM; + } + + cmd_reg |= FQSPI_RD_CFG_D_BUFFER(rd_config.d_buffer); + cmd_reg |= FQSPI_RD_CFG_SCK_SEL(rd_config.rd_sck_sel); + + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_RD_CFG_OFFSET, cmd_reg); + + return ret; +} + +/** + * @name: FQspiWrCfgConfig + * @msg: config write config register + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiWrCfgConfig(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + u32 cmd_reg = 0; + uintptr base_addr = pctrl->config.base_addr; + + FQspiWrCfgDef wr_config = pctrl->wr_cfg; + + cmd_reg |= FQSPI_WR_CFG_CMD(wr_config.wr_cmd); + cmd_reg |= FQSPI_WR_CFG_WAIT(wr_config.wr_wait); + cmd_reg |= FQSPI_WR_CFG_THROUGH(wr_config.wr_through); + cmd_reg |= FQSPI_WR_CFG_TRANSFER(wr_config.wr_transfer); + cmd_reg |= FQSPI_WR_CFG_ADDRSEL(wr_config.wr_addr_sel); + cmd_reg |= FQSPI_WR_CFG_MODE(wr_config.wr_mode); + cmd_reg |= FQSPI_WR_CFG_SCK_SEL(wr_config.wr_sck_sel); + + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_WR_CFG_OFFSET, cmd_reg); + + return ret; +} + + +/** + * @name: FQspiCommandPortConfig + * @msg: config command port register + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiCommandPortConfig(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + u32 cmd_reg = 0; + uintptr base_addr = pctrl->config.base_addr; + + FQspiCommandPortDef cmd_port_config = pctrl->cmd_def; + + cmd_reg |= FQSPI_CMD_PORT_CMD_MASK & FQSPI_CMD_PORT_CMD(cmd_port_config.cmd); + + cmd_reg |= FQSPI_CMD_PORT_WAIT(cmd_port_config.wait); + + cmd_reg |= FQSPI_CMD_PORT_THROUGH(cmd_port_config.through); + + cmd_reg |= FQSPI_CMD_PORT_CS_MASK & FQSPI_CMD_PORT_CS(cmd_port_config.cs); + + cmd_reg |= FQSPI_CMD_PORT_TRANSFER(cmd_port_config.transfer); + + cmd_reg |= FQSPI_CMD_PORT_CMD_ADDR(cmd_port_config.cmd_addr); + + cmd_reg |= FQSPI_CMD_PORT_LATENCY(cmd_port_config.latency); + + cmd_reg |= FQSPI_CMD_PORT_DATA_TRANS(cmd_port_config.data_transfer); + + cmd_reg |= FQSPI_CMD_PORT_ADDR_SEL(cmd_port_config.addr_sel); + + if ((cmd_port_config.latency == FQSPI_CMD_LATENCY_ENABLE) || (cmd_port_config.dummy == 0)) + { + cmd_port_config.dummy = cmd_port_config.dummy ? cmd_port_config.dummy : 1; + cmd_reg |= FQSPI_CMD_PORT_DUMMY(cmd_port_config.dummy); + } + else + { + FQSPI_ERROR("cmd_port latency disable !!!"); + return FQSPI_INVAL_PARAM; + } + + cmd_reg |= FQSPI_CMD_PORT_P_BUFFER(cmd_port_config.p_buffer); + + /* read data num */ + cmd_reg |= FQSPI_CMD_PORT_RW_NUM_MASK & FQSPI_CMD_PORT_RW_NUM(cmd_port_config.rw_num); + + cmd_reg |= FQSPI_CMD_PORT_CLK_SEL_MASK & FQSPI_CMD_PORT_CLK_SEL(cmd_port_config.sck_sel); + + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_CMD_PORT_OFFSET, cmd_reg); + + return ret; +} + + +/** + * @name: FQspiChannelSet + * @msg: config qspi cs num + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {FQspiChipCS} channel, cs number + * @return + */ +void FQspiChannelSet(FQspiCtrl *pctrl, FQspiChipCS channel) +{ + FASSERT(pctrl); + FASSERT(channel < FQSPI_CS_NUM); + pctrl->config.channel = channel; +} + +/** + * @name: FQspiCsTimingSet + * @msg: config qspi cs timing + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {FQspiCsTimingCfgDef} cs_timing_cfg, cs timing + * @return err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +void FQspiCsTimingSet(FQspiCtrl *pctrl, FQspiCsTimingCfgDef *cs_timing_cfg) +{ + FASSERT(pctrl); + u32 cmd_reg = 0; + uintptr base_addr = pctrl->config.base_addr; + + cmd_reg |= FQSPI_FUN_SET_CS_HOLD(cs_timing_cfg->cs_hold); + + cmd_reg |= FQSPI_FUN_SET_CS_SETUP(cs_timing_cfg->cs_setup); + + cmd_reg |= FQSPI_FUN_SET_CS_DELAY(cs_timing_cfg->cs_delay); + + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_CS_TIMING_SET_OFFSET, cmd_reg); + +} diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi.h b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi.h new file mode 100644 index 0000000000..407187ec26 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi.h @@ -0,0 +1,238 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:00:55 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 wangxiaodong 2021.11.12 re-construct + */ + +#ifndef BSP_DRIVERS_FQSPI_H +#define BSP_DRIVERS_FQSPI_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fkernel.h" +#include "ftypes.h" +#include "ferror_code.h" +#include "fdebug.h" +#include "fparameters.h" + +#define FQSPI_SUCCESS FT_SUCCESS +#define FQSPI_INVAL_PARAM FT_MAKE_ERRCODE(ErrModBsp, ErrBspQSpi, 1) +#define FQSPI_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspQSpi, 2) +#define FQSPI_NOT_ALLIGN FT_MAKE_ERRCODE(ErrModBsp, ErrBspQSpi, 3) +#define FQSPI_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspQSpi, 4) +#define FQSPI_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspQSpi, 5) + +/* FQSPI Transfer mode, command-addr-data protocols */ +typedef enum +{ + FQSPI_TRANSFER_1_1_1 = 0x0, + FQSPI_TRANSFER_1_1_2 = 0x1, + FQSPI_TRANSFER_1_1_4 = 0x2, + FQSPI_TRANSFER_1_2_2 = 0x3, + FQSPI_TRANSFER_1_4_4 = 0x4, + FQSPI_TRANSFER_2_2_2 = 0x5, + FQSPI_TRANSFER_4_4_4 = 0x6 +} FQspiTransferMode; + +/* FQSPI Flash Capcity type */ +typedef enum +{ + FQSPI_FLASH_CAP_4MB = 0b000, + FQSPI_FLASH_CAP_8MB = 0b001, + FQSPI_FLASH_CAP_16MB = 0b010, + FQSPI_FLASH_CAP_32MB = 0b011, + FQSPI_FLASH_CAP_64MB = 0b100, + FQSPI_FLASH_CAP_128MB = 0b101, + FQSPI_FLASH_CAP_256MB = 0b110, +} FQspiFlashCapcityType; + +/* FQSPI pclk divider type */ +typedef enum +{ + FQSPI_SCK_DIV_128 = 0x0, + FQSPI_SCK_DIV_2 = 0x1, + FQSPI_SCK_DIV_4 = 0x2, + FQSPI_SCK_DIV_8 = 0x3, + FQSPI_SCK_DIV_16 = 0x4, + FQSPI_SCK_DIV_32 = 0x5, + FQSPI_SCK_DIV_64 = 0x6 +} FQspiSckDivType; + +/* FQSPI Address type */ +typedef enum +{ + FQSPI_ADDR_SEL_3 = 0x0, + FQSPI_ADDR_SEL_4 = 0x1 +} FQspiAddrType; + +/* Specifies if the Instruction need transfer address */ +typedef enum +{ + FQSPI_CMD_ADDR_DISABLE = 0x0, + FQSPI_CMD_ADDR_ENABLE = 0x1 +} FQspiCmdAddrType; + +/* Specifies if the Instruction have latency */ +typedef enum +{ + FQSPI_CMD_LATENCY_DISABLE = 0x0, + FQSPI_CMD_LATENCY_ENABLE = 0x1 +} FQspiCmdLatencyType; + +/* Specifies if the Instruction need transfer data */ +typedef enum +{ + FQSPI_CMD_DATA_DISABLE = 0x0, + FQSPI_CMD_DATA_ENABLE = 0x1 +} FQspiCmdDataType; + +/* Specifies if the Instruction use buffer */ +typedef enum +{ + FQSPI_USE_BUFFER_DISABLE = 0x0, + FQSPI_USE_BUFFER_ENABLE = 0x1 +} FQspiUseBufferType; + +/* Specifies if the Instruction need some execution time */ +typedef enum +{ + FQSPI_WAIT_DISABLE = 0x0, + FQSPI_WAIT_ENABLE = 0x1 +} FQspiWaitType; + + +typedef enum +{ + FQSPI_XIP_EXIT = 0x0, + FQSPI_XIP_ENTER = 0x1 +} FQspiXIPState; + +typedef struct +{ + u32 instance_id; /* Id of device */ + uintptr base_addr; /* Base address of qspi */ + uintptr mem_start; /* Start address of qspi memory */ + u32 capacity; /* Flash capacity */ + u32 dev_num; /* Qspi device number */ + u32 channel; /* channel number, cs number */ +} FQspiConfig; + +/* rd_cfg register */ +typedef struct +{ + u8 rd_cmd : 8; /* Specifies the Instruction to be sent */ + u8 rd_through : 1; + u8 rd_transfer : 3;/* Specifies the Instruction tranfer Mode 1-1-1~4-4-4*/ + u8 rd_addr_sel : 1;/* Specifies the Instruction addr mode 3 byte addr or 4 byte addr*/ + u8 rd_latency : 1; /* Specifies if the Instruction need read latency*/ + u8 mode_byte : 1; /* Specifies if the Instruction need modifier*/ + u8 cmd_sign : 8; /* Specifies the Instruction modifier*/ + u8 dummy : 5; /* Specifies the Number of Dummy Cycles.*/ + u8 d_buffer : 1; /* Specifies if the Instruction use buffer to read data*/ + u8 rd_sck_sel : 3; /* Specifies the pclk division .*/ +} FQspiRdCfgDef; + +/* wr_cfg register */ +typedef struct +{ + u8 wr_cmd : 8; /* Specifies the Instruction to be sent */ + u16 reserved : 14; + u8 wr_wait : 1; + u8 wr_through : 1; + u8 wr_transfer : 3;/* Specifies the Instruction tranfer Mode 1-1-1~4-4-4*/ + u8 wr_addr_sel : 1;/* Specifies the Instruction addr mode 3 byte addr or 4 byte addr*/ + u8 wr_mode : 1; /* Specifies if the Instruction need modifier*/ + u8 wr_sck_sel : 3; /* Specifies the pclk division .*/ +} FQspiWrCfgDef; + +/* cmd_port register */ +typedef struct +{ + u8 cmd : 8; /* Specifies the Instruction to be sent */ + u8 reserved : 1; + u8 wait : 1; + u8 through : 1; + u8 cs : 2; + u8 transfer : 3;/* Specifies the Instruction tranfer Mode 1-1-1~4-4-4*/ + u8 cmd_addr : 1; /* Specifies if the Instruction need transfer address*/ + u8 latency : 1; /* Specifies if the Instruction need read latency*/ + u8 data_transfer : 1; /* Specifies if the Instruction need tranfer data*/ + u8 addr_sel : 1; /* Specifies the Instruction addr mode 3 byte addr or 4 byte addr*/ + u8 dummy : 5; /* Specifies the Number of Dummy Cycles.*/ + u8 p_buffer : 1; /* Specifies if the Instruction use buffer to read data*/ + u8 rw_num : 3; /* Specifies the read or write bytes number.*/ + u8 sck_sel : 3; /* Specifies the pclk division .*/ +} FQspiCommandPortDef; + +typedef struct +{ + u8 cs_hold; /* Specifies the cs valid hold time */ + u8 cs_setup; /* Specifies the cs valid setup time */ + u16 cs_delay; /* Specifies the cs delay time */ +} FQspiCsTimingCfgDef; + +typedef struct +{ + FQspiConfig config; + FQspiRdCfgDef rd_cfg; + FQspiWrCfgDef wr_cfg; + FQspiCommandPortDef cmd_def; + FQspiCsTimingCfgDef cs_timing_cfg; + u32 is_ready; /**< Device is initialized and ready */ + u32 flash_size; /* size of QSPI flash */ + u8 mf_id; /* manufacturer information */ +} FQspiCtrl; + +/* lookup FQSPI default Configuration parameters */ +const FQspiConfig *FQspiLookupConfig(u32 instance_id); + +/* set capacity and number of flash connect to qspi */ +void FQspiSetCapacityAndNum(FQspiCtrl *pctrl); + +/* qspi instance initialization */ +FError FQspiCfgInitialize(FQspiCtrl *pctrl, const FQspiConfig *input_config_p); + +/* qspi instance de-initialization */ +void FQspiDeInitialize(FQspiCtrl *pctrl); + +/* command port register config */ +FError FQspiCommandPortConfig(FQspiCtrl *pctrl); + +/* read register config */ +FError FQspiRdCfgConfig(FQspiCtrl *pctrl); + +/* write register config */ +FError FQspiWrCfgConfig(FQspiCtrl *pctrl); + +/* qspi cs number set */ +void FQspiChannelSet(FQspiCtrl *pctrl, FQspiChipCS channel); + +/* qspi cs timing set */ +void FQspiCsTimingSet(FQspiCtrl *pctrl, FQspiCsTimingCfgDef *cs_timing_cfg); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_flash.c b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_flash.c new file mode 100644 index 0000000000..a3e5fbf0c8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_flash.c @@ -0,0 +1,1039 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi_flash.c + * Date: 2022-07-12 15:42:55 + * LastEditTime: 2022-07-12 15:42:56 + * Description: This file is for + * + * Modify History: + * Ver Who Date Changes + * ----- ------ -------- -------------------------------------- + */ + +#include +#include "fkernel.h" +#include "fassert.h" +#include "fqspi_flash.h" +#include "fqspi_hw.h" +#include "fqspi.h" +#include "sdkconfig.h" + +#define FQSPI_DEBUG_TAG "FQSPI_FLASH" +#define FQSPI_ERROR(format, ...) FT_DEBUG_PRINT_E(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_WARN(format, ...) FT_DEBUG_PRINT_W(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_INFO(format, ...) FT_DEBUG_PRINT_I(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_DEBUG(format, ...) FT_DEBUG_PRINT_D(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) + +/* When entering direct address access mode, + read and write memory addresses need to be accessed in 4-byte alignment */ +#define FQSPI_ALIGNED_BYTE 4 + +typedef struct +{ + char *name; + u8 mf_id; + u8 type_id; + u8 capacity_id; + u32 capacity; +} FQspiFlashInfo; + +/* supported manufacturer information table */ +static const FQspiFlashInfo flash_info_table[] = FQSPI_FLASH_INFO_TABLE; + +/* + * @name: FQspiFlashDetect + * @msg: detect qspi flash information, include id, type, capacity, set qspi capacity register. + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiFlashDetect(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + u8 flash_id[3] = {0}; + u8 i = 0; + + /* read id to flash_id */ + ret = FQspiFlashSpecialInstruction(pctrl, FQSPI_FLASH_CMD_RDID, flash_id, sizeof(flash_id)); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("read flash id failed, ret 0x%x\r\n", ret); + return ret; + } + + FQSPI_INFO("flash id = 0x%x, 0x%x, 0x%x\r\n", flash_id[0], flash_id[1], flash_id[2]); + + for (i = 0; i < sizeof(flash_info_table) / sizeof(FQspiFlashInfo); i++) + { + if ((flash_info_table[i].mf_id == flash_id[0]) && (flash_info_table[i].type_id == flash_id[1]) + && (flash_info_table[i].capacity_id == flash_id[2])) + { + pctrl->mf_id = flash_info_table[i].mf_id; + pctrl->config.capacity = flash_info_table[i].capacity; + break; + } + } + + if (i == sizeof(flash_info_table) / sizeof(FQspiFlashInfo)) + { + FQSPI_ERROR("The Detected flash is not matched, id = 0x%x, 0x%x, 0x%x\r\n", flash_id[0], flash_id[1], flash_id[2]); + return FQSPI_NOT_SUPPORT; + } + + /* set flash num and flash capacity */ + FQspiSetCapacityAndNum(pctrl); + FQSPI_INFO("Find a %s flash chip. Size is %ld bytes.\n", flash_info_table[i].name, pctrl->flash_size); + + return ret; +} + +/* + * @name: FQspiFlashReset + * @msg: qspi Flash soft reset, FQSPI_CMD_ENABLE_RESET and FQSPI_CMD_RESET. + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +static FError FQspiFlashReset(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + ret = FQspiFlashWriteReg(pctrl, FQSPI_CMD_ENABLE_RESET, NULL, 0); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("failed to enable reset, test result 0x%x\r\n", ret); + return ret; + } + + ret = FQspiFlashWriteReg(pctrl, FQSPI_CMD_RESET, NULL, 0); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("failed to reset, test result 0x%x\r\n", ret); + return ret; + } + + return ret; +} + +/** + * @name: FQspiFlashSpecialInstruction + * @msg: Read some flash information by different cmd + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u8} cmd, read register value command, include RDID, RDSR1, RDSR2, RDCR... + * @param {u8} *buf, read buffer + * @param {size_t} len, read length + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiFlashSpecialInstruction(FQspiCtrl *pctrl, u8 cmd, u8 *buf, size_t len) +{ + FASSERT(pctrl && buf); + FError ret = FQSPI_SUCCESS; + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + uintptr base_addr = pctrl->config.base_addr; + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = cmd; + pctrl->cmd_def.wait = FQSPI_WAIT_DISABLE; + pctrl->cmd_def.through = 0; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.transfer = FQSPI_TRANSFER_1_1_1; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_DISABLE; + pctrl->cmd_def.latency = FQSPI_CMD_LATENCY_DISABLE; + pctrl->cmd_def.data_transfer = FQSPI_CMD_DATA_ENABLE; + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + pctrl->cmd_def.dummy = 0; + pctrl->cmd_def.p_buffer = FQSPI_USE_BUFFER_ENABLE; + pctrl->cmd_def.rw_num = (len - 1); + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashSpecialInstruction FQspiCommandPortConfig failed!"); + return ret; + } + + FQspiCommandPortSend(base_addr); + + FQspiGetLdPortData(base_addr, buf, len); + + return ret; +} + +/** + * @name: FQspiFlashReadSfdp + * @msg: Read flash Serial Flash Discoverable Parameters + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u32} offset,Relative Byte Address Offset + * @param {u8} *buf, read buffer + * @param {size_t} len, read length + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiFlashReadSfdp(FQspiCtrl *pctrl, u32 offset, u8 *buf, size_t len) +{ + FASSERT(pctrl && buf); + FError ret = FQSPI_SUCCESS; + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + uintptr base_addr = pctrl->config.base_addr; + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = FQSPI_FLASH_CMD_SFDP; + pctrl->cmd_def.wait = FQSPI_WAIT_DISABLE; + pctrl->cmd_def.through = 0; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.transfer = FQSPI_TRANSFER_1_1_1; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + pctrl->cmd_def.latency = FQSPI_CMD_LATENCY_ENABLE; + pctrl->cmd_def.data_transfer = FQSPI_CMD_DATA_ENABLE; + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + pctrl->cmd_def.dummy = 8; + pctrl->cmd_def.p_buffer = FQSPI_USE_BUFFER_ENABLE; + pctrl->cmd_def.rw_num = (len - 1); + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashReadSfdp FQspiCommandPortConfig failed!"); + return ret; + } + + /* write addr port register */ + FQspiAddrPortConfig(base_addr, offset); + + FQspiCommandPortSend(base_addr); + + FQspiGetLdPortData(base_addr, buf, len); + + return ret; +} + +/** + * @name: FQspiFlashReadReg + * @msg: Read Qspi register value + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u32} offset,Relative Byte Address Offset + * @param {u8} *buf, read buffer + * @param {size_t} len, read length + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiFlashReadReg(FQspiCtrl *pctrl, u32 offset, u8 *buf, size_t len) +{ + FASSERT(pctrl && buf); + FError ret = FQSPI_SUCCESS; + u32 cmd_reg = 0; + uintptr base_addr = pctrl->config.base_addr; + + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = FQSPI_FLASH_CMD_RDAR; + pctrl->cmd_def.wait = FQSPI_WAIT_DISABLE; + pctrl->cmd_def.through = 0; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.transfer = FQSPI_TRANSFER_1_1_1; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + pctrl->cmd_def.latency = FQSPI_CMD_LATENCY_ENABLE; + pctrl->cmd_def.data_transfer = FQSPI_CMD_DATA_ENABLE; + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + pctrl->cmd_def.dummy = 8; + pctrl->cmd_def.p_buffer = FQSPI_USE_BUFFER_ENABLE; + pctrl->cmd_def.rw_num = (len - 1); + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashReadReg FQspiCommandPortConfig failed!"); + return ret; + } + + /* write addr port register */ + FQspiAddrPortConfig(base_addr, offset); + + FQspiCommandPortSend(base_addr); + + FQspiGetLdPortData(base_addr, buf, len); + + /* wait SR1V bit0 WIP is ready, not device busy */ + ret = FQspiFlashWaitForCmd(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashReadReg FQspiCommandPortConfig failed!"); + return ret; + } + + return ret; +} + +/** + * @name: FQspiFlashReadData + * @msg: read flash data + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u32} chip_addr, The start address of the chip to read + * @param {u8} *buf, read buffer + * @param {size_t} len, read length + * @return size_t Indicates the length of the data read, zero indicates read fails + */ +size_t FQspiFlashReadData(FQspiCtrl *pctrl, u32 chip_addr, u8 *buf, size_t len) +{ + /* addr of copy dst or src might be zero */ + FASSERT(pctrl && buf); + size_t loop = 0; + const size_t cnt = len / FQSPI_ALIGNED_BYTE; /* cnt number of 4-bytes need copy */ + const size_t remain = len % FQSPI_ALIGNED_BYTE; /* remain number of 1-byte not aligned */ + u8 align_buf[FQSPI_ALIGNED_BYTE]; + size_t copy_len = 0; + u32 addr = pctrl->config.mem_start + pctrl->config.channel * pctrl->flash_size + chip_addr; + intptr src_addr = (intptr)addr; /* conver to 32/64 bit addr */ + intptr dst_addr = (intptr)buf; + + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return 0; + } + if (0 == pctrl->rd_cfg.rd_cmd) + { + FQSPI_ERROR("Nor flash read command is not ready !!!"); + return 0; + } + + if (0 == len) + { + return 0; + } + + if (IS_ALIGNED(src_addr, FQSPI_ALIGNED_BYTE)) /* if copy src is aligned by 4 bytes */ + { + /* read 4-bytes aligned buf part */ + for (loop = 0; loop < cnt; loop++) + { + *(u32 *)dst_addr = *(volatile u32 *)(src_addr); + src_addr += FQSPI_ALIGNED_BYTE; + dst_addr += FQSPI_ALIGNED_BYTE; + } + + copy_len += (loop << 2); + + if (remain > 0) + { + *(u32 *)align_buf = *(volatile u32 *)(src_addr); + } + + /* read remain un-aligned buf byte by byte */ + for (loop = 0; loop < remain; loop++) + { + *(u8 *)dst_addr = align_buf[loop]; + dst_addr += 1; + } + + copy_len += loop; + + } + else /* if copy src is not aligned */ + { + /* read byte by byte */ + for (loop = 0; loop < len; loop++) + { + *(u8 *)dst_addr = *(volatile u8 *)(src_addr); + dst_addr += 1; + src_addr += 1; + } + copy_len += loop; + + } + + return copy_len; +} + +/** + * @name: FQspiFlashReadDataConfig + * @msg: read flash data configuration + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u8} command, command to read flash,see the Flash manual for details + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed 表示配置成功,其它返回值表示配置失败 + */ +FError FQspiFlashReadDataConfig(FQspiCtrl *pctrl, u8 command) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + ret |= FQSPI_NOT_READY; + return ret; + } + + uintptr base_addr = pctrl->config.base_addr; + + /* clear sr1 = 0, set config register1 bit1 quad = 1 */ + u8 wrr_buf[2] = {0x0, 0x02}; + + FQspiXIPModeSet(base_addr, FQSPI_XIP_ENTER); + + /* set cmd region, command */ + memset(&pctrl->rd_cfg, 0, sizeof(pctrl->rd_cfg)); + pctrl->rd_cfg.rd_cmd = command; + + /* read buffer */ + pctrl->rd_cfg.d_buffer = FQSPI_USE_BUFFER_ENABLE; + pctrl->rd_cfg.rd_sck_sel = FQSPI_SCK_DIV_128; + + switch (command) + { + case FQSPI_FLASH_CMD_READ: + FQspiFlashReset(pctrl); + pctrl->rd_cfg.rd_addr_sel = FQSPI_ADDR_SEL_3; + pctrl->rd_cfg.rd_transfer = FQSPI_TRANSFER_1_1_1; + break; + + case FQSPI_FLASH_CMD_4READ: + pctrl->rd_cfg.rd_addr_sel = FQSPI_ADDR_SEL_4; + pctrl->rd_cfg.rd_transfer = FQSPI_TRANSFER_1_1_1; + break; + + case FQSPI_FLASH_CMD_FAST_READ: + pctrl->rd_cfg.rd_addr_sel = FQSPI_ADDR_SEL_3; + pctrl->rd_cfg.rd_transfer = FQSPI_TRANSFER_1_1_1; + pctrl->rd_cfg.dummy = 8; + pctrl->rd_cfg.rd_latency = FQSPI_CMD_LATENCY_ENABLE; + break; + + case FQSPI_FLASH_CMD_4FAST_READ: + pctrl->rd_cfg.rd_addr_sel = FQSPI_ADDR_SEL_4; + pctrl->rd_cfg.rd_transfer = FQSPI_TRANSFER_1_1_1; + pctrl->rd_cfg.dummy = 8; + pctrl->rd_cfg.rd_latency = FQSPI_CMD_LATENCY_ENABLE; + break; + + case FQSPI_FLASH_CMD_DUAL_READ: + pctrl->rd_cfg.rd_addr_sel = FQSPI_ADDR_SEL_3; + pctrl->rd_cfg.rd_transfer = FQSPI_TRANSFER_1_2_2; + pctrl->rd_cfg.rd_latency = FQSPI_CMD_LATENCY_ENABLE; + + if (pctrl->mf_id == FQSPI_FLASH_MF_ID_CYPRESS) + { + pctrl->rd_cfg.mode_byte = 0x1; + pctrl->rd_cfg.cmd_sign = FQSPI_QUAD_READ_MODE_CMD; + pctrl->rd_cfg.dummy = 8; + } + else if (pctrl->mf_id == FQSPI_FLASH_MF_ID_GIGADEVICE) + { + pctrl->rd_cfg.dummy = 4; + } + else if (pctrl->mf_id == FQSPI_FLASH_MF_ID_BOYA) + { + pctrl->rd_cfg.dummy = 4; + } + break; + + case FQSPI_FLASH_CMD_QIOR: + /* set SR1V and CR1V */ + FQspiFlashEnableWrite(pctrl); + + pctrl->rd_cfg.rd_addr_sel = FQSPI_ADDR_SEL_3; + pctrl->rd_cfg.rd_transfer = FQSPI_TRANSFER_1_4_4; + pctrl->rd_cfg.rd_latency = FQSPI_CMD_LATENCY_ENABLE; + + if (pctrl->mf_id == FQSPI_FLASH_MF_ID_CYPRESS) + { + pctrl->rd_cfg.dummy = 10; + /* use wrr write config register 1 */ + ret = FQspiFlashWriteReg(pctrl, FQSPI_FLASH_CMD_WRR, wrr_buf, sizeof(wrr_buf)); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("failed to write cmd wrr, test result 0x%x", ret); + return 0; + } + } + else if (pctrl->mf_id == FQSPI_FLASH_MF_ID_GIGADEVICE) + { + pctrl->rd_cfg.dummy = 6; + /* use wrr write config register 1 */ + ret = FQspiFlashWriteReg(pctrl, FQSPI_FLASH_CMD_WRR, wrr_buf, sizeof(wrr_buf)); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("failed to write cmd wrr, test result 0x%x", ret); + return 0; + } + } + else if (pctrl->mf_id == FQSPI_FLASH_MF_ID_BOYA) + { + pctrl->rd_cfg.dummy = 6; + ret = FQspiFlashWriteReg(pctrl, FQSPI_FLASH_CMD_WRITE_SR2, &wrr_buf[1], 1); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("failed to write cmd wrr, test result 0x%x", ret); + return 0; + } + } + + break; + + case FQSPI_FLASH_CMD_4QIOR: + pctrl->rd_cfg.rd_addr_sel = FQSPI_ADDR_SEL_4; + pctrl->rd_cfg.rd_transfer = FQSPI_TRANSFER_1_4_4; + pctrl->rd_cfg.mode_byte = 0x1; + pctrl->rd_cfg.cmd_sign = FQSPI_QUAD_READ_MODE_CMD; + pctrl->rd_cfg.rd_latency = FQSPI_CMD_LATENCY_ENABLE; + pctrl->rd_cfg.dummy = 8; + + /* set SR1V and CR1V */ + FQspiFlashEnableWrite(pctrl); + /* use wrr write config register 1 */ + ret = FQspiFlashWriteReg(pctrl, FQSPI_FLASH_CMD_WRR, wrr_buf, sizeof(wrr_buf)); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("failed to write cmd wrr, test result 0x%x\r\n", ret); + return ret; + } + break; + + default: + return FQSPI_INVAL_PARAM; + break; + } + + ret = FQspiRdCfgConfig(pctrl); + + return ret; +} + +/** + * @name: FQspiFlashWriteData + * @msg: write flash data + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u8} command, command to write flash,see the Flash manual for details + * @param {u32} chip_addr, The start address of the chip to write + * @param {u8} *buf, write buffer + * @param {size_t} len, write length + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed 表示写入成功,其它返回值表示写入失败 + */ +FError FQspiFlashWriteData(FQspiCtrl *pctrl, u8 command, u32 chip_addr, const u8 *buf, size_t len) +{ + FASSERT(pctrl && buf); + FError ret = FQSPI_SUCCESS; + u32 loop = 0; + const u32 mask = (u32)GENMASK(1, 0); + u32 reg_val = 0; + u32 val = 0; + u32 aligned_bit = 0; + + u8 tmp[FQSPI_ALIGNED_BYTE] = {0xff, 0xff, 0xff, 0xff}; + u32 addr = pctrl->config.mem_start + pctrl->config.channel * pctrl->flash_size + chip_addr; + uintptr base_addr = pctrl->config.base_addr; + + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + /* Flash write enable */ + FQspiFlashEnableWrite(pctrl); + + memset(&pctrl->wr_cfg, 0, sizeof(pctrl->wr_cfg)); + /* set cmd region, command */ + pctrl->wr_cfg.wr_cmd = command; + pctrl->wr_cfg.wr_wait = FQSPI_WAIT_ENABLE; + /* clear addr select bit */ + pctrl->wr_cfg.wr_addr_sel = 0; + /* set wr mode, use buffer */ + pctrl->wr_cfg.wr_mode = FQSPI_USE_BUFFER_ENABLE; + /* set sck_sel region, clk_div */ + pctrl->wr_cfg.wr_sck_sel = FQSPI_SCK_DIV_128; + + /* set addr_sel region, FQSPI_ADDR_SEL_3 or FQSPI_ADDR_SEL_4 */ + switch (command) + { + case FQSPI_FLASH_CMD_PP: + case FQSPI_FLASH_CMD_QPP: + pctrl->wr_cfg.wr_addr_sel = FQSPI_ADDR_SEL_3; + break; + case FQSPI_FLASH_CMD_4PP: + case FQSPI_FLASH_CMD_4QPP: + pctrl->wr_cfg.wr_addr_sel = FQSPI_ADDR_SEL_4; + break; + default: + ret |= FQSPI_NOT_SUPPORT; + return ret; + break; + } + + /*write wr_cfg to Write config register 0x08 */ + FQspiWrCfgConfig(pctrl); + + if (IS_ALIGNED(addr, FQSPI_ALIGNED_BYTE)) /* if copy src is aligned by 4 bytes */ + { + /* write alligned data into memory space */ + for (loop = 0; loop < (len >> 2); loop++) + { + FQSPI_DAT_WRITE(addr + FQSPI_ALIGNED_BYTE * loop, *(u32 *)(buf + FQSPI_ALIGNED_BYTE * loop)); + } + /* write not alligned data into memory space */ + if (len & mask) + { + addr = addr + (len & ~mask); + memcpy(tmp, buf + (len & ~mask), len & mask); + FQSPI_DAT_WRITE(addr, *(u32 *)(tmp)); + } + } + else + { + aligned_bit = (addr & mask); + addr = addr - aligned_bit; + reg_val = FQSPI_READ_REG32(addr, 0); + + for (loop = 0; loop < (FQSPI_ALIGNED_BYTE - aligned_bit); loop++) + { + val = (val << 8) | (buf[loop]); + reg_val &= (~(0xff << (loop * 8))); + } + + reg_val |= val; + reg_val = __builtin_bswap32(reg_val); + FQSPI_DAT_WRITE(addr, reg_val); + + buf = buf + loop; + len = len - loop; + addr = addr + FQSPI_ALIGNED_BYTE; + + FQSPI_DEBUG("addr=%p, buf=%p, len=%d, value=%#x\r\n", addr, buf, len, *(u32 *)(buf)); + + for (loop = 0; loop < (len >> 2); loop++) + { + FQSPI_DAT_WRITE(addr + FQSPI_ALIGNED_BYTE * loop, *(u32 *)(buf + FQSPI_ALIGNED_BYTE * loop)); + } + + if (!IS_ALIGNED(len, FQSPI_ALIGNED_BYTE)) + { + buf = buf + FQSPI_ALIGNED_BYTE * loop; + len = len - FQSPI_ALIGNED_BYTE * loop; + addr = addr + FQSPI_ALIGNED_BYTE * loop; + memcpy(tmp, buf, len); + FQSPI_DAT_WRITE(addr, *(u32 *)(tmp)); + } + } + + /* flush buffer data to Flash */ + FQspiWriteFlush(base_addr); + + ret = FQspiFlashWaitForCmd(pctrl); + + return ret; +} + +/** + * @name: FQspiFlashPortReadData + * @msg: read flash data use register port + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u8} cmd, command to read flash,see the Flash manual for details + * @param {u32} chip_addr, The start address of the chip to read + * @param {u8} *buf, read buffer + * @param {size_t} len, read length + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiFlashPortReadData(FQspiCtrl *pctrl, u8 cmd, u32 chip_addr, u8 *buf, size_t len) +{ + FASSERT(pctrl && buf); + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + FError ret = FQSPI_SUCCESS; + u32 addr = chip_addr + pctrl->config.channel * pctrl->flash_size; + uintptr base_addr = pctrl->config.base_addr; + + FQspiXIPModeSet(base_addr, FQSPI_XIP_EXIT); + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = cmd; + pctrl->cmd_def.wait = FQSPI_WAIT_ENABLE; + pctrl->cmd_def.through = 0; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.transfer = FQSPI_TRANSFER_1_1_1; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + pctrl->cmd_def.latency = FQSPI_CMD_LATENCY_DISABLE; + pctrl->cmd_def.data_transfer = FQSPI_CMD_DATA_ENABLE; + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + pctrl->cmd_def.dummy = 0; + pctrl->cmd_def.p_buffer = FQSPI_USE_BUFFER_ENABLE; + pctrl->cmd_def.rw_num = (len - 1); + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashPortReadData FQspiCommandPortConfig failed!"); + return ret; + } + + /* write addr port register */ + FQspiAddrPortConfig(base_addr, addr); + + FQspiCommandPortSend(base_addr); + + FQspiGetLdPortData(base_addr, buf, len); + + /* wait SR1V bit0 WIP is ready, not device busy */ + ret = FQspiFlashWaitForCmd(pctrl); + + return ret; +} + +/** + * @name: FQspiFlashPortWriteData + * @msg: write flash data use register port + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u8} cmd, command to write flash,see the Flash manual for details + * @param {u32} chip_addr, The start address of the chip to write + * @param {u8} *buf, write buffer + * @param {size_t} len, write length + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed + */ +FError FQspiFlashPortWriteData(FQspiCtrl *pctrl, u8 cmd, u32 chip_addr, u8 *buf, size_t len) +{ + FASSERT(pctrl && buf); + FASSERT(len <= FQSPI_CMD_PORT_CMD_RW_MAX); + + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + FError ret = FQSPI_SUCCESS; + u32 addr = chip_addr + pctrl->config.channel * pctrl->flash_size; + uintptr base_addr = pctrl->config.base_addr; + + /* Flash write enable */ + FQspiFlashEnableWrite(pctrl); + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = cmd; + pctrl->cmd_def.wait = FQSPI_WAIT_ENABLE; + pctrl->cmd_def.through = 0; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.transfer = FQSPI_TRANSFER_1_1_1; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + pctrl->cmd_def.latency = FQSPI_CMD_LATENCY_DISABLE; + pctrl->cmd_def.data_transfer = FQSPI_CMD_DATA_ENABLE; + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + pctrl->cmd_def.dummy = 0; + pctrl->cmd_def.p_buffer = FQSPI_USE_BUFFER_DISABLE; + pctrl->cmd_def.rw_num = (len - 1); + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + /*write cmd_reg to Command port register 0x10 */ + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashPortWriteData FQspiCommandPortConfig failed!"); + return ret; + } + + /* write addr port register */ + FQspiAddrPortConfig(base_addr, addr); + + FQspiSetLdPortData(base_addr, buf, len); + + /* wait SR1V bit0 WIP is ready, not device busy */ + ret = FQspiFlashWaitForCmd(pctrl); + + return ret; +} + + +/** + * @name: FQspiFlashErase + * @msg: erase flash data + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u8} command, command to erase flash, see the Flash manual for details + * @param {u32} offset,Relative Byte Address Offset + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed 表示擦除成功,其它返回值表示擦除失败 + */ +FError FQspiFlashErase(FQspiCtrl *pctrl, u8 command, u32 offset) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + uintptr base_addr = pctrl->config.base_addr; + + /* Flash write enable */ + FQspiFlashEnableWrite(pctrl); + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = command; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + switch (command) + { + case FQSPI_FLASH_CMD_SE: + /* set addr_sel region, FQSPI_ADDR_SEL_3 or FQSPI_ADDR_SEL_4 */ + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + + /* set cmd_addr region, by command, have addr transfer */ + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + + /* need some execution time */ + pctrl->cmd_def.wait = FQSPI_WAIT_ENABLE; + + break; + case FQSPI_FLASH_CMD_4SE: + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_4; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + pctrl->cmd_def.wait = FQSPI_WAIT_ENABLE; + + break; + case FQSPI_FLASH_CMD_P4E: + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + + break; + case FQSPI_FLASH_CMD_4P4E: + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_4; + pctrl->cmd_def.cmd_addr = FQSPI_CMD_ADDR_ENABLE; + + break; + case FQSPI_FLASH_CMD_BE: + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + break; + case FQSPI_FLASH_CMD_4BE: + pctrl->cmd_def.addr_sel = FQSPI_ADDR_SEL_3; + break; + default: + return FQSPI_NOT_SUPPORT; + } + + /*write cmd_reg to Command port register 0x10 */ + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashErase FQspiCommandPortConfig failed!"); + return ret; + } + + /* set addr port register, specify addr transfer */ + FQspiAddrPortConfig(base_addr, offset); + + /*write value to low bit port register 0x1c, make command valid */ + FQspiCommandPortSend(base_addr); + + /* wait command perform end */ + ret = FQspiFlashWaitForCmd(pctrl); + + return ret; +} + +/** + * @name: FQspiFlashEnableWrite + * @msg: Flash write enable + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed 表示执行成功,其它返回值表示执行失败 + */ +FError FQspiFlashEnableWrite(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + u32 timeout = FQSPI_BUSY_TIMEOUT_US; + + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + uintptr base_addr = pctrl->config.base_addr; + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = FQSPI_FLASH_CMD_WREN; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + /*write cmd_reg to Command port register 0x10 */ + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashEnableWrite FQspiCommandPortConfig failed!"); + return ret; + } + + /*write value to low bit port register 0x1c, make command valid */ + FQspiCommandPortSend(base_addr); + + /* wait SR1V bit0 WIP is ready, not device busy */ + ret = FQspiFlashWaitForCmd(pctrl); + + return ret; +} + +/** + * @name: FQspiFlashDisableWrite + * @msg: Flash write disable + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed 表示执行成功,其它返回值表示执行失败 + */ +FError FQspiFlashDisableWrite(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + uintptr base_addr = pctrl->config.base_addr; + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = FQSPI_FLASH_CMD_WRDI; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + /*write cmd_reg to Command port register 0x10 */ + ret = FQspiCommandPortConfig(pctrl); + if (ret != FT_SUCCESS) + { + FQSPI_ERROR("FQspiFlashDisableWrite FQspiCommandPortConfig failed!"); + return ret; + } + + /*write value to low bit port register 0x1c, make command valid */ + FQspiCommandPortSend(base_addr); + + return ret; +} + +/** + * @name: FQspiFlashWriteReg + * @msg: write flash register + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @param {u8} command, command to write flash register,see the Flash manual for details + * @param {u8} *buf, write buffer + * @param {size_t} len, write length + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed 表示写入成功,其它返回值表示写入失败 + */ +FError FQspiFlashWriteReg(FQspiCtrl *pctrl, u8 command, const u8 *buf, size_t len) +{ + FASSERT(pctrl); + FError ret = FQSPI_SUCCESS; + u8 sr1_v = 0; + + if (FT_COMPONENT_IS_READY != pctrl->is_ready) + { + FQSPI_ERROR("Nor flash not ready !!!"); + return FQSPI_NOT_READY; + } + + uintptr base_addr = pctrl->config.base_addr; + + memset(&pctrl->cmd_def, 0, sizeof(pctrl->cmd_def)); + pctrl->cmd_def.cmd = command; + pctrl->cmd_def.cs = pctrl->config.channel; + pctrl->cmd_def.data_transfer = FQSPI_CMD_DATA_ENABLE; + pctrl->cmd_def.p_buffer = FQSPI_USE_BUFFER_ENABLE; + pctrl->cmd_def.sck_sel = FQSPI_SCK_DIV_128; + + if (len > 4) + { + FQSPI_ERROR("data length exceed. commad 0x%lx, len:%d \n", command, len); + return FQSPI_INVAL_PARAM; + } + else if ((len > 0) && (buf != NULL)) + { + /* set rw_num region, len - 1 */ + pctrl->cmd_def.rw_num = (len - 1); + + /*write cmd_reg to Command port register 0x10 */ + FQspiCommandPortConfig(pctrl); + + /* set ld port data(buf) and make command valid */ + FQspiSetLdPortData(base_addr, buf, len); + } + else + { + /*write cmd_reg to Command port register 0x10 */ + FQspiCommandPortConfig(pctrl); + + FQspiCommandPortSend(base_addr); + } + + /* wait SR1V bit0 WIP is ready, not device busy */ + ret = FQspiFlashWaitForCmd(pctrl); + + return ret; +} + +/** + * @name: FQspiFlashWaitForCmd + * @msg: wait flash command execution complete + * @param {FQspiCtrl} *pctrl, instance of FQSPI controller + * @return {FError} err code information, FQSPI_SUCCESS indicates success,others indicates failed 表示成功完成,其它返回值表示失败 + */ +FError FQspiFlashWaitForCmd(FQspiCtrl *pctrl) +{ + FASSERT(pctrl); + u32 timeout = FQSPI_BUSY_TIMEOUT_US; + FError ret = FQSPI_SUCCESS; + u8 sr1 = 0; + + uintptr base_addr = pctrl->config.base_addr; + + ret = FQspiFlashSpecialInstruction(pctrl, FQSPI_FLASH_CMD_RDSR1, &sr1, sizeof(sr1)); + if (FQSPI_SUCCESS != ret) + { + FQSPI_ERROR("failed to read sr1, result 0x%x\r\n", ret); + return ret; + } + + do + { + timeout--; + /* read value from low bit port register 0x1c, + Read Status Register 1 is related to SR1V WIP field (bit0) */ + FQspiGetLdPortData(base_addr, &sr1, 1); + + if (!timeout) + { + FQSPI_ERROR("wait cmd timeout !!!"); + ret = FQSPI_TIMEOUT; + break; + } + + } + while (sr1 & FQSPI_NOR_FLASH_STATE_BUSY); + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_flash.h b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_flash.h new file mode 100644 index 0000000000..26712ca9b3 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_flash.h @@ -0,0 +1,147 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi_flash.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-07-12 16:20:55 + * Description:   + * This file is for S25FS256, GD25Q256, GD25Q64 norflash program, includes reading and writing registers and data, + * Users can refer to this file to adapt chips from other manufacturers. + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 wangxiaodong 2021.11.12 re-construct + * 1.2 wangxiaodong 2022.3.27 re-construct + * 1.3 wangxiaodong 2022.7.5 adapt to e2000 + */ + +#ifndef BSP_DRIVERS_FQSPI_FLASH_H +#define BSP_DRIVERS_FQSPI_FLASH_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fkernel.h" +#include "ftypes.h" +#include "ferror_code.h" +#include "fqspi.h" + +/* qspi flash support manufacturer JEDEC ID */ +#define FQSPI_FLASH_MF_ID_CYPRESS 0x01 +#define FQSPI_FLASH_MF_ID_GIGADEVICE 0xC8 +#define FQSPI_FLASH_MF_ID_BOYA 0x68 + +/* qspi flash supported information table */ +#define FQSPI_FLASH_INFO_TABLE \ +{ \ + {"S25FS256S", FQSPI_FLASH_MF_ID_CYPRESS, 0x02, 0x19, FQSPI_FLASH_CAP_32MB}, \ + {"GD25Q32C", FQSPI_FLASH_MF_ID_GIGADEVICE, 0x40, 0x16, FQSPI_FLASH_CAP_4MB}, \ + {"GD25Q32E", FQSPI_FLASH_MF_ID_GIGADEVICE, 0x60, 0x16, FQSPI_FLASH_CAP_4MB}, \ + {"GD25Q64B", FQSPI_FLASH_MF_ID_GIGADEVICE, 0x40, 0x17, FQSPI_FLASH_CAP_8MB}, \ + {"GD25LQ128E", FQSPI_FLASH_MF_ID_GIGADEVICE, 0x40, 0x18, FQSPI_FLASH_CAP_16MB}, \ + {"GD25QL256D", FQSPI_FLASH_MF_ID_GIGADEVICE, 0x60, 0x19, FQSPI_FLASH_CAP_32MB}, \ + {"BY25Q64BS", FQSPI_FLASH_MF_ID_BOYA, 0x40, 0x17, FQSPI_FLASH_CAP_8MB}, \ + {"BY25Q32BS", FQSPI_FLASH_MF_ID_BOYA, 0x40, 0x16, FQSPI_FLASH_CAP_4MB} \ +} + +#define FQSPI_FLASH_CMD_WRR 0x01 /* Write status register */ +#define FQSPI_FLASH_CMD_PP 0x02 /* Page program */ +#define FQSPI_FLASH_CMD_READ 0x03 /* Normal read data bytes */ +#define FQSPI_FLASH_CMD_WRDI 0x04 /* Write disable */ +#define FQSPI_FLASH_CMD_RDSR1 0x05 /* Read status register */ +#define FQSPI_FLASH_CMD_WREN 0x06 /* Write enable */ +#define FQSPI_FLASH_CMD_RDSR2 0x07 /* Read status register */ +#define FQSPI_FLASH_CMD_FAST_READ 0x0B /* Fast read data bytes */ +#define FQSPI_FLASH_CMD_4FAST_READ 0x0C /* Fast read data bytes */ +#define FQSPI_FLASH_CMD_DUAL_READ 0xBB /* Dual read data bytes */ +#define FQSPI_FLASH_CMD_4PP 0x12 /* Page program */ +#define FQSPI_FLASH_CMD_4READ 0x13 /* Normal read data bytes */ +#define FQSPI_FLASH_CMD_P4E 0x20 /* Erase 4kb sector */ +#define FQSPI_FLASH_CMD_4P4E 0x21 /* Erase 4kb sector */ +#define FQSPI_FLASH_CMD_QPP 0x32 /* Quad Page program */ +#define FQSPI_FLASH_CMD_4QPP 0x34 /* Quad Page program */ +#define FQSPI_FLASH_CMD_RDCR 0x35 /* Read config register */ +#define FQSPI_FLASH_CMD_BE 0x60 /* Bulk erase */ +#define FQSPI_FLASH_CMD_RDAR 0x65 /* Read Any Register */ +#define FQSPI_FLASH_CMD_QOR 0x6B /* Quad read data bytes */ +#define FQSPI_FLASH_CMD_4QOR 0x6C /* Quad read data bytes */ +#define FQSPI_FLASH_CMD_WRAR 0x71 /* Write Any Register */ +#define FQSPI_FLASH_CMD_RDID 0x9F /* Read JEDEC ID */ +#define FQSPI_FLASH_CMD_4BAM 0xB7 /* Enter 4 Bytes Mode */ +#define FQSPI_FLASH_CMD_4BE 0xC7 /* Bulk erase */ +#define FQSPI_FLASH_CMD_SE 0xD8 /* Sector erase */ +#define FQSPI_FLASH_CMD_4SE 0xDC /* Sector erase */ +#define FQSPI_FLASH_CMD_4BEX 0xE9 /* Exit 4 Bytes Mode */ +#define FQSPI_FLASH_CMD_QIOR 0xEB /* Quad read data bytes */ +#define FQSPI_FLASH_CMD_4QIOR 0xEC /* Quad read data bytes */ +#define FQSPI_FLASH_CMD_SFDP 0x5A /* Read JEDEC Serial Manu ID */ +#define FQSPI_CMD_ENABLE_RESET 0x66 /* Software Reset Enable */ +#define FQSPI_CMD_RESET 0x99 /* Software Reset */ + +/* boya flash */ +#define FQSPI_FLASH_CMD_WRITE_SR2 0x31 /* Write status register 2 */ + + +#define FQSPI_BUSY_TIMEOUT_US 1000000 +#define FQSPI_NOR_FLASH_STATE_BUSY BIT(0) + +/* Read some flash information */ +FError FQspiFlashSpecialInstruction(FQspiCtrl *pctrl, u8 cmd, u8 *buf, size_t len); + +/* read flash sfdp-Serial Flash Discoverable Parameter */ +FError FQspiFlashReadSfdp(FQspiCtrl *pctrl, u32 offset, u8 *buf, size_t len); + +/* read flash register */ +FError FQspiFlashReadReg(FQspiCtrl *pctrl, u32 offset, u8 *buf, size_t len); + +/* write flash register */ +FError FQspiFlashWriteReg(FQspiCtrl *pctrl, u8 command, const u8 *buf, size_t len); + +/* read flash data config */ +FError FQspiFlashReadDataConfig(FQspiCtrl *pctrl, u8 command); + +/* read flash data */ +size_t FQspiFlashReadData(FQspiCtrl *pctrl, u32 chip_addr, u8 *buf, size_t len); + +/* write flash data */ +FError FQspiFlashWriteData(FQspiCtrl *pctrl, u8 command, u32 chip_addr, const u8 *buf, size_t len); + +/* flash erase */ +FError FQspiFlashErase(FQspiCtrl *pctrl, u8 command, u32 offset); + +/* flash write enable */ +FError FQspiFlashEnableWrite(FQspiCtrl *pctrl); + +/* flash write disable */ +FError FQspiFlashDisableWrite(FQspiCtrl *pctrl); + +/* wait flash command execution complete */ +FError FQspiFlashWaitForCmd(FQspiCtrl *pctrl); + +/* read flash data use register port */ +FError FQspiFlashPortReadData(FQspiCtrl *pctrl, u8 cmd, u32 chip_addr, u8 *buf, size_t len); + +/* write flash data use register port */ +FError FQspiFlashPortWriteData(FQspiCtrl *pctrl, u8 cmd, u32 chip_addr, u8 *buf, size_t len); + +/* detect flash information */ +FError FQspiFlashDetect(FQspiCtrl *pctrl); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_g.c b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_g.c new file mode 100644 index 0000000000..e152ccd9f0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_g.c @@ -0,0 +1,42 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:00:41 + * Description:   + * This file is for + * + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 wangxiaodong 2021.11.12 re-construct + * 1.2 wangxiaodong 2022.3.27 re-construct + */ + +#include "fparameters.h" +#include "fqspi.h" +#include "sdkconfig.h" + +FQspiConfig FQspiConfigTbl[FQSPI_INSTANCE_NUM] = +{ + { + .instance_id = FQSPI_INSTANCE_0, + .base_addr = FQSPI_BASEADDR, + .mem_start = FQSPI_MEM_START_ADDR, + .capacity = 0, + .dev_num = 0, + .channel = 0, + } +}; \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_hw.c b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_hw.c new file mode 100644 index 0000000000..e759c661a5 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_hw.c @@ -0,0 +1,159 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:00:41 + * Description:   + * This file is for + * + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +#include "ftypes.h" +#include "ferror_code.h" +#include "fassert.h" +#include "fdebug.h" +#include "fqspi_hw.h" + +#define FQSPI_DEBUG_TAG "FQSPI-HW" +#define FQSPI_ERROR(format, ...) FT_DEBUG_PRINT_E(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_WARN(format, ...) FT_DEBUG_PRINT_W(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_INFO(format, ...) FT_DEBUG_PRINT_I(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) +#define FQSPI_DEBUG(format, ...) FT_DEBUG_PRINT_D(FQSPI_DEBUG_TAG, format, ##__VA_ARGS__) + + +/** + * @name: FQspiGetLdPortData + * @msg: read low data port register data + * @param {uintptr} base_addr, FQSPI controller base address + * @param {u8} *buf, read buffer + * @param {size_t} len, read length + * @return + */ +void FQspiGetLdPortData(uintptr base_addr, u8 *buf, size_t len) +{ + FASSERT(buf); + u32 loop = 0; + u32 reg_val = 0; + + for (loop = 0; loop < len; loop++) + { + /* read 4 bytes one time */ + if (0 == loop % 4) + { + reg_val = FQSPI_READ_REG32(base_addr, FQSPI_REG_LD_PORT_OFFSET); + } + + /* assign buf byte by byte */ + buf[loop] = (u8)((reg_val >> (loop % 4) * 8) & 0xFF); + } + +} + +/** + * @name: FQspiSetLdPortData + * @msg: set low data port register data + * @param {uintptr} base_addr, FQSPI controller base address + * @param {u8} *buf, write buffer + * @param {size_t} len, write length + * @return + */ +void FQspiSetLdPortData(uintptr base_addr, const u8 *buf, size_t len) +{ + FASSERT(buf); + FASSERT((len < 5) && (len)); + u32 reg_val = 0; + + if (1 == len) + { + reg_val = buf[0]; + } + else if (2 == len) + { + reg_val = buf[1]; + reg_val = (reg_val << 8) + buf[0]; + } + else if (3 == len) + { + reg_val = buf[2]; + reg_val = (reg_val << 8) + buf[1]; + reg_val = (reg_val << 8) + buf[0]; + } + else + { + reg_val = buf[3]; + reg_val = (reg_val << 8) + buf[2]; + reg_val = (reg_val << 8) + buf[1]; + reg_val = (reg_val << 8) + buf[0]; + } + + /*write value to low bit port register 0x1c, make command valid */ + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_LD_PORT_OFFSET, reg_val); +} + + +/** + * @name: FQspiWriteFlush + * @msg: config write flush register to make wr_cfg complete program + * @param {uintptr} base_addr, FQSPI controller base address + * @return + */ +void FQspiWriteFlush(uintptr base_addr) +{ + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_FLUSH_OFFSET, 0x1); +} + +/** + * @name: FQspiCommandPortSend + * @msg: send command port register value + * @param {uintptr} base_addr, FQSPI controller base address + * @return void + */ +void FQspiCommandPortSend(uintptr base_addr) +{ + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_LD_PORT_OFFSET, 0x0); +} + +/** + * @name: FQspiAddrPortConfig + * @msg: config address port register value + * @param {uintptr} base_addr, FQSPI controller base address + * @param {u32} addr addresss value write to register + * @return + */ +void FQspiAddrPortConfig(uintptr base_addr, u32 addr) +{ + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_ADDR_PORT_OFFSET, addr); +} + +/** + * @name: FQspiXIPModeSet + * @msg: config qspi xip mode + * @param {uintptr} base_addr, FQSPI controller base address + * @param {u8} enable enable or disable xip mode + * @return + */ +void FQspiXIPModeSet(uintptr base_addr, u8 enable) +{ + if (enable) + { + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_MODE_OFFSET, FQSPI_QUAD_READ_MODE_ENABLE); + } + else + { + FQSPI_WRITE_REG32(base_addr, FQSPI_REG_MODE_OFFSET, FQSPI_QUAD_READ_MODE_DISABLE); + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_hw.h b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_hw.h new file mode 100644 index 0000000000..d80c0a1398 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_hw.h @@ -0,0 +1,189 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:00:23 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 wangxiaodong 2021.11.12 re-construct + */ + +#ifndef BSP_DRIVERS_FQSPI_HW_H +#define BSP_DRIVERS_FQSPI_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fio.h" +#include "fkernel.h" + +/* register definition */ +#define FQSPI_REG_CAP_OFFSET (0x00) /* Flash capacity setting register */ +#define FQSPI_REG_RD_CFG_OFFSET (0x04) /* Address access reads configuration registers */ +#define FQSPI_REG_WR_CFG_OFFSET (0x08) /* Write buffer flush register */ +#define FQSPI_REG_FLUSH_OFFSET (0x0C) /* Write buffer flush register */ +#define FQSPI_REG_CMD_PORT_OFFSET (0x10) /* Command port register */ +#define FQSPI_REG_ADDR_PORT_OFFSET (0x14) /* Address port register */ +#define FQSPI_REG_HD_PORT_OFFSET (0x18) /* Upper bit port register */ +#define FQSPI_REG_LD_PORT_OFFSET (0x1C) /* low bit port register */ +#define FQSPI_REG_CS_TIMING_SET_OFFSET (0x20) /* CS setting register */ +#define FQSPI_REG_WIP_RD_OFFSET (0x24) /* WIP reads the Settings register */ +#define FQSPI_REG_WP_OFFSET (0x28) /* WP register */ +#define FQSPI_REG_MODE_OFFSET (0x2C) /* Mode setting register */ + +/* FQSPI_CAP */ +#define FQSPI_CAP_FLASH_NUM(data) ((data) << 3) /* Flash number */ +#define FQSPI_CAP_FLASH_CAP(data) ((data) << 0) /* The flash capacity */ + +#define FQSPI_CAP_FLASH_NUM_MASK GENMASK(4, 3) +#define FQSPI_CAP_FLASH_CAP_MASK GENMASK(2, 0) + +/* RD_CFG */ +#define FQSPI_RD_CFG_CMD(data) ((data) << 24) /* Read Command */ +#define FQSPI_RD_CFG_THROUGH(data) ((data) << 23) /* The programming flag in the status register */ +#define FQSPI_RD_CFG_TRANSFER(data) ((data) << 20) /* rd_tranfer region */ +#define FQSPI_RD_CFG_ADDR_SEL(data) ((data) << 19) /* rd_addr_sel region*/ +#define FQSPI_RD_CFG_LATENCY(data) ((data) << 18) /* rd_latency region*/ +#define FQSPI_RD_CFG_MODE_BYTE(data) ((data) << 17) /* mode byte region*/ +#define FQSPI_RD_CFG_CMD_SIGN(data) ((data) << 9) /* cmd_sign region*/ +#define FQSPI_RD_CFG_DUMMY(data) ((data-1) << 4) /* dummy region*/ +#define FQSPI_RD_CFG_D_BUFFER(data) ((data) << 3) /* d_buffer region*/ +#define FQSPI_RD_CFG_SCK_SEL(data) ((data) << 0) /* rd_sck_sel region*/ + +#define FQSPI_RD_CFG_CMD_MASK GENMASK(31, 24) +#define FQSPI_RD_CFG_SCK_SEL_MASK GENMASK(2, 0) +#define FQSPI_RD_CFG_TRANSFER_MASK GENMASK(22, 20) +#define FQSPI_RD_CFG_ADDR_SEL_MASK FQSPI_RD_CFG_ADDR_SEL(0x1) +#define FQSPI_RD_CFG_DUMMY_MASK GENMASK(8, 4) + +/* FQSPI_WR_CFG */ +#define FQSPI_WR_CFG_CMD(data) ((data) << 24) +#define FQSPI_WR_CFG_WAIT(data) ((data) << 9) +#define FQSPI_WR_CFG_THROUGH(data) ((data) << 8) +#define FQSPI_WR_CFG_TRANSFER(data) ((data) << 5) +#define FQSPI_WR_CFG_ADDRSEL(data) ((data) << 4) +#define FQSPI_WR_CFG_MODE(data) ((data) << 3) +#define FQSPI_WR_CFG_SCK_SEL(data) ((data) << 0) + +#define FQSPI_WR_CFG_CMD_MASK GENMASK(31, 24) +#define FQSPI_WR_CFG_SCK_SEL_MASK GENMASK(2, 0) +#define FQSPI_WR_CFG_ADDRSEL_MASK FQSPI_WR_CFG_ADDRSEL(0x1) + +/* FQSPI_CMD_PORT */ +#define FQSPI_CMD_PORT_CMD(data) ((data) << 24) +#define FQSPI_CMD_PORT_WAIT(data) ((data) << 22) +#define FQSPI_CMD_PORT_THROUGH(data) ((data) << 21) +#define FQSPI_CMD_PORT_CS(data) ((data) << 19) +#define FQSPI_CMD_PORT_TRANSFER(data) ((data) << 16) +#define FQSPI_CMD_PORT_CMD_ADDR(data) ((data) << 15) +#define FQSPI_CMD_PORT_LATENCY(data) ((data) << 14) +#define FQSPI_CMD_PORT_DATA_TRANS(data) ((data) << 13) +#define FQSPI_CMD_PORT_ADDR_SEL(data) ((data) << 12) +#define FQSPI_CMD_PORT_DUMMY(data) ((data-1) << 7) +#define FQSPI_CMD_PORT_P_BUFFER(data) ((data) << 6) +#define FQSPI_CMD_PORT_RW_NUM(data) ((data) << 3) +#define FQSPI_CMD_PORT_CLK_SEL(data) ((data) << 0) + +#define FQSPI_CMD_PORT_RW_NUM_MASK GENMASK(5, 3) +#define FQSPI_CMD_PORT_CLK_SEL_MASK GENMASK(2, 0) +#define FQSPI_CMD_PORT_CS_MASK GENMASK(20, 19) +#define FQSPI_CMD_PORT_CMD_MASK GENMASK(31, 24) +#define FQSPI_CMD_PORT_ADDR_SEL_MASK FQSPI_CMD_PORT_ADDR_SEL(0x1) + +#define FQSPI_CMD_PORT_CMD_RW_MAX 8 + +/* FQSPI_CS_TIMING_SET */ +#define FQSPI_FUN_SET_CS_HOLD(data) ((data) << 24) +#define FQSPI_FUN_SET_CS_SETUP(data) ((data) << 16) +#define FQSPI_FUN_SET_CS_DELAY(data) ((data) << 0) + +/* FQSPI_WIP_RD */ +#define FQSPI_WIP_RD_CMD(data) ((data) << 24) +#define FQSPI_WIP_RD_TRANSFER(data) ((data) << 3) +#define FQSPI_WIP_RD_SCK_SEL(data) ((data) << 0) + +/* FQSPI_WP */ +#define FQSPI_WP_EN(data) ((data) << 17) +#define FQSPI_WP_WP(data) ((data) << 16) +#define FQSPI_WP_HOLD(data) ((data) << 8) +#define FQSPI_WP_SETUP(data) ((data) << 0) + +/* FQSPI_MODE */ +#define FQSPI_MODE_VALID(data) ((data) << 8) +#define FQSPI_MODE_MODE(data) ((data) << 0) + +#define FQSPI_QUAD_READ_MODE_ENABLE 0xF0A0 /* enable FLASH XIP MODE */ +#define FQSPI_QUAD_READ_MODE_DISABLE 0xF0BF /* disable FLASH XIP MODE */ +#define FQSPI_QUAD_READ_MODE_CMD 0xA0 /* FLASH XIP MODE CMD SIGN */ + + +typedef enum +{ + FQSPI_CMD_READ = 0x01, + FQSPI_CMD_WRITE = 0x02, +} FQspiCmdFlags; + +/** + * @name: FQSPI_READ_REG32 + * @msg: read FQSPI register + * @param {u32} addr, base address of FQSPI + * @param {u32} reg_offset, offset of register + * @return {u32} register value + */ +#define FQSPI_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) + +/** + * @name: FQSPI_WRITE_REG32 + * @msg: write FQSPI register + * @param {u32} addr, base address of FQSPI + * @param {u32} reg_offset, offset of register + * @param {u32} reg_value, set register value + * @return {void} + */ +#define FQSPI_WRITE_REG32(addr, reg_offset, reg_value) FtOut32(addr + (u32)reg_offset, (u32)reg_value) + +/* FQSPI Data Operations */ +#define FQSPI_DAT_WRITE(addr, dat) FtOut32((addr), (u32)(dat)) + + +/* read ld port data */ +void FQspiGetLdPortData(uintptr base_addr, u8 *buf, size_t len); + +/* set ld port data */ +void FQspiSetLdPortData(uintptr base_addr, const u8 *buf, size_t len); + +/* send command port register config */ +void FQspiCommandPortSend(uintptr base_addr); + +/* address port register config */ +void FQspiAddrPortConfig(uintptr base_addr, u32 addr); + +/* write flush register */ +void FQspiWriteFlush(uintptr base_addr); + +/* qspi xip mode set */ +void FQspiXIPModeSet(uintptr base_addr, u8 enable); + + + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_sinit.c b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_sinit.c new file mode 100644 index 0000000000..d6636990a8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/qspi/fqspi/fqspi_sinit.c @@ -0,0 +1,47 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fqspi_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:01:10 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.1 wangxiaodong 2021.11.12 re-construct + */ + +#include "fparameters.h" +#include "fassert.h" +#include "fqspi.h" + +extern FQspiConfig FQspiConfigTbl[FQSPI_INSTANCE_NUM]; + +const FQspiConfig *FQspiLookupConfig(u32 instance_id) +{ + FASSERT(instance_id < FQSPI_INSTANCE_NUM); + const FQspiConfig *pconfig = NULL; + u32 index; + + for (index = 0; index < (u32)FQSPI_INSTANCE_NUM; index++) + { + if (FQspiConfigTbl[index].instance_id == instance_id) + { + pconfig = &FQspiConfigTbl[index]; + break; + } + } + + return (const FQspiConfig *)pconfig; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/Kconfig b/bsp/phytium/libraries/standalone/drivers/rtc/Kconfig new file mode 100644 index 0000000000..63cedcbe5c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/Kconfig @@ -0,0 +1,9 @@ +menu "FRTC Configuration" + config ENABLE_FRTC + bool + prompt "Use FRTC" + default n + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc.c b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc.c new file mode 100644 index 0000000000..8ee7ad3484 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc.c @@ -0,0 +1,231 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: frtc.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:02:33 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Wangxiaodong 2021/11/5 init + */ + +#include +#include "fgeneric_timer.h" +#include "ftypes.h" +#include "fassert.h" + +#include "fdebug.h" +#include "fsleep.h" + +#include "frtc.h" +#include "frtc_hw.h" + + +#define FRTC_DEBUG_TAG "RTC" +#define FRTC_ERROR(format, ...) FT_DEBUG_PRINT_E(FRTC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FRTC_INFO(format, ...) FT_DEBUG_PRINT_I(FRTC_DEBUG_TAG, format, ##__VA_ARGS__) +#define FRTC_DEBUG(format, ...) FT_DEBUG_PRINT_D(FRTC_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FRTC_IS_LEAP_YEAR(year) ((((year) % 4 == 0 ) && ((year) %100 != 0))||( (year) % 400 == 0)) + +/** + * @name: FRtcCheckDateTime + * @msg: check if the date year, month, day, hour, ... is valid + * @return {u32} whether the date is valid + * @param {FRtcDate} *date, pointer to a FRtcDate structure that contains year, month and day + */ +static FError FRtcCheckDateTime(const FRtcDateTime *date_time) +{ + FASSERT(date_time != NULL); + u8 w_hour = date_time->hour; + u8 w_minute = date_time->minute; + u8 w_second = date_time->second; + u8 w_year = date_time->year; + u8 w_month = date_time->month; + u8 w_day = date_time->mday; + u8 days_of_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /* 月份天数表 */ + + /* 闰年2月+1天 */ + if ((w_month == 2) && (FRTC_IS_LEAP_YEAR(w_year))) + days_of_month[w_month - 1] += 1; + + /* 判断月份日期是否合法 */ + if ((w_month > 12) || (w_month < 1) || (w_day > days_of_month[w_month - 1]) || (w_day < 1)) + { + FRTC_ERROR("invalid input date: month: %d, day: %d", w_month, w_day); + return FRTC_ERR_DATE_INVALID; + } + + /* 判断时分秒是否合法 */ + if ((w_hour > 23) || (w_minute > 59) || (w_second > 59)) + { + FRTC_ERROR("invalid input time: hour: %d, minute: %d, second: %d", + w_hour, w_minute, w_second); + return FRTC_ERR_TIME_INVALID; + } + + return FRTC_SUCCESS; +} + +/** + * @name: FRtcSetDateTime + * @msg: Set current time in FRtcDateTime + * @return {u32} whether the time setting is successful + * @param {FRtcCtrl} *pctrl, pointer to a FRtcCtrl structure that contains + * the configuration information for the specified rtc module. + * @param {FRtcDate} *date, pointer to a FRtcDate structure that contains year, month and day + * @param {FRtcTime} *time, pointer to a FRtcTime structure that contains hour, minute and second + */ +FError FRtcSetDateTime(FRtcCtrl *pctrl, const FRtcDateTime *date_time) +{ + FASSERT(pctrl != NULL); + FASSERT(date_time != NULL); + uintptr base_addr = pctrl->config.control_base_addr; + struct tm tm; + time_t t; + u32 ret = 0; + + ret = FRtcCheckDateTime(date_time); + if (ret != FRTC_SUCCESS) + { + return ret; + } + + tm.tm_sec = date_time->second; + tm.tm_min = date_time->minute; + tm.tm_hour = date_time->hour; + /* tm->tm_wday */ + tm.tm_mday = date_time->mday; + tm.tm_mon = (date_time->month - 1); + tm.tm_year = (date_time->year - 1900); + + t = mktime(&tm); + + FRTC_WRITE_AES_SEL(base_addr, FRTC_AES_SEL_COUNTER); + + /* write low 32 bit first */ + FRTC_WRITE_CLR_LOW(base_addr, 0); + + /* write low 32 bit next */ + FRTC_WRITE_CLR(base_addr, t); + + return FT_SUCCESS; +} + +/** + * @name: FRtcGetDateTime + * @msg: Get current time in FRtcDateTime + * @return {*} + * @param {FRtcCtrl} *pctrl + * @param {FRtcDateTime} *date_time + */ +FError FRtcGetDateTime(FRtcCtrl *pctrl, FRtcDateTime *date_time) +{ + FASSERT(pctrl != NULL); + FASSERT(date_time != NULL); + time_t seconds = 0; + struct tm *time_p; + + FRtcReadTimeStamp(pctrl, &seconds, NULL); + time_p = localtime(&seconds); + + date_time->year = time_p->tm_year + 1900; + date_time->month = time_p->tm_mon + 1; + date_time->mday = time_p->tm_mday; + date_time->hour = time_p->tm_hour; + date_time->minute = time_p->tm_min; + date_time->second = time_p->tm_sec; + + return FRTC_SUCCESS; +} + +/** + * @name: FRtcReadTimeStamp + * @msg: Read time stamp in seconds and milliseconds + * @return {*} none + * @param {FRtcCtrl} *pctrl + * @param {time_t} *sec_p + * @param {time_t} *msec_p + */ +void FRtcReadTimeStamp(FRtcCtrl *pctrl, time_t *sec_p, time_t *msec_p) +{ + FASSERT(pctrl != NULL); + time_t sec = 0; + u32 msec = 0; + u32 tick = 0; + + uintptr base_addr = pctrl->config.control_base_addr; + + /* tick = 1/32.768k = 0.03ms = 30us, delay more than 4 ticks */ + fsleep_microsec(FRTC_COUNTER_DELAY); + + /* write AES_SEL register, to read CCVR and CDR register */ + FRTC_WRITE_AES_SEL(base_addr, FRTC_AES_SEL_COUNTER); + + /* tick = 1/32.768k = 0.03ms = 30us, delay more than 4 ticks */ + fsleep_microsec(FRTC_COUNTER_DELAY); + + /* read high 32 bit first */ + sec = FRTC_READ_CCVR(base_addr); + + /* read low 32 bit next, The lower 15 bits are valid */ + tick = (FRTC_READ_CDR_LOW(base_addr) & FRTC_COUNTER_LB_MASK); + + /* convert 15 bits tick to milliseconds, count by 32.768k */ + msec = ((tick * 1000) >> FRTC_COUNTER_HB_OFFSET); + + if (sec_p) + *sec_p = sec; + + if (msec_p) + *msec_p = msec; + + return; +} + +/** + * @name: FRtcCfgInitialize + * @msg: Initialize RTC ctrl + * @return {*} + * @param {FRtcCtrl} *instance_p + * @param {FRtcConfig} *input_config_p + */ +FError FRtcCfgInitialize(FRtcCtrl *instance_p, const FRtcConfig *input_config_p) +{ + FASSERT(instance_p && input_config_p); + uintptr base_addr = instance_p->config.control_base_addr; + + instance_p->config = *input_config_p; + instance_p->is_ready = FT_COMPONENT_IS_READY; + + return FRTC_SUCCESS; +} + +/** + * @name: FRtcCfgDeInitialize + * @msg: DeInitialization function for the device instance + * @param {FRtcCtrl} *instance_p FRTC驱动控制数据 + * @return {*} + */ +void FRtcCfgDeInitialize(FRtcCtrl *pctrl) +{ + FASSERT(pctrl); + + pctrl->is_ready = 0; + memset(pctrl, 0, sizeof(*pctrl)); + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc.h b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc.h new file mode 100644 index 0000000000..25fdd276d6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc.h @@ -0,0 +1,92 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: frtc.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:02:51 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Wangxiaodong 2021/8/26 init + */ + +#ifndef BSP_DRIVERS_FRTC_H +#define BSP_DRIVERS_FRTC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +#include "ftypes.h" +#include "ferror_code.h" + +typedef struct +{ + uintptr control_base_addr; /* rtc控制寄存器基地址 */ + const char *instance_name; /* instance name */ +} FRtcConfig; /* rtc配置 */ + +typedef struct +{ + FRtcConfig config; /* rtc配置 */ + u32 is_ready; /* rtc初始化完成标志 */ +} FRtcCtrl; + +typedef struct +{ + u16 year; /*Specifies the RTC Date Year. + This parameter must be a number between Min_Data = 2000 and Max_Data = 2099 */ + u8 month; /*Specifies the RTC Date Month. + This parameter must be a number between Min_Data = 1 and Max_Data = 12 */ + u8 mday; /*Specifies the RTC day of Month. + This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ + u8 hour; /*Specifies the RTC Time Hour. + This parameter must be a number between Min_Data = 0 and Max_Data = 23 */ + u8 minute; /*Specifies the RTC Time Minute. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + u8 second; /*Specifies the RTC Time Second. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ +} FRtcDateTime; + +#define FRTC_SUCCESS FT_SUCCESS +#define FRTC_ERR_DATE_INVALID FT_MAKE_ERRCODE(ErrModBsp, ErrBspRtc, BIT(1)) +#define FRTC_ERR_TIME_INVALID FT_MAKE_ERRCODE(ErrModBsp, ErrBspRtc, BIT(2)) + +/* rtc config init */ +const FRtcConfig *FRtcLookupConfig(void); + +/* initialize rtc ctrl */ +FError FRtcCfgInitialize(FRtcCtrl *instance_p, const FRtcConfig *config_p); + +/* deinitialize rtc ctrl */ +void FRtcCfgDeInitialize(FRtcCtrl *pctrl); + +/* set rtc time */ +FError FRtcSetDateTime(FRtcCtrl *pctrl, const FRtcDateTime *date_time); + +/* get rtc time */ +FError FRtcGetDateTime(FRtcCtrl *pctrl, FRtcDateTime *date_time); + +/* read rtc time in secs and mesc */ +void FRtcReadTimeStamp(FRtcCtrl *pctrl, time_t *sec, time_t *msec); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_g.c b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_g.c new file mode 100644 index 0000000000..e3b54ab488 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_g.c @@ -0,0 +1,34 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: frtc_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:01:26 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Wangxiaodong 2021/8/25 init + */ + +#include "fparameters.h" +#include "frtc.h" + +/* default configs of rtc ctrl */ +const FRtcConfig FRtcConfigTbl = +{ + .control_base_addr = RTC_CONTROL_BASE, + .instance_name = "RTC" +}; + diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_hw.c b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_hw.c new file mode 100644 index 0000000000..b7d0772096 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_hw.c @@ -0,0 +1,36 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: frtc_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:01:40 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "frtc_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_hw.h b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_hw.h new file mode 100644 index 0000000000..d104692667 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_hw.h @@ -0,0 +1,99 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: frtc_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:01:54 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 wangxiaodong 2021/11/5 init + */ + +#ifndef BSP_DRIVERS_FRTC_HW_H +#define BSP_DRIVERS_FRTC_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fkernel.h" +#include "ftypes.h" +#include "fio.h" + +/* Rtc register definitions */ + +#define FRTC_CMR 0x04 +#define FRTC_AES_SEL 0x08 +#define FRTC_AES_SEL_COUNTER 0x100 + +#define FRTC_CCR 0x0C +#define FRTC_STAT 0x10 +#define FRTC_RSTAT 0x14 +#define FRTC_EOI 0x18 +#define FRTC_VER 0x1C +#define FRTC_CDR_LOW 0x20 +#define FRTC_CCVR 0x24 +#define FRTC_CLR_LOW 0x28 +#define FRTC_CLR 0x2c + +#define FRTC_COUNTER_HB_OFFSET 15 +#define FRTC_COUNTER_LB_MASK 0x7fff +#define FRTC_COUNTER_DELAY 150 + +/***************** Macros (Inline Functions) Definitions *********************/ + +/** + * @name: RTC_READ_REG32 + * @msg: 读取RTC寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @return {u32} 寄存器参数 + */ +#define FRTC_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)reg_offset) + +/** + * @name: RTC_READ_REG64 + * @msg: 读取RTC寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @return {u64} 寄存器参数 + */ +#define FRTC_READ_REG64(addr, reg_offset) FtIn64((addr) + (u64)reg_offset) + +/** + * @name: RTC_WRITE_REG32 + * @msg: 写入RTC寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @param {u32} reg_value 写入寄存器参数 + * @return {void} + */ +#define FRTC_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)reg_offset, (u32)reg_value) + +#define FRTC_WRITE_AES_SEL(addr, regVal) FRTC_WRITE_REG32((addr), FRTC_AES_SEL, (regVal)) +#define FRTC_WRITE_CLR_LOW(addr, regVal) FRTC_WRITE_REG32((addr), FRTC_CLR_LOW, (u32)(regVal)) +#define FRTC_WRITE_CLR(addr, regVal) FRTC_WRITE_REG32((addr), FRTC_CLR, (u32)(regVal)) + +#define FRTC_READ_CDR_LOW(addr) FRTC_READ_REG32((addr), FRTC_CDR_LOW) +#define FRTC_READ_CCVR(addr) FRTC_READ_REG32((addr), FRTC_CCVR) + + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_intr.c b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_intr.c new file mode 100644 index 0000000000..9b7803214b --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_intr.c @@ -0,0 +1,30 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: frtc_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:02:07 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Wangxiaodong 2021/8/3 init + */ + +#include "fparameters.h" +#include "fassert.h" +#include "frtc.h" +#include "finterrupt.h" + + diff --git a/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_sinit.c b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_sinit.c new file mode 100644 index 0000000000..7ded7bdbcc --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/rtc/frtc/frtc_sinit.c @@ -0,0 +1,51 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: frtc_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:02:24 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "frtc.h" + +extern const FRtcConfig FRtcConfigTbl; +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ +/** + * @name: RtcLookupConfig + * @msg: get rtc configs by id + * @return {*} + * @param {u32} instanceId, id of rtc ctrl + */ +const FRtcConfig *FRtcLookupConfig(void) +{ + const FRtcConfig *pconfig = NULL; + + pconfig = &FRtcConfigTbl; + + return (const FRtcConfig *)pconfig; +} diff --git a/bsp/phytium/libraries/standalone/drivers/sata/Kconfig b/bsp/phytium/libraries/standalone/drivers/sata/Kconfig new file mode 100644 index 0000000000..f2c51a66d4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/Kconfig @@ -0,0 +1,9 @@ +menu "FSATA Configuration" + config ENABLE_FSATA + bool + prompt "Use FSATA" + default n + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata.c b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata.c new file mode 100644 index 0000000000..c9fa80705b --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata.c @@ -0,0 +1,916 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsata.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 09:05:09 + * Description:  This files is for sata ctrl function implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include +#include +#include "ftypes.h" +#include "fassert.h" +#include "fcache.h" +#include "fdebug.h" +#include "fsleep.h" +#include "fswap.h" +#include "fsata.h" +#include "fsata_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +#define FSATA_DEBUG_TAG "SATA" +#define FSATA_ERROR(format, ...) FT_DEBUG_PRINT_E(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSATA_WARN(format, ...) FT_DEBUG_PRINT_W(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSATA_INFO(format, ...) FT_DEBUG_PRINT_I(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSATA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) + +#ifndef MAX_SATA_BLOCKS_READ_WRITE + #define MAX_SATA_BLOCKS_READ_WRITE 0x80 +#endif + +/* Maximum timeouts for each event */ +#define WAIT_MS_RESET 1000 +#define WAIT_MS_TFD 20000 /* task file data transfer is not busy */ +#define WAIT_MS_DATAIO 20000 +#define WAIT_MS_LINKUP 200 + + +static FError FSataAhciDataIO(FSataCtrl *instance_p, u8 port, u8 *fis, + int fis_len, u8 *buf, int buf_len, boolean is_ncq, boolean is_write); + +/** + * @name: FSataAhciPortBase + * @msg: get port x base address + * @param {uintptr} base_address FSata base address + * @param {u32} port sata port number + * @return {uintptr} port x base address + */ +static uintptr FSataAhciPortBase(uintptr base_address, u32 port) +{ + return (base_address + 0x100 + (port * 0x80)); +} + +/** + * @name: FSataWaitCmdCompleted + * @msg: read register status and wait command execution is completed + * @param {uintptr} reg FSata register + * @param {int} timeout_msec wait timeout value + * @param {u32} sign register status flag bit + * @return {int} return 0 if command execute success, return -1 if command execute timeout + */ +static int FSataWaitCmdCompleted(uintptr reg, int timeout_msec, u32 sign) +{ + int i; + + for (i = 0; (FtIn32(reg)& sign) && (i < timeout_msec); i++) + { + fsleep_millisec(1); + } + + return (i < timeout_msec) ? 0 : -1; +} + +/** + * @name: FSataAhciLinkUp + * @msg: check sata ahci port link status + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance. + * @param {u8} port, port number + * @return {int} return FSATA_SUCCESS if successful, return others if failed + */ +static FError FSataAhciLinkUp(FSataCtrl *instance_p, u8 port) +{ + u32 reg_val; + int i = 0; + uintptr port_base_addr = instance_p->port[port].port_base_addr; + + /* + * Bring up SATA link. + * SATA link bringup time is usually less than 1 ms; only very + * rarely has it taken between 1-2 ms. Never seen it above 2 ms. + */ + while (i < WAIT_MS_LINKUP) + { + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_SCR_STAT); + if ((reg_val & FSATA_PORT_SCR_STAT_DET_MASK) == FSATA_PORT_SCR_STAT_DET_PHYRDY) + return FSATA_SUCCESS; + fsleep_microsec(1000); + i++; + } + + return FSATA_ERR_TIMEOUT; +} + +/** + * @name: FSataAhciInquiry + * @msg: inquiry sata information + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance. + * @param {u8} port, port number + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +static FError FSataAhciInquiry(FSataCtrl *instance_p, u8 port) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FError ret = FSATA_SUCCESS; + u16 *idbuf; + + /* 64位需要预留给内存池更大的空间 */ + static u16 tmpid[FSATA_ID_WORDS] __attribute__((aligned(128))) = {0}; + + u8 fis[20]; + /* Preset the FIS */ + memset(fis, 0, sizeof(fis)); + + fis[0] = FSATA_FIS_REG_HOST_TO_DEVICE; /* Register Host to Device FIS */ + fis[1] = FSATA_FIS_REG_HOST_TO_DEVICE_C; + fis[2] = FSATA_CMD_IDENTIFY_DEVICE; /* Command byte. */ + ret = FSataAhciDataIO(instance_p, port, fis, sizeof(fis), + (u8 *)tmpid, FSATA_ID_WORDS * 2, FALSE, FALSE); + if (ret != FSATA_SUCCESS) + { + FSATA_ERROR("FSataAhciInquiry: command failure. ret = %#x", ret); + return FSATA_ERR_OPERATION; + } + + instance_p->ataid[port] = tmpid; + + return FSATA_SUCCESS; +} + +/** + * @name: FSataIdentityCopy + * @msg: parse sata Identity information to vendor, product, revision + * @param {unsigned char } *dest, pointer to the destination address. + * @param {unsigned char } *src, pointer to the source address. + * @param {u32} len, parse length. + * @return {void} + */ +static void FSataIdentityCopy(unsigned char *dest, unsigned char *src, u32 len) +{ + FASSERT(dest != NULL); + FASSERT(src != NULL); + FASSERT(len != 0); + + u32 start, end; + + start = 0; + while (start < len) + { + if (src[start] != 0x20)/* character is not sapce */ + break; + start++; + } + end = len - 1; + while (end > start) + { + if (src[end] != 0x20)/* character is not sapce */ + break; + end--; + } + for (; start <= end; start++) + *dest ++ = src[start]; + *dest = '\0'; +} + +/** + * @name: FSataIdToSectors + * @msg: parse sata Identity information to capacity. + * @param {u16} *id, pointer to Identity information . + * @return {u64} capacity + */ +static u64 FSataIdToSectors(u16 *id) +{ + if (FSataIdHasLba(id)) + { + if (FSataIdHasLba48(id)) + return FSATA_ID_U64(id, FSATA_ID_LBA48_SECTORS); + else + return (u64)(FSATA_ID_U32(id, FSATA_ID_LBA_SECTORS)); + } + else + { + return 0; + } +} + +/** + * @name: FSataIdStrCopy + * @msg: swap sata Identity information + * @param {u16} *dest, pointer to the destination address. + * @param {u16} *src, pointer to the source address. + * @param {int} len, swap length. + * @return {void} + */ +static void FSataIdStrCopy(u16 *dest, u16 *src, int len) +{ + int i; + for (i = 0; i < len / 2; i++) + dest[i] = __swab16(src[i]); +} + +/** + * @name: FSataBlockToMB + * @msg: Converts the number of blocks in 512 byte to 0.1MB + * @param {unsigned long} block_count, block count. + * @param {unsigned long} mul_by, multiple value. + * @param {int} div_by, divided value. + * @return {unsigned long} convert value + */ +static unsigned long FSataBlockToMB(unsigned long block_count, unsigned long mul, int div) +{ + unsigned long bc_quot, bc_rem; + + /* x * m / d == x / d * m + (x % d) * m / d */ + bc_quot = (block_count >> div); /* upper > div bit */ + bc_rem = block_count - (bc_quot << div); /* low div bit */ + return (bc_quot * mul + ((bc_rem * mul) >> div)); +} + +/** + * @name: FSataInfoPrint + * @msg: printf sata information + * @param {FSataInfo} *dev_desc, pointer to the FSata information. + * @return {void} + */ +void FSataInfoPrint(FSataInfo *dev_desc) +{ + unsigned long lba512; /* number of blocks if 512bytes block size */ + + if (dev_desc->type == FSATA_DEV_TYPE_UNKNOWN) + { + FSATA_INFO("not available"); + return; + } + + if (dev_desc->if_type == FSATA_IF_TYPE_SCSI) + { + FSATA_INFO("Vendor: %s Prod: %s Rev: %s", + dev_desc->vendor, + dev_desc->product, + dev_desc->revision); + } + + if (dev_desc->type == FSATA_DEV_TYPE_HARDDISK) + { + FSATA_INFO("Type: Hard Disk"); + } + + if ((dev_desc->lba > 0L) && (dev_desc->blksz > 0L)) + { + unsigned long mb, mb_quot, mb_rem, gb, gb_quot, gb_rem; + unsigned long lba; + + lba = dev_desc->lba; + + lba512 = (lba * (dev_desc->blksz / 512)); + /* round to 1 digit */ + /* 2048 = (1024 * 1024) / 512 MB */ + mb = FSataBlockToMB(lba512, 10, 11); + + dev_desc->lba512 = lba512; + + FSATA_INFO("lba512=%lu, mb=%lu", lba512, mb); + + mb_quot = mb / 10; + mb_rem = mb - (10 * mb_quot); + + gb = mb / 1024; + gb_quot = gb / 10; + gb_rem = gb - (10 * gb_quot); + + FSATA_INFO("Capacity: %lu.%lu MB = %lu.%lu GB (%lu x %lu)", + mb_quot, mb_rem, + gb_quot, gb_rem, + (unsigned long)lba, + dev_desc->blksz); + } + else + { + FSATA_INFO("Capacity: not available"); + } +} + +/** + * @name: FSataAhciReadCapacity + * @msg: get sata capacity by parse instance_p ataid + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance. + * @param {u8} port, port number + * @param {unsigned long} *capacity, pointer to capacity value + * @param {unsigned long} *blksz, pointer to block size + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +static FError FSataAhciReadCapacity(FSataCtrl *instance_p, u8 port, + unsigned long *capacity, unsigned long *blksz) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FError ret = FSATA_SUCCESS; + + u32 transfer_size; /* number of bytes per iteration */ + + if (!instance_p->ataid[port]) + { + FSATA_ERROR("READ CAPACITY10 command failure. " + "\tNo ATA info!\n" + "\tPlease run command INQUIRY first!"); + return FSATA_ERR_OPERATION; + } + + u64 cap64 = FSataIdToSectors(instance_p->ataid[port]); + if (cap64 > 0x100000000ULL) + cap64 = 0xffffffff; + + *capacity = (unsigned long)(cap64); + if (*capacity != 0xffffffff) + { + /* Read capacity (10) was sufficient for this drive. */ + *blksz = 512; + return FSATA_SUCCESS; + } + else + { + FSATA_DEBUG("should read capacity 16?"); + } + + return FSATA_SUCCESS; +} + +/** + * @name: FSataAhciReadInfo + * @msg: get sata information + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance. + * @param {u8} port, port number + * @return {FError} return FSATA_SUCCESS if read successful, return others if read failed + */ +FError FSataAhciReadInfo(FSataCtrl *instance_p, u8 port) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FSATA_SUCCESS; + + u16 *idbuf; + unsigned long capacity, blksz; + unsigned char info_data[50]; + memset(info_data, 0, sizeof(info_data)); + + ret = FSataAhciInquiry(instance_p, port); + if (ret != FSATA_SUCCESS) + { + FSATA_ERROR("FSataAhciInquiry!"); + return FSATA_ERR_OPERATION; + } + + /* Parse SATA Information */ + idbuf = instance_p->ataid[port]; + FSataIdStrCopy((u16 *)&info_data[16], &idbuf[FSATA_ID_PROD], 16); + FSataIdStrCopy((u16 *)&info_data[32], &idbuf[FSATA_ID_FW_REV], 4); + + /* is ata device */ + if (!((__swab16(idbuf[0]) & FSATA_ID_ATA_DEVICE))) + { + instance_p->port[port].dev_info.type = FSATA_DEV_TYPE_HARDDISK; + memcpy(&info_data[8], "ATA ", 8); /* copy 8 bytes */ + } + else + { + instance_p->port[port].dev_info.type = FSATA_DEV_TYPE_UNKNOWN; + } + + /* get info for this device */ + FSataIdentityCopy((unsigned char *)instance_p->port[port].dev_info.vendor, &info_data[8], 8); + FSataIdentityCopy((unsigned char *)instance_p->port[port].dev_info.product, &info_data[16], 16); + FSataIdentityCopy((unsigned char *)instance_p->port[port].dev_info.revision, &info_data[32], 4); + + /* get sata capacity by parse ataid */ + ret = FSataAhciReadCapacity(instance_p, port, &capacity, &blksz); + if (ret != FSATA_SUCCESS) + { + FSATA_ERROR("FSataAhciReadCapacity error!"); + return FSATA_ERR_OPERATION; + } + + instance_p->port[port].dev_info.lba = capacity; + instance_p->port[port].dev_info.blksz = blksz; + instance_p->port[port].dev_info.if_type = FSATA_IF_TYPE_SCSI; + + FSataInfoPrint(&(instance_p->port[port].dev_info)); + + return ret; +} + +/** + * @name: FSataAhciReset + * @msg: reset ahci / hba(host bus adapter) + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +static FError FSataAhciReset(FSataCtrl *instance_p) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + int i = WAIT_MS_RESET; + uintptr base_addr = instance_p->config.base_addr; + + u32 reg_val = 0; + + /* read host control register and reset */ + reg_val = FSATA_READ_REG32(base_addr, FSATA_HOST_CTL); + + if ((reg_val & FSATA_HOST_RESET) == 0) + { + FSATA_SETBIT(base_addr, FSATA_HOST_CTL, FSATA_HOST_RESET); + } + + /* reset must complete within 1 millisecond, or the hardware should be considered fried.*/ + do + { + fsleep_microsec(1000); + reg_val = FSATA_READ_REG32(base_addr, FSATA_HOST_CTL); + i--; + } + while ((i > 0) && (reg_val & FSATA_HOST_RESET)); + + if (i == 0) + { + FSATA_ERROR("controller reset failed (0x%x)", reg_val); + return FSATA_ERR_TIMEOUT; + } + + return FSATA_SUCCESS; +} + +/** + * @name: FSataAhciInit + * @msg: init ahci / hba(host bus adapter) + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +FError FSataAhciInit(FSataCtrl *instance_p) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FSATA_SUCCESS; + u32 i; + uintptr port_base_addr = 0; /* ahci port x base address */ + u32 reg_val = 0; + u32 port_num = 0; + + /* reset host control */ + ret = FSataAhciReset(instance_p); + if (ret != FSATA_SUCCESS) + return ret; + + /* ahci enable */ + FSATA_WRITE_REG32(base_addr, FSATA_HOST_CTL, FSATA_HOST_AHCI_EN); + FSATA_READ_REG32(base_addr, FSATA_HOST_CTL); + + /* read cap.np, set the ports bit which are available for software to use. */ + port_num = FSATA_READ_REG32(base_addr, FSATA_HOST_CAP) & FSATA_HOST_CAP_NP_MASK; + FSATA_WRITE_REG32(base_addr, FSATA_HOST_PORTS_IMPL, FSATA_HOST_PORTS_IMPL_MASK(port_num)); + + /* set instance_p paramameters */ + instance_p->n_ports = port_num + 1; + instance_p->port_map = FSATA_READ_REG32(base_addr, FSATA_HOST_PORTS_IMPL); + FSATA_DEBUG("port_map 0x%x n_ports %d", instance_p->port_map, instance_p->n_ports); + + for (i = 0; i < instance_p->n_ports; i++) + { + if (!(instance_p->port_map & BIT(i))) + continue; + /* set ports base address */ + instance_p->port[i].port_base_addr = FSataAhciPortBase(base_addr, i); + port_base_addr = instance_p->port[i].port_base_addr; + + /* make sure port is not active */ + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_CMD); + if (reg_val & (FSATA_PORT_CMD_LIST_ON | FSATA_PORT_CMD_FIS_ON | + FSATA_PORT_CMD_FIS_RX | FSATA_PORT_CMD_START)) + { + FSATA_DEBUG("Port %d is active, reg = %#x. Deactivating.", i, reg_val); + reg_val &= ~(FSATA_PORT_CMD_LIST_ON | FSATA_PORT_CMD_FIS_ON | + FSATA_PORT_CMD_FIS_RX | FSATA_PORT_CMD_START); + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_CMD, reg_val); + + /* spec says 500 msecs for each bit, so this is slightly incorrect.*/ + fsleep_millisec(500); + } + + /* Add the spinup command to whatever mode bits may + * already be on in the command register, set not support staggered spin-up */ + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_CMD); + reg_val |= FSATA_PORT_CMD_SPIN_UP; + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_CMD, reg_val); + + /* check sata port is linked */ + ret = FSataAhciLinkUp(instance_p, i); + if (ret) + { + FSATA_DEBUG("sata host %d, port %d link timeout", instance_p->config.instance_id, i); + continue; + } + else + { + FSATA_DEBUG("sata host %d , port %d link ok.", instance_p->config.instance_id, i) ; + } + + /* Clear error status */ + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_SCR_ERR); + if (reg_val) + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_SCR_ERR, reg_val); + + /* Device presence detected but Phy communication not established, retry once more */ + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_SCR_STAT) & FSATA_PORT_SCR_STAT_DET_MASK; + if (reg_val == FSATA_PORT_SCR_STAT_DET_COMINIT) + { + FSATA_INFO("sata link %d down, retrying...", i); + i--; + continue; + } + + /* Clear error status */ + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_SCR_ERR); + if (reg_val) + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_SCR_ERR, reg_val); + + /* clear port irq status */ + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_IRQ_STAT); + if (reg_val) + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_IRQ_STAT, reg_val); + + /* clear host corresponding port interrupt status register */ + FSATA_WRITE_REG32(base_addr, FSATA_HOST_IRQ_STAT, BIT(i)); + + /* register linkup ports */ + reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_SCR_STAT); + if ((reg_val & FSATA_PORT_SCR_STAT_DET_MASK) == FSATA_PORT_SCR_STAT_DET_PHYRDY) + instance_p->link_port_map |= BIT(i); + } + + /* host interrupt enable */ + reg_val = FSATA_READ_REG32(base_addr, FSATA_HOST_CTL); + FSATA_WRITE_REG32(base_addr, FSATA_HOST_CTL, reg_val | FSATA_HOST_IRQ_EN); + + return FSATA_SUCCESS; +} + +/** + * @name: FSataAhciPortStart + * @msg: init ahci port, allocate Port Memory Usage + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @param {u8} port, port number + * @param {uintptr} mem, Memory start address allocated to port + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +FError FSataAhciPortStart(FSataCtrl *instance_p, u8 port, uintptr mem) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(mem); + uintptr base_addr = instance_p->config.base_addr; + + FError ret = FSATA_SUCCESS; + FSataAhciPorts *port_info = &(instance_p->port[port]); + uintptr port_base_addr = port_info->port_base_addr; + + u32 reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_SCR_STAT); + if ((reg_val & FSATA_PORT_SCR_STAT_DET_MASK) != FSATA_PORT_SCR_STAT_DET_PHYRDY) + { + FSATA_ERROR("No Link on host %d port %d!", instance_p->config.instance_id, port); + return FSATA_ERR_OPERATION; + } + + memset((void *)mem, 0, FSATA_AHCI_PORT_PRIV_DMA_SZ); + + /* First item in chunk of DMA memory: 32 command lists, 32 bytes each in size */ + port_info->cmd_list = (FSataAhciCommandList *)(mem); + mem += FSATA_AHCI_CMD_LIST_HEADER_SIZE * FSATA_AHCI_CMD_LIST_HEADER_NUM; + + /* Second item: Received-FIS area */ + port_info->rx_fis = (FSataAhciRecvFis *)(mem); + mem += FSATA_AHCI_RX_FIS_SZ; + + /* Third item: data area for storing a single command and its scatter-gather table */ + port_info->cmd_tbl_base_addr = (uintptr)mem; + mem += FSATA_AHCI_CMD_TABLE_HEADER_SIZE; + + /* command table prdt */ + port_info->cmd_tbl_prdt = (FSataAhciCommandTablePrdt *)mem; + + /* set ahci port registers */ + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_LST_ADDR, + (uintptr)port_info->cmd_list & FSATA_PORT_CMD_LIST_ADDR_MASK); + + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_LST_ADDR_HI, 0); + + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_FIS_ADDR, + (uintptr)port_info->rx_fis & FSATA_PORT_CMD_FIS_ADDR_MASK); + + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_FIS_ADDR_HI, 0); + + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_CMD, FSATA_PORT_CMD_ICC_ACTIVE | FSATA_PORT_CMD_FIS_RX | + FSATA_PORT_CMD_POWER_ON | FSATA_PORT_CMD_SPIN_UP | FSATA_PORT_CMD_START); + + /* + * Make sure interface is not busy based on error and status + * information from task file data register before proceeding + */ + if (FSataWaitCmdCompleted(port_base_addr + FSATA_PORT_TFDATA, WAIT_MS_TFD, FSATA_BUSY)) + { + FSATA_DEBUG("timeout exit!"); + return FSATA_ERR_TIMEOUT; + } + + instance_p->private_data |= BIT(port); + + return ret; +} + +/** + * @name: FSataAhciFillCmdTablePrdt + * @msg: allocate ahci command table prdt information + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @param {u8} port, port number + * @param {unsigned char} *buffer, data buffer address + * @param {int} buf_len, data length + * @return {int} return item_count if successful, return -1 if failed + */ +static int FSataAhciFillCmdTablePrdt(FSataCtrl *instance_p, u8 port, + unsigned char *buf, int buf_len) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + FSataAhciPorts *port_info = &(instance_p->port[port]); + FSataAhciCommandTablePrdt *command_table_prdt = port_info->cmd_tbl_prdt; + int item_count; + int i; + + item_count = ((buf_len - 1) / MAX_DATA_BYTE_COUNT) + 1; + if (item_count > FSATA_AHCI_PRTD_ITEM_NUM) + { + FSATA_ERROR("Too much command table prdt items %d!", item_count); + return -1; + } + + for (i = 0; i < item_count; i++) + { + command_table_prdt->addr_low = ((unsigned long) buf + i * MAX_DATA_BYTE_COUNT); + command_table_prdt->addr_high = 0; + command_table_prdt->data_byte = (0x3fffff & + (buf_len < MAX_DATA_BYTE_COUNT + ? (buf_len - 1) + : (MAX_DATA_BYTE_COUNT - 1))); + command_table_prdt++; + buf_len -= MAX_DATA_BYTE_COUNT; + } + + return item_count; +} + +/** + * @name: FSataAhciFillCmdList + * @msg: allocate ahci command list information + * @param {FSataAhciPorts} *port_info is a pointer to the FSataAhciPorts instance + * @param {u32} description_info, prdtl+flag+cfl + * @return {void} + */ +static void FSataAhciFillCmdList(FSataAhciPorts *port_info, u32 description_info) +{ + FASSERT(port_info != NULL); + + port_info->cmd_list->description_info = description_info; + port_info->cmd_list->status = 0; + port_info->cmd_list->tbl_addr = ((u32)port_info->cmd_tbl_base_addr & FSATA_PORT_CMD_TABLE_ADDR_MASK); +#ifdef __aarch64__ + port_info->cmd_list->tbl_addr_hi = (u32)(((port_info->cmd_tbl_base_addr) >> 16) >> 16); +#endif +} + +/** + * @name: FSataAhciDataIO + * @msg: transfer ahci command fis and data buffer + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @param {u8} port number + * @param {u8} *fis, command fis buffer + * @param {int} fis_len, command fis length + * @param {u8} *buf, data read/write buffer + * @param {int} buf_len, data length + * @param {u8} is_write, 0-read, 1-write + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +static FError FSataAhciDataIO(FSataCtrl *instance_p, u8 port, u8 *fis, + int fis_len, u8 *buf, int buf_len, boolean is_ncq, boolean is_write) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(fis != NULL); + + FSataAhciPorts *port_info = &(instance_p->port[port]); + + uintptr base_addr = instance_p->config.base_addr; + uintptr port_base_addr = instance_p->port[port].port_base_addr; + + if (port >= instance_p->n_ports) + { + FSATA_DEBUG("Invalid port number %d", port); + return FSATA_ERR_INVAILD_PARAMETER; + } + + u32 reg_val = FSATA_READ_REG32(port_base_addr, FSATA_PORT_SCR_STAT); + if ((reg_val & FSATA_PORT_SCR_STAT_DET_MASK) != FSATA_PORT_SCR_STAT_DET_PHYRDY) + { + FSATA_ERROR("No Link on host %d port %d!", instance_p->config.instance_id, port); + return FSATA_ERR_OPERATION; + } + + /* copy fis command to command table CFIS */ + memcpy((unsigned char *)port_info->cmd_tbl_base_addr, fis, fis_len); + + /* copy data buffer address to command table prdt item */ + int prdt_length = FSataAhciFillCmdTablePrdt(instance_p, port, buf, buf_len); + if (prdt_length == -1) + { + FSATA_ERROR("FSataAhciFillCmdTablePrdt failed, buf_len = %d\n", buf_len); + return FSATA_ERR_INVAILD_PARAMETER; + } + + /* command list DW0: PRDTL(buf len) + W/R + CFL(fis len, 4 Byte(Dword) aligned) */ + u32 description_info = (prdt_length << 16) | (is_write << 6) | (fis_len >> 2); + + /* copy data to command list struct */ + FSataAhciFillCmdList(port_info, description_info); + + FCacheDCacheFlushRange((unsigned long)port_info->cmd_list, FSATA_AHCI_PORT_PRIV_DMA_SZ); + FCacheDCacheFlushRange((unsigned long)buf, (unsigned long)buf_len); + + /* set tag bit in SACT register before write CI register when use native cmd */ + if (is_ncq == TRUE) + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_SCR_ACT, FSATA_PORT_SCR_ACT_ENABLE); + + /* send cmd */ + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_CMD_ISSUE, FSATA_PORT_CMD_ISSUE_ENABLE); + + if (FSataWaitCmdCompleted(port_base_addr + FSATA_PORT_CMD_ISSUE, WAIT_MS_DATAIO, FSATA_PORT_CMD_ISSUE_ENABLE)) + { + FSATA_ERROR("timeout exit!"); + return FSATA_ERR_TIMEOUT; + } + + return FSATA_SUCCESS; +} + +/** + * @name: FSataReadWrite + * @msg: read or write sata block data, choose if use ncq + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @param {u8} port, port number + * @param {u32} start, start block + * @param {u32} blk_cnt, block count + * @param {u8} *buffer, data buffer + * @param {boolean} is_ncq, FALSE-not support ncq, TRUE-support ncq + * @param {boolean} is_write, read or write, FALSE-read, TRUE-write + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +FError FSataReadWrite(FSataCtrl *instance_p, u8 port, u32 start, + u16 blk_cnt, u8 *buffer, boolean is_ncq, boolean is_write) +{ + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(blk_cnt); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FSATA_SUCCESS; + + u16 now_blocks; /* number of blocks per iteration */ + u32 transfer_size; /* number of bytes per iteration */ + + u8 fis[20]; + /* Preset the FIS */ + memset(fis, 0, sizeof(fis)); + + fis[0] = FSATA_FIS_REG_HOST_TO_DEVICE;/* fis type */ + fis[1] = FSATA_FIS_REG_HOST_TO_DEVICE_C; /* C and PM Port */ + if (is_ncq == FALSE) + fis[2] = is_write ? FSATA_CMD_WRITE_EXT : FSATA_CMD_READ_EXT; /* Command */ + else + fis[2] = is_write ? FSATA_CMD_FPDMA_WRITE : FSATA_CMD_FPDMA_READ; /* Command */ + + while (blk_cnt) + { + now_blocks = min((u16)MAX_SATA_BLOCKS_READ_WRITE, blk_cnt); + transfer_size = FSATA_SECT_SIZE * now_blocks; + if (is_ncq == FALSE) + { + /* FEATURE Reserved */ + fis[3] = 0; /* features 7:0 */ + fis[11] = 0; /* features 15:8 */ + + /* LBA of first logical sector to be transferred */ + fis[4] = ((start >> 0) & 0xff); /* lba 7:0 */ + fis[5] = ((start >> 8) & 0xff); /* lba 15:8 */ + fis[6] = ((start >> 16) & 0xff); /* lba 23:16 */ + fis[8] = ((start >> 24) & 0xff); /* lba 31:24 */ + + /* device reg, bit 6 Shall be set to one in read command */ + fis[7] = FSATA_CMD_EXT_DEVICE; + + /* The number of logical sectors to be transferred. */ + fis[12] = (now_blocks >> 0) & 0xff;/* count 7:0 */ + fis[13] = (now_blocks >> 8) & 0xff;/* count 15:8 */ + } + else + { + /* FEATURE:The number of logical sectors to be transferred. */ + fis[3] = (now_blocks >> 0) & 0xff; /* features 7:0 */ + fis[11] = (now_blocks >> 8) & 0xff; /* features 15:8 */ + + /* LBA of first logical sector to be transferred */ + fis[4] = ((start >> 0) & 0xff); /* lba 7:0 */ + fis[5] = ((start >> 8) & 0xff); /* lba 15:8 */ + fis[6] = ((start >> 16) & 0xff); /* lba 23:16 */ + fis[8] = ((start >> 24) & 0xff); /* lba 31:24 */ + + /* device reg, bit 6 Shall be set to one */ + fis[7] = FSATA_CMD_EXT_DEVICE; + + /* count */ + fis[12] = 0;/* count 7:0, NCQ TAG field */ + fis[13] = 0;/* count 15:8, Normal priority */ + } + + ret = FSataAhciDataIO(instance_p, port, fis, sizeof(fis), + buffer, transfer_size, is_ncq, is_write); + if (ret) + { + FSATA_ERROR("scsi_ahci: SCSI command failure. ret = %#x", ret); + return FSATA_ERR_OPERATION; + } + + buffer += transfer_size; + blk_cnt -= now_blocks; + start += now_blocks; + } + return ret; +} + +/** + * @name: FSataCfgInitialize + * @msg: Initialize Sata ctrl + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance. + * @param {FSataConfig} *input_config_p, Default configuration parameters of FSata + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +FError FSataCfgInitialize(FSataCtrl *instance_p, const FSataConfig *input_config_p) +{ + FASSERT(instance_p); + + /*Set default values and configuration data */ + FSataCfgDeInitialize(instance_p); + + instance_p->config = *input_config_p; + + instance_p->is_ready = FT_COMPONENT_IS_READY; + + return FSATA_SUCCESS; +} + +/** + * @name: FSataCfgDeInitialize + * @msg: DeInitialization function for the device instance + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance. + * @return {*} + */ +void FSataCfgDeInitialize(FSataCtrl *pctrl) +{ + FASSERT(pctrl); + + pctrl->is_ready = 0; + memset(pctrl, 0, sizeof(*pctrl)); + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata.h b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata.h new file mode 100644 index 0000000000..d901b34485 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata.h @@ -0,0 +1,277 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsata.h + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 09:05:24 + * Description:  This files is for sata ctrl function definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_FSATA_H +#define BSP_DRIVERS_FSATA_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ +#include "ftypes.h" +#include "ferror_code.h" +#include "fkernel.h" + +#define FSATA_SUCCESS FT_SUCCESS +#define FSATA_ERR_INVAILD_PARAMETER FT_MAKE_ERRCODE(ErrModBsp, ErrBspSata, 1) +#define FSATA_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspSata, 2) +#define FSATA_ERR_OPERATION FT_MAKE_ERRCODE(ErrModBsp, ErrBspSata, 3) +#define FSATA_UNKNOWN_DEVICE FT_MAKE_ERRCODE(ErrModBsp, ErrBspSata, 4) + +/************************** Constant Definitions *****************************/ +#define FSATA_AHCI_MAX_PORTS 32 +#define FSATA_AHCI_MAX_PRD_ENTRIES 16 + +#define MAX_DATA_BYTE_COUNT SZ_4M + +#define FSATA_AHCI_CMD_LIST_HEADER_SIZE 0x20 +#define FSATA_AHCI_CMD_LIST_HEADER_NUM 32 +#define FSATA_AHCI_RX_FIS_SZ 0x100 +#define FSATA_AHCI_CMD_TABLE_HEADER_SIZE 0x80 +#define FSATA_AHCI_PRTD_ITEM_SIZE 0x10 +#define FSATA_AHCI_PRTD_ITEM_NUM 0x40 /*set 64 item, hardware max is 64K */ + +#define FSATA_AHCI_CMD_TABLE_SIZE (FSATA_AHCI_CMD_TABLE_HEADER_SIZE + (FSATA_AHCI_PRTD_ITEM_NUM * FSATA_AHCI_PRTD_ITEM_SIZE)) +#define FSATA_AHCI_PORT_PRIV_DMA_SZ (FSATA_AHCI_CMD_LIST_HEADER_SIZE * FSATA_AHCI_CMD_LIST_HEADER_NUM + \ + FSATA_AHCI_CMD_TABLE_SIZE + FSATA_AHCI_RX_FIS_SZ) + +#define FSATA_AHCI_CMD_ATAPI BIT(5) +#define FSATA_AHCI_CMD_WRITE BIT(6) +#define FSATA_AHCI_CMD_PREFETCH BIT(7) +#define FSATA_AHCI_CMD_RESET BIT(8) +#define FSATA_AHCI_CMD_CLR_BUSY BIT(10) + +#define FSATA_ID_LBA48_SECTORS 100 +#define FSATA_ID_LBA_SECTORS 60 + +#define FSATA_ID_ATA_DEVICE BIT(15) /* IDENTIFY DEVICE word 0, if ATA device */ +#define FSATA_ID_COMPLETE BIT(2) /* IDENTIFY DEVICE word 0, if the content of the IDENTIFY DEVICE data is incomplete */ + +#define FSATA_ID_FW_REV 23 /* firmware revision position */ +#define FSATA_ID_PROD 27 /* Model number position */ +#define FSATA_ID_WORDS 256 /* IDENTIFY DEVICE data length */ + +enum +{ + FSATA_FIS_REG_HOST_TO_DEVICE = 0x27, + FSATA_FIS_REG_DEVICE_TO_HOST = 0x34, + FSATA_FIS_DMA_SETUP = 0x41 +}; + +#define FSATA_FIS_REG_HOST_TO_DEVICE_C BIT(7) /* update of the command register */ +#define FSATA_CMD_EXT_DEVICE BIT(6) /* command device byte requirement */ + +enum +{ + FSATA_CMD_READ_EXT = 0x25, + FSATA_CMD_WRITE_EXT = 0x35, + FSATA_CMD_IDENTIFY_DEVICE = 0xEC, + FSATA_CMD_FPDMA_READ = 0x60, + FSATA_CMD_FPDMA_WRITE = 0x61 +}; + +#define FSATA_BUSY BIT(7) /* BSY status bit */ + +#define FSATA_SECT_SIZE 512 /* sata sector size */ + +#define FSATA_BLK_VEN_SIZE 40 /* device vendor string size */ +#define FSATA_BLK_PRD_SIZE 20 /* device product number size */ +#define FSATA_BLK_REV_SIZE 8 /* firmware revision size */ + +#define FSATA_DEV_TYPE_UNKNOWN 0xff /* not connected */ +#define FSATA_DEV_TYPE_HARDDISK 0x00 /* harddisk */ + +#define FSATA_IF_TYPE_UNKNOWN 0xff +#define FSATA_IF_TYPE_SCSI 0x00 + +enum +{ + FSATA_TYPE_PCIE = 0, + FSATA_TYPE_CONTROLLER = 1 +}; + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/* Number of User Addressable Logical Sectors lba28 */ +#define FSATA_ID_U32(id,n) \ + (((u32) (id)[(n) + 1] << 16) | ((u32) (id)[(n)])) + +/* Number of User Addressable Logical Sectors lba48 */ +#define FSATA_ID_U64(id,n) \ + ( ((u64) (id)[(n) + 3] << 48) | \ + ((u64) (id)[(n) + 2] << 32) | \ + ((u64) (id)[(n) + 1] << 16) | \ + ((u64) (id)[(n) + 0]) ) + +/* if sata id is support lba */ +#define FSataIdHasLba(id) ((id)[49] & BIT(9)) + +/* if sata id is support lba48 */ +static inline int FSataIdHasLba48(const u16 *id) +{ + if ((id[83] & 0xC000) != 0x4000) + return 0; + if (!FSATA_ID_U64(id, 100)) + return 0; + return id[83] & BIT(10); +} + +/**************************** Type Definitions *******************************/ +typedef void (*FSataIrqCallBack)(void *args); + +/* sata info */ +typedef struct +{ + unsigned char if_type; /* type of the interface */ + unsigned char type; /* device type */ + char vendor[FSATA_BLK_VEN_SIZE + 1]; /* device vendor string */ + char product[FSATA_BLK_PRD_SIZE + 1]; /* device product number */ + char revision[FSATA_BLK_REV_SIZE + 1]; /* firmware revision */ + unsigned long lba; /* number of blocks */ + unsigned long lba512; /* number of blocks of 512 bytes */ + unsigned long blksz; /* block size */ +} FSataInfo; + +/* Received FIS Structure */ +typedef struct __attribute__((__packed__)) +{ + u8 dma_setup_fis[28]; + u8 reserved0[4]; + u8 pio_setup_fis[20]; + u8 reserved1[12]; + u8 d2h_register_fis[20]; + u8 reserved2[4]; + u8 set_device_bits_fis[8]; + u8 unknown_fis[64]; + u8 reserved3[96]; +} +FSataAhciRecvFis; + +/* command list structure - command header */ +typedef struct +{ + u32 description_info;/* DW 0 – Description Information */ + u32 status; /* DW 1 - Command Status */ + u32 tbl_addr; /* DW 2 – Command Table Base Address */ + u32 tbl_addr_hi; /* DW 3 – Command Table Base Address Upper */ + u32 reserved[4]; +} FSataAhciCommandList; + +/* command table - PRDT */ +typedef struct +{ + u32 addr_low; /* DW 0 – Data Base Address */ + u32 addr_high; /* DW 1 – Data Base Address Upper */ + u32 reserved; /* DW 2 – Reserved */ + u32 data_byte; /* DW 3 – Description Information */ +} FSataAhciCommandTablePrdt; + +/* ahci port information structure */ +typedef struct +{ + uintptr port_base_addr; /* port base address */ + FSataAhciCommandList *cmd_list; /* Command List structure, will include cmd_tbl's address */ + FSataAhciRecvFis *rx_fis; /* Received FIS Structure */ + uintptr cmd_tbl_base_addr; /* command table addr, also the command table's first part */ + FSataAhciCommandTablePrdt *cmd_tbl_prdt;/* command table's second part , cmd_tbl + cmd_tbl_prdt = command table*/ + FSataInfo dev_info; +} FSataAhciPorts; + +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* sata base address */ + char *instance_name; /* instance name */ + u32 irq_num; /* Irq number */ +} FSataConfig; /* sata config */ + +typedef struct +{ + FSataConfig config; + u32 is_ready; + + FSataAhciPorts port[FSATA_AHCI_MAX_PORTS]; + u16 *ataid[FSATA_AHCI_MAX_PORTS]; + u32 n_ports; /* maximum number of ports supported by the ahci, Number of Ports (NP)*/ + u32 port_map; /* each bit indicate port can be used, If a bit is set to ‘1’, the corresponding port is available for software to use. */ + u32 link_port_map; /* each bit indicate port linkup sata device */ + u32 private_data; /* each bit indicate port sata achi started */ + + FSataIrqCallBack fsata_dhrs_cb; /* device-to-host register fis interrupt */ + void *dhrs_args; + FSataIrqCallBack fsata_pss_cb; /* pio setup fis interrupt */ + void *pss_args; + FSataIrqCallBack fsata_dss_cb; /* dma setup fis interrupt */ + void *dss_args; + FSataIrqCallBack fsata_sdbs_cb; /* set device bits interrupt */ + void *sdbs_args; + FSataIrqCallBack fsata_pcs_cb; /* port connect change status interrupt */ + void *pcs_args; + + volatile u8 dhrs_flag; + volatile u8 sdb_flag; +} FSataCtrl; + + +/************************** Function Prototypes ******************************/ + +/* sata config init */ +const FSataConfig *FSataLookupConfig(u32 instance_id, u8 type); + +/* initialize sata ctrl */ +FError FSataCfgInitialize(FSataCtrl *instance_p, const FSataConfig *input_config_p); + +/* deinitialize sata ctrl */ +void FSataCfgDeInitialize(FSataCtrl *pctrl); + +/* read sata info */ +FError FSataAhciReadInfo(FSataCtrl *instance_p, u8 port); + +/* init ahci */ +FError FSataAhciInit(FSataCtrl *instance_p); + +/* init ahci port */ +FError FSataAhciPortStart(FSataCtrl *instance_p, u8 port, uintptr mem); + +/* read or write sata data */ +FError FSataReadWrite(FSataCtrl *instance_p, u8 port, u32 start, + u16 blk_cnt, u8 *buffer, boolean is_ncq, boolean is_write); + +/* sata all irq handler entry */ +void FSataIrqHandler(s32 vector, void *param); + +/* set specific sata irq function entry */ +FError FSataSetHandler(FSataCtrl *instance_p, u32 handler_type, + void *func_pointer, void *call_back_ref); + +/* set sata irq mask */ +void FSataIrqEnable(FSataCtrl *instance_p, u32 int_mask); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_g.c b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_g.c new file mode 100644 index 0000000000..dc90afa636 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_g.c @@ -0,0 +1,103 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsata_g.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 09:03:08 + * Description:  This files is for static config of sata ctrl + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fparameters.h" +#include "fsata.h" +#include "sdkconfig.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + + +/* configs of pcie ahci ctrl */ +const FSataConfig FSataPcieConfigTbl[PLAT_AHCI_HOST_MAX_COUNT] = +{ + [0] = + { + .base_addr = AHCI_BASE_0, + .instance_name = "sata0", + .irq_num = AHCI_IRQ_0 /* Irq number */ + + }, + [1] = + { + .base_addr = AHCI_BASE_1, + .instance_name = "sata1", + .irq_num = AHCI_IRQ_1 /* Irq number */ + + }, + [2] = + { + .base_addr = AHCI_BASE_2, + .instance_name = "sata2", + .irq_num = AHCI_IRQ_2 /* Irq number */ + + }, + [3] = + { + .base_addr = AHCI_BASE_3, + .instance_name = "sata3", + .irq_num = AHCI_IRQ_3 /* Irq number */ + + }, + [4] = + { + .base_addr = AHCI_BASE_4, + .instance_name = "sata4", + .irq_num = AHCI_IRQ_4 /* Irq number */ + + }, +}; + +#if defined(CONFIG_TARGET_E2000) + +/* configs of controller ahci ctrl */ +const FSataConfig FSataControllerConfigTbl[FSATA_INSTANCE_NUM] = +{ + [0] = + { + .instance_id = FSATA_INSTANCE_0, + .base_addr = FSATA0_BASEADDR, + .instance_name = "sata0", + .irq_num = FSATA0_IRQNUM /* Irq number */ + + }, + [1] = + { + .instance_id = FSATA_INSTANCE_1, + .base_addr = FSATA1_BASEADDR, + .instance_name = "sata1", + .irq_num = FSATA1_IRQNUM /* Irq number */ + + }, + +}; + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_hw.c b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_hw.c new file mode 100644 index 0000000000..278636bc93 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_hw.c @@ -0,0 +1,36 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsata_hw.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 09:03:23 + * Description:  This files is for sata register function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fsata_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_hw.h b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_hw.h new file mode 100644 index 0000000000..39c1b8001f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_hw.h @@ -0,0 +1,164 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsata_hw.h + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 09:03:41 + * Description:  This files is for ctrl of sata functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_FSATA_HW_H +#define BSP_DRIVERS_FSATA_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fkernel.h" +#include "ftypes.h" +#include "fio.h" + +/************************** Constant Definitions *****************************/ +/* SATA register definitions */ + +/* Global controller registers */ +#define FSATA_HOST_CAP 0x00 /* host capabilities */ +#define FSATA_HOST_CTL 0x04 /* global host control */ +#define FSATA_HOST_IRQ_STAT 0x08 /* interrupt status */ +#define FSATA_HOST_PORTS_IMPL 0x0c /* bitmap of implemented ports */ +#define FSATA_HOST_VERSION 0x10 /* AHCI spec. version compliancy */ +#define FSATA_HOST_CAP2 0x24 /* host capabilities, extended */ + +/* FSATA_HOST_CTL bits */ +#define FSATA_HOST_CAP_NP_MASK GENMASK(4, 0) /* Number of Ports (NP) */ +#define FSATA_HOST_AHCI_EN BIT(31) /* AHCI enabled */ +#define FSATA_HOST_CAP_SMPS BIT(28) /* AHCI Supports Mechanical Presence Switch */ +#define FSATA_HOST_CAP_SSS BIT(27) /* AHCI staggered spin-up */ +#define FSATA_HOST_CAP_SPM BIT(17) /* AHCI port multiplier */ +#define FSATA_HOST_IRQ_EN BIT(1) /* global IRQ enable */ +#define FSATA_HOST_RESET BIT(0) /* reset controller; self-clear */ +#define FSATA_HOST_PORTS_IMPL_MASK(x) GENMASK(x, 0) /* Ports Implemented */ + +/* Registers for each SATA port */ +#define FSATA_PORT_LST_ADDR 0x00 /* command list DMA addr */ +#define FSATA_PORT_LST_ADDR_HI 0x04 /* command list DMA addr hi */ +#define FSATA_PORT_FIS_ADDR 0x08 /* FIS rx buf addr */ +#define FSATA_PORT_FIS_ADDR_HI 0x0c /* FIS rx buf addr hi */ +#define FSATA_PORT_IRQ_STAT 0x10 /* interrupt status */ +#define FSATA_PORT_IRQ_MASK 0x14 /* interrupt enable/disable mask */ +#define FSATA_PORT_CMD 0x18 /* port command */ +#define FSATA_PORT_TFDATA 0x20 /* taskfile data */ +#define FSATA_PORT_SIG 0x24 /* device TF signature */ +#define FSATA_PORT_SCR_STAT 0x28 /* SATA phy register: SStatus */ +#define FSATA_PORT_SCR_CTL 0x2c /* SATA phy register: SControl */ +#define FSATA_PORT_SCR_ERR 0x30 /* SATA phy register: SError */ +#define FSATA_PORT_SCR_ACT 0x34 /* SATA phy register: SActive */ +#define FSATA_PORT_CMD_ISSUE 0x38 /* command issue */ + +/* PORT_SCR_STAT bits */ +#define FSATA_PORT_SCR_STAT_DET_MASK GENMASK(3, 0) +#define FSATA_PORT_SCR_STAT_DET_COMINIT 0x1 +#define FSATA_PORT_SCR_STAT_DET_PHYRDY 0x3 /* SATA exist and phy connected */ + +/* PORT_CMD bits */ +#define FSATA_PORT_CMD_LIST_ADDR_MASK GENMASK(31, 10) +#define FSATA_PORT_CMD_FIS_ADDR_MASK GENMASK(31, 8) +#define FSATA_PORT_CMD_TABLE_ADDR_MASK GENMASK(31, 7) + +#define FSATA_PORT_CMD_ATAPI BIT(24) /* Device is ATAPI */ +#define FSATA_PORT_CMD_LIST_ON BIT(15) /* cmd list DMA engine running */ +#define FSATA_PORT_CMD_FIS_ON BIT(14) /* FIS DMA engine running */ +#define FSATA_PORT_CMD_FIS_RX BIT(4) /* Enable FIS receive DMA engine */ +#define FSATA_PORT_CMD_CLO BIT(3) /* Command list override */ +#define FSATA_PORT_CMD_POWER_ON BIT(2) /* Power up device */ +#define FSATA_PORT_CMD_SPIN_UP BIT(1) /* Spin up device */ +#define FSATA_PORT_CMD_START BIT(0) /* Enable port DMA engine */ + +#define FSATA_PORT_CMD_ICC_ACTIVE BIT(28) /* Put i/f in active state */ +#define FSATA_PORT_CMD_ICC_PARTIAL BIT(29) /* Put i/f in partial state */ +#define FSATA_PORT_CMD_ICC_SLUMBER (0x6 << 28) /* Put i/f in slumber state */ + +#define FSATA_PORT_TFDATA_ATA_BUSY BIT(7) /* BSY status bit */ +#define FSATA_PORT_TFDATA_ATA_DRDY BIT(6) /* device ready */ +#define FSATA_PORT_TFDATA_ATA_DF BIT(5) /* device fault */ +#define FSATA_PORT_TFDATA_ATA_DRQ BIT(3) /* data request i/o */ +#define FSATA_PORT_TFDATA_ATA_ERR BIT(0) /* have an error */ + +/* PORT_IRQ_{STAT,MASK} bits */ +#define FSATA_PORT_IRQ_COLD_PRES BIT(31) /* cold presence detect */ +#define FSATA_PORT_IRQ_TF_ERR BIT(30) /* task file error */ +#define FSATA_PORT_IRQ_HBUS_ERR BIT(29) /* host bus fatal error */ +#define FSATA_PORT_IRQ_HBUS_DATA_ERR BIT(28) /* host bus data error */ +#define FSATA_PORT_IRQ_IF_ERR BIT(27) /* interface fatal error */ +#define FSATA_PORT_IRQ_IF_NONFATAL BIT(26) /* interface non-fatal error */ +#define FSATA_PORT_IRQ_OVERFLOW BIT(24) /* xfer exhausted available S/G */ +#define FSATA_PORT_IRQ_BAD_PMP BIT(23) /* incorrect port multiplier */ + +#define FSATA_PORT_IRQ_PHYRDY BIT(22) /* PhyRdy changed */ +#define FSATA_PORT_IRQ_DEV_ILCK BIT(7) /* device interlock */ +#define FSATA_PORT_IRQ_CONNECT BIT(6) /* port connect change status */ +#define FSATA_PORT_IRQ_SG_DONE BIT(5) /* descriptor processed */ +#define FSATA_PORT_IRQ_UNK_FIS BIT(4) /* unknown FIS rx'd */ +#define FSATA_PORT_IRQ_SDB_FIS BIT(3) /* Set Device Bits FIS rx'd */ +#define FSATA_PORT_IRQ_DMAS_FIS BIT(2) /* DMA Setup FIS rx'd */ +#define FSATA_PORT_IRQ_PIOS_FIS BIT(1) /* PIO Setup FIS rx'd */ +#define FSATA_PORT_IRQ_D2H_REG_FIS BIT(0) /* D2H Register FIS rx'd */ + +#define FSATA_PORT_IRQ_FREEZE FSATA_PORT_IRQ_CONNECT | FSATA_PORT_IRQ_SDB_FIS | \ + FSATA_PORT_IRQ_D2H_REG_FIS | FSATA_PORT_IRQ_PIOS_FIS + +#define FSATA_PORT_SCR_ACT_ENABLE BIT(0) /* Port Serial ATA Active */ +#define FSATA_PORT_CMD_ISSUE_ENABLE BIT(0) /* Port Command Issue enable */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/** + * @name: SATA_READ_REG32 + * @msg: 读取SATA寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @return {u32} 寄存器参数 + */ +#define FSATA_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)reg_offset) + +/** + * @name: SATA_WRITE_REG32 + * @msg: 写入SATA寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @param {u32} reg_value 写入寄存器参数 + * @return {void} + */ +#define FSATA_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)reg_offset, (u32)reg_value) + +#define FSATA_SETBIT(base_addr, reg_offset, data) \ + FtSetBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#define FSATA_CLEARBIT(base_addr, reg_offset, data) \ + FtClearBit32((base_addr) + (u32)(reg_offset), (u32)(data)) + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_intr.c b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_intr.c new file mode 100644 index 0000000000..56fc9dc401 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_intr.c @@ -0,0 +1,223 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsata_intr.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 09:03:57 + * Description:  This files is for intrrupt function of Sata ctrl + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include "fassert.h" +#include "fdebug.h" +#include "fsata.h" +#include "fsata_hw.h" +#include "finterrupt.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +#define FSATA_DEBUG_TAG "FSATA_INTR" +#define FSATA_ERROR(format, ...) FT_DEBUG_PRINT_E(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSATA_WARN(format, ...) FT_DEBUG_PRINT_W(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSATA_INFO(format, ...) FT_DEBUG_PRINT_I(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSATA_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSATA_DEBUG_TAG, format, ##__VA_ARGS__) + +/** + * @name: FSataIrqEnable + * @msg: enable sata interrupt mask + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @param {u32} int_mask, interrupt enable mask + * @return {void} + */ +void FSataIrqEnable(FSataCtrl *instance_p, u32 int_mask) +{ + u32 reg_value; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + u32 port = instance_p->private_data; + u32 i; + for (i = 0; i < instance_p->n_ports; i++) + { + if (!(port & BIT(i))) + continue; + + uintptr port_base_addr = instance_p->port[i].port_base_addr; + FSATA_SETBIT(port_base_addr, FSATA_PORT_IRQ_MASK, int_mask); + } +} + +/** + * @name: FSataIrqDisable + * @msg: disable sata interrupt mask + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @param {u32} int_mask, interrupt disable mask + * @return {void} + */ +void FSataIrqDisable(FSataCtrl *instance_p, u32 int_mask) +{ + u32 reg_value; + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + u32 port = instance_p->private_data; + u32 i; + for (i = 0; i < instance_p->n_ports; i++) + { + if (!(port & BIT(i))) + continue; + + uintptr port_base_addr = instance_p->port[i].port_base_addr; + + FSATA_CLEARBIT(port_base_addr, FSATA_PORT_IRQ_MASK, int_mask); + } +} + +/** + * @name: FSataSetHandler + * @msg: set sata interrupt handler function + * @param {FSataCtrl} *instance_p, pointer to the FSataCtrl instance + * @param {u32} irq_type, interrupt type + * @param {void} *func_pointer, interrupt handler function + * @param {void} *call_back_ref, interrupt handler function argument + * @return {FError} return FSATA_SUCCESS if successful, return others if failed + */ +FError FSataSetHandler(FSataCtrl *instance_p, u32 irq_type, void *func_pointer, void *call_back_ref) +{ + FError status = FT_SUCCESS; + FASSERT(instance_p != NULL); + FASSERT(func_pointer != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + + switch (irq_type) + { + case FSATA_PORT_IRQ_D2H_REG_FIS: + instance_p->fsata_dhrs_cb = ((FSataIrqCallBack)(void *)func_pointer); + instance_p->dhrs_args = call_back_ref; + break; + + case FSATA_PORT_IRQ_SDB_FIS: + instance_p->fsata_sdbs_cb = ((FSataIrqCallBack)(void *)func_pointer); + instance_p->sdbs_args = call_back_ref; + break; + + case FSATA_PORT_IRQ_CONNECT: + instance_p->fsata_pcs_cb = ((FSataIrqCallBack)(void *)func_pointer); + instance_p->pcs_args = call_back_ref; + break; + + case FSATA_PORT_IRQ_PIOS_FIS: + instance_p->fsata_pss_cb = ((FSataIrqCallBack)(void *)func_pointer); + instance_p->pss_args = call_back_ref; + break; + + default: + status = (FSATA_ERR_OPERATION); + break; + } + return status; +} + +/** + * @name: FSataIrqHandler + * @msg: sata interrupt handler entry + * @param {void} *param, function parameters, users can set + * @return {void} + */ +void FSataIrqHandler(s32 vector, void *param) +{ + FSataCtrl *instance_p = (FSataCtrl *)param; + FSataConfig *config_p; + + FASSERT(instance_p != NULL); + FASSERT(instance_p->is_ready == FT_COMPONENT_IS_READY); + u32 port = instance_p->private_data; + u32 status; + u32 mask_status = 0; + uintptr base_addr = instance_p->config.base_addr; + u32 irq_state = 0; + u32 i = 0; + + uintptr port_base_addr = 0; + + for (i = 0; i < instance_p->n_ports; i++) + { + if (!(port & BIT(i))) + continue; + + port_base_addr = instance_p->port[i].port_base_addr; + irq_state = FSATA_READ_REG32(base_addr, FSATA_HOST_IRQ_STAT); + status = FSATA_READ_REG32(port_base_addr, FSATA_PORT_IRQ_STAT); + mask_status = FSATA_READ_REG32(port_base_addr, FSATA_PORT_IRQ_MASK); + + /* clear port first, host second */ + FSATA_WRITE_REG32(port_base_addr, FSATA_PORT_IRQ_STAT, status); + FSATA_WRITE_REG32(base_addr, FSATA_HOST_IRQ_STAT, irq_state); + + if (status & mask_status & FSATA_PORT_IRQ_D2H_REG_FIS) + { + if (instance_p->fsata_dhrs_cb) + { + instance_p->fsata_dhrs_cb(instance_p->dhrs_args); + } + } + + if (status & mask_status & FSATA_PORT_IRQ_PIOS_FIS) + { + if (instance_p->fsata_pss_cb) + { + instance_p->fsata_pss_cb(instance_p->pss_args); + } + } + + if (status & mask_status & FSATA_PORT_IRQ_SDB_FIS) + { + if (instance_p->fsata_sdbs_cb) + { + instance_p->fsata_sdbs_cb(instance_p->sdbs_args); + } + } + + if (status & mask_status & FSATA_PORT_IRQ_DMAS_FIS) + { + if (instance_p->fsata_dss_cb) + { + instance_p->fsata_dss_cb(instance_p->dss_args); + } + } + + if (status & mask_status & FSATA_PORT_IRQ_CONNECT) + { + if (instance_p->fsata_pcs_cb) + { + instance_p->fsata_pcs_cb(instance_p->pcs_args); + } + + /* reset hba */ + FSATA_WRITE_REG32(base_addr, FSATA_HOST_CTL, FSATA_HOST_RESET); + FSataAhciInit(instance_p); + FSataIrqEnable(instance_p, FSATA_PORT_IRQ_FREEZE); + } + + } +} + diff --git a/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_sinit.c b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_sinit.c new file mode 100644 index 0000000000..8f0af5c686 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/sata/fsata/fsata_sinit.c @@ -0,0 +1,72 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fsata_sinit.c + * Date: 2022-02-10 14:55:11 + * LastEditTime: 2022-02-18 09:04:15 + * Description:  This files is for sata static init + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fsata.h" +#include "fparameters.h" +#include "sdkconfig.h" +#include "fassert.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +extern const FSataConfig FSataPcieConfigTbl[PLAT_AHCI_HOST_MAX_COUNT]; + +#if defined(CONFIG_TARGET_E2000) + extern const FSataConfig FSataControllerConfigTbl[FSATA_INSTANCE_NUM]; +#endif + +/*****************************************************************************/ +/** + * @name: FSataLookupConfig + * @msg: get sata configs by id and type, Support both pcie and SATA controllers + * @return {FSataConfig *} + * @param {u32} instance_id, id of sata ctrl + */ +const FSataConfig *FSataLookupConfig(u32 instance_id, u8 type) +{ + const FSataConfig *pconfig = NULL; + if (type == FSATA_TYPE_CONTROLLER) + { +#if defined(CONFIG_TARGET_E2000) + FASSERT(instance_id < FSATA_INSTANCE_NUM); + pconfig = &FSataControllerConfigTbl[instance_id]; +#endif + } + else + { + FASSERT(instance_id < PLAT_AHCI_HOST_MAX_COUNT); + pconfig = &FSataPcieConfigTbl[instance_id]; + } + + return (const FSataConfig *)pconfig; +} + diff --git a/bsp/phytium/libraries/standalone/drivers/serial/Kconfig b/bsp/phytium/libraries/standalone/drivers/serial/Kconfig new file mode 100644 index 0000000000..e84c41301c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/Kconfig @@ -0,0 +1,10 @@ + +menu "Usart Configuration" + config ENABLE_Pl011_UART + bool + prompt "Use Pl011 uart" + default n + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011.c b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011.c new file mode 100644 index 0000000000..f7023b1b2f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011.c @@ -0,0 +1,287 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:07:24 + * Description:  This files is for uart functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files ********************************/ + +#include "fpl011.h" +#include "fio.h" +#include "ferror_code.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +u32 FPl011SendBuffer(FPl011 *uart_p); +u32 FPl011ReceiveBuffer(FPl011 *uart_p); + +static void FPl011StubHandler(void *Args, u32 Event, + u32 ByteCount); +/*****************************************************************************/ + + +FError FPl011CfgInitialize(FPl011 *uart_p, FPl011Config *config) +{ + u32 reg_value = 0; + FError ret ; + FASSERT(uart_p != NULL); + FASSERT(config != NULL); + + uart_p->config.instance_id = config->instance_id; + uart_p->config.base_address = config->base_address; + uart_p->config.ref_clock_hz = config->ref_clock_hz; + uart_p->config.irq_num = config->irq_num; + uart_p->config.baudrate = config->baudrate; + + uart_p->handler = FPl011StubHandler; + + uart_p->send_buffer.byte_p = NULL; + uart_p->send_buffer.requested_bytes = 0; + uart_p->send_buffer.remaining_bytes = 0; + + uart_p->receive_buffer.byte_p = NULL; + uart_p->receive_buffer.requested_bytes = 0; + uart_p->receive_buffer.remaining_bytes = 0; + uart_p->rxbs_error = 0; + + uart_p->is_ready = FT_COMPONENT_IS_READY; + ret = FPl011SetBaudRate(uart_p, uart_p->config.baudrate); + if (ret != FT_SUCCESS) + { + uart_p->is_ready = 0U; + } + else + { + /* + * Set up the default data format: 8 bit data, 1 stop bit, no + * parity + */ + reg_value = ((FPL011_FORMAT_WORDLENGTH_8BIT << 5) & FPL011LCR_H_WLEN); //config.base_address, FPL011LCR_H_OFFSET, reg_value); + + /* Set the RX FIFO trigger at 8 data bytes.Tx FIFO trigger is 8 data bytes*/ + reg_value = (1 << 3) | (1 << 0); + FUART_WRITEREG32(uart_p->config.base_address, FPL011IFLS_OFFSET, reg_value); + + /* Disable all interrupts, polled mode is the default */ + reg_value = 0; + FUART_WRITEREG32(uart_p->config.base_address, FPL011IMSC_OFFSET, reg_value); + } + + return FT_SUCCESS; +} + + +/** + * @name: FPl011Send + * @msg: This functions sends the specified buffer using the device in either + * polled or interrupt driven mode. + * @return The number of bytes actually sent. + * @param uart_p is a pointer to the FPl011 instance. + * @param byte_p is pointer to a buffer of data to be sent. + * @param length ontains the number of bytes to be sent. Any data that was already put into the + * transmit FIFO will be sent. + */ +u32 FPl011Send(FPl011 *uart_p, u8 *byte_p, u32 length) +{ + u32 sent_count = 0; + FASSERT(uart_p != NULL); + FASSERT(byte_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + + uart_p->send_buffer.byte_p = byte_p; + uart_p->send_buffer.requested_bytes = length; + uart_p->send_buffer.remaining_bytes = length; + sent_count = FPl011SendBuffer(uart_p); + return sent_count; +} + + + +static void FPl011StubHandler(void *args, u32 event, + u32 byte_count) +{ + (void)args; + (void)event; + (void)byte_count; + + FASSERT(0); +} + +/** + * @name: FPl011SendBuffer + * @msg: send data buffer through uart + * @return {*} + * @param uart_p + */ +u32 FPl011SendBuffer(FPl011 *uart_p) +{ + u32 sent_count = 0U; + u32 isbusy; + + isbusy = (u32)FUART_ISTRANSMITBUSY(uart_p->config.base_address); + while (isbusy == TRUE) + { + isbusy = (u32)FUART_ISTRANSMITBUSY(uart_p->config.base_address); + } + + /* + * If the TX FIFO is full, send nothing. + * Otherwise put bytes into the TX FIFO unil it is full, or all of the + * data has been put into the FIFO. + */ + while ((!FUART_ISTRANSMITFULL(uart_p->config.base_address)) && (uart_p->send_buffer.remaining_bytes > sent_count)) + { + FUART_WRITEREG32(uart_p->config.base_address, FPL011DR_OFFSET, (u32)uart_p->send_buffer.byte_p[sent_count]); + sent_count++; + } + /* Update the buffer to reflect the bytes that were sent from it */ + uart_p->send_buffer.byte_p += sent_count; + uart_p->send_buffer.remaining_bytes -= sent_count; + + return sent_count; +} + +/** + * @name: FPl011Receive + * @msg: This function attempts to receive a specified number of bytes of data + * from the device and store it into the specified buffer. + * @param uart_p is a pointer to the FPl011 instance + * @param byte_p is pointer to buffer for data to be received into + * @param length is the number of bytes to be received. + * @return The number of bytes received. + */ +u32 FPl011Receive(FPl011 *uart_p, u8 *byte_p, u32 length) +{ + u32 received; + + FASSERT(uart_p != NULL); + FASSERT(byte_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + + uart_p->receive_buffer.byte_p = byte_p; + uart_p->receive_buffer.requested_bytes = length; + uart_p->receive_buffer.remaining_bytes = length; + + received = FPl011ReceiveBuffer(uart_p); + + return received; +} + + +u32 FPl011ReceiveBuffer(FPl011 *uart_p) +{ + + u32 received_count = 0U; + u32 event; + u32 event_data; + u32 byte_value; + + while ((received_count < uart_p->receive_buffer.remaining_bytes) && !FUART_ISRECEIVEDATA(uart_p->config.base_address)) + { + byte_value = FUART_READREG32(uart_p->config.base_address, FPL011DR_OFFSET); + + if (uart_p->rxbs_error) + { + if ((byte_value & FPL011DR_ALLE) != 0) + { + event_data = byte_value; + event = FPL011_EVENT_PARE_FRAME_BRKE; + + if (uart_p->handler) + { + uart_p->handler(uart_p->args, event, event_data); + } + } + } + uart_p->receive_buffer.byte_p[received_count] = (u8)(byte_value & 0xff); + received_count++; + } + + uart_p->rxbs_error = 0; + + if (uart_p->receive_buffer.byte_p != NULL) + { + uart_p->receive_buffer.byte_p += received_count; + } + uart_p->receive_buffer.remaining_bytes -= received_count; + + return received_count; +} + +/** + * @name: FPl011BlockSend + * @msg: initiate uart block send + * @return {*} + * @param uart_p + * @param byte_p + * @param length + */ +void FPl011BlockSend(FPl011 *uart_p, u8 *byte_p, u32 length) +{ + u32 index; + + FASSERT(uart_p != NULL); + FASSERT(byte_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + + for (index = 0; index < length; index++) + { + FPl011SendByte(uart_p->config.base_address, byte_p[index]); + } +} + +/** + * @name: FPl011BlockReceive + * @msg: initiate uart block receive + * @return {*} + * @param uart_p + */ +u8 FPl011BlockReceive(FPl011 *uart_p) +{ + FASSERT(uart_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + return FPl011RecvByte(uart_p->config.base_address); +} + +void FPl011IrqClearReciveTimeOut(FPl011 *uart_p) +{ + u32 reg_temp; + reg_temp = FPl011GetInterruptMask(uart_p); + reg_temp &= ~FPL011MIS_RTMIS; + FPl011SetInterruptMask(uart_p, reg_temp); +} + +void FPl011IrqEnableReciveTimeOut(FPl011 *uart_p) +{ + u32 reg_temp; + reg_temp = FPl011GetInterruptMask(uart_p); + reg_temp |= FPL011MIS_RTMIS; + FPl011SetInterruptMask(uart_p, reg_temp); +} diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011.h b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011.h new file mode 100644 index 0000000000..349b6a352e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011.h @@ -0,0 +1,182 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:07:38 + * Description:  This files is for uart functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_SERIAL_PL011_UART_H +#define BSP_DRIVERS_SERIAL_PL011_UART_H + + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fassert.h" +#include "fpl011_hw.h" +#include "sdkconfig.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FPL011_ERROR_PARAM FT_CODE_ERR(ErrModBsp, ErrBspUart, 0x1u) + +#define FPL011_BAUDRATE 115200U + +/* Config options */ +#define FPL011_OPTION_UARTEN 0x1U +#define FPL011_OPTION_RXEN 0x2U +#define FPL011_OPTION_TXEN 0x4U +#define FPL011_OPTION_FIFOEN 0x8U +#define FPL011_OPTION_CTS 0x10U +#define FPL011_OPTION_RTS 0x20U +#define FPL011_OPTION_DTR 0x40U +#define FPL011_OPTION_RTSEN 0x80U +#define FPL011_OPTION_CTSEN 0x100U +#define FPL011_OPTION_TXDMAEN 0x200U +#define FPL011_OPTION_RXDMAEN 0x400U + +/* Channel Operational Mode */ +#define FPL011_OPER_MODE_NORMAL (u8)0x00U /* Normal Mode */ +#define FPL011_OPER_MODE_LOCAL_LOOP (u8)0x01U /* Local Loop back Mode */ + + +/* Data format values */ +#define FPL011_FORMAT_WORDLENGTH_8BIT 0x3 +#define FPL011_FORMAT_WORDLENGTH_7BIT 0x2 +#define FPL011_FORMAT_WORDLENGTH_6BIT 0x1 +#define FPL011_FORMAT_WORDLENGTH_5BIT 0x0 + +#define FPL011_FORMAT_NO_PARITY 0U /* No parity */ +#define FPL011_FORMAT_EN_PARITY 1U /* Enable parity */ +#define FPL011_FORMAT_EVEN_PARITY 2U /* Even parity */ +#define FPL011_FORMAT_ODD_PARITY 0U /* Odd parity */ +#define FPL011_FORMAT_EN_STICK_PARITY 4U /* Stick parity */ +#define FPL011_FORMAT_NO_STICK_PARITY 0U /* Stick parity */ + +#define FPL011_FORMAT_PARITY_MASK 7U /* Format parity mask */ + +#define FPL011_FORMAT_EVEN_PARITY_SHIFT 1U /* Even parity shift */ +#define FPL011_FORMAT_EN_STICK_PARITY_SHIFT 5U /* Stick parity shift */ + +#define FPL011_FORMAT_2_STOP_BIT 1U +#define FPL011_FORMAT_1_STOP_BIT 0U + + +/* Callback events */ +#define FPL011_EVENT_RECV_DATA 1U /* Data receiving done */ +#define FPL011_EVENT_RECV_TOUT 2U /* A receive timeout occurred */ +#define FPL011_EVENT_SENT_DATA 3U /* Data transmission done */ +#define FPL011_EVENT_RECV_ERROR 4U /* A receive error detected */ +#define FPL011_EVENT_MODEM 5U /* Modem status changed */ +#define FPL011_EVENT_PARE_FRAME_BRKE 6U /* A receive parity, frame, break \ + * error detected */ +#define FPL011_EVENT_RECV_ORERR 7U /* A receive overrun error detected */ + + +/**************************** Type Definitions ******************************/ + +/** + * Keep track of data format setting of a device. + */ +typedef struct +{ + u32 baudrate ; /* In bps, ie 1200 */ + u32 data_bits ; /* Number of data bits */ + u32 parity ; /* Parity */ + u8 stopbits ; /* Number of stop bits */ +} FPl011Format ; + + +typedef struct +{ + u32 instance_id; /* Id of device*/ + u32 base_address; + u32 ref_clock_hz; + u32 irq_num; + u32 baudrate; +} FPl011Config; + +typedef struct +{ + u8 *byte_p; + u32 requested_bytes; + u32 remaining_bytes; +} FPl011Buffer; + +typedef void (*FPl011EventHandler)(void *args, u32 event, u32 event_data); + +typedef struct +{ + FPl011Config config; /* Configuration data structure */ + u32 is_ready; /* Device is ininitialized and ready*/ + + FPl011Buffer send_buffer; + FPl011Buffer receive_buffer; + + FPl011EventHandler handler; + void *args; + uint8_t rxbs_error; /* An error occurs during receiving. 0 has no error and 1 has an error */ + +} FPl011; + + +/************************** Function Prototypes ******************************/ + +/* FPl011_uart_sinit.c */ +const FPl011Config *FPl011LookupConfig(u32 instance_id); +/* FPl011_uart.c */ +FError FPl011CfgInitialize(FPl011 *uart_p, FPl011Config *config); +void FPl011BlockSend(FPl011 *uart_p, u8 *byte_p, u32 length); +u32 FPl011Send(FPl011 *uart_p, u8 *byte_p, u32 length); +u32 FPl011Receive(FPl011 *uart_p, u8 *byte_p, u32 length); +u8 FPl011BlockReceive(FPl011 *uart_p); +void FPl011ProgramCtlReg(FPl011 *uart_p, u32 ctrl_reg); + +/* FPl011_uart_options.c */ +void FPl011SetOperMode(FPl011 *uart_p, u8 operation_mode); +void FPl011SetOptions(FPl011 *uart_p, u32 options); +void FPl011SetSpecificOptions(FPl011 *uart_p, u32 options); +void FPl011ClearSpecificOptions(FPl011 *uart_p, u32 options); +FError FPl011SetBaudRate(FPl011 *uart_p, u32 baudrate) ; +void FPl011GetDataFormat(FPl011 *uart_p, FPl011Format *format_p) ; +FError FPl011SetDataFormat(FPl011 *uart_p, FPl011Format *format_p) ; +void FPl011SetTxFifoThreadHold(FPl011 *uart_p, u8 trigger_level) ; +void FPl011SetRxFifoThreadhold(FPl011 *uart_p, u8 trigger_level) ; + +/* FPl011_uart_intr.c */ +u32 FPl011GetInterruptMask(FPl011 *uart_p) ; +void FPl011InterruptHandler(s32 vector, void *param); +void FPl011SetHandler(FPl011 *uart_p, FPl011EventHandler fun_p, void *args); +void FPl011SetInterruptMask(FPl011 *uart_p, u32 mask); + + + +#ifdef __cplusplus +} +#endif + +#endif // ! diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_g.c b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_g.c new file mode 100644 index 0000000000..2717101988 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_g.c @@ -0,0 +1,70 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:05:41 + * Description:  This files is for uart config + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fpl011.h" +#include "fparameters.h" +#include "sdkconfig.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +const FPl011Config FPl011ConfigTable[FUART_NUM] = +{ + { + .instance_id = FUART0_ID, + .base_address = FUART0_BASE_ADDR, + .ref_clock_hz = FUART0_CLK_FREQ_HZ, + .irq_num = FUART0_IRQ_NUM, + .baudrate = 115200 + }, + { + .instance_id = FUART1_ID, + .base_address = FUART1_BASE_ADDR, + .ref_clock_hz = FUART1_CLK_FREQ_HZ, + .irq_num = FUART1_IRQ_NUM, + .baudrate = 115200 + }, + { + .instance_id = FUART2_ID, + .base_address = FUART2_BASE_ADDR, + .ref_clock_hz = FUART2_CLK_FREQ_HZ, + .irq_num = FUART2_IRQ_NUM, + .baudrate = 115200 + }, + { + .instance_id = FUART3_ID, + .base_address = FUART3_BASE_ADDR, + .ref_clock_hz = FUART3_CLK_FREQ_HZ, + .irq_num = FUART3_IRQ_NUM, + .baudrate = 115200 + } +}; diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_hw.c b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_hw.c new file mode 100644 index 0000000000..9b468f2439 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_hw.c @@ -0,0 +1,73 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:05:56 + * Description:  This files is for uart register function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fpl011_hw.h" + + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/** + * @name: FPl011SendByte + * @msg: This function sends one byte using the device.This function operates in polled mode and blocks + * until the data has been put into the TX FIFO register. + * @param addr contains the base address of the device. + * @param Byte contains the byte to be sent. + */ +void FPl011SendByte(u32 addr, u8 byte) +{ + + while (FUART_ISTRANSMITFULL(addr)) + { + ; + } + FUART_WRITEREG32(addr, FPL011DR_OFFSET, (u32)byte); +} + +/** + * @name: FPl011RecvByte + * @msg: This function receives a byte from the device. It operates in polled mode + * and blocks until a byte has received. + * @param addr contains the base address of the device. + */ +u8 FPl011RecvByte(u32 addr) +{ + u32 recieved_byte; + + while (FUART_ISRECEIVEDATA(addr)) + { + ; + } + recieved_byte = FUART_READREG32(addr, FPL011DR_OFFSET); + return recieved_byte; +} + diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_hw.h b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_hw.h new file mode 100644 index 0000000000..cec10c1fa0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_hw.h @@ -0,0 +1,255 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:06:10 + * Description:  This files is for definition of uart register + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_SERIAL_PL011_UART_HW_H +#define BSP_DRIVERS_SERIAL_PL011_UART_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fassert.h" +#include "fio.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/** @name Register Map + * + * Register offsets for the UART. + */ +#define FPL011DR_OFFSET 0U /* Data */ +#define FPL011RSR_OFFSET 4U /* Receive Status Register/Error Clear */ +#define FPL011ECR_OFFSET FPL011RSR_OFFSET +#define FPL011FTR_OFFSET 0x18U /* Flag Register */ +#define FPL011ILPR_OFFSET 0x020U /* IrDA Low-Power Counter */ +#define FPL011IBRD_OFFSET 0x024U /* Integer Baud Rate */ +#define FPL011FBRD_OFFSET 0x028U /* Fractional Baud Rate */ +#define FPL011LCR_H_OFFSET 0x02cU /* Line Control */ +#define FPL011CR_OFFSET 0x030U /* Control */ +#define FPL011IFLS_OFFSET 0x034U /* Interrupt FIFO Level Select */ +#define FPL011IMSC_OFFSET 0x038U /* Interrupt Mask Set/Clear */ +#define FPL011RIS_OFFSET 0x03cU /* Raw interrupt Status */ +#define FPL011MIS_OFFSET 0x040U /* Mask interrupt Status */ +#define FPL011ICR_OFFSET 0x044U /* Interrupt Clear */ +#define FPL011DMACR_OFFSET 0x048U /* DMA Control */ + +/* Data RW */ +#define FPL011DR_OE 0x800U /* This bit is set to 1 if data is received and the received FIFO is full */ +#define FPL011DR_BE 0x400U /* Break error */ +#define FPL011DR_PE 0x200U /* Parity error */ +#define FPL011DR_FE 0x100U /* Frame error */ +#define FPL011DR_ALLE (FPL011DR_OE | FPL011DR_BE | FPL011DR_PE | FPL011DR_FE) +#define FPL011DR_DATA 0xffU + +/* Receive Status Register/Error Clear RW */ +#define FPL011RSR_OE 0x8U /* overflow error */ +#define FPL011RSR_BE 0x4U /* Break error */ +#define FPL011RSR_PE 0x2U /* Parity error */ +#define FPL011RSR_FE 0x1U /* Frame error */ + +#define FPL011ECR_CLE 0xffU /* Clear */ + +/* Flag Register RO */ +#define FPL011FTR_RI 0x100U /* Ring indicator */ +#define FPL011FTR_TXFE 0x80U /* Transmit FIFO empty */ +#define FPL011FTR_RXFF 0x40U /* Receive FIFO full */ +#define FPL011FTR_TXFF 0x20U /* Transmit FIFO full. */ +#define FPL011FTR_RXFE 0x10U /* Receive FIFO empty */ +#define FPL011FTR_BUSY 0x08U /* UART busy */ +#define FPL011FTR_DCD 0x04U /* Data carrier detect. */ +#define FPL011FTR_DSR 0x02U /* Data set ready. */ +#define FPL011FTR_CTS 0x1U /* Clear to send */ + +/* IrDA Low-Power Counter RW */ +#define FPL011ILPR_ILPDVSR 0xffU /* 8-bit low-power divisor value. These bits are cleared to 0 at reset */ + +/* Integer Baud Rate RW */ +#define FPL011IBRD_BAUD_DIVFRAC 0xffffU /* The fractional baud rate divisor. */ + +/* Fractional Baud Rate RW */ +#define FPL011FBRD_BAUD_DIVFRAC 0x3fU /* The fractional baud rate divisor. */ + +/* Line Control RW */ +#define FPL011LCR_H_SPS 0x80U /* Stick parity select. */ +#define FPL011LCR_H_WLEN 0x60U /* Word length. */ +#define FPL011LCR_H_FEN 0x10U /* Enable FIFOs. */ +#define FPL011LCR_H_STP2 0x08U /* Two stop bits select. */ +#define FPL011LCR_H_EPS 0x04U /* Even parity select. */ +#define FPL011LCR_H_PEN 0x02U /* Parity enable. */ +#define FPL011LCR_H_BRK 0x01U /* send break */ + +#define FPL011LCR_H_WLEN_SHIFT 0x00000005U /* Word length shift */ +#define FPL011LCR_H_WLEN_5_BIT 0x00000000U /* 5 bits data */ +#define FPL011LCR_H_WLEN_6_BIT 0x00000020U /* 6 bits data */ +#define FPL011LCR_H_WLEN_7_BIT 0x00000040U /* 7 bits data */ +#define FPL011LCR_H_WLEN_8_BIT 0x00000060U /* 8 bits data */ +#define FPL011LCR_H_STP_1_BIT 0x00000000U + +#define FPL011LCR_H_STP_MASK 0x00000008U /* Stop bits mask */ +#define FPL011LCR_H_STP_SHIFT 0x00000003U /* Stop bits shift */ +#define FPL011LCR_H_PARITY_EVEN 0x00000004U /* Even parity mode */ +#define FPL011LCR_H_PARITY_MASK 0x00000002U /* Parity mask */ +#define FPL011LCR_H_PARITY_SHIFT 0x00000001U /* Parity shift */ +#define FPL011LCR_H_PARITY_NONE 0x00000000U /* No parity mode */ +#define FPL011LCR_H_PARITY_ODD 0x00000000U /* Odd parity mode */ + +/* Control RW */ +#define FPL011CR_CTSEN 0x8000U /* CTS hardware flow control enable. */ +#define FPL011CR_RTSEN 0x4000U /* RTS hardware flow control enable. */ +#define FPL011CR_OUT2 0x2000U /* This bit is the complement of the UART Out2 (nUARTOut2) modem status output. */ +#define FPL011CR_OUT1 0x1000U /* This bit is the complement of the UART Out1 (nUARTOut1) modem status output. */ +#define FPL011CR_RTS 0x0800U /* Request to send. */ +#define FPL011CR_DTR 0x0400U /* Data transmit ready */ +#define FPL011CR_RXE 0x0200U /* Receive enable. */ +#define FPL011CR_TXE 0x0100U /* Transmit enable. */ +#define FPL011CR_LBE 0x0080U /* Loop back enable.*/ +#define FPL011CR_SIRLP 0x4U /* IrDA SIR low power mode. */ +#define FPL011CR_SIREN 0x2U /* SIR enable. */ +#define FPL011CR_UARTEN 0x1U /* UART enable. */ +#define FPL011CR_MODE_NORMAL 0x00000000U /* Normal Mode */ + + +/* Interrupt FIFO Level Select RW */ +#define FPL011IFLS_RXIFLSEL_MASK 0x00000038U /* Receive interrupt FIFO level select mask */ +#define FPL011IFLS_TXIFLSEL_MASK 0x00000007U /* Receive interrupt FIFO level select mask */ +#define FPL011IFLS_RXIFLSEL_1_8 0x00000000U /* Receive FIFO becomes . 1/8 full */ +#define FPL011IFLS_RXIFLSEL_1_4 0x00000008U /* Receive FIFO becomes . 1/4 full */ +#define FPL011IFLS_RXIFLSEL_1_2 0x00000010U /* Receive FIFO becomes * . 1/2 full */ +#define FPL011IFLS_RXIFLSEL_3_4 0x00000018U /* Receive FIFO becomes * . 3/4 full */ +#define FPL011IFLS_RXIFLSEL_7_8 0x00000020U /* Receive FIFO becomes * . 7/8 full */ +#define FPL011IFLS_TXIFLSEL_1_8 0x00000000U /* Transmit FIFO becomes * . 1/8 full */ +#define FPL011IFLS_TXIFLSEL_1_4 0x00000001U /* Transmit FIFO becomes * . 1/4 full */ +#define FPL011IFLS_TXIFLSEL_1_2 0x00000002U /* Transmit FIFO becomes * . 1/2 full */ +#define FPL011IFLS_TXIFLSEL_3_4 0x00000003U /* Transmit FIFO becomes * . 3/4 full */ +#define FPL011IFLS_TXIFLSEL_7_8 0x00000004U /* Transmit FIFO becomes * . 7/8 full */ + +/* Interrupt Mask Set/Clear RW */ +#define FPL011IMSC_OEIM 0x400U /* Overrun error interrupt mask. */ +#define FPL011IMSC_BEIM 0x200U /* Break error interrupt mask */ +#define FPL011IMSC_PEIM 0x100U /* Parity error interrupt mask. */ +#define FPL011IMSC_FEIM 0x80U /* Framing error interrupt mask. */ +#define FPL011IMSC_RTIM 0x40U /* Receive timeout interrupt mask. */ +#define FPL011IMSC_TXIM 0x20U /* Transmit interrupt mask. */ +#define FPL011IMSC_RXIM 0x10U /* Receive interrupt mask. */ +#define FPL011IMSC_DSRMIM 0x8U /* nUARTDSR modem interrupt mask. */ +#define FPL011IMSC_DCDMIM 0x4U /* nUARTDCD modem interrupt mask. */ +#define FPL011IMSC_CTSMIM 0x2U /* nUARTCTS modem interrupt mask. */ +#define FPL011IMSC_RIMIM 0x1U /* nUARTRI modem interrupt mask. */ +#define FPL011IMSC_ALLM 0x7ffU /* all interrupt mask */ + +/* Raw interrupt Status RO */ + +#define FPL011RIS_OEIS 0x400U /* Overrun error interrupt mask. */ +#define FPL011RIS_BEIS 0x200U /* Break error interrupt mask */ +#define FPL011RIS_PEIS 0x100U /* Parity error interrupt mask. */ +#define FPL011RIS_FEIS 0x80U /* Framing error interrupt mask. */ +#define FPL011RIS_RTIS 0x40U /* Receive timeout interrupt mask. */ +#define FPL011RIS_TXIS 0x20U /* Transmit interrupt mask. */ +#define FPL011RIS_RXIS 0x10U /* Receive interrupt mask. */ +#define FPL011RIS_DSRMIS 0x8U /* nUARTDSR modem interrupt mask. */ +#define FPL011RIS_DCDMIS 0x4U /* nUARTDCD modem interrupt mask. */ +#define FPL011RIS_CTSMIS 0x2U /* nUARTCTS modem interrupt mask. */ +#define FPL011RIS_RIMIS 0x1U /* nUARTRI modem interrupt mask. */ + +/* Mask interrupt Status R0 */ + +#define FPL011MIS_OEMIS 0x400U /* Overrun error interrupt mask. */ +#define FPL011MIS_BEMIS 0x200U /* Break error interrupt mask */ +#define FPL011MIS_PEMIS 0x100U /* Parity error interrupt mask. */ +#define FPL011MIS_FEMIS 0x80U /* Framing error interrupt mask. */ +#define FPL011MIS_RTMIS 0x40U /* Receive timeout interrupt mask. */ +#define FPL011MIS_TXMIS 0x20U /* Transmit interrupt mask. */ +#define FPL011MIS_RXMIS 0x10U /* Receive interrupt mask. */ +#define FPL011MIS_DSRMMIS 0x8U /* nUARTDSR modem interrupt mask. */ +#define FPL011MIS_DCDMMIS 0x4U /* nUARTDCD modem interrupt mask. */ +#define FPL011MIS_CTSMMIS 0x2U /* nUARTCTS modem interrupt mask. */ +#define FPL011MIS_RIMMIS 0x1U /* nUARTRI modem interrupt mask. */ + +/* Interrupt Clear WO */ +#define FPL011ICR_OEIC 0x400U /* Overrun error interrupt mask. */ +#define FPL011ICR_BEIC 0x200U /* Break error interrupt mask */ +#define FPL011ICR_PEIC 0x100U /* Parity error interrupt mask. */ +#define FPL011ICR_FEIC 0x80U /* Framing error interrupt mask. */ +#define FPL011ICR_RTIC 0x40U /* Receive timeout interrupt mask. */ +#define FPL011ICR_TXIC 0x20U /* Transmit interrupt mask. */ +#define FPL011ICR_RXIC 0x10U /* Receive interrupt mask. */ +#define FPL011ICR_DSRMIC 0x8U /* nUARTDSR modem interrupt mask. */ +#define FPL011ICR_DCDMIC 0x4U /* nUARTDCD modem interrupt mask. */ +#define FPL011ICR_CTSMIC 0x2U /* nUARTCTS modem interrupt mask. */ +#define FPL011ICR_RIMIC 0x1U /* nUARTRI modem interrupt mask. */ +#define FPL011ICR_ALL_CLEAR (FPL011ICR_OEIC |FPL011ICR_BEIC |FPL011ICR_PEIC |FPL011ICR_FEIC |FPL011ICR_RTIC |FPL011ICR_TXIC |FPL011ICR_RXIC |FPL011ICR_DSRMIC |FPL011ICR_DCDMIC |FPL011ICR_CTSMIC |FPL011ICR_RIMIC ) + +/* DMA Control RW */ +#define FPL011DMACR_DMAONERR 0x4U /* DMA on error. */ +#define FPL011DMACR_TXDMAE 0x2U /* Transmit DMA enable. */ +#define FPL011DMACR_RXDMAE 0x1U /* Receive DMA enable. */ + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FUART_READREG32(addr, reg_offset) FtIn32(addr + (u32)reg_offset) +#define FUART_WRITEREG32(addr, reg_offset, reg_value) FtOut32(addr + (u32)reg_offset, (u32)reg_value) + +/** + * @name: FUART_ISRECEIVEDATA + * @msg: Used to confirm whether data has been received + * @param addr contains the base address of the device. + * @return {bool} true 是存在数据 , false 是不存在数据 + * + */ +#define FUART_ISRECEIVEDATA(addr) (FtIn32(addr + FPL011FTR_OFFSET) & FPL011FTR_RXFE) + +/** + * @name: FUART_ISTRANSMITFULL + * @msg: Used to confirm whether data can be sent + * @param addr contains the base address of the device. + * @return {bool} true 是数据已满 , false 可以发送数据 + */ +#define FUART_ISTRANSMITFULL(addr) ((FtIn32(addr + FPL011FTR_OFFSET) & (u32)FPL011FTR_TXFF) == FPL011FTR_TXFF) + + +/** + * @name: FUART_ISTRANSMITBUSY + * @msg: Determine if a byte of data can be sent with the transmitter. + * @return TRUE if the TX is busy, FALSE if a byte can be put in the + * FIFO. + */ +#define FUART_ISTRANSMITBUSY(addr) ((FtIn32(addr + FPL011FTR_OFFSET) & (u32)FPL011FTR_BUSY) == FPL011FTR_BUSY) + +/************************** Function Prototypes ******************************/ + +void FPl011SendByte(u32 addr, u8 byte); +u8 FPl011RecvByte(u32 addr); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_intr.c b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_intr.c new file mode 100644 index 0000000000..de69f982ae --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_intr.c @@ -0,0 +1,234 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:06:30 + * Description:  This files is for uart irq functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ + +#include "fpl011.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ +/*****************************************************************************/ + +extern u32 FPl011SendBuffer(FPl011 *uart_p); +extern u32 FPl011ReceiveBuffer(FPl011 *uart_p); + +static void FPl011ReceiveErrorHandler(FPl011 *uart_p, u32 InterruptStatus); +static void FPl011ReceiveDataHandler(FPl011 *uart_p); +static void FPl011ReceiveTimeoutHandler(FPl011 *uart_p); +static void FPl011SendDataHandler(FPl011 *uart_p, u32 InterruptStatus); + +/** + * @name: FPl011GetInterruptMask + * @msg: 此函数获取所有串口中断的mask。 + * @param uart_p + * @return mask + */ +/** + * @name: FPl011GetInterruptMask + * @msg: This function gets the interrupt mask. + * @param uart_p is a pointer to the uart instance + * @return {*} + */ +u32 FPl011GetInterruptMask(FPl011 *uart_p) +{ + FASSERT(uart_p != NULL); + return FUART_READREG32(uart_p->config.base_address, FPL011IMSC_OFFSET); +} + + +/** + * @name: FPl011SetInterruptMask + * @msg: This function sets the interrupt mask. + * @param uart_p is a pointer to the uart instance + * @param mask contains the interrupts to be enabled or disabled. + * A '1' enables an interrupt, and a '0' disables. + */ +void FPl011SetInterruptMask(FPl011 *uart_p, u32 mask) +{ + u32 temp_mask = mask; + FASSERT(uart_p != NULL); + + temp_mask &= FPL011IMSC_ALLM; + + FUART_WRITEREG32(uart_p->config.base_address, FPL011IMSC_OFFSET, temp_mask); +} + +/** + * @name: FPl011SetHandler + * @msg: This function sets the handler that will be called when an event (interrupt) + * occurs that needs application's attention. + * @param uart_p is a pointer to the uart instance + * @param fun_p is the pointer to the callback function. + * @param args is the upper layer callback reference passed back + * when the callback function is invoked. + * @return {*} + */ +void FPl011SetHandler(FPl011 *uart_p, FPl011EventHandler fun_p, void *args) +{ + FASSERT(uart_p != NULL); + FASSERT(fun_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + + uart_p->handler = fun_p; + uart_p->args = args; +} + + +/** + * @name: FPl011InterruptHandler + * @msg: This function is the interrupt handler for the driver. + * It must be connected to an interrupt system by the application such that it + * can be called when an interrupt occurs. + * @param vector Irq num ,Don't need attention . + * @param param contains a pointer to the driver instance + */ +void FPl011InterruptHandler(s32 vector, void *param) +{ + FPl011 *uart_p = (FPl011 *)param; + u32 reg_value = 0; + FASSERT(uart_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + + reg_value = FUART_READREG32(uart_p->config.base_address, FPL011IMSC_OFFSET); + reg_value &= FUART_READREG32(uart_p->config.base_address, FPL011MIS_OFFSET); + + if ((reg_value & ((u32)FPL011MIS_RXMIS)) != (u32)0) + { + /* Received data interrupt */ + FPl011ReceiveDataHandler(uart_p); + } + + if ((reg_value & ((u32)FPL011MIS_TXMIS)) != (u32)0) + { + /* Transmit data interrupt */ + FPl011SendDataHandler(uart_p, reg_value); + } + + if (((reg_value) & ((u32)FPL011MIS_OEMIS | (u32)FPL011MIS_BEMIS | (u32)FPL011MIS_PEMIS | (u32)FPL011MIS_FEMIS)) != (u32)0) + { + /* Received Error Status interrupt */ + FPl011ReceiveErrorHandler(uart_p, reg_value); + } + + if ((reg_value & ((u32)FPL011MIS_RTMIS)) != (u32)0) + { + /* Received Timeout interrupt */ + FPl011ReceiveTimeoutHandler(uart_p); + } + + if (((reg_value) & ((u32)FPL011MIS_DSRMMIS | (u32)FPL011MIS_DCDMMIS | (u32)FPL011MIS_CTSMMIS | (u32)FPL011MIS_RIMMIS)) != (u32)0) + { + /* Modem status interrupt */ + } + + /* Clear the interrupt status. */ + FUART_WRITEREG32(uart_p->config.base_address, FPL011ICR_OFFSET, + reg_value); + +} + +static void FPl011ReceiveErrorHandler(FPl011 *uart_p, u32 InterruptStatus) +{ + uart_p->rxbs_error = 0; + + if (((InterruptStatus) & ((u32)FPL011MIS_OEMIS | (u32)FPL011MIS_BEMIS | (u32)FPL011MIS_PEMIS | (u32)FPL011MIS_FEMIS)) != 0) + { + uart_p->rxbs_error = 1; + } + + (void)FPl011ReceiveBuffer(uart_p); + + if (0 == uart_p->rxbs_error) + { + if (uart_p->handler) + { + uart_p->handler(uart_p->args, FPL011_EVENT_RECV_ERROR, uart_p->receive_buffer.requested_bytes - uart_p->receive_buffer.remaining_bytes); + } + } +} + +/** + * @name: FPl011ReceiveDataHandler + * @msg: + * @param {*} + * @return {*} + */ +static void FPl011ReceiveDataHandler(FPl011 *uart_p) +{ + if ((u32)0 != uart_p->receive_buffer.remaining_bytes) + { + (void)FPl011ReceiveBuffer(uart_p); + } + + if ((u32)0 == uart_p->receive_buffer.remaining_bytes) + { + if (uart_p->handler) + { + uart_p->handler(uart_p->args, FPL011_EVENT_RECV_DATA, uart_p->receive_buffer.requested_bytes - uart_p->receive_buffer.remaining_bytes); + } + } +} + +static void FPl011ReceiveTimeoutHandler(FPl011 *uart_p) +{ + u32 event; + + if ((u32)0 != uart_p->receive_buffer.remaining_bytes) + { + (void)FPl011ReceiveBuffer(uart_p); + } + + if ((u32)0 == uart_p->receive_buffer.remaining_bytes) + { + event = FPL011_EVENT_RECV_TOUT; + } + else + { + event = FPL011_EVENT_RECV_DATA; + } + + if (uart_p->handler) + { + uart_p->handler(uart_p->args, event, uart_p->receive_buffer.requested_bytes - uart_p->receive_buffer.remaining_bytes); + } +} + +static void FPl011SendDataHandler(FPl011 *uart_p, u32 InterruptStatus) +{ + FPl011SendBuffer(uart_p); + if (uart_p->send_buffer.remaining_bytes == (u32)0) + { + if (uart_p->handler) + { + uart_p->handler(uart_p->args, FPL011_EVENT_SENT_DATA, uart_p->send_buffer.requested_bytes); + } + } +} diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_options.c b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_options.c new file mode 100644 index 0000000000..4e4584d077 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_options.c @@ -0,0 +1,482 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011_options.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:06:45 + * Description:  This files is for uart option setting + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ + +#include "fpl011.h" +#include "fpl011_hw.h" +#include "ftypes.h" + +/************************** Variable Definitions ****************************/ +/************************** Constant Definitions *****************************/ +/**************************** Type Definitions *******************************/ +/* + * The following data type is a map from an option to the offset in the + * register to which it belongs as well as its bit mask in that register. + */ +typedef struct +{ + u32 option; + u32 register_offset; + u32 mask; +} Mapping; + +static Mapping option_table[] = +{ + {FPL011_OPTION_UARTEN, FPL011CR_OFFSET, FPL011CR_UARTEN}, + {FPL011_OPTION_RXEN, FPL011CR_OFFSET, FPL011CR_RXE}, + {FPL011_OPTION_TXEN, FPL011CR_OFFSET, FPL011CR_TXE}, + {FPL011_OPTION_FIFOEN, FPL011LCR_H_OFFSET, FPL011LCR_H_FEN}, + {FPL011_OPTION_RTS, FPL011CR_OFFSET, FPL011CR_RTS}, + {FPL011_OPTION_DTR, FPL011CR_OFFSET, FPL011CR_DTR}, + {FPL011_OPTION_RTSEN, FPL011CR_OFFSET, FPL011CR_RTSEN}, + {FPL011_OPTION_CTSEN, FPL011CR_OFFSET, FPL011CR_CTSEN}, + {FPL011_OPTION_TXDMAEN, FPL011DMACR_OFFSET, FPL011DMACR_TXDMAE}, + {FPL011_OPTION_RXDMAEN, FPL011DMACR_OFFSET, FPL011DMACR_RXDMAE} +}; + +/***************** Macros (Inline Functions) Definitions *********************/ + +#define FUART_NUM_OPITIONS (sizeof(option_table) / sizeof(Mapping)) +/************************** Function Prototypes ******************************/ +/*****************************************************************************/ +/** + * @name: FPl011SetOptions + * @msg: Sets the options for the specified driver instance. The options are implemented as bit masks such that multiple options may be enabled or disabled simultaneously. + * @param uart_p is a pointer to the uart instance. + * @param options contains the options to be set which are bit masks + * contained in the file FPl011_uart.h and named FUART_OPTION_*. + */ +void FPl011SetOptions(FPl011 *uart_p, u32 options) +{ + u32 index; + u32 reg_value; + FASSERT(uart_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + + for (index = 0; index < FUART_NUM_OPITIONS; index++) + { + reg_value = FUART_READREG32(uart_p->config.base_address, option_table[index].register_offset); + + if ((options & option_table[index].option) != (u32)(0)) + { + reg_value |= option_table[index].mask; + } + else + { + reg_value &= ~option_table[index].mask; + } + + FUART_WRITEREG32(uart_p->config.base_address, option_table[index].register_offset, reg_value); + } +} + +/** + * @name: FPl011SetSpecificOptions + * @msg: Sets the options for the specified driver instance. + * @param {FPl011} *uart_p is a pointer to the uart instance. + * @param {u32} options contains the options to be set which are bit masks + * contained in the file FPl011_uart.h and named FUART_OPTION_*. + */ +void FPl011SetSpecificOptions(FPl011 *uart_p, u32 options) +{ + u32 index; + u32 reg_value; + FASSERT(uart_p != NULL); + + for (index = 0; index < FUART_NUM_OPITIONS; index++) + { + if ((options & option_table[index].option) == (u32)(0)) + continue; + reg_value = FUART_READREG32(uart_p->config.base_address, option_table[index].register_offset); + + /* set specific options */ + reg_value |= option_table[index].mask; + FUART_WRITEREG32(uart_p->config.base_address, option_table[index].register_offset, reg_value); + } +} + +/** + * @name: FPl011SetSpecificOptions + * @msg: Clear the options for the specified driver instance. + * @param uart_p is a pointer to the uart instance. + * @param options contains the options to be set which are bit masks + * contained in the file FPl011_uart.h and named FUART_OPTION_*. + */ +void FPl011ClearSpecificOptions(FPl011 *uart_p, u32 options) +{ + u32 index; + u32 reg_value; + FASSERT(uart_p != NULL); + + for (index = 0; index < FUART_NUM_OPITIONS; index++) + { + if ((options & option_table[index].option) == (u32)(0)) + continue; + reg_value = FUART_READREG32(uart_p->config.base_address, option_table[index].register_offset); + + /* remove specific options */ + reg_value &= ~option_table[index].mask; + FUART_WRITEREG32(uart_p->config.base_address, option_table[index].register_offset, reg_value); + } +} + + + +/** + * @name: FPl011SetDataFormat + * @msg: Sets the data format for the specified UART. + * @param uart_p is a pointer to the uart instance. + * @param format_p is a pointer to a format structure that will + * contain the data format after this call completes. + * @return + * FT_SUCCESS if everything configured as expected + * FPL011_ERROR_PARAM if one of the parameters was not valid. + */ +FError FPl011SetDataFormat(FPl011 *uart_p, FPl011Format *format_p) +{ + FError ret ; + u32 line_ctrl_reg ; + FPl011Config *config_p; + FASSERT(uart_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(format_p != NULL) ; + + config_p = &uart_p->config; + + if ((format_p->data_bits > ((u32)(FPL011_FORMAT_WORDLENGTH_8BIT))) || + (format_p->parity > ((u32)(FPL011_FORMAT_PARITY_MASK))) || + (format_p->stopbits > ((u32)(FPL011_FORMAT_PARITY_MASK))) + ) + { + return FPL011_ERROR_PARAM ; + } + else + { + /* + * Try to set the baud rate and if it's not successful then + * don't continue altering the data format, this is done + * first to avoid the format from being altered when an + * error occurs + */ + ret = FPl011SetBaudRate(uart_p, format_p->baudrate) ; + if (ret != FT_SUCCESS) + { + + } + else + { + line_ctrl_reg = FUART_READREG32(config_p->base_address, FPL011LCR_H_OFFSET); + + /* + * Set the length of data (8,7,6) by first clearing + * out the bits that control it in the register, + * then set the length in the register + */ + line_ctrl_reg &= ~(u32)FPL011LCR_H_WLEN ; + line_ctrl_reg |= (format_p->data_bits << + FPL011LCR_H_WLEN_SHIFT); + + /* + * Set the number of stop bits in the mode register by + * first clearing out the bits that control it in the + * register, then set the number of stop bits in the + * register. + */ + line_ctrl_reg &= ~FPL011LCR_H_STP_MASK; + line_ctrl_reg |= (format_p->stopbits << + FPL011LCR_H_STP_SHIFT); + + /* + * Set the parity by first clearing out the bits that + * control it in the register, then set the bits in + * the register, the default is no parity after + * clearing the register bits + */ + line_ctrl_reg &= ~FPL011LCR_H_PARITY_MASK; + line_ctrl_reg |= ((format_p->parity & + FPL011_FORMAT_EN_PARITY) << + FPL011LCR_H_PARITY_SHIFT); + + /* Even/Odd parity set */ + line_ctrl_reg |= ((format_p->parity & + FPL011_FORMAT_EVEN_PARITY) << + FPL011_FORMAT_EVEN_PARITY_SHIFT); + + /* Stick parity enable/disable */ + line_ctrl_reg |= ((format_p->parity & + FPL011_FORMAT_EN_STICK_PARITY) << + FPL011_FORMAT_EN_STICK_PARITY_SHIFT); + + /* Update the Line control register */ + FUART_WRITEREG32(config_p->base_address, FPL011LCR_H_OFFSET, line_ctrl_reg) ; + + return FT_SUCCESS ; + } + } + + return ret ; +} + +/** + * @name: FPl011GetDataFormat + * @msg: Gets the data format for the specified UART. + * @param uart_p is a pointer to the uart instance. + * @param format_p is a pointer to a format structure that will + * contain the data format after this call completes. + */ +void FPl011GetDataFormat(FPl011 *uart_p, FPl011Format *format_p) +{ + u32 line_ctrl_reg ; + FPl011Config *config_p; + /* Assert validates the input arguments */ + FASSERT(uart_p != NULL); + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + FASSERT(format_p != NULL) ; + + config_p = &uart_p->config; + /* + * Get the baud rate from the instance, this is not retrieved from + * the hardware because it is only kept as a divisor such that it + * is more difficult to get back to the baud rate + */ + format_p->baudrate = uart_p->config.baudrate ; + + line_ctrl_reg = FUART_READREG32(config_p->base_address, FPL011LCR_H_OFFSET); + + /* Get the length of data (8,7,6,5) */ + format_p->data_bits = ((line_ctrl_reg & FPL011LCR_H_WLEN) >> FPL011LCR_H_WLEN_SHIFT) ; + + /* Get the number of stop bits */ + format_p->stopbits = (u8)((line_ctrl_reg & FPL011LCR_H_STP_MASK) >> FPL011LCR_H_STP_SHIFT) ; + + /* Determine what parity is */ + format_p->parity = (u32)((line_ctrl_reg & (u32)FPL011LCR_H_PARITY_MASK) >> FPL011LCR_H_PARITY_SHIFT) ; +} + + + +/** + * @name: FPl011SetTxFifoThreadHold + * @msg: This functions sets the Tx FIFO trigger level to the 'TriggerLevel' + * argument. + * @param uart_p is a pointer to the uart instance. + * @param trigger_level contains the trigger level to set. This is a value + * from 0-32 (FPL011IFLS_TXIFLSEL_1_8 - FPL011IFLS_TXIFLSEL_7_8) + */ +void FPl011SetTxFifoThreadHold(FPl011 *uart_p, u8 trigger_level) +{ + u32 fifo_trig_reg; + FPl011Config *config_p; + FASSERT(uart_p != NULL); + FASSERT(trigger_level <= (u8)FPL011IFLS_TXIFLSEL_MASK) ; + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &uart_p->config; + + trigger_level = trigger_level & (u8)FPL011IFLS_TXIFLSEL_MASK; + + fifo_trig_reg = FUART_READREG32(config_p->base_address, + FPL011IFLS_OFFSET); + + fifo_trig_reg &= ~(FPL011IFLS_TXIFLSEL_MASK | FPL011IFLS_RXIFLSEL_MASK); + + fifo_trig_reg |= (u32)trigger_level; + + /* + * Write the new value for the FIFO control register to it such that + * the threshold is changed + */ + FUART_WRITEREG32(config_p->base_address, + FPL011IFLS_OFFSET, fifo_trig_reg); +} + + + +/** + * @name: FPl011SetRxFifoThreadhold + * @msg: This functions sets the Rx FIFO trigger level to the 'TriggerLevel' + * argument. + * @param uart_p is a pointer to the uart instance. + * @param trigger_level contains the trigger level to set. This is a value + * from 0-32 (FPL011IFLS_RXIFLSEL_1_8 - FPL011IFLS_RXIFLSEL_7_8) + */ +void FPl011SetRxFifoThreadhold(FPl011 *uart_p, u8 trigger_level) +{ + u32 fifo_trig_reg; + FPl011Config *config_p; + FASSERT(uart_p != NULL); + FASSERT(trigger_level <= (u8)FPL011IFLS_RXIFLSEL_MASK) ; + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &uart_p->config; + + trigger_level = trigger_level & (u8)FPL011IFLS_RXIFLSEL_MASK; + + fifo_trig_reg = FUART_READREG32(config_p->base_address, + FPL011IFLS_OFFSET); + + fifo_trig_reg &= ~FPL011IFLS_RXIFLSEL_MASK; + + fifo_trig_reg |= (u32)trigger_level ; + + /* + * Write the new value for the FIFO control register to it such that + * the threshold is changed + */ + FUART_WRITEREG32(config_p->base_address, + FPL011IFLS_OFFSET, fifo_trig_reg); +} + +/** + * @name: FPl011SetBaudRate + * @msg: Sets the baud rate for the device. + * @param uart_p is a pointer to the FPl011 instance + * @param BaudRate to be set + * @return + * FT_SUCCESS if everything configured as expected + * FPL011_ERROR_PARAM if the requested rate is not available + * because there was too much error + */ +FError FPl011SetBaudRate(FPl011 *uart_p, u32 baudrate) +{ + u32 temp; + u32 divider; + u32 remainder; + u32 fraction; + + FASSERT(NULL != uart_p); + if ((baudrate * 2) > uart_p->config.ref_clock_hz) + { + return FPL011_ERROR_PARAM; + } + + /* calculate baud rate divisor */ + temp = 16 * baudrate; + divider = uart_p->config.ref_clock_hz / temp; + remainder = uart_p->config.ref_clock_hz % temp; + temp = (128 * remainder) / temp; + fraction = temp / 2; + + if (0 != (temp & 1)) + { + fraction++; + } + + FPl011ClearSpecificOptions(uart_p, FPL011_OPTION_RXEN | FPL011_OPTION_TXEN); + /* set baud register */ + FUART_WRITEREG32(uart_p->config.base_address, FPL011IBRD_OFFSET, divider); + FUART_WRITEREG32(uart_p->config.base_address, FPL011FBRD_OFFSET, fraction); + FPl011SetSpecificOptions(uart_p, FPL011_OPTION_RXEN | FPL011_OPTION_TXEN); + uart_p->config.baudrate = baudrate; + return FT_SUCCESS; +} + +/** + * @name: FPl011ProgramCtlReg + * @msg: This function reprograms the control register according to the following + * sequence mentioned in the TRM + * @param uart_p is a pointer to the FPl011 instance + * @param ctrl_reg value to be written + */ +void FPl011ProgramCtlReg(FPl011 *uart_p, u32 ctrl_reg) +{ + u32 line_ctrl_reg; + u32 temp_ctrl_reg; + u32 isbusy; + u32 addr = uart_p->config.base_address; + FASSERT(uart_p); + + /* + * Check is TX completed. If Uart is disabled in the middle, cannot + * recover. So, keep this check before disable. + */ + isbusy = FUART_ISTRANSMITBUSY(addr); + while (isbusy == (u32)TRUE) + { + isbusy = (u32)FUART_ISTRANSMITBUSY(addr); + } + + /* Disable UART */ + temp_ctrl_reg = FUART_READREG32(addr, FPL011CR_OFFSET); + temp_ctrl_reg &= (~FPL011CR_UARTEN); + FUART_WRITEREG32(addr, FPL011CR_OFFSET, temp_ctrl_reg); + + /* + * Flush the transmit FIFO by setting the FEN bit to 0 in the + * Line Control Register + */ + line_ctrl_reg = FUART_READREG32(addr, FPL011LCR_H_OFFSET); + line_ctrl_reg &= ~FPL011LCR_H_FEN; + FUART_WRITEREG32(addr, FPL011LCR_H_OFFSET, line_ctrl_reg); + + /* Setup the Control Register with the passed argument.*/ + FUART_WRITEREG32(addr, FPL011CR_OFFSET, ctrl_reg); + + /* By default, driver works in FIFO mode, so set FEN as it is + * cleared above + */ + line_ctrl_reg |= FPL011LCR_H_FEN; + FUART_WRITEREG32(addr, FPL011LCR_H_OFFSET, line_ctrl_reg); + + /* Enable UART */ + temp_ctrl_reg = FUART_READREG32(addr, FPL011CR_OFFSET); + temp_ctrl_reg |= FPL011CR_UARTEN; + FUART_WRITEREG32(addr, FPL011CR_OFFSET, temp_ctrl_reg); +} + +/** + * @name: FPl011SetOperMode + * @msg: This function sets the operational mode of the UART. The UART can operate + * in one of four modes: Normal, Local Loopback. + * @param uart_p is a pointer to the FPl011 instance. + * @param operation_mode is the mode of the UART. + */ +void FPl011SetOperMode(FPl011 *uart_p, u8 operation_mode) +{ + u32 ctrl_reg; + FPl011Config *config_p; + FASSERT(uart_p != NULL); + FASSERT(operation_mode <= (u8)FPL011_OPER_MODE_LOCAL_LOOP) ; + FASSERT(uart_p->is_ready == FT_COMPONENT_IS_READY); + config_p = &uart_p->config; + + ctrl_reg = FUART_READREG32(config_p->base_address, FPL011CR_OFFSET) ; + + /* Set the correct value by masking the bits, then ORing the const. */ + ctrl_reg &= ~(u32)FPL011CR_LBE; + + switch (operation_mode) + { + case FPL011_OPER_MODE_NORMAL: + ctrl_reg |= FPL011CR_MODE_NORMAL; + break; + case FPL011_OPER_MODE_LOCAL_LOOP: + ctrl_reg |= FPL011CR_LBE; + break; + default: + break; + } + + /* Setup the Control Register with the passed argument.*/ + FPl011ProgramCtlReg(uart_p, ctrl_reg); +} diff --git a/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_sinit.c b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_sinit.c new file mode 100644 index 0000000000..ae9f4834e7 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/serial/fpl011/fpl011_sinit.c @@ -0,0 +1,62 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fpl011_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:07:00 + * Description:  This files is for uart static init + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fpl011.h" +#include "fparameters.h" +#include "sdkconfig.h" + +extern FPl011Config FPl011ConfigTable[FUART_NUM]; +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ +/** + * @name: FPl011LookupConfig + * @msg: Initializes a specific FPl011 instance such that it is ready to be used. + * @param contains the ID of the device + * @return {FPl011Config *} A pointer to the configuration structure or NULL if the + * specified device is not in the system. + */ +const FPl011Config *FPl011LookupConfig(u32 instance_id) +{ + const FPl011Config *cfg_ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FUART_NUM; index++) + { + if (FPl011ConfigTable[index].instance_id == instance_id) + { + cfg_ptr = &FPl011ConfigTable[index]; + break; + } + } + + return (const FPl011Config *)cfg_ptr; +} diff --git a/bsp/phytium/libraries/standalone/drivers/spi/Kconfig b/bsp/phytium/libraries/standalone/drivers/spi/Kconfig new file mode 100644 index 0000000000..0e35640055 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/Kconfig @@ -0,0 +1,11 @@ + +config USE_FSPIM + bool + prompt "Use FSPIM" + default n + depends on USE_SPI + depends on TARGET_F2000_4 || TARGET_D2000 || TARGET_E2000S || TARGET_E2000D || TARGET_E2000Q + help + Select FSPIM driver component + + diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim.c b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim.c new file mode 100644 index 0000000000..b2694483ad --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim.c @@ -0,0 +1,620 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:08:32 + * Description:  This files is for spim api implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021-12-3 init commit + * 1.1 zhugengyu 2022-4-15 support test mode + * 1.2 zhugengyu 2022-5-13 support spi dma + */ + + +/***************************** Include Files *********************************/ + +#include +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fdebug.h" +#include "fspim_hw.h" +#include "fspim.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSPIM_DEBUG_TAG "SPIM" +#define FSPIM_ERROR(format, ...) FT_DEBUG_PRINT_E(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_WARN(format, ...) FT_DEBUG_PRINT_W(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_INFO(format, ...) FT_DEBUG_PRINT_I(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ +FError FSpimReset(FSpim *instance_p); + +/************************** Variable Definitions *****************************/ +static const char *FSPIM_ERROR_CODE_MSG[FSPIM_NUM_OF_ERR_CODE] = +{ + "FSPIM_SUCCESS : fspim success", + "FSPIM_ERR_INVAL_STATE : fspim invalid state", + "FSPIM_ERR_NOT_READY : fspim driver not ready", + "FSPIM_ERR_INVAL_PARAM : fspim invalid input parameters", + "FSPIM_ERR_BUS_BUSY : fspim bus is busy", + "FSPIM_ERR_NOT_SUPPORT : fspim not support operation", + "FSPIM_ERR_TIMEOUT : fspim wait timeout", + "FSPIM_ERR_TRANS_FAIL : fspim data transfer failed", +}; + + +/*****************************************************************************/ + +/* 此文件主要为了完成用户对外接口,用户可以使用这些接口直接开始工作 */ + +/* - 包括用户API的定义和实现 + - 同时包含必要的OPTION方法,方便用户进行配置 + - 如果驱动可以直接进行I/O操作,在此源文件下可以将API 进行实现 */ + +/* + * @name: FSpimCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {FSpim} *instance_p FSPIM驱动控制数据 + * @param {FSpimConfig} *config_p FSPIM驱动配置数据 + * @return 驱动初始化的错误码信息,FSPIM_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + */ +FError FSpimCfgInitialize(FSpim *instance_p, const FSpimConfig *input_config_p) +{ + FASSERT(instance_p && input_config_p); + uintptr base_addr = instance_p->config.base_addr; + + FError ret = FSPIM_SUCCESS; + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == instance_p->is_ready) + { + FSPIM_WARN("device is already initialized!!!"); + } + + /* + * Set default values and configuration data, including setting the + * callback handlers to stubs so the system will not crash should the + * application not assign its own callbacks. + */ + FSpimDeInitialize(instance_p); + instance_p->config = *input_config_p; + + /* + * Reset the device. + */ + ret = FSpimReset(instance_p); + if (FSPIM_SUCCESS == ret) + { + instance_p->is_ready = FT_COMPONENT_IS_READY; + } + + return ret; +} + +/** + * @name: FSpimDeInitialize + * @msg: DeInitialization function for the device instance + * @return {无} + * @param {FSpim} *instance_p FSPIM驱动控制数据 + */ +void FSpimDeInitialize(FSpim *instance_p) +{ + FASSERT(instance_p); + + instance_p->is_ready = 0; + memset(instance_p, 0, sizeof(*instance_p)); + + return; +} + +/** + * @name: FSpimReset + * @msg: 重置FSPIM控制器 + * @return {FError} FSPIM_SUCCESS表示重置成功,其它返回值表示重置失败 + * @param {FSpim} *instance_p + */ +FError FSpimReset(FSpim *instance_p) +{ + FASSERT(instance_p); + uintptr base_addr = instance_p->config.base_addr; + FError ret = FSPIM_SUCCESS; + u32 reg_val; + u32 fifo; + + /* 禁用SPI控制器 */ + FSpimSetEnable(base_addr, FALSE); + + /* 选择数据长度和帧格式 */ + reg_val = FSPIM_CTRL_R0_DFS(FSPIM_DEFAULT_DFS) | + FSPIM_CTRL_R0_FRF(FSPIM_DEFAULT_FRF) | + FSPIM_CTRL_R0_CFS(FSPIM_DEFAULT_CFS); + + if (instance_p->config.en_test) + { + reg_val |= FSPIM_CTRL_R0_SLV_SRL(FSPIM_SRL_TEST); /* 设置测试模式,TX Fifo和RX Fifo内部短接 */ + } + else + { + reg_val |= FSPIM_CTRL_R0_SLV_SRL(FSPIM_SRL_NORAML); /* 设置为正常模式 */ + } + + FSpimSetCtrlR0(base_addr, reg_val); + + /* 选择串行时钟极性和相位 */ + FSpimSetCpha(base_addr, instance_p->config.cpha); + FSpimSetCpol(base_addr, instance_p->config.cpol); + + /* 设置传输模式 */ + FSpimSetTransMode(base_addr, FSPIM_TRANS_MODE_RX_TX); + + /* 禁用slave */ + FSpimSetSlaveEnable(base_addr, FALSE); + + /* 禁用SPI 中断,设置slave设备 */ + FSpimMaskIrq(base_addr, FSPIM_IMR_ALL_BITS); + FSpimSelSlaveDev(base_addr, instance_p->config.slave_dev_id); + + /* 获取SPI RX/TX FIFO 深度 */ + if (0 == instance_p->tx_fifo_len) + { + fifo = FSpimGetTxFifoDepth(base_addr); + instance_p->tx_fifo_len = ((fifo == 1) ? 0 : fifo); + FSPIM_INFO("fifo depth %d tx_fifo_len %d", fifo, instance_p->tx_fifo_len); + } + + if (0 == instance_p->rx_fifo_len) + { + fifo = FSpimGetRxFifoDepth(base_addr); + instance_p->rx_fifo_len = ((fifo == 1) ? 0 : fifo); + FSPIM_INFO("fifo depth %d tx_fifo_len %d", fifo, instance_p->tx_fifo_len); + } + + FSPIM_WRITE_REG32(base_addr, FSPIM_DMA_CR_OFFSET, 0x0); /* disable ddma */ + + if (instance_p->config.en_dma) + { + /* recv data in continuous way */ + FSpimSetCtrlR1(base_addr, FSPIM_CTRL_R1_NDF_64KB); + + /* setup fifo threshold */ + FSpimSetRxFifoThreshold(base_addr, instance_p->rx_fifo_len); + FSpimSetTxFifoThreshold(base_addr, instance_p->tx_fifo_len); + + /* setup fifo DMA level to trigger interrupt */ + FSpimSetRxDMALevel(base_addr, FSPIM_RX_DMA_LEVEL); + FSpimSetTxDMALevel(base_addr, FSPIM_TX_DMA_LEVEL); + } + else + { + FSpimSetCtrlR1(base_addr, 0); + + FSpimSetRxFifoThreshold(base_addr, 0); + FSpimSetTxFifoThreshold(base_addr, 0); + FSpimSetRxDMALevel(base_addr, 0); + FSpimSetTxDMALevel(base_addr, 0); + } + + + ret = FSpimSetSpeed(base_addr, instance_p->config.max_freq_hz); + if (FSPIM_SUCCESS != ret) + return ret; + + FSPIM_WRITE_REG32(base_addr, FSPIM_RX_SAMPLE_DLY_OFFSET, FSPIM_DEFAULT_RSD); + + /* 使能SPI控制器 */ + FSpimSetEnable(base_addr, TRUE); + + return ret; +} + +/** + * @name: FSpimGetTxRound + * @msg: 计算当前FIFO支持的发送字节数 + * @return {fsize_t} 当前TX FIFO可以容纳的字节数 + * @param {FSpim} *instance_p + */ +static fsize_t FSpimGetTxRound(FSpim *instance_p) +{ + fsize_t data_width = instance_p->config.n_bytes; + uintptr base_addr = instance_p->config.base_addr; + fsize_t tx_left_round, tx_fifo_room, rx_tx_gap; + + tx_left_round = (fsize_t)(instance_p->tx_buff_end - instance_p->tx_buff) / data_width; + tx_fifo_room = instance_p->tx_fifo_len - + FSpimGetTxFifoLevel(base_addr); + rx_tx_gap = ((fsize_t)(instance_p->rx_buff_end - instance_p->rx_buff) - + (fsize_t)(instance_p->tx_buff_end - instance_p->tx_buff)) / data_width; + + FSPIM_DEBUG("tx_left_round: %d, tx_fifo_room: %d, gap: %d", + tx_left_round, + tx_fifo_room, + ((fsize_t)(instance_p->tx_fifo_len) - rx_tx_gap)); + return min3(tx_left_round, + tx_fifo_room, + ((fsize_t)(instance_p->tx_fifo_len) - rx_tx_gap)); +} + +/** + * @name: FSpimFifoTx + * @msg: 利用Fifo进行发送 + * @return {无} + * @param {FSpim} *instance_p + */ +void FSpimFifoTx(FSpim *instance_p) +{ + FASSERT(instance_p); + fsize_t tx_round = FSpimGetTxRound(instance_p); + FSPIM_DEBUG("tx round: %d", tx_round); + uintptr base_addr = instance_p->config.base_addr; + u32 data_width = instance_p->config.n_bytes; + u16 data = 0xff; + + while (tx_round) + { + if (instance_p->tx_buff_end - instance_p->length) + { + if (FSPIM_1_BYTE == data_width) + { + /* + * Data Transfer Width is Byte (8 bit). + */ + data = *(u8 *)(instance_p->tx_buff); + } + else if (FSPIM_2_BYTE == data_width) + { + /* + * Data Transfer Width is Half Word (16 bit). + */ + data = *(u16 *)(instance_p->tx_buff); + } + else + { + FASSERT(0); + } + } + + FSpimWriteData(base_addr, data); + FSPIM_DEBUG(" send 0x%x", data); + instance_p->tx_buff += data_width; + tx_round--; + } +} + +/** + * @name: FSpimGetRxRound + * @msg: 获取当前Fifo支持的接收字节数 + * @return {fsize_t} 当前RX FIFO可以容纳的字节数 + * @param {FSpim} *instance_p + */ +static fsize_t FSpimGetRxRound(FSpim *instance_p) +{ + fsize_t data_width = instance_p->config.n_bytes; + uintptr base_addr = instance_p->config.base_addr; + + fsize_t rx_left_round = (fsize_t)(instance_p->rx_buff_end - instance_p->rx_buff) / data_width; + + FSPIM_DEBUG("left round %d, rx level %d", rx_left_round, FSpimGetRxFifoLevel(base_addr)); + return min(rx_left_round, (fsize_t)FSpimGetRxFifoLevel(base_addr)); +} + +/** + * @name: FSpimFifoRx + * @msg: 利用Fifo进行接收 + * @return {无} + * @param {FSpim} *instance_p + */ +void FSpimFifoRx(FSpim *instance_p) +{ + FASSERT(instance_p); + fsize_t rx_round = FSpimGetRxRound(instance_p); + FSPIM_DEBUG("rx round: %d", rx_round); + uintptr base_addr = instance_p->config.base_addr; + u32 data_width = instance_p->config.n_bytes; + u16 data; + + while (rx_round) + { + data = FSpimReadData(base_addr); + if ((fsize_t)(instance_p->rx_buff_end - instance_p->length)) + { + if (FSPIM_1_BYTE == data_width) + { + /* + * Data Transfer Width is Byte (8 bit). + */ + *(u8 *)(instance_p->rx_buff) = (u8)data; + FSPIM_DEBUG(" recv 0x%x", *(u8 *)(instance_p->rx_buff)); + } + else if (FSPIM_2_BYTE == data_width) + { + /* + * Data Transfer Width is Half Word (16 bit). + */ + *(u16 *)(instance_p->rx_buff) = (u16)data; + FSPIM_DEBUG(" recv 0x%x", *(u16 *)(instance_p->rx_buff)); + } + else + { + FASSERT(0); + } + + } + + instance_p->rx_buff += data_width; + rx_round--; + } + + return; +} + +/** + * @name: FSpimTransferPollFifo + * @msg: 先发送后接收数据 (阻塞处理),利用Fifo进行处理 + * @return {FError} FSPIM_SUCCESS表示处理成功,其它返回值表示处理失败 + * @param {FSpim} *instance_p 驱动控制数据 + * @param {void} *tx_buf 写缓冲区,可以为空,为空时表示只关注读数据,此时驱动会发送0xff读数据 + * @param {void} *rx_buf 读缓冲区, 可以为空,为空时表示值关注写数据,此时SPI总线上返回的数据会被抛弃 + * @param {fsize_t} len 进行传输的长度,如果tx_buf或者rx_buf不为空,则两个buf的长度必须为len + - 使用此函数前需要确保FSPIM驱动初始化成功 + - 从函数不会使用中断,会按照TX FIFO的深度进行传输,每次发送填满TX FIFO后触发发送/接收动作 + */ +FError FSpimTransferPollFifo(FSpim *instance_p, const void *tx_buf, void *rx_buf, fsize_t len) +{ + FASSERT(instance_p); + u32 reg_val; + uintptr base_addr = instance_p->config.base_addr; + u32 data_width = instance_p->config.n_bytes; + u32 tx_level; + FError ret = FSPIM_SUCCESS; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSPIM_ERROR("device is already initialized!!!"); + return FSPIM_ERR_NOT_READY; + } + + FSpimSetEnable(base_addr, FALSE); + + reg_val = FSpimGetCtrlR0(base_addr); + + reg_val &= ~FSPIM_CTRL_R0_DFS_MASK; + reg_val |= FSPIM_CTRL_R0_DFS((data_width << 3) - 1); + + reg_val &= ~FSPIM_CTRL_R0_TMOD_MASK; + if (tx_buf && rx_buf) + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_TX); + else if (rx_buf) + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_ONLY); + else + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_TX); + + FSpimSetCtrlR0(base_addr, reg_val); + + FSpimMaskIrq(base_addr, FSPIM_IMR_ALL_BITS); + + instance_p->length = len; + instance_p->tx_buff = tx_buf; + instance_p->tx_buff_end = tx_buf + len; + instance_p->rx_buff = rx_buf; + instance_p->rx_buff_end = rx_buf + len; + FSPIM_DEBUG("tx buff@%p-%d, rx buff@%p-%d", + instance_p->tx_buff, len, + instance_p->rx_buff, len); + + FSpimSetEnable(base_addr, TRUE); + + do + { + FSpimFifoTx(instance_p); + FSpimFifoRx(instance_p); + } + while (instance_p->rx_buff_end > instance_p->rx_buff); + + return ret; +} + +/** + * @name: FSpimTransferByInterrupt + * @msg: 先发送后接收数据 (中断处理),利用Fifo进行处理 + * @return {FError} FSPIM_SUCCESS表示处理成功,其它返回值表示处理失败 + * @param {FSpim} *instance_p 驱动控制数据 + * @param {void} *tx_buf 写缓冲区 + * @param {void} *rx_buf 读缓冲区 + * @param {fsize_t} len 读写缓冲区长度 (必须相等) + */ +FError FSpimTransferByInterrupt(FSpim *instance_p, const void *tx_buf, void *rx_buf, fsize_t len) +{ + FASSERT(instance_p); + u32 reg_val; + uintptr base_addr = instance_p->config.base_addr; + u32 data_width = instance_p->config.n_bytes; + u32 tx_level; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSPIM_ERROR("device is already initialized!!!"); + return FSPIM_ERR_NOT_READY; + } + + FSpimSetEnable(base_addr, FALSE); + + reg_val = FSpimGetCtrlR0(base_addr); + + reg_val &= ~FSPIM_CTRL_R0_DFS_MASK; + reg_val |= FSPIM_CTRL_R0_DFS((data_width << 3) - 1); + + reg_val &= ~FSPIM_CTRL_R0_TMOD_MASK; + if (tx_buf && rx_buf) + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_TX); + else if (rx_buf) + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_ONLY); + else + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_TX); + + FSpimSetCtrlR0(base_addr, reg_val); + + FSpimMaskIrq(base_addr, FSPIM_IMR_ALL_BITS); + + instance_p->length = len; + instance_p->tx_buff = tx_buf; + instance_p->tx_buff_end = instance_p->tx_buff + len; + instance_p->rx_buff = rx_buf; + instance_p->rx_buff_end = instance_p->rx_buff + len; + + /* 设置中断触发的时机,fifo填满一半,或者所有的数据填完 */ + tx_level = min(instance_p->tx_fifo_len / 2, instance_p->length / data_width); + FSpimSetTxFifoThreshold(base_addr, tx_level); + FSpimUmaskIrq(base_addr, FSPIM_IMR_TXEIS | FSPIM_IMR_TXOIS | FSPIM_IMR_RXUIS | FSPIM_IMR_RXOIS); + + FSpimSetEnable(base_addr, TRUE); + + return FSPIM_SUCCESS; +} + +#ifdef FSPIM_VERSION_2 /* E2000 */ + +/** + * @name: FSpimTransferDMA + * @msg: 启动SPIM DMA数据传输 + * @return {FError} FSPIM_SUCCESS表示启动DMA传输成功,其它值表示失败 + * @param {FSpim} *instance_p, 驱动控制数据 + * @param {boolean} tx, TRUE: 启动发送DMA + * @param {boolean} rx, TRUE: 启动接收DMA + */ +FError FSpimTransferDMA(FSpim *instance_p, boolean tx, boolean rx) +{ + FASSERT(instance_p); + u32 reg_val; + uintptr base_addr = instance_p->config.base_addr; + u32 data_width = instance_p->config.n_bytes; + + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSPIM_ERROR("device is not yet initialized!!!"); + return FSPIM_ERR_NOT_READY; + } + + FSpimSetEnable(base_addr, FALSE); + + /* set up spim transfer mode */ + reg_val = FSpimGetCtrlR0(base_addr); + reg_val &= ~FSPIM_CTRL_R0_DFS_MASK; + reg_val |= FSPIM_CTRL_R0_DFS((data_width << 3) - 1); + + reg_val &= ~FSPIM_CTRL_R0_TMOD_MASK; + if (tx && rx) + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_TX); + else if (rx) + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_ONLY); + else + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_TX); + + FSpimSetCtrlR0(base_addr, reg_val); + + FSpimMaskIrq(base_addr, FSPIM_IMR_ALL_BITS); /* mask all interrupts */ + + FSpimSetEnable(base_addr, TRUE); + + /* enable DMA tx / rx */ + reg_val = FSPIM_READ_REG32(base_addr, FSPIM_DMA_CR_OFFSET); + if (tx) + reg_val |= FSPIM_DMA_CR_TDMAE; + else + reg_val &= ~FSPIM_DMA_CR_TDMAE; + + if (rx) + reg_val |= FSPIM_DMA_CR_RDMAE; + else + reg_val &= ~FSPIM_DMA_CR_RDMAE; + FSPIM_WRITE_REG32(base_addr, FSPIM_DMA_CR_OFFSET, reg_val); + + FSpimSelSlaveDev(base_addr, instance_p->config.slave_dev_id); + + return FSPIM_SUCCESS; +} + +/** + * @name: FSpimSetChipSelection + * @msg: 设置片选信号 + * @return {NONE} + * @param {FSpim} *instance_p, 驱动控制数据 + * @param {boolean} on, TRUE: 片选打开, FALSE: 片选关闭 + */ +void FSpimSetChipSelection(FSpim *instance_p, boolean on) +{ + FASSERT(instance_p); + u32 reg_val; + FSpimSlaveDevice cs_n = instance_p->config.slave_dev_id; + uintptr base_addr = instance_p->config.base_addr; + if (FT_COMPONENT_IS_READY != instance_p->is_ready) + { + FSPIM_ERROR("device is not yet initialized!!!"); + return; + } + + reg_val = FSPIM_READ_REG32(base_addr, FSPIM_CS_OFFSET); + + if (on) + { + reg_val |= FSPIM_CHIP_SEL_EN((u32)cs_n); + reg_val |= FSPIM_CHIP_SEL((u32)cs_n); + } + else + { + reg_val &= ~FSPIM_CHIP_SEL_EN((u32)cs_n); + reg_val &= ~FSPIM_CHIP_SEL((u32)cs_n); + } + + FSPIM_WRITE_REG32(base_addr, FSPIM_CS_OFFSET, reg_val); + + return; +} +#endif + +/** + * @name: FSpimErrorToMessage + * @msg: 获取FSPIM模块错误码对应的错误信息 + * @return {const char *}, 错误码信息,NULL表示失败 + * @param {FError} error, FSPIM输入错误码 + */ +const char *FSpimErrorToMessage(FError error) +{ + const char *msg = NULL; + if (FSPIM_SUCCESS != error && (FSPIM_ERR_CODE_PREFIX != error & (FT_ERRCODE_SYS_MODULE_MASK | FT_ERRCODE_SUB_MODULE_MASK))) + { + /* if input error do not belong to this module */ + return msg; + } + u32 index = error & FT_ERRCODE_TAIL_VALUE_MASK; + + if (index < FSPIM_NUM_OF_ERR_CODE) + { + msg = FSPIM_ERROR_CODE_MSG[index]; + } + + return msg; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim.h b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim.h new file mode 100644 index 0000000000..cb3ffb346e --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim.h @@ -0,0 +1,214 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:08:38 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021-12-3 init commit + * 1.1 zhugengyu 2022-4-15 support test mode + * 1.2 zhugengyu 2022-5-13 support spi dma + */ + + +#ifndef DRIVERS_FSPI_M_H +#define DRIVERS_FSPI_M_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "ferror_code.h" +#include "fassert.h" +#include "sdkconfig.h" + +/************************** Constant Definitions *****************************/ + +#define FSPIM_SUCCESS FT_SUCCESS +#define FSPIM_ERR_INVAL_STATE FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 0) +#define FSPIM_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 1) +#define FSPIM_ERR_INVAL_PARAM FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 2) +#define FSPIM_ERR_BUS_BUSY FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 3) +#define FSPIM_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 4) +#define FSPIM_ERR_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 5) +#define FSPIM_ERR_TRANS_FAIL FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 6) +#define FSPIM_ERR_DMA_INIT FT_MAKE_ERRCODE(ErrModBsp, ErrBspSpi, 6) + +#if defined(CONFIG_TARGET_F2000_4) || defined(CONFIG_TARGET_D2000) +#define FSPIM_VERSION_1 /* 用于FT2000/4和D2000平台的SPIM */ +#elif defined(CONFIG_TARGET_E2000) +#define FSPIM_VERSION_2 /* 用于E2000平台的SPIM */ +#else +#error "Invalid target board !!!" +#endif + +/* add up new error code above and plust FSPIM_ERR_CODE_MAX by ONE*/ +#define FSPIM_ERR_CODE_PREFIX FSPIM_ERR_TRANS_FAIL & (FT_ERRCODE_SYS_MODULE_MASK | FT_ERRCODE_SUB_MODULE_MASK) +#define FSPIM_NUM_OF_ERR_CODE 8 + +typedef enum +{ + FSPIM_SLAVE_DEV_0 = 0, + FSPIM_SLAVE_DEV_1, + FSPIM_SLAVE_DEV_2, + FSPIM_SLAVE_DEV_3, + + FSPIM_NUM_OF_SLAVE_DEV +} FSpimSlaveDevice; + +typedef enum +{ + FSPIM_1_BYTE = 1, + FSPIM_2_BYTE = 2, + + FSPIM_MAX_BYTES_NUM +} FSpimTransByte; + +typedef enum +{ + FSPIM_TRANS_MODE_RX_TX = 0x0, + FSPIM_TRANS_MODE_TX_ONLY = 0x1, + FSPIM_TRANS_MODE_RX_ONLY = 0x2, + FSPIM_TRANS_MODE_READ_EEPROM = 0x3, + + FSPIM_TRANS_MODE_MAX +} FSpimTransMode; + +/* + CPOL = 0, CPHA = 0, sample at the first rising edge + CPOL = 1, CPHA = 1, sample at the second rising edge + CPOL = 1, CPHA = 0, sample at the second falling edge + CPOL = 0, CPHA = 1, sample at the first falling edge +*/ + +typedef enum +{ + FSPIM_CPOL_LOW = 0, /* pharse 0 CPOL=0 */ + FSPIM_CPOL_HIGH /* pharse 1 CPOL=1 */ +} FSpimCpolType; + +typedef enum +{ + FSPIM_CPHA_1_EDGE = 0, /* sample at the 1st edge, CPHA=0 */ + FSPIM_CPHA_2_EDGE /* sample at the 2nd edge, CPHA=1 */ +} FSpimCphaType; + +typedef enum +{ + FSPIM_INTR_EVT_RX_DONE = 0, /* 接收完成事件 */ + FSPIM_INTR_EVT_TX_OVERFLOW, /* 发送FIFO上溢事件 */ + FSPIM_INTR_EVT_RX_UNDERFLOW, /* 接收FIFO下溢事件 */ + FSPIM_INTR_EVT_RX_OVERFLOW, /* 接收FIFO上溢事件 */ + + FSPIM_INTR_EVT_NUM +} FSpimIntrEvtType; + +/**************************** Type Definitions *******************************/ + +/** + * This typedef contains configuration information for the device. + */ +typedef struct +{ + u32 instance_id; /* Device instance id */ + uintptr base_addr; /* Device base address */ + u32 irq_num; /* Device intrrupt id */ + u32 irq_prority; /* Device intrrupt priority */ + FSpimSlaveDevice slave_dev_id; /* Slave device id */ + u32 max_freq_hz; /* Clock frequency in Hz */ + FSpimTransByte n_bytes; /* Bytes in transfer */ + FSpimCpolType cpol; /* Polarity of the clock */ + FSpimCphaType cpha; /* Phase of the clock */ + boolean en_test; /* Enable test mode */ + boolean en_dma; /* Enable DMA */ +} FSpimConfig; + +typedef void (*FSpimEvtHandler)(void *instance_p, void *param); + +/** + * This typedef contains driver instance data. The user is required to allocate a + * variable of this type for every device in the system. A pointer + * to a variable of this type is then passed to the driver API functions. + */ +typedef struct +{ + FSpimConfig config; /* Current active configs */ + u32 is_ready; /* Device is initialized and ready */ + u32 length; /* Data length in transfer */ + const void *tx_buff; /* Tx buffer beg */ + void *rx_buff; /* Rx buffer beg */ + const void *tx_buff_end; /* Tx buffer end */ + void *rx_buff_end; /* Rx buffer end */ + u32 tx_fifo_len; /* Depth of tx fifo */ + u32 rx_fifo_len; /* Depth of rx fifo */ + FSpimEvtHandler evt_handler[FSPIM_INTR_EVT_NUM]; /* event handler for interrupt */ + void *evt_param[FSPIM_INTR_EVT_NUM]; /* parameters ptr of event handler */ +} FSpim; + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/* fspim_sinit.c */ +/* 获取FSPIM驱动的默认配置参数 */ +const FSpimConfig *FSpimLookupConfig(u32 instance_id); + +/* fspim.c */ +/* 完成FSPIM驱动实例的初始化,使之可以使用*/ +FError FSpimCfgInitialize(FSpim *instance_p, const FSpimConfig *cofig_p); + +/* 完成I2C驱动实例去使能,清零实例数据 */ +void FSpimDeInitialize(FSpim *instance_p); + +/* 先发送后接收数据 (阻塞处理),利用Fifo进行处理 */ +FError FSpimTransferPollFifo(FSpim *instance_p, const void *tx_buf, void *rx_buf, fsize_t len); + +#ifdef FSPIM_VERSION_2 /* E2000 */ +/* 启动SPIM DMA数据传输 */ +FError FSpimTransferDMA(FSpim *instance_p, boolean tx, boolean rx); + +/* 设置片选信号 */ +void FSpimSetChipSelection(FSpim *instance_p, boolean on); +#endif + +/* 获取FSPIM模块错误码对应的错误信息 */ +const char *FSpimErrorToMessage(FError error); + +/* fspim_intr.c */ +/* 先发送后接收数据 (中断处理),利用Fifo进行处理 */ +FError FSpimTransferByInterrupt(FSpim *instance_p, const void *tx_buf, void *rx_buf, fsize_t len); + +/* SPIM中断处理函数 */ +void FSpimInterruptHandler(s32 vector, void *param); + +/* 注册FSPIM中断事件处理函数 */ +void FSpimRegisterIntrruptHandler(FSpim *instance_p, FSpimIntrEvtType evt, FSpimEvtHandler handler, void *param); + +/* 打印SPIM控制寄存器信息 */ +void FSpimDumpRegister(uintptr base_addr); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_g.c b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_g.c new file mode 100644 index 0000000000..5094ff58ea --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_g.c @@ -0,0 +1,100 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:07:55 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021-12-3 init commit + * 1.1 zhugengyu 2022-4-15 support test mode + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "sdkconfig.h" + +#include "fspim.h" +#include "fspim_hw.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +const FSpimConfig FSPIM_CONFIG_TBL[FSPI_DEVICE_NUM] = +{ + [FSPI0_ID] = + { + .instance_id = FSPI0_ID, /* Id of device*/ + .base_addr = FSPI0_BASE, + .irq_num = FSPI0_IRQ_NUM, + .irq_prority = 0, + .slave_dev_id = FSPIM_SLAVE_DEV_0, + .max_freq_hz = 4000000, + .n_bytes = 1, + .en_test = FALSE, + .en_dma = FALSE + }, + [FSPI1_ID] = + { + .instance_id = FSPI1_ID, /* Id of device*/ + .base_addr = FSPI1_BASE, + .irq_num = FSPI1_IRQ_NUM, + .irq_prority = 0, + .slave_dev_id = FSPIM_SLAVE_DEV_0, + .max_freq_hz = 4000000, + .n_bytes = 1, + .en_test = FALSE, + .en_dma = FALSE + }, +#if defined(CONFIG_TARGET_E2000S) || defined(CONFIG_TARGET_E2000D) || defined(CONFIG_TARGET_E2000Q) + [FSPI2_ID] = + { + .instance_id = FSPI2_ID, /* Id of device*/ + .base_addr = FSPI2_BASE, + .irq_num = FSPI2_IRQ_NUM, + .irq_prority = 0, + .slave_dev_id = FSPIM_SLAVE_DEV_0, + .max_freq_hz = 4000000, + .n_bytes = 1, + .en_test = FALSE, + .en_dma = FALSE + }, + [FSPI3_ID] = + { + .instance_id = FSPI3_ID, /* Id of device*/ + .base_addr = FSPI3_BASE, + .irq_num = FSPI3_IRQ_NUM, + .irq_prority = 0, + .slave_dev_id = FSPIM_SLAVE_DEV_0, + .max_freq_hz = 4000000, + .n_bytes = 1, + .en_test = FALSE, + .en_dma = FALSE + }, +#endif +}; + + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_hw.c b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_hw.c new file mode 100644 index 0000000000..c1004bea23 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_hw.c @@ -0,0 +1,256 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:08:00 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021-12-3 init commit + * 1.1 zhugengyu 2022-4-15 support test mode + */ + + +#include "fassert.h" +#include "fdebug.h" +#include "fspim_hw.h" +#include "fspim.h" + +/***************************** Include Files *********************************/ + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSPIM_DEBUG_TAG "SPIM-HW" +#define FSPIM_ERROR(format, ...) FT_DEBUG_PRINT_E(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_WARN(format, ...) FT_DEBUG_PRINT_W(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_INFO(format, ...) FT_DEBUG_PRINT_I(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/** + * @name: FSpimGetTxFifoDepth + * @msg: 获取TX Fifo可以设置的最大深度 + * @return {u32} TX Fifo的深度 + * @param {uintptr} base_addr, SPI控制器基地址 + */ +u32 FSpimGetTxFifoDepth(uintptr base_addr) +{ + u32 fifo_depth; + for (fifo_depth = 1; fifo_depth < FSPIM_MAX_FIFO_DEPTH; fifo_depth++) + { + FSpimSetTxFifoThreshold(base_addr, fifo_depth); + if (fifo_depth != FSpimGetTxFifoThreshold(base_addr)) + { + FSPIM_INFO("Tx fifo threshold is %d", fifo_depth); + break; + } + } + + FSpimSetTxFifoThreshold(base_addr, 0); + return fifo_depth; +} + +/** + * @name: FSpimGetRxFifoDepth + * @msg: 获取RX Fifo可以设置的最大深度 + * @return {u32} Rx Fifo的深度 + * @param {uintptr} base_addr, SPI控制器基地址 + */ +u32 FSpimGetRxFifoDepth(uintptr base_addr) +{ + u32 fifo_depth = FSPIM_MIN_FIFO_DEPTH; + while (FSPIM_MAX_FIFO_DEPTH >= fifo_depth) + { + FSpimSetRxFifoThreshold(base_addr, fifo_depth); + if (fifo_depth != FSpimGetRxFifoThreshold(base_addr)) + { + FSPIM_INFO("Rx fifo threshold is %d", fifo_depth); + break; + } + + fifo_depth++; + } + + return fifo_depth; +} + +/** + * @name: FSpimSelSlaveDev + * @msg: 选择SPI从设备 + * @return {无} + * @param {uintptr} base_addr, SPI控制器基地址 + * @param {u32} slave_dev_id, 从设备ID + */ +void FSpimSelSlaveDev(uintptr base_addr, u32 slave_dev_id) +{ + FASSERT(slave_dev_id < FSPIM_NUM_OF_SLAVE_DEV); + u32 reg_val; + + reg_val = (FSPIM_SER_SELECT << slave_dev_id); + FSPIM_WRITE_REG32(base_addr, FSPIM_SER_OFFSET, reg_val); + return; +} + +/** + * @name: FSpimSetSpeed + * @msg: 设置SPI传输速度 + * @return {FError} + * @param {uintptr} base_addr, SPI控制器基地址 + * @param {u32} speed, SPI传输速度设置 + */ +FError FSpimSetSpeed(uintptr base_addr, u32 speed) +{ + u32 clk_div; + boolean enabled = FSpimGetEnable(base_addr); + + if (enabled) + FSpimSetEnable(base_addr, FALSE); + + clk_div = FSPI_FREQ / speed; + FSPIM_INFO("set clk div as %d", clk_div); + FSPIM_WRITE_REG32(base_addr, FSPIM_BAUD_R_OFFSET, clk_div); + + if (enabled) + FSpimSetEnable(base_addr, TRUE); + + return FSPIM_SUCCESS; +} + +/** + * @name: FSpimSetTransMode + * @msg: 设置SPI传输模式 + * @return {无} + * @param {uintptr} base_addr, SPI控制器基地址 + * @param {u32} trans_mode, SPI传输模式设置 + */ +void FSpimSetTransMode(uintptr base_addr, u32 trans_mode) +{ + FASSERT(trans_mode < FSPIM_TRANS_MODE_MAX); + u32 reg_val; + boolean enabled = FSpimGetEnable(base_addr); + + if (enabled) + FSpimSetEnable(base_addr, FALSE); + + reg_val = FSpimGetCtrlR0(base_addr); + reg_val &= ~FSPIM_CTRL_R0_TMOD_MASK; /* clear trans mode bits */ + switch (trans_mode) + { + case FSPIM_TRANS_MODE_RX_TX: + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_TX); + break; + case FSPIM_TRANS_MODE_TX_ONLY: + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_TX_ONLY); + break; + case FSPIM_TRANS_MODE_RX_ONLY: + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RX_ONLY); + break; + case FSPIM_TRANS_MODE_READ_EEPROM: + reg_val |= FSPIM_CTRL_R0_TMOD(FSPIM_TMOD_RD_EEPROM); + break; + default: + FASSERT(0); + break; + } + + FSpimSetCtrlR0(base_addr, reg_val); + + if (enabled) + FSpimSetEnable(base_addr, TRUE); + + return; +} + +/** + * @name: FSpimSetCpha + * @msg: 设置串行时钟相位 + * @return {无} + * @param {uintptr} base_addr, SPI控制器基地址 + * @param {u32} cpha_mode, SPI控制器的相位设置 + */ +void FSpimSetCpha(uintptr base_addr, u32 cpha_mode) +{ + u32 reg_val = FSpimGetCtrlR0(base_addr); + + reg_val &= ~FSPIM_CTRL_R0_SCPHA_MASK; /* clear bits */ + if (FSPIM_CPHA_1_EDGE == cpha_mode) + reg_val |= FSPIM_CTRL_R0_SCPHA(FSPIM_SCPHA_SWITCH_DATA_MID); + else if (FSPIM_CPHA_2_EDGE == cpha_mode) + reg_val |= FSPIM_CTRL_R0_SCPHA(FSPIM_SCPHA_SWITCH_DATA_BEG); + else + FASSERT(0); + + FSpimSetCtrlR0(base_addr, reg_val); +} + +/** + * @name: FSpimSetCpol + * @msg: 设置串行时钟极性 + * @return {无} + * @param {uintptr} base_addr, SPI控制器基地址 + * @param {u32} cpol_mode, SPI控制器的极性设置 + */ +void FSpimSetCpol(uintptr base_addr, u32 cpol_mode) +{ + u32 reg_val = FSpimGetCtrlR0(base_addr); + + reg_val &= ~FSPIM_CTRL_R0_SCPOL_MASK; /* clear bits */ + if (FSPIM_CPOL_LOW == cpol_mode) + reg_val |= FSPIM_CTRL_R0_SCPOL(FSPIM_SCPOL_INACTIVE_LOW); + else if (FSPIM_CPOL_HIGH == cpol_mode) + reg_val |= FSPIM_CTRL_R0_SCPOL(FSPIM_SCPOL_INACTIVE_HIGH); + else + FASSERT(0); + + FSpimSetCtrlR0(base_addr, reg_val); +} + +/** + * @name: FSpimSetSlaveEnable + * @msg: 使能/去使能和从设备的连接 + * @return {无} + * @param {uintptr} base_addr, SPI控制器基地址 + * @param {boolean} enable, TRUE: 使能从设备, FALSE: 去使能从设备 + */ +void FSpimSetSlaveEnable(uintptr base_addr, boolean enable) +{ + u32 reg_val; + boolean enabled = FSpimGetEnable(base_addr); + + if (enabled) + FSpimSetEnable(base_addr, FALSE); + + reg_val = FSpimGetCtrlR0(base_addr); + + reg_val &= ~FSPIM_CTRL_R0_SLV_OE_MASK; + if (enable) + reg_val |= FSPIM_CTRL_R0_SLV_OE(FSPIM_SLAVE_TX_ENABLE); + else + reg_val |= FSPIM_CTRL_R0_SLV_OE(FSPIM_SLAVE_TX_DISALE); + + FSpimSetCtrlR0(base_addr, reg_val); + + if (enabled) + FSpimSetEnable(base_addr, TRUE); + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_hw.h b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_hw.h new file mode 100644 index 0000000000..d66f3bfa30 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_hw.h @@ -0,0 +1,588 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:08:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021-12-3 init commit + * 1.1 zhugengyu 2022-4-15 support test mode + * 1.2 zhugengyu 2022-5-13 support spi dma + */ + + +#ifndef DRIVERS_FSPIM_M_HW_H +#define DRIVERS_FSPIM_M_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif +/***************************** Include Files *********************************/ + +#include "fparameters.h" +#include "fkernel.h" +#include "fio.h" +#include "ftypes.h" + +/************************** Constant Definitions *****************************/ +/** @name Register Map + * + * Register offsets from the base address of an SD device. + * @{ + */ +/* offset map of SPI register */ +#define FSPIM_CTRL_R0_OFFSET 0x00 /* Ctrl register 0 */ +#define FSPIM_CTRL_R1_OFFSET 0x04 /* Ctrl register 1 */ +#define FSPIM_SSIENR_OFFSET 0x08 /* SPI enable register */ +#define FSPIM_MWCR_OFFSET 0x0c /* Microwire ctrl register */ +#define FSPIM_SER_OFFSET 0x10 /* Slave enable register */ +#define FSPIM_BAUD_R_OFFSET 0x14 /* Baudrate set register */ +#define FSPIM_TXFTL_R_OFFSET 0x18 /* Tx threshold register */ +#define FSPIM_RXFTL_R_OFFSET 0x1c /* Rx threshold register */ +#define FSPIM_TXFLR_OFFSET 0x20 /* Tx level register */ +#define FSPIM_RXFLR_OFFSET 0x24 /* Rx level register */ +#define FSPIM_SR_OFFSET 0x28 /* Status register */ +#define FSPIM_IMR_OFFSET 0x2c /* Intr mask register */ +#define FSPIM_ISR_OFFSET 0x30 /* Irq Status register */ +#define FSPIM_RIS_R_OFFSET 0x34 /* Intr status register */ +#define FSPIM_TXOI_CR_OFFSET 0x38 /* TX FIFO overflow intr clear register */ +#define FSPIM_RXOI_CR_OFFSET 0x3c /* RX FIFO overflow intr clear register */ +#define FSPIM_RXUI_CR_OFFSET 0x40 /* TX FIFO underflow intr clear register */ +#define FSPIM_MSTI_CR_OFFSET 0x44 /* Multi slave intr clear register */ +#define FSPIM_ICR_OFFSET 0x48 /* Intr clear register */ +#define FSPIM_DMA_CR_OFFSET 0x4c /* DMA ctrl register */ +#define FSPIM_DMA_TDLR_OFFSET 0x50 /* DMA TX Data level register */ +#define FSPIM_DMA_RDLR_OFFSET 0x54 /* DMA RX Data level register */ +#define FSPIM_IDR_OFFSET 0x58 /* Identification register */ +#define FSPIM_DR_OFFSET 0x60 /* Data register */ +#define FSPIM_RX_SAMPLE_DLY_OFFSET 0xfc /* RX Data delay register */ +#define FSPIM_CS_OFFSET 0x100 /* Chip selection register */ + +/** @name FSPIM_CTRL_R0_OFFSET Register + */ + +#define FSPIM_CTRL_R0_DFS_MASK GENMASK(3, 0) +#define FSPIM_CTRL_R0_DFS(x) (FSPIM_CTRL_R0_DFS_MASK & ((x) << 0)) /* 选择数据长度 */ +#define FSPIM_CTRL_R0_FRF(x) (GENMASK(5, 4) & ((x) << 4)) /* 选择传输模式 */ +#define FSPIM_CTRL_R0_SCPHA(x) ((x) << 6) /* 串行时钟相位 */ +#define FSPIM_CTRL_R0_SCPHA_MASK BIT(6) +enum +{ + FSPIM_SCPHA_SWITCH_DATA_MID = 0x0, + FSPIM_SCPHA_SWITCH_DATA_BEG = 0x1 +}; +#define FSPIM_CTRL_R0_SCPOL(x) ((x) << 7) /* 串行时钟极性 */ +#define FSPIM_CTRL_R0_SCPOL_MASK BIT(7) +enum +{ + FSPIM_SCPOL_INACTIVE_LOW = 0, + FSPIM_SCPOL_INACTIVE_HIGH = 1 +}; +#define FSPIM_CTRL_R0_TMOD_MASK GENMASK(9, 8) +#define FSPIM_CTRL_R0_TMOD(x) (FSPIM_CTRL_R0_TMOD_MASK & ((x) << 8)) /* 传输模式控制位 */ +#define FSPIM_CTRL_R0_TMOD_SHIFT 8 +enum +{ + FSPIM_TMOD_RX_TX = 0b00, + FSPIM_TMOD_TX_ONLY = 0b01, + FSPIM_TMOD_RX_ONLY = 0b10, + FSPIM_TMOD_RD_EEPROM = 0b11 +}; +#define FSPIM_CTRL_R0_SLV_OE(x) ((x) << 10) /* 从机发送逻辑使能位 */ +#define FSPIM_CTRL_R0_SLV_OE_MASK BIT(10) +enum +{ + FSPIM_SLAVE_TX_ENABLE = 0, + FSPIM_SLAVE_TX_DISALE = 1 +}; +#define FSPIM_CTRL_R0_SLV_SRL(x) ((x) << 11) /* 移位寄存器回环 */ +enum +{ + FSPIM_SRL_NORAML = 0, + FSPIM_SRL_TEST = 1 +}; +#define FSPIM_CTRL_R0_CFS(x) (GENMASK(5, 12) & ((x) << 12)) /* 数据大小控制位,用于 Microwire 模式 */ + +/** @name FSPIM_CTRL_R1_OFFSET Register + */ +/* FSPIM_TMOD_RX_ONLY 或 FSPIM_TMOD_RD_EEPROM 该字段设置为 SPI 连续接收的数据量 */ +#define FSPIM_CTRL_R1_NDF(x) (GENMASK(15, 0) & ((x) << 0)) +#define FSPIM_CTRL_R1_NDF_64KB 0b11 + +/** @name FSPIM_SSIENR_OFFSET Register + */ +#define FSPIM_SSIENR_SSI_EN(x) ((x) << 0) /* SPI 使能启用和禁用所有 SPI 操作 */ + +/** @name FSPIM_MWCR_OFFSET Register + */ +#define FSPIM_MWCR_MW_MOD(x) ((x) << 0) /* Microwire 传输模式 */ +enum +{ + FSPIM_MWMODE_NO_CONT_TRANS = 0, /* 非连续传输 */ + FSPIM_MWMODE_CONT_TRANS = 1 /* 连续传输 */ +}; + +#define FSPIM_MWCR_MDD(x) ((x) << 1) /* Microwire 控制位 */ +enum +{ + FSPIM_MWCR_RX_EXT = 0, /* 从外部串行设备接收数据 */ + FSPIM_MWCR_TX_EXT /* 数据发送到外部串行设备 */ +}; + +#define FSPIM_MWCR_MHS(x) ((x) << 2) /* Microwire 握手 */ +enum +{ + FSPU_MWCR_DISABLE_HANDSHAKING = 0, + FSPU_MWCR_ENABLE_HANDSHAKING = 1 +}; + +/** @name FSPIM_SER_OFFSET Register + */ +#define FSPIM_SER(x) (GENMASK(3, 0) & ((x) << 0)) /* 从机选择信号启动标志 */ +/* 寄存器中的每一个位都对应来自 SPI 主机的从选信号(ss_x_n]).当此寄 + 存器中的某个位被置为 1 时,串行口传输开始时 */ +enum +{ + FSPIM_SER_UNSELECT = 0x0, + FSPIM_SER_SELECT = 0x1 +}; + +/** @name FSPIM_BAUD_R_OFFSET Register + */ +#define FSPIM_BAUD_R_SCKDV(x) (GENMASK(15, 0) & ((x) << 0)) /* SCKDV 为 2 ~ 65534 之间的任何偶数值 */ +#define FSPIM_BAUD_R_SCKDV_MIN 2 +#define FSPIM_BAUD_R_SCKDV_MAX 65534 +#define FSPIM_BAUD_R_SCKDV_IS_VALID(x) (0 == (x) % 2) + +/** @name FSPIM_TXFTL_R_OFFSET Register + */ +#define FSPIM_TXFTL_R_TFT(x) (GENMASK(2, 0) & ((x) << 0)) /* 发送 FIFO 阙值 */ + +/** @name FSPIM_RXFTL_R_OFFSET Register + */ +#define FSPIM_RXFTL_R_RFT(x) (GENMASK(3, 0) & ((x) << 0)) /* 接收 FIFO 阙值 */ + +/** @name FSPIM_TXFLR_OFFSET Register + */ +#define FSPIM_TXFLR_TXTFL(x) (GENMASK(3, 0) & ((x) << 0)) /* 发送 FIFO 等级 */ + +/** @name FSPIM_RXFLR_OFFSET Register + */ +#define FSPIM_RXFLR_RXTFL(x) (GENMASK(3, 0) & ((x) << 0)) /* 接收 FIFO 等级 */ + +/** @name FSPIM_SR_OFFSET Register, RO + */ +#define FSPIM_SR_BUSY BIT(0) /* SPI 总线繁忙标志位 */ +#define FSPIM_SR_TFNF BIT(1) /* 发送 FIFO 不满 */ +#define FSPIM_SR_TFE BIT(2) /* 发送 FIFO 为空 */ +#define FSPIM_SR_RFNE BIT(3) /* 接收 FIFO 不为空 */ +#define FSPIM_SR_RFF BIT(4) /* 接收 FIFO 满 */ +#define FSPIM_SR_TXE BIT(5) /* 传输错误 */ +#define FSPIM_SR_DCOL BIT(6) /* 传输数据冲突错误 */ +#define FSPIM_SR_ALL_BITS GENMASK(0, 6) + +/** @name FSPIM_IMR_OFFSET Register + */ +#define FSPIM_IMR_TXEIS BIT(0) /* 发送 FIFO 空中断 */ +#define FSPIM_IMR_TXOIS BIT(1) /* 发送 FIFO 上溢中断 */ +#define FSPIM_IMR_RXUIS BIT(2) /* 接收 FIFO 下溢中断 */ +#define FSPIM_IMR_RXOIS BIT(3) /* 接收 FIFO 上溢中断 */ +#define FSPIM_IMR_RXFIS BIT(4) /* 接收 FIFO 满中断 */ +#define FSPIM_IMR_ALL_BITS GENMASK(4, 0) + +/** @name FSPIM_ISR_OFFSET Register + */ +#define FSPIM_ISR_TXEIS BIT(0) /* 发送 FIFO 空中断状态 */ +#define FSPIM_ISR_TXOIS BIT(1) /* 发送 FIFO 上溢中断状态 */ +#define FSPIM_ISR_RXUIS BIT(2) /* 接收 FIFO 下溢中断状态 */ +#define FSPIM_ISR_RXOIS BIT(3) /* 接收 FIFO 上溢中断状态 */ +#define FSPIM_ISR_RXFIS BIT(4) /* 接收 FIFO 满中断状态 */ +#define FSPIM_ISR_MSTIS BIT(5) /* 多主机竞争中断状态 */ + +/** @name FSPIM_RIS_R_OFFSET Register + */ +#define FSPIM_RIS_R_TXEIR BIT(0) /* 传输 FIFO 空生成中断状态 */ +#define FSPIM_RIS_R_TXOIR BIT(1) /* 传输 FIFO 上溢生成中断状态 */ +#define FSPIM_RIS_R_RXUIR BIT(2) /* 接收 FIFO 下溢生成中断状态 */ +#define FSPIM_RIS_R_RXOIR BIT(3) /* 接收 FIFO 上溢生成中断状态 */ +#define FSPIM_RIS_R_RXFIR BIT(4) /* 接收 FIFO 满生成中断状态 */ +#define FSPIM_RIS_R_MSTIR BIT(5) /* 多主机冲突生成中断状态 */ +#define FSPIM_RIS_R_ALL_BITS GENMASK(5, 0) + +/** @name FSPIM_TXOI_CR_OFFSET Register + */ +#define FSPIM_TXOICR BIT(0) /* 清除传输 FIFO 溢出中断 */ + +/** @name FSPIM_RXOI_CR_OFFSET Register + */ +#define FSPIM_RXOICR BIT(0) /* 清除传输 FIFO 溢出中断 */ + +/** @name FSPIM_RXUI_CR_OFFSET Register + */ +#define FSPIM_RXUICR BIT(0) /* 清除传输 FIFO 下溢中断 */ + +/** @name FSPIM_MSTI_CR_OFFSET Register + */ +#define FSPIM_MSTICR BIT(0) /* 清除多主争用中断 */ + +/** @name FSPIM_ICR_OFFSET Register + */ +#define FSPIM_ICR BIT(0) /* 清除中断 */ + +/** @name FSPIM_DMA_CR_OFFSET Register + */ +#define FSPIM_DMA_CR_RDMAE BIT(0) /* DMA 接收使能 */ +#define FSPIM_DMA_CR_TDMAE BIT(1) /* DMA 发送使能 */ + +/** @name FSPIM_DMA_TDLR_OFFSET Register + */ +#define FSPIM_DMATDL(x) (GENMASK(2, 0) & ((x) << 0)) /* 发送数据等级 */ + +/** @name FSPIM_DMA_RDLR_OFFSET Register + */ +#define FSPIM_DMARDL(x) (GENMASK(2, 0) & ((x) << 0)) /* 接收数据等级 */ + +/** @name FSPIM_IDR_OFFSET Register + */ +#define FSPIM_IDCODE(x) (GENMASK(31, 0) & ((x) << 0)) /* 识别码。即外部设备标识代码 */ + +/** @name FSPIM_DR_OFFSET Register + */ +#define FSPIM_DR(x) (GENMASK(15, 0) & ((x) << 0)) /* 数据寄存器 */ + +/** @name FSPIM_RX_SAMPLE_DLY_OFFSET Register + */ +#define FSPIM_RSD(x) (GENMASK(7, 0) & ((x) << 0)) /* 接收数据延时 */ + +/** @name FSPIM_CS_OFFSET Register + */ +#define FSPIM_NUM_OF_CS 4U +#define FSPIM_CHIP_SEL_EN(cs) BIT((cs) + FSPIM_NUM_OF_CS) /* 1: enable chip selection */ +#define FSPIM_CHIP_SEL(cs) BIT(cs) + +#define FSPIM_DEFAULT_DFS 0x7 +#define FSPIM_DEFAULT_FRF 0x0 +#define FSPIM_DEFAULT_RSD 0x6 +#define FSPIM_DEFAULT_CFS 0x0 + +#define FSPIM_MIN_FIFO_DEPTH 0 +#define FSPIM_MAX_FIFO_DEPTH 256 +#define FSPIM_TIMEOUT 256 + +#define FSPIM_TX_DMA_LEVEL 0x10 +#define FSPIM_RX_DMA_LEVEL 0xf + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSPIM_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) +#define FSPIM_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)(reg_offset), (u32)(reg_value)) + +/** + * @name: FSpimSetCtrlR0 + * @msg: 设置CTRL_R0寄存器 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} val + */ +static inline void FSpimSetCtrlR0(uintptr base_addr, u32 val) +{ + FSPIM_WRITE_REG32(base_addr, FSPIM_CTRL_R0_OFFSET, val); +} + +/** + * @name: FSpimGetCtrlR0 + * @msg: 获取CTRL_R0寄存器的值 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetCtrlR0(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_CTRL_R0_OFFSET); +} + +/** + * @name: FSpimSetCtrlR0 + * @msg: 设置CTRL_R1寄存器 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} val + */ +static inline void FSpimSetCtrlR1(uintptr base_addr, u32 val) +{ + FSPIM_WRITE_REG32(base_addr, FSPIM_CTRL_R1_OFFSET, val); +} + +/** + * @name: FSpimSetTxFifoThreshold + * @msg: 设置TX Fifo阈值 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} val + */ +static inline void FSpimSetTxFifoThreshold(uintptr base_addr, u32 val) +{ + FSPIM_WRITE_REG32(base_addr, FSPIM_TXFTL_R_OFFSET, val); +} + +/** + * @name: FSpimGetTxFifoThreshold + * @msg: 获取TX Fifo阈值 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetTxFifoThreshold(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_TXFTL_R_OFFSET); +} + +/** + * @name: FSpimSetRxFifoThreshold + * @msg: 设置RX Fifo阈值 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} val + */ +static inline void FSpimSetRxFifoThreshold(uintptr base_addr, u32 val) +{ + FSPIM_WRITE_REG32(base_addr, FSPIM_RXFTL_R_OFFSET, val); +} + +/** + * @name: FSpimGetRxFifoThreshold + * @msg: 获取RX Fifo阈值 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetRxFifoThreshold(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_RXFTL_R_OFFSET); +} + +/** + * @name: FSpimGetTxFifoLevel + * @msg: 获取当前TX Fifo等级 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetTxFifoLevel(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_TXFLR_OFFSET); +} + +/** + * @name: FSpimGetRxFifoLevel + * @msg: 获取当前RX Fifo等级 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetRxFifoLevel(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_RXFLR_OFFSET); +} + +/** + * @name: FSpimGetTxDMALevel + * @msg: 获取当前的TX DMA等级 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetTxDMALevel(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_DMA_TDLR_OFFSET); +} + +/** + * @name: FSpimGetRxDMALevel + * @msg: 获取当前的RX DMA等级 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetRxDMALevel(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_DMA_RDLR_OFFSET); +} + +/** + * @name: FSpimSetTxDMALevel + * @msg: 设置TX DMA等级 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} level, TX DMA等级, 应该与FIFO阈值保持一致 + */ +static inline void FSpimSetTxDMALevel(uintptr base_addr, u32 level) +{ + FSPIM_WRITE_REG32(base_addr, FSPIM_DMA_TDLR_OFFSET, level); +} + +/** + * @name: FSpimSetRxDMALevel + * @msg: 设置RX DMA等级 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} level, RX DMA等级, 应该与FIFO阈值保持一致 + */ +static inline void FSpimSetRxDMALevel(uintptr base_addr, u32 level) +{ + FSPIM_WRITE_REG32(base_addr, FSPIM_DMA_RDLR_OFFSET, level); +} + + +/** + * @name: FSpimGetEnable + * @msg: 获取FSPIM控制器的使能状态 + * @return {*} + * @param {uintptr} base_addr + */ +static inline boolean FSpimGetEnable(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_SSIENR_OFFSET); +} + +/** + * @name: FSpimSetEnable + * @msg: 使能/去使能FSPIM控制器 + * @return {*} + * @param {uintptr} base_addr + * @param {boolean} enable + */ +static inline void FSpimSetEnable(uintptr base_addr, boolean enable) +{ + if (enable) + FSPIM_WRITE_REG32(base_addr, FSPIM_SSIENR_OFFSET, FSPIM_SSIENR_SSI_EN(1)); + else + FSPIM_WRITE_REG32(base_addr, FSPIM_SSIENR_OFFSET, FSPIM_SSIENR_SSI_EN(0)); +} + +/** + * @name: FSpimMaskIrq + * @msg: 屏蔽指定的中断位,去使能中断 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} mask + */ +static inline void FSpimMaskIrq(uintptr base_addr, u32 mask) +{ + u32 curr_mask; + curr_mask = FSPIM_READ_REG32(base_addr, FSPIM_IMR_OFFSET) & ~mask; /* = 0 中断不活动*/ + FSPIM_WRITE_REG32(base_addr, FSPIM_IMR_OFFSET, curr_mask); +} + +/** + * @name: FSpimUmaskIrq + * @msg: 取消屏蔽指定的中断位,使能中断 + * @return {*} + * @param {uintptr} base_addr + * @param {u32} mask + */ +static inline void FSpimUmaskIrq(uintptr base_addr, u32 mask) +{ + u32 curr_mask; + curr_mask = FSPIM_READ_REG32(base_addr, FSPIM_IMR_OFFSET) | mask; /* = 1 中断活动 */ + FSPIM_WRITE_REG32(base_addr, FSPIM_IMR_OFFSET, curr_mask); +} + + +/** + * @name: FSpimGetMask + * @msg: 获取当前的中断屏蔽位 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetMask(uintptr base_addr) +{ + return FSPIM_IMR_ALL_BITS & FSPIM_READ_REG32(base_addr, FSPIM_IMR_OFFSET); +} + +/** + * @name: FSpimGetTransMode + * @msg: 获取当前的传输模式 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetTransMode(uintptr base_addr) +{ + return ((FSpimGetCtrlR0(base_addr) & FSPIM_CTRL_R0_TMOD_MASK) >> FSPIM_CTRL_R0_TMOD_SHIFT); +} + +/** + * @name: FSpimGetStatus + * @msg: 获取当前的FSPIM控制器状态 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u32 FSpimGetStatus(uintptr base_addr) +{ + return FSPIM_READ_REG32(base_addr, FSPIM_SR_OFFSET); +} + +/** + * @name: FSpimWriteData + * @msg: 写SPI数据 + * @return {*} + * @param {uintptr} base_addr + * @param {u16} dat + */ +static inline void FSpimWriteData(uintptr base_addr, u16 dat) +{ + FSPIM_WRITE_REG32(base_addr, FSPIM_DR_OFFSET, FSPIM_DR(dat)); +} + +/** + * @name: FSpimReadData + * @msg: 读SPI数据 + * @return {*} + * @param {uintptr} base_addr + */ +static inline u16 FSpimReadData(uintptr base_addr) +{ + return (u16)(FSPIM_READ_REG32(base_addr, FSPIM_DR_OFFSET)); +} + +/************************** Function Prototypes ******************************/ +/* 使能/去使能和从设备的连接 */ +void FSpimSetSlaveEnable(uintptr base_addr, boolean enable); + +/* 获取TX Fifo可以设置的最大深度 */ +u32 FSpimGetTxFifoDepth(uintptr base_addr); + +/* 获取RX Fifo可以设置的最大深度 */ +u32 FSpimGetRxFifoDepth(uintptr base_addr); + +/* 选择SPI从设备 */ +void FSpimSelSlaveDev(uintptr base_addr, u32 slave_dev_id); + +/* 设置SPI传输速度 */ +FError FSpimSetSpeed(uintptr base_addr, u32 speed); + +/* 设置SPI传输模式 */ +void FSpimSetTransMode(uintptr base_addr, u32 trans_mode); + +/* 设置串行时钟相位 */ +void FSpimSetCpha(uintptr base_addr, u32 cpha_mode); + +/* 设置串行时钟极性 */ +void FSpimSetCpol(uintptr base_addr, u32 cpol_mode); + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_intr.c b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_intr.c new file mode 100644 index 0000000000..6d1e85df4d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_intr.c @@ -0,0 +1,133 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:08:10 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021-12-3 init commit + * 1.1 zhugengyu 2022-4-15 support test mode + */ + +/***************************** Include Files *********************************/ +#include +#include "fio.h" +#include "ferror_code.h" +#include "ftypes.h" +#include "fassert.h" +#include "fdebug.h" +#include "fspim_hw.h" +#include "fspim.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +/* be very careful to use print log in intrrupt handler */ +#define FSPIM_DEBUG_TAG "SPIM-INTR" +#define FSPIM_ERROR(format, ...) FT_DEBUG_PRINT_E(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_WARN(format, ...) FT_DEBUG_PRINT_W(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_INFO(format, ...) FT_DEBUG_PRINT_I(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FSPIM_CALL_INTR_EVT_HANDLDER(instance_p, evt) \ + if (instance_p->evt_handler[evt]) \ + instance_p->evt_handler[evt](instance_p, instance_p->evt_param[evt]) + +/************************** Function Prototypes ******************************/ +extern void FSpimFifoTx(FSpim *instance_p); +extern void FSpimFifoRx(FSpim *instance_p); +extern FError FSpimReset(FSpim *instance_p); + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +/** + * @name: FSpimInterruptHandler + * @msg: SPIM中断处理函数 + * @return {无} + * @param {s32} vector,中断向量号,此处不关心此参数 + * @param {void} *param, 中断输入参数, 指向FSPIM的驱动控制实例 + */ +void FSpimInterruptHandler(s32 vector, void *param) +{ + FASSERT(param); + FSpim *instance_p = (FSpim *)param; + uintptr base_addr = instance_p->config.base_addr; + u32 intr_status = FSPIM_RIS_R_ALL_BITS & FSPIM_READ_REG32(base_addr, FSPIM_RIS_R_OFFSET); + + if (0 == intr_status) + { + return; + } + + if ((FSPIM_RIS_R_TXOIR | FSPIM_RIS_R_RXOIR | FSPIM_RIS_R_RXUIR) & intr_status) /* 发送FIFO溢出 */ + { + FSPIM_WARN("Fifo overflow or underflow"); + if (FSPIM_RIS_R_TXOIR & intr_status) + { + FSPIM_CALL_INTR_EVT_HANDLDER(instance_p, FSPIM_INTR_EVT_TX_OVERFLOW); + } + + if (FSPIM_RIS_R_RXUIR & intr_status) + { + FSPIM_CALL_INTR_EVT_HANDLDER(instance_p, FSPIM_INTR_EVT_RX_UNDERFLOW); + } + + if (FSPIM_RIS_R_RXOIR & intr_status) + { + FSPIM_CALL_INTR_EVT_HANDLDER(instance_p, FSPIM_INTR_EVT_RX_OVERFLOW); + } + + FSpimReset(instance_p); + return; + } + + FSpimFifoRx(instance_p); /* 检查 RX Fifo是否为空,如果不为空则接收数据 */ + + if (instance_p->rx_buff_end == instance_p->rx_buff) /* RX 缓冲区已满,停止填入发送数据 */ + { + FSpimMaskIrq(base_addr, FSPIM_IMR_TXEIS); + FSPIM_CALL_INTR_EVT_HANDLDER(instance_p, FSPIM_INTR_EVT_RX_DONE); + return; + } + + if (FSPIM_RIS_R_TXEIR & intr_status) /* TX Fifo为空,填入待发送数据 */ + { + FSpimMaskIrq(base_addr, FSPIM_IMR_TXEIS); + FSpimFifoTx(instance_p); + FSpimUmaskIrq(base_addr, FSPIM_IMR_TXEIS); + } + + return; +} + +/** + * @name: FSpimRegisterIntrruptHandler + * @msg: 注册FSPIM中断事件处理函数 + * @return {*} + * @param {FI2c} *instance_p + * @param {u32} evt + * @param {FI2cEvtHandler} handler + */ +void FSpimRegisterIntrruptHandler(FSpim *instance_p, FSpimIntrEvtType evt, FSpimEvtHandler handler, void *param) +{ + FASSERT(instance_p && evt < FSPIM_INTR_EVT_NUM); + instance_p->evt_handler[evt] = handler; + instance_p->evt_param[evt] = param; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_selftest.c b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_selftest.c new file mode 100644 index 0000000000..1040178d77 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_selftest.c @@ -0,0 +1,73 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim_selftest.c + * Date: 2022-07-21 13:21:43 + * LastEditTime: 2022-07-21 13:21:44 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ +/***************************** Include Files *********************************/ +#include "fio.h" +#include "fdebug.h" +#include "fassert.h" +#include "ftypes.h" + +#include "fspim_hw.h" +#include "fspim.h" +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FSPIM_DEBUG_TAG "SPIM-TEST" +#define FSPIM_ERROR(format, ...) FT_DEBUG_PRINT_E(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_WARN(format, ...) FT_DEBUG_PRINT_W(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_INFO(format, ...) FT_DEBUG_PRINT_I(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) +#define FSPIM_DEBUG(format, ...) FT_DEBUG_PRINT_D(FSPIM_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FSPIM_DUMPER(base_addr, reg_off, reg_name) \ + FSPIM_DEBUG("\t\t[%s]@0x%x\t=\t0x%x", reg_name, (reg_off), FSPIM_READ_REG32((base_addr), (reg_off))) +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + +void FSpimDumpRegister(uintptr base_addr) +{ + FSPIM_DEBUG("Dump register info @0x%x", base_addr); + FSPIM_DUMPER(base_addr, FSPIM_CTRL_R0_OFFSET, "ctrl_r0"); + FSPIM_DUMPER(base_addr, FSPIM_CTRL_R1_OFFSET, "ctrl_r1"); + FSPIM_DUMPER(base_addr, FSPIM_SSIENR_OFFSET, "ssienr"); + FSPIM_DUMPER(base_addr, FSPIM_MWCR_OFFSET, "mwcr"); + FSPIM_DUMPER(base_addr, FSPIM_SER_OFFSET, "ser"); + FSPIM_DUMPER(base_addr, FSPIM_BAUD_R_OFFSET, "baud"); + FSPIM_DUMPER(base_addr, FSPIM_TXFTL_R_OFFSET, "txftl"); + FSPIM_DUMPER(base_addr, FSPIM_RXFTL_R_OFFSET, "rxftl"); + FSPIM_DUMPER(base_addr, FSPIM_TXFLR_OFFSET, "txflr"); + FSPIM_DUMPER(base_addr, FSPIM_RXFLR_OFFSET, "rxflr"); + FSPIM_DUMPER(base_addr, FSPIM_SR_OFFSET, "sr"); + FSPIM_DUMPER(base_addr, FSPIM_IMR_OFFSET, "imr"); + FSPIM_DUMPER(base_addr, FSPIM_ISR_OFFSET, "isr"); + FSPIM_DUMPER(base_addr, FSPIM_RIS_R_OFFSET, "ris_r"); + FSPIM_DUMPER(base_addr, FSPIM_DMA_CR_OFFSET, "cr"); + FSPIM_DUMPER(base_addr, FSPIM_DMA_TDLR_OFFSET, "tdlr"); + FSPIM_DUMPER(base_addr, FSPIM_DMA_RDLR_OFFSET, "rdlr"); + FSPIM_DUMPER(base_addr, FSPIM_IDR_OFFSET, "idr"); + FSPIM_DUMPER(base_addr, FSPIM_RX_SAMPLE_DLY_OFFSET, "rx_sample"); + FSPIM_DUMPER(base_addr, FSPIM_CS_OFFSET, "cs"); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_sinit.c b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_sinit.c new file mode 100644 index 0000000000..13b2d17666 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/spi/fspim/fspim_sinit.c @@ -0,0 +1,64 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fspim_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:08:24 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 zhugengyu 2021-12-3 init commit + * 1.1 zhugengyu 2022-4-15 support test mode + */ + +/***************************** Include Files *********************************/ + +#include "ftypes.h" +#include "fparameters.h" +#include "fspim.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +extern const FSpimConfig FSPIM_CONFIG_TBL[FSPI_DEVICE_NUM]; + +/************************** Function Prototypes ******************************/ +/** + * @name: FSpimLookupConfig + * @msg: 获取FSPIM实例的默认配置 + * @return {const FSpimConfig *} FSPIM实例的默认配置 + * @param {u32} instance_id, SPI控制器ID + */ +const FSpimConfig *FSpimLookupConfig(u32 instance_id) +{ + const FSpimConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FSPI_DEVICE_NUM; index++) + { + if (FSPIM_CONFIG_TBL[index].instance_id == instance_id) + { + ptr = &FSPIM_CONFIG_TBL[index]; + break; + } + } + + return (const FSpimConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/timer/Kconfig b/bsp/phytium/libraries/standalone/drivers/timer/Kconfig new file mode 100644 index 0000000000..2ba3ac26d8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/timer/Kconfig @@ -0,0 +1,9 @@ +menu "Hardware Timer Configuration" + config ENABLE_TIMER_TACHO + bool + prompt "Use Timer Tacho" + depends on TARGET_E2000S || TARGET_E2000D || TARGET_E2000Q + + default n +endmenu + diff --git a/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftacho.c b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftacho.c new file mode 100644 index 0000000000..87087e6caa --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftacho.c @@ -0,0 +1,298 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ftacho.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-05-20 09:08:52 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include +#include "fassert.h" +#include "fkernel.h" +#include "fsleep.h" +#include "ftimer_tacho_hw.h" +#include "ftimer_tacho.h" +#include "fparameters.h" + +/************************** Function Prototypes ******************************/ +/** + * @name: FTachoInit + * @msg: 初始化Tacho,并且使能计数器和tachometer + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {FTimerTachoConfig} *config_p 驱动配置数据结构 + */ +FError FTachoInit(FTimerTachoCtrl *instance_p, const FTimerTachoConfig *config_p) +{ + FASSERT(instance_p && config_p); + + u32 reg_val = 0; + + if (instance_p->isready == FT_COMPONENT_IS_READY) + { + FTIMER_INFO("device is already initialized.!!!\r\n"); + return FTIMER_TACHO_ERR_IS_READ; + } + + /* set work mode */ + if (FTIMER_WORK_MODE_TACHO == config_p->work_mode) + { + reg_val |= FTIMER_REG_TACHO_MODE_TACHO; + reg_val |= FTACHO_REG_CAP_IN_ENABLE; + /* plus num of rpm calculate period */ + FTIMER_CMPL_WRITE(instance_p, config_p->plus_num); + } + else if (FTIMER_WORK_MODE_CAPTURE == config_p->work_mode) + { + reg_val |= FTIMER_REG_TACHO_MODE_CAPTURE; + reg_val |= FTIMER_REG_TACHO_CAPTURE_ENABLE; + /* set capture cnt to assert capture intr */ + reg_val |= FTIMER_REG_TACHO_CAPTURE_CNT_MASK & (config_p->captue_cnt << FTIMER_REG_TACHO_CAPTURE_CNT_SHIFT); + reg_val |= FTIMER_REG_ENABLE; + } + else + { + FTACHO_ERROR("not support work_mode."); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + /* set timer bits */ + if (FTIMER_32_BITS == config_p->timer_bits) + { + reg_val &= (~FTIMER_REG_CNT_SERIES_64BIT); + } + else if (FTIMER_64_BITS == config_p->timer_bits) + { + reg_val |= FTIMER_REG_CNT_SERIES_64BIT; + } + else + { + FTACHO_ERROR("invalid input 32/64bits."); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + /* set edge mode */ + if (FTACHO_FALLING_EDGE == config_p->edge_mode) + { + reg_val &= ~FTACHO_REG_MODE_MASK; + reg_val |= FTACHO_REG_MODE_FALLING_EDGE; + } + else if (FTACHO_RISING_EDGE == config_p->edge_mode) + { + reg_val &= ~FTACHO_REG_MODE_MASK; + reg_val |= FTACHO_REG_MODE_RISING_EDGE; + } + else if (FTACHO_DOUBLE_EDGE == config_p->edge_mode) + { + reg_val &= ~FTACHO_REG_MODE_MASK; + reg_val |= FTACHO_REG_MODE_DOUBLE_EDGE; + } + else + { + FTACHO_ERROR("invalid input edge."); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + /* set jitter level */ + reg_val |= FTACHO_REG_ANTI_JITTER_MASK & + (config_p->jitter_level << FTACHO_REG_ANTI_JITTER_SHIFT); + + //use input config + if (config_p != &instance_p->config) + { + instance_p->config = *config_p; + } + + FTIMER_CTRL_WRITE(instance_p, reg_val); + instance_p->isready = FT_COMPONENT_IS_READY; + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: FTachoGetFanRPM + * @msg: 获取风扇的转速值 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {u32} *rpm 将获取到的数值写入到此地址 + */ +FError FTachoGetFanRPM(FTimerTachoCtrl *instance_p, u32 *rpm) +{ + u32 loop_cnt; + u32 raw_dat; + + FASSERT(instance_p); + + if (instance_p->isready != FT_COMPONENT_IS_READY || instance_p->config.work_mode != FTIMER_WORK_MODE_TACHO) + { + FTIMER_ERROR("device is not already or not work on TACHO_MODE!!!"); + return FTIMER_TACHO_ERR_NOT_READY; + } + + u32 cnt_num = FTIMER_CMPL_READ(instance_p); + + for (loop_cnt = 0;; loop_cnt++) + { + raw_dat = FTACHO_RESU_READ(instance_p); + /* wait for tacho result */ + if (raw_dat & FTACHO_REG_RESU_ISVALID) + { + break; + } + + if (loop_cnt < 300) + { + fsleep_millisec(20); //20ms + } + else + { + return FTIMER_TACHO_ERR_ABORT; + } + } + + raw_dat &= FTACHO_REG_RESU_MASK; + if (0 == raw_dat) + { + *rpm = 0; + } + else + { + /* calculate rpm */ + /* (60(second) * freq * tacho) / (2 * (cmp_l + 1)) cmp_l */ + *rpm = (TIMER_CLK_FREQ_HZ * 60 * raw_dat) / (2 * (cnt_num + 1)); + } + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: FTachoGetCaptureCnt + * @msg: 获取capture模式下,tacho输入脉冲的个数 + * @return {u32}返回获取到的数值 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +u32 FTachoGetCaptureCnt(FTimerTachoCtrl *instance_p) +{ + u32 cap_cnt = FTIMER_TACHO_SUCCESS; + + FASSERT(instance_p); + + if (instance_p->isready != FT_COMPONENT_IS_READY || instance_p->config.work_mode != FTIMER_WORK_MODE_CAPTURE) + { + FTIMER_ERROR("device is not already or not work on CAPTURE_MODE!!!"); + return FTIMER_TACHO_ERR_NOT_READY; + } + + /* read cap cnt */ + cap_cnt = FTIMER_CNTL_READ(instance_p); + + return cap_cnt; +} + +/** + * @name: FTimerSwithMode + * @msg: 切换定时器模式和tachometer-capture模式 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {FTimerTachoConfig} *pNewConfig 新的驱动配置数据结构 + */ +FError FTimerSwithMode(FTimerTachoCtrl *instance_p, FTimerTachoConfig *pNewConfig) +{ + FASSERT(instance_p && pNewConfig); + + u32 ret = FTIMER_TACHO_SUCCESS; + + if (instance_p->config.work_mode == pNewConfig->work_mode) + { + return FTIMER_TACHO_SUCCESS; + } + + /* disable and clear timer */ + u32 reg_val = FTIMER_CTRL_READ(instance_p); + reg_val &= (~FTIMER_REG_ENABLE); + reg_val |= FTIMER_REG_CNT_CLR; + FTIMER_CTRL_WRITE(instance_p, reg_val); + + if (FTIMER_WORK_MODE_TIMER == pNewConfig->work_mode) + { + ret = FTimerInit(instance_p, pNewConfig); + } + else + { + ret = FTachoInit(instance_p, pNewConfig); + } + + return ret; +} + +/** + * @name: FTachoSetCntPeriod + * @msg: 配置 tach计数周期 = pulse_num + * @return {void} + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {u32}计数ticks + */ +void FTachoSetCntPeriod(FTimerTachoCtrl *instance_p, u32 ticks) +{ + FTIMER_CMPL_WRITE(instance_p, ticks); +} + +/** + * @name: FTachoSetOverLimit + * @msg: 预设tacho的最大值 + * @return {void} + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {u32}上限值 + */ +void FTachoSetOverLimit(FTimerTachoCtrl *instance_p, u32 overLim) +{ + FTACHO_OVER_WRITE(instance_p, overLim); +} + +/** + * @name: FTachoSetUnderLimit + * @msg: 预设tacho的最小值 + * @return {void} + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {u32}下限值 + */ +void FTachoSetUnderLimit(FTimerTachoCtrl *instance_p, u32 underLim) +{ + FTACHO_UNDER_WRITE(instance_p, underLim); +} + +/** + * @name: FTachoDeInit + * @msg: 去初始化,寄存器复位,结构体参数置0 + * @return {void} + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +void FTachoDeInit(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + + /* reset reg*/ + FTimerSoftwareReset(instance_p); + + instance_p->isready = 0; + memset(instance_p, 0, sizeof(*instance_p)); + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer.c b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer.c new file mode 100644 index 0000000000..3b10410b4c --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer.c @@ -0,0 +1,459 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ftimer.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:09:49 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ +#include +#include "fassert.h" +#include "ftimer_tacho_hw.h" +#include "ftimer_tacho.h" + + +/************************** Function Prototypes ******************************/ +/** + * @name: FTimerSoftwareReset + * @msg: 将控制器复位 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +FError FTimerSoftwareReset(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + + if (instance_p->isready != FT_COMPONENT_IS_READY) + { + FTIMER_ERROR("device is not already!!!"); + return FTIMER_TACHO_ERR_NOT_READY; + } + + u32 reg_val = FTIMER_CTRL_READ(instance_p); + u32 Timeout = 0; + reg_val |= FTIMER_REG_TACHO_RESET; + FTIMER_CTRL_WRITE(instance_p, reg_val); + + do + { + reg_val = FTIMER_CTRL_READ(instance_p); + Timeout++; + } + while ((reg_val & FTIMER_REG_TACHO_RESET) && (Timeout < FTIMER_TIMEOUT)); + + if (Timeout >= FTIMER_TIMEOUT) + { + FTIMER_ERROR("Software Reset Failed!!!"); + return FTIMER_TACHO_ERR_FAILED; + } + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: FTimerStart + * @msg: 启动timer_tacho外设,根据不同的功能,开启使能位 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +FError FTimerStart(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + u32 reg_val; + reg_val = FTIMER_CTRL_READ(instance_p); + if (FTIMER_WORK_MODE_TIMER == instance_p->config.work_mode) + { + reg_val |= FTIMER_REG_ENABLE; + } + else + { + /* for tacho mode and capture mode */ + reg_val |= FTIMER_REG_ENABLE | FTACHO_REG_CAP_IN_ENABLE; + } + + FTIMER_CTRL_WRITE(instance_p, reg_val); + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: FTimerStop + * @msg: 停止timer外设,根据不同的功能,关闭使能位,计数值停止并冻结 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +FError FTimerStop(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + u32 reg_val = FTIMER_CTRL_READ(instance_p); + + if (FTIMER_WORK_MODE_TIMER == instance_p->config.work_mode) + { + reg_val &= (~FTIMER_REG_ENABLE); + } + else + { + /* for tacho mode and capture mode */ + reg_val &= (~FTIMER_REG_ENABLE) & (~FTACHO_REG_CAP_IN_ENABLE); + } + + FTIMER_CTRL_WRITE(instance_p, reg_val); + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: TimerSwithBits + * @msg: 计数器32/64切换 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +static FError TimerSwithBits(FTimerTachoCtrl *instance_p) +{ + u32 reg_val; + + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + reg_val = FTIMER_CTRL_READ(instance_p); + + if (FTIMER_32_BITS == instance_p->config.timer_bits) + { + reg_val &= (~FTIMER_REG_CNT_SERIES_64BIT); + } + else if (FTIMER_64_BITS == instance_p->config.timer_bits) + { + reg_val |= FTIMER_REG_CNT_SERIES_64BIT; + } + else + { + FTIMER_ERROR("invalid input"); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + FTIMER_CTRL_WRITE(instance_p, reg_val); + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: TimerForceLoad + * @msg: 强制更新位置位 + * @return {void} 无 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +static void TimerForceLoad(FTimerTachoCtrl *instance_p) +{ + u32 reg_val; + + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + reg_val = FTIMER_CTRL_READ(instance_p); + reg_val |= FTIMER_REG_TACHO_FORCE_LOAD; + FTIMER_CTRL_WRITE(instance_p, reg_val); + + return; +} + +/** + * @name: FTimerSetPeriod32 + * @msg: 设置32位计数模式下,计数器的compare的值,达到此值,如果开启中断,则开启中断 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {u32}NewCmpL + */ +FError FTimerSetPeriod32(FTimerTachoCtrl *instance_p, u32 new_cmp_l) +{ + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + if (FTIMER_64_BITS == instance_p->config.timer_bits) + { + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + /* update cmp val */ + FTIMER_CMPL_WRITE(instance_p, new_cmp_l); + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: FTimerSetPeriod64 + * @msg: 设置64位计数模式下,计数器的compare的值,达到此值,如果开启中断,则开启中断 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {u64}ticks + */ +FError FTimerSetPeriod64(FTimerTachoCtrl *instance_p, u64 ticks) +{ + u32 low_cmp; + u32 up_cmp; + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + if (FTIMER_32_BITS == instance_p->config.timer_bits) + { + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + low_cmp = (u32)(GENMASK_ULL(31, 0) & ticks); + up_cmp = (u32)((GENMASK_ULL(63, 32) & ticks) >> 32); + + /* MUST write low 32 bit first !!! */ + FTIMER_CMPL_WRITE(instance_p, low_cmp); + FTIMER_CMPU_WRITE(instance_p, up_cmp); + + return FTIMER_TACHO_SUCCESS; +} + +/** + * @name: FTimerSetStartVal + * @msg: 设置计数器初始值 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {u32} cnt + */ +inline FError FTimerSetStartVal(FTimerTachoCtrl *instance_p, u32 cnt) +{ + u32 ret = FTIMER_TACHO_SUCCESS; + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + ret = TimerSwithBits(instance_p); + if (FTIMER_TACHO_SUCCESS != ret) + { + return ret; + } + + FTIMER_STAR_WRITE(instance_p, cnt); + /* set force_load=1,invalid previous cmp val, + otherwise the previous cmp val still work */ + TimerForceLoad(instance_p); + + FTIMER_INFO("set start val 0x%x", FTIMER_STAR_READ(instance_p)); + + return ret; +} + + +/** + * @name: FTimerGetCurCnt32 + * @msg: 32位模式下,获取计数器当前计数值 + * @return {u32}返回当前计数器的值 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +u32 FTimerGetCurCnt32(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + return FTIMER_CNTL_READ(instance_p); +} + +/** + * @name: FTimerGetCurCnt64 + * @msg: 64位模式下,获取计数器当前计数值 + * @return {u64}返回当前计数器的值 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +inline u64 FTimerGetCurCnt64(FTimerTachoCtrl *instance_p) +{ + u64 cnt = 0; + FASSERT(instance_p); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + /* must read lower 32 bits first */ + cnt |= (u64)FTIMER_CNTL_READ(instance_p); + cnt |= (u64)(((u64)FTIMER_CNTU_READ(instance_p)) << 32); + return cnt; +} + +/** + * @name: FTimerInit + * @msg: 完成TimerTacho驱动实例的初始化,使之在就绪状态 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {FTimerTachoConfig} *config_p 驱动配置数据结构 + */ +FError FTimerInit(FTimerTachoCtrl *instance_p, const FTimerTachoConfig *config_p) +{ + FASSERT(instance_p && config_p); + + u32 reg_val = 0; + u32 Ret = FTIMER_TACHO_SUCCESS; + + if ((FTIMER_ONCE_CMP == config_p->cmp_type) && + (FTIMER_FREE_RUN != config_p->timer_mode)) + { + FTIMER_ERROR("time mode shall be free-run when use once timer!!"); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + if (instance_p->isready == FT_COMPONENT_IS_READY) + { + FTIMER_INFO("device is already initialized.!!!\r\n"); + return FTIMER_TACHO_ERR_IS_READ; + } + + if (FTIMER_WORK_MODE_TIMER == config_p->work_mode) + { + reg_val |= FTIMER_REG_TACHO_MODE_TIMER; + } + else + { + FTIMER_ERROR("not support"); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + if (FTIMER_FREE_RUN == config_p->timer_mode) + { + reg_val &= (~FTIMER_REG_CNT_RESTART); + } + else if (FTIMER_RESTART == config_p->timer_mode) + { + reg_val |= FTIMER_REG_CNT_RESTART; + } + else + { + FTIMER_ERROR("invalid input"); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + if (FTIMER_32_BITS == config_p->timer_bits) + { + reg_val &= (~FTIMER_REG_CNT_SERIES_64BIT); + } + else if (FTIMER_64_BITS == config_p->timer_bits) + { + reg_val |= FTIMER_REG_CNT_SERIES_64BIT; + } + else + { + FTIMER_ERROR("invalid input"); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + if (FTIMER_ONCE_CMP == config_p->cmp_type) + { + reg_val |= FTIMER_REG_MODE_ONCE; + } + else if (FTIMER_CYC_CMP == config_p->cmp_type) + { + reg_val &= (~FTIMER_REG_MODE_ONCE); + } + else + { + FTIMER_ERROR("invalid input"); + return FTIMER_TACHO_ERR_INVAL_PARM; + } + + if (TRUE == config_p->force_load) + { + reg_val |= FTIMER_REG_TACHO_FORCE_LOAD; + } + + if (TRUE == config_p->clear_cnt) + { + reg_val |= FTIMER_REG_CNT_CLR; + } + + /*use input config*/ + if (config_p != &instance_p->config) + { + instance_p->config = *config_p; + } + + FTIMER_CTRL_WRITE(instance_p, reg_val); + instance_p->isready = FT_COMPONENT_IS_READY; + + return FTIMER_TACHO_SUCCESS; +} + +void FTimerDeInit(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + + /* stop timer first */ + FTimerStop(instance_p); + /* reset reg*/ + FTimerSoftwareReset(instance_p); + + instance_p->isready = 0; + memset(instance_p, 0, sizeof(*instance_p)); + + return; +} + +/** + * @name: FTimeSettingDump + * @msg: 打印寄存器信息 + * @return {FError} 驱动初始化的错误码信息,FTIMER_TACHO_SUCCESS 表示初始化成功,其它返回值表示初始化失败 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +FError FTimeSettingDump(const FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + u32 CtrlReg = FTIMER_CTRL_READ(instance_p); + boolean is64Bit = ((CtrlReg & FTIMER_REG_CNT_SERIES_64BIT) != 0); + + FASSERT(FT_COMPONENT_IS_READY == instance_p->isready); + + printf("ctrl: \r\n"); + printf("===%d-bit timer\r\n", is64Bit ? 64 : 32); + printf("===timer enabled: %d\r\n", (CtrlReg & FTIMER_REG_ENABLE) ? 1 : 0); + printf("===timer mode: %d\r\n", (CtrlReg & FTIMER_REG_TACHO_MODE_TIMER) ? 1 : 0); + printf("===once timer: %d\r\n", (CtrlReg & FTIMER_REG_MODE_ONCE) ? 1 : 0); + printf("===restart mode: %d\r\n", (CtrlReg & FTIMER_REG_CNT_RESTART) ? 1 : 0); + printf("===in reset: %d\r\n", (CtrlReg & FTIMER_REG_TACHO_RESET) ? 1 : 0); + printf("===force load: %d\r\n", (CtrlReg & FTIMER_REG_TACHO_FORCE_LOAD) ? 1 : 0); + printf("===clear cnt: %d\r\n", (CtrlReg & FTIMER_REG_CNT_CLR) ? 1 : 0); + + printf("start cnt: 0x%08x\r\n", FTIMER_STAR_READ(instance_p)); + if (is64Bit) + { + printf("cmp low: 0x%08x", FTIMER_CMPL_READ(instance_p)); + printf("high: 0x%08x\r\n", FTIMER_CMPU_READ(instance_p)); + printf("cur cnt: low: 0x%08x", FTIMER_CNTL_READ(instance_p)); + printf("high: 0x%08x\r\n", FTIMER_CNTU_READ(instance_p)); + } + else + { + printf("cmp low: 0x%08x\r\n", FTIMER_CMPL_READ(instance_p)); + printf("cur cnt: low: 0x%08x", FTIMER_CNTL_READ(instance_p)); + } + + printf("intr mask: 0x%08x\r\n", FTIMER_INTR_M_READ(instance_p)); + printf("intr status: 0x%08x\r\n", FTIMER_INTR_S_READ(instance_p)); + + return FTIMER_TACHO_SUCCESS; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho.h b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho.h new file mode 100644 index 0000000000..8f8b4a9edf --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho.h @@ -0,0 +1,227 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ftimer_tacho.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:09:43 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_E2000_TIMER_TACHO_H +#define BSP_DRIVERS_E2000_TIMER_TACHO_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fdebug.h" +#include "ferror_code.h" + +#define FTIMER_TACHO_SUCCESS FT_SUCCESS +#define FTIMER_TACHO_ERR_INVAL_PARM FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 1) +#define FTIMER_TACHO_ERR_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 2) +#define FTIMER_TACHO_ERR_INIT_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 3) +#define FTIMER_TACHO_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 4) +#define FTIMER_TACHO_ERR_INVAL_STATE FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 5) +#define FTIMER_TACHO_ERR_IS_READ FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 6) +#define FTIMER_TACHO_ERR_ABORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 7) +#define FTIMER_TACHO_ERR_FAILED FT_MAKE_ERRCODE(ErrModBsp, ErrBspTimer, 8) + +#define FTIMER_DEBUG_TAG "TIMER" +#define FTIMER_ERROR(format, ...) FT_DEBUG_PRINT_E(FTIMER_DEBUG_TAG, format, ##__VA_ARGS__) +#define FTIMER_INFO(format, ...) FT_DEBUG_PRINT_I(FTIMER_DEBUG_TAG, format, ##__VA_ARGS__) +#define FTIMER_DEBUG(format, ...) FT_DEBUG_PRINT_D(FTIMER_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FTACHO_DEBUG_TAG "TACHO" +#define FTACHO_ERROR(format, ...) FT_DEBUG_PRINT_E(FTACHO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FTACHO_INFO(format, ...) FT_DEBUG_PRINT_I(FTACHO_DEBUG_TAG, format, ##__VA_ARGS__) +#define FTACHO_DEBUG(format, ...) FT_DEBUG_PRINT_D(FTACHO_DEBUG_TAG, format, ##__VA_ARGS__) + +typedef enum +{ + /*TimerTacho mode */ + FTIMER_WORK_MODE_TIMER = 0, + FTIMER_WORK_MODE_TACHO, + FTIMER_WORK_MODE_CAPTURE +} FTimerTachoModeType; + +typedef enum +{ + /*Timer count mode*/ + FTIMER_FREE_RUN = 0, + FTIMER_RESTART +} FTimerCntModeType; + +typedef enum +{ + FTIMER_32_BITS = 0, + FTIMER_64_BITS +} FTimerBitsType; + +typedef enum +{ + FTIMER_ONCE_CMP = 0, + FTIMER_CYC_CMP +} FTimerCmpType; + +typedef enum +{ + FTACHO_EVENT_OVER = 0, /*tacho超速事件*/ + FTACHO_EVENT_UNDER, /*tacho低速事件*/ + FTIMER_EVENT_ROLL_OVER, /*计数器翻转事件*/ + FTIMER_EVENT_ONCE_CMP, /*单次定时输出事件*/ + FTIMER_EVENT_CYC_CMP, /*重复定时输出事件*/ + FTACHO_EVENT_CAPTURE, /*tacho输入捕获事件*/ + + FMAX_TIMER_TACHO_EVENT +} FTimerTachoEventType; + +typedef enum +{ + FTACHO_FALLING_EDGE = 0, /*下降沿触发模式*/ + FTACHO_RISING_EDGE, /*上升沿触发模式*/ + FTACHO_DOUBLE_EDGE /*双边沿触发模式*/ +} FTachoEdgeType; + +typedef enum +{ + FTACHO_JITTER_LEVEL0 = 0, /*消抖等级*/ + FTACHO_JITTER_LEVEL1, + FTACHO_JITTER_LEVEL2, + FTACHO_JITTER_LEVEL3, +} FTachoJitterLevelType; + +typedef struct +{ + u32 id; /* id of timer tacho */ + char name[12]; /* instance name */ + u32 irq_priority; /* intr priority */ + u32 work_mode; /* timer/tacho/capture mode */ + /* for timer function */ + u32 timer_mode; /* free-run/restart */ + u32 timer_bits; /* 32/64 bits */ + u32 cmp_type; /* once/cycle cmp */ + boolean clear_cnt; /* clear timer counts */ + boolean force_load; /* start count from start val */ + /* for tacho function */ + u32 edge_mode; /* rising/falling/double */ + u32 jitter_level; /* jitter level */ + u32 plus_num; /* plus_num of period to calculate rpm */ + u32 captue_cnt; /* in capture mode, when cnt reach this val, intr asserted */ +} FTimerTachoConfig; + +typedef void (*FTimerEventHandler)(void *instance_p); + +typedef struct +{ + FTimerTachoConfig config; /* Current active configs */ + boolean isready; /* Device is initialized and ready */ + FTimerEventHandler evt_handlers[FMAX_TIMER_TACHO_EVENT];/* event handler for interrupt */ +} FTimerTachoCtrl; + +/* Time & Tacho API */ +/*将控制器复位*/ +FError FTimerSoftwareReset(FTimerTachoCtrl *instance_p); + +/*获取中断设置*/ +u32 FTimerGetInterruptMask(FTimerTachoCtrl *instance_p); + +/*设置中断,根据不同的intrType,将对于的中断mask置位*/ +void FTimerSetInterruptMask(FTimerTachoCtrl *instance_p, + FTimerTachoEventType intrType, + boolean enable); + +/*启动timer_tacho外设,根据不同的功能,开启使能位*/ +FError FTimerStart(FTimerTachoCtrl *instance_p); + +/*停止timer外设,根据不同的功能,关闭使能位,计数值停止并冻结*/ +FError FTimerStop(FTimerTachoCtrl *instance_p); + +/*用于timer 与 tacho-capture两种模式的切换,切换需要失能和清除计数器*/ +FError FTimerSwithMode(FTimerTachoCtrl *instance_p, FTimerTachoConfig *new_config_p); + +/* 注册中断事件处理回调函数 */ +void FTimerRegisterEvtCallback(FTimerTachoCtrl *instance_p, + FTimerTachoEventType evt, + FTimerEventHandler callback); + +/*打印寄存器信息*/ +FError FTimeSettingDump(const FTimerTachoCtrl *instance_p); + +/*TimerTacho中断处理函数,如果注册回调函数,则跳转到回调函数*/ +void FTimerTachoIntrHandler(s32 vector, void *param); + +/*根据工作模式和状态设置相应的中断*/ +void FTimerTachoSetIntr(FTimerTachoCtrl *instance_p); + +/* Timer API */ +/*完成TimerTacho驱动实例的初始化,使之在就绪状态*/ +FError FTimerInit(FTimerTachoCtrl *instance_p, const FTimerTachoConfig *config_p); + +/*获取Timer驱动的默认配置参数*/ +void FTimerGetDefConfig(u32 timer_id, FTimerTachoConfig *config_p); + +/*设置32位计数模式下,计数器的compare的值,达到此值,如果开启中断,则开启中断*/ +FError FTimerSetPeriod32(FTimerTachoCtrl *instance_p, u32 ticks); + +/*设置64位计数模式下,计数器的compare的值,达到此值,如果开启中断,则开启中断*/ +FError FTimerSetPeriod64(FTimerTachoCtrl *instance_p, u64 ticks); + +/*32位模式下,获取计数器当前计数值*/ +u32 FTimerGetCurCnt32(FTimerTachoCtrl *instance_p); + +/*64位模式下,获取计数器当前计数值*/ +u64 FTimerGetCurCnt64(FTimerTachoCtrl *instance_p); + +/*设置计数器初始值*/ +FError FTimerSetStartVal(FTimerTachoCtrl *instance_p, u32 cnt); + +/*完成Timer驱动实例去使能,清零实例数据*/ +void FTimerDeInit(FTimerTachoCtrl *instance_p); + +/* Tacho API */ +/*完成Tacho驱动实例的初始化,使之在就绪状态*/ +FError FTachoInit(FTimerTachoCtrl *instance_p, const FTimerTachoConfig *config_p); + +/*获取Tacho驱动的默认配置参数*/ +void FTachoGetDefConfig(u32 tacho_id, FTimerTachoConfig *config_p); + +/*配置tach转速周期= pulse_num*/ +void FTachoSetCntPeriod(FTimerTachoCtrl *instance_p, u32 ticks); + +/*预设的 tach 最大值*/ +void FTachoSetOverLimit(FTimerTachoCtrl *instance_p, u32 overLim); + +/*预设的 tach 最小值*/ +void FTachoSetUnderLimit(FTimerTachoCtrl *instance_p, u32 underLim); + +/*根据预设采样周期的值,来获取风扇的转速值*/ +FError FTachoGetFanRPM(FTimerTachoCtrl *instance_p, u32 *rpm); + +/*获取capture模式下tacho输入脉冲的个数*/ +u32 FTachoGetCaptureCnt(FTimerTachoCtrl *instance_p); + +/*完成Tacho驱动实例去使能,清零实例数据*/ +void FTachoDeInit(FTimerTachoCtrl *instance_p); + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_g.c b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_g.c new file mode 100644 index 0000000000..8c4868c3af --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_g.c @@ -0,0 +1,62 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ftimer_tacho_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:09:07 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include +#include "fparameters.h" +#include "fassert.h" +#include "ftimer_tacho_hw.h" +#include "ftimer_tacho.h" + +#define TACHO_PERIOD 1000000 /* 1000000/50000000 = 0.02s*/ +/************************** Function Prototypes ******************************/ +void FTimerGetDefConfig(u32 timer_id, FTimerTachoConfig *config_p) +{ + FASSERT((timer_id < TIMER_NUM) && (NULL != config_p)); + + memset(config_p, 0, sizeof(FTimerTachoConfig)); + config_p->id = timer_id; + config_p->work_mode = FTIMER_WORK_MODE_TIMER; + config_p->timer_mode = FTIMER_RESTART; + config_p->timer_bits = FTIMER_32_BITS; + config_p->cmp_type = FTIMER_CYC_CMP; + config_p->clear_cnt = FALSE; + config_p->force_load = TRUE; +} + +void FTachoGetDefConfig(u32 tacho_id, FTimerTachoConfig *config_p) +{ + FASSERT((tacho_id < TACHO_NUM) && (NULL != config_p)); + + memset(config_p, 0, sizeof(FTimerTachoConfig)); + config_p->id = tacho_id; + config_p->timer_bits = FTIMER_32_BITS; + config_p->work_mode = FTIMER_WORK_MODE_TACHO; + config_p->timer_mode = FTIMER_RESTART; + config_p->edge_mode = FTACHO_RISING_EDGE; + config_p->jitter_level = 0; + config_p->plus_num = TACHO_PERIOD;/*采样周期越长,能够检测到的单位时间脉冲越多,能够检测更小的频率*/ + config_p->clear_cnt = FALSE; + config_p->force_load = TRUE; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_hw.h b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_hw.h new file mode 100644 index 0000000000..e9bc4d6bd1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_hw.h @@ -0,0 +1,163 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ftimer_tacho_hw.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:09:15 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#ifndef BSP_DRIVERS_E2000_TIMER_HW_H +#define BSP_DRIVERS_E2000_TIMER_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fio.h" +#include "ftypes.h" +#include "fkernel.h" +#include "fparameters.h" + +/* register offset */ +#define FTIMER_CTRL_REG_OFFSET (0x0) /*Timer or Tachometer 控制寄存器*/ +#define FTACHO_RESULT_REG_OFFSET (0x4) /*一个转速周期内的时钟周期计数结果*/ +#define FTIMER_COMP_VALU_OFFSET (0x8) /*定时计数值高 32 位*/ +#define FTIMER_COMP_VALL_OFFSET (0x1c) /*timer模式下:定时计数值低32位,tacho模式下:配置tach转速周期 = pulse_num*/ +#define FTIMER_CNT_VALU_OFFSET (0x20) /*计数器当前计数值高 32 位*/ +#define FTIMER_CNT_VALL_OFFSET (0x24) /*计数器当前计数值低 32 位*/ +#define FTIMER_INTR_MASK_OFFSET (0x28) /*中断使能寄存器*/ +#define FTIMER_INTR_STATUS_OFFSET (0x2c) /*中断状态寄存器*/ +#define FTACHO_OVER_LIM_OFFSET (0x30) /*预设的 tach 最大值*/ +#define FTACHO_UNDER_LIM_OFFSET (0x34) /*预设的 tach 最小值*/ +#define FTIMER_START_VAL_OFFSET (0x38) /*计数器初始值*/ + +/* bit set */ +/* timer ctrl */ +#define FTIMER_REG_TACHO_MODE_MASK (0x3 << 0) /*bit [1:0] RW*/ +#define FTIMER_REG_TACHO_MODE_TIMER (0x0 << 0) /*定时器功能*/ +#define FTIMER_REG_TACHO_MODE_TACHO (0x1 << 0) /*tachometer 功能*/ +#define FTIMER_REG_TACHO_MODE_CAPTURE (0x2 << 0) /*输入 capture 功能*/ + +#define FTIMER_REG_TACHO_RESET (0x1 << 2) /*in reset status*/ + +#define FTIMER_REG_TACHO_FORCE_LOAD (0x1 << 3) /*force to update*/ +#define FTIMER_REG_TACHO_CAPTURE_ENABLE (0x1 << 4) /*enable input capture*/ +#define FTIMER_REG_TACHO_CAPTURE_CNT_MASK (0x7f << 5) /*in capture mode, cause intr when egde counting reach this val*/ +#define FTIMER_REG_TACHO_CAPTURE_CNT_SHIFT 5 /*cap_cnt shift*/ + +#define FTACHO_REG_ANTI_JITTER_MASK (0x3 << 18) /*anti jitter num = N + 1*/ +#define FTACHO_REG_ANTI_JITTER_SHIFT 18 /*anti_jitter_number shift*/ + +#define FTACHO_REG_MODE_MASK (0x3 << 20) /*select tacho input mode*/ +#define FTACHO_REG_MODE_FALLING_EDGE (0x0 << 20) /*select falling edge*/ +#define FTACHO_REG_MODE_RISING_EDGE (0x1 << 20) /*select rising edge*/ +#define FTACHO_REG_MODE_DOUBLE_EDGE (0x2 << 20) /*select both falling edge and rising*/ + +#define FTIMER_REG_CNT_RESTART (0x1 << 22) /*select timer restart mode*/ +#define FTIMER_REG_CNT_FREERUN (0x0 << 22) /*select timer free_run mode*/ + +#define FTIMER_REG_CNT_SERIES_64BIT (0x1 << 24) /*select counter bit 64 */ +#define FTIMER_REG_CNT_SERIES_32BIT (0x0 << 24) /*select counter bit 32 */ + +#define FTIMER_REG_ENABLE (0x1 << 25) /*enable timer count*/ + +#define FTIMER_REG_CNT_CLR (0x1 << 26) /*clear counter*/ +#define FTIMER_REG_CNT_NOCLR (0x0 << 26) /*don't clear counter*/ + +#define FTIMER_REG_MODE_ONCE (0x1 << 27) /*one time timer*/ +#define FTIMER_REG_MODE_CYC (0x0 << 27) /*cycle timer*/ + +#define FTACHO_REG_CAP_IN_ENABLE (0x1 << 31) /*enable tacho capture input*/ + +/* tacho result */ +#define FTACHO_REG_RESU_MASK GENMASK(30, 0) /*bit [30:0], tacho result*/ +#define FTACHO_REG_RESU_ISVALID (0x1 << 31) /*tacho result is valid*/ + +/* tacho over */ +#define FTACHO_REG_OVER_MASK GENMASK(30, 0) /*tacho max value mask*/ + +/* tacho under */ +#define FTACHO_REG_UNDER_MASK GENMASK(30, 0) /*tacho min value mask*/ + +/* intr mask */ +#define FTACHO_OVER_INTR_EN (0x1 << 0) /*tach 超转速中断使能*/ +#define FTACHO_UNDER_INTR_EN (0x1 << 1) /*tach 低于转速中断使能*/ +#define FTIMER_ROLLOVER_INTR_EN (0x1 << 2) /*计数器翻转中断使能*/ +#define FTIMER_ONCECMP_INTR_EN (0x1 << 3) /*一次定时输出中断使能*/ +#define FTIMER_CYCCMP_INTR_EN (0x1 << 4) /*重复定时输出中断使能*/ +#define FTACHO_CAPTURE_INTR_EN (0x1 << 5) /*tach 输入捕获中断使能*/ + +#define FTIMER_ALL_INTR_EN (FTIMER_ROLLOVER_INTR_EN | FTIMER_ONCECMP_INTR_EN | FTIMER_CYCCMP_INTR_EN) + +/* intr status */ +#define FTACHO_OVER_INTR_STATUS (0x1 << 0) /*tach 超转速中断*/ +#define FTACHO_UNDER_INTR_STATUS (0x1 << 1) /*tach 低于转速中断*/ +#define FTIMER_ROLLOVER_INTR_STATUS (0x1 << 2) /*计数器翻转中断*/ +#define FTIMER_ONCECMP_INTR_STATUS (0x1 << 3) /*一次定时输出中断*/ +#define FTIMER_CYCCMP_INTR_STATUS (0x1 << 4) /*重复定时输出中断*/ +#define FTACHO_CAPTURE_INTR_STATUS (0x1 << 5) /*tach 输入捕获中断*/ + +/** + * @name: FTIMER_READ_REG32 + * @msg: 读取定时器寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @return {u32} 寄存器参数 + */ +#define FTIMER_READ_REG32(addr, reg_offset) FtIn32(addr + (u32)reg_offset) + +/** + * @name: FTIMER_WRITE_REG32 + * @msg: 写入定时器寄存器 + * @param {u32} addr 定时器的基地址 + * @param {u32} reg_offset 定时器的寄存器的偏移 + * @param {u32} reg_value 写入寄存器参数 + * @return {void} + */ +#define FTIMER_WRITE_REG32(addr, reg_offset, reg_value) FtOut32(addr + (u32)reg_offset, (u32)reg_value) + +#define FTIMER_TIMEOUT 3000 /*超时时间*/ + +#define FTIMER_BASE_ADDR(instance_p) TIMER_TACHO_BASE_ADDR((instance_p)->config.id) /*获取设备基地址*/ +/*read and write reg value*/ +#define FTIMER_CTRL_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_CTRL_REG_OFFSET) +#define FTIMER_CTRL_WRITE(instance_p, regVal) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_CTRL_REG_OFFSET, (regVal)) +#define FTIMER_CMPL_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_COMP_VALL_OFFSET) +#define FTIMER_CMPL_WRITE(instance_p, cmpL) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_COMP_VALL_OFFSET, (cmpL)) +#define FTIMER_CMPU_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_COMP_VALU_OFFSET) +#define FTIMER_CMPU_WRITE(instance_p, cmpU) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_COMP_VALU_OFFSET, (cmpU)) +#define FTIMER_STAR_WRITE(instance_p, cnt) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_START_VAL_OFFSET, (cnt)) +#define FTIMER_STAR_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_START_VAL_OFFSET) +#define FTIMER_CNTL_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_CNT_VALL_OFFSET) +#define FTIMER_CNTU_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_CNT_VALU_OFFSET) +#define FTACHO_RESU_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTACHO_RESULT_REG_OFFSET) +#define FTACHO_OVER_WRITE(instance_p, over) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTACHO_OVER_LIM_OFFSET, (over)) +#define FTACHO_UNDER_WRITE(instance_p, under) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTACHO_UNDER_LIM_OFFSET, (under)) + +#define FTIMER_INTR_M_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_INTR_MASK_OFFSET) +#define FTIMER_INTR_M_WRITE(instance_p, mask) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_INTR_MASK_OFFSET, (mask)) +#define FTIMER_INTR_S_READ(instance_p) FTIMER_READ_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_INTR_STATUS_OFFSET) +/* write 1 clear */ +#define FTIMER_INTR_S_CLEAR(instance_p, status) FTIMER_WRITE_REG32(FTIMER_BASE_ADDR(instance_p), FTIMER_INTR_STATUS_OFFSET, (status)) + +#ifdef __cplusplus +} +#endif + +#endif // ! \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_intr.c b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_intr.c new file mode 100644 index 0000000000..015a0799df --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/timer/ftimer_tacho/ftimer_tacho_intr.c @@ -0,0 +1,211 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: ftimer_tacho_intr.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:09:36 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ +#include "fassert.h" +#include "ftimer_tacho.h" +#include "ftimer_tacho_hw.h" +#include "finterrupt.h" + +/************************** Constant Definitions *****************************/ + +static const u32 g_intrBits[FMAX_TIMER_TACHO_EVENT] = +{ + FTACHO_OVER_INTR_EN, FTACHO_UNDER_INTR_EN, + FTIMER_ROLLOVER_INTR_EN, FTIMER_ONCECMP_INTR_EN, FTIMER_CYCCMP_INTR_EN, + FTACHO_CAPTURE_INTR_EN +}; + +static const u32 g_intrStats[FMAX_TIMER_TACHO_EVENT] = +{ + FTACHO_OVER_INTR_STATUS, FTACHO_UNDER_INTR_STATUS, + FTIMER_ROLLOVER_INTR_STATUS, FTIMER_ONCECMP_INTR_STATUS, FTIMER_CYCCMP_INTR_STATUS, + FTACHO_CAPTURE_INTR_STATUS +}; + +/************************** Function Prototypes ******************************/ +/** + * @name: FTimerGetInterruptMask + * @msg: 获取中断设置 + * @return {u32} 返回中断寄存器的值 + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +u32 FTimerGetInterruptMask(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + return FTIMER_INTR_M_READ(instance_p); +} + +/** + * @name: FTimerSetInterruptMask + * @msg: 设置中断 + * @return {void} + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {enum} intrType 中断枚举类型 + * @param {boolean} enable 使能或者失能 + */ +void FTimerSetInterruptMask(FTimerTachoCtrl *instance_p, + FTimerTachoEventType intrType, + boolean enable) +{ + FASSERT(instance_p && intrType < FMAX_TIMER_TACHO_EVENT); + u32 mask = FTIMER_INTR_M_READ(instance_p); + + if (enable) + { + mask |= g_intrBits[intrType]; + } + else + { + mask &= ~g_intrBits[intrType]; + } + + FTIMER_INTR_M_WRITE(instance_p, mask); +} + +/** + * @name: FTimerTachoIntrHandler + * @msg: 中断服务函数,跳转到自己注册的回调函数(如果注册,没有注册则跳转到FTimerDefaultEvtCallback) + * @return {void} + * @param {s32} vector,中断向量号,此处不关心此参数 + * @param {void} *param, 中断输入参数, 指向FTimerTachoCtrl的驱动控制实例 + */ +void FTimerTachoIntrHandler(s32 vector, void *param) +{ + FASSERT(param); + + FTimerTachoCtrl *instance_p = (FTimerTachoCtrl *)param; + const u32 intr_status = FTIMER_INTR_S_READ(instance_p); + u32 loop; + FTimerEventHandler evtHandler; + + FTIMER_INFO("intr entered cause: 0x%x.\r\n", intr_status); + + /* check intr status bit by bit */ + for (loop = 0; loop < FMAX_TIMER_TACHO_EVENT; loop++) + { + evtHandler = instance_p->evt_handlers[loop]; + + if ((g_intrStats[loop] & intr_status) && (NULL != evtHandler)) + { + evtHandler((void *)instance_p); + } + } + + FTIMER_INTR_S_CLEAR(instance_p, intr_status); +} + +/** + * @name: FTimerDefaultEvtCallback + * @msg: 默认中断回调函数 + * @return {void} + * @param {void} *param,函数输入参数指向FTimerTachoCtrl的驱动控制实例 + */ +static void FTimerDefaultEvtCallback(void *param) +{ + FASSERT(param); + FTimerTachoCtrl *instance_p = (FTimerTachoCtrl *)param; + const u32 intr_status = FTIMER_INTR_S_READ(instance_p); + + FTIMER_INFO("timer id: 0x%x, intr cause: 0x%x.\r\n", intr_status); +} + +/** + * @name: FTimerRegisterEvtCallback + * @msg: 回调函数的注册函数 + * @return {void} + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + * @param {enum} intrType 中断枚举类型 + * @param {FTimerEventHandler} + */ +void FTimerRegisterEvtCallback(FTimerTachoCtrl *instance_p, + FTimerTachoEventType evt, + FTimerEventHandler callback) +{ + FASSERT(instance_p && evt < FMAX_TIMER_TACHO_EVENT); + instance_p->evt_handlers[evt] = callback; +} + +/** + * @name: FTimerTachoSetIntr + * @msg: 根据工作模式和状态设置相应的中断 + * @return {void} + * @param {FTimerTachoCtrl} *instance_p 驱动控制数据结构 + */ +void FTimerTachoSetIntr(FTimerTachoCtrl *instance_p) +{ + FASSERT(instance_p); + + if (FTIMER_WORK_MODE_TIMER == instance_p->config.work_mode) + { + if (FTIMER_ONCE_CMP == instance_p->config.cmp_type) + { + FTimerSetInterruptMask(instance_p, FTIMER_EVENT_ONCE_CMP, TRUE); + if (instance_p->evt_handlers[FTIMER_EVENT_ONCE_CMP] == NULL) + { + FTimerRegisterEvtCallback(instance_p, FTIMER_EVENT_ONCE_CMP, FTimerDefaultEvtCallback); + } + } + else + { + FTimerSetInterruptMask(instance_p, FTIMER_EVENT_CYC_CMP, TRUE); + if (instance_p->evt_handlers[FTIMER_EVENT_CYC_CMP] == NULL) + { + FTimerRegisterEvtCallback(instance_p, FTIMER_EVENT_CYC_CMP, FTimerDefaultEvtCallback); + } + } + /*暂时屏蔽不开启翻转中断,因为cmp设置触发就是最大值,等同于翻转中断*/ + /*FTimerSetInterruptMask(instance_p, FTIMER_EVENT_ROLL_OVER, TRUE);*/ + if (instance_p->evt_handlers[FTIMER_EVENT_ROLL_OVER] == NULL) + { + FTimerRegisterEvtCallback(instance_p, FTIMER_EVENT_ROLL_OVER, FTimerDefaultEvtCallback); + } + } + else if (FTIMER_WORK_MODE_TACHO == instance_p->config.work_mode) + { + FTimerSetInterruptMask(instance_p, FTACHO_EVENT_OVER, TRUE); + FTimerSetInterruptMask(instance_p, FTACHO_EVENT_UNDER, TRUE); + if (instance_p->evt_handlers[FTACHO_EVENT_OVER] == NULL) + { + FTimerRegisterEvtCallback(instance_p, FTACHO_EVENT_OVER, FTimerDefaultEvtCallback); + } + if (instance_p->evt_handlers[FTACHO_EVENT_UNDER] == NULL) + { + FTimerRegisterEvtCallback(instance_p, FTACHO_EVENT_UNDER, FTimerDefaultEvtCallback); + } + } + else if (FTIMER_WORK_MODE_CAPTURE == instance_p->config.work_mode) + { + FTimerSetInterruptMask(instance_p, FTACHO_EVENT_CAPTURE, TRUE); + if (instance_p->evt_handlers[FTACHO_EVENT_CAPTURE] == NULL) + { + FTimerRegisterEvtCallback(instance_p, FTACHO_EVENT_CAPTURE, FTimerDefaultEvtCallback); + } + } + else + { + FASSERT(0); + } + FTIMER_INFO("mask:0x%x.\r\n", FTIMER_INTR_M_READ(instance_p)); + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/Kconfig b/bsp/phytium/libraries/standalone/drivers/usb/Kconfig new file mode 100644 index 0000000000..18d0f459d8 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/Kconfig @@ -0,0 +1,9 @@ +config ENABLE_USB_FXHCI + bool + prompt "Use USB3.0 Host(FUSB_HC_XHCI)" + default n + depends on USE_USB + help + Select USB FUSB_HC_XHCI Host driver component + + diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb.c new file mode 100644 index 0000000000..f5e0818757 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb.c @@ -0,0 +1,1024 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb.c + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:22:06 + * Description:  This files is for implmentation of USB user API + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/8 init commit + */ + +#include + +#include "fdebug.h" +#include "fsleep.h" + +#include "fusb_private.h" +#include "fxhci.h" + +#define FUSB_DEBUG_TAG "FUSB" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FUSB_DR_DESC FUsbGenerateReqType(FUSB_REQ_DEVICE_TO_HOST, FUSB_REQ_TYPE_STANDARD, FUSB_REQ_RECP_DEV) + +/* + * Certain Lexar / Micron USB 2.0 disks will fail the FUsbGetDescriptor(FUSB_DESC_TYPE_CONFIG) + * call due to timing issues. Work around this by making extra attempts on + * failure. + */ +#define FUSB_GET_DESCRIPTOR_RETRIES 3 + +/** + * @name: FUsbCfgInitialize + * @msg: 初始化USB实例 + * @return {FError} 初始化错误码 + * @param {FUsb} *instance, USB实例 + * @param {const FUsbConfig} *input_config, USB输入配置 + * @note 在PCIE模式下,USB Hc实例在PCIE总线发现控制器后创建 + */ +FError FUsbCfgInitialize(FUsb *instance, const FUsbConfig *input_config) +{ + FASSERT(instance && input_config); + FError ret = FUSB_SUCCESS; + + if (input_config != &instance->config) + instance->config = *input_config; + + instance->hc = NULL; /* non usb host attached */ + + /* create usb hc instance, which will be add as the head of hc list */ + if (NULL == FXhciHcInit(instance, instance->config.base_addr)) + ret = FUSB_ERR_ALLOCATE_FAIL; + + if (FUSB_SUCCESS == ret) + { + instance->is_ready = FT_COMPONENT_IS_READY; + } + + return ret; +} + +/** + * @name: FUsbDeInitialize + * @msg: 去初始化USB实例 + * @return {*} + * @param {FUsb} *instance, USB实例 + */ +void FUsbDeInitialize(FUsb *instance) +{ + FASSERT(instance); + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FUSB_ERROR("USB not ready !!!"); + return; + } + + instance->is_ready = 0; + + return; +} + +/** + * @name: FUsbPoll + * @msg: 轮询所有的USB控制器连接的所有设备, 更新设备拓扑 + * @return {*} + * @param {FUsb} *instance, USB实例 + */ +void FUsbPoll(FUsb *instance) +{ + FASSERT(instance); + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FUSB_ERROR("USB not ready !!!"); + return; + } + + if (FUsbPollPrepare) + FUsbPollPrepare(instance); + + FUsbHc *controller = instance->hc; + if (controller != NULL) + { + int i; + for (i = 0; i < FUSB_MAX_DEV_NUM; i++) + { + if (controller->devices[i] != NULL) + { + controller->devices[i]->poll(controller->devices[i]); + } + } + } + + return; +} + +/** + * @name: FUsbExit + * @msg: 关闭所有的USB控制器,移除所有连接的设备 + * @return {*} + * @param {FUsb} *instance, USB实例 + */ +void FUsbExit(FUsb *instance) +{ + FASSERT(instance); + + if (FT_COMPONENT_IS_READY != instance->is_ready) + { + FUSB_ERROR("USB not ready !!!"); + return; + } + + if (FUsbExitPrepare) + FUsbExitPrepare(instance); + + FUsbHc *controller = instance->hc; + if (controller != NULL) + { + FASSERT(controller->shutdown); + controller->shutdown(controller); + FUSB_FREE(instance, instance->hc); + instance->hc = NULL; + } + + + return; +} + +/** + * @name: FUsbMempAllocate + * @msg: 从USB内存池分配一块内存,并清零分配的空间 + * @return {void *} 分配的内存空间,如果失败返回NULL + * @param {FUsb} *instance, USB实例 + * @param {size_t} size, 请求分配的字节数 + * @param {size_t} align, 分配空间的对齐方式,起始地址按align字节对齐 + */ +void *FUsbMempAllocate(FUsb *instance, size_t size, size_t align) +{ + FASSERT(instance); + void *result = NULL; + FUsbMemAllocator *allocator = &(instance->config.allocator); + + if (allocator->malloc_align) + { + result = allocator->malloc_align(size, align); + } + + return result; +} + +/** + * @name: FUsbMempFree + * @msg: 释放从USB内存池分配的空间 + * @return {*} + * @param {FUsb} *instance, USB实例 + * @param {void} *ptr, 待释放空间的首地址 + */ +void FUsbMempFree(FUsb *instance, void *ptr) +{ + FASSERT(instance); + FUsbMemAllocator *allocator = &(instance->config.allocator); + + if ((NULL != ptr) && (allocator->free)) + { + allocator->free(ptr); + } + + return; +} + +#ifdef FMEMP_TAG_DEBUG +void *FUsbMempAllocateTag(FUsb *instance, size_t size, size_t align, const char *file, unsigned long line, const char *msg) +{ + FASSERT(instance); + void *result = NULL; + FMemp *memp = &instance->memp; + + if (FUSB_DEFAULT_ALIGN == align) + { + result = FMempCallocTag(memp, 1, size, file, line, msg); + } + else + { + result = FMempMallocAlignTag(memp, size, align, file, line, msg); + if (NULL != result) + { + memset(result, 0, size); + } + } + + return result; +} + +void FUsbMempFreeTag(FUsb *instance, void *ptr) +{ + FASSERT(instance); + if (NULL != ptr) + FMempFreeTag(&instance->memp, ptr); + + return; +} +#endif + +/** + * @name: FUsbAllocateHc + * @msg: 创建USB控制器实例,添加到USB实例的Hc链表中 + * @return {*} + * @param {FUsb} *instance, USB实例 + */ +FUsbHc *FUsbAllocateHc(FUsb *instance) +{ + FASSERT(instance); + FUsbHc *controller = FUSB_ALLOCATE(instance, sizeof(FUsbHc), FUSB_DEFAULT_ALIGN); + instance->hc = controller; + + + return controller; +} + +/** + * @name: FUsbDetachHc + * @msg: 删除USB控制器实例,从USB实例的Hc链表中删去 + * @return {*} + * @param {FUsbHc} *controller, USB控制器实例 + */ +void FUsbDetachHc(FUsbHc *controller) +{ + if (controller == NULL) + return; + + FUsb *instance = controller->usb; + FUsbDetachDev(controller, 0); /* tear down root hub tree */ + + return; +} + +/** + * @name: FUsbFindValidInitFunc + * @msg: 寻找特定USB设备的初始化函数 + * @return {*} + * @param {FUsb} *instance, USB实例 + * @param {FUsbDevIndex} *index, 特定USB设备的索引 + */ +static FUsbDevInitHandler FUsbFindValidInitFunc(FUsb *instance, const FUsbDevIndex *index) +{ + FASSERT(instance); + u32 loop; + FUsbDevInitFunc *func; + FUsbDevInitHandler handler = NULL; + + for (loop = 0; loop < instance->dev_init_num; loop++) + { + func = &instance->dev_init[loop]; + if ((index->category == func->index.category) && + (index->class == func->index.class) && + (index->sub_class == func->index.sub_class) && + (index->protocol == func->index.protocol)) + { + handler = func->handler; + } + } + + return handler; +} + +/** + * @name: FUsbAssignDevInitFunc + * @msg: 指定特定USB设备的初始化函数,供创建USB设备实例时使用 + * @return {FError} 处理返回错误码 + * @param {FUsb} *instance, USB实例 + * @param {FUsbDevIndex} *index, 特定USB设备的索引 + * @param {FUsbDevInitHandler} handler, 特定USB设备的初始化函数 + */ +FError FUsbAssignDevInitFunc(FUsb *instance, const FUsbDevIndex *index, FUsbDevInitHandler handler) +{ + FASSERT(instance && index && handler); + if (FUSB_MAX_DEV_TYPE_NUM == instance->dev_init_num) + return FUSB_ERR_INVALID_PARA; + + if (NULL != FUsbFindValidInitFunc(instance, index)) + { + FUSB_WARN("Will remove device init for class 0x%x", index->class); + } + + instance->dev_init[instance->dev_init_num].index = *index; + instance->dev_init[instance->dev_init_num].handler = handler; + instance->dev_init_num++; + + return FUSB_SUCCESS; +} + +/** + * @name: FUsbInitDevEntry + * @msg: 初始化USB设备 + * @return {*} + * @param {FUsbHc} *controller, USB Hc + * @param {int} slot_id,slot号 + */ +FUsbDev *FUsbInitDevEntry(FUsbHc *controller, int slot_id) +{ + FASSERT(controller && controller->usb); + FASSERT(FUSB_SLOT_ID_VALID(slot_id)); + + FUsb *instace = controller->usb; + FUsbDev *dev = FUSB_ALLOCATE(instace, sizeof(FUsbDev), FUSB_DEFAULT_ALIGN); + + if (NULL == dev) + { + FUSB_ERROR("no memory to allocate device structure "); + return NULL; + } + + if (controller->devices[slot_id] != NULL) + { + FUSB_WARN("warning: device %d reassigned? ", slot_id); + } + + controller->devices[slot_id] = dev; + dev->controller = controller; + dev->address = FUSB_NO_DEV_ADDR; + dev->hub = FUSB_NO_HUB; + dev->port = FUSB_NO_PORT; + dev->init = FUsbNopDevInit; + dev->init(controller->devices[slot_id]); + + return dev; +} + +/** + * @name: FUsbGetAllDevEntries + * @msg: 获取USB控制器上连接的所有USB设备实例 + * @return {size_t} 实际获取的USB设备实例数目 + * @param {FUsbHc} *controller, USB控制器实例 + * @param {FUsbDev} *devs, 放置USB设备实例的缓冲区 + * @param {size_t} max_dev_num, 最多可以获取的USB设备实例数目 + */ +size_t FUsbGetAllDevEntries(FUsbHc *controller, FUsbDev *devs[], size_t max_dev_num) +{ + FASSERT(controller && devs && max_dev_num > 0); + size_t loop; + size_t num = 0; + + /* loop over all dev address in case there are holes */ + for (loop = 0; loop < FUSB_MAX_DEV_NUM; loop++) + { + if (NULL != controller->devices[loop]) + { + devs[num] = controller->devices[loop]; + num++; + + /* get at most max_dev_num device entry before exit */ + if (num >= max_dev_num) + break; + } + } + + return num; +} + +/** + * @name: FUsbDecodeMaxPacketSz0 + * @msg: 根据USB设备速度,选择最大包长度 + * @return {*} 输出最大包长度 + * @param {FUsbSpeed} speed, USB设备速度类型 + * @param {u8} bMaxPacketSize0, 输入最大包长度 + */ +int FUsbDecodeMaxPacketSz0(FUsbSpeed speed, u8 bMaxPacketSize0) +{ + switch (speed) + { + case FUSB_LOW_SPEED: + if (bMaxPacketSize0 != 8) + { + FUSB_ERROR("Invalid MPS0: 0x%02x ", bMaxPacketSize0); + bMaxPacketSize0 = 8; + } + return bMaxPacketSize0; + case FUSB_FULL_SPEED: + switch (bMaxPacketSize0) + { + case 8: + case 16: + case 32: + case 64: + return bMaxPacketSize0; + default: + FUSB_ERROR("Invalid MPS0: 0x%02x ", bMaxPacketSize0); + return 8; + } + case FUSB_HIGH_SPEED: + if (bMaxPacketSize0 != 64) + { + FUSB_ERROR("Invalid MPS0: 0x%02x ", bMaxPacketSize0); + bMaxPacketSize0 = 64; + } + return bMaxPacketSize0; + case FUSB_SUPER_SPEED: + /* Intentional fallthrough */ + case FUSB_SUPER_SPEED_PLUS: + if (bMaxPacketSize0 != 9) + { + FUSB_ERROR("Invalid MPS0: 0x%02x ", bMaxPacketSize0); + bMaxPacketSize0 = 9; + } + return 1 << bMaxPacketSize0; + default: + return 8; + } +} + +/** + * @name: FUsbSetFeature + * @msg: 标准USB主机请求,使能设备/接口/端点的某个特性 + * @return {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + * @param {FUsbDev} *dev, USB设备实例 + * @param {int} endp, 设备号(0x00)/接口号/端点号 + * @param {int} feature, 待使能的特性 + * @param {int} rtype, 请求类型,由FUsbGenerateReqType生成 + */ +FUsbTransCode FUsbSetFeature(FUsbDev *dev, int endp, int feature, int rtype) +{ + FASSERT(dev && dev->controller && dev->controller->control); + FUsbDevReq dr; + + dr.bmRequestType = rtype; + dr.data_dir = FUSB_REQ_HOST_TO_DEVICE; + dr.bRequest = FUSB_SET_FEATURE; + dr.wValue = feature; + dr.wIndex = endp; + dr.wLength = 0; + + return dev->controller->control(dev, FUSB_OUT, sizeof(dr), &dr, 0, NULL); +} + +/** + * @name: FUsbGetStatus + * @msg: 标准USB主机请求,获取设备/接口/端点的状态 + * @return {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + * @param {FUsbDev} *dev, USB设备实例 + * @param {int} intf,设备号(0x00)/接口号/端点号 + * @param {int} rtype, 请求类型,由FUsbGenerateReqType生成 + * @param {int} len, Data Stage的数据长度 + * @param {void} *data, Data Stage的数据缓冲区 + */ +FUsbTransCode FUsbGetStatus(FUsbDev *dev, int intf, int rtype, int len, void *data) +{ + FASSERT(dev && dev->controller && dev->controller->control); + FUsbDevReq dr; + + dr.bmRequestType = rtype; + dr.data_dir = FUSB_REQ_DEVICE_TO_HOST; + dr.bRequest = FUSB_GET_STATUS; + dr.wValue = 0; + dr.wIndex = intf; + dr.wLength = len; + + return dev->controller->control(dev, FUSB_IN, sizeof(dr), &dr, len, data); +} + +/** + * @name: FUsbGetDescriptor + * @msg: 标准USB主机请求,获取指定描述符 + * @return {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + * @param {FUsbDev} *dev, USB设备实例 + * @param {int} rtype, 请求类型,由FUsbGenerateReqType生成 + * @param {FUsbDescriptorType} desc_type, 描述符类型 + * @param {int} desc_idx, 描述符索引 + * @param {void} *data, Data Stage的数据缓冲区 + * @param {size_t} len, Data Stage的数据长度 + */ +FUsbTransCode FUsbGetDescriptor(FUsbDev *dev, int rtype, FUsbDescriptorType desc_type, int desc_idx, void *data, + size_t len) +{ + FASSERT(dev && dev->controller && dev->controller->control); + FUsbDevReq dr; + int fail_tries = 0; + FUsbTransCode ret = FUSB_CC_ZERO_BYTES; + + while (fail_tries++ < FUSB_GET_DESCRIPTOR_RETRIES) + { + dr.bmRequestType = rtype; + dr.bRequest = FUSB_GET_DESCRIPTOR; + dr.wValue = desc_type << 8 | desc_idx; + dr.wIndex = 0; + dr.wLength = len; + + ret = dev->controller->control(dev, FUSB_IN, + sizeof(dr), &dr, len, data); + + if (ret == (int)len) + break; + + fsleep_microsec(10); + } + + return ret; +} + +/** + * @name: FUsbGetStringDescriptor + * @msg: USB主机请求,获取字符串描述符 + * @return {int} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + * @param {FUsbDev} *dev, USB设备实例 + * @param {int} rtype, 请求类型,由FUsbGenerateReqType生成 + * @param {int} desc_type, 描述符类型 + * @param {int} desc_idx, 描述符索引 + * @param {int} lang_id, 语言类型 + * @param {void} *data, Data Stage的数据缓冲区 + * @param {size_t} len, Data Stage的数据长度 + */ +FUsbTransCode FUsbGetStringDescriptor(FUsbDev *dev, int rtype, FUsbDescriptorType desc_type, int desc_idx, int lang_id, void *data, size_t len) +{ + FASSERT(dev && dev->controller && dev->controller->control); + FUsbDevReq dr; + int fail_tries = 0; + FUsbTransCode ret = FUSB_CC_ZERO_BYTES; + + while (fail_tries++ < FUSB_GET_DESCRIPTOR_RETRIES) + { + dr.bmRequestType = rtype; + dr.bRequest = FUSB_GET_DESCRIPTOR; + dr.wValue = desc_type << 8 | desc_idx; + dr.wIndex = lang_id; + dr.wLength = len; + + ret = dev->controller->control(dev, FUSB_IN, sizeof(dr), &dr, len, data); + if (ret == (int)len) + break; + + fsleep_microsec(10); + } + + return ret; +} + +/** + * @name: FUsbSetConfiguration + * @msg: 标准USB主机请求,设置配置值 + * @return {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + * @param {FUsbDev} *dev, USB设备实例 + */ +FUsbTransCode FUsbSetConfiguration(FUsbDev *dev) +{ + FASSERT(dev && dev->controller && dev->controller->control); + FUsbDevReq dr; + + dr.bmRequestType = 0; + dr.bRequest = FUSB_SET_CONFIGURATION; + dr.wValue = dev->configuration->bConfigurationValue; + dr.wIndex = 0; + dr.wLength = 0; + + return dev->controller->control(dev, FUSB_OUT, sizeof(dr), &dr, 0, NULL); +} + +/** + * @name: FUsbClearFeature + * @msg: 标准USB主机请求,去使能设备/接口/端点的某个特性 + * @return {FUsbTransCode} 控制传输的返回值,小于0表示失败,大于0表示成功传输的字节数目 + * @param {FUsbDev} *dev, USB设备实例 + * @param {int} endp, 设备号(0x00)/接口号/端点号 + * @param {int} feature,待去除的特性 + * @param {int} rtype, 请求类型,由FUsbGenerateReqType生成 + */ +FUsbTransCode FUsbClearFeature(FUsbDev *dev, int endp, int feature, int rtype) +{ + FASSERT(dev && dev->controller && dev->controller->control); + FUsbDevReq dr; + + dr.bmRequestType = rtype; + dr.data_dir = FUSB_REQ_HOST_TO_DEVICE; + dr.bRequest = FUSB_CLEAR_FEATURE; + dr.wValue = feature; + dr.wIndex = endp; + dr.wLength = 0; + + return dev->controller->control(dev, FUSB_OUT, sizeof(dr), &dr, 0, NULL) < 0; +} + +/** + * @name: FUsbSpeedtoDefaultMaxPacketSz + * @msg: 根据设备速度获取最大包长度 + * @return {int} 最大包长度 + * @param {FUsbSpeed} speed, 设备速度类型 + */ +int FUsbSpeedtoDefaultMaxPacketSz(FUsbSpeed speed) +{ + switch (speed) + { + case FUSB_LOW_SPEED: + return 8; + case FUSB_FULL_SPEED: + case FUSB_HIGH_SPEED: + return 64; + case FUSB_SUPER_SPEED: + /* Intentional fallthrough */ + case FUSB_SUPER_SPEED_PLUS: + default: + return 512; + } +} + +/** + * @name: FUsbDecodeInterval + * @msg: 获取USB传输间隔时间 + * @return {int} 传输间隔时间, 0表示失败 + * @param {FUsbSpeed} speed, USB设备速度类型 + * @param {FUsbEpType} type, 端点类型 + * @param {unsigned char} bInterval, 设置的间隔时间 + */ +static int FUsbDecodeInterval(FUsbSpeed speed, const FUsbEpType type, const unsigned char bInterval) +{ + /* Normalize bInterval to log2 of microframes */ +#define LOG2(a) ((sizeof(unsigned) << 3) - __builtin_clz(a) - 1) + switch (speed) + { + case FUSB_LOW_SPEED: + switch (type) + { + case FUSB_ISOCHRONOUS_EP: + case FUSB_INTERRUPT_EP: + return LOG2(bInterval) + 3; + default: + return 0; + } + case FUSB_FULL_SPEED: + switch (type) + { + case FUSB_ISOCHRONOUS_EP: + return (bInterval - 1) + 3; + case FUSB_INTERRUPT_EP: + return LOG2(bInterval) + 3; + default: + return 0; + } + case FUSB_HIGH_SPEED: + switch (type) + { + case FUSB_ISOCHRONOUS_EP: + case FUSB_INTERRUPT_EP: + return bInterval - 1; + default: + return LOG2(bInterval); + } + case FUSB_SUPER_SPEED: + /* Intentional fallthrough */ + case FUSB_SUPER_SPEED_PLUS: + switch (type) + { + case FUSB_ISOCHRONOUS_EP: + case FUSB_INTERRUPT_EP: + return bInterval - 1; + default: + return 0; + } + default: + return 0; + } +#undef LOG2 +} + +/** + * @name: FUsbSetAddress + * @msg: 获取USB设备的描述符信息,根据USB设备类型完成配置和初始化 + * @return {FUsbDevAddr} 为USB设备分配的地址,-1表示USB设备初始化失败 + * @param {FUsbHc} *controller, USB控制器实例 + * @param {FUsbSpeed} speed, USB设备速度类型 + * @param {int} hubport, USB设备连接的Hub端口号 + * @param {int} hubaddr, USB设备连接Hub的地址 + */ +static FUsbDevAddr FUsbSetAddress(FUsbHc *controller, FUsbSpeed speed, int hubport, int hubaddr) +{ + FASSERT(controller); + FUsbDev *dev = controller->set_address(controller, speed, + hubport, hubaddr); + FUsbDevIndex index; + FUsbDevInitHandler init_handler = NULL; + + FUsb *instace = controller->usb; + FASSERT(instace); + if (NULL == dev) + { + FUSB_INFO("set_address failed "); + return FUSB_NO_DEV_ADDR; + } + + FASSERT(NULL == dev->descriptor); + dev->descriptor = FUSB_ALLOCATE(instace, sizeof(*dev->descriptor), FUSB_DEFAULT_ALIGN); + if ((NULL == dev->descriptor) || FUsbGetDescriptor(dev, FUSB_DR_DESC, FUSB_DESC_TYPE_DEVICE, 0, + dev->descriptor, sizeof(*dev->descriptor)) != sizeof(*dev->descriptor)) + { + FUSB_INFO("FUsbGetDescriptor(FUSB_DESC_TYPE_DEVICE) failed "); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + FUSB_INFO("* found device (0x%04x:0x%04x, USB %x.%x, MPS0: %d) ", + dev->descriptor->idVendor, dev->descriptor->idProduct, + dev->descriptor->bcdUSB >> 8, dev->descriptor->bcdUSB & 0xff, + dev->endpoints[0].maxpacketsize); + + FUSB_INFO("device has %d configurations ", + dev->descriptor->bNumConfigurations); + if (dev->descriptor->bNumConfigurations == 0) + { + /* device isn't usable */ + FUSB_INFO("... no usable configuration! "); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + u16 buf[2]; + if (FUsbGetDescriptor(dev, FUSB_DR_DESC, FUSB_DESC_TYPE_CONFIG, 0, buf, sizeof(buf)) != sizeof(buf)) + { + FUSB_INFO("first FUsbGetDescriptor(FUSB_DESC_TYPE_CONFIG) failed "); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + /* workaround for some USB devices: wait until they're ready, or + * they send a NAK when they're not allowed to do. 1ms is enough */ + fsleep_millisec(1); + FASSERT(NULL == dev->configuration); + dev->configuration = FUSB_ALLOCATE(instace, buf[1], FUSB_DEFAULT_ALIGN); + if (NULL == dev->configuration) + { + FUSB_INFO("could not allocate %d bytes for FUSB_DESC_TYPE_CONFIG ", buf[1]); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + if (FUsbGetDescriptor(dev, FUSB_DR_DESC, FUSB_DESC_TYPE_CONFIG, 0, dev->configuration, + buf[1]) != buf[1]) + { + FUSB_INFO("FUsbGetDescriptor(FUSB_DESC_TYPE_CONFIG) failed "); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + FUsbConfigurationDescriptor *cd = dev->configuration; + if (cd->wTotalLength != buf[1]) + { + FUSB_INFO("configuration descriptor size changed, aborting "); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + /* + * If the device is not well known (ifnum == -1), we use the first + * interface we encounter, as there was no need to implement something + * else for the time being. If you need it, see the SetInterface and + * GetInterface functions in the USB specification and set it yourself. + */ + FUSB_INFO("device has %x interfaces ", cd->bNumInterfaces); + + u8 *end = (void *)dev->configuration + cd->wTotalLength; + FUsbInterfaceDescriptor *intf; + u8 *ptr; + + /* Find our interface (or the first good one if we don't know) */ + for (ptr = (void *)dev->configuration + sizeof(*cd);; ptr += ptr[0]) + { + if (ptr + 2 > end || !ptr[0] || ptr + ptr[0] > end) + { + FUSB_INFO("Couldn't find usable FUSB_DESC_TYPE_INTERFACE "); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + if (ptr[1] != FUSB_DESC_TYPE_INTERFACE) + continue; + + intf = (void *)ptr; + if (intf->bLength != sizeof(*intf)) + { + FUSB_INFO("Skipping broken FUSB_DESC_TYPE_INTERFACE "); + continue; + } + + FUSB_INFO("Interface %d: class 0x%x, sub 0x%x. proto 0x%x ", + intf->bInterfaceNumber, intf->bInterfaceClass, + intf->bInterfaceSubClass, intf->bInterfaceProtocol); + ptr += sizeof(*intf); + + break; + } + + /* Gather up all endpoints belonging to this interface */ + dev->num_endp = 1; + for (; ptr + 2 <= end && ptr[0] && ptr + ptr[0] <= end; ptr += ptr[0]) + { + if (ptr[1] == FUSB_DESC_TYPE_INTERFACE || ptr[1] == FUSB_DESC_TYPE_CONFIG || + (size_t)dev->num_endp >= ARRAY_SIZE(dev->endpoints)) + break; + + if (ptr[1] != FUSB_DESC_TYPE_ENDPOINT) + continue; + + FUsbEndpointDescriptor *desc = (void *)ptr; + static const char *transfertypes[4] = + { + "control", "isochronous", "bulk", "interrupt" + }; + FUSB_INFO(" #Endpoint %d (%s), max packet size %x, type %s ", + desc->bEndpointAddress & 0x7f, + (desc->bEndpointAddress & 0x80) ? "in" : "out", + desc->wMaxPacketSize, + transfertypes[desc->bmAttributes & 0x3]); + + FUsbEndpoint *ep = &dev->endpoints[dev->num_endp++]; + ep->dev = dev; + ep->endpoint = desc->bEndpointAddress; + ep->toggle = 0; + ep->maxpacketsize = desc->wMaxPacketSize; + ep->direction = (desc->bEndpointAddress & 0x80) ? FUSB_IN : FUSB_OUT; + ep->type = desc->bmAttributes & 0x3; + ep->interval = FUsbDecodeInterval(dev->speed, ep->type, + desc->bInterval); + } + + if ((controller->finish_device_config && + controller->finish_device_config(dev)) || + FUsbSetConfiguration(dev) < 0) + { + FUSB_INFO("Could not finalize device configuration "); + FUsbDetachDev(controller, dev->address); + return FUSB_NO_DEV_ADDR; + } + + int class = dev->descriptor->bDeviceClass; + if (class == 0) + class = intf->bInterfaceClass; + + switch (class) + { + case FUSB_AUDIO_DEVICE: + FUSB_INFO("Audio Class "); + break; + case FUSB_COMM_DEVICE: + FUSB_INFO("Communication Class "); + break; + case FUSB_HID_DEVICE: + FUSB_INFO("HID Class "); + break; + case FUSB_PHYSICAL_DEVICE: + FUSB_INFO("Physical Class"); + break; + case FUSB_IMAGE_DEVICE: + FUSB_INFO("Camera Class "); + break; + case FUSB_PRINTER_DEVICE: + FUSB_INFO("Printer Class"); + break; + case FUSB_MASS_STORAGE_DEVICE: + FUSB_INFO("Mass Storage Class "); + break; + case FUSB_HUB_DEVICE: + FUSB_INFO("Hub Class "); + break; + default: + FUSB_ERROR("Unsupported Class %x ", class); + break; + } + + index.category = FUSB_STANDARD_INTERFACE; + index.class = class; + index.sub_class = intf->bInterfaceSubClass; + index.protocol = intf->bInterfaceProtocol; + + FUSB_INFO("class: 0x%x sub-class: 0x%x, protocol: 0x%x", + index.class, index.sub_class, index.protocol); + + init_handler = FUsbFindValidInitFunc(instace, &index); + if (NULL != init_handler) + { + dev->init = init_handler; + dev->class = (FUsbDevClass)class; + } + else + { + FUSB_WARN("Init function for the device not found, use generic one instead !!!"); + dev->init = FUsbGenericDevInit; + } + + return dev->address; +} + +/** + * @name: FUsbDetachDev + * @msg: 从USB主机移除指定USB设备(USB设备驱动使用) + * @return {*} + * @param {FUsbHc} *controller, USB控制器实例 + * @param {int} devno, USB设备索引 + * @note Should be called by the hub drivers whenever a physical detach occurs + * and can be called by USB class drivers if they are unsatisfied with a + * malfunctioning device. + */ +void FUsbDetachDev(FUsbHc *controller, int devno) +{ + FUsb *instace = controller->usb; + /* check if device exists, as we may have + been called yet by the USB class driver */ + if (controller->devices[devno]) + { + controller->devices[devno]->destroy(controller->devices[devno]); + + if (controller->destroy_device) + controller->destroy_device(controller, devno); + + FUSB_FREE(instace, controller->devices[devno]->descriptor); + controller->devices[devno]->descriptor = NULL; + FUSB_FREE(instace, controller->devices[devno]->configuration); + controller->devices[devno]->configuration = NULL; + + /* Tear down the device itself *after* destroy_device() + * has had a chance to interrogate it. */ + FUSB_FREE(instace, controller->devices[devno]); + controller->devices[devno] = NULL; + } + + return; +} + +/** + * @name: FUsbAttachDev + * @msg: 向USB主机添加USB设备(USB设备驱动使用) + * @return {FUsbDevAddr} 分配的USB设备地址 + * @param {FUsbHc} *controller, USB控制器实例 + * @param {int} hubaddress, Hub地址 + * @param {int} port, 连接的Port + * @param {FUsbSpeed} speed, USB设备的设置速度类型 + */ +FUsbDevAddr FUsbAttachDev(FUsbHc *controller, int hubaddress, int port, FUsbSpeed speed) +{ + static const char *speeds[] = {"FULL", "LOW", "HIGH", "SUPER", "ULTRA-SUPER"}; + FUSB_INFO("%s-Speed Device ", ((size_t)speed < sizeof(speeds) / sizeof(char *)) + ? speeds[speed] + : "Unkonwn"); + FUsbDevAddr newdev = FUsbSetAddress(controller, speed, port, hubaddress); + if (newdev == FUSB_NO_DEV_ADDR) + return FUSB_NO_DEV_ADDR; + + FUsbDev *newdev_t = controller->devices[newdev]; + + /* determine responsible driver - current done in set_address */ + newdev_t->init(newdev_t); + + /* init() may have called FUsbDetachDev() yet, so check */ + return controller->devices[newdev] ? newdev : FUSB_NO_DEV_ADDR; +} + +/** + * @name: FUsbGenericDestory + * @msg: 一般USB设备去初始化函数 + * @return {*} + * @param {FUsbDev} *dev, USB设备实例 + */ +static void FUsbGenericDestory(FUsbDev *dev) +{ + if (FUsbGenericRemove) + FUsbGenericRemove(dev); + + return; +} + +/** + * @name: FUsbGenericDevInit + * @msg: 默认的USB设备初始化函数 + * @return {*} + * @param {FUsbDev} *dev, USB设备实例 + */ +void FUsbGenericDevInit(FUsbDev *dev) +{ + dev->data = NULL; + dev->destroy = FUsbGenericDestory; + + if (FUsbGenericCreate) + FUsbGenericCreate(dev); + + if (dev->data == NULL) + { + FUSB_INFO("Detaching device not used by payload "); + FUsbDetachDev(dev->controller, dev->address); + } + + return; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb.h b/bsp/phytium/libraries/standalone/drivers/usb/fusb.h new file mode 100644 index 0000000000..7967cb1b49 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb.h @@ -0,0 +1,398 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb.h + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:22:25 + * Description:  This files is for definition of FUSB user interface + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_FUSB_H +#define DRIVERS_FUSB_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "ftypes.h" +#include "ferror_code.h" +#include "fassert.h" +#include "fusb_def.h" + +/************************** Constant Definitions *****************************/ +#define FUSB_SUCCESS FT_SUCCESS +#define FUSB_ERR_WAIT_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x0) +#define FUSB_ERR_INVALID_PARA FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x1) +#define FUSB_ERR_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x2) +#define FUSB_ERR_NON_INSTANCE FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x3) +#define FUSB_ERR_INVALID_DATA FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x4) +#define FUSB_ERR_DESC_PARSE_ERR FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x5) +#define FUSB_ERR_ALLOCATE_FAIL FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x6) +#define FUSB_ERR_TRANS_FAIL FT_MAKE_ERRCODE(ErrModBsp, ErrUsb, 0x7) + +/* SetAddress() recovery interval (USB 2.0 specification 9.2.6.3 */ +#define FUSB_SET_ADDRESS_MDELAY 2 + +/* + * USB sets an upper limit of 5 seconds for any transfer to be completed. + * + * Data originally from FUSB_HC_EHCI driver: + * Tested with some USB2.0 flash sticks: + * TUR turn around took about 2.2s for the slowest (13fe:3800), maximum + * of 250ms for the others. + * + * SET ADDRESS on xHCI controllers. + * The USB specification indicates that devices must complete processing + * of a SET ADDRESS request within 50 ms. However, some hubs were found + * to take more than 100 ms to complete a SET ADDRESS request on a + * downstream port. + */ +#define FUSB_USB_MAX_PROCESSING_TIME_US (5 * 1000 * 1000) +#define FUSB_FULL_LOW_SPEED_FRAME_US 1000 +#define FUSB_MAX_CTRL_NUM 1 +#define FUSB_MAX_DEV_TYPE_NUM 8 +#define FUSB_MAX_DEV_NUM 128 +#define FUSB_MAX_EP_NUM 32 +#define FUSB_MAX_SLOT_NUM FUSB_MAX_DEV_NUM + +#define FUSB_SLOT_ID_VALID(slot) ((0 <= (slot)) && (FUSB_MAX_SLOT_NUM > (slot))) + + +#define FUSB_DEFAULT_ALIGN 1 +#define FUSB_NO_DEV_ADDR -1 +#define FUSB_NO_HUB -1 +#define FUSB_NO_PORT -1 + +/**************************** Type Definitions *******************************/ + +typedef struct _FUsbDev FUsbDev; +typedef struct _FUsbHc FUsbHc; +typedef struct _FUsb FUsb; + +/* Transfer complete code for USB */ +enum +{ + FUSB_CC_ZERO_BYTES = 0, + FUSB_CC_SUCCESS = 1 + + /* for XHCI transfer complete code, please refer to e.g. FXHCI_CC_SUCCESS */ + /* be careful not define conflict CC code */ +}; + +/* less than 0 means error (implemented by usb Hc, e.g. FXhciTransCode), + greater or equal than 0 means bytes transfered */ +typedef int FUsbTransCode; + +typedef struct +{ + FUsbDev *dev; /* device instance of this endpoint */ + int endpoint; /* endpoint address ep0 = 0, epn = n */ + FUsbDirection direction; /* type or direction of ep */ + int toggle; /* ep state for some device to toggle */ + int maxpacketsize; /* max packet size for ep transfer */ + FUsbEpType type; /* transfer type of ep, control, bulk or so on */ + int interval; /* expressed as binary logarithm of the number + of microframes (i.e. t = 125us * 2^interval) */ +} FUsbEndpoint; /* encapsulates a single endpoint of an USB device */ +typedef struct +{ + const FUsbDescriptor *buf; + u32 buf_len; + boolean is_valid; + const FUsbDescriptor *end_pos; + const FUsbDescriptor *next_pos; + const FUsbDescriptor *cur_desc; + const FUsbDescriptor *err_pos; +} FUsbConfigParser; /* parser for configure descriptor */ + +typedef struct +{ +#define FUSB_USBSTR_MIN_LEN 4 + FUsbStringDescriptor *usb_str; +#define FUSB_STRDESC_BUF_MAX 64 + char str_buf[FUSB_STRDESC_BUF_MAX]; +} FUsbStringParser; /* parser for string descriptor */ + +typedef int FUsbDevAddr; + +typedef struct _FUsbDev +{ + FUsbHc *controller; /* Hc instance where device attached */ + FUsbEndpoint endpoints[FUSB_MAX_EP_NUM]; /* all Ep instance of device */ + int num_endp; /* num of Ep in use */ + FUsbDevAddr address; /* USB address */ + FUsbDevClass class; /* USB device class, e.g hid */ + int hub; /* hub where device is attached to */ + int port; /* port where device is attached */ + FUsbSpeed speed; /* speed type of device */ + void *data; /* private data for specific type of device */ + FUsbDeviceDescriptor *descriptor; /* device descriptor ever get from device hw */ + FUsbConfigurationDescriptor *configuration; /* configure descriptor followed with interface descriptor ever get from device hw */ + FUsbConfigParser config_parser; /* parser for configure descriptor */ + FUsbStringParser string_parser; /* parser for string descriptor */ + void (*init)(FUsbDev *dev); /* device init function of specific device type for register */ + void (*destroy)(FUsbDev *dev); /* device deinit function of specific device type for register */ + void (*poll)(FUsbDev *dev); /* device poll function of specific device type for register */ +} FUsbDev; /* encapsulates a single USB device */ + +typedef enum +{ + FUSB_HC_OHCI = 0, + FUSB_HC_UHCI = 1, + FUSB_HC_EHCI = 2, + FUSB_HC_XHCI = 3, + FUSB_HC_DWC2 = 4 +} FUsbHcType; + +typedef struct _FUsbHc +{ + uintptr reg_base; /* base address of Hc register */ + FUsb *usb; /* instance of USB system */ + FUsbHcType type; /* type of Hc, e.g XHCI */ + FUsbDev *devices[FUSB_MAX_DEV_NUM]; /* dev 0 is root hub, 127 is last addressable */ + + /* start(): Resume operation. */ + void (*start)(FUsbHc *controller); + /* stop(): Stop operation but keep controller initialized. */ + void (*stop)(FUsbHc *controller); + /* reset(): Perform a controller reset. The controller needs to + be (re)initialized afterwards to work (again). */ + FUsbTransCode(*reset)(FUsbHc *controller); + /* init(): Initialize a (previously reset) controller + to a working state. */ + void (*init)(FUsbHc *controller); + /* shutdown(): Stop operation, detach host controller and shutdown + this driver instance. After calling shutdown() any + other usage of this hci_t* is invalid. */ + void (*shutdown)(FUsbHc *controller); + + FUsbTransCode(*bulk)(FUsbEndpoint *ep, int size, u8 *data, int finalize); + FUsbTransCode(*control)(FUsbDev *dev, FUsbDirection pid, int dr_length, + void *devreq, int data_length, u8 *data); + void *(*create_intr_queue)(FUsbEndpoint *ep, int reqsize, int reqcount, int reqtiming); + void (*destroy_intr_queue)(FUsbEndpoint *ep, void *queue); + u8 *(*poll_intr_queue)(void *queue); + void *instance; /* instance to specific Hc implementation, e.g XHCI */ + + /* set_address(): Tell the USB device its address (xHCI + controllers want to do this by + themselves). Also, allocate the FUsbDev + structure, initialize enpoint 0 + (including MPS) and return it. */ + FUsbDev *(*set_address)(FUsbHc *controller, FUsbSpeed speed, + int hubport, int hubaddr); + /* finish_device_config(): Another hook for xHCI, returns 0 on success. */ + int (*finish_device_config)(FUsbDev *dev); + /* destroy_device(): Finally, destroy all structures that + were allocated during set_address() + and finish_device_config(). */ + void (*destroy_device)(FUsbHc *controller, int devaddr); +} FUsbHc; /* encapsulates a single USB host */ + +typedef struct +{ + void *(*malloc_align)(size_t size, size_t align); + void (*free)(void *mem); +} FUsbMemAllocator; /* memory allocator used in USB system */ + +typedef struct +{ + u32 instance_id; /* id for this USB system */ + uintptr base_addr; /* base addr of Hc register, set as 0 for pci-usb */ + u32 irq_num; + u32 irq_priority; + FUsbMemAllocator allocator; /* memory allocator to support dynamic memory */ +} FUsbConfig; /* configure data of the USB system */ + +typedef enum +{ + FUSB_STANDARD_INTERFACE, + FUSB_VENDOR_SPECIFIED +} FUsbDevCategory; + +typedef struct +{ + FUsbDevCategory category; + FUsbDevClass class; + u32 sub_class; + u32 protocol; +} FUsbDevIndex; + +typedef void (* FUsbDevInitHandler)(FUsbDev *dev); + +typedef struct +{ + FUsbDevIndex index; + FUsbDevInitHandler handler; +} FUsbDevInitFunc; + +typedef struct _FUsb +{ + FUsbConfig config; /* configuration of USB system */ + void *pcie_instance; /* NULL if unused */ + void *pcie_info[FUSB_MAX_CTRL_NUM]; /* NULL if unused */ + FUsbHc *hc; /* first hc, there might have multiple hc in pcie-mode */ + /* hook to set init function for specific device type */ + FUsbDevInitFunc dev_init[FUSB_MAX_DEV_TYPE_NUM]; + u32 dev_init_num; /* number of init function in used */ + u32 is_ready; /* indicator of system okay */ +} FUsb; /* instance of the USB system */ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +static FUsbDev *FUsbGetDevEntry(FUsbHc *controller, int dev_address) +{ + FASSERT(controller && controller->devices); + FUsbDev *result = NULL; + u32 loop; + + for (loop = 0; loop < FUSB_MAX_DEV_NUM; loop++) + { + if ((NULL != controller->devices[loop]) && (dev_address == controller->devices[loop]->address)) + { + result = controller->devices[loop]; + break; + } + } + + return result; +} + +/* + * returns the speed is above FUSB_SUPER_SPEED or not + */ +static inline boolean FUsbIsSuperSpeed(FUsbSpeed speed) +{ + return (speed == FUSB_SUPER_SPEED || speed == FUSB_SUPER_SPEED_PLUS); +} + +static inline unsigned char FUsbGenerateReqType(FUsbReqDirection dir, FUsbReqType type, FUsbReqRecpient recp) +{ + return (dir << 7) | (type << 5) | recp; +} + +/************************** Function Prototypes ******************************/ +/* 获取USB的默认配置 */ +const FUsbConfig *FUsbLookupConfig(u32 instance_id); + +/* 初始化USB实例 */ +FError FUsbCfgInitialize(FUsb *instance, const FUsbConfig *config); + +/* 去初始化USB实例 */ +void FUsbDeInitialize(FUsb *instance); + +/* 轮询所有的USB控制器连接的所有设备, 更新设备拓扑 */ +void FUsbPoll(FUsb *instance); + +/* 关闭所有的USB控制器,移除所有连接的设备 */ +void FUsbExit(FUsb *instance); + +/* 从USB内存池分配一块内存,并清零分配的空间 */ +void *FUsbMempAllocate(FUsb *instance, size_t size, size_t align); + +/* 释放从USB内存池分配的空间 */ +void FUsbMempFree(FUsb *instance, void *ptr); + +/* 指定特定USB设备的初始化函数,供创建USB设备实例时使用 */ +FError FUsbAssignDevInitFunc(FUsb *instance, const FUsbDevIndex *index, FUsbDevInitHandler handler); + +/* 获取USB控制器上连接的所有USB设备实例 */ +size_t FUsbGetAllDevEntries(FUsbHc *controller, FUsbDev *devs[], size_t max_dev_num); + +/* 标准USB主机请求,使能设备/接口/端点的某个特性 */ +FUsbTransCode FUsbSetFeature(FUsbDev *dev, int endp, int feature, int rtype); + +/* 标准USB主机请求,获取设备/接口/端点的状态 */ +FUsbTransCode FUsbGetStatus(FUsbDev *dev, int endp, int rtype, int len, void *data); + +/* 标准USB主机请求,获取指定描述符 */ +FUsbTransCode FUsbGetDescriptor(FUsbDev *dev, int rtype, FUsbDescriptorType descType, int descIdx, + void *data, size_t len); + +/* USB主机请求,获取字符串描述符 */ +FUsbTransCode FUsbGetStringDescriptor(FUsbDev *dev, int rtype, FUsbDescriptorType desc_type, int desc_idx, int lang_id, + void *data, size_t len); + +/* 标准USB主机请求,设置配置值 */ +FUsbTransCode FUsbSetConfiguration(FUsbDev *dev); + +/* 标准USB主机请求,去使能设备/接口/端点的某个特性 */ +FUsbTransCode FUsbClearFeature(FUsbDev *dev, int endp, int feature, int rtype); + +/* 打印描述符信息 */ +void FUsbDumpAllDescriptors(FUsbDev *dev); + +/* 从USB主机移除指定USB设备(USB设备驱动使用) */ +void FUsbDetachDev(FUsbHc *controller, int devno); + +/* 向USB主机添加USB设备(USB设备驱动使用) */ +FUsbDevAddr FUsbAttachDev(FUsbHc *controller, int hubaddress, int port, + FUsbSpeed speed); + +/** + * To be implemented by application. It's called by the USB + * stack just before iterating over known devices to poll them for + * status change. + */ +void __attribute__((weak)) FUsbPollPrepare(FUsb *instance); + +/** + * To be implemented by application. It's called by the USB + * stack just before exit known Hc. + */ +void __attribute__((weak)) FUsbExitPrepare(FUsb *instance); + +/** + * To be implemented by application. It's called by the USB stack + * when a new USB device is found which isn't claimed by a built in driver, + * so the client has the chance to know about it. + * + * @param dev descriptor for the USB device + */ +void __attribute__((weak)) FUsbGenericCreate(FUsbDev *dev); + +/** + * To be implemented by application. It's called by the USB stack + * when it finds out that a USB device is removed which wasn't claimed by a + * built in driver. + * + * @param dev descriptor for the USB device + */ +void __attribute__((weak)) FUsbGenericRemove(FUsbDev *dev); + +/* 支持带TAG的内存分配,用于跟踪动态内存使用 */ +#ifdef FMEMP_TAG_DEBUG +void *FUsbMempAllocateTag(FUsb *instance, size_t size, size_t align, const char *file, unsigned long line, const char *msg); +void FUsbMempFreeTag(FUsb *instance, void *ptr); + +#define FUSB_ALLOCATE(instance, size, align) FUsbMempAllocateTag((instance), (size), (align), __FILE__, __LINE__, "") +#define FUSB_FREE(instance, ptr) FUsbMempFreeTag((instance), (ptr)) +#else +#define FUSB_ALLOCATE(instance, size, align) FUsbMempAllocate((instance), (size), (align)) +#define FUSB_FREE(instance, ptr) FUsbMempFree((instance), (ptr)) +#endif + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_debug.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_debug.c new file mode 100644 index 0000000000..7870df0f4d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_debug.c @@ -0,0 +1,230 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_debug.c + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:18:04 + * Description:  This files is for implmentation of USB debug utilities + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include "fdebug.h" + +#include "fusb_private.h" + +#define FUSB_DEBUG_TAG "FUSB_DEBUG" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +static inline boolean FUsbIsValidStringIndex(u8 id) +{ + return (0 != id) && (0xff != id); +} + +/** + * @name: FUsbDumpAllDescriptors + * @msg: 打印USB设备的描述符信息(设备描述符,配置描述符和接口描述符) + * @return {*} + * @param {FUsbDev} *dev, USB设备实例,已完成初始化 + */ +void FUsbDumpAllDescriptors(FUsbDev *dev) +{ + FError ret = FUSB_SUCCESS; + if ((NULL == dev) || (NULL == dev->configuration)) + return; + + const FUsbDeviceDescriptor *dev_desc = NULL; + const FUsbConfigurationDescriptor *config_desc = NULL; + const FUsbInterfaceDescriptor *if_desc = NULL; + FASSERT(dev->controller && dev->controller->usb); + FUsb *instance = dev->controller->usb; + u8 if_num = 0; + u8 func_id = 0; + FUsbConfigParser *parser = &dev->config_parser; + + dev_desc = dev->descriptor; + config_desc = dev->configuration; + + /* init descriptor parser in each dump */ + ret = FUsbSetupConfigParser(dev, config_desc, config_desc->wTotalLength); + FUsbSetupStringParser(dev); + if (FUSB_SUCCESS != ret) + return; + + if (FUsbIsValidStringIndex(dev_desc->iManufacturer)) + { + ret = FUsbSearchStringDescriptor(instance, dev, dev_desc->iManufacturer); + if (FUSB_SUCCESS == ret) + printf(" Manufacturer: %s\r\n", FUsbGetString(dev)); + } + + if (FUsbIsValidStringIndex(dev_desc->iProduct)) + { + ret = FUsbSearchStringDescriptor(instance, dev, dev_desc->iProduct); + if (FUSB_SUCCESS == ret) + printf(" Product: %s\r\n", FUsbGetString(dev)); + } + + if (FUsbIsValidStringIndex(dev_desc->iSerialNumber)) + { + ret = FUsbSearchStringDescriptor(instance, dev, dev_desc->iSerialNumber); + if (FUSB_SUCCESS == ret) + printf(" Serial No.: %s\r\n", FUsbGetString(dev)); + } + + while (NULL != (if_desc = (const FUsbInterfaceDescriptor *)FUsbGetDescriptorFromParser(parser, FUSB_DESC_TYPE_INTERFACE))) + { + if (if_desc->bInterfaceNumber > if_num) + { + if_num = if_desc->bInterfaceNumber; + } + + if (if_desc->bInterfaceNumber != if_num) + { + FUSB_INFO("Alternate setting %u ignored", if_desc->bInterfaceNumber); + continue; + } + + if (FUsbIsValidStringIndex(if_desc->iInterface)) + { + ret = FUsbSearchStringDescriptor(instance, dev, if_desc->iInterface); + if (FUSB_SUCCESS == ret) + printf(" Interface: %s\r\n", FUsbGetString(dev)); + } + + } + + /* revoke descriptor parser after used */ + FUsbRevokeConfigParser(dev); + FUsbRevokeStringParser(dev); + + return; +} + +/** + * @name: FUsbDumpDeviceDescriptor + * @msg: 打印设备描述符信息 + * @return {*} + * @param {FUsbDeviceDescriptor} *descriptor, 设备描述符 + */ +void FUsbDumpDeviceDescriptor(const FUsbDeviceDescriptor *descriptor) +{ + if (NULL != descriptor) + { + FUSB_INFO(""); + FUSB_INFO("===Device Descriptor"); + FUSB_INFO(" bLength: %d", descriptor->bLength); + FUSB_INFO(" bDescriptorType: %d", descriptor->bDescriptorType); + FUSB_INFO(" bcdUSB: 0x%x", descriptor->bcdUSB); + FUSB_INFO(" bDeviceClass: %d", descriptor->bDeviceClass); + FUSB_INFO(" bDeviceSubClass: %d", descriptor->bDeviceSubClass); + FUSB_INFO(" bDeviceProtocol: %d", descriptor->bDeviceProtocol); + FUSB_INFO(" bMaxPacketSize0: %d", descriptor->bMaxPacketSize0); + FUSB_INFO(" idVendor: 0x%x", descriptor->idVendor); + FUSB_INFO(" idProduct: 0x%x", descriptor->idProduct); + FUSB_INFO(" bcdDevice: 0x%x", descriptor->bcdDevice); + FUSB_INFO(" iManufacturer: %d", descriptor->iManufacturer); + FUSB_INFO(" iSerialNumber: %d", descriptor->iSerialNumber); + FUSB_INFO(" bNumConfigurations: %d", descriptor->bNumConfigurations); + FUSB_INFO(""); + } +} + +/** + * @name: FUsbDumpConfigDescriptor + * @msg: 打印配置描述符信息 + * @return {*} + * @param {FUsbConfigurationDescriptor} *descriptor, 配置描述符 + */ +void FUsbDumpConfigDescriptor(const FUsbConfigurationDescriptor *descriptor) +{ + if (NULL != descriptor) + { + FUSB_INFO(""); + FUSB_INFO("===Configure Descriptor"); + FUSB_INFO(" bLength: %d", descriptor->bLength); + FUSB_INFO(" bDescriptorType: %d", descriptor->bDescriptorType); + FUSB_INFO(" wTotalLength: %d", descriptor->wTotalLength); + FUSB_INFO(" bNumInterfaces: %d", descriptor->bNumInterfaces); /* 该配置下有多少个接口描述符 */ + FUSB_INFO(" bConfigurationValue: %d", descriptor->bConfigurationValue); /* 该配置描述符的配置号信息 */ + FUSB_INFO(" iConfiguration: %d", descriptor->iConfiguration); + FUSB_INFO(" bmAttributes: 0x%x", descriptor->bmAttributes); + FUSB_INFO(" remote-weakup: %s", + (descriptor->bmAttributes & FUSB_CONFIG_DESC_ATTR_REMOTE_WEAKUP) ? "yes" : "no"); + FUSB_INFO(" self-power: %s", + (descriptor->bmAttributes & FUSB_CONFIG_DESC_ATTR_SELF_POWER) ? "yes" : "no"); + FUSB_INFO(" usb1.0-compatible: %s", + (descriptor->bmAttributes & FUSB_CONFIG_DESC_ATTR_USB1_COMPATIABLE) ? "yes" : "no"); + FUSB_INFO(" max power: %dmA", 2 * (descriptor->bMaxPower)); + FUSB_INFO(" "); + } +} + +/** + * @name: FUsbDumpInterfaceDescriptor + * @msg: 打印接口描述符信息 + * @return {*} + * @param {FUsbInterfaceDescriptor} *descriptor, 接口描述符 + */ +void FUsbDumpInterfaceDescriptor(const FUsbInterfaceDescriptor *descriptor) +{ + if (NULL != descriptor) + { + FUSB_INFO(""); + FUSB_INFO("===Interface Descriptor"); + FUSB_INFO(" bLength: %d", descriptor->bLength); + FUSB_INFO(" bDescriptorType: %d", descriptor->bDescriptorType); + FUSB_INFO(" bInterfaceNumber: %d", descriptor->bInterfaceNumber); + FUSB_INFO(" bAlternateSetting: %d", descriptor->bAlternateSetting); + FUSB_INFO(" bNumEndpoints: %d", descriptor->bNumEndpoints); + FUSB_INFO(" bInterfaceClass: %d", descriptor->bInterfaceClass); + FUSB_INFO(" bInterfaceSubClass: %d", descriptor->bInterfaceSubClass); + FUSB_INFO(" bInterfaceProtocol: %d", descriptor->bInterfaceProtocol); + FUSB_INFO(" iInterface: %d", descriptor->iInterface); + FUSB_INFO(" "); + } +} + +/** + * @name: FUsbDumpEndpointDescriptor + * @msg: 打印端点描述符信息 + * @return {*} + * @param {FUsbEndpointDescriptor} *descriptor, 端点描述符 + */ +void FUsbDumpEndpointDescriptor(const FUsbEndpointDescriptor *descriptor) +{ + if (NULL != descriptor) + { + FUSB_INFO(""); + FUSB_INFO("===Endpoint Descriptor"); + FUSB_INFO(" bLength: %d", descriptor->bLength); + FUSB_INFO(" bDescriptorType: %d", descriptor->bDescriptorType); + FUSB_INFO(" bEndpointAddress: %d", descriptor->bEndpointAddress); + FUSB_INFO(" ep num: %d", FUSB_EP_DESC_EP_NUM(descriptor->bEndpointAddress)); + FUSB_INFO(" ep dir: %s", + (FUSB_EP_DESC_EP_DIR_IN & descriptor->bEndpointAddress) ? "IN" : "OUT"); + FUSB_INFO(" bmAttributes: 0x%x", descriptor->bmAttributes); + FUSB_INFO(" trans type: %d ([0]-%s, [1]-%s, [2]-%s, [3]-%s)", + FUSB_EP_DESC_TRANS_TYPE(descriptor->bmAttributes), + "control", "isochronous", "bulk", "interrupt"); + FUSB_INFO(" wMaxPacketSize: %d", descriptor->wMaxPacketSize); + FUSB_INFO(" bInterval: %d", descriptor->bInterval); + FUSB_INFO(" "); + } +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_def.h b/bsp/phytium/libraries/standalone/drivers/usb/fusb_def.h new file mode 100644 index 0000000000..5d66390d21 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_def.h @@ -0,0 +1,288 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_def.h + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:18:24 + * Description:  This files is for definition of spec defined USB data structure + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_FUSB_DEF_H +#define DRIVERS_FUSB_DEF_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "ftypes.h" + +/************************** Constant Definitions *****************************/ +typedef enum +{ + FUSB_UNKNOWN_SPEED = -1, + FUSB_FULL_SPEED = 0, + FUSB_LOW_SPEED = 1, + FUSB_HIGH_SPEED = 2, + FUSB_SUPER_SPEED = 3, + FUSB_SUPER_SPEED_PLUS = 4, +} FUsbSpeed; + +typedef enum +{ + FUSB_REQ_HOST_TO_DEVICE = 0, + FUSB_REQ_DEVICE_TO_HOST = 1 +} FUsbReqDirection; + +typedef enum +{ + FUSB_REQ_TYPE_STANDARD = 0, + FUSB_REQ_TYPE_CLASS = 1, + FUSB_REQ_TYPE_VENDOR = 2, + FUSB_REQ_TYPE_RESERVED = 3 +} FUsbReqType; + +typedef enum +{ + FUSB_REQ_RECP_DEV = 0, + FUSB_REQ_RECP_IF = 1, + FUSB_REQ_RECP_EP = 2, + FUSB_REQ_RECP_OTHER = 3 +} FUsbReqRecpient; + +/* refer to Table 9-5. Descriptor Types in USB spec. for details */ +typedef enum +{ + FUSB_DESC_TYPE_NONE = 0, + FUSB_DESC_TYPE_DEVICE = 1, + FUSB_DESC_TYPE_CONFIG = 2, + FUSB_DESC_TYPE_STRING = 3, + FUSB_DESC_TYPE_INTERFACE = 4, + FUSB_DESC_TYPE_ENDPOINT = 5, + FUSB_DESC_TYPE_HUB = 41, + FUSB_DESC_TYPE_SUPER_SPEED_HUB = 42 +} FUsbDescriptorType; + +typedef enum +{ + FUSB_GET_STATUS = 0, + FUSB_CLEAR_FEATURE = 1, + FUSB_SET_FEATURE = 3, + FUSB_SET_ADDRESS = 5, + FUSB_GET_DESCRIPTOR = 6, + FUSB_SET_DESCRIPTOR = 7, + FUSB_GET_CONFIGURATION = 8, + FUSB_SET_CONFIGURATION = 9, + FUSB_GET_INTERFACE = 10, + FUSB_SET_INTERFACE = 11, + FUSB_SYNCH_FRAME = 12 +} FUsbRequestCode; + +typedef enum +{ + FUSB_ENDPOINT_HALT = 0, + FUSB_DEVICE_REMOTE_WAKEUP = 1, + FUSB_TEST_MODE = 2 +} FUsbFeatureSelectors; + +typedef enum +{ + FUSB_SETUP, + FUSB_IN, + FUSB_OUT +} FUsbDirection; + +typedef enum +{ + FUSB_CONTROL_EP = 0, + FUSB_ISOCHRONOUS_EP = 1, + FUSB_BULK_EP = 2, + FUSB_INTERRUPT_EP = 3 +} FUsbEpType; + +typedef enum +{ + FUSB_UNKOWN_DEVICE = 0x0, + FUSB_AUDIO_DEVICE = 0x01, + FUSB_COMM_DEVICE = 0x02, + FUSB_HID_DEVICE = 0x03, + FUSB_PHYSICAL_DEVICE = 0x05, + FUSB_IMAGE_DEVICE = 0x06, + FUSB_PRINTER_DEVICE = 0x07, + FUSB_MASS_STORAGE_DEVICE = 0x08, + FUSB_HUB_DEVICE = 0x09, +} FUsbDevClass; /* definition of device class */ + +/**************************** Type Definitions *******************************/ + +/* following data structure is defined according to spec. name their member + may not compliant with code convention */ +typedef struct +{ + unsigned char bDescLength; + unsigned char bDescriptorType; + unsigned char bNbrPorts; /* Number of downstream facing ports supports */ + union + { + struct + { + unsigned long logicalPowerSwitchingMode: 2; /* BIT[1:0] */ + unsigned long isCompoundDevice: 1; /* BIT[2] */ + unsigned long overcurrentProtectionMode: 2; /* BIT[4:3] */ + unsigned long ttThinkTime: 2; /* BIT[6:5] */ + unsigned long arePortIndicatorsSupported: 1; /* BIT[7] */ + unsigned long: 8; + } __attribute__((packed)); + unsigned short wHubCharacteristics; + } __attribute__((packed)); + unsigned char bPowerOn2PwrGood; /* in 2 ms intervals */ + unsigned char bHubContrCurrent; /* max current requirements */ + char DeviceRemovable[]; /* indicates if a port has a removable device attached */ +} __attribute__((packed)) FUsbHubDescriptor; + +typedef struct +{ + unsigned char bLength; + unsigned char bDescriptorType; + unsigned short bcdUSB; + unsigned char bDeviceClass; + unsigned char bDeviceSubClass; + unsigned char bDeviceProtocol; + unsigned char bMaxPacketSize0; + unsigned short idVendor; + unsigned short idProduct; + unsigned short bcdDevice; + unsigned char iManufacturer; + unsigned char iProduct; + unsigned char iSerialNumber; + unsigned char bNumConfigurations; +} __attribute__((packed)) FUsbDeviceDescriptor; + +typedef struct +{ + unsigned char bLength; + unsigned char bDescriptorType; + unsigned short wTotalLength; + unsigned char bNumInterfaces; + unsigned char bConfigurationValue; + unsigned char iConfiguration; + unsigned char bmAttributes; +#define FUSB_CONFIG_DESC_ATTR_REMOTE_WEAKUP BIT(5) /* 1: remote wakeup feature */ +#define FUSB_CONFIG_DESC_ATTR_SELF_POWER BIT(6) /* 1: self-powered 0: bus-powered */ +#define FUSB_CONFIG_DESC_ATTR_USB1_COMPATIABLE BIT(7) /* 1: compatibility with USB 1.0 */ + unsigned char bMaxPower; + /* configuration descriptor may follow more buffers, need to allocate dynamic memory for all contents */ +} __attribute__((packed)) FUsbConfigurationDescriptor; + +typedef struct +{ + unsigned char bLength; + unsigned char bDescriptorType; + unsigned char bInterfaceNumber; + unsigned char bAlternateSetting; + unsigned char bNumEndpoints; + unsigned char bInterfaceClass; + unsigned char bInterfaceSubClass; + unsigned char bInterfaceProtocol; + unsigned char iInterface; +} __attribute__((packed)) FUsbInterfaceDescriptor; + +typedef struct +{ + unsigned char bLength; + unsigned char bDescriptorType; + unsigned char bEndpointAddress; + /* Low-speed devices can have a maximum of 3 endpoint, other devices can have 16 (0–15) */ +#define FUSB_EP_DESC_EP_NUM(x) (GENMASK(3, 0) & (x)) /* endpoint number */ +#define FUSB_EP_DESC_EP_DIR_IN BIT(7) /* direction, 0: OUT, 1: IN */ + unsigned char bmAttributes; +#define FUSB_EP_DESC_TRANS_TYPE(x) (GENMASK(1, 0) & (x)) +#define FUSB_EP_DESC_TRANS_CTRL 0b00 /* control */ +#define FUSB_EP_DESC_TRANS_ISOC 0b01 /* isochronous */ +#define FUSB_EP_DESC_TRANS_BULK 0b10 /* bulk */ +#define FUSB_EP_DESC_TRANS_INTR 0b11 /* interrupt */ + unsigned short wMaxPacketSize; +#define FUSB_EP_DESC_MAX_PACKET_SZ GENMASK(10, 0) + unsigned char bInterval; +} __attribute__((packed)) FUsbEndpointDescriptor; + +typedef union +{ + struct + { + u8 len; + u8 type; + } header; +#define FUSB_DESCRIPTOR_HEADER_SIZE 2 + FUsbConfigurationDescriptor configuration; + FUsbInterfaceDescriptor interface; + FUsbEndpointDescriptor endpoint; +} __attribute__((packed)) FUsbDescriptor; + +typedef struct +{ + unsigned char bLength; + unsigned char bDescriptorType; + unsigned short bcdHID; + unsigned char bCountryCode; + unsigned char bNumDescriptors; + unsigned char bReportDescriptorType; + unsigned short wReportDescriptorLength; +} __attribute__((packed)) FUsbHidDescriptor; + +typedef struct +{ + u8 len; /* Descriptor size in bytes (variable) */ + u8 type; /* The constant String (0x03 DESCRIPTOR_STRING) */ + u16 string[0]; /* Unicode UTF- 16LE string */ +} __attribute__((packed)) FUsbStringDescriptor; + +typedef struct +{ + union + { + struct + { + FUsbReqRecpient req_recp: 5; + FUsbReqType req_type: 2; + FUsbReqDirection data_dir: 1; + } __attribute__((packed)); + unsigned char bmRequestType; + } __attribute__((packed)); + unsigned char bRequest; + unsigned short wValue; + unsigned short wIndex; + unsigned short wLength; +} __attribute__((packed)) FUsbDevReq; + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FUSB_DEFAULT_LANG_ID 0x409 /* English */ + +/************************** Function Prototypes ******************************/ + + +#ifdef __cplusplus +} +#endif + + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_dev.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_dev.c new file mode 100644 index 0000000000..2d3fdf0dbd --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_dev.c @@ -0,0 +1,439 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_dev.c + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:18:45 + * Description:  This files is for USB device function implementation + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include + +#include "fdebug.h" + +#include "fusb_private.h" + +#define FUSB_DEBUG_TAG "FUSB-DEV" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +#define FUSB_DR_DESC FUsbGenerateReqType(FUSB_REQ_DEVICE_TO_HOST, FUSB_REQ_TYPE_STANDARD, FUSB_REQ_RECP_DEV) + +#define FUSB_SKIP_BYTES(desc, bytes) ((FUsbDescriptor *) ((u8 *) (desc) + (bytes))) +#define FUSB_CONFIG_DESC_SIZE 512 /* best guess */ + +static void FUsbNopDevDestory(FUsbDev *dev) +{ + FUsbNopDevInit(dev); + dev->address = FUSB_NO_DEV_ADDR; + dev->hub = FUSB_NO_HUB; + dev->port = FUSB_NO_PORT; +} + +static void FUsbNopDevPoll(FUsbDev *dev) +{ + return; +} + +/** + * @name: FUsbNopDevInit + * @msg: 默认的USB设备初始化函数 + * @return {*} + * @param {FUsbDev} *dev, USB设备实例 + */ +void FUsbNopDevInit(FUsbDev *dev) +{ + dev->descriptor = NULL; + dev->configuration = NULL; + dev->destroy = FUsbNopDevDestory; + dev->poll = FUsbNopDevPoll; +} + +static inline boolean FUsbParserIsValid(const FUsbConfigParser *parser) +{ + FASSERT(parser); + return parser->is_valid; +} + +static FError FUsbParserDescriptor(FUsbConfigParser *parser) +{ + FASSERT(parser && parser->buf); + const FUsbDescriptor *cur_pos = parser->buf; + const FUsbDescriptor *desc_end; + FUsbDescriptorType last_desc_type = FUSB_DESC_TYPE_NONE; + FUsbDescriptorType desc_type; + u8 desc_len, exp_len, alt_len; + FError ret = FUSB_SUCCESS; + + while (FUSB_SKIP_BYTES(cur_pos, FUSB_DESCRIPTOR_HEADER_SIZE) < parser->end_pos) + { + /* get length and type of descriptor */ + desc_len = cur_pos->header.len; + desc_type = cur_pos->header.type; + + desc_end = FUSB_SKIP_BYTES(cur_pos, desc_len); + if (desc_end > parser->end_pos) + { + FUSB_ERROR("Parse descriptor out of boundary !!!"); + parser->err_pos = cur_pos; + ret = FUSB_ERR_DESC_PARSE_ERR; + goto err_handle; + } + + exp_len = 0; + alt_len = 0; + switch (desc_type) + { + case FUSB_DESC_TYPE_CONFIG: + if (FUSB_DESC_TYPE_NONE != last_desc_type) + { + FUSB_ERROR("Configuration descriptor must be the first !!!"); + parser->err_pos = cur_pos; + ret = FUSB_ERR_DESC_PARSE_ERR; + goto err_handle; + } + exp_len = sizeof(FUsbConfigurationDescriptor); + break; + case FUSB_DESC_TYPE_INTERFACE: + if (FUSB_DESC_TYPE_NONE == last_desc_type) + { + FUSB_ERROR("Interface descriptor must not be the first !!!"); + parser->err_pos = cur_pos; + ret = FUSB_ERR_DESC_PARSE_ERR; + goto err_handle; + } + exp_len = sizeof(FUsbInterfaceDescriptor); + break; + case FUSB_DESC_TYPE_ENDPOINT: + if ((FUSB_DESC_TYPE_NONE == last_desc_type) || + (FUSB_DESC_TYPE_CONFIG == last_desc_type)) + { + FUSB_ERROR("Endpoint descriptor must follow interface descriptor !!!"); + parser->err_pos = cur_pos; + ret = FUSB_ERR_DESC_PARSE_ERR; + goto err_handle; + } + break; + default: + FUSB_DEBUG("Descriptor %d not handled !!!", desc_type); + break; + } + + if (((exp_len != 0) && (desc_len != exp_len)) && + ((alt_len == 0) || (desc_len != alt_len))) + { + FUSB_ERROR("Descriptor %d invalid !!!", desc_type); + parser->err_pos = cur_pos; + ret = FUSB_ERR_DESC_PARSE_ERR; + goto err_handle; + } + + last_desc_type = desc_type; + cur_pos = desc_end; + } + + if (cur_pos != parser->end_pos) + { + parser->err_pos = cur_pos; + ret = FUSB_ERR_DESC_PARSE_ERR; + goto err_handle; + } + +err_handle: + if (FUSB_SUCCESS == ret) + { + parser->is_valid = TRUE; + } + + return ret; +} + +/** + * @name: FUsbSetupConfigParser + * @msg: 配置USB配置描述符解析器 + * @return {*} + * @param {FUsbDev} *dev, USB设备实例 + * @param {void} *buf, 配置描述符缓冲区 + * @param {u32} buf_len, 配置描述符缓冲区长度 + */ +FError FUsbSetupConfigParser(FUsbDev *dev, const void *buf, u32 buf_len) +{ + FASSERT(dev && buf && (buf_len > 0)); + const FUsbConfigurationDescriptor *config_desc; + FUsbConfigParser *parser = &dev->config_parser; + + memset(parser, 0, sizeof(*parser)); + + parser->buf = buf; + parser->buf_len = buf_len; + parser->is_valid = FALSE; + parser->end_pos = FUSB_SKIP_BYTES(parser->buf, parser->buf_len); + parser->next_pos = parser->buf; + parser->cur_desc = NULL; + parser->err_pos = parser->buf; + + if ((parser->buf_len < sizeof(u32)) || (parser->buf_len > FUSB_CONFIG_DESC_SIZE)) + { + FUSB_ERROR("Invalid buffer length !!!"); + return FUSB_ERR_INVALID_DATA; + } + + /* input buffer must start with config desc */ + config_desc = (FUsbConfigurationDescriptor *)parser->buf; + if ((config_desc->bLength != sizeof(FUsbConfigurationDescriptor)) || + (config_desc->bDescriptorType != FUSB_DESC_TYPE_CONFIG) || + (config_desc->wTotalLength > parser->buf_len)) + { + FUSB_ERROR("Invalid configuration descriptor !!!"); + return FUSB_ERR_INVALID_DATA; + } + + /* adjust end position */ + if (config_desc->wTotalLength < parser->buf_len) + { + parser->end_pos = FUSB_SKIP_BYTES(parser->buf, config_desc->wTotalLength); + } + + return FUsbParserDescriptor(parser); +} + +/** + * @name: FUsbRevokeConfigParser + * @msg: 去初始化USB配置描述符解析器 + * @return {*} + * @param {FUsbDev} *dev, USB设备实例 + */ +void FUsbRevokeConfigParser(FUsbDev *dev) +{ + FASSERT(dev); + memset(&dev->config_parser, 0, sizeof(dev->config_parser)); + return; +} + +/** + * @name: FUsbGetDescriptorFromParser + * @msg: 从配置描述符解析器中获取指定类型的描述符(端点描述符/接口描述符) + * @return {const FUsbDescriptor *} 获取的描述符 + * @param {FUsbConfigParser} *parser, 配置描述符解析器 + * @param {FUsbDescriptorType} type, 获取描述符的类型 + */ +const FUsbDescriptor *FUsbGetDescriptorFromParser(FUsbConfigParser *parser, FUsbDescriptorType type) +{ + FASSERT(parser); + if (!FUsbParserIsValid(parser)) + { + FUSB_ERROR("Config parse is not valid !!!"); + return NULL; + } + + const FUsbDescriptor *result = NULL; + FUsbDescriptorType desc_type; + u8 desc_len; + const FUsbDescriptor *desc_end; + + /* travesal all descriptors */ + while (parser->next_pos < parser->end_pos) + { + desc_len = parser->next_pos->header.len; + desc_type = parser->next_pos->header.type; + + desc_end = FUSB_SKIP_BYTES(parser->next_pos, desc_len); + if (desc_end > parser->end_pos) + break; + + if ((FUSB_DESC_TYPE_ENDPOINT == type) && + (FUSB_DESC_TYPE_INTERFACE == desc_type)) + break; /* there is no chance to find endpoint desc after interface desc */ + + if (type == desc_type) + { + /* target desc found !!! */ + result = parser->next_pos; + parser->next_pos = desc_end; + break; + } + + parser->next_pos = desc_end;/* check next one */ + } + + if (NULL != result) + { + parser->err_pos = result; + } + + parser->cur_desc = result; + return result; +} + +/** + * @name: FUsbSetupStringParser + * @msg: 初始化字符串描述符解析器 + * @return {*} + * @param {FUsbDev} *dev, USB设备实例 + */ +void FUsbSetupStringParser(FUsbDev *dev) +{ + FASSERT(dev); + FUsbStringParser *parser = &dev->string_parser; + + if (NULL != parser->usb_str) + { + FUSB_WARN("String descriptor exists, might cause memory leakage !!!"); + } + + parser->usb_str = NULL; + memset(parser->str_buf, 0, sizeof(parser->str_buf)); + + return; +} + +/** + * @name: FUsbRevokeStringParser + * @msg: 去初始化字符串描述符解析器 + * @return {*} + * @param {FUsbDev} *dev, USB设备实例 + */ +void FUsbRevokeStringParser(FUsbDev *dev) +{ + FASSERT(dev); + FUsbStringParser *parser = &dev->string_parser; + FASSERT(dev->controller && dev->controller->usb); + FUsb *instance = dev->controller->usb; + + if (NULL != parser->usb_str) + { + FUSB_FREE(instance, parser->usb_str); + parser->usb_str = NULL; + } + + return; +} + +/** + * @name: FUsbSearchStringDescriptor + * @msg: 检索字符串描述符,保存在FUsbStringParser结构中 + * @return {*} + * @param {FUsb} *instance, USB实例 + * @param {FUsbDev} *dev, USB设备实例 + * @param {u8} id, 要获取字符串描述符的ID + */ +FError FUsbSearchStringDescriptor(FUsb *instance, FUsbDev *dev, u8 id) +{ + FASSERT(instance && dev); + FUsbStringParser *parser = &dev->string_parser; + const FUsbStringDescriptor *usb_str = NULL; + u8 total_len; + u8 char_num; + u16 character; + + /* re-malloc usb string desc buffer with length 4 */ + if (NULL != parser->usb_str) + { + FUSB_FREE(instance, parser->usb_str); + parser->usb_str = NULL; + } + + parser->usb_str = FUSB_ALLOCATE(instance, FUSB_USBSTR_MIN_LEN, FUSB_DEFAULT_ALIGN); + if (NULL == parser->usb_str) + return FUSB_ERR_ALLOCATE_FAIL; + + /* get header of string for the full length */ + if (FUsbGetStringDescriptor(dev, FUSB_DR_DESC, FUSB_DESC_TYPE_STRING, id, FUSB_DEFAULT_LANG_ID, + parser->usb_str, FUSB_USBSTR_MIN_LEN) < 0) + { + FUSB_ERROR("Parse string descriptor failed (len: %d) !!!", FUSB_USBSTR_MIN_LEN); + return FUSB_ERR_DESC_PARSE_ERR; + } + + /* check if string descriptor header is valid */ + total_len = parser->usb_str->len; + if ((total_len < FUSB_DESCRIPTOR_HEADER_SIZE) || + ((total_len & 1) != 0) || + (parser->usb_str->type != FUSB_DESC_TYPE_STRING)) + { + FUSB_ERROR("Get invalid string descriptor (len: %d) !!!", FUSB_USBSTR_MIN_LEN); + return FUSB_ERR_DESC_PARSE_ERR; + } + + /* return if no need to get more */ + if (total_len <= FUSB_USBSTR_MIN_LEN) + return FUSB_SUCCESS; + + /* re-malloc usb string desc buffer with full length */ + FASSERT(parser->usb_str); + FUSB_FREE(instance, parser->usb_str); + parser->usb_str = NULL; + + parser->usb_str = FUSB_ALLOCATE(instance, total_len, FUSB_DEFAULT_ALIGN); + if (NULL == parser->usb_str) + return FUSB_ERR_ALLOCATE_FAIL; + + /* get the whole string descriptor */ + if (FUsbGetStringDescriptor(dev, FUSB_DR_DESC, FUSB_DESC_TYPE_STRING, id, FUSB_DEFAULT_LANG_ID, + parser->usb_str, total_len) < 0) + { + FUSB_ERROR("Parse string descriptor failed (len: %d)!!!", total_len); + return FUSB_ERR_DESC_PARSE_ERR; + } + + if ((parser->usb_str->len < FUSB_DESCRIPTOR_HEADER_SIZE) || + ((parser->usb_str->len & 1) != 0) || + (parser->usb_str->type != FUSB_DESC_TYPE_STRING)) + { + FUSB_ERROR("Get invalid string descriptor (len: %d) !!!", total_len); + return FUSB_ERR_DESC_PARSE_ERR; + } + + /* convert into ASCII string */ + usb_str = parser->usb_str; + char_num = (usb_str->len - FUSB_DESCRIPTOR_HEADER_SIZE) / 2; /* in 16-bit way */ + + if (char_num >= FUSB_STRDESC_BUF_MAX - 1) + { + return FUSB_ERR_NOT_SUPPORT; + } + + for (u8 i = 0; i < char_num; i++) + { + character = usb_str->string[i]; + if (character < ' ' /* 0x20 */ + || character > '~') /* 0x7E */ + { + character = '_'; + } + + parser->str_buf[i] = (char)character; + } + + parser->str_buf[char_num] = '\0'; + return FUSB_SUCCESS; +} + +/** + * @name: FUsbGetString + * @msg: 获取刚刚检索到的字符串描述符内容 + * @return {const char *}, 字符串描述符中的内容 + * @param {FUsbDev} *dev, USB设备实例 + */ +const char *FUsbGetString(const FUsbDev *const dev) +{ + FASSERT(dev); + return (const char *)dev->string_parser.str_buf; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_g.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_g.c new file mode 100644 index 0000000000..dd088f21bd --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_g.c @@ -0,0 +1,60 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_g.c + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:19:07 + * Description:  This files is for gloabl parameters + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +/***************************** Include Files *********************************/ +#include "fparameters.h" +#include "fusb_private.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ +const FUsbConfig FUSBHC_CONFIG_TBL[FUSB3_NUM] = +{ + [FUSB3_ID_0] = + { + .instance_id = FUSB3_ID_0, + .base_addr = FUSB3_0_BASE_ADDR, + .irq_num = FUSB3_0_IRQ_NUM, + .irq_priority = 0U, + .allocator = NULL + }, + + [FUSB3_ID_1] = + { + .instance_id = FUSB3_ID_1, + .base_addr = FUSB3_1_BASE_ADDR, + .irq_num = FUSB3_1_IRQ_NUM, + .irq_priority = 0U, + .allocator = NULL + } +}; + + +/*****************************************************************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_generic_hub.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_generic_hub.c new file mode 100644 index 0000000000..5aa2236124 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_generic_hub.c @@ -0,0 +1,295 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_generic_hub.c + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:19:27 + * Description:  This files is for implmentation of generic hub function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include "fsleep.h" +#include "fdebug.h" +#include "fusb.h" +#include "fusb_generic_hub.h" + +#define FUSB_DEBUG_TAG "FUSB_HUB" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +void FUsbGenericHubDestory(FUsbDev *const dev) +{ + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + FUsb *instace = dev->controller->usb; + if (!hub) + return; + + /* First, detach all devices behind this hub */ + int port; + for (port = 1; port <= hub->num_ports; ++port) + { + if (hub->ports[port] >= 0) + { + FUSB_INFO("generic_hub: Detachment at port %d ", port); + FUsbDetachDev(dev->controller, hub->ports[port]); + hub->ports[port] = FUSB_NO_DEV_ADDR; + } + } + + /* Disable all ports */ + if (hub->ops->disable_port) + { + for (port = 1; port <= hub->num_ports; ++port) + hub->ops->disable_port(dev, port); + } + + FUSB_FREE(instace, hub->ports); // free(hub->ports); + FUSB_FREE(instace, hub); // free(hub); +} + +static int FUsbGenericHubDebounce(FUsbDev *const dev, const int port) +{ + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + + const int step_ms = 1; /* linux uses 25ms, we're busy anyway */ + const int at_least_ms = 100; /* 100ms as in usb20 spec 9.1.2 */ + const int timeout_ms = 1500; /* linux uses this value */ + + int total_ms = 0; + int stable_ms = 0; + while (stable_ms < at_least_ms && total_ms < timeout_ms) + { + fsleep_millisec(step_ms); + + const int changed = hub->ops->port_status_changed(dev, port); + const int connected = hub->ops->port_connected(dev, port); + if (changed < 0 || connected < 0) + return -1; + + if (!changed && connected) + { + stable_ms += step_ms; + } + else + { + FUSB_INFO("generic_hub: Unstable connection at %d ", + port); + stable_ms = 0; + } + total_ms += step_ms; + } + if (total_ms >= timeout_ms) + FUSB_INFO("generic_hub: Debouncing timed out at %d ", port); + return 0; /* ignore timeouts, try to always go on */ +} + +int FUsbGenericHubWaitForPort(FUsbDev *const dev, const int port, + const int wait_for, + int (*const port_op)(FUsbDev *, int), + int timeout_steps, const int step_us) +{ + int state; + do + { + state = port_op(dev, port); + if (state < 0) + return -1; + else if (!!state == wait_for) + return timeout_steps; + fsleep_microsec(step_us); + --timeout_steps; + } + while (timeout_steps); + + return 0; +} + +int FUsbGenericHubResetPort(FUsbDev *const dev, const int port) +{ + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + + if (hub->ops->start_port_reset(dev, port) < 0) + return -1; + + /* wait for 10ms (usb20 spec 11.5.1.5: reset should take 10 to 20ms) */ + fsleep_millisec(10); + + /* now wait 12ms for the hub to finish the reset */ + const int ret = FUsbGenericHubWaitForPort( + /* time out after 120 * 100us = 12ms */ + dev, port, 0, hub->ops->port_in_reset, 120, 100); + if (ret < 0) + return -1; + else if (!ret) + FUSB_INFO("generic_hub: Reset timed out at port %d ", port); + + return 0; /* ignore timeouts, try to always go on */ +} + +static int FUsbGenericHubDetachDev(FUsbDev *const dev, const int port) +{ + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + + FUsbDetachDev(dev->controller, hub->ports[port]); + hub->ports[port] = FUSB_NO_DEV_ADDR; + + return 0; +} + +static int FUsbGenericHubAttachDev(FUsbDev *const dev, const int port) +{ + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + + if (FUsbGenericHubDebounce(dev, port) < 0) + return -1; + + if (hub->ops->reset_port) + { + if (hub->ops->reset_port(dev, port) < 0) + return -1; + + if (!hub->ops->port_connected(dev, port)) + { + FUSB_INFO( + "generic_hub: Port %d disconnected after " + "reset. Possibly upgraded, rescan required. ", + port); + return 0; + } + + /* after reset the port will be enabled automatically */ + const int ret = FUsbGenericHubWaitForPort( + /* time out after 1,000 * 10us = 10ms */ + dev, port, 1, hub->ops->port_enabled, 1000, 10); + if (ret < 0) + return -1; + else if (!ret) + FUSB_INFO("generic_hub: Port %d still " + "disabled after 10ms ", + port); + } + + const FUsbSpeed speed = hub->ops->port_speed(dev, port); + if (speed >= 0) + { + FUSB_DEBUG("generic_hub: Success at port %d ", port); + if (hub->ops->reset_port) + fsleep_millisec(10); /* Reset recovery time + (usb20 spec 7.1.7.5) */ + hub->ports[port] = FUsbAttachDev( + dev->controller, dev->address, port, speed); + } + return 0; +} + +int FUsbGenericHubScanPort(FUsbDev *const dev, const int port) +{ + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + + if (hub->ports[port] >= 0) + { + FUSB_INFO("generic_hub: Detachment at port %d ", port); + const int ret = FUsbGenericHubDetachDev(dev, port); + if (ret < 0) + return ret; + } + + if (hub->ops->port_connected(dev, port)) + { + FUSB_INFO("generic_hub: Attachment at port %d ", port); + return FUsbGenericHubAttachDev(dev, port); + } + + return 0; +} + +static void FUsbGenericHubPoll(FUsbDev *const dev) +{ + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + if (!hub) + return; + + if (hub->ops->hub_status_changed && + hub->ops->hub_status_changed(dev) != FUSB_CC_SUCCESS) + { + return; + } + + int port; + for (port = 1; port <= hub->num_ports; ++port) + { + const FUsbTransCode ret = hub->ops->port_status_changed(dev, port); + if (ret < 0) + { + FUSB_WARN("Transcode %d", ret); + return; + } + else if (ret == FUSB_CC_SUCCESS) + { + FUSB_INFO("generic_hub: Port change at %d ", port); + if (FUsbGenericHubScanPort(dev, port) < 0) + return; + } + } +} + +int FUsbGenericHubInit(FUsbDev *const dev, const int num_ports, + const FUsbGenericHubOps *const ops) +{ + int port; + FUsb *instance = dev->controller->usb; + + dev->destroy = FUsbGenericHubDestory; + dev->poll = FUsbGenericHubPoll; + FASSERT(NULL == dev->data); + dev->data = FUSB_ALLOCATE(instance, sizeof(FUsbGenericHub), FUSB_DEFAULT_ALIGN); + if (NULL == dev->data) + { + FUSB_ERROR("generic_hub: ERROR: Out of memory "); + return -1; + } + + FUsbGenericHub *const hub = FUSB_GEN_HUB_GET(dev); + hub->num_ports = num_ports; + FASSERT(NULL == hub->ports); + hub->ports = FUSB_ALLOCATE(instance, sizeof(*hub->ports) * (num_ports + 1), FUSB_DEFAULT_ALIGN); + hub->ops = ops; + if (NULL == hub->ports) + { + FUSB_ERROR("generic_hub: ERROR: Out of memory "); + FUSB_FREE(instance, dev->data); + dev->data = NULL; + return -1; + } + + for (port = 1; port <= num_ports; ++port) + hub->ports[port] = FUSB_NO_DEV_ADDR; + + /* Enable all ports */ + if (ops->enable_port) + { + for (port = 1; port <= num_ports; ++port) + ops->enable_port(dev, port); + + /* wait once for all ports */ + fsleep_millisec(20); + } + + return 0; +} diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_generic_hub.h b/bsp/phytium/libraries/standalone/drivers/usb/fusb_generic_hub.h new file mode 100644 index 0000000000..da3bd6cc2d --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_generic_hub.h @@ -0,0 +1,93 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_generic_hub.h + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:20:23 + * Description:  This files is for definition of generic hub function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_FUSB_GENERIC_HUB_H +#define DRIVERS_FUSB_GENERIC_HUB_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fusb_private.h" + +typedef struct +{ + /* negative results denote an error */ + + /* returns 1 if the hub's status changed since the last call (optional) */ + FUsbTransCode(*hub_status_changed)(FUsbDev *); + /* returns 1 if the port's status changed since the last call */ + FUsbTransCode(*port_status_changed)(FUsbDev *, int port); + /* returns 1 if something is connected to the port */ + FUsbTransCode(*port_connected)(FUsbDev *, int port); + /* returns 1 if port is currently resetting */ + FUsbTransCode(*port_in_reset)(FUsbDev *, int port); + /* returns 1 if the port is enabled */ + FUsbTransCode(*port_enabled)(FUsbDev *, int port); + /* returns speed if port is enabled, negative value if not */ + FUsbSpeed(*port_speed)(FUsbDev *, int port); + + /* enables (powers up) a port (optional) */ + FUsbTransCode(*enable_port)(FUsbDev *, int port); + /* disables (powers down) a port (optional) */ + FUsbTransCode(*disable_port)(FUsbDev *, int port); + /* starts a port reset (required if reset_port is set to a generic one from below) */ + FUsbTransCode(*start_port_reset)(FUsbDev *, int port); + + /* performs a port reset (optional, generic implementations below) */ + FUsbTransCode(*reset_port)(FUsbDev *, int port); +} FUsbGenericHubOps; + +typedef struct +{ + int num_ports; + /* port numbers are always 1 based, + so we waste one int for convenience */ + int *ports; /* allocated to sizeof(*ports)*(num_ports+1) */ +#define FUSB_NO_DEV_ADDR -1 + + const FUsbGenericHubOps *ops; + + void *data; +} FUsbGenericHub; + +void FUsbGenericHubDestory(FUsbDev *); +int FUsbGenericHubWaitForPort(FUsbDev *const dev, const int port, + const int wait_for, + int (*const port_op)(FUsbDev *, int), + int timeout_steps, const int step_us); +int FUsbGenericHubResetPort(FUsbDev *, int port); +int FUsbGenericHubScanPort(FUsbDev *, int port); +/* the provided generic_hub_ops struct has to be static */ +int FUsbGenericHubInit(FUsbDev *, int num_ports, const FUsbGenericHubOps *); + +#define FUSB_GEN_HUB_GET(FUsbDev) ((FUsbGenericHub *)(FUsbDev)->data) + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_hid.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hid.c new file mode 100644 index 0000000000..a2df9e6e13 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hid.c @@ -0,0 +1,554 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_hid.c + * Date: 2022-09-28 18:26:42 + * LastEditTime: 2022-09-29 14:50:09 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +#include + +#include "fkernel.h" +#include "fdebug.h" +#include "fsleep.h" + +#include "fusb.h" +#include "fusb_hid.h" + +enum FUsbHidRequests +{ + GET_REPORT = 0x1, + GET_IDLE = 0x2, + GET_PROTOCOL = 0x3, + SET_REPORT = 0x9, + SET_IDLE = 0xa, + SET_PROTOCOL = 0xb +}; + +enum FUsbHidKeyboardModifiers +{ + KB_MOD_SHIFT = (1 << 0), + KB_MOD_ALT = (1 << 1), + KB_MOD_CTRL = (1 << 2), + KB_MOD_CAPSLOCK = (1 << 3), +}; + +typedef union +{ + struct + { + u8 modifiers; + u8 repeats; + u8 keys[6]; + }; + u8 buffer[8]; +} FUsbHidKeyboardEvent; + +typedef struct +{ + void *queue; + FUsbHidDescriptor *descriptor; + + FUsbHidKeyboardEvent previous; + int lastkeypress; + int repeat_delay; +} FUsbHid; + +#define KEYBOARD_REPEAT_MS 30 +#define INITIAL_REPEAT_DELAY 10 +#define REPEAT_DELAY 2 + +#define FUSB_HID_INST(dev) ((FUsbHid*)(dev)->data) + +#define FUSB_DEBUG_TAG "FUSB_HID" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +static const char *boot_protos[3] = { "(none)", "keyboard", "mouse" }; + +static void FUsbHidDestory(FUsbDev *dev) +{ + FUsb *instance = dev->controller->usb; + + if (FUSB_HID_INST(dev)->queue) + { + int i; + for (i = 0; i <= dev->num_endp; i++) + { + if (dev->endpoints[i].endpoint == 0) + continue; + if (dev->endpoints[i].type != FUSB_INTERRUPT_EP) + continue; + if (dev->endpoints[i].direction != FUSB_IN) + continue; + break; + } + dev->controller->destroy_intr_queue( + &dev->endpoints[i], FUSB_HID_INST(dev)->queue); + FUSB_HID_INST(dev)->queue = NULL; + } + FUSB_FREE(instance, FUSB_HID_INST(dev)->descriptor); + FUSB_HID_INST(dev)->descriptor = NULL; + + FUSB_FREE(instance, dev->data); +} + +/* keybuffer is global to all USB keyboards */ +static int keycount; +#define KEYBOARD_BUFFER_SIZE 16 +static short keybuffer[KEYBOARD_BUFFER_SIZE]; +static int modifiers; + +static const char *countries[36][2] = +{ + { "not supported", "us" }, + { "Arabic", "ae" }, + { "Belgian", "be" }, + { "Canadian-Bilingual", "ca" }, + { "Canadian-French", "ca" }, + { "Czech Republic", "cz" }, + { "Danish", "dk" }, + { "Finnish", "fi" }, + { "French", "fr" }, + { "German", "de" }, + { "Greek", "gr" }, + { "Hebrew", "il" }, + { "Hungary", "hu" }, + { "International (ISO)", "iso" }, + { "Italian", "it" }, + { "Japan (Katakana)", "jp" }, + { "Korean", "us" }, + { "Latin American", "us" }, + { "Netherlands/Dutch", "nl" }, + { "Norwegian", "no" }, + { "Persian (Farsi)", "ir" }, + { "Poland", "pl" }, + { "Portuguese", "pt" }, + { "Russia", "ru" }, + { "Slovakia", "sl" }, + { "Spanish", "es" }, + { "Swedish", "se" }, + { "Swiss/French", "ch" }, + { "Swiss/German", "ch" }, + { "Switzerland", "ch" }, + { "Taiwan", "tw" }, + { "Turkish-Q", "tr" }, + { "UK", "uk" }, + { "US", "us" }, + { "Yugoslavia", "yu" }, + { "Turkish-F", "tr" }, + /* 36 - 255: Reserved */ +}; + +struct FUsbHidLayoutMaps +{ + const char *country; + const short map[4][0x80]; +}; + +static const struct FUsbHidLayoutMaps *map; + +static const struct FUsbHidLayoutMaps keyboard_layouts[] = +{ + { + .country = "us", + .map = { + { /* No modifier */ + -1, -1, -1, -1, 'a', 'b', 'c', 'd', + 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + /* 0x10 */ + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', + /* 0x20 */ + '3', '4', '5', '6', '7', '8', '9', '0', + '\n', '\e', '\b', '\t', ' ', '-', '=', '[', + /* 0x30 */ + ']', '\\', -1, ';', '\'', '`', ',', '.', + '/', -1 /* CapsLk */, KEY_F(1), KEY_F(2), KEY_F(3), KEY_F(4), KEY_F(5), KEY_F(6), + /* 0x40 */ + KEY_F(7), KEY_F(8), KEY_F(9), KEY_F(10), KEY_F(11), KEY_F(12), KEY_PRINT, -1 /* ScrLk */, + KEY_BREAK, KEY_IC, KEY_HOME, KEY_PPAGE, KEY_DC, KEY_END, KEY_NPAGE, KEY_RIGHT, + /* 50 */ + KEY_LEFT, KEY_DOWN, KEY_UP, -1 /*NumLck*/, '/', '*', '-' /* = ? */, '+', + KEY_ENTER, KEY_END, KEY_DOWN, KEY_NPAGE, KEY_LEFT, -1, KEY_RIGHT, KEY_HOME, + /* 60 */ + KEY_UP, KEY_PPAGE, -1, KEY_DC, -1 /* < > | */, -1 /* Win Key Right */, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + /* 70 */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + }, + { /* Shift modifier */ + -1, -1, -1, -1, 'A', 'B', 'C', 'D', + 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', + /* 0x10 */ + 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '@', + /* 0x20 */ + '#', '$', '%', '^', '&', '*', '(', ')', + '\n', '\e', '\b', '\t', ' ', '_', '+', '[', + /* 0x30 */ + ']', '\\', -1, ':', '\'', '`', ',', '.', + '/', -1 /* CapsLk */, KEY_F(1), KEY_F(2), KEY_F(3), KEY_F(4), KEY_F(5), KEY_F(6), + /* 0x40 */ + KEY_F(7), KEY_F(8), KEY_F(9), KEY_F(10), KEY_F(11), KEY_F(12), KEY_PRINT, -1 /* ScrLk */, + KEY_BREAK, KEY_IC, KEY_HOME, KEY_PPAGE, KEY_DC, KEY_END, KEY_NPAGE, KEY_RIGHT, + /* 50 */ + KEY_LEFT, KEY_DOWN, KEY_UP, -1 /*NumLck*/, '/', '*', '-' /* = ? */, '+', + KEY_ENTER, KEY_END, KEY_DOWN, KEY_NPAGE, KEY_LEFT, -1, KEY_RIGHT, KEY_HOME, + /* 60 */ + KEY_UP, KEY_PPAGE, -1, KEY_DC, -1 /* < > | */, -1 /* Win Key Right */, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + /* 70 */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + }, + { /* Alt */ + -1, -1, -1, -1, 'a', 'b', 'c', 'd', + 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + /* 0x10 */ + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', + /* 0x20 */ + '3', '4', '5', '6', '7', '8', '9', '0', + '\n', '\e', '\b', '\t', ' ', '-', '=', '[', + /* 0x30 */ + ']', '\\', -1, ';', '\'', '`', ',', '.', + '/', -1 /* CapsLk */, KEY_F(1), KEY_F(2), KEY_F(3), KEY_F(4), KEY_F(5), KEY_F(6), + /* 0x40 */ + KEY_F(7), KEY_F(8), KEY_F(9), KEY_F(10), KEY_F(11), KEY_F(12), KEY_PRINT, -1 /* ScrLk */, + KEY_BREAK, KEY_IC, KEY_HOME, KEY_PPAGE, KEY_DC, KEY_END, KEY_NPAGE, KEY_RIGHT, + /* 50 */ + KEY_LEFT, KEY_DOWN, KEY_UP, -1 /*NumLck*/, '/', '*', '-' /* = ? */, '+', + KEY_ENTER, KEY_END, KEY_DOWN, KEY_NPAGE, KEY_LEFT, -1, KEY_RIGHT, KEY_HOME, + /* 60 */ + KEY_UP, KEY_PPAGE, -1, KEY_DC, -1 /* < > | */, -1 /* Win Key Right */, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + /* 70 */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + }, + { /* Shift+Alt modifier */ + -1, -1, -1, -1, 'A', 'B', 'C', 'D', + 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', + /* 0x10 */ + 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', 'Z', '!', '@', + /* 0x20 */ + '#', '$', '%', '^', '&', '*', '(', ')', + '\n', '\e', '\b', '\t', ' ', '-', '=', '[', + /* 0x30 */ + ']', '\\', -1, ':', '\'', '`', ',', '.', + '/', -1 /* CapsLk */, KEY_F(1), KEY_F(2), KEY_F(3), KEY_F(4), KEY_F(5), KEY_F(6), + /* 0x40 */ + KEY_F(7), KEY_F(8), KEY_F(9), KEY_F(10), KEY_F(11), KEY_F(12), KEY_PRINT, -1 /* ScrLk */, + KEY_BREAK, KEY_IC, KEY_HOME, KEY_PPAGE, KEY_DC, KEY_END, KEY_NPAGE, KEY_RIGHT, + /* 50 */ + KEY_LEFT, KEY_DOWN, KEY_UP, -1 /*NumLck*/, '/', '*', '-' /* = ? */, '+', + KEY_ENTER, KEY_END, KEY_DOWN, KEY_NPAGE, KEY_LEFT, -1, KEY_RIGHT, KEY_HOME, + /* 60 */ + KEY_UP, KEY_PPAGE, -1, KEY_DC, -1 /* < > | */, -1 /* Win Key Right */, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + /* 70 */ + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + } + } + }, +}; + +static void FUsbHidKeyboardQueue(int ch) +{ + /* ignore key presses if buffer full */ + if (keycount < KEYBOARD_BUFFER_SIZE) + keybuffer[keycount++] = ch; +} + +/* handle hid received data */ +static void FUsbHidProcessKeyboardEvent(FUsbHid *const inst, + const FUsbHidKeyboardEvent *const current) +{ + const FUsbHidKeyboardEvent *const previous = &inst->previous; + + int i, keypress = 0; + + modifiers = 0; + + if (current->modifiers & 0x01) /* Left-Ctrl */ + modifiers |= KB_MOD_CTRL; + if (current->modifiers & 0x02) /* Left-Shift */ + modifiers |= KB_MOD_SHIFT; + if (current->modifiers & 0x04) /* Left-Alt */ + modifiers |= KB_MOD_ALT; + if (current->modifiers & 0x08) /* Left-GUI */ + { + + } + + if (current->modifiers & 0x10) /* Right-Ctrl */ + modifiers |= KB_MOD_CTRL; + if (current->modifiers & 0x20) /* Right-Shift */ + modifiers |= KB_MOD_SHIFT; + if (current->modifiers & 0x40) /* Right-AltGr */ + modifiers |= KB_MOD_ALT; + if (current->modifiers & 0x80) /* Right-GUI */ + { + + } + + if ((current->modifiers & 0x05) && ((current->keys[0] == 0x4c) || + (current->keys[0] == 0x63))) + { + /* todo, Reboot here */ + } + + /* Did the event change at all? */ + if (inst->lastkeypress && + !memcmp(current, previous, sizeof(*current))) + { + /* No. Then it's a key repeat event. */ + if (inst->repeat_delay) + { + inst->repeat_delay--; + } + else + { + FUsbHidKeyboardQueue(inst->lastkeypress); + inst->repeat_delay = REPEAT_DELAY; + } + + return; + } + + inst->lastkeypress = 0; + + for (i = 0; i < 6; i++) + { + int j; + int skip = 0; + /* No more keys? skip */ + if (current->keys[i] == 0) + return; + + for (j = 0; j < 6; j++) + { + if (current->keys[i] == previous->keys[j]) + { + skip = 1; + break; + } + } + + if (skip) + continue; + + /* Mask off KB_MOD_CTRL */ + keypress = map->map[modifiers & 0x03][current->keys[i]]; + + if (modifiers & KB_MOD_CTRL) + { + switch (keypress) + { + case 'a' ... 'z': + keypress &= 0x1f; + break; + default: + continue; + } + } + + if (keypress == -1) + { + /* Debug: Print unknown keys */ + FUSB_INFO("usbhid: <%x> %x [ %x %x %x %x %x %x ] %d\n", + current->modifiers, current->repeats, + current->keys[0], current->keys[1], + current->keys[2], current->keys[3], + current->keys[4], current->keys[5], i); + + /* Unknown key? Try next one in the queue */ + continue; + } + + FUsbHidKeyboardQueue(keypress); + + /* Remember for authentic key repeat */ + inst->lastkeypress = keypress; + inst->repeat_delay = INITIAL_REPEAT_DELAY; + } +} + +static void FUsbHidPoll(FUsbDev *dev) +{ + FUsbHidKeyboardEvent current; + const u8 *buf; + + while ((buf = dev->controller->poll_intr_queue(FUSB_HID_INST(dev)->queue))) + { + memcpy(¤t.buffer, buf, 8); + FUsbHidProcessKeyboardEvent(FUSB_HID_INST(dev), ¤t); + FUSB_HID_INST(dev)->previous = current; + } +} + +static void FUsbHidSetIdle(FUsbDev *dev, FUsbInterfaceDescriptor *interface, u16 duration) +{ + FUsbDevReq dr; + dr.data_dir = FUSB_REQ_HOST_TO_DEVICE; + dr.req_type = FUSB_REQ_TYPE_CLASS; + dr.req_recp = FUSB_REQ_RECP_IF; + dr.bRequest = SET_IDLE; + dr.wValue = (duration >> 2) << 8; + dr.wIndex = interface->bInterfaceNumber; + dr.wLength = 0; + dev->controller->control(dev, FUSB_OUT, sizeof(FUsbDevReq), &dr, 0, NULL); +} + +static void FUsbHidSetProtocol(FUsbDev *dev, FUsbInterfaceDescriptor *interface, FUsbHidProtocol proto) +{ + FUsbDevReq dr; + dr.data_dir = FUSB_REQ_HOST_TO_DEVICE; + dr.req_type = FUSB_REQ_TYPE_CLASS; + dr.req_recp = FUSB_REQ_RECP_IF; + dr.bRequest = SET_PROTOCOL; + dr.wValue = proto; + dr.wIndex = interface->bInterfaceNumber; + dr.wLength = 0; + dev->controller->control(dev, FUSB_OUT, sizeof(FUsbDevReq), &dr, 0, 0); +} + +static int FUsbHidSetLayout(const char *country) +{ + /* FIXME should be per keyboard */ + for (fsize_t i = 0; i < ARRAY_SIZE(keyboard_layouts); i++) + { + if (strncmp(keyboard_layouts[i].country, country, + strlen(keyboard_layouts[i].country))) + continue; + + /* Found, changing keyboard layout */ + map = &keyboard_layouts[i]; + FUSB_DEBUG(" Keyboard layout '%s'\n", map->country); + return 0; + } + + FUSB_DEBUG(" Keyboard layout '%s' not found, using '%s'\n", + country, map->country); + + /* Nothing found, not changed */ + return -1; +} + +void FUsbHidInit(FUsbDev *dev) +{ + FUsb *instance = dev->controller->usb; + + FUsbConfigurationDescriptor *cd = (FUsbConfigurationDescriptor *)dev->configuration; + FUsbInterfaceDescriptor *interface = (FUsbInterfaceDescriptor *)(((char *) cd) + cd->bLength); + + if (interface->bInterfaceSubClass == FUSB_HID_SUBCLASS_BOOT) + { + u8 countrycode; + FUSB_DEBUG(" supports boot interface..\n"); + FUSB_DEBUG(" it's a %s\n", + boot_protos[interface->bInterfaceProtocol]); + switch (interface->bInterfaceProtocol) + { + case FUSB_HID_BOOT_PROTOCOL_KEYBOARD: + dev->data = FUSB_ALLOCATE(instance, sizeof(FUsbHid), FUSB_DEFAULT_ALIGN); + FUSB_DEBUG(" configuring...\n"); + FUsbHidSetProtocol(dev, interface, FUSB_HID_PROTOCOL_BOOT); + FUsbHidSetIdle(dev, interface, KEYBOARD_REPEAT_MS); + FUSB_DEBUG(" activating...\n"); + + FUsbHidDescriptor *desc = FUSB_ALLOCATE(instance, sizeof(FUsbHidDescriptor), FUSB_DEFAULT_ALIGN); + if (!desc || FUsbGetDescriptor(dev, FUsbGenerateReqType( + FUSB_REQ_DEVICE_TO_HOST, FUSB_REQ_TYPE_STANDARD, FUSB_REQ_RECP_IF), + 0x21, 0, desc, sizeof(*desc)) != sizeof(*desc)) + { + FUSB_DEBUG("FUsbGetDescriptor(HID) failed\n"); + FUsbDetachDev(dev->controller, dev->address); + return; + } + FUSB_HID_INST(dev)->descriptor = desc; + countrycode = desc->bCountryCode; + /* 35 countries defined: */ + if (countrycode >= ARRAY_SIZE(countries)) + countrycode = 0; + printf(" Keyboard has %s layout (country code %02x)\n", + countries[countrycode][0], countrycode); + + /* Set keyboard layout accordingly */ + FUsbHidSetLayout(countries[countrycode][1]); + + // only add here, because we only support boot-keyboard HID devices + dev->destroy = FUsbHidDestory; + dev->poll = FUsbHidPoll; + int i; + for (i = 1; i < dev->num_endp; i++) + { + if (dev->endpoints[i].type != FUSB_INTERRUPT_EP) + continue; + if (dev->endpoints[i].direction != FUSB_IN) + continue; + break; + } + + if (i >= dev->num_endp) + { + FUSB_DEBUG("Could not find HID endpoint\n"); + FUsbDetachDev(dev->controller, dev->address); + return; + } + + FUSB_DEBUG(" found endpoint %x for interrupt-in\n", i); + /* 20 buffers of 8 bytes, for every 10 msecs */ + FUSB_HID_INST(dev)->queue = dev->controller->create_intr_queue(&dev->endpoints[i], 8, 20, 10); + keycount = 0; + FUSB_DEBUG(" configuration done.\n"); + break; + case FUSB_HID_BOOT_PROTOCOL_MOUSE: + FUSB_DEBUG("NOTICE: USB mice are not supported.\n"); + break; + } + } +} + +int FUsbHidCheckInput(FUsbDev *dev, int times) +{ + short ret; + FUsb *instance = dev->controller->usb; + + for (int i = 0; i < times; i++) + { + FUsbPoll(instance); + + while (keycount != 0) + { + ret = keybuffer[0]; + memmove(keybuffer, keybuffer + 1, --keycount); + printf("%c", ret); + } + + fsleep_millisec(10); + } + + printf("\r\n"); +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_hid.h b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hid.h new file mode 100644 index 0000000000..e4bc50e363 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hid.h @@ -0,0 +1,328 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_hid.h + * Date: 2022-02-11 13:33:09 + * LastEditTime: 2022-02-17 17:49:20 + * Description:  This files is for definition of USB hub device function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/9/28 init commit + */ + +#ifndef DRIVERS_USB_HID_H +#define DRIVERS_USB_HID_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "fusb.h" + +/************************** Constant Definitions *****************************/ +/*---------------------------------------------------------------------- + * + * Function and Keypad Key Definitions. + * Many are just for compatibility. + * + */ + +#define KEY_CODE_YES 0x100 /* If get_wch() gives a key code */ + +#define KEY_BREAK 0x101 /* Not on PC KBD */ +#define KEY_DOWN 0x102 /* Down arrow key */ +#define KEY_UP 0x103 /* Up arrow key */ +#define KEY_LEFT 0x104 /* Left arrow key */ +#define KEY_RIGHT 0x105 /* Right arrow key */ +#define KEY_HOME 0x106 /* home key */ +#define KEY_BACKSPACE 0x107 /* not on pc */ +#define KEY_F0 0x108 /* function keys; 64 reserved */ + +#define KEY_DL 0x148 /* delete line */ +#define KEY_IL 0x149 /* insert line */ +#define KEY_DC 0x14a /* delete character */ +#define KEY_IC 0x14b /* insert char or enter ins mode */ +#define KEY_EIC 0x14c /* exit insert char mode */ +#define KEY_CLEAR 0x14d /* clear screen */ +#define KEY_EOS 0x14e /* clear to end of screen */ +#define KEY_EOL 0x14f /* clear to end of line */ +#define KEY_SF 0x150 /* scroll 1 line forward */ +#define KEY_SR 0x151 /* scroll 1 line back (reverse) */ +#define KEY_NPAGE 0x152 /* next page */ +#define KEY_PPAGE 0x153 /* previous page */ +#define KEY_STAB 0x154 /* set tab */ +#define KEY_CTAB 0x155 /* clear tab */ +#define KEY_CATAB 0x156 /* clear all tabs */ +#define KEY_ENTER 0x157 /* enter or send (unreliable) */ +#define KEY_SRESET 0x158 /* soft/reset (partial/unreliable) */ +#define KEY_RESET 0x159 /* reset/hard reset (unreliable) */ +#define KEY_PRINT 0x15a /* print/copy */ +#define KEY_LL 0x15b /* home down/bottom (lower left) */ +#define KEY_ABORT 0x15c /* abort/terminate key (any) */ +#define KEY_SHELP 0x15d /* short help */ +#define KEY_LHELP 0x15e /* long help */ +#define KEY_BTAB 0x15f /* Back tab key */ +#define KEY_BEG 0x160 /* beg(inning) key */ +#define KEY_CANCEL 0x161 /* cancel key */ +#define KEY_CLOSE 0x162 /* close key */ +#define KEY_COMMAND 0x163 /* cmd (command) key */ +#define KEY_COPY 0x164 /* copy key */ +#define KEY_CREATE 0x165 /* create key */ +#define KEY_END 0x166 /* end key */ +#define KEY_EXIT 0x167 /* exit key */ +#define KEY_FIND 0x168 /* find key */ +#define KEY_HELP 0x169 /* help key */ +#define KEY_MARK 0x16a /* mark key */ +#define KEY_MESSAGE 0x16b /* message key */ +#define KEY_MOVE 0x16c /* move key */ +#define KEY_NEXT 0x16d /* next object key */ +#define KEY_OPEN 0x16e /* open key */ +#define KEY_OPTIONS 0x16f /* options key */ +#define KEY_PREVIOUS 0x170 /* previous object key */ +#define KEY_REDO 0x171 /* redo key */ +#define KEY_REFERENCE 0x172 /* ref(erence) key */ +#define KEY_REFRESH 0x173 /* refresh key */ +#define KEY_REPLACE 0x174 /* replace key */ +#define KEY_RESTART 0x175 /* restart key */ +#define KEY_RESUME 0x176 /* resume key */ +#define KEY_SAVE 0x177 /* save key */ +#define KEY_SBEG 0x178 /* shifted beginning key */ +#define KEY_SCANCEL 0x179 /* shifted cancel key */ +#define KEY_SCOMMAND 0x17a /* shifted command key */ +#define KEY_SCOPY 0x17b /* shifted copy key */ +#define KEY_SCREATE 0x17c /* shifted create key */ +#define KEY_SDC 0x17d /* shifted delete char key */ +#define KEY_SDL 0x17e /* shifted delete line key */ +#define KEY_SELECT 0x17f /* select key */ +#define KEY_SEND 0x180 /* shifted end key */ +#define KEY_SEOL 0x181 /* shifted clear line key */ +#define KEY_SEXIT 0x182 /* shifted exit key */ +#define KEY_SFIND 0x183 /* shifted find key */ +#define KEY_SHOME 0x184 /* shifted home key */ +#define KEY_SIC 0x185 /* shifted input key */ + +#define KEY_SLEFT 0x187 /* shifted left arrow key */ +#define KEY_SMESSAGE 0x188 /* shifted message key */ +#define KEY_SMOVE 0x189 /* shifted move key */ +#define KEY_SNEXT 0x18a /* shifted next key */ +#define KEY_SOPTIONS 0x18b /* shifted options key */ +#define KEY_SPREVIOUS 0x18c /* shifted prev key */ +#define KEY_SPRINT 0x18d /* shifted print key */ +#define KEY_SREDO 0x18e /* shifted redo key */ +#define KEY_SREPLACE 0x18f /* shifted replace key */ +#define KEY_SRIGHT 0x190 /* shifted right arrow */ +#define KEY_SRSUME 0x191 /* shifted resume key */ +#define KEY_SSAVE 0x192 /* shifted save key */ +#define KEY_SSUSPEND 0x193 /* shifted suspend key */ +#define KEY_SUNDO 0x194 /* shifted undo key */ +#define KEY_SUSPEND 0x195 /* suspend key */ +#define KEY_UNDO 0x196 /* undo key */ + +/* PDCurses-specific key definitions -- PC only */ + +#define ALT_0 0x197 +#define ALT_1 0x198 +#define ALT_2 0x199 +#define ALT_3 0x19a +#define ALT_4 0x19b +#define ALT_5 0x19c +#define ALT_6 0x19d +#define ALT_7 0x19e +#define ALT_8 0x19f +#define ALT_9 0x1a0 +#define ALT_A 0x1a1 +#define ALT_B 0x1a2 +#define ALT_C 0x1a3 +#define ALT_D 0x1a4 +#define ALT_E 0x1a5 +#define ALT_F 0x1a6 +#define ALT_G 0x1a7 +#define ALT_H 0x1a8 +#define ALT_I 0x1a9 +#define ALT_J 0x1aa +#define ALT_K 0x1ab +#define ALT_L 0x1ac +#define ALT_M 0x1ad +#define ALT_N 0x1ae +#define ALT_O 0x1af +#define ALT_P 0x1b0 +#define ALT_Q 0x1b1 +#define ALT_R 0x1b2 +#define ALT_S 0x1b3 +#define ALT_T 0x1b4 +#define ALT_U 0x1b5 +#define ALT_V 0x1b6 +#define ALT_W 0x1b7 +#define ALT_X 0x1b8 +#define ALT_Y 0x1b9 +#define ALT_Z 0x1ba + +#define CTL_LEFT 0x1bb /* Control-Left-Arrow */ +#define CTL_RIGHT 0x1bc +#define CTL_PGUP 0x1bd +#define CTL_PGDN 0x1be +#define CTL_HOME 0x1bf +#define CTL_END 0x1c0 + +#define KEY_A1 0x1c1 /* upper left on Virtual keypad */ +#define KEY_A2 0x1c2 /* upper middle on Virt. keypad */ +#define KEY_A3 0x1c3 /* upper right on Vir. keypad */ +#define KEY_B1 0x1c4 /* middle left on Virt. keypad */ +#define KEY_B2 0x1c5 /* center on Virt. keypad */ +#define KEY_B3 0x1c6 /* middle right on Vir. keypad */ +#define KEY_C1 0x1c7 /* lower left on Virt. keypad */ +#define KEY_C2 0x1c8 /* lower middle on Virt. keypad */ +#define KEY_C3 0x1c9 /* lower right on Vir. keypad */ + +#define PADSLASH 0x1ca /* slash on keypad */ +#define PADENTER 0x1cb /* enter on keypad */ +#define CTL_PADENTER 0x1cc /* ctl-enter on keypad */ +#define ALT_PADENTER 0x1cd /* alt-enter on keypad */ +#define PADSTOP 0x1ce /* stop on keypad */ +#define PADSTAR 0x1cf /* star on keypad */ +#define PADMINUS 0x1d0 /* minus on keypad */ +#define PADPLUS 0x1d1 /* plus on keypad */ +#define CTL_PADSTOP 0x1d2 /* ctl-stop on keypad */ +#define CTL_PADCENTER 0x1d3 /* ctl-enter on keypad */ +#define CTL_PADPLUS 0x1d4 /* ctl-plus on keypad */ +#define CTL_PADMINUS 0x1d5 /* ctl-minus on keypad */ +#define CTL_PADSLASH 0x1d6 /* ctl-slash on keypad */ +#define CTL_PADSTAR 0x1d7 /* ctl-star on keypad */ +#define ALT_PADPLUS 0x1d8 /* alt-plus on keypad */ +#define ALT_PADMINUS 0x1d9 /* alt-minus on keypad */ +#define ALT_PADSLASH 0x1da /* alt-slash on keypad */ +#define ALT_PADSTAR 0x1db /* alt-star on keypad */ +#define ALT_PADSTOP 0x1dc /* alt-stop on keypad */ +#define CTL_INS 0x1dd /* ctl-insert */ +#define ALT_DEL 0x1de /* alt-delete */ +#define ALT_INS 0x1df /* alt-insert */ +#define CTL_UP 0x1e0 /* ctl-up arrow */ +#define CTL_DOWN 0x1e1 /* ctl-down arrow */ +#define CTL_TAB 0x1e2 /* ctl-tab */ +#define ALT_TAB 0x1e3 +#define ALT_MINUS 0x1e4 +#define ALT_EQUAL 0x1e5 +#define ALT_HOME 0x1e6 +#define ALT_PGUP 0x1e7 +#define ALT_PGDN 0x1e8 +#define ALT_END 0x1e9 +#define ALT_UP 0x1ea /* alt-up arrow */ +#define ALT_DOWN 0x1eb /* alt-down arrow */ +#define ALT_RIGHT 0x1ec /* alt-right arrow */ +#define ALT_LEFT 0x1ed /* alt-left arrow */ +#define ALT_ENTER 0x1ee /* alt-enter */ +#define ALT_ESC 0x1ef /* alt-escape */ +#define ALT_BQUOTE 0x1f0 /* alt-back quote */ +#define ALT_LBRACKET 0x1f1 /* alt-left bracket */ +#define ALT_RBRACKET 0x1f2 /* alt-right bracket */ +#define ALT_SEMICOLON 0x1f3 /* alt-semi-colon */ +#define ALT_FQUOTE 0x1f4 /* alt-forward quote */ +#define ALT_COMMA 0x1f5 /* alt-comma */ +#define ALT_STOP 0x1f6 /* alt-stop */ +#define ALT_FSLASH 0x1f7 /* alt-forward slash */ +#define ALT_BKSP 0x1f8 /* alt-backspace */ +#define CTL_BKSP 0x1f9 /* ctl-backspace */ +#define PAD0 0x1fa /* keypad 0 */ + +#define CTL_PAD0 0x1fb /* ctl-keypad 0 */ +#define CTL_PAD1 0x1fc +#define CTL_PAD2 0x1fd +#define CTL_PAD3 0x1fe +#define CTL_PAD4 0x1ff +#define CTL_PAD5 0x200 +#define CTL_PAD6 0x201 +#define CTL_PAD7 0x202 +#define CTL_PAD8 0x203 +#define CTL_PAD9 0x204 + +#define ALT_PAD0 0x205 /* alt-keypad 0 */ +#define ALT_PAD1 0x206 +#define ALT_PAD2 0x207 +#define ALT_PAD3 0x208 +#define ALT_PAD4 0x209 +#define ALT_PAD5 0x20a +#define ALT_PAD6 0x20b +#define ALT_PAD7 0x20c +#define ALT_PAD8 0x20d +#define ALT_PAD9 0x20e + +#define CTL_DEL 0x20f /* clt-delete */ +#define ALT_BSLASH 0x210 /* alt-back slash */ +#define CTL_ENTER 0x211 /* ctl-enter */ + +#define SHF_PADENTER 0x212 /* shift-enter on keypad */ +#define SHF_PADSLASH 0x213 /* shift-slash on keypad */ +#define SHF_PADSTAR 0x214 /* shift-star on keypad */ +#define SHF_PADPLUS 0x215 /* shift-plus on keypad */ +#define SHF_PADMINUS 0x216 /* shift-minus on keypad */ +#define SHF_UP 0x217 /* shift-up on keypad */ +#define SHF_DOWN 0x218 /* shift-down on keypad */ +#define SHF_IC 0x219 /* shift-insert on keypad */ +#define SHF_DC 0x21a /* shift-delete on keypad */ + +#define KEY_MOUSE 0x21b /* "mouse" key */ +#define KEY_SHIFT_L 0x21c /* Left-shift */ +#define KEY_SHIFT_R 0x21d /* Right-shift */ +#define KEY_CONTROL_L 0x21e /* Left-control */ +#define KEY_CONTROL_R 0x21f /* Right-control */ +#define KEY_ALT_L 0x220 /* Left-alt */ +#define KEY_ALT_R 0x221 /* Right-alt */ +#define KEY_RESIZE 0x222 /* Window resize */ +#define KEY_SUP 0x223 /* Shifted up arrow */ +#define KEY_SDOWN 0x224 /* Shifted down arrow */ + +#define KEY_MIN KEY_BREAK /* Minimum curses key value */ +#define KEY_MAX KEY_SDOWN /* Maximum curses key */ + +#define KEY_F(n) (KEY_F0 + (n)) + +/**************************** Type Definitions *******************************/ +enum +{ + FUSB_HID_SUBCLASS_NONE = 0, + FUSB_HID_SUBCLASS_BOOT = 1 +}; + +typedef enum +{ + FUSB_HID_PROTOCOL_BOOT = 0, + FUSB_HID_PROTOCOL_REPORT = 1 +} FUsbHidProtocol; + +enum +{ + FUSB_HID_BOOT_PROTOCOL_NONE = 0, + FUSB_HID_BOOT_PROTOCOL_KEYBOARD = 1, + FUSB_HID_BOOT_PROTOCOL_MOUSE = 2 +}; + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/* USB HID的初始化函数,由应用程序注册到FUSB框架中 */ +void FUsbHidInit(FUsbDev *dev); +int FUsbHidCheckInput(FUsbDev *dev, int times); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_hub.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hub.c new file mode 100644 index 0000000000..a18cd4e09f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hub.c @@ -0,0 +1,493 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_hub.c + * Date: 2022-02-11 13:33:07 + * LastEditTime: 2022-02-17 17:48:52 + * Description:  This files is for implmentation of USB hub function + * you may refer to chapter 11 Hub specification for details + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include "fkernel.h" +#include "fdebug.h" +#include "fassert.h" + +#include "fusb_private.h" +#include "fusb_generic_hub.h" + +#define FUSB_DEBUG_TAG "FUSB_HUB" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +/* assume that FUSB_REQ_HOST_TO_DEVICE is overwritten if necessary */ +#define DR_PORT FUsbGenerateReqType(FUSB_REQ_HOST_TO_DEVICE, FUSB_REQ_TYPE_CLASS, FUSB_REQ_RECP_OTHER) /* 10100011B */ +#define DR_HUB FUsbGenerateReqType(FUSB_REQ_HOST_TO_DEVICE, FUSB_REQ_TYPE_CLASS, FUSB_REQ_RECP_DEV) /* 10100000B */ + +#define FUSB_HUB_PORT_STATUS 0 +#define FUSB_HUB_PORT_CHANGE 1 + +#define FUSB_HUB_PORT_BUF_LEN 2 + +/* status (and status change) bits, refer to Table 10-10, Port Status Field in USB spec */ +#define FUSB_HUB_STATUS_PORT_CONNECTION BIT(0) /* reflects if device is currently connected to this port */ +#define FUSB_HUB_STATUS_PORT_ENABLE BIT(1) /* reflects if this port is enabled */ +#define FUSB_HUB_STATUS_PORT_SUSPEND BIT(2) /* reflects if this port is suspend, only for USB2 */ +#define FUSB_HUB_STATUS_PORT_OVER_CURRENT BIT(3) /* reports over-current conditions in this port */ +#define FUSB_HUB_STATUS_PORT_RESET BIT(4) /* reset signaling asserted */ +#define FUSB_HUB_STATUS_BH_PORT_RESET BIT(5) /* warm reset completed */ +#define FUSB_HUB_STATUS_PORT_LINK_STATE BIT(6) /* link state changed */ +#define FUSB_HUB_STATUS_PORT_PORT_CONFIG_ERROR BIT(7) /* port fails to config */ + +/* feature selectors (for setting / clearing features), refer to USB spec. Table 10-17. Hub Class Feature Selectors for details */ +#define FUSB_HUB_SEL_PORT_RESET 4 +#define FUSB_HUB_SEL_PORT_POWER 8 +#define FUSB_HUB_SEL_C_PORT_CONNECTION 16 +#define FUSB_HUB_SEL_C_PORT_ENABLE 17 /* USB2 only */ +#define FUSB_HUB_SEL_C_PORT_SUSPEND 18 /* USB2 only */ +#define FUSB_HUB_SEL_C_PORT_OVER_CURRENT 19 +#define FUSB_HUB_SEL_C_PORT_RESET 20 +#define FUSB_HUB_SEL_C_PORT_LINK_STATE 25 +#define FUSB_HUB_SEL_C_PORT_CONFIG_ERROR 26 +#define FUSB_HUB_SEL_C_BH_PORT_RESET 27 + +/* request type (USB 3.0 hubs only) */ +#define SET_HUB_DEPTH 12 + +/** + * @name: FUsbHubIntrEp + * @msg: 获取USB Hub的中断端点 + * @return {FUsbEndpoint *} 中断类型的功能端点 + * @param {FUsbDev} *dev, Hub实例 + */ +static FUsbEndpoint *FUsbHubIntrEp(FUsbDev *const dev) +{ + FASSERT(dev); + int i; + + for (i = 0; i < dev->num_endp; ++i) + { + if (dev->endpoints[i].type == FUSB_INTERRUPT_EP && + dev->endpoints[i].direction == FUSB_IN) + return &dev->endpoints[i]; + } + + return NULL; +} + +/** + * @name: FUsbHubPortStatusChange + * @msg: Usb Hub的Port状态变化回调函数 + * @return {FUsbTransCode} USB请求返回值 + * @param {FUsbDev} *dev, Hub实例 + * @param {int} port, Port号 + */ +static FUsbTransCode FUsbHubPortStatusChange(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + unsigned short buf[FUSB_HUB_PORT_BUF_LEN]; /* Hub Status and Change Status */ + FUsbTransCode ret = FUsbGetStatus(dev, port, DR_PORT, sizeof(buf), buf); + + if (ret >= FUSB_CC_ZERO_BYTES) + { + ret = buf[FUSB_HUB_PORT_CHANGE] & FUSB_HUB_STATUS_PORT_CONNECTION; + if (ret) + { + ret = FUsbClearFeature(dev, port, FUSB_HUB_SEL_C_PORT_CONNECTION, DR_PORT); + } + } + + return ret; +} + +/** + * @name: FUsbHubPortConnected + * @msg: Usb Hub的Port连接回调函数 + * @return {FUsbTransCode} USB请求返回值 + * @param {FUsbDev} *dev, Hub实例 + * @param {int} port, Port号 + */ +static FUsbTransCode FUsbHubPortConnected(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + unsigned short buf[FUSB_HUB_PORT_BUF_LEN]; /* Hub Status and Change Status */ + FUsbTransCode ret = FUsbGetStatus(dev, port, DR_PORT, sizeof(buf), buf); + + if (ret >= FUSB_CC_ZERO_BYTES) + { + ret = buf[FUSB_HUB_PORT_STATUS] & FUSB_HUB_STATUS_PORT_CONNECTION; + } + + return ret; +} + +/** + * @name: FUsbHubPortInReset + * @msg: 检查Hub port是否处于Reset状态 + * @return {FUsbTransCode} USB请求返回值 + * @param {FUsbDev} *dev, Hub实例 + * @param {int} port, Port号 + */ +static FUsbTransCode FUsbHubPortInReset(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + unsigned short buf[FUSB_HUB_PORT_BUF_LEN]; /* Hub Status and Change Status */ + FUsbTransCode ret = FUsbGetStatus(dev, port, DR_PORT, sizeof(buf), buf); + + if (ret >= FUSB_CC_ZERO_BYTES) + ret = buf[FUSB_HUB_PORT_STATUS] & FUSB_HUB_STATUS_PORT_RESET; + + return ret; +} + +/** + * @name: FUsbHubPortEnabled + * @msg: 检查Hub port是否已使能 + * @return {FUsbTransCode} USB请求返回值 + * @param {FUsbDev} *dev, Hub实例 + * @param {int} port, Port号 + */ +static FUsbTransCode FUsbHubPortEnabled(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + unsigned short buf[FUSB_HUB_PORT_BUF_LEN]; /* Hub Status and Change Status */ + FUsbTransCode ret = FUsbGetStatus(dev, port, DR_PORT, sizeof(buf), buf); + + if (ret >= FUSB_CC_ZERO_BYTES) + ret = buf[FUSB_HUB_PORT_STATUS] & FUSB_HUB_STATUS_PORT_ENABLE; + + return ret; +} + +/** + * @name: FUsbHubPortSpeed + * @msg: 获取Hub port的速度类型 + * @return {FUsbSpeed} Port的速度类型,支持SuperSpeed和HighSpeed + * @param {FUsbDev} *dev, Hub实例 + * @param {int} port, Port号 + */ +static FUsbSpeed FUsbHubPortSpeed(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + unsigned short buf[FUSB_HUB_PORT_BUF_LEN]; /* Hub Status and Change Status */ + FUsbTransCode ret = FUsbGetStatus(dev, port, DR_PORT, sizeof(buf), buf); + int speed; + + if (ret >= FUSB_CC_ZERO_BYTES && (buf[FUSB_HUB_PORT_STATUS] & FUSB_HUB_STATUS_PORT_ENABLE)) + { + /* SuperSpeed hubs can only have SuperSpeed devices. */ + if (FUsbIsSuperSpeed(dev->speed)) + return dev->speed; + + /*[bit] 10 9 (USB 2.0 port status word) + * 0 0 full speed + * 0 1 low speed + * 1 0 high speed + * 1 1 invalid + */ + speed = (buf[FUSB_HUB_PORT_STATUS] >> 9) & 0x3; + if (speed != 0x3) /* high-speed device */ + return speed; + } + + return FUSB_UNKNOWN_SPEED; +} + +/** + * @name: FUsbHubEnablePort + * @msg: 使能Hub port + * @return {FUsbTransCode} USB请求返回值 + * @param {FUsbDev} *dev, Hub实例 + * @param {int} port, port号 + */ +static FUsbTransCode FUsbHubEnablePort(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + return FUsbSetFeature(dev, port, FUSB_HUB_SEL_PORT_POWER, DR_PORT); +} + +/** + * @name: FUsbHubStartPortReset + * @msg: 开始Reset Hub port + * @return {FUsbTransCode} USB请求返回值 + * @param {FUsbDev} *dev, Hub实例 + * @param {int} port, port号 + */ +static FUsbTransCode FUsbHubStartPortReset(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + return FUsbSetFeature(dev, port, FUSB_HUB_SEL_PORT_RESET, DR_PORT); +} + +static void FUsbHubSetHubDepth(FUsbDev *const dev) +{ + FASSERT(dev); + FUsbDevReq dr = + { + .bmRequestType = FUsbGenerateReqType(FUSB_REQ_HOST_TO_DEVICE, + FUSB_REQ_TYPE_CLASS, FUSB_REQ_RECP_DEV), + .bRequest = SET_HUB_DEPTH, + .wValue = 0, + .wIndex = 0, + .wLength = 0, + }; + FUsbDev *parent = dev; + + FASSERT(dev->controller); + while (parent->hub > 0) + { + FASSERT(dev->controller->devices[parent->hub]); + parent = dev->controller->devices[parent->hub]; + dr.wValue++; + } + + FUsbTransCode ret = dev->controller->control(dev, FUSB_OUT, sizeof(dr), &dr, 0, NULL); + if (ret < FUSB_CC_ZERO_BYTES) + { + FUSB_ERROR("Failed SET_HUB_DEPTH(%d) on hub %d: %d ", + dr.wValue, dev->address, ret); + } + + return; +} + +static const FUsbGenericHubOps FUSB_HUB_OPS = +{ + .hub_status_changed = NULL, + .port_status_changed = FUsbHubPortStatusChange, + .port_connected = FUsbHubPortConnected, + .port_in_reset = FUsbHubPortInReset, + .port_enabled = FUsbHubPortEnabled, + .port_speed = FUsbHubPortSpeed, + .enable_port = FUsbHubEnablePort, + .disable_port = NULL, + .start_port_reset = FUsbHubStartPortReset, + .reset_port = FUsbGenericHubResetPort, +}; + +/* Clear CSC if set and enumerate port if it's connected regardless of change + bits. Some broken hubs don't set CSC if already connected during reset. */ +static void FUsbHubPortInit(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + unsigned short buf[FUSB_HUB_PORT_BUF_LEN]; /* Hub Status and Change Status */ + FUsbTransCode ret = FUsbGetStatus(dev, port, DR_PORT, sizeof(buf), buf); + + if (ret < FUSB_CC_ZERO_BYTES) + return; + + if (buf[FUSB_HUB_PORT_CHANGE] & FUSB_HUB_STATUS_PORT_CONNECTION) + FUsbClearFeature(dev, port, FUSB_HUB_SEL_C_PORT_CONNECTION, DR_PORT); + + if (buf[FUSB_HUB_PORT_STATUS] & FUSB_HUB_STATUS_PORT_CONNECTION) + { + FUSB_INFO("usbhub: Port coldplug at %d ", port); + FUsbGenericHubScanPort(dev, port); + } + + return; +} + +/** + * @name: FUsbHubHandlePortChange + * @msg: Hub端口状态变化的处理回调函数 + * @return {*} + * @param {FUsbDev} *dev + * @param {int} port + */ +static FUsbTransCode FUsbHubHandlePortChange(FUsbDev *const dev, const int port) +{ + FASSERT(dev); + static const struct + { + unsigned short change_bit; + unsigned short clear_sel; + } change_bits[] = + { + {FUSB_HUB_STATUS_PORT_CONNECTION, FUSB_HUB_SEL_C_PORT_CONNECTION}, + {FUSB_HUB_STATUS_PORT_ENABLE, FUSB_HUB_SEL_C_PORT_ENABLE}, + {FUSB_HUB_STATUS_PORT_SUSPEND, FUSB_HUB_SEL_C_PORT_SUSPEND}, + {FUSB_HUB_STATUS_PORT_OVER_CURRENT, FUSB_HUB_SEL_C_PORT_OVER_CURRENT}, + {FUSB_HUB_STATUS_PORT_RESET, FUSB_HUB_SEL_C_PORT_RESET}, + {FUSB_HUB_STATUS_BH_PORT_RESET, FUSB_HUB_SEL_C_BH_PORT_RESET}, + {FUSB_HUB_STATUS_PORT_LINK_STATE, FUSB_HUB_SEL_C_PORT_LINK_STATE}, + {FUSB_HUB_STATUS_PORT_PORT_CONFIG_ERROR, FUSB_HUB_SEL_C_PORT_CONFIG_ERROR}, + }; + + FUsbTransCode ret = 0; + unsigned int i; + unsigned short checked_bits = 0; + unsigned short buf[FUSB_HUB_PORT_BUF_LEN] = {0, 0}; /* Hub Status and Change Status */ + + ret = FUsbGetStatus(dev, port, DR_PORT, sizeof(buf), buf); + if (ret < FUSB_CC_ZERO_BYTES) + return ret; + + /* + * Second word holds the change bits. The interrupt transfer shows + * a logical or of these bits, so we have to clear them all. + */ + for (i = 0; i < ARRAY_SIZE(change_bits); ++i) + { + if (buf[FUSB_HUB_PORT_CHANGE] & change_bits[i].change_bit) + { + /* clear feature if specific change bit = 1 */ + FUsbClearFeature(dev, port, change_bits[i].clear_sel, DR_PORT); + } + + checked_bits |= change_bits[i].change_bit; + } + + if (buf[FUSB_HUB_PORT_CHANGE] & ~checked_bits) + FUSB_DEBUG("Spurious change bit at port %d ", port); + + /* Now, handle connection changes. */ + if (buf[FUSB_HUB_PORT_CHANGE] & FUSB_HUB_STATUS_PORT_CONNECTION) + { + FUSB_DEBUG("Port change at %d ", port); + ret = FUsbGenericHubScanPort(dev, port); + } + + return ret; +} + +/** + * @name: FUsbHubPoll + * @msg: 轮询Hub的所有端口,检查端口状态变化 + * @return {*} + * @param {FUsbDev} *dev, Hub设备实例 + */ +static void FUsbHubPoll(FUsbDev *const dev) +{ + FASSERT(dev); + int port, i; + u8 buf[32] = {0}; + const u8 *ibuf; + + /* First, gather all change bits from finished interrupt transfers. */ + const size_t port_bytes = min(ARRAY_SIZE(buf), + (size_t)DIV_ROUND_UP(FUSB_GEN_HUB_GET(dev)->num_ports + 1, 8)); + + while (NULL != (ibuf = dev->controller->poll_intr_queue(FUSB_GEN_HUB_GET(dev)->data))) + { + for (i = 0; (size_t)i < port_bytes; ++i) + buf[i] |= ibuf[i]; + } + + for (port = 1; port <= FUSB_GEN_HUB_GET(dev)->num_ports; ++port) + { + /* ports start at bit1; bit0 is hub status change */ + if (buf[port / 8] & (1 << (port % 8))) + { + if (FUsbHubHandlePortChange(dev, port) < 0) + return; + } + } + + return; +} + +/** + * @name: FUsbHubDestory + * @msg: USB Hub的去初始化函数 + * @return {*} + * @param {FUsbDev} *dev, Hub设备实例 + */ +static void FUsbHubDestory(FUsbDev *const dev) +{ + FASSERT(dev); + FUsbEndpoint *const intr_ep = FUsbHubIntrEp(dev); + FASSERT(intr_ep); /* interrupt ep must exists */ + dev->controller->destroy_intr_queue(intr_ep, FUSB_GEN_HUB_GET(dev)->data); + FUsbGenericHubDestory(dev); +} + +/** + * @name: FUsbHubInit + * @msg: USB Hub的初始化函数,由应用程序注册到FUSB框架中 + * @return {*} + * @param {FUsbDev} *dev, Hub设备实例 + */ +void FUsbHubInit(FUsbDev *dev) +{ + FASSERT(dev); + FUsbEndpoint *const intr_ep = FUsbHubIntrEp(dev); /* get the first intrrupt ep found */ + if (NULL == intr_ep) + { + FUSB_ERROR("No interrupt-in endpoint found "); + return; + } + + FASSERT(dev->controller); + + /* Get number of ports from hub descriptor */ + int type = FUsbIsSuperSpeed(dev->speed) ? FUSB_DESC_TYPE_SUPER_SPEED_HUB : FUSB_DESC_TYPE_HUB; /* similar enough */ + FUsbHubDescriptor desc; /* won't fit the whole thing, we don't care */ + if (FUsbGetDescriptor(dev, FUsbGenerateReqType(FUSB_REQ_DEVICE_TO_HOST, FUSB_REQ_TYPE_CLASS, FUSB_REQ_RECP_DEV), type, 0, &desc, sizeof(desc)) != sizeof(desc)) + { + FUSB_ERROR("FUsbGetDescriptor(HUB) failed "); + FUsbDetachDev(dev->controller, dev->address); + return; + } + + if (FUsbIsSuperSpeed(dev->speed)) + { + FUsbHubSetHubDepth(dev); + } + + /* + * Register interrupt transfer: + * one bit per port + one bit for the hub, + * 20 transfers in the queue, like our HID driver, + * one transfer per 256ms + */ + void *const intrq = dev->controller->create_intr_queue( + intr_ep, intr_ep->maxpacketsize, 20, 256); + if (NULL == intrq) + { + FUsbDetachDev(dev->controller, dev->address); + return; + } + + /* + * Limit the number of ports by the max packet size of + * the interrupt endpoint. This shouldn't be necessary + * but prevents a potential overflow in FUsbHubPoll(). + */ + const unsigned int num_ports = + min((int)desc.bNbrPorts, intr_ep->maxpacketsize * 8 - 1); + if (FUsbGenericHubInit(dev, num_ports, &FUSB_HUB_OPS)) + { + dev->controller->destroy_intr_queue(intr_ep, intrq); + FUsbDetachDev(dev->controller, dev->address); + return; + } + + unsigned int port; + for (port = 1; port <= num_ports; ++port) + { + FUsbHubPortInit(dev, port); + } + + FUSB_GEN_HUB_GET(dev)->data = intrq; + dev->poll = FUsbHubPoll; + dev->destroy = FUsbHubDestory; + + return; +} diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_hub.h b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hub.h new file mode 100644 index 0000000000..5e6235a11f --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_hub.h @@ -0,0 +1,65 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_hub.h + * Date: 2022-02-11 13:33:09 + * LastEditTime: 2022-02-17 17:49:20 + * Description:  This files is for definition of USB hub device function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_USB_HUB_H +#define DRIVERS_USB_HUB_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "fusb.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ +enum +{ + FUSB_HUB_SUBCLASS_DEFAULT = 0x0 +}; + +enum +{ + FUSB_HUB_PROTOCOL_FULL_SPEED = 0x0, + FUSB_HUB_PROTOCOL_HIGH_SPEED_WITH_SINGLE_TT = 0x1, + FUSB_HUB_PROTOCOL_HIGH_SPEED_WITH_MULTIPLE_TT = 0x2 +}; + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/* USB Hub的初始化函数,由应用程序注册到FUSB框架中 */ +void FUsbHubInit(FUsbDev *dev); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_msc.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_msc.c new file mode 100644 index 0000000000..0e6a8a64ef --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_msc.c @@ -0,0 +1,859 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_msc.c + * Date: 2022-02-11 13:33:09 + * LastEditTime: 2022-02-17 17:49:43 + * Description:  This files is for implementation of USB mass storage function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include +#include "fswap.h" +#include "fsleep.h" +#include "fassert.h" +#include "fgeneric_timer.h" +#include "fdebug.h" + +#include "fusb.h" +#include "fusb_msc.h" + + +#define FUSB_DEBUG_TAG "FUSB_MSC" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +static inline tick_t FUsbMscGetTick(void) +{ + return GenericTimerRead(); +} + +static inline tick_t FUsbMscStartTick(void) +{ + GenericTimerStart(); + return FUsbMscGetTick(); +} + +static inline void FUsbMscStopTick(void) +{ + GenericTimerStop(); +} + +static inline boolean FUsbMscTimeout(tick_t start_tick, tick_t timeout_tick) +{ + return (FUsbMscGetTick() - start_tick) > timeout_tick; +} + +static void FUsbMassStorageForceInit(FUsbDev *dev, u32 quirks); +static int FUsbMscRwBlks(FUsbDev *dev, int start, int n, FUsbMassStorageDirection dir, u8 *buf); + +static const char *FUsbMscSubClassString[7] = +{ + "(none)", + "RBC", + "MMC-2", + "QIC-157", + "UFI", + "SFF-8070i", + "SCSI transparent" +}; + +static const char *FUsbMscProtocolStrings[0x51] = +{ + "Control/Bulk/Interrupt protocol (with command completion interrupt)", + "Control/Bulk/Interrupt protocol (with no command completion interrupt)", + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + "Bulk-Only Transport" +}; + +/** + * @name: FUsbMscCreateDisk + * @msg: 调用应用程序实现的钩子函数,创建USB Disk + * @return {*} + * @param {FUsbDev} *dev, USB大容量存储设备实例 + */ +static void FUsbMscCreateDisk(FUsbDev *dev) +{ + FASSERT(dev); + + if (FUsbDiskCreate) + { + FUsbDiskCreate(dev); + MSC_INST(dev)->usbdisk_created = 1; + } + + return; +} + +/** + * @name: FUsbMscRemoveDisk + * @msg: 调用应用程序实现的钩子函数,移除USB Disk + * @return {*} + * @param {FUsbDev} *dev, USB大容量存储设备实例 + */ +static void FUsbMscRemoveDisk(FUsbDev *dev) +{ + FASSERT(dev); + + if (MSC_INST(dev)->usbdisk_created && FUsbDiskRemove) + FUsbDiskRemove(dev); + + return; +} + +/** + * @name: FUsbMscDestory + * @msg: 移除USB大容量存储设备实例 + * @return {*} + * @param {FUsbDev} *dev, USB大容量存储设备实例 + */ +static void FUsbMscDestory(FUsbDev *dev) +{ + FASSERT(dev && dev->controller); + FUsb *instance = dev->controller->usb; + FASSERT(instance); + + if (NULL != dev->data) + { + FUsbMscRemoveDisk(dev); + FUSB_FREE(instance, dev->data); + } + + dev->data = NULL; + return; +} + +const int DEV_RESET = 0xff; +const int GET_MAX_LUN = 0xfe; +/* Many USB3 devices do not work with large transfer requests. + * Limit the request size to 64KB chunks to ensure maximum compatibility. */ +const int MAX_CHUNK_BYTES = 1024 * 64; + +const unsigned int cbw_signature = 0x43425355; /* according to USB mass-bulk spec. helps to identify data packets */ +const unsigned int csw_signature = 0x53425355; + +/* following data structure following name convention in USB mass-bulk spec., which may not compiliance to other code */ + +/* A packet containing a command block and associated information. */ +typedef struct +{ + unsigned int dCBWSignature; + unsigned int dCBWTag; + unsigned int dCBWDataTransferLength; + unsigned char bmCBWFlags; + unsigned long bCBWLUN : 4; /* device Logical Unit Number (LUN) */ + unsigned long : 4; + unsigned long bCBWCBLength : 5; + unsigned long : 3; + unsigned char CBWCB[31 - 15]; +} __attribute__((packed)) FUsbMscCbw; /* Command Block Wrapper (CBW) */ + +/* A packet containing the status of a command block */ +typedef struct +{ + unsigned int dCSWSignature; + unsigned int dCSWTag; + unsigned int dCSWDataResidue; + unsigned char bCSWStatus; +} __attribute__((packed)) FUsbMscCsw; + +enum +{ + /* + * MSC commands can be + * successful, + * fail with proper response or + * fail totally, which results in detaching of the USB device + * and immediate cleanup of the FUsbDev structure. + * In the latter case the caller has to make sure, that he won't + * use the device any more. + */ + MSC_COMMAND_OK = 0, + MSC_COMMAND_FAIL, + MSC_COMMAND_DETACHED +}; + +static int FUsbMscRequestSense(FUsbDev *dev); +static int FUsbMscRequestNoMedia(FUsbDev *dev); +static void FUsbMscPoll(FUsbDev *dev); + +static int FUsbClearStall(FUsbEndpoint *ep) +{ + FASSERT(ep); + int ret = FUsbClearFeature(ep->dev, ep->endpoint, FUSB_ENDPOINT_HALT, + FUsbGenerateReqType(FUSB_REQ_HOST_TO_DEVICE, FUSB_REQ_TYPE_STANDARD, FUSB_REQ_RECP_EP)); + + ep->toggle = 0; + + return ret; +} + +static int FUsbMscResetTransport(FUsbDev *dev) +{ + FUsbDevReq dr; + memset(&dr, 0, sizeof(dr)); + dr.bmRequestType = 0; + dr.data_dir = FUSB_REQ_HOST_TO_DEVICE; + dr.req_type = FUSB_REQ_TYPE_CLASS; + dr.req_recp = FUSB_REQ_RECP_IF; + dr.bRequest = DEV_RESET; + dr.wValue = 0; + dr.wIndex = 0; + dr.wLength = 0; + + if (MSC_INST(dev)->quirks & FUSB_MSC_QUIRK_NO_RESET) + return MSC_COMMAND_FAIL; + + /* if any of these fails, detach device, as we are lost */ + if (dev->controller->control(dev, FUSB_OUT, sizeof(dr), &dr, 0, 0) < 0 || + FUsbClearStall(MSC_INST(dev)->bulk_in) || + FUsbClearStall(MSC_INST(dev)->bulk_out)) + { + FUSB_INFO("Detaching unresponsive device. "); + FUsbDetachDev(dev->controller, dev->address); + return MSC_COMMAND_DETACHED; + } + /* return fail as we are only called in case of failure */ + return MSC_COMMAND_FAIL; +} + +/* device may stall this command, so beware! */ +static void FUsbMscInitLuns(FUsbDev *dev) +{ + FUsbMassStorage *msc = MSC_INST(dev); + FUsbDevReq dr; + dr.bmRequestType = 0; + dr.data_dir = FUSB_REQ_DEVICE_TO_HOST; + dr.req_type = FUSB_REQ_TYPE_CLASS; + dr.req_recp = FUSB_REQ_RECP_IF; + dr.bRequest = GET_MAX_LUN; + dr.wValue = 0; + dr.wIndex = 0; + dr.wLength = 1; + + /* send class-spefic request Get Max Lun */ + if ((MSC_INST(dev)->quirks & FUSB_MSC_QUIRK_NO_LUNS) || + (dev->controller->control(dev, FUSB_IN, sizeof(dr), &dr, + sizeof(msc->num_luns), &msc->num_luns) < FUSB_CC_ZERO_BYTES)) + { + msc->num_luns = 0; /* assume only 1 lun if req fails */ + } + + msc->num_luns++; /* Get Max LUN returns number of last LUN */ + msc->lun = 0; + + return; +} + +unsigned int tag; +static void FUsbMscWrapCbw(FUsbMscCbw *cbw, int datalen, FUsbMassStorageDirection dir, const u8 *cmd, + int cmdlen, u8 lun) +{ + memset(cbw, 0, sizeof(FUsbMscCbw)); + + /* commands are typically shorter, but we don't want overflows */ + if ((size_t)cmdlen > sizeof(cbw->CBWCB)) + { + cmdlen = (int)sizeof(cbw->CBWCB); + } + + cbw->dCBWSignature = cbw_signature; + cbw->dCBWTag = ++tag; /* command block tag to device */ + cbw->bCBWLUN = lun; /* logic unit number to send */ + + cbw->dCBWDataTransferLength = datalen; /* number of bytes of data expect to transfer */ + cbw->bmCBWFlags = dir; + + memcpy(cbw->CBWCB, cmd, cmdlen); /* the command block to be executed by the device */ + + cbw->bCBWCBLength = cmdlen; /* the valid length of the CBWCB in bytes */ + return; +} + +static int FUsbMscGetCsw(FUsbEndpoint *ep, FUsbMscCsw *csw) +{ + FUsbHc *ctrlr = ep->dev->controller; + int ret = ctrlr->bulk(ep, sizeof(FUsbMscCsw), (u8 *)csw, 1); + + /* Some broken sticks send a zero-length packet at the end of their data + transfer which would show up here. Skip it to get the actual CSW. */ + if (ret == 0) + ret = ctrlr->bulk(ep, sizeof(FUsbMscCsw), (u8 *)csw, 1); + + if (ret < 0) + { + FUsbClearStall(ep); + ret = ctrlr->bulk(ep, sizeof(FUsbMscCsw), (u8 *)csw, 1); + if (ret < 0) + return FUsbMscResetTransport(ep->dev); + } + + if (ret != sizeof(FUsbMscCsw) || csw->dCSWTag != tag || + csw->dCSWSignature != csw_signature) + { + FUSB_INFO("MSC: received malformed CSW "); + return FUsbMscResetTransport(ep->dev); + } + + return MSC_COMMAND_OK; +} + +static int FUsbMscExecCmd(FUsbDev *dev, FUsbMassStorageDirection dir, const u8 *cb, int cblen, + u8 *buf, int buflen, int residue_ok) +{ + FUsbMscCbw cbw; + FUsbMscCsw csw; + + int always_succeed = 0; + if ((cb[0] == 0x1b) && (cb[4] == 1)) /* check if it is Bulk-Only Mass Storage Reset request with reques type 00100001b */ + { + /* start command, always succeed */ + always_succeed = 1; + } + + FUsbMscWrapCbw(&cbw, buflen, dir, cb, cblen, MSC_INST(dev)->lun); + + if (dev->controller->bulk(MSC_INST(dev)->bulk_out, sizeof(cbw), (u8 *)&cbw, 0) < 0) + { + return FUsbMscResetTransport(dev); + } + + if (buflen > 0) + { + if (dir == FUSB_DIR_DATA_IN) + { + if (dev->controller->bulk(MSC_INST(dev)->bulk_in, buflen, buf, 0) < 0) + FUsbClearStall(MSC_INST(dev)->bulk_in); + } + else + { + if (dev->controller->bulk(MSC_INST(dev)->bulk_out, buflen, buf, 0) < 0) + FUsbClearStall(MSC_INST(dev)->bulk_out); + } + } + + int ret = FUsbMscGetCsw(MSC_INST(dev)->bulk_in, &csw); + + if (ret) + { + return ret; + } + else if (always_succeed == 1) + { + /* return success, regardless of message */ + return MSC_COMMAND_OK; + } + else if (csw.bCSWStatus == 2) + { + /* phase error, reset transport */ + return FUsbMscResetTransport(dev); + } + else if (csw.bCSWStatus == 0) + { + if ((csw.dCSWDataResidue == 0) || residue_ok) + /* no error, exit */ + return MSC_COMMAND_OK; + else + /* missed some bytes */ + return MSC_COMMAND_FAIL; + } + else + { + if (cb[0] == 0x03) + /* requesting sense failed, that's bad */ + return MSC_COMMAND_FAIL; + else if (cb[0] == 0) + /* If command was TEST UNIT READY determine if the + * device is of removable type indicating no media + * found. */ + return FUsbMscRequestNoMedia(dev); + /* error "check condition" or reserved error */ + ret = FUsbMscRequestSense(dev); + /* return fail or the status of FUsbMscRequestSense if it's worse */ + return ret ? ret : MSC_COMMAND_FAIL; + } +} + +typedef struct +{ + unsigned char command; /* 0 */ + unsigned char res1; /* 1 */ + unsigned int block; /* 2-5 */ + unsigned char res2; /* 6 */ + unsigned short numblocks; /* 7-8 */ + unsigned char control; /* 9 - the block is 10 bytes long */ +} __attribute__((packed)) FUsbMscCmdBlk; + +typedef struct +{ + unsigned char command; /* 0 */ + unsigned char res1; /* 1 */ + unsigned char res2; /* 2 */ + unsigned char res3; /* 3 */ + union + { + /* 4 */ + struct + { + unsigned long start : 1; /* for START STOP UNIT */ + unsigned long : 7; + }; + unsigned char length; /* for REQUEST SENSE */ + }; + unsigned char control; /* 5 */ +} __attribute__((packed)) FUsbMscCmdBlk6; + +/** + * Like FUsbMscRwBlks, but for soft-sectors of 512b size. Converts the + * start and count from 512b units. + * Start and count must be aligned so that they match the native + * sector size. + * + */ +/** + * @name: FUsbMscRwBlk512 + * @msg: 读写USB大容量存储设备,以512字节为一块 + * @param dev device to access + * @param start first sector to access + * @param n number of sectors to access + * @param dir direction of access: FUSB_DIR_DATA_IN == read, FUSB_DIR_DATA_OUT == write + * @param buf buffer to read into or write from. Must be at least n*512 bytes + * @return 0 on success, 1 on failure + */ +int FUsbMscRwBlk512(FUsbDev *dev, int start, int n, + FUsbMassStorageDirection dir, u8 *buf) +{ + int blocksize_divider = MSC_INST(dev)->blocksize / 512; + return FUsbMscRwBlks(dev, start / blocksize_divider, + n / blocksize_divider, dir, buf); +} + +/** + * Reads or writes a number of sequential blocks on a USB storage device. + * As it uses the READ(10) SCSI-2 command, it's limited to storage devices + * of at most 2TB. It assumes sectors of 512 bytes. + * + * @param dev device to access + * @param start first sector to access + * @param n number of sectors to access + * @param dir direction of access: FUSB_DIR_DATA_IN == read, FUSB_DIR_DATA_OUT == write + * @param buf buffer to read into or write from. Must be at least n*sectorsize bytes + * @return 0 on success, 1 on failure + */ +static int FUsbMscRwChunk(FUsbDev *dev, int start, int n, FUsbMassStorageDirection dir, u8 *buf) +{ + FUsbMscCmdBlk cb; + memset(&cb, 0, sizeof(cb)); + if (dir == FUSB_DIR_DATA_IN) + { + /* read */ + cb.command = 0x28; + } + else + { + /* write */ + cb.command = 0x2a; + } + cb.block = htonl(start); + cb.numblocks = htons(n); + + return FUsbMscExecCmd(dev, dir, (u8 *)&cb, sizeof(cb), buf, + n * MSC_INST(dev)->blocksize, 0) != MSC_COMMAND_OK + ? 1 + : 0; +} + +/** + * Reads or writes a number of sequential blocks on a USB storage device + * that is split into MAX_CHUNK_BYTES size requests. + * + * As it uses the READ(10) SCSI-2 command, it's limited to storage devices + * of at most 2TB. It assumes sectors of 512 bytes. + * + * @param dev device to access + * @param start first sector to access + * @param n number of sectors to access + * @param dir direction of access: FUSB_DIR_DATA_IN == read, + * FUSB_DIR_DATA_OUT == write + * @param buf buffer to read into or write from. + * Must be at least n*sectorsize bytes + * @return 0 on success, 1 on failure + */ +static int FUsbMscRwBlks(FUsbDev *dev, int start, int n, FUsbMassStorageDirection dir, u8 *buf) +{ + int chunk_size = MAX_CHUNK_BYTES / MSC_INST(dev)->blocksize; + int chunk; + + /* Read as many full chunks as needed. */ + for (chunk = 0; chunk < (n / chunk_size); chunk++) + { + if (FUsbMscRwChunk(dev, start + (chunk * chunk_size), + chunk_size, dir, + buf + (chunk * MAX_CHUNK_BYTES)) != MSC_COMMAND_OK) + return 1; + } + + /* Read any remaining partial chunk at the end. */ + if (n % chunk_size) + { + if (FUsbMscRwChunk(dev, start + (chunk * chunk_size), + n % chunk_size, dir, + buf + (chunk * MAX_CHUNK_BYTES)) != MSC_COMMAND_OK) + return 1; + } + + return 0; +} + +/* Only request it, we don't interpret it. + On certain errors, that's necessary to get devices out of + a special state called "Contingent Allegiance Condition" */ +static int FUsbMscRequestSense(FUsbDev *dev) +{ + u8 buf[19]; + FUsbMscCmdBlk6 cb; + memset(&cb, 0, sizeof(cb)); + cb.command = 0x3; + cb.length = sizeof(buf); + + return FUsbMscExecCmd(dev, FUSB_DIR_DATA_IN, (u8 *)&cb, + sizeof(cb), buf, sizeof(buf), 1); +} + +static int FUsbMscRequestNoMedia(FUsbDev *dev) +{ + u8 buf[19]; + int ret; + FUsbMscCmdBlk6 cb; + memset(&cb, 0, sizeof(cb)); + cb.command = 0x3; + cb.length = sizeof(buf); + + ret = FUsbMscExecCmd(dev, FUSB_DIR_DATA_IN, (u8 *)&cb, + sizeof(cb), buf, sizeof(buf), 1); + + if (ret) + return ret; + + /* Check if sense key is set to NOT READY. */ + if ((buf[2] & 0xf) != 2) + return MSC_COMMAND_FAIL; + + /* Check if additional sense code is 0x3a. */ + if (buf[12] != 0x3a) + return MSC_COMMAND_FAIL; + + /* No media is present. Return MSC_COMMAND_OK while marking the disk + * not ready. */ + FUSB_INFO("Empty media found. "); + MSC_INST(dev)->ready = FUSB_MSC_NOT_READY; + return MSC_COMMAND_OK; +} + +static int FUsbMscCheckIfReady(FUsbDev *dev) +{ + FUsbMscCmdBlk6 cb; + memset(&cb, 0, sizeof(cb)); /* full initialization for T-U-R */ + + /* Bulk-Only Mass Storage Reset, class-specific request */ + return FUsbMscExecCmd(dev, FUSB_DIR_DATA_OUT, (u8 *)&cb, + sizeof(cb), 0, 0, 0); +} + +static int FUsbMscSpinUp(FUsbDev *dev) +{ + FUsbMscCmdBlk6 cb; + memset(&cb, 0, sizeof(cb)); + cb.command = 0x1b; + cb.start = 1; + return FUsbMscExecCmd(dev, FUSB_DIR_DATA_OUT, (u8 *)&cb, + sizeof(cb), 0, 0, 0); +} + +static int FUsbMscReadCapcity(FUsbDev *dev) +{ + FUsbMscCmdBlk cb; + memset(&cb, 0, sizeof(cb)); + cb.command = 0x25; /* read capacity */ + u32 buf[2]; + + FUSB_INFO("Reading capacity of mass storage device. "); + int count = 0, ret; + while (count++ < 20) + { + switch (ret = FUsbMscExecCmd(dev, FUSB_DIR_DATA_IN, (u8 *)&cb, + sizeof(cb), (u8 *)buf, 8, 0)) + { + case MSC_COMMAND_OK: + break; + case MSC_COMMAND_FAIL: + continue; + default: /* if it's worse return */ + return ret; + } + break; + } + if (count >= 20) + { + /* still not successful, assume 2tb in 512byte sectors, which is just the same garbage as any other number, but probably more usable. */ + FUSB_WARN(" assuming 2 TB with 512-byte sectors as READ CAPACITY didn't answer. "); + MSC_INST(dev)->numblocks = 0xffffffff; + MSC_INST(dev)->blocksize = 512; + } + else + { + MSC_INST(dev)->numblocks = ntohl(buf[0]) + 1; + MSC_INST(dev)->blocksize = ntohl(buf[1]); + } + + FUSB_INFO(" %d %d-byte sectors (%d MB) ", MSC_INST(dev)->numblocks, + MSC_INST(dev)->blocksize, + /* round down high block counts to avoid integer overflow */ + MSC_INST(dev)->numblocks > 1000000 + ? (MSC_INST(dev)->numblocks / 1000) * MSC_INST(dev)->blocksize / 1000 + : MSC_INST(dev)->numblocks * MSC_INST(dev)->blocksize / 1000 / 1000); + + return MSC_COMMAND_OK; +} + +static int FUsbMscWaitReady(FUsbDev *dev) +{ + int i; + /* SCSI/ATA specs say we have to wait up to 30s, but most devices + * are ready much sooner. Use a 5 sec timeout to better accommodate + * devices which fail to respond. */ + const tick_t timeout_tick = 1000000; + FError ret = FUSB_ERR_WAIT_TIMEOUT; + + FUSB_INFO(" Waiting for device to become ready..."); + + /* Initially mark the device ready. */ + MSC_INST(dev)->ready = FUSB_MSC_READY; + tick_t start_tick = FUsbMscStartTick(); + + do + { + switch (FUsbMscCheckIfReady(dev)) + { + case MSC_COMMAND_OK: + break; + case MSC_COMMAND_FAIL: + fsleep_millisec(100); + FUSB_INFO("."); + continue; + default: + /* Device detached, return immediately */ + return FUSB_MSC_DETACHED; + } + break; + } + while (!FUsbMscTimeout(start_tick, timeout_tick)); + + if (FUsbMscTimeout(start_tick, timeout_tick)) + { + FUSB_INFO("timeout. Device not ready. "); + MSC_INST(dev)->ready = FUSB_MSC_NOT_READY; + } + + /* Don't bother spinning up the storage device if the device is not + * ready. This can happen when empty card readers are present. + * Polling will pick it back up if readiness changes. */ + if (!MSC_INST(dev)->ready) + return MSC_INST(dev)->ready; + + for (i = 0; i < 30; i++) + { + FUSB_INFO("."); + switch (FUsbMscSpinUp(dev)) + { + case MSC_COMMAND_OK: + FUSB_INFO(" OK."); + break; + case MSC_COMMAND_FAIL: + fsleep_millisec(100); + continue; + default: + /* Device detached, return immediately */ + return FUSB_MSC_DETACHED; + } + break; + } + + if (FUsbMscReadCapcity(dev) == MSC_COMMAND_DETACHED) + return FUSB_MSC_DETACHED; + + return MSC_INST(dev)->ready; +} + +/** + * @name: FUsbMassStorageInit + * @msg: USB大容量存储设备的初始化函数,由应用程序注册到FUSB框架中 + * @return {*} + * @param {FUsbDev} *dev, USB大容量存储设备实例 + */ +void FUsbMassStorageInit(FUsbDev *dev) +{ + FASSERT(dev && dev->configuration); + FUsbConfigurationDescriptor *cd = + (FUsbConfigurationDescriptor *)dev->configuration; + FASSERT(FUSB_DESC_TYPE_CONFIG == cd->bDescriptorType); + FUsbInterfaceDescriptor *interface = + (FUsbInterfaceDescriptor *)(((char *)cd) + cd->bLength); + FASSERT(FUSB_DESC_TYPE_INTERFACE == interface->bDescriptorType); + + if (FUSB_MASS_STORAGE_DEVICE != interface->bInterfaceClass) + { + FUSB_ERROR("Class %d not supported. ", interface->bInterfaceClass); + return; + } + + FUSB_INFO(" command set: %s protocol: %s ", + FUsbMscSubClassString[interface->bInterfaceSubClass], + FUsbMscProtocolStrings[interface->bInterfaceProtocol]); + + if (interface->bInterfaceProtocol != FUSB_MSC_PROTOCOL_BULK_ONLY) + { + FUSB_ERROR(" Protocol not supported. "); + FUsbDetachDev(dev->controller, dev->address); + return; + } + + if ((interface->bInterfaceSubClass != FUSB_MSC_SUBCLASS_ATAPI_8020) && /* ATAPI 8020 */ + (interface->bInterfaceSubClass != FUSB_MSC_SUBCLASS_ATAPI_8070) && /* ATAPI 8070 */ + (interface->bInterfaceSubClass != FUSB_MSC_SUBCLASS_SCSI)) + { + /* SCSI */ + /* Other protocols, such as ATAPI don't seem to be very popular. looks like ATAPI would be really easy to add, if necessary. */ + FUSB_ERROR(" Interface SubClass not supported. "); + FUsbDetachDev(dev->controller, dev->address); + return; + } + + FUsbMassStorageForceInit(dev, 0); + return; +} + +/* Force a device to enumerate as MSC, without checking class/protocol types. + It must still have a bulk endpoint pair and respond to MSC commands. */ +static void FUsbMassStorageForceInit(FUsbDev *dev, u32 quirks) +{ + FASSERT(dev && dev->controller); + int i; + FUsb *instance = dev->controller->usb; + FASSERT(instance); + + /* init .data before setting .destroy */ + dev->data = NULL; + dev->destroy = FUsbMscDestory; + dev->poll = FUsbMscPoll; + + FASSERT(NULL == dev->data); + dev->data = FUSB_ALLOCATE(instance, sizeof(FUsbMassStorage), FUSB_DEFAULT_ALIGN); + if (NULL == dev->data) + { + FUSB_ERROR("Not enough memory for USB MSC device. "); + FASSERT(0); + } + + MSC_INST(dev)->bulk_in = NULL; + MSC_INST(dev)->bulk_out = NULL; + MSC_INST(dev)->usbdisk_created = 0; + MSC_INST(dev)->quirks = quirks; + + /* loop over all ep except ep0 to get bulk-in/bulk-out ep instance */ + for (i = 1; i <= dev->num_endp; i++) + { + if (dev->endpoints[i].endpoint == 0) + continue; + if (dev->endpoints[i].type != FUSB_BULK_EP) + continue; + if ((dev->endpoints[i].direction == FUSB_IN) && (MSC_INST(dev)->bulk_in == 0)) + MSC_INST(dev)->bulk_in = &dev->endpoints[i]; + if ((dev->endpoints[i].direction == FUSB_OUT) && (MSC_INST(dev)->bulk_out == 0)) + MSC_INST(dev)->bulk_out = &dev->endpoints[i]; + } + + /* check if non bulk-in ep */ + if (MSC_INST(dev)->bulk_in == NULL) + { + FUSB_ERROR("couldn't find bulk-in endpoint. "); + FUsbDetachDev(dev->controller, dev->address); + return; + } + + /* check if non bulk-out ep */ + if (MSC_INST(dev)->bulk_out == NULL) + { + FUSB_ERROR("couldn't find bulk-out endpoint. "); + FUsbDetachDev(dev->controller, dev->address); + return; + } + + FUSB_INFO("using endpoint %x as in, %x as out ", + MSC_INST(dev)->bulk_in->endpoint, + MSC_INST(dev)->bulk_out->endpoint); + + /* Some sticks need a little more time to get ready after SET_CONFIG. */ + fsleep_microsec(50); + + FUsbMscInitLuns(dev); + FUSB_INFO(" has %d luns ", MSC_INST(dev)->num_luns); + + /* Test if msc is ready (nothing to do if it isn't). */ + if (FUsbMscWaitReady(dev) != FUSB_MSC_READY) + return; + + /* Create the disk. */ + FUsbMscCreateDisk(dev); + + return; +} + +static void FUsbMscPoll(FUsbDev *dev) +{ + FUsbMassStorage *msc = MSC_INST(dev); + int prev_ready = msc->ready; + + if (FUsbMscWaitReady(dev) == FUSB_MSC_DETACHED) + return; + + if (!prev_ready && msc->ready) + { + FUSB_INFO("USB msc: not ready -> ready (lun %d) ", msc->lun); + FUsbMscCreateDisk(dev); + } + else if (prev_ready && !msc->ready) + { + FUSB_INFO("USB msc: ready -> not ready (lun %d) ", msc->lun); + FUsbMscRemoveDisk(dev); + } + else if (!prev_ready && !msc->ready) + { + u8 new_lun = (msc->lun + 1) % msc->num_luns; + FUSB_INFO("USB msc: not ready (lun %d) -> lun %d ", msc->lun, + new_lun); + msc->lun = new_lun; + } + + return; +} diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_msc.h b/bsp/phytium/libraries/standalone/drivers/usb/fusb_msc.h new file mode 100644 index 0000000000..bc0a1989b9 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_msc.h @@ -0,0 +1,163 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_msc.h + * Date: 2022-02-11 13:33:09 + * LastEditTime: 2022-02-17 17:50:46 + * Description:  This files is for definition of USB mass storage function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_USB_MSC_H +#define DRIVERS_USB_MSC_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ + +#include "fusb.h" + +/************************** Constant Definitions *****************************/ +/* Possible values for quirks field. */ +enum +{ + /* Don't check for LUNs (force assumption that there's only one LUN). */ + FUSB_MSC_QUIRK_NO_LUNS = 1 << 0, + /* Never do a BULK_ONLY reset, just continue. This means that the device + cannot recover from phase errors and won't detach automatically for + unrecoverable errors. Do not use unless you have to. */ + FUSB_MSC_QUIRK_NO_RESET = 1 << 1, +}; + +/* Possible values for ready field. */ +enum +{ + FUSB_MSC_DETACHED = -1, /* Disk detached or out to lunch. */ + FUSB_MSC_NOT_READY = 0, /* Disk not ready yet -- empty card reader */ + FUSB_MSC_READY = 1, /* Disk ready to communicate. */ +}; + +enum +{ + FUSB_MSC_SUBCLASS_ATAPI_8020 = 0x2, + FUSB_MSC_SUBCLASS_ATAPI_8070 = 0x5, + FUSB_MSC_SUBCLASS_SCSI = 0x6 +}; + +/* Protocols of MSC */ +enum +{ + FUSB_MSC_PROTOCOL_BULK_ONLY = 0x50 /* Usb bulk-only transfer protocol */ +}; + +typedef enum +{ + FUSB_DIR_DATA_IN = 0x80, /* data from the device to the host */ + FUSB_DIR_DATA_OUT = 0 /* data from the host to the device */ +} FUsbMassStorageDirection; + +/**************************** Type Definitions *******************************/ +typedef struct +{ + unsigned int blocksize; + unsigned int numblocks; + FUsbEndpoint *bulk_in; + FUsbEndpoint *bulk_out; + u8 quirks : 7; + u8 usbdisk_created : 1; + s8 ready; + u8 lun; + u8 num_luns; + void *data; /* For use by consumers of libpayload. */ +} FUsbMassStorage; + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define MSC_INST(dev) ((FUsbMassStorage*)(dev)->data) + +/** + * @name: FUsbMscGetCapcityMB + * @msg: 获取USB大容量存储设备的容量,单位MB + * @return {fsize_t} 容量,MB + * @param {FUsbDev} *dev, USB大容量存储设备实例 + */ +static inline u32 FUsbMscGetCapcityMB(FUsbDev *dev) +{ + FASSERT(dev); + return (u32)(MSC_INST(dev)->numblocks > 1000000 + ? (MSC_INST(dev)->numblocks / 1024) * MSC_INST(dev)->blocksize / 1024 + : MSC_INST(dev)->numblocks * MSC_INST(dev)->blocksize / 1024 / 1024); +} + +/** + * @name: FUsbMscGetBlkSize + * @msg: 获取USB大容量存储设备的块大小 + * @return {*} 块大小,字节数 + * @param {FUsbDev} *dev, USB大容量存储设备实例 + */ +static inline u32 FUsbMscGetBlkSize(FUsbDev *dev) +{ + FASSERT(dev); + return (u32)MSC_INST(dev)->blocksize; +} + +/** + * @name: FUsbMscGetBlkNum + * @msg: 获取USB大容量存储设备块数目 + * @return {*} 块数目 + * @param {FUsbDev} *dev, USB大容量存储设备实例 + */ +static inline u32 FUsbMscGetBlkNum(FUsbDev *dev) +{ + FASSERT(dev); + return (u32)MSC_INST(dev)->numblocks; +} + +/************************** Function Prototypes ******************************/ +/* 读写USB大容量存储设备,以512字节为一块 */ +int FUsbMscRwBlk512(FUsbDev *dev, int start, int n, FUsbMassStorageDirection dir, u8 *buf); + +/* USB大容量存储设备的初始化函数,由应用程序注册到FUSB框架中 */ +void FUsbMassStorageInit(FUsbDev *dev); + +/** + * To be implemented by application. It's called by the USB stack + * when a new USB storage device is found, so the client has the chance + * to know about it. + * + * @param dev descriptor for the USB storage device + */ +void __attribute__((weak)) FUsbDiskCreate(FUsbDev *dev); + +/** + * To be implemented by application. It's called by the USB stack + * when it finds out that a USB storage device is removed. + * + * @param dev descriptor for the USB storage device + */ +void __attribute__((weak)) FUsbDiskRemove(FUsbDev *dev); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_private.h b/bsp/phytium/libraries/standalone/drivers/usb/fusb_private.h new file mode 100644 index 0000000000..b1db521507 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_private.h @@ -0,0 +1,104 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_private.h + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:21:22 + * Description:  This files is for definition of internal function interface + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#pragma once + +/***************************** Include Files *********************************/ +#ifdef __aarch64__ + #include "faarch64.h" +#else + #include "fcp15.h" +#endif + +#include "fkernel.h" +#include "fio.h" +#include "fassert.h" +#include "fusb.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FUSB_REG32_GET_BITS(x, a, b) (u32)((((u32)(x)) & GENMASK(a, b)) >> b) +#define FUSB_REG32_SET_BITS(x, a, b) (u32)((((u32)(x)) << b) & GENMASK(a, b)) +#define FUSB_REG64_GET_BITS(x, a, b) (u64)((((u64)(x)) & GENMASK_ULL(a, b)) >> b) +#define FUSB_REG64_SET_BITS(x, a, b) (u64)((((u64)(x)) << b) & GENMASK_ULL(a, b)) + +/************************** Function Prototypes ******************************/ +/* 创建USB控制器实例,添加到USB实例的Hc链表中 */ +FUsbHc *FUsbAllocateHc(FUsb *instance); + +/* 删除USB控制器实例,从USB实例的Hc链表中删去 */ +void FUsbDetachHc(FUsbHc *controller); + +/* 初始化USB设备 */ +FUsbDev *FUsbInitDevEntry(FUsbHc *controller, int slot_id); + +/* 根据USB设备速度,选择最大包长度 */ +int FUsbDecodeMaxPacketSz0(FUsbSpeed speed, u8 bMaxPacketSize0); + +/* 据设备速度获取最大包长度 */ +int FUsbSpeedtoDefaultMaxPacketSz(FUsbSpeed speed); + +/* 配置USB配置描述符解析器 */ +FError FUsbSetupConfigParser(FUsbDev *dev, const void *buf, u32 buf_len); + +/* 去初始化USB配置描述符解析器 */ +void FUsbRevokeConfigParser(FUsbDev *dev); + +/* 初始化字符串描述符解析器 */ +void FUsbSetupStringParser(FUsbDev *dev); + +/* 去初始化字符串描述符解析器 */ +void FUsbRevokeStringParser(FUsbDev *dev); + +/* 检索字符串描述符,保存在FUsbStringParser结构中 */ +FError FUsbSearchStringDescriptor(FUsb *instance, FUsbDev *dev, u8 id); + +/* 获取刚刚检索到的字符串描述符内容 */ +const char *FUsbGetString(const FUsbDev *const dev); + +/* 从配置描述符解析器中获取指定类型的描述符(端点描述符/接口描述符) */ +const FUsbDescriptor *FUsbGetDescriptorFromParser(FUsbConfigParser *parser, FUsbDescriptorType type); + +/* 默认的USB设备初始化函数 */ +void FUsbNopDevInit(FUsbDev *dev); + +/* 默认的USB设备初始化函数 */ +void FUsbGenericDevInit(FUsbDev *dev); + +/* 打印设备描述符信息 */ +void FUsbDumpDeviceDescriptor(const FUsbDeviceDescriptor *descriptor); + +/* 打印配置描述符信息 */ +void FUsbDumpConfigDescriptor(const FUsbConfigurationDescriptor *descriptor); + +/* 打印接口描述符信息 */ +void FUsbDumpInterfaceDescriptor(const FUsbInterfaceDescriptor *descriptor); + +/* 打印端点描述符信息 */ +void FUsbDumpEndpointDescriptor(const FUsbEndpointDescriptor *descriptor); \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fusb_sinit.c b/bsp/phytium/libraries/standalone/drivers/usb/fusb_sinit.c new file mode 100644 index 0000000000..cf5af243e1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fusb_sinit.c @@ -0,0 +1,60 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fusb_sinit.c + * Date: 2022-02-11 13:33:11 + * LastEditTime: 2022-02-18 09:21:45 + * Description:  This files is for static initialization of USB + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/8 init version + */ + +/***************************** Include Files *********************************/ +#include "fparameters.h" +#include "fusb_private.h" + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ +extern const FUsbConfig FUSBHC_CONFIG_TBL[FUSB3_NUM]; + +/************************** Function Prototypes ******************************/ +/** + * @name: FUsbLookupConfig + * @msg: 获取USB的默认配置 + * @return {const FUsbConfig *} USB默认配置 + * @param {u32} instance_id USB实例号 + */ +const FUsbConfig *FUsbLookupConfig(u32 instance_id) +{ + const FUsbConfig *ptr = NULL; + u32 index; + + for (index = 0; index < (u32)FUSB3_NUM; index++) + { + if (FUSBHC_CONFIG_TBL[index].instance_id == instance_id) + { + ptr = &FUSBHC_CONFIG_TBL[index]; + break; + } + } + + return (const FUsbConfig *)ptr; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci.c b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci.c new file mode 100644 index 0000000000..17b5538d47 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci.c @@ -0,0 +1,1240 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci.c + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:17:20 + * Description:  This files is for implmentation of XHCI driver + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include +#include "fsleep.h" +#include "fcache.h" + +#include "fparameters.h" +#include "fdebug.h" + +#include "fxhci_private.h" + +#define FUSB_DEBUG_TAG "FXHCI" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +typedef enum +{ + FXHCI_OP_REG, +} FXhciHandShakeType; + +static void FXhciStart(FUsbHc *controller); +static void FXhciStop(FUsbHc *controller); +static FXhciTransCode FXhciReset(FUsbHc *controller); +static void FXhciReinit(FUsbHc *controller); +static void FXhciShutdown(FUsbHc *controller); +static FXhciTransCode FXhciBulk(FUsbEndpoint *ep, int size, u8 *data, int finalize); +static FXhciTransCode FXhciControl(FUsbDev *dev, FUsbDirection dir, int drlen, void *devreq, + int dalen, u8 *data); +static void *FXhciCreateIntrQueue(FUsbEndpoint *ep, int reqsize, int reqcount, int reqtiming); +static void FXhciDestoryIntrQueue(FUsbEndpoint *ep, void *queue); +static u8 *FXhciPollIntrQueue(void *queue); + +/* + * Some structures must not cross page boundaries. To get this, + * we align them by their size (or the next greater power of 2). + */ +/** + * @name: FXhciAlign + * @msg: 分配一段对齐的内存 + * @return {*} + * @param {FXhci} *xhci, XHCI控制器实例 + * @param {size_t} min_align, 对齐方式 + * @param {size_t} size, 请求的字节数目 + */ +void *FXhciAlign(FXhci *const xhci, const size_t min_align, const size_t size) +{ + FASSERT(xhci && xhci->usb); + size_t align; + FUsb *instance = xhci->usb; + + if (!(size & (size - 1))) + align = size; /* It's a power of 2 */ + else + align = 1 << ((sizeof(unsigned) << 3) - __builtin_clz(size)); + + if (align < min_align) + align = min_align; + + return FUSB_ALLOCATE(instance, size, align); +} + +#ifdef FMEMP_TAG_DEBUG +void *FXhciAlignTag(FXhci *const xhci, const size_t min_align, const size_t size, const char *file, unsigned long line, const char *msg) +{ + FASSERT(xhci && xhci->usb); + size_t align; + FUsb *instance = xhci->usb; + + if (!(size & (size - 1))) + align = size; /* It's a power of 2 */ + else + align = 1 << ((sizeof(unsigned) << 3) - __builtin_clz(size)); + + if (align < min_align) + align = min_align; + + return FUsbMempAllocateTag(instance, size, align, file, line, msg); +} +#endif + +/** + * @name: FXhciClearTrb + * @msg: 清空TRB,反转TRB的Cycle state + * @return {*} + * @param {FXhciTrb} *trb, TRB实例 + * @param {int} pcs, TRB ring的Cycle state + */ +void FXhciClearTrb(FXhciTrb *const trb, const int pcs) +{ + FASSERT(trb); + + trb->ptr_low = 0; + trb->ptr_high = 0; + trb->status = 0; + trb->control = !pcs; + + return; +} + +/** + * @name: FXhciInitCycleRing + * @msg: 初始化TRB ring + * @return {*} + * @param {FXhciTransRing} *tr, TRB ring实例 + * @param {size_t} ring_size, TRB ring中的TRB数目 + */ +void FXhciInitCycleRing(FXhciTransRing *const tr, const size_t ring_size) +{ + FASSERT(tr && tr->ring); + + memset((void *)tr->ring, 0, ring_size * sizeof(*tr->ring)); + FXHCI_TRB_SET(TT, &tr->ring[ring_size - 1], FXHCI_TRB_LINK); /* TRB Type */ + FXHCI_TRB_SET(TC, &tr->ring[ring_size - 1], 1); /* Toggle Cycle */ + + /* only one segment that points to itself */ + tr->ring[ring_size - 1].ptr_low = (uintptr)(tr->ring); + + tr->pcs = 1; + tr->cur = tr->ring; + + return; +} + +/** + * @name: FXhciHandShake + * @msg: 等待XHCI状态,完成握手 + * @return {FError} 等待返回值 + * @param {FXhci} *xhci, xhci实例 + * @param {FXhciHandShakeType} type, 等待类型,e.g 等待Op寄存器 + * @param {uintptr} reg_off, 寄存器偏移量 + * @param {u32} mask, 寄存器掩码位 + * @param {u32} wait_for, 等待的状态,如果状态到达,成功退出 + * @param {s32} timeout, 等待的tick超时 + */ +static FError FXhciHandShake(FXhci *xhci, FXhciHandShakeType type, uintptr reg_off, u32 mask, u32 wait_for, s32 timeout) +{ + FASSERT(xhci); + FError ret = FUSB_SUCCESS; + + switch (type) + { + case FXHCI_OP_REG: + ret = FXhciWaitOper32(&xhci->mmio, reg_off, mask, wait_for, timeout); + break; + default: + FASSERT(0); + break; + } + + return ret; +} + +/** + * @name: FXhciWaitReady + * @msg: 等待XHCI控制器重置完成 + * @return {*} + * @param {FXhci} *xhci, xhci实例 + */ +static FError FXhciWaitReady(FXhci *const xhci) +{ + FASSERT(xhci); + FUSB_INFO("Waiting for controller to be ready... "); + FError ret = FXhciHandShake(xhci, FXHCI_OP_REG, FXHCI_REG_OP_USBSTS, FXHCI_REG_OP_USBSTS_CNR, 0, FXHCI_TIMEOUT); + + if (FUSB_SUCCESS == ret) + FUSB_INFO("ok"); + else + FUSB_ERROR("timeout."); + + return ret; +} + +/** + * @name: FXhciHcInit + * @msg: 创建XHCI USB 控制器实例,完成初始化 + * @return {FUsbHc *} XHCI控制器实例 + * @param {FUsb} *instance, USB实例 + * @param {uintptr} base_addr, XHCI控制器基地址 + */ +FUsbHc *FXhciHcInit(FUsb *instance, uintptr base_addr) +{ + FASSERT(instance); + int i; + FXhciMMIO *mmio = NULL; + u32 reg_val; + u16 hc_version; + uintptr xhci_base_addr = base_addr + FUSB3_XHCI_OFFSET; + + FUSB_DEBUG("xhci base addr: 0x%x", xhci_base_addr); + /* First, allocate and initialize static controller structures */ + FUsbHc *const controller = FUsbAllocateHc(instance); + if (NULL == controller) + { + FUSB_ERROR("Out of memory "); + return NULL; + } + + /* set USB Hc CB according to XHCI */ + controller->type = FUSB_HC_XHCI; + controller->start = FXhciStart; + controller->stop = FXhciStop; + controller->reset = FXhciReset; + controller->init = FXhciReinit; + controller->shutdown = FXhciShutdown; + controller->bulk = FXhciBulk; + controller->control = FXhciControl; + controller->set_address = FXhciSetAddress; + controller->finish_device_config = FXhciFinishDevConfig; + controller->destroy_device = FXhciDestoryDev; + controller->create_intr_queue = FXhciCreateIntrQueue; + controller->destroy_intr_queue = FXhciDestoryIntrQueue; + controller->poll_intr_queue = FXhciPollIntrQueue; + + /* allocate xhci instance */ + controller->reg_base = base_addr; + FASSERT(NULL == controller->instance); + controller->instance = FUSB_ALLOCATE(instance, sizeof(FXhci), FUSB_DEFAULT_ALIGN); + if (NULL == controller->instance) + { + FUSB_INFO("Out of memory "); + goto _free_controller; + } + + controller->usb = instance; + + FXhci *const xhci = (FXhci *)controller->instance; + xhci->usb = instance; + + /* init roothub at slot-0 */ + FUsbInitDevEntry(controller, 0); + xhci->roothub = controller->devices[0]; + + /* allocate command ring and event ring */ + FASSERT((NULL == xhci->cr.ring) && (NULL == xhci->er.ring) && + (NULL == xhci->ev_ring_table)); + xhci->cr.ring = FXHCI_ALIGN(xhci, 64, FXHCI_COMMAND_RING_SIZE * sizeof(FXhciTrb)); + xhci->er.ring = FXHCI_ALIGN(xhci, 64, FXHCI_EVENT_RING_SIZE * sizeof(FXhciTrb)); + xhci->ev_ring_table = FXHCI_ALIGN(xhci, 64, sizeof(FXhciErstEntry)); + if ((NULL == xhci->roothub) || (NULL == xhci->cr.ring) || + (NULL == xhci->er.ring) || (NULL == xhci->ev_ring_table)) + { + FUSB_INFO("Out of memory "); + goto _free_xhci; + } + + /* setup xhci mmio for register access */ + mmio = &xhci->mmio; + FXhciSetupMMIO(mmio, xhci_base_addr); + + /* check if XHCI version is supported */ + hc_version = FXhciReadHcVersion(mmio); + if (hc_version < FXHCI_HC_VERSION_MIN || hc_version > FXHCI_HC_VERSION_MAX) + { + FUSB_ERROR("xHCI version 0x%x not support", hc_version); + goto _free_xhci; + } + + const unsigned pagesize = FXhciReadOper32(mmio, FXHCI_REG_OP_PAGESIZE) << 12; + + FUSB_INFO("regbase: 0x%x", mmio->base); + FUSB_INFO("caplen: 0x%x", FXhciReadCaplen(mmio)); + FUSB_INFO("rtsoff: 0X%x", mmio->runtime_base - mmio->base); + FUSB_INFO("dboff: 0X%x", mmio->doorbell_base - mmio->base); + FUSB_INFO("hciversion: 0x%x", FXhciReadHcVersion(mmio)); + FUSB_INFO("context size: %dB ", FXhciGetCtxSize(mmio)); + FUSB_INFO("page size: %dB ", pagesize); + + /* + * We haven't touched the hardware yet. So we allocate all dynamic + * structures at first and can still chicken out easily if we run out + * of memory. + */ + reg_val = FXhciReadCap32(&xhci->mmio, FXHCI_REG_CAP_HCSPARAMS1); + xhci->max_slots_en = FXHCI_REG_CAP_HCSPARAMS1_MAX_SLOTS_GET(reg_val); /* record max slot num */ + + /* allocate device related memory, DCBAA and device info */ + FASSERT(NULL == xhci->dcbaa); + xhci->dcbaa = FXHCI_ALIGN(xhci, 64, (xhci->max_slots_en + 1) * sizeof(u64)); + FASSERT(NULL == xhci->dev); + xhci->dev = FUSB_ALLOCATE(instance, (xhci->max_slots_en + 1) * sizeof(*xhci->dev), FUSB_DEFAULT_ALIGN); + if ((NULL == xhci->dcbaa) || (NULL == xhci->dev)) + { + FUSB_INFO("Out of memory "); + goto _free_xhci; + } + + /* + * Let dcbaa[0] point to another array of pointers, sp_ptrs. + * The pointers therein point to scratchpad buffers (pages). + */ + reg_val = FXhciReadCap32(&xhci->mmio, FXHCI_REG_CAP_HCSPARAMS2); + const size_t max_sp_bufs = FXHCI_REG_CAP_HCSPARAMS2_MAX_SCRATCHPAD_BUFS_GET(reg_val); + FUSB_INFO("max scratchpad bufs: 0x%lx reg_val : 0x%x", max_sp_bufs, reg_val); + if (0 < max_sp_bufs) + { + FUSB_INFO("allocate sp_ptrs"); + const size_t sp_ptrs_size = max_sp_bufs * sizeof(u64); + /* allocate scratchpad bufs entry to preserve pointers of scratchpad buf */ + FASSERT(NULL == xhci->sp_ptrs); + xhci->sp_ptrs = FXHCI_ALIGN(xhci, 64, sp_ptrs_size); + if (NULL == xhci->sp_ptrs) + { + FUSB_INFO("Out of memory "); + goto _free_xhci_structs; + } + + for (i = 0; (size_t)i < max_sp_bufs; ++i) + { + /* allocate each scratchpad buf */ + void *const page = FUSB_ALLOCATE(instance, pagesize, pagesize); + if (NULL == page) + { + FUSB_INFO("Out of memory "); + goto _free_xhci_structs; + } + + xhci->sp_ptrs[i] = (uintptr)(page); /* assign pointer to scratchpad buf*/ + } + + xhci->dcbaa[0] = (uintptr)(xhci->sp_ptrs); /* assign pointer to scratchpad bufs entry */ + } + + /* Now start working on the hardware */ + if (FUSB_SUCCESS != FXhciWaitReady(xhci)) + goto _free_xhci_structs; + + /* TODO: Check if BIOS claims ownership (and hand over) */ + + if (FUSB_CC_SUCCESS != FXhciReset(controller)) + { + goto _free_xhci_structs; + } + + FXhciReinit(controller); + + /* init roothub device instance */ + xhci->roothub->controller = controller; + xhci->roothub->init = FXhciRootHubInit; + xhci->roothub->init(xhci->roothub); + + FUSB_INFO("init xHc@%p success", controller); + return controller; + +_free_xhci_structs: + if (xhci->sp_ptrs) + { + for (i = 0; (size_t)i < max_sp_bufs; ++i) + { + if (xhci->sp_ptrs[i]) + FUSB_FREE(instance, (void *)(uintptr)(xhci->sp_ptrs[i])); + } + } + FUSB_FREE(instance, xhci->sp_ptrs); + FUSB_FREE(instance, xhci->dcbaa); + +_free_xhci: + FUSB_FREE(instance, (void *)xhci->ev_ring_table); + FUSB_FREE(instance, (void *)xhci->er.ring); + FUSB_FREE(instance, (void *)xhci->cr.ring); + FUSB_FREE(instance, xhci->roothub); + FUSB_FREE(instance, xhci->dev); + FUSB_FREE(instance, xhci); + +_free_controller: + FUsbDetachHc(controller); + FUSB_FREE(instance, controller); + + return NULL; +} + +/** + * @name: FXhciReset + * @msg: 重置XHCI控制器 + * @return {*} + * @param {FUsbHc} *controller, USB Hc控制器 + */ +static FUsbTransCode FXhciReset(FUsbHc *const controller) +{ + FASSERT(controller); + FXhci *const xhci = FXHCI_INST_GET(controller); + FASSERT(xhci); + u32 reg_val; + + /* stop xhci if still run */ + FXhciStop(controller); + + reg_val = FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD); + reg_val |= FXHCI_REG_OP_USBCMD_HCRST; + FXhciWriteOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD, reg_val); + + FUSB_INFO("Resetting hc..."); + if (FUSB_SUCCESS != FXhciHandShake(xhci, FXHCI_OP_REG, FXHCI_REG_OP_USBCMD, FXHCI_REG_OP_USBCMD_HCRST, 0, FXHCI_TIMEOUT)) + { + FUSB_ERROR("Wait hc reset timeout !!!"); + return -1; + } + + return FUSB_CC_SUCCESS; +} + +/** + * @name: FXhciReinit + * @msg: 重新初始化XHCI控制器 + * @return {*} + * @param {FUsbHc} *controller, USB Hc控制器 + */ +static void FXhciReinit(FUsbHc *controller) +{ + FASSERT(controller); + FXhci *const xhci = FXHCI_INST_GET(controller); + FASSERT(xhci); + const FUsbConfig *const config = &controller->usb->config; + u32 reg_val; + u64 reg_val64; + + /* wait xhci ready */ + if (FUSB_SUCCESS != FXhciWaitReady(xhci)) + return; + + /* Enable all available slots */ + reg_val = FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_CONFIG); + reg_val &= ~FXHCI_REG_OP_CONFIG_MAX_SLOTS_EN_MASK; + reg_val |= FXHCI_REG_OP_CONFIG_MAX_SLOTS_EN_SET(xhci->max_slots_en); + FXhciWriteOper32(&xhci->mmio, FXHCI_REG_OP_CONFIG, reg_val); + + /* Set DCBAA */ + FXhciWriteOper64(&xhci->mmio, FXHCI_REG_OP_DCBAAP, (u64)(uintptr)xhci->dcbaa); + FUSB_INFO("dcba at 0x%lx", FXhciReadOper64(&xhci->mmio, FXHCI_REG_OP_DCBAAP)); + + /* Initialize command ring */ + FXhciInitCycleRing(&xhci->cr, FXHCI_COMMAND_RING_SIZE); + FUSB_INFO("command ring @%p", xhci->cr.ring); + reg_val64 = FXhciReadOper64(&xhci->mmio, FXHCI_REG_OP_CRCR); + + reg_val64 = FXHCI_REG_OP_CRCR_CR_PTR_MASK & (u64)(uintptr)xhci->cr.ring; + reg_val64 |= FXHCI_REG_OP_CRCR_RCS & xhci->cr.pcs; + FXhciWriteOper64(&xhci->mmio, FXHCI_REG_OP_CRCR, reg_val64); + + /* Make sure interrupts are disabled */ + reg_val = FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD); + reg_val &= ~FXHCI_REG_OP_USBCMD_INTE; + FXhciWriteOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD, reg_val); + + /* Initialize event ring */ + FXhciResetEvtRing(&xhci->er); + FUSB_INFO("event ring @%p (0x%08p) ", + xhci->er.ring, (uintptr)(xhci->er.ring)); + + reg_val = FXhciReadCap32(&xhci->mmio, FXHCI_REG_CAP_HCSPARAMS2); + FUSB_INFO("ERST Max: %d", + FXHCI_REG_CAP_HCSPARAMS2_ERST_MAX_GET(reg_val)); + memset((void *)xhci->ev_ring_table, 0x00, sizeof(FXhciErstEntry)); + xhci->ev_ring_table[0].seg_base_lo = (uintptr)(xhci->er.ring); + xhci->ev_ring_table[0].seg_base_hi = 0; + xhci->ev_ring_table[0].seg_size = FXHCI_EVENT_RING_SIZE; + + /* pass event ring table to hardware */ + WMB(); + + /* Initialize primary interrupter */ + FXhciWriteRt32(&xhci->mmio, 0, FXHCI_REG_RT_IR_ERSTSZ, FXHCI_REG_RT_IR_ERSTSZ_MASK & 1); /* Segment Table Size = 1 */ + FXhciUpdateEvtDQ(xhci); + + /* erstba has to be written at last */ + FXhciWriteRt64(&xhci->mmio, 0, FXHCI_REG_RT_IR_ERSTBA, FXHCI_REG_RT_IR_ERSTBA_MASK & ((u64)(uintptr)xhci->ev_ring_table)); + FUSB_INFO("ERST base: 0x%lx == %p", + FXhciReadRt64(&xhci->mmio, 0, FXHCI_REG_RT_IR_ERSTBA), + xhci->ev_ring_table); + + FXhciStart(controller); + + /* run Cmd Nop to test if command ring okay */ + for (int i = 0; i < 3; ++i) + { + FUSB_INFO("NOOP run #%d ", i); + if (FXHCI_CC_SUCCESS != FXhciCmdNop(xhci)) + { + FUSB_ERROR("noop command failed. "); + break; + } + } + + return; +} + +/** + * @name: FXhciShutdown + * @msg: 关闭XHCI控制器 + * @return {*} + * @param {FUsbHc} *controller, USB Hc控制器 + */ +static void FXhciShutdown(FUsbHc *const controller) +{ + int i; + u32 reg_val; + + if (controller == NULL) + return; + + /* detach the Hc instance */ + FUsbDetachHc(controller); + + FXhci *const xhci = FXHCI_INST_GET(controller); + FASSERT(xhci && xhci->usb); + FUsb *instance = xhci->usb; + FXhciStop(controller); /* stop xhci instance */ + + /* free scatchpad bufs */ + if (NULL != xhci->sp_ptrs) + { + reg_val = FXhciReadCap32(&xhci->mmio, FXHCI_REG_CAP_HCSPARAMS2); + const size_t max_sp_bufs = FXHCI_REG_CAP_HCSPARAMS2_MAX_SCRATCHPAD_BUFS_GET(reg_val); + for (i = 0; (size_t)i < max_sp_bufs; ++i) + { + if (NULL != (void *)(uintptr)xhci->sp_ptrs[i]) + FUSB_FREE(instance, (void *)(uintptr)(xhci->sp_ptrs[i])); + } + } + + + FUSB_FREE(instance, xhci->sp_ptrs); + FUSB_FREE(instance, xhci->dcbaa); + FUSB_FREE(instance, xhci->dev); + FUSB_FREE(instance, (void *)xhci->ev_ring_table); + FUSB_FREE(instance, (void *)xhci->er.ring); + FUSB_FREE(instance, (void *)xhci->cr.ring); + FUSB_FREE(instance, xhci); + + return; +} + +/** + * @name: FXhciStart + * @msg: 启动XHCI控制器 + * @return {*} + * @param {FUsbHc} *controller, USB Hc控制器 + */ +static void FXhciStart(FUsbHc *controller) +{ + FASSERT(controller); + FXhci *const xhci = FXHCI_INST_GET(controller); + FASSERT(xhci); + u32 reg_val; + + /* setting the USBCMD register Run/Stop (R/S) bit to ‘1’ */ + reg_val = FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD); + reg_val |= FXHCI_REG_OP_USBCMD_RUN_STOP; + FXhciWriteOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD, reg_val); + + if (FUSB_SUCCESS != FXhciHandShake(xhci, FXHCI_OP_REG, FXHCI_REG_OP_USBSTS, FXHCI_REG_OP_USBSTS_HCH, 0, FXHCI_TIMEOUT)) + { + FUSB_ERROR("Wait hc start timeout !!!"); + } + + return; +} + +/** + * @name: FXhciStop + * @msg: 停止XHCI控制器 + * @return {*} + * @param {FUsbHc} *controller, USB Hc控制器 + */ +static void FXhciStop(FUsbHc *controller) +{ + FASSERT(controller); + FXhci *const xhci = FXHCI_INST_GET(controller); + FASSERT(xhci); + u32 reg_val; + + /* setting the USBCMD register Run/Stop (R/S) bit to ‘0’ */ + reg_val = FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD); + reg_val &= ~FXHCI_REG_OP_USBCMD_RUN_STOP; + FXhciWriteOper32(&xhci->mmio, FXHCI_REG_OP_USBCMD, reg_val); + + if (FUSB_SUCCESS != FXhciHandShake(xhci, FXHCI_OP_REG, FXHCI_REG_OP_USBSTS, FXHCI_REG_OP_USBSTS_HCH, FXHCI_REG_OP_USBSTS_HCH, FXHCI_TIMEOUT)) + { + FUSB_ERROR("Wait hc stop timeout !!!"); + } + + return; +} + +/** + * @name: FXhciResetEp + * @msg: 重置XHCI端点 + * @return {FError} 返回错误码 + * @param {FUsbDev} *dev, 端点所在的USB设备实例 + * @param {FUsbEndpoint} *ep, 端点实例 + */ +static FError FXhciResetEp(FUsbDev *const dev, FUsbEndpoint *const ep) +{ + FASSERT(dev && dev->controller); + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + const int slot_id = dev->address; + const int ep_id = (NULL != ep) ? FXhciEpId(ep) : FXHCI_EP0_ID; /* ep-0 or normal ep */ + FXhciEpCtx *const epctx = xhci->dev[slot_id].ctx.ep[ep_id]; + + FUSB_INFO("Resetting ID %d EP %d (ep state: %d) ", + slot_id, ep_id, FXHCI_EC_GET(STATE, epctx)); + + /* Run Reset Endpoint Command if the EP is in Halted state */ + if (FXHCI_EC_GET(STATE, epctx) == FXHCI_EC_STATE_HALTED) + { + const FXhciTransCode cc = FXhciCmdResetEp(xhci, slot_id, ep_id); + if (cc != FXHCI_CC_SUCCESS) + { + FUSB_INFO("Reset Endpoint Command failed: %d ", cc); + return FUSB_ERR_TRANS_FAIL; + } + } + + /* Clear TT buffer for bulk and control endpoints behind a TT */ + const int hub = dev->hub; + if (hub && dev->speed < FUSB_HIGH_SPEED && + dev->controller->devices[hub]->speed == FUSB_HIGH_SPEED) + { + /* TODO */; + } + + /* Reset transfer ring if the endpoint is in the right state */ + const unsigned ep_state = FXHCI_EC_GET(STATE, epctx); + if (ep_state == FXHCI_EC_STATE_STOPPED || ep_state == FXHCI_EC_STATE_ERROR) + { + FXhciTransRing *const tr = + xhci->dev[slot_id].transfer_rings[ep_id]; + const FXhciTransCode cc = FXhciCmdSetTrDq(xhci, slot_id, ep_id, + tr->ring, 1); + if (cc != FXHCI_CC_SUCCESS) + { + FUSB_INFO("Set TR Dequeue Command failed: %d ", cc); + return FUSB_ERR_TRANS_FAIL; + } + + FXhciInitCycleRing(tr, FXHCI_TRANSFER_RING_SIZE); + } + + FUSB_INFO("Finished resetting ID %d EP %d (ep state: %d) ", + slot_id, ep_id, FXHCI_EC_GET(STATE, epctx)); + + return FUSB_SUCCESS; +} + +/** + * @name: FXhciEnqueueTrb + * @msg: TRB入队,向TRB ring加入一条TRB + * @return {*} + * @param {FXhciTransRing} *tr, TRB ring实例 + */ +static void FXhciEnqueueTrb(FXhciTransRing *const tr) +{ + FASSERT(tr); + + const int chain = FXHCI_TRB_GET(CH, tr->cur); + FXHCI_TRB_SET(C, tr->cur, tr->pcs); /* Cycle Bit */ + ++tr->cur; + + while (FXHCI_TRB_GET(TT, tr->cur) == FXHCI_TRB_LINK) + { + FUSB_DEBUG("Handling LINK pointer "); + + const int tc = FXHCI_TRB_GET(TC, tr->cur); + FXHCI_TRB_SET(CH, tr->cur, chain); /* Chain Bit */ + + WMB(); + + FXHCI_TRB_SET(C, tr->cur, tr->pcs); /* Cycle Bit */ + tr->cur = (void *)(uintptr)(tr->cur->ptr_low); + + /* toggle cycle state */ + if (tc) + tr->pcs ^= 1; + } + + return; +} + +/** + * @name: FXhciRingDoorbell + * @msg: 提醒Hc处理刚加入的TRB + * @return {*} + * @param {FUsbEndpoint} *ep, 端点实例 + */ +static void FXhciRingDoorbell(FUsbEndpoint *const ep) +{ + FASSERT(ep); + FXhci *xhci = FXHCI_INST_GET(ep->dev->controller); + + /* Ensure all TRB changes are written to memory. */ + WMB(); + + FXhciWriteDb32(&xhci->mmio, ep->dev->address, FXhciEpId(ep)); + + return; +} + +/** + * @name: FXhciEnqueueTD + * @msg: 填充一条TRB + * @return {*} + * @param {FXhciTransRing} *tr, TRB ring实例 + * @param {int} ep, 端点实例 + * @param {size_t} mps, 最大包长度 + * @param {int} dalen, 数据长度 + * @param {void} *data, 数据缓冲区 + * @param {int} dir, 发送方向 + */ +static void FXhciEnqueueTD(FXhciTransRing *const tr, const int ep, const size_t mps, + const int dalen, void *const data, const int dir) +{ + FASSERT(tr); + FXhciTrb *trb = NULL; /* cur TRB */ + u8 *cur_start = data; /* cur data pointer */ + size_t length = dalen; /* remaining bytes */ + size_t packets = (length + mps - 1) / mps; /* remaining packets */ + size_t residue = 0; /* residue from last TRB */ + size_t trb_count = 0; /* TRBs added so far */ + + while ((length > 0) || (trb_count == 0) /* enqueue at least one */) + { + const size_t cur_end = ((size_t)cur_start + 0x10000) & ~0xffff; /* best guess, send at most 0x1000 bytes */ + size_t cur_length = cur_end - (size_t)cur_start; + + if (length < cur_length) + { + cur_length = length; + packets = 0; + length = 0; + } + else + { + packets -= (residue + cur_length) / mps; + residue = (residue + cur_length) % mps; + length -= cur_length; + } + + trb = tr->cur; + FXhciClearTrb(trb, tr->pcs); + trb->ptr_low = (uintptr)(cur_start); + FXHCI_TRB_SET(TL, trb, cur_length); /* Transfer Length */ + FXHCI_TRB_SET(TDS, trb, min((size_t)FXHCI_TRB_MAX_TD_SIZE, packets)); /* TD Size */ + FXHCI_TRB_SET(CH, trb, 1); /* associate this TRB with the next TRB on the Ring */ + + /* Check for first, data stage TRB, only Ep0 can handle */ + if ((trb_count == 0) && ep == FXHCI_EP0_ID) + { + FXHCI_TRB_SET(DIR, trb, dir); /* Direction */ + FXHCI_TRB_SET(TT, trb, FXHCI_TRB_DATA_STAGE); /* TRB Type */ + } + else + { + FXHCI_TRB_SET(TT, trb, FXHCI_TRB_NORMAL); /* TRB Type */ + } + + /* + * This is a workaround for Synopsys DWC3. If the ENT flag is + * not set for the Normal and Data Stage TRBs. We get Event TRB + * with length 0x20d from the controller when we enqueue a TRB + * for the IN endpoint with length 0x200. + */ + if (0 == length) + { + /* xHC shall fetch and evaluate the next TRB before saving the endpoint state */ + FXHCI_TRB_SET(ENT, trb, 1); /* Evaluate Next TRB */ + } + + FXhciEnqueueTrb(tr); + + cur_start += cur_length; + ++trb_count; + } + + trb = tr->cur; + FXhciClearTrb(trb, tr->pcs); + trb->ptr_low = (uintptr)(trb); /* for easier debugging only */ + FXHCI_TRB_SET(TT, trb, FXHCI_TRB_EVENT_DATA); /* set transfer type */ + FXHCI_TRB_SET(IOC, trb, 1); /* xHc shalle notify the system of the completion by placing an Transfer Event TRB on the Event ring */ + + FXhciEnqueueTrb(tr); + + return; +} + +/** + * @name: FXhciControl + * @msg: XHCI控制传输 + * @return {FXhciTransCode} 传输返回值 + * @param {FUsbDev} *dev, USB设备实例 + * @param {FUsbDirection} dir, 控制传输类型, IN, OUT, SETUP + * @param {int} drlen, USB请求长度 + * @param {void} *devreq, USB请求,参考FUsbDevReq + * @param {int} dalen, 控制传输数据长度 + * @param {unsigned char} *src, 控制传输数据 + */ +static FXhciTransCode FXhciControl(FUsbDev *const dev, const FUsbDirection dir, + const int drlen, void *const devreq, const int dalen, + unsigned char *const src) +{ + FASSERT(dev && dev->controller); + unsigned char *data = src; + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + FXhciEpCtx *const epctx = xhci->dev[dev->address].ctx.ep0; + FXhciTransRing *const tr = xhci->dev[dev->address].transfer_rings[1]; + FASSERT(epctx && tr); + + /* check the transfer data length, less than WORD size, u16 pointer can hold */ + const size_t off = (size_t)data & 0xffff; + if ((off + dalen) > ((FXHCI_TRANSFER_RING_SIZE - 4) << 16)) + { + FUSB_ERROR("Unsupported transfer size 0x%lx!!!", dalen); + return FXHCI_CC_GENERAL_ERROR; + } + + /* Reset endpoint if it's not running and not disabled */ + const unsigned ep_state = FXHCI_EC_GET(STATE, epctx); + if (ep_state > FXHCI_EC_STATE_RUNNING) + { + if (FUSB_SUCCESS != FXhciResetEp(dev, NULL)) + { + FUSB_ERROR("Reset endpoint failed !!!"); + return FXHCI_CC_GENERAL_ERROR; + } + } + + /* Fill and enqueue setup TRB */ + FXhciTrb *const setup = tr->cur; + FXhciClearTrb(setup, tr->pcs); + setup->ptr_low = ((u32 *)devreq)[0]; /* request data */ + setup->ptr_high = ((u32 *)devreq)[1]; + FXHCI_TRB_SET(TL, setup, drlen/*8*/); /* Transfer length */ + FXHCI_TRB_SET(TRT, setup, (dalen > 0) ? ((dir == FUSB_OUT) ? FXHCI_TRB_TRT_OUT_DATA : FXHCI_TRB_TRT_IN_DATA) : FXHCI_TRB_TRT_NO_DATA); + FXHCI_TRB_SET(TT, setup, FXHCI_TRB_SETUP_STAGE); /* TRB Type */ + FXHCI_TRB_SET(IDT, setup, 1); /* Immediate Data (IDT). shall be set to ‘1’ in a Setup Stage TRB */ + FXHCI_TRB_SET(IOC, setup, 1); /* Interrupt On Completion (IOC) */ + FXhciEnqueueTrb(tr); + + /* Fill and enqueue data TRBs (if any) */ + if (dalen > 0) + { + const unsigned mps = FXHCI_EC_GET(MPS, epctx); + const unsigned dt_dir = (dir == FUSB_OUT) ? FXHCI_TRB_DIR_OUT : FXHCI_TRB_DIR_IN; + FXhciEnqueueTD(tr, FXHCI_EP0_ID, mps, dalen, data, dt_dir); + } + + /* Fill status TRB */ + FXhciTrb *const status = tr->cur; + FXhciClearTrb(status, tr->pcs); + FXHCI_TRB_SET(DIR, status, (dir == FUSB_OUT) ? FXHCI_TRB_DIR_IN : FXHCI_TRB_DIR_OUT); /* Direction */ + FXHCI_TRB_SET(TT, status, FXHCI_TRB_STATUS_STAGE); /* TRB Type */ + FXHCI_TRB_SET(IOC, status, 1); /* Interrupt On Completion */ + FXhciEnqueueTrb(tr); + + /* Ring doorbell for EP0 */ + FXhciRingDoorbell(&dev->endpoints[0]); + + /* Wait for transfer events from IN DATA OUT stages */ + int i, transferred = 0; + const int n_stages = 2 + !!dalen; /* 2 stage without data */ + + /* flush cache of request data / transfer data before transfer */ + if (dalen > 0) + { + FCacheDCacheInvalidateRange((uintptr)data, dalen); + FCacheDCacheInvalidateRange((uintptr)devreq, drlen); + } + + for (i = 0; i < n_stages; ++i) + { + const FXhciTransCode ret = FXhciWaitForTransfer(xhci, dev->address, 1); + transferred += ret; /* record bytes transfered successfully */ + if (ret < FXHCI_CC_ZERO_BYTES) /* negative ret means transfer error */ + { + if (ret == FXHCI_CC_TIMEOUT) + { + FUSB_ERROR("Stopping ID %d EP 1 ", + dev->address); + FXhciCmdStopEp(xhci, dev->address, FXHCI_EP0_ID); + } + + FUSB_ERROR("Stage %d/%d failed: %d \r\n" + " trb ring: @%p \r\n" + " setup trb: @%p \r\n" + " status trb: @%p \r\n" + " ep state: %d -> %d \r\n" + " usbsts: 0x%08x ", + i, n_stages, ret, + tr->ring, setup, status, + ep_state, FXHCI_EC_GET(STATE, epctx), + FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_USBSTS)); + return ret; + } + } + + /* flush cache of request data / transfer data after transfer */ + if (dalen > 0) + { + FCacheDCacheInvalidateRange((uintptr)data, dalen); + FCacheDCacheInvalidateRange((uintptr)devreq, drlen); + } + + return transferred; +} + +/** + * @name: FXhciBulk + * @msg: XHCI块传输 + * @return {FXhciTransCode} + * @param {FUsbEndpoint} *ep, 端点实例 + * @param {int} size, + * @param {u8} *src + * @param {int} finalize + * @note: finalize == 1: if data is of packet aligned size, add a zero length packet + */ +static FXhciTransCode FXhciBulk(FUsbEndpoint *const ep, const int size, u8 *const src, + const int finalize) +{ + /* finalize: Hopefully the xHCI controller always does this. + We have no control over the packets. */ + FASSERT(ep); + u8 *data = src; + FXhci *const xhci = FXHCI_INST_GET(ep->dev->controller); + FASSERT(xhci); + const int slot_id = ep->dev->address; + const int ep_id = FXhciEpId(ep); /* must not for Ep0 */ + FXhciEpCtx *const epctx = xhci->dev[slot_id].ctx.ep[ep_id]; + FXhciTransRing *const tr = xhci->dev[slot_id].transfer_rings[ep_id]; + + /* check the transfer data length, less than WORD size, u16 pointer can hold */ + const size_t off = (size_t)data & 0xffff; + if ((off + size) > ((FXHCI_TRANSFER_RING_SIZE - 2) << 16)) + { + FUSB_INFO("Unsupported transfer size "); + return FXHCI_CC_GENERAL_ERROR; + } + + /* Reset endpoint if it's not running */ + const unsigned ep_state = FXHCI_EC_GET(STATE, epctx); + if (ep_state > FXHCI_EC_STATE_RUNNING) + { + if (FUSB_SUCCESS != FXhciResetEp(ep->dev, ep)) + return FXHCI_CC_GENERAL_ERROR; + } + + FCacheDCacheInvalidateRange((uintptr)data, size); + + /* Enqueue transfer and ring doorbell */ + const unsigned mps = FXHCI_EC_GET(MPS, epctx); + const unsigned dir = (ep->direction == FUSB_OUT) ? FXHCI_TRB_DIR_OUT : FXHCI_TRB_DIR_IN; + FXhciEnqueueTD(tr, ep_id, mps, size, data, dir); + FXhciRingDoorbell(ep); + + /* Wait for transfer event */ + const FXhciTransCode ret = FXhciWaitForTransfer(xhci, ep->dev->address, ep_id); + if (ret < FXHCI_CC_ZERO_BYTES) + { + if (ret == FXHCI_CC_TIMEOUT) + { + FUSB_INFO("Stopping ID %d EP %d ", + ep->dev->address, ep_id); + FXhciCmdStopEp(xhci, ep->dev->address, ep_id); + } + + FUSB_INFO("Bulk transfer failed: %d \r\n" + " ep state: %d -> %d \r\n" + " usbsts: 0x%08x ", + ret, ep_state, + FXHCI_EC_GET(STATE, epctx), + FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_USBSTS)); + + return ret; + } + + return ret; +} + +/** + * @name: FXhciNextTrb + * @msg: 获取下一个可用的TRB + * @return {FXhciTrb*} 可用的TRB + * @param {FXhciTrb} *cur, 当前TRB + * @param {int} *pcs, 传入的待反转的Cycle state + */ +static FXhciTrb *FXhciNextTrb(FXhciTrb *cur, int *const pcs) +{ + FASSERT(cur); + ++cur; + + while (FXHCI_TRB_GET(TT, cur) == FXHCI_TRB_LINK) + { + if (pcs && FXHCI_TRB_GET(TC, cur)) + *pcs ^= 1; + + cur = (void *)(uintptr)(cur->ptr_low); + } + + return cur; +} + +/** + * @name: FXhciCreateIntrQueue + * @msg: 创建XHCI的中断队列 + * @return {void *} 成功则返回指向中断队列的指针,失败返回NULL + * @param {FUsbEndpoint} *ep, 端点实例 + * @param {int} reqsize, 中断队列可接受的请求字节数 + * @param {int} reqcount, 中断队列可接受的最大请求数目 + * @param {int} reqtiming, 请求超时 + * @note create and hook-up an intr queue into device schedul + */ +static void *FXhciCreateIntrQueue(FUsbEndpoint *const ep, const int reqsize, const int reqcount, + const int reqtiming) +{ + /* reqtiming: We ignore it and use the interval from the + endpoint descriptor configured earlier. */ + FASSERT(ep); + FXhci *const xhci = FXHCI_INST_GET(ep->dev->controller); + FASSERT(xhci && xhci->usb); + FUsb *instance = xhci->usb; + const int slot_id = ep->dev->address; + const int ep_id = FXhciEpId(ep); + FXhciTransRing *const tr = xhci->dev[slot_id].transfer_rings[ep_id]; + + if (reqcount > (FXHCI_TRANSFER_RING_SIZE - 2)) + { + FUSB_INFO("reqcount is too high, at most %d supported ", + FXHCI_TRANSFER_RING_SIZE - 2); + return NULL; + } + + if (reqsize > 0x10000) + { + FUSB_INFO("reqsize is too large, at most 64KiB supported "); + return NULL; + } + + if (xhci->dev[slot_id].interrupt_queues[ep_id]) + { + FUSB_INFO("Only one interrupt queue per endpoint supported "); + return NULL; + } + + /* Allocate intrq structure and reqdata chunks */ + FXhciIntrQ *const intrq = FUSB_ALLOCATE(instance, sizeof(*intrq), FUSB_DEFAULT_ALIGN); + if (NULL == intrq) + { + FUSB_INFO("Out of memory "); + return NULL; + } + + int i; + int pcs = tr->pcs; + FXhciTrb *cur = tr->cur; + for (i = 0; i < reqcount; ++i) + { + if (FXHCI_TRB_GET(C, cur) == (unsigned int)pcs) + { + FUSB_INFO("Not enough empty TRBs "); + goto _free_return; + } + + /* allocate request buffer for each TRB */ + void *const reqdata = FXHCI_ALIGN(xhci, 1, reqsize); + if (NULL == reqdata) + { + FUSB_INFO("Out of memory "); + goto _free_return; + } + + FXhciClearTrb(cur, pcs); + cur->ptr_low = (uintptr)(reqdata); + cur->ptr_high = 0; + FXHCI_TRB_SET(TL, cur, reqsize); /* Transfer Length */ + FXHCI_TRB_SET(TT, cur, FXHCI_TRB_NORMAL); /* TRB Type */ + FXHCI_TRB_SET(ISP, cur, 1); /* Interrupt-on Short Packet */ + FXHCI_TRB_SET(IOC, cur, 1); /* Interrupt On Completion */ + + cur = FXhciNextTrb(cur, &pcs); + } + + intrq->size = reqsize; + intrq->count = reqcount; + intrq->next = tr->cur; + intrq->ready = NULL; + intrq->ep = ep; + xhci->dev[slot_id].interrupt_queues[ep_id] = intrq; + + /* Now enqueue all the prepared TRBs but the last + and ring the doorbell. */ + for (i = 0; i < (reqcount - 1); ++i) + FXhciEnqueueTrb(tr); + + FXhciRingDoorbell(ep); + return intrq; + +_free_return: + cur = tr->cur; + for (--i; i >= 0; --i) + { + FUSB_FREE(instance, (void *)(uintptr)(cur->ptr_low)); + cur = FXhciNextTrb(cur, NULL); + } + FUSB_FREE(instance, intrq); + return NULL; +} + +/** + * @name: FXhciDestoryIntrQueue + * @msg: 删除中断队列 + * @return {*} + * @param {FUsbEndpoint} *ep, 端点实例 + * @param {void} *q, 中断队列 + * @note remove queue from device schedule, dropping all data that came in + */ +static void FXhciDestoryIntrQueue(FUsbEndpoint *const ep, void *const q) +{ + FASSERT(ep && q); + FXhci *const xhci = FXHCI_INST_GET(ep->dev->controller); + FASSERT(xhci); + FUsb *instance = xhci->usb; + const int slot_id = ep->dev->address; + const int ep_id = FXhciEpId(ep); + FXhciTransRing *const tr = xhci->dev[slot_id].transfer_rings[ep_id]; + FXhciIntrQ *const intrq = (FXhciIntrQ *)q; + + /* Make sure the endpoint is stopped */ + if (FXHCI_EC_GET(STATE, xhci->dev[slot_id].ctx.ep[ep_id]) == FXHCI_EC_STATE_RUNNING) + { + const FXhciTransCode cc = FXhciCmdStopEp(xhci, slot_id, ep_id); + if (cc != FXHCI_CC_SUCCESS) + FUSB_INFO("Warning: Failed to stop endpoint "); + } + + /* Process all remaining transfer events */ + FXhciHandleEvts(xhci); + + /* Free all pending transfers and the interrupt queue structure */ + int i; + for (i = 0; (size_t)i < intrq->count; ++i) + { + FUSB_FREE(instance, (void *)(uintptr)(intrq->next->ptr_low)); + intrq->next = FXhciNextTrb(intrq->next, NULL); + } + + xhci->dev[slot_id].interrupt_queues[ep_id] = NULL; + FUSB_FREE(instance, (void *)intrq); + + /* Reset the controller's dequeue pointer and reinitialize the ring */ + FXhciCmdSetTrDq(xhci, slot_id, ep_id, tr->ring, 1); + FXhciInitCycleRing(tr, FXHCI_TRANSFER_RING_SIZE); + + return; +} + +/** + * @name: FXhciPollIntrQueue + * @msg: 轮询一次中断队列进行处理 + * @return {*} + * @param {void} *q, 中断队列 + * @note read one intr-packet from queue, if available. extend the queue for new input. + return NULL if nothing new available. + Recommended use: while (data=poll_intr_queue(q)) process(data); + */ +static u8 *FXhciPollIntrQueue(void *const q) +{ + if (NULL == q) + return NULL; + + FXhciIntrQ *const intrq = (FXhciIntrQ *)q; + FUsbEndpoint *const ep = intrq->ep; + FXhci *const xhci = FXHCI_INST_GET(ep->dev->controller); + FASSERT(xhci); + + /* TODO: Reset interrupt queue if it gets halted? */ + FXhciHandleEvts(xhci); + + u8 *reqdata = NULL; + while (!reqdata && intrq->ready) + { + const int ep_id = FXhciEpId(ep); + FXhciTransRing *const tr = + xhci->dev[ep->dev->address].transfer_rings[ep_id]; + + /* Fetch the request's buffer */ + reqdata = (void *)(uintptr)(intrq->next->ptr_low); + + /* Enqueue the last (spare) TRB and ring doorbell */ + FXhciEnqueueTrb(tr); + FXhciRingDoorbell(ep); + + /* Reuse the current buffer for the next spare TRB */ + FXhciClearTrb(tr->cur, tr->pcs); + tr->cur->ptr_low = (uintptr)(reqdata); + tr->cur->ptr_high = 0; + FXHCI_TRB_SET(TL, tr->cur, intrq->size); /* Transfer Length */ + FXHCI_TRB_SET(TT, tr->cur, FXHCI_TRB_NORMAL); /* TRB Type */ + FXHCI_TRB_SET(ISP, tr->cur, 1); /* Interrupt-on Short Packet */ + FXHCI_TRB_SET(IOC, tr->cur, 1); /* Interrupt On Completion */ + + /* Check if anything was transferred */ + const size_t read = FXHCI_TRB_GET(TL, intrq->next); + if (!read) + reqdata = NULL; + else if (read < intrq->size) + /* At least zero it, poll interface is rather limited */ + memset(reqdata + read, 0x00, intrq->size - read); + + /* Advance the interrupt queue */ + if (intrq->ready == intrq->next) + /* This was last TRB being ready */ + intrq->ready = NULL; + intrq->next = FXhciNextTrb(intrq->next, NULL); + } + + return reqdata; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci.h b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci.h new file mode 100644 index 0000000000..b23ebd05a1 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci.h @@ -0,0 +1,94 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci.h + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:17:44 + * Description:  This files is for definition of XHCI user function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_USB_FXHCI_H +#define DRIVERS_USB_FXHCI_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fusb.h" + +/************************** Constant Definitions *****************************/ +#define FXHCI_EVENT_RING_SIZE 64 +#define FXHCI_TRANSFER_RING_SIZE 32 /* Never raise this above 256 to prevent transfer event length overflow! */ +#define FXHCI_COMMAND_RING_SIZE 4 +#define FXHCI_NUM_EPS 32 + +#define FXHCI_HC_VERSION_MIN 0x96 /* supported XHCI version from v0.96 to v1.2 */ +#define FXHCI_HC_VERSION_MAX 0x120 + +/* completion code for xhci */ +enum +{ + /* Make these high enough to not collide with negative FUSB_HC_XHCI CCs */ + FXHCI_CC_TIMEOUT = -65, + FXHCI_CC_CONTROLLER_ERROR = -66, + FXHCI_CC_COMMUNICATION_ERROR = -67, + FXHCI_CC_OUT_OF_MEMORY = -68, + FXHCI_CC_DRIVER_ERROR = -69, + FXHCI_CC_GENERAL_ERROR = -1, + + FXHCI_CC_ZERO_BYTES = FUSB_CC_ZERO_BYTES, + + /* defined according to Table 130: TRB Completion Code Definitions in spec */ + FXHCI_CC_SUCCESS = FUSB_CC_SUCCESS, + + /* Use as -FXHCI_CC_TRB_ERROR when return as error */ + FXHCI_CC_TRB_ERROR = 5, + FXHCI_CC_STALL_ERROR = 6, + FXHCI_CC_RESOURCE_ERROR = 7, + FXHCI_CC_BANDWIDTH_ERROR = 8, + FXHCI_CC_NO_SLOTS_AVAILABLE = 9, + FXHCI_CC_SLOT_NOT_ENABLED = 11, + FXHCI_CC_SHORT_PACKET = 13, + FXHCI_CC_EVENT_RING_FULL_ERROR = 21, + FXHCI_CC_COMMAND_RING_STOPPED = 24, + FXHCI_CC_COMMAND_ABORTED = 25, + FXHCI_CC_STOPPED = 26, + FXHCI_CC_STOPPED_LENGTH_INVALID = 27 +}; + +typedef FUsbTransCode FXhciTransCode; +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ +/* 创建XHCI USB 控制器实例,完成初始化 */ +FUsbHc *FXhciHcInit(FUsb *instance, uintptr base_addr); + +#ifdef __cplusplus +} +#endif + + +#endif + + diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_cmd.c b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_cmd.c new file mode 100644 index 0000000000..dbfb2780da --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_cmd.c @@ -0,0 +1,243 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_cmd.c + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:11:23 + * Description:  This files is for implementation of XHCI command + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include "fdebug.h" +#include "fxhci_private.h" + +#define FUSB_DEBUG_TAG "FXHCI_CMD" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +FXhciTrb *FXhciNextCmdTrb(FXhci *const xhci) +{ + FXhciClearTrb(xhci->cr.cur, xhci->cr.pcs); + return xhci->cr.cur; +} + +void FXhciPostCmd(FXhci *const xhci) +{ + FUSB_INFO("Command %d (@%p) ", FXHCI_TRB_GET(TT, xhci->cr.cur), xhci->cr.cur); + + FXHCI_TRB_SET(C, xhci->cr.cur, xhci->cr.pcs); /* Cycle Bit */ + ++xhci->cr.cur; + + /* pass command trb to hardware */ + WMB(); + + /* Ring the doorbell */ + FXhciWriteDb32(&xhci->mmio, FXHCI_REG_DB_HOST_CONTROLLER, FXHCI_REG_DB_TARGET_HC_COMMAND); + + while (FXHCI_TRB_GET(TT, xhci->cr.cur) == FXHCI_TRB_LINK) + { + FUSB_DEBUG("Handling LINK pointer (@%p) ", xhci->cr.cur); + const int tc = FXHCI_TRB_GET(TC, xhci->cr.cur); /* Completion Code */ + FXHCI_TRB_SET(C, xhci->cr.cur, xhci->cr.pcs); /* Cycle Bit */ + xhci->cr.cur = (void *)(uintptr)(xhci->cr.cur->ptr_low); + if (tc) + xhci->cr.pcs ^= 1; + } +} + +static FXhciTransCode FXhciWaitForCmd(FXhci *const xhci, + const FXhciTrb *const cmd_trb, + const int clear_event) +{ + FXhciTransCode cc; + u64 reg_val64; + + cc = FXhciWaitForCmdDone(xhci, cmd_trb, clear_event); + if (cc != FXHCI_CC_TIMEOUT) + return cc; + + /* Abort command on timeout */ + FUSB_ERROR("Aborting command (@%p), CRCR: 0x%x ", cmd_trb, FXhciReadOper64(&xhci->mmio, FXHCI_REG_OP_CRCR)); + + /* + * Ref. xHCI Specification Revision 1.2, May 2019. + * Section 5.4.5, Table 5-24. + * + * Abort the command and stop the ring. + */ + reg_val64 = FXhciReadOper64(&xhci->mmio, FXHCI_REG_OP_CRCR); + reg_val64 |= FXHCI_REG_OP_CRCR_CA; + FXhciWriteOper64(&xhci->mmio, FXHCI_REG_OP_CRCR, reg_val64); + + cc = FXhciWaitForCmdAborted(xhci, cmd_trb); + + if ((FXhciReadOper64(&xhci->mmio, FXHCI_REG_OP_CRCR) & FXHCI_REG_OP_CRCR_CRR)) + FUSB_ERROR("xhci_wait_for_command: Command ring still running"); + + return cc; +} + +FXhciTransCode FXhciCmdNop(FXhci *const xhci) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_NOOP); /* TRB Type */ + + FXhciPostCmd(xhci); + + /* wait for result in event ring */ + FXhciTransCode cc = FXhciWaitForCmdDone(xhci, cmd, 1); + + FUSB_INFO("Command ring is %srunning: cc: %d", + (FXhciReadOper64(&xhci->mmio, FXHCI_REG_OP_CRCR) & FXHCI_REG_OP_CRCR_CRR) ? "" : "not ", /* check if cmd ring is running */ + cc); + + if (cc != FXHCI_CC_SUCCESS) + FUSB_ERROR("noop command failed. "); + + return cc; +} + +/* + * xhci_cmd_* return >= 0: xhci completion code (cc) + * < 0: driver error code + */ + +FXhciTransCode FXhciCmdEnableSlot(FXhci *const xhci, int *const slot_id) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_ENABLE_SLOT); /* TRB Type */ + FXhciPostCmd(xhci); + + FXhciTransCode cc = FXhciWaitForCmd(xhci, cmd, 0); + if (cc >= 0) + { + if (cc == FXHCI_CC_SUCCESS) + { + *slot_id = FXHCI_TRB_GET(ID, xhci->er.cur); + if (*slot_id > xhci->max_slots_en) + cc = FXHCI_CC_CONTROLLER_ERROR; + } + + FXhciAdvanceEvtRing(xhci); + FXhciHandleEvts(xhci); + } + + return cc; +} + +FXhciTransCode FXhciCmdDisableSlot(FXhci *const xhci, const int slot_id) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_DISABLE_SLOT); /* TRB Type */ + FXHCI_TRB_SET(ID, cmd, slot_id); /* Slot ID */ + FXhciPostCmd(xhci); + + return FXhciWaitForCmd(xhci, cmd, 1); +} + +FXhciTransCode FXhciCmdAddressDevice(FXhci *const xhci, + const int slot_id, + FXhciInputCtx *const ic) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_ADDRESS_DEV); /* TRB Type */ + FXHCI_TRB_SET(ID, cmd, slot_id); /* Slot ID */ + cmd->ptr_low = (uintptr)(ic->raw); + FXhciPostCmd(xhci); + + return FXhciWaitForCmd(xhci, cmd, 1); +} + +FXhciTransCode FXhciCmdConfigureEp(FXhci *const xhci, + const int slot_id, + const int config_id, + FXhciInputCtx *const ic) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_CONFIGURE_EP); /* TRB Type */ + FXHCI_TRB_SET(ID, cmd, slot_id); /* Slot ID */ + cmd->ptr_low = (uintptr)(ic->raw); + + if (config_id == 0) + FXHCI_TRB_SET(DC, cmd, 1); /* Deconfigure */ + + FXhciPostCmd(xhci); + + return FXhciWaitForCmd(xhci, cmd, 1); +} + +FXhciTransCode FXhciCmdEvaluateCtx(FXhci *const xhci, + const int slot_id, + FXhciInputCtx *const ic) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_EVAL_CTX); /* TRB Type */ + FXHCI_TRB_SET(ID, cmd, slot_id); /* Slot ID */ + + cmd->ptr_low = (uintptr)(ic->raw); + FXhciPostCmd(xhci); + + return FXhciWaitForCmd(xhci, cmd, 1); +} + +FXhciTransCode FXhciCmdResetEp(FXhci *const xhci, const int slot_id, const int ep) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_RESET_EP); /* TRB Type */ + FXHCI_TRB_SET(ID, cmd, slot_id); /* Slot ID */ + FXHCI_TRB_SET(EP, cmd, ep); /* Endpoint ID */ + + FXhciPostCmd(xhci); + + return FXhciWaitForCmd(xhci, cmd, 1); +} + +FXhciTransCode FXhciCmdStopEp(FXhci *const xhci, const int slot_id, const int ep) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_STOP_EP); /* TRB Type */ + FXHCI_TRB_SET(ID, cmd, slot_id); /* Slot ID */ + FXHCI_TRB_SET(EP, cmd, ep); /* Endpoint ID */ + + FXhciPostCmd(xhci); + + return FXhciWaitForCmd(xhci, cmd, 1); +} + +FXhciTransCode FXhciCmdSetTrDq(FXhci *const xhci, const int slot_id, const int ep, + FXhciTrb *const dq_trb, const int dcs) +{ + FXhciTrb *const cmd = FXhciNextCmdTrb(xhci); + + FXHCI_TRB_SET(TT, cmd, FXHCI_TRB_CMD_SET_TR_DQ); /* TRB Type */ + FXHCI_TRB_SET(ID, cmd, slot_id); /* Slot ID */ + FXHCI_TRB_SET(EP, cmd, ep); /* Endpoint ID */ + + cmd->ptr_low = (uintptr)(dq_trb) | dcs; + + FXhciPostCmd(xhci); + + return FXhciWaitForCmd(xhci, cmd, 1); +} diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_debug.c b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_debug.c new file mode 100644 index 0000000000..027a7f4390 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_debug.c @@ -0,0 +1,131 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_debug.c + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:12:15 + * Description:  This files is for implementation of XHCI debug utilities + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include +#include "fdebug.h" +#include "fxhci_private.h" + +#define FUSB_DEBUG_TAG "FXHCI_DEBUG" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +void FXhciDumpSlotCtx(const FXhciSlotCtx *const sc) +{ + FUSB_INFO("Slot Context (@%p): ", sc); + FUSB_INFO(" FIELD1\t0x%08x ", sc->f1); + FUSB_INFO(" FIELD2\t0x%08x ", sc->f2); + FUSB_INFO(" FIELD3\t0x%08x ", sc->f3); + FUSB_INFO(" FIELD4\t0x%08x ", sc->f4); + FXHCI_SC_DUMP(FUSB_INFO, ROUTE, sc); + FXHCI_SC_DUMP(FUSB_INFO, SPEED1, sc); + FXHCI_SC_DUMP(FUSB_INFO, MTT, sc); + FXHCI_SC_DUMP(FUSB_INFO, HUB, sc); + FXHCI_SC_DUMP(FUSB_INFO, CTXENT, sc); + FXHCI_SC_DUMP(FUSB_INFO, RHPORT, sc); + FXHCI_SC_DUMP(FUSB_INFO, NPORTS, sc); + FXHCI_SC_DUMP(FUSB_INFO, TTID, sc); + FXHCI_SC_DUMP(FUSB_INFO, TTPORT, sc); + FXHCI_SC_DUMP(FUSB_INFO, TTT, sc); + FXHCI_SC_DUMP(FUSB_INFO, UADDR, sc); + FXHCI_SC_DUMP(FUSB_INFO, STATE, sc); +} + +void FXhciDumpEpCtx(const FXhciEpCtx *const ec) +{ + FUSB_INFO("Endpoint Context (@%p): ", ec); + FUSB_INFO(" FIELD1\t0x%08x ", ec->f1); + FUSB_INFO(" FIELD2\t0x%08x ", ec->f2); + FUSB_INFO(" TRDQ_L\t0x%08x ", ec->tr_dq_low); + FUSB_INFO(" TRDQ_H\t0x%08x ", ec->tr_dq_high); + FUSB_INFO(" FIELD5\t0x%08x ", ec->f5); + FXHCI_EC_DUMP(FUSB_INFO, STATE, ec); + FXHCI_EC_DUMP(FUSB_INFO, INTVAL, ec); + FXHCI_EC_DUMP(FUSB_INFO, CERR, ec); + FXHCI_EC_DUMP(FUSB_INFO, TYPE, ec); + FXHCI_EC_DUMP(FUSB_INFO, MBS, ec); + FXHCI_EC_DUMP(FUSB_INFO, MPS, ec); + FXHCI_EC_DUMP(FUSB_INFO, DCS, ec); + FXHCI_EC_DUMP(FUSB_INFO, AVRTRB, ec); + FXHCI_EC_DUMP(FUSB_INFO, MXESIT, ec); +} + +void FXhciDumpDevCtx(const FXhciDevCtx *const dc, const u32 ctx_mask) +{ + unsigned int i; + + if (ctx_mask & 1) + FXhciDumpSlotCtx(dc->slot); + + for (i = 1; i <= FXHCI_SC_GET(CTXENT, dc->slot); ++i) + { + if (ctx_mask & (1 << i)) + FXhciDumpEpCtx(dc->ep[i]); + } +} + +void FXhciDumpInputCtx(const FXhciInputCtx *const ic) +{ + FUSB_INFO("Input Control add: 0x%08x ", *ic->add); + FUSB_INFO("Input Control drop: 0x%08x ", *ic->drop); + FXhciDumpDevCtx(&ic->dev, *ic->add); +} + +void FXhciDumpTransferTrb(const FXhciTrb *const cur) +{ + FUSB_INFO("Transfer TRB (@%p): ", cur); + FUSB_INFO(" PTR_L\t0x%08x ", cur->ptr_low); + FUSB_INFO(" PTR_H\t0x%08x ", cur->ptr_high); + FUSB_INFO(" STATUS\t0x%08x ", cur->status); + FUSB_INFO(" CNTRL\t0x%08x ", cur->control); + FXHCI_TRB_DUMP(FUSB_INFO, TL, cur); + FXHCI_TRB_DUMP(FUSB_INFO, TDS, cur); + FXHCI_TRB_DUMP(FUSB_INFO, C, cur); + FXHCI_TRB_DUMP(FUSB_INFO, ISP, cur); + FXHCI_TRB_DUMP(FUSB_INFO, CH, cur); + FXHCI_TRB_DUMP(FUSB_INFO, IOC, cur); + FXHCI_TRB_DUMP(FUSB_INFO, IDT, cur); + FXHCI_TRB_DUMP(FUSB_INFO, TT, cur); + FXHCI_TRB_DUMP(FUSB_INFO, DIR, cur); +} + +static const FXhciTrb *FXhciNextTrb(const FXhciTrb *const cur) +{ + if (FXHCI_TRB_GET(TT, cur) == FXHCI_TRB_LINK) + return (!cur->ptr_low) ? NULL : (void *)(uintptr)(cur->ptr_low); + else + return cur + 1; +} + +void FXhciDumpTransferTrbs(const FXhciTrb *const first, const FXhciTrb *const last) +{ + const FXhciTrb *cur; + for (cur = first; cur; cur = FXhciNextTrb(cur)) + { + FXhciDumpTransferTrb(cur); + if (cur == last) + break; + } +} diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_dev.c b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_dev.c new file mode 100644 index 0000000000..3d1b868c85 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_dev.c @@ -0,0 +1,597 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_dev.c + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:12:46 + * Description:  This files is for implementation of XHCI device + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include +#include "fsleep.h" +#include "fcache.h" +#include "fdebug.h" + +#include "fxhci_private.h" + +#define FUSB_DEBUG_TAG "FXHCI_DEV" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +static u32 FXhciGenRounte(FXhci *const xhci, const int hubport, const int hubaddr) +{ + FASSERT(xhci); + if (!hubaddr) + return 0; + + u32 route_string = FXHCI_SC_GET(ROUTE, xhci->dev[hubaddr].ctx.slot); + int i; + + for (i = 0; i < 20; i += 4) + { + if (!(route_string & (0xf << i))) + { + route_string |= (hubport & 0xf) << i; + break; + } + } + + return route_string; +} + +static int FXhciGetRoothubPort(FXhci *const xhci, const int hubport, const int hubaddr) +{ + FASSERT(xhci); + if (!hubaddr) + return hubport; + + return FXHCI_SC_GET(RHPORT, xhci->dev[hubaddr].ctx.slot); +} + +static int FXhciGetTT(FXhci *const xhci, const FUsbSpeed speed, + const int hubport, const int hubaddr, + int *const tt, int *const tt_port) +{ + FASSERT(xhci); + if (!hubaddr) + return 0; + + const FXhciSlotCtx *const slot = xhci->dev[hubaddr].ctx.slot; + + if ((*tt = FXHCI_SC_GET(TTID, slot))) + { + *tt_port = FXHCI_SC_GET(TTPORT, slot); + } + else if (speed < FUSB_HIGH_SPEED && + FXHCI_SC_GET(SPEED1, slot) - 1 == FUSB_HIGH_SPEED) + { + *tt = hubaddr; + *tt_port = hubport; + } + + return *tt != 0; +} + +static void FXhciReapSlots(FXhci *const xhci, int skip_slot) +{ + FASSERT(xhci); + int i; + FUsb *instance = xhci->usb; + + FUSB_INFO("xHC resource shortage, trying to reap old slots... "); + for (i = 1; i <= xhci->max_slots_en; i++) + { + if (i == skip_slot) + continue; /* don't reap slot we were working on */ + if (xhci->dev[i].transfer_rings[1]) + continue; /* slot still in use */ + if (NULL == xhci->dev[i].ctx.raw) + continue; /* slot already disabled */ + + const FXhciTransCode cc = FXhciCmdDisableSlot(xhci, i); + if (cc != FXHCI_CC_SUCCESS) + FUSB_INFO("Failed to disable slot %d: %d ", i, cc); + else + FUSB_INFO("Successfully reaped slot %d ", i); + xhci->dcbaa[i] = 0; + + FUSB_FREE(instance, xhci->dev[i].ctx.raw); + xhci->dev[i].ctx.raw = NULL; + } +} + +static FXhciInputCtx *FXhciMakeInputCtx(FXhci *xhci, const size_t ctxsize) +{ + int i; + const size_t size = (1 + FXHCI_NUM_EPS) * ctxsize; + FUsb *instance = xhci->usb; + FXhciInputCtx *const ic = FUSB_ALLOCATE(instance, sizeof(*ic), FUSB_DEFAULT_ALIGN); + void *dma_buffer = FUSB_ALLOCATE(instance, size, 64); + + if ((NULL == ic) || (NULL == dma_buffer)) + { + FUSB_FREE(instance, ic); + FUSB_FREE(instance, dma_buffer); + return NULL; + } + + + memset(dma_buffer, 0, size); + ic->drop = dma_buffer + 0; + ic->add = dma_buffer + 4; + dma_buffer += ctxsize; + for (i = 0; i < FXHCI_NUM_EPS; i++, dma_buffer += ctxsize) + ic->dev.ep[i] = dma_buffer; + + return ic; +} + +/** + * @name: FXhciSetAddress + * @msg: 设备USB设备的地址 + * @return {FUsbDev *}, USB设备实例 + * @param {FUsbHc} *controller, USB控制器实例 + * @param {FUsbSpeed} speed, USB设备的速度类型 + * @param {int} hubport, USB设备连接的port号 + * @param {int} hubaddr, USB设备连接的hub地址 + */ +FUsbDev *FXhciSetAddress(FUsbHc *controller, FUsbSpeed speed, int hubport, int hubaddr) +{ + FXhci *const xhci = FXHCI_INST_GET(controller); + FASSERT(xhci); + const size_t ctxsize = FXhciGetCtxSize(&xhci->mmio); + FXhciDevInfo *di = NULL; + FUsbDev *dev = NULL; + FUsb *instance = controller->usb; + int i; + + FXhciInputCtx *const ic = FXhciMakeInputCtx(xhci, ctxsize); + FXhciTransRing *const tr = FUSB_ALLOCATE(instance, sizeof(*tr), FUSB_DEFAULT_ALIGN); + + if (NULL != tr) + { + FASSERT(NULL == tr->ring); + tr->ring = FXHCI_ALIGN(xhci, 16, FXHCI_TRANSFER_RING_SIZE * sizeof(FXhciTrb)); + } + + if ((NULL == ic) || (NULL == tr) || (NULL == tr->ring)) + { + FUSB_INFO("Out of memory "); + goto _free_return; + } + + + int slot_id; + FXhciTransCode cc = FXhciCmdEnableSlot(xhci, &slot_id); + if (cc == FXHCI_CC_NO_SLOTS_AVAILABLE) + { + FXhciReapSlots(xhci, 0); + cc = FXhciCmdEnableSlot(xhci, &slot_id); + } + + if (cc != FXHCI_CC_SUCCESS) + { + FUSB_INFO("Enable slot failed: %d ", cc); + goto _free_return; + } + else + { + FUSB_INFO("Enabled slot %d ", slot_id); + } + + di = &xhci->dev[slot_id]; + void *dma_buffer = FUSB_ALLOCATE(instance, FXHCI_NUM_EPS * ctxsize, 64); + if (NULL == dma_buffer) + goto _disable_return; + + memset(dma_buffer, 0, FXHCI_NUM_EPS * ctxsize); + for (i = 0; i < FXHCI_NUM_EPS; i++, dma_buffer += ctxsize) + di->ctx.ep[i] = dma_buffer; + + *ic->add = (1 << 0) /* Slot Context */ | (1 << 1) /* EP0 Context */; + + FXHCI_SC_SET(ROUTE, ic->dev.slot, FXhciGenRounte(xhci, hubport, hubaddr)); + FXHCI_SC_SET(SPEED1, ic->dev.slot, speed + 1); + FXHCI_SC_SET(CTXENT, ic->dev.slot, 1); /* the endpoint 0 context */ + FXHCI_SC_SET(RHPORT, ic->dev.slot, FXhciGetRoothubPort(xhci, hubport, hubaddr)); + + int tt, tt_port; + if (FXhciGetTT(xhci, speed, hubport, hubaddr, &tt, &tt_port)) + { + FUSB_INFO("TT for %d: %d[%d] ", slot_id, tt, tt_port); + FXHCI_SC_SET(MTT, ic->dev.slot, FXHCI_SC_GET(MTT, xhci->dev[tt].ctx.slot)); + FXHCI_SC_SET(TTID, ic->dev.slot, tt); + FXHCI_SC_SET(TTPORT, ic->dev.slot, tt_port); + } + + di->transfer_rings[1] = tr; + FXhciInitCycleRing(tr, FXHCI_TRANSFER_RING_SIZE); + + ic->dev.ep0->tr_dq_low = (uintptr)(tr->ring); + ic->dev.ep0->tr_dq_high = 0; + FXHCI_EC_SET(TYPE, ic->dev.ep0, FXHCI_EP_CONTROL); + FXHCI_EC_SET(AVRTRB, ic->dev.ep0, 8); + FXHCI_EC_SET(MPS, ic->dev.ep0, FUsbSpeedtoDefaultMaxPacketSz(speed)); + FXHCI_EC_SET(CERR, ic->dev.ep0, 3); + FXHCI_EC_SET(DCS, ic->dev.ep0, 1); + + xhci->dcbaa[slot_id] = (uintptr)(di->ctx.raw); + + FCacheDCacheInvalidateRange((uintptr)ic, sizeof(*ic)); /* flush cache of input address */ + + cc = FXhciCmdAddressDevice(xhci, slot_id, ic); + if (cc == FXHCI_CC_RESOURCE_ERROR) + { + FXhciReapSlots(xhci, slot_id); + cc = FXhciCmdAddressDevice(xhci, slot_id, ic); + } + + if (cc != FXHCI_CC_SUCCESS) + { + FUSB_INFO("Address device failed: %d ", cc); + goto _disable_return; + } + else + { + FUSB_INFO("Addressed device %d (USB: %d) ", + slot_id, FXHCI_SC_GET(UADDR, di->ctx.slot)); + } + + fsleep_millisec(FUSB_SET_ADDRESS_MDELAY); + + dev = FUsbInitDevEntry(controller, slot_id); + if (!dev) + goto _disable_return; + + dev->address = slot_id; + dev->hub = hubaddr; + dev->port = hubport; + dev->speed = speed; + dev->endpoints[0].dev = dev; + dev->endpoints[0].endpoint = 0; + dev->endpoints[0].toggle = 0; + dev->endpoints[0].direction = FUSB_SETUP; + dev->endpoints[0].type = FUSB_CONTROL_EP; + + u8 buf[8]; + if (FUsbGetDescriptor(dev, FUsbGenerateReqType(FUSB_REQ_DEVICE_TO_HOST, FUSB_REQ_TYPE_STANDARD, FUSB_REQ_RECP_DEV), FUSB_DESC_TYPE_DEVICE, 0, buf, sizeof(buf)) != sizeof(buf)) + { + FUSB_INFO("first FUsbGetDescriptor(FUSB_DESC_TYPE_DEVICE) failed "); + goto _disable_return; + } + + dev->endpoints[0].maxpacketsize = FUsbDecodeMaxPacketSz0(speed, buf[7]); + if (dev->endpoints[0].maxpacketsize != FUsbSpeedtoDefaultMaxPacketSz(speed)) + { + memset((void *)ic->dev.ep0, 0x00, ctxsize); + *ic->add = (1 << 1); /* EP0 Context */ + FXHCI_EC_SET(MPS, ic->dev.ep0, dev->endpoints[0].maxpacketsize); + + /* flush cache of input context before send command */ + FCacheDCacheInvalidateRange((uintptr)ic, sizeof(*ic)); + + cc = FXhciCmdEvaluateCtx(xhci, slot_id, ic); + if (cc == FXHCI_CC_RESOURCE_ERROR) + { + FXhciReapSlots(xhci, slot_id); + cc = FXhciCmdEvaluateCtx(xhci, slot_id, ic); + } + if (cc != FXHCI_CC_SUCCESS) + { + FUSB_INFO("Context evaluation failed: %d ", cc); + goto _disable_return; + } + } + + goto _free_ic_return; + +_disable_return: + FXhciCmdDisableSlot(xhci, slot_id); + xhci->dcbaa[slot_id] = 0; + FUsbDetachDev(controller, slot_id); + dev = NULL; +_free_return: + if (tr) + FUSB_FREE(instance, (void *)tr->ring); + FUSB_FREE(instance, tr); + if (di) + { + FUSB_FREE(instance, di->ctx.raw); + di->ctx.raw = 0; + } +_free_ic_return: + if (ic) + { + FUSB_FREE(instance, ic->raw); + FUSB_FREE(instance, ic); + } + return dev; +} + +static int FXhciFinishHubConfig(FUsbDev *const dev, FXhciInputCtx *const ic) +{ + int type = FUsbIsSuperSpeed(dev->speed) ? 0x2a : 0x29; /* similar enough */ + FUsbHubDescriptor desc; + + if (FUsbGetDescriptor(dev, FUsbGenerateReqType(FUSB_REQ_DEVICE_TO_HOST, FUSB_REQ_TYPE_CLASS, FUSB_REQ_RECP_DEV), type, 0, &desc, sizeof(desc)) != sizeof(desc)) + { + FUSB_INFO("Failed to fetch hub descriptor "); + return FXHCI_CC_COMMUNICATION_ERROR; + } + + FXHCI_SC_SET(HUB, ic->dev.slot, 1); + FXHCI_SC_SET(MTT, ic->dev.slot, 0); /* No support for Multi-TT */ + FXHCI_SC_SET(NPORTS, ic->dev.slot, desc.bNbrPorts); + + if (dev->speed == FUSB_HIGH_SPEED) + FXHCI_SC_SET(TTT, ic->dev.slot, + (desc.wHubCharacteristics >> 5) & 0x0003); + + return 0; +} + +static size_t FXhciBoundInterval(const FUsbEndpoint *const ep) +{ + if ((ep->dev->speed == FUSB_LOW_SPEED && + (ep->type == FUSB_ISOCHRONOUS_EP || + ep->type == FUSB_INTERRUPT_EP)) || + (ep->dev->speed == FUSB_FULL_SPEED && + ep->type == FUSB_INTERRUPT_EP)) + { + if (ep->interval < 3) + return 3; + else if (ep->interval > 11) + return 11; + else + return ep->interval; + } + else + { + if (ep->interval < 0) + return 0; + else if (ep->interval > 15) + return 15; + else + return ep->interval; + } +} + +static int FXhciFinishEpConfig(const FUsbEndpoint *const ep, FXhciInputCtx *const ic) +{ + FXhci *const xhci = FXHCI_INST_GET(ep->dev->controller); + FASSERT(xhci); + FUsb *instance = xhci->usb; + const int ep_id = FXhciEpId(ep); + FUSB_INFO("ep_id: %d ", ep_id); + + if (ep_id <= 1 || 32 <= ep_id) + return FXHCI_CC_DRIVER_ERROR; + + FXhciTransRing *const tr = FUSB_ALLOCATE(instance, sizeof(*tr), FUSB_DEFAULT_ALIGN); + if (NULL != tr) + { + FASSERT(NULL == tr->ring); + tr->ring = FXHCI_ALIGN(xhci, 16, FXHCI_TRANSFER_RING_SIZE * sizeof(FXhciTrb)); + } + + if ((NULL == tr) || (NULL == tr->ring)) + { + FUSB_FREE(instance, tr); + FUSB_ERROR("Out of memory "); + return FXHCI_CC_OUT_OF_MEMORY; + } + + xhci->dev[ep->dev->address].transfer_rings[ep_id] = tr; + FXhciInitCycleRing(tr, FXHCI_TRANSFER_RING_SIZE); + + *ic->add |= (1 << ep_id); + if ((int)FXHCI_SC_GET(CTXENT, ic->dev.slot) < ep_id) + FXHCI_SC_SET(CTXENT, ic->dev.slot, ep_id); + + FXhciEpCtx *const epctx = ic->dev.ep[ep_id]; + + FUSB_DEBUG("Filling epctx (@%p) ", epctx); + epctx->tr_dq_low = (uintptr)(tr->ring); + epctx->tr_dq_high = 0; + + FXHCI_EC_SET(INTVAL, epctx, FXhciBoundInterval(ep)); + FXHCI_EC_SET(CERR, epctx, 3); + FXHCI_EC_SET(TYPE, epctx, ep->type | ((ep->direction != FUSB_OUT) << 2)); + FXHCI_EC_SET(MPS, epctx, ep->maxpacketsize); + FXHCI_EC_SET(DCS, epctx, 1); + + size_t avrtrb; + switch (ep->type) + { + case FUSB_BULK_EP: + case FUSB_ISOCHRONOUS_EP: + avrtrb = 3 * 1024; + break; + case FUSB_INTERRUPT_EP: + avrtrb = 1024; + break; + default: + avrtrb = 8; + break; + } + FXHCI_EC_SET(AVRTRB, epctx, avrtrb); + FXHCI_EC_SET(MXESIT, epctx, FXHCI_EC_GET(MPS, epctx) * FXHCI_EC_GET(MBS, epctx)); + + return 0; +} + +/** + * @name: FXhciFinishDevConfig + * @msg: 完成USB设备配置 + * @return {FXhciTransCode} 传输返回码 + * @param {FUsbDev} *dev, USB设备实例 + */ +FXhciTransCode FXhciFinishDevConfig(FUsbDev *const dev) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + FUsb *instance = xhci->usb; + int slot_id = dev->address; + FXhciDevInfo *const di = &xhci->dev[slot_id]; + + int i; + FXhciTransCode ret = FXHCI_CC_ZERO_BYTES; + + FXhciInputCtx *const ic = FXhciMakeInputCtx(xhci, FXhciGetCtxSize(&xhci->mmio)); + if (!ic) + { + FUSB_INFO("Out of memory "); + return FXHCI_CC_OUT_OF_MEMORY; + } + + *ic->add = (1 << 0); /* Slot Context */ + + ic->dev.slot->f1 = di->ctx.slot->f1; + ic->dev.slot->f2 = di->ctx.slot->f2; + ic->dev.slot->f3 = di->ctx.slot->f3; + /* f4 *must* be 0 in the Input Context... yeah, it's weird, I know. */ + + FCacheDCacheInvalidateRange((uintptr)ic, sizeof(*ic)); + + if (dev->descriptor->bDeviceClass == FUSB_HUB_DEVICE) + { + ret = FXhciFinishHubConfig(dev, ic); + if (ret) + goto _free_return; + } + + for (i = 1; i < dev->num_endp; ++i) + { + ret = FXhciFinishEpConfig(&dev->endpoints[i], ic); + if (ret) + goto _free_ep_ctx_return; + } + + const int config_id = dev->configuration->bConfigurationValue; + FUSB_INFO("config_id: %d ", config_id); + FXhciTransCode cc = FXhciCmdConfigureEp(xhci, slot_id, config_id, ic); + + if (cc == FXHCI_CC_RESOURCE_ERROR || cc == FXHCI_CC_BANDWIDTH_ERROR) + { + FXhciReapSlots(xhci, slot_id); + cc = FXhciCmdConfigureEp(xhci, slot_id, config_id, ic); + } + + if (cc != FXHCI_CC_SUCCESS) + { + FUSB_INFO("Configure endpoint failed: %d ", cc); + ret = FXHCI_CC_CONTROLLER_ERROR; + goto _free_ep_ctx_return; + } + else + { + FUSB_INFO("Endpoints configured "); + } + + goto _free_return; + +_free_ep_ctx_return: + for (i = 2; i < 31; ++i) + { + if (di->transfer_rings[i]) + { + FUSB_FREE(instance, (void *)di->transfer_rings[i]->ring); + FUSB_FREE(instance, di->transfer_rings[i]); + } + di->transfer_rings[i] = NULL; + } +_free_return: + if (NULL != ic) + { + FUSB_FREE(instance, ic->raw); + FUSB_FREE(instance, ic); + } + return ret; +} + +/** + * @name: FXhciDestoryDev + * @msg: 删除指定USB设备实例 + * @return {*} + * @param {FUsbHc} *controller, USB控制器实例 + * @param {int} slot_id, USB设备所在的slot号 + */ +void FXhciDestoryDev(FUsbHc *const controller, const int slot_id) +{ + FXhci *const xhci = FXHCI_INST_GET(controller); + FASSERT(xhci); + FUsb *instance = xhci->usb; + + if (slot_id <= 0 || slot_id > xhci->max_slots_en) + return; + + FXhciInputCtx *const ic = FXhciMakeInputCtx(xhci, FXhciGetCtxSize(&xhci->mmio)); + if (NULL == ic) + { + FUSB_WARN("Out of memory, leaking resources! "); + return; + } + + const int num_eps = controller->devices[slot_id]->num_endp; + *ic->add = 0; /* Leave Slot/EP0 state as it is for now. */ + *ic->drop = (1 << num_eps) - 1; /* Drop all endpoints we can. */ + *ic->drop &= ~(1 << 1 | 1 << 0); /* Not allowed to drop EP0 or Slot. */ + + FCacheDCacheInvalidateRange((uintptr)ic, sizeof(*ic)); + + FXhciTransCode cc = FXhciCmdEvaluateCtx(xhci, slot_id, ic); + + if (NULL != ic) + { + FUSB_FREE(instance, ic->raw); + FUSB_FREE(instance, ic); + } + + if (cc != FXHCI_CC_SUCCESS) + FUSB_INFO("Failed to quiesce slot %d: %d ", slot_id, cc); + + cc = FXhciCmdStopEp(xhci, slot_id, FXHCI_EP0_ID); + if (cc != FXHCI_CC_SUCCESS) + FUSB_INFO("Failed to stop EP0 on slot %d: %d ", slot_id, cc); + + int i; + FXhciDevInfo *const di = &xhci->dev[slot_id]; + for (i = 1; i < /*num_eps*/FXHCI_NUM_EPS; ++i) + { + if (di->transfer_rings[i]) + { + FUSB_FREE(instance, (void *)di->transfer_rings[i]->ring); + FUSB_FREE(instance, (void *)di->transfer_rings[i]); + } + FUSB_FREE(instance, di->interrupt_queues[i]); + } + + /* free device context */ + if (NULL != di->ctx.raw) + { + FUSB_FREE(instance, di->ctx.raw); + di->ctx.raw = NULL; + } + + FUSB_INFO("Stopped slot %d, but not disabling it yet. ", slot_id); + di->transfer_rings[1] = NULL; + + return; +} diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_evt.c b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_evt.c new file mode 100644 index 0000000000..cfa984ed6a --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_evt.c @@ -0,0 +1,371 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_evt.c + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:13:09 + * Description:  This files is for implementation of XHCI event + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include "fsleep.h" +#include "fdebug.h" + +#include "fxhci_private.h" + +#define FUSB_DEBUG_TAG "FXHCI-EVT" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +/** + * @name: FXhciResetEvtRing + * @msg: 重置Event TRB ring + * @return {*} + * @param {FXhciEvtRing} *er, Event TRB ring实例 + */ +void FXhciResetEvtRing(FXhciEvtRing *const er) +{ + int i; + for (i = 0; i < FXHCI_EVENT_RING_SIZE; ++i) + er->ring[i].control &= ~FXHCI_TRB_CYCLE; + er->cur = er->ring; + er->last = er->ring + FXHCI_EVENT_RING_SIZE; + er->ccs = 1; + er->adv = 1; +} + +static inline int FXhciEvtReady(const FXhciEvtRing *const er) +{ + return (er->cur->control & FXHCI_TRB_CYCLE) == er->ccs; +} + +void FXhciUpdateEvtDQ(FXhci *const xhci) +{ + if (xhci->er.adv) + { + FUSB_DEBUG("Updating dq ptr: @0x%lx -> %p", + FXhciReadRt64(&xhci->mmio, 0, FXHCI_REG_RT_IR_ERDP), + xhci->er.cur); + FXhciWriteRt64(&xhci->mmio, 0, FXHCI_REG_RT_IR_ERDP, FXHCI_REG_RT_IR_ERDP_MASK & ((u64)(uintptr)xhci->er.cur)); + xhci->er.adv = 0; + } +} + +void FXhciAdvanceEvtRing(FXhci *const xhci) +{ + xhci->er.cur++; + xhci->er.adv = 1; + if (xhci->er.cur == xhci->er.last) + { + FUSB_DEBUG("Roll over in event ring "); + xhci->er.cur = xhci->er.ring; + xhci->er.ccs ^= 1; + FXhciUpdateEvtDQ(xhci); + } +} + +static void FXhciHandleTransferEvt(FXhci *const xhci) +{ + const FXhciTrb *const ev = xhci->er.cur; + + const FXhciTransCode cc = FXHCI_TRB_GET(CC, ev); /* Completion Code */ + const int id = FXHCI_TRB_GET(ID, ev); + const int ep = FXHCI_TRB_GET(EP, ev); + + FXhciIntrQ *intrq; + + if (id && id <= xhci->max_slots_en && + (intrq = xhci->dev[id].interrupt_queues[ep])) + { + /* It's a running interrupt endpoint */ + intrq->ready = (void *)(uintptr)(ev->ptr_low); + if (cc == FXHCI_CC_SUCCESS || cc == FXHCI_CC_SHORT_PACKET) + { + FXHCI_TRB_SET(TL, intrq->ready, + intrq->size - FXHCI_TRB_GET(EVTL, ev)); /* Transfer Length */ + } + else + { + FUSB_INFO("Interrupt Transfer failed: %d ", cc); + FXHCI_TRB_SET(TL, intrq->ready, 0); /* Transfer Length */ + } + } + else if (cc == FXHCI_CC_STOPPED || cc == FXHCI_CC_STOPPED_LENGTH_INVALID) + { + /* Ignore 'Forced Stop Events' */ + } + else + { + FUSB_WARN("Warning: \r\n" + "Spurious transfer event for ID %d, EP %d: \r\n" + " Pointer: 0x%08x%08x \r\n" + " TL: 0x%06x \r\n" + " CC: %d ", + id, ep, + ev->ptr_high, ev->ptr_low, + FXHCI_TRB_GET(EVTL, ev), cc); + } + + FXhciAdvanceEvtRing(xhci); +} + +static void FXhciHandleCmdCompletionEvt(FXhci *const xhci) +{ + const FXhciTrb *const ev = xhci->er.cur; + + FUSB_INFO("Warning: Spurious command completion event: \r\n" + " Pointer: 0x%08x%08x \r\n" + " CC: %d \r\n" + " Slot ID: %d \r\n" + " Cycle: %d ", + ev->ptr_high, ev->ptr_low, + FXHCI_TRB_GET(CC, ev), FXHCI_TRB_GET(ID, ev), ev->control & FXHCI_TRB_CYCLE); + FXhciAdvanceEvtRing(xhci); +} + +static void FXhciHandleHostCtrlEvt(FXhci *const xhci) +{ + const FXhciTrb *const ev = xhci->er.cur; + + const FXhciTransCode cc = FXHCI_TRB_GET(CC, ev); + switch (cc) + { + case FXHCI_CC_EVENT_RING_FULL_ERROR: + FUSB_INFO("Event ring full! (@%p) ", xhci->er.cur); + /* + * If we get here, we have processed the whole queue: + * xHC pushes this event, when it sees the ring full, + * full of other events. + * IMO it's save and necessary to update the dequeue + * pointer here. + */ + FXhciAdvanceEvtRing(xhci); + FXhciUpdateEvtDQ(xhci); + break; + default: + FUSB_INFO("Warning: Spurious host controller event: %d ", cc); + FXhciAdvanceEvtRing(xhci); + break; + } +} + +/* handle standard types: + * - command completion event + * - port status change event + * - transfer event + * - host controller event + */ +static void FXhciHandleEvt(FXhci *const xhci) +{ + const FXhciTrb *const ev = xhci->er.cur; + + const int trb_type = FXHCI_TRB_GET(TT, ev); + switch (trb_type) + { + /* Either pass along the event or advance event ring */ + case FXHCI_TRB_EV_TRANSFER: + FXhciHandleTransferEvt(xhci); + break; + case FXHCI_TRB_EV_CMD_CMPL: + FXhciHandleCmdCompletionEvt(xhci); + break; + case FXHCI_TRB_EV_PORTSC: + FUSB_INFO("Port Status Change Event for %d: %d ", + FXHCI_TRB_GET(PORT, ev), FXHCI_TRB_GET(CC, ev)); + /* We ignore the event as we look for the PORTSC + registers instead, at a time when it suits _us_. */ + FXhciAdvanceEvtRing(xhci); + break; + case FXHCI_TRB_EV_HOST: + FXhciHandleHostCtrlEvt(xhci); + break; + default: + FUSB_INFO("Warning: Spurious event: %d, Completion Code: %d ", + trb_type, FXHCI_TRB_GET(CC, ev)); + FXhciAdvanceEvtRing(xhci); + break; + } +} + +void FXhciHandleEvts(FXhci *const xhci) +{ + while (FXhciEvtReady(&xhci->er)) + FXhciHandleEvt(xhci); + + FXhciUpdateEvtDQ(xhci); + return; +} + +static unsigned long FXhciWaitForEvt(const FXhciEvtRing *const er, + unsigned long *const timeout_us) +{ + while (!FXhciEvtReady(er) && *timeout_us) + { + --*timeout_us; + fsleep_microsec(1); + } + return *timeout_us; +} + +static unsigned long FXhciWaitForEvtType(FXhci *const xhci, + const int trb_type, + unsigned long *const timeout_us) +{ + while (FXhciWaitForEvt(&xhci->er, timeout_us)) + { + if (FXHCI_TRB_GET(TT, xhci->er.cur) == (unsigned int)trb_type) + break; + + FXhciHandleEvt(xhci); + } + + return *timeout_us; +} + +/* + * Ref. xHCI Specification Revision 1.2, May 2019. + * Section 4.6.1.2. + * + * Process events from xHCI Abort command. + * + * Returns FXHCI_CC_COMMAND_RING_STOPPED on success and FXHCI_CC_TIMEOUT on failure. + */ + +FXhciTransCode FXhciWaitForCmdAborted(FXhci *const xhci, const FXhciTrb *const address) +{ + /* + * Specification says that something might be seriously wrong, if + * we don't get a response after 5s. Still, let the caller decide, + * what to do then. + */ + unsigned long timeout_us = FUSB_USB_MAX_PROCESSING_TIME_US; /* 5s */ + FXhciTransCode cc = FXHCI_CC_TIMEOUT; + /* + * Expects two command completion events: + * The first with CC == COMMAND_ABORTED should point to address + * (not present if command was not running), + * the second with CC == COMMAND_RING_STOPPED should point to new dq. + */ + while (FXhciWaitForEvtType(xhci, FXHCI_TRB_EV_CMD_CMPL, &timeout_us)) + { + if ((xhci->er.cur->ptr_low == (uintptr)(address)) && + (xhci->er.cur->ptr_high == 0)) + { + cc = FXHCI_TRB_GET(CC, xhci->er.cur); + FXhciAdvanceEvtRing(xhci); + break; + } + + FXhciHandleCmdCompletionEvt(xhci); + } + if (timeout_us == 0) + { + FUSB_INFO("Warning: Timed out waiting for " + "COMMAND_ABORTED or COMMAND_RING_STOPPED. "); + goto update_and_return; + } + if (cc == FXHCI_CC_COMMAND_RING_STOPPED) + { + /* There may not have been a command to abort. */ + goto update_and_return; + } + + timeout_us = FUSB_USB_MAX_PROCESSING_TIME_US; /* 5s */ + while (FXhciWaitForEvtType(xhci, FXHCI_TRB_EV_CMD_CMPL, &timeout_us)) + { + if (FXHCI_TRB_GET(CC, xhci->er.cur) == FXHCI_CC_COMMAND_RING_STOPPED) + { + cc = FXHCI_CC_COMMAND_RING_STOPPED; + FXhciAdvanceEvtRing(xhci); + break; + } + + FXhciHandleCmdCompletionEvt(xhci); + } + if (timeout_us == 0) + FUSB_INFO("Warning: Timed out " + "waiting for COMMAND_RING_STOPPED. "); + +update_and_return: + FXhciUpdateEvtDQ(xhci); + return cc; +} + +/* + * returns cc of command in question (pointed to by `address`) + * caller should abort command if cc is FXHCI_CC_TIMEOUT + */ +FXhciTransCode FXhciWaitForCmdDone(FXhci *const xhci, + const FXhciTrb *const address, + const int clear_event) +{ + unsigned long timeout_us = FUSB_USB_MAX_PROCESSING_TIME_US; /* 5s */ + FXhciTransCode cc = FXHCI_CC_TIMEOUT; + + while (FXhciWaitForEvtType(xhci, FXHCI_TRB_EV_CMD_CMPL, &timeout_us)) + { + if ((xhci->er.cur->ptr_low == (uintptr)(address)) && + (xhci->er.cur->ptr_high == 0)) + { + cc = FXHCI_TRB_GET(CC, xhci->er.cur); + break; + } + + FXhciHandleCmdCompletionEvt(xhci); + } + + if (!timeout_us) + { + FUSB_INFO("Warning: Timed out waiting for FXHCI_TRB_EV_CMD_CMPL. "); + } + else if (clear_event) + { + FXhciAdvanceEvtRing(xhci); + } + + FXhciUpdateEvtDQ(xhci); + return cc; +} + +/* returns amount of bytes transferred on success, negative CC on error */ +FXhciTransCode FXhciWaitForTransfer(FXhci *const xhci, const int slot_id, const int ep_id) +{ + /* 5s for all types of transfers */ + unsigned long timeout_us = FUSB_USB_MAX_PROCESSING_TIME_US; + FXhciTransCode ret = FXHCI_CC_TIMEOUT; + while (FXhciWaitForEvtType(xhci, FXHCI_TRB_EV_TRANSFER, &timeout_us)) + { + if (FXHCI_TRB_GET(ID, xhci->er.cur) == (unsigned int)slot_id && + FXHCI_TRB_GET(EP, xhci->er.cur) == (unsigned int)ep_id) + { + ret = -FXHCI_TRB_GET(CC, xhci->er.cur); + if (ret == -FXHCI_CC_SUCCESS || ret == -FXHCI_CC_SHORT_PACKET) + ret = FXHCI_TRB_GET(EVTL, xhci->er.cur); + FXhciAdvanceEvtRing(xhci); + break; + } + + FXhciHandleTransferEvt(xhci); + } + if (!timeout_us) + FUSB_INFO("Warning: Timed out waiting for FXHCI_TRB_EV_TRANSFER. "); + + FXhciUpdateEvtDQ(xhci); + return ret; +} diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_hw.c b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_hw.c new file mode 100644 index 0000000000..3af4ad4968 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_hw.c @@ -0,0 +1,217 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_hw.c + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:13:30 + * Description:  This files is for implementation of XHCI register functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +/***************************** Include Files *********************************/ +#include "fdebug.h" +#include "fgeneric_timer.h" +#include "fsleep.h" + +#include "fxhci_private.h" + + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FUSB_DEBUG_TAG "FXHCI_HW" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +/************************** Function Prototypes ******************************/ + +/************************** Variable Definitions *****************************/ + +/*****************************************************************************/ +FError FXhciSetupMMIO(FXhciMMIO *mmio, uintptr base_addr) +{ + FASSERT(mmio); + u32 reg_val; + + mmio->base = base_addr; + + /* add to register base to find the beginning of the Operational Register Space */ + mmio->oper_base = mmio->base + FtIn8(mmio->base + FXHCI_REG_CAP_CAPLENGTH); + mmio->doorbell_base = mmio->base + FXHCI_REG_CAP_DBOFF_GET(FtIn32(mmio->base + FXHCI_REG_CAP_DBOFF)); + mmio->runtime_base = mmio->base + FXHCI_REG_CAP_RTSOFF_GET(FtIn32(mmio->base + FXHCI_REG_CAP_RTSOFF)); + mmio->port_base = mmio->oper_base + FXHCI_REG_OP_PORTS_BASE; + + /* cache static information of CAP_HCSPARAMS */ + mmio->hcx_params[0] = FtIn32(mmio->base + FXHCI_REG_CAP_HCSPARAMS1); + mmio->hcx_params[1] = FtIn32(mmio->base + FXHCI_REG_CAP_HCSPARAMS2); + mmio->hcx_params[2] = FtIn32(mmio->base + FXHCI_REG_CAP_HCSPARAMS3); + mmio->hcx_params[3] = FtIn32(mmio->base + FXHCI_REG_CAP_HCCPARAMS); + + reg_val = mmio->hcx_params[3]; + mmio->xecp_base = mmio->base + (FXHCI_REG_CAP_HCCPARAMS_XECP_GET(reg_val) << 2); + + FUSB_DEBUG(" mmio base: 0x%x", mmio->base); + FUSB_DEBUG(" oper base: 0x%x", mmio->oper_base); + FUSB_DEBUG(" doorbell base: 0x%x", mmio->doorbell_base); + FUSB_DEBUG(" runtime base: 0x%x", mmio->runtime_base); + FUSB_DEBUG(" port base: 0x%x", mmio->port_base); + + return FUSB_SUCCESS; +} + +static void FXhciParseExtCap(FXhciMMIO *mmio, const uintptr offset, const u32 cap_id) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + u32 reg_val; + u32 major_ver, minor_ver; + u32 psic; /* Protocol Speed ID (PSI) */ + + switch (cap_id) + { + case FXHCI_EXT_CAP_ID_USB_LEGACY_SUPPORT: + reg_val = FXhciReadExtCap32(mmio, offset + FXHCI_REG_EXT_CAP_USBLEGSUP_OFFSET); + FUSB_INFO(" BIOS owned %d OS owned %d", + FXHCI_USBLEGSUP_BIOS_OWNED_SEMAPHORE & reg_val, + FXHCI_USBLEGSUP_OS_OWNED_SEMAPHORE & reg_val); + + reg_val = FXhciReadExtCap32(mmio, offset + FXHCI_REG_EXT_CAP_USBLEGCTLSTS_OFFSET); + FUSB_INFO(" SMI ctrl/status 0x%x", reg_val); + break; + case FXHCI_EXT_CAP_ID_SUPPORT_PROTOCOL: + reg_val = FXhciReadExtCap32(mmio, offset + FXHCI_REG_EXT_CAP_USBSPCFDEF_OFFSET); + FUSB_INFO(" Name: %c%c%c%c", + *((char *)®_val), *((char *)®_val + 1), + *((char *)®_val + 2), *((char *)®_val + 3)); + + reg_val = FXhciReadExtCap32(mmio, offset + FXHCI_REG_EXT_CAP_USBSPCF_OFFSET); + major_ver = FXHCI_USBSPCF_MAJOR_REVERSION_GET(reg_val); + minor_ver = FXHCI_USBSPCF_MINOR_REVERSION_GET(reg_val); + FUSB_INFO(" Version: %d.%d", major_ver, minor_ver); + + reg_val = FXhciReadExtCap32(mmio, offset + FXHCI_REG_EXT_CAP_USBSPCFDEF2_OFFSET); + FUSB_INFO(" Compatible ports: [%d-%d]", + FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_OFF_GET(reg_val), + FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_OFF_GET(reg_val) + FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_CNT_GET(reg_val) - 1); + + if (FXHCI_MAJOR_REVERSION_USB2 == major_ver) + { + mmio->usb2_ports.port_beg = FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_OFF_GET(reg_val); + mmio->usb2_ports.port_end = FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_OFF_GET(reg_val) + FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_CNT_GET(reg_val) - 1; + + FUSB_INFO(" High-speed only: %d, Integrated hub: %d, Hardware LMP: %d", + FXHCI_USBSPCFDEF2_USB2_HIGH_SPEED_ONLY & reg_val, + FXHCI_USBSPCFDEF2_USB2_INTERGRATED_HUB & reg_val, + FXHCI_USBSPCFDEF2_USB2_HW_LMP_CAP & reg_val); + } + else if (FXHCI_MAJOR_REVERSION_USB3 == major_ver) + { + mmio->usb3_ports.port_beg = FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_OFF_GET(reg_val); + mmio->usb3_ports.port_end = FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_OFF_GET(reg_val) + FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_CNT_GET(reg_val) - 1; + } + + psic = FXHCI_USBSPCFDEF2_PROTOCOL_SPEED_ID_CNT_GET(reg_val); + FUSB_INFO(" PSIC: 0x%x", psic); + + if (0 != psic) + { + reg_val = FXhciReadExtCap32(mmio, offset + FXHCI_REG_PROTOCOL_SPEED_ID_OFFSET(psic)); + + FUSB_INFO(" Protocol speed-id: %d^%d", + FXHCI_PROTOCOL_SPEED_ID_VALUE_GET(reg_val), + FXHCI_PROTOCOL_SPEED_ID_EXPONENT_GET(reg_val)); + FUSB_INFO(" PSI type: %d, PSI full-duplex: %d, Mantissa: 0x%x", + FXHCI_PROTOCOL_SPEED_ID_PSI_TYPE_GET(reg_val), + (FXHCI_PROTOCOL_SPEED_ID_PSI_FULL_DUPLEX & reg_val == FXHCI_PROTOCOL_SPEED_ID_PSI_FULL_DUPLEX), + FXHCI_PROTOCOL_SPEED_ID_MANTISSA_GET(reg_val)); + } + else + { + if (FXHCI_MAJOR_REVERSION_USB3 == major_ver) + FUSB_INFO("For USB3, only the default SuperSpeed bit rate is supported !!!"); + else if (FXHCI_MAJOR_REVERSION_USB2 == major_ver) + FUSB_INFO("For USB2, default Full-speed, Low-speed and High-speed bit rate supported !!!"); + } + + break; + case FXHCI_EXT_CAP_ID_USB_DEBUG_CAPABILITY: + + break; + default: + FUSB_WARN("Unhandled extend capabilities %d", cap_id); + break; + } + + return; +} + +void FXhciListExtCap(FXhciMMIO *mmio) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + uintptr next_ext_cap_offset = 0; + uintptr ext_cap_offset = 0; + u32 cap_id = 0; + u32 reg_val; + + FUSB_INFO("Extended capabilities"); + do + { + reg_val = FXhciReadExtCap32(mmio, ext_cap_offset); + next_ext_cap_offset = (FXHCI_REG_EXT_CAP_NEXT_CAP_PTR_GET(reg_val) << 2); + cap_id = FXHCI_REG_EXT_CAP_CAP_ID_GET(reg_val); + FXhciParseExtCap(mmio, ext_cap_offset, cap_id); + + FUSB_INFO("==== Capability ID: %d, Next Capability Pointer: 0x%x", + cap_id, next_ext_cap_offset); + ext_cap_offset += next_ext_cap_offset; + } + while (0 != next_ext_cap_offset); + + return; +} + +FError FXhciWaitOper32(FXhciMMIO *mmio, u32 offset, u32 mask, u32 exp_val, u32 timeout_tick) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + FError ret = FUSB_ERR_WAIT_TIMEOUT; + u32 tick = 0U; + + do + { + if ((FXhciReadOper32(mmio, offset) & mask) == exp_val) + { + ret = FUSB_SUCCESS; + break; + } + fsleep_millisec(10); + } + while (tick++ < timeout_tick); + + if (FUSB_SUCCESS != ret) + { + FUSB_ERROR("wait status 0x%x timeout, current 0x%x, tick: %ld", exp_val, mask, tick); + } + + return ret; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_hw.h b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_hw.h new file mode 100644 index 0000000000..6c780e6a96 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_hw.h @@ -0,0 +1,589 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_hw.h + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:13:47 + * Description:  This files is for definition of XHCI hardware register interface + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_USB_FXHCI_HW_H +#define DRIVERS_USB_FXHCI_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fio.h" +#include "fassert.h" +#include "fkernel.h" + + +/************************** Constant Definitions *****************************/ +/** @name Register Map + * + * Register offsets from the base address of an SD device. + * @{ + */ +/***************** eXtensible Host Controller Capability Registers ***********************/ +#define FXHCI_REG_CAP_CAPLENGTH 0x00 /* specify the limits, restrictions and capabilities */ +#define FXHCI_REG_CAP_HCIVERSION 0x02 /* Interface Version Number */ +#define FXHCI_REG_CAP_HCSPARAMS1 0x04 /* Host Controller Structural Parameters 1 */ +#define FXHCI_REG_CAP_HCSPARAMS2 0x08 /* Host Controller Structural Parameters 2 */ +#define FXHCI_REG_CAP_HCSPARAMS3 0x0C /* Host Controller Structural Parameters 3 */ +#define FXHCI_REG_CAP_HCCPARAMS 0x10 /* Capability Parameters 1 */ +#define FXHCI_REG_CAP_DBOFF 0x14 /* Doorbell Offset Register */ +#define FXHCI_REG_CAP_RTSOFF 0x18 /* Runtime Register Space Offset Register */ + +/***************** Host Controller Operational Registers ***********************/ +#define FXHCI_REG_OP_USBCMD 0x00 /* USB Command Register */ +#define FXHCI_REG_OP_USBSTS 0x04 /* USB Status Register */ +#define FXHCI_REG_OP_PAGESIZE 0x08 /* Page Size Register */ +#define FXHCI_REG_OP_DNCTRL 0x14 /* Device Notification Control Register */ +#define FXHCI_REG_OP_CRCR 0x18 /* Command Ring Control Register */ +#define FXHCI_REG_OP_DCBAAP 0x30 /* Device Context Base Address Array Pointer Register */ +#define FXHCI_REG_OP_CONFIG 0x38 /* Configure Register */ + +/* Port Status and Ctrl Register : OP Base + (400h + (10h * (n–1))) 'n' is port num */ +#define FXHCI_REG_OP_PORTS_BASE 0x400 /* Port Status and Control Register Base */ +#define FXHCI_REG_OP_PORTS_SIZE 0x10 /* Size of one Port SC Register */ +#define FXHCI_REG_OP_PORTS_PORTSC 0x00 /* Port Status and Control Register */ +#define FXHCI_REG_OP_PORTS_PORTPMSC 0x04 /* USB3 Port Power Management Status and Control Register */ +#define FXHCI_REG_OP_PORTS_PORTLI 0x08 /* Port Link Info Register */ + +/***************** Host Controller Runtime Registers ***********************/ +#define FXHCI_REG_RT_MFINDEX 0x00 /* Microframe Index */ +#define FXHCI_REG_RT_IR0 0x20 /* Interrupter Register Set 0 */ +#define FXHCI_REG_RT_IR1023 0x8000 /* Interrupter Register Set 1023 */ + +/* Interrupter Register Set : RT Base + 020h + (32 * Interrupter) */ +#define FXHCI_REG_RT_IR_SIZE 0x20 /* Size of one IR Register */ +#define FXHCI_REG_RT_IR_IMAN 0x00 /* Interrupter Management Register */ +#define FXHCI_REG_RT_IR_IMOD 0x04 /* Interrupter Moderation Register */ +#define FXHCI_REG_RT_IR_ERSTSZ 0x08 /* Event Ring Segment Table Size Register */ +#define FXHCI_REG_RT_IR_ERSTBA 0x10 /* Event Ring Segment Table Base Address Register */ +#define FXHCI_REG_RT_IR_ERDP 0x18 /* Event Ring Dequeue Pointer Register */ + +/***************** Doorbell Register ***********************/ +#define FXHCI_REG_DB_SIZE 4 /* Doorbell registers are 32 bits in length */ + +/***************** eXtensible Host Controller Capability Registers ***********************/ + +/** @name FXHCI_REG_CAP_HCSPARAMS1 Register + */ +#define FXHCI_REG_CAP_HCSPARAMS1_MAX_SLOTS_GET(x) FUSB_REG32_GET_BITS(x, 7, 0) /* Number of Device Slots (MaxSlots) */ +#define FXHCI_REG_CAP_HCSPARAMS1_MAX_INTRS_GET(x) FUSB_REG32_GET_BITS(x, 18, 8) /* Number of Interrupters (MaxIntrs) */ +#define FXHCI_REG_CAP_HCSPARAMS1_MAX_PORTS_GET(x) FUSB_REG32_GET_BITS(x, 31, 24) /* Number of Ports (MaxPorts) */ + +/** @name FXHCI_REG_CAP_HCSPARAMS2 Register + */ +#define FXHCI_REG_CAP_HCSPARAMS2_IST_GET(x) FUSB_REG32_GET_BITS(x, 3, 0) /* Isochronous Scheduling Threshold (IST) */ +#define FXHCI_REG_CAP_HCSPARAMS2_ERST_MAX_GET(x) FUSB_REG32_GET_BITS(x, 7, 4) /* Event Ring Segment Table Max (ERST Max) */ +#define FXHCI_REG_CAP_HCSPARAMS2_SPR (1 << 26) /* Scratchpad Restore (SPR) */ +#define FXHCI_REG_CAP_HCSPARAMS2_MAX_SCRATCHPAD_BUFS_GET(x) FUSB_REG32_GET_BITS(x, 31, 27) /* Max Scratchpad Buffers (Max Scratchpad Bufs) */ + +/** @name FXHCI_REG_CAP_HCSPARAMS3 Register + */ +#define FXHCI_REG_CAP_HCSPARAMS3_U1_DEV_EXIT_LATENCY_GET(x) FUSB_REG32_GET_BITS(x, 7, 0) /* U1 Device Exit Latency */ +#define FXHCI_REG_CAP_HCSPARAMS3_U2_DEV_EXIT_LATENCY_GET(x) FUSB_REG32_GET_BITS(x, 31, 16) /* U2 Device Exit Latency */ + +/** @name FXHCI_REG_CAP_HCCPARAMS Register + */ +#define FXHCI_REG_CAP_HCCPARAMS_AC64 (1 << 0) /* 64-bit Addressing Capabilitya 1: 64-bit */ +#define FXHCI_REG_CAP_HCCPARAMS_BNC (1 << 1) /* BW Negotiation Capability (BNC) 1: support */ +#define FXHCI_REG_CAP_HCCPARAMS_CSZ (1 << 2) /* Context Size (CSZ) 1: 64 byte context data */ +#define FXHCI_REG_CAP_HCCPARAMS_PPC (1 << 3) /* Port Power Control (PPC) 1: support */ +#define FXHCI_REG_CAP_HCCPARAMS_PIND (1 << 4) /* Port Indicators (PIND) 1: support */ +#define FXHCI_REG_CAP_HCCPARAMS_LHRC (1 << 5) /* Light HC Reset Capability (LHRC) 1: support */ +#define FXHCI_REG_CAP_HCCPARAMS_LTC (1 << 6) /* Latency Tolerance Messaging Capability (LTC) */ +#define FXHCI_REG_CAP_HCCPARAMS_NSS (1 << 7) /* No Secondary SID Support (NSS) */ +#define FXHCI_REG_CAP_HCCPARAMS_MAX_PSA_SIZE_GET(x) FUSB_REG32_GET_BITS(x, 15, 12) /* Maximum Primary Stream Array Size (MaxPSASize) */ +#define FXHCI_REG_CAP_HCCPARAMS_XECP_GET(x) FUSB_REG32_GET_BITS(x, 31, 16) /* xHCI Extended Capabilities Pointer (xECP) */ + +/** @name FXHCI_REG_CAP_DBOFF Register + */ +#define FXHCI_REG_CAP_DBOFF_GET(x) ((x) & GENMASK(31, 2)) /* 32-byte offset of the Doorbell Array base address from the Base */ + +/** @name FXHCI_REG_CAP_RTSOFF Register + */ +#define FXHCI_REG_CAP_RTSOFF_GET(x) ((x) & GENMASK(31, 5)) /* 32-byte offset of the xHCI Runtime Registers */ + +/***************** Host Controller Operational Registers ***********************/ + +/** @name FXHCI_REG_OP_USBCMD Register + */ +#define FXHCI_REG_OP_USBCMD_RUN_STOP (1 << 0) /* Run/Stop (R/S) 1: RUN, 0: STOP - RW */ +#define FXHCI_REG_OP_USBCMD_HCRST (1 << 1) /* Host Controller Reset (HCRST) 1: RESET - RW */ +#define FXHCI_REG_OP_USBCMD_INTE (1 << 2) /* Interrupter Enable (INTE) 1: enabled - RW */ +#define FXHCI_REG_OP_USBCMD_HSEE (1 << 3) /* Host System Error Enable (HSEE) - RW */ +#define FXHCI_REG_OP_USBCMD_LHCRST (1 << 7) /* Light Host Controller Reset (LHCRST) - RW */ +#define FXHCI_REG_OP_USBCMD_CSS (1 << 8) /* Controller Save State (CSS) - RW */ +#define FXHCI_REG_OP_USBCMD_CRS (1 << 9) /* Controller Restore State (CRS) - RW */ +#define FXHCI_REG_OP_USBCMD_EWE (1 << 10) /* Enable Wrap Event (EWE) - RW */ +#define FXHCI_REG_OP_USBCMD_EU3S (1 << 11) /* Enable U3 MFINDEX Stop (EU3S) - RW */ + +/** @name FXHCI_REG_OP_USBSTS Register + */ +#define FXHCI_REG_OP_USBSTS_HCH (1 << 0) /* 1: Stopped executing */ +#define FXHCI_REG_OP_USBSTS_HSE (1 << 2) /* 1: Serious error detected */ +#define FXHCI_REG_OP_USBSTS_EINT (1 << 3) /* 1: Interrupt Pending (IP) */ +#define FXHCI_REG_OP_USBSTS_PCD (1 << 4) /* 1: Port Change Detect */ +#define FXHCI_REG_OP_USBSTS_SSS (1 << 8) /* remain 1 while the xHC saves its internal state */ +#define FXHCI_REG_OP_USBSTS_RSS (1 << 9) /* remain 1 while the xHC restores its internal state */ +#define FXHCI_REG_OP_USBSTS_SRE (1 << 10) /* if error occurs during a Save or Restore operation this bit shall be set to ‘1’. */ +#define FXHCI_REG_OP_USBSTS_CNR (1 << 11) /* 1: Controller Not Ready */ +#define FXHCI_REG_OP_USBSTS_HCE (1 << 12) /* 1: Internal xHC error condition */ +#define FXHCI_REG_OP_USBSTS_PRSRV_MASK ((1 << 1) | 0xffffe000) /* Rsvd bits */ + +/** @name FXHCI_REG_OP_PAGESIZE Register + */ +/* This xHC supports a page size of 2^(n+12) if bit n is Set */ +#define FXHCI_REG_OP_PAGESIZE_4K (1 << 0) /* if bit 0 is Set, the xHC supports 4k byte page sizes */ + +/** @name FXHCI_REG_OP_CRCR Register + */ +#define FXHCI_REG_OP_CRCR_RCS (1 << 0) /* Ring Cycle State, value of the xHC Consumer Cycle State (CCS) flag */ +#define FXHCI_REG_OP_CRCR_CS (1 << 1) /* Command Stop, 1 */ +#define FXHCI_REG_OP_CRCR_CA (1 << 2) /* Command Abort, 1 */ +#define FXHCI_REG_OP_CRCR_CRR (1 << 3) /* Command Ring Running */ +#define FXHCI_REG_OP_CRCR_CR_PTR_MASK GENMASK_ULL(63, 6) /* Command Ring Pointer, Dequeue Ptr of Command Ring */ + +/** @name FXHCI_REG_OP_DCBAAP Register + */ +#define FXHCI_REG_OP_DCBAAP_MASK GENMASK_ULL(63, 6) /* bit[31:6] Ptr of DCBAA */ + +/** @name FXHCI_REG_OP_CONFIG Register + */ +#define FXHCI_REG_OP_CONFIG_MAX_SLOTS_EN_MASK GENMASK(7, 0) /* Max Device Slots Enabled (MaxSlotsEn) – RW */ +#define FXHCI_REG_OP_CONFIG_MAX_SLOTS_EN_SET(x) FUSB_REG32_SET_BITS(x, 7, 0) /* bit[7:0] Max Device Slots Enabled */ +#define FXHCI_REG_OP_CONFIG_MAX_SLOTS_EN_GET(x) FUSB_REG32_GET_BITS(x, 7, 0) + +/** @name FXHCI_REG_OP_PORTS_PORTSC Register + */ +#define FXHCI_REG_OP_PORTS_PORTSC_CCS (1 << 0) /* Current Connect Status (CCS) – ROS */ +#define FXHCI_REG_OP_PORTS_PORTSC_PED (1 << 1) /* Port Enabled/Disabled (PED) – RW1CS */ +#define FXHCI_REG_OP_PORTS_PORTSC_OCA (1 << 3) /* Over-current Active (OCA) – RO */ +#define FXHCI_REG_OP_PORTS_PORTSC_PR (1 << 4) /* Port Reset (PR) – RW1S */ +#define FXHCI_REG_OP_PORTS_PORTSC_PLS_GET(x) FUSB_REG32_GET_BITS(x, 8, 5) /* Port Link State (PLS) – RWS */ +#define FXHCI_REG_OP_PORTS_PORTSC_PLS_SET(x) FUSB_REG32_SET_BITS(x, 8, 5) +#define FXHCI_REG_OP_PORTS_PORTSC_PLS_MASK GENMASK(8, 5) +#define FXHCI_REG_OP_PORTS_PORTSC_PLS(x) (x << 5) +/* Read value of Port Link State (PLS) */ +/* refer to FXHCI doc page-408 for details (Port Link State) */ +enum +{ + FXHCI_LINK_STATE_U0 = 0, /* U0 State */ + FXHCI_LINK_STATE_U1 = 1, /* U1 State */ + FXHCI_LINK_STATE_U2 = 2, /* U2 State */ + FXHCI_LINK_STATE_U3 = 3, /* U3 State (Device Suspended) */ + FXHCI_LINK_STATE_DISABLED = 4, /* Disabled State */ + FXHCI_LINK_STATE_RX_DETECT = 5, /* RxDetect State (Disconnected) */ + FXHCI_LINK_STATE_INACTIVE = 6, /* Inactive State */ + FXHCI_LINK_STATE_POLLING = 7, /* Polling State */ + FXHCI_LINK_STATE_RECOVERY = 8, /* Recovery State */ + FXHCI_LINK_STATE_HOT_RESET = 9, /* Hot Reset State */ + FXHCI_LINK_STATE_COMPLIANCE_MODE = 10, /* Compliance Mode State */ + FXHCI_LINK_STATE_TEST_MODE = 11, /* Test Mode State */ + FXHCI_LINK_STATE_RESUME = 15, /* Resume State */ + + FXHCI_LINK_STATE_MAX +}; + +#define FXHCI_REG_OP_PORTS_PORTSC_PLS_SET(x) FUSB_REG32_SET_BITS(x, 8, 5) + +#define FXHCI_REG_OP_PORTS_PORTSC_PP (1 << 9) /* Port Power (PP) – RWS */ +#define FXHCI_REG_OP_PORTS_PORTSC_PORT_SPEED_GET(x) FUSB_REG32_GET_BITS(x, 13, 10) /* Port Speed (Port Speed) – ROS */ +/* Protocol Speed ID (PSI) 1~15 */ +enum +{ + FXHCI_PORT_SPEED_UNDEFINED = 0, + FXHCI_PORT_SPEED_1 = 1, + FXHCI_PORT_SPEED_15 = 15, +}; + + +#define FXHCI_REG_OP_PORTS_PORTSC_PIC_SET(x) FUSB_REG32_SET_BITS(x, 15, 14) +#define FXHCI_REG_OP_PORTS_PORTSC_PIC_MASK GENMASK(15, 14) +enum +{ + FXHCI_PORT_INDICATOR_OFF = 0, + FXHCI_PORT_INDICATOR_AMBER = 1, + FXHCI_PORT_INDICATOR_GREEN = 2, + FXHCI_PORT_INDICATOR_UNDEFINED = 3 +}; + +#define FXHCI_REG_OP_PORTS_PORTSC_LWS (1 << 16) /* Port Link State Write Strobe (LWS) */ +#define FXHCI_REG_OP_PORTS_PORTSC_CSC (1 << 17) /* Connect Status Change (CSC) */ +#define FXHCI_REG_OP_PORTS_PORTSC_PEC (1 << 18) /* Port Enabled/Disabled Change (PEC) 1: clear PED */ +#define FXHCI_REG_OP_PORTS_PORTSC_WRC (1 << 19) /* Warm Port Reset Change 1: Warm Reset complete */ +#define FXHCI_REG_OP_PORTS_PORTSC_OCC (1 << 20) /* Over-current Change 1: Over-current Active */ +#define FXHCI_REG_OP_PORTS_PORTSC_PRC (1 << 21) /* Port Reset Change 1: Transition of Port Reset */ +#define FXHCI_REG_OP_PORTS_PORTSC_PLC (1 << 22) /* Port Link State Change 1: PLS transition */ +#define FXHCI_REG_OP_PORTS_PORTSC_CEC (1 << 23) /* Port Config Error Change 1: Port Config Error detected */ +#define FXHCI_REG_OP_PORTS_PORTSC_CAS (1 << 24) /* Cold Attach Status 1: Far-end Receiver Terminations were detected */ +#define FXHCI_REG_OP_PORTS_PORTSC_WCE (1 << 25) /* Wake on Connect Enable 1: enable port to be sensitive to device connects */ +#define FXHCI_REG_OP_PORTS_PORTSC_WDE (1 << 26) /* Wake on Disconnect Enable 1: enable port to be sensitive to device disconnects */ +#define FXHCI_REG_OP_PORTS_PORTSC_WOE (1 << 27) /* Wake on Over-current Enable 1: enable port to be sensitive to over-current conditions */ +#define FXHCI_REG_OP_PORTS_PORTSC_DR (1 << 30) /* Device Removable, 0: Device is removable. 1: Device is non-removable */ +#define FXHCI_REG_OP_PORTS_PORTSC_WPR (1 << 31) /* Warm Port Reset 1: follow Warm Reset sequence */ +#define FXHCI_REG_OP_PORTS_PORTSC_RW_MASK (FXHCI_REG_OP_PORTS_PORTSC_PR | FXHCI_REG_OP_PORTS_PORTSC_PLS_MASK | FXHCI_REG_OP_PORTS_PORTSC_PP \ + | FXHCI_REG_OP_PORTS_PORTSC_PIC_MASK | FXHCI_REG_OP_PORTS_PORTSC_LWS | FXHCI_REG_OP_PORTS_PORTSC_WCE \ + | FXHCI_REG_OP_PORTS_PORTSC_WDE | FXHCI_REG_OP_PORTS_PORTSC_WOE) + +/***************** Host Controller Runtime Registers ***********************/ + +/** @name FXHCI_REG_RT_IR_IMAN Register + */ +#define FXHCI_REG_RT_IR_IMAN_IP (1 << 0) /* Interrupt Pending, 1: an interrupt is pending for this Interrupter */ +#define FXHCI_REG_RT_IR_IMAN_IE (1 << 1) /* Interrupt Enable, 1: capable of generating an interrupt. */ + +/** @name FXHCI_REG_RT_IR_IMOD Register + */ +#define FXHCI_REG_RT_IR_IMOD_IMODI_MASK GENMASK(15, 0) /* bit[15:0] Interrupt Moderation Interval default 4000 ==> 1ms */ +#define FXHCI_REG_RT_IR_IMOD_IMODC_MASK GENMASK(31, 16) /* bit[31:16] Interrupt Moderation Counter(Down counter) */ + +/** @name FXHCI_REG_RT_IR_ERSTSZ Register + */ +#define FXHCI_REG_RT_IR_ERSTSZ_MASK GENMASK(15, 0) /* bit[15:0] the number of valid Event Ring Segment Table entries */ + +/** @name FXHCI_REG_RT_IR_ERSTBA Register + */ +#define FXHCI_REG_RT_IR_ERSTBA_MASK GENMASK_ULL(63, 6) /* Event Ring Segment Table Base Address */ + +/** @name FXHCI_REG_RT_IR_ERDP Register + */ +#define FXHCI_REG_RT_IR_ERDP_DESI_MASK GENMASK_ULL(2, 0) /* bit[2:0] Dequeue ERST Segment Index */ +#define FXHCI_REG_RT_IR_ERDP_EHB (1 << 3) /* Event Handler Busy */ +#define FXHCI_REG_RT_IR_ERDP_MASK GENMASK_ULL(63, 4) /* Event Ring Dequeue Pointer */ + +/***************** Doorbell Register ***********************/ +#define FXHCI_REG_DB_TARGET_HC_COMMAND 0 /* Host Controller Doorbell (0) Command Doorbell */ +#define FXHCI_REG_DB_TARGET_EP0 1 /* Device Context Doorbells Control EP 0 Enqueue Pointer Update */ +#define FXHCI_REG_DB_TARGET_EP1_OUT 2 /* EP 1 OUT Enqueue Pointer Update */ +#define FXHCI_REG_DB_TARGET_EP1_IN 3 /* EP 1 IN Enqueue Pointer Update */ +#define FXHCI_REG_DB_TARGET_EP15_OUT 30 /* EP 15 OUT Enqueue Pointer Update */ +#define FXHCI_REG_DB_TARGET_EP15_IN 31 /* EP 15 IN Enqueue Pointer Update */ + +/***************** xHCI Extended Capabilities Registers ***********************/ +#define FXHCI_REG_EXT_CAP_CAP_ID_GET(x) FUSB_REG32_GET_BITS(x, 7, 0) +/* refer to 'Table 138: xHCI Extended Capability Codes' for more details */ +enum +{ + FXHCI_EXT_CAP_ID_USB_LEGACY_SUPPORT = 1, + FXHCI_EXT_CAP_ID_SUPPORT_PROTOCOL = 2, + FXHCI_EXT_CAP_ID_EXTEND_POWER_MANAGEMENT = 3, + FXHCI_EXT_CAP_ID_IO_VIRTUALIZATION = 4, + FXHCI_EXT_CAP_ID_MESSAGE_INTERRUPT = 5, + FXHCI_EXT_CAP_ID_LOCAL_MEMORY = 6, + FXHCI_EXT_CAP_ID_USB_DEBUG_CAPABILITY = 10, + FXHCI_EXT_CAP_ID_EXT_MESSAGE_INTERRUPT = 17, + + FXHCI_EXT_CAP_ID_VENDOR_DEFINED_MIN = 192, + FXHCI_EXT_CAP_ID_VENDOR_DEFINED_MAX = 255 +}; + +#define FXHCI_REG_EXT_CAP_NEXT_CAP_PTR_GET(x) FUSB_REG32_GET_BITS(x, 15, 8) +#define FXHCI_REG_EXT_CAP_CAP_SPEC_GET(x) FUSB_REG32_GET_BITS(x, 31, 16) +/* Ext capabilities specific definitions */ +/* USB Legacy Support Capability */ +#define FXHCI_REG_EXT_CAP_USBLEGSUP_OFFSET 0x0 /* used by pre-OS software (BIOS) and the operating system to coordinate ownership of the xHC. */ +#define FXHCI_USBLEGSUP_BIOS_OWNED_SEMAPHORE (1 << 16) /* RW, The BIOS sets this bit to establish ownership of the xHC */ +#define FXHCI_USBLEGSUP_OS_OWNED_SEMAPHORE (1 << 24) /* RW, System software sets this bit to request ownership of the xHC */ + +#define FXHCI_REG_EXT_CAP_USBLEGCTLSTS_OFFSET 0x4 /* uses this register to enable System Management Interrupts (SMIs) for every xHCI/USB event it needs to track */ +#define FXHCI_USBLEGCTLSTS_USB_SMI_EN (1 << 0) /* RW, enable interrupts to trach event */ +#define FXHCI_USBLEGCTLSTS_SMI_HC_ERR_EN (1 << 4) /* RW */ +#define FXHCI_USBLEGCTLSTS_SMI_OS_OWE_EN (1 << 13) /* RW */ +#define FXHCI_USBLEGCTLSTS_SMI_PCI_CMD_EN (1 << 14) /* RW */ +#define FXHCI_USBLEGCTLSTS_SMI_BAR_EN (1 << 15) /* RW */ +#define FXHCI_USBLEGCTLSTS_SMI_EVT_INTERRUPT (1 << 16) /* RO */ +#define FXHCI_USBLEGCTLSTS_SMI_HC_SYS_ERR (1 << 20) /* RO */ +#define FXHCI_USBLEGCTLSTS_SMI_OS_OWN_CHG (1 << 29) /* RW1C */ +#define FXHCI_USBLEGCTLSTS_SMI_PCI_CMD (1 << 30) /* RW1C */ +#define FXHCI_USBLEGCTLSTS_SMI_BAR (1 << 31) /* RW1C */ + +/* xHCI Supported Protocol Capability */ +#define FXHCI_REG_EXT_CAP_USBSPCF_OFFSET 0x0 +#define FXHCI_USBSPCF_MINOR_REVERSION_GET(x) FUSB_REG32_GET_BITS(x, 23, 16) +#define FXHCI_USBSPCF_MAJOR_REVERSION_GET(x) FUSB_REG32_GET_BITS(x, 31, 24) +enum +{ + FXHCI_MAJOR_REVERSION_USB2 = 2, + FXHCI_MAJOR_REVERSION_USB3 = 3 +}; + +#define FXHCI_REG_EXT_CAP_USBSPCFDEF_OFFSET 0x4 +#define FXHCI_USBSPCFDEF_NAME_STRING_GET(x) FUSB_REG32_GET_BITS(x, 31, 0) /* four ASCII characters may be defined */ +#define FXHCI_USBSPCFDEF_NAME_STRING_USB 0x20425355 /* ASCII = "USB" */ + +#define FXHCI_REG_EXT_CAP_USBSPCFDEF2_OFFSET 0x8 +#define FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_OFF_GET(x) FUSB_REG32_GET_BITS(x, 7, 0) +#define FXHCI_USBSPCFDEF2_COMPATIBLE_PORT_CNT_GET(x) FUSB_REG32_GET_BITS(x, 15, 8) +#define FXHCI_USBSPCFDEF2_PROTOCOL_DEFINED_GET(x) FUSB_REG32_GET_BITS(x, 27, 16) +/* USB3 - No Protocol Defined fields */ +/* USB2 */ +#define FXHCI_USBSPCFDEF2_USB2_HIGH_SPEED_ONLY (1 << 17) /* High-speed Only (HSO) - RO */ +#define FXHCI_USBSPCFDEF2_USB2_INTERGRATED_HUB (1 << 18) /* Integrated Hub Implemented (IHI) - RO */ +#define FXHCI_USBSPCFDEF2_USB2_HW_LMP_CAP (1 << 19) /* Hardware LMP Capability (HLC) - RO */ + +#define FXHCI_USBSPCFDEF2_PROTOCOL_SPEED_ID_CNT_GET(x) FUSB_REG32_GET_BITS(x, 31, 28) + +/* Protocol Speed ID (PSI) */ +#define FXHCI_REG_PROTOCOL_SPEED_ID_OFFSET(psic) (0xc + ((psic) * sizeof(u32))) +#define FXHCI_PROTOCOL_SPEED_ID_VALUE_GET(x) FUSB_REG32_GET_BITS(x, 3, 0) /* Protocol Speed ID Value (PSIV) */ +#define FXHCI_PROTOCOL_SPEED_ID_EXPONENT_GET(x) FUSB_REG32_GET_BITS(x, 5, 4) /* Protocol Speed ID Exponent (PSIE) */ +#define FXHCI_PROTOCOL_SPEED_ID_PSI_TYPE_GET(x) FUSB_REG32_GET_BITS(x, 7, 6) /* PSI Type (PLT) */ +enum +{ + FXHCI_PROTOCOL_SPEED_ID_PSI_SYMMETRIC = 0, + FXHCI_PROTOCOL_SPEED_ID_PSI_ASYMMETRIC_RX = 2, + FXHCI_PROTOCOL_SPEED_ID_PSI_ASYMMETRIC_TX = 3 +}; +#define FXHCI_PROTOCOL_SPEED_ID_PSI_FULL_DUPLEX (1 << 8) +#define FXHCI_PROTOCOL_SPEED_ID_MANTISSA_GET(x) FUSB_REG32_GET_BITS(x, 31, 16) /* Protocol Speed ID Mantissa (PSIM) */ + +/**************************** Type Definitions *******************************/ + +/* Device Context Base Address Array */ +#define FXHCI_SCRATCHPAD_BUF_ARRAY_BASE_ADDR_MASK GENMASK_ULL(63, 6) /* Array Element 0 Field Bit */ +#define FXHCI_DEVICE_CONTEXT_BASE_ADDR_MASK GENMASK_ULL(63, 6) /* Array Element 1-n Field Bit */ + +/* Slot index */ +#define FXHCI_REG_DB_HOST_CONTROLLER 0 +#define FXHCI_REG_DB_DEVICE_CONTEXT1 1 +#define FXHCI_REG_DB_DEVICE_CONTEXT255 255 + +typedef struct +{ + u8 port_beg; + u8 port_end; +} FXhciPortRange; + +typedef enum +{ + FXHCI_USB2_COMPATIBLE_PORT, + FXHCI_USB3_COMPATIBLE_PORT, + + FXHCI_NONE_COMPATIBLE_PORT +} FXhciPortCompatible; + +typedef struct +{ + uintptr base; /* Capability registers offset */ + uintptr oper_base; /* Operational registers offset */ + uintptr doorbell_base; /* Doorbell registers offset */ + uintptr runtime_base; /* Runtime registers offset */ + uintptr port_base; /* Port register set offset */ + uintptr xecp_base; /* xHCI Extended Capabilities register offset */ + u32 hcx_params[4]; /* Capability cache */ + FXhciPortRange usb2_ports; + FXhciPortRange usb3_ports; +} FXhciMMIO; + + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +static inline FXhciPortCompatible FUsb3CheckPortCompatible(FXhciMMIO *mmio, u8 port_id) +{ + FASSERT(mmio); + if ((port_id >= mmio->usb3_ports.port_beg) && (port_id <= mmio->usb3_ports.port_end)) + { + return FXHCI_USB3_COMPATIBLE_PORT; + } + else if ((port_id >= mmio->usb2_ports.port_beg) && (port_id <= mmio->usb2_ports.port_end)) + { + return FXHCI_USB2_COMPATIBLE_PORT; + } + + FASSERT(0); /* must not reach there */ + return FXHCI_NONE_COMPATIBLE_PORT; +} + +static inline u32 FXhciReadCap(const FXhciMMIO *mmio) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + return FtIn32(mmio->base + FXHCI_REG_CAP_CAPLENGTH); +} + +static inline u8 FXhciReadCaplen(const FXhciMMIO *mmio) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + u32 reg_val = FXhciReadCap(mmio); + + /* get lower 8-bits */ + return (u8)(reg_val & 0xff); +} + +static inline u16 FXhciReadHcVersion(const FXhciMMIO *mmio) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + u32 reg_val = FXhciReadCap(mmio); + + /* get upper 16 bits */ + return (u16)((reg_val >> 16) & 0xffff); +} + +static inline u32 FXhciReadCap32(const FXhciMMIO *mmio, u32 offset) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + offset -= FXHCI_REG_CAP_HCSPARAMS1; + offset /= 4; + + FASSERT(offset < 4); + return mmio->hcx_params[offset]; /* read caps from cache */ +} + +static inline u32 FXhciReadOper32(const FXhciMMIO *mmio, u32 offset) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + return FtIn32(mmio->oper_base + offset); +} + +static inline u64 FXhciReadOper64(const FXhciMMIO *mmio, u32 offset) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + uintptr addr = mmio->oper_base + offset; + + u64 val = FtIn32(addr); + val |= ((u64)FtIn32(addr + 4)) << 32; + + return val; +} + +static inline void FXhciWriteOper32(const FXhciMMIO *mmio, u32 offset, u32 val) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + FtOut32(mmio->oper_base + offset, val); +} + +static inline void FXhciWriteOper64(const FXhciMMIO *mmio, u32 offset, u64 val) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + FXhciWriteOper32(mmio, offset, LOWER_32_BITS(val)); + FXhciWriteOper32(mmio, offset + 4, UPPER_32_BITS(val)); +} + +static inline u32 FXhciReadPort32(const FXhciMMIO *mmio, u32 port, u32 offset) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + /* Operational Base + (400h + (10h * (n–1))) */ + return FtIn32(mmio->port_base + port * FXHCI_REG_OP_PORTS_SIZE + offset); +} + +static inline void FXhciWritePort32(const FXhciMMIO *mmio, u32 port, u32 offset, u32 val) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + FtOut32(mmio->port_base + port * FXHCI_REG_OP_PORTS_SIZE + offset, val); +} + +static inline u32 FXhciReadRt32(const FXhciMMIO *mmio, u32 interrupt, u32 offset) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + /* Runtime Base + 020h + (32 * Interrupter) */ + return FtIn32(mmio->runtime_base + FXHCI_REG_RT_IR0 + interrupt * FXHCI_REG_RT_IR_SIZE + offset); +} + +static inline u64 FXhciReadRt64(const FXhciMMIO *mmio, u32 interrupt, u32 offset) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + uintptr addr = mmio->runtime_base + FXHCI_REG_RT_IR0 + interrupt * FXHCI_REG_RT_IR_SIZE + offset; + u64 reg_val = FtIn32(addr); + reg_val |= (u64)FtIn32(addr + 4) << 32; + + return reg_val; +} + +static inline void FXhciWriteRt32(const FXhciMMIO *mmio, u32 interrupt, u32 offset, u32 val) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + FtOut32(mmio->runtime_base + FXHCI_REG_RT_IR0 + interrupt * FXHCI_REG_RT_IR_SIZE + offset, val); +} + +static inline void FXhciWriteRt64(const FXhciMMIO *mmio, u32 interrupt, u32 offset, u64 val) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + FXhciWriteRt32(mmio, interrupt, offset, (u32)val); + FXhciWriteRt32(mmio, interrupt, offset + 4, (u32)(val >> 32)); +} + +static inline u32 FXhciReadExtCap32(const FXhciMMIO *mmio, u32 offset) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + FASSERT(mmio->xecp_base != 0); + + return FtIn32(mmio->xecp_base + offset); +} + +static inline void FXhciWriteDb32(const FXhciMMIO *mmio, u32 slot, u32 val) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + FtOut32(mmio->doorbell_base + slot * FXHCI_REG_DB_SIZE, val); +} + +static inline int FXhciGetCtxSize(const FXhciMMIO *mmio) +{ + FASSERT(mmio); + FASSERT(mmio->base != 0); + + u32 reg_val = FXhciReadCap32(mmio, FXHCI_REG_CAP_HCCPARAMS); + return ((reg_val & FXHCI_REG_CAP_HCCPARAMS_CSZ) == FXHCI_REG_CAP_HCCPARAMS_CSZ) ? 64 : 32; +} + +/************************** Function Prototypes ******************************/ +FError FXhciSetupMMIO(FXhciMMIO *mmio, uintptr base_addr); +void FXhciListExtCap(FXhciMMIO *mmio); +FError FXhciWaitOper32(FXhciMMIO *mmio, u32 offset, u32 mask, u32 exp_val, u32 timeout_tick); + +#ifdef __cplusplus +} +#endif + + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_private.h b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_private.h new file mode 100644 index 0000000000..818b5f2520 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_private.h @@ -0,0 +1,475 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_private.h + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:16:44 + * Description:  This files is for definition of XHCI internal function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#ifndef DRIVERS_USB_FXHCI_PRIVATE_H +#define DRIVERS_USB_FXHCI_PRIVATE_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/***************************** Include Files *********************************/ +#include "fusb_private.h" +#include "fxhci_hw.h" +#include "fxhci.h" + +/************************** Constant Definitions *****************************/ +typedef enum +{ + FXHCI_TRB_NORMAL = 1, + FXHCI_TRB_SETUP_STAGE = 2, + FXHCI_TRB_DATA_STAGE = 3, + FXHCI_TRB_STATUS_STAGE = 4, + FXHCI_TRB_LINK = 6, + FXHCI_TRB_EVENT_DATA = 7, + FXHCI_TRB_CMD_ENABLE_SLOT = 9, + FXHCI_TRB_CMD_DISABLE_SLOT = 10, + FXHCI_TRB_CMD_ADDRESS_DEV = 11, + FXHCI_TRB_CMD_CONFIGURE_EP = 12, + FXHCI_TRB_CMD_EVAL_CTX = 13, + FXHCI_TRB_CMD_RESET_EP = 14, + FXHCI_TRB_CMD_STOP_EP = 15, + FXHCI_TRB_CMD_SET_TR_DQ = 16, + FXHCI_TRB_CMD_NOOP = 23, + FXHCI_TRB_EV_TRANSFER = 32, + FXHCI_TRB_EV_CMD_CMPL = 33, + FXHCI_TRB_EV_PORTSC = 34, + FXHCI_TRB_EV_HOST = 37, +} FXhciTrbType; + +enum +{ + FXHCI_TRB_TRT_NO_DATA = 0, + FXHCI_TRB_TRT_OUT_DATA = 2, + FXHCI_TRB_TRT_IN_DATA = 3 +}; + +enum +{ + FXHCI_TRB_DIR_OUT = 0, + FXHCI_TRB_DIR_IN = 1 +}; + +#define FXHCI_TRB_MAX_TD_SIZE 0x1F /* bits 21:17 of TD Size in TRB */ +#define FXHCI_DMA_SIZE (64 * 1024) +#define FXHCI_TIMEOUT 1000000 + +enum +{ + FXHCI_EP_ISOC_OUT = 1, + FXHCI_EP_BULK_OUT = 2, + FXHCI_EP_INTR_OUT = 3, + FXHCI_EP_CONTROL = 4, + FXHCI_EP_ISOC_IN = 5, + FXHCI_EP_BULK_IN = 6, + FXHCI_EP_INTR_IN = 7 +}; + +/**************************** Type Definitions *******************************/ +typedef volatile struct +{ + u32 ptr_low; + u32 ptr_high; + u32 status; + u32 control; +} FXhciTrb; + +typedef struct +{ + FXhciTrb *ring; + FXhciTrb *cur; + FXhciTrb *last; + u8 ccs; + u8 adv; +} FXhciEvtRing; + +typedef struct +{ + FXhciTrb *ring; + FXhciTrb *cur; + u8 pcs; +} __attribute__((packed)) FXhciTransRing; + +typedef FXhciTransRing FXhciCmdRing; + +typedef volatile struct +{ + u32 f1; + u32 f2; + u32 f3; + u32 f4; + u32 rsvd[4]; +} FXhciSlotCtx; + +typedef volatile struct +{ + u32 f1; + u32 f2; + u32 tr_dq_low; + u32 tr_dq_high; + u32 f5; + u32 rsvd[3]; +} FXhciEpCtx; + +typedef union +{ + /* set of pointers, so we can dynamically adjust Slot/EP context size */ + struct + { + union + { + FXhciSlotCtx *slot; + void *raw; /* Pointer to the whole dev context. */ + }; + FXhciEpCtx *ep0; + FXhciEpCtx *eps1_30[FXHCI_NUM_EPS - 2]; + }; + FXhciEpCtx *ep[FXHCI_NUM_EPS]; /* At index 0 it's actually the slotctx, + we have it like that so we can use + the ep_id directly as index. */ +} FXhciDevCtx; + +typedef struct +{ + union + { + /* The drop flags are located at the start of the */ + u32 *drop; /* structure, so a pointer to them is equivalent */ + void *raw; /* to a pointer to the whole (raw) input context. */ + }; + u32 *add; + FXhciDevCtx dev; +} FXhciInputCtx; + +typedef struct +{ + u32 seg_base_lo; + u32 seg_base_hi; + u32 seg_size; + u32 rsvd; +} FXhciErstEntry; + +typedef struct +{ + size_t size; /* Size of each transfer */ + size_t count; /* The number of TRBs to fill at once */ + FXhciTrb *next; /* The next TRB expected to be processed by the controller */ + FXhciTrb *ready; /* The last TRB in the transfer ring processed by the controller */ + FUsbEndpoint *ep; +} FXhciIntrQ; + +typedef struct +{ + FXhciDevCtx ctx; + FXhciTransRing *transfer_rings[FXHCI_NUM_EPS]; + FXhciIntrQ *interrupt_queues[FXHCI_NUM_EPS]; +} FXhciDevInfo; + +typedef enum +{ + FXHCI_DMA_SET_ADDR = 0, + FXHCI_DMA_INPUT_CTX, + FXHCI_DMA_TRANS_RING, + FXHCI_DMA_TRANS_RING_TRB, + + FXHCI_MAX_DMA_TYPE +} FXhciDMAType; + +typedef struct +{ + FXhciDMAType type; +#define FXHCI_MAX_DMA_ENTRY 10 + void *entries[FXHCI_MAX_DMA_ENTRY]; + uintptr count; +} FXhciDMABuffer; + +typedef struct +{ + /* R/W, volatile, Memory -> bitfields allowed */ + u64 *dcbaa; /* pointers to sp_ptrs and output (device) contexts */ + u64 *sp_ptrs; /* pointers to scratchpad buffers */ + + FXhciCmdRing cr; + FXhciEvtRing er; + volatile FXhciErstEntry *ev_ring_table; + + FUsbDev *roothub; + + u8 max_slots_en; + FXhciDevInfo *dev; /* array of devinfos by slot_id */ + FUsb *usb; + FXhciMMIO mmio; +} FXhci; +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ +#define FXHCI_MASK(startbit, lenbit) (((1<<(lenbit))-1)<<(startbit)) + +/* shorcut to access TRB */ +#define FXHCI_TRB_PORT_FIELD ptr_low /* Pointer field of Port TRB */ +#define FXHCI_TRB_PORT_START 24 +#define FXHCI_TRB_PORT_LEN 8 +#define FXHCI_TRB_TL_FIELD status /* TL - Transfer Length */ +#define FXHCI_TRB_TL_START 0 +#define FXHCI_TRB_TL_LEN 17 +#define FXHCI_TRB_EVTL_FIELD status /* EVTL - (Event TRB) Transfer Length */ +#define FXHCI_TRB_EVTL_START 0 +#define FXHCI_TRB_EVTL_LEN 24 +#define FXHCI_TRB_TDS_FIELD status /* TDS - TD Size */ +#define FXHCI_TRB_TDS_START 17 +#define FXHCI_TRB_TDS_LEN 5 +#define FXHCI_TRB_CC_FIELD status /* CC - Completion Code */ +#define FXHCI_TRB_CC_START 24 +#define FXHCI_TRB_CC_LEN 8 +#define FXHCI_TRB_C_FIELD control /* C - Cycle Bit */ +#define FXHCI_TRB_C_START 0 +#define FXHCI_TRB_C_LEN 1 +#define FXHCI_TRB_TC_FIELD control /* TC - Toggle Cycle */ +#define FXHCI_TRB_TC_START 1 +#define FXHCI_TRB_TC_LEN 1 +#define FXHCI_TRB_ENT_FIELD control /* ENT - Evaluate Next TRB */ +#define FXHCI_TRB_ENT_START 1 +#define FXHCI_TRB_ENT_LEN 1 +#define FXHCI_TRB_ISP_FIELD control /* ISP - Interrupt-on Short Packet */ +#define FXHCI_TRB_ISP_START 2 +#define FXHCI_TRB_ISP_LEN 1 +#define FXHCI_TRB_CH_FIELD control /* CH - Chain Bit */ +#define FXHCI_TRB_CH_START 4 +#define FXHCI_TRB_CH_LEN 1 +#define FXHCI_TRB_IOC_FIELD control /* IOC - Interrupt On Completion */ +#define FXHCI_TRB_IOC_START 5 +#define FXHCI_TRB_IOC_LEN 1 +#define FXHCI_TRB_IDT_FIELD control /* IDT - Immediate Data */ +#define FXHCI_TRB_IDT_START 6 +#define FXHCI_TRB_IDT_LEN 1 +#define FXHCI_TRB_DC_FIELD control /* DC - Deconfigure */ +#define FXHCI_TRB_DC_START 9 +#define FXHCI_TRB_DC_LEN 1 +#define FXHCI_TRB_TT_FIELD control /* TT - TRB Type */ +#define FXHCI_TRB_TT_START 10 +#define FXHCI_TRB_TT_LEN 6 +#define FXHCI_TRB_TRT_FIELD control /* TRT - Transfer Type */ +#define FXHCI_TRB_TRT_START 16 +#define FXHCI_TRB_TRT_LEN 2 +#define FXHCI_TRB_DIR_FIELD control /* DIR - Direction */ +#define FXHCI_TRB_DIR_START 16 +#define FXHCI_TRB_DIR_LEN 1 +#define FXHCI_TRB_EP_FIELD control /* EP - Endpoint ID */ +#define FXHCI_TRB_EP_START 16 +#define FXHCI_TRB_EP_LEN 5 +#define FXHCI_TRB_ID_FIELD control /* ID - Slot ID */ +#define FXHCI_TRB_ID_START 24 +#define FXHCI_TRB_ID_LEN 8 +#define FXHCI_TRB_MASK(tok) FXHCI_MASK(FXHCI_TRB_##tok##_START, FXHCI_TRB_##tok##_LEN) +#define FXHCI_TRB_GET(tok, trb) (((trb)->FXHCI_TRB_##tok##_FIELD & FXHCI_TRB_MASK(tok)) \ + >> FXHCI_TRB_##tok##_START) +#define FXHCI_TRB_SET(tok, trb, to) (trb)->FXHCI_TRB_##tok##_FIELD = \ + (((trb)->FXHCI_TRB_##tok##_FIELD & ~FXHCI_TRB_MASK(tok)) | \ + (((to) << FXHCI_TRB_##tok##_START) & FXHCI_TRB_MASK(tok))) +#define FXHCI_TRB_DUMP(dumper, tok, trb) dumper(" "#tok"\t0x%04x ", FXHCI_TRB_GET(tok, trb)) + +#define FXHCI_TRB_CYCLE (1 << 0) + +/* shortcut to access slot context */ +#define FXHCI_SC_ROUTE_FIELD f1 /* ROUTE - Route String */ +#define FXHCI_SC_ROUTE_START 0 +#define FXHCI_SC_ROUTE_LEN 20 +#define FXHCI_SC_SPEED1_FIELD f1 /* SPEED - Port speed plus one (compared to FUsbSpeed enum) */ +#define FXHCI_SC_SPEED1_START 20 +#define FXHCI_SC_SPEED1_LEN 4 +#define FXHCI_SC_MTT_FIELD f1 /* MTT - Multi Transaction Translator */ +#define FXHCI_SC_MTT_START 25 +#define FXHCI_SC_MTT_LEN 1 +#define FXHCI_SC_HUB_FIELD f1 /* HUB - Is this a hub? */ +#define FXHCI_SC_HUB_START 26 +#define FXHCI_SC_HUB_LEN 1 +#define FXHCI_SC_CTXENT_FIELD f1 /* CTXENT - Context Entries (number of following ep contexts) */ +#define FXHCI_SC_CTXENT_START 27 +#define FXHCI_SC_CTXENT_LEN 5 +#define FXHCI_SC_RHPORT_FIELD f2 /* RHPORT - Root Hub Port Number */ +#define FXHCI_SC_RHPORT_START 16 +#define FXHCI_SC_RHPORT_LEN 8 +#define FXHCI_SC_NPORTS_FIELD f2 /* NPORTS - Number of Ports */ +#define FXHCI_SC_NPORTS_START 24 +#define FXHCI_SC_NPORTS_LEN 8 +#define FXHCI_SC_TTID_FIELD f3 /* TTID - TT Hub Slot ID */ +#define FXHCI_SC_TTID_START 0 +#define FXHCI_SC_TTID_LEN 8 +#define FXHCI_SC_TTPORT_FIELD f3 /* TTPORT - TT Port Number */ +#define FXHCI_SC_TTPORT_START 8 +#define FXHCI_SC_TTPORT_LEN 8 +#define FXHCI_SC_TTT_FIELD f3 /* TTT - TT Think Time */ +#define FXHCI_SC_TTT_START 16 +#define FXHCI_SC_TTT_LEN 2 +#define FXHCI_SC_UADDR_FIELD f4 /* UADDR - USB Device Address */ +#define FXHCI_SC_UADDR_START 0 +#define FXHCI_SC_UADDR_LEN 8 +#define FXHCI_SC_STATE_FIELD f4 /* STATE - Slot State */ +#define FXHCI_SC_STATE_START 27 +#define FXHCI_SC_STATE_LEN 5 +#define FXHCI_SC_MASK(tok) FXHCI_MASK(FXHCI_SC_##tok##_START, FXHCI_SC_##tok##_LEN) +#define FXHCI_SC_GET(tok, sc) (((sc)->FXHCI_SC_##tok##_FIELD & FXHCI_SC_MASK(tok)) \ + >> FXHCI_SC_##tok##_START) +#define FXHCI_SC_SET(tok, sc, to) (sc)->FXHCI_SC_##tok##_FIELD = \ + (((sc)->FXHCI_SC_##tok##_FIELD & ~FXHCI_SC_MASK(tok)) | \ + (((to) << FXHCI_SC_##tok##_START) & FXHCI_SC_MASK(tok))) +#define FXHCI_SC_DUMP(dumper, tok, sc) dumper(" "#tok"\t0x%04x ", FXHCI_SC_GET(tok, sc)) + +/* shortcut to access endpoint context */ +#define FXHCI_EC_STATE_FIELD f1 /* STATE - Endpoint State */ +#define FXHCI_EC_STATE_START 0 +#define FXHCI_EC_STATE_LEN 3 +#define FXHCI_EC_INTVAL_FIELD f1 /* INTVAL - Interval */ +#define FXHCI_EC_INTVAL_START 16 +#define FXHCI_EC_INTVAL_LEN 8 +#define FXHCI_EC_CERR_FIELD f2 /* CERR - Error Count */ +#define FXHCI_EC_CERR_START 1 +#define FXHCI_EC_CERR_LEN 2 +#define FXHCI_EC_TYPE_FIELD f2 /* TYPE - EP Type */ +#define FXHCI_EC_TYPE_START 3 +#define FXHCI_EC_TYPE_LEN 3 +#define FXHCI_EC_MBS_FIELD f2 /* MBS - Max Burst Size */ +#define FXHCI_EC_MBS_START 8 +#define FXHCI_EC_MBS_LEN 8 +#define FXHCI_EC_MPS_FIELD f2 /* MPS - Max Packet Size */ +#define FXHCI_EC_MPS_START 16 +#define FXHCI_EC_MPS_LEN 16 +#define FXHCI_EC_DCS_FIELD tr_dq_low /* DCS - Dequeue Cycle State */ +#define FXHCI_EC_DCS_START 0 +#define FXHCI_EC_DCS_LEN 1 +#define FXHCI_EC_AVRTRB_FIELD f5 /* AVRTRB - Average TRB Length */ +#define FXHCI_EC_AVRTRB_START 0 +#define FXHCI_EC_AVRTRB_LEN 16 +#define FXHCI_EC_MXESIT_FIELD f5 /* MXESIT - Max ESIT Payload */ +#define FXHCI_EC_MXESIT_START 16 +#define FXHCI_EC_MXESIT_LEN 16 +#define FXHCI_EC_BPKTS_FIELD rsvd[0] /* BPKTS - packets tx in scheduled uframe */ +#define FXHCI_EC_BPKTS_START 0 +#define FXHCI_EC_BPKTS_LEN 6 +#define FXHCI_EC_BBM_FIELD rsvd[0] /* BBM - burst mode for scheduling */ +#define FXHCI_EC_BBM_START 11 +#define FXHCI_EC_BBM_LEN 1 + +#define FXHCI_EC_MASK(tok) FXHCI_MASK(FXHCI_EC_##tok##_START, FXHCI_EC_##tok##_LEN) +#define FXHCI_EC_GET(tok, ec) (((ec)->FXHCI_EC_##tok##_FIELD & FXHCI_EC_MASK(tok)) \ + >> FXHCI_EC_##tok##_START) +#define FXHCI_EC_SET(tok, ec, to) (ec)->FXHCI_EC_##tok##_FIELD = \ + (((ec)->FXHCI_EC_##tok##_FIELD & ~FXHCI_EC_MASK(tok)) | \ + (((to) << FXHCI_EC_##tok##_START) & FXHCI_EC_MASK(tok))) +#define FXHCI_EC_DUMP(dumper, tok, ec) dumper(" "#tok"\t0x%04x ", FXHCI_EC_GET(tok, ec)) + +/* the current operational state of the endpoint. */ +enum +{ + FXHCI_EC_STATE_DISABLED = 0, /* endpoint is not operational */ + FXHCI_EC_STATE_RUNNING = 1, /* endpoint is operational */ + FXHCI_EC_STATE_HALTED = 2, /* endpoint is halted due to a Halt condition detected on the USB */ + FXHCI_EC_STATE_STOPPED = 3, /* endpoint is not running due to a Stop Endpoint Command */ + FXHCI_EC_STATE_ERROR = 4 /* endpoint is not running due to a TRB Error */ +}; + +#define FXHCI_INST_GET(controller) ((FXhci*)((controller)->instance)) + +static inline int FXhciEpId(const FUsbEndpoint *const ep) +{ + /* calculate endpoint ID (Device Context Index (DCI)) The range of DCI values is 0 to 31. + * For Isoch, Interrupt, or Bulk type endpoints + * DCI = (Endpoint Number * 2) + Direction , Direction = ‘0’ for OUT ‘1’ for IN + * For Control type endpoints + * DCI = (Endpoint Number * 2) + 1. + */ + return ((ep->endpoint & 0x7f) * 2) + (ep->direction != FUSB_OUT); +} + +#define FXHCI_EP0_ID 1 + +/************************** Function Prototypes ******************************/ +/* 初始化Roothub */ +void FXhciRootHubInit(FUsbDev *dev); + +/* 分配一段对齐的内存 */ +void *FXhciAlign(FXhci *xhci, const size_t min_align, const size_t size); + +/* 初始化TRB ring */ +void FXhciInitCycleRing(FXhciTransRing *ring, const size_t ring_size); + +/* 设备USB设备的地址 */ +FUsbDev *FXhciSetAddress(FUsbHc *hc, FUsbSpeed speed, int hubport, int hubaddr); + +/* 完成USB设备配置 */ +FXhciTransCode FXhciFinishDevConfig(FUsbDev *hc); + +/* 删除指定USB设备实例 */ +void FXhciDestoryDev(FUsbHc *xhci, int slot_id); + +/* 重置Event TRB ring */ +void FXhciResetEvtRing(FXhciEvtRing *ring); + +void FXhciAdvanceEvtRing(FXhci *xhci); +void FXhciUpdateEvtDQ(FXhci *xhci); +void FXhciHandleEvts(FXhci *xhci); + +FXhciTransCode FXhciWaitForCmdAborted(FXhci *xhci, const FXhciTrb *trb); +FXhciTransCode FXhciWaitForCmdDone(FXhci *xhci, const FXhciTrb *trb, int clear_event); +FXhciTransCode FXhciWaitForTransfer(FXhci *xhci, const int slot_id, const int ep_id); + +void FXhciClearTrb(FXhciTrb *trb, int pcs); +FXhciTrb *FXhciNextCmdTrb(FXhci *xhci); +void FXhciPostCmd(FXhci *xhci); + +FXhciTransCode FXhciCmdNop(FXhci *const xhci); +FXhciTransCode FXhciCmdEnableSlot(FXhci *xhci, int *slot_id); +FXhciTransCode FXhciCmdDisableSlot(FXhci *xhci, int slot_id); +FXhciTransCode FXhciCmdAddressDevice(FXhci *xhci, int slot_id, FXhciInputCtx *ctx); +FXhciTransCode FXhciCmdConfigureEp(FXhci *xhci, int slot_id, int config_id, FXhciInputCtx *ctx); +FXhciTransCode FXhciCmdEvaluateCtx(FXhci *xhci, int slot_id, FXhciInputCtx *ctx); +FXhciTransCode FXhciCmdResetEp(FXhci *xhci, int slot_id, int ep); +FXhciTransCode FXhciCmdStopEp(FXhci *xhci, int slot_id, int ep); +FXhciTransCode FXhciCmdSetTrDq(FXhci *xhci, int slot_id, int ep, FXhciTrb *trb, int dcs); + +void FXhciDumpSlotCtx(const FXhciSlotCtx *ctx); +void FXhciDumpEpCtx(const FXhciEpCtx *ctx); +void FXhciDumpDevCtx(const FXhciDevCtx *ctx, const u32 ctx_mask); +void FXhciDumpInputCtx(const FXhciInputCtx *ctx); +void FXhciDumpTransferTrb(const FXhciTrb *trb); +void FXhciDumpTransferTrbs(const FXhciTrb *first, const FXhciTrb *last); + + +/* 支持带TAG的内存分配,用于跟踪动态内存使用 */ +#ifdef FMEMP_TAG_DEBUG +void *FXhciAlignTag(FXhci *const xhci, const size_t min_align, const size_t size, const char *file, unsigned long line, const char *msg); + +#define FXHCI_ALIGN(xhci, min_align, size) FXhciAlignTag((xhci), (min_align), (size), __FILE__, __LINE__, "") +#else + +#define FXHCI_ALIGN(xhci, min_align, size) FXhciAlign((xhci), (min_align), (size)) +#endif + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_roothub.c b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_roothub.c new file mode 100644 index 0000000000..56619be498 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/usb/fxhci/fxhci_roothub.c @@ -0,0 +1,193 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fxhci_roothub.c + * Date: 2022-02-11 13:33:12 + * LastEditTime: 2022-02-18 09:17:02 + * Description:  This files is for implementation of XHCI roothub function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Zhugengyu 2022/2/7 init commit + */ + +#include "fdebug.h" + +#include "fusb.h" +#include "fusb_generic_hub.h" +#include "fxhci_private.h" + +#define FUSB_DEBUG_TAG "FXHCI_ROOTHUB" +#define FUSB_ERROR(format, ...) FT_DEBUG_PRINT_E(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_WARN(format, ...) FT_DEBUG_PRINT_W(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_INFO(format, ...) FT_DEBUG_PRINT_I(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) +#define FUSB_DEBUG(format, ...) FT_DEBUG_PRINT_D(FUSB_DEBUG_TAG, format, ##__VA_ARGS__) + +static int FXhciRootHubStatusChanged(FUsbDev *const dev) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 reg_val = FXhciReadOper32(&xhci->mmio, FXHCI_REG_OP_USBSTS); + const int changed = !!(FXHCI_REG_OP_USBSTS_PCD & reg_val); + + /* clear port change bit */ + if (changed) + { + reg_val &= FXHCI_REG_OP_USBSTS_PRSRV_MASK; + reg_val |= FXHCI_REG_OP_USBSTS_PCD; + FXhciWriteOper32(&xhci->mmio, FXHCI_REG_OP_USBSTS, reg_val); + } + + return changed; +} + +static int FXhciRootHubPortStatusChanged(FUsbDev *const dev, const int port) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + const int changed = !!(portsc & (FXHCI_REG_OP_PORTS_PORTSC_CSC | FXHCI_REG_OP_PORTS_PORTSC_PRC)); + + /* always clear all the status change bits */ + portsc &= FXHCI_REG_OP_PORTS_PORTSC_RW_MASK; + portsc |= 0x00fe0000; + FXhciWritePort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC, portsc); + + return changed; +} + +static int FXhciRootHubPortConnected(FUsbDev *const dev, const int port) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + return portsc & FXHCI_REG_OP_PORTS_PORTSC_CCS; +} + +static int FXhciRootHubPortInReset(FUsbDev *const dev, const int port) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + return !!(portsc & FXHCI_REG_OP_PORTS_PORTSC_PR); +} + +static int FXhciRootHubPortEnabled(FUsbDev *const dev, const int port) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + return !!(portsc & FXHCI_REG_OP_PORTS_PORTSC_PED); +} + +static FUsbSpeed FXhciRootHubPortSpeed(FUsbDev *const dev, const int port) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + + if (portsc & FXHCI_REG_OP_PORTS_PORTSC_PED) + { + return FXHCI_REG_OP_PORTS_PORTSC_PORT_SPEED_GET(portsc) - 1; + } + else + { + return FUSB_UNKNOWN_SPEED; + } +} + +static int FXhciRootHubResetPort(FUsbDev *const dev, const int port) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + + /* Trigger port reset. */ + portsc &= FXHCI_REG_OP_PORTS_PORTSC_RW_MASK; + portsc |= FXHCI_REG_OP_PORTS_PORTSC_PR; + FXhciWritePort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC, portsc); + + /* Wait for port_in_reset == 0, up to 150 * 1000us = 150ms */ + if (FUsbGenericHubWaitForPort(dev, port, 0, FXhciRootHubPortInReset, + 150, 1000) == 0) + { + FUSB_INFO("xhci_rh: Reset timed out at port %d ", port); + } + else + { + portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + portsc &= FXHCI_REG_OP_PORTS_PORTSC_RW_MASK; + portsc |= FXHCI_REG_OP_PORTS_PORTSC_PRC | FXHCI_REG_OP_PORTS_PORTSC_WRC; + FXhciWritePort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC, portsc); + } + + return 0; +} + +static int FXhciRootHubEnablePort(FUsbDev *const dev, int port) +{ + FXhci *const xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + u32 portsc = FXhciReadPort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC); + + /* + * Before sending commands to a port, the Port Power in + * PORTSC register should be enabled. + */ + portsc &= FXHCI_REG_OP_PORTS_PORTSC_RW_MASK; + portsc |= FXHCI_REG_OP_PORTS_PORTSC_PP; + FXhciWritePort32(&xhci->mmio, port - 1, FXHCI_REG_OP_PORTS_PORTSC, portsc); + + return 0; +} + +static const FUsbGenericHubOps FXHCI_ROOTHUB_OPS = +{ + .hub_status_changed = FXhciRootHubStatusChanged, + .port_status_changed = FXhciRootHubPortStatusChanged, + .port_connected = FXhciRootHubPortConnected, + .port_in_reset = FXhciRootHubPortInReset, + .port_enabled = FXhciRootHubPortEnabled, + .port_speed = FXhciRootHubPortSpeed, + .enable_port = FXhciRootHubEnablePort, + .disable_port = NULL, + .start_port_reset = NULL, + .reset_port = FXhciRootHubResetPort, +}; + +/** + * @name: FXhciRootHubInit + * @msg: 初始化Roothub + * @return {*} + * @param {FUsbDev} *dev, Roothub实例 + */ +void FXhciRootHubInit(FUsbDev *dev) +{ + u32 reg_val; + FXhci *xhci = FXHCI_INST_GET(dev->controller); + FASSERT(xhci); + + /* we can set them here because a root hub _really_ shouldn't + appear elsewhere */ + dev->address = 0; + dev->hub = FUSB_NO_HUB; + dev->port = FUSB_NO_PORT; + + reg_val = FXhciReadCap32(&xhci->mmio, FXHCI_REG_CAP_HCSPARAMS1); + const int num_ports = FXHCI_REG_CAP_HCSPARAMS1_MAX_PORTS_GET(reg_val); /* TODO: maybe we need to read extended caps */ + + FUsbGenericHubInit(dev, num_ports, &FXHCI_ROOTHUB_OPS); + + FUSB_INFO("xHCI: root hub init done "); +} diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/Kconfig b/bsp/phytium/libraries/standalone/drivers/watchdog/Kconfig new file mode 100644 index 0000000000..5da173ab68 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/Kconfig @@ -0,0 +1,10 @@ + +menu "FWDT Configuration" + config USE_FWDT + bool + prompt "Use FWDT" + default n + +endmenu + + diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt.c b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt.c new file mode 100644 index 0000000000..68b0db3f15 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt.c @@ -0,0 +1,255 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * FilePath: fwdt.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-07-15 17:05:09 + * Description:  This files is for wdt ctrl function implementation. + * Users can operate as a single stage watchdog or a two stages watchdog. + * In the single stage mode, when the timeout is reached, your system will + * be reset by WS1. The first signal (WS0) is ignored. + * In the two stages mode, when the timeout is reached, the first signal (WS0) + * will trigger panic. If the system is getting into trouble and cannot be reset + * by panic or restart properly by the kdump kernel(if supported), then the + * second stage (as long as the first stage) will be reached, system will be + * reset by WS1. This function can help administrator to backup the system + * context info by panic console output or kdump. + * + * GWDT: + * two stages mode: + * |--------WOR-------WS0--------WOR-------WS1 + * |----timeout-----(panic)----timeout-----reset + * + * single stage mode: + * |------WOR-----WS0(ignored)-----WOR------WS1 + * |--------------timeout-------------------reset + * + * Note: Since this watchdog timer has two stages, and each stage is determined + * by WOR, in the single stage mode, the timeout is (WOR * 2); in the two + * stages mode, the timeout is WOR. + * This driver use two stages mode, when WS0=1, it can Raise the timeout interrupt. + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Wangxiaodong 2021/8/25 init + * 1.1 Wangxiaodong 2021/11/5 restruct + * 1.2 Wangxiaodong 2022/7/20 add some functions + */ + +#include +#include "fgeneric_timer.h" +#include "fkernel.h" +#include "fparameters.h" +#include "ftypes.h" +#include "ferror_code.h" +#include "fdebug.h" +#include "fwdt.h" +#include "fwdt_hw.h" + +#define FWDT_DEBUG_TAG "WDT" +#define FWDT_ERROR(format, ...) FT_DEBUG_PRINT_E(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) +#define FWDT_WARN(format, ...) FT_DEBUG_PRINT_W(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) +#define FWDT_INFO(format, ...) FT_DEBUG_PRINT_I(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) +#define FWDT_DEBUG(format, ...) FT_DEBUG_PRINT_D(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) + +/** + * @name: FWdtCfgInitialize + * @msg: Initializes a specific instance such that it is ready to be used. + * @param {FWdtCtrl} *pctrl, instance of FWDT controller + * @param {FWdtConfig} *input_config_p, Configuration parameters of FWdt + * @return err code information, FWDT_SUCCESS indicates success,others indicates failed + */ +FError FWdtCfgInitialize(FWdtCtrl *pctrl, const FWdtConfig *input_config_p) +{ + FASSERT(pctrl && input_config_p); + + FError ret = FWDT_SUCCESS; + /* + * If the device is started, disallow the initialize and return a Status + * indicating it is started. This allows the user to de-initialize the device + * and reinitialize, but prevents a user from inadvertently + * initializing. + */ + if (FT_COMPONENT_IS_READY == pctrl->is_ready) + { + FWDT_WARN("device is already initialized!!!"); + } + + /*Set default values and configuration data */ + FWdtDeInitialize(pctrl); + + pctrl->config = *input_config_p; + + pctrl->is_ready = FT_COMPONENT_IS_READY; + + return ret; +} + +/** + * @name: FWdtDeInitialize + * @msg: DeInitialization function for the device instance + * @param {FWdtCtrl} *pctrl, instance of FWDT controller + * @return {*} + */ +void FWdtDeInitialize(FWdtCtrl *pctrl) +{ + FASSERT(pctrl); + + pctrl->is_ready = 0; + memset(pctrl, 0, sizeof(*pctrl)); + + return; +} + +/** + * @name: FWdtSetTimeout + * @msg: Set Timeout Value, the first time it will raise a signal, which is typically + * wired to an interrupt; If this watchdog remains un-refreshed, it will raise a + * second signal which can be used to interrupt higher-privileged software + * or cause a PE reset. + * @param {WdtCtrl} *pctrl, instance of FWDT controller. + * @param {u32} timeout, represent in seconds, this parameter must be a number between 1 and 89. + * @return {FError} err code information, FWDT_SUCCESS indicates success, others indicates failed. + */ +FError FWdtSetTimeout(FWdtCtrl *pctrl, u32 timeout) +{ + FASSERT(pctrl != NULL); + if (pctrl->is_ready != FT_COMPONENT_IS_READY) + { + FWDT_ERROR("device is not already!!!"); + return FWDT_NOT_READY; + } + if (timeout > FWDT_MAX_TIMEOUT) + { + FWDT_ERROR("timeout value is invalid"); + return FWDT_ERR_INVAL_PARM; + } + uintptr base_addr = pctrl->config.control_base_addr; + + FWDT_WRITE_REG32(base_addr, FWDT_GWDT_WOR, (u32)(FWDT_CLK * timeout)); + + return FWDT_SUCCESS; +} + +/** + * @name: WdtGetTimeleft + * @msg: Get Timeout countdown, in seconds + * @param {FWdtCtrl} *pctrl, pointer to a WdtCtrl structure that contains + * the configuration information for the specified wdt module. + * @return {u32} Timeout countdown, in seconds + */ +u32 FWdtGetTimeleft(FWdtCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + u64 timeleft = 0; + uintptr base_addr = pctrl->config.control_base_addr; + + /* if the ws0 bit of register WCS is zero,indicates that there is one more timeout opportunity */ + if (!(FWdtReadWCS(base_addr) & FWDT_GWDT_WCS_WS0)) + timeleft += FWdtReadWOR(base_addr); + + u32 wcvh = (u32)FWdtReadWCVH(base_addr); + u32 wcvl = (u32)FWdtReadWCVL(base_addr); + u64 wcv = (((u64)wcvh << 32) | wcvl); + + timeleft += (wcv - GenericTimerRead()); + + // f_printk("------wcvh=%llx, wcvl=%llx, wcv=%llx, timeleft=%llx\n", wcvh, wcvl, wcv, timeleft); + + do_div(timeleft, FWDT_CLK); + + return (u32)timeleft; +} + +/** + * @name: FWdtRefresh + * @msg: Refresh watchdog + * @param {WdtCtrl} *pctrl, instance of FWDT controller. + * @return {FError} err code information, FWDT_SUCCESS indicates success, others indicates failed. + */ +FError FWdtRefresh(FWdtCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + if (pctrl->is_ready != FT_COMPONENT_IS_READY) + { + FWDT_ERROR("device is not already!!!"); + return FWDT_NOT_READY; + } + uintptr base_addr = pctrl->config.refresh_base_addr; + FWDT_WRITE_REG32(base_addr, FWDT_GWDT_WRR, 0); + return FWDT_SUCCESS; +} + +/** + * @name: FWdtStart + * @msg: Start watchdog + * @param {WdtCtrl} *pctrl, instance of FWDT controller + * @return {FError} err code information, FWDT_SUCCESS indicates success, others indicates failed. + */ +FError FWdtStart(FWdtCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + if (pctrl->is_ready != FT_COMPONENT_IS_READY) + { + FWDT_ERROR("device is not already!!!"); + return FWDT_NOT_READY; + } + + uintptr base_addr = pctrl->config.control_base_addr; + FWDT_WRITE_REG32(base_addr, FWDT_GWDT_WCS, FWDT_GWDT_WCS_WDT_EN); + + return FWDT_SUCCESS; +} + +/** + * @name: FWdtStop + * @msg: Stop watchdog + * @param {WdtCtrl} *pctrl, instance of FWDT controller + * @return {FError} err code information, FWDT_SUCCESS indicates success, others indicates failed. + */ +FError FWdtStop(FWdtCtrl *pctrl) +{ + FASSERT(pctrl != NULL); + uintptr base_addr = pctrl->config.control_base_addr; + FWDT_WRITE_REG32(base_addr, FWDT_GWDT_WCS, 0); + return FWDT_SUCCESS; +} + +/** + * @name: FWdtReadFWdtReadWIIDR + * @msg: Read wdt iidr register value. + * @param {FWdtCtrl} *pctrl, instance of FWDT controller + * @param {FWdtIdentifier} *wdt_identify, wdt identifier struct. + * @return {FError} err code information, FWDT_SUCCESS indicates success, others indicates failed. + */ +FError FWdtReadFWdtReadWIIDR(FWdtCtrl *pctrl, FWdtIdentifier *wdt_identify) +{ + FASSERT(pctrl != NULL); + FASSERT(wdt_identify != NULL); + + if (pctrl->is_ready != FT_COMPONENT_IS_READY) + { + FWDT_ERROR("device is not already!!!"); + return FWDT_NOT_READY; + } + + u32 reg_val = 0; + uintptr base_addr = pctrl->config.refresh_base_addr; + reg_val = FWDT_READ_REG32(base_addr, FWDT_GWDT_W_IIDR); + + wdt_identify->version = (u16)((reg_val & FWDT_VERSION_MASK) >> 16); + wdt_identify->continuation_code = (u8)((reg_val & FWDT_CONTINUATION_CODE_MASK) >> 8); + wdt_identify->identity_code = (u8)((reg_val & FWDT_IDENTIFY_CODE_MASK)); + + return FWDT_SUCCESS; +} \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt.h b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt.h new file mode 100644 index 0000000000..e1fcc10390 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt.h @@ -0,0 +1,103 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fwdt.h + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:24:34 + * Description:  This files is for wdt ctrl function definition + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Wangxiaodong 2021/8/26 init + * 1.1 Wangxiaodong 2021/11/5 restruct + */ + +#ifndef BSP_DRIVERS_FWDT_H +#define BSP_DRIVERS_FWDT_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "ftypes.h" +#include "fdebug.h" +#include "ferror_code.h" +#include "fkernel.h" +#include "fassert.h" + +#define FWDT_SUCCESS FT_SUCCESS +#define FWDT_ERR_INVAL_PARM FT_MAKE_ERRCODE(ErrModBsp, ErrBspWdt, 1) +#define FWDT_NOT_READY FT_MAKE_ERRCODE(ErrModBsp, ErrBspWdt, 2) +#define FWDT_NOT_SUPPORT FT_MAKE_ERRCODE(ErrModBsp, ErrBspWdt, 3) +#define FWDT_TIMEOUT FT_MAKE_ERRCODE(ErrModBsp, ErrBspWdt, 4) + +/* max timeout = 0xFFFFFFFF/ WDT_CLK = 89 */ +#define FWDT_MAX_TIMEOUT 89 + +typedef struct +{ + u16 version; /* wdt version */ + u8 continuation_code;/* JEP106 continuation code of the implementer */ + u8 identity_code; /* JEP106 identity code of the implementer */ +} FWdtIdentifier; /* wdt Identifier*/ + +typedef struct +{ + u32 instance_id;/* wdt id */ + uintptr refresh_base_addr;/* wdt refresh base addr */ + uintptr control_base_addr;/* wdt control base addr */ + u32 irq_num; /* wdt ir num */ + u32 irq_prority;/* wdt irq priority */ + const char *instance_name;/* instance name */ +} FWdtConfig; /* wdt config */ + +typedef struct +{ + FWdtConfig config; /* wdt config */ + u32 is_ready; /* wdt initialize the complete flag */ +} FWdtCtrl; + + +/* get wdt default configs */ +const FWdtConfig *FWdtLookupConfig(u32 instance_id); + +/* wdt config init */ +FError FWdtCfgInitialize(FWdtCtrl *pctrl, const FWdtConfig *input_config_p); + +/* wdt config deinit */ +void FWdtDeInitialize(FWdtCtrl *pctrl); + +/* set wdt timeout value*/ +FError FWdtSetTimeout(FWdtCtrl *pCtrl, u32 timeout); + +u32 FWdtGetTimeleft(FWdtCtrl *pctrl); + +/* fresh the wdt */ +FError FWdtRefresh(FWdtCtrl *pCtrl); + +/* start wdt*/ +FError FWdtStart(FWdtCtrl *pCtrl); + +/* stop wdt*/ +FError FWdtStop(FWdtCtrl *pCtrl); + +/* read wdt w_iidr register*/ +FError FWdtReadFWdtReadWIIDR(FWdtCtrl *pctrl, FWdtIdentifier *wdt_identify); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_g.c b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_g.c new file mode 100644 index 0000000000..21bc05458b --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_g.c @@ -0,0 +1,48 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fwdt_g.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:22:49 + * Description:  This files is for static config of wdt ctrl + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 Wangxiaodong 2021/8/25 init + */ + +#include "fparameters.h" +#include "fwdt.h" + +/* default configs of wdt ctrl */ +const FWdtConfig FWdtConfigTbl[FWDT_INSTANCE_NUM] = +{ + { + .instance_id = FWDT_INSTANCE_0, + .refresh_base_addr = FWDT0_REFRESH_BASE, + .control_base_addr = FWDT0_CONTROL_BASE, + .irq_num = FWDT0_INTR_IRQ, + .irq_prority = 0, + .instance_name = "WDT-0" + }, + + { + .instance_id = FWDT_INSTANCE_1, + .refresh_base_addr = FWDT1_REFRESH_BASE, + .control_base_addr = FWDT1_CONTROL_BASE, + .irq_num = FWDT1_INTR_IRQ, + .irq_prority = 0, + .instance_name = "WDT-1" + } +}; diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_hw.c b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_hw.c new file mode 100644 index 0000000000..d81b945332 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_hw.c @@ -0,0 +1,37 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fwdt_hw.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-18 09:23:08 + * Description:  This files is for wdt register function + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + +/***************************** Include Files *********************************/ + +#include "fwdt_hw.h" + + +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/************************** Variable Definitions *****************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_hw.h b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_hw.h new file mode 100644 index 0000000000..ede7d81373 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_hw.h @@ -0,0 +1,131 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fwdt_hw.h + * Date: 2021-08-25 10:27:42 + * LastEditTime: 2022-02-25 11:44:33 + * Description:  This files is for ctrl of watchdog timer functions + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + * 1.0 wangxiaodong 2021/8/25 init + */ + +#ifndef BSP_DRIVERS_FWDT_HW_H +#define BSP_DRIVERS_FWDT_HW_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "fkernel.h" +#include "fio.h" + +/* Watchdog register definitions */ + +/* refresh frame */ +#define FWDT_GWDT_WRR 0x000 + +/* control frame */ +#define FWDT_GWDT_WCS 0x000 /* WCS register */ +#define FWDT_GWDT_WOR 0x008 +#define FWDT_GWDT_WCVL 0x010 +#define FWDT_GWDT_WCVH 0x014 + +/* refresh/control frame */ +#define FWDT_GWDT_W_IIDR 0xfcc +#define FWDT_GWDT_IDR 0xfd0 + +/* Watchdog Control and Status Register */ +#define FWDT_GWDT_WCS_WDT_EN BIT(0) +#define FWDT_GWDT_WCS_WS0 BIT(1) +#define FWDT_GWDT_WCS_WS1 BIT(2) + +/***************** Macros (Inline Functions) Definitions *********************/ + +/** + * @name: WDT_READ_REG32 + * @msg: read WDT register + * @param {u32} addr, base address + * @param {u32} reg_offset, register offset + * @return {u32} register value + */ +#define FWDT_READ_REG32(addr, reg_offset) FtIn32((addr) + (u32)(reg_offset)) + +/** + * @name: FWDT_WRITE_REG32 + * @msg: write WDT register + * @param {u32} addr, base address + * @param {u32} reg_offset, register offset + * @param {u32} reg_value, value write to register + * @return {u32} register value + */ +#define FWDT_WRITE_REG32(addr, reg_offset, reg_value) FtOut32((addr) + (u32)(reg_offset), (u32)(reg_value)) + +#define FWDT_VERSION_MASK GENMASK(19, 16) +#define FWDT_CONTINUATION_CODE_MASK GENMASK(11, 8) +#define FWDT_IDENTIFY_CODE_MASK GENMASK(6, 0) +/** + * @name: FWdtReadWCVH + * @msg: Read wdt wcvh register value. wcvl and wclh register stores the comparison value of the watchdog count. + * timeout value = comparison value - sys_cnt. + * @param {uintptr} addr, pointer to a WdtCtrl base addr. + * @return {u32} register value + */ + +static inline u32 FWdtReadWCVH(uintptr addr) +{ + return FWDT_READ_REG32(addr, FWDT_GWDT_WCVH); +} + +/** + * @name: FWdtReadWCVL + * @msg: Read wdt wcvl register value. wcvl and wclh register stores the comparison value of the watchdog count. + * timeout value = comparison value - sys_cnt. + * @param {uintptr} addr, pointer to a WdtCtrl base addr. + * @return {u32} register value + */ +static inline u32 FWdtReadWCVL(uintptr addr) +{ + return FWDT_READ_REG32(addr, FWDT_GWDT_WCVL); +} + +/** + * @name: FWdtReadWOR + * @msg: Read wdt wor register value. used to set timeout value, wor + sys_cnt = wcv. + * @param {uintptr} addr, pointer to a WdtCtrl base addr. + * @return {u32} register value + */ +static inline u32 FWdtReadWOR(uintptr addr) +{ + return FWDT_READ_REG32(addr, FWDT_GWDT_WOR); +} + +/** + * @name: FWdtReadWCS + * @msg: Read wdt wcs register value. wcs is control and state register. bit0 enable(1) or disable(0) wdt. + * @param {uintptr} addr, pointer to a WdtCtrl base addr. + * @return {u32} register value + */ +static inline u32 FWdtReadWCS(uintptr addr) +{ + return FWDT_READ_REG32(addr, FWDT_GWDT_WCS); +} + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_intr.c b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_intr.c new file mode 100644 index 0000000000..39972e27a0 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_intr.c @@ -0,0 +1,22 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fwdt_intr.c + * Date: 2021-11-05 10:01:59 + * LastEditTime: 2022-02-25 11:44:02 + * Description:  This files is for intrrupt function of wdt ctrl + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ diff --git a/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_sinit.c b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_sinit.c new file mode 100644 index 0000000000..69498558e4 --- /dev/null +++ b/bsp/phytium/libraries/standalone/drivers/watchdog/fwdt/fwdt_sinit.c @@ -0,0 +1,75 @@ +/* + * Copyright : (C) 2022 Phytium Information Technology, Inc. + * All Rights Reserved. + * + * This program is OPEN SOURCE software: you can redistribute it and/or modify it + * under the terms of the Phytium Public License as published by the Phytium Technology Co.,Ltd, + * either version 1.0 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the Phytium Public License for more details. + * + * + * FilePath: fwdt_sinit.c + * Date: 2022-02-10 14:53:42 + * LastEditTime: 2022-02-25 11:45:05 + * Description:  This files is for + * + * Modify History: + * Ver   Who        Date         Changes + * ----- ------     --------    -------------------------------------- + */ + + +/***************************** Include Files *********************************/ + +#include "fwdt.h" +#include "fparameters.h" + +#define FWDT_DEBUG_TAG "WDT_SINIT" +#define FWDT_ERROR(format, ...) FT_DEBUG_PRINT_E(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) +#define FWDT_WARN(format, ...) FT_DEBUG_PRINT_W(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) +#define FWDT_INFO(format, ...) FT_DEBUG_PRINT_I(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) +#define FWDT_DEBUG(format, ...) FT_DEBUG_PRINT_D(FWDT_DEBUG_TAG, format, ##__VA_ARGS__) + + +extern FWdtConfig FWdtConfigTbl[FWDT_INSTANCE_NUM]; +/************************** Constant Definitions *****************************/ + +/**************************** Type Definitions *******************************/ + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Function Prototypes ******************************/ + +/*****************************************************************************/ + +/** + * @name: FWdtLookupConfig + * @msg: get wdt configs by id + * @param {u32} instance_id, id of wdt ctrl + * @return {FWdtConfig *}, wdt config address + */ +const FWdtConfig *FWdtLookupConfig(u32 instance_id) +{ + const FWdtConfig *pconfig = NULL; + u32 index; + + if (instance_id >= FWDT_INSTANCE_NUM) + { + FWDT_ERROR("wdt id is not invalid."); + return NULL; + } + + for (index = 0; index < (u32)FWDT_INSTANCE_NUM; index++) + { + if (FWdtConfigTbl[index].instance_id == instance_id) + { + pconfig = &FWdtConfigTbl[index]; + break; + } + } + return (const FWdtConfig *)pconfig; +} + diff --git a/bsp/phytium/libraries/standalone/gitinfo b/bsp/phytium/libraries/standalone/gitinfo new file mode 100644 index 0000000000..4cb410e5a6 --- /dev/null +++ b/bsp/phytium/libraries/standalone/gitinfo @@ -0,0 +1,4 @@ +[commit-id]: +ccf728ed578713cae89a5472f7dfb6fbd01e7a70 +[branch]: +new_master