2014-04-03 11:25:47 u014368398 阅读数 814
  • Android底层技术:Java层系统服务(Android Service)

    为什么我们需要学习撰写系统服务呢? 底层系统服务是Android 框架裡接近Linux/Driver 的部分。为了充分发挥硬件设备的差異化特性,系统服务是让上层Java 应用程序來使用Driver/HW Device 特色的重要管道。于此,先仔细解析Java层系统服务的架构,然后阐述这系统服务的代码开发要点,以及其API设计方法。

    32505 人正在学习 去看看 高煥堂

1. 前言

device和device driver是Linux驱动开发的基本概念。Linux kernel的思路很简单:驱动开发,就是要开发指定的软件(driver)以驱动指定的设备,所以kernel就为设备和驱动它的driver定义了两个数据结构,分别是device和device_driver。因此本文将会围绕这两个数据结构,介绍Linux设备模型的核心逻辑,包括:

设备及设备驱动在kernel中的抽象、使用和维护;

设备及设备驱动的注册、加载、初始化原理;

设备模型在实际驱动开发过程中的使用方法。

注:在介绍device和device_driver的过程中,会遇到很多额外的知识点,如Class、Bus、DMA、电源管理等等,这些知识点都很复杂,任何一个都可以作为一个单独的专题区阐述,因此本文不会深入解析它们,而会在后续的文章中专门描述。

2. struct device和struct device_driver

在阅读Linux内核源代码时,通过核心数据结构,即可理解某个模块60%以上的逻辑,设备模型部分尤为明显。

在include/linux/device.h中,Linux内核定义了设备模型中最重要的两个数据结构,struct device和struct device_driver。

  • struct device
 1: /* include/linux/device.h, line 660 */
 2: struct device {
 3:     struct device       *parent;
 4:  
 5:     struct device_private   *p;
 6:  
 7:     struct kobject kobj;
 8:     const char *init_name; /* initial name of the device */
 9:     const struct device_type *type;
 10:  
 11:    struct mutex        mutex; /* mutex to synchronize calls to
 12:                             * its driver.
 13:                             */
 14:  
 15:    struct bus_type *bus; /* type of bus device is on */
 16:    struct device_driver *driver; /* which driver has allocated this
 17:                                 device */
 18:    void *platform_data; /* Platform specific data, device
 19:                         core doesn't touch it */
 20:    struct dev_pm_info  power;
 21:    struct dev_pm_domain    *pm_domain;
 22:  
 23: #ifdef CONFIG_PINCTRL
 24:    struct dev_pin_info *pins;
 25: #endif
 26:  
 27: #ifdef CONFIG_NUMA
 28:    int numa_node; /* NUMA node this device is close to */
 29: #endif
 30:    u64     *dma_mask; /* dma mask (if dma'able device) */
 31:    u64     coherent_dma_mask;/* Like dma_mask, but for
 32:                             alloc_coherent mappings as
 33:                             not all hardware supports
 34:                             64 bit addresses for consistent
 35:                             allocations such descriptors. */
 36:  
 37:    struct device_dma_parameters *dma_parms;
 38:  
 39:    struct list_head    dma_pools; /* dma pools (if dma'ble) */
 40:  
 41:    struct dma_coherent_mem *dma_mem; /* internal for coherent mem
 42:                            override */
 43: #ifdef CONFIG_CMA
 44:    struct cma *cma_area; /* contiguous memory area for dma
 45:                            allocations */
 46: #endif
 47:    /* arch specific additions */
 48:    struct dev_archdata archdata;
 49:  
 50:    struct device_node  *of_node; /* associated device tree node */
 51:    struct acpi_dev_node    acpi_node; /* associated ACPI device node */
 52:  
 53:    dev_t           devt; /* dev_t, creates the sysfs "dev" */
 54:    u32         id; /* device instance */
 55:  
 56:    spinlock_t      devres_lock;
 57:    struct list_head    devres_head;
 58:  
 59:    struct klist_node   knode_class;
 60:    struct class *class;
 61:    const struct attribute_group **groups; /* optional groups */
 62:  
 63:    void (*release)(struct device *dev);
 64:    struct iommu_group  *iommu_group;
 65: };

device结构很复杂(不过linux内核的开发人员素质是很高的,该接口的注释写的非常详细,感兴趣的同学可以参考内核源代码),这里将会选一些对理解设备模型非常关键的字段进行说明。

parent,该设备的父设备,一般是该设备所从属的bus、controller等设备。

p,一个用于struct device的私有数据结构指针,该指针中会保存子设备链表、用于添加到bus/driver/prent等设备中的链表头等等,具体可查看源代码。

kobj,该数据结构对应的struct kobject。

init_name,该设备的名称。

       注1:在设备模型中,名称是一个非常重要的变量,任何注册到内核中的设备,都必须有一个合法的名称,可以在初始化时给出,也可以由内核根据“bus name + device ID”的方式创造。

type,struct device_type结构是新版本内核新引入的一个结构,它和struct device关系,非常类似stuct kobj_type和struct kobject之间的关系,后续会再详细说明。

bus,该device属于哪个总线(后续会详细描述)。

driver,该device对应的device driver。

platform_data,一个指针,用于保存具体的平台相关的数据。具体的driver模块,可以将一些私有的数据,暂存在这里,需要使用的时候,再拿出来,因此设备模型并不关心该指针得实际含义。

power、pm_domain,电源管理相关的逻辑,后续会由电源管理专题讲解。

pins,"PINCTRL”功能,暂不描述。

numa_node,"NUMA”功能,暂不描述。

dma_mask~archdata,DMA相关的功能,暂不描述。

devt,dev_t是一个32位的整数,它由两个部分(Major和Minor)组成,在需要以设备节点的形式(字符设备和块设备)向用户空间提供接口的设备中,当作设备号使用。在这里,该变量主要用于在sys文件系统中,为每个具有设备号的device,创建/sys/dev/* 下的对应目录,如下:

1|root@android:/storage/sdcard0 #ls /sys/dev/char/1\:                                                                     
1:1/  1:11/ 1:13/ 1:14/ 1:2/  1:3/  1:5/  1:7/  1:8/  1:9/  
1|root@android:/storage/sdcard0 #ls /sys/dev/char/1:1                                                                     
1:1/  1:11/ 1:13/ 1:14/ 
1|root@android:/storage/sdcard0 # ls /sys/dev/char/1\:1  
/sys/dev/char/1:1  

class,该设备属于哪个class。

groups,该设备的默认attribute集合。将会在设备注册时自动在sysfs中创建对应的文件。

 

  • struct device_driver
 1: /* include/linux/device.h, line 213 */
 2: struct device_driver {  
 3:     const char *name;  
 4:     struct bus_type     *bus;
 5:  
 6:     struct module       *owner;
 7:     const char *mod_name; /* used for built-in modules */
 8:  
 9:     bool suppress_bind_attrs; /* disables bind/unbind via sysfs */
 10:  
 11:    const struct of_device_id   *of_match_table;
 12:    const struct acpi_device_id *acpi_match_table;
 13:  
 14:    int (*probe) (struct device *dev);
 15:    int (*remove) (struct device *dev);
 16:    void (*shutdown) (struct device *dev);
 17:    int (*suspend) (struct device *dev, pm_message_t state);
 18:    int (*resume) (struct device *dev);
 19:    const struct attribute_group **groups;
 20:  
 21:    const struct dev_pm_ops *pm;
 22:  
 23:    struct driver_private *p;
 24: };

device_driver就简单多了(在早期的内核版本中driver的数据结构为"struct driver”,不知道从哪个版本开始,就改成device_driver了):

name,该driver的名称。和device结构一样,该名称非常重要,后面会再详细说明。

bus,该driver所驱动设备的总线设备。为什么driver需要记录总线设备的指针呢?因为内核要保证在driver运行前,设备所依赖的总线能够正确初始化。

owner、mod_name,內核module相关的变量,暂不描述。

suppress_bind_attrs,是不在sysfs中启用bind和unbind attribute,如下:root@android:/storage/sdcard0 # ls /sys/bus/platform/drivers/switch-gpio/                                                   
bind   uevent unbind 
在kernel中,bind/unbind是从用户空间手动的为driver绑定/解绑定指定的设备的机制。这种机制是在bus.c中完成的,后面会详细解释。

probe、remove,这两个接口函数用于实现driver逻辑的开始和结束。Driver是一段软件code,因此会有开始和结束两个代码逻辑,就像PC程序,会有一个main函数,main函数的开始就是开始,return的地方就是结束。而内核driver却有其特殊性:在设备模型的结构下,只有driver和device同时存在时,才需要开始执行driver的代码逻辑。这也是probe和remove两个接口名称的由来:检测到了设备和移除了设备(就是为热拔插起的!)。

shutdown、suspend、resume、pm,电源管理相关的内容,会在电源管理专题中详细说明。

groups,和struct device结构中的同名变量类似,driver也可以定义一些默认attribute,这样在将driver注册到内核中时,内核设备模型部分的代码(driver/base/driver.c)会自动将这些attribute添加到sysfs中。

p,私有数据的指针,具体的driver代码可以把任何需要的内容放在这里,反正设备模型代码不关心。

3. 设备模型框架下驱动开发的基本步骤

在设备模型框架下,设备驱动的开发是一件很简单的事情,主要包括2个步骤:

步骤1:分配一个struct device类型的变量,填充必要的信息后,把它注册到内核中。

步骤2:分配一个struct device_driver类型的变量,填充必要的信息后,把它注册到内核中。

这两步完成后,内核会在合适的时机(后面会讲),调用struct device_driver变量中的probe、remove、suspend、resume等回调函数,从而触发或者终结设备驱动的执行。而所有的驱动程序逻辑,都会由这些回调函数实现,此时,驱动开发者眼中便不再有“设备模型”,转而只关心驱动本身的实现。

以上两个步骤的补充说明:

1. 一般情况下,Linux驱动开发很少直接使用device和device_driver,因为内核在它们之上又封装了一层,如soc device、platform device等等,而这些层次提供的接口更为简单、易用(也正是因为这个原因,本文并不会过多涉及device、device_driver等模块的实现细节)。

2. 内核提供很多struct device结构的操作接口(具体可以参考include/linux/device.h和drivers/base/core.c的代码),主要包括初始化(device_initialize)、注册到内核(device_register)、分配存储空间+初始化+注册到内核(device_create)等等,可以根据需要使用。

3. device和device_driver必须具备相同的名称,内核才能完成匹配操作,进而调用device_driver中的相应接口。这里的同名,作用范围是同一个bus下的所有device和device_driver

4. device和device_driver必须挂载在一个bus之下,该bus可以是实际存在的,也可以是虚拟的。

5. driver开发者可以在struct device变量中,保存描述设备特征的信息,如寻址空间、依赖的GPIOs等,因为device指针会在执行probe等接口时传入,这时driver就可以根据这些信息,执行相应的逻辑操作了。

4. 设备驱动probe的时机

所谓的"probe”,是指在Linux内核中,如果存在相同名称的device和device_driver,内核就会执行device_driver中的probe回调函数,而该函数就是所有driver的入口,可以执行诸如硬件设备初始化、字符设备注册、设备文件操作ops注册等动作("remove”是它的反操作,发生在device或者device_driver任何一方从内核注销时,其原理类似,就不再单独说明了)。

设备驱动prove的时机有如下几种(分为自动触发和手动触发):

  • 将struct device类型的变量注册到内核中时自动触发(device_register,device_add,device_create_vargs,device_create)
  • 将struct device_driver类型的变量注册到内核中时自动触发(driver_register)
  • 手动查找同一bus下的所有device_driver,如果有和指定device同名的driver,执行probe操作(device_attach)
  • 手动查找同一bus下的所有device,如果有和指定driver同名的device,执行probe操作(driver_attach)
  • 自行调用driver的probe接口,并在该接口中将该driver绑定到某个device结构中----即设置dev->driver(device_bind_driver)

注2:probe动作实际是由bus模块(会在下一篇文章讲解)实现的,这不难理解:device和device_driver都是挂载在bus这根线上,因此只有bus最清楚应该为哪些device、哪些driver配对。

注3:每个bus都有一个drivers_autoprobe变量,用于控制是否在device或者driver注册时,自动probe。该变量默认为1(即自动probe),bus模块将它开放到sysfs中了,因而可在用户空间修改,进而控制probe行为。

5. 其它杂项

5.1 device_attribute和driver_attribute

在"Linux设备模型(4)_sysfs”中,我们有讲到,大多数时候,attribute文件的读写数据流为:vfs---->sysfs---->kobject---->attibute---->kobj_type---->sysfs_ops---->xxx_attribute,其中kobj_type、sysfs_ops和xxx_attribute都是由包含kobject的上层数据结构实现。

Linux内核中关于该内容的例证到处都是,device也不无例外的提供了这种例子,如下:

 1: /* driver/base/core.c, line 118 */
 2: static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
 3: char *buf) 
 4: {   
 5:     struct device_attribute *dev_attr = to_dev_attr(attr);
 6:     struct device *dev = kobj_to_dev(kobj);
 7:     ssize_t ret = -EIO;
 8: 
 9:     if (dev_attr->show)
 10:        ret = dev_attr->show(dev, dev_attr, buf);
 11:        if (ret >= (ssize_t)PAGE_SIZE) {
 12:            print_symbol("dev_attr_show: %s returned bad count\n",
 13:                        (unsigned long)dev_attr->show);
 14:    }
 15:    return ret;
 16: }
 17:  
 18: static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
 19: const char *buf, size_t count)
 20: {
 21:    struct device_attribute *dev_attr = to_dev_attr(attr);
 22:    struct device *dev = kobj_to_dev(kobj);
 23:    ssize_t ret = -EIO;
 24: 
 25:    if (dev_attr->store)
 26:        ret = dev_attr->store(dev, dev_attr, buf, count);
 27:    return ret;
 28: }
 29:  
 30: static const struct sysfs_ops dev_sysfs_ops = {
 31:    .show   = dev_attr_show,
 32:    .store  = dev_attr_store,
 33: };
 34:  
 35: /* driver/base/core.c, line 243 */
 36: static struct kobj_type device_ktype = {
 37:    .release    = device_release,
 38:    .sysfs_ops  = &dev_sysfs_ops,
 39:    .namespace = device_namespace,
 40: };
 41:  
 42: /* include/linux/device.h, line 478 */
 43: /* interface for exporting device attributes */
 44: struct device_attribute {
 45:    struct attribute    attr;
 46:    ssize_t (*show)(struct device *dev, struct device_attribute *attr,
 47:                    char *buf);
 48:    ssize_t (*store)(struct device *dev, struct device_attribute *attr,
 49:                    const char *buf, size_t count);
 50: };

 

至于driver的attribute,则要简单的多,其数据流为:vfs---->sysfs---->kobject---->attribute---->driver_attribute,如下:

 1: /* include/linux/device.h, line 247 */
 2: /* sysfs interface for exporting driver attributes */
 3:  
 4: struct driver_attribute {
 5:     struct attribute attr;
 6:     ssize_t (*show)(struct device_driver *driver, char *buf);
 7:     ssize_t (*store)(struct device_driver *driver, const char *buf,
 8:                     size_t count);
 9: };
 10:  
 11: #define DRIVER_ATTR(_name, _mode, _show, _store)    \
 12: struct driver_attribute driver_attr_##_name =       \
 13:    __ATTR(_name, _mode, _show, _store)

5.2 device_type

device_type是内嵌在struct device结构中的一个数据结构,用于指明设备的类型,并提供一些额外的辅助功能。它的的形式如下:

 1: /* include/linux/device.h, line 467 */
 2: struct device_type {
 3:     const char *name;
 4:     const struct attribute_group **groups;
 5:     int (*uevent)(struct device *dev, struct kobj_uevent_env *env);
 6:     char *(*devnode)(struct device *dev, umode_t *mode,
 7:                     kuid_t *uid, kgid_t *gid);
 8:     void (*release)(struct device *dev);
 9:  
 10:    const struct dev_pm_ops *pm;
 11: };

device_type的功能包括:

  • name表示该类型的名称,当该类型的设备添加到内核时,内核会发出"DEVTYPE=‘name’”类型的uevent,告知用户空间某个类型的设备available了
  • groups,该类型设备的公共attribute集合。设备注册时,会同时注册这些attribute。这就是面向对象中“继承”的概念
  • uevent,同理,所有相同类型的设备,会有一些共有的uevent需要发送,由该接口实现
  • devnode,devtmpfs有关的内容,暂不说明
  • release,如果device结构没有提供release接口,就要查询它所属的type是否提供。用于释放device变量所占的空间

5.3 root device

在sysfs中有这样一个目录:/sys/devices,系统中所有的设备,都归集在该目录下。而该目录是没有意义的,它不代表任何实体的device,因此设备模型提供了两个接口,用于注册和注销这样的一个虚拟设备。具体如下:

 1: /* include/linux/device.h, line 859 */
 2: /*
 3:  * Root device objects for grouping under /sys/devices
 4:  */
 5: extern struct device *__root_device_register(const char *name,
 6: struct module *owner);
 7:  
 8: /*
 9:  * This is a macro to avoid include problems with THIS_MODULE,
 10:  * just as per what is done for device_schedule_callback() above.
 11:  */
 12: #define root_device_register(name) \
 13: __root_device_register(name, THIS_MODULE)
 14:  
 15: extern void root_device_unregister(struct device *root);

该接口会调用device_register函数,向内核中注册一个设备,但是(你也想到了),没必要注册与之对应的driver(顺便提一下,内核中有很多不需要driver的设备,这是之一)。

 

原创文章,转发请注明出处。蜗窝科技,www.wowotech.net

2017-08-05 08:33:47 u010352083 阅读数 1427
  • Android底层技术:Java层系统服务(Android Service)

    为什么我们需要学习撰写系统服务呢? 底层系统服务是Android 框架裡接近Linux/Driver 的部分。为了充分发挥硬件设备的差異化特性,系统服务是让上层Java 应用程序來使用Driver/HW Device 特色的重要管道。于此,先仔细解析Java层系统服务的架构,然后阐述这系统服务的代码开发要点,以及其API设计方法。

    32505 人正在学习 去看看 高煥堂

Linux设备模型中,Bus(总线)是一类特殊的设备,它是连接处理器和其它设备之间的通道(channel)。为了方便设备模型的实现,内核规定,系统中的每个设备都要连接在一个Bus上,这个Bus可以是一个内部Bus、虚拟Bus或者Platform Bus

devicedevice driverLinux驱动开发的基本概念。Linux kernel的思路很简单:驱动开发,就是要开发指定的软件(driver)以驱动指定的设备,所以kernel就为设备和驱动它的driver定义了两个数据结构,分别是devicedevice_driver(本文以http://www.wowotech.net/device_model/device_and_driver.html,http://www.wowotech.net/device_model/bus.html为基础,结合自己的理解和4.1内核的修改)。

bus_type

内核通过struct bus_type结构,抽象Bus

 

 

 

name,该bus的名称,会在sysfs中以目录的形式存在,如platform bussysfs中表现为"/sys/bus/platform”。

dev_name,该名称和下面讲到的struct device结构中的init_name有关。对有些设备而言,允许将设备的名字留空。这样当设备注册到内核后,设备模型的核心逻辑就会用"bus->dev_name+device ID”的形式,为这样的设备生成一个名称。

dev_attrs,被下边的groups取代

bus_groupsdev_groupsdrv_groups,一些默认的attribute,可以在busdevice或者device_driver添加到内核时,自动为它们添加相应的attribute

dev_rootdev_root设备为bus的默认父设备(Default device to use as the parent),但在内核实际实现中,和一个叫sub system的功能有关。

match,一个由具体的bus driver实现的回调函数。当任何属于该Busdevice或者device_driver添加到内核时,内核都会调用该接口,如果新加的devicedevice_driver匹配上了彼此的话,该接口要返回非零值,此时Bus模块的核心逻辑就会执行后续的处理。

uevent,一个由具体的bus driver实现的回调函数。当任何属于该Busdevice,发生添加、移除或者其它动作时,Bus模块的核心逻辑就会调用该接口,以便bus driver能够修改环境变量。

proberemove,这两个回调函数,和device_driver中的非常类似,但它们的存在是非常有意义的。可以想象一下,如果需要probe(其实就是初始化)指定的device话,需要保证该device所在的bus是被初始化过、确保能正确工作的。这就要就在执行device_driverprobe前,先执行它的busproberemove的过程相反。

并不是所有的bus都需要proberemove接口的,因为对有些bus来说(例如platform bus),它本身就是一个虚拟的总线,无所谓初始化,直接就能使用,因此这些busdriver就可以将这两个回调函数留空。

shutdownsuspendresume,和proberemove的原理类似,电源管理相关的实现。

onlineoffline,和属于这个总线设备的online属性相关。

pm,电源管理相关的逻辑。

iommu_ops,总线的IOMMU相关操作,IOMMUMMU功能类似,可以给设备一个内核空间的地址(或叫总线地址),而不限于可以直接访问的常规内存区域。

p,一个struct subsys_private类型的指针,kobject隐藏在这个结构后面。这个结构也很重要。

 

device

 

 

 

device结构很复杂,这里将会选一些对理解设备模型非常关键的字段进行说明。

parent,该设备的父设备,一般是该设备所从属的buscontroller等设备。

p,一个用于设备的私有数据结构指针,保存子设备链表,添加父节点,邻居节点和总线链表等。

kobj,该数据结构对应的struct kobject

init_name,该设备的名称。

在设备模型中,名称是一个非常重要的变量,任何注册到内核中的设备,都必须有一个合法的名称,可以在初始化时给出,也可以由内核根据bus name + device ID”的方式创造。见bus_type.dev_name的说明。

typestruct device_type结构是新版本内核新引入的一个结构,它和struct device关系,非常类似stuct kobj_typestruct kobject之间的关系。

bus,该device属于哪个总线。

driver,该device对应的device driver

platform_data,一个指针,用于保存具体的平台相关的数据。linux经常用来保存一些单板相关的数据,来描述包含哪些设备,以及它们如何互联。以便大幅减少BSP的代码量和驱动中ifdef的使用。

powerpm_domain,电源管理相关的逻辑,后续会由电源管理专题讲解。

pins"PINCTRL”功能。

numa_node"NUMA”功能。

devt,设备号。在这里,该变量主要用于在sys文件系统中,为每个具有设备号的device,创建/sys/dev/*下的对应目录,如下:

 



class,该设备属于哪个class。这从侧面说明了classdevice的集合。

groups,该设备的默认attribute集合。将会在设备注册时自动在sysfs中创建对应的文件。

 

device_driver

 

 

 

name,该driver的名称。和device结构一样,该名称非常重要,和devicedriver的匹配有关。

bus,该driver所驱动设备的总线设备。内核要保证在driver运行前,设备所依赖的总线能够正确初始化。

ownermod_name,內核module相关的变量。

suppress_bind_attrs,通过sysfs启用bindunbindattribute,如下:

# ls /sys/bus/platform/drivers/switch-gpio/                                                  

    bind   uevent    unbind

kernel中,bind/unbind是从用户空间手动的为driver绑定/解绑定指定的设备的机制。

proberemove,这两个接口函数用于实现driver逻辑的开始和结束。在设备模型的结构下,只有driverdevice同时存在时,才需要开始执行driver的代码逻辑。这也是proberemove两个接口名称的由来:检测到了设备和移除了设备(就是为热拔插起的!)。

shutdownsuspendresumepm,电源管理相关的内容。

groups,和struct device结构中的同名变量类似,driver也可以定义一些默认attribute,这样在将driver注册到内核中时,内核设备模型部分的代码会自动将这些attribute添加到sysfs中。

p,私有数据的指针。

 

subsys_private

旧的linux存在独立的子系统数据结构subsystem2.6.35抛弃了这个数据结构。转而用subsys_private表示。

什么是子系统?无论是bus,还是class,还是一些虚拟的子系统,它都构成了一个“子系统(sub-system)”,该子系统会包含形形色色的devicedevice_driver,就像一个独立的王国一样,存在于内核中。而这些子系统的表现形式,就是/sys/bus(或/sys/class,或其它)目录下面的子目录,每一个子目录,都是一个子系统(如/sys/bus/spi/)。从子系统的角度看bus和后面的class很类似,它们都用subsys_private表示子系统。

 

 

 

subsysdevices_ksetdrivers_kset是三个kset。其中subsys,代表了本bus(如/sys/bus/spi),它下面可以包含其它的kset或者其它的kobjectdevices_ksetdrivers_kset则是bus下面的两个kset(如/sys/bus/spi/devices/sys/bus/spi/drivers),分别包括本bus下所有的devicedevice_driverbus_typekobject的关系通过subsys成员体现。通过宏to_subsys_private(obj)可以看出。

interface用于保存该bus下所有的interfaceinterface抽象了此类子系统的专有功能。

klist_devicesklist_drivers,分别保存了本bus下所有的devicedevice_driver的指针,以方便查找。

drivers_autoprobe,用于控制该bus下的drivers或者device是否自动probe

busclass,分别保存上层的bus或者class指针。

 

device_private

 

 

 

klist_childre,包含此设备所有的子设备。

knode_parent,连入父设备的klist_children时所用的节点。

knode_driver,连入驱动的设备链表所用的节点,driver_privateklist_devices节点。

knode_bus,连入总线的设备链表时所用的节点,subsys_privateklist_devices的节点。

deferred_probedeferred_probe_list的入口,deferred_probe_list用来重新绑定那些暂时不能获得device全部资源的驱动,这种情况常常是因为某一个驱动需要另一个驱动首先probe

device,指向包含device_privatedevice

 

driver_private

 

 

 

kboj,结构对应的kobject

klist_devices,包含此驱动可以驱动的设备。

knode_bus,连入bus的驱动链表的节点,代表subsys_privateklist_drivers的节点。

mkobj,内核module相关变量。

driver,指向包含driver_privatedriver

 

device_type

 

 

 

 

name,表示该类型的名称,当该类型的设备添加到内核时,内核会发出"DEVTYPE=name’”类型的uevent,告知用户空间某个类型的设备available了。

groups,该类型设备的公共attribute集合。设备注册时,会同时注册这些attribute。这就是面向对象中“继承”的概念。

uevent,所有相同类型的设备,会有一些共有的uevent需要发送,由该接口实现。

release,如果device结构没有提供release接口,就要查询它所属的type是否提供,用于释放device变量所占的空间。

 

bus_typedevicedevice_driverkobject的关系

devicedevice_driver的角度看

 

 

 

devicedevice_driver直接继承kobjectbus_type通过subsys_privatekobject发生联系。图中ksetkobject的关系是从kset与包含在它里边的kobject的角度看的,与前面ksetkobjcet的关系角度不同。由此可见,总线、设备和驱动是建立在kobject基础上的,借由kobjectkset建立层次关系。

 

bus_typedevicedevice_driver的关系

 

 

 

一个device_driver可以支持多个devicebus_type通过subsys_privatedevice_driverdevice发生关联。

 

bus_typedevicedevice_driversysfs的关系

总线,设备和设备驱动与sysfs的对应关系相对简单直观。

 

核心数据结构或成员

sysfs对应表现形式

bus_type.name

/sys/bus下的目录名

bus_type.dev_name

设备委托给总线给其一个名字,如果设备没有起名,与device_id一起作为/sys/devices下的目录名

device.name

/sys/devices下的目录名

driver.name

/sys/devices下的目录名


2015-03-19 10:34:12 litianze99 阅读数 1842
  • Android底层技术:Java层系统服务(Android Service)

    为什么我们需要学习撰写系统服务呢? 底层系统服务是Android 框架裡接近Linux/Driver 的部分。为了充分发挥硬件设备的差異化特性,系统服务是让上层Java 应用程序來使用Driver/HW Device 特色的重要管道。于此,先仔细解析Java层系统服务的架构,然后阐述这系统服务的代码开发要点,以及其API设计方法。

    32505 人正在学习 去看看 高煥堂

losetup 是一个设置和控制loop device设备的linux命令

loseup可以将文件或者block device与loop device关联、分离以及查询loop device的当前状态。
#循环设备可把文件虚拟成块设备(block device),借以模拟整个文件系统,让用户能使其为硬盘光驱或软盘等设备、
#并挂载(mount)来使用。losetup可用于文件块或者loop device的连接或者设置。
[root@compute-192-168-2-190 ~]# losetup

用dd创建一个2G的空文件
[root@compute-192-168-2-190 ~]# dd if=/dev/zero of=/var/cloud bs=1 count=0 seek=2G
0+0 records in
0+0 records out
0 bytes (0 B) copied, 0.000103106 s, 0.0 kB/s
You have new mail in /var/spool/mail/root
[root@compute-192-168-2-190 ~]# losetup --show -f /var/cloud
/dev/loop2
losetup --show -f /var/cloud  将文件/var/cloud、与loop device设备关联

Usage:
 losetup loop_device                             #give info 列出loop device设备的信息
 [root@compute-192-168-2-190 ~]# losetup /dev/loop1
/dev/loop1: [fd00]:4326534 (/var/youyun)
#列出所有被使用的loop device设备
 losetup -a | --all                              list all used
 [root@compute-192-168-2-190 ~]# losetup -a
/dev/loop0: [fd00]:14417924 (/srv/loopback-device/swift_loopback)
/dev/loop1: [fd00]:4326534 (/var/youyun)
/dev/loop2: [fd00]:4326518 (/var/cloud)
#将一个loop device设备与关联的文件或设备分离
 losetup -d | --detach <loopdev> [<loopdev> ...] delete
 [root@compute-192-168-2-190 ~]# losetup -d /dev/loop1
[root@compute-192-168-2-190 ~]# losetup -a
/dev/loop0: [fd00]:14417924 (/srv/loopback-device/swift_loopback)
/dev/loop2: [fd00]:4326518 (/var/cloud)
#查找一个未使用的loop device
 losetup -f | --find                             find unused
 [root@compute-192-168-2-190 ~]# losetup -f
/dev/loop1
#修改loop device大小
 losetup -c | --set-capacity <loopdev>           resize
 #列出与指定文件相关联的loop device
 losetup -j | --associated <file> [-o <num>]     list all associated with <file>
 [root@compute-192-168-2-190 ~]# losetup -j /var/cloud
/dev/loop2: [fd00]:4326518 (/var/cloud)
[root@compute-192-168-2-190 ~]#
设置文件属性
 losetup [ options ] {-f|--find|loopdev} <file>  setup

Options:
#启动资料编码.下列可用的选项参数:
#NONE
#不编码(定义值).
#XOR
#使用简易的XOR编码
#DES
#使用DES编码.DES编码须在kernel上加上DES编码功能.
#DES编码是利用启始值做为密码保护来防止他人用字典功击法破解.
 -e | --encryption <type> enable data encryption with specified <name/num>
#打印帮助信息
 -h | --help              this help
#设置开始访问时平移的字节数
 -o | --offset <num>      start at offset <num> into file
      --sizelimit <num>   loop limited to only <num> bytes of the file
 -p | --pass-fd <num>     read passphrase from file descriptor <num>
 #设置设备只读
 -r | --read-only         setup read-only loop device
#显示与文件关联的loop device
      --show              print device name (with -f <file>)
 -v | --verbose           verbose mode


2012-10-30 08:09:36 imace1 阅读数 27
  • Android底层技术:Java层系统服务(Android Service)

    为什么我们需要学习撰写系统服务呢? 底层系统服务是Android 框架裡接近Linux/Driver 的部分。为了充分发挥硬件设备的差異化特性,系统服务是让上层Java 应用程序來使用Driver/HW Device 特色的重要管道。于此,先仔细解析Java层系统服务的架构,然后阐述这系统服务的代码开发要点,以及其API设计方法。

    32505 人正在学习 去看看 高煥堂

Writing device drivers in Linux: A brief tutorial

转自:http://fsmsh.com/1238

Pre-requisites

In order to develop Linux device drivers, it is necessary to have an understanding of the following:

  • C programming . Some in-depth knowledge of C programming is needed, like pointer usage, bit manipulating functions, etc.
  • Microprocessor programming . It is necessary to know how microcomputers work internally: memory addressing, interrupts, etc. All of these concepts should be familiar to an assembler programmer.

There are several different devices in Linux. For simplicity, this brief tutorial will only cover type char devices loaded as modules. Kernel 2.6.x will be used (in particular, kernel 2.6.8 under Debian Sarge, which is now Debian Stable).

User space and kernel space

When you write device drivers, it’s important to make the distinction between “user space” and “kernel space”.

  • Kernel space . Linux (which is a kernel) manages the machine's hardware in a simple and efficient manner, offering the user a simple and uniform programming interface. In the same way, the kernel, and in particular its device drivers, form a bridge or interface between the end-user/programmer and the hardware. Any subroutines or functions forming part of the kernel (modules and device drivers, for example) are considered to be part of kernel space.
  • User space . End-user programs, like the UNIX shell or other GUI based applications (kpresenter for example), are part of the user space. Obviously, these applications need to interact with the system's hardware . However, they don’t do so directly, but through the kernel supported functions.

All of this is shown in figure 1.

Figure 1: User space where applications reside, and kernel space where modules or device drivers reside Figure 1: User space where applications reside, and kernel space where modules or device drivers reside

Interfacing functions between user space and kernel space

The kernel offers several subroutines or functions in user space, which allow the end-user application programmer to interact with the hardware. Usually, in UNIX or Linux systems, this dialogue is performed through functions or subroutines in order to read and write files. The reason for this is that in Unix devices are seen, from the point of view of the user, as files.

On the other hand, in kernel space Linux also offers several functions or subroutines to perform the low level interactions directly with the hardware, and allow the transfer of information from kernel to user space.

Usually, for each function in user space (allowing the use of devices or files), there exists an equivalent in kernel space (allowing the transfer of information from the kernel to the user and vice-versa). This is shown in Table 1, which is, at this point, empty. It will be filled when the different device drivers concepts are introduced.

Events User functions Kernel functions
Load module
Open device
Read device
Write device
Close device
Remove module

Table 1. Device driver events and their associated interfacing functions in kernel space and user space.

Interfacing functions between kernel space and the hardware device

There are also functions in kernel space which control the device or exchange information between the kernel and the hardware. Table 2 illustrates these concepts. This table will also be filled as the concepts are introduced.

Events Kernel functions
Read data
Write data

Table 2. Device driver events and their associated functions between kernel space and the hardware device.

The first driver: loading and removing the driver in user space

I’ll now show you how to develop your first Linux device driver, which will be introduced in the kernel as a module.

For this purpose I’ll write the following program in a file named nothing.c

<nothing.c> =

 

#include <linux/module.h>

MODULE_LICENSE("Dual BSD/GPL");
 

Since the release of kernel version 2.6.x, compiling modules has become slightly more complicated. First, you need to have a complete, compiled kernel source-code-tree. If you have a Debian Sarge system, you can follow the steps in Appendix B (towards the end of this article). In the following, I’ll assume that a kernel version 2.6.8 is being used.

Next, you need to generate a makefile. The makefile for this example, which should be named Makefile , will be:

<Makefile1> =

obj-m := nothing.o

Unlike with previous versions of the kernel, it’s now also necessary to compile the module using the same kernel that you’re going to load and use the module with. To compile it, you can type:

$ make -C /usr/src/kernel-source-2.6.8 M= pwd modules

This extremely simple module belongs to kernel space and will form part of it once it’s loaded.

In user space, you can load the module as root by typing the following into the command line:

# insmod nothing.ko

The insmod command allows the installation of the module in the kernel. However, this particular module isn’t of much use.

It is possible to check that the module has been installed correctly by looking at all installed modules:

# lsmod

Finally, the module can be removed from the kernel using the command:

# rmmod nothing

By issuing the lsmod command again, you can verify that the module is no longer in the kernel.

The summary of all this is shown in Table 3.

Events User functions Kernel functions
Load module insmod
Open device
Read device
Write device
Close device
Remove module rmmod

Table 3. Device driver events and their associated interfacing functions between kernel space and user space.

The “Hello world” driver: loading and removing the driver in kernel space

When a module device driver is loaded into the kernel, some preliminary tasks are usually performed like resetting the device, reserving RAM, reserving interrupts, and reserving input/output ports, etc.

These tasks are performed, in kernel space, by two functions which need to be present (and explicitly declared): module_init and module_exit ; they correspond to the user space commands insmod and rmmod , which are used when installing or removing a module. To sum up, the user commands insmod and rmmod use the kernel space functions module_init and module_exit .

Let’s see a practical example with the classic program Hello world :

<hello.c> =

 

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void) {
  printk("<1> Hello world!\n");
  return 0;
}

static void hello_exit(void) {
  printk("<1> Bye, cruel world\n");
}

module_init(hello_init);
 

The actual functions hello_init and hello_exit can be given any name desired. However, in order for them to be identified as the corresponding loading and removing functions, they have to be passed as parameters to the functions module_init and module_exit .

The printk function has also been introduced. It is very similar to the well known printf apart from the fact that it only works inside the kernel. The <1> symbol shows the high priority of the message (low number). In this way, besides getting the message in the kernel system log files, you should also receive this message in the system console.

This module can be compiled using the same command as before, after adding its name into the Makefile.

<Makefile2> =

obj-m := nothing.o hello.o 

In the rest of the article, I have left the Makefiles as an exercise for the reader. A complete Makefile that will compile all of the modules of this tutorial is shown in Appendix A.

When the module is loaded or removed, the messages that were written in the printk statement will be displayed in the system console. If these messages do not appear in the console, you can view them by issuing the dmesg command or by looking at the system log file with cat /var/log/syslog .

Table 4 shows these two new functions.

Events User functions Kernel functions
Load module insmod module_init()
Open device
Read device
Write device
Close device
Remove module rmmod module_exit()

Table 4. Device driver events and their associated interfacing functions between kernel space and user space.

The complete driver “memory”: initial part of the driver

I’ll now show how to build a complete device driver: memory.c . This device will allow a character to be read from or written into it. This device, while normally not very useful, provides a very illustrative example since it is a complete driver; it's also easy to implement, since it doesn’t interface to a real hardware device (besides the computer itself).

To develop this driver, several new #include statements which appear frequently in device drivers need to be added:

<memory initial> =

/* Necessary includes for device drivers */
#include <linux/init.h>
#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h> /* printk() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/fs.h> /* everything... */
#include <linux/errno.h> /* error codes */
#include <linux/types.h> /* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h> /* O_ACCMODE */
#include <asm/system.h> /* cli(), *_flags */
#include <asm/uaccess.h> /* copy_from/to_user */

MODULE_LICENSE("Dual BSD/GPL");

/* Declaration of memory.c functions */
int memory_open(struct inode *inode, struct file *filp);
int memory_release(struct inode *inode, struct file *filp);
ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);
ssize_t memory_write(struct file *filp, char *buf, size_t count, loff_t *f_pos);
void memory_exit(void);
int memory_init(void);

/* Structure that declares the usual file */
/* access functions */
struct file_operations memory_fops = {
  read: memory_read,
  write: memory_write,
  open: memory_open,
  release: memory_release
};

/* Declaration of the init and exit functions */
module_init(memory_init);
module_exit(memory_exit);

/* Global variables of the driver */
/* Major number */
int memory_major = 60;
/* Buffer to store data */
char *memory_buffer;
 

 

After the #include files, the functions that will be defined later are declared. The common functions which are typically used to manipulate files are declared in the definition of the file_operations structure. These will also be explained in detail later. Next, the initialization and exit functions—used when loading and removing the module—are declared to the kernel. Finally, the global variables of the driver are declared: one of them is the major number of the driver, the other is a pointer to a region in memory, memory_buffer , which will be used as storage for the driver data.

The “memory” driver: connection of the device with its files

In UNIX and Linux, devices are accessed from user space in exactly the same way as files are accessed. These device files are normally subdirectories of the /dev directory.

To link normal files with a kernel module two numbers are used: major number and minor number . The major number is the one the kernel uses to link a file with its driver. The minor number is for internal use of the device and for simplicity it won’t be covered in this article.

To achieve this, a file (which will be used to access the device driver) must be created, by typing the following command as root:

# mknod /dev/memory c 60 0

In the above, c means that a char device is to be created, 60 is the major number and 0 is the minor number .

Within the driver, in order to link it with its corresponding /dev file in kernel space, the register_chrdev function is used. It is called with three arguments: major number , a string of characters showing the module name, and a file_operations structure which links the call with the file functions it defines. It is invoked, when installing the module, in this way:

<memory init module> =

int memory_init(void) {
  int result;

  /* Registering device */
  result = register_chrdev(memory_major, "memory", &memory_fops);
  if (result < 0) {
    printk(
      "<1>memory: cannot obtain major number %d\n", memory_major);
    return result;
  }

  /* Allocating memory for the buffer */
  memory_buffer = kmalloc(1, GFP_KERNEL); 
  if (!memory_buffer) { 
    result = -ENOMEM;
    goto fail; 
  } 
  memset(memory_buffer, 0, 1);

  printk("<1>Inserting memory module\n"); 
  return 0;

  fail: 
    memory_exit(); 
    return result;
}
 

Also, note the use of the kmalloc function. This function is used for memory allocation of the buffer in the device driver which resides in kernel space. Its use is very similar to the well known malloc function. Finally, if registering the major number or allocating the memory fails, the module acts accordingly.

The “memory” driver: removing the driver

In order to remove the module inside the memory_exit function, the function unregsiter_chrdev needs to be present. This will free the major number for the kernel.

<memory exit module> =

 

void memory_exit(void) {
  /* Freeing the major number */
  unregister_chrdev(memory_major, "memory");

  /* Freeing buffer memory */
  if (memory_buffer) {
    kfree(memory_buffer);
  }

  printk("<1>Removing memory module\n");

}
 

The buffer memory is also freed in this function, in order to leave a clean kernel when removing the device driver.

The “memory” driver: opening the device as a file

The kernel space function, which corresponds to opening a file in user space (fopen ), is the member open: of the file_operations structure in the call to register_chrdev . In this case, it is the memory_open function. It takes as arguments: an inode structure, which sends information to the kernel regarding the major number and minor number ; and a file structure with information relative to the different operations that can be performed on a file. Neither of these functions will be covered in depth within this article.

When a file is opened, it’s normally necessary to initialize driver variables or reset the device. In this simple example, though, these operations are not performed.

The memory_open function can be seen below:

<memory open> =

int memory_open(struct inode *inode, struct file *filp) {

  /* Success */
  return 0;
}

This new function is now shown in Table 5.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Read device
Write device
Close device
Remove module rmmod module_exit()

Table 5. Device driver events and their associated interfacing functions between kernel space and user space.

The “memory” driver: closing the device as a file

The corresponding function for closing a file in user space (fclose ) is the release: member of the file_operations structure in the call to register_chrdev . In this particular case, it is the function memory_release , which has as arguments an inode structure and a file structure, just like before.

When a file is closed, it’s usually necessary to free the used memory and any variables related to the opening of the device. But, once again, due to the simplicity of this example, none of these operations are performed.

The memory_release function is shown below:

<memory release> =

int memory_release(struct inode *inode, struct file *filp) {
 
  /* Success */
  return 0;
}

This new function is shown in Table 6.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Read device
Write device
Close device fclose file_operations: release
Remove module rmmod module_exit()

Table 6. Device driver events and their associated interfacing functions between kernel space and user space.

The “memory” driver: reading the device

To read a device with the user function fread or similar, the member read: of the file_operations structure is used in the call to register_chrdev . This time, it is the function memory_read . Its arguments are: a type file structure; a buffer (buf ), from which the user space function (fread ) will read; a counter with the number of bytes to transfer (count ), which has the same value as the usual counter in the user space function (fread ); and finally, the position of where to start reading the file (f_pos ).

In this simple case, the memory_read function transfers a single byte from the driver buffer (memory_buffer ) to user space with the function copy_to_user :

<memory read> =

ssize_t memory_read(struct file *filp, char *buf, 
                    size_t count, loff_t *f_pos) { 
 
  /* Transfering data to user space */ 
  copy_to_user(buf,memory_buffer,1);

  /* Changing reading position as best suits */ 
  if (*f_pos == 0) { 
    *f_pos+=1; 
    return 1; 
  } else { 
    return 0; 
  }
}
 

 

The reading position in the file (f_pos ) is also changed. If the position is at the beginning of the file, it is increased by one and the number of bytes that have been properly read is given as a return value, 1 . If not at the beginning of the file, an end of file (0 ) is returned since the file only stores one byte.

In Table 7 this new function has been added.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Read device fread file_operations: read
Write device
Close device fclose file_operations: release
Remove modules rmmod module_exit()

Table 7. Device driver events and their associated interfacing functions between kernel space and user space.

The “memory” driver: writing to a device

To write to a device with the user function fwrite or similar, the member write: of the file_operations structure is used in the call to register_chrdev . It is the function memory_write , in this particular example, which has the following as arguments: a type file structure; buf , a buffer in which the user space function (fwrite ) will write; count , a counter with the number of bytes to transfer, which has the same values as the usual counter in the user space function (fwrite ); and finally, f_pos , the position of where to start writing in the file.

<memory write> =

ssize_t memory_write( struct file *filp, char *buf,
                      size_t count, loff_t *f_pos) {

  char *tmp;

  tmp=buf+count-1;
  copy_from_user(memory_buffer,tmp,1);
  return 1;
}

In this case, the function copy_from_user transfers the data from user space to kernel space.

In Table 8 this new function is shown.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Close device fread file_operations: read
Write device fwrite file_operations: write
Close device fclose file_operations: release
Remove module rmmod module_exit()

Device driver events and their associated interfacing functions between kernel space and user space.

The complete “memory” driver

By joining all of the previously shown code, the complete driver is achieved:

<memory.c> =

<memory initial>
<memory init module>
<memory exit module>
<memory open>
<memory release>
<memory read>
<memory write>

Before this module can be used, you will need to compile it in the same way as with previous modules. The module can then be loaded with:

# insmod memory.ko

It’s also convenient to unprotect the device:

# chmod 666 /dev/memory

If everything went well, you will have a device /dev/memory to which you can write a string of characters and it will store the last one of them. You can perform the operation like this:

$ echo -n abcdef >/dev/memory

To check the content of the device you can use a simple cat :

$ cat /dev/memory

The stored character will not change until it is overwritten or the module is removed.

The real “parlelport” driver: description of the parallel port

I’ll now proceed by modifying the driver that I just created to develop one that does a real task on a real device. I’ll use the simple and ubiquitous computer parallel port and the driver will be called parlelport .

The parallel port is effectively a device that allows the input and output of digital information. More specifically it has a female D-25 connector with twenty-five pins. Internally, from the point of view of the CPU, it uses three bytes of memory. In a PC, the base address (the one from the first byte of the device) is usually 0x378 . In this basic example, I’ll use just the first byte, which consists entirely of digital outputs.

The connection of the above-mentioned byte with the external connector pins is shown in figure 2.

Figure 2: The first byte of the parallel port and its pin connections with the external female D-25 connector Figure 2: The first byte of the parallel port and its pin connections with the external female D-25 connector

The “parlelport” driver: initializing the module

The previous memory_init function needs modification—changing the RAM memory allocation for the reservation of the memory address of the parallel port (0x378 ). To achieve this, use the function for checking the availability of a memory region (check_region ), and the function to reserve the memory region for this device (request_region ). Both have as arguments the base address of the memory region and its length. The request_region function also accepts a string which defines the module.

<parlelport modified init module> =

  /* Registering port */
  port = check_region(0x378, 1);
  if (port) { 
    printk("<1>parlelport: cannot reserve 0x378\n"); 
    result = port; 
    goto fail;
  } 
  request_region(0x378, 1, "parlelport");

The “parlelport” driver: removing the module

It will be very similar to the memory module but substituting the freeing of memory with the removal of the reserved memory of the parallel port. This is done by the release_region function, which has the same arguments as check_region .

<parlelport modified exit module> =

  /* Make port free! */ 
  if (!port) { 
    release_region(0x378,1);
  }

The “parlelport” driver: reading the device

In this case, a real device reading action needs to be added to allow the transfer of this information to user space. The inb function achieves this; its arguments are the address of the parallel port and it returns the content of the port.

<parlelport inport> =

/* Reading port */
parlelport_buffer = inb(0x378);

Table 9 (the equivalent of Table 2) shows this new function.

Events Kernel functions
Read data inb
Write data

Device driver events and their associated functions between kernel space and the hardware device.

The “parlelport” driver: writing to the device

Again, you have to add the “writing to the device” function to be able to transfer later this data to user space. The function outb accomplishes this; it takes as arguments the content to write in the port and its address.

<parlelport outport> =

/* Writing to the port */
outb(parlelport_buffer,0x378);

Table 10 summarizes this new function.

Events Kernel functions
Read data inb
Write data outb

Device driver events and their associated functions between kernel space and the hardware device.

The complete “parlelport” driver

I’ll proceed by looking at the whole code of the parlelport module. You have to replace the word memory for the word parlelport throughout the code for the memory module. The final result is shown below:

<parlelport.c> =

<parlelport initial>
<parlelport init module>
<parlelport exit module>
<parlelport open>
<parlelport release>
<parlelport read>
<parlelport write>

Initial section

In the initial section of the driver a different major number is used (61 ). Also, the global variable memory_buffer is changed to port and two more #include lines are added: ioport.h and io.h .

<parlelport initial> =

/* Necessary includes for drivers */
#include <linux/init.h>
#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h> /* printk() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/fs.h> /* everything... */
#include <linux/errno.h> /* error codes */
#include <linux/types.h> /* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h> /* O_ACCMODE */
#include <linux/ioport.h>
#include <asm/system.h> /* cli(), *_flags */
#include <asm/uaccess.h> /* copy_from/to_user */
#include <asm/io.h> /* inb, outb */

MODULE_LICENSE("Dual BSD/GPL");

/* Function declaration of parlelport.c */ 
int parlelport_open(struct inode *inode, struct file *filp); 
int parlelport_release(struct inode *inode, struct file *filp); 
ssize_t parlelport_read(struct file *filp, char *buf, 
                       size_t count, loff_t *f_pos); 
ssize_t parlelport_write(struct file *filp, char *buf, 
                       size_t count, loff_t *f_pos); 
void parlelport_exit(void);
int parlelport_init(void);

/* Structure that declares the common */
/* file access fcuntions */
struct file_operations parlelport_fops = { 
  read: parlelport_read,
  write: parlelport_write,
  open: parlelport_open,
  release: parlelport_release
};

/* Driver global variables */
/* Major number */
int parlelport_major = 61;

/* Control variable for memory */ 
/* reservation of the parallel port*/
int port;

module_init(parlelport_init);
module_exit(parlelport_exit);
 

Module init

In this module-initializing-routine I’ll introduce the memory reserve of the parallel port as was described before.

<parlelport init module> =

Removing the module

This routine will include the modifications previously mentioned.

<parlelport exit module> =

void parlelport_exit(void) {

  /* Make major number free! */
  unregister_chrdev(parlelport_major, "parlelport");

  <parlelport modified exit module>

  printk("<1>Removing parlelport module\n");
}

Opening the device as a file

This routine is identical to the memory driver.

<parlelport open> =

int parlelport_open(struct inode *inode, struct file *filp) {

  /* Success */
  return 0;

}

Closing the device as a file

Again, the match is perfect.

<parlelport release> =

int parlelport_release(struct inode *inode, struct file *filp) {

  /* Success */
  return 0; 
}

Reading the device

The reading function is similar to the memory one with the corresponding modifications to read from the port of a device.

<parlelport read> =

ssize_t parlelport_read(struct file *filp, char *buf, 
  size_t count, loff_t *f_pos) {
 
  /* Buffer to read the device */
  char parlelport_buffer;

  <parlelport inport>

  /* We transfer data to user space */
  copy_to_user(buf,&parlelport_buffer,1); 
  
  /* We change the reading position as best suits */
  if (*f_pos == 0) { 
    *f_pos+=1; 
    return 1; 
  } else { 
    return 0; 
  }
}

Writing to the device

It is analogous to the memory one except for writing to a device.

<parlelport write> =

ssize_t parlelport_write( struct file *filp, char *buf, 
  size_t count, loff_t *f_pos) {

  char *tmp;

  /* Buffer writing to the device */
  char parlelport_buffer;

  tmp=buf+count-1;
  copy_from_user(&parlelport_buffer,tmp,1);

  <parlelport outport>
  
  return 1; 
}

LEDs to test the use of the parallel port

In this section I’ll detail the construction of a piece of hardware that can be used to visualize the state of the parallel port with some simple LEDs.

WARNING: Connecting devices to the parallel port can harm your computer. Make sure that you are properly earthed and your computer is turned off when connecting the device. Any problems that arise due to undertaking these experiments is your sole responsibility.

The circuit to build is shown in figure 3 You can also read “PC & Electronics: Connecting Your PC to the Outside World” by Zoller as reference.

In order to use it, you must first ensure that all hardware is correctly connected. Next, switch off the PC and connect the device to the parallel port. The PC can then be turned on and all device drivers related to the parallel port should be removed (for example, lp , parport , parport_pc , etc.). The hotplug module of the Debian Sarge distribution is particularly annoying and should be removed. If the file /dev/parlelport does not exist, it must be created as root with the command:

# mknod /dev/parlelport c 61 0

Then it needs to be made readable and writable by anybody with:

# chmod 666 /dev/parlelport

The module can now be installed, parlelport . You can check that it is effectively reserving the input/output port addresses 0x378 with the command:

$ cat /proc/ioports

To turn on the LEDs and check that the system is working, execute the command:

$ echo -n A >/dev/parlelport

This should turn on LED zero and six, leaving all of the others off.

You can check the state of the parallel port issuing the command:

$ cat /dev/parlelport

Figure 3: Electronic diagram of the LED matrix to monitor the parallel port Figure 3: Electronic diagram of the LED matrix to monitor the parallel port

Final application: flashing lights

Finally, I’ll develop a pretty application which will make the LEDs flash in succession. To achieve this, a program in user space needs to be written with which only one bit at a time will be written to the /dev/parlelport device.

<lights.c> =

#include <stdio.h>
#include <unistd.h></p>

int main() { 
  unsigned char byte,dummy;
  FILE * PARLELPORT;

  /* Opening the device parlelport */
  PARLELPORT=fopen("/dev/parlelport","w");
  /* We remove the buffer from the file i/o */
  setvbuf(PARLELPORT,&dummy,_IONBF,1);

  /* Initializing the variable to one */
  byte=1;

  /* We make an infinite loop */
  while (1) { 
    /* Writing to the parallel port */
    /* to turn on a LED */
    printf("Byte value is %d\n",byte);
    fwrite(&byte,1,1,PARLELPORT);
    sleep(1);

    /* Updating the byte value */
    byte<<=1;
    if (byte == 0) byte = 1;
  }

  fclose(PARLELPORT);

}
 

It can be compiled in the usual way:

$ gcc -o lights lights.c

and can be executed with the command:

$ lights

The lights will flash successively one after the other! The flashing LEDs and the Linux computer running this program are shown in figure 4.

Conclusion

Having followed this brief tutorial you should now be capable of writing your own complete device driver for simple hardware like a relay board (see Appendix C), or a minimal device driver for complex hardware. Learning to understand some of these simple concepts behind the Linux kernel allows you, in a quick and easy way, to get up to speed with respect to writing device drivers. And, this will bring you another step closer to becoming a true Linux kernel developer.

Figure 4: Flashing LEDs mounted on the circuit board and the computer running Linux. Two terminals are shown: one where the “parlelport” module is loaded and another one where the “lights” program is run. Tux is closely following what is going on Figure 4: Flashing LEDs mounted on the circuit board and the computer running Linux. Two terminals are shown: one where the “parlelport” module is loaded and another one where the “lights” program is run. Tux is closely following what is going on

Bibliography

A. Rubini, J. Corbert. 2001. Linux device drivers (second edition) . Ed. O’Reilly. This book is available for free on the internet.

Jonathan Corbet. 2003/2004. Porting device drivers to the 2.6 kernel . This is a very valuable resource for porting drivers to the new 2.6 Linux kernel and also for learning about Linux device drivers.

B. Zoller. 1998. PC & Electronics: Connecting Your PC to the Outside World (Productivity Series). Nowadays it is probably easier to surf the web for hardware projects like this one.

M. Waite, S. Prata. 1990. C Programming. Any other good book on C programming would suffice.

Appendix A. Complete Makefile

<Makefile> =

obj-m := nothing.o hello.o memory.o parlelport.o

Appendix B. Compiling the kernel on a Debian Sarge system

To compile a 2.6.x kernel on a Debian Sarge system you need to perform the following steps, which should be run as root:

  1. Install the “kernel-image-2.6.x” package.
  2. Reboot the machine to make this the running kernel image. This is done semi-automatically by Debian. You may need to tweak the lilo configuration file /etc/lilo.conf and then run lilo to achieve this.
  3. Install the “kernel-source-2.6.x” package.
  4. Change to the source code directory, cd /usr/src and unzip and untar the source code with bunzip2 kernel-source-2.6.x.tar.bz2 and tar xvf kernel-source-2.6.x.tar . Change to the kernel source directory with cd /usr/src/kernel-source-2.6.x
  5. Copy the default Debian kernel configuration file to your local kernel source directory cp /boot/config-2.6.x .config .
  6. Make the kernel and the modules with make and then make modules .

Appendix C. Exercises

If you would like to take on some bigger challenges, here are a couple of exercises you can do:

  1. I once wrote two device drivers for two ISA Meilhaus boards, an analog to digital converter (ME26) and a relay control board (ME53). The software is available from the ADQ project. Get the newer PCI versions of these Meilhaus boards and update the software.
  2. Take any device that doesn’t work on Linux, but has a very similar chipset to another device which does have a proven device driver for Linux. Try to modify the working device driver to make it work for the new device. If you achieve this, submit your code to the kernel and become a kernel developer yourself!

Comments and acknowledgements

Three years have elapsed since the first version of this document was written. It was originally written in Spanish and intended for version 2.2 of the kernel, but kernel 2.4 was already making its first steps at that time. The reason for this choice is that good documentation for writing device drivers, the Linux device drivers book (see bibliography), lagged the release of the kernel in some months. This new version is also coming out soon after the release of the new 2.6 kernel, but up to date documentation is now readily available in Linux Weekly News making it possible to have this document synchronized with the newest kernel.

Fortunately enough, PCs still come with a built-in parallel port, despite the actual trend of changing everything inside a PC to render it obsolete in no time. Let us hope that PCs still continue to have built-in parallel ports for some time in the future, or that at least, parallel port PCI cards are still being sold.

This tutorial has been originally typed using a text editor (i.e. emacs ) in noweb format. This text is then processed with the noweb tool to create a LaTeX file ( .tex ) and the source code files ( .c ). All this can be done using the supplied makefile.document with the command make -f makefile.document .

I would like to thank the “Instituto Politécnico de Bragança”, the “Núcleo Estudantil de Linux del Instituto Politécnico de Bragança (NUX)”, the “Asociación de Software Libre de León (SLeón)” and the “Núcleo de Estudantes de Engenharia Informática da Universidade de Évora” for making this update possible.

2018-07-11 20:41:25 lujian186 阅读数 83
  • Android底层技术:Java层系统服务(Android Service)

    为什么我们需要学习撰写系统服务呢? 底层系统服务是Android 框架裡接近Linux/Driver 的部分。为了充分发挥硬件设备的差異化特性,系统服务是让上层Java 应用程序來使用Driver/HW Device 特色的重要管道。于此,先仔细解析Java层系统服务的架构,然后阐述这系统服务的代码开发要点,以及其API设计方法。

    32505 人正在学习 去看看 高煥堂

Linux代码版本:linux3.0

开发板环境: tiny4412

导读:前面先后分析了kset、kobject、bus和class,其中在bus和class的代码之中已经展示了对kobject和kset的应用,而bus和class中的一些结构体成员并没有涉及,在device和driver的注册过程中,将会展示一些成员的用途。

一、device结构体

linux中有各种各样的设备,不同的设备有不同的属性,但是这些设备又有一些共同点,所以device结构体所谓所有类型设备的基类,然后再根据不同的设备封装不同的结构体。下面将介绍device和platform_device结构体,然后分析一个i2c控制器的注册过程。

struct device {
	struct device		*parent;

	struct device_private	*p;

	struct kobject kobj;
	const char		*init_name; /* initial name of the device */
	const struct device_type *type;

	struct mutex		mutex;	/* mutex to synchronize calls to
					 * its driver.
					 */

	struct bus_type	*bus;		/* type of bus device is on */
	struct device_driver *driver;	/* which driver has allocated this
					   device */
	void		*platform_data;	/* Platform specific data, device
					   core doesn't touch it */
	struct dev_pm_info	power;
	struct dev_power_domain	*pwr_domain;

#ifdef CONFIG_NUMA
	int		numa_node;	/* NUMA node this device is close to */
#endif
	u64		*dma_mask;	/* dma mask (if dma'able device) */
	u64		coherent_dma_mask;/* Like dma_mask, but for
					     alloc_coherent mappings as
					     not all hardware supports
					     64 bit addresses for consistent
					     allocations such descriptors. */

	struct device_dma_parameters *dma_parms;

	struct list_head	dma_pools;	/* dma pools (if dma'ble) */

	struct dma_coherent_mem	*dma_mem; /* internal for coherent mem
					     override */
#ifdef CONFIG_DMA_CMA
	struct cma	*cma_area;	/* contiguous memory area for dma
						allocation */
#endif
	/* arch specific additions */
	struct dev_archdata	archdata;

	struct device_node	*of_node; /* associated device tree node */

	dev_t			devt;	/* dev_t, creates the sysfs "dev" */

	spinlock_t		devres_lock;
	struct list_head	devres_head;

	struct klist_node	knode_class;
	struct class		*class;
	const struct attribute_group **groups;	/* optional groups */

	void	(*release)(struct device *dev);
};

struct device *parent;
device的父设备
struct device_private *p;
device的私有结构体
struct kobject kobj;
device封装的kobj,bus,kset和class最终也都封装了kobject
const char *init_name; /* initial name of the device */
device初始化的名字
const struct device_type *type;
device的类型如partitions、disks和mouse等
struct mutex mutex; /* mutex to synchronize calls to * its driver. */
信号量,操作结构体成员时使用
struct bus_type *bus; /* type of bus device is on */
挂接的bus类型
struct device_driver *driver; /* which driver has allocated thisdevice */
该device对应的driver
void *platform_data; /* Platform specific data, device core doesn't touch it */
platform使用的特殊数据
struct dev_pm_info power;
电源管理相关
struct dev_power_domain *pwr_domain;
电源管理相关
struct device_node *of_node; /* associated device tree node */
device tree相关的node
dev_t   devt; /* dev_t, creates the sysfs "dev" */
设备号
struct klist_node knode_class;
用于挂接在class的链表
struct class *class;
device所属的class
const struct attribute_group **groups; /* optional groups */
属性组,用于创建属性属性文件
void (*release)(struct device *dev);
释放device结构体的时候使用

 

struct platform_device {
	const char    * name;
	int    id;
	struct device	dev;
	u32    num_resources;
	struct resource	* resource;

	const struct platform_device_id	*id_entry;

	/* MFD cell pointer */
	struct mfd_cell *mfd_cell;

	/* arch specific additions */
	struct pdev_archdata	archdata;
};

 

const char * name:

设备名字

int id:

设备id号,只有一个此类设备的话设置-1,多个有同类设备在创建设备目录的时候会带上此id号

struct device dev:

封装的device结构体;

u32 num_resources;

所占用的resources的个数

struct resource * resource:

所占用的resource,如IORESOURCE_MEM和IORESOURCE_IRQ等

const struct platform_device_id *id_entry:

和驱动中的id_table相关,当通过驱动 id_table 匹配上时,将匹配到的id_table赋值给id_entry,暂时不知道实际用途

遇到的时候再分析

二、platform_device实例

虽然i2c本身也是一种总线,但是其也挂接在platform总线上。因为重点是platform_device的注册过程,所以对涉及i2c的一些细节不再分析(如硬件资源)。下面的代码还是原始在plat和mach中声明platform_device形式,device tree的形式等分析device tree的时候再详细看。

struct platform_device s3c_device_i2c3 = {
	.name		  = "s3c2440-i2c",
	.id		  = 3,
	.num_resources	  = ARRAY_SIZE(s3c_i2c_resource),
	.resource	  = s3c_i2c_resource,
};
static struct platform_device *torbreck_devices[] __initdata = {
	&s5pv210_device_iis0,
	&s3c_device_cfcon,
	&s3c_device_hsmmc0,
	&s3c_device_hsmmc1,
	&s3c_device_hsmmc2,
	&s3c_device_hsmmc3,
	&s3c_device_i2c0,
	&s3c_device_i2c3,
	&s3c_device_i2c4,
	&s3c_device_rtc,
	&s3c_device_wdt,
};&s3c_device_i2c3,
	&s3c_device_i2c4,
	&s3c_device_rtc,
	&s3c_device_wdt,
};
static void __init torbreck_machine_init(void)
{
        .......
	platform_add_devices(torbreck_devices, ARRAY_SIZE(torbreck_devices));
}	platform_add_devices(torbreck_devices, ARRAY_SIZE(torbreck_devices));
}

 

将上面的过程简化 就是

 

 

int platform_device_register(struct platform_device *pdev)
{
	device_initialize(&pdev->dev);
    {
    	/**初始化 s3c_device_i2c3->dev->kobj.kset = devices_kset,还记得sys下的deivces目录吗
        devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);*/
        dev->kobj.kset = devices_kset;
        /*初始化 s3c_device_i2c3->dev->kobj->ktype = &device_ktype,device设备kobj类型为device_ktype,
        还记得 device_uevent_ops 中的filter 函数过判断此类型吗*/
        kobject_init(&dev->kobj, &device_ktype);
        INIT_LIST_HEAD(&dev->dma_pools);
        mutex_init(&dev->mutex);
        lockdep_set_novalidate_class(&dev->mutex);
        spin_lock_init(&dev->devres_lock);
        INIT_LIST_HEAD(&dev->devres_head);
        device_pm_init(dev);
        set_dev_node(dev, -1);
    }
	return platform_device_add(pdev);
           {
            	int i, ret = 0;

            	if (!pdev)
            		return -EINVAL;
                /*初始化s3c_device_i2c3->dev.parent 为 platform_bus,
                意味着device对应的目录会在 sys/devices/platform下*/
            	if (!pdev->dev.parent)
            		pdev->dev.parent = &platform_bus;
                /*挂接在platform总线上*/
            	pdev->dev.bus = &platform_bus_type;
                /*看结构体定义s3c_device_i2c3->id = 3,所以pdev->dev->kobj->name = "s3c2440-i2c.3"
                如果系统里只有一个此类设备,id初始化为 -1就行了*/
            	if (pdev->id != -1)
            		dev_set_name(&pdev->dev, "%s.%d", pdev->name,  pdev->id);
            	else
            		dev_set_name(&pdev->dev, "%s", pdev->name);
                /*下面就是将 s3c_device_i2c3.resource插入到 reourse tree,
                插入的时候会做冲突检查*/
            	for (i = 0; i < pdev->num_resources; i++) {
            		struct resource *p, *r = &pdev->resource[i];

            		if (r->name == NULL)
            			r->name = dev_name(&pdev->dev);

            		p = r->parent;
            		if (!p) {
            			if (resource_type(r) == IORESOURCE_MEM)
            				p = &iomem_resource;
            			else if (resource_type(r) == IORESOURCE_IO)
            				p = &ioport_resource;
            		}
                    /*插入到 resource tree的时候如果检查到 recourse 已被插入过,说明resource冲突,
                    一个硬件资源不能同时分给多个设备用,不然会出错*/
            		if (p && insert_resource(p, r)) {
            			printk(KERN_ERR
            			       "%s: failed to claim resource %d\n",
            			       dev_name(&pdev->dev), i);
            			ret = -EBUSY;
            			goto failed;
            		}
            	}

            	pr_debug("Registering platform device '%s'. Parent at %s\n",
            		 dev_name(&pdev->dev), dev_name(pdev->dev.parent));

            	ret = device_add(&pdev->dev);      
                    {
                    	struct device *parent = NULL;
                    	struct class_interface *class_intf;
                    	int error = -EINVAL;
                        /*增加设备引用计数*/
                    	dev = get_device(dev);
                    	if (!dev)
                    		goto done;

                    	if (!dev->p) {
                    		error = device_private_init(dev);
                    		if (error)
                    			goto done;
                    	}

                    	/*
                    	 * for statically allocated devices, which should all be converted
                    	 * some day, we need to initialize the name. We prevent reading back
                    	 * the name, and force the use of dev_name()
                    	 */
                         /*s3c_device_i2c3->dev->init_name未赋值,也就是为NULL*/
                    	if (dev->init_name) {
                    		dev_set_name(dev, "%s", dev->init_name);
                    		dev->init_name = NULL;
                    	}
                        /*s3c_device_i2c3->dev->name 定义时初始化为 "s3c2410-i2c"*/
                    	if (!dev_name(dev)) {
                    		error = -EINVAL;
                    		goto name_error;
                    	}

                    	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
                        /*前面初始化s3c_device_i2c3->dev->parent = &platform_bus*/
                    	parent = get_device(dev->parent);
                        /*device层面的parent已经建立,setup_parent要建立kobject 层面的关系*/
                    	setup_parent(dev, parent);
                        {
                        	struct kobject *kobj;
                            /*执行结果kobj = &parent->kobj*/
                        	kobj = get_device_parent(dev, parent);
                                   {
                                        /*s3c_device_i2c3->dev->class未初始化,所以为NULL,
                                        等后面分析device_creat的时候再详细分析此函数*/
                                    	if (dev->class) {
                                            ......
                                    	}

                                    	if (parent)
                                    		return &parent->kobj;
                                    	return NULL;
                                    }
                            /*赋值结果 s3c_device_i2c3->dev->kobj->parent =  platform_bus->kobj*/
                        	if (kobj)
                        		dev->kobj.parent = kobj;
                        }

                    	/* use parent numa_node */
                    	if (parent)
                    		set_dev_node(dev, dev_to_node(parent));

                    	/* first, register with generic layer. */
                    	/* we require the name to be set before, and pass NULL */
                        /*又看见kobject_add,在sys/devices/platform下创建s3c2440-i2c.3*/
                    	error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
                    	if (error)
                    		goto Error;

                    	/* notify platform of device entry */
                        /*暂时不知道具体用途,代码中极少给platform_notify赋值*/
                    	if (platform_notify)
                    		platform_notify(dev);
                        /*在sys/devices/platform/s3c2440-i2c.3创建uevent文件*/
                    	error = device_create_file(dev, &uevent_attr);
                    	if (error)
                    		goto attrError;
                        /*此时s3c_device_i2c3->dev还没有设备号,所以执行不到,等到device_creat的时候再详细分析*/
                    	if (MAJOR(dev->devt)) {
                    		......
                    	}
                        /*在class下创建链接*/
                    	error = device_add_class_symlinks(dev);
                                {
                                	int error;
                                    /*s3c_device_i2c3->dev->class未赋值,也就是为NULL,在此返回*/
                                	if (!dev->class)
                                		return 0;
                                  
                                	......
                                }
                    	if (error)
                    		goto SymlinkError;
                        /*为s3c_device_i2c3->dev穿件属性文件*/
                    	error = device_add_attrs(dev);
                                {
                                	struct class *class = dev->class;
                                	const struct device_type *type = dev->type;
                                	int error;
                                    /*s3c_device_i2c3->dev->class未赋值,也就是为NULL,在此返回*/
                                	if (class) {
                                		......
                                	}
                                    /* s3c_device_i2c3->dev-type 未赋值,所以为NULL*/
                                	if (type) {
                                		......
                                	}
                                    /*s3c_device_i2c3->dev->groups也是未初始化的*/
                                	error = device_add_groups(dev, dev->groups);
                                	if (error)
                                		goto err_remove_type_groups;

                                	return 0;

                                 err_remove_type_groups:
                                	if (type)
                                		device_remove_groups(dev, type->groups);
                                 err_remove_class_bin_attrs:
                                	if (class)
                                		device_remove_bin_attributes(dev, class->dev_bin_attrs);
                                 err_remove_class_attrs:
                                	if (class)
                                		device_remove_attributes(dev, class->dev_attrs);

                                	return error;
                                }
                    	if (error)
                    		goto AttrsError;
                        /*将device挂接到bus上去,并创建一些属性文件*/
                    	error = bus_add_device(dev);
                                {
                                	struct bus_type *bus = bus_get(dev->bus);
                                	int error = 0;

                                	if (bus) {
                                		pr_debug("bus: '%s': add device %s\n", bus->name, dev_name(dev));
                                		error = device_add_attrs(bus, dev);
                                                {
                                                	int error = 0;
                                                	int i;
                                                    /*结构体定义时就初始化为platform_bus_type->dev_attrs = platform_dev_attrs
                                                    platform_dev_attrs.name = "modalias",也就是会在/sys/devices/platform/s3c2440-i2c.3
                                                    创建一个modalias属性文件*/
                                                	if (!bus->dev_attrs)
                                                		return 0;

                                                	for (i = 0; attr_name(bus->dev_attrs[i]); i++) {
                                                		error = device_create_file(dev, &bus->dev_attrs[i]);
                                                		if (error) {
                                                			while (--i >= 0)
                                                				device_remove_file(dev, &bus->dev_attrs[i]);
                                                			break;
                                                		}
                                                	}
                                                	return error;
                                                }
                                		if (error)
                                			goto out_put;
                                        /*还记得cd /sys/bus//platform/devices 吗
                                         priv->devices_kset = kset_create_and_add("devices", NULL,&priv->subsys.kobj);
                                         下面就是要在/sys/bus//platform/devices创建指向 /sys/devices/platform/s3c2440-i2c.3
                                         的链接,名字也为s3c2440-i2c.3*/
                                		error = sysfs_create_link(&bus->p->devices_kset->kobj,
                                						&dev->kobj, dev_name(dev));
                                		if (error)
                                			goto out_id;
                                        /*在/sys/devices/platform/s3c2440-i2c.3创建指向/sys/bus//platform/的链接,
                                        名字为subsystem*/
                                		error = sysfs_create_link(&dev->kobj,
                                				&dev->bus->p->subsys.kobj, "subsystem");
                                		if (error)
                                			goto out_subsys;
                                        /*将s3c_device_i2c3加入到platform_bus_type->p->klist_devices链表中*/
                                		klist_add_tail(&dev->p->knode_bus, &bus->p->klist_devices);
                                	}
                                	return 0;

                                out_subsys:
                                	sysfs_remove_link(&bus->p->devices_kset->kobj, dev_name(dev));
                                out_id:
                                	device_remove_attrs(bus, dev);
                                out_put:
                                	bus_put(dev->bus);
                                	return error;
                                }
                    	if (error)
                    		goto BusError;
                        /*电源管理相关,后面分析的电源管理机制的时候再详细分析*/
                    	error = dpm_sysfs_add(dev);
                    	if (error)
                    		goto DPMError;
                        /*电源管理相关,后面分析的电源管理机制的时候再详细分析*/
                    	device_pm_add(dev);
                        
                    	/* Notify clients of device addition.  This call must come
                    	 * after dpm_sysf_add() and before kobject_uevent().
                    	 */
                    	if (dev->bus)
                    		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
                    					     BUS_NOTIFY_ADD_DEVICE, dev);

                    	kobject_uevent(&dev->kobj, KOBJ_ADD);
                        
                    	bus_probe_device(dev);
                        {
                        	struct bus_type *bus = dev->bus;
                        	int ret;
                            /*还记得赋值platform_bus_type->p->drivers_autoprobe = 1
                            跟/sys/bus/platform下的drivers_autoprobe文件吗,drivers_autoprobe被置1
                            则自动进行驱动匹配*/
                        	if (bus && bus->p->drivers_autoprobe) {
                        		ret = device_attach(dev);
                                    {
                                    	int ret = 0;

                                    	device_lock(dev);
                                        /*现在只是注册s3c_device_i2c3,还没有匹配驱动,所以 s3c_device_i2c3->dev->driver = NULL*/
                                    	if (dev->driver) {
                                    		if (klist_node_attached(&dev->p->knode_driver)) {
                                    			ret = 1;
                                    			goto out_unlock;
                                    		}
                                    		ret = device_bind_driver(dev);
                                                {
                                                	int ret;

                                                	ret = driver_sysfs_add(dev);
                                                	if (!ret)
                                                		driver_bound(dev);
                                                	return ret;
                                                }
                                    		if (ret == 0)
                                    			ret = 1;
                                    		else {
                                    			dev->driver = NULL;
                                    			ret = 0;
                                    		}
                                    	} else {
                                    		pm_runtime_get_noresume(dev);
                                            /*通过__device_attach函数逐个匹配platform_bus_type->p->klist_drivers成员
                                            也说明了device_drivver会挂接在platform_bus_type->p->klist_drivers*/
                                    		ret = bus_for_each_drv(dev->bus, NULL, dev, __device_attach);
                                                {
                                                	struct klist_iter i;
                                                	struct device_driver *drv;
                                                	int error = 0;

                                                	if (!bus)
                                                		return -EINVAL;

                                                	klist_iter_init_node(&bus->p->klist_drivers, &i,
                                                			     start ? &start->p->knode_bus : NULL);
                                                	while ((drv = next_driver(&i)) && !error)
                                                		error = fn(drv, data);  //fn就是__device_attach
                                                                {
                                                                    struct device *dev = data;
                                                                    /*这就调用到传说中的match函数了,在此调用到的是platform_match,在此由于还未
                                                                    注册驱动,所以是匹配不到的*/
                                                                    if (!driver_match_device(drv, dev))
                                                                        {
                                                                            /*drv->bus->match就是platform_bus_type->match = platform_match*/
                                                                            return drv->bus->match ? drv->bus->match(dev, drv) : 1;
                                                                                   {
                                                                                        struct platform_device *pdev = to_platform_device(dev);
                                                                                        struct platform_driver *pdrv = to_platform_driver(drv);

                                                                                        /* Attempt an OF style match first */
                                                                                        /*先进行device tree风格的匹配,到device tree的时候再详细分析*/
                                                                                        if (of_driver_match_device(dev, drv))
                                                                                            return 1;

                                                                                        /* Then try to match against the id table */
                                                                                        /*再进行id_table形式的匹配,后面device_driver再详细分析id_table*/
                                                                                        if (pdrv->id_table)
                                                                                            return platform_match_id(pdrv->id_table, pdev) != NULL;

                                                                                        /* fall-back to driver name match */
                                                                                        /*这就是最原始的比较device和driver的名字*/
                                                                                        return (strcmp(pdev->name, drv->name) == 0);
                                                                                    }
                                                                        }
                                                                        return 0;
                                                                           /*如果匹配到驱动,最终会调用到注册driver中的probe函数
                                                                           后面注册driver的时候再详细分析*/
                                                                    return driver_probe_device(drv, dev); 
                                                                           
                                                                }
                                                	klist_iter_exit(&i);
                                                	return error;
                                                }
                                    		pm_runtime_put_sync(dev);
                                    	}
                                    out_unlock:
                                    	device_unlock(dev);
                                    	return ret;
                                    }
                        		WARN_ON(ret < 0);
                        	}
                        }
                        
                    	if (parent)
                            /*将s3c_device_i2c3加入platform_bus的子设备链表*/
                    		klist_add_tail(&dev->p->knode_parent,
                    			       &parent->p->klist_children);
                        /*将s3c_device_i2c3加入到class的设备链表中*/
                    	if (dev->class) {
                    		mutex_lock(&dev->class->p->class_mutex);
                    		/* tie the class to the device */
                    		klist_add_tail(&dev->knode_class,
                    			       &dev->class->p->klist_devices);
                            /*暂时还没弄清class_interface的具体用途*/
                    		/* notify any interfaces that the device is here */
                    		list_for_each_entry(class_intf,
                    				    &dev->class->p->class_interfaces, node)
                    			if (class_intf->add_dev)
                    				class_intf->add_dev(dev, class_intf);
                    		mutex_unlock(&dev->class->p->class_mutex);
                    	}
                    done:
                    	put_device(dev);
                    	return error;
                     DPMError:
                    	bus_remove_device(dev);
                     BusError:
                    	device_remove_attrs(dev);
                     AttrsError:
                    	device_remove_class_symlinks(dev);
                     SymlinkError:
                    	if (MAJOR(dev->devt))
                    		devtmpfs_delete_node(dev);
                    	if (MAJOR(dev->devt))
                    		device_remove_sys_dev_entry(dev);
                     devtattrError:
                    	if (MAJOR(dev->devt))
                    		device_remove_file(dev, &devt_attr);
                     ueventattrError:
                    	device_remove_file(dev, &uevent_attr);
                     attrError:
                    	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
                    	kobject_del(&dev->kobj);
                     Error:
                    	cleanup_device_parent(dev);
                    	if (parent)
                    		put_device(parent);
                    name_error:
                    	kfree(dev->p);
                    	dev->p = NULL;
                    	goto done;
                    }
            	if (ret == 0)
            		return ret;

             failed:
            	while (--i >= 0) {
            		struct resource *r = &pdev->resource[i];
            		unsigned long type = resource_type(r);

            		if (type == IORESOURCE_MEM || type == IORESOURCE_IO)
            			release_resource(r);
            	}

            	return ret;
            }
}device_initialize(&pdev->dev);
    {
    	/**初始化 s3c_device_i2c3->dev->kobj.kset = devices_kset,还记得sys下的deivces目录吗
        devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);*/
        dev->kobj.kset = devices_kset;
        /*初始化 s3c_device_i2c3->dev->kobj->ktype = &device_ktype,device设备kobj类型为device_ktype,
        还记得 device_uevent_ops 中的filter 函数过判断此类型吗*/
        kobject_init(&dev->kobj, &device_ktype);
        INIT_LIST_HEAD(&dev->dma_pools);
        mutex_init(&dev->mutex);
        lockdep_set_novalidate_class(&dev->mutex);
        spin_lock_init(&dev->devres_lock);
        INIT_LIST_HEAD(&dev->devres_head);
        device_pm_init(dev);
        set_dev_node(dev, -1);
    }
	return platform_device_add(pdev);
           {
            	int i, ret = 0;

            	if (!pdev)
            		return -EINVAL;
                /*初始化s3c_device_i2c3->dev.parent 为 platform_bus,
                意味着device对应的目录会在 sys/devices/platform下*/
            	if (!pdev->dev.parent)
            		pdev->dev.parent = &platform_bus;
                /*挂接在platform总线上*/
            	pdev->dev.bus = &platform_bus_type;
                /*看结构体定义s3c_device_i2c3->id = 3,所以pdev->dev->kobj->name = "s3c2440-i2c.3"
                如果系统里只有一个此类设备,id初始化为 -1就行了*/
            	if (pdev->id != -1)
            		dev_set_name(&pdev->dev, "%s.%d", pdev->name,  pdev->id);
            	else
            		dev_set_name(&pdev->dev, "%s", pdev->name);
                /*下面就是将 s3c_device_i2c3.resource插入到 reourse tree,
                插入的时候会做冲突检查*/
            	for (i = 0; i < pdev->num_resources; i++) {
            		struct resource *p, *r = &pdev->resource[i];

            		if (r->name == NULL)
            			r->name = dev_name(&pdev->dev);

            		p = r->parent;
            		if (!p) {
            			if (resource_type(r) == IORESOURCE_MEM)
            				p = &iomem_resource;
            			else if (resource_type(r) == IORESOURCE_IO)
            				p = &ioport_resource;
            		}
                    /*插入到 resource tree的时候如果检查到 recourse 已被插入过,说明resource冲突,
                    一个硬件资源不能同时分给多个设备用,不然会出错*/
            		if (p && insert_resource(p, r)) {
            			printk(KERN_ERR
            			       "%s: failed to claim resource %d\n",
            			       dev_name(&pdev->dev), i);
            			ret = -EBUSY;
            			goto failed;
            		}
            	}

            	pr_debug("Registering platform device '%s'. Parent at %s\n",
            		 dev_name(&pdev->dev), dev_name(pdev->dev.parent));

            	ret = device_add(&pdev->dev);      
                    {
                    	struct device *parent = NULL;
                    	struct class_interface *class_intf;
                    	int error = -EINVAL;
                        /*增加设备引用计数*/
                    	dev = get_device(dev);
                    	if (!dev)
                    		goto done;

                    	if (!dev->p) {
                    		error = device_private_init(dev);
                    		if (error)
                    			goto done;
                    	}

                    	/*
                    	 * for statically allocated devices, which should all be converted
                    	 * some day, we need to initialize the name. We prevent reading back
                    	 * the name, and force the use of dev_name()
                    	 */
                         /*s3c_device_i2c3->dev->init_name未赋值,也就是为NULL*/
                    	if (dev->init_name) {
                    		dev_set_name(dev, "%s", dev->init_name);
                    		dev->init_name = NULL;
                    	}
                        /*s3c_device_i2c3->dev->name 定义时初始化为 "s3c2410-i2c"*/
                    	if (!dev_name(dev)) {
                    		error = -EINVAL;
                    		goto name_error;
                    	}

                    	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
                        /*前面初始化s3c_device_i2c3->dev->parent = &platform_bus*/
                    	parent = get_device(dev->parent);
                        /*device层面的parent已经建立,setup_parent要建立kobject 层面的关系*/
                    	setup_parent(dev, parent);
                        {
                        	struct kobject *kobj;
                            /*执行结果kobj = &parent->kobj*/
                        	kobj = get_device_parent(dev, parent);
                                   {
                                        /*s3c_device_i2c3->dev->class未初始化,所以为NULL,
                                        等后面分析device_creat的时候再详细分析此函数*/
                                    	if (dev->class) {
                                            ......
                                    	}

                                    	if (parent)
                                    		return &parent->kobj;
                                    	return NULL;
                                    }
                            /*赋值结果 s3c_device_i2c3->dev->kobj->parent =  platform_bus->kobj*/
                        	if (kobj)
                        		dev->kobj.parent = kobj;
                        }

                    	/* use parent numa_node */
                    	if (parent)
                    		set_dev_node(dev, dev_to_node(parent));

                    	/* first, register with generic layer. */
                    	/* we require the name to be set before, and pass NULL */
                        /*又看见kobject_add,在sys/devices/platform下创建s3c2440-i2c.3*/
                    	error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
                    	if (error)
                    		goto Error;

                    	/* notify platform of device entry */
                        /*暂时不知道具体用途,代码中极少给platform_notify赋值*/
                    	if (platform_notify)
                    		platform_notify(dev);
                        /*在sys/devices/platform/s3c2440-i2c.3创建uevent文件*/
                    	error = device_create_file(dev, &uevent_attr);
                    	if (error)
                    		goto attrError;
                        /*此时s3c_device_i2c3->dev还没有设备号,所以执行不到,等到device_creat的时候再详细分析*/
                    	if (MAJOR(dev->devt)) {
                    		......
                    	}
                        /*在class下创建链接*/
                    	error = device_add_class_symlinks(dev);
                                {
                                	int error;
                                    /*s3c_device_i2c3->dev->class未赋值,也就是为NULL,在此返回*/
                                	if (!dev->class)
                                		return 0;
                                  
                                	......
                                }
                    	if (error)
                    		goto SymlinkError;
                        /*为s3c_device_i2c3->dev穿件属性文件*/
                    	error = device_add_attrs(dev);
                                {
                                	struct class *class = dev->class;
                                	const struct device_type *type = dev->type;
                                	int error;
                                    /*s3c_device_i2c3->dev->class未赋值,也就是为NULL,在此返回*/
                                	if (class) {
                                		......
                                	}
                                    /* s3c_device_i2c3->dev-type 未赋值,所以为NULL*/
                                	if (type) {
                                		......
                                	}
                                    /*s3c_device_i2c3->dev->groups也是未初始化的*/
                                	error = device_add_groups(dev, dev->groups);
                                	if (error)
                                		goto err_remove_type_groups;

                                	return 0;

                                 err_remove_type_groups:
                                	if (type)
                                		device_remove_groups(dev, type->groups);
                                 err_remove_class_bin_attrs:
                                	if (class)
                                		device_remove_bin_attributes(dev, class->dev_bin_attrs);
                                 err_remove_class_attrs:
                                	if (class)
                                		device_remove_attributes(dev, class->dev_attrs);

                                	return error;
                                }
                    	if (error)
                    		goto AttrsError;
                        /*将device挂接到bus上去,并创建一些属性文件*/
                    	error = bus_add_device(dev);
                                {
                                	struct bus_type *bus = bus_get(dev->bus);
                                	int error = 0;

                                	if (bus) {
                                		pr_debug("bus: '%s': add device %s\n", bus->name, dev_name(dev));
                                		error = device_add_attrs(bus, dev);
                                                {
                                                	int error = 0;
                                                	int i;
                                                    /*结构体定义时就初始化为platform_bus_type->dev_attrs = platform_dev_attrs
                                                    platform_dev_attrs.name = "modalias",也就是会在/sys/devices/platform/s3c2440-i2c.3
                                                    创建一个modalias属性文件*/
                                                	if (!bus->dev_attrs)
                                                		return 0;

                                                	for (i = 0; attr_name(bus->dev_attrs[i]); i++) {
                                                		error = device_create_file(dev, &bus->dev_attrs[i]);
                                                		if (error) {
                                                			while (--i >= 0)
                                                				device_remove_file(dev, &bus->dev_attrs[i]);
                                                			break;
                                                		}
                                                	}
                                                	return error;
                                                }
                                		if (error)
                                			goto out_put;
                                        /*还记得cd /sys/bus//platform/devices 吗
                                         priv->devices_kset = kset_create_and_add("devices", NULL,&priv->subsys.kobj);
                                         下面就是要在/sys/bus//platform/devices创建指向 /sys/devices/platform/s3c2440-i2c.3
                                         的链接,名字也为s3c2440-i2c.3*/
                                		error = sysfs_create_link(&bus->p->devices_kset->kobj,
                                						&dev->kobj, dev_name(dev));
                                		if (error)
                                			goto out_id;
                                        /*在/sys/devices/platform/s3c2440-i2c.3创建指向/sys/bus//platform/的链接,
                                        名字为subsystem*/
                                		error = sysfs_create_link(&dev->kobj,
                                				&dev->bus->p->subsys.kobj, "subsystem");
                                		if (error)
                                			goto out_subsys;
                                        /*将s3c_device_i2c3加入到platform_bus_type->p->klist_devices链表中*/
                                		klist_add_tail(&dev->p->knode_bus, &bus->p->klist_devices);
                                	}
                                	return 0;

                                out_subsys:
                                	sysfs_remove_link(&bus->p->devices_kset->kobj, dev_name(dev));
                                out_id:
                                	device_remove_attrs(bus, dev);
                                out_put:
                                	bus_put(dev->bus);
                                	return error;
                                }
                    	if (error)
                    		goto BusError;
                        /*电源管理相关,后面分析的电源管理机制的时候再详细分析*/
                    	error = dpm_sysfs_add(dev);
                    	if (error)
                    		goto DPMError;
                        /*电源管理相关,后面分析的电源管理机制的时候再详细分析*/
                    	device_pm_add(dev);
                        
                    	/* Notify clients of device addition.  This call must come
                    	 * after dpm_sysf_add() and before kobject_uevent().
                    	 */
                    	if (dev->bus)
                    		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
                    					     BUS_NOTIFY_ADD_DEVICE, dev);

                    	kobject_uevent(&dev->kobj, KOBJ_ADD);
                        
                    	bus_probe_device(dev);
                        {
                        	struct bus_type *bus = dev->bus;
                        	int ret;
                            /*还记得赋值platform_bus_type->p->drivers_autoprobe = 1
                            跟/sys/bus/platform下的drivers_autoprobe文件吗,drivers_autoprobe被置1
                            则自动进行驱动匹配*/
                        	if (bus && bus->p->drivers_autoprobe) {
                        		ret = device_attach(dev);
                                    {
                                    	int ret = 0;

                                    	device_lock(dev);
                                        /*现在只是注册s3c_device_i2c3,还没有匹配驱动,所以 s3c_device_i2c3->dev->driver = NULL*/
                                    	if (dev->driver) {
                                    		if (klist_node_attached(&dev->p->knode_driver)) {
                                    			ret = 1;
                                    			goto out_unlock;
                                    		}
                                    		ret = device_bind_driver(dev);
                                                {
                                                	int ret;

                                                	ret = driver_sysfs_add(dev);
                                                	if (!ret)
                                                		driver_bound(dev);
                                                	return ret;
                                                }
                                    		if (ret == 0)
                                    			ret = 1;
                                    		else {
                                    			dev->driver = NULL;
                                    			ret = 0;
                                    		}
                                    	} else {
                                    		pm_runtime_get_noresume(dev);
                                            /*通过__device_attach函数逐个匹配platform_bus_type->p->klist_drivers成员
                                            也说明了device_drivver会挂接在platform_bus_type->p->klist_drivers*/
                                    		ret = bus_for_each_drv(dev->bus, NULL, dev, __device_attach);
                                                {
                                                	struct klist_iter i;
                                                	struct device_driver *drv;
                                                	int error = 0;

                                                	if (!bus)
                                                		return -EINVAL;

                                                	klist_iter_init_node(&bus->p->klist_drivers, &i,
                                                			     start ? &start->p->knode_bus : NULL);
                                                	while ((drv = next_driver(&i)) && !error)
                                                		error = fn(drv, data);  //fn就是__device_attach
                                                                {
                                                                    struct device *dev = data;
                                                                    /*这就调用到传说中的match函数了,在此调用到的是platform_match,在此由于还未
                                                                    注册驱动,所以是匹配不到的*/
                                                                    if (!driver_match_device(drv, dev))
                                                                        {
                                                                            /*drv->bus->match就是platform_bus_type->match = platform_match*/
                                                                            return drv->bus->match ? drv->bus->match(dev, drv) : 1;
                                                                                   {
                                                                                        struct platform_device *pdev = to_platform_device(dev);
                                                                                        struct platform_driver *pdrv = to_platform_driver(drv);

                                                                                        /* Attempt an OF style match first */
                                                                                        /*先进行device tree风格的匹配,到device tree的时候再详细分析*/
                                                                                        if (of_driver_match_device(dev, drv))
                                                                                            return 1;

                                                                                        /* Then try to match against the id table */
                                                                                        /*再进行id_table形式的匹配,后面device_driver再详细分析id_table*/
                                                                                        if (pdrv->id_table)
                                                                                            return platform_match_id(pdrv->id_table, pdev) != NULL;

                                                                                        /* fall-back to driver name match */
                                                                                        /*这就是最原始的比较device和driver的名字*/
                                                                                        return (strcmp(pdev->name, drv->name) == 0);
                                                                                    }
                                                                        }
                                                                        return 0;
                                                                           /*如果匹配到驱动,最终会调用到注册driver中的probe函数
                                                                           后面注册driver的时候再详细分析*/
                                                                    return driver_probe_device(drv, dev); 
                                                                           
                                                                }
                                                	klist_iter_exit(&i);
                                                	return error;
                                                }
                                    		pm_runtime_put_sync(dev);
                                    	}
                                    out_unlock:
                                    	device_unlock(dev);
                                    	return ret;
                                    }
                        		WARN_ON(ret < 0);
                        	}
                        }
                        
                    	if (parent)
                            /*将s3c_device_i2c3加入platform_bus的子设备链表*/
                    		klist_add_tail(&dev->p->knode_parent,
                    			       &parent->p->klist_children);
                        /*将s3c_device_i2c3加入到class的设备链表中*/
                    	if (dev->class) {
                    		mutex_lock(&dev->class->p->class_mutex);
                    		/* tie the class to the device */
                    		klist_add_tail(&dev->knode_class,
                    			       &dev->class->p->klist_devices);
                            /*暂时还没弄清class_interface的具体用途*/
                    		/* notify any interfaces that the device is here */
                    		list_for_each_entry(class_intf,
                    				    &dev->class->p->class_interfaces, node)
                    			if (class_intf->add_dev)
                    				class_intf->add_dev(dev, class_intf);
                    		mutex_unlock(&dev->class->p->class_mutex);
                    	}
                    done:
                    	put_device(dev);
                    	return error;
                     DPMError:
                    	bus_remove_device(dev);
                     BusError:
                    	device_remove_attrs(dev);
                     AttrsError:
                    	device_remove_class_symlinks(dev);
                     SymlinkError:
                    	if (MAJOR(dev->devt))
                    		devtmpfs_delete_node(dev);
                    	if (MAJOR(dev->devt))
                    		device_remove_sys_dev_entry(dev);
                     devtattrError:
                    	if (MAJOR(dev->devt))
                    		device_remove_file(dev, &devt_attr);
                     ueventattrError:
                    	device_remove_file(dev, &uevent_attr);
                     attrError:
                    	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
                    	kobject_del(&dev->kobj);
                     Error:
                    	cleanup_device_parent(dev);
                    	if (parent)
                    		put_device(parent);
                    name_error:
                    	kfree(dev->p);
                    	dev->p = NULL;
                    	goto done;
                    }
            	if (ret == 0)
            		return ret;

             failed:
            	while (--i >= 0) {
            		struct resource *r = &pdev->resource[i];
            		unsigned long type = resource_type(r);

            		if (type == IORESOURCE_MEM || type == IORESOURCE_IO)
            			release_resource(r);
            	}

            	return ret;
            }
}

从paltform_device注册可以 看出,实际没有做多少工作,还有好多工作没做,比如因class为NULL部分代码执行不到,以及因没有设备号也有一些工作没做。下面进入设备看下整个过程建立的目录、文件和链接。

1. 在sys/devices/platform下创建s3c2440-i2c.3

[root@FriendlyARM rtc0]# cd /sys/devices/platform/
[root@FriendlyARM platform]# ls
alarm                s3c2440-i2c.3        samsung-audio

        ......s3c2440-i2c.3        samsung-audio

        ......

2. 在sys/devices/platform/s3c2440-i2c.3创建uevent文件

[root@FriendlyARM platform]# cd s3c2440-i2c.3/
[root@FriendlyARM s3c2440-i2c.3]# ls
driver     i2c-3      modalias   power      subsystem  ueventuevent

3. 在/sys/devices/platform/s3c2440-i2c.3创建一个modalias属性文件

 

[root@FriendlyARM platform]# cd s3c2440-i2c.3/
[root@FriendlyARM s3c2440-i2c.3]# ls
driver     i2c-3      modalias   power      subsystem  ueventmodalias   power      subsystem  uevent

4. 在/sys/bus/platform/devices创建指向 /sys/devices/platform/s3c2440-i2c.3 的链接,名字也为s3c2440-i2c.3*/

[root@FriendlyARM s3c-i2c]# cd /sys/bus/platform/devices/
[root@FriendlyARM devices]# ls -l 

......
lrwxrwxrwx    1 root     root             0 Jan  1 13:18 s3c2440-i2c.3 -> ../../../devices/platform/s3c2440-i2c.3
......s3c2440-i2c.3 -> ../../../devices/platform/s3c2440-i2c.3
......

5. 在/sys/devices/platform/s3c2440-i2c.3创建指向/sys/bus/platform/的链接,名字为subsystem

[root@FriendlyARM s3c2440-i2c.3]# cd /sys/devices/platform/s3c2440-i2c.3
[root@FriendlyARM s3c2440-i2c.3]# ls
driver     i2c-3      modalias   power      subsystem  ueventsubsystem  uevent

对于uevent和modalias属性文件,可以通过其store和show函数看其功能,下面只展示一下modalias属性的定义

static struct device_attribute platform_dev_attrs[] = { 
        .attr = { 
        .name = “modalias”, 
        .mode = 0444
    },
.show = modalias_show,

};

除了一句打印,没有其它作用。

static ssize_t modalias_show(struct device *dev, struct device_attribute *a,
    char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
int len = snprintf(buf, PAGE_SIZE, "platform:%s\n", pdev->name);


return (len >= PAGE_SIZE) ? (PAGE_SIZE - 1) : len;
}

三、platform_driver实例

上面是platform_device的实例,下面就分析platform_driver实例,看看实际的driver如何和device匹配的,上面是s3c_device_i2c3的注册,下面就分析其对应的s3c24xx_i2c_driver为例。

先看 platform_driver 结构体

struct platform_driver {
	int (*probe)(struct platform_device *);
	int (*remove)(struct platform_device *);
	void (*shutdown)(struct platform_device *);
	int (*suspend)(struct platform_device *, pm_message_t state);
	int (*resume)(struct platform_device *);
	struct device_driver driver;
	const struct platform_device_id *id_table;
}; 

platform_driver比较简单,看名字也比较好理解,只关注
const struct platform_device_id *id_table;

驱动兼容的 device 列表,表明此驱动都可用于哪些device,总线的match会用到这个进行匹配

再看

struct device_driver {
	const char		*name;
	struct bus_type		*bus;

	struct module		*owner;
	const char		*mod_name;	/* used for built-in modules */

	bool suppress_bind_attrs;	/* disables bind/unbind via sysfs */

	const struct of_device_id	*of_match_table;

	int (*probe) (struct device *dev);
	int (*remove) (struct device *dev);
	void (*shutdown) (struct device *dev);
	int (*suspend) (struct device *dev, pm_message_t state);
	int (*resume) (struct device *dev);
	const struct attribute_group **groups;

	const struct dev_pm_ops *pm;

	struct driver_private *p;
};


const char *name;
驱动的name
struct bus_type *bus;
指向的bus
struct module *owner;
所属的模块,绝大多数情况为 THIS_MODULE,如果不将此驱动编译成模块则为NULL
const char *mod_name; /* used for built-in modules */
bool suppress_bind_attrs; /* disables bind/unbind via sysfs */

决定是否在/sys/bus/platform/drivers/s3c-i2c下生成 bind 和 ubind 文件
const struct of_device_id *of_match_table;
在总线的 match 函数中用于device tree形式的匹配
int (*probe) (struct device *dev);
int (*remove) (struct device *dev);
void (*shutdown) (struct device *dev);
int (*suspend) (struct device *dev, pm_message_t state);
int (*resume) (struct device *dev);
const struct attribute_group **groups;
const struct dev_pm_ops *pm;

电源管理相关
struct driver_private *p;

 

封装的私有结构体。还记得devce、class和bus_type中都有封装私有结构体吗

 

s3c24xx_i2c_driver实例

 
static struct platform_driver s3c24xx_i2c_driver = {
	.probe		= s3c24xx_i2c_probe,
	.remove		= s3c24xx_i2c_remove,
	.id_table	= s3c24xx_driver_ids,
	.driver		= {
		.owner	= THIS_MODULE,
		.name	= "s3c-i2c",
		.pm	= S3C24XX_DEV_PM_OPS,
	},
};

看兼容的设备列表

static struct platform_device_id s3c24xx_driver_ids[] = {
	{
		.name		= "s3c2410-i2c",
		.driver_data	= TYPE_S3C2410,
	}, {
		.name		= "s3c2440-i2c",
		.driver_data	= TYPE_S3C2440,
	}, {
		.name		= "s3c2440-hdmiphy-i2c",
		.driver_data	= TYPE_S3C2440_HDMIPHY,
	}, { },
};

下面看注册过程:

static int __init i2c_adap_s3c_init(void)
{
	return platform_driver_register(&s3c24xx_i2c_driver);
            {
            	drv->driver.bus = &platform_bus_type;
                /*s3c24xx_i2c_driver->probe = s3c24xx_i2c_probe
                s3c24xx_i2c_driver->remove = s3c24xx_i2c_remove*/
            	if (drv->probe)
            		drv->driver.probe = platform_drv_probe;
                                        {
                                        	struct platform_driver *drv = to_platform_driver(_dev->driver);
                                        	struct platform_device *dev = to_platform_device(_dev);
                                            /*最终还是调用的s3c24xx_i2c_driver->probe = s3c24xx_i2c_probe*/
                                        	return drv->probe(dev);
                                        }   
            	if (drv->remove)
            		drv->driver.remove = platform_drv_remove;
                                        {
                                        	struct platform_driver *drv = to_platform_driver(_dev->driver);
                                        	struct platform_device *dev = to_platform_device(_dev);
                                            /*最终还是调用的s3c24xx_i2c_driver->remove = s3c24xx_i2c_remove*/
                                        	return drv->remove(dev);
                /*s3c24xx_i2c_driver.shutdown = NULL*/                        }
            	if (drv->shutdown)
            		drv->driver.shutdown = platform_drv_shutdown;
                /*注册driver*/
            	return driver_register(&drv->driver);
                        {
                        	int ret;
                        	struct device_driver *other;

                        	BUG_ON(!drv->bus->p);
                            /*platform_bus_type->probe = NULL
                            platform_bus_type->remove = NULL
                            platform_bus_type->shutdown = NULL
                            s3c24xx_i2c_driver->probe = s3c24xx_i2c_probe
                            s3c24xx_i2c_driver->remove = s3c24xx_i2c_remove
                            s3c24xx_i2c_driver.shutdown = NULL*/
                        	if ((drv->bus->probe && drv->probe) ||
                        	    (drv->bus->remove && drv->remove) ||
                        	    (drv->bus->shutdown && drv->shutdown))
                        		printk(KERN_WARNING "Driver '%s' needs updating - please use "
                        			"bus_type methods\n", drv->name);
                            /*通过name查找是否已经注册过此driver*/
                        	other = driver_find(drv->name, drv->bus);
                                    {
                                    	struct kobject *k = kset_find_obj(bus->p->drivers_kset, name);
                                    	struct driver_private *priv;

                                    	if (k) {
                                    		priv = to_driver(k);
                                    		return priv->driver;
                                    	}
                                    	return NULL;
                                    }
                            /*如果已经注册过此driver,打印错误信息并返回EBUSY*/
                            if (other) {
                        		put_driver(other);
                        		printk(KERN_ERR "Error: Driver '%s' is already registered, "
                        			"aborting...\n", drv->name);
                        		return -EBUSY;
                        	}

                        	ret = bus_add_driver(drv);
                                 {
                                	struct bus_type *bus;
                                	struct driver_private *priv;
                                	int error = 0;
                            /*前面初始化 s3c24xx_i2c_driver->driver.bus = &platform_bus_type*/
                                	bus = bus_get(drv->bus);
                                	if (!bus)
                                		return -EINVAL;

                                	pr_debug("bus: '%s': add driver %s\n", bus->name, drv->name);

                                    /*为s3c24xx_i2c_driver->driver申请私有结构体*/

                                	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
                                	if (!priv) {
                                		error = -ENOMEM;
                                		goto out_put_bus;
                                	}
                                	klist_init(&priv->klist_devices, NULL, NULL);
                                	priv->driver = drv;
                                	drv->p = priv;
                                    /*s3c24xx_i2c_driver->driver->priv->kobj.kset = platform_bus_type->p->drivers_kset
                                    还记得sys/bus/platform下的drivers目录吗
                                    priv->drivers_kset = kset_create_and_add("drivers", NULL, &priv->subsys.kobj);*/
                                	priv->kobj.kset = bus->p->drivers_kset;
                                    /*在sys/bus/platform/drivers目录下创建s3c-i2c的目录*/
                                	error = kobject_init_and_add(&priv->kobj, &driver_ktype, NULL,
                                				     "%s", drv->name);
                                	if (error)
                                		goto out_unregister;
                                    /*又见到了drivers_autoprobe,还记得/sys/bus/platform下的drivers_autoprobe文件吗
                                    platform_bus_type->p->drivers_autoprobe = 1,自动匹配device和driver*/
                                	if (drv->bus->p->drivers_autoprobe) {
                                		error = driver_attach(drv);
                                                {
                                                	return bus_for_each_dev(drv->bus, NULL, drv, __driver_attach);
                                                           {
                                                            	struct klist_iter i;
                                                            	struct device *dev;
                                                            	int error = 0;

                                                            	if (!bus || !bus->p)
                                                            		return -EINVAL;
                                                                /*device注册的时候就是挂接到 platform_bus_type->p->klist_devices
                                                                下面就是遍历platform_bus_type的device链表,然后通过__driver_attach和driver
                                                                做匹配*/

                                                            	klist_iter_init_node(&bus->p->klist_devices, &i,
                                                            			     (start ? &start->p->knode_bus : NULL));
                                                            	while ((dev = next_device(&i)) && !error)
                                                            		error = fn(dev, data);  //fn = __driver_attach
                                                                            {
                                                                            	struct device_driver *drv = data;

                                                                            	/*
                                                                            	 * Lock device and try to bind to it. We drop the error
                                                                            	 * here and always return 0, because we need to keep trying
                                                                            	 * to bind to devices and some drivers will return an error
                                                                            	 * simply if it didn't support the device.
                                                                            	 *
                                                                            	 * driver_probe_device() will spit a warning if there
                                                                            	 * is an error.
                                                                            	 */

                                                                            	if (!driver_match_device(drv, dev))
                                                                                    {   /*drv->bus->match = platform_match,最终还是调用到platform的match函数
                                                                                        最终会匹配到 s3c_device_i2c3*/
                                                                                    	return drv->bus->match ? drv->bus->match(dev, drv) : 1;
                                                                                    }
                                                                            		return 0;
                                                                                /*dev = s3c_device_i2c3->dev
                                                                                  s3c_device_i2c3->dev->parent = &platform_bus */

                                                                            	if (dev->parent)	/* Needed for USB */
                                                                            		device_lock(dev->parent);
                                                                            	device_lock(dev);
                                                                                /*虽然device和driver都找到了,可还未将driver赋值给device呢*/
                                                                            	if (!dev->driver)
                                                                            		driver_probe_device(drv, dev);
                                                                                    {
                                                                                    	int ret = 0;

                                                                                    	if (!device_is_registered(dev))
                                                                                    		return -ENODEV;

                                                                                    	pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
                                                                                    		 drv->bus->name, __func__, dev_name(dev), drv->name);

                                                                                    	pm_runtime_get_noresume(dev);
                                                                                    	pm_runtime_barrier(dev);
                                                                                    	ret = really_probe(dev, drv);
                                                                                            {
                                                                                            	int ret = 0;

                                                                                            	atomic_inc(&probe_count);
                                                                                            	pr_debug("bus: '%s': %s: probing driver %s with device %s\n",
                                                                                            		 drv->bus->name, __func__, drv->name, dev_name(dev));
                                                                                            	WARN_ON(!list_empty(&dev->devres_head));
                                                                                                /*这里才将driver和device关联起来*/
                                                                                            	dev->driver = drv;
                                                                                            	if (driver_sysfs_add(dev)) {
                                                                                                    {
                                                                                                    	int ret;

                                                                                                    	if (dev->bus)
                                                                                                    		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
                                                                                                    					     BUS_NOTIFY_BIND_DRIVER, dev);
                                                                                                        /*sys/bus/platform/drivers/s3c-i2c创建指向s3c2440-i2c.3的链接,
                                                                                                        名字仍然为s3c2440-i2c.3*/
                                                                                                    	ret = sysfs_create_link(&dev->driver->p->kobj, &dev->kobj,
                                                                                                    			  kobject_name(&dev->kobj));
                                                                                                    	if (ret == 0) {
                                                                                                            /*在sys/bus/platform/device/s3c2440-i2c.3下
                                                                                                            创建指向sys/bus/platform/drivers/s3c-i2c的链接,名字为driver*/
                                                                                                    		ret = sysfs_create_link(&dev->kobj, &dev->driver->p->kobj,
                                                                                                    					"driver");
                                                                                                    		if (ret)
                                                                                                    			sysfs_remove_link(&dev->driver->p->kobj,
                                                                                                    					kobject_name(&dev->kobj));
                                                                                                    	}
                                                                                                    	return ret;
                                                                                                    }
                                                                                            		printk(KERN_ERR "%s: driver_sysfs_add(%s) failed\n",
                                                                                            			__func__, dev_name(dev));
                                                                                            		goto probe_failed;
                                                                                            	}
                                                                                                /*platform_bus_type->probe = NULL,所以调用
                                                                                                s3c24xx_i2c_driver->probe也就是 s3c24xx_i2c_probe*/
                                                                                            	if (dev->bus->probe) {
                                                                                            		ret = dev->bus->probe(dev);
                                                                                            		if (ret)
                                                                                            			goto probe_failed;
                                                                                            	} else if (drv->probe) {
                                                                                            		ret = drv->probe(dev);
                                                                                            		if (ret)
                                                                                            			goto probe_failed;
                                                                                            	}

                                                                                            	driver_bound(dev);
                                                                                                {   /*前面s3c_device_i2c3->dev->p->knode_driver未初始化,也就是为NULL*/
                                                                                                	if (klist_node_attached(&dev->p->knode_driver)) {
                                                                                                		printk(KERN_WARNING "%s: device %s already bound\n",
                                                                                                			__func__, kobject_name(&dev->kobj));
                                                                                                		return;
                                                                                                	}

                                                                                                	pr_debug("driver: '%s': %s: bound to device '%s'\n", dev_name(dev),
                                                                                                		 __func__, dev->driver->name);
                                                                                                    /*将device挂接在driver的设备链表中*/
                                                                                                	klist_add_tail(&dev->p->knode_driver, &dev->driver->p->klist_devices);

                                                                                                	if (dev->bus)
                                                                                                		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
                                                                                                					     BUS_NOTIFY_BOUND_DRIVER, dev);
                                                                                                }
                                                                                            	ret = 1;
                                                                                            	pr_debug("bus: '%s': %s: bound device %s to driver %s\n",
                                                                                            		 drv->bus->name, __func__, dev_name(dev), drv->name);
                                                                                            	goto done;

                                                                                            probe_failed:
                                                                                            	devres_release_all(dev);
                                                                                            	driver_sysfs_remove(dev);
                                                                                            	dev->driver = NULL;

                                                                                            	if (ret != -ENODEV && ret != -ENXIO) {
                                                                                            		/* driver matched but the probe failed */
                                                                                            		printk(KERN_WARNING
                                                                                            		       "%s: probe of %s failed with error %d\n",
                                                                                            		       drv->name, dev_name(dev), ret);
                                                                                            	}
                                                                                            	/*
                                                                                            	 * Ignore errors returned by ->probe so that the next driver can try
                                                                                            	 * its luck.
                                                                                            	 */
                                                                                            	ret = 0;
                                                                                            done:
                                                                                            	atomic_dec(&probe_count);
                                                                                            	wake_up(&probe_waitqueue);
                                                                                            	return ret;
                                                                                            }
                                                                                    	pm_runtime_put_sync(dev);

                                                                                    	return ret;
                                                                                    }
                                                                            	device_unlock(dev);
                                                                            	if (dev->parent)
                                                                            		device_unlock(dev->parent);

                                                                            	return 0;
                                                                            }
                                                            	klist_iter_exit(&i);
                                                            	return error;
                                                           }
                                                }
                                		if (error)
                                			goto out_unregister;
                                	}
                                    /*将s3c24xx_i2c_driver挂接在platform的driver链表中*/
                                	klist_add_tail(&priv->knode_bus, &bus->p->klist_drivers);
                                	module_add_driver(drv->owner, drv);
                                    /*在/sys/bus/platform/drivers/s3c-i2c创建uevent文件*/
                                	error = driver_create_file(drv, &driver_attr_uevent);
                                	if (error) {
                                		printk(KERN_ERR "%s: uevent attr (%s) failed\n",
                                			__func__, drv->name);
                                	}
                                    /*为 s3c24xx_i2c_driver 创建默认的属性文件,可是platform_bus_type->drv_attrs = NULL,所以此例中没有
                                    没有创建任何文件*/
                                	error = driver_add_attrs(bus, drv);
                                            {
                                            	int error = 0;
                                            	int i;

                                            	if (bus->drv_attrs) {
                                            		for (i = 0; attr_name(bus->drv_attrs[i]); i++) {
                                            			error = driver_create_file(drv, &bus->drv_attrs[i]);
                                            			if (error)
                                            				goto err;
                                            		}
                                            	}
                                            done:
                                            	return error;
                                            err:
                                            	while (--i >= 0)
                                            		driver_remove_file(drv, &bus->drv_attrs[i]);
                                            	goto done;
                                            }
                                	if (error) {
                                		/* How the hell do we get out of this pickle? Give up */
                                		printk(KERN_ERR "%s: driver_add_attrs(%s) failed\n",
                                			__func__, drv->name);
                                	}
                                    /*s3c24xx_i2c_driver->drv->suppress_bind_attrs 未赋值,也就是为0*/
                                	if (!drv->suppress_bind_attrs) {
                                		error = add_bind_files(drv);
                                                {
                                                	int ret;
                                                    /*在/sys/bus/platform/drivers/s3c-i2c目录下创建 ubind 文件*/
                                                	ret = driver_create_file(drv, &driver_attr_unbind);
                                                	if (ret == 0) {
                                                        /*在/sys/bus/platform/drivers/s3c-i2c目录下创建 bind 文件*/
                                                		ret = driver_create_file(drv, &driver_attr_bind);
                                                		if (ret)
                                                			driver_remove_file(drv, &driver_attr_unbind);
                                                	}
                                                	return ret;
                                                }
                                		if (error) {
                                			/* Ditto */
                                			printk(KERN_ERR "%s: add_bind_files(%s) failed\n",
                                				__func__, drv->name);
                                		}
                                	}
                                    /*发送 KOBJ_ADD */
                                	kobject_uevent(&priv->kobj, KOBJ_ADD);
                                	return 0;

                                out_unregister:
                                	kobject_put(&priv->kobj);
                                	kfree(drv->p);
                                	drv->p = NULL;
                                out_put_bus:
                                	bus_put(bus);
                                	return error;
                                }
                        	if (ret)
                        		return ret;
                            /*创建属性组及文件,s3c24xx_i2c_driver->drv未初始化,也就是为NULL,不会创建任何文件*/
                        	ret = driver_add_groups(drv, drv->groups);
                                {
                                	int error = 0;
                                	int i;

                                	if (groups) {
                                		for (i = 0; groups[i]; i++) {
                                			error = sysfs_create_group(&drv->p->kobj, groups[i]);
                                			if (error) {
                                				while (--i >= 0)
                                					sysfs_remove_group(&drv->p->kobj,
                                							   groups[i]);
                                				break;
                                			}
                                		}
                                	}
                                	return error;
                                }
                        	if (ret)
                        		bus_remove_driver(drv);
                        	return ret;
                        }
            }
}{
            	drv->driver.bus = &platform_bus_type;
                /*s3c24xx_i2c_driver->probe = s3c24xx_i2c_probe
                s3c24xx_i2c_driver->remove = s3c24xx_i2c_remove*/
            	if (drv->probe)
            		drv->driver.probe = platform_drv_probe;
                                        {
                                        	struct platform_driver *drv = to_platform_driver(_dev->driver);
                                        	struct platform_device *dev = to_platform_device(_dev);
                                            /*最终还是调用的s3c24xx_i2c_driver->probe = s3c24xx_i2c_probe*/
                                        	return drv->probe(dev);
                                        }   
            	if (drv->remove)
            		drv->driver.remove = platform_drv_remove;
                                        {
                                        	struct platform_driver *drv = to_platform_driver(_dev->driver);
                                        	struct platform_device *dev = to_platform_device(_dev);
                                            /*最终还是调用的s3c24xx_i2c_driver->remove = s3c24xx_i2c_remove*/
                                        	return drv->remove(dev);
                /*s3c24xx_i2c_driver.shutdown = NULL*/                        }
            	if (drv->shutdown)
            		drv->driver.shutdown = platform_drv_shutdown;
                /*注册driver*/
            	return driver_register(&drv->driver);
                        {
                        	int ret;
                        	struct device_driver *other;

                        	BUG_ON(!drv->bus->p);
                            /*platform_bus_type->probe = NULL
                            platform_bus_type->remove = NULL
                            platform_bus_type->shutdown = NULL
                            s3c24xx_i2c_driver->probe = s3c24xx_i2c_probe
                            s3c24xx_i2c_driver->remove = s3c24xx_i2c_remove
                            s3c24xx_i2c_driver.shutdown = NULL*/
                        	if ((drv->bus->probe && drv->probe) ||
                        	    (drv->bus->remove && drv->remove) ||
                        	    (drv->bus->shutdown && drv->shutdown))
                        		printk(KERN_WARNING "Driver '%s' needs updating - please use "
                        			"bus_type methods\n", drv->name);
                            /*通过name查找是否已经注册过此driver*/
                        	other = driver_find(drv->name, drv->bus);
                                    {
                                    	struct kobject *k = kset_find_obj(bus->p->drivers_kset, name);
                                    	struct driver_private *priv;

                                    	if (k) {
                                    		priv = to_driver(k);
                                    		return priv->driver;
                                    	}
                                    	return NULL;
                                    }
                            /*如果已经注册过此driver,打印错误信息并返回EBUSY*/
                            if (other) {
                        		put_driver(other);
                        		printk(KERN_ERR "Error: Driver '%s' is already registered, "
                        			"aborting...\n", drv->name);
                        		return -EBUSY;
                        	}

                        	ret = bus_add_driver(drv);
                                 {
                                	struct bus_type *bus;
                                	struct driver_private *priv;
                                	int error = 0;
                            /*前面初始化 s3c24xx_i2c_driver->driver.bus = &platform_bus_type*/
                                	bus = bus_get(drv->bus);
                                	if (!bus)
                                		return -EINVAL;

                                	pr_debug("bus: '%s': add driver %s\n", bus->name, drv->name);

                                    /*为s3c24xx_i2c_driver->driver申请私有结构体*/

                                	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
                                	if (!priv) {
                                		error = -ENOMEM;
                                		goto out_put_bus;
                                	}
                                	klist_init(&priv->klist_devices, NULL, NULL);
                                	priv->driver = drv;
                                	drv->p = priv;
                                    /*s3c24xx_i2c_driver->driver->priv->kobj.kset = platform_bus_type->p->drivers_kset
                                    还记得sys/bus/platform下的drivers目录吗
                                    priv->drivers_kset = kset_create_and_add("drivers", NULL, &priv->subsys.kobj);*/
                                	priv->kobj.kset = bus->p->drivers_kset;
                                    /*在sys/bus/platform/drivers目录下创建s3c-i2c的目录*/
                                	error = kobject_init_and_add(&priv->kobj, &driver_ktype, NULL,
                                				     "%s", drv->name);
                                	if (error)
                                		goto out_unregister;
                                    /*又见到了drivers_autoprobe,还记得/sys/bus/platform下的drivers_autoprobe文件吗
                                    platform_bus_type->p->drivers_autoprobe = 1,自动匹配device和driver*/
                                	if (drv->bus->p->drivers_autoprobe) {
                                		error = driver_attach(drv);
                                                {
                                                	return bus_for_each_dev(drv->bus, NULL, drv, __driver_attach);
                                                           {
                                                            	struct klist_iter i;
                                                            	struct device *dev;
                                                            	int error = 0;

                                                            	if (!bus || !bus->p)
                                                            		return -EINVAL;
                                                                /*device注册的时候就是挂接到 platform_bus_type->p->klist_devices
                                                                下面就是遍历platform_bus_type的device链表,然后通过__driver_attach和driver
                                                                做匹配*/

                                                            	klist_iter_init_node(&bus->p->klist_devices, &i,
                                                            			     (start ? &start->p->knode_bus : NULL));
                                                            	while ((dev = next_device(&i)) && !error)
                                                            		error = fn(dev, data);  //fn = __driver_attach
                                                                            {
                                                                            	struct device_driver *drv = data;

                                                                            	/*
                                                                            	 * Lock device and try to bind to it. We drop the error
                                                                            	 * here and always return 0, because we need to keep trying
                                                                            	 * to bind to devices and some drivers will return an error
                                                                            	 * simply if it didn't support the device.
                                                                            	 *
                                                                            	 * driver_probe_device() will spit a warning if there
                                                                            	 * is an error.
                                                                            	 */

                                                                            	if (!driver_match_device(drv, dev))
                                                                                    {   /*drv->bus->match = platform_match,最终还是调用到platform的match函数
                                                                                        最终会匹配到 s3c_device_i2c3*/
                                                                                    	return drv->bus->match ? drv->bus->match(dev, drv) : 1;
                                                                                    }
                                                                            		return 0;
                                                                                /*dev = s3c_device_i2c3->dev
                                                                                  s3c_device_i2c3->dev->parent = &platform_bus */

                                                                            	if (dev->parent)	/* Needed for USB */
                                                                            		device_lock(dev->parent);
                                                                            	device_lock(dev);
                                                                                /*虽然device和driver都找到了,可还未将driver赋值给device呢*/
                                                                            	if (!dev->driver)
                                                                            		driver_probe_device(drv, dev);
                                                                                    {
                                                                                    	int ret = 0;

                                                                                    	if (!device_is_registered(dev))
                                                                                    		return -ENODEV;

                                                                                    	pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
                                                                                    		 drv->bus->name, __func__, dev_name(dev), drv->name);

                                                                                    	pm_runtime_get_noresume(dev);
                                                                                    	pm_runtime_barrier(dev);
                                                                                    	ret = really_probe(dev, drv);
                                                                                            {
                                                                                            	int ret = 0;

                                                                                            	atomic_inc(&probe_count);
                                                                                            	pr_debug("bus: '%s': %s: probing driver %s with device %s\n",
                                                                                            		 drv->bus->name, __func__, drv->name, dev_name(dev));
                                                                                            	WARN_ON(!list_empty(&dev->devres_head));
                                                                                                /*这里才将driver和device关联起来*/
                                                                                            	dev->driver = drv;
                                                                                            	if (driver_sysfs_add(dev)) {
                                                                                                    {
                                                                                                    	int ret;

                                                                                                    	if (dev->bus)
                                                                                                    		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
                                                                                                    					     BUS_NOTIFY_BIND_DRIVER, dev);
                                                                                                        /*sys/bus/platform/drivers/s3c-i2c创建指向s3c2440-i2c.3的链接,
                                                                                                        名字仍然为s3c2440-i2c.3*/
                                                                                                    	ret = sysfs_create_link(&dev->driver->p->kobj, &dev->kobj,
                                                                                                    			  kobject_name(&dev->kobj));
                                                                                                    	if (ret == 0) {
                                                                                                            /*在sys/bus/platform/device/s3c2440-i2c.3下
                                                                                                            创建指向sys/bus/platform/drivers/s3c-i2c的链接,名字为driver*/
                                                                                                    		ret = sysfs_create_link(&dev->kobj, &dev->driver->p->kobj,
                                                                                                    					"driver");
                                                                                                    		if (ret)
                                                                                                    			sysfs_remove_link(&dev->driver->p->kobj,
                                                                                                    					kobject_name(&dev->kobj));
                                                                                                    	}
                                                                                                    	return ret;
                                                                                                    }
                                                                                            		printk(KERN_ERR "%s: driver_sysfs_add(%s) failed\n",
                                                                                            			__func__, dev_name(dev));
                                                                                            		goto probe_failed;
                                                                                            	}
                                                                                                /*platform_bus_type->probe = NULL,所以调用
                                                                                                s3c24xx_i2c_driver->probe也就是 s3c24xx_i2c_probe*/
                                                                                            	if (dev->bus->probe) {
                                                                                            		ret = dev->bus->probe(dev);
                                                                                            		if (ret)
                                                                                            			goto probe_failed;
                                                                                            	} else if (drv->probe) {
                                                                                            		ret = drv->probe(dev);
                                                                                            		if (ret)
                                                                                            			goto probe_failed;
                                                                                            	}

                                                                                            	driver_bound(dev);
                                                                                                {   /*前面s3c_device_i2c3->dev->p->knode_driver未初始化,也就是为NULL*/
                                                                                                	if (klist_node_attached(&dev->p->knode_driver)) {
                                                                                                		printk(KERN_WARNING "%s: device %s already bound\n",
                                                                                                			__func__, kobject_name(&dev->kobj));
                                                                                                		return;
                                                                                                	}

                                                                                                	pr_debug("driver: '%s': %s: bound to device '%s'\n", dev_name(dev),
                                                                                                		 __func__, dev->driver->name);
                                                                                                    /*将device挂接在driver的设备链表中*/
                                                                                                	klist_add_tail(&dev->p->knode_driver, &dev->driver->p->klist_devices);

                                                                                                	if (dev->bus)
                                                                                                		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
                                                                                                					     BUS_NOTIFY_BOUND_DRIVER, dev);
                                                                                                }
                                                                                            	ret = 1;
                                                                                            	pr_debug("bus: '%s': %s: bound device %s to driver %s\n",
                                                                                            		 drv->bus->name, __func__, dev_name(dev), drv->name);
                                                                                            	goto done;

                                                                                            probe_failed:
                                                                                            	devres_release_all(dev);
                                                                                            	driver_sysfs_remove(dev);
                                                                                            	dev->driver = NULL;

                                                                                            	if (ret != -ENODEV && ret != -ENXIO) {
                                                                                            		/* driver matched but the probe failed */
                                                                                            		printk(KERN_WARNING
                                                                                            		       "%s: probe of %s failed with error %d\n",
                                                                                            		       drv->name, dev_name(dev), ret);
                                                                                            	}
                                                                                            	/*
                                                                                            	 * Ignore errors returned by ->probe so that the next driver can try
                                                                                            	 * its luck.
                                                                                            	 */
                                                                                            	ret = 0;
                                                                                            done:
                                                                                            	atomic_dec(&probe_count);
                                                                                            	wake_up(&probe_waitqueue);
                                                                                            	return ret;
                                                                                            }
                                                                                    	pm_runtime_put_sync(dev);

                                                                                    	return ret;
                                                                                    }
                                                                            	device_unlock(dev);
                                                                            	if (dev->parent)
                                                                            		device_unlock(dev->parent);

                                                                            	return 0;
                                                                            }
                                                            	klist_iter_exit(&i);
                                                            	return error;
                                                           }
                                                }
                                		if (error)
                                			goto out_unregister;
                                	}
                                    /*将s3c24xx_i2c_driver挂接在platform的driver链表中*/
                                	klist_add_tail(&priv->knode_bus, &bus->p->klist_drivers);
                                	module_add_driver(drv->owner, drv);
                                    /*在/sys/bus/platform/drivers/s3c-i2c创建uevent文件*/
                                	error = driver_create_file(drv, &driver_attr_uevent);
                                	if (error) {
                                		printk(KERN_ERR "%s: uevent attr (%s) failed\n",
                                			__func__, drv->name);
                                	}
                                    /*为 s3c24xx_i2c_driver 创建默认的属性文件,可是platform_bus_type->drv_attrs = NULL,所以此例中没有
                                    没有创建任何文件*/
                                	error = driver_add_attrs(bus, drv);
                                            {
                                            	int error = 0;
                                            	int i;

                                            	if (bus->drv_attrs) {
                                            		for (i = 0; attr_name(bus->drv_attrs[i]); i++) {
                                            			error = driver_create_file(drv, &bus->drv_attrs[i]);
                                            			if (error)
                                            				goto err;
                                            		}
                                            	}
                                            done:
                                            	return error;
                                            err:
                                            	while (--i >= 0)
                                            		driver_remove_file(drv, &bus->drv_attrs[i]);
                                            	goto done;
                                            }
                                	if (error) {
                                		/* How the hell do we get out of this pickle? Give up */
                                		printk(KERN_ERR "%s: driver_add_attrs(%s) failed\n",
                                			__func__, drv->name);
                                	}
                                    /*s3c24xx_i2c_driver->drv->suppress_bind_attrs 未赋值,也就是为0*/
                                	if (!drv->suppress_bind_attrs) {
                                		error = add_bind_files(drv);
                                                {
                                                	int ret;
                                                    /*在/sys/bus/platform/drivers/s3c-i2c目录下创建 ubind 文件*/
                                                	ret = driver_create_file(drv, &driver_attr_unbind);
                                                	if (ret == 0) {
                                                        /*在/sys/bus/platform/drivers/s3c-i2c目录下创建 bind 文件*/
                                                		ret = driver_create_file(drv, &driver_attr_bind);
                                                		if (ret)
                                                			driver_remove_file(drv, &driver_attr_unbind);
                                                	}
                                                	return ret;
                                                }
                                		if (error) {
                                			/* Ditto */
                                			printk(KERN_ERR "%s: add_bind_files(%s) failed\n",
                                				__func__, drv->name);
                                		}
                                	}
                                    /*发送 KOBJ_ADD */
                                	kobject_uevent(&priv->kobj, KOBJ_ADD);
                                	return 0;

                                out_unregister:
                                	kobject_put(&priv->kobj);
                                	kfree(drv->p);
                                	drv->p = NULL;
                                out_put_bus:
                                	bus_put(bus);
                                	return error;
                                }
                        	if (ret)
                        		return ret;
                            /*创建属性组及文件,s3c24xx_i2c_driver->drv未初始化,也就是为NULL,不会创建任何文件*/
                        	ret = driver_add_groups(drv, drv->groups);
                                {
                                	int error = 0;
                                	int i;

                                	if (groups) {
                                		for (i = 0; groups[i]; i++) {
                                			error = sysfs_create_group(&drv->p->kobj, groups[i]);
                                			if (error) {
                                				while (--i >= 0)
                                					sysfs_remove_group(&drv->p->kobj,
                                							   groups[i]);
                                				break;
                                			}
                                		}
                                	}
                                	return error;
                                }
                        	if (ret)
                        		bus_remove_driver(drv);
                        	return ret;
                        }
            }
}

上面的 s3c24xx_i2c_driver 注册过程,大致就是从platform总线上匹配到 s3c_device_i2c3 ,然后调用 s3c24xx_i2c_probe,同时建立一些目录、链接和属性文件。简单一点描述就是先注册个platform类型的device,在注册一个platform类型的driver,在platform总线的牵引(match)下,device 和driver绑定并调用到driver的初始化函数。到此只是驱动模型框架的作用,真正驱动的是从 s3c24xx_i2c_probe 开始,设置时钟,IO口和中断等等。下面看下s3c24xx_i2c_driver 注册过程中产生的文件。

1. 在sys/bus/platform/drivers目录下创建s3c-i2c的目录

[root@FriendlyARM drivers]# ls
alarm               s3c-i2c             s5p-tmu
......s3c-i2c             s5p-tmu
......

2. 在sys/bus/platform/drivers/s3c-i2c创建指向s3c2440-i2c.3的链接,名字仍然为s3c2440-i2c.3

[root@FriendlyARM s3c-i2c]# cd /sys/bus/platform/drivers/s3c-i2c/
[root@FriendlyARM s3c-i2c]# ls -l
--w-------    1 root     root          4096 Jan  1 12:48 bind
lrwxrwxrwx    1 root     root             0 Jan  1 12:48 s3c2440-i2c.0 -> ../../../../devices/platform/s3c2440-i2c.0
lrwxrwxrwx    1 root     root             0 Jan  1 12:48 s3c2440-i2c.3 -> ../../../../devices/platform/s3c2440-i2c.3
lrwxrwxrwx    1 root     root             0 Jan  1 12:48 s3c2440-i2c.4 -> ../../../../devices/platform/s3c2440-i2c.4s3c2440-i2c.3 -> ../../../../devices/platform/s3c2440-i2c.3
lrwxrwxrwx    1 root     root             0 Jan  1 12:48 s3c2440-i2c.4 -> ../../../../devices/platform/s3c2440-i2c.4

3. 在sys/bus/platform/device/s3c2440-i2c.3下创建指向sys/bus/platform/drivers/s3c-i2c的链接,名字为driver

[root@FriendlyARM s3c-i2c]# cd /sys/bus/platform/devices/s3c2440-i2c.3
[root@FriendlyARM s3c2440-i2c.3]# ls -l
lrwxrwxrwx    1 root     root             0 Jan  1 13:21 driver -> ../../../bus/platform/drivers/s3c-i2c
drwxr-xr-x    9 root     root             0 Jan  1  2016 i2c-3driver -> ../../../bus/platform/drivers/s3c-i2c
drwxr-xr-x    9 root     root             0 Jan  1  2016 i2c-3

4. 在/sys/bus/platform/drivers/s3c-i2c创建uevent文件

[root@FriendlyARM s3c2440-i2c.3]# cd /sys/bus/platform/drivers/s3c-i2c/
[root@FriendlyARM s3c-i2c]# ls
bind           s3c2440-i2c.3  s3c2440-i2c.3  s3c2440-i2c.7  unbind
s3c2440-i2c.0  s3c2440-i2c.2  s3c2440-i2c.4  uevent

5.在/sys/bus/platform/drivers/s3c-i2c目录下创建 ubind 文件

在/sys/bus/platform/drivers/s3c-i2c目录下创建 bind 文件

 

[root@FriendlyARM s3c2440-i2c.3]# cd /sys/bus/platform/drivers/s3c-i2c/
[root@FriendlyARM s3c-i2c]# ls
bind           s3c2440-i2c.3  s3c2440-i2c.3  s3c2440-i2c.7  unbind
s3c2440-i2c.0  s3c2440-i2c.2  s3c2440-i2c.4  ueventbind           s3c2440-i2c.3  s3c2440-i2c.3  s3c2440-i2c.7  unbind
s3c2440-i2c.0  s3c2440-i2c.2  s3c2440-i2c.4  uevent

对于uevent、bind和ubind等属性文件,可以查看store和show函数。下面展开一下ubind和bind属性的定义:

static DRIVER_ATTR(unbind, S_IWUSR, NULL, driver_unbind);

展开:

struct driver_attribute driver_attr_unbind = 
{
    .attr = {
        .name = "unbind",
        .mode = _mode 
    },	
	.show	= NULL,					
	.store	= driver_bind,
}

store函数:

static ssize_t driver_unbind(struct device_driver *drv,
			     const char *buf, size_t count)
{
	struct bus_type *bus = bus_get(drv->bus);
	struct device *dev;
	int err = -ENODEV;

	dev = bus_find_device_by_name(bus, NULL, buf);
	if (dev && dev->driver == drv) {
		if (dev->parent)	/* Needed for USB */
			device_lock(dev->parent);
		device_release_driver(dev);
        {
        	struct device_driver *drv;

        	drv = dev->driver;
        	if (drv) {
        		pm_runtime_get_sync(dev);

        		driver_sysfs_remove(dev);

        		if (dev->bus)
        			blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
        						     BUS_NOTIFY_UNBIND_DRIVER,
        						     dev);

        		pm_runtime_put_sync(dev);

        		if (dev->bus && dev->bus->remove)
        			dev->bus->remove(dev);
        		else if (drv->remove)
        			drv->remove(dev);
        		devres_release_all(dev);
        		dev->driver = NULL;
        		klist_remove(&dev->p->knode_driver);
        		if (dev->bus)
        			blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
        						     BUS_NOTIFY_UNBOUND_DRIVER,
        						     dev);

        	}
        }
		if (dev->parent)
			device_unlock(dev->parent);
		err = count;
	}
	put_device(dev);
	bus_put(bus);
	return err;
}

从上面代码可看出,像unbind文件中写入device的name,就会取消device和该driver的绑定。

下面再看bind属性的定义:

static DRIVER_ATTR(bind, S_IWUSR, NULL, driver_bind);

展开;

struct driver_attribute driver_attr_bind = 
{
    .attr = {
        .name = "bind",
        .mode = _mode 
    },	
	.show	= NULL,					
	.store	= driver_bind,
}

store函数:

static ssize_t driver_bind(struct device_driver *drv,
			   const char *buf, size_t count)
{
	struct bus_type *bus = bus_get(drv->bus);
	struct device *dev;
	int err = -ENODEV;

	dev = bus_find_device_by_name(bus, NULL, buf);
	if (dev && dev->driver == NULL && driver_match_device(drv, dev)) {
		if (dev->parent)	/* Needed for USB */
			device_lock(dev->parent);
		device_lock(dev);
		err = driver_probe_device(drv, dev);
            {
            	int ret = 0;

            	if (!device_is_registered(dev))
            		return -ENODEV;

            	pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
            		 drv->bus->name, __func__, dev_name(dev), drv->name);

            	pm_runtime_get_noresume(dev);
            	pm_runtime_barrier(dev);
            	ret = really_probe(dev, drv);
            	pm_runtime_put_sync(dev);

            	return ret;
            }
		device_unlock(dev);
		if (dev->parent)
			device_unlock(dev->parent);

		if (err > 0) {
			/* success */
			err = count;
		} else if (err == 0) {
			/* driver didn't accept device */
			err = -ENODEV;
		}
	}
	put_device(dev);
	bus_put(bus);
	return err;
}

从上面的代码可以看出,向bind文件写入device的name,那么就将搜索device和该driver绑定。

上面的unbind和bing是不是很像/sys/bus/platform/下的drivers_probe文件?

下一节将从 s3c24xx_i2c_probe 分析i2c的驱动框架。

 

linux class device

阅读数 450

没有更多推荐了,返回首页