Professional Documents
Culture Documents
LinuxUSBdrivers
MichaelOpdenacker FreeElectrons http://freeelectrons.com/
CreatedwithOpenOffice.org2.x
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
Purposeofthiscourse
Learnhowtoimplement Linuxdrivers forsomeofthemost complexUSBdevices!
Buyyoursonhttp://www.thinkgeek.com/stuff/41/fundue.shtml!
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
Rightstocopy
Copyright20062007 FreeElectrons feedback@freeelectrons.com Documentsources,updatesandtranslations: http://freeelectrons.com/articles/linuxusb Corrections,suggestions,contributionsand translationsarewelcome!
AttributionShareAlike2.5 Youarefree tocopy,distribute,display,andperformthework tomakederivativeworks tomakecommercialuseofthework Underthefollowingconditions Attribution.Youmustgivetheoriginalauthorcredit. ShareAlike.Ifyoualter,transform,orbuilduponthiswork, youmaydistributetheresultingworkonlyunderalicense identicaltothisone. Foranyreuseordistribution,youmustmakecleartoothersthe licensetermsofthiswork. Anyoftheseconditionscanbewaivedifyougetpermissionfrom thecopyrightholder. Yourfairuseandotherrightsareinnowayaffectedbytheabove. Licensetext:http://creativecommons.org/licenses/bysa/2.5/legalcode
Bestviewedwith...
ThisdocumentisbestviewedwitharecentPDFreader orwithOpenOffice.orgitself! Takeadvantageofinternalorexternalhyperlinks. So,donthesitatetoclickonthem! Findpagesquicklythankstoautomaticsearch Usethumbnailstonavigateinthedocumentinaquickway IfyourereadingapaperorHTMLcopy,youshouldgetyour copyinPDForOpenOffice.orgformaton http://freeelectrons.com/articles/linuxusb!
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
Courseprerequisites
Fonduecheese GoodknowledgeaboutLinuxdevicedriverdevelopment. MostnotionswhicharenotUSBspecificarecovered inourhttp://freeelectrons.com/training/driverscourse. Tocreatereal,workingdrivers:agoodknowledgeaboutthe USBdevicesyouwanttowritedriversfor.Agood knowledgeaboutUSBspecificationstoo.
Contents
LinuxUSBbasics LinuxUSBdrivers USBdevices Userspacerepresentation LinuxUSBcommunication USBRequestBlocks InitializingandsubmittingURBs Completionhandlers
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
LinuxUSBdrivers
LinuxUSBbasics
LinuxUSBdrivers
USBdrivers(1)
USBcoredrivers Architectureindependentkernelsubsystem. ImplementstheUSBbusspecification. Outsidethescopeofthistraining. USBhostdrivers DifferentdriversforeachUSBcontrolhardware. UsuallyavailableintheBoardSupportPackage. Architectureandplatformdependent. Notcoveredyetbythistraining.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
USBdrivers(2)
USBdevicedrivers DriversfordevicesontheUSBbus. Themainfocusofthiscourse! Platformindependent:whenyouuseLinuxonanembedded platform,youcanuseanyUSBdevicesupportedbyLinux (cameras,keyboards,videocapture,wifidongles...). USBdevicecontrollerdrivers ForLinuxsystemswithjustaUSBdevicecontroller (frequentinembeddedsystems). Notcoveredyetbythiscourse.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
USBgadgetdrivers
DriversforLinuxsystemswithaUSBdevicecontroller Typicalexample:digitalcameras. YouconnectthedevicetoaPCandseethecamera asaUSBstoragedevice. USBdevicecontrollerdriver: Platformdependent.SupportsthechipconnectingtotheUSBbus. USBgadgetdrivers,platformindependent.Examples: Ethernetgadget:implementsnetworkingthroughUSB Storagegadget:makesthehostseeaUSBstoragedevice Serialgadget:forterminaltypeofcommunication. SeeDocumentation/DocBook/gadget/inkernelsources.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
10
LinuxUSBsupportoverview
Userapplications Systemcallinterface
Users
LinuxKernel Hardware
USBdevice
11
USBhostcontrollersOHCIandUHCI
2competingHostControlDevice(HCD)interfaces OHCIOpenHostControllerInterface Compaq'simplementationadoptedasastandardforUSB1.0and1.1 bytheUSBImplementersForum(USBIF). AlsousedforFirewiredevices. UHCIUniversalHostControllerInterface. CreatedbyIntel,insistingthatotherimplementersuseitandpay royaltiesforit.OnlyVIAlicensedUHCI,andothersstucktoOHCI. Thiscompetitionrequiredtotestdevicesforbothhostcontrollerstandards! ForUSB2.0,theUSBIFinsistedonhavingonlyonestandard.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
12
USBhostcontrollersEHCI
EHCIExtendedHostControllerInterface. ForUSB2.0.Theonlyonetosupporthighspeedtransfers. EachEHCIcontrollercontainsfourvirtualHCDimplementationsto supportFullSpeedandLowSpeeddevices. OnIntelandVIAchipsets,virtualHCDsareUHCI. OtherchipsetmakershaveOHCIvirtualHCDs.
13
USBtransferspeed
LowSpeed:upto1.5Mbps SinceUSB1.0 FullSpeed:upto12Mbps SinceUSB1.1 HiSpeed:upto480Mbps SinceUSB2.0
14
LinuxUSBdrivers
LinuxUSBbasics
USBdevices
15
USBdescriptors
Operatingsystemindependent.DescribedintheUSBspecification DeviceRepresentthedevicesconnectedtotheUSBbus. Example:USBspeakerwithvolumecontrolbuttons. ConfigurationsRepresentthestateofthedevice. Examples:Active,Standby,Initialization InterfacesLogicaldevices. Examples:speaker,volumecontrolbuttons. EndpointsUnidirectionalcommunicationpipes. EitherIN(devicetocomputer)orOUT(computertodevice).
16
Controlendpoints
Usedtoconfigurethedevice,getinformationaboutit,send commandstoit,retrievestatusinformation. Simple,smalldatatransfers. Everydevicehasacontrolendpoint(endpoint0), usedtoconfigurethedeviceatinsertiontime. TheUSBprotocolguaranteesthatthecorrespondingdata transferswillalwayshaveenough(reserved)bandwidth.
17
Interruptendpoints
Transfersmallamountsofdataatafixedrate eachtimethehostsasksthedevicefordata. Guaranteed,reservedbandwidth. Fordevicesrequiringguaranteedresponsetime, suchasUSBmiceandkeyboards. Note:differentthanhardwareinterrupts. Requireconstantpollingfromthehost.
18
Bulkendpoints
Largesporadicdatatransfers usingallremainingavailablebandwidth. Noguaranteeonbandwidthorlatency. Guaranteethatnodataislost. Typicallyusedforprinters,storageornetworkdevices.
19
Isochronousendpoints
Alsoforlargeamountsofdata. Guaranteedspeed (oftenbutnotnecessarilyasfastaspossible). Noguaranteethatalldatamakesitthrough. Usedbyrealtimedatatransfers(typicallyaudioandvideo).
20
Theusb_endpoint_descriptorstructure(1)
Theusb_endpoint_descriptorstructurecontainsallthe USBspecificdataannouncedbythedeviceitself. Hereareusefulfieldsfordriverwriters: __u8bEndpointAddress: USBaddressoftheendpoint. Italsoincludesthedirectionoftheendpoint.Youcanusethe USB_ENDPOINT_DIR_MASKbitmasktotellwhetherthisisa USB_DIR_INorUSB_DIR_OUTendpoint.Example: if((endpoint>desc.bEndpointAddress& USB_ENDPOINT_DIR_MASK)==USB_DIR_IN)
21
Theusb_endpoint_descriptorstructure(2)
__u8bmAttributes: Thetypeoftheendpoint.YoucanusetheUSB_ENDPOINT_XFERTYPE_MASK bitmasktotellwhetherthetypeisUSB_ENDPOINT_XFER_ISOC, USB_ENDPOINT_XFER_BULK,USB_ENDPOINT_XFER_INTor USB_ENDPOINT_XFER_CONTROL. __u8wMaxPacketSize: Maximumsizeinbytesthattheendpointcanhandle.Notethatifgreatersizesareused, datawillbesplitinwMaxPacketSizechunks. __u8bInterval: Forinterruptendpoints,devicepollinginterval(inmilliseconds). NotethattheabovenamesdonotfollowLinuxcodingstandards. TheLinuxUSBimplementationkepttheoriginalnamefromtheUSBspecification (http://www.usb.org/developers/docs/).
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
22
Interfaces
Eachinterfaceencapsulatesasinglehighlevelfunction(USBlogical connection).Example(USBwebcam):videostream,audiostream, keyboard(controlbuttons). Onedriverisneededforeachinterface! Alternatesettings:eachUSBinterfacemayhavedifferentparameter settings.Example:differentbandwidthsettingsforanaudiointerface. Theinitialstateisinthefirstsetting,(number0). Alternatesettingsareoftenusedtocontroltheuseofperiodicendpoints, suchasbyhavingdifferentendpointsusedifferentamountsofreserved USBbandwidth.AllstandardscompliantUSBdevicesthatuse isochronousendpointswillusetheminnondefaultsettings.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
23
Theusb_interfacestructure(1)
USBinterfacesarerepresentedbytheusb_interfacestructure. ItiswhattheUSBcorepassestoUSBdrivers. structusb_host_interface*altsetting; Listofalternatesettingsthatmaybeselectedforthisinterface,in noparticularorder. Theusb_host_interfacestructureforeachalternatesetting allowstoaccesstheusb_endpoint_descriptorstructure foreachofitsendpoints: interface>alsetting[i]>endpoint[j]>desc unsignedintnum_altsetting; Thenumberofalternatesettings.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
24
Theusb_interfacestructure(2)
structusb_host_interface*cur_altsetting; Thecurrentlyactivealternatesetting. intminor; Minornumberthisinterfaceisboundto. (fordriversusingusb_register_dev(),describedlater). Otherfieldsinthestructureshouldn'tbeneededbyUSBdrivers.
25
Configurations
Interfacesarebundledintoconfigurations. Configurationsrepresentthestateofthedevice. Examples:Active,Standby,Initialization Configurationsaredescribed withtheusb_host_configstructure. However,driversdonotneedtoaccessthisstructure.
26
Devices
Devicesarerepresentedbytheusb_devicestructure. WewillseelaterthatseveralUSBAPIfunctionsneedsucha structure. Manydriversusetheinterface_to_usbdev() functiontoaccesstheirusb_devicestructurefromthe usb_interfacestructuretheyaregivenbytheUSBcore.
27
USBdeviceoverview
endpoint
control
endpoint
input
endpoint
control
endpoint
input
InterfaceAudio
InterfaceAudio
endpoint
control
endpoint
input
endpoint
control
endpoint
input
28
USBdevicesSummary
Hierarchy:deviceconfigurations interfaces endpoints 4differenttypesofendpoints control:devicecontrol,accessinginformation,smalltransfers. Guaranteedbandwidth. interrupt(keyboards,mice...):datatransferatafixedrate. Guaranteedbandwidth. bulk(storage,network,printers...):useallremaining bandwidth.Nobandwidthorlatencyguarantee. isochronous(audio,video...):guaranteedspeed. Possibledataloss.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
29
LinuxUSBdrivers
LinuxUSBbasics
Userspacerepresentation
30
usbview
http://usbview.sourceforge.net Graphicaldisplay ofthecontentsof
/proc/bus/usb/devices.
31
usbtree
http://www.linuxusb.org/usbtree Alsodisplaysinformationfrom/proc/bus/usb/devices:
>usbtree \/:Bus04.Port1:Dev1,Class=root_hub,Driver=ehci_hcd/6p,480M /:Bus03.Port1:Dev1,Class=root_hub,Driver=uhci_hcd/2p,12M /:Bus02.Port1:Dev1,Class=root_hub,Driver=uhci_hcd/2p,12M |__Port1:Dev7,If0,Class=HID,Driver=usbhid,1.5M /:Bus01.Port1:Dev1,Class=root_hub,Driver=uhci_hcd/2p,12M
32
LinuxUSBdrivers
LinuxUSBcommunication
USBRequestBlocks
33
USBRequestBlocks
Anycommunicationbetweenthehostanddeviceisdone asynchronouslyusingUSBRequestBlocks(urbs). Theyaresimilartopacketsinnetworkcommunications. Everyendpointcanhandleaqueueofurbs. Everyurbhasacompletionhandler. Adrivermayallocatemanyurbsforasingleendpoint,or reusethesameurbfordifferentendpoints. SeeDocumentation/usb/URB.txtinkernelsources.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
34
Urbanlife
Device driver
Creation Assigned toanendpoint Submitted totheUSBcore canbe reused? no Deletion
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
Thelifecycleofanurb
USBcore (controller driver)
Transfered tothedevice Notificationat transfercompletion
yes
35
Theurbstructure(1)
FieldsoftheurbstructureusefultoUSBdevicedrivers: structusb_device*dev; Devicetheurbissentto. unsignedintpipe; Informationabouttheendpointinthetargetdevice. intstatus; Transferstatus. unsignedinttransfer_flags; Instructionsforhandlingtheurb.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
36
Theurbstructure(2)
void*transfer_buffer; Bufferstoringtransferreddata. Mustbecreatedwithkmalloc()! dma_addr_ttransfer_dma; DatatransferbufferwhenDMAisused. inttransfer_buffer_length; Transferbufferlength. intactual_length; Actuallengthofdatareceivedorsentbytheurb. usb_complete_tcomplete; Completionhandlercalledwhenthetransferiscomplete.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
37
Theurbstructure(3)
void*context; Datablobwhichcanbeusedinthecompletionhandler. unsignedchar*setup_packet;(controlurbs) Setuppackettransferredbeforethedatainthetransferbuffer. dma_addr_tsetup_dma;(controlurbs) Same,butwhenthesetuppacketistransferredwithDMA. intinterval;(isochronousandinterrupturbs) Urbpollinginterval. interror_count;(isochronousurbs) Numberofisochronoustransferswhichreportedanerror.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
38
Theurbstructure(4)
intstart_frame;(isochronousurbs) Setsorreturnstheinitialframenumbertouse. intnumber_of_packets;(isochronousurbs) Numberofisochronoustransferbufferstouse. structusb_iso_packet_descriptor(isochronousurbs) iso_frame_desc[0]; Allowsasingleurbtodefinemultipleisochronoustransfersatonce.
39
Creatingpipes
Functionsusedtoinitializethepipefieldoftheurbstructure: Controlpipes usb_sndctrlpipe(),usb_rcvctrlpipe() Bulkpipes usb_sndbulkpipe(),usb_rcvbulkpipe() Interruptpipes usb_sndintpipe(),usb_rcvintpipe() Isochronouspipes usb_sndisocpipe(),usb_rcvisocpipe() Prototype
send(out)
receive(in)
unsignedintusb_[snd/rcv][ctrl/bulk/int/isoc]pipe( structusb_device*dev,unsignedintendpoint);
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
40
Creatingurbs
urbstructuresmustalwaysbeallocatedwiththeusb_alloc_urb() function. That'sneededforreferencecountingusedbytheUSBcore. #include<linux/usb.h> structurb*usb_alloc_urb( intiso_packets, //Numberofisochronous //packetstheurbshouldcontain. //0forothertransfertypes gfp_tmem_flags); //Standardkmalloc()flags Checkthatitdidn'treturnNULL(allocationfailed)! Typicalexample: urb=usb_alloc_urb(0,GFP_KERNEL);
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
41
Freeingurbs
Similarly,youhavetouseadedicatedfunctiontoreleaseurbs: voidusb_free_urb(structurb*urb);
42
USBRequestBlocksSummary
BasicdatastructureusedinanyUSBcommunication. Implementedbythestructurbtype. Mustbecreatedwiththeusb_alloc_urb()function. Shouldn'tbeallocatedstaticallyorwithkmalloc(). Mustbedeletedwithusb_free_urb().
43
LinuxUSBdrivers
LinuxUSBcommunication
Initializingandsubmittingurbs
44
Initializinginterrupturbs
voidusb_fill_int_urb( structurb*urb, //urbtobeinitialized structusb_device*dev, //devicetosendtheurbto unsignedintpipe, //pipe(endpointanddevicespecific) void*transfer_buffer, //transferbuffer intbuffer_length, //transferbuffersize usb_complete_tcomplete, //completionhandler void*context, //context(forhandler) intinterval //Schedulinginterval(seenextpage) ); Thisdoesn'tpreventyoufrommakingmorechanges totheurbfieldsbeforeurbsubmission. Thetransfer_flagsfieldneedstobesetbythedriver.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
45
urbschedulinginterval
Forinterruptandisochronoustransfers LowSpeedandFullSpeeddevices: theintervalunitisframes(ms) HiSpeeddevices: theintervalunitismicroframes(1/8ms)
46
Initializingbulkurbs
Sameparametersasinusb_fill_int_urb(), exceptthatthereisnointervalparameter. voidusb_fill_bulk_urb( structurb*urb, structusb_device*dev, unsignedintpipe, void*transfer_buffer, intbuffer_length, usb_complete_tcomplete, void*context, ); //urbtobeinitialized //devicetosendtheurbto //pipe(endpointanddevicespecific) //transferbuffer //transferbuffersize //completionhandler //context(forhandler)
47
Initializingcontrolurbs
Sameparametersasinusb_fill_bulk_urb(), exceptthatthereisasetup_packetparameter. voidusb_fill_control_urb( structurb*urb, //urbtobeinitialized structusb_device*dev, //devicetosendtheurbto unsignedintpipe, //pipe(endpointanddevicespecific) unsignedchar*setup_packet,//setuppacketdata void*transfer_buffer, //transferbuffer intbuffer_length, //transferbuffersize usb_complete_tcomplete, //completionhandler void*context, //context(forhandler) ); Notethatmanydriversusetheusb_control_msg()functioninstead (explainedlater).
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
48
Initializingisochronousurbs
Nohelperfunction.Hastobedonemanuallybythedriver.
for(i=0;i<USBVIDEO_NUMSBUF;i++){ intj,k; structurb*urb=uvd>sbuf[i].urb; urb>dev=dev; urb>context=uvd; urb>pipe=usb_rcvisocpipe(dev,uvd>video_endp); urb>interval=1; urb>transfer_flags=URB_ISO_ASAP; urb>transfer_buffer=uvd>sbuf[i].data; urb>complete=usbvideo_IsocIrq; urb>number_of_packets=FRAMES_PER_DESC; urb>transfer_buffer_length=uvd>iso_packet_len*FRAMES_PER_DESC; for(j=k=0;j<FRAMES_PER_DESC;j++,k+=uvd>iso_packet_len){ urb>iso_frame_desc[j].offset=k; urb>iso_frame_desc[j].length=uvd>iso_packet_len; } }
drivers/media/video/usbvideo/usbvideo.cexample
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
49
AllocatingDMAbuffers(1)
Youcanusetheusb_buffer_alloc()function toallocateaDMAconsistentbuffer: void*usb_buffer_alloc( structusb_device*dev,//device size_tsize, //buffersize gfp_tmem_flags, //kmalloc()flags dma_addr_t*dma //(output)DMAaddress ); //ofthebuffer. Example: buf=usb_buffer_alloc(dev>udev, count,GFP_KERNEL,&urb>transfer_dma);
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
50
AllocatingDMAbuffers(2)
Tousethesebuffers,usetheURB_NO_TRANSFER_DMA_MAP orURB_NO_SETUP_DMA_MAPsettingsforurb>transfer_flagstoindicate thaturb>transfer_dmaorurb>setup_dmaarevalidonsubmit. Examples: urb>transfer_flags|=URB_NO_TRANSFER_DMA_MAP; u>transfer_flags|=URB_NO_SETUP_DMA_MAP; Freeingthesebuffers: voidusb_buffer_free( structusb_device*dev, //device size_tsize, //buffersize void*addr, //CPUaddressofbuffer dma_addr_tdma //DMAaddressofbuffer );
51
Submittingurbs
Aftercreatingandinitializingtheurb intusb_submit_urb( structurb*urb, intmem_flags); //urbtosubmit //kmalloc()flags
52
usb_submit_urbreturnvalues
usb_submit_urb()immediatelyreturns: 0: ENOMEM: ENODEV: EPIPE: EAGAIN: EFBIG: EINVAL: Requestqueued Outofmemory Unpluggeddevice Stalledendpoint ToomanyqueuedISOtransfers ToomanyrequestedISOframes InvalidINTinterval MorethanonepacketforINT
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
53
Cancelingurbsasynchronously
Tocancelasubmittedurbwithoutwaiting intusb_unlink_urb(structurb*urb); Success:returnsEINPROGRESS Failure:anyotherreturnvalue.Itcanhappen: Whentheurbwasneversubmitted Whenthehasalreadybeenunlinked Whenthehardwareisdonewiththeurb, evenifthecompletionhandlerhasn'tbeencalledyet. Thecorrespondingcompletionhandlerswillstillberun andwillseeurb>status==ECONNRESET.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
54
Cancelingurbssynchronously
Tocancelanurbandwaitforallcompletionhandlerstocomplete Thisguaranteesthattheurbistotallyidleandcanbereused. voidusb_kill_urb(structurb*urb); Typicallyusedinadisconnect()callbackorclose()function. Caution:thisroutinemustn'tbecalledinsituations whichcannotsleep:ininterruptcontext, inacompletionhandler,orwhenholdingaspinlock. Seecommentsindrivers/usb/core/urb.c inkernelsourcesforusefuldetails.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
55
InitializingandsubmittingurbsSummary
urbstructurefieldscanbeinitializedwithhelperfunctions usb_fill_int_urb(),usb_fill_bulk_urb(), usb_fill_control_urb() Isochronousurbshavetobeinitializedbyhand. Thetransfer_flagsfieldmustbeinitialized manuallybyeachdriver. Usetheusb_submit_urb()functiontoqueueurbs. Submittedurbscanbecanceledusingusb_unlink_urb() (asynchronous)orusb_kill_urb()(synchronous).
56
LinuxUSBdrivers
LinuxUSBcommunication
Completionhandlers
57
Whenisthecompletionhandlercalled?
Thecompletionhandleriscalledininterruptcontext,inonly3situations. Checktheerrorvalueinurb>status. Afterthedatatransfersuccessfullycompleted. urb>status==0 Error(s)happenedduringthetransfer. TheurbwasunlinkedbytheUSBcore. urb>statusshouldonlybecheckedfromthecompletionhandler!
58
Transferstatus(1)
DescribedinDocumentation/usb/errorcodes.txt Theurbisnolongerlinkedinthesystem ECONNRESET Theurbwasunlinkedbyusb_unlink_urb(). ENOENT Theurbwasstoppedbyusb_kill_urb(). ESHUTDOWN Errorinfromthehostcontrollerdriver.Thedevicewasdisconnectedfromthe system,thecontrollerwasdisabled,ortheconfigurationwaschangedwhilethe urbwassent. ENODEV Deviceremoved.Oftenprecededbyaburstofothererrors,sincethehub driverdoesn'tdetectdeviceremovaleventsimmediately.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
59
Transferstatus(2)
Typicalhardwareproblemswiththecableorthedevice (includingitsfirmware) EPROTO Bitstufferror,noresponsepacketreceivedintimebythehardware, orunknownUSBerror. EILSEQ CRCerror,noresponsepacketreceivedintime,orunknownUSBerror. EOVERFLOW Theamountofdatareturnedbytheendpointwasgreaterthaneitherthe maxpacketsizeoftheendpointortheremainingbuffersize."Babble".
60
Transferstatus(3)
Othererrorstatusvalues EINPROGRESS Urbnotcompletedyet.Yourdrivershouldnevergetthisvalue. ETIMEDOUT UsuallyreportedbysynchronousUSBmessagefunctions whenthespecifiedtimeoutwasexceed. EPIPE Endpointstalled.Fornoncontrolendpoints, resetthisstatuswithusb_clear_halt(). ECOMM DuringanINtransfer,thehostcontrollerreceiveddatafromanendpointfaster thanitcouldbewrittentosystemmemory.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
61
Transferstatus(4)
ENOSR DuringanOUTtransfer,thehostcontrollercouldnotretrievedatafrom systemmemoryfastenoughtokeepupwiththeUSBdatarate. EREMOTEIO Thedatareadfromtheendpointdidnotfillthespecifiedbuffer,and URB_SHORT_NOT_OKwassetinurb>transfer_flags. EXDEV Isochronoustransferonlypartiallycompleted. Lookatindividualframestatusfordetails. EINVAL Typicallyhappenswithanincorrecturbstructurefield orusb_submit_urb()functionparameter.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
62
Completionhandlerimplementation
Prototype: void(*usb_complete_t)( structurb*, //Thecompletedurb structpt_regs* //Registervaluesatthetime //ofthecorrespondinginterrupt(ifany) ); Rememberyouareininterruptcontext: Donotexecutecallwhichmaysleep(useGFP_ATOMIC,etc.). Completeasquicklyaspossible. Scheduleremainingworkinataskletifneeded.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
63
CompletionhandlerSummary
Thecompletionhandleriscalledininterruptcontext. Don'trunanycodewhichcouldsleep! Checktheurb>statusvalueinthishandler, andnotbefore. Success:urb>status==0 Otherwise,errorstatusdescribedin Documentation/usb/errorcodes.txt.
64
LinuxUSBdrivers
WritingUSBdrivers
Supporteddevices
65
Whatdevicesdoesthedriversupport?
Orwhatdriversupportsagivendevice? Informationneededbyuserspace,tofindtherightdriverto loadorremoveafteraUSBhotplugevent. Informationneededbythedriver,tocalltherightprobe() anddisconnect()driverfunctions(seelater). Suchinformationisdeclaredinausb_device_idstructure bythedriverinit()function.
66
Theusb_device_idstructure(1)
DefinedaccordingtoUSBspecificationsanddescribedin include/linux/mod_devicetable.h. __u16match_flags Bitmaskdefiningwhichfieldsinthestructurearetobematched against.Usuallysetwithhelperfunctionsdescribedlater. __u16idVendor,idProduct USBvendorandproductid,assignedbytheUSBIF. __u16bcdDevice_lo,bcdDevice_hi Productversionrangesupportedbythedriver, expressedinbinarycodeddecimal(BCD)form.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
67
Theusb_device_idstructure(2)
__u8bDeviceClass,bDeviceSubClass,bDeviceProtocol Class,subclassandprotocolofthedevice. NumbersassignedbytheUSBIF. Productsmaychoosetoimplementclasses,orbevendorspecific.Device classesspecifythebehaviorofalltheinterfacesonadevice. __u8bInterfaceClass,bInterfaceSubclass, bInterfaceProtocol Class,subclassandprotocoloftheindividualinterface. NumbersassignedbytheUSBIF. Interfaceclassesonlyspecifythebehaviorofagiveninterface. Otherinterfacesmaysupportotherclasses. kernel_ulong_tdriver_info
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
68
Theusb_device_idstructure(3)
kernel_ulong_tdriver_info Holdsinformationusedbythedriver.Usuallyitholdsapointertoa descriptorunderstoodbythedriver,orperhapsdeviceflags. Thisfieldisusefultodifferentiatedifferentdevices fromeachotherintheprobe()function.
69
Declaringsupporteddevices(1)
USB_DEVICE(vendor,product) Createsausb_device_idstructurewhichcanbeusedto matchonlythespecifiedvendorandproductids. Usedbymostdriversfornonstandarddevices. USB_DEVICE_VER(vendor,product,lo,hi) Similar,butonlyforagivenversionrange. Onlyused11timesthroughoutLinux2.6.18!
70
Declaringsupporteddevices(2)
USB_DEVICE_INFO(class,subclass,protocol) MatchesaspecificclassofUSBdevices. USB_INTERFACE_INFO(class,subclass,protocol) MatchesaspecificclassofUSBinterfaces. Theabove2macrosareonlyusedintheimplementationsofstandard deviceandinterfaceclasses.
71
Declaringsupporteddevices(3)
Createdusb_device_idstructuresaredeclared withtheMODULE_DEVICE_TABLE()macroasinthebelowexample:
/*Examplefromdrivers/usb/net/catc.c*/ staticstructusb_device_idcatc_id_table[]={ {USB_DEVICE(0x0423,0xa)},/*CATCNetmate,BelkinF5U011*/ {USB_DEVICE(0x0423,0xc)},/*CATCNetmateII,BelkinF5U111*/ {USB_DEVICE(0x08d1,0x1)},/*smartBridgessmartNIC*/ {} /*Terminatingentry*/ }; MODULE_DEVICE_TABLE(usb,catc_id_table);
NotethatMODULE_DEVICE_TABLE()isalsoused withothersubsystems:pci,pcmcia,serio,isapnp,input...
72
SupporteddevicesSummary
Driversneedtoannouncethedevicestheysupport inusb_device_idstructures. Neededforuserspacetoknowwhichmoduleto(un)load, andforthekernelwhichdrivercodetoexecute,whena deviceisinsertedorremoved. MostdriversuseUSB_DEVICE()tocreatethestructures. Thesestructuresarethenregistered withMODULE_DEVICE_TABLE(usb,xxx).
73
LinuxUSBdrivers
WritingUSBdrivers
RegisteringaUSBdriver
74
Theusb_driverstructure
USBdriversmustdefineausb_driverstructure: constchar*name Uniquedrivername.Usuallybesettothemodulename. conststructusb_device_id*id_table; ThetablealreadydeclaredwithMODULE_DEVICE_TABLE().
int(*probe)(structusb_interface*intf, conststructusb_device_id*id); Probecallback(detailedlater). void(*disconnect)(structusb_interface*intf); Disconnectcallback(detailedlater).
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
75
Optionalusb_driverstructurefields
int(*suspend)(structusb_interface*intf, pm_message_tmessage); int(*resume)(structusb_interface*intf); Powermanagement:callbackscalledbeforeandaftertheUSBcore suspendsandresumesthedevice. void(*pre_reset)(structusb_interface*intf); void(*post_reset)(structusb_interface*intf); Calledbyusb_reset_composite_device() beforeandafteritperformsaUSBportreset.
76
Driverregistration
Useusb_register()toregisteryourdriver.Example:
/*Examplefromdrivers/usb/input/mtouchusb.c*/ staticstructusb_drivermtouchusb_driver={ .name="mtouchusb", .probe=mtouchusb_probe, .disconnect=mtouchusb_disconnect, .id_table=mtouchusb_devices, }; staticint__initmtouchusb_init(void) { dbg("%scalled",__FUNCTION__); returnusb_register(&mtouchusb_driver); }
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
77
Driverunregistration
Useusb_deregister()toregisteryourdriver.Example:
/*Examplefromdrivers/usb/input/mtouchusb.c*/ staticvoid__exitmtouchusb_cleanup(void) { dbg("%scalled",__FUNCTION__); usb_deregister(&mtouchusb_driver); }
78
probe()anddisconnect()functions
Theprobe()functioniscalledbytheUSBcoretoseeifthe driveriswillingtomanageaparticularinterfaceonadevice. Thedrivershouldthenmakechecksontheinformationpassedto itaboutthedevice. Ifitdecidestomanagetheinterface,theprobe()functionwill return0.Otherwise,itwillreturnanegativevalue. Thedisconnect()functioniscalledbytheUSBcorewhena drivershouldnolongercontrolthedevice(evenifthedriveris stillloaded),andshoulddosomecleanup.
79
Context:USBhubkernelthread
Theprobe()anddisconnect()callbacksarecalledin thecontextoftheUSBhubkernelthread. So,itislegaltocallfunctionswhichmaysleepinthese functions. However,alladditionandremovalofdevicesismanagedby thissinglethread. Mostoftheprobefunctionworkshouldindeedbedonewhen thedeviceisactuallyopenedbyauser.Thisway,thisdoesn't impacttheperformanceofthekernelthreadinmanaging otherdevices.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
80
probe()functionwork
Inthisfunctionthedrivershouldinitializelocalstructureswhichit mayneedtomanagethedevice. Inparticular,itcantakeadvantageofinformationitisgivenabout thedevice. Forexample,driversusuallyneedtodetectendpointaddressesand buffersizes. Timetoshowandexplainexamplesindetail!
81
usb_set_intfdata()/usb_get_intfdata()
staticinlinevoidusb_set_intfdata( structusb_interface*intf, void*data); Functionusedinprobe()functionstoattachcollecteddevicedatatoan interface.Anypointerwilldo! Usefultostoreinformationforeachdevicesupportedbyadriver,without havingtokeepastaticdataarray. Theusb_get_intfdata()functionistypicallyusedinthedeviceopen functionstoretrievethedata. Storeddataneedtobefreedindisconnect()functions: usb_set_intfdata(interface,NULL); Plentyofexamplesareavailableinthekernelsources.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
82
LinuxUSBdrivers
WritingUSBdrivers
USBtransferswithoutURBs
83
TransferswithoutURBs
Thekernelprovidestwousb_bulk_msg() andusb_control_msg()helperfunctionsthatmakeitpossibleto transfersimplebulkandcontrolmessages,withouthavingto: Createorreuseanurbstructure, Initializeit, Submitit, Andwaitforitscompletionhandler.
84
TransferswithoutURBsconstraints
Thesefunctionsaresynchronousandwillmakeyourcode sleep.Youmustnotcallthemfrominterruptcontextorwith aspinlockheld. Youcannotcancelyourrequests,asyouhavenohandleon theURBusedinternally.Makesureyourdisconnect() functioncanwaitforthesefunctionstocomplete. Seethekernelsourcesforexamplesusingthesefunctions!
85
USBdevicedriversSummary
Moduleloading Declaresupporteddevices(interfaces). Bindthemtoprobe()and disconnect()functions. Supporteddevicesarefound probe()functionsformatching interfacedriversarecalled. Theyrecordinterfaceinformationand registerresourcesorservices. Devicesareopened Thiscallsdataaccessfunctionsregistered bythedriver. URBsareinitialized. Oncethetransfersareover,completion functionsarecalled. Dataarecopiedfrom/touserspace. Devicesareremoved Thedisconnect()functions arecalled. Thedriversmaybeunloaded.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
86
Adviceforembeddedsystemdevelopers
IfyouneedtodevelopaUSBdevicedriverforanembedded Linuxsystem. DevelopyourdriveronyourGNU/Linuxdevelopmenthost! ThedriverwillrunwithnochangeonthetargetLinux system(providedyouwroteportablecode!):allUSBdevice driversareplatformindependent. Yourdriverwillbemucheasiertodeveloponthehost, becauseofitsflexibilityandtheavailabilityofdebugging anddevelopmenttools.
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
87
References
Wikipedia'sarticleonUSB http://en.wikipedia.org/wiki/Universal_Serial_Bus TheUSBdriverschapterintheLinuxDeviceDriversbook: http://lwn.net/Kernel/LDD3/(FreeLicense!) TheLinuxkernelsources(hundredsofexamples,UsetheSource!) Browsethemwithhttp://lxr.freeelectrons.com. LinuxUSBproject http://www.linuxusb.org/ Linuxkerneldocumentation: Documentation/usb/ LinuxUSBAPI(generatedfromkernelsources): http://freeelectrons.com/kerneldoc/latest/DocBook/usb/ USBspecifications: http://www.usb.org/developers/docs/
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
88
LinuxUSBdrivers
Annex
EthernetoverUSB
89
EthernetoverUSB(1)
Ifyourdevicedoesn'thaveEthernetconnectivity, buthasaUSBdevicecontroller YoucanuseEthernetoverUSBthroughtheg_etherUSB device(gadget)driver(CONFIG_USB_GADGET) Ofcourse,youneedaworkingUSBdevicedriver.Generally availableasmoreandmoreembeddedprocessors(well supportedbyLinux)haveabuiltinUSBdevicecontroller PluginbothendsoftheUSBcable
90
EthernetoverUSB(2)
Onthehost,youneedtohavetheusbnetmodule (CONFIG_USB_USBNET) PluginbothendsoftheUSBcable.Configurebothendsas regularnetworkingdevices.Example:
Onthetargetdevice modprobeg_ether ifconfigusb0192.168.0.202 routeadd192.168.0.200devusb0 Onthehost modprobeusbnet ifconfigusb0192.168.0.200 routeadd192.168.0.202devusb0
WorksgreatoniPAQPDAs!
LinuxUSBdrivers Copyright20062007,FreeElectrons CreativeCommonsAttributionShareAlike2.5license http://freeelectrons.com Dec9,2007
91
Howtohelp
Ifyousupportthiswork,youcanhelp... Bysendingideas,corrections,suggestions,contributions andtranslationsforthisdocument. Byspeakingaboutittoyourfriends,colleagues andlocalFreeSoftwarecommunity. Byaddinglinkstoouronlinematerialsonyourwebsite, toincreasetheirvisibilityinsearchengineresults. Andofcourse,butwritingyourowndrivers!
92
Thanks
TotheOpenOffice.orgproject,fortheir presentationandwordprocessortoolswhich satisfiedallmyneeds Tohttp://openclipart.orgprojectcontributorsfor theirnicepublicdomainclipart. TothemembersofthewholeFreeSoftwareand OpenSourcecommunity,forsharingthebestof themselves:theirwork,theirknowledge,their friendship.
Topeoplewhohelped, sentcorrectionsor suggestions:
ManishKatiyar
93
Relateddocuments
AllthetechnicalpresentationsandtrainingmaterialscreatedandusedbyFreeElectrons, availableunderafreedocumentationlicense(morethan1500pages!). http://freeelectrons.com/training
IntroductiontoUnixandGNU/Linux EmbeddedLinuxkernelanddriverdevelopment FreeSoftwaretoolsforembeddedLinuxsystems AudioinembeddedLinuxsystems MultimediainembeddedLinuxsystems LinuxUSBdrivers RealtimeinembeddedLinuxsystems IntroductiontouClinux LinuxonTIOMAPprocessors FreeSoftwaredevelopmenttools JavainembeddedLinuxsystems IntroductiontoGNU/LinuxandFreeSoftware Linuxandecology What'snewinLinux2.6? HowtoportLinuxonanewPDA
http://freeelectrons.com/articles
AdvantagesofFreeSoftwareinembeddedsystems EmbeddedLinuxoptimizations EmbeddedLinuxfromScratch...in40min!
94
EmbeddedLinuxTraining Allmaterialsreleasedwithafreelicense! UnixandGNU/Linuxbasics Linuxkernelanddriversdevelopment RealtimeLinux,uClinux Developmentandprofilingtools Lightweighttoolsforembeddedsystems Rootfilesystemcreation Audioandmultimedia Systemoptimization Consulting Helpindecisionmaking Systemarchitecture Identificationofsuitabletechnologies Managinglicensingrequirements Systemdesignandperformancereview
FreeElectrons
FreeSoftwareforembeddedsystems
CustomDevelopment Systemintegration EmbeddedLinuxdemosandprototypes Systemoptimization Linuxkerneldrivers Applicationandinterfacedevelopment
http://freeelectrons.com