int i2c_register_driver(struct module *owner, struct i2c_driver *driver) { int res; /* Can't register until after driver model init */ if (unlikely(WARN_ON(!i2c_bus_type.p))){ printk("Can't register until after driver model init\n"); return -EAGAIN; } /* add the driver to the list of i2c drivers in the driver core */ driver->driver.owner = owner; driver->driver.bus = &i2c_bus_type; /* When registration returns, the driver core * will have called probe() for all matching-but-unbound devices. */ res = driver_register(&driver->driver); if (res) return res; pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name); INIT_LIST_HEAD(&driver->clients); /* Walk the adapters that are already present */ mutex_lock(&core_lock); bus_for_each_dev(&i2c_bus_type, NULL, driver, __process_new_driver); mutex_unlock(&core_lock); return 0; }
函数通过
driver->driver.bus = &i2c_bus_type;
可见此驱动通过函数driver_register()之后 同样会被注册到了i2c总线上。值得一提的是此处i2cdev_driver中的attach_adapter的执行机会很大,通过bus_for_each_dev()函数
bus_for_each_dev(&i2c_bus_type, NULL, driver, __process_new_driver);
会尝试和i2c总线上所有的dev进行一次匹配,只要获取的dev为adapter时,就可执行后续操作。此处的bus_for_each_dev函数主要功能就是循环查询一遍i2c总线上所有的dev,包括adapter device和client device。
然后依次将dev和driver作为__process_new_driver的参数并执行__process_new_driver函数,但是只有adapter device
才会执行后续的操作,否则返回继续轮询i2c总线上的dev。
static int __process_new_driver(struct device *dev, void *data) { if (dev->type != &i2c_adapter_type) return 0; return i2c_do_add_adapter(data, to_i2c_adapter(dev)); }
可以发现__process_new_driver函数首先判断的是dev的类型,假如是adapter类型才会继续执行后面的代码,假如不是则立即返回继续摘取下个dev然后循环执行__process_new_driver。因为对我们来说,我们只需要注册adapter的驱动就可以了,i2c的所有操作是通过主机来完成的,从机只是被动接受。由于之前已经通过i2cadd_numbered_adapter()注册过adapter到总线i2c_bus_type,所以此处有机会执行后面的i2c_do_add_adapter函数。