]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/io/usb/slave/v2_0/doc/usbs.sgml
unified MX27, MX25, MX37 trees
[karo-tx-redboot.git] / packages / io / usb / slave / v2_0 / doc / usbs.sgml
1 <!-- DOCTYPE reference  PUBLIC "-//OASIS//DTD DocBook V3.1//EN" -->
2
3 <!-- {{{ Banner                         -->
4
5 <!-- =============================================================== -->
6 <!--                                                                 -->
7 <!--     usbs.sgml                                                   -->
8 <!--                                                                 -->
9 <!--     Generic USB-slave documentation.                            -->
10 <!--                                                                 -->
11 <!-- =============================================================== -->
12 <!-- ####COPYRIGHTBEGIN####                                          -->
13 <!--                                                                 -->
14 <!-- =============================================================== -->
15 <!-- Copyright (C) 2001, 2002 Red Hat, Inc.                          -->
16 <!-- This material may be distributed only subject to the terms      -->
17 <!-- and conditions set forth in the Open Publication License, v1.0  -->
18 <!-- or later (the latest version is presently available at          -->
19 <!-- http://www.opencontent.org/openpub/)                            -->
20 <!-- Distribution of the work or derivative of the work in any       -->
21 <!-- standard (paper) book form is prohibited unless prior           -->
22 <!-- permission obtained from the copyright holder                   -->
23 <!-- =============================================================== -->
24 <!--                                                                 -->      
25 <!-- ####COPYRIGHTEND####                                            -->
26 <!-- =============================================================== -->
27 <!-- #####DESCRIPTIONBEGIN####                                       -->
28 <!--                                                                 -->
29 <!-- Author(s):   bartv                                              -->
30 <!-- Contact(s):  bartv                                              -->
31 <!-- Date:        2001/01/03                                         -->
32 <!-- Version:     0.01                                               -->
33 <!--                                                                 -->
34 <!-- ####DESCRIPTIONEND####                                          -->
35 <!-- =============================================================== -->
36
37 <!-- }}} -->
38
39 <part id="io-usb-slave">
40 <!-- reference id="io-usb-slave" -->
41   <title>eCos USB Slave Support</title>
42
43 <!-- {{{ Intro                          -->
44
45 <refentry id="usbs-intro">
46 <refmeta>
47 <refentrytitle>Introduction</refentrytitle>
48 </refmeta>
49 <refnamediv>
50 <refname>Introduction</refname>
51 <refpurpose>eCos support for USB slave devices</refpurpose>
52 </refnamediv>
53
54 <refsect1><title>Introduction</title>
55 <para>
56 The eCos USB slave support allows developers to produce USB
57 peripherals. It consists of a number of different eCos packages:
58 </para>
59 <orderedlist>
60
61 <listitem>
62 <para>
63 Device drivers for specific implementations of USB slave hardware, for
64 example the on-chip USB Device Controller provided by the Intel SA1110
65 processor. A typical USB peripheral will only provide one USB slave
66 port and therefore only one such device driver package will be needed.
67 Usually the device driver package will be loaded automatically when
68 you create an eCos configuration for target hardware that has a USB
69 slave device. If you select a target which does have a USB slave
70 device but no USB device driver is loaded, this implies that no such
71 device driver is currently available.
72 </para>
73 </listitem>
74
75 <listitem>
76 <para>
77 The common USB slave package. This serves two purposes. It defines the
78 API that specific device drivers should implement. It also provides
79 various utilities that will be needed by most USB device drivers and
80 applications, such as handlers for standard control messages.
81 Usually this package will be loaded automatically at the same time as
82 the USB device driver.
83 </para>
84 </listitem>
85
86 <listitem>
87 <para>
88 The common USB package. This merely provides some information common
89 to both the host and slave sides of USB, such as details of the
90 control protocol. It is also used to place the other USB-related
91 packages appropriately in the overall configuration hierarchy. Usually
92 this package will be loaded at the same time as the USB device driver.
93 </para>
94 </listitem>
95
96 <listitem>
97 <para>
98 Class-specific USB support packages. These make it easier to develop
99 specific classes of USB peripheral, such as a USB-ethernet device. If
100 no suitable package is available for a given class of peripheral then
101 the USB device driver can instead be accessed directly from
102 application code. Such packages will never be loaded automatically
103 since the configuration system has no way of knowing what class of USB
104 peripheral is being developed. Instead developers have to add the
105 appropriate package or packages explicitly.
106 </para>
107 </listitem>
108
109 </orderedlist>
110
111 <para>
112 These packages only provide support for developing USB peripherals,
113 not USB hosts.
114 </para>
115 </refsect1>
116
117 <refsect1><title>USB Concepts</title>
118 <para>
119 Information about USB can be obtained from a number of sources
120 including the <ulink url="http://www.usb.org/">USB Implementers Forum
121 web site</ulink>. Only a brief summary is provided here.
122 </para>
123 <para>
124 A USB network is asymmetrical: it consists of a single host, one or
125 more slave devices, and possibly some number of intermediate hubs. The
126 host side is significantly more complicated than the slave side.
127 Essentially, all operations are initiated by the host. For example, if
128 the host needs to receive some data from a particular USB peripheral
129 then it will send an IN token to that peripheral; the latter should
130 respond with either a NAK or with appropriate data. Similarly, when
131 the host wants to transmit data to a peripheral it will send an OUT
132 token followed by the data; the peripheral will return a NAK if it is
133 currently unable to receive more data or if there was corruption,
134 otherwise it will return an ACK. All transfers are check-summed and
135 there is a clearly-defined error recovery process. USB peripherals can
136 only interact with the host, not with each other.
137 </para>
138 <para>
139 USB supports four different types of communication: control messages,
140 interrupt transfers, isochronous transfers, and bulk transfers.
141 Control messages are further subdivided into four categories:
142 standard, class, vendor and a reserved category. All USB peripherals
143 must respond to certain standard control messages, and usually this
144 will be handled by the common USB slave package (for complicated
145 peripherals, application support will be needed). Class and vendor
146 control messages may be handled by an class-specific USB support
147 package, for example the USB-ethernet package will handle control
148 messages such as getting the MAC address or enabling/disabling
149 promiscuous mode. Alternatively, some or all of these messages will
150 have to be handled by application code.
151 </para>
152 <para>
153 Interrupt transfers are used for devices which need to be polled
154 regularly. For example, a USB keyboard might be polled once every
155 millisecond. The host will not poll the device more frequently than
156 this, so interrupt transfers are best suited to peripherals that
157 involve a relatively small amount of data. Isochronous transfers are
158 intended for multimedia-related peripherals where typically a large
159 amount of video or audio data needs to be exchanged continuously.
160 Given appropriate host support a USB peripheral can reserve some of
161 the available bandwidth. Isochronous transfers are not reliable; if a
162 particular packet is corrupted then it will just be discarded and
163 software is expected to recover from this. Bulk transfers are used for
164 everything else: after taking care of any pending control, isochronous
165 and interrupt transfers the host will use whatever bandwidth remains
166 for bulk transfers. Bulk transfers are reliable.
167 </para>
168 <para>
169 Transfers are organized into USB packets, with the details depending
170 on the transfer type. Control messages always involve an initial
171 8-byte packet from host to peripheral, optionally followed by some
172 additional packets; in theory these additional packets can be up to 64
173 bytes, but hardware may limit it to 8 bytes. Interrupt transfers
174 involve a single packet of up to 64 bytes. Isochronous transfers
175 involve a single packet of up to 1024 bytes. Bulk transfers involve
176 multiple packets. There will be some number, possibly zero, of 64-byte
177 packets. The transfer is terminated by a single packet of less than 64
178 bytes. If the transfer involves an exact multiple of 64 bytes than the
179 final packet will be 0 bytes, consisting of just a header and checksum
180 which typically will be generated by the hardware. There is no
181 pre-defined limit on the size of a bulk transfer. Instead higher-level
182 protocols are expected to handle this, so for a USB-ethernet
183 peripheral the protocol could impose a limit of 1514 bytes of data
184 plus maybe some additional protocol overhead.
185 </para>
186 <para>
187 Transfers from the host to a peripheral are addressed not just to that
188 peripheral but to a specific endpoint within that peripheral.
189 Similarly, the host requests incoming data from a specific endpoint
190 rather than from the peripheral as a whole. For example, a combined
191 keyboard/touchpad device could provide the keyboard events on endpoint
192 1 and the mouse events on endpoint 2. A given USB peripheral can have
193 up to 16 endpoints for incoming data and another 16 for outgoing data.
194 However, given the comparatively high speed of USB I/O this endpoint
195 addressing is typically implemented in hardware rather than software,
196 and the hardware will only implement a small number of endpoints.
197 Endpoint 0 is generally used only for control messages.
198 </para>
199 <para>
200 In practice, many of these details are irrelevant to application code
201 or to class packages. Instead, such higher-level code usually just
202 performs blocking <function>read</function> and
203 <function>write</function>, or non-blocking USB-specific calls, to
204 transfer data between host and target via a specific endpoint. Control
205 messages are more complicated but are usually handled by existing
206 code.
207 </para>
208 <para>
209 When a USB peripheral is plugged into the host there is an initial
210 enumeration and configuration process. The peripheral provides
211 information such as its class of device (audio, video, etc.), a
212 vendor id, which endpoints should be used for what kind of data, and
213 so on. The host OS uses this information to identify a suitable host
214 device driver. This could be a generic driver for a class of
215 peripherals, or it could be a vendor-specific driver. Assuming a
216 suitable driver is installed the host will then activate the USB
217 peripheral and perform additional application-specific initialisation.
218 For example for a USB-ethernet device this would involve obtaining an
219 ethernet MAC address. Most USB peripherals will be fairly simple, but
220 it is possible to build multifunction peripherals with multiple
221 configurations, interfaces, and alternate interface settings.
222 </para>
223 <para>
224 It is not possible for any of the eCos packages to generate all the
225 enumeration data automatically. Some of the required information such
226 as the vendor id cannot be supplied by generic packages; only by the
227 application developer. Class support code such as the USB-ethernet
228 package could in theory supply some of the information automatically,
229 but there are also hardware dependencies such as which endpoints get
230 used for incoming and outgoing ethernet frames. Instead it is the
231 responsibility of the application developer to provide all the
232 enumeration data and perform some additional initialisation. In
233 addition, the common USB slave package can handle all the standard
234 control messages for a simple USB peripheral, but for something like a
235 multifunction peripheral additional application support is needed.
236 </para>
237
238 <note><para>
239 The initial implementation of the eCos USB slave packages involved
240 hardware that only supported control and bulk transfers, not
241 isochronous or interrupt. There may be future changes to the USB
242 code and API to allow for isochronous and interrupt transfers,
243 especially the former. Other changes may be required to support
244 different USB devices. At present there is no support for USB remote
245 wakeups, since again it is not supported by the hardware.
246 </para></note>
247
248 </refsect1>
249
250 <refsect1><title>eCos USB I/O Facilities</title>
251 <para>
252 For protocols other than control messages, eCos provides two ways of
253 performing USB I/O. The first involves device table or devtab entries such
254 as <link linkend="usbs-devtab"><literal>/dev/usb1r</literal></link>,
255 with one entry per endpoint per USB device. It is possible to
256 <function>open</function> these devices and use conventional blocking
257 I/O functions such as <function>read</function> and
258 <function>write</function> to exchange data between host and
259 peripheral.
260 </para>
261 <para>
262 There is also a lower-level USB-specific API, consisting of functions
263 such as <link
264 linkend="usbs-start-rx"><function>usbs_start_rx_buffer</function></link>.
265 A USB device driver will supply a data structure for each endpoint,
266 for example a <link
267 linkend="usbs-data"><structname>usbs_rx_endpoint</structname></link>
268 structure for every receive endpoint. The first argument to
269 <function>usbs_start_rx_buffer</function> should be a pointer to such
270 a data structure. The USB-specific API is non-blocking: the initial
271 call merely starts the transfer; some time later, once the transfer
272 has completed or has been aborted, the device driver will invoke a
273 completion function.
274 </para>
275 <para>
276 Control messages are different. With four different categories of
277 control messages including application and vendor specific ones, the
278 conventional
279 <function>open</function>/<function>read</function>/<function>write</function>
280 model of I/O cannot easily be applied. Instead, a USB device driver
281 will supply a <link
282 linkend="usbs-control"><structname>usbs_control_endpoint</structname></link>
283 data structure which can be manipulated appropriately. In practice the
284 standard control messages will usually be handled by the common USB
285 slave package, and other control messages will be handled by
286 class-specific code such as the USB-ethernet package. Typically,
287 application code remains responsible for supplying the <link
288 linkend="usbs-enum">enumeration data</link> and for actually <link
289 linkend="usbs-start">starting</link> up the USB device.
290 </para>
291 </refsect1>
292
293 <refsect1><title>Enabling the USB code</title>
294 <para>
295 If the target hardware contains a USB slave device then the
296 appropriate USB device driver and the common packages will typically
297 be loaded into the configuration automatically when that target is
298 selected (assuming a suitable device driver exists). However, the
299 driver will not necessarily be active. For example a processor might
300 have an on-chip USB device, but not all applications using that
301 processor will want to use USB functionality. Hence by default the USB
302 device is disabled, ensuring that applications do not suffer any
303 memory or other penalties for functionality that is not required.
304 </para>
305 <para>
306 If the application developer explicitly adds a class support package
307 such as the USB-ethernet one then this implies that the USB device is
308 actually needed, and the device will be enabled automatically.
309 However, if no suitable class package is available and the USB device
310 will instead be accessed by application code, it is necessary to
311 enable the USB device manually. Usually the easiest way to do this is
312 to enable the configuration option
313 <literal>CYGGLO_IO_USB_SLAVE_APPLICATION</literal>, and the USB device
314 driver and related packages will adjust accordingly. Alternatively,
315 the device driver may provide some configuration options to provide
316 more fine-grained control.
317 </para>
318 </refsect1>
319
320 </refentry>
321
322 <!-- }}} -->
323 <!-- {{{ Enumeration Data               -->
324
325 <refentry id="usbs-enum">
326 <refmeta>
327 <refentrytitle>USB Enumeration Data</refentrytitle>
328 </refmeta>
329 <refnamediv>
330 <refname>Enumeration Data</refname>
331 <refpurpose>The USB enumeration data structures</refpurpose>
332 </refnamediv>
333
334 <refsynopsisdiv>
335 <synopsis>
336 #include &lt;cyg/io/usb/usb.h&gt;
337 #include &lt;cyg/io/usb/usbs.h&gt;
338
339 typedef struct usb_device_descriptor {
340     &hellip;
341 } usb_device_descriptor __attribute__((packed));
342
343 typedef struct usb_configuration_descriptor {
344     &hellip;
345 } usb_configuration_descriptor __attribute__((packed));
346
347 typedef struct usb_interface_descriptor {
348     &hellip;
349 } usb_interface_descriptor __attribute__((packed));        
350
351 typedef struct usb_endpoint_descriptor {
352     &hellip;
353 } usb_endpoint_descriptor;
354
355 typedef struct usbs_enumeration_data {
356     usb_device_descriptor               device;
357     int                                 total_number_interfaces;
358     int                                 total_number_endpoints;
359     int                                 total_number_strings;
360     const usb_configuration_descriptor* configurations;
361     const usb_interface_descriptor*     interfaces;
362     const usb_endpoint_descriptor*      endpoints;
363     const unsigned char**               strings;
364 } usbs_enumeration_data;
365 </synopsis>
366 </refsynopsisdiv>
367
368 <refsect1><title>USB Enumeration Data</title>
369 <para>
370 When a USB host detects that a peripheral has been plugged in or
371 powered up, one of the first steps is to ask the peripheral to
372 describe itself by supplying enumeration data. Some of this data
373 depends on the class of peripheral. Other fields are vendor-specific.
374 There is also a dependency on the hardware, specifically which
375 endpoints are available should be used. In general it is not possible
376 for generic code to provide this information, so it is the
377 responsibility of application code to provide a suitable
378 <structname>usbs_enumeration_data</structname> data structure and
379 install it in the endpoint 0 data structure during initialization.
380 This must happen before the USB device is enabled by a call to
381 <function>usbs_start</function>, for example:
382 </para>
383 <programlisting width=72>
384 const usbs_enumeration_data usb_enum_data = {
385     &hellip;
386 };
387
388 int
389 main(int argc, char** argv)
390 {
391     usbs_sa11x0_ep0.enumeration_data = &amp;usb_enum_data;
392     &hellip;
393     usbs_start(&amp;usbs_sa11x0_ep0);
394     &hellip;
395 }
396 </programlisting>
397 <para>
398 For most applications the enumeration data will be static, although
399 the <structname>usbs_enumeration_data</structname> structure can be
400 filled in at run-time if necessary. Full details of the enumeration
401 data can be found in the Universal Serial Bus specification obtainable
402 from the <ulink url="http://www.usb.org/">USB Implementers Forum web
403 site</ulink>, although the meaning of most fields is fairly obvious.
404 The various data structures and utility macros are defined in the
405 header files <filename class="headerfile">cyg/io/usb/usb.h</filename>
406 and <filename class="headerfile">cyg/io/usb/usbs.h</filename>. Note
407 that the example code below makes use of the gcc labelled element
408 extension.
409 </para>
410
411 <refsect2><title><structname>usb_device_descriptor</structname></title>
412 <para>
413 The main information about a USB peripheral comes from a single
414 <structname>usb_device_descriptor</structname> structure, which is
415 embedded in the <structname>usbs_enumeration_data</structname>
416 structure. A typical example might look like this:
417 </para>
418 <programlisting width=72>
419 const usbs_enumeration_data usb_enum_data = {
420     {
421         length:                 USB_DEVICE_DESCRIPTOR_LENGTH,
422         type:                   USB_DEVICE_DESCRIPTOR_TYPE,
423         usb_spec_lo:            USB_DEVICE_DESCRIPTOR_USB11_LO,
424         usb_spec_hi:            USB_DEVICE_DESCRIPTOR_USB11_HI,
425         device_class:           USB_DEVICE_DESCRIPTOR_CLASS_VENDOR,
426         device_subclass:        USB_DEVICE_DESCRIPTOR_SUBCLASS_VENDOR,
427         device_protocol:        USB_DEVICE_DESCRIPTOR_PROTOCOL_VENDOR,
428         max_packet_size:        8,
429         vendor_lo:              0x42,
430         vendor_hi:              0x42,
431         product_lo:             0x42,
432         product_hi:             0x42,
433         device_lo:              0x00,
434         device_hi:              0x01,
435         manufacturer_str:       1,
436         product_str:            2,
437         serial_number_str:      0,
438         number_configurations:  1
439     },
440     &hellip;
441 };
442 </programlisting>
443 <para>
444 The length and type fields are specified by the USB standard. The
445 <structfield>usb_spec_lo</structfield> and
446 <structfield>usb_spec_hi</structfield> fields identify the particular
447 revision of the standard that the peripheral implements, for example
448 revision 1.1.
449 </para>
450 <para>
451 The device class, subclass, and protocol fields are used by generic
452 host-side USB software to determine which host-side device driver
453 should be loaded to interact with the peripheral. A number of standard
454 classes are defined, for example mass-storage devices and
455 human-interface devices. If a peripheral implements one of the
456 standard classes then a standard existing host-side device driver may
457 exist, eliminating the need to write a custom driver. The value
458 <literal>0xFF</literal> (<literal>VENDOR</literal>) is reserved for
459 peripherals that implement a vendor-specific protocol rather than a
460 standard one. Such peripherals will require a custom host-side device
461 driver. The value <literal>0x00</literal>
462 (<literal>INTERFACE</literal>) is reserved and indicates that the
463 protocol used by the peripheral is defined at the interface level
464 rather than for the peripheral as a whole.
465 </para>
466 <para>
467 The <structfield>max_package_size</structfield> field specifies the
468 maximum length of a control message. There is a lower bound of eight
469 bytes, and typical hardware will not support anything larger because
470 control messages are usually small and not performance-critical.
471 </para>
472 <para>
473 The <structfield>vendor_lo</structfield> and
474 <structfield>vendor_hi</structfield> fields specify a vendor id, which
475 must be obtained from the USB Implementor's Forum. The numbers used in
476 the code fragment above are examples only and must not be used in real
477 USB peripherals. The product identifier is determined by the vendor,
478 and different USB peripherals should use different identifiers. The
479 device identifier field should indicate a release number in
480 binary-coded decimal.
481 </para>
482 <para>
483 The above fields are all numerical in nature. A USB peripheral can
484 also provide a number of strings as described <link
485 linkend="usbs-enum-strings">below</link>, for example the name of the
486 vendor can be provided. The various <structfield>_str</structfield>
487 fields act as indices into an array of strings, with index 0
488 indicating that no string is available. 
489 </para>
490 <para>
491 A typical USB peripheral involves just a single configuration. However
492 more complicated peripherals can support multiple configurations. Only
493 one configuration will be active at any one time, and the host will
494 switch between them as appropriate. If a peripheral does involve
495 multiple configurations then typically it will be the responsibility
496 of application code to <link
497 linkend="usbs-control-standard">handle</link> the standard
498 set-configuration control message.
499 </para>
500 </refsect2>
501
502 <refsect2><title><structname>usb_configuration_descriptor</structname></title>
503 <para>
504 A USB peripheral involves at least one and possible several different
505 configurations. The <structname>usbs_enumeration_data</structname>
506 structure requires a pointer to an array, possibly of length 1, of
507 <structname>usb_configuration_descriptor</structname> structures.
508 Usually a single structure suffices:
509 </para>
510 <programlisting width=72>
511 const usb_configuration_descriptor usb_configuration = {
512     length:             USB_CONFIGURATION_DESCRIPTOR_LENGTH,
513     type:               USB_CONFIGURATION_DESCRIPTOR_TYPE,
514     total_length_lo:    USB_CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_LO(1, 2),
515     total_length_hi:    USB_CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_HI(1, 2),
516     number_interfaces:  1,
517     configuration_id:   1,
518     configuration_str:  0,
519     attributes:         USB_CONFIGURATION_DESCRIPTOR_ATTR_REQUIRED |
520                         USB_CONFIGURATION_DESCRIPTOR_ATTR_SELF_POWERED,
521     max_power:          50
522 };
523
524 const usbs_enumeration_data usb_enum_data = {
525     &hellip;
526     configurations:             &amp;usb_configuration,
527     &hellip;
528 };
529 </programlisting>
530 <para>
531 The values for the <structfield>length</structfield> and
532 <structfield>type</structfield> fields are determined by the standard.
533 The <structfield>total_length</structfield> field depends on the
534 number of interfaces and endpoints used by this configuration, and
535 convenience macros are provided to calculate this: the first argument
536 to the macros specify the number of interfaces, the second the number
537 of endpoints. The <structfield>number_interfaces</structfield> field
538 is self-explanatory. If the peripheral involves multiple
539 configurations then each one must have a unique id, and this will be
540 used in the set-configuration control message. The id
541 <literal>0</literal> is reserved, and a set-configuration control
542 message that uses this id indicates that the peripheral should be
543 inactive. Configurations can have a string description if required.
544 The <structfield>attributes</structfield> field must have the
545 <literal>REQUIRED</literal> bit set; the
546 <literal>SELF_POWERED</literal> bit informs the host that the
547 peripheral has its own power supply and will not draw any power over
548 the bus, leaving more bus power available to other peripherals; the
549 <literal>REMOTE_WAKEUP</literal> bit is used if the peripheral can
550 interrupt the host when the latter is in power-saving mode. For
551 peripherals that are not self-powered, the
552 <structfield>max_power</structfield> field specifies the power
553 requirements in units of 2mA.
554 </para>
555 </refsect2>
556
557 <refsect2><title><structname>usb_interface_descriptor</structname></title>
558 <para>
559 A USB configuration involves one or more interfaces, typically
560 corresponding to different streams of data. For example, one interface
561 might involve video data while another interface is for audio.
562 Multiple interfaces in a single configuration will be active at the
563 same time.
564 </para>
565 <programlisting width=72>
566 const usb_interface_descriptor usb_interface = {
567     length:             USB_INTERFACE_DESCRIPTOR_LENGTH,
568     type:               USB_INTERFACE_DESCRIPTOR_TYPE,
569     interface_id:       0,
570     alternate_setting:  0,
571     number_endpoints:   2,
572     interface_class:    USB_INTERFACE_DESCRIPTOR_CLASS_VENDOR,
573     interface_subclass: USB_INTERFACE_DESCRIPTOR_SUBCLASS_VENDOR,
574     interface_protocol: USB_INTERFACE_DESCRIPTOR_PROTOCOL_VENDOR,
575     interface_str:      0
576 };
577
578 const usbs_enumeration_data usb_enum_data = {
579     &hellip;
580     total_number_interfaces:    1,
581     interfaces:                 &amp;usb_interface,
582     &hellip;
583 };
584 </programlisting>
585 <para>
586 Again, the <structfield>length</structfield> and
587 <structfield>type</structfield> fields are specified by the standard.
588 Each interface within a configuration requires its own id. However, a
589 given interface may have several alternate settings, in other words
590 entries in the interfaces array with the same id but different
591 <structfield>alternate_setting</structfield> fields. For example,
592 there might be one setting which requires a bandwidth of 100K/s and
593 another setting that only needs 50K/s. The host can use the standard
594 set-interface control message to choose the most appropriate setting.
595 The handling of this request is the responsibility of higher-level
596 code, so the application may have to <link
597 linkend="usbs-control-standard">install</link> its own handler.
598 </para>
599 <para>
600 The number of endpoints used by an interface is specified in the
601 <structfield>number_endpoints</structfield> field. Exact details of
602 which endpoints are used is held in a separate array of endpoint
603 descriptors. The class, subclass and protocol fields are used by
604 host-side code to determine which host-side device driver should
605 handle this specific interface. Usually this is determined on a
606 per-peripheral basis in the
607 <structname>usb_device_descriptor</structname> structure, but that can
608 defer the details to individual interfaces. A per-interface string
609 is allowed as well.
610 </para>
611 <para>
612 For USB peripherals involving multiple configurations, the array of
613 <structname>usb_interface_descriptor</structname> structures should
614 first contain all the interfaces for the first configuration, then all
615 the interfaces for the second configuration, and so on.
616 </para>
617 </refsect2>
618
619 <refsect2><title id="usbs-enum-endpoint"><structname>usb_endpoint_descriptor</structname></title>
620 <para>
621 The host also needs information about which endpoint should be used
622 for what. This involves an array of endpoint descriptors:
623 </para>
624 <programlisting width=72>
625 const usb_endpoint_descriptor usb_endpoints[] = {
626     {
627         length:         USB_ENDPOINT_DESCRIPTOR_LENGTH,
628         type:           USB_ENDPOINT_DESCRIPTOR_TYPE,
629         endpoint:       USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT | 1,
630         attributes:     USB_ENDPOINT_DESCRIPTOR_ATTR_BULK,
631         max_packet_lo:  64,
632         max_packet_hi:  0,
633         interval:       0
634     },
635     {
636         length:         USB_ENDPOINT_DESCRIPTOR_LENGTH,
637         type:           USB_ENDPOINT_DESCRIPTOR_TYPE,
638         endpoint:       USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN | 2,
639         attributes:     USB_ENDPOINT_DESCRIPTOR_ATTR_BULK,
640         max_packet_lo:  64,
641         max_packet_hi:  0,
642         interval:       0
643     }
644 };
645
646 const usbs_enumeration_data usb_enum_data = {
647     &hellip;
648     total_number_endpoints:     2,
649     endpoints:                  usb_endpoints,
650     &hellip;
651 };
652 </programlisting>
653 <para>
654 As usual the values for the <structfield>length</structfield> and
655 <structfield>type</structfield> fields are specified by the standard.
656 The <structfield>endpoint</structfield> field gives both the endpoint
657 number and the direction, so in the above example endpoint 1 is used
658 for OUT (host to peripheral) transfers and endpoint 2 is used for IN
659 (peripheral to host) transfers. The
660 <structfield>attributes</structfield> field indicates the USB protocol
661 that should be used on this endpoint: <literal>CONTROL</literal>,
662 <literal>ISOCHRONOUS</literal>, <literal>BULK</literal> or
663 <literal>INTERRUPT</literal>. The
664 <structfield>max_packet</structfield> field specifies the maximum size
665 of a single USB packet. For bulk transfers this will typically be 64
666 bytes. For isochronous transfers this can be up to 1023 bytes. For
667 interrupt transfers it can be up to 64 bytes, although usually a
668 smaller value will be used. The <structfield>interval</structfield>
669 field is ignored for control and bulk transfers. For isochronous
670 transfers it should be set to 1. For interrupt transfers it can be a
671 value between 1 and 255, and indicates the number of milliseconds
672 between successive polling operations.
673 </para>
674 <para>
675 For USB peripherals involving multiple configurations or interfaces
676 the array of endpoint descriptors should be organized sequentially:
677 first the endpoints corresponding to the first interface of the first
678 configuration, then the second interface in that configuration, and so
679 on; then all the endpoints for all the interfaces in the second
680 configuration; etc.
681 </para>
682 </refsect2>
683
684 <refsect2><title id="usbs-enum-strings">Strings</title>
685 <para>
686 The enumeration data can contain a number of strings with additional
687 information. Unicode encoding is used for the strings, and it is
688 possible for a peripheral to supply a given string in multiple
689 languages using the appropriate characters. The first two bytes of
690 each string give a length and type field. The first string is special;
691 after the two bytes header it consists of an array of 2-byte language
692 id codes, indicating the supported languages. The language code
693 0x0409 corresponds to English (United States). 
694 </para>
695 <programlisting width=72>
696 const unsigned char* usb_strings[] = {
697     "\004\003\011\004",
698     "\020\003R\000e\000d\000 \000H\000a\000t\000"
699 };
700
701 const usbs_enumeration_data usb_enum_data = {
702     &hellip;
703     total_number_strings:       2,
704     strings:                    usb_strings,
705     &hellip;
706 };
707 </programlisting>
708 <para>
709 The default handler for standard control messages assumes that the
710 peripheral only uses a single language. If this is not the case then
711 higher-level code will have to handle the standard get-descriptor
712 control messages when a string descriptor is requested.
713 </para>
714 </refsect2>
715
716 <refsect2><title><structname>usbs_enumeration_data</structname></title>
717 <para>
718 The <structname>usbs_enumeration_data</structname> data structure
719 collects together all the various descriptors that make up the
720 enumeration data. It is the responsibility of application code to
721 supply a suitable data structure and install it in the control
722 endpoints's <structfield>enumeration_data</structfield> field before
723 the USB device is started.
724 </para>
725 </refsect2>
726
727 </refsect1>
728 </refentry>
729
730 <!-- }}} -->
731 <!-- {{{ usbs_start()                   -->
732
733 <refentry id="usbs-start">
734 <refmeta>
735 <refentrytitle>Starting up a USB Device</refentrytitle>
736 </refmeta>
737 <refnamediv>
738 <refname><function>usbs_start</function></refname>
739 <refpurpose>Starting up a USB Device</refpurpose>
740 </refnamediv>
741
742 <refsynopsisdiv>
743 <funcsynopsis>
744 <funcsynopsisinfo>
745 #include &lt;cyg/io/usb/usbs.h&gt;
746 </funcsynopsisinfo>
747 <funcprototype>
748 <funcdef>void <function>usbs_start</function></funcdef>
749 <paramdef>usbs_control_endpoint* <parameter>ep0</parameter></paramdef>
750 </funcprototype>
751 </funcsynopsis>
752 </refsynopsisdiv>
753
754 <refsect1><title>Description</title>
755 <para>
756 Initializing a USB device requires some support from higher-level
757 code, typically the application, in the form of enumeration data.
758 Hence it is not possible for the low-level USB driver to activate a
759 USB device itself. Instead the higher-level code has to take care of
760 this by invoking <function>usbs_start</function>. This function takes
761 a pointer to a USB control endpoint data structure. USB device drivers
762 should provide exactly one such data structure for every USB device,
763 so the pointer uniquely identifies the device.
764 </para>
765 <programlisting width=72>
766 const usbs_enumeration_data usb_enum_data = {
767     &hellip;
768 };
769
770 int
771 main(int argc, char** argv)
772 {
773     usbs_sa11x0_ep0.enumeration_data = &amp;usb_enum_data;
774     &hellip;
775     usbs_start(&amp;usbs_sa11x0_ep0);
776     &hellip;
777 }
778 </programlisting>
779 <para>
780 The exact behaviour of <function>usbs_start</function> depends on the
781 USB hardware and the device driver. A typical implementation would
782 change the USB data pins from tristated to active. If the peripheral
783 is already plugged into a host then the latter should detect this
784 change and start interacting with the peripheral, including requesting
785 the enumeration data. Some of this may happen before
786 <function>usbs_start</function> returns, but given that multiple
787 interactions between USB host and peripheral are required it is likely
788 that the function will return before the peripheral is fully
789 configured. Control endpoints provide a <link
790 linkend="usbs-control-state">mechanism</link> for informing
791 higher-level code of USB state changes.
792 <function>usbs_start</function> will return even if the peripheral is
793 not currently connected to a host: it will not block until the
794 connection is established.
795 </para>
796 <para>
797 <function>usbs_start</function> should only be called once for a given
798 USB device. There are no defined error conditions. Note that the
799 function affects the entire USB device and not just the control
800 endpoint: there is no need to start any data endpoints as well.
801 </para>
802 </refsect1>
803 </refentry>
804
805 <!-- }}} -->
806 <!-- {{{ Devtab Entries                 -->
807
808 <refentry id="usbs-devtab">
809 <refmeta>
810 <refentrytitle>Devtab Entries</refentrytitle>
811 </refmeta>
812 <refnamediv>
813 <refname>Devtab Entries</refname>
814 <refpurpose>Data endpoint data structure</refpurpose>
815 </refnamediv>
816
817 <refsynopsisdiv>
818 <synopsis>
819 /dev/usb0c
820 /dev/usb1r
821 /dev/usb2w
822 </synopsis>
823 </refsynopsisdiv>
824
825 <refsect1><title>Devtab Entries</title>
826 <para>
827 USB device drivers provide two ways of transferring data between host
828 and peripheral. The first involves USB-specific functionality such as
829 <link
830 linkend="usbs-start-rx"><function>usbs_start_rx_buffer</function></link>.
831 This provides non-blocking I/O: a transfer is started, and some time
832 later the device driver will call a supplied completion function. The
833 second uses the conventional I/O model: there are entries in the
834 device table corresponding to the various endpoints. Standard calls
835 such as <function>open</function> can then be used to get a suitable
836 handle. Actual I/O happens via blocking <function>read</function> and
837 <function>write</function> calls. In practice the blocking operations
838 are simply implemented using the underlying non-blocking
839 functionality.
840 </para>
841 <para>
842 Each endpoint will have its own devtab entry. The exact names are
843 controlled by the device driver package, but typically the root will
844 be <literal>/dev/usb</literal>. This is followed by one or more
845 decimal digits giving the endpoint number, followed by
846 <literal>c</literal> for a control endpoint, <literal>r</literal> for
847 a receive endpoint (host to peripheral), and <literal>w</literal> for
848 a transmit endpoint (peripheral to host). If the target hardware
849 involves more than one USB device then different roots should be used,
850 for example <literal>/dev/usb0c</literal> and
851 <literal>/dev/usb1_0c</literal>. This may require explicit
852 manipulation of device driver configuration options by the application
853 developer.
854 </para>
855 <para>
856 At present the devtab entry for a control endpoint does not support
857 any I/O operations. 
858 </para>
859
860 <refsect2><title><function>write</function> operations</title>
861 <para>
862 <function>cyg_io_write</function> and similar functions in
863 higher-level packages can be used to perform a transfer from
864 peripheral to host. Successive write operations will not be coalesced.
865 For example, when doing a 1000 byte write to an endpoint that uses the
866 bulk transfer protocol this will involve 15 full-size 64-byte packets
867 and a terminating 40-byte packet. USB device drivers are not expected
868 to do any locking, and if higher-level code performs multiple
869 concurrent write operations on a single endpoint then the resulting
870 behaviour is undefined.
871 </para>
872 <para>
873 A USB <function>write</function> operation will never transfer less
874 data than specified. It is the responsibility of higher-level code to
875 ensure that the amount of data being transferred is acceptable to the
876 host-side code. Usually this will be defined by a higher-level
877 protocol. If an attempt is made to transfer more data than the host
878 expects then the resulting behaviour is undefined.
879 </para>
880 <para>
881 There are two likely error conditions. <literal>EPIPE</literal>
882 indicates that the connection between host and target has been broken.
883 <literal>EAGAIN</literal> indicates that the endpoint has been
884 stalled, either at the request of the host or by other activity
885 inside the peripheral.
886 </para>
887 </refsect2>
888
889 <refsect2><title><function>read</function> operations</title>
890 <para>
891 <function>cyg_io_read</function> and similar functions in higher-level
892 packages can be used to perform a transfer from host to peripheral.
893 This should be a complete transfer: higher-level protocols should
894 define an upper bound on the amount of data being transferred, and the
895 <function>read</function> operation should involve at least this
896 amount of data. The return value will indicate the actual transfer
897 size, which may be less than requested.
898 </para>
899 <para>
900 Some device drivers may support partial reads, but USB device drivers
901 are not expected to perform any buffering because that involves both
902 memory and code overheads. One technique that may work for bulk
903 transfers is to exploit the fact that such transfers happen in 64-byte
904 packets. It is possible to <function>read</function> an initial 64
905 bytes, corresponding to the first packet in the transfer. These 64
906 bytes can then be examined to determine the total transfer size, and
907 the remaining data can be transferred in another
908 <function>read</function> operation. This technique is not guaranteed
909 to work with all USB hardware. Also, if the delay between accepting
910 the first packet and the remainder of the transfer is excessive then
911 this could cause timeout problems for the host-side software. For
912 these reasons the use of partial reads should be avoided.
913 </para>
914 <para>
915 There are two likely error conditions. <literal>EPIPE</literal>
916 indicates that the connection between host and target has been broken.
917 <literal>EAGAIN</literal> indicates that the endpoint has been
918 stalled, either at the request of the host or by other activity
919 inside the peripheral.
920 </para>
921 <para>
922 USB device drivers are not expected to do any locking. If higher-level
923 code performs multiple concurrent read operations on a single endpoint
924 then the resulting behaviour is undefined.
925 </para>
926 </refsect2>
927
928 <refsect2><title><function>select</function> operations</title>
929 <para>
930 Typical USB device drivers will not provide any support for
931 <function>select</function>. Consider bulk transfers from the host to
932 the peripheral. At the USB device driver level there is no way of
933 knowing in advance how large a transfer will be, so it is not feasible
934 for the device driver to buffer the entire transfer. It may be
935 possible to buffer part of the transfer, for example the first 64-byte
936 packet, and copy this into application space at the start of a
937 <function>read</function>, but this adds code and memory overheads.
938 Worse, it means that there is an unknown but potentially long delay
939 between a peripheral accepting the first packet of a transfer and the
940 remaining packets, which could confuse or upset the host-side
941 software.
942 </para>
943 <para>
944 With some USB hardware it may be possible for the device driver to
945 detect OUT tokens from the host without actually accepting the data,
946 and this would indicate that a  <function>read</function> is likely to
947 succeed. However, it would not be reliable since the host-side I/O
948 operation could time out. A similar mechanism could be used to
949 implement <function>select</function> for outgoing data, but again
950 this would not be reliable.
951 </para>
952 <para>
953 Some device drivers may provide partial support for
954 <function>select</function> anyway, possibly under the control of a
955 configuration option. The device driver's documentation should be
956 consulted for further information. It is also worth noting that the
957 USB-specific non-blocking API can often be used as an alternative to
958 <function>select</function>.
959 </para>
960 </refsect2>
961
962 <refsect2><title><function>get_config</function> and
963 <function>set_config</function> operations</title>
964 <para>
965 There are no <function>set_config</function> or
966 <function>get_config</function> (also known as
967 <function>ioctl</function>) operations defined for USB devices.
968 Some device drivers may provide hardware-specific facilities this way. 
969 </para>
970 <note>
971 <para>
972 Currently the USB-specific functions related to <link
973 linkend="usbs-halt">halted endpoints</link> cannot be accessed readily
974 via devtab entries. This functionality should probably be made
975 available via <function>set_config</function> and
976 <function>get_config</function>. It may also prove useful to provide
977 a <function>get_config</function> operation that maps from the
978 devtab entries to the underlying endpoint data structures.
979 </para>
980 </note>
981 </refsect2>
982
983 <refsect2><title>Presence</title>
984 <para>
985 The devtab entries are optional. If the USB device is accessed
986 primarily by class-specific code such as the USB-ethernet package and
987 that package uses the USB-specific API directly, the devtab entries
988 are redundant. Even if application code does need to access the USB
989 device, the non-blocking API may be more convenient than the blocking
990 I/O provided via the devtab entries. In these cases the devtab entries
991 serve no useful purpose, but they still impose a memory overhead. It
992 is possible to suppress the presence of these entries by disabling the
993 configuration option
994 <literal>CYGGLO_IO_USB_SLAVE_PROVIDE_DEVTAB_ENTRIES</literal>.
995 </para>
996 </refsect2>
997 </refsect1>
998 </refentry>
999
1000 <!-- }}} -->
1001 <!-- {{{ usbs_start_rx_buffer()         -->
1002
1003 <refentry id="usbs-start-rx">
1004 <refmeta>
1005 <refentrytitle>Receiving Data from the Host</refentrytitle>
1006 </refmeta>
1007 <refnamediv>
1008 <refname><function>usbs_start_rx_buffer</function></refname>
1009 <refpurpose>Receiving Data from the Host</refpurpose>
1010 </refnamediv>
1011
1012 <refsynopsisdiv>
1013 <funcsynopsis>
1014 <funcsynopsisinfo>
1015 #include &lt;cyg/io/usb/usbs.h&gt;
1016 </funcsynopsisinfo>
1017 <funcprototype>
1018 <funcdef>void <function>usbs_start_rx_buffer</function></funcdef>
1019 <paramdef>usbs_rx_endpoint* <parameter>ep</parameter></paramdef>
1020 <paramdef>unsigned char* <parameter>buffer</parameter></paramdef>
1021 <paramdef>int <parameter>length</parameter></paramdef>
1022 <paramdef>void (*)(void*,int) <parameter>complete_fn</parameter></paramdef>
1023 <paramdef>void * <parameter>complete_data</parameter></paramdef>
1024 </funcprototype>
1025
1026 <funcprototype>
1027 <funcdef>void <function>usbs_start_rx</function></funcdef>
1028 <paramdef>usbs_rx_endpoint* <parameter>ep</parameter></paramdef>
1029 </funcprototype>
1030
1031 </funcsynopsis>
1032 </refsynopsisdiv>
1033
1034 <refsect1><title><function>Description</function></title>
1035 <para>
1036 <function>usbs_start_rx_buffer</function> is a USB-specific function
1037 to accept a transfer from host to peripheral. It can be used for bulk,
1038 interrupt or isochronous transfers, but not for control messages.
1039 Instead those involve manipulating the <link
1040 linkend="usbs-control"><structname>usbs_control_endpoint</structname></link>
1041 data structure directly. The function takes five arguments:
1042 </para>
1043 <orderedlist>
1044 <listitem>
1045 <para>
1046 The first argument identifies the specific endpoint that should be
1047 used. Different USB devices will support different sets of endpoints
1048 and the device driver will provide appropriate data structures. The
1049 device driver's documentation should be consulted for details of which
1050 endpoints are available.
1051 </para>
1052 </listitem>
1053 <listitem>
1054 <para>
1055 The <parameter>buffer</parameter> and <parameter>length</parameter>
1056 arguments control the actual transfer. USB device drivers are not
1057 expected to perform any buffering or to support partial transfers, so
1058 the length specified should correspond to the maximum transfer that is
1059 currently possible and the buffer should be at least this large. For
1060 isochronous transfers the USB specification imposes an upper bound of
1061 1023 bytes, and a smaller limit may be set in the <link
1062 linkend="usbs-enum-endpoint">enumeration data</link>. Interrupt
1063 transfers are similarly straightforward with an upper bound of 64
1064 bytes, or less as per the enumeration data. Bulk transfers are more
1065 complicated because they can involve multiple 64-byte packets plus a
1066 terminating packet of less than 64 bytes, so there is no predefined
1067 limit on the transfer size. Instead it is left to higher-level
1068 protocols to specify an appropriate upper bound.
1069 </para>
1070 <para>
1071 One technique that may work for bulk transfers is to exploit the fact
1072 that such transfers happen in 64-byte packets: it may be possible to
1073 receive an initial 64 bytes, corresponding to the first packet in the
1074 transfer; these 64 bytes can then be examined to determine the total
1075 transfer size, and the remaining data can be transferred in another
1076 receive operation. This technique is not guaranteed to work with all
1077 USB hardware. Also, if the delay between accepting the first packet and
1078 the remainder of the transfer is excessive then this could cause
1079 timeout problems for the host-side software. For these reasons this
1080 technique should be avoided.
1081 </para>
1082 </listitem>
1083 <listitem>
1084 <para>
1085 <function>usbs_start_rx_buffer</function> is non-blocking. It merely
1086 starts the receive operation, and does not wait for completion. At
1087 some later point the USB device driver will invoke the completion
1088 function parameter with two arguments: the completion data defined by
1089 the last parameter and a result field. A result &gt;=
1090 <literal>0</literal> indicates a successful transfer of that many
1091 bytes, which may be less than the upper bound imposed by the
1092 <parameter>length</parameter> argument. A result &lt;
1093 <literal>0</literal> indicates an error. The most likely errors are
1094 <literal>-EPIPE</literal> to indicate that the connection between the
1095 host and the target has been broken, and <literal>-EAGAIN</literal>
1096 for when the endpoint has been <link
1097 linkend="usbs-halt">halted</link>. Specific USB device drivers may
1098 specify additional error conditions.
1099 </para>
1100 </listitem>
1101 </orderedlist>
1102 <para>
1103 The normal sequence of events is that the USB device driver will
1104 update the appropriate hardware registers. At some point after that
1105 the host will attempt to send data by transmitting an OUT token
1106 followed by a data packet, and since a receive operation is now in
1107 progress the data will be accepted and ACK'd. If there were no receive
1108 operation then the peripheral would instead generate a NAK. The USB
1109 hardware will generate an interrupt once the whole packet has been
1110 received, and the USB device driver will service this interrupt and
1111 arrange for a DSR to be called. Isochronous and interrupt transfers
1112 involve just a single packet. However, bulk transfers may involve
1113 multiple packets so the device driver has to check whether the packet
1114 was a full 64 bytes or whether it was a terminating packet of less
1115 than this. When the device driver DSR detects a complete transfer it
1116 will inform higher-level code by invoking the supplied completion
1117 function.
1118 </para>
1119 <para>
1120 This means that the completion function will normally be invoked by a
1121 DSR and not in thread context - although some USB device drivers may
1122 have a different implementation. Therefore the completion function is
1123 restricted in what it can do. In particular it must not make any
1124 calls that will or may block such as locking a mutex or allocating
1125 memory. The kernel documentation should be consulted for more details
1126 of DSR's and interrupt handling generally.
1127 </para>
1128 <para>
1129 It is possible that the completion function will be invoked before
1130 <function>usbs_start_rx_buffer</function> returns. Such an event would
1131 be unusual because the transfer cannot happen until the next time the
1132 host tries to send data to this peripheral, but it may happen if for
1133 example another interrupt happens and a higher priority thread is
1134 scheduled to run. Also, if the endpoint is currently halted then the
1135 completion function will be invoked immediately with
1136 <literal>-EAGAIN</literal>: typically this will happen in the current
1137 thread rather than in a separate DSR. The completion function is
1138 allowed to start another transfer immediately by calling
1139 <function>usbs_start_rx_buffer</function> again.
1140 </para>
1141 <para>
1142 USB device drivers are not expected to perform any locking. It is the
1143 responsibility of higher-level code to ensure that there is only one
1144 receive operation for a given endpoint in progress at any one time. If
1145 there are concurrent calls to
1146 <function>usbs_start_rx_buffer</function> then the resulting behaviour
1147 is undefined. For typical USB applications this does not present any
1148 problems, because only one piece of code will access a given endpoint
1149 at any particular time.
1150 </para>
1151 <para>
1152 The following code fragment illustrates a very simple use of
1153 <function>usbs_start_rx_buffer</function> to implement a blocking
1154 receive, using a semaphore to synchronise between the foreground
1155 thread and the DSR. For a simple example like this no completion data
1156 is needed.
1157 </para>
1158 <programlisting width=72>
1159 static int error_code = 0;
1160 static cyg_sem_t completion_wait;
1161
1162 static void
1163 completion_fn(void* data, int result)
1164 {
1165     error_code = result;
1166     cyg_semaphore_post(&amp;completion_wait);
1167 }
1168
1169 int
1170 blocking_receive(usbs_rx_endpoint* ep, unsigned char* buf, int len)
1171 {
1172     error_code = 0;
1173     usbs_start_rx_buffer(ep, buf, len, &amp;completion_fn, NULL);
1174     cyg_semaphore_wait(&amp;completion_wait);
1175     return error_code;
1176 }
1177 </programlisting>
1178 <para>
1179 There is also a utility function <function>usbs_start_rx</function>. This
1180 can be used by code that wants to manipulate <link
1181 linkend="usbs-data">data endpoints</link> directly, specifically the
1182 <structfield>complete_fn</structfield>,
1183 <structfield>complete_data</structfield>,
1184 <structfield>buffer</structfield> and
1185 <structfield>buffer_size</structfield> fields.
1186 <function>usbs_start_tx</function> just invokes a function
1187 supplied by the device driver.
1188 </para>
1189 </refsect1>
1190 </refentry>
1191
1192 <!-- }}} -->
1193 <!-- {{{ usbs_start_tx_buffer()         -->
1194
1195 <refentry id="usbs-start-tx">
1196 <refmeta>
1197 <refentrytitle>Sending Data to the Host</refentrytitle>
1198 </refmeta>
1199 <refnamediv>
1200 <refname><function>usbs_start_tx_buffer</function></refname>
1201 <refpurpose>Sending Data to the Host</refpurpose>
1202 </refnamediv>
1203
1204 <refsynopsisdiv>
1205 <funcsynopsis>
1206 <funcsynopsisinfo>
1207 #include &lt;cyg/io/usb/usbs.h&gt;
1208 </funcsynopsisinfo>
1209 <funcprototype>
1210 <funcdef>void <function>usbs_start_tx_buffer</function></funcdef>
1211 <paramdef>usbs_tx_endpoint* <parameter>ep</parameter></paramdef>
1212 <paramdef>const unsigned char* <parameter>buffer</parameter></paramdef>
1213 <paramdef>int <parameter>length</parameter></paramdef>
1214 <paramdef>void (*)(void*,int) <parameter>complete_fn</parameter></paramdef>
1215 <paramdef>void * <parameter>complete_data</parameter></paramdef>
1216 </funcprototype>
1217
1218 <funcprototype>
1219 <funcdef>void <function>usbs_start_tx</function></funcdef>
1220 <paramdef>usbs_tx_endpoint* <parameter>ep</parameter></paramdef>
1221 </funcprototype>
1222
1223 </funcsynopsis>
1224 </refsynopsisdiv>
1225
1226 <refsect1><title><function>Description</function></title>
1227 <para>
1228 <function>usbs_start_tx_buffer</function> is a USB-specific function
1229 to transfer data from peripheral to host. It can be used for bulk,
1230 interrupt or isochronous transfers, but not for control messages;
1231 instead those involve manipulating the <link
1232 linkend="usbs-control"><structname>usbs_control_endpoint</structname></link>
1233 data structure directly. The function takes five arguments:
1234 </para>
1235 <orderedlist>
1236 <listitem>
1237 <para>
1238 The first argument identifies the specific endpoint that should be
1239 used. Different USB devices will support different sets of endpoints
1240 and the device driver will provide appropriate data structures. The
1241 device driver's documentation should be consulted for details of which
1242 endpoints are available.
1243 </para>
1244 </listitem>
1245 <listitem>
1246 <para>
1247 The <parameter>buffer</parameter> and <parameter>length</parameter>
1248 arguments control the actual transfer. USB device drivers are not
1249 allowed to modify the buffer during the transfer, so the data can
1250 reside in read-only memory. The transfer will be for all the data
1251 specified, and it is the responsibility of higher-level code to make
1252 sure that the host is expecting this amount of data. For isochronous
1253 transfers the USB specification imposes an upper bound of 1023 bytes,
1254 but a smaller limit may be set in the <link
1255 linkend="usbs-enum-endpoint">enumeration data</link>. Interrupt
1256 transfers have an upper bound of 64 bytes or less, as per the
1257 enumeration data. Bulk transfers are more complicated because they can
1258 involve multiple 64-byte packets plus a terminating packet of less
1259 than 64 bytes, so the basic USB specification does not impose an upper
1260 limit on the total transfer size. Instead it is left to higher-level
1261 protocols to specify an appropriate upper bound. If the peripheral
1262 attempts to send more data than the host is willing to accept then the
1263 resulting behaviour is undefined and may well depend on the specific
1264 host operating system being used.
1265 </para>
1266 <para>
1267 For bulk transfers, the USB device driver or the underlying hardware
1268 will automatically split the transfer up into the appropriate number
1269 of full-size 64-byte packets plus a single terminating packet, which
1270 may be 0 bytes.
1271 </para>
1272 </listitem>
1273 <listitem>
1274 <para>
1275 <function>usbs_start_tx_buffer</function> is non-blocking. It merely
1276 starts the transmit operation, and does not wait for completion. At
1277 some later point the USB device driver will invoke the completion
1278 function parameter with two arguments: the completion data defined by
1279 the last parameter, and a result field. This result will be either an
1280 error code &lt; <literal>0</literal>, or the amount of data
1281 transferred which should correspond to the
1282 <parameter>length</parameter> argument. The most likely errors are
1283 <literal>-EPIPE</literal> to indicate that the connection between the
1284 host and the target has been broken, and <literal>-EAGAIN</literal>
1285 for when the endpoint has been <link
1286 linkend="usbs-halt">halted</link>. Specific USB device drivers may
1287 define additional error conditions.
1288 </para>
1289 </listitem>
1290 </orderedlist>
1291 <para>
1292 The normal sequence of events is that the USB device driver will
1293 update the appropriate hardware registers. At some point after that
1294 the host will attempt to fetch data by transmitting an IN token. Since
1295 a transmit operation is now in progress the peripheral can send a
1296 packet of data, and the host will generate an ACK. At this point the
1297 USB hardware will generate an interrupt, and the device driver will
1298 service this interrupt and arrange for a DSR to be called. Isochronous
1299 and interrupt transfers involve just a single packet. However, bulk
1300 transfers may involve multiple packets so the device driver has to
1301 check whether there is more data to send and set things up for the
1302 next packet. When the device driver DSR detects a complete transfer it
1303 will inform higher-level code by invoking the supplied completion
1304 function.
1305 </para>
1306 <para>
1307 This means that the completion function will normally be invoked by a
1308 DSR and not in thread context - although some USB device drivers may
1309 have a different implementation. Therefore the completion function is
1310 restricted in what it can do, in particular it must not make any
1311 calls that will or may block such as locking a mutex or allocating
1312 memory. The kernel documentation should be consulted for more details
1313 of DSR's and interrupt handling generally.
1314 </para>
1315 <para>
1316 It is possible that the completion function will be invoked before
1317 <function>usbs_start_tx_buffer</function> returns. Such an event would
1318 be unusual because the transfer cannot happen until the next time the
1319 host tries to fetch data from this peripheral, but it may happen if,
1320 for example, another interrupt happens and a higher priority thread is
1321 scheduled to run. Also, if the endpoint is currently halted then the
1322 completion function will be invoked immediately with
1323 <literal>-EAGAIN</literal>: typically this will happen in the current
1324 thread rather than in a separate DSR. The completion function is
1325 allowed to start another transfer immediately by calling
1326 <function>usbs_start_tx_buffer</function> again.
1327 </para>
1328 <para>
1329 USB device drivers are not expected to perform any locking. It is the
1330 responsibility of higher-level code to ensure that there is only one
1331 transmit operation for a given endpoint in progress at any one time.
1332 If there are concurrent calls to
1333 <function>usbs_start_tx_buffer</function> then the resulting behaviour
1334 is undefined. For typical USB applications this does not present any
1335 problems because only piece of code will access a given endpoint at
1336 any particular time.
1337 </para>
1338 <para>
1339 The following code fragment illustrates a very simple use of
1340 <function>usbs_start_tx_buffer</function> to implement a blocking
1341 transmit, using a semaphore to synchronise between the foreground
1342 thread and the DSR. For a simple example like this no completion data
1343 is needed.
1344 </para>
1345 <programlisting width=72>
1346 static int error_code = 0;
1347 static cyg_sem_t completion_wait;
1348
1349 static void
1350 completion_fn(void* data, int result)
1351 {
1352     error_code = result;
1353     cyg_semaphore_post(&amp;completion_wait);
1354 }
1355
1356 int
1357 blocking_transmit(usbs_tx_endpoint* ep, const unsigned char* buf, int len)
1358 {
1359     error_code = 0;
1360     usbs_start_tx_buffer(ep, buf, len, &amp;completion_fn, NULL);
1361     cyg_semaphore_wait(&amp;completion_wait);
1362     return error_code;
1363 }
1364 </programlisting>
1365 <para>
1366 There is also a utility function <function>usbs_start</function>. This
1367 can be used by code that wants to manipulate <link
1368 linkend="usbs-data">data endpoints</link> directly, specifically the
1369 <structfield>complete_fn</structfield>,
1370 <structfield>complete_data</structfield>,
1371 <structfield>buffer</structfield> and
1372 <structfield>buffer_size</structfield> fields.
1373 <function>usbs_start_tx</function> just calls a function supplied by
1374 the device driver.
1375 </para>
1376 </refsect1>
1377 </refentry>
1378
1379 <!-- }}} -->
1380 <!-- {{{ Halted endpoints               -->
1381
1382 <refentry id="usbs-halt">
1383 <refmeta>
1384 <refentrytitle>Halted Endpoints</refentrytitle>
1385 </refmeta>
1386 <refnamediv>
1387 <refname>Halted Endpoints</refname>
1388 <refpurpose>Support for Halting and Halted Endpoints</refpurpose>
1389 </refnamediv>
1390
1391 <refsynopsisdiv>
1392 <funcsynopsis>
1393
1394 <funcsynopsisinfo>
1395 #include &lt;cyg/io/usb/usbs.h&gt;
1396 </funcsynopsisinfo>
1397
1398 <funcprototype>
1399 <funcdef>cyg_bool <function>usbs_rx_endpoint_halted</function></funcdef>
1400 <paramdef>usbs_rx_endpoint* <parameter>ep</parameter></paramdef>
1401 </funcprototype>
1402 <funcprototype>
1403 <funcdef>void <function>usbs_set_rx_endpoint_halted</function></funcdef>
1404 <paramdef>usbs_rx_endpoint* <parameter>ep</parameter></paramdef>
1405 <paramdef>cyg_bool <parameter>new_state</parameter></paramdef>
1406 </funcprototype>
1407 <funcprototype>
1408 <funcdef>void <function>usbs_start_rx_endpoint_wait</function></funcdef>
1409 <paramdef>usbs_rx_endpoint* <parameter>ep</parameter></paramdef>
1410 <paramdef>void (*)(void*, int) <parameter>complete_fn</parameter></paramdef>
1411 <paramdef>void * <parameter>complete_data</parameter></paramdef>
1412 </funcprototype>
1413
1414 <funcprototype>
1415 <funcdef>cyg_bool
1416 <function>usbs_tx_endpoint_halted</function></funcdef>
1417 <paramdef>usbs_tx_endpoint* <parameter>ep</parameter></paramdef>
1418 </funcprototype>
1419 <funcprototype>
1420 <funcdef>void <function>usbs_set_tx_endpoint_halted</function></funcdef>
1421 <paramdef>usbs_tx_endpoint* <parameter>ep</parameter></paramdef>
1422 <paramdef>cyg_bool <parameter>new_state</parameter></paramdef>
1423 </funcprototype>
1424 <funcprototype>
1425 <funcdef>void <function>usbs_start_tx_endpoint_wait</function></funcdef>
1426 <paramdef>usbs_tx_endpoint* <parameter>ep</parameter></paramdef>
1427 <paramdef>void (*)(void*, int) <parameter>complete_fn</parameter></paramdef>
1428 <paramdef>void * <parameter>complete_data</parameter></paramdef>
1429 </funcprototype>
1430
1431 </funcsynopsis>
1432 </refsynopsisdiv>
1433
1434 <refsect1><title><function>Description</function></title>
1435 <para>
1436 Normal USB traffic involves straightforward handshakes, with either an
1437 <literal>ACK</literal> to indicate that a packet was transferred
1438 without errors, or a <literal>NAK</literal> if an error occurred, or
1439 if a peripheral is currently unable to process another packet from the
1440 host, or has no packet to send to the host. There is a third form of
1441 handshake, a <literal>STALL</literal>, which indicates that the
1442 endpoint is currently <emphasis>halted</emphasis>.
1443 </para>
1444 <para>
1445 When an endpoint is halted it means that the host-side code needs to
1446 take some sort of recovery action before communication over that
1447 endpoint can resume. The exact circumstances under which this can
1448 happen are not defined by the USB specification, but one example would
1449 be a protocol violation if say the peripheral attempted to transmit
1450 more data to the host than was permitted by the protocol in use. The
1451 host can use the standard control messages get-status, set-feature and
1452 clear-feature to examine and manipulate the halted status of a given
1453 endpoint. There are USB-specific functions which can be used inside
1454 the peripheral to achieve the same effect. Once an endpoint has been
1455 halted the host can then interact with the peripheral using class or
1456 vendor control messages to perform appropriate recovery, and then the
1457 halted condition can be cleared.
1458 </para>
1459 <para>
1460 Halting an endpoint does not constitute a device state change, and
1461 there is no mechanism by which higher-level code can be informed
1462 immediately. However, any ongoing receive or transmit operations will
1463 be aborted with an <literal>-EAGAIN</literal> error, and any new
1464 receives or transmits will fail immediately with the same error.
1465 </para>
1466 <para>
1467 There are six functions to support halted endpoints, one set for
1468 receive endpoints and another for transmit endpoints, with both sets
1469 behaving in essentially the same way. The first,
1470 <function>usbs_rx_endpoint_halted</function>, can be used to determine
1471 whether or not an endpoint is currently halted: it takes a single
1472 argument that identifies the endpoint of interest. The second
1473 function, <function>usbs_set_rx_endpoint_halted</function>, can be
1474 used to change the halted condition of an endpoint: it takes two
1475 arguments; one to identify the endpoint and another to specify the new
1476 state. The last function
1477 <function>usbs_start_rx_endpoint_wait</function> operates in much the
1478 same way as <function>usbs_start_rx_buffer</function>: when the
1479 endpoint is no longer halted the device driver will invoke the
1480 supplied completion function with a status of 0. The completion
1481 function has the same signature as that for a transfer operation.
1482 Often it will be possible to use a single completion function and have
1483 the foreground code invoke either
1484 <function>usbs_start_rx_buffer</function> or
1485 <function>usbs_start_rx_endpoint_wait</function> depending on the
1486 current state of the endpoint.
1487 </para>
1488 </refsect1>
1489 </refentry>
1490
1491 <!-- }}} -->
1492 <!-- {{{ Control Endpoint               -->
1493
1494 <refentry id="usbs-control">
1495 <refmeta>
1496 <refentrytitle>Control Endpoints</refentrytitle>
1497 </refmeta>
1498 <refnamediv>
1499 <refname>Control Endpoints</refname>
1500 <refpurpose>Control endpoint data structure</refpurpose>
1501 </refnamediv>
1502
1503 <refsynopsisdiv>
1504 <synopsis>
1505 #include &lt;cyg/io/usb/usbs.h&gt;
1506
1507 typedef struct usbs_control_endpoint {
1508     *hellip;
1509 } usbs_control_endpoint;
1510 </synopsis>
1511 </refsynopsisdiv>
1512
1513 <refsect1><title><literal>usbs_control_endpoint</literal> Data Structure</title>
1514 <para>
1515 The device driver for a USB slave device should supply one
1516 <structname>usbs_control_endpoint</structname> data structure per USB
1517 device. This corresponds to endpoint 0 which will be used for all
1518 control message interaction between the host and that device. The data
1519 structure is also used for internal management purposes, for example
1520 to keep track of the current state. In a typical USB peripheral there
1521 will only be one such data structure in the entire system, but if
1522 there are multiple USB slave ports, allowing the peripheral to be
1523 connected to multiple hosts, then there will be a separate data
1524 structure for each one. The name or names of the data structures are
1525 determined by the device drivers. For example, the SA11x0 USB device
1526 driver package provides <literal>usbs_sa11x0_ep0</literal>.
1527 </para>
1528 <para>
1529 The operations on a control endpoint do not fit cleanly into a
1530 conventional open/read/write I/O model. For example, when the host
1531 sends a control message to the USB peripheral this may be one of four
1532 types: standard, class, vendor and reserved. Some or all of the
1533 standard control messages will be handled automatically by the common
1534 USB slave package or by the device driver itself. Other standard
1535 control messages and the other types of control messages may be
1536 handled by a class-specific package or by application code. Although
1537 it would be possible to have devtab entries such as
1538 <literal>/dev/usbs_ep0/standard</literal> and
1539 <literal>/dev/usbs_ep0/class</literal>, and then support read and
1540 write operations on these devtab entries, this would add significant
1541 overhead and code complexity. Instead, all of the fields in the
1542 control endpoint data structure are public and can be manipulated
1543 directly by higher level code if and when required. 
1544 </para>
1545 <para>
1546 Control endpoints involve a number of callback functions, with
1547 higher-level code installing suitable function pointers in the control
1548 endpoint data structure. For example, if the peripheral involves
1549 vendor-specific control messages then a suitable handler for these
1550 messages should be installed. Although the exact details depend on the
1551 device driver, typically these callback functions will be invoked at
1552 DSR level rather than thread level. Therefore, only certain eCos
1553 functions can be invoked; specifically, those functions that are
1554 guaranteed not to block. If a potentially blocking function such as a
1555 semaphore wait or a mutex lock operation is invoked from inside the
1556 callback then the resulting behaviour is undefined, and the system as
1557 a whole may fail. In addition, if one of the callback functions
1558 involves significant processing effort then this may adversely affect
1559 the system's real time characteristics. The eCos kernel documentation
1560 should be consulted for more details of DSR handling.
1561 </para>
1562
1563 <refsect2><title>Initialization</title>
1564 <para>
1565 The <structname>usbs_control_endpoint</structname> data structure
1566 contains the following fields related to initialization.
1567 </para>
1568 <programlisting width=72>
1569 typedef struct usbs_control_endpoint {
1570     &hellip;
1571     const usbs_enumeration_data* enumeration_data;
1572     void                         (*start_fn)(usbs_control_endpoint*);
1573     &hellip;
1574 };
1575 </programlisting>
1576 <para>
1577 It is the responsibility of higher-level code, usually the
1578 application, to define the USB enumeration data. This needs to be
1579 installed in the control endpoint data structure early on during
1580 system startup, before the USB device is actually started and any
1581 interaction with the host is possible. Details of the enumeration data
1582 are supplied in the section <link linkend="usbs-enum">USB Enumeration
1583 Data</link>. Typically, the enumeration data is constant for a given
1584 peripheral, although it can be constructed dynamically if necessary.
1585 However, the enumeration data cannot change while the peripheral is
1586 connected to a host: the peripheral cannot easily claim to be a
1587 keyboard one second and a printer the next.
1588 </para>
1589 <para>
1590 The <structfield>start_fn</structfield> member is normally accessed
1591 via the utility <link
1592 linkend="usbs-start"><function>usbs_start</function></link> rather
1593 than directly. It is provided by the device driver and should be
1594 invoked once the system is fully initialized and interaction with the
1595 host is possible. A typical implementation would change the USB data
1596 pins from tristated to active. If the peripheral is already plugged
1597 into a host then the latter should detect this change and start
1598 interacting with the peripheral, including requesting the enumeration
1599 data.
1600 </para>
1601 </refsect2>
1602
1603 <refsect2><title id="usbs-control-state">State</title>
1604 <para>
1605 There are three <structname>usbs_control_endpoint</structname> fields
1606 related to the current state of a USB slave device, plus some state
1607 constants and an enumeration of the possible state changes:
1608 </para>
1609 <programlisting width=72>
1610 typedef struct usbs_control_endpoint {
1611     &hellip;
1612     int     state;
1613     void    (*state_change_fn)(struct usbs_control_endpoint*, void*,
1614                                usbs_state_change, int);
1615     void*   state_change_data;
1616     &hellip;
1617 };
1618
1619 #define USBS_STATE_DETACHED             0x01
1620 #define USBS_STATE_ATTACHED             0x02
1621 #define USBS_STATE_POWERED              0x03
1622 #define USBS_STATE_DEFAULT              0x04
1623 #define USBS_STATE_ADDRESSED            0x05
1624 #define USBS_STATE_CONFIGURED           0x06
1625 #define USBS_STATE_MASK                 0x7F
1626 #define USBS_STATE_SUSPENDED            (1 &lt;&lt; 7)
1627
1628 typedef enum {
1629     USBS_STATE_CHANGE_DETACHED          = 1,
1630     USBS_STATE_CHANGE_ATTACHED          = 2,
1631     USBS_STATE_CHANGE_POWERED           = 3,
1632     USBS_STATE_CHANGE_RESET             = 4,    
1633     USBS_STATE_CHANGE_ADDRESSED         = 5,
1634     USBS_STATE_CHANGE_CONFIGURED        = 6,
1635     USBS_STATE_CHANGE_DECONFIGURED      = 7,    
1636     USBS_STATE_CHANGE_SUSPENDED         = 8,
1637     USBS_STATE_CHANGE_RESUMED           = 9
1638 } usbs_state_change;
1639 </programlisting>
1640 <para>
1641 The USB standard defines a number of states for a given USB
1642 peripheral. The initial state is <emphasis>detached</emphasis>, where
1643 the peripheral is either not connected to a host at all or, from the
1644 host's perspective, the peripheral has not started up yet because the
1645 relevant pins are tristated. The peripheral then moves via
1646 intermediate <emphasis>attached</emphasis> and
1647 <emphasis>powered</emphasis> states to its default or
1648 <emphasis>reset</emphasis> state, at which point the host and
1649 peripheral can actually start exchanging data. The first message is
1650 from host to peripheral and provides a unique 7-bit address within the
1651 local USB network, resulting in a state change to
1652 <emphasis>addressed</emphasis>. The host then requests enumeration
1653 data and performs other initialization. If everything succeeds the
1654 host sends a standard set-configuration control message, after which
1655 the peripheral is <emphasis>configured</emphasis> and expected to be
1656 up and running. Note that some USB device drivers may be unable to
1657 distinguish between the <emphasis>detached</emphasis>,
1658 <emphasis>attached</emphasis> and <emphasis>powered</emphasis> states
1659 but generally this is not important to higher-level code.
1660 </para>
1661 <para>
1662 A USB host should generate at least one token every millisecond. If a
1663 peripheral fails to detect any USB traffic for a period of time then
1664 typically this indicates that the host has entered a power-saving
1665 mode, and the peripheral should do the same if possible. This
1666 corresponds to the <emphasis>suspended</emphasis> bit. The actual
1667 state is a combination of <emphasis>suspended</emphasis> and the
1668 previous state, for example <emphasis>configured</emphasis> and
1669 <emphasis>suspended</emphasis> rather than just
1670 <emphasis>suspended</emphasis>. When the peripheral subsequently
1671 detects USB traffic it would switch back to the
1672 <emphasis>configured</emphasis> state.
1673 </para>
1674 <para>
1675 The USB device driver and the common USB slave package will maintain
1676 the current state in the control endpoint's
1677 <structfield>state</structfield> field. There should be no need for
1678 any other code to change this field, but it can be examined whenever
1679 appropriate. In addition whenever a state change occurs the generic
1680 code can invoke a state change callback function. By default, no such
1681 callback function will be installed. Some class-specific packages such
1682 as the USB-ethernet package will install a suitable function to keep
1683 track of whether or not the host-peripheral connection is up, that is
1684 whether or not ethernet packets can be exchanged. Application code can
1685 also update this field. If multiple parties want to be informed of
1686 state changes, for example both a class-specific package and
1687 application code, then typically the application code will install its
1688 state change handler after the class-specific package and is
1689 responsible for chaining into the package's handler.
1690 </para>
1691 <para>
1692 The state change callback function is invoked with four arguments. The
1693 first identifies the control endpoint. The second is an arbitrary
1694 pointer: higher-level code can fill in the
1695 <structfield>state_change_data</structfield> field to set this. The
1696 third argument specifies the state change that has occurred, and the
1697 last argument supplies the previous state (the new state is readily
1698 available from the control endpoint structure).
1699 </para>
1700 <para>
1701 eCos does not provide any utility functions for updating or examining
1702 the <structfield>state_change_fn</structfield> or
1703 <structfield>state_change_data</structfield> fields. Instead, it is
1704 expected that the fields in the
1705 <structname>usbs_control_endpoint</structname> data structure will be
1706 manipulated directly. Any utility functions would do just this, but
1707 at the cost of increased code and cpu overheads.
1708 </para>
1709 </refsect2>
1710
1711 <refsect2><title id="usbs-control-standard">Standard Control Messages</title>
1712 <programlisting width=88>
1713 typedef struct usbs_control_endpoint {
1714     &hellip;
1715     unsigned char       control_buffer[8];
1716     usbs_control_return (*standard_control_fn)(struct usbs_control_endpoint*, void*);
1717     void*               standard_control_data;
1718     &hellip;
1719 } usbs_control_endpoint;
1720
1721 typedef enum {
1722     USBS_CONTROL_RETURN_HANDLED = 0,
1723     USBS_CONTROL_RETURN_UNKNOWN = 1,
1724     USBS_CONTROL_RETURN_STALL   = 2
1725 } usbs_control_return;
1726
1727 extern usbs_control_return usbs_handle_standard_control(struct usbs_control_endpoint*);
1728 </programlisting>
1729 <para>
1730 When a USB peripheral is connected to the host it must always respond
1731 to control messages sent to endpoint 0. Control messages always
1732 consist of an initial eight-byte header, containing fields such as a
1733 request type. This may be followed by a further data transfer, either
1734 from host to peripheral or from peripheral to host. The way this is
1735 handled is described in the <link
1736 linkend="usbs-control-buffer">Buffer Management</link> section below.
1737 </para>
1738 <para>
1739 The USB device driver will always accept the initial eight-byte
1740 header, storing it in the <structfield>control_buffer</structfield>
1741 field. Then it determines the request type: standard, class, vendor,
1742 or reserved. The way in which the last three of these are processed is
1743 described in the section <link linkend="usbs-control-other">Other
1744 Control Messages</link>. Some
1745 standard control messages will be handled by the device driver itself;
1746 typically the <emphasis>set-address</emphasis> request and the
1747 <emphasis>get-status</emphasis>, <emphasis>set-feature</emphasis> and
1748 <emphasis>clear-feature</emphasis> requests when applied to endpoints.
1749 </para>
1750 <para>
1751 If a standard control message cannot be handled by the device driver
1752 itself, the driver checks the
1753 <structfield>standard_control_fn</structfield> field in the control
1754 endpoint data structure. If higher-level code has installed a suitable
1755 callback function then this will be invoked with two argument, the
1756 control endpoint data structure itself and the
1757 <structfield>standard_control_data</structfield> field. The latter
1758 allows the higher level code to associate arbitrary data with the
1759 control endpoint. The callback function can return one of three
1760 values: <emphasis>HANDLED</emphasis> to indicate that the request has
1761 been processed; <emphasis>UNKNOWN</emphasis> if the message should be
1762 handled by the default code; or <emphasis>STALL</emphasis> to indicate
1763 an error condition. If higher level code has not installed a callback
1764 function or if the callback function has returned
1765 <emphasis>UNKNOWN</emphasis> then the device driver will invoke a
1766 default handler, <function>usbs_handle_standard_control</function>
1767 provided by the common USB slave package.
1768 </para>
1769 <para>
1770 The default handler can cope with all of the standard control messages
1771 for a simple USB peripheral. However, if the peripheral involves
1772 multiple configurations, multiple interfaces in a configuration, or
1773 alternate settings for an interface, then this cannot be handled by
1774 generic code. For example, a multimedia peripheral may support various
1775 alternate settings for a given data source with different bandwidth
1776 requirements, and the host can select a setting that takes into
1777 account the current load. Clearly higher-level code needs to be aware
1778 when the host changes the current setting, so that it can adjust the
1779 rate at which data is fed to or retrieved from the host. Therefore the
1780 higher-level code needs to install its own standard control callback
1781 and process appropriate messages, rather than leaving these to the
1782 default handler.
1783 </para>
1784 <para>
1785 The default handler will take care of the
1786 <emphasis>get-descriptor</emphasis> request used to obtain the
1787 enumeration data. It has support for string descriptors but ignores
1788 language encoding issues. If language encoding is important for the
1789 peripheral then this will have to be handled by an
1790 application-specific standard control handler.
1791 </para>
1792 <para>
1793 The header file <filename
1794 class="headerfile">&lt;cyg/io/usb/usb.h&gt;</filename> defines various
1795 constants related to control messages, for example the function codes
1796 corresponding to the standard request types. This header file is
1797 provided by the common USB package, not by the USB slave package,
1798 since the information is also relevant to USB hosts.
1799 </para>
1800 </refsect2>
1801
1802 <refsect2><title id="usbs-control-other">Other Control Messages</title>
1803 <programlisting width=88>
1804 typedef struct usbs_control_endpoint {
1805     &hellip;
1806     usbs_control_return (*class_control_fn)(struct usbs_control_endpoint*, void*);
1807     void*               class_control_data;
1808     usbs_control_return (*vendor_control_fn)(struct usbs_control_endpoint*, void*);
1809     void*               vendor_control_data;
1810     usbs_control_return (*reserved_control_fn)(struct usbs_control_endpoint*, void*);
1811     void*               reserved_control_data;
1812     &hellip;
1813 } usbs_control_endpoint;
1814 </programlisting>
1815 <para>
1816 Non-standard control messages always have to be processed by
1817 higher-level code. This could be class-specific packages. For example,
1818 the USB-ethernet package will handle requests for getting the MAC
1819 address and for enabling or disabling promiscuous mode. In all cases
1820 the device driver will store the initial request in the
1821 <structfield>control_buffer</structfield> field, check for an
1822 appropriate handler, and invoke it with details of the control
1823 endpoint and any handler-specific data that has been installed
1824 alongside the handler itself. The handler should return either
1825 <literal>USBS_CONTROL_RETURN_HANDLED</literal> to report success or
1826 <literal>USBS_CONTROL_RETURN_STALL</literal> to report failure. The
1827 device driver will report this to the host.
1828 </para>
1829 <para>
1830 If there are multiple parties interested in a particular type of
1831 control messages, it is the responsibility of application code to
1832 install an appropriate handler and process the requests appropriately. 
1833 </para>
1834 </refsect2>
1835
1836 <refsect2><title id="usbs-control-buffer">Buffer Management</title>
1837 <programlisting width=76>
1838 typedef struct usbs_control_endpoint {
1839     &hellip;
1840     unsigned char*      buffer;
1841     int                 buffer_size;
1842     void                (*fill_buffer_fn)(struct usbs_control_endpoint*);
1843     void*               fill_data;
1844     int                 fill_index;
1845     usbs_control_return (*complete_fn)(struct usbs_control_endpoint*, int);
1846     &hellip;
1847 } usbs_control_endpoint;
1848 </programlisting>
1849 <para>
1850 Many USB control messages involve transferring more data than just the
1851 initial eight-byte header. The header indicates the direction of the
1852 transfer, OUT for host to peripheral or IN for peripheral to host.
1853 It also specifies a length field, which is exact for an OUT transfer
1854 or an upper bound for an IN transfer. Control message handlers can
1855 manipulate six fields within the control endpoint data structure to
1856 ensure that the transfer happens correctly.
1857 </para>
1858 <para>
1859 For an OUT transfer, the handler should examine the length field in
1860 the header and provide a single buffer for all the data. A
1861 class-specific protocol would typically impose an upper bound on the
1862 amount of data, allowing the buffer to be allocated statically.
1863 The handler should update the <structfield>buffer</structfield> and
1864 <structfield>complete_fn</structfield> fields. When all the data has
1865 been transferred the completion callback will be invoked, and its
1866 return value determines the response sent back to the host. The USB
1867 standard allows for a new control message to be sent before the
1868 current transfer has completed, effectively cancelling the current
1869 operation. When this happens the completion function will also be
1870 invoked. The second argument to the completion function specifies what
1871 has happened, with a value of 0 indicating success and an error code
1872 such as <literal>-EPIPE</literal> or <literal>-EIO</literal>
1873 indicating that the current transfer has been cancelled.
1874 </para>
1875 <para>
1876 IN transfers are a little bit more complicated. The required
1877 information, for example the enumeration data, may not be in a single
1878 contiguous buffer. Instead a mechanism is provided by which the buffer
1879 can be refilled, thus allowing the transfer to move from one record to
1880 the next. Essentially, the transfer operates as follows:
1881 </para>
1882 <orderedlist>
1883 <listitem>
1884 <para>
1885 When the host requests another chunk of data (typically eight bytes),
1886 the USB device driver will examine the
1887 <structfield>buffer_size</structfield> field. If non-zero then
1888 <structfield>buffer</structfield> contains at least one more byte of
1889 data, and then <structfield>buffer_size</structfield> is decremented.
1890 </para>
1891 </listitem>
1892 <listitem>
1893 <para>
1894 When <structfield>buffer_size</structfield> has dropped to 0, the
1895 <structfield>fill_buffer_fn</structfield> field will be examined. If
1896 non-null it will be invoked to refill the buffer.
1897 </para>
1898 </listitem>
1899 <listitem>
1900 <para>
1901 The <structfield>fill_data</structfield> and
1902 <structfield>fill_index</structfield> fields are not used by the
1903 device driver. Instead these fields are available to the refill
1904 function to keep track of the current state of the transfer.
1905 </para>
1906 </listitem>
1907 <listitem>
1908 <para>
1909 When <structfield>buffer_size</structfield> is 0 and
1910 <structfield>fill_buffer_fn</structfield> is NULL, no more data is
1911 available and the transfer has completed.
1912 </para>
1913 </listitem>
1914 <listitem>
1915 <para>
1916 Optionally a completion function can be installed. This will be
1917 invoked with 0 if the transfer completes successfully, or with an
1918 error code if the transfer is cancelled because of another control
1919 messsage. 
1920 </para>
1921 </listitem>
1922 </orderedlist>
1923 <para>
1924 If the requested data is contiguous then the only fields that need
1925 to be manipulated are <structfield>buffer</structfield> and
1926 <structfield>buffer_size</structfield>, and optionally
1927 <structfield>complete_fn</structfield>. If the requested data is not
1928 contiguous then the initial control message handler should update
1929 <structfield>fill_buffer_fn</structfield> and some or all of the other
1930 fields, as required. An example of this is the handling of the
1931 standard <emphasis>get-descriptor</emphasis> control message by
1932 <function>usbs_handle_standard_control</function>.
1933 </para>
1934 </refsect2>
1935
1936 <refsect2><title>Polling Support</title>
1937 <programlisting width=72>
1938 typedef struct usbs_control_endpoint {
1939     void                (*poll_fn)(struct usbs_control_endpoint*);
1940     int                 interrupt_vector;
1941     &hellip;
1942 } usbs_control_endpoint;
1943 </programlisting>
1944 <para>
1945 In nearly all circumstances USB I/O should be interrupt-driven.
1946 However, there are special environments such as RedBoot where polled
1947 operation may be appropriate. If the device driver can operate in
1948 polled mode then it will provide a suitable function via the
1949 <structfield>poll_fn</structfield> field, and higher-level code can
1950 invoke this regularly. This polling function will take care of all
1951 endpoints associated with the device, not just the control endpoint.
1952 If the USB hardware involves a single interrupt vector then this will
1953 be identified in the data structure as well.
1954 </para>
1955 </refsect2>
1956
1957 </refsect1>
1958
1959 </refentry>
1960
1961 <!-- }}} -->
1962 <!-- {{{ Data Endpoints                 -->
1963
1964 <refentry id="usbs-data">
1965 <refmeta>
1966 <refentrytitle>Data Endpoints</refentrytitle>
1967 </refmeta>
1968 <refnamediv>
1969 <refname>Data Endpoints</refname>
1970 <refpurpose>Data endpoint data structures</refpurpose>
1971 </refnamediv>
1972
1973 <refsynopsisdiv>
1974 <synopsis>
1975 #include &lt;cyg/io/usb/usbs.h&gt;
1976
1977 typedef struct usbs_rx_endpoint {
1978     void                 (*start_rx_fn)(struct usbs_rx_endpoint*);
1979     void                 (*set_halted_fn)(struct usbs_rx_endpoint*, cyg_bool);
1980     void                 (*complete_fn)(void*, int);
1981     void*                complete_data;
1982     unsigned char*       buffer;
1983     int                  buffer_size;
1984     cyg_bool             halted;
1985 } usbs_rx_endpoint;
1986
1987 typedef struct usbs_tx_endpoint {
1988     void                 (*start_tx_fn)(struct usbs_tx_endpoint*);
1989     void                 (*set_halted_fn)(struct usbs_tx_endpoint*, cyg_bool);
1990     void                 (*complete_fn)(void*, int);
1991     void*                complete_data;
1992     const unsigned char* buffer;
1993     int                  buffer_size;
1994     cyg_bool             halted;
1995 } usbs_tx_endpoint;
1996 </synopsis>
1997 </refsynopsisdiv>
1998
1999 <refsect1><title>Receive and Transmit Data Structures</title>
2000 <para>
2001 In addition to a single <structname>usbs_control_endpoint</structname>
2002 data structure per USB slave device, the USB device driver should also
2003 provide receive and transmit data structures corresponding to the
2004 other endpoints. The names of these are determined by the device
2005 driver. For example, the SA1110 USB device driver package provides
2006 <literal>usbs_sa11x0_ep1</literal> for receives and
2007 <literal>usbs_sa11x0_ep2</literal> for transmits.
2008 </para>
2009 <para>
2010 Unlike control endpoints, the common USB slave package does provide a
2011 number of utility routines to manipulate data endpoints. For example
2012 <link
2013 linkend="usbs-start-rx"><function>usbs_start_rx_buffer</function></link>
2014 can be used to receive data from the host into a buffer. In addition
2015 the USB device driver can provide devtab entries such as
2016 <literal>/dev/usbs1r</literal> and <literal>/dev/usbs2w</literal>, so
2017 higher-level code can <function>open</function> these devices and then
2018 perform blocking <function>read</function> and
2019 <function>write</function> operations.
2020 </para>
2021 <para>
2022 However, the operation of data endpoints and the various
2023 endpoint-related functions is relatively straightforward. First
2024 consider a <structname>usbs_rx_endpoint</structname> structure. The
2025 device driver will provide the members
2026 <structfield>start_rx_fn</structfield> and
2027 <structfield>set_halted_fn</structfield>, and it will maintain the
2028 <structfield>halted</structfield> field. To receive data, higher-level
2029 code sets the <structfield>buffer</structfield>,
2030 <structfield>buffer_size</structfield>,
2031 <structfield>complete_fn</structfield> and optionally the
2032 <structfield>complete_data</structfield> fields. Next the
2033 <structfield>start_rx_fn</structfield> member should be called. When
2034 the transfer has finished the device driver will invoke the completion
2035 function, using <structfield>complete_data</structfield> as the first
2036 argument and a size field for the second argument. A negative size
2037 indicates an error of some sort: <literal>-EGAIN</literal> indicates
2038 that the endpoint has been halted, usually at the request of the host;
2039 <literal>-EPIPE</literal> indicates that the connection between the
2040 host and the peripheral has been broken. Certain device drivers may
2041 generate other error codes.
2042 </para>
2043 <para>
2044 If higher-level code needs to halt or unhalt an endpoint then it can
2045 invoke the <structfield>set_halted_fn</structfield> member. When an
2046 endpoint is halted, invoking <structfield>start_rx_fn</structfield>
2047 wit <structfield>buffer_size</structfield> set to 0 indicates that
2048 higher-level code wants to block until the endpoint is no longer
2049 halted; at that point the completion function will be invoked.
2050 </para>
2051 <para>
2052 USB device drivers are allowed to assume that higher-level protocols
2053 ensure that host and peripheral agree on the amount of data that will
2054 be transferred, or at least on an upper bound. Therefore there is no
2055 need for the device driver to maintain its own buffers, and copy
2056 operations are avoided. If the host sends more data than expected then
2057 the resulting behaviour is undefined.
2058 </para>
2059 <para>
2060 Transmit endpoints work in essentially the same way as receive
2061 endpoints. Higher-level code should set the
2062 <structfield>buffer</structfield> and
2063 <structfield>buffer_size</structfield> fields to point at the data to
2064 be transferred, then call <structfield>start_tx_fn</structfield>, and
2065 the device driver will invoked the completion function when the
2066 transfer has completed.
2067 </para>
2068 <para>
2069 USB device drivers are not expected to perform any locking. If at any
2070 time there are two concurrent receive operations for a given endpoint,
2071 or two concurrent transmit operations, then the resulting behaviour is
2072 undefined. It is the responsibility of higher-level code to perform
2073 any synchronisation that may be necessary. In practice, conflicts are
2074 unlikely because typically a given endpoint will only be accessed
2075 sequentially by just one part of the overall system.
2076 </para>
2077
2078 </refsect1>
2079
2080 </refentry>
2081
2082 <!-- }}} -->
2083 <!-- {{{ Writing a USB Device Driver    -->
2084
2085 <refentry id="usbs-writing">
2086 <refmeta>
2087 <refentrytitle>Writing a USB Device Driver</refentrytitle>
2088 </refmeta>
2089 <refnamediv>
2090 <refname>Writing a USB Device Driver</refname>
2091 <refpurpose>USB Device Driver Porting Guide</refpurpose>
2092 </refnamediv>
2093
2094 <refsect1><title>Introduction</title>
2095 <para>
2096 Often the best way to write a USB device driver will be to start with
2097 an existing one and modify it as necessary. The information given here
2098 is intended primarily as an outline rather than as a complete guide.
2099 </para>
2100 <note>
2101 <para>
2102 At the time of writing only one USB device driver has been
2103 implemented. Hence it is possible, perhaps probable, that some
2104 portability issues have not yet been addressed. One issue
2105 involves the different types of transfer, for example the initial
2106 target hardware had no support for isochronous or interrupt transfers,
2107 so additional functionality may be needed to switch between transfer
2108 types. Another issue would be hardware where a given endpoint number,
2109 say endpoint 1, could be used for either receiving or transmitting
2110 data, but not both because a single fifo is used. Issues like these
2111 will have to be resolved as and when additional USB device drivers are
2112 written.
2113 </para>
2114 </note>
2115 </refsect1>
2116
2117 <refsect1><title>The Control Endpoint</title>
2118 <para>
2119 A USB device driver should provide a single <link
2120 linkend="usbs-control"><structname>usbs_control_endpoint</structname></link>
2121 data structure for every USB device. Typical peripherals will have
2122 only one USB port so there will be just one such data structure in the
2123 entire system, but theoretically it is possible to have multiple USB
2124 devices. These may all involve the same chip, in which case a single
2125 device driver should support multiple device instances, or they may
2126 involve different chips. The name or names of these data structures
2127 are determined by the device driver, but appropriate care should be
2128 taken to avoid name clashes. 
2129 </para>
2130 <para>
2131 A USB device cannot be used unless the control endpoint data structure
2132 exists. However, the presence of USB hardware in the target processor
2133 or board does not guarantee that the application will necessarily want
2134 to use that hardware. To avoid unwanted code or data overheads, the
2135 device driver can provide a configuration option to determine whether
2136 or not the endpoint 0 data structure is actually provided. A default
2137 value of <literal>CYGINT_IO_USB_SLAVE_CLIENTS</literal> ensures that
2138 the USB driver will be enabled automatically if higher-level code does
2139 require USB support, while leaving ultimate control to the user.
2140 </para>
2141 <para>
2142 The USB device driver is responsible for filling in the
2143 <structfield>start_fn</structfield>,
2144 <structfield>poll_fn</structfield> and
2145 <structfield>interrupt_vector</structfield> fields. Usually this can
2146 be achieved by static initialization. The driver is also largely
2147 responsible for maintaining the <structfield>state</structfield>
2148 field. The <structfield>control_buffer</structfield> array should be
2149 used to hold the first packet of a control message. The
2150 <structfield>buffer</structfield> and other fields related to data
2151 transfers will be managed <link
2152 linkend="usbs-control-buffer">jointly</link> by higher-level code and
2153 the device driver. The remaining fields are generally filled in by
2154 higher-level code, although the driver should initialize them to NULL
2155 values.
2156 </para>
2157 <para>
2158 Hardware permitting, the USB device should be inactive until the
2159 <structfield>start_fn</structfield> is invoked, for example by
2160 tristating the appropriate pins. This prevents the host from
2161 interacting with the peripheral before all other parts of the system
2162 have initialized. It is expected that the
2163 <structfield>start_fn</structfield> will only be invoked once, shortly
2164 after power-up.
2165 </para>
2166 <para>
2167 Where possible the device driver should detect state changes, such as
2168 when the connection between host and peripheral is established, and
2169 <link linkend="usbs-control-state">report</link> these to higher-level
2170 code via the <structfield>state_change_fn</structfield> callback, if
2171 any. The state change to and from configured state cannot easily be
2172 handled by the device driver itself, instead higher-level code such as
2173 the common USB slave package will take care of this.
2174 </para>
2175 <para>
2176 Once the connection between host and peripheral has been established,
2177 the peripheral must be ready to accept control messages at all times,
2178 and must respond to these within certain time constraints. For
2179 example, the standard set-address control message must be handled
2180 within 50ms. The USB specification provides more information on these
2181 constraints. The device driver is responsible for receiving the
2182 initial packet of a control message. This packet will always be eight
2183 bytes and should be stored in the
2184 <structfield>control_buffer</structfield> field. Certain standard
2185 control messages should be detected and handled by the device driver
2186 itself. The most important is set-address, but usually the get-status,
2187 set-feature and clear-feature requests when applied to halted
2188 endpoints should also be handled by the driver. Other standard control
2189 messages should first be passed on to the
2190 <structfield>standard_control_fn</structfield> callback (if any), and
2191 finally to the default handler
2192 <function>usbs_handle_standard_control</function> provided by the
2193 common USB slave package. Class, vendor and reserved control messages
2194 should always be dispatched to the appropriate callback and there is
2195 no default handler for these.
2196 </para>
2197 <para>
2198 Some control messages will involve further data transfer, not just the
2199 initial packet. The device driver must handle this in accordance with
2200 the USB specification and the <link
2201 linkend="usbs-control-buffer">buffer management strategy</link>. The
2202 driver is also responsible for keeping track of whether or not the
2203 control operation has succeeded and generating an ACK or STALL
2204 handshake. 
2205 </para>
2206 <para>
2207 The polling support is optional and may not be feasible on all
2208 hardware. It is only used in certain specialised environments such as
2209 RedBoot. A typical implementation of the polling function would just
2210 check whether or not an interrupt would have occurred and, if so, call
2211 the same code that the interrupt handler would.
2212 </para>
2213 </refsect1>
2214
2215 <refsect1><title>Data Endpoints</title>
2216 <para>
2217 In addition to the control endpoint data structure, a USB device
2218 driver should also provide appropriate <link linkend="usbs-data">data
2219 endpoint</link> data structures. Obviously this is only relevant if
2220 the USB support generally is desired, that is if the control endpoint is
2221 provided. In addition, higher-level code may not require all the
2222 endpoints, so it may be useful to provide configuration options that
2223 control the presence of each endpoint. For example, the intended
2224 application might only involve a single transmit endpoint and of
2225 course control messages, so supporting receive endpoints might waste
2226 memory.
2227 </para>
2228 <para>
2229 Conceptually, data endpoints are much simpler than the control
2230 endpoint. The device driver has to supply two functions, one for
2231 data transfers and another to control the halted condition. These
2232 implement the functionality for
2233 <link linkend="usbs-start-rx"><function>usbs_start_rx_buffer</function></link>,
2234 <link linkend="usbs-start-tx"><function>usbs_start_tx_buffer</function></link>,
2235 <link linkend="usbs-halt"><function>usbs_set_rx_endpoint_halted</function></link> and
2236 <link linkend="usbs-halt"><function>usbs_set_tx_endpoint_halted</function></link>.
2237 The device driver is also responsible for maintaining the
2238 <structfield>halted</structfield> status.
2239 </para>
2240 <para>
2241 For data transfers, higher-level code will have filled in the
2242 <structfield>buffer</structfield>,
2243 <structfield>buffer_size</structfield>,
2244 <structfield>complete_fn</structfield> and
2245 <structfield>complete_data</structfield> fields. The transfer function
2246 should arrange for the transfer to start, allowing the host to send or
2247 receive packets. Typically this will result in an interrupt at the end
2248 of the transfer or after each packet. Once the entire transfer has
2249 been completed, the driver's interrupt handling code should invoke the
2250 completion function. This can happen either in DSR context or thread
2251 context, depending on the driver's implementation. There are a number
2252 of special cases to consider. If the endpoint is halted when the
2253 transfer is started then the completion function can be invoked
2254 immediately with <literal>-EAGAIN</literal>. If the transfer cannot be
2255 completed because the connection is broken then the completion
2256 function should be invoked with <literal>-EPIPE</literal>. If the
2257 endpoint is stalled during the transfer, either because of a standard
2258 control message or because higher-level code calls the appropriate
2259 <structfield>set_halted_fn</structfield>, then again the completion
2260 function should be invoked with <literal>-EAGAIN</literal>. Finally,
2261 the <<function>usbs_start_rx_endpoint_wait</function> and
2262 <function>usbs_start_tx_endpoint_wait</function> functions involve
2263 calling the device driver's data transfer function with a buffer size
2264 of 0 bytes.
2265 </para>
2266 <note><para>
2267 Giving a buffer size of 0 bytes a special meaning is problematical
2268 because it prevents transfers of that size. Such transfers are allowed
2269 by the USB protocol, consisting of just headers and acknowledgements
2270 and an empty data phase, although rarely useful. A future modification
2271 of the device driver specification will address this issue, although
2272 care has to be taken that the functionality remains accessible through
2273 devtab entries as well as via low-level accesses.
2274 </para></note>
2275 </refsect1>
2276
2277 <refsect1><title>Devtab Entries</title>
2278 <para>
2279 For some applications or higher-level packages it may be more
2280 convenient to use traditional open/read/write I/O calls rather than
2281 the non-blocking USB I/O calls. To support this the device driver can
2282 provide a devtab entry for each endpoint, for example:
2283 </para>
2284 <programlisting width=72>
2285 #ifdef CYGVAR_DEVS_USB_SA11X0_EP1_DEVTAB_ENTRY
2286
2287 static CHAR_DEVIO_TABLE(usbs_sa11x0_ep1_devtab_functions,
2288                         &amp;cyg_devio_cwrite,
2289                         &amp;usbs_devtab_cread,
2290                         &amp;cyg_devio_bwrite,
2291                         &amp;cyg_devio_bread,
2292                         &amp;cyg_devio_select,
2293                         &amp;cyg_devio_get_config,
2294                         &amp;cyg_devio_set_config);
2295
2296 static CHAR_DEVTAB_ENTRY(usbs_sa11x0_ep1_devtab_entry,
2297                          CYGDAT_DEVS_USB_SA11X0_DEVTAB_BASENAME "1r",
2298                          0,
2299                          &amp;usbs_sa11x0_ep1_devtab_functions,
2300                          &amp;usbs_sa11x0_devtab_dummy_init,
2301                          0,
2302                          (void*) &amp;usbs_sa11x0_ep1);
2303 #endif
2304 </programlisting>
2305 <para>
2306 Again care must be taken to avoid name clashes. This can be achieved
2307 by having a configuration option to control the base name, with a
2308 default value of e.g. <literal>/dev/usbs</literal>, and appending an
2309 endpoint-specific string. This gives the application developer
2310 sufficient control to eliminate any name clashes. The common USB slave
2311 package provides functions <function>usbs_devtab_cwrite</function> and
2312 <function>usbs_devtab_cread</function>, which can be used in the
2313 function tables for transmit and receive endpoints respectively. The
2314 private field <structfield>priv</structfield> of the devtab entry
2315 should be a pointer to the underlying endpoint data structure.
2316 </para>
2317 <para>
2318 Because devtab entries are never accessed directly, only indirectly,
2319 they would usually be eliminated by the linker. To avoid this the
2320 devtab entries should normally be defined in a separate source file
2321 which ends up the special library <filename>libextras.a</filename>
2322 rather than in the default library <filename>libtarget.a</filename>.
2323 </para>
2324 <para>
2325 Not all applications or higher-level packages will want to use the
2326 devtab entries and the blocking I/O facilities. It may be appropriate
2327 for the device driver to provide additional configuration options that
2328 control whether or not any or all of the devtab entries should be
2329 provided, to avoid unnecessary memory overheads.
2330 </para>
2331 </refsect1>
2332
2333 <refsect1><title>Interrupt Handling</title>
2334 <para>
2335 A typical USB device driver will need to service interrupts for all of
2336 the endpoints and possibly for additional USB events such as entering
2337 or leaving suspended mode. Usually these interrupts need not be
2338 serviced directly by the ISR. Instead, they can be left to a DSR. If
2339 the peripheral is not able to accept or send another packet just yet,
2340 the hardware will generate a NAK and the host will just retry a little
2341 bit later. If high throughput is required then it may be desirable to
2342 handle the bulk transfer protocol largely at ISR level, that is take
2343 care of each packet in the ISR and only activate the DSR once the
2344 whole transfer has completed.
2345 </para>
2346 <para>
2347 Control messages may involve invoking arbitrary callback functions in
2348 higher-level code. This should normally happen at DSR level. Doing it
2349 at ISR level could seriously affect the system's interrupt latency and
2350 impose unacceptable constraints on what operations can be performed by
2351 those callbacks. If the device driver requires a thread anyway then it
2352 may be appropriate to use this thread for invoking the callbacks, but
2353 usually it is not worthwhile to add a new thread to the system just
2354 for this; higher-level code is expected to write callbacks that
2355 function sensibly at DSR level. Much the same applies to the
2356 completion functions associated with data transfers. These should also
2357 be invoked at DSR or thread level.
2358 </para>
2359
2360 </refsect1>
2361 <refsect1><title>Support for USB Testing</title>
2362 <para>
2363 Optionally a USB device driver can provide support for the
2364 <link linkend="usbs-testing">USB test software</link>. This requires
2365 defining a number of additional data structures, allowing the
2366 generic test code to work out just what the hardware is capable of and
2367 hence what testing can be performed.
2368 </para>
2369 <para>
2370 The key data structure is
2371 <structname>usbs_testing_endpoint</structname>, defined in <filename
2372 class="headerfile">cyg/io/usb/usbs.h</filename>. In addition some
2373 commonly required constants are provided by the common USB package in
2374 <filename class="headerfile">cyg/io/usb/usb.h</filename>. One
2375 <structname>usbs_testing_endpoint</structname> structure should be
2376 defined for each supported endpoint. The following fields need to be
2377 filled in:
2378 </para>
2379 <variablelist>
2380 <varlistentry>
2381   <term><structfield>endpoint_type</structfield></term>
2382   <listitem><para>
2383     This specifies the type of endpoint and should be one of
2384     <literal>USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL</literal>,
2385     <literal>BULK</literal>, <literal>ISOCHRONOUS</literal> or
2386     <literal>INTERRUPT</literal>.
2387   </para></listitem>
2388 </varlistentry>
2389 <varlistentry>
2390   <term><structfield>endpoint_number</structfield></term>
2391   <listitem><para>
2392     This identifies the number that should be used by the host
2393     to address this endpoint. For a control endpoint it should
2394     be 0. For other types of endpoints it should be between
2395     1 and 15.
2396   </para></listitem>
2397 </varlistentry>
2398 <varlistentry>
2399   <term><structfield>endpoint_direction</structfield></term>
2400   <listitem><para>
2401     For control endpoints this field is irrelevant. For other
2402     types of endpoint it should be either
2403     <literal>USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN</literal> or
2404     <literal>USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT</literal>. If a given
2405     endpoint number can be used for traffic in both directions then
2406     there should be two entries in the array, one for each direction.
2407   </para></listitem>
2408 </varlistentry>
2409 <varlistentry>
2410   <term><structfield>endpoint</structfield></term>
2411   <listitem><para>
2412     This should be a pointer to the appropriate
2413     <structname>usbs_control_endpoint</structname>,
2414     <structname>usbs_rx_endpoint</structname> or
2415     <structname>usbs_tx_endpoint</structname> structure, allowing the
2416     generic testing code to perform low-level I/O.
2417   </para></listitem>
2418 </varlistentry>
2419 <varlistentry>
2420   <term><structfield>devtab_entry</structfield></term>
2421   <listitem><para>
2422     If the endpoint also has an entry in the system's device table then
2423     this field should give the corresponding string, for example
2424     <literal>&quot;/dev/usbs1r&quot;</literal>. This allows the
2425     generic testing code to access the device via higher-level
2426     calls like <function>open</function> and <function>read</function>. 
2427   </para></listitem>
2428 </varlistentry>
2429 <varlistentry>
2430   <term><structfield>min_size</structfield></term>
2431   <listitem><para>
2432     This indicates the smallest transfer size that the hardware can
2433     support on this endpoint. Typically this will be one.
2434   </para>
2435   <note><para>
2436     Strictly speaking a minimum size of one is not quite right since it
2437     is valid for a USB transfer to involve zero bytes, in other words a
2438     transfer that involves just headers and acknowledgements and an
2439     empty data phase, and that should be tested as well. However current
2440     device drivers interpret a transfer size of 0 as special, so that
2441     would have to be resolved first.
2442   </para></note>
2443   </listitem>
2444 </varlistentry>
2445 <varlistentry>
2446   <term><structfield>max_size</structfield></term>
2447   <listitem><para>
2448     Similarly, this specifies the largest transfer size. For control
2449     endpoints the USB protocol uses only two bytes to hold the transfer
2450     length, so there is an upper bound of 65535 bytes. In practice
2451     it is very unlikely that any control transfers would ever need to
2452     be this large, and in fact such transfers would take a long time
2453     and probably violate timing constraints. For other types of endpoint
2454     any of the protocol, the hardware, or the device driver may impose
2455     size limits. For example a given device driver might be unable to
2456     cope with transfers larger than 65535 bytes. If it should be
2457     possible to transfer arbitrary amounts of data then a value of
2458     <literal>-1</literal> indicates no upper limit, and transfer
2459     sizes will be limited by available memory and by the capabilities
2460     of the host machine.
2461   </para></listitem>
2462 </varlistentry>
2463 <varlistentry>
2464   <term><structfield>max_in_padding</structfield></term>
2465   <listitem><para>
2466     This field is needed on some hardware where it is impossible to
2467     send packets of a certain size. For example the hardware may be
2468     incapable of sending an empty bulk packet to terminate a transfer
2469     that is an exact multiple of the 64-byte bulk packet size.
2470     Instead the driver has to do some padding and send an extra byte,
2471     and the host has to be prepared to receive this extra byte. Such a
2472     driver should specify a value of <literal>1</literal> for the
2473     padding field. For most drivers this field should be set to
2474   <literal>0</literal>.
2475   </para>
2476   <para>
2477     A better solution would be for the device driver to supply a
2478     fragment of Tcl code that would adjust the receive buffer size
2479     only when necessary, rather than for every transfer. Forcing
2480     receive padding on all transfers when only certain transfers
2481     will actually be padded reduces the accuracy of certain tests.
2482   </para></listitem>
2483 </varlistentry>
2484 <varlistentry>
2485   <term><structfield>alignment</structfield></term>
2486   <listitem><para>
2487     On some hardware data transfers may need to be aligned to certain
2488     boundaries, for example a word boundary or a cacheline boundary.
2489     Although in theory device drivers could hide such alignment
2490     restrictions from higher-level code by having their own buffers and
2491     performing appropriate copying, that would be expensive in terms of
2492     both memory and cpu cycles. Instead the generic testing code will
2493     align any buffers passed to the device driver to the specified
2494     boundary. For example, if the driver requires that buffers be
2495     aligned to a word boundary then it should specify an alignment
2496     value of 4.
2497   </para></listitem>
2498 </varlistentry>
2499 </variablelist>
2500
2501 <para>
2502 The device driver should provide an array of these structures
2503 <varname>usbs_testing_endpoints[]</varname>. The USB testing code
2504 examines this array and uses the information to perform appropriate
2505 tests. Because different USB devices support different numbers of
2506 endpoints the number of entries in the array is not known in advance,
2507 so instead the testing code looks for a special terminator
2508 <varname>USBS_TESTING_ENDPOINTS_TERMINATOR</varname>. An example
2509 array, showing just the control endpoint and the terminator, might
2510 look like this:
2511 </para>
2512 <programlisting width=72>
2513 usbs_testing_endpoint usbs_testing_endpoints[] = {
2514     {
2515         endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL, 
2516         endpoint_number     : 0,
2517         endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN,
2518         endpoint            : (void*) &amp;ep0.common,
2519         devtab_entry        : (const char*) 0,
2520         min_size            : 1,
2521         max_size            : 0x0FFFF,
2522         max_in_padding      : 0,
2523         alignment           : 0
2524     },
2525     &hellip;,
2526     USBS_TESTING_ENDPOINTS_TERMINATOR
2527 };
2528 </programlisting>
2529
2530 <note>
2531 <para>
2532 The use of a single array <varname>usbs_testing_endpoints</varname>
2533 limits USB testing to platforms with a single USB device: if there
2534 were multiple devices, each defining their own instance of this array,
2535 then there would a collision at link time. In practice this should not
2536 be a major problem since typical USB peripherals only interact with a
2537 single host machine via a single slave port. In addition, even if a
2538 peripheral did have multiple slave ports the current USB testing code
2539 would not support this since it would not know which port to use.
2540 </para>
2541 </note>
2542
2543 </refsect1>
2544
2545 </refentry>
2546
2547 <!-- }}} -->
2548 <!-- {{{ USB Testing support            -->
2549
2550 <refentry id="usbs-testing">
2551 <refmeta>
2552 <refentrytitle>Testing</refentrytitle>
2553 </refmeta>
2554 <refnamediv>
2555 <refname>Testing</refname>
2556 <refpurpose>Testing of USB Device Drivers</refpurpose>
2557 </refnamediv>
2558
2559 <refsect1><title>Introduction</title>
2560 <para>
2561 The support for USB testing provided by the eCos USB common slave
2562 package is somewhat different in nature from the kind of testing used
2563 in many other packages. One obvious problem is that USB tests cannot
2564 be run on just a bare target platform: instead the target platform
2565 must be connected to a suitable USB host machine, and that host
2566 machine must be running appropriate software for the test code to
2567 interact with. This is very different from say a kernel test which
2568 typically will have no external dependencies. Another important
2569 difference between USB testing and say a C library
2570 <function>strcmp</function> test is sensitivity to timing and to
2571 hardware boundary conditions: although a simple test case that just
2572 performs a small number of USB transfers is better than no testing at
2573 all, it should also be possible to run tests for hours or days on end,
2574 under a variety of loads. In order to provide the required
2575 functionality the basic architecture of the USB testing support is as
2576 follows: 
2577 </para>
2578 <orderedlist>
2579   <listitem><para>
2580     There is a single target-side program
2581     <application>usbtarget</application>. By default when this is run
2582     on a target platform it will appear to do nothing. In fact it is
2583     waiting to be contacted by another program
2584     <application>usbhost</application> which will tell it what test or
2585     tests to run. <application>usbtarget</application> provides
2586     mechanisms for running a wide range of tests.
2587   </para></listitem>
2588   <listitem><para>
2589     <application>usbtarget</application> is a generic program, but USB
2590     testing depends to some extent on the functionality provided by the
2591     hardware. For example there is no point in testing bulk transmits
2592     to endpoint 12 if the target hardware does not support an endpoint
2593     12. Therefore each USB device driver should supply information about
2594     what the hardware is actually capable of, in the form of an array of
2595     <structname>usbs_testing_endpoint</structname> data structures.
2596   </para></listitem>
2597   <listitem><para>
2598     There is a single host-side program
2599     <application>usbhost</application>, which acts as a counterpart to
2600     <application>usbtarget</application>. Again
2601     <application>usbhost</application> has no built-in knowledge of
2602     the test or tests that are supposed to run, it only provides
2603     mechanisms for running a wide range of tests. On start-up
2604     <application>usbhost</application> will search the USB bus for
2605     hardware running the target-side program, specifically a USB device
2606     that identifies itself as the product <literal>&quot;Red Hat eCos
2607     USB test&quot;</literal>.
2608   </para></listitem>
2609   <listitem><para>
2610     <application>usbhost</application> contains a Tcl interpreter, and
2611     will execute any Tcl scripts specified on the command line
2612     together with appropriate arguments. The Tcl interpreter has been
2613     extended with various commands such as
2614     <literal>usbtest::bulktest</literal>, so the script can perform
2615     the desired test or tests.
2616   </para></listitem>
2617   <listitem><para>
2618     Adding a new test simply involves writing a short Tcl script that
2619     invokes the appropriate USB-specific commands. Running multiple
2620     tests involves passing appropriate arguments to
2621     <application>usbhost</application>, or alternatively writing a
2622     single script that just invokes other scripts.
2623   </para></listitem>
2624 </orderedlist>
2625 <para>
2626 The current implementation of <application>usbhost</application>
2627 depends heavily on functionality provided by the Linux kernel and in
2628 particular the usbdevfs support. It uses
2629 <filename>/proc/bus/usb/devices</filename> to find out what devices
2630 are attached to the bus, and will then access the device by opening
2631 <filename>/proc/bus/usb/xxx/yyy</filename> and performing
2632 <function>ioctl</function> operations. This allows USB testing to take
2633 place without having to write a new host-side device driver, but
2634 getting the code working on host machines not running Linux would
2635 obviously be problematical.
2636 </para>
2637 </refsect1>
2638
2639 <refsect1><title>Building and Running the Target-side Code</title>
2640 <para>
2641 The target-side component of the USB testing software consists of a
2642 single program <application>usbtarget</application> which contains
2643 support for a range of different tests, under the control of host-side
2644 software. This program is not built by default alongside other eCos
2645 test cases since it will only operate in certain environments,
2646 specifically when the target board's connector is plugged into a Linux
2647 host, and when the appropriate host-side software has been installed
2648 on that host. Instead the user must enable a configuration option
2649 <literal>CYGBLD_IO_USB_SLAVE_USBTEST</literal> to add the program to
2650 the list of tests for the current configuration.
2651 </para>
2652 <para>
2653 Starting the <application>usbtarget</application> program does not
2654 require anything unusual, so it can be run in a normal
2655 <application>gdb</application> session just like any eCos application.
2656 After initialization the program will wait for activity from the host.
2657 Depending on the hardware, the Linux host will detect that a new USB
2658 peripheral is present on the bus either when the
2659 <application>usbtarget</application> initialization is complete or
2660 when the cable between target and host is connected. The host will
2661 perform the normal USB enumeration sequence and discover that the
2662 peripheral does not match any known vendor or product id and that
2663 there is no device driver for <literal>&quot;Red Hat eCos USB
2664 test&quot;</literal>, so it will ignore the peripheral. When the
2665 <application>usbhost</application> program is run on the host it will
2666 connect to the target-side software, and testing can now commence.
2667 </para>
2668 </refsect1>
2669
2670 <refsect1><title>Building and Running the Host-side Code</title>
2671 <note><para>
2672 In theory the host-side software should be built when the package is
2673 installed in the component repository, and removed when a package
2674 is uninstalled. The current eCos administration tool does not provide
2675 this functionality.
2676 </para></note>
2677 <para>
2678 The host-side software should be built via the usual sequence of
2679 &quot;configure/make/make install&quot;. It can only be built on a
2680 Linux host and the <command>configure</command> script contains an
2681 explicit test for this. Because the eCos component repository should
2682 generally be treated as a read-only resource the configure script will
2683 also prevent you from trying to build inside the source tree. Instead
2684 a separate build tree is required. Hence a typical sequence for
2685 building the host-side software would be as follows:
2686 </para>
2687 <screen>
2688 $ mkdir usbhost_build
2689 $ cd usbhost_build
2690 $ &lt;repo&gt;packages/io/usb/slave/current/host/configure <co id="path"> <co id="version"> &lt;args&gt; <co id="args">
2691 $ make
2692 &lt;output from make&gt;
2693 $ su <co id="root">
2694 $ make install
2695 &lt;output from make install&gt;
2696 $
2697 </screen>
2698 <calloutlist>
2699 <callout arearefs="path">
2700 <para>
2701 The location of the eCos component repository should be substituted
2702 for <literal>&lt;repo&gt;</literal>.
2703 </para>
2704 </callout>
2705 <callout arearefs="version">
2706 <para>
2707 If the package has been obtained via CVS or anonymous CVS then the
2708 package version will be <filename>current</filename>, as per the
2709 example. If instead the package has been obtained as part of a full
2710 eCos release or as a separate <filename>.epk</filename> file then the
2711 appropriate package version should be used instead of
2712 <filename>current</filename>.
2713 </para>
2714 </callout>
2715 <callout arearefs="args">
2716 <para>
2717 The <command>configure</command> script takes the usual arguments such
2718 as <parameter>--prefix=</parameter> to specify where the executables
2719 and support files should be installed. The only other parameter that
2720 some users may wish to specify is the location of a suitable Tcl
2721 installation. By default <application>usbhost</application> will use
2722 the existing Tcl installation in <filename class="directory">/usr</filename>,
2723 as provided by your Linux distribution. An alternative Tcl
2724 installation can be specified using the parameter
2725 <parameter>--with-tcl=</parameter>, or alternatively using some
2726 combination of <parameter>--with-tcl-include</parameter>,
2727 <parameter>--with-tcl-lib</parameter> and
2728 <parameter>--with-tcl-version</parameter>. 
2729 </para>
2730 </callout>
2731 <callout arearefs="root">
2732 <para>
2733 One of the host-side executables that gets built,
2734 <application>usbchmod</application>, needs to be installed with suid
2735 root privileges. Although the Linux kernel makes it possible for
2736 applications to perform low-level USB operations such as transmitting
2737 bulk packets, by default access to this functionality is restricted to
2738 programs with superuser privileges. It is undesirable to run a complex
2739 program such as <application>usbhost</application> with such
2740 privileges, especially since the program contains a general-purpose
2741 Tcl interpreter. Therefore when <application>usbhost</application>
2742 starts up and discovers that it does not have sufficient access to the
2743 appropriate entries in <filename class="directory">/proc/bus/usb</filename>, 
2744 it spawns an instance of <application>usbchmod</application> to modify
2745 the permissions on these entries. <application>usbchmod</application>
2746 will only do this for a USB device <literal>&quot;Red Hat eCos USB
2747 test&quot;</literal>, so installing this program suid root should not
2748 introduce any security problems.
2749 </para>
2750 </callout>
2751 </calloutlist>
2752
2753 <para>
2754 During <command>make install</command> the following actions will take
2755 place: 
2756 </para>
2757 <orderedlist>
2758 <listitem>
2759 <para>
2760 <application>usbhost</application> will be installed in <filename class="directory">/usr/local/bin</filename>,
2761 or some other <filename class="directory">bin</filename> directory if
2762 the default location is changed at configure-time using a
2763 <parameter>--prefix=</parameter> or similar option. It will be
2764 installed as the executable
2765 <application>usbhost_&lt;version&gt;</application>, for example
2766 <application>usbhost_current</application>, thus allowing several
2767 releases of the USB slave package to co-exist. For convenience a
2768 symbolic link from <filename>usbhost</filename> to this executable
2769 will be created, so users can just run <command>usbhost</command> to
2770 access the most recently-installed version.
2771 </para>
2772 </listitem>
2773 <listitem>
2774 <para>
2775 <application>usbchmod</application> will be installed in
2776 <filename class="directory">/usr/local/libexec/ecos/io_usb_slave_&lt;version&gt;</filename>.
2777 This program should only be run by <application>usbhost</application>,
2778 not invoked directly, so it is not placed in the <filename class="directory">bin</filename> 
2779 directory. Again the presence of the package version in the directory
2780 name allows multiple releases of the package to co-exist.
2781 </para>
2782 </listitem>
2783 <listitem>
2784 <para>
2785 A Tcl script <filename>usbhost.tcl</filename> will get installed in
2786 the same directory as <application>usbchmod</application>. This Tcl
2787 script is loaded automatically by the
2788 <application>usbhost</application> executable. 
2789 </para>
2790 </listitem>
2791 <listitem>
2792 <para>
2793 A number of additional Tcl scripts, for example
2794 <filename>list.tcl</filename> will get installed alongside
2795 <filename>usbhost.tcl</filename>. These correspond to various test
2796 cases provided as standard. If a given test case is specified on the
2797 command line and cannot be found relative to the current directory
2798 then <application>usbhost</application> will search the install
2799 directory for these test cases.
2800 </para>
2801 <note><para>
2802 Strictly speaking installing the <filename>usbhost.tcl</filename> and
2803 other Tcl scripts below the <filename class="directory">libexec</filename>
2804 directory deviates from standard practice: they are
2805 architecture-independent data files so should be installed below
2806 the <filename class="directory">share</filename> subdirectory. In
2807 practice the files are sufficiently small that there is no point in
2808 sharing them, and keeping them below <filename class="directory">libexec</filename>
2809 simplifies the host-side software somewhat.
2810 </para></note>
2811 </listitem>
2812 </orderedlist>
2813
2814 <para>
2815 The <command>usbhost</command> should be run only when there is a
2816 suitable target attached to the USB bus and running the
2817 <application>usbtarget</application> program. It will search
2818 <filename>/proc/bus/usb/devices</filename> for an entry corresponding
2819 to this program, invoke <application>usbchmod</application> if
2820 necessary to change the access rights, and then interact with
2821 <application>usbtarget</application> over the USB bus.
2822 <command>usbhost</command> should be invoked as follows:
2823 </para>
2824 <screen>
2825 $ usbhost [-v|--version] [-h|--help] [-V|--verbose] &lt;test&gt; [&lt;test parameters&gt;]
2826 </screen>
2827 <orderedlist>
2828 <listitem>
2829 <para>
2830 The <parameter>-v</parameter> or <parameter>--version</parameter>
2831 option will display version information for
2832 <application>usbhost</application> including the version of the USB
2833 slave package that was used to build the executable.
2834 </para>
2835 </listitem>
2836 <listitem>
2837 <para>
2838 The <parameter>-h</parameter> or <parameter>--help</parameter> option
2839 will display usage information.
2840 </para>
2841 </listitem>
2842 <listitem>
2843 <para>
2844 The <parameter>-V</parameter> or <parameter>--verbose</parameter>
2845 option can be used to obtain more information at run-time, for example
2846 some output for every USB transfer. This option can be repeated
2847 multiple times to increase the amount of output.
2848 </para>
2849 </listitem>
2850 <listitem>
2851 <para>
2852 The first argument that does not begin with a hyphen specifies a test
2853 that should be run, in the form of a Tcl script. For example an
2854 argument of <parameter>list.tcl</parameter> will cause
2855 <application>usbhost</application> to look for a script with that
2856 name, adding a <filename>.tcl</filename> suffix if necessarary, and
2857 run that script. <application>usbhost</application> will look in the
2858 current directory first, then in the install tree for standard test
2859 scripts provided by the USB slave package.
2860 </para>
2861 </listitem>
2862 <listitem>
2863 <para>
2864 Some test scripts may want their own parameters, for example a
2865 duration in seconds. These can be passed on the command line after
2866 the name of the test, for example
2867 <command>usbhost&nbsp;mytest&nbsp;60</command>. 
2868 </para>
2869 </listitem>
2870 </orderedlist>
2871 </refsect1>
2872
2873 <refsect1><title>Writing a Test</title>
2874 <para>
2875 Each test is defined by a Tcl script, running inside an interpreter
2876 provided by <application>usbhost</application>. In addition to the
2877 normal Tcl functionality this interpreter provides a number of
2878 variables and functions related to USB testing. For example there is a
2879 variable <varname>bulk_in_endpoints</varname> that lists all the
2880 endpoints on the target that can perform bulk IN operations, and a
2881 related array <varname>bulk_in</varname> which contains information
2882 such as the minimum and maximum packets sizes. There is a function
2883 <function>bulktest</function> which can be used to perform bulk tests
2884 on a particular endpoint. A simple test script aimed at specific
2885 hardware could ignore the information variables since it would know
2886 exactly what USB hardware is available on the target, whereas a
2887 general-purpose script would use the information to adapt to the
2888 hardware capabilities.
2889 </para>
2890 <para>
2891 To avoid namespace pollution all USB-related Tcl variables and
2892 functions live in the <varname>usbtest::</varname> namespace.
2893 Therefore accessing requires either explicitly including the
2894 namespace any references, for example
2895 <literal>$usbtest::bulk_in_endpoints</literal>, or by using Tcl's
2896 <function>namespace import</function> facility.
2897 </para>
2898 <para>
2899 A very simple test script might look like this:
2900 </para>
2901 <programlisting width=72>
2902 usbtest::bulktest 1 out 4000
2903 usbtest::bulktest 2 in  4000
2904 if { [usbtest::start 60] } {
2905     puts "Test successful"
2906 } else
2907     puts "Test failed"
2908     foreach result $usbtest::results {
2909         puts $result
2910     }
2911 }
2912 </programlisting>
2913 <para>
2914 This would perform a test run involving 4000 bulk transfers from the
2915 host to the target's endpoint 1, and concurrently 4000 bulk transfers
2916 from endpoint 2. Default settings for packet sizes, contents, and
2917 delays would be used. The actual test would not start running until
2918 <filename>usbtest</filename> is invoked, and it is expected that the
2919 test would complete within 60 seconds. If any failures occur then they
2920 are reported.
2921 </para>
2922 </refsect1>
2923
2924 <refsect1><title>Available Hardware</title>
2925 <para>
2926 Each target-side USB device driver provides information about the
2927 actual capabilities of the hardware, for example which endpoints are
2928 available. Strictly speaking it provides information about what is
2929 actually supported by the device driver, which may be a subset of what
2930 the hardware is capable of. For example, the hardware may support
2931 isochronous transfers on a particular endpoint but if there is no
2932 software support for this in the driver then this endpoint will not be
2933 listed. When <application>usbhost</application> first contacts the
2934 <application>usbtarget</application> program running on the target
2935 platform, it obtains this information and makes it available to test
2936 scripts via Tcl variables:
2937 </para>
2938 <variablelist>
2939 <varlistentry>
2940   <term><varname>bulk_in_endpoints</varname></term>
2941   <listitem><para>
2942     This is a simple list of the endpoints which can support bulk IN
2943     transfers. For example if the target-side hardware supports
2944     these transfers on endpoints 3 and 5 then the value would be
2945     <literal>&quot;3 5&quot;</literal> Typical test scripts would
2946     iterate over the list using something like:
2947   </para>
2948   <programlisting width=72>
2949   if { 0 != [llength $usbtest::bulk_in_endpoints] } {
2950       puts"Bulk IN endpoints: $usbtest::bulk_in_endpoints"
2951       foreach endpoint $usbtest:bulk_in_endpoints {
2952           &hellip;
2953       }
2954   }
2955   </programlisting>
2956   </listitem>
2957 </varlistentry>
2958 <varlistentry>
2959   <term><varname>bulk_in()</varname></term>
2960   <listitem><para>
2961   This array holds additional information about each bulk IN endpoint.
2962   The array is indexed by two fields, the endpoint number and one of
2963   <literal>min_size</literal>, <literal>max_size</literal>,
2964   <literal>max_in_padding</literal> and <literal>devtab</literal>:
2965   </para>
2966   <variablelist>
2967   <varlistentry>
2968     <term><literal>min_size</literal></term>
2969     <listitem><para>
2970     This field specifies a lower bound on the size of bulk transfers,
2971     and will typically will have a value of 1.
2972     </para>
2973     <note><para>
2974     The typical minimum transfer size of a single byte is not strictly
2975     speaking correct, since under some circumstances it can make sense
2976     to have a transfer size of zero bytes. However current target-side
2977     device drivers interpret a request to transfer zero bytes as a way
2978     for higher-level code to determine whether or not an endpoint is
2979     stalled, so it is not actually possible to perform zero-byte
2980     transfers. This issue will be addressed at some future point.
2981     </para></note>
2982     </listitem>
2983   </varlistentry>
2984   <varlistentry>
2985     <term><literal>max_size</literal></term>
2986     <listitem><para>
2987     This field specifies an upper bound on the size of bulk transfers.
2988     Some target-side drivers may be limited to transfers of say
2989     0x0FFFF bytes because of hardware limitations. In practice the
2990     transfer size is likely to be limited primarily to limit memory
2991     consumption of the test code on the target hardware, and to ensure
2992     that tests complete reasonably quickly. At the time of writing
2993     transfers are limited to 4K.
2994     </para></listitem>
2995   </varlistentry>
2996   <varlistentry>
2997     <term><literal>max_in_padding</literal></term>
2998     <listitem><para>
2999     On some hardware it may be necessary for the target-side device
3000     driver to send more data than is actually intended. For example
3001     the SA11x0 USB hardware cannot perform bulk transfers that are
3002     an exact multiple of 64 bytes, instead it must pad such
3003     transfers with an extra byte and the host must be ready to
3004     accept and discard this byte. The
3005     <literal>max_in_padding</literal> field indicates the amount of
3006     padding that is required. The low-level code inside
3007     <application>usbhost</application> will use this field
3008     automatically, and there is no need for test scripts to adjust
3009     packet sizes for padding. The field is provided for
3010     informational purposes only.
3011     </para></listitem>
3012   </varlistentry>
3013   <varlistentry>
3014     <term><literal>devtab</literal></term>
3015     <listitem><para>
3016     This is a string indicating whether or not the
3017     target-side USB device driver supports access to this endpoint
3018     via entries in the device table, in other words through
3019     conventional calls like <function>open</function> and
3020     <function>write</function>. Some device drivers may only
3021     support low-level USB access because typically that is what gets
3022     used by USB class-specific packages such as USB-ethernet.
3023     An empty string indicates that no devtab entry is available,
3024     otherwise it will be something like
3025     <literal>&quot;/dev/usbs2w&quot;</literal>. 
3026     </para></listitem>
3027   </varlistentry>
3028   </variablelist>
3029   <para>
3030   Typical test scripts would access this data using something like:
3031   </para>
3032   <programlisting width=72>
3033   foreach endpoint $usbtest:bulk_in_endpoints {
3034       puts "Endpoint $endpoint: "
3035       puts "    minimum transfer size $usbtest::bulk_in($endpoint,min_size)"
3036       puts "    maximum transfer size $usbtest::bulk_in($endpoint,max_size)"
3037       if { 0 == $usbtest::bulk_in($endpoint,max_in_padding) } {
3038           puts "    no IN padding required"
3039       } else {
3040           puts "    $usbtest::bulk_in($endpoint,max_in_padding) bytes of IN padding required"
3041       }
3042       if { "" == $usbtest::bulk_in($endpoint,devtab) } {
3043           puts "    no devtab entry provided"
3044       } else {
3045           puts "    corresponding devtab entry is $usbtest::bulk_in($endpoint,devtab)"
3046       }
3047   }
3048   </programlisting>
3049   </listitem>
3050 </varlistentry>
3051 <varlistentry>
3052   <term><varname>bulk_out_endpoint</varname></term>
3053   <listitem><para>
3054     This is a simple list of the endpoints which can support bulk OUT
3055     transfers. It is analogous to
3056     <varname>bulk_in_endpoints</varname>.
3057   </para></listitem>
3058 </varlistentry>
3059 <varlistentry>
3060   <term><varname>bulk_out()</varname></term>
3061   <listitem><para>
3062   This array holds additional information about each bulk OUT
3063   endpoint. It can be accessed in the same way as
3064   <varname>bulk_in()</varname>, except that there is no
3065   <literal>max_in_padding</literal> field because that field only
3066   makes sense for IN transfers.
3067   </para></listitem>
3068 </varlistentry>
3069 <varlistentry>
3070   <term><varname>control()</varname></term>
3071   <listitem><para>
3072   This array holds information about the control endpoint. It contains
3073   two fields, <literal>min_size</literal> and
3074   <literal>max_size</literal>. Note that there is no variable
3075   <varname>control_endpoints</varname> because a USB target always
3076   supports a single control endpoint <literal>0</literal>. Similarly
3077   the <varname>control</varname> array does not use an endpoint number
3078   as the first index because that would be redundant.
3079   </para></listitem>
3080 </varlistentry>
3081 <varlistentry>
3082   <term><varname>isochronous_in_endpoints</varname> and
3083         <varname>isochronous_in()</varname></term>
3084   <listitem><para>
3085   These variables provide the same information as
3086   <varname>bulk_in_endpoints</varname> and <varname>bulk_in</varname>,
3087   but for endpoints that support isochronous IN transfers.
3088   </para></listitem>
3089 </varlistentry>
3090 <varlistentry>
3091   <term><varname>isochronous_out_endpoints</varname> and
3092         <varname>isochronous_out()</varname></term>
3093   <listitem><para>
3094   These variables provide the same information as
3095   <varname>bulk_out_endpoints</varname> and <varname>bulk_out</varname>,
3096   but for endpoints that support isochronous OUT transfers.
3097   </para></listitem>
3098 </varlistentry>
3099 <varlistentry>
3100   <term><varname>interrupt_in_endpoints</varname> and
3101         <varname>interrupt_in()</varname></term>
3102   <listitem><para>
3103   These variables provide the same information as
3104   <varname>bulk_in_endpoints</varname> and <varname>bulk_in</varname>,
3105   but for endpoints that support interrupt IN transfers.
3106   </para></listitem>
3107 </varlistentry>
3108 <varlistentry>
3109   <term><varname>interrupt_out_endpoints</varname> and
3110         <varname>interrupt_out()</varname></term>
3111   <listitem><para>
3112   These variables provide the same information as
3113   <varname>bulk_out_endpoints</varname> and <varname>bulk_out</varname>,
3114   but for endpoints that support interrupt OUT transfers.
3115   </para></listitem>
3116 </varlistentry>
3117 </variablelist>
3118 </refsect1>
3119
3120
3121 <refsect1><title>Testing Bulk Transfers</title>
3122 <para>
3123 The main function for initiating a bulk test is
3124 <function>usbtest::bulktest</function>. This takes three compulsory
3125 arguments, and can be given a number of additional arguments to
3126 control the exact behaviour. The compulsory arguments are:
3127 </para>
3128 <variablelist>
3129 <varlistentry>
3130   <term>endpoint</term>
3131   <listitem><para>
3132     This specifies the endpoint to use. It should correspond to
3133     one of the entries in
3134     <varname>usbtest::bulk_in_endpoints</varname> or
3135     <varname>usbtest::bulk_out_endpoints</varname>, depending on the
3136     transfer direction.
3137   </para></listitem>
3138 </varlistentry>
3139 <varlistentry>
3140   <term>direction</term>
3141   <listitem><para>
3142   This should be either <literal>in</literal> or <literal>out</literal>.
3143   </para></listitem>
3144 </varlistentry>
3145 <varlistentry>
3146   <term>number of transfers</term>
3147   <listitem><para>
3148   This specifies the number of transfers that should take place. The
3149   testing software does not currently support the concept of performing
3150   transfers for a given period of time because synchronising this on
3151   both the host and a wide range of targets is difficult. However it
3152   is relatively easy to work out the approximate time a number of bulk
3153   transfers should take place, based on a typical bandwidth of
3154   1MB/second and assuming say a 1ms overhead per transfer.
3155   Alternatively a test script could perform a small initial run to
3156   determine what performance can actually be expected from a given
3157   target, and then use this information to run a much longer test.
3158   </para></listitem>
3159 </varlistentry>
3160 </variablelist>
3161 <para>
3162 Additional arguments can be used to control the exact transfer. For
3163 example a <parameter>txdelay+</parameter> argument can be used to
3164 slowly increase the delay between transfers. All such arguments involve
3165 a value which can be passed either as part of the argument itself,
3166 for example <literal>txdelay+=5</literal>, or as a subsequent
3167 argument, <literal>txdelay+ 5</literal>. The possible arguments fall
3168 into a number of categories: data, I/O mechanism, transmit size,
3169 receive size, transmit delay, and receive delay.
3170 </para>
3171
3172 <refsect2><title>Data</title>
3173 <para>
3174 An obvious parameter to control is the actual data that gets sent.
3175 This can be controlled by the argument <parameter>data</parameter>
3176 which can take one of five values: <literal>none</literal>,
3177 <literal>bytefill</literal>, <literal>intfill</literal>,
3178 <literal>byteseq</literal> and <literal>wordseq</literal>. The default
3179 value is <literal>none</literal>.
3180 </para>
3181 <variablelist>
3182 <varlistentry>
3183   <term><literal>none</literal></term>
3184   <listitem><para>
3185   The transmit code will not attempt to fill the buffer in any way,
3186   and the receive code will not check it. The actual data that gets
3187   transferred will be whatever happened to be in the buffer before
3188   the transfer started.
3189   </para></listitem>
3190 </varlistentry>
3191 <varlistentry>
3192   <term><literal>bytefill</literal></term>
3193   <listitem><para>
3194   The entire buffer will be filled with a single byte, as per
3195   <function>memset</function>. 
3196   </para></listitem>
3197 </varlistentry>
3198 <varlistentry>
3199   <term><literal>intfill</literal></term>
3200   <listitem><para>
3201   The buffer will be treated as an array of 32-bit integers, and will
3202   be filled with the same integer repeated the appropriate number of
3203   times. If the buffer size is not a multiple of four bytes then
3204   the last few bytes will be set to 0.
3205   </para></listitem>
3206 </varlistentry>
3207 <varlistentry>
3208   <term><literal>byteseq</literal></term>
3209   <listitem><para>
3210   The buffer will be filled with a sequence of bytes, generated by
3211   a linear congruential generator. If the first byte in the buffer is
3212   filled with the value <literal>x</literal>, the next byte will be
3213   <literal>(m*x)+i</literal>. For example a sequence of slowly
3214   incrementing bytes can be achieved by setting both the multiplier
3215   and the increment to 1. Alternatively a pseudo-random number
3216   sequence can be achieved using values 1103515245 and 12345, as
3217   per the standard C library <function>rand</function> function.
3218   For convenience these two constants are available as Tcl
3219   variables <varname>usbtest::MULTIPLIER</varname> and
3220   <varname>usbtest::INCREMENT</varname>.
3221   </para></listitem>
3222 </varlistentry>
3223 <varlistentry>
3224   <term><literal>wordseq</literal></term>
3225   <listitem><para>
3226   This acts like <literal>byteseq</literal>, except that the buffer is
3227   treated as an array of 32-bit integers rather than as an array of
3228   bytes. If the buffer is not a multiple of four bytes then the last
3229   few bytes will be filled with zeroes.
3230   </para></listitem>
3231 </varlistentry>
3232 </variablelist>
3233 <para>
3234 The above requires three additional parameters
3235 <parameter>data1</parameter>, <parameter>data*</parameter> and
3236 <parameter>data+</parameter>. <parameter>data1</parameter> specifies
3237 the value to be used for byte or word fills, or the first number when
3238 calculating a sequence. The default value is <literal>0</literal>.
3239 <parameter>data*</parameter> and <parameter>data+</parameter> specify
3240 the multiplier and increment for a sequence, and have default values
3241 of <literal>1</literal> and <literal>0</literal> respectively. For
3242 example, to perform a bulk transfer of a pseudo-random sequence of
3243 integers starting with 42 the following code could be used:
3244 </para>
3245 <programlisting width=72>
3246 bulktest 2 IN 1000 data=wordseq data1=42 \
3247     data* $usbtest::MULTIPLIER data+ $usbtest::INCREMENT
3248 </programlisting>
3249 <para>
3250 The above parameters define what data gets transferred for the first
3251 transfer, but a test can involve multiple transfers. The data format
3252 will be the same for all transfers, but it is possible to adjust the
3253 current value, the multiplier, and the increment between each
3254 transfer. This is achieved with parameters <parameter>data1*</parameter>,
3255 <parameter>data1+</parameter>, <parameter>data**</parameter>,
3256 <parameter>data*+</parameter>, <parameter>data+*</parameter>, and
3257 <parameter>data++</parameter>, with default values of 1 for each
3258 multiplier and 0 for each increment. For example, if the multiplier
3259 for the first transfer is set to <literal>2</literal> using
3260 <parameter>data*</parameter>, and arguments
3261 <literal>data**&nbsp;2</literal> and <literal>data*+&nbsp;-1</literal> are also
3262 supplied, then the multiplier for subsequent transfers will be
3263 <literal>3</literal>, <literal>5</literal>, <literal>9</literal>,
3264 &hellip;.
3265 </para>
3266
3267 <note><para>
3268 Currently it is not possible for a test script to send specific data,
3269 for example a specific sequence of bytes captured by a protocol analyser
3270 that caused a problem. If the transfer was from host to target then
3271 the target would have to know the exact sequence of bytes to expect,
3272 which means transferring data over the USB bus when that data is known
3273 to have caused problems in the past. Similarly for target to host
3274 transfers the target would have to know what bytes to send. A possible
3275 future extension of the USB testing support would allow for bounce
3276 operations, where a given message is first sent to the target and then
3277 sent back to the host, with only the host checking that the data was
3278 returned correctly.
3279 </para></note>
3280 </refsect2>
3281
3282 <refsect2><title>I/O Mechanism</title>
3283 <para>
3284 On the target side USB transfers can happen using either low-level
3285 USB calls such as <function>usbs_start_rx_buffer</function>, or by
3286 higher-level calls which go through the device table. By default the
3287 target-side code will use the low-level calls. If it is desired to
3288 test the higher-level calls instead, for example because those are
3289 what the application uses, then that can be achieved with an
3290 argument <parameter>mechanism=devtab</parameter>.
3291 </para>
3292 </refsect2>
3293
3294 <refsect2><title>Transmit Size</title>
3295 <para>
3296 The next set of arguments can be used to control the size of the
3297 transmitted buffer: <parameter>txsize1</parameter>,
3298 <parameter>txsize&gt;=</parameter>, <parameter>txsize&lt;=</parameter>
3299 <parameter>txsize*</parameter>, <parameter>txsize/</parameter>,
3300 and <parameter>txsize+</parameter>.
3301 </para>
3302 <para>
3303 <parameter>txsize1</parameter> determines the size of the first
3304 transfer, and has a default value of 32 bytes. The size of the next
3305 transfer is calculated by first multiplying by the
3306 <parameter>txsize*</parameter> value, then dividing by the
3307 <parameter>txsize/</parameter> value, and finally adding the
3308 <parameter>txsize+</parameter> value. The defaults for these are
3309 <literal>1</literal>, <literal>1</literal>, and <literal>0</literal>
3310 respectively, which means that the transfer size will remain
3311 unchanged. If for example the transfer size should increase by
3312 approximately 50 per cent each time then suitable values might be
3313 <literal>txsize*&nbsp;3</literal>, <literal>txsize/&nbsp;2</literal>,
3314 and <literal>txsize+&nbsp;1</literal>. 
3315 </para>
3316 <para>
3317 The <parameter>txsize&gt;=</parameter> and
3318 <parameter>txsize&lt;=</parameter> arguments can be used to impose
3319 lower and upper bounds on the transfer. By default the
3320 <literal>min_size</literal> and <literal>max_size</literal> values
3321 appropriate for the endpoint will be used. If at any time the
3322 current size falls outside the bounds then it will be normalized.
3323 </para>
3324 </refsect2>
3325
3326 <refsect2><title>Receive Size</title>
3327 <para>
3328 The receive size, in other words the number of bytes that either host
3329 or target will expect to receive as opposed to the number of bytes
3330 that actually get sent, can be adjusted using a similar set of
3331 arguments: <parameter>rxsize1</parameter>,
3332 <parameter>rxsize&gt;=</parameter>,
3333 <parameter>rxsize&lt;=</parameter>,
3334 <parameter>rxsize*</parameter>, <parameter>rxsize/</parameter> and
3335 <parameter>rxsize+</parameter>. The current receive size will be
3336 adjusted between transfers just like the transmit size. However when
3337 communicating over USB it is not a good idea to attempt to receive
3338 less data than will actually be sent: typically neither the hardware
3339 nor the software will be able to do anything useful with the excess,
3340 so there will be problems. Therefore if at any time the calculated
3341 receive size is less than the transmit size, the actual receive will
3342 be for the exact number of bytes that will get transmitted. However
3343 this will not affect the calculations for the next receive size.
3344 </para>
3345 <para>
3346 The default values for <parameter>rxsize1</parameter>,
3347 <parameter>rxsize*</parameter>, <parameter>rxsize/</parameter> and
3348 <parameter>rxsize+</parameter> are <literal>0</literal>,
3349 <literal>1</literal>, <literal>1</literal> and <literal>0</literal>
3350 respectively. This means that the calculated receive size will always
3351 be less than the transmit size, so the receive operation will be for
3352 the exact number of bytes transmitted. For some USB protocols this
3353 would not accurately reflect the traffic that will happen. For example
3354 with USB-ethernet transfer sizes will vary between 16 and 1516 bytes,
3355 so the receiver will always expect up to 1516 bytes. This can be
3356 achieved using <literal>rxsize1&nbsp;1516</literal>, leaving the
3357 other parameters at their default values.
3358 </para>
3359 <para>
3360 For target hardware which involves non-zero
3361 <literal>max_in_padding</literal>, on the host side the padding will
3362 be added automatically to the receive size if necessary.
3363 </para>
3364 </refsect2>
3365
3366 <refsect2><title>Transmit and Receive Delays</title>
3367 <para>
3368 Typically during the testing there will be some minor delays between
3369 transfers on both host and target. Some of these delays will be caused
3370 by timeslicing, for example another process running on the host, or a
3371 concurrent test thread running inside the target. Other delays will be
3372 caused by the USB bus itself, for example activity from another device
3373 on the bus. However it is desirable that test cases be allowed to
3374 inject additional and somewhat more controlled delays into the system,
3375 for example to make sure that the target behaves correctly even if the
3376 target is not yet ready to receive data from the host.
3377 </para>
3378 <para>
3379 The transmit delay is controlled by six parameters:
3380 <parameter>txdelay1</parameter>, <parameter>txdelay*</parameter>,
3381 <parameter>txdelay/</parameter>, <parameter>txdelay+</parameter>,
3382 <parameter>txdelay&gt;=</parameter> and
3383 <parameter>txdelay&lt;=</parameter>. The default values for these are
3384 <literal>0</literal>, <literal>1</literal>, <literal>1</literal>,
3385 <literal>0</literal>, <literal>0</literal> and
3386 <literal>1000000000</literal> respectively, so that by default
3387 transmits will happen as quickly as possible. Delays are measured in
3388 nanoseconds, so a value of <literal>1000000</literal> would correspond
3389 to a delay of 0.001 seconds or one millisecond. By default delays have
3390 an upper bound of one second. Between transfers the transmit delay is
3391 updated in much the same was as the transfer sizes.
3392 </para>
3393 <para>
3394 The receive delay is controlled by a similar set of six parameters:
3395 <parameter>rxdelay1</parameter>, <parameter>rxdelay*</parameter>,
3396 <parameter>rxdelay/</parameter>, <parameter>rxdelay+</parameter>,
3397 <parameter>rxdelay&gt;=</parameter> and
3398 <parameter>rxdelay&lt;=</parameter>. The default values for these are
3399 the same as for transmit delays.
3400 </para>
3401 <para>
3402 The transmit delay is used on the side which sends data over the USB
3403 bus, so for a bulk IN transfer it is the target that sends data and
3404 hence sleeps for the specified transmit delay, while the host receives
3405 data sleeps for the receive delay. For an OUT transfer the positions
3406 are reversed.
3407 </para>
3408 <para>
3409 It should be noted that although the delays are measured in
3410 nanoseconds, the actual delays will be much less precise and are
3411 likely to be of the order of milliseconds. The exact details will
3412 depend on the kernel clock speed.
3413 </para>
3414 </refsect2>
3415
3416 </refsect1>
3417
3418 <refsect1><title>Other Types of Transfer</title>
3419 <para>
3420 Support for testing other types of USB traffic such as isochronous
3421 transfers is not yet implemented.
3422 </para>
3423 </refsect1>
3424
3425 <refsect1><title>Starting a Test and Collecting Results</title>
3426 <para>
3427 A USB test script should prepare one or more transfers using
3428 appropriate functions such as <function>usbtest::bulktest</function>.
3429 Once all the individual tests have been prepared they can be started
3430 by a call to <function>usbtest::start</function>. This takes a single
3431 argument, a maximum duration measured in seconds. If all transfers
3432 have not been completed in the specified time then any remaining
3433 transfers will be aborted.
3434 </para>
3435 <para>
3436 <function>usbtest::start</function> will return <literal>1</literal>
3437 if all the tests have succeeded, or <literal>0</literal> if any of
3438 them have failed. More detailed reports will be stored in the
3439 Tcl variable <varname>usbtests::results</varname>, which will be a
3440 list of string messages.
3441 </para>
3442 </refsect1>
3443
3444 <refsect1><title>Existing Test Scripts</title>
3445 <para>
3446 A number of test scripts are provided as standard. These are located
3447 in the <filename class="directory">host</filename> subdirectory of the
3448 common USB slave package, and will be installed as part of the process
3449 of building the host-side software. When a script is specified on the
3450 command line <application>usbhost</application> will first search for
3451 it in the current directory, then in the install tree. Standard
3452 test scripts include the following:
3453 </para>
3454 <variablelist>
3455   <varlistentry><term><filename>list.tcl</filename></term>
3456     <listitem><para>
3457       This script simply displays information about the capabilities
3458       of the target platform, as provided by the target-side USB
3459       device driver. It can help with tracking down problems, but its
3460       primary purpose is to let users check that everything is working
3461       correctly: if running <command>usbhost list.tcl</command>
3462       outputs sensible information then the user knows that the
3463       target side is running correctly and that communication between
3464       host and target is possible.
3465     </para></listitem>
3466   </varlistentry>
3467   <varlistentry><term><filename>verbose.tcl</filename></term>
3468     <listitem><para>
3469       The target-side code can provide information about what
3470       is happening while tests are prepared and run. This facility
3471       should not normally be used since the extra I/O involved will
3472       significantly affect the behaviour of the system, but in some
3473       circumstances it may prove useful. Since an eCos application
3474       cannot easily be given command-line arguments the target-side
3475       verbosity level cannot be controlled using
3476       <parameter>-V</parameter> or <parameter>--verbose</parameter>
3477       options. Instead it can be controlled from inside
3478       <application>gdb</application> by changing the integer
3479       variable <varname>verbose</varname>. Alternatively it can
3480       be manipulated by running the test script
3481       <filename>verbose.tcl</filename>. This script takes a single
3482       argument, the desired verbosity level, which should be a small
3483       integer. For example, to disable target-side run-time logging
3484       the command <command>usbhost&nbsp;verbose&nbsp;0</command> can
3485       be used.
3486     </para></listitem>
3487   </varlistentry>
3488   <varlistentry><term><filename>bulk-boundaries.tcl</filename></term>
3489     <listitem><para> This script performs simple bulk IN and OUT
3490       transfers of different sizes around interesting boundaries. This
3491       test is useful to ensure the driver correctly handles the case
3492       where a transfer is just smaller than, the same size as, and
3493       just bigger than the hardware buffer in the endpoint hardware.
3494       This script takes no parameters. It determines what endpoints
3495       the device has by asking it.
3496     </para></listitem>
3497   </varlistentry>
3498 </variablelist>
3499 </refsect1>
3500
3501 <refsect1><title>Possible Problems</title>
3502 <para>
3503 If all transfers succeed within the specified time then both host and
3504 target remain in synch and further tests can be run without problem.
3505 However, if at any time a failure occurs then things get more
3506 complicated. For example, if the current test involves a series of
3507 bulk OUT transfers and the target detects that for one of these
3508 transfers it received less data than was expected then the test has
3509 failed, and the target will stop accepting data on this endpoint.
3510 However the host-side software may not have detected anything wrong
3511 and is now blocked trying to send the next lot of data.
3512 </para>
3513 <para>
3514 The test code goes to considerable effort to recover from problems
3515 such as these. On the host-side separate threads are used for
3516 concurrent transfers, and on the target-side appropriate asynchronous
3517 I/O mechanisms are used. In addition there is a control thread on the
3518 host that checks the state of all the main host-side threads, and the
3519 state of the target using private control messages. If it discovers
3520 that one side has stopped sending or receiving data because of an
3521 error and the other side is blocked as a result, it will set certain
3522 flags and then cause one additional transfer to take place. That
3523 additional transfer will have the effect of unblocking the other side,
3524 which then discovers that an error has occurred by checking the
3525 appropriate flags. In this way both host and target should end up back
3526 in synch, and it is possible to move on to the next set of tests.
3527 </para>
3528 <para>
3529 However, the above assumes that the testing has not triggered any
3530 serious hardware conditions. If instead the target-side hardware has
3531 been left in some strange state so that, for example, it will no
3532 longer raise an interrupt for traffic on a particular endpoint then
3533 recovery is not currently possible, and the testing software will just
3534 hang.
3535 </para>
3536 <para>
3537 A possible future enhancement to the testing software would allow the
3538 host-side to raise a USB reset signal whenever a failure occurs, in
3539 the hope that this would clear any remaining problems within the
3540 target-side USB hardware.
3541 </para>
3542
3543 </refsect1>
3544
3545 </refentry>
3546
3547 <!-- }}} -->
3548
3549 </part>
3550 <!-- /reference -->