Linux設備模型分析之device_driver(基於3.10.1內核)

作者:劉昊昱 

博客:http://blog.csdn.net/liuhaoyutz

內核版本:3.10.1

 
一、device_driver定義
 181/**
 182 * struct device_driver - The basic device driver structure
 183 * @name:   Name of the device driver.
 184 * @bus:    The bus which the device of this driver belongs to.
 185 * @owner:  The module owner.
 186 * @mod_name:   Used for built-in modules.
 187 * @suppress_bind_attrs: Disables bind/unbind via sysfs.
 188 * @of_match_table: The open firmware table.
 189 * @acpi_match_table: The ACPI match table.
 190 * @probe:  Called to query the existence of a specific device,
 191 *      whether this driver can work with it, and bind the driver
 192 *      to a specific device.
 193 * @remove: Called when the device is removed from the system to
 194 *      unbind a device from this driver.
 195 * @shutdown:   Called at shut-down time to quiesce the device.
 196 * @suspend:    Called to put the device to sleep mode. Usually to a
 197 *      low power state.
 198 * @resume: Called to bring a device from sleep mode.
 199 * @groups: Default attributes that get created by the driver core
 200 *      automatically.
 201 * @pm:     Power management operations of the device which matched
 202 *      this driver.
 203 * @p:      Driver core's private data, no one other than the driver
 204 *      core can touch this.
 205 *
 206 * The device driver-model tracks all of the drivers known to the system.
 207 * The main reason for this tracking is to enable the driver core to match
 208 * up drivers with new devices. Once drivers are known objects within the
 209 * system, however, a number of other things become possible. Device drivers
 210 * can export information and configuration variables that are independent
 211 * of any specific device.
 212 */
 213struct device_driver {
 214    const char      *name;
 215    struct bus_type     *bus;
 216
 217    struct module       *owner;
 218    const char      *mod_name;  /* used for built-in modules */
 219
 220    bool suppress_bind_attrs;   /* disables bind/unbind via sysfs */
 221
 222    const struct of_device_id   *of_match_table;
 223    const struct acpi_device_id *acpi_match_table;
 224
 225    int (*probe) (struct device *dev);
 226    int (*remove) (struct device *dev);
 227    void (*shutdown) (struct device *dev);
 228    int (*suspend) (struct device *dev, pm_message_t state);
 229    int (*resume) (struct device *dev);
 230    const struct attribute_group **groups;
 231
 232    const struct dev_pm_ops *pm;
 233
 234    struct driver_private *p;
 235};


name,device_driver的名字。
bus,device_driver支持的device所依附的bus。
probe,探測device_drvier是否支持參數指定的device。如果支持,則綁定該device_driver和該device。
remove,該device被移除時調用該函數,解除該device與device_driver的綁定。
shutdown,當關機時調用該函數,以關閉參數指定的device。
suspend,當device進入休眠狀態時,調用該函數。
resume,當device從休眠狀態被喚醒時,調用該函數。
p,device_driver私有數據,它是struct driver_private類型,該類型定義在drivers/base/base.h文件中,其內容如下:
 46struct driver_private {
 47    struct kobject kobj;
 48    struct klist klist_devices;
 49    struct klist_node knode_bus;
 50    struct module_kobject *mkobj;
 51    struct device_driver *driver;
 52};


kobj,是其所屬的device_driver對應的kobject。
klist_devices,其所屬的device_driver支持的device鏈表。
driver,所屬的device_driver。
 
二、device_driver的註冊
device_driver的註冊是通過調用driver_register函數完成的,該函數定義在drivers/base/driver.c文件中,其內容如下:
156/**
157 * driver_register - register driver with bus
158 * @drv: driver to register
159 *
160 * We pass off most of the work to the bus_add_driver() call,
161 * since most of the things we have to do deal with the bus
162 * structures.
163 */
164int driver_register(struct device_driver *drv)
165{
166    int ret;
167    struct device_driver *other;
168
169    BUG_ON(!drv->bus->p);
170
171    if ((drv->bus->probe && drv->probe) ||
172        (drv->bus->remove && drv->remove) ||
173        (drv->bus->shutdown && drv->shutdown))
174        printk(KERN_WARNING "Driver '%s' needs updating - please use "
175            "bus_type methods\n", drv->name);
176
177    other = driver_find(drv->name, drv->bus);
178    if (other) {
179        printk(KERN_ERR "Error: Driver '%s' is already registered, "
180            "aborting...\n", drv->name);
181        return -EBUSY;
182    }
183
184    ret = bus_add_driver(drv);
185    if (ret)
186        return ret;
187    ret = driver_add_groups(drv, drv->groups);
188    if (ret) {
189        bus_remove_driver(drv);
190        return ret;
191    }
192    kobject_uevent(&drv->p->kobj, KOBJ_ADD);
193
194    return ret;
195}


171-175行,如果bus和device_driver定義了相同的函數,會優先調用bus的相應函數,這裏會發出警告信息。
177行,調用driver_find在bus的drivers_kset中查找是否已經有同名device_driver已經註冊過,如果已經註冊過,則退出。
184行,調用bus_add_driver函數完成註冊,該函數定義在drivers/base/bus.c文件中,其內容如下:
 673/**
 674 * bus_add_driver - Add a driver to the bus.
 675 * @drv: driver.
 676 */
 677int bus_add_driver(struct device_driver *drv)
 678{
 679    struct bus_type *bus;
 680    struct driver_private *priv;
 681    int error = 0;
 682
 683    bus = bus_get(drv->bus);
 684    if (!bus)
 685        return -EINVAL;
 686
 687    pr_debug("bus: '%s': add driver %s\n", bus->name, drv->name);
 688
 689    priv = kzalloc(sizeof(*priv), GFP_KERNEL);
 690    if (!priv) {
 691        error = -ENOMEM;
 692        goto out_put_bus;
 693    }
 694    klist_init(&priv->klist_devices, NULL, NULL);
 695    priv->driver = drv;
 696    drv->p = priv;
 697    priv->kobj.kset = bus->p->drivers_kset;
 698    error = kobject_init_and_add(&priv->kobj, &driver_ktype, NULL,
 699                     "%s", drv->name);
 700    if (error)
 701        goto out_unregister;
 702
 703    klist_add_tail(&priv->knode_bus, &bus->p->klist_drivers);
 704    if (drv->bus->p->drivers_autoprobe) {
 705        error = driver_attach(drv);
 706        if (error)
 707            goto out_unregister;
 708    }
 709    module_add_driver(drv->owner, drv);
 710
 711    error = driver_create_file(drv, &driver_attr_uevent);
 712    if (error) {
 713        printk(KERN_ERR "%s: uevent attr (%s) failed\n",
 714            __func__, drv->name);
 715    }
 716    error = driver_add_attrs(bus, drv);
 717    if (error) {
 718        /* How the hell do we get out of this pickle? Give up */
 719        printk(KERN_ERR "%s: driver_add_attrs(%s) failed\n",
 720            __func__, drv->name);
 721    }
 722
 723    if (!drv->suppress_bind_attrs) {
 724        error = add_bind_files(drv);
 725        if (error) {
 726            /* Ditto */
 727            printk(KERN_ERR "%s: add_bind_files(%s) failed\n",
 728                __func__, drv->name);
 729        }
 730    }
 731
 732    return 0;
 733
 734out_unregister:
 735    kobject_put(&priv->kobj);
 736    kfree(drv->p);
 737    drv->p = NULL;
 738out_put_bus:
 739    bus_put(bus);
 740    return error;
 741}


698行,調用kobject_init_and_add函數將device_driver添加到sysfs文件系統中,因爲指定了priv->kobj.kset爲bus->p->drivers_kset,所以其對應的目錄會出現在/sys/bus/bus_name/drivers目錄下。
703行,調用klist_add_tail將device_driver加入到bus->p->klist_drivers中。
704-708行,如果drv->bus->p->drivers_autoprobe爲1,則調用driver_attach(drv)函數將當前device_driver與相應device進行綁定。該函數與上一篇博客中分析device的註冊過程中調用的device_attach類似。driver_attach函數定義在drivers/base/dd.c文件中,其內容如下:
468/**
469 * driver_attach - try to bind driver to devices.
470 * @drv: driver.
471 *
472 * Walk the list of devices that the bus has on it and try to
473 * match the driver with each one.  If driver_probe_device()
474 * returns 0 and the @dev->driver is set, we've found a
475 * compatible pair.
476 */
477int driver_attach(struct device_driver *drv)
478{
479    return bus_for_each_dev(drv->bus, NULL, drv, __driver_attach);
480}


bus_for_each_dev函數定義在drivers/base/bus.c文件中,其內容如下:
 267/**
 268 * bus_for_each_dev - device iterator.
 269 * @bus: bus type.
 270 * @start: device to start iterating from.
 271 * @data: data for the callback.
 272 * @fn: function to be called for each device.
 273 *
 274 * Iterate over @bus's list of devices, and call @fn for each,
 275 * passing it @data. If @start is not NULL, we use that device to
 276 * begin iterating from.
 277 *
 278 * We check the return of @fn each time. If it returns anything
 279 * other than 0, we break out and return that value.
 280 *
 281 * NOTE: The device that returns a non-zero value is not retained
 282 * in any way, nor is its refcount incremented. If the caller needs
 283 * to retain this data, it should do so, and increment the reference
 284 * count in the supplied callback.
 285 */
 286int bus_for_each_dev(struct bus_type *bus, struct device *start,
 287             void *data, int (*fn)(struct device *, void *))
 288{
 289    struct klist_iter i;
 290    struct device *dev;
 291    int error = 0;
 292
 293    if (!bus || !bus->p)
 294        return -EINVAL;
 295
 296    klist_iter_init_node(&bus->p->klist_devices, &i,
 297                 (start ? &start->p->knode_bus : NULL));
 298    while ((dev = next_device(&i)) && !error)
 299        error = fn(dev, data);
 300    klist_iter_exit(&i);
 301    return error;
 302}


298-299行,這個while循環遍歷bus->p->klist_devices鏈表,對註冊在bus上的每個device調用fn函數,這裏,fn函數是傳遞進來的__driver_attach函數,該函數定義在drivers/base/dd.c文件中,其內容如下:
439static int __driver_attach(struct device *dev, void *data)
440{
441    struct device_driver *drv = data;
442
443    /*
444     * Lock device and try to bind to it. We drop the error
445     * here and always return 0, because we need to keep trying
446     * to bind to devices and some drivers will return an error
447     * simply if it didn't support the device.
448     *
449     * driver_probe_device() will spit a warning if there
450     * is an error.
451     */
452
453    if (!driver_match_device(drv, dev))
454        return 0;
455
456    if (dev->parent)    /* Needed for USB */
457        device_lock(dev->parent);
458    device_lock(dev);
459    if (!dev->driver)
460        driver_probe_device(drv, dev);
461    device_unlock(dev);
462    if (dev->parent)
463        device_unlock(dev->parent);
464
465    return 0;
466}


453行,調用driver_match_device函數,該函數定義在drivers/base/base.h文件中,其內容如下:
116static inline int driver_match_device(struct device_driver *drv,
117                      struct device *dev)
118{
119    return drv->bus->match ? drv->bus->match(dev, drv) : 1;
120}


如果定義了drv->bus->match函數,則調用之,否則直接返回1。
回到__driver_attach函數:
460行,調用driver_probe_device函數,該函數定義在drivers/base/dd.c文件中,其內容如下:
360/**
361 * driver_probe_device - attempt to bind device & driver together
362 * @drv: driver to bind a device to
363 * @dev: device to try to bind to the driver
364 *
365 * This function returns -ENODEV if the device is not registered,
366 * 1 if the device is bound successfully and 0 otherwise.
367 *
368 * This function must be called with @dev lock held.  When called for a
369 * USB interface, @dev->parent lock must be held as well.
370 */
371int driver_probe_device(struct device_driver *drv, struct device *dev)
372{
373    int ret = 0;
374
375    if (!device_is_registered(dev))
376        return -ENODEV;
377
378    pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
379         drv->bus->name, __func__, dev_name(dev), drv->name);
380
381    pm_runtime_barrier(dev);
382    ret = really_probe(dev, drv);
383    pm_request_idle(dev);
384
385    return ret;
386}


375行,調用device_is_registered函數判斷device是否已經在sysfs系統中註冊過,如果還沒有註冊過,則返回ENODEV,退出。該函數定義在include/linux/device.h文件中,其內容如下:
 787static inline int device_is_registered(struct device *dev)
 788{
 789    return dev->kobj.state_in_sysfs;
 790}


382行,調用really_probe函數,該函數定義在drivers/base/dd.c文件中,其內容如下:
265static int really_probe(struct device *dev, struct device_driver *drv)
266{
267    int ret = 0;
268
269    atomic_inc(&probe_count);
270    pr_debug("bus: '%s': %s: probing driver %s with device %s\n",
271         drv->bus->name, __func__, drv->name, dev_name(dev));
272    WARN_ON(!list_empty(&dev->devres_head));
273
274    dev->driver = drv;
275
276    /* If using pinctrl, bind pins now before probing */
277    ret = pinctrl_bind_pins(dev);
278    if (ret)
279        goto probe_failed;
280
281    if (driver_sysfs_add(dev)) {
282        printk(KERN_ERR "%s: driver_sysfs_add(%s) failed\n",
283            __func__, dev_name(dev));
284        goto probe_failed;
285    }
286
287    if (dev->bus->probe) {
288        ret = dev->bus->probe(dev);
289        if (ret)
290            goto probe_failed;
291    } else if (drv->probe) {
292        ret = drv->probe(dev);
293        if (ret)
294            goto probe_failed;
295    }
296
297    driver_bound(dev);
298    ret = 1;
299    pr_debug("bus: '%s': %s: bound device %s to driver %s\n",
300         drv->bus->name, __func__, dev_name(dev), drv->name);
301    goto done;
302
303probe_failed:
304    devres_release_all(dev);
305    driver_sysfs_remove(dev);
306    dev->driver = NULL;
307    dev_set_drvdata(dev, NULL);
308
309    if (ret == -EPROBE_DEFER) {
310        /* Driver requested deferred probing */
311        dev_info(dev, "Driver %s requests probe deferral\n", drv->name);
312        driver_deferred_probe_add(dev);
313    } else if (ret != -ENODEV && ret != -ENXIO) {
314        /* driver matched but the probe failed */
315        printk(KERN_WARNING
316               "%s: probe of %s failed with error %d\n",
317               drv->name, dev_name(dev), ret);
318    } else {
319        pr_debug("%s: probe of %s rejects match %d\n",
320               drv->name, dev_name(dev), ret);
321    }
322    /*
323     * Ignore errors returned by ->probe so that the next driver can try
324     * its luck.
325     */
326    ret = 0;
327done:
328    atomic_dec(&probe_count);
329    wake_up(&probe_waitqueue);
330    return ret;
331}


287-295行,如果定義了dev->bus->probe函數,則調用該函數;如果沒有定義dev->bus->probe函數,但是定義了drv->probe函數,則調用drv->probe函數。這裏,我們一般寫Linux驅動程序時都要實現的probe函數就會被調用了。
297行,調用driver_bound(dev)函數,該函數定義在drivers/base/dd.c文件中,其內容如下:
182static void driver_bound(struct device *dev)
183{
184    if (klist_node_attached(&dev->p->knode_driver)) {
185        printk(KERN_WARNING "%s: device %s already bound\n",
186            __func__, kobject_name(&dev->kobj));
187        return;
188    }
189
190    pr_debug("driver: '%s': %s: bound to device '%s'\n", dev_name(dev),
191         __func__, dev->driver->name);
192
193    klist_add_tail(&dev->p->knode_driver, &dev->driver->p->klist_devices);
194
195    /*
196     * Make sure the device is no longer in one of the deferred lists and
197     * kick off retrying all pending devices
198     */
199    driver_deferred_probe_del(dev);
200    driver_deferred_probe_trigger();
201
202    if (dev->bus)
203        blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
204                         BUS_NOTIFY_BOUND_DRIVER, dev);
205}


193行,調用klist_add_tail函數將device加入到device_driver的driver->p->klist_devices鏈表中。
至此,我們一步一步回退driver_bound->really_probe-> driver_probe_device->__driver_attach->driver_attach->bus_add_driver。
回到bus_add_driver函數:
711行,調用driver_create_file(drv, &driver_attr_uevent)函數,創建屬性文件,driver_attr_uevent定義在drivers/base/bus.c文件中:
671static DRIVER_ATTR(uevent, S_IWUSR, NULL, driver_uevent_store);


DRIVER_ATTR宏定義在include/linux/device.h文件中:
 256#define DRIVER_ATTR(_name, _mode, _show, _store)    \
 257struct driver_attribute driver_attr_##_name =       \
 258    __ATTR(_name, _mode, _show, _store)


__ATTR宏定義在include/linux/sysfs.h文件中:
 71#define __ATTR(_name,_mode,_show,_store) { \
 72    .attr = {.name = __stringify(_name), .mode = _mode },   \
 73    .show   = _show,                    \
 74    .store  = _store,                   \
 75}


回到bus_add_driver函數:
716行,調用driver_add_attrs(bus, drv)函數,爲bus->drv_attrs創建屬性文件。
724行,調用add_bind_files爲driver_attr_unbind和driver_attr_bind創建屬性文件。
回到driver_register函數:
187行,調用driver_add_groups,創建屬性組。
192行,調用kobject_uevent(&drv->p->kobj, KOBJ_ADD),發送uenvnt事件通知用戶空間。
至此,我們就清楚device_driver是怎樣註冊的了。

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