900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Linux内核部件分析 设备驱动模型之device-driver

Linux内核部件分析 设备驱动模型之device-driver

时间:2022-12-11 04:17:34

相关推荐

Linux内核部件分析  设备驱动模型之device-driver

前面我们分析了device、driver、bus三种类型,主要是三者的注册与注销,在sysfs中的目录与属性文件创建等内容。本节就来详细分析下,在设备注册到总线上时,总线是如何为其寻找对应的驱动的;在驱动注册到总线上时,总线又是如何为其寻找对应的设备的。

本节的实现代码集中在drivers/base/bus.c和drivers/base/dd.c中。

先来回忆下,在device_register()->device_add()中,先是调用bus_add_device()添加device与bus间的联系,并添加bus为device定义的属性,然后会调用bus_probe_device()。bus_probe_device()会试图为已挂在总线上的该设备寻找对应的驱动。我们的故事就从这里开始。

/***bus_probe_device-probedriversforanewdevice*@dev:devicetoprobe**-Automaticallyprobeforadriverifthebusallowsit.*/voidbus_probe_device(structdevice*dev){structbus_type*bus=dev->bus;intret;if(bus&&bus->p->drivers_autoprobe){ret=device_attach(dev);WARN_ON(ret<0);}} bus_probe_device()为总线上的设备寻找驱动。它先是检查bus->p->drivers_autoprobe,看是否允许自动探测。允许了才会调用device_attach()进行实际的寻找工作。

说到bus->p->drivers_autoprobe这个变量,它是在bus_type_private中的,在调用bus_register()前都初始化不了,在bus_register()中自动定为1。所以,除非是用户空间通过drivers_autoprobe属性文件主动禁止,bus总是允许自动探测的,所有的bus都是如此。

/***device_attach-trytoattachdevicetoadriver.*@dev:device.**Walkthelistofdriversthatthebushasandcall*driver_probe_device()foreachpair.Ifacompatible*pairisfound,breakoutandreturn.**Returns1ifthedevicewasboundtoadriver;*0ifnomatchingdriverwasfound;*-ENODEVifthedeviceisnotregistered.**WhencalledforaUSBinterface,@dev->parent->semmustbeheld.*/intdevice_attach(structdevice*dev){intret=0;down(&dev->sem);if(dev->driver){ret=device_bind_driver(dev);if(ret==0)ret=1;else{dev->driver=NULL;ret=0;}}else{pm_runtime_get_noresume(dev);ret=bus_for_each_drv(dev->bus,NULL,dev,__device_attach);pm_runtime_put_sync(dev);}up(&dev->sem);returnret;}

device_attach()在实际绑定之前,会用dev->sem进行加锁。不错,dev->sem几乎就是为了在设备与驱动绑定或者解除绑定时加锁用的。还没有看到它在其它地方被调用。

如果在调用device_attach()前就已经有了dev->driver(),就调用device_bind_driver()进行绑定,不然还要调用bus_for_each_drv()进行依次匹配。至于pm_runtime_get_noresume之类的函数,属于电源管理部分,我们现在先忽略。

staticvoiddriver_bound(structdevice*dev){if(klist_node_attached(&dev->p->knode_driver)){printk(KERN_WARNING"%s:device%salreadybound\n",__func__,kobject_name(&dev->kobj));return;}pr_debug("driver:'%s':%s:boundtodevice'%s'\n",dev_name(dev),__func__,dev->driver->name);if(dev->bus)blocking_notifier_call_chain(&dev->bus->p->bus_notifier,BUS_NOTIFY_BOUND_DRIVER,dev);klist_add_tail(&dev->p->knode_driver,&dev->driver->p->klist_devices);}staticintdriver_sysfs_add(structdevice*dev){intret;ret=sysfs_create_link(&dev->driver->p->kobj,&dev->kobj,kobject_name(&dev->kobj));if(ret==0){ret=sysfs_create_link(&dev->kobj,&dev->driver->p->kobj,"driver");if(ret)sysfs_remove_link(&dev->driver->p->kobj,kobject_name(&dev->kobj));}returnret;}staticvoiddriver_sysfs_remove(structdevice*dev){structdevice_driver*drv=dev->driver;if(drv){sysfs_remove_link(&drv->p->kobj,kobject_name(&dev->kobj));sysfs_remove_link(&dev->kobj,"driver");}}/***device_bind_driver-bindadrivertoonedevice.*@dev:device.**Allowmanualattachmentofadrivertoadevice.*Callermusthavealreadyset@dev->driver.**Notethatthisdoesnotmodifythebusreferencecount*nortakethebus'srwsem.Pleaseverifythoseareaccounted*forbeforecallingthis.(Itisoktocallwithnoothereffort*fromadriver'sprobe()method.)**Thisfunctionmustbecalledwith@dev->semheld.*/intdevice_bind_driver(structdevice*dev){intret;ret=driver_sysfs_add(dev);if(!ret)driver_bound(dev);returnret;} device_bind_driver()将device与driver绑定。它调用了两个内部函数。

其中drivers_sysfs_add()负责创建sysfs中driver和device指向对方的软链接。还有一个与它相对的函数drivers_sysfs_remove()。

driver_bound()则实际将device加入驱动的设备链表。

因为在调用device_bind_driver()之前就已经设置过dev->driver了,所以这样就将device和driver绑定了。

只是这样好像还缺少了什么,不错,之前看到driver时曾定义了drv->probe函数,bus->probe也有类似的功能,这里只是绑定,却没有调用probe函数。

让我们回过头来,继续看如果device_attach()中没有定义dev->driver会怎么样,是用bus_for_each_drv()对bus的驱动链表进行遍历,遍历函数使用__device_attach。

staticint__device_attach(structdevice_driver*drv,void*data){structdevice*dev=data;if(!driver_match_device(drv,dev))return0;returndriver_probe_device(drv,dev);} 不要小看了__device_attach(),就是在__device_attach()中既完成了匹配工作,又完成了绑定工作。bus_for_each_drv()在遍历中,如果遍历函数返回值不为0,则遍历结束。所以在__device_attach()找到并绑定了适合的驱动,就会返回1停止遍历,否则继续遍历剩余的驱动。

先来看匹配工作,这是在driver_match_device()中完成的。

staticinlineintdriver_match_device(structdevice_driver*drv,structdevice*dev){returndrv->bus->match?drv->bus->match(dev,drv):1;} 原来driver_match_device()实际是调用drv->bus->match()来完成设备和驱动的匹配的。其实这也是理所当然。因为总线不同,总线规范设备、厂商、类设备等定义的规格都不同,也只有bus亲自主持匹配工作。再具体的就只能等分析具体总线的时候了。intdriver_probe_device(structdevice_driver*drv,structdevice*dev){intret=0;if(!device_is_registered(dev))return-ENODEV;pr_debug("bus:'%s':%s:matcheddevice%swithdriver%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);returnret;} 如果driver_match_device()匹配成功了,__device_attach()就会继续调用driver_probe_devices()完成绑定。但driver_probe_devices()又是调用really_probe()完成的。staticatomic_tprobe_count=ATOMIC_INIT(0);staticDECLARE_WAIT_QUEUE_HEAD(probe_waitqueue);staticintreally_probe(structdevice*dev,structdevice_driver*drv){intret=0;atomic_inc(&probe_count);pr_debug("bus:'%s':%s:probingdriver%swithdevice%s\n",drv->bus->name,__func__,drv->name,dev_name(dev));WARN_ON(!list_empty(&dev->devres_head));dev->driver=drv;if(driver_sysfs_add(dev)){printk(KERN_ERR"%s:driver_sysfs_add(%s)failed\n",__func__,dev_name(dev));gotoprobe_failed;}if(dev->bus->probe){ret=dev->bus->probe(dev);if(ret)gotoprobe_failed;}elseif(drv->probe){ret=drv->probe(dev);if(ret)gotoprobe_failed;}driver_bound(dev);ret=1;pr_debug("bus:'%s':%s:bounddevice%stodriver%s\n",drv->bus->name,__func__,dev_name(dev),drv->name);gotodone;probe_failed:devres_release_all(dev);driver_sysfs_remove(dev);dev->driver=NULL;if(ret!=-ENODEV&&ret!=-ENXIO){/*drivermatchedbuttheprobefailed*/printk(KERN_WARNING"%s:probeof%sfailedwitherror%d\n",drv->name,dev_name(dev),ret);}/**Ignoreerrorsreturnedby->probesothatthenextdrivercantry*itsluck.*/ret=0;done:atomic_dec(&probe_count);wake_up(&probe_waitqueue);returnret;} really_probe()完成的绑定工作和device_bind_driver()差不多,只是它还会调用bus->probe或者drv->probe中定义的probe函数。

至于在really_probe()中使用probe_count保护,最后调用wake_up(&probe_waitqueue),都是为了进行同步。

/***driver_probe_done*Determineiftheprobesequenceisfinishedornot.**Shouldsomehowfigureouthowtouseasemaphore,notanatomicvariable...*/intdriver_probe_done(void){pr_debug("%s:probe_count=%d\n",__func__,atomic_read(&probe_count));if(atomic_read(&probe_count))return-EBUSY;return0;}/***wait_for_device_probe*Waitfordeviceprobingtobecompleted.*/voidwait_for_device_probe(void){/*waitfortheknowndevicestocompletetheirprobing*/wait_event(probe_waitqueue,atomic_read(&probe_count)==0);async_synchronize_full();} driver_probe_done()检查当前是否有设备正在绑定驱动。

wait_for_device_probe()会阻塞到所有的设备绑定完驱动。

关于bus_probe_device()的过程就分析到这里,下面来看下bus_add_driver()又是怎样做的。

之前我们已经知道driver_register()把绝大部分操作都移到了bus_add_driver()中来。其中只有一点和设备与驱动的绑定相关,就是对driver_attach()的调用。

intdriver_attach(structdevice_driver*drv){returnbus_for_each_dev(drv->bus,NULL,drv,__driver_attach);} driver_attach()一如device_attach,只是这里是对总线的设备链表进行遍历,使用的遍历函数是__driver_attach()。staticint__driver_attach(structdevice*dev,void*data){structdevice_driver*drv=data;/**Lockdeviceandtrytobindtoit.Wedroptheerror*hereandalwaysreturn0,becauseweneedtokeeptrying*tobindtodevicesandsomedriverswillreturnanerror*simplyifitdidn'tsupportthedevice.**driver_probe_device()willspitawarningifthere*isanerror.*/if(!driver_match_device(drv,dev))return0;if(dev->parent)/*NeededforUSB*/down(&dev->parent->sem);down(&dev->sem);if(!dev->driver)driver_probe_device(drv,dev);up(&dev->sem);if(dev->parent)up(&dev->parent->sem);return0;} 在__driver_attach()中,driver_match_device()就不说了,它是调到bus->match去的。

然后依然是加锁,调用driver_probe_device()函数。这就与__device_attach()的路径一致了。

不要以为就这样结束了,现在我们只是看到了把device和driver绑定到一起的方法,却没有看到解除绑定的方法。

既然绑定的方法是在设备和驱动注册的时候调用的,那解除绑定自然是在设备或驱动注销的时候。

还是先来看设备的,device_unregister()->device_del()会调用bus_remove_device()将设备从总线上删除。

bus_remove_device()是与bus_add_device()相对的,但也不仅如此,它还调用了device_release_driver()来解除与driver的绑定。

/***device_release_driver-manuallydetachdevicefromdriver.*@dev:device.**Manuallydetachdevicefromdriver.*WhencalledforaUSBinterface,@dev->parent->semmustbeheld.*/voiddevice_release_driver(structdevice*dev){/**Ifanyonecallsdevice_release_driver()recursivelyfrom*withintheir->removecallbackforthesamedevice,they*willdeadlockrighthere.*/down(&dev->sem);__device_release_driver(dev);up(&dev->sem);}/**__device_release_driver()mustbecalledwith@dev->semheld.*WhencalledforaUSBinterface,@dev->parent->semmustbeheldaswell.*/staticvoid__device_release_driver(structdevice*dev){structdevice_driver*drv;drv=dev->driver;if(drv){pm_runtime_get_noresume(dev);pm_runtime_barrier(dev);driver_sysfs_remove(dev);if(dev->bus)blocking_notifier_call_chain(&dev->bus->p->bus_notifier,BUS_NOTIFY_UNBIND_DRIVER,dev);if(dev->bus&&dev->bus->remove)dev->bus->remove(dev);elseif(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);pm_runtime_put_sync(dev);}} device_release_driver()还是负责加加锁,实际的工作由__device_release_driver()来完成。

除了sysfs和结构中解除绑定的操作,还调用了bus->remove或者driver->remove。

虽然device注销时与driver解除绑定很简单,但driver注销要与device解除绑定就要复杂一些,因为它要与设备链表上所有的设备解除绑定。

在driver_unregister()->bus_remove_driver()中,调用了driver_detach()函数。

/***driver_detach-detachdriverfromalldevicesitcontrols.*@drv:driver.*/voiddriver_detach(structdevice_driver*drv){structdevice_private*dev_prv;structdevice*dev;for(;;){spin_lock(&drv->p->klist_devices.k_lock);if(list_empty(&drv->p->klist_devices.k_list)){spin_unlock(&drv->p->klist_devices.k_lock);break;}dev_prv=list_entry(drv->p->klist_devices.k_list.prev,structdevice_private,knode_driver.n_node);dev=dev_prv->device;get_device(dev);spin_unlock(&drv->p->klist_devices.k_lock);if(dev->parent)/*NeededforUSB*/down(&dev->parent->sem);down(&dev->sem);if(dev->driver==drv)__device_release_driver(dev);up(&dev->sem);if(dev->parent)up(&dev->parent->sem);put_device(dev);}} 可以看到,driver_detach()基本操作就是与设备链表上的设备解除绑定。等了这么久,终于有个有点意思的地方。一看这个drv的设备链表遍历,首先明明是klist,却没使用标准的循环函数,奇怪,然后发现竟然没有将设备卸下链表的地方,更奇怪。其实再一想就明白了。你看到list_entry()中,是从设备链表末尾取设备解除绑定的,这是驱动生怕前面的设备解除绑定了,后面的就不工作了。也正是因为klist遍历是逆向的,所以无法使用标准函数。至于将设备卸下链表的地方,是在__device_release_driver()中。

或许会奇怪这里为什么会有get_device()和put_device()的操作。这是为了防止设备一取下链表,就会释放最后一个引用计数,导致直接注销。那时候的情况,一定是在占用了dev->sem的同时去等待dev->sem,通俗来说就是死锁。

通过driver_attach()和driver_detach()的训练,我们已经习惯在为设备加锁时,顺便为其父设备加锁。虽然在device_attach()和device_release_driver()中只是对设备本身加锁。或许是害怕在驱动与设备解除绑定的过程中,父设备突然也要解除绑定,导致不一致状态。为至于为什么设备方主动要求时不需要对父设备加锁,或许是设备的主动申请更靠谱,不会在子设备绑定或释放的同时,父设备也申请释放。总之,在linux看来,设备恐怕比驱动还要靠谱一些,从driver和bus的引用计数,从这里的加锁情况,都可以看出一二。

void*dev_get_drvdata(conststructdevice*dev){if(dev&&dev->p)returndev->p->driver_data;returnNULL;}voiddev_set_drvdata(structdevice*dev,void*data){interror;if(!dev)return;if(!dev->p){error=device_private_init(dev);if(error)return;}dev->p->driver_data=data;} 最后的dev_set_drvdata()是在dev->p->driver_data中存放驱动定义的数据。dev_get_drvdata()是获取这个数据。

不要 小看这个device_private结构中小小的driver_data,在驱动编写中总能派上大用场。当然也不是说没有driver_data就过不下去,毕竟驱动可以定义一个自己的device结构,并把通用的struct device内嵌其中,然后想放多少数据都行。可那样太麻烦,许多驱动都要专门设置这样一个变量,索性加到通用的数据结构中。而且是直接加到device_private中,眼不见为净,方便省事。

/***device_reprobe-removedriverforadeviceandprobeforanewdriver*@dev:thedevicetoreprobe**Thisfunctiondetachestheattacheddriver(ifany)forthegiven*deviceandrestartsthedriverprobingprocess.Itisintended*touseifprobingcriteriachangedduringadeviceslifetimeand*driverattachmentshouldchangeaccordingly.*/intdevice_reprobe(structdevice*dev){if(dev->driver){if(dev->parent)/*NeededforUSB*/down(&dev->parent->sem);device_release_driver(dev);if(dev->parent)up(&dev->parent->sem);}returnbus_rescan_devices_helper(dev,NULL);} device_reprobe()显然是dev对之前的驱动不满意,要新绑定一个。staticint__must_checkbus_rescan_devices_helper(structdevice*dev,void*data){intret=0;if(!dev->driver){if(dev->parent)/*NeededforUSB*/down(&dev->parent->sem);ret=device_attach(dev);if(dev->parent)up(&dev->parent->sem);}returnret<0?ret:0;} bus_rescan_devices_helper()就是用来绑定新驱动的内部函数。

我们终于成功完成了对dd.c的分析,并将bus.c剩余的部分结了尾。想必大家已经充分领略了device、driver和bus的铁三角结构,下节我们将进入设备驱动模型的另一方天地。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。