Linux IIC設備驅動剖析

本文轉載,自己稍加修改。

寫在前面

      由於IIC總線只需要兩根線就可以完成讀寫操作,而且通信協議簡單,一條總線上可以掛載多個設備,因此被廣泛使用。但是IIC總線有一個缺點,就是傳輸速率比較低。本文基於Linux-2.6.36版本,說說IIC子系統在Linux中的實現。

      IIC子系統框架分爲3各部分:

 1. I2C核心:I2C總線和I2C設備驅動的中間樞紐,它爲I2C總線和設備驅動提供了註冊、註銷等方法。

 2. I2C總線驅動(I2C控制器驅動):對I2C硬件體系中適配器端的實現,控制器可以在CPU內部,也可以集成在CPU內部。     

主要包含:

  •  I2C適配器數據結構i2c_adapter、
  •  I2C適配器的Algorithm數據結構i2c_algorithm
  •  控制I2C適配器產生通信信號的函數

      經由I2C總線驅動的代碼,我們可以控制I2C適配器以主控的方式產生開始位、停止位、讀寫週期,以及以從設備方式被讀寫、產生ACK。

 3. I2C設備驅動(客戶驅動):對I2C從設備驅動實現,如:AT24C02的驅動。

     借用某書上的IIC子系統的體系結構圖:

                            Linux IIC子系統體系結構

       下面開始分析IIC子系統。

      IIC子系統的初始化在drivers/i2c/i2c-core.c文件中的i2c_init函數中:

複製代碼
00001221 static int __init i2c_init(void)
00001222 {
00001223     int retval;
00001224 
00001225     retval = bus_register(&i2c_bus_type);
00001226     if (retval)
00001227         return retval;
00001228 #ifdef CONFIG_I2C_COMPAT
00001229     i2c_adapter_compat_class = class_compat_register("i2c-adapter");
00001230     if (!i2c_adapter_compat_class) {
00001231         retval = -ENOMEM;
00001232         goto bus_err;
00001233     }
00001234 #endif
00001235     retval = i2c_add_driver(&dummy_driver);
00001236     if (retval)
00001237         goto class_err;
00001238     return 0;
00001239 
00001240 class_err:
00001241 #ifdef CONFIG_I2C_COMPAT
00001242     class_compat_unregister(i2c_adapter_compat_class);
00001243 bus_err:
00001244 #endif
00001245     bus_unregister(&i2c_bus_type);
00001246     return retval;
00001247 }
複製代碼

1225行,向系統註冊IIC總線,其中i2c_bus_type的定義爲:

複製代碼
00000343 struct bus_type i2c_bus_type = {
00000344     .name        = "i2c",
00000345     .match        = i2c_device_match,
00000346     .probe        = i2c_device_probe,
00000347     .remove        = i2c_device_remove,
00000348     .shutdown    = i2c_device_shutdown,
00000349     .pm        = &i2c_device_pm_ops,
00000350 };
複製代碼

345行,i2c_device_match函數時用來匹配IIC總線上的設備和設備驅動的,下面看下它的定義:

複製代碼
00000068 static int i2c_device_match(struct device *dev, struct device_driver *drv)
00000069 {
00000070     struct i2c_client    *client = i2c_verify_client(dev);
00000071     struct i2c_driver    *driver;
00000072 
00000073     if (!client)
00000074         return 0;
00000075 
00000076     /* Attempt an OF style match */
00000077     if (of_driver_match_device(dev, drv))
00000078         return 1;
00000079 
00000080     driver = to_i2c_driver(drv);
00000081     /* match on an id table if there is one */
00000082     if (driver->id_table)
00000083         return i2c_match_id(driver->id_table, client) != NULL;
00000084 
00000085     return 0;
00000086 }
複製代碼

在IIC子系統中,用struct i2c_client來描述一個具體的IIC設備(IIC從機)。73行,如果沒有IIC設備的話就直接返回0,表示匹配不成功。

77行,用of的方式進行匹配,應該是設備樹方面的,具體沒了解過。

82行,如果驅動的id table存在則調用83行的i2c_match_id函數進行匹配:

複製代碼
00000057 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
00000058                         const struct i2c_client *client)
00000059 {
00000060     while (id->name[0]) {
00000061         if (strcmp(client->name, id->name) == 0)
00000062             return id;
00000063         id++;
00000064     }
00000065     return NULL;
00000066 }
複製代碼

很簡單,就是拿驅動的id table中的每一項與i2c_client的name成員進行比較,如果它們的名字相同就表示匹配成功,否則匹配失敗,返回NULL。從這裏也可以看出IIC的總線匹配方式與platform總線的匹配方式是不一樣,一般情況下,IIC總線的匹配方式是根據設備名字和驅動中的id table,而platfrom總線的匹配方式是根據設備名字和驅動名字。下面看i2c_device_probe函數:

複製代碼
00000106 static int i2c_device_probe(struct device *dev)
00000107 {
00000108     struct i2c_client    *client = i2c_verify_client(dev);
00000109     struct i2c_driver    *driver;
00000110     int status;
00000111 
00000112     if (!client)
00000113         return 0;
00000114 
00000115     driver = to_i2c_driver(dev->driver);
00000116     if (!driver->probe || !driver->id_table)
00000117         return -ENODEV;
00000118     client->driver = driver;
00000119     if (!device_can_wakeup(&client->dev))
00000120         device_init_wakeup(&client->dev,
00000121                     client->flags & I2C_CLIENT_WAKE);
00000122     dev_dbg(dev, "probe\n");
00000123 
00000124     status = driver->probe(client, i2c_match_id(driver->id_table, client));
00000125     if (status) {
00000126         client->driver = NULL;
00000127         i2c_set_clientdata(client, NULL);
00000128     }
00000129     return status;
00000130 }
複製代碼

112行,檢查IIC設備是否存在。

119至121行,電源管理方面的,IIC在電源管理方面做得還是不錯的,有興趣可以看一下。

124行,重要,調用IIC設備驅動中probe函數。

     下面以tiny6410爲具體平臺去說IIC子系統的其他內容。S3c6410的IIC控制器驅動位於drivers/i2c/busses/i2c-s3c2410.c文件中,首先看初始化函數:

複製代碼
00001009 static struct platform_driver s3c24xx_i2c_driver = {
00001010     .probe        = s3c24xx_i2c_probe,
00001011     .remove        = s3c24xx_i2c_remove,
00001012     .id_table    = s3c24xx_driver_ids,
00001013     .driver        = {
00001014         .owner    = THIS_MODULE,
00001015         .name    = "s3c-i2c",
00001016         .pm    = S3C24XX_DEV_PM_OPS,
00001017     },
00001018 };
00001019 
00001020 static int __init i2c_adap_s3c_init(void)
00001021 {
00001022     return platform_driver_register(&s3c24xx_i2c_driver);
00001023 }
00001024 subsys_initcall(i2c_adap_s3c_init);
複製代碼

1022行,註冊平臺驅動,看下s3c24xx_i2c_driver的定義可以發現.driver.name的值與板文件中定義的platform device的name不一樣,所以這裏採用的是id table方式進行匹配。我們知道,當此驅動與設備匹配後,驅動中的probe函數將會被調用,那麼下面看probe函數的定義:

複製代碼
00000790 static int s3c24xx_i2c_probe(struct platform_device *pdev)
00000791 {
00000792     struct s3c24xx_i2c *i2c;
00000793     struct s3c2410_platform_i2c *pdata;
00000794     struct resource *res;
00000795     int ret;
00000796 
00000797     pdata = pdev->dev.platform_data;
00000798     if (!pdata) {
00000799         dev_err(&pdev->dev, "no platform data\n");
00000800         return -EINVAL;
00000801     }
00000802 
00000803     i2c = kzalloc(sizeof(struct s3c24xx_i2c), GFP_KERNEL);
00000804     if (!i2c) {
00000805         dev_err(&pdev->dev, "no memory for state\n");
00000806         return -ENOMEM;
00000807     }
00000808 
00000809     strlcpy(i2c->adap.name, "s3c2410-i2c", sizeof(i2c->adap.name));
00000810     i2c->adap.owner   = THIS_MODULE;
00000811     i2c->adap.algo    = &s3c24xx_i2c_algorithm;
00000812     i2c->adap.retries = 2;
00000813     i2c->adap.class   = I2C_CLASS_HWMON | I2C_CLASS_SPD;
00000814     i2c->tx_setup     = 50;
00000815 
00000816     spin_lock_init(&i2c->lock);
00000817     init_waitqueue_head(&i2c->wait);
00000818 
00000819     /* find the clock and enable it */
00000820 
00000821     i2c->dev = &pdev->dev;
00000822     i2c->clk = clk_get(&pdev->dev, "i2c");
00000823     if (IS_ERR(i2c->clk)) {
00000824         dev_err(&pdev->dev, "cannot get clock\n");
00000825         ret = -ENOENT;
00000826         goto err_noclk;
00000827     }
00000828 
00000829     dev_dbg(&pdev->dev, "clock source %p\n", i2c->clk);
00000830 
00000831     clk_enable(i2c->clk);
00000832 
00000833     /* map the registers */
00000834 
00000835     res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
00000836     if (res == NULL) {
00000837         dev_err(&pdev->dev, "cannot find IO resource\n");
00000838         ret = -ENOENT;
00000839         goto err_clk;
00000840     }
00000841 
00000842     i2c->ioarea = request_mem_region(res->start, resource_size(res),
00000843                      pdev->name);
00000844 
00000845     if (i2c->ioarea == NULL) {
00000846         dev_err(&pdev->dev, "cannot request IO\n");
00000847         ret = -ENXIO;
00000848         goto err_clk;
00000849     }
00000850 
00000851     i2c->regs = ioremap(res->start, resource_size(res));
00000852 
00000853     if (i2c->regs == NULL) {
00000854         dev_err(&pdev->dev, "cannot map IO\n");
00000855         ret = -ENXIO;
00000856         goto err_ioarea;
00000857     }
00000858 
00000859     dev_dbg(&pdev->dev, "registers %p (%p, %p)\n",
00000860         i2c->regs, i2c->ioarea, res);
00000861 
00000862     /* setup info block for the i2c core */
00000863 
00000864     i2c->adap.algo_data = i2c;
00000865     i2c->adap.dev.parent = &pdev->dev;
00000866 
00000867     /* initialise the i2c controller */
00000868 
00000869     ret = s3c24xx_i2c_init(i2c);
00000870     if (ret != 0)
00000871         goto err_iomap;
00000872 
00000873     /* find the IRQ for this unit (note, this relies on the init call to
00000874      * ensure no current IRQs pending
00000875      */
00000876 
00000877     i2c->irq = ret = platform_get_irq(pdev, 0);
00000878     if (ret <= 0) {
00000879         dev_err(&pdev->dev, "cannot find IRQ\n");
00000880         goto err_iomap;
00000881     }
00000882 
00000883     ret = request_irq(i2c->irq, s3c24xx_i2c_irq, IRQF_DISABLED,
00000884               dev_name(&pdev->dev), i2c);
00000885 
00000886     if (ret != 0) {
00000887         dev_err(&pdev->dev, "cannot claim IRQ %d\n", i2c->irq);
00000888         goto err_iomap;
00000889     }
00000890 
00000891     ret = s3c24xx_i2c_register_cpufreq(i2c);
00000892     if (ret < 0) {
00000893         dev_err(&pdev->dev, "failed to register cpufreq notifier\n");
00000894         goto err_irq;
00000895     }
00000896 
00000897     /* Note, previous versions of the driver used i2c_add_adapter()
00000898      * to add the bus at any number. We now pass the bus number via
00000899      * the platform data, so if unset it will now default to always
00000900      * being bus 0.
00000901      */
00000902 
00000903     i2c->adap.nr = pdata->bus_num;
00000904 
00000905     ret = i2c_add_numbered_adapter(&i2c->adap);
00000906     if (ret < 0) {
00000907         dev_err(&pdev->dev, "failed to add bus to i2c core\n");
00000908         goto err_cpufreq;
00000909     }
00000910 
00000911     platform_set_drvdata(pdev, i2c);
00000912 
00000913     dev_info(&pdev->dev, "%s: S3C I2C adapter\n", dev_name(&i2c->adap.dev));
00000914     return 0;
00000915 
00000916  err_cpufreq:
00000917     s3c24xx_i2c_deregister_cpufreq(i2c);
00000918 
00000919  err_irq:
00000920     free_irq(i2c->irq, i2c);
00000921 
00000922  err_iomap:
00000923     iounmap(i2c->regs);
00000924 
00000925  err_ioarea:
00000926     release_resource(i2c->ioarea);
00000927     kfree(i2c->ioarea);
00000928 
00000929  err_clk:
00000930     clk_disable(i2c->clk);
00000931     clk_put(i2c->clk);
00000932 
00000933  err_noclk:
00000934     kfree(i2c);
00000935     return ret;
00000936 }
複製代碼

797至801行,沒有平臺數據是不行的。

803至807行,爲具體平臺的IIC控制器數據結構申請內存,一般來說,不僅是IIC控制器,每一個控制器都會有一個結構體來描述。struct s3c24xx_i2c的定義也是在drivers/i2c/busses/i2c-s3c2410.c中:

複製代碼
00000060 struct s3c24xx_i2c {
00000061     spinlock_t        lock;
00000062     wait_queue_head_t    wait;
00000063     unsigned int        suspended:1;
00000064 
00000065     struct i2c_msg        *msg;
00000066     unsigned int        msg_num;
00000067     unsigned int        msg_idx;
00000068     unsigned int        msg_ptr;
00000069 
00000070     unsigned int        tx_setup;
00000071     unsigned int        irq;
00000072 
00000073     enum s3c24xx_i2c_state    state;
00000074     unsigned long        clkrate;
00000075 
00000076     void __iomem        *regs;
00000077     struct clk        *clk;
00000078     struct device        *dev;
00000079     struct resource        *ioarea;
00000080     struct i2c_adapter    adap;
00000081 
00000082 #ifdef CONFIG_CPU_FREQ
00000083     struct notifier_block    freq_transition;
00000084 #endif
00000085 };
複製代碼

63行,表示IIC控制器是否已經掛起,掛起的話就不能操作IIC控制器了。

65行,struct i2c_msg用來描述一次讀寫操作包含的信息。定義在include/linux/i2c.h,比較簡單:

複製代碼
00000507 struct i2c_msg {
00000508     __u16 addr;    /* slave address            */
00000509     __u16 flags;
00000510 #define I2C_M_TEN        0x0010    /* this is a ten bit chip address */
00000511 #define I2C_M_RD        0x0001    /* read data, from slave to master */
00000512 #define I2C_M_NOSTART        0x4000    /* if I2C_FUNC_PROTOCOL_MANGLING */
00000513 #define I2C_M_REV_DIR_ADDR    0x2000    /* if I2C_FUNC_PROTOCOL_MANGLING */
00000514 #define I2C_M_IGNORE_NAK    0x1000    /* if I2C_FUNC_PROTOCOL_MANGLING */
00000515 #define I2C_M_NO_RD_ACK        0x0800    /* if I2C_FUNC_PROTOCOL_MANGLING */
00000516 #define I2C_M_RECV_LEN        0x0400    /* length will be first received byte */
00000517     __u16 len;        /* msg length                */
00000518     __u8 *buf;        /* pointer to msg data            */
00000519 };
複製代碼

508行,IIC從機的地址。

509行,flags的取值就是510至516行這些值。

517行,這次讀寫操作的數據長度。518行,讀寫數據的地址。

      回到struct s3c24xx_i2c,66行,message的數量。67行,當前是第幾個message。68行,緩衝區數組成員的索引值,表示當前要讀寫的是第幾個數據。

70行,當數據寫入IIC控制器的數據移位寄存器後需要延時多久,在s3c6410裏的單位是ns。

71行,IIC控制器使用的中斷號。

73行,IIC控制器的狀態,具體來說有以下幾種狀態:

複製代碼
00000047 enum s3c24xx_i2c_state {
00000048     STATE_IDLE,
00000049     STATE_START,
00000050     STATE_READ,
00000051     STATE_WRITE,
00000052     STATE_STOP
00000053 };
複製代碼

74行,IIC總線的速率。76行,IIC控制器寄存器起始地址。

77行,IIC控制器時鐘。78行,設備模型相關的。79行,IO口資源。

80行,每一個IIC控制器對應一個adapter。struct i2c_adapter同樣是在include/linux/i2c.h中定義:

複製代碼
00000354 struct i2c_adapter {
00000355     struct module *owner;
00000356     unsigned int id;
00000357     unsigned int class;          /* classes to allow probing for */
00000358     const struct i2c_algorithm *algo; /* the algorithm to access the bus */
00000359     void *algo_data;
00000360 
00000361     /* data fields that are valid for all devices    */
00000362     struct rt_mutex bus_lock;
00000363 
00000364     int timeout;            /* in jiffies */
00000365     int retries;
00000366     struct device dev;        /* the adapter device */
00000367 
00000368     int nr;
00000369     char name[48];
00000370     struct completion dev_released;
00000371 
00000372     struct mutex userspace_clients_lock;
00000373     struct list_head userspace_clients;
00000374 };
複製代碼

355行,模塊的所有者。

356行,此適配器的編號,第1個適配器的編號爲0,以此類推。

358行,算法?第一眼看到的時候差點被嚇倒了,其實就是定義了3個函數指針,這些函數來完成具體的讀寫操作。

364行,超時時間。365行,重試次數,一次讀寫操作不成功的話就多試幾次。368行,適配器編號。369行,適配器的名字。

     回到s3c24xx_i2c_probe函數,809行,設置適配器的名字。

811行,s3c6410的IIC控制器進行讀寫操作時所使用的邏輯,等碰到時再詳細說吧。

813行,剛纔在說struct i2c_adapter時被忽略的成員class就是在這裏被賦值的。

814行,對於s3c6410的IIC控制器而言,數據被寫入移位寄存器後需要延時50ns。

822至831行,獲取IIC時鐘並使能。

835至857行,獲取IO口資源並進行映射。

869行,設置相應的IO口爲IIC功能,並設置IICADD寄存器和IICCON寄存器。

877至889行,申請IIC中斷,中斷處理函數爲s3c24xx_i2c_irq,後面會遇到,到時再說。

891至895行,CPU頻率相關的,略過吧。

905行,“重頭戲”啊,註冊IIC適配器和註冊IIC設備等都發生在裏面,i2c_add_numbered_adapter函數在drivers/i2c/i2c-core.c裏定義:

複製代碼
00000948 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
00000949 {
00000950     int    id;
00000951     int    status;
00000952 
00000953     if (adap->nr & ~MAX_ID_MASK)
00000954         return -EINVAL;
00000955 
00000956 retry:
00000957     if (idr_pre_get(&i2c_adapter_idr, GFP_KERNEL) == 0)
00000958         return -ENOMEM;
00000959 
00000960     mutex_lock(&core_lock);
00000961     /* "above" here means "above or equal to", sigh;
00000962      * we need the "equal to" result to force the result
00000963      */
00000964     status = idr_get_new_above(&i2c_adapter_idr, adap, adap->nr, &id);
00000965     if (status == 0 && id != adap->nr) {
00000966         status = -EBUSY;
00000967         idr_remove(&i2c_adapter_idr, id);
00000968     }
00000969     mutex_unlock(&core_lock);
00000970     if (status == -EAGAIN)
00000971         goto retry;
00000972 
00000973     if (status == 0)
00000974         status = i2c_register_adapter(adap);
00000975     return status;
00000976 }
複製代碼

953行,適配器的編號大於MAX_ID_MASK是不行的,MAX_ID_MASK是一個宏,展開後的值爲61。

957至968行,關於管理小整形ID數的,沒怎麼了解,略過。

974行,調用i2c_register_adapter函數註冊IIC適配器,下面是它的定義:

複製代碼
00000837 static int i2c_register_adapter(struct i2c_adapter *adap)
00000838 {
00000839     int res = 0;
00000840 
00000841     /* Can't register until after driver model init */
00000842     if (unlikely(WARN_ON(!i2c_bus_type.p))) {
00000843         res = -EAGAIN;
00000844         goto out_list;
00000845     }
00000846 
00000847     rt_mutex_init(&adap->bus_lock);
00000848     mutex_init(&adap->userspace_clients_lock);
00000849     INIT_LIST_HEAD(&adap->userspace_clients);
00000850 
00000851     /* Set default timeout to 1 second if not already set */
00000852     if (adap->timeout == 0)
00000853         adap->timeout = HZ;
00000854 
00000855     dev_set_name(&adap->dev, "i2c-%d", adap->nr);
00000856     adap->dev.bus = &i2c_bus_type;
00000857     adap->dev.type = &i2c_adapter_type;
00000858     res = device_register(&adap->dev);
00000859     if (res)
00000860         goto out_list;
00000861 
00000862     dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
00000863 
00000864 #ifdef CONFIG_I2C_COMPAT
00000865     res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
00000866                        adap->dev.parent);
00000867     if (res)
00000868         dev_warn(&adap->dev,
00000869              "Failed to create compatibility class link\n");
00000870 #endif
00000871 
00000872     /* create pre-declared device nodes */
00000873     if (adap->nr < __i2c_first_dynamic_bus_num)
00000874         i2c_scan_static_board_info(adap);
00000875 
00000876     /* Notify drivers */
00000877     mutex_lock(&core_lock);
00000878     bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
00000879     mutex_unlock(&core_lock);
00000880 
00000881     return 0;
00000882 
00000883 out_list:
00000884     mutex_lock(&core_lock);
00000885     idr_remove(&i2c_adapter_idr, adap->nr);
00000886     mutex_unlock(&core_lock);
00000887     return res;
00000888 }
複製代碼

842至845行,i2c_bus_type的私有成員p在IIC子系統初始化時在bus_register函數裏已經被初始化了,因此if條件不會成立,可以繼續往下走。

848、849行,之前說struct i2c_adapter時被略過的最後兩個成員在這裏被初始化。

852、853行,如果timeout沒有設置,那麼就給它個默認值HZ。一路走來可以發現,timeout在這裏會被設置成HZ。

858行,註冊適配器這個設備。

864至870行,兼容性方面的,略過。

874行,調用i2c_scan_static_board_info函數註冊所有在板文件裏定義的設備,下面看它的定義:

複製代碼
00000802 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
00000803 {
00000804     struct i2c_devinfo    *devinfo;
00000805 
00000806     down_read(&__i2c_board_lock);
00000807     list_for_each_entry(devinfo, &__i2c_board_list, list) {
00000808         if (devinfo->busnum == adapter->nr
00000809                 && !i2c_new_device(adapter,
00000810                         &devinfo->board_info))
00000811             dev_err(&adapter->dev,
00000812                 "Can't create device at 0x%02x\n",
00000813                 devinfo->board_info.addr);
00000814     }
00000815     up_read(&__i2c_board_lock);
00000816 }
複製代碼

807行,遍歷__i2c_board_list鏈表,每找到一個成員就調用i2c_new_device函數創建一個IIC從機設備,下面是i2c_new_device函數的定義:

複製代碼
00000523 struct i2c_client *
00000524 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
00000525 {
00000526     struct i2c_client    *client;
00000527     int            status;
00000528 
00000529     client = kzalloc(sizeof *client, GFP_KERNEL);
00000530     if (!client)
00000531         return NULL;
00000532 
00000533     client->adapter = adap;
00000534 
00000535     client->dev.platform_data = info->platform_data;
00000536 
00000537     if (info->archdata)
00000538         client->dev.archdata = *info->archdata;
00000539 
00000540     client->flags = info->flags;
00000541     client->addr = info->addr;
00000542     client->irq = info->irq;
00000543 
00000544     strlcpy(client->name, info->type, sizeof(client->name));
00000545 
00000546     /* Check for address validity */
00000547     status = i2c_check_client_addr_validity(client);
00000548     if (status) {
00000549         dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
00000550             client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
00000551         goto out_err_silent;
00000552     }
00000553 
00000554     /* Check for address business */
00000555     status = i2c_check_addr_busy(adap, client->addr);
00000556     if (status)
00000557         goto out_err;
00000558 
00000559     client->dev.parent = &client->adapter->dev;
00000560     client->dev.bus = &i2c_bus_type;
00000561     client->dev.type = &i2c_client_type;
00000562 #ifdef CONFIG_OF
00000563     client->dev.of_node = info->of_node;
00000564 #endif
00000565 
00000566     dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
00000567              client->addr);
00000568     status = device_register(&client->dev);
00000569     if (status)
00000570         goto out_err;
00000571 
00000572     dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
00000573         client->name, dev_name(&client->dev));
00000574 
00000575     return client;
00000576 
00000577 out_err:
00000578     dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
00000579         "(%d)\n", client->name, client->addr, status);
00000580 out_err_silent:
00000581     kfree(client);
00000582     return NULL;
00000583 }
複製代碼

529行,爲IIC從機設備結構體申請內存。

533至542行,一些賦值。

544行,爲client的name成員賦值,IIC總線的match函數能否匹配成功就要看這裏了。從這裏也可以知道如何讓板文件裏定義的設備與驅動匹配起來。

547行,檢查IIC從機設備地址的合法性,怎樣才合法?如果從機使用十位地址的話,那麼地址的最大值不能大於0x3ff;如果使用的是七位地址,那麼地址的最大值不能大於0x7f,也不能爲0。

555行,檢查當前IIC從機設備的地址有沒有被使用,一條IIC總線或者一個IIC適配器上可以掛多個從機設備,靠設備的地址來識別不同的設備,因此一條總線上不能有兩個同樣地址的設備。

561行,設備的類型,IIC從機設備在IIC子系統裏屬於client類型。

568行,將IIC從機設備註冊進系統。

      回到i2c_register_adapter函數,878行,遍歷IIC總線上的所有已經註冊了的驅動,每找到一個就調用__process_new_adapter函數進行處理,__process_new_adapter函數的定義如下:

00000832 static int __process_new_adapter(struct device_driver *d, void *data)
00000833 {
00000834     return i2c_do_add_adapter(to_i2c_driver(d), data);
00000835 }

裏面就是調用i2c_do_add_adapter函數:

複製代碼
00000818 static int i2c_do_add_adapter(struct i2c_driver *driver,
00000819                   struct i2c_adapter *adap)
00000820 {
00000821     /* Detect supported devices on that bus, and instantiate them */
00000822     i2c_detect(adap, driver);
00000823 
00000824     /* Let legacy drivers scan this bus for matching devices */
00000825     if (driver->attach_adapter) {
00000826         /* We ignore the return code; if it fails, too bad */
00000827         driver->attach_adapter(adap);
00000828     }
00000829     return 0;
00000830 }
複製代碼

822行,檢查驅動是否能夠與該適配器所在總線上的設備匹配。

825行,如果驅動的attach_adapter函數有定義就調用之,這主要針對舊的驅動,像i2c-dev.c就是使用這種方式來驅動IIC適配器的,這個函數指針在將來可能會被移除。

      到這裏,說完了s3c6410的IIC控制器驅動的初始化過程。下面開始說drivers/i2c/i2c-dev.c這個通用的i2c驅動,首先看它的初始化函數i2c_dev_init:

複製代碼
00000595 static int __init i2c_dev_init(void)
00000596 {
00000597     int res;
00000598 
00000599     printk(KERN_INFO "i2c /dev entries driver\n");
00000600 
00000601     res = register_chrdev(I2C_MAJOR, "i2c", &i2cdev_fops);
00000602     if (res)
00000603         goto out;
00000604 
00000605     i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
00000606     if (IS_ERR(i2c_dev_class)) {
00000607         res = PTR_ERR(i2c_dev_class);
00000608         goto out_unreg_chrdev;
00000609     }
00000610 
00000611     res = i2c_add_driver(&i2cdev_driver);
00000612     if (res)
00000613         goto out_unreg_class;
00000614 
00000615     return 0;
00000616 
00000617 out_unreg_class:
00000618     class_destroy(i2c_dev_class);
00000619 out_unreg_chrdev:
00000620     unregister_chrdev(I2C_MAJOR, "i2c");
00000621 out:
00000622     printk(KERN_ERR "%s: Driver Initialisation failed\n", __FILE__);
00000623     return res;
00000624 }
複製代碼

601行,註冊IIC設備,主設備號爲I2C_MAJOR,它的值爲89,文件操作結構體對象是i2cdev_fops,定義爲:

複製代碼
00000514 static const struct file_operations i2cdev_fops = {
00000515     .owner        = THIS_MODULE,
00000516     .llseek        = no_llseek,
00000517     .read        = i2cdev_read,
00000518     .write        = i2cdev_write,
00000519     .unlocked_ioctl    = i2cdev_ioctl,
00000520     .open        = i2cdev_open,
00000521     .release    = i2cdev_release,
00000522 };
複製代碼

後面會以i2cdev_ioctl爲例說說它的工作過程。

605至609行,創建IIC設備類,是後面自動創建設備節點的基礎。

611行,添加IIC驅動,起始裏面是對i2c_register_driver函數的包裝,在include/linux/i2c.h裏定義:

00000434 static inline int i2c_add_driver(struct i2c_driver *driver)
00000435 {
00000436     return i2c_register_driver(THIS_MODULE, driver);
00000437 }

這樣就可以省去寫THIS_MODULE,也可以避免忘記寫THIS_MODULE。下面看i2c_register_driver函數的定義,在drivers/i2c/i2c-core.c中:

複製代碼
00001108 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
00001109 {
00001110     int res;
00001111 
00001112     /* Can't register until after driver model init */
00001113     if (unlikely(WARN_ON(!i2c_bus_type.p)))
00001114         return -EAGAIN;
00001115 
00001116     /* add the driver to the list of i2c drivers in the driver core */
00001117     driver->driver.owner = owner;
00001118     driver->driver.bus = &i2c_bus_type;
00001119 
00001120     /* When registration returns, the driver core
00001121      * will have called probe() for all matching-but-unbound devices.
00001122      */
00001123     res = driver_register(&driver->driver);
00001124     if (res)
00001125         return res;
00001126 
00001127     pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
00001128 
00001129     INIT_LIST_HEAD(&driver->clients);
00001130     /* Walk the adapters that are already present */
00001131     mutex_lock(&core_lock);
00001132     bus_for_each_dev(&i2c_bus_type, NULL, driver, __process_new_driver);
00001133     mutex_unlock(&core_lock);
00001134 
00001135     return 0;
00001136 }
複製代碼

1113行,檢查IIC總線的私有數據p是否已經初始化,前面已經說過了,在IIC子系統初始化的時候p就已經被初始化了。

1117、1118行,沒什麼好說的吧。

1123行,將該驅動註冊進系統,經過一層層調用後會調用IIC總線的match函數。

1132行,遍歷IIC總線上的所有設備,每找到一個就調用__process_new_driver函數進行處理,__process_new_driver函數的定義:

00001096 static int __process_new_driver(struct device *dev, void *data)
00001097 {
00001098     if (dev->type != &i2c_adapter_type)
00001099         return 0;
00001100     return i2c_do_add_adapter(data, to_i2c_adapter(dev));
00001101 }

1098行,如果設備不是適配器類型,就表示不是要找的設備,直接返回0。否則調用1100行的i2c_do_add_adapter函數,這個函數前面已經說過了,這裏就不重複了。

我們知道,此驅動註冊進系統後會導致i2cdev_attach_adapter函數被調用,下面看它的定義:

複製代碼
00000534 static int i2cdev_attach_adapter(struct i2c_adapter *adap)
00000535 {
00000536     struct i2c_dev *i2c_dev;
00000537     int res;
00000538 
00000539     i2c_dev = get_free_i2c_dev(adap);
00000540     if (IS_ERR(i2c_dev))
00000541         return PTR_ERR(i2c_dev);
00000542 
00000543     /* register this i2c device with the driver core */
00000544     i2c_dev->dev = device_create(i2c_dev_class, &adap->dev,
00000545                      MKDEV(I2C_MAJOR, adap->nr), NULL,
00000546                      "i2c-%d", adap->nr);
00000547     if (IS_ERR(i2c_dev->dev)) {
00000548         res = PTR_ERR(i2c_dev->dev);
00000549         goto error;
00000550     }
00000551     res = device_create_file(i2c_dev->dev, &dev_attr_name);
00000552     if (res)
00000553         goto error_destroy;
00000554 
00000555     pr_debug("i2c-dev: adapter [%s] registered as minor %d\n",
00000556          adap->name, adap->nr);
00000557     return 0;
00000558 error_destroy:
00000559     device_destroy(i2c_dev_class, MKDEV(I2C_MAJOR, adap->nr));
00000560 error:
00000561     return_i2c_dev(i2c_dev);
00000562     return res;
00000563 }
複製代碼

539行,不要被它的名字所迷惑,看它的定義:

複製代碼
00000076 static struct i2c_dev *get_free_i2c_dev(struct i2c_adapter *adap)
00000077 {
00000078     struct i2c_dev *i2c_dev;
00000079 
00000080     if (adap->nr >= I2C_MINORS) {
00000081         printk(KERN_ERR "i2c-dev: Out of device minors (%d)\n",
00000082                adap->nr);
00000083         return ERR_PTR(-ENODEV);
00000084     }
00000085 
00000086     i2c_dev = kzalloc(sizeof(*i2c_dev), GFP_KERNEL);
00000087     if (!i2c_dev)
00000088         return ERR_PTR(-ENOMEM);
00000089     i2c_dev->adap = adap;
00000090 
00000091     spin_lock(&i2c_dev_list_lock);
00000092     list_add_tail(&i2c_dev->list, &i2c_dev_list);
00000093     spin_unlock(&i2c_dev_list_lock);
00000094     return i2c_dev;
00000095 }
複製代碼

80至84行,如果適配器的編號大於最大的次設備號,那麼就返回出錯。I2C_MINORS的值爲256。

86行,爲i2c_dev對象申請內存。

92行,將i2c_dev對象加入到i2c_dev_list鏈表中。

      回到i2cdev_attach_adapter函數,544行,創建設備節點,主設備號爲I2C_MAJOR,次設備號爲適配器的編號,設備節點的名字爲i2c-x,x的值就是適配器的編號。如果適配器的編號爲0,那麼就會在/dev下創建一個名爲i2c-0的文件,即/dev/i2c-0,但在某些嵌入式Linux平臺上沒有看到這個文件,而是/dev/i2c/0這種形式,原因在於在啓動文件裏調用了mdev –s這條命令,導致/dev/i2c-0變成了/dev/i2c/0,不信?把i2c-x的-去掉,變成i2cx,重新編譯後啓動內核,看生成的是否是/dev/i2cx文件。之所以會造成那樣是因爲字符‘-’引起的。

551行,創建設備文件,關於設備模型的,不多說了。

     到此,i2c-dev.c的初始化過程也說完了。

     某某大俠說得對:“內核代碼就像酒,有的苦有的烈,這樣的滋味你我早晚要體會,請與我舉起杯,與內核乾杯。”多麼形象的比喻!多麼可愛的文字!

     不管多“苦”多“累”,既然認定了前方,路還是要走下去的。



下面以eeprom用戶程序調用ioctl函數的寫操作爲例追蹤IIC子系統的調用過程。eeprom的用戶測試是大部分開發板都自帶的。看寫一個字節數據的eeprom_write_byte函數的定義:

複製代碼
int eeprom_write_byte(struct eeprom *e, __u16 mem_addr, __u8 data)
{
    if(e->type == EEPROM_TYPE_8BIT_ADDR) {
        __u8 buf[2] = { mem_addr & 0x00ff, data };
        return i2c_write_2b(e, buf);
    } else if(e->type == EEPROM_TYPE_16BIT_ADDR) {
        __u8 buf[3] = 
            { (mem_addr >> 8) & 0x00ff, mem_addr & 0x00ff, data };
        return i2c_write_3b(e, buf);
    } 
    fprintf(stderr, "ERR: unknown eeprom type\n");
    return -1;
}
複製代碼

這裏使用的是8位地址,因此調用的是i2c_write_2b函數,爲什麼是2b?這是eeprom規定的,寫數據之前要先寫地址。注意buf[0]=要寫的地址,buf[1]=要寫的字節數據。下面是i2c_write_2b函數的定義:

複製代碼
static int i2c_write_2b(struct eeprom *e, __u8 buf[2])
{
    int r;
    // we must simulate a plain I2C byte write with SMBus functions
    r = i2c_smbus_write_byte_data(e->fd, buf[0], buf[1]);
    if(r < 0)
        fprintf(stderr, "Error i2c_write_2b: %s\n", strerror(errno));
    usleep(10);
    return r;
}
複製代碼

就調用了i2c_smbus_write_byte_data函數,注意參數的含義,下面是它的定義:

複製代碼
static inline __s32 i2c_smbus_write_byte_data(int file, __u8 command, 
                                              __u8 value)
{
    union i2c_smbus_data data;
    data.byte = value;
    return i2c_smbus_access(file,I2C_SMBUS_WRITE,command,
                            I2C_SMBUS_BYTE_DATA, &data);
}
複製代碼

調用了i2c_smbus_access函數,繼續追蹤,看i2c_smbus_access函數的定義:

複製代碼
static inline __s32 i2c_smbus_access(int file, char read_write, __u8 command, 
                                     int size, union i2c_smbus_data *data)
{
    struct i2c_smbus_ioctl_data args;

    args.read_write = read_write;
    args.command = command;
    args.size = size;
    args.data = data;
    return ioctl(file,I2C_SMBUS,&args);
}
複製代碼

首先弄清楚參數的含義,file是使用open打開的文件。read_write表示是讀操作還是寫操作,這裏是寫,所以它的值爲I2C_SMBUS_WRITE。command是要寫的地址。size的值爲I2C_SMBUS_BYTE_DATA。最後一個參數data.byte=要寫的字節數據。

     下面開始進入ioctl系統調用,最後會到達i2c-dev.c中的i2cdev_ioctl函數,看它的定義:

複製代碼
00000396 static long i2cdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
00000397 {
00000398     struct i2c_client *client = file->private_data;
00000399     unsigned long funcs;
00000400 
00000401     dev_dbg(&client->adapter->dev, "ioctl, cmd=0x%02x, arg=0x%02lx\n",
00000402         cmd, arg);
00000403 
00000404     switch (cmd) {
00000405     case I2C_SLAVE:
00000406     case I2C_SLAVE_FORCE:
00000407         /* NOTE:  devices set up to work with "new style" drivers
00000408          * can't use I2C_SLAVE, even when the device node is not
00000409          * bound to a driver.  Only I2C_SLAVE_FORCE will work.
00000410          *
00000411          * Setting the PEC flag here won't affect kernel drivers,
00000412          * which will be using the i2c_client node registered with
00000413          * the driver model core.  Likewise, when that client has
00000414          * the PEC flag already set, the i2c-dev driver won't see
00000415          * (or use) this setting.
00000416          */
00000417         if ((arg > 0x3ff) ||
00000418             (((client->flags & I2C_M_TEN) == 0) && arg > 0x7f))
00000419             return -EINVAL;
00000420         if (cmd == I2C_SLAVE && i2cdev_check_addr(client->adapter, arg))
00000421             return -EBUSY;
00000422         /* REVISIT: address could become busy later */
00000423         client->addr = arg;
00000424         return 0;
00000425     case I2C_TENBIT:
00000426         if (arg)
00000427             client->flags |= I2C_M_TEN;
00000428         else
00000429             client->flags &= ~I2C_M_TEN;
00000430         return 0;
00000431     case I2C_PEC:
00000432         if (arg)
00000433             client->flags |= I2C_CLIENT_PEC;
00000434         else
00000435             client->flags &= ~I2C_CLIENT_PEC;
00000436         return 0;
00000437     case I2C_FUNCS:
00000438         funcs = i2c_get_functionality(client->adapter);
00000439         return put_user(funcs, (unsigned long __user *)arg);
00000440 
00000441     case I2C_RDWR:
00000442         return i2cdev_ioctl_rdrw(client, arg);
00000443 
00000444     case I2C_SMBUS:
00000445         return i2cdev_ioctl_smbus(client, arg);
00000446 
00000447     case I2C_RETRIES:
00000448         client->adapter->retries = arg;
00000449         break;
00000450     case I2C_TIMEOUT:
00000451         /* For historical reasons, user-space sets the timeout
00000452          * value in units of 10 ms.
00000453          */
00000454         client->adapter->timeout = msecs_to_jiffies(arg * 10);
00000455         break;
00000456     default:
00000457         /* NOTE:  returning a fault code here could cause trouble
00000458          * in buggy userspace code.  Some old kernel bugs returned
00000459          * zero in this case, and userspace code might accidentally
00000460          * have depended on that bug.
00000461          */
00000462         return -ENOTTY;
00000463     }
00000464     return 0;
00000465 }
複製代碼

比較簡單,根據不同的cmd執行不同的分支。由於ioctl傳下來的cmd是I2C_SMBUS,因此直接看444、445行,調用i2cdev_ioctl_smbus函數:

複製代碼
00000311 static noinline int i2cdev_ioctl_smbus(struct i2c_client *client,
00000312         unsigned long arg)
00000313 {
00000314     struct i2c_smbus_ioctl_data data_arg;
00000315     union i2c_smbus_data temp;
00000316     int datasize, res;
00000317 
00000318     if (copy_from_user(&data_arg,
00000319                (struct i2c_smbus_ioctl_data __user *) arg,
00000320                sizeof(struct i2c_smbus_ioctl_data)))
00000321         return -EFAULT;
00000322     if ((data_arg.size != I2C_SMBUS_BYTE) &&
00000323         (data_arg.size != I2C_SMBUS_QUICK) &&
00000324         (data_arg.size != I2C_SMBUS_BYTE_DATA) &&
00000325         (data_arg.size != I2C_SMBUS_WORD_DATA) &&
00000326         (data_arg.size != I2C_SMBUS_PROC_CALL) &&
00000327         (data_arg.size != I2C_SMBUS_BLOCK_DATA) &&
00000328         (data_arg.size != I2C_SMBUS_I2C_BLOCK_BROKEN) &&
00000329         (data_arg.size != I2C_SMBUS_I2C_BLOCK_DATA) &&
00000330         (data_arg.size != I2C_SMBUS_BLOCK_PROC_CALL)) {
00000331         dev_dbg(&client->adapter->dev,
00000332             "size out of range (%x) in ioctl I2C_SMBUS.\n",
00000333             data_arg.size);
00000334         return -EINVAL;
00000335     }
00000336     /* Note that I2C_SMBUS_READ and I2C_SMBUS_WRITE are 0 and 1,
00000337        so the check is valid if size==I2C_SMBUS_QUICK too. */
00000338     if ((data_arg.read_write != I2C_SMBUS_READ) &&
00000339         (data_arg.read_write != I2C_SMBUS_WRITE)) {
00000340         dev_dbg(&client->adapter->dev,
00000341             "read_write out of range (%x) in ioctl I2C_SMBUS.\n",
00000342             data_arg.read_write);
00000343         return -EINVAL;
00000344     }
00000345 
00000346     /* Note that command values are always valid! */
00000347 
00000348     if ((data_arg.size == I2C_SMBUS_QUICK) ||
00000349         ((data_arg.size == I2C_SMBUS_BYTE) &&
00000350         (data_arg.read_write == I2C_SMBUS_WRITE)))
00000351         /* These are special: we do not use data */
00000352         return i2c_smbus_xfer(client->adapter, client->addr,
00000353                       client->flags, data_arg.read_write,
00000354                       data_arg.command, data_arg.size, NULL);
00000355 
00000356     if (data_arg.data == NULL) {
00000357         dev_dbg(&client->adapter->dev,
00000358             "data is NULL pointer in ioctl I2C_SMBUS.\n");
00000359         return -EINVAL;
00000360     }
00000361 
00000362     if ((data_arg.size == I2C_SMBUS_BYTE_DATA) ||
00000363         (data_arg.size == I2C_SMBUS_BYTE))
00000364         datasize = sizeof(data_arg.data->byte);
00000365     else if ((data_arg.size == I2C_SMBUS_WORD_DATA) ||
00000366          (data_arg.size == I2C_SMBUS_PROC_CALL))
00000367         datasize = sizeof(data_arg.data->word);
00000368     else /* size == smbus block, i2c block, or block proc. call */
00000369         datasize = sizeof(data_arg.data->block);
00000370 
00000371     if ((data_arg.size == I2C_SMBUS_PROC_CALL) ||
00000372         (data_arg.size == I2C_SMBUS_BLOCK_PROC_CALL) ||
00000373         (data_arg.size == I2C_SMBUS_I2C_BLOCK_DATA) ||
00000374         (data_arg.read_write == I2C_SMBUS_WRITE)) {
00000375         if (copy_from_user(&temp, data_arg.data, datasize))
00000376             return -EFAULT;
00000377     }
00000378     if (data_arg.size == I2C_SMBUS_I2C_BLOCK_BROKEN) {
00000379         /* Convert old I2C block commands to the new
00000380            convention. This preserves binary compatibility. */
00000381         data_arg.size = I2C_SMBUS_I2C_BLOCK_DATA;
00000382         if (data_arg.read_write == I2C_SMBUS_READ)
00000383             temp.block[0] = I2C_SMBUS_BLOCK_MAX;
00000384     }
00000385     res = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
00000386           data_arg.read_write, data_arg.command, data_arg.size, &temp);
00000387     if (!res && ((data_arg.size == I2C_SMBUS_PROC_CALL) ||
00000388              (data_arg.size == I2C_SMBUS_BLOCK_PROC_CALL) ||
00000389              (data_arg.read_write == I2C_SMBUS_READ))) {
00000390         if (copy_to_user(data_arg.data, &temp, datasize))
00000391             return -EFAULT;
00000392     }
00000393     return res;
00000394 }
複製代碼

一大堆的if判斷。318行,調用copy_from_user函數將用戶空間的數據拷貝到內核空間。這樣data_arg的內容就與ioctl第三個參數的內容是一樣的了。

322至335行,都是判斷,一路走來,我們知道data_arg.size的值爲I2C_SMBUS_BYTE_DATA,所以這裏的if條件不會成立。

338至344行,如果既不是讀操作又不是寫操作,那肯定不行,返回出錯。

348行,由於不滿足第一個條件,所以不會執行if裏的語句。

356至360行,我們的data_arg.data是不爲NULL的,可以繼續往下執行。

362行,data_arg.size == I2C_SMBUS_BYTE_DATA這個條件滿足,所以執行364行的語句,因此datasize的值爲1。

371行,由於滿足data_arg.read_write == I2C_SMBUS_WRITE這個條件,所以執行375行語句,將data_arg.data的第一個字節拷貝到temp變量中。

378行,條件不滿足,略過。

先看387行,條件不滿足,因此就剩下385行的i2c_smbus_xfer函數,下面看它在drivers/i2c/i2c-core.c中的定義:

複製代碼
00002066 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
00002067            char read_write, u8 command, int protocol,
00002068            union i2c_smbus_data *data)
00002069 {
00002070     unsigned long orig_jiffies;
00002071     int try;
00002072     s32 res;
00002073 
00002074     flags &= I2C_M_TEN | I2C_CLIENT_PEC;
00002075 
00002076     if (adapter->algo->smbus_xfer) {
00002077         i2c_lock_adapter(adapter);
00002078 
00002079         /* Retry automatically on arbitration loss */
00002080         orig_jiffies = jiffies;
00002081         for (res = 0, try = 0; try <= adapter->retries; try++) {
00002082             res = adapter->algo->smbus_xfer(adapter, addr, flags,
00002083                             read_write, command,
00002084                             protocol, data);
00002085             if (res != -EAGAIN)
00002086                 break;
00002087             if (time_after(jiffies,
00002088                        orig_jiffies + adapter->timeout))
00002089                 break;
00002090         }
00002091         i2c_unlock_adapter(adapter);
00002092     } else
00002093         res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
00002094                           command, protocol, data);
00002095 
00002096     return res;
00002097 }
複製代碼

2076行,對於s3c6410的IIC控制器驅動來說,沒有定義smbus_xfer函數,因此執行2093行的i2c_smbus_xfer_emulated函數,它的定義如下:

複製代碼
00001889 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
00001890                    unsigned short flags,
00001891                    char read_write, u8 command, int size,
00001892                    union i2c_smbus_data *data)
00001893 {
00001894     /* So we need to generate a series of msgs. In the case of writing, we
00001895       need to use only one message; when reading, we need two. We initialize
00001896       most things with sane defaults, to keep the code below somewhat
00001897       simpler. */
00001898     unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
00001899     unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
00001900     int num = read_write == I2C_SMBUS_READ ? 2 : 1;
00001901     struct i2c_msg msg[2] = { { addr, flags, 1, msgbuf0 },
00001902                               { addr, flags | I2C_M_RD, 0, msgbuf1 }
00001903                             };
00001904     int i;
00001905     u8 partial_pec = 0;
00001906     int status;
00001907 
00001908     msgbuf0[0] = command;
00001909     switch (size) {
00001910     case I2C_SMBUS_QUICK:
00001911         msg[0].len = 0;
00001912         /* Special case: The read/write field is used as data */
00001913         msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
00001914                     I2C_M_RD : 0);
00001915         num = 1;
00001916         break;
00001917     case I2C_SMBUS_BYTE:
00001918         if (read_write == I2C_SMBUS_READ) {
00001919             /* Special case: only a read! */
00001920             msg[0].flags = I2C_M_RD | flags;
00001921             num = 1;
00001922         }
00001923         break;
00001924     case I2C_SMBUS_BYTE_DATA:
00001925         if (read_write == I2C_SMBUS_READ)
00001926             msg[1].len = 1;
00001927         else {
00001928             msg[0].len = 2;
00001929             msgbuf0[1] = data->byte;
00001930         }
00001931         break;
00001932     case I2C_SMBUS_WORD_DATA:
00001933         if (read_write == I2C_SMBUS_READ)
00001934             msg[1].len = 2;
00001935         else {
00001936             msg[0].len = 3;
00001937             msgbuf0[1] = data->word & 0xff;
00001938             msgbuf0[2] = data->word >> 8;
00001939         }
00001940         break;
00001941     case I2C_SMBUS_PROC_CALL:
00001942         num = 2; /* Special case */
00001943         read_write = I2C_SMBUS_READ;
00001944         msg[0].len = 3;
00001945         msg[1].len = 2;
00001946         msgbuf0[1] = data->word & 0xff;
00001947         msgbuf0[2] = data->word >> 8;
00001948         break;
00001949     case I2C_SMBUS_BLOCK_DATA:
00001950         if (read_write == I2C_SMBUS_READ) {
00001951             msg[1].flags |= I2C_M_RECV_LEN;
00001952             msg[1].len = 1; /* block length will be added by
00001953                        the underlying bus driver */
00001954         } else {
00001955             msg[0].len = data->block[0] + 2;
00001956             if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
00001957                 dev_err(&adapter->dev,
00001958                     "Invalid block write size %d\n",
00001959                     data->block[0]);
00001960                 return -EINVAL;
00001961             }
00001962             for (i = 1; i < msg[0].len; i++)
00001963                 msgbuf0[i] = data->block[i-1];
00001964         }
00001965         break;
00001966     case I2C_SMBUS_BLOCK_PROC_CALL:
00001967         num = 2; /* Another special case */
00001968         read_write = I2C_SMBUS_READ;
00001969         if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
00001970             dev_err(&adapter->dev,
00001971                 "Invalid block write size %d\n",
00001972                 data->block[0]);
00001973             return -EINVAL;
00001974         }
00001975         msg[0].len = data->block[0] + 2;
00001976         for (i = 1; i < msg[0].len; i++)
00001977             msgbuf0[i] = data->block[i-1];
00001978         msg[1].flags |= I2C_M_RECV_LEN;
00001979         msg[1].len = 1; /* block length will be added by
00001980                    the underlying bus driver */
00001981         break;
00001982     case I2C_SMBUS_I2C_BLOCK_DATA:
00001983         if (read_write == I2C_SMBUS_READ) {
00001984             msg[1].len = data->block[0];
00001985         } else {
00001986             msg[0].len = data->block[0] + 1;
00001987             if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
00001988                 dev_err(&adapter->dev,
00001989                     "Invalid block write size %d\n",
00001990                     data->block[0]);
00001991                 return -EINVAL;
00001992             }
00001993             for (i = 1; i <= data->block[0]; i++)
00001994                 msgbuf0[i] = data->block[i];
00001995         }
00001996         break;
00001997     default:
00001998         dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
00001999         return -EOPNOTSUPP;
00002000     }
00002001 
00002002     i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
00002003                       && size != I2C_SMBUS_I2C_BLOCK_DATA);
00002004     if (i) {
00002005         /* Compute PEC if first message is a write */
00002006         if (!(msg[0].flags & I2C_M_RD)) {
00002007             if (num == 1) /* Write only */
00002008                 i2c_smbus_add_pec(&msg[0]);
00002009             else /* Write followed by read */
00002010                 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
00002011         }
00002012         /* Ask for PEC if last message is a read */
00002013         if (msg[num-1].flags & I2C_M_RD)
00002014             msg[num-1].len++;
00002015     }
00002016 
00002017     status = i2c_transfer(adapter, msg, num);
00002018     if (status < 0)
00002019         return status;
00002020 
00002021     /* Check PEC if last message is a read */
00002022     if (i && (msg[num-1].flags & I2C_M_RD)) {
00002023         status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
00002024         if (status < 0)
00002025             return status;
00002026     }
00002027 
00002028     if (read_write == I2C_SMBUS_READ)
00002029         switch (size) {
00002030         case I2C_SMBUS_BYTE:
00002031             data->byte = msgbuf0[0];
00002032             break;
00002033         case I2C_SMBUS_BYTE_DATA:
00002034             data->byte = msgbuf1[0];
00002035             break;
00002036         case I2C_SMBUS_WORD_DATA:
00002037         case I2C_SMBUS_PROC_CALL:
00002038             data->word = msgbuf1[0] | (msgbuf1[1] << 8);
00002039             break;
00002040         case I2C_SMBUS_I2C_BLOCK_DATA:
00002041             for (i = 0; i < data->block[0]; i++)
00002042                 data->block[i+1] = msgbuf1[i];
00002043             break;
00002044         case I2C_SMBUS_BLOCK_DATA:
00002045         case I2C_SMBUS_BLOCK_PROC_CALL:
00002046             for (i = 0; i < msgbuf1[0] + 1; i++)
00002047                 data->block[i] = msgbuf1[i];
00002048             break;
00002049         }
00002050     return 0;
00002051 }
複製代碼

函數很長,但是邏輯卻很簡單。1898行,定義msgbuf0數組用作寫操作,裏面放的是要寫的數據,後面會看到。

1899行,定義msgbuf1數組用作讀操作,這裏討論的是寫操作,因此略過與讀操作相關的內容。

1900行,因爲read_write=I2C_SMBUS_WRITE,所以num的值爲1。

1901行,定義2個message數組,同樣,一個用作寫,一個用作讀。

1908行,msgbuf0[0] = command,即要寫數據的地址。

1909行,switch(size),由於size的值爲I2C_SMBUS_BYTE_DATA,所以1924行的條件成立。

1925行,條件不成立,因此直接到1928行,msg[0].len = 2,寫一字節地址和寫一個字節數據加起來剛好是2字節。1929行,msgbuf0[1] = data->byte,即要寫入的數據。

2002至2015行,與錯誤檢測相關的,略過它不會有什麼影響。

先看2022至2050行,都是與讀操作相關的,因此不說了。

再看2017行,調用i2c_transfer函數來進行傳輸,i2c_transfer函數的定義:

複製代碼
00001281 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
00001282 {
00001283     unsigned long orig_jiffies;
00001284     int ret, try;
00001285 
00001286     /* REVISIT the fault reporting model here is weak:
00001287      *
00001288      *  - When we get an error after receiving N bytes from a slave,
00001289      *    there is no way to report "N".
00001290      *
00001291      *  - When we get a NAK after transmitting N bytes to a slave,
00001292      *    there is no way to report "N" ... or to let the master
00001293      *    continue executing the rest of this combined message, if
00001294      *    that's the appropriate response.
00001295      *
00001296      *  - When for example "num" is two and we successfully complete
00001297      *    the first message but get an error part way through the
00001298      *    second, it's unclear whether that should be reported as
00001299      *    one (discarding status on the second message) or errno
00001300      *    (discarding status on the first one).
00001301      */
00001302 
00001303     if (adap->algo->master_xfer) {
00001304 #ifdef DEBUG
00001305         for (ret = 0; ret < num; ret++) {
00001306             dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
00001307                 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
00001308                 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
00001309                 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
00001310         }
00001311 #endif
00001312 
00001313         if (in_atomic() || irqs_disabled()) {
00001314             ret = i2c_trylock_adapter(adap);
00001315             if (!ret)
00001316                 /* I2C activity is ongoing. */
00001317                 return -EAGAIN;
00001318         } else {
00001319             i2c_lock_adapter(adap);
00001320         }
00001321 
00001322         /* Retry automatically on arbitration loss */
00001323         orig_jiffies = jiffies;
00001324         for (ret = 0, try = 0; try <= adap->retries; try++) {
00001325             ret = adap->algo->master_xfer(adap, msgs, num);
00001326             if (ret != -EAGAIN)
00001327                 break;
00001328             if (time_after(jiffies, orig_jiffies + adap->timeout))
00001329                 break;
00001330         }
00001331         i2c_unlock_adapter(adap);
00001332 
00001333         return ret;
00001334     } else {
00001335         dev_dbg(&adap->dev, "I2C level transfers not supported\n");
00001336         return -EOPNOTSUPP;
00001337     }
00001338 }
複製代碼

一看,呆了眼,函數裏面竟然有這麼多註釋。

1303行,master_xfer這個指針是有賦值的,因此執行if裏面的語句。

1304至1311行,調試相關的,打印一些調試信息。

1313至1320行,鎖住當前的適配器。

1324行,adap->retries的值在IIC控制器初始化的時候就設置爲2,因此重試2次。

1325行,調用的是drivers/i2c/busses/i2c-s3c2410.c裏的s3c24xx_i2c_xfer函數,它的定義:

複製代碼
00000551 static int s3c24xx_i2c_xfer(struct i2c_adapter *adap,
00000552             struct i2c_msg *msgs, int num)
00000553 {
00000554     struct s3c24xx_i2c *i2c = (struct s3c24xx_i2c *)adap->algo_data;
00000555     int retry;
00000556     int ret;
00000557 
00000558     for (retry = 0; retry < adap->retries; retry++) {
00000559 
00000560         ret = s3c24xx_i2c_doxfer(i2c, msgs, num);
00000561 
00000562         if (ret != -EAGAIN)
00000563             return ret;
00000564 
00000565         dev_dbg(i2c->dev, "Retrying transmission (%d)\n", retry);
00000566 
00000567         udelay(100);
00000568     }
00000569 
00000570     return -EREMOTEIO;
00000571 }
複製代碼

558行,又重試2次。

560行,調用s3c24xx_i2c_doxfer函數:

複製代碼
00000482 static int s3c24xx_i2c_doxfer(struct s3c24xx_i2c *i2c,
00000483                   struct i2c_msg *msgs, int num)
00000484 {
00000485     unsigned long iicstat, timeout;
00000486     int spins = 20;
00000487     int ret;
00000488 
00000489     if (i2c->suspended)
00000490         return -EIO;
00000491 
00000492     ret = s3c24xx_i2c_set_master(i2c);
00000493     if (ret != 0) {
00000494         dev_err(i2c->dev, "cannot get bus (error %d)\n", ret);
00000495         ret = -EAGAIN;
00000496         goto out;
00000497     }
00000498 
00000499     spin_lock_irq(&i2c->lock);
00000500 
00000501     i2c->msg     = msgs;
00000502     i2c->msg_num = num;
00000503     i2c->msg_ptr = 0;
00000504     i2c->msg_idx = 0;
00000505     i2c->state   = STATE_START;
00000506 
00000507     s3c24xx_i2c_enable_irq(i2c);
00000508     s3c24xx_i2c_message_start(i2c, msgs);
00000509     spin_unlock_irq(&i2c->lock);
00000510 
00000511     timeout = wait_event_timeout(i2c->wait, i2c->msg_num == 0, HZ * 5);
00000512 
00000513     ret = i2c->msg_idx;
00000514 
00000515     /* having these next two as dev_err() makes life very
00000516      * noisy when doing an i2cdetect */
00000517 
00000518     if (timeout == 0)
00000519         dev_dbg(i2c->dev, "timeout\n");
00000520     else if (ret != num)
00000521         dev_dbg(i2c->dev, "incomplete xfer (%d)\n", ret);
00000522 
00000523     /* ensure the stop has been through the bus */
00000524 
00000525     dev_dbg(i2c->dev, "waiting for bus idle\n");
00000526 
00000527     /* first, try busy waiting briefly */
00000528     do {
00000529         iicstat = readl(i2c->regs + S3C2410_IICSTAT);
00000530     } while ((iicstat & S3C2410_IICSTAT_START) && --spins);
00000531 
00000532     /* if that timed out sleep */
00000533     if (!spins) {
00000534         msleep(1);
00000535         iicstat = readl(i2c->regs + S3C2410_IICSTAT);
00000536     }
00000537 
00000538     if (iicstat & S3C2410_IICSTAT_START)
00000539         dev_warn(i2c->dev, "timeout waiting for bus idle\n");
00000540 
00000541  out:
00000542     return ret;
00000543 }
複製代碼

489行,如果IIC控制器掛起了的話就不用往下走了,返回出錯。

492至497行,調用s3c24xx_i2c_set_master函數,讀取IICSTAT寄存器,等待IIC總線空閒。

501至505行,記住這些變量的值,後面的分析會遇到。

507行,使能IIC控制器中斷。

508行,調用s3c24xx_i2c_message_start函數開始讀寫操作,它的定義如下:

複製代碼
00000163 static void s3c24xx_i2c_message_start(struct s3c24xx_i2c *i2c,
00000164                       struct i2c_msg *msg)
00000165 {
00000166     unsigned int addr = (msg->addr & 0x7f) << 1;
00000167     unsigned long stat;
00000168     unsigned long iiccon;
00000169 
00000170     stat = 0;
00000171     stat |=  S3C2410_IICSTAT_TXRXEN;
00000172 
00000173     if (msg->flags & I2C_M_RD) {
00000174         stat |= S3C2410_IICSTAT_MASTER_RX;
00000175         addr |= 1;
00000176     } else
00000177         stat |= S3C2410_IICSTAT_MASTER_TX;
00000178 
00000179     if (msg->flags & I2C_M_REV_DIR_ADDR)
00000180         addr ^= 1;
00000181 
00000182     /* todo - check for wether ack wanted or not */
00000183     s3c24xx_i2c_enable_ack(i2c);
00000184 
00000185     iiccon = readl(i2c->regs + S3C2410_IICCON);
00000186     writel(stat, i2c->regs + S3C2410_IICSTAT);
00000187 
00000188     dev_dbg(i2c->dev, "START: %08lx to IICSTAT, %02x to DS\n", stat, addr);
00000189     writeb(addr, i2c->regs + S3C2410_IICDS);
00000190 
00000191     /* delay here to ensure the data byte has gotten onto the bus
00000192      * before the transaction is started */
00000193 
00000194     ndelay(i2c->tx_setup);
00000195 
00000196     dev_dbg(i2c->dev, "iiccon, %08lx\n", iiccon);
00000197     writel(iiccon, i2c->regs + S3C2410_IICCON);
00000198 
00000199     stat |= S3C2410_IICSTAT_START;
00000200     writel(stat, i2c->regs + S3C2410_IICSTAT);
00000201 }
複製代碼

166行,高7位表示從機地址,最低1位表示讀或寫操作,0表示寫,1表示讀。

171行,IIC控制器發送和接收使能。

173行,條件不成立,所以執行177行,主機發送使能。

179行,與讀操作相關的,因此if條件不成立。

183行,使能IIC控制器ACK應答。

剩下那些語句基本上都是在操作IIC控制器的寄存器,具體含義請看s3c6410的數據手冊。

189行,將從機地址寫入移位寄存器。

        s3c24xx_i2c_message_start函數執行完後硬件就開始進行數據傳輸,回到s3c24xx_i2c_doxfer函數的第509行,釋放鎖,與499行是配對使用的。

511行,等待,等待傳輸操作完成,等待,只因曾經承若。有兩種情況會喚醒它,一是超時,二是傳輸完成。

      程序是在等待了,但我們的步伐卻不會因此而停留,前面還有很長的路等着我們呢,還等什麼,繼續前進!

接下來看等待過程中發生的事情,沒錯,就是在中斷裏。中斷處理函數是s3c24xx_i2c_irq,它的定義:

複製代碼
00000423 static irqreturn_t s3c24xx_i2c_irq(int irqno, void *dev_id)
00000424 {
00000425     struct s3c24xx_i2c *i2c = dev_id;
00000426     unsigned long status;
00000427     unsigned long tmp;
00000428 
00000429     status = readl(i2c->regs + S3C2410_IICSTAT);
00000430 
00000431     if (status & S3C2410_IICSTAT_ARBITR) {
00000432         /* deal with arbitration loss */
00000433         dev_err(i2c->dev, "deal with arbitration loss\n");
00000434     }
00000435 
00000436     if (i2c->state == STATE_IDLE) {
00000437         dev_dbg(i2c->dev, "IRQ: error i2c->state == IDLE\n");
00000438 
00000439         tmp = readl(i2c->regs + S3C2410_IICCON);
00000440         tmp &= ~S3C2410_IICCON_IRQPEND;
00000441         writel(tmp, i2c->regs +  S3C2410_IICCON);
00000442         goto out;
00000443     }
00000444 
00000445     /* pretty much this leaves us with the fact that we've
00000446      * transmitted or received whatever byte we last sent */
00000447 
00000448     i2s_s3c_irq_nextbyte(i2c, status);
00000449 
00000450  out:
00000451     return IRQ_HANDLED;
00000452 }
複製代碼

429行,讀取狀態寄存器。

431至434行,如果總線仲裁失敗就打印錯誤信息。

436至443行,我們知道i2c->state是等於STATE_START的,因此這裏的if條件不成立。

448行,i2s_s3c_irq_nextbyte函數執行具體中斷處理,i2s_s3c_irq_nextbyte函數的定義:

複製代碼
00000257 static int i2s_s3c_irq_nextbyte(struct s3c24xx_i2c *i2c, unsigned long iicstat)
00000258 {
00000259     unsigned long tmp;
00000260     unsigned char byte;
00000261     int ret = 0;
00000262 
00000263     switch (i2c->state) {
00000264 
00000265     case STATE_IDLE:
00000266         dev_err(i2c->dev, "%s: called in STATE_IDLE\n", __func__);
00000267         goto out;
00000268         break;
00000269 
00000270     case STATE_STOP:
00000271         dev_err(i2c->dev, "%s: called in STATE_STOP\n", __func__);
00000272         s3c24xx_i2c_disable_irq(i2c);
00000273         goto out_ack;
00000274 
00000275     case STATE_START:
00000276         /* last thing we did was send a start condition on the
00000277          * bus, or started a new i2c message
00000278          */
00000279 
00000280         if (iicstat & S3C2410_IICSTAT_LASTBIT &&
00000281             !(i2c->msg->flags & I2C_M_IGNORE_NAK)) {
00000282             /* ack was not received... */
00000283 
00000284             dev_dbg(i2c->dev, "ack was not received\n");
00000285             s3c24xx_i2c_stop(i2c, -ENXIO);
00000286             goto out_ack;
00000287         }
00000288 
00000289         if (i2c->msg->flags & I2C_M_RD)
00000290             i2c->state = STATE_READ;
00000291         else
00000292             i2c->state = STATE_WRITE;
00000293 
00000294         /* terminate the transfer if there is nothing to do
00000295          * as this is used by the i2c probe to find devices. */
00000296 
00000297         if (is_lastmsg(i2c) && i2c->msg->len == 0) {
00000298             s3c24xx_i2c_stop(i2c, 0);
00000299             goto out_ack;
00000300         }
00000301 
00000302         if (i2c->state == STATE_READ)
00000303             goto prepare_read;
00000304 
00000305         /* fall through to the write state, as we will need to
00000306          * send a byte as well */
00000307 
00000308     case STATE_WRITE:
00000309         /* we are writing data to the device... check for the
00000310          * end of the message, and if so, work out what to do
00000311          */
00000312 
00000313         if (!(i2c->msg->flags & I2C_M_IGNORE_NAK)) {
00000314             if (iicstat & S3C2410_IICSTAT_LASTBIT) {
00000315                 dev_dbg(i2c->dev, "WRITE: No Ack\n");
00000316 
00000317                 s3c24xx_i2c_stop(i2c, -ECONNREFUSED);
00000318                 goto out_ack;
00000319             }
00000320         }
00000321 
00000322  retry_write:
00000323 
00000324         if (!is_msgend(i2c)) {
00000325             byte = i2c->msg->buf[i2c->msg_ptr++];
00000326             writeb(byte, i2c->regs + S3C2410_IICDS);
00000327 
00000328             /* delay after writing the byte to allow the
00000329              * data setup time on the bus, as writing the
00000330              * data to the register causes the first bit
00000331              * to appear on SDA, and SCL will change as
00000332              * soon as the interrupt is acknowledged */
00000333 
00000334             ndelay(i2c->tx_setup);
00000335 
00000336         } else if (!is_lastmsg(i2c)) {
00000337             /* we need to go to the next i2c message */
00000338 
00000339             dev_dbg(i2c->dev, "WRITE: Next Message\n");
00000340 
00000341             i2c->msg_ptr = 0;
00000342             i2c->msg_idx++;
00000343             i2c->msg++;
00000344 
00000345             /* check to see if we need to do another message */
00000346             if (i2c->msg->flags & I2C_M_NOSTART) {
00000347 
00000348                 if (i2c->msg->flags & I2C_M_RD) {
00000349                     /* cannot do this, the controller
00000350                      * forces us to send a new START
00000351                      * when we change direction */
00000352 
00000353                     s3c24xx_i2c_stop(i2c, -EINVAL);
00000354                 }
00000355 
00000356                 goto retry_write;
00000357             } else {
00000358                 /* send the new start */
00000359                 s3c24xx_i2c_message_start(i2c, i2c->msg);
00000360                 i2c->state = STATE_START;
00000361             }
00000362 
00000363         } else {
00000364             /* send stop */
00000365 
00000366             s3c24xx_i2c_stop(i2c, 0);
00000367         }
00000368         break;
00000369 
00000370     case STATE_READ:
00000371         /* we have a byte of data in the data register, do
00000372          * something with it, and then work out wether we are
00000373          * going to do any more read/write
00000374          */
00000375 
00000376         byte = readb(i2c->regs + S3C2410_IICDS);
00000377         i2c->msg->buf[i2c->msg_ptr++] = byte;
00000378 
00000379  prepare_read:
00000380         if (is_msglast(i2c)) {
00000381             /* last byte of buffer */
00000382 
00000383             if (is_lastmsg(i2c))
00000384                 s3c24xx_i2c_disable_ack(i2c);
00000385 
00000386         } else if (is_msgend(i2c)) {
00000387             /* ok, we've read the entire buffer, see if there
00000388              * is anything else we need to do */
00000389 
00000390             if (is_lastmsg(i2c)) {
00000391                 /* last message, send stop and complete */
00000392                 dev_dbg(i2c->dev, "READ: Send Stop\n");
00000393 
00000394                 s3c24xx_i2c_stop(i2c, 0);
00000395             } else {
00000396                 /* go to the next transfer */
00000397                 dev_dbg(i2c->dev, "READ: Next Transfer\n");
00000398 
00000399                 i2c->msg_ptr = 0;
00000400                 i2c->msg_idx++;
00000401                 i2c->msg++;
00000402             }
00000403         }
00000404 
00000405         break;
00000406     }
00000407 
00000408     /* acknowlegde the IRQ and get back on with the work */
00000409 
00000410  out_ack:
00000411     tmp = readl(i2c->regs + S3C2410_IICCON);
00000412     tmp &= ~S3C2410_IICCON_IRQPEND;
00000413     writel(tmp, i2c->regs + S3C2410_IICCON);
00000414  out:
00000415     return ret;
00000416 }
複製代碼

函數夠長的,不過一路走來,早就已經習慣了。

263行,因爲i2c->state=STATE_START,因此忽略其他case,直接從275行開始看。

280行,如果沒有收到ACK信號並且沒有設置忽略ACK則停止這次傳輸。

289行,if條件不成立,執行292行,i2c->state = STATE_WRITE。

297行,is_lastmsg函數的定義:

00000227 static inline int is_lastmsg(struct s3c24xx_i2c *i2c)
00000228 {
00000229     return i2c->msg_idx >= (i2c->msg_num - 1);
00000230 }

因爲i2c->msg_idx=0,i2c->msg_num=1,所以返回1。但是i2c->msg->len=2不爲0,所以297行的if條件不成立。

302行,if條件不成立。

注意,這個case裏沒有並沒有break,因此會繼續往下執行。

313至320行,也是沒收到ACK條件纔會成立的。

324行,is_msgend函數的定義:

00000247 static inline int is_msgend(struct s3c24xx_i2c *i2c)
00000248 {
00000249     return i2c->msg_ptr >= i2c->msg->len;
00000250 }

因爲i2c->msg_ptr=0,i2c->msg->len=2,因此返回0。324行的if條件成立。

325行,讀取第一個要寫的字節數據,然後i2c->msg_ptr= i2c->msg_ptr +1。

326行,將數據寫入移位寄存器。

334行,延時一下。

368行,跳出switch,到411行。

411至413行,清除pending標誌,恢復IIC傳輸。

      下一次進中斷的時候會進入308行的case,經過313至320行的判斷後來到324行,這次is_msgend函數還是會返回0。325行,讀取下一個字節數據,326行,將數據寫入移位寄存器,過程和前面的一樣。

     當第三次進中斷的時候,324行的條件就不會成立了,並且336行的if條件也不會成立,因此就會執行366行的s3c24xx_i2c_stop函數,它的定義如下:

複製代碼
00000203 static inline void s3c24xx_i2c_stop(struct s3c24xx_i2c *i2c, int ret)
00000204 {
00000205     unsigned long iicstat = readl(i2c->regs + S3C2410_IICSTAT);
00000206 
00000207     dev_dbg(i2c->dev, "STOP\n");
00000208 
00000209     /* stop the transfer */
00000210     iicstat &= ~S3C2410_IICSTAT_START;
00000211     writel(iicstat, i2c->regs + S3C2410_IICSTAT);
00000212 
00000213     i2c->state = STATE_STOP;
00000214 
00000215     s3c24xx_i2c_master_complete(i2c, ret);
00000216     s3c24xx_i2c_disable_irq(i2c);
00000217 }
複製代碼

205行,讀取狀態寄存器。

210、211行,發送停止信號。

213行,i2c->state = STATE_STOP。

215行,調用s3c24xx_i2c_master_complete函數。

216行,禁止IIC控制器中斷。下面看s3c24xx_i2c_master_complete函數的定義:

複製代碼
00000109 static inline void s3c24xx_i2c_master_complete(struct s3c24xx_i2c *i2c, int ret)
00000110 {
00000111     dev_dbg(i2c->dev, "master_complete %d\n", ret);
00000112 
00000113     i2c->msg_ptr = 0;
00000114     i2c->msg = NULL;
00000115     i2c->msg_idx++;
00000116     i2c->msg_num = 0;
00000117     if (ret)
00000118         i2c->msg_idx = ret;
00000119 
00000120     wake_up(&i2c->wait);
00000121 }
複製代碼

113至118行,不用說了。

120行,喚醒那個睡着了的她,誰?就是那個“承若”。忘記了的話就回去看看唄。

     至此,可以說ioctl的整個寫過程已經說完了,至於讀過程就不說了。累,確實有點累。

 

結束語

     i2c-dev.c提供了一套不依賴於具體平臺的驅動,讓具體的驅動邏輯放在應用程序中,和SPI中的spidev.c的作用是很類似的。




















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章