Vous êtes sur la page 1sur 28
DesignDesign ofof aa USBUSB DeviceDevice DriverDriver Joe Flynn Questra Corporation jflynn@questra.com (716)381-0260 1
DesignDesign ofof aa USBUSB DeviceDevice DriverDriver
Joe Flynn
Questra Corporation
jflynn@questra.com
(716)381-0260
1
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
2
USBUSB OverviewOverview ??HardwareHardware OverviewOverview ––TopologyTopology ??ProtocolProtocol
USBUSB OverviewOverview
??HardwareHardware OverviewOverview
––TopologyTopology
??ProtocolProtocol CharacteristicsCharacteristics
––PacketPacket TypesTypes
––USBUSB TransactionsTransactions
??EnumerationEnumeration
––EnumerationEnumeration StatesStates
??ExamplesExamples ofof USBUSB devicesdevices
3
HardwareHardware OverviewOverview HUB HUB HOST/HUB ??TopologyTopology Kbd Monitor PC –– TieredTiered StarStar
HardwareHardware OverviewOverview
HUB
HUB
HOST/HUB
??TopologyTopology
Kbd
Monitor
PC
–– TieredTiered StarStar
(Distributes(Distributes ConnectivityConnectivity Points)Points)
–– 127127 logicallogical connectionsconnections
(up(up toto 55 metersmeters perper segment)segment)
–– UpUp toto 66 tierstiers
Pen
Mouse
Speaker
Mic
Phone
??BusBus transactionstransactions
–– Speed:Speed: 12Mbps12Mbps aggregateaggregate
PhysicalPhysical HardwareHardware ViewView
••1.5Mbps1.5Mbps sub-channelsub-channel
–– IsochronousIsochronous andand AsynchronousAsynchronous
–– MediaMedia accessaccess controlledcontrolled byby hosthost
PC PC
Monitor
??ConfigurationConfiguration
Kbd
–– DynamicDynamic insertion-removalinsertion-removal
–– AutoconfigurationAutoconfiguration onon changechange
Pen
Phone
??PhysicalPhysical LayerLayer
Mouse
Speaker
Mic Mic
LogicalLogical HardwareHardware ViewView
–– 2-wire2-wire differentialdifferential signaling,signaling, NRZINRZI
codedcoded withwith bitbit stuffingstuffing
–– 44 pinpin connector,connector, 44 wirewire cablecable
–– SupplySupply SourcingSourcing +5V+5V
4
TheThe TransactionTransaction ProtocolProtocol isis HostHost BasedBased ??HostHost basedbased tokentoken pollingpolling
TheThe TransactionTransaction ProtocolProtocol isis HostHost BasedBased
??HostHost basedbased tokentoken pollingpolling
––DataData fromfrom host-to-functionhost-to-function andand function-to-hostfunction-to-host
––HostHost handleshandles mostmost ofof thethe protocolprotocol complexitycomplexity
––PeripheralPeripheral designdesign isis simplesimple andand low-costlow-cost
??RobustnessRobustness
––HandshakeHandshake toto acknowledgeacknowledge datadata transfertransfer andand flowflow controlcontrol
––VeryVery lowlow rawraw physicalphysical bitbit errorerror raterate (( <10<10 -10-10 ))
––CRCCRC protectionprotection plusplus hardwarehardware retryretry optionoption
––DataData ToggleToggle SequenceSequence bitsbits
??BoundedBounded transfertransfer characteristicscharacteristics
––DataData transfertransfer bandwidthbandwidth andand latencylatency prenegotiatedprenegotiated
––FlowFlow controlcontrol forfor peripheralperipheral bufferbuffer managementmanagement
TokenToken
DataData TransferTransfer
HandshakeHandshake
5
PacketPacket TypesTypes ??TokenToken -- OUT,OUT, IN,IN, SOF,SOF, SETUPSETUP ––FirstFirst packetpacket inin anyany
PacketPacket TypesTypes
??TokenToken -- OUT,OUT, IN,IN, SOF,SOF, SETUPSETUP
––FirstFirst packetpacket inin anyany transactiontransaction
––SpecifiesSpecifies functionfunction address,address, endpointendpoint
––SpecifiesSpecifies datadata directiondirection
??DataData -- DATA0,DATA0, DATA1DATA1
––00 -- 10231023 bytesbytes
??HandshakeHandshake -- ACK,ACK, NAK,NAK, STALLSTALL
––ReportReport statusstatus ofof datadata transactiontransaction
––FlowFlow controlcontrol
––StallStall conditionsconditions
??SpecialSpecial -- PREPRE
––EnablesEnables HubHub forfor lowlow speedspeed communicationscommunications
6
AA TypicalTypical USBUSB TransactionTransaction ConsistsConsists ofof ThreeThree PacketsPackets IdleIdle TokenToken IN
AA TypicalTypical USBUSB TransactionTransaction ConsistsConsists
ofof ThreeThree PacketsPackets
IdleIdle
TokenToken
IN
SET
OUT
DATA0/
DATA0/
T/O
NAK
STALL
DATA0/ DATA0/
DATA0
DataData
DATA DATA 1 1
DATA1 DATA1
IdleIdle
T/O
ACK
HandshakeHandshake
ACKACK
ACK
NAK
STALL
T/O
IdleIdle
HostHost
FunctionFunction
7
ThereThere areare FourFour TypesTypes ofof USBUSB TransactionsTransactions ??IsochronousIsochronous (Audio,(Audio,
ThereThere areare FourFour TypesTypes ofof USBUSB
TransactionsTransactions
??IsochronousIsochronous (Audio,(Audio, telephonytelephony …)…)
––Periodic,Periodic, BoundedBounded latencies,latencies, guaranteedguaranteed bandwidthbandwidth
??InterruptInterrupt (Mouse,(Mouse, joystickjoystick …)…)
––Asynchronous,Asynchronous, burstybursty,, non-periodic,non-periodic, lowlow bandwidthbandwidth
??BulkBulk (Printer,(Printer, scanner,scanner, digitaldigital cameracamera …)…)
––Non-periodic,Non-periodic, burstybursty,, highhigh bandwidthbandwidth utilizationutilization
??ControlControl (Configuration(Configuration messagesmessages …)…)
––BurstyBursty,, host-initiatedhost-initiated (bus(bus management,management,
configuration)configuration)
8
TheThe BasicBasic USBUSB ModelModel hashas SeveralSeveral LayersLayers ofof AbstractionAbstraction Host Function
TheThe BasicBasic USBUSB ModelModel hashas SeveralSeveral
LayersLayers ofof AbstractionAbstraction
Host
Function
Device
Client SW
Interface
a collection
manages an
x
of
interface
EndpointEndpoint 00
-- Required,Required, sharedshared
-- ConfigurationConfiguration accessaccess
-- CapabilityCapability controlcontrol
Interfaces
PipePipe BundleBundle
InterfaceInterface
BuffersBuffers
NoNo USBUSB
NoNo USBUSB
toto anan
SpecificSpecific
FormatFormat
FormatFormat
interfaceinterface
USB Device
USB System
Endpoint
a collection
manages devices
Zero
of
DefaultDefault
endpoints
PipePipe toto
USBUSB
DataData
EndpointEndpoint ZeroZero
DataData PerPer
UnspecifiedUnspecified
FramedFramed
EndpointEndpoint
DataData
USB Bus Interface
Host
USB Bus
USB Framed
Cntrl
Interface
Data
SIE
SIE
Transactions
USB Wire
Pipe,Pipe, connectionconnection abstractionabstraction
betweenbetween twotwo horizontalhorizontal layerslayers
DataData transporttransport mechanismmechanism
USB-relevantUSB-relevant formatformat ofof transportedtransported datadata
9
Enumeration:Enumeration: DeviceDevice perspectiveperspective ??AttachedAttached StateState ––EnteredEntered byby
Enumeration:Enumeration: DeviceDevice perspectiveperspective
??AttachedAttached StateState
––EnteredEntered byby attachingattaching USBUSB CableCable
??PoweredPowered StateState
––USBUSB HostHost AppliesApplies powerpower
??DefaultDefault statestate
––USBUSB HostHost resetsresets busbus
??AddressedAddressed StateState
––USBUSB HostHost sendssends SetSet AddressAddress withwith non-zeronon-zero addressaddress
??ConfiguredConfigured statestate
––USBUSB HostHost sendssends SetSet ConfigurationConfiguration withwith non-zeronon-zero
valuevalue
??SuspendedSuspended statestate
––USBUSB HostHost stopsstops sendingsending SOFSOF forfor 33 msecmsec
10
TheThe DeviceDevice StateState MachineMachine HubHub ConfiguredConfigured BusBus ActivityActivity ResetReset Attached
TheThe DeviceDevice StateState MachineMachine
HubHub
ConfiguredConfigured
BusBus ActivityActivity
ResetReset
Attached
Powered
Suspended
Bus Activity
HubHub ResetReset
IdleIdle BusBus
oror DeconfiguredDeconfigured
Default
Suspended
ResetReset
PowerPower
Address
Idle Bus
InterruptionInterruption
Assigned
Bus Activity
Address
Suspended
Idle
Bus
Device
Device
Configured
Deconfigured
Bus
Configured
Activity
Suspended
Idle Bus
11
EnumerationEnumeration isis thethe ProcessProcess ofof AssigningAssigning AddressesAddresses andand SettingSetting
EnumerationEnumeration isis thethe ProcessProcess ofof AssigningAssigning
AddressesAddresses andand SettingSetting ConfigurationsConfigurations
HostHost
HubHub
DeviceDevice
ConnectConnect CableCable
StatusStatus ChangeChange
AttachedAttached
QueryQuery ChangeChange
PortPort EnableEnable
PoweredPowered
ResetReset DeviceDevice
DefaultDefault
Get Device Descriptor via Default Pipe and Address
Get Device Descriptor via Default Pipe and Address
Assign a Unique Address
Assign a Unique Address
AddrAddr
AssignedAssigned
Read All Configuration Information
Read All Configuration Information
Configure and Assign Configuration Value
Configure and Assign Configuration Value
ConfiguredConfigured
12
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
13
TypesTypes ofof USBUSB ControllersControllers ??DiscreteDiscrete ComponentsComponents ––NetChipNetChip,,
TypesTypes ofof USBUSB ControllersControllers
??DiscreteDiscrete ComponentsComponents
––NetChipNetChip,, Intel,Intel, NationalNational Semiconductor,Semiconductor, PhillipsPhillips
??USBUSB IPIP CoresCores asas partpart ofof anan ASICASIC
––Sand,Sand, Motorola,Motorola, TexasTexas Instruments,Instruments, .etc.etc
??CombinationCombination USBUSB HostHost andand USBUSB PeripheralPeripheral chipchip
––ScanLogicScanLogic
??CombinationCombination micro-processormicro-processor andand USBUSB CoreCore
––8/168/16 bitbit processorprocessor Mitsubishi,Mitsubishi, .etc.etc
??SingleSingle ChipChip SolutionsSolutions
––NetchipNetchip NET1031NET1031 SingleSingle chipchip scannerscanner controller.controller.
14
USBUSB ControllerController HardwareHardware ArchitectureArchitecture ??USBUSB CoreCore ??RegistersRegisters forfor
USBUSB ControllerController HardwareHardware ArchitectureArchitecture
??USBUSB CoreCore
??RegistersRegisters forfor ControlControl andand EndpointEndpoint DataData
TransferTransfer
??FIFOFIFO ControllerController
––InputInput andand OutputOutput FIFOsFIFOs forfor ControlControl EndpointEndpoint
––InputInput oror OutputOutput FIFOFIFO forfor otherother EndpointsEndpoints
??DMADMA ControllerController
??InternalInternal BusBus
??SerialSerial InterfaceInterface EngineEngine
??OutputOutput PadsPads
15
ExampleExample ofof USBUSB ControllerController Processor Bus EP0 FIFO DMA and EP0 FIFO EP1 FIFO EP2
ExampleExample ofof USBUSB ControllerController
Processor Bus
EP0 FIFO
DMA and
EP0 FIFO
EP1 FIFO
EP2 FIFO
EP3 FIFO
FIFO Control
Register
Bank
EPx Status
USB Internal Bus
Reg
EPx Ctl Reg
USB Control
EP 1
EP2
EP3
EP 0
Reg
Bulk/ISO
Bulk/Iso
Interrupt
Control
IN
Out
IN
Serial Interface Engine
USB Core Logic
Output Pad Enable
USB Pads
16
KeyKey FeaturesFeatures ofof aa USBUSB ControllerController ??ImplementsImplements mostmost USBUSB RequestsRequests inin
KeyKey FeaturesFeatures ofof aa USBUSB ControllerController
??ImplementsImplements mostmost USBUSB RequestsRequests inin hardwarehardware
––StandardStandard RequestsRequests
••GET_DESCRIPTORGET_DESCRIPTOR andand SET_DESCRIPTORSET_DESCRIPTOR maymay bebe
implementedimplemented inin softwaresoftware forfor versatilityversatility
––Class/VendorClass/Vendor RequestsRequests asas appropriateappropriate
??USBUSB EventEvent InterruptsInterrupts andand statusstatus
––Setup,Setup, Suspend,Suspend, Resume,Resume, SOF,SOF, Reset,Reset, ZeroZero ByteByte
PacketPacket
––DMADMA CompleteComplete
––Transmit/ReceiveTransmit/Receive AckAck//NackNack/Error/Error statusstatus
––FIFOFIFO empty/fullempty/full oror atat high/lowhigh/low thresholdthreshold levellevel
??FIFOsFIFOs supportingsupporting
––multiplemultiple packetpacket depthdepth
––HardwareHardware RetryRetry ofof PacketPacket TransfersTransfers onon errorerror
17
KeyKey FeaturesFeatures ofof aa USBUSB ControllerController IIII ??HardwareHardware shouldshould provideprovide
KeyKey FeaturesFeatures ofof aa USBUSB ControllerController IIII
??HardwareHardware shouldshould provideprovide abilityability toto
––initiateinitiate aa RemoteRemote WakeupWakeup
––detectdetect aa USBUSB ResetReset
––resetreset USBUSB ControllerController
––SelectSelect endpointendpoint asas DMADMA destinationdestination
––DetectDetect enumerationenumeration
––ReadRead CurrentCurrent ConfigurationConfiguration andand InterfaceInterface
––StallStall endpointsendpoints
18
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
19
ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice USBUSB ProtocolProtocol ApplicationApplication
ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB
DeviceDevice
USBUSB ProtocolProtocol
ApplicationApplication
APIAPI
APIAPI
DriverDriver
LogicalLogical pipepipe
LogicalLogical pipepipe
FifoFifo
FifoFifo
DataData packetspackets fromfrom hosthost
HardwareHardware
20
SystemSystem ArchitectureArchitecture ISR Thread USB Protocol Thread Main Thread USB Controller Hardware File
SystemSystem ArchitectureArchitecture
ISR
Thread
USB Protocol
Thread
Main Thread
USB Controller
Hardware
File System
Thread
21
USBUSB PeripheralPeripheral ThreadsThreads ??ISRISR ThreadThread ––LowLow LevelLevel InterruptInterrupt
USBUSB PeripheralPeripheral ThreadsThreads
??ISRISR ThreadThread
––LowLow LevelLevel InterruptInterrupt ServiceService routine(s)routine(s)
••USBUSB ControllerController InterruptInterrupt
••DMADMA ControllerController InterruptInterrupt
??USBUSB ProtocolProtocol ThreadThread
––TaskTask whichwhich implementsimplements USBUSB ProtocolProtocol
••Control,Control, Bulk,Bulk, IsochrnousIsochrnous,, InterruptInterrupt EndpointsEndpoints
••Attach/Attach/DettachDettach,, SOF,SOF, Suspend/ResumeSuspend/Resume
??MainMain ThreadThread
––ThreadThread whichwhich executesexecutes thethe productproduct applicationapplication
––CallsCalls andand isis triggeredtriggered byby CallbackCallback fromfrom USBUSB DriverDriver
layerlayer
??FileFile SystemSystem ThreadThread
––LowerLower PriorityPriority FileFile SystemSystem ThreadThread
22
InterruptInterrupt SourcesSources ??SOFSOF ??Attach/Attach/DettachDettach ??Suspend/ResumeSuspend/Resume ??SetupSetup
InterruptInterrupt SourcesSources
??SOFSOF
??Attach/Attach/DettachDettach
??Suspend/ResumeSuspend/Resume
??SetupSetup PacketPacket
??DataData ININ AckAck
??DataData OUTOUT AckAck
??FIFOFIFO EmptyEmpty oror LowLow levellevel thresholdthreshold metmet
??FIFOFIFO FullFull oror HighHigh levellevel thresholdthreshold metmet
??DMADMA CompleteComplete
23
Driver/HardwareDriver/Hardware EnumerationEnumeration ArchitectureArchitecture EmbeddedEmbedded ApplicationApplication
Driver/HardwareDriver/Hardware EnumerationEnumeration
ArchitectureArchitecture
EmbeddedEmbedded ApplicationApplication
ININ
OUTOUT
ININ
LogicalLogical pipespipes
EnumerationEnumeration RoutinesRoutines
ISR,ISR, DescriptorDescriptor structuresstructures
USBUSB DriverDriver
EP0EP0 FifoFifo’’ss
EP1EP1 FifoFifo
EP2EP2 FifoFifo
EP3EP3 FifoFifo
To Host
HardwareHardware
24
SingleSingle ThreadThread ArchitectureArchitecture EmbeddedEmbedded ApplicationApplication MainMain Thread,Thread,
SingleSingle ThreadThread ArchitectureArchitecture
EmbeddedEmbedded ApplicationApplication
MainMain Thread,Thread, Class/VendorClass/Vendor RequestsRequests
ControlControl
messagesmessages
ININ
OUTOUT
ININ
LogicalLogical pipespipes
EnumerationEnumeration
USBUSB DriverDriver
EP0EP0 FifoFifo’’ss
EP1EP1 FifoFifo
EP2EP2 FifoFifo
EP3EP3 FifoFifo
To Host
HardwareHardware
25
MultipleMultiple ThreadThread ArchitectureArchitecture USBUSB ProtocolProtocol ApplicationApplication ThreadThread
MultipleMultiple ThreadThread ArchitectureArchitecture
USBUSB ProtocolProtocol
ApplicationApplication
ThreadThread
(Main(Main Thread)Thread)
ControlControl
messagesmessages
ControlControl
ININ
OUTOUT
ININ
LogicalLogical pipespipes
USBUSB DriverDriver
EP0EP0 FifoFifo’’ss
EP1EP1 FifoFifo
EP2EP2 FifoFifo
EP3EP3 FifoFifo
To Host
HardwareHardware
26
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
27
USBUSB DeviceDevice DriverDriver ComponentsComponents USB Device Driver API Endpoint Data Control Protocol Attach/
USBUSB DeviceDevice DriverDriver ComponentsComponents
USB Device Driver API
Endpoint Data
Control Protocol
Attach/
Status
Transfer Protocols
Power
- Standard Requests
Detach
&
-
Bulk In/Out
Management
- Class Requests
Processing
Control
-
Isochronous In/Out
- Vendor Requests
-
Interrupt In/Out
Clock
Clock
DMA
USB Driver Low Level Access Methods and ISRs
Driver
Driver
Driver
Clock
Pull-Up
USB Controller
Endpoint FIFO
DMA
Registers
Resistor
Registers
Registers
Controller
28
USBUSB DeviceDevice DriverDriver ArchitectureArchitecture Callback Driver Interface Function UsbDrv UsbDevCreate
USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
Callback
Driver Interface
Function
UsbDrv
UsbDevCreate
USB_open
USB_close
USB_read
USB_write
USB_ioctl
Context of
Callback
Message Queue
COMMOM
USB
Functions
Utilities
USB
UsbOpen
UsbClose
UsbRead
UsbWrite
UsbIoctl
HW/SW
Initialize
Functions
UsbIsr
Framer Layer Hardware Specific Functions
USB Controller Hardware
29
USBUSB DeviceDevice DriverDriver APIAPI ??USBInitUSBInit()() ??USBDeleteUSBDelete()() ??USBOpenUSBOpen()()
USBUSB DeviceDevice DriverDriver APIAPI
??USBInitUSBInit()()
??USBDeleteUSBDelete()()
??USBOpenUSBOpen()()
??USBCloseUSBClose()()
??USBReadUSBRead()()
??USBWriteUSBWrite()()
??USBIoctlUSBIoctl()()
??CallbackCallback MessageMessage QueueQueue
30
USBInitUSBInit()() andand USBDeleteUSBDelete()() ??USBInitUSBInit()() -- InitializeInitialize USBUSB DriverDriver
USBInitUSBInit()() andand USBDeleteUSBDelete()()
??USBInitUSBInit()() -- InitializeInitialize USBUSB DriverDriver
––InstallsInstalls driverdriver inin IOIO systemsystem
––CreatesCreates oror acquiresacquires OSOS resourcesresources
••Semaphores,Semaphores, queues,queues, ISRISR vector,vector, task,task, memory,memory, etc.etc.
––InitializesInitializes USBUSB ControllerController hardwarehardware
––EnableEnable USBUSB ControllerController toto allowallow enumerationenumeration
??USBDeleteUSBDelete()() -- DeleteDelete USBUSB DriverDriver
––DisableDisable USBUSB ControllerController HardwareHardware
––ReturnReturn OSOS resourcesresources
••Semaphores,Semaphores, queues,queues, ISRISR vector,vector, task,task, memory,memory, etc.etc.
––RemoveRemove driverdriver fromfrom IOIO systemsystem
31
USBOpenUSBOpen()() andand USBCloseUSBClose()() ??USBOpenUSBOpen()() -- OpensOpens anan endpointendpoint ––IfIf
USBOpenUSBOpen()() andand USBCloseUSBClose()()
??USBOpenUSBOpen()() -- OpensOpens anan endpointendpoint
––IfIf notnot thethe ControlControl endpointendpoint
••VerifiesVerifies devicedevice isis enumeratedenumerated
••VerifiesVerifies endpointendpoint isis partpart ofof currentcurrent configuration/interfaceconfiguration/interface
––SelectsSelects CPUCPU oror DMADMA transfertransfer modemode
••IfIf DMADMA selectsselects endpointendpoint’’ss FIFOFIFO forfor useuse withwith DMADMA
––SetSet EndpointEndpoint statesstates toto OPENEDOPENED
??USBCloseUSBClose()() -- ClosesCloses anan endpointendpoint
––DisablesDisables DMADMA controllercontroller’’ss useuse ofof endpointendpoint’’ss FIFOFIFO
––SetSet endpointendpoint statestate toto CLOSEDCLOSED
32
USBReadUSBRead()() ??ReadRead fromfrom Bulk,Bulk, IsochronousIsochronous oror InterruptInterrupt endpointendpoint
USBReadUSBRead()()
??ReadRead fromfrom Bulk,Bulk, IsochronousIsochronous oror InterruptInterrupt
endpointendpoint
––VerifyVerify endpointendpoint isis openopen
––IfIf transfertransfer modemode isis DMADMA
••SetupSetup andand startstart DMADMA readread ofof fixedfixed sizesize fromfrom EndpointEndpoint FIFOFIFO
••BlockBlock untiluntil DMADMA isis completecomplete oror aa timeouttimeout occursoccurs
––elseelse
••ISRISR CalledCalled
••LoopLoop untiluntil allall datadata isis read,read, aa timeouttimeout occursoccurs oror aa shortshort packetpacket
isis receivedreceived
••ExitExit ISRISR
33
USBUSB ReadRead ProcessProcess USBUSB DriverDriver EndpointEndpoint FIFOFIFO USBUSB HostHost OutOut TokenToken
USBUSB ReadRead ProcessProcess
USBUSB DriverDriver
EndpointEndpoint FIFOFIFO
USBUSB HostHost
OutOut TokenToken
DataData PacketPacket
ACKACK
DataData
BufferBuffer
DataData PacketPacket
OutOut TokenToken
DataData PacketPacket
DataData PacketPacket
ACKACK
34
USBWriteUSBWrite()() ?Write to Bulk, Isochronous or Interrupt endpoint –Verify endpoint is open –If transfer mode
USBWriteUSBWrite()()
?Write to Bulk, Isochronous or Interrupt
endpoint
–Verify endpoint is open
–If transfer mode is DMA
•Setup and start DMA write of fixed size to Endpoint FIFO
•Block until DMA is complete or a timeout occurs
–else
•ISR Called
•Loop until all data is written, or a timeout occurs
•Exit ISR
35
USBUSB WriteWrite ProcessProcess USBUSB DriverDriver EndpointEndpoint FIFOFIFO USBUSB HostHost DataData PacketPacket
USBUSB WriteWrite ProcessProcess
USBUSB DriverDriver
EndpointEndpoint FIFOFIFO
USBUSB HostHost
DataData PacketPacket
ININ TokenToken
DataData PacketPacket
ACKACK
DataData
BufferBuffer
DataData PacketPacket
ININ TokenToken
DataData PacketPacket
ACKACK
36
ControlControl ReadRead ??CallCall USBReadUSBRead(( EP0EP0 )) toto readread aa SetupSetup PacketPacket ––ReadRead
ControlControl ReadRead
??CallCall USBReadUSBRead(( EP0EP0 )) toto readread aa SetupSetup PacketPacket
––ReadRead fromfrom EP0EP0 OUTOUT FIFOFIFO
??IdentifyIdentify SetupSetup PacketPacket
––Standard,Standard, ClassClass oror VendorVendor
??CreateCreate responseresponse toto SetupSetup PacketPacket
––ForFor exampleexample prepareprepare toto returnreturn aa DescriptorDescriptor
??CallCall USBWriteUSBWrite(( EP0EP0 )) toto writewrite thethe responseresponse
––PerformPerform normalnormal USBWriteUSBWrite()() functionfunction toto EP0EP0 ININ FIFOFIFO
––WaitWait forfor HostHost toto returnreturn aa ZeroZero ByteByte packetpacket
terminatingterminating ControlControl transfertransfer
??RepeatRepeat
37
ControlControl WriteWrite ??CallCall USBReadUSBRead(( EP0)EP0) toto readread aa SetupSetup PacketPacket ––ReadRead
ControlControl WriteWrite
??CallCall USBReadUSBRead(( EP0)EP0) toto readread aa SetupSetup PacketPacket
––ReadRead fromfrom EP0EP0 OUTOUT FIFOFIFO
??IdentifyIdentify SetupSetup PacketPacket
––Standard,Standard, ClassClass oror VendorVendor
??PreparePrepare toto receivereceive datadata fromfrom HostHost
??CallCall USBReadUSBRead(( EP0EP0 )) toto readread datadata fromfrom thethe HostHost
––PerformPerform normalnormal USBReadUSBRead()() functionfunction fromfrom EP0EP0 OUTOUT
FIFOFIFO
––SendSend aa ZeroZero ByteByte packetpacket toto thethe HostHost terminatingterminating thethe
ControlControl transfertransfer
??RepeatRepeat
38
CallbackCallback MessageMessage QueueQueue ??MessageMessage InterfaceInterface usedused toto sendsend
CallbackCallback MessageMessage QueueQueue
??MessageMessage InterfaceInterface usedused toto sendsend notificationnotification toto
applicationapplication ofof asynchronousasynchronous eventsevents
––USBUSB ResetReset
––EnumerationEnumeration
––ConfigurationConfiguration ChangeChange
––InterfaceInterface ChangeChange
––Suspend/ResumeSuspend/Resume
––Attach/Attach/DettachDettach
––SOFSOF
––ReportReport SetupSetup PacketPacket receivedreceived byby ControlControl EndpointEndpoint 00
39
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
40
Windows 98 OS Application TWAIN Still Still Still Digital Camara or Image Color image image
Windows 98 OS
Application
TWAIN
Still
Still
Still
Digital Camara
or
Image Color
image
image
image
Application
other
Management
control
event
control
Image
(ICM 2.0)
panel
monitor
center
API
Still Image DDI
User-mode
minidriver
User Mode
Driver Interface
Kernel Mode
WDM still
Provided by:
image
driver for
Microsoft
USB
IHV
ISV
USB
USB Device
Driver
USB Cable
41
WDMWDM StillStill ImageImage ArchitectureArchitecture AttemptsAttempts toto KeepKeep AllAll CustomCustom SoftwareSoftware
WDMWDM StillStill ImageImage ArchitectureArchitecture AttemptsAttempts toto
KeepKeep AllAll CustomCustom SoftwareSoftware inin UserUser ModeMode
ApplicationApplication
Still StillStill Image ImageImage
Still StillStill Image ImageImage
Still StillStill Image ImageImage
Color ColorColor
TWAINTWAIN
ISISISIS
Control ControlControl
Event EventEvent
Control ControlControl
Manager ManagerManager
APIAPI
APIAPI
Panel PanelPanel
Monitor MonitorMonitor
Center CenterCenter
(ICM (ICM(ICM 2.0) 2.0)2.0)
StillStill ImageImage DeviceDevice DriverDriver InterfaceInterface (DDI)(DDI)
UserUser ModeMode
KernelKernel ModeMode
COMMCOMMCOMM PortsPortsPorts
USBUSBUSB
SCSISCSISCSI
42
DesignDesign ConstraintsConstraints ??HardwareHardware SelectionSelection ––StillStill imageimage
DesignDesign ConstraintsConstraints
??HardwareHardware SelectionSelection
––StillStill imageimage architecturearchitecture requiresrequires Control,Control, BulkBulk In,In,
BulkBulk OutOut andand InterruptInterrupt endpoints.endpoints.
??HostHost applicationapplication controlscontrols cameracamera viavia controlcontrol oror
bulkbulk endpoints.endpoints.
––DesignDesign ofof thethe communicationscommunications protocolprotocol isis contingentcontingent
onon thethe TwainTwain datadata sourcesource andand anyany classesclasses supported.supported.
??HostHost ApplicationApplication definesdefines
––FeaturesFeatures supportedsupported byby cameracamera applicationapplication
––PowerPower ManagementManagement requirementsrequirements
43
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
44
EffectiveEffective TestingTesting StrategiesStrategies ??DevelopDevelop WrittenWritten TestTest PlansPlans ––
EffectiveEffective TestingTesting StrategiesStrategies
??DevelopDevelop WrittenWritten TestTest PlansPlans
–– DefineDefine UnitUnit TestsTests
–– DefineDefine SystemSystem TestsTests
??DefineDefine minimumminimum USBUSB HostHost DriverDriver TestTest
–– CapabilitiesCapabilities
–– Enumeration,Enumeration, DataData Transfer,Transfer, LoopbackLoopback,, etc.etc.
??AcquireAcquire anan USBUSB AnalyzerAnalyzer
–– UseUse analyzeranalyzer forfor documentingdocumenting testtest resultsresults
–– DebugDebug DriverDriver enumerationenumeration andand DataData TransferTransfer
–– VerifyVerify SystemSystem levellevel behaviorbehavior withwith analyzeranalyzer
–– ExecuteExecute ComplianceCompliance TestTest inin looploop modemode (>1000x)(>1000x)
??PurchasePurchase aa USBUSB EvaluationEvaluation BoardBoard && sourcesource
codecode
??UtilizeUtilize USBUSB OrganizationsOrganizations TestTest ResourcesResources
45
AnalyzerAnalyzer ViewView 46
AnalyzerAnalyzer ViewView
46
HostHost SoftwareSoftware TestingTesting StrategiesStrategies ??ScheduleSchedule availabilityavailability ofof HostHost
HostHost SoftwareSoftware TestingTesting StrategiesStrategies
??ScheduleSchedule availabilityavailability ofof HostHost softwaresoftware
––USBUSB mini-drivermini-driver
––HostHost TestTest ApplicationApplication
??RequestRequest HostHost TestTest ApplicationApplication supportsupport
––EnumerationEnumeration
––DataData TransferTransfer
––DataData TransferTransfer LoopbackLoopback TestingTesting
––Vendor/ClassVendor/Class RequestRequest SupportSupport
??LeverageLeverage USBUSB EvaluationEvaluation samplesample sourcesource
––StimulateStimulate USBUSB peripheralperipheral usingusing samplesample codecode
??SystemSystem TestsTests
––PerformPerform typicaltypical useuse casescases withwith ProductProduct softwaresoftware
47
EmbeddedEmbedded SoftwareSoftware TestingTesting StrategiesStrategies ??UnitUnit TestsTests ––DriverDriver
EmbeddedEmbedded SoftwareSoftware TestingTesting StrategiesStrategies
??UnitUnit TestsTests
––DriverDriver InstallInstall andand UninstallUninstall
––EnumerationEnumeration TestTest
––DeviceDevice DriverDriver APIAPI
••Open/CloseOpen/Close endpointsendpoints
••DataData TransferTransfer (read(read andand write)write)
••SelectSelect EndpointEndpoint usingusing DMADMA
••IOIO ControlControl TestTest
––LoopbackLoopback TestingTesting (>1000x,(>1000x, varyvary transfertransfer sizes)sizes)
––Vendor/ClassVendor/Class RequestRequest SupportSupport
??SystemSystem TestsTests
––PerformPerform typicaltypical useuse casescases withwith ProductProduct softwaresoftware
––SystemSystem LevelLevel PowerPower ManagementManagement
48
USBUSB OrganizationOrganization’’ss TestingTesting ResourcesResources ??USB-IFUSB-IF ComplianceCompliance
USBUSB OrganizationOrganization’’ss TestingTesting ResourcesResources
??USB-IFUSB-IF ComplianceCompliance ProgramProgram
––WorksheetsWorksheets
••DeviceDevice FrameworkFramework
••SignalSignal QualityQuality
••PowerPower DistributionDistribution andand ConsumptionConsumption
––InteroperabilityInteroperability GuidelinesGuidelines
––TestTest ToolsTools
••USBCheckUSBCheck,, HIDViewHIDView
––ComplianceCompliance WorkshopsWorkshops
••VerifiesVerifies USBUSB ComplianceCompliance andand InteroperabilityInteroperability
••in-housein-house USBUSB ComplianceCompliance andand InteroperabilityInteroperability
––VerifyVerify throughoutthroughout productproduct developmentdevelopment
49
USBUSB AnalyzersAnalyzers ??BenefitsBenefits ofof anan USBUSB AnalyzerAnalyzer ToolTool ––PassivelyPassively
USBUSB AnalyzersAnalyzers
??BenefitsBenefits ofof anan USBUSB AnalyzerAnalyzer ToolTool
––PassivelyPassively monitorsmonitors USBUSB BusBus
––AllowsAllows debugdebug ofof Enumeration,Enumeration, Vendor/ClassVendor/Class RequestsRequests
––RevealsReveals systemsystem levellevel behaviorbehavior
––SomeSome toolstools allowallow forfor activeactive introductionintroduction ofof faults,faults,
standardstandard RequestsRequests oror Vendor/ClassVendor/Class RequestsRequests
??DrawbacksDrawbacks
––PurchasePurchase PricePrice
––SelectingSelecting whichwhich oneone youyou wantwant
––SomeSome PCPC’’ss havehave demonstrateddemonstrated signal/noisesignal/noise errorserrors
withwith USBUSB analyzeranalyzer’’ss attachedattached
50
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
51
IssuesIssues toto considerconsider ??MoreMore ClassClass SupportSupport ––HID,HID, Common,Common, MassMass
IssuesIssues toto considerconsider
??MoreMore ClassClass SupportSupport
––HID,HID, Common,Common, MassMass Storage,Storage, FirmwareFirmware Upgrade,Upgrade,
??USBUSB 2.02.0
––DoDo youyou needneed it?it?
––NOTNOT supportedsupported inin WindowsWindows XPXP
??ProtocolProtocol StacksStacks
––PIMA/ISO-15740PIMA/ISO-15740
––USBUSB MassMass StorageStorage DevicesDevices
––WDMWDM StillStill ImageImage ArchitectureArchitecture
52
OutlineOutline ??USBUSB OverviewOverview ??USBUSB HardwareHardware ControllersControllers ??ArchitectureArchitecture
OutlineOutline
??USBUSB OverviewOverview
??USBUSB HardwareHardware ControllersControllers
??ArchitectureArchitecture ofof anan EmbeddedEmbedded USBUSB DeviceDevice
??USBUSB DeviceDevice DriverDriver ArchitectureArchitecture
??CaseCase StudyStudy ofof aa USBUSB DeviceDevice DriverDriver
??TestingTesting StrategiesStrategies
??IssuesIssues toto considerconsider
??ConclusionsConclusions
53
ConclusionConclusion ??SelectingSelecting aa moremore capablecapable USBUSB controllercontroller simplifiessimplifies
ConclusionConclusion
??SelectingSelecting aa moremore capablecapable USBUSB controllercontroller simplifiessimplifies thethe
designdesign USBUSB DeviceDevice DriversDrivers
??SupportSupport bothboth CPUCPU andand DMADMA transferstransfers
??DataData TransferTransfer SpeedSpeed isis aa prioritypriority
–– TransferTransfer DataData insideinside ISRISR
–– OptimizeOptimize codecode executionexecution ofof criticalcritical routinesroutines
–– DesignDesign aa solutionsolution withwith parallelismparallelism ofof processingprocessing andand datadata
transfertransfer
–– DedicateDedicate thethe DMADMA toto thethe highesthighest busbus bandwidthbandwidth scenariosscenarios
??USBUSB ComplianceCompliance testingtesting occursoccurs throughoutthroughout
developmentdevelopment
??TakeTake advantageadvantage ofof
–– USBUSB TestTest toolstools
–– USBUSB AnalyzersAnalyzers
–– ComplianceCompliance WorksheetsWorksheets
54
ForFor MoreMore InformationInformation ??USBUSB SpecificationSpecification RevRev 1.1,1.1, 1.01.0
ForFor MoreMore InformationInformation
??USBUSB SpecificationSpecification RevRev 1.1,1.1, 1.01.0
??http://www.http://www.usbusb.org.org -- thethe rootroot nodenode
??http://www.http://www.intelintel.com.com
??www.www.microsoftmicrosoft.com.com
–– SearchSearch forfor WDM,WDM, WinHECWinHEC,, ActiveMovie,ActiveMovie, StillStill Image,Image, etc.etc.
??USBUSB SystemSystem Architecture,Architecture, DonDon AndersonAnderson --
MindshareMindshare Inc.Inc.
??www.www.linuxlinux.org.org
??www.www.catccatc.com.com
??QuestraQuestra CorporationCorporation (716)(716) 381-0260381-0260
www.www.questraquestra.com.com
55
DesignDesign ofof aa USBUSB DeviceDevice DriverDriver JoeJoe FlynnFlynn QuestraQuestra CorporationCorporation
DesignDesign ofof aa USBUSB DeviceDevice DriverDriver
JoeJoe FlynnFlynn
QuestraQuestra CorporationCorporation
jflynn@jflynn@questraquestra.com.com
(716)381-0260(716)381-0260
56