由於工作緣故,我對 SPI 的理解最為深刻,也最有感情。過去多在 OSEK 系統上實作,也在 US/OS3 上寫過 SPI 驅動並做過測試,但那些都是基於基本暫存器操作,缺乏系統軟體架構的思維。我覺得 Linux 的 SPI 驅動很強大、水很深。廢話少說,SPI 總線上有兩類設備:一類是主機端,通常作為 SOC 的一個子模塊,很多嵌入式 MPU 都內含 SPI 模塊;一類是從機被控端,例如 SPI 介面的 Flash、感測器等。主機端是 SPI 總線的控制者,主動發起會話;受控端被動接受指令並回應。本文前提是讀者必須熟練掌握 Linux Platform 總線驅動模型與基本字符設備驅動的實作。
SPI 總線由 MISO(串行資料輸入)、MOSI(串行資料輸出)、SCK(串行移位時鐘)、CS(使能信號)四條信號線組成。SPI 常用四種傳輸模式,差別在於輸出串行同步時鐘的極性(CPOL)與相位(CPHA)可配置。CPOL=0 時時鐘空閒為低電位,CPOL=1 時為高電位;CPHA=0 時在時鐘前沿(上升或下降)採樣,CPHA=1 時在後沿採樣。與 I2C 子系統類似,SPI 子系統分三部分:SPI 核心層、主控制器驅動與協議驅動。通俗地說,SPI 核心層負責:1. 定義並註冊 SPI 總線 spi_bus_type 與控制器類 spi_master_class;2. 提供 spi_driver、spi_device、spi_master 的分配、建立、註冊與註銷;3. 實作 SPI 通信方法的上層代碼。主控制器驅動對應 I2C 的適配器驅動,用 spi_master 描述控制器,通常用 spi_bitbang 控制實際傳輸,功能類似 i2c_algorithm。協議驅動類比 I2C 設備驅動,可理解成客戶端驅動。下面詳細分析並實作基於 Linux 3.14.78 內核、在 S3C2440/6410 上的 SPI 驅動移植。
Step1,實作 SPI 控制器的設備接口(有兩種方式:S3c2440 純粹靠配置實現,或針對 m25p10 獨立編寫 SPI 驅動模塊)
先針對 S3C2440,SPI 控制器的設備接口在 drivers/spi/spidev.c 中實作。spidev.c 的 spidev_init() 作為模塊初始化函數,在系統啟動或模塊加載時被呼叫,主要完成三件事:
1、呼叫 register_chrdev() 為 SPI 控制器註冊主設備號 153、次設備號 0~255、文件操作集合為 spidev_fops 的字符設備;
2、呼叫 class_create() 註冊一個名為 "spidev" 的設備類;
3、呼叫 spi_register_driver() 向系統添加 SPI 控制器的設備驅動 spidev_spi。
spi_register_driver() 會把 spidev_spi 添加到 SPI 核心層註冊的 spi_bus_type 總線上(在 drivers/spi/spi.c 定義,高版本引入 id_table 可匹配多個名稱)。由於 SPI 總線的匹配方式是檢查 spi_device.modalias 與 spi_driver.driver.name 是否相同,而 spidev_spi 的 name 是 "spidev",因此只有 modalias 為 "spidev" 的設備才能與它匹配。S3C2440 有兩個 SPI 控制器,對應平台信息為 s3c_device_spi0 與 s3c_device_spi1,可加入機器配置檔的 My2440_devices 陣列;probe 用到的總線編號、片選數量等來自平台數據,平台設備數據類型是 S3C2410_SPI_info,可在板級初始化檔中為兩個 SPI 平台設備分別定義並添加;此外還需為 SPI 控制器添加並註冊 spi_board_info 對象。設備與驅動匹配後會呼叫 spidev_spi 的 probe 完成綁定。SPI 控制器設備操作集合 spidev_fops 主要包括 spidev_write、spidev_read、spidev_ioctl、spidev_open 與 spidev_release。spidev_read() 的實作過程見下方註釋,spidev_write() 與 read 類似;spidev_open() 會遍歷 device_list 鏈表,找出設備號與 inode.i_rdev 相等的 spidev_data 對象並記錄在 filp->private_data,供 read/write 使用。要實現全雙工傳輸則需借助 ioctl(spidev_ioctl()),全雙工同樣透過 spidev_sync() 完成,與半雙工唯一不同是傳輸段中 tx_buffer 與 rx_buffer 同時被設置,此外它還提供獲取與修改時鐘模式、字寬、最大時鐘頻率的命令。
1 static struct s3c2410_spi_info s3c2410_spi0_platdata = { 2 .pin_cs = S3C2410_GPG2, 3 .num_cs = 2, 4 .bus_num = 0, 5 .gpio_setup = s3c24xx_spi_gpiocfg_bus0_gpe11_12_13, 6 }; 7 static struct spi_board_info s3c2410_spi0_board[] = 8 { 9 [0] = { 10 .modalias = "spidev", 11 .bus_num = 0, 12 .chip_select = 0, 13 .max_speed_hz = 500 * 1000, 14 }, 15 [1] = { 16 .modalias = "at25", 17 .platform_data = &at25_eeprom_data, 18 .bus_num = 0, 19 .chip_select = 1, 20 .max_speed_hz = 500 * 1000, 21 } 22 }; 23 static struct s3c2410_spi_info s3c2410_spi1_platdata = { 24 .pin_cs = S3C2410_GPG3, 25 .num_cs = 1, 26 .bus_num = 1, 27 .gpio_setup = s3c24xx_spi_gpiocfg_bus1_gpg5_6_7, 28 }; 29 static struct spi_board_info s3c2410_spi1_board[] = 30 { 31 [0] = { 32 .modalias = "spidev", 33 .bus_num = 1, 34 .chip_select = 0, 35 .max_speed_hz = 500 * 1000, 36 } 37 }; 38 static void __init My2440_machine_init(void) 39 { 40 s3c24xx_fb_set_platdata(&My2440_fb_info); 41 s3c_i2c0_set_platdata(NULL); 42 i2c_register_board_info(0, i2c_devices, ARRAY_SIZE(i2c_devices)); 43 s3c_device_spi0.dev.platform_data= &s3c2410_spi0_platdata; 44 spi_register_board_info(s3c2410_spi0_board, ARRAY_SIZE(s3c2410_spi0_board)); 45 s3c_device_spi1.dev.platform_data= &s3c2410_spi1_platdata; 46 spi_register_board_info(s3c2410_spi1_board, ARRAY_SIZE(s3c2410_spi1_board)); 47 s3c_device_nand.dev.platform_data = &My2440_nand_info; 48 s3c_device_sdi.dev.platform_data = &My2440_mmc_cfg; 49 platform_add_devices(My2440_devices, ARRAY_SIZE(My2440_devices)); 50 }
1 struct bus_type spi_bus_type = { 2 .name = "spi", 3 .dev_attrs = spi_dev_attrs, 4 .match = spi_match_device, 5 .uevent = spi_uevent, 6 .suspend = spi_suspend, 7 .resume = spi_resume, 8 };
static int spi_match_device(struct device *dev, struct device_driver *drv) { const struct spi_device *spi = to_spi_device(dev); return strcmp(spi->modalias, drv->name) == 0; }
static int spidev_probe(struct spi_device *spi) { struct spidev_data *spidev; int status; unsigned long minor; /* Allocate driver data, 分配並初始化一個spidev_data對象,用來描述SPI控制器設備驅動操作的控制器設備,包含它的設備號,傳輸緩存和內嵌spi_device*/ spidev = kzalloc(sizeof(*spidev), GFP_KERNEL); if (!spidev) return -ENOMEM; /* Initialize the driver data ,將與spidev_spi驅動匹配的spi_device賦值給spidev_data.spi,通過find_first_zero_bit()從位圖minors中分配到次設備號,
與主設備號SPIDEV_MAJOR構成設備號並賦值給spidev_data.devt,然後調用device_create()在/dev下創建名稱格式為“spidev%d%d”的字符設備文件,第一個%d表示控制器編號,
即spi_device.master.bus_num,第二個對應片選號,即spi_device.chip_select*/ spidev->spi = spi; spin_lock_init(&spidev->spi_lock); mutex_init(&spidev->buf_lock); INIT_LIST_HEAD(&spidev->device_entry); /* If we can allocate a minor number, hook up this device. * Reusing minors is fine so long as udev or mdev is working. */ mutex_lock(&device_list_lock); minor = find_first_zero_bit(minors, N_SPI_MINORS); if (minor < N_SPI_MINORS) { struct device *dev; spidev->devt = MKDEV(SPIDEV_MAJOR, minor); dev = device_create(spidev_class, &spi->dev, spidev->devt, spidev, "spidev%d.%d", spi->master->bus_num, spi->chip_select); status = PTR_ERR_OR_ZERO(dev); } else { dev_dbg(&spi->dev, "no minor number available!\n"); status = -ENODEV; } if (status == 0) { set_bit(minor, minors);
/*將spidev_data對象添加到一個名為device_list的設備列表中,最後將spidev_data對象設置為對應spi_device的驅動數據,將其值賦值給dpi_device.dev.driver_data*/ list_add(&spidev->device_entry, &device_list); } mutex_unlock(&device_list_lock); if (status == 0) spi_set_drvdata(spi, spidev); else kfree(spidev); return status; }
/*spidev_read(),spidev_write()實現的讀寫操作都是半雙工的傳輸,要實現全雙工傳輸需要調用spidev_ioctl()操作,在spidev_read()中,通過調用spidev_sync_read()
同步讀取指定長度數據到spidev_data_buffer中,然後調用copy_to_user()將讀取的數據復制到用戶空間緩沖*/
static ssize_t spidev_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) { struct spidev_data *spidev; ssize_t status = 0; /* chipselect only toggles at start or end of operation */ if (count > bufsiz) return -EMSGSIZE; spidev = filp->private_data; mutex_lock(&spidev->buf_lock); status = spidev_sync_read(spidev, count); if (status > 0) { unsigned long missing; missing = copy_to_user(buf, spidev->buffer, status); if (missing == status) status = -EFAULT; else status = status - missing; } mutex_unlock(&spidev->buf_lock); return status; }
/*spidev_sync_read()中定義一個spi_transfer和spi_message對象,使用spidev_data.buffer初始化spi_transfer.rx_buf,
然後將spi_transfer對象添加到spi_message中,調用spidev_sync()傳輸信息;*/
spidev_sync_read(struct spidev_data *spidev, size_t len)
{ struct spi_transfer t = { .rx_buf = spidev->buffer, .len = len, }; struct spi_message m; spi_message_init(&m); spi_message_add_tail(&t, &m); return spidev_sync(spidev, &m); }
/*spidev_sync()實現同步傳輸的機制:首先為傳入的消息對象的complete和context成員賦值,context被設置為完成接口done,complete被設置成spidev_complete(),然後
調用spi_async()啟動異步傳輸,spi_async()返回後,通過調用wait_for_completion()阻塞調用進程,直到異步傳輸完成,spi_message的complete方法,即spidev_complete()
被調用來喚醒被阻塞的進程,異步傳輸接口函數spi_async()屬於SPI核心層,在include/linux/spi/spi.h中定義並實現,它只調用了spi_device所屬控制器的transfer方法*/
static ssize_t spidev_sync(struct spidev_data *spidev, struct spi_message *message) { DECLARE_COMPLETION_ONSTACK(done); int status; message->complete = spidev_complete; message->context = &done; spin_lock_irq(&spidev->spi_lock); if (spidev->spi == NULL) status = -ESHUTDOWN; else status = spi_async(spidev->spi, message); spin_unlock_irq(&spidev->spi_lock); if (status == 0) { wait_for_completion(&done); status = message->status; if (status == 0) status = message->actual_length; } return status; }

針對 FS_S5PC100 上的 M25P10 芯片:

//spi_device對應的含義是掛接在spi總線上的一個設備,所以描述它的時候應該明確它自身的設備特性、傳輸要求、及掛接在哪個總線上 static struct spi_board_info s3c_spi_devs[] __initdata = { { .modalias = "m25p10", .mode = SPI_MODE_0, //CPOL=0, CPHA=0 此處選擇具體數據傳輸模式 .max_speed_hz = 10000000, //最大的spi時鐘頻率 /* Connected to SPI-0 as 1st Slave */ .bus_num = 0, //設備連接在spi控制器0上 .chip_select = 0, //片選線號,在S5PC100的控制器驅動中沒有使用它作為片選的依據,而是選擇了下文controller_data裡的方法 .controller_data = &smdk_spi0_csi[0], }, }; static struct s3c64xx_spi_csinfo smdk_spi0_csi[] = { [0] = { .set_level = smdk_m25p10_cs_set_level, .fb_delay = 0x3, }, }; static void smdk_m25p10_cs_set_level(int high) //spi控制器會用這個方法設置cs { u32 val; val = readl(S5PC1XX_GPBDAT); if (high) val |= (1<<3); else val &= ~(1<<3); writel(val, S5PC1XX_GPBDAT); } spi_register_board_info(s3c_spi_devs, ARRAY_SIZE(s3c_spi_devs));//注冊spi_board_info,這個代碼會把spi_board_info注冊要鏈表board_list上。 //spi_master的注冊會在spi_register_board_info之後,spi_master注冊的過程中會調用scan_boardinfo掃描board_list,找到掛接在它上面的spi設備,然後創建並注冊spi_device。 static void scan_boardinfo(struct spi_master *master) { struct boardinfo *bi; mutex_lock(&board_lock); list_for_each_entry(bi, &board_list, list) { struct spi_board_info *chip = bi->board_info; unsigned n; for (n = bi->n_board_info; n > 0; n--, chip++) { if (chip->bus_num != master->bus_num) continue; /* NOTE: this relies on spi_new_device to * issue diagnostics when given bogus inputs */ (void) spi_new_device(master, chip); //創建並注冊了spi_device } } mutex_unlock(&board_lock); } //spi_driver.c linux內核中的/driver/mtd/devices/m25p80.c驅動為參考 static struct spi_driver m25p80_driver = { //spi_driver的構建 .driver = { .name = "m25p80", .bus = &spi_bus_type, .owner = THIS_MODULE, }, .probe = m25p_probe, .remove = __devexit_p(m25p_remove), */ }; spi_register_driver(&m25p80_driver);//spi driver的注冊 //在有匹配的spi device時,會調用m25p_probe,根據傳入的spi_device參數,可以找到對應的spi_master。接下來就可以利用spi子系統為我們完成數據交互了 static int __devinit m25p_probe(struct spi_device *spi)
Step2,實作 SPI platform 總線匹配
S3C2440 與 S5PC100 的 SPI 控制器驅動同樣採用 Platform 驅動模型。針對 S3C2440 在 drivers/spi/spi_s3c24xx.c 中,模塊初始化函數 s3c24xx_spi_init() 完成 platform 驅動的註冊,名稱是 "s3c2410-spi",與之匹配的平台設備在 arch/arm/plat-samsung/devs.c 定義且同名。針對 S5PC100,詳見下文,匹配完成後呼叫相應 probe:
//Platform_device,SPI控制器對應platform_device的定義方式,同樣以S5PC100中的SPI控制器為例,參看arch/arm/plat-s5pc1xx/dev-spi.c文件 struct platform_device s3c_device_spi0 = { .name = "s3c64xx-spi", //名稱,要和Platform_driver匹配 .id = 0, //第0個控制器,S5PC100中有3個控制器 .num_resources = ARRAY_SIZE(s5pc1xx_spi0_resource), //占用資源的種類 .resource = s5pc1xx_spi0_resource, //指向資源結構數組的指針 .dev = { .dma_mask = &spi_dmamask, //dma尋址范圍 .coherent_dma_mask = DMA_BIT_MASK(32), //可以通過關閉cache等措施保證一致性的dma尋址范圍 .platform_data = &s5pc1xx_spi0_pdata, //特殊的平台數據,參看後文 }, }; static struct s3c64xx_spi_cntrlr_info s5pc1xx_spi0_pdata = { .cfg_gpio = s5pc1xx_spi_cfg_gpio, //用於控制器管腳的IO配置 .fifo_lvl_mask = 0x7f, .rx_lvl_offset = 13, }; static int s5pc1xx_spi_cfg_gpio(struct platform_device *pdev) { switch (pdev->id) { case 0: s3c_gpio_cfgpin(S5PC1XX_GPB(0), S5PC1XX_GPB0_SPI_MISO0); s3c_gpio_cfgpin(S5PC1XX_GPB(1), S5PC1XX_GPB1_SPI_CLK0); s3c_gpio_cfgpin(S5PC1XX_GPB(2), S5PC1XX_GPB2_SPI_MOSI0); s3c_gpio_setpull(S5PC1XX_GPB(0), S3C_GPIO_PULL_UP); s3c_gpio_setpull(S5PC1XX_GPB(1), S3C_GPIO_PULL_UP); s3c_gpio_setpull(S5PC1XX_GPB(2), S3C_GPIO_PULL_UP); break; case 1: s3c_gpio_cfgpin(S5PC1XX_GPB(4), S5PC1XX_GPB4_SPI_MISO1); s3c_gpio_cfgpin(S5PC1XX_GPB(5), S5PC1XX_GPB5_SPI_CLK1); s3c_gpio_cfgpin(S5PC1XX_GPB(6), S5PC1XX_GPB6_SPI_MOSI1); s3c_gpio_setpull(S5PC1XX_GPB(4), S3C_GPIO_PULL_UP); s3c_gpio_setpull(S5PC1XX_GPB(5), S3C_GPIO_PULL_UP); s3c_gpio_setpull(S5PC1XX_GPB(6), S3C_GPIO_PULL_UP); break; case 2: s3c_gpio_cfgpin(S5PC1XX_GPG3(0), S5PC1XX_GPG3_0_SPI_CLK2); s3c_gpio_cfgpin(S5PC1XX_GPG3(2), S5PC1XX_GPG3_2_SPI_MISO2); s3c_gpio_cfgpin(S5PC1XX_GPG3(3), S5PC1XX_GPG3_3_SPI_MOSI2); s3c_gpio_setpull(S5PC1XX_GPG3(0), S3C_GPIO_PULL_UP); s3c_gpio_setpull(S5PC1XX_GPG3(2), S3C_GPIO_PULL_UP); s3c_gpio_setpull(S5PC1XX_GPG3(3), S3C_GPIO_PULL_UP); break; default: dev_err(&pdev->dev, "Invalid SPI Controller number!"); return -EINVAL; } //platform_driver,參看drivers/spi/spi_s3c64xx.c文件 static struct platform_driver s3c64xx_spi_driver = { .driver = { .name = "s3c64xx-spi", //名稱,和platform_device對應 .owner = THIS_MODULE, }, .remove = s3c64xx_spi_remove, .suspend = s3c64xx_spi_suspend, .resume = s3c64xx_spi_resume, }; platform_driver_probe(&s3c64xx_spi_driver, s3c64xx_spi_probe);//注冊s3c64xx_spi_driver //和平台中注冊的platform_device匹配後,調用s3c64xx_spi_probe。然後根據傳入的platform_device參數,構建一個用於描述SPI控制器的結構體spi_master,並注冊。spi_register_master(master)。後續注冊的spi_device需要選定自己的spi_master,並利用spi_master提供的傳輸功能傳輸spi數據。和I2C類似,SPI也有一個描述控制器的對象叫spi_master,其主要成員是主機控制器的序號(系統中可能存在多個SPI主機控制器)、片選數量、SPI模式和時鐘設置用到的函數、數據傳輸用到的函數等; struct spi_master { struct device dev; s16 bus_num; //表示是SPI主機控制器的編號。由平台代碼決定 u16 num_chipselect; //控制器支持的片選數量,即能支持多少個spi設備 int (*setup)(struct spi_device *spi); //針對設備設置SPI的工作時鐘及數據傳輸模式等。在spi_add_device函數中調用。 int (*transfer)(struct spi_device *spi, struct spi_message *mesg); //實現數據的雙向傳輸,可能會睡眠 void (*cleanup)(struct spi_device *spi); //注銷時調用 };
static int s3c24xx_spi_probe(struct platform_device *pdev) { struct s3c2410_spi_info *pdata; struct s3c24xx_spi *hw; struct spi_master *master; struct resource *res; int err = 0; master = spi_alloc_master(&pdev->dev, sizeof(struct s3c24xx_spi));//分配SPI控制器結構及驅動私有數據 if (master == NULL) { dev_err(&pdev->dev, "No memory for spi_master\n"); return -ENOMEM; } hw = spi_master_get_devdata(master); memset(hw, 0, sizeof(struct s3c24xx_spi)); hw->master = master; hw->pdata = pdata = dev_get_platdata(&pdev->dev); hw->dev = &pdev->dev; if (pdata == NULL) { dev_err(&pdev->dev, "No platform data supplied\n"); err = -ENOENT; goto err_no_pdata; } platform_set_drvdata(pdev, hw);//將SPI控制器私有數據作為平台設備驅動數據,便於通過相應接口獲得 init_completion(&hw->done);//初始化完成接口 /* initialise fiq handler */ s3c24xx_spi_initfiq(hw); /* setup the master state. */ /* the spi->mode bits understood by this driver: */ master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH; master->num_chipselect = hw->pdata->num_cs;//設置控制器片選總數和總線編號 master->bus_num = pdata->bus_num; /* setup the state for the bitbang driver 初始化bitbang驅動的相關成員*/ hw->bitbang.master = hw->master; hw->bitbang.setup_transfer = s3c24xx_spi_setupxfer; hw->bitbang.chipselect = s3c24xx_spi_chipsel; hw->bitbang.txrx_bufs = s3c24xx_spi_txrx; hw->master->setup = s3c24xx_spi_setup; hw->master->cleanup = s3c24xx_spi_cleanup; dev_dbg(hw->dev, "bitbang at %p\n", &hw->bitbang); /* find and map our resources 這是平台驅動中最常規的工作,找到並映射資源*/ res = platform_get_resource(pdev, IORESOURCE_MEM, 0); hw->regs = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(hw->regs)) { err = PTR_ERR(hw->regs); goto err_no_pdata; } hw->irq = platform_get_irq(pdev, 0); if (hw->irq < 0) { dev_err(&pdev->dev, "No IRQ specified\n"); err = -ENOENT; goto err_no_pdata; } err = devm_request_irq(&pdev->dev, hw->irq, s3c24xx_spi_irq, 0, pdev->name, hw); if (err) { dev_err(&pdev->dev, "Cannot claim IRQ\n"); goto err_no_pdata; } hw->clk = devm_clk_get(&pdev->dev, "spi");//獲取SPI的時鐘資源 if (IS_ERR(hw->clk)) { dev_err(&pdev->dev, "No clock for device\n"); err = PTR_ERR(hw->clk); goto err_no_pdata; } /* setup any gpio we can 設置片選方法並配置片選引腳 */ if (!pdata->set_cs) { if (pdata->pin_cs < 0) { dev_err(&pdev->dev, "No chipselect pin\n"); err = -EINVAL; goto err_register; } err = devm_gpio_request(&pdev->dev, pdata->pin_cs, dev_name(&pdev->dev)); if (err) { dev_err(&pdev->dev, "Failed to get gpio for cs\n"); goto err_register; } hw->set_cs = s3c24xx_spi_gpiocs; gpio_direction_output(pdata->pin_cs, 1); } else hw->set_cs = pdata->set_cs; s3c24xx_spi_initialsetup(hw);//使能SPI時鐘,初始化2440 SPI控制器寄存器及片選引腳等 /* register our spi controller 注冊SPI控制器,進而完成對控制器對象的分配初始化和注冊,注冊控制器會掃描
board_list鏈表,從中取出spi_board_info創建spi_device設備,因此在執行probe方法時,只要board_list鏈表
上有控制器對應的spi_board_info,就能創建出控制器的設備對象,並與控制器設備驅動匹配,進而創建出用於訪問該控制器的設備文件
*/ err = spi_bitbang_start(&hw->bitbang); if (err) { dev_err(&pdev->dev, "Failed to register SPI master\n"); goto err_register; } return 0; err_register: clk_disable(hw->clk); err_no_pdata: spi_master_put(hw->master); return err; }
Step3,分析實作 SPI 總線通信方法
SPI 控制器通常由 spi_bitbang 完成實際傳輸,其定義如下:
struct spi_bitbang { spinlock_t lock; /*操作工作隊列時使用的自旋鎖*/ u8 busy; u8 use_dma; u8 flags; /* extra spi->mode support */ struct spi_master *master; /* setup_transfer() changes clock and/or wordsize to match settings * for this transfer; zeroes restore defaults from spi_device.為特定的傳輸設置時鐘、字寬等屬性的方法 */ int (*setup_transfer)(struct spi_device *spi, struct spi_transfer *t); void (*chipselect)(struct spi_device *spi, int is_on); #define BITBANG_CS_ACTIVE 1 /* normally nCS, active low */ #define BITBANG_CS_INACTIVE 0 /* txrx_bufs()為實際的傳輸方法 may handle dma mapping for transfers that don't * already have one (transfer.{tx,rx}_dma is zero), or use PIO */ int (*txrx_bufs)(struct spi_device *spi, struct spi_transfer *t); /* txrx_word[SPI_MODE_*]()按字傳輸的方法 just looks like a shift register */ u32 (*txrx_word[4])(struct spi_device *spi, unsigned nsecs, u32 word, u8 bits); };
兩者的通信控制方法不同。從 spi_bitbang 可見,消息傳輸啟動用的是 spi_bibang_txrx_bufs(),在 2440 驅動中由 s3c24xx_spi_txrx() 實作:它把傳輸段中請求資料的緩衝區與長度賦值給 s3c24xx_spi 的相關成員,主動送出一個位元組啟動傳輸,之後用行程阻塞在完成接口 s3c24xx_spi.done 上,其餘資料的傳輸在中斷處理函數中完成,中斷檢查到送完後通知完成接口、喚醒阻塞的行程(特別說明:6410 的 SPI 通信與 2440 不同,採用 DMA 傳輸,實作函數為 s3c64xx_spi_transfer(),利用工作隊列做延遲調度)。m25p80 的 SPI 通信詳見下文;需說明的是 spi_message 可同步也可異步傳輸,正式產品基本都是異步,傳輸結束由 spi_message.complete() 完成,下面以同步做簡單示範:
#include <linux/platform_device.h> #include <linux/spi/spi.h> #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/interrupt.h> #include <linux/mutex.h> #include <linux/slab.h> // kzalloc #include <linux/delay.h> #define FLASH_PAGE_SIZE 256 /* Flash Operating Commands */ #define CMD_READ_ID 0x9f #define CMD_WRITE_ENABLE 0x06 #define CMD_BULK_ERASE 0xc7 #define CMD_READ_BYTES 0x03 #define CMD_PAGE_PROGRAM 0x02 #define CMD_RDSR 0x05 /* Status Register bits. */ #define SR_WIP 1 /* Write in progress */ #define SR_WEL 2 /* Write enable latch */ /* ID Numbers */ #define MANUFACTURER_ID 0x20 #define DEVICE_ID 0x1120 /* Define max times to check status register before we give up. */ #define MAX_READY_WAIT_COUNT 100000 #define CMD_SZ 4 struct m25p10a { struct spi_device *spi; struct mutex lock; char erase_opcode; char cmd[ CMD_SZ ]; }; /* * Internal Helper functions */ /* * Read the status register, returning its value in the location * Return the status register value. * Returns negative if error occurred. */ static int read_sr(struct m25p10a *flash) { ssize_t retval; u8 code = CMD_RDSR; u8 val; retval = spi_write_then_read(flash->spi, &code, 1, &val, 1); if (retval < 0) { dev_err(&flash->spi->dev, "error %d reading SR\n", (int) retval); return retval; } return val; } /* * Service routine to read status register until ready, or timeout occurs. * Returns non-zero if error. */ static int wait_till_ready(struct m25p10a *flash) { int count; int sr; /* one chip guarantees max 5 msec wait here after page writes, * but potentially three seconds (!) after page erase. */ for (count = 0; count < MAX_READY_WAIT_COUNT; count++) { if ((sr = read_sr(flash)) < 0) break; else if (!(sr & SR_WIP)) return 0; /* REVISIT sometimes sleeping would be best */ } printk( "in (%s): count = %d\n", count ); return 1; } /* * Set write enable latch with Write Enable command. * Returns negative if error occurred. */ static inline int write_enable( struct m25p10a *flash ) { flash->cmd[0] = CMD_WRITE_ENABLE; return spi_write( flash->spi, flash->cmd, 1 ); } /* * Erase the whole flash memory * * Returns 0 if successful, non-zero otherwise. */ static int erase_chip( struct m25p10a *flash ) { /* Wait until finished previous write command. */ if (wait_till_ready(flash)) return -1; /* Send write enable, then erase commands. */ write_enable( flash ); flash->cmd[0] = CMD_BULK_ERASE; return spi_write( flash->spi, flash->cmd, 1 ); } /* * Read an address range from the flash chip. The address range * may be any size provided it is within the physical boundaries. */ static int m25p10a_read( struct m25p10a *flash, loff_t from, size_t len, char *buf ) { int r_count = 0, i; flash->cmd[0] = CMD_READ_BYTES; flash->cmd[1] = from >> 16; flash->cmd[2] = from >> 8; flash->cmd[3] = from; #if 1 struct spi_transfer st[2]; struct spi_message msg; spi_message_init( &msg ); memset( st, 0, sizeof(st) ); flash->cmd[0] = CMD_READ_BYTES; flash->cmd[1] = from >> 16; flash->cmd[2] = from >> 8; flash->cmd[3] = from; st[ 0 ].tx_buf = flash->cmd; st[ 0 ].len = CMD_SZ; spi_message_add_tail( &st[0], &msg ); st[ 1 ].rx_buf = buf; st[ 1 ].len = len; spi_message_add_tail( &st[1], &msg ); mutex_lock( &flash->lock ); /* Wait until finished previous write command. */ if (wait_till_ready(flash)) { mutex_unlock( &flash->lock ); return -1; } spi_sync( flash->spi, &msg ); r_count = msg.actual_length - CMD_SZ; printk( "in (%s): read %d bytes\n", __func__, r_count ); for( i = 0; i < r_count; i++ ) { printk( "0x%02x\n", buf[ i ] ); } mutex_unlock( &flash->lock ); #endif return 0; } /* * Write an address range to the flash chip. Data must be written in * FLASH_PAGE_SIZE chunks. The address range may be any size provided * it is within the physical boundaries. */ static int m25p10a_write( struct m25p10a *flash, loff_t to, size_t len, const char *buf ) { int w_count = 0, i, page_offset; struct spi_transfer st[2]; struct spi_message msg; #if 1 if (wait_till_ready(flash)) { //讀狀態,等待ready mutex_unlock( &flash->lock ); return -1; } #endif write_enable( flash ); //寫使能 spi_message_init( &msg ); memset( st, 0, sizeof(st) ); flash->cmd[0] = CMD_PAGE_PROGRAM; flash->cmd[1] = to >> 16; flash->cmd[2] = to >> 8; flash->cmd[3] = to; st[ 0 ].tx_buf = flash->cmd; st[ 0 ].len = CMD_SZ; spi_message_add_tail( &st[0], &msg ); st[ 1 ].tx_buf = buf; st[ 1 ].len = len; spi_message_add_tail( &st[1], &msg ); mutex_lock( &flash->lock ); /* get offset address inside a page */ page_offset = to % FLASH_PAGE_SIZE; /* do all the bytes fit onto one page? */ if( page_offset + len <= FLASH_PAGE_SIZE ) { // yes st[ 1 ].len = len; printk("%d, cmd = %d\n", st[ 1 ].len, *(char *)st[0].tx_buf); //while(1) { spi_sync( flash->spi, &msg ); } w_count = msg.actual_length - CMD_SZ; } else { // no } printk( "in (%s): write %d bytes to flash in total\n", __func__, w_count ); mutex_unlock( &flash->lock ); return 0; } static int check_id( struct m25p10a *flash ) { char buf[10] = {0}; flash->cmd[0] = CMD_READ_ID; spi_write_then_read( flash->spi, flash->cmd, 1, buf, 3 ); printk( "Manufacture ID: 0x%x\n", buf[0] ); printk( "Device ID: 0x%x\n", buf[1] | buf[2] << 8 ); return buf[2] << 16 | buf[1] << 8 | buf[0]; } static int m25p10a_probe(struct spi_device *spi) { int ret = 0; struct m25p10a *flash; char buf[ 256 ]; printk( "%s was called\n", __func__ ); flash = kzalloc( sizeof(struct m25p10a), GFP_KERNEL ); if( !flash ) { return -ENOMEM; } flash->spi = spi; mutex_init( &flash->lock ); /* save flash as driver's private data */ spi_set_drvdata( spi, flash ); check_id( flash ); //讀取ID #if 1 ret = erase_chip( flash ); //擦除 if( ret < 0 ) { printk( "erase the entirely chip failed\n" ); } printk( "erase the whole chip done\n" ); memset( buf, 0x7, 256 ); m25p10a_write( flash, 0, 20, buf); //0地址寫入20個7 memset( buf, 0, 256 ); m25p10a_read( flash, 0, 25, buf ); //0地址讀出25個數 #endif return 0; } static int m25p10a_remove(struct spi_device *spi) { return 0; } static struct spi_driver m25p10a_driver = { .probe = m25p10a_probe, .remove = m25p10a_remove, .driver = { .name = "m25p10a", }, }; static int __init m25p10a_init(void) { return spi_register_driver(&m25p10a_driver); } static void __exit m25p10a_exit(void) { spi_unregister_driver(&m25p10a_driver); } module_init(m25p10a_init); module_exit(m25p10a_exit); MODULE_DESCRIPTION("m25p10a driver for FS_S5PC100"); MODULE_LICENSE("GPL");
參考文獻 1.《深入 Linux 內核架構》 2.《Linux 設備驅動開發詳解》