5.25 SFlash SPI Flash设备
2026/7/20大约 2 分钟设备驱动驱动SFlashSPI FlashSFDP存储
5.25 SFlash SPI Flash设备
📚 本节导读
学习时长: 约 35 分钟
难度级别: ⭐⭐⭐⭐☆
前置知识: C 语言基础、SPI 总线基础、5.1 设备驱动框架
🎯 学习目标
- 理解 SFlash SPI Flash 驱动框架的分层架构
- 掌握 SFDP(Serial Flash Discoverable Parameters)自动探测机制
- 理解 SFBus 总线抽象层的作用
- 掌握页读写、块擦除等存储操作
一、概述
SFlash 是 OneOS 提供的 SPI Flash 设备驱动框架,支持通过 SPI/QSPI 接口访问 NOR Flash 存储芯片。驱动源码位于 drivers/sflash/ 目录下,核心头文件为 sflash.h、sfbus.h、sfdp.h。
SFlash 设备框架的特点:
- 分层架构:应用层 → SFlash 设备层 → SFBus 总线层 → SPI 硬件层
- SFDP 自动探测:通过 SFDP(JESD216 标准)自动识别 Flash 芯片参数
- 设备信息表:通过
OS_SFLASH_INFO宏声明设备信息,放入os_sflash_info链接器段 - 统一接口:提供
read_page、write_page、erase_block标准操作
二、核心数据结构
2.1 SFlash 设备结构体 struct os_sflash
struct os_sflash
{
struct os_device parent;
struct os_sfbus *sfbus;
struct os_spi_configuration config;
int cs;
const struct os_sflash_info *info;
struct os_sflash_commands cmds;
};2.2 Flash 设备信息 struct os_sflash_info
struct os_sflash_info
{
uint8_t mf; /* 厂商 ID */
uint8_t id; /* 设备 ID */
const char *name; /* 设备名称 */
const struct os_xspi_message_cfg *supported_cmds;
int supported_cmds_nr;
uint32_t capacity; /* 容量(字节) */
uint32_t page_size; /* 页大小(字节) */
uint8_t addr_bytes; /* 地址字节数 */
};2.3 设备信息声明宏
#define OS_SFLASH_INFO static OS_USED OS_SECTION("os_sflash_info") const struct os_sflash_info三、关键 API
3.1 初始化与配置
struct os_sflash *os_sflash_init(const char *bus_name, int cs);
int os_sflash_configure(struct os_sflash *sflash, struct os_spi_configuration *cfg);3.2 页读写与块擦除
int os_sflash_read_page(struct os_sflash *sflash, uint32_t offset, uint8_t *buf, os_size_t size);
int os_sflash_write_page(struct os_sflash *sflash, uint32_t offset, const uint8_t *buf, os_size_t size);
int os_sflash_erase_block(struct os_sflash *sflash, uint32_t offset);
void sflash_write_unlock(struct os_sflash *sflash);四、使用示例
4.1 声明 Flash 设备信息
#include <sflash.h>
OS_SFLASH_INFO w25q32_info = {
.mf = 0xEF,
.id = 0x4016,
.name = "W25Q32",
.capacity = 4 * 1024 * 1024, /* 4MB */
.page_size = 256,
.addr_bytes = 3,
};4.2 初始化与读写操作
#include <sflash.h>
void sflash_demo(void)
{
struct os_sflash *sflash;
uint8_t buf[256];
/* 初始化 */
sflash = os_sflash_init("spi0", 0);
if (sflash == NULL) return;
/* 读取第一页 */
os_sflash_read_page(sflash, 0, buf, sizeof(buf));
/* 擦除块 0 并写入 */
os_sflash_erase_block(sflash, 0);
memset(buf, 0xAA, sizeof(buf));
os_sflash_write_page(sflash, 0, buf, sizeof(buf));
}📝 本节小结
本节介绍了 OneOS 中 SFlash SPI Flash 设备驱动的使用方法,包括分层架构、SFDP 自动探测、设备信息声明、页读写块擦除等核心操作。