2.6. Device

设备驱动层为应用层提供外部设备的操作接口,应用层可以不用关注外部设备操作的内部实现,只需要调用设备注册到设备驱动层的操作函数集合,即可实现对设备进行操作。

2.6.1. 设备管理说明

以下为外部设备需要提供的函数操作集合。

struct device_operations {
    // 设备在线状态
    bool (*online)(const struct dev_node *node);
    // 设备初始化
    int (*init)(const struct dev_node *node, void *);
    // 打开设备
    int (*open)(const char *name, struct device **device, void *arg);
    // 按byte读取
    int (*read)(struct device *device, void *buf, u32 len, u32);
    // 按byte写入
    int (*write)(struct device *device, void *buf, u32 len, u32);
    // 按块读取
    int (*bulk_read)(struct device *device, void *buf, u32 len, u32);
    // 按块写入
    int (*bulk_write)(struct device *device, void *buf, u32 len, u32);
    // seek到相应位置
    int (*seek)(struct device *device, u32 offset, int orig);
    // 设备ioctl
    int (*ioctl)(struct device *device, u32 cmd, u32 arg);
    // 关闭设备
    int (*close)(struct device *device);
};

以下为设备注册到设备管理列表的结构体。

struct dev_node {
    // 设备名字
    const char *name;
    // 设备操作函数集合
    const struct device_operations *ops;
    // 设备私有数据 传递给init函数
    void *priv_data;
};

外部设备通过如下宏定义进行注册。

#define REGISTER_DEVICES(node) \
    const struct dev_node node[] sec_used(.device)

2.6.2. 设备管理注册参考demo

// 设备操作函数集合
const struct device_operations norfs_dev_ops = {
    .init   = norflash_dev_init,
    .online = norflash_dev_online,
    .open   = norflash_dev_open,
    .read   = norflash_byte_read,
    .write  = norflash_byte_write,
    .bulk_read   = NULL,
    .bulk_write  = NULL,
    .ioctl  = norflash_byte_ioctl,
    .close  = norflash_dev_close,
};

// 设备私有数据
static struct norflash_dev_platform_data norfs_dev_data = {
    .spi_hw_num     = HW_SPI2,
    .spi_cs_port    = TCFG_HW_SPI2_PORT_CS,
    .spi_pdata      = &spi2_p_data, // 详见device_config.c
    .start_addr     = 1 * 1024 * 1024,
    .size           = 1 * 1024 * 1024,
};

// 设备注册
REGISTER_DEVICES(device_table) = {
    {.name = __EXT_FLASH_BYTE, .ops = &norfs_dev_ops, .priv_data = (void *) &norfs_dev_data},
};

// 对注册在设备管理列表上的所有设备进行初始化
devices_init();

// 根据设备名字打开设备 返回设备句柄
void *dev_hdl;
dev_hdl = dev_open(__EXT_FLASH_BYTE, NULL);

// 使用初始化返回的设备句柄对设备进行其他操作
dev_byte_read(dev_hdl, flash_buffer, addr, len);
dev_byte_write(dev_hdl, flash_buffer, addr, len);