1How USB works with driver model
2===============================
3
4Introduction
5------------
6
7Driver model USB support makes use of existing features but changes how
8drivers are found. This document provides some information intended to help
9understand how things work with USB in U-Boot when driver model is enabled.
10
11
12Enabling driver model for USB
13-----------------------------
14
15A new CONFIG_DM_USB option is provided to enable driver model for USB. This
16causes the USB uclass to be included, and drops the equivalent code in
17usb.c. In particular the usb_init() function is then implemented by the
18uclass.
19
20
21Support for EHCI and XHCI
22-------------------------
23
24So far OHCI is not supported. Both EHCI and XHCI drivers should be declared
25as drivers in the USB uclass. For example:
26
27static const struct udevice_id ehci_usb_ids[] = {
28	{ .compatible = "nvidia,tegra20-ehci", .data = USB_CTLR_T20 },
29	{ .compatible = "nvidia,tegra30-ehci", .data = USB_CTLR_T30 },
30	{ .compatible = "nvidia,tegra114-ehci", .data = USB_CTLR_T114 },
31	{ }
32};
33
34U_BOOT_DRIVER(usb_ehci) = {
35	.name	= "ehci_tegra",
36	.id	= UCLASS_USB,
37	.of_match = ehci_usb_ids,
38	.ofdata_to_platdata = ehci_usb_ofdata_to_platdata,
39	.probe = tegra_ehci_usb_probe,
40	.remove = tegra_ehci_usb_remove,
41	.ops	= &ehci_usb_ops,
42	.platdata_auto_alloc_size = sizeof(struct usb_platdata),
43	.priv_auto_alloc_size = sizeof(struct fdt_usb),
44	.flags	= DM_FLAG_ALLOC_PRIV_DMA,
45};
46
47Here ehci_usb_ids is used to list the controllers that the driver supports.
48Each has its own data value. Controllers must be in the UCLASS_USB uclass.
49
50The ofdata_to_platdata() method allows the controller driver to grab any
51necessary settings from the device tree.
52
53The ops here are ehci_usb_ops. All EHCI drivers will use these same ops in
54most cases, since they are all EHCI-compatible. For EHCI there are also some
55special operations that can be overridden when calling ehci_register().
56
57The driver can use priv_auto_alloc_size to set the size of its private data.
58This can hold run-time information needed by the driver for operation. It
59exists when the device is probed (not when it is bound) and is removed when
60the driver is removed.
61
62Note that usb_platdata is currently only used to deal with setting up a bus
63in USB device mode (OTG operation). It can be omitted if that is not
64supported.
65
66The driver's probe() method should do the basic controller init and then
67call ehci_register() to register itself as an EHCI device. It should call
68ehci_deregister() in the remove() method. Registering a new EHCI device
69does not by itself cause the bus to be scanned.
70
71The old ehci_hcd_init() function is no-longer used. Nor is it necessary to
72set up the USB controllers from board init code. When 'usb start' is used,
73each controller will be probed and its bus scanned.
74
75XHCI works in a similar way.
76
77
78Data structures
79---------------
80
81The following primary data structures are in use:
82
83- struct usb_device
84	This holds information about a device on the bus. All devices have
85	this structure, even the root hub. The controller itself does not
86	have this structure. You can access it for a device 'dev' with
87	dev_get_parentdata(dev). It matches the old structure except that the
88	parent and child information is not present (since driver model
89	handles that). Once the device is set up, you can find the device
90	descriptor and current configuration descriptor in this structure.
91
92- struct usb_platdata
93	This holds platform data for a controller. So far this is only used
94	as a work-around for controllers which can act as USB devices in OTG
95	mode, since the gadget framework does not use driver model.
96
97- struct usb_dev_platdata
98	This holds platform data for a device. You can access it for a
99	device 'dev' with dev_get_parent_platdata(dev). It holds the device
100	address and speed - anything that can be determined before the device
101	driver is actually set up. When probing the bus this structure is
102	used to provide essential information to the device driver.
103
104- struct usb_bus_priv
105	This is private information for each controller, maintained by the
106	controller uclass. It is mostly used to keep track of the next
107	device address to use.
108
109Of these, only struct usb_device was used prior to driver model.
110
111
112USB buses
113---------
114
115Given a controller, you know the bus - it is the one attached to the
116controller. Each controller handles exactly one bus. Every controller has a
117root hub attached to it. This hub, which is itself a USB device, can provide
118one or more 'ports' to which additional devices can be attached. It is
119possible to power up a hub and find out which of its ports have devices
120attached.
121
122Devices are given addresses starting at 1. The root hub is always address 1,
123and from there the devices are numbered in sequence. The USB uclass takes
124care of this numbering automatically during enumeration.
125
126USB devices are enumerated by finding a device on a particular hub, and
127setting its address to the next available address. The USB bus stretches out
128in a tree structure, potentially with multiple hubs each with several ports
129and perhaps other hubs. Some hubs will have their own power since otherwise
130the 5V 500mA power supplied by the controller will not be sufficient to run
131very many devices.
132
133Enumeration in U-Boot takes a long time since devices are probed one at a
134time, and each is given sufficient time to wake up and announce itself. The
135timeouts are set for the slowest device.
136
137Up to 127 devices can be on each bus. USB has four bus speeds: low
138(1.5Mbps), full (12Mbps), high (480Mbps) which is only available with USB2
139and newer (EHCI), and super (5Gbps) which is only available with USB3 and
140newer (XHCI). If you connect a super-speed device to a high-speed hub, you
141will only get high-speed.
142
143
144USB operations
145--------------
146
147As before driver model, messages can be sent using submit_bulk_msg() and the
148like. These are now implemented by the USB uclass and route through the
149controller drivers. Note that messages are not sent to the driver of the
150device itself - i.e. they don't pass down the stack to the controller.
151U-Boot simply finds the controller to which the device is attached, and sends
152the message there with an appropriate 'pipe' value so it can be addressed
153properly. Having said that, the USB device which should receive the message
154is passed in to the driver methods, for use by sandbox. This design decision
155is open for review and the code impact of changing it is small since the
156methods are typically implemented by the EHCI and XHCI stacks.
157
158Controller drivers (in UCLASS_USB) themselves provide methods for sending
159each message type. For XHCI an additional alloc_device() method is provided
160since XHCI needs to allocate a device context before it can even read the
161device's descriptor.
162
163These methods use a 'pipe' which is a collection of bit fields used to
164describe the type of message, direction of transfer and the intended
165recipient (device number).
166
167
168USB Devices
169-----------
170
171USB devices are found using a simple algorithm which works through the
172available hubs in a depth-first search. Devices can be in any uclass, but
173are attached to a parent hub (or controller in the case of the root hub) and
174so have parent data attached to them (this is struct usb_device).
175
176By the time the device's probe() method is called, it is enumerated and is
177ready to talk to the host.
178
179The enumeration process needs to work out which driver to attach to each USB
180device. It does this by examining the device class, interface class, vendor
181ID, product ID, etc. See struct usb_driver_entry for how drivers are matched
182with USB devices - you can use the USB_DEVICE() macro to declare a USB
183driver. For example, usb_storage.c defines a USB_DEVICE() to handle storage
184devices, and it will be used for all USB devices which match.
185
186
187
188Technical details on enumeration flow
189-------------------------------------
190
191It is useful to understand precisely how a USB bus is enumerating to avoid
192confusion when dealing with USB devices.
193
194Device initialisation happens roughly like this:
195
196- At some point the 'usb start' command is run
197- This calls usb_init() which works through each controller in turn
198- The controller is probed(). This does no enumeration.
199- Then usb_scan_bus() is called. This calls usb_scan_device() to scan the
200(only) device that is attached to the controller - a root hub
201- usb_scan_device() sets up a fake struct usb_device and calls
202usb_setup_device(), passing the port number to be scanned, in this case port
2030
204- usb_setup_device() first calls usb_prepare_device() to set the device
205address, then usb_select_config() to select the first configuration
206- at this point the device is enumerated but we do not have a real struct
207udevice for it. But we do have the descriptor in struct usb_device so we can
208use this to figure out what driver to use
209- back in usb_scan_device(), we call usb_find_child() to try to find an
210existing device which matches the one we just found on the bus. This can
211happen if the device is mentioned in the device tree, or if we previously
212scanned the bus and so the device was created before
213- if usb_find_child() does not find an existing device, we call
214usb_find_and_bind_driver() which tries to bind one
215- usb_find_and_bind_driver() searches all available USB drivers (declared
216with USB_DEVICE()). If it finds a match it binds that driver to create a new
217device.
218- If it does not, it binds a generic driver. A generic driver is good enough
219to allow access to the device (sending it packets, etc.) but all
220functionality will need to be implemented outside the driver model.
221- in any case, when usb_find_child() and/or usb_find_and_bind_driver() are
222done, we have a device with the correct uclass. At this point we want to
223probe the device
224- first we store basic information about the new device (address, port,
225speed) in its parent platform data. We cannot store it its private data
226since that will not exist until the device is probed.
227- then we call device_probe() which probes the device
228- the first probe step is actually the USB controller's (or USB hubs's)
229child_pre_probe() method. This gets called before anything else and is
230intended to set up a child device ready to be used with its parent bus. For
231USB this calls usb_child_pre_probe() which grabs the information that was
232stored in the parent platform data and stores it in the parent private data
233(which is struct usb_device, a real one this time). It then calls
234usb_select_config() again to make sure that everything about the device is
235set up
236- note that we have called usb_select_config() twice. This is inefficient
237but the alternative is to store additional information in the platform data.
238The time taken is minimal and this way is simpler
239- at this point the device is set up and ready for use so far as the USB
240subsystem is concerned
241- the device's probe() method is then called. It can send messages and do
242whatever else it wants to make the device work.
243
244Note that the first device is always a root hub, and this must be scanned to
245find any devices. The above steps will have created a hub (UCLASS_USB_HUB),
246given it address 1 and set the configuration.
247
248For hubs, the hub uclass has a post_probe() method. This means that after
249any hub is probed, the uclass gets to do some processing. In this case
250usb_hub_post_probe() is called, and the following steps take place:
251
252- usb_hub_post_probe() calls usb_hub_scan() to scan the hub, which in turn
253calls usb_hub_configure()
254- hub power is enabled
255- we loop through each port on the hub, performing the same steps for each
256- first, check if there is a device present. This happens in
257usb_hub_port_connect_change(). If so, then usb_scan_device() is called to
258scan the device, passing the appropriate port number.
259- you will recognise usb_scan_device() from the steps above. It sets up the
260device ready for use. If it is a hub, it will scan that hub before it
261continues here (recursively, depth-first)
262- once all hub ports are scanned in this way, the hub is ready for use and
263all of its downstream devices also
264- additional controllers are scanned in the same way
265
266The above method has some nice properties:
267
268- the bus enumeration happens by virtue of driver model's natural device flow
269- most logic is in the USB controller and hub uclasses; the actual device
270drivers do not need to know they are on a USB bus, at least so far as
271enumeration goes
272- hub scanning happens automatically after a hub is probed
273
274
275Hubs
276----
277
278USB hubs are scanned as in the section above. While hubs have their own
279uclass, they share some common elements with controllers:
280
281- they both attach private data to their children (struct usb_device,
282accessible for a child with dev_get_parentdata(child))
283- they both use usb_child_pre_probe() to set up their children as proper USB
284devices
285
286
287Example - Mass Storage
288----------------------
289
290As an example of a USB device driver, see usb_storage.c. It uses its own
291uclass and declares itself as follows:
292
293U_BOOT_DRIVER(usb_mass_storage) = {
294	.name	= "usb_mass_storage",
295	.id	= UCLASS_MASS_STORAGE,
296	.of_match = usb_mass_storage_ids,
297	.probe = usb_mass_storage_probe,
298};
299
300static const struct usb_device_id mass_storage_id_table[] = {
301    { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
302      .bInterfaceClass = USB_CLASS_MASS_STORAGE},
303    { }						/* Terminating entry */
304};
305
306USB_DEVICE(usb_mass_storage, mass_storage_id_table);
307
308The USB_DEVICE() macro attaches the given table of matching information to
309the given driver. Note that the driver is declared in U_BOOT_DRIVER() as
310'usb_mass_storage' and this must match the first parameter of USB_DEVICE.
311
312When usb_find_and_bind_driver() is called on a USB device with the
313bInterfaceClass value of USB_CLASS_MASS_STORAGE, it will automatically find
314this driver and use it.
315
316
317Counter-example: USB Ethernet
318-----------------------------
319
320As an example of the old way of doing things, see usb_ether.c. When the bus
321is scanned, all Ethernet devices will be created as generic USB devices (in
322uclass UCLASS_USB_DEV_GENERIC). Then, when the scan is completed,
323usb_host_eth_scan() will be called. This looks through all the devices on
324each bus and manually figures out which are Ethernet devices in the ways of
325yore.
326
327In fact, usb_ether should be moved to driver model. Each USB Ethernet driver
328(e.g drivers/usb/eth/asix.c) should include a USB_DEVICE() declaration, so
329that it will be found as part of normal USB enumeration. Then, instead of a
330generic USB driver, a real (driver-model-aware) driver will be used. Since
331Ethernet now supports driver model, this should be fairly easy to achieve,
332and then usb_ether.c and the usb_host_eth_scan() will melt away.
333
334
335Sandbox
336-------
337
338All driver model uclasses must have tests and USB is no exception. To
339achieve this, a sandbox USB controller is provided. This can make use of
340emulation drivers which pretend to be USB devices. Emulations are provided
341for a hub and a flash stick. These are enough to create a pretend USB bus
342(defined by the sandbox device tree sandbox.dts) which can be scanned and
343used.
344
345Tests in test/dm/usb.c make use of this feature. It allows much of the USB
346stack to be tested without real hardware being needed.
347
348Here is an example device tree fragment:
349
350	usb@1 {
351		compatible = "sandbox,usb";
352		hub {
353			compatible = "usb-hub";
354			usb,device-class = <USB_CLASS_HUB>;
355			hub-emul {
356				compatible = "sandbox,usb-hub";
357				#address-cells = <1>;
358				#size-cells = <0>;
359				flash-stick {
360					reg = <0>;
361					compatible = "sandbox,usb-flash";
362					sandbox,filepath = "flash.bin";
363				};
364			};
365		};
366	};
367
368This defines a single controller, containing a root hub (which is required).
369The hub is emulated by a hub emulator, and the emulated hub has a single
370flash stick to emulate on one of its ports.
371
372When 'usb start' is used, the following 'dm tree' output will be available:
373
374 usb         [ + ]    `-- usb@1
375 usb_hub     [ + ]        `-- hub
376 usb_emul    [ + ]            |-- hub-emul
377 usb_emul    [ + ]            |   `-- flash-stick
378 usb_mass_st [ + ]            `-- usb_mass_storage
379
380
381This may look confusing. Most of it mirrors the device tree, but the
382'usb_mass_storage' device is not in the device tree. This is created by
383usb_find_and_bind_driver() based on the USB_DRIVER in usb_storage.c. While
384'flash-stick' is the emulation device, 'usb_mass_storage' is the real U-Boot
385USB device driver that talks to it.
386
387
388Future work
389-----------
390
391It is pretty uncommon to have a large USB bus with lots of hubs on an
392embedded system. In fact anything other than a root hub is uncommon. Still
393it would be possible to speed up enumeration in two ways:
394
395- breadth-first search would allow devices to be reset and probed in
396parallel to some extent
397- enumeration could be lazy, in the sense that we could enumerate just the
398root hub at first, then only progress to the next 'level' when a device is
399used that we cannot find. This could be made easier if the devices were
400statically declared in the device tree (which is acceptable for production
401boards where the same, known, things are on each bus).
402
403But in common cases the current algorithm is sufficient.
404
405Other things that need doing:
406- Convert usb_ether to use driver model as described above
407- Test that keyboards work (and convert to driver model)
408- Move the USB gadget framework to driver model
409- Implement OHCI in driver model
410- Implement USB PHYs in driver model
411- Work out a clever way to provide lazy init for USB devices
412
413--
414Simon Glass <sjg@chromium.org>
41523-Mar-15
416