spi flash读写驱动程序实例
时间: 2023-10-11 15:04:51 浏览: 47
以下是一个简单的SPI Flash读写驱动程序示例,使用的是Linux内核自带的SPI驱动接口。
#include <linux/module.h>
#include <linux/spi/spi.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#define FLASH_PAGE_SIZE 256
#define FLASH_SECTOR_SIZE 4096
#define FLASH_BLOCK_SIZE 65536
struct spi_flash {
struct mtd_info mtd;
struct spi_device *spi;
};
static int spi_flash_probe(struct spi_device *spi)
{
struct spi_flash *flash;
struct mtd_partition *parts;
int nparts, err;
flash = kzalloc(sizeof(struct spi_flash), GFP_KERNEL);
if (!flash) {
dev_err(&spi->dev, "Failed to allocate memory for spi_flash\n");
return -ENOMEM;
}
flash->spi = spi;
/* Set up MTD structure */
flash->mtd.name = spi->modalias;
flash->mtd.owner = THIS_MODULE;
flash->mtd.type = MTD_NORFLASH;
flash->mtd.flags = MTD_CAP_NORFLASH;
flash->mtd.erasesize = FLASH_BLOCK_SIZE;
flash->mtd.writesize = FLASH_PAGE_SIZE;
flash->mtd.writebufsize = FLASH_PAGE_SIZE;
/* Register MTD device */
err = mtd_device_register(&flash->mtd, NULL, 0);
if (err) {
dev_err(&spi->dev, "Failed to register MTD device, error %d\n", err);
kfree(flash);
return err;
}
/* Set up partition table */
nparts = get_mtd_device_partitions(&flash->mtd, &parts, 0);
if (nparts <= 0) {
dev_err(&spi->dev, "Failed to create partition table\n");
mtd_device_unregister(&flash->mtd);
kfree(flash);
return -EINVAL;
}
/* Print information about the device */
dev_info(&spi->dev, "SPI Flash device detected, %d partitions.\n", nparts);
dev_info(&spi->dev, "Flash device size %llu bytes, erase size %d bytes, write size %d bytes.\n",
(unsigned long long)flash->mtd.size, flash->mtd.erasesize, flash->mtd.writesize);
return 0;
}
static int spi_flash_remove(struct spi_device *spi)
{
struct spi_flash *flash = spi_get_drvdata(spi);
mtd_device_unregister(&flash->mtd);
kfree(flash);
return 0;
}
static const struct of_device_id spi_flash_of_match[] = {
{ .compatible = "spansion, s25fl064k", },
{ /* end of table */ }
};
MODULE_DEVICE_TABLE(of, spi_flash_of_match);
static struct spi_driver spi_flash_driver = {
.driver = {
.name = "spi_flash",
.owner = THIS_MODULE,
.of_match_table = spi_flash_of_match,
},
.probe = spi_flash_probe,
.remove = spi_flash_remove,
};
static int __init spi_flash_init(void)
{
return spi_register_driver(&spi_flash_driver);
}
static void __exit spi_flash_exit(void)
{
spi_unregister_driver(&spi_flash_driver);
}
module_init(spi_flash_init);
module_exit(spi_flash_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("SPI Flash driver");
MODULE_ALIAS("spi:spi_flash");
以上代码定义了一个名为spi_flash的驱动程序,它基于Linux内核自带的SPI驱动接口,并提供了一个MTD设备,可以进行SPI Flash的读写操作。在probe函数中,驱动程序会初始化MTD设备,并创建分区表。在remove函数中,驱动程序会注销MTD设备。在spi_flash_init函数中,驱动程序会注册SPI驱动程序。在spi_flash_exit函数中,驱动程序会注销SPI驱动程序。