]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/io/usb/slave/v2_0/tests/usbtarget.c
unified MX27, MX25, MX37 trees
[karo-tx-redboot.git] / packages / io / usb / slave / v2_0 / tests / usbtarget.c
1 /*{{{  Banner                                                   */
2
3 /*=================================================================
4 //
5 //        target.c
6 //
7 //        USB testing - target-side
8 //
9 //==========================================================================
10 //####ECOSGPLCOPYRIGHTBEGIN####
11 // -------------------------------------------
12 // This file is part of eCos, the Embedded Configurable Operating System.
13 // Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
14 //
15 // eCos is free software; you can redistribute it and/or modify it under
16 // the terms of the GNU General Public License as published by the Free
17 // Software Foundation; either version 2 or (at your option) any later version.
18 //
19 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
20 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
21 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
22 // for more details.
23 //
24 // You should have received a copy of the GNU General Public License along
25 // with eCos; if not, write to the Free Software Foundation, Inc.,
26 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
27 //
28 // As a special exception, if other files instantiate templates or use macros
29 // or inline functions from this file, or you compile this file and link it
30 // with other works to produce a work based on this file, this file does not
31 // by itself cause the resulting work to be covered by the GNU General Public
32 // License. However the source code for this file must still be made available
33 // in accordance with section (3) of the GNU General Public License.
34 //
35 // This exception does not invalidate any other reasons why a work based on
36 // this file might be covered by the GNU General Public License.
37 //
38 // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
39 // at http://sources.redhat.com/ecos/ecos-license/
40 // -------------------------------------------
41 //####ECOSGPLCOPYRIGHTEND####
42 //==========================================================================
43 //#####DESCRIPTIONBEGIN####
44 //
45 // This program performs appropriate USB initialization and initializes
46 // itself as a specific type of USB peripheral, Red Hat eCos testing.
47 // There is no actual host-side device driver for this, instead there is
48 // a test application which performs ioctl's on /proc/bus/usb/... and
49 // makes appropriate functionality available to a Tcl script.
50 //
51 // Author(s):     bartv
52 // Date:          2001-07-04
53 //####DESCRIPTIONEND####
54 //==========================================================================
55 */
56
57 /*}}}*/
58 /*{{{  #include's                                               */
59
60 #include <stdio.h>
61 #include <cyg/infra/cyg_ass.h>
62 #include <cyg/infra/diag.h>
63 #include <cyg/kernel/kapi.h>
64 #include <cyg/hal/hal_arch.h>
65 #include <cyg/io/io.h>
66 #include <cyg/io/usb/usbs.h>
67 #include <cyg/infra/testcase.h>
68 #include "protocol.h"
69
70 /*}}}*/
71
72 /*{{{  Statics                                                  */
73
74 // ----------------------------------------------------------------------------
75 // Statics.
76
77 // The number of endpoints supported by the device driver.
78 static int number_endpoints     = 0;
79
80 // The control endpoint
81 static usbs_control_endpoint* control_endpoint = (usbs_control_endpoint*) 0;
82
83 // Buffers for incoming and outgoing data, and a length field.
84 static unsigned char class_request[USBTEST_MAX_CONTROL_DATA + 1];
85 static unsigned char class_reply[USBTEST_MAX_CONTROL_DATA + 1];
86 static int           class_request_size  = 0;
87
88 // This semaphore is used by DSRs to wake up the main thread when work has to
89 // be done at thread level.
90 static cyg_sem_t    main_wakeup;
91
92 // And this function pointer identifies the work that has to be done.
93 static void         (*main_thread_action)(void)  = (void (*)(void)) 0;
94
95 // Is the system still busy processing a previous request? This variable is
96 // checked in response to the synch request. It may get updated in
97 // DSRs as well as at thread level, hence volatile.
98 static volatile int idle    = 1;
99
100 // Are any tests currently running?
101 static int          running = 0;
102
103 // Has the current batch of tests been terminated by the host? This
104 // flag is checked by the various test handlers at appropriate
105 // intervals, and helps to handle the case where one of the side has
106 // terminated early because an error has been detected.
107 static int          current_tests_terminated = 0;
108
109 // A counter for the number of threads involved in the current batch of tests.
110 static int          thread_counter    = 0;
111
112 // An extra buffer for recovery operations, for example to accept and discard
113 // data which the host is still trying to send.
114 static unsigned char recovery_buffer[USBTEST_MAX_BULK_DATA + USBTEST_MAX_BULK_DATA_EXTRA];
115
116 /*}}}*/
117 /*{{{  Logging                                                  */
118
119 // ----------------------------------------------------------------------------
120 // The target-side code can provide various levels of run-time logging.
121 // Obviously the verbose flag cannot be controlled by a command-line
122 // argument, but it can be set from inside gdb or alternatively by
123 // a request from the host.
124 //
125 // NOTE: is printf() the best I/O routine to use here?
126
127 static int verbose = 0;
128
129 #define VERBOSE(_level_, _format_, _args_...)   \
130     do {                                        \
131         if (verbose >= _level_) {               \
132             diag_printf(_format_, ## _args_);        \
133         }                                       \
134     } while (0);
135
136 /*}}}*/
137 /*{{{  Utilities                                                */
138
139 // ----------------------------------------------------------------------------
140 // A reimplementation of nanosleep, to avoid having to pull in the
141 // POSIX compatibility testing for USB testing.
142 static void
143 usbs_nanosleep(int delay)
144 {
145     cyg_tick_count_t ticks;
146     cyg_resolution_t resolution = cyg_clock_get_resolution(cyg_real_time_clock());
147
148     // (resolution.dividend/resolution.divisor) == nanoseconds/tick
149     //   e.g. 1000000000/100, i.e. 10000000 ns or 10 ms per tick
150     // So ticks = (delay * divisor) / dividend
151     //   e.g. (10000000 * 100) / 1000000000
152     // with a likely value of 0 for delays of less than the clock resolution,
153     // so round those up to one tick.
154
155     cyg_uint64 tmp = (cyg_uint64) delay;
156     tmp *= (cyg_uint64) resolution.divisor;
157     tmp /= (cyg_uint64) resolution.dividend;
158
159     ticks = (int) tmp;
160     if (0 != ticks) {
161         cyg_thread_delay(ticks);
162     }
163 }
164
165 // ----------------------------------------------------------------------------
166 // Fix any problems in the driver-supplied endpoint data
167 //
168 // Maximum transfer sizes are limited not just by the capabilities
169 // of the driver but also by the testing code itself, since e.g.
170 // buffers for transfers are statically allocated.
171 static void
172 fix_driver_endpoint_data(void)
173 {
174     int i;
175     
176     for (i = 0; !USBS_TESTING_ENDPOINTS_IS_TERMINATOR(usbs_testing_endpoints[i]); i++) {
177         if (USB_ENDPOINT_DESCRIPTOR_ATTR_BULK == usbs_testing_endpoints[i].endpoint_type) {
178             if ((-1 == usbs_testing_endpoints[i].max_size) ||
179                 (usbs_testing_endpoints[i].max_size > USBTEST_MAX_BULK_DATA)) {
180                 usbs_testing_endpoints[i].max_size = USBTEST_MAX_BULK_DATA;
181             }
182         }
183     }
184 }
185
186 // ----------------------------------------------------------------------------
187 // A heartbeat thread.
188 //
189 // USB tests can run for a long time with no traffic on the debug channel,
190 // which can cause problems. To avoid problems it is possible to have a
191 // heartbeat thread running in the background, sending output at one
192 // second intervals.
193 //
194 // Depending on the configuration the output may still be line-buffered,
195 // but that is still sufficient to keep things happy.
196
197 static cyg_bool     heartbeat = false;
198 static cyg_thread   heartbeat_data;
199 static cyg_handle_t heartbeat_handle;
200 static char         heartbeat_stack[CYGNUM_HAL_STACK_SIZE_TYPICAL];
201
202 static void
203 heartbeat_function(cyg_addrword_t arg __attribute((unused)))
204 {
205     char* message = "alive\n";
206     int i;
207     
208     for ( i = 0; ; i = (i + 1) % 6) {
209         usbs_nanosleep(1000000000);
210         if (heartbeat) {
211             diag_write_char(message[i]);
212         }
213     }
214 }
215
216 static void
217 start_heartbeat(void)
218 {
219     cyg_thread_create( 0, &heartbeat_function, 0,
220                        "heartbeat", heartbeat_stack, CYGNUM_HAL_STACK_SIZE_TYPICAL,
221                        &heartbeat_handle, &heartbeat_data);
222     cyg_thread_resume(heartbeat_handle);
223 }
224
225
226 /*}}}*/
227 /*{{{  Endpoint usage                                           */
228
229 // ----------------------------------------------------------------------------
230 // It is important to keep track of which endpoints are currently in use,
231 // because the behaviour of the USB I/O routines is undefined if there are
232 // concurrent attempts to communicate on the same endpoint. Normally this is
233 // not a problem because the host will ensure that a given endpoint is used
234 // for only one endpoint at a time, but when performing recovery action it
235 // is important that the system is sure that a given endpoint can be accessed
236 // safely.
237
238 static cyg_bool in_endpoint_in_use[16];
239 static cyg_bool out_endpoint_in_use[16];
240
241 // Lock the given endpoint. In theory this is only ever accessed from a single
242 // test thread at a time, but just in case...
243 static void
244 lock_endpoint(int endpoint, int direction)
245 {
246     CYG_ASSERTC((endpoint >=0) && (endpoint < 16));
247     CYG_ASSERTC((USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN == direction) || (USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT == direction));
248     
249     cyg_scheduler_lock();
250     if (0 == endpoint) {
251         // Comms traffic on endpoint 0 is implemented using reserved control messages.
252         // It is not really possible to have concurrent IN and OUT operations because
253         // the two would interfere with each other.
254         CYG_ASSERTC(!in_endpoint_in_use[0] && !out_endpoint_in_use[0]);
255         in_endpoint_in_use[0]  = true;
256         out_endpoint_in_use[0] = true;
257     } else if (USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN == direction) {
258         CYG_ASSERTC(!in_endpoint_in_use[endpoint]);
259         in_endpoint_in_use[endpoint] = true;
260     } else {
261         CYG_ASSERTC(!out_endpoint_in_use[endpoint]);
262         out_endpoint_in_use[endpoint] = true;
263     }
264     cyg_scheduler_unlock();
265 }
266
267 static void
268 unlock_endpoint(int endpoint, int direction)
269 {
270     CYG_ASSERTC((endpoint >= 0) && (endpoint < 16));
271     CYG_ASSERTC((USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN == direction) || (USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT == direction));
272     
273     if (0 == endpoint) {
274         CYG_ASSERTC(in_endpoint_in_use[0] && out_endpoint_in_use[0]);
275         in_endpoint_in_use[0]   = false;
276         out_endpoint_in_use[0]  = false;
277     } else if (USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN == direction) {
278         CYG_ASSERTC(in_endpoint_in_use[endpoint]);
279         in_endpoint_in_use[endpoint] = false;
280     } else {
281         CYG_ASSERTC(out_endpoint_in_use[endpoint]);
282         out_endpoint_in_use[endpoint] = false;
283     }
284 }
285
286 static cyg_bool
287 is_endpoint_locked(int endpoint, int direction)
288 {
289     cyg_bool    result = false;
290     
291     if (0 == endpoint) {
292         result = in_endpoint_in_use[0];
293     } else if (USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN == direction) {
294         result = in_endpoint_in_use[endpoint];
295     } else {
296         result = out_endpoint_in_use[endpoint];
297     }
298     return result;
299 }
300
301 // For a given endpoint number, direction and protocol, search through the table 
302 // supplied by the device driver of all available endpoints. This can be used
303 // to e.g. get hold of the name of the devtab entry or a pointer to the endpoint
304 // data structure itself.
305 static int
306 lookup_endpoint(int endpoint_number, int direction, int protocol)
307 {
308     int result = -1;
309     int i;
310
311     for (i = 0; !USBS_TESTING_ENDPOINTS_IS_TERMINATOR(usbs_testing_endpoints[i]); i++) {
312         if ((usbs_testing_endpoints[i].endpoint_type        == protocol)        &&
313             (usbs_testing_endpoints[i].endpoint_number      == endpoint_number) &&
314             (usbs_testing_endpoints[i].endpoint_direction   == direction)) {
315             result = i;
316             break;
317         }
318     }
319     return result;
320 }
321
322 /*}}}*/
323 /*{{{  Enumeration data                                         */
324
325 // ----------------------------------------------------------------------------
326 // The enumeration data.
327 //
328 // For simplicity this configuration involves just a single interface.
329 // The target has to list all the endpoints, or the Linux kernel will
330 // not allow application code to access them. Hence the information
331 // provided by the device drivers has to be turned into endpoint descriptors.
332
333 usb_configuration_descriptor usb_configuration = {
334     length:             USB_CONFIGURATION_DESCRIPTOR_LENGTH,
335     type:               USB_CONFIGURATION_DESCRIPTOR_TYPE,
336     total_length_lo:    USB_CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_LO(1, 0),
337     total_length_hi:    USB_CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_HI(1, 0),
338     number_interfaces:  1,
339     configuration_id:   1,      // id 0 is special according to the spec
340     configuration_str:  0,
341     attributes:         USB_CONFIGURATION_DESCRIPTOR_ATTR_REQUIRED |
342                         USB_CONFIGURATION_DESCRIPTOR_ATTR_SELF_POWERED,
343     max_power:          50
344 };
345
346 usb_interface_descriptor usb_interface = {
347     length:             USB_INTERFACE_DESCRIPTOR_LENGTH,
348     type:               USB_INTERFACE_DESCRIPTOR_TYPE,
349     interface_id:       0,
350     alternate_setting:  0,
351     number_endpoints:   0,
352     interface_class:    USB_INTERFACE_DESCRIPTOR_CLASS_VENDOR,
353     interface_subclass: USB_INTERFACE_DESCRIPTOR_SUBCLASS_VENDOR,
354     interface_protocol: USB_INTERFACE_DESCRIPTOR_PROTOCOL_VENDOR,
355     interface_str:      0
356 };
357
358 usb_endpoint_descriptor usb_endpoints[USBTEST_MAX_ENDPOINTS];
359                                
360 const unsigned char* usb_strings[] = {
361     "\004\003\011\004",
362     "\020\003R\000e\000d\000 \000H\000a\000t\000",
363     "\054\003R\000e\000d\000 \000H\000a\000t\000 \000e\000C\000o\000s\000 \000"
364     "U\000S\000B\000 \000t\000e\000s\000t\000"
365 };
366
367 usbs_enumeration_data usb_enum_data = {
368     {
369         length:                 USB_DEVICE_DESCRIPTOR_LENGTH,
370         type:                   USB_DEVICE_DESCRIPTOR_TYPE,
371         usb_spec_lo:            USB_DEVICE_DESCRIPTOR_USB11_LO,
372         usb_spec_hi:            USB_DEVICE_DESCRIPTOR_USB11_HI,
373         device_class:           USB_DEVICE_DESCRIPTOR_CLASS_VENDOR,
374         device_subclass:        USB_DEVICE_DESCRIPTOR_SUBCLASS_VENDOR,
375         device_protocol:        USB_DEVICE_DESCRIPTOR_PROTOCOL_VENDOR,
376         max_packet_size:        8,
377         vendor_lo:              0x42,   // Note: this is not an allocated vendor id
378         vendor_hi:              0x42,
379         product_lo:             0x00,
380         product_hi:             0x01,
381         device_lo:              0x00,
382         device_hi:              0x01,
383         manufacturer_str:       1,
384         product_str:            2,
385         serial_number_str:      0,
386         number_configurations:  1
387     },
388     total_number_interfaces:    1,
389     total_number_endpoints:     0,
390     total_number_strings:       3,
391     configurations:             &usb_configuration,
392     interfaces:                 &usb_interface,
393     endpoints:                  usb_endpoints,
394     strings:                    usb_strings
395 };
396
397 static void
398 provide_endpoint_enumeration_data(void)
399 {
400     int enum_endpoint_count = 0;
401     int i;
402
403     for (i = 0; !USBS_TESTING_ENDPOINTS_IS_TERMINATOR(usbs_testing_endpoints[i]); i++) {
404
405         // The control endpoint need not appear in the enumeration data.
406         if (USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL == usbs_testing_endpoints[i].endpoint_type) {
407             continue;
408         }
409
410         usb_endpoints[enum_endpoint_count].length          = USB_ENDPOINT_DESCRIPTOR_LENGTH;
411         usb_endpoints[enum_endpoint_count].type            = USB_ENDPOINT_DESCRIPTOR_TYPE;
412         usb_endpoints[enum_endpoint_count].endpoint        = usbs_testing_endpoints[i].endpoint_number |
413                                                              usbs_testing_endpoints[i].endpoint_direction;
414
415         switch (usbs_testing_endpoints[i].endpoint_type) {
416           case USB_ENDPOINT_DESCRIPTOR_ATTR_BULK:
417             usb_endpoints[enum_endpoint_count].attributes      = USB_ENDPOINT_DESCRIPTOR_ATTR_BULK;
418             usb_endpoints[enum_endpoint_count].max_packet_lo   = 64;
419             usb_endpoints[enum_endpoint_count].max_packet_hi   = 0;
420             usb_endpoints[enum_endpoint_count].interval        = 0;
421             break;
422             
423           case USB_ENDPOINT_DESCRIPTOR_ATTR_ISOCHRONOUS:
424             usb_endpoints[enum_endpoint_count].attributes      = USB_ENDPOINT_DESCRIPTOR_ATTR_ISOCHRONOUS;
425             usb_endpoints[enum_endpoint_count].max_packet_lo   = usbs_testing_endpoints[i].max_size & 0x0FF;
426             usb_endpoints[enum_endpoint_count].max_packet_hi   = (usbs_testing_endpoints[i].max_size >> 8) & 0x0FF;
427             usb_endpoints[enum_endpoint_count].interval        = 1;
428             break;
429             
430           case USB_ENDPOINT_DESCRIPTOR_ATTR_INTERRUPT:
431             usb_endpoints[enum_endpoint_count].attributes      = USB_ENDPOINT_DESCRIPTOR_ATTR_INTERRUPT;
432             usb_endpoints[enum_endpoint_count].max_packet_lo   = (unsigned char) usbs_testing_endpoints[i].max_size;
433             usb_endpoints[enum_endpoint_count].max_packet_hi   = 0;
434             usb_endpoints[enum_endpoint_count].interval        = 1;    // NOTE: possibly incorrect
435             break;
436         }
437
438         enum_endpoint_count++;
439     }
440
441     usb_interface.number_endpoints          = enum_endpoint_count;
442     usb_enum_data.total_number_endpoints    = enum_endpoint_count;
443     usb_configuration.total_length_lo       = USB_CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_LO(1, enum_endpoint_count);
444     usb_configuration.total_length_hi       = USB_CONFIGURATION_DESCRIPTOR_TOTAL_LENGTH_HI(1, enum_endpoint_count);
445 }
446
447 /*}}}*/
448 /*{{{  Host/target common code                                  */
449
450 #define TARGET
451 #include "common.c"
452
453 /*}}}*/
454 /*{{{  The tests                                                */
455
456 /*{{{  UsbTest structure                                        */
457
458 // ----------------------------------------------------------------------------
459 // All the information associated with a particular testcase. Much of this
460 // is identical to the equivalent host-side structure, but some additional
461 // information is needed so the structure and associated routines are not
462 // shared.
463 typedef struct UsbTest {
464
465     // A unique identifier to make verbose output easier to understand
466     int                 id;
467     
468     // Which test should be run
469     usbtest             which_test;
470
471     // Test-specific details.
472     union {
473         UsbTest_Bulk        bulk;
474         UsbTest_ControlIn   control_in;
475     } test_params;
476
477     // How to recover from any problems. Specifically, what kind of message
478     // could the target send or receive that would unlock the thread on this
479     // side.
480     UsbTest_Recovery    recovery;
481
482     // The test result, to be collected and passed back to the host.
483     int                 result_pass;
484     char                result_message[USBTEST_MAX_MESSAGE];
485
486     // Support for synchronization. This allows the UsbTest structure to be
487     // used as the callback data for low-level USB calls.
488     cyg_sem_t           sem;
489     int                 transferred;
490
491     // Some tests may need extra cancellation support
492     void                (*cancel_fn)(struct UsbTest*);
493     unsigned char       buffer[USBTEST_MAX_BULK_DATA + USBTEST_MAX_BULK_DATA_EXTRA];
494 } UsbTest;
495
496 // Reset the information in a given test. This is used by the pool allocation
497 // code. The data union is left alone, filling in the appropriate union
498 // member is left to other code.
499 static void
500 reset_usbtest(UsbTest* test)
501 {
502     static int next_id = 1;
503     test->id                    = next_id++;
504     test->which_test            = usbtest_invalid;
505     usbtest_recovery_reset(&(test->recovery));
506     test->result_pass           = 0;
507     test->result_message[0]     = '\0';
508     cyg_semaphore_init(&(test->sem), 0);
509     test->transferred           = 0;
510     test->cancel_fn             = (void (*)(UsbTest*)) 0;
511 }
512
513 // Forward declaration. The pool code depends on run_test(), setting up a test requires the pool.
514 static UsbTest* pool_allocate(void);
515
516 /*}}}*/
517 /*{{{  Bulk transfers                                           */
518
519 /*{{{  handle_test_bulk()                                       */
520
521 // Prepare for a bulk transfer test. This means allocating a thread to do
522 // the work, and extracting the test parameters from the current buffer.
523 // The thread allocation code does not require any locking since all worker
524 // threads should be idle when starting a new thread, so the work can be
525 // done entirely at DSR level and no synch is required.
526 static usbs_control_return
527 handle_test_bulk(usb_devreq* req)
528 {
529     UsbTest*    test;
530     int         index   = 0;
531
532     test = pool_allocate();
533     unpack_usbtest_bulk(&(test->test_params.bulk), class_request, &index);
534     test->which_test = (USB_DEVREQ_DIRECTION_IN == (test->test_params.bulk.endpoint & USB_DEVREQ_DIRECTION_MASK)) ?
535         usbtest_bulk_in : usbtest_bulk_out;
536
537     VERBOSE(3, "Preparing USB bulk test on endpoint %d, direction %s, for %d packets\n", \
538             test->test_params.bulk.endpoint & ~USB_DEVREQ_DIRECTION_MASK,                \
539             (usbtest_bulk_in == test->which_test) ? "IN" : "OUT",                           \
540             test->test_params.bulk.number_packets);
541     VERBOSE(3, "  I/O mechanism is %s\n", \
542             (usb_io_mechanism_usb == test->test_params.bulk.io_mechanism) ? "low-level USB" : \
543             (usb_io_mechanism_dev == test->test_params.bulk.io_mechanism) ? "devtab" : "<invalid>");
544     VERBOSE(3, "  Data format %s, data1 %d, data* %d, data+ %d, data1* %d, data1+ %d, data** %d, data*+ %d, data+* %d, data++ %d\n",\
545             (usbtestdata_none     == test->test_params.bulk.data.format) ? "none" :     \
546             (usbtestdata_bytefill == test->test_params.bulk.data.format) ? "bytefill" : \
547             (usbtestdata_wordfill == test->test_params.bulk.data.format) ? "wordfill" : \
548             (usbtestdata_byteseq  == test->test_params.bulk.data.format) ? "byteseq"  : \
549             (usbtestdata_wordseq  == test->test_params.bulk.data.format) ? "wordseq"  : "<invalid>", \
550             test->test_params.bulk.data.seed,                            \
551             test->test_params.bulk.data.multiplier,                      \
552             test->test_params.bulk.data.increment,                       \
553             test->test_params.bulk.data.transfer_seed_multiplier,        \
554             test->test_params.bulk.data.transfer_seed_increment,         \
555             test->test_params.bulk.data.transfer_multiplier_multiplier,  \
556             test->test_params.bulk.data.transfer_multiplier_increment,   \
557             test->test_params.bulk.data.transfer_increment_multiplier,   \
558             test->test_params.bulk.data.transfer_increment_increment);
559     VERBOSE(3, "  txsize1 %d, txsize>= %d, txsize<= %d, txsize* %d, txsize/ %d, txsize+ %d\n", \
560             test->test_params.bulk.tx_size,         test->test_params.bulk.tx_size_min,        \
561             test->test_params.bulk.tx_size_max,     test->test_params.bulk.tx_size_multiplier, \
562             test->test_params.bulk.tx_size_divisor, test->test_params.bulk.tx_size_increment);
563     VERBOSE(3, "  rxsize1 %d, rxsize>= %d, rxsize<= %d, rxsize* %d, rxsize/ %d, rxsize+ %d\n", \
564             test->test_params.bulk.rx_size,         test->test_params.bulk.rx_size_min,        \
565             test->test_params.bulk.rx_size_max,     test->test_params.bulk.rx_size_multiplier, \
566             test->test_params.bulk.rx_size_divisor, test->test_params.bulk.rx_size_increment);
567     VERBOSE(3, "  txdelay1 %d, txdelay>= %d, txdelay<= %d, txdelay* %d, txdelay/ %d, txdelay+ %d\n", \
568             test->test_params.bulk.tx_delay,         test->test_params.bulk.tx_delay_min,            \
569             test->test_params.bulk.tx_delay_max,     test->test_params.bulk.tx_delay_multiplier,     \
570             test->test_params.bulk.tx_delay_divisor, test->test_params.bulk.tx_delay_increment);
571     VERBOSE(3, "  rxdelay1 %d, rxdelay>= %d, rxdelay<= %d, rxdelay* %d, rxdelay/ %d, rxdelay+ %d\n", \
572             test->test_params.bulk.rx_delay,         test->test_params.bulk.rx_delay_min,            \
573             test->test_params.bulk.rx_delay_max,     test->test_params.bulk.rx_delay_multiplier,     \
574             test->test_params.bulk.rx_delay_divisor, test->test_params.bulk.rx_delay_increment);
575     
576     return USBS_CONTROL_RETURN_HANDLED;
577 }
578
579 /*}}}*/
580 /*{{{  run_test_bulk_out()                                      */
581
582 // The same callback can be used for IN and OUT transfers. Note that
583 // starting the next transfer is left to the thread, it is not done
584 // at DSR level.
585 static void
586 run_test_bulk_in_out_callback(void* callback_arg, int transferred)
587 {
588     UsbTest*    test    = (UsbTest*) callback_arg;
589     test->transferred   = transferred;
590     cyg_semaphore_post(&(test->sem));
591 }
592
593 // OUT transfers, i.e. the host will be sending some number of
594 // packets. The I/O can happen in a number of different ways, e.g. via
595 // the low-level USB API or via devtab routines.
596 static void
597 run_test_bulk_out(UsbTest* test)
598 {
599     unsigned char*      buf;
600     int                 endpoint_number = test->test_params.bulk.endpoint & ~USB_DEVREQ_DIRECTION_MASK;
601     int                 ep_index;
602     usbs_rx_endpoint*   endpoint        = 0;
603     cyg_io_handle_t     io_handle       = (cyg_io_handle_t)0;
604     int                 alignment;
605     int                 transferred;
606     int                 i;
607
608     VERBOSE(1, "Starting test %d, bulk out on endpoint %d\n", test->id, endpoint_number);
609
610     ep_index = lookup_endpoint(endpoint_number, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT, USB_ENDPOINT_DESCRIPTOR_ATTR_BULK);
611     if (ep_index == -1) {
612             test->result_pass   = 0;
613             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
614                      "Target, bulk OUT transfer on endpoint %d: no such bulk endpoint", endpoint_number);
615             return;
616     }
617     endpoint    = (usbs_rx_endpoint*) usbs_testing_endpoints[ep_index].endpoint;
618     alignment   = usbs_testing_endpoints[ep_index].alignment;
619     if (0 != alignment) {
620         buf         = (unsigned char*) ((((cyg_uint32)test->buffer) + alignment - 1) & ~(alignment - 1));
621     } else {
622         buf = test->buffer;
623     }
624     
625     CYG_ASSERTC((usb_io_mechanism_usb == test->test_params.bulk.io_mechanism) || \
626                 (usb_io_mechanism_dev == test->test_params.bulk.io_mechanism));
627     if (usb_io_mechanism_dev == test->test_params.bulk.io_mechanism) {
628         if (((const char*)0 == usbs_testing_endpoints[ep_index].devtab_entry) ||
629             (0 != cyg_io_lookup(usbs_testing_endpoints[ep_index].devtab_entry, &io_handle))) {
630             
631             test->result_pass   = 0;
632             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
633                      "Target, bulk OUT transfer on endpoint %d: no devtab entry", endpoint_number);
634             return;
635         }
636     }
637
638     // Make sure nobody else is using this endpoint
639     lock_endpoint(endpoint_number, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT);
640
641     for (i = 0; i < test->test_params.bulk.number_packets; i++) {
642         int rx_size = test->test_params.bulk.rx_size;
643         int tx_size = test->test_params.bulk.tx_size;
644
645         VERBOSE(2, "Bulk OUT test %d: iteration %d, rx size %d, tx size %d\n", test->id, i, rx_size, tx_size);
646         
647         if (rx_size < tx_size) {
648             rx_size = tx_size;
649             VERBOSE(2, "Bulk OUT test %d: iteration %d, packet size reset to %d to match tx size\n",
650                     test->id, i, rx_size);
651         }
652                                                               
653         test->recovery.endpoint     = endpoint_number | USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT;
654         test->recovery.protocol     = USB_ENDPOINT_DESCRIPTOR_ATTR_BULK;
655         test->recovery.size         = rx_size;
656
657         // Make sure there is no old data lying around
658         if (usbtestdata_none != test->test_params.bulk.data.format) {
659             memset(buf, 0, rx_size);
660         }
661
662         // Do the actual transfer, using the I/O mechanism specified for this test.
663         switch (test->test_params.bulk.io_mechanism)
664         {
665           case usb_io_mechanism_usb :
666           {
667               test->transferred = 0;
668               usbs_start_rx_buffer(endpoint, buf, rx_size, &run_test_bulk_in_out_callback, (void*) test);
669               cyg_semaphore_wait(&(test->sem));
670               transferred = test->transferred;
671               break;
672           }
673
674           case usb_io_mechanism_dev :
675           {
676               int result;
677               transferred   = rx_size;
678               result = cyg_io_read(io_handle, (void*) buf, &transferred);
679               if (result < 0) {
680                   transferred = result;
681               }
682               break;
683           }
684
685           default:
686             CYG_FAIL("Invalid test mechanism specified");
687             break;
688         }
689
690         // Has this test been aborted for some reason?
691         if (current_tests_terminated) {
692             VERBOSE(2, "Bulk OUT test %d: iteration %d, termination detected\n", test->id, i);
693             test->result_pass = 0;
694             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
695                      "Target, bulk OUT transfer on endpoint %d: transfer aborted after iteration %d", endpoint_number, i);
696             break;
697         }
698
699         // If an error occurred, abort this run
700         if (transferred < 0) {
701             test->result_pass   = 0;
702             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
703                      "Target, bulk OUT transfer on endpoint %d: transfer failed with %d", endpoint_number, transferred);
704             VERBOSE(2, "Bulk OUT test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
705             break;
706         }
707
708         // Did the host send the expected amount of data?
709         if (transferred < test->test_params.bulk.tx_size) {
710             test->result_pass   = 0;
711             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
712                      "Target, bulk OUT transfer on endpoint %d : the host only sent %d bytes when %d were expected",
713                      endpoint_number, transferred, tx_size);
714             VERBOSE(2, "Bulk OUT test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
715             break;
716         }
717
718         if (verbose >= 3) {
719             // Output the first 32 bytes of data
720             char msg[256];
721             int  index;
722             int  j;
723             index = snprintf(msg, 255, "Bulk OUT test %d: iteration %d, transferred %d\n    Data %s:",
724                              test->id, i, transferred,
725                              (usbtestdata_none == test->test_params.bulk.data.format) ? "(uninitialized)" : "");
726
727             for (j = 0; ((j + 3) < transferred) && (j < 32); j+= 4) {
728                 index += snprintf(msg+index, 255-index, " %02x%02x%02x%02x",
729                                   buf[j], buf[j+1], buf[j+2], buf[j+3]);
730             }
731             if (j < 32) {
732                 index += snprintf(msg+index, 255-index, " ");
733                 for ( ; j < transferred; j++) {
734                     index += snprintf(msg+index, 255-index, "%02x", buf[j]);
735                 }
736                 
737             }
738             VERBOSE(3, "%s\n", msg);
739         }
740         
741         // Is the data correct?
742         if (!usbtest_check_buffer(&(test->test_params.bulk.data), buf, transferred)) {
743             test->result_pass   = 0;
744             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
745                      "Target, bulk OUT transfer on endpoint %d : mismatch between received and expected data", endpoint_number);
746             VERBOSE(2, "Bulk OUt test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
747             break;
748         }
749
750         if (0 != test->test_params.bulk.rx_delay) {
751             VERBOSE(2, "Bulk OUT test %d: iteration %d, sleeping for %d nanoseconds\n", test->id, \
752                     i, test->test_params.bulk.rx_delay);
753             usbs_nanosleep(test->test_params.bulk.rx_delay);
754         }
755         
756         // Move on to the next transfer
757         USBTEST_BULK_NEXT(test->test_params.bulk);
758     }
759
760     // Always unlock the endpoint on completion
761     unlock_endpoint(endpoint_number, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT);
762
763     // If all the packets have been transferred this test has passed.
764     if (i >= test->test_params.bulk.number_packets) {
765         test->result_pass   = 1;
766     }
767     
768     VERBOSE(1, "Test %d bulk OUT on endpoint %d, result %d\n", test->id, endpoint_number, test->result_pass);
769 }
770
771 /*}}}*/
772 /*{{{  run_test_bulk_in()                                       */
773
774 // IN transfers, i.e. the host is expected to receive some data. These are slightly
775 // easier than OUT transfers because it is the host that will do the checking.
776 static void
777 run_test_bulk_in(UsbTest* test)
778 {
779     unsigned char*      buf;
780     int                 endpoint_number = test->test_params.bulk.endpoint & ~USB_DEVREQ_DIRECTION_MASK;
781     int                 ep_index;
782     usbs_tx_endpoint*   endpoint        = 0;
783     cyg_io_handle_t     io_handle       = (cyg_io_handle_t)0;
784     int                 alignment;
785     int                 transferred;
786     int                 i;
787
788     VERBOSE(1, "Starting test %d, bulk IN on endpoint %d\n", test->id, endpoint_number);
789     
790     ep_index = lookup_endpoint(endpoint_number, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN, USB_ENDPOINT_DESCRIPTOR_ATTR_BULK);
791     if (ep_index == -1) {
792             test->result_pass   = 0;
793             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
794                      "Target, bulk IN transfer on endpoint %d: no such bulk endpoint", endpoint_number);
795             return;
796     }
797     endpoint    = (usbs_tx_endpoint*) usbs_testing_endpoints[ep_index].endpoint;
798     alignment   = usbs_testing_endpoints[ep_index].alignment;
799     if (0 != alignment) {
800         buf         = (unsigned char*) ((((cyg_uint32)test->buffer) + alignment - 1) & ~(alignment - 1));
801     } else {
802         buf = test->buffer;
803     }
804     
805     CYG_ASSERTC((usb_io_mechanism_usb == test->test_params.bulk.io_mechanism) || \
806                 (usb_io_mechanism_dev == test->test_params.bulk.io_mechanism));
807     if (usb_io_mechanism_dev == test->test_params.bulk.io_mechanism) {
808         if (((const char*)0 == usbs_testing_endpoints[ep_index].devtab_entry) ||
809             (0 != cyg_io_lookup(usbs_testing_endpoints[ep_index].devtab_entry, &io_handle))) {
810             
811             test->result_pass   = 0;
812             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
813                      "Target, bulk IN transfer on endpoint %d: no devtab entry", endpoint_number);
814             return;
815         }
816     }
817
818     // Make sure nobody else is using this endpoint
819     lock_endpoint(endpoint_number, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
820     
821     for (i = 0; i < test->test_params.bulk.number_packets; i++) {
822         int packet_size = test->test_params.bulk.tx_size;
823         
824         test->recovery.endpoint     = endpoint_number | USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN;
825         test->recovery.protocol     = USB_ENDPOINT_DESCRIPTOR_ATTR_BULK;
826         test->recovery.size         = packet_size + usbs_testing_endpoints[ep_index].max_in_padding;
827
828         CYG_ASSERTC(sizeof(test->buffer) > packet_size);
829         
830         // Make sure the buffer contains the data expected by the host
831         usbtest_fill_buffer(&(test->test_params.bulk.data), buf, packet_size);
832
833         if (verbose < 3) {
834             VERBOSE(2, "Bulk OUT test %d: iteration %d, packet size %d\n", test->id, i, packet_size);
835         } else {
836             // Output the first 32 bytes of data as well.
837             char msg[256];
838             int  index;
839             int  j;
840             index = snprintf(msg, 255, "Bulk IN test %d: iteration %d, packet size %d\n    Data %s:",
841                              test->id, i, packet_size,
842                              (usbtestdata_none == test->test_params.bulk.data.format) ? "(uninitialized)" : "");
843
844             for (j = 0; ((j + 3) < packet_size) && (j < 32); j+= 4) {
845                 index += snprintf(msg+index, 255-index, " %02x%02x%02x%02x",
846                                   buf[j], buf[j+1], buf[j+2], buf[j+3]);
847             }
848             if (j < 32) {
849                 index += snprintf(msg+index, 255-index, " ");
850                 for ( ; j < packet_size; j++) {
851                     index += snprintf(msg+index, 255-index, "%02x", buf[j]);
852                 }
853                 
854             }
855             VERBOSE(3, "%s\n", msg);
856         }
857         
858         // Do the actual transfer, using the I/O mechanism specified for this test.
859         switch (test->test_params.bulk.io_mechanism)
860         {
861           case usb_io_mechanism_usb :
862           {
863               test->transferred = 0;
864               usbs_start_tx_buffer(endpoint, buf, packet_size, &run_test_bulk_in_out_callback, (void*) test);
865               cyg_semaphore_wait(&(test->sem));
866               transferred = test->transferred;
867               break;
868           }
869
870           case usb_io_mechanism_dev :
871           {
872               int result;
873               transferred   = packet_size;
874               result = cyg_io_write(io_handle, (void*) buf, &transferred);
875               if (result < 0) {
876                   transferred = result;
877               }
878               break;
879           }
880
881           default:
882             CYG_FAIL("Invalid test mechanism specified");
883             break;
884         }
885
886         // Has this test been aborted for some reason?
887         if (current_tests_terminated) {
888             VERBOSE(2, "Bulk IN test %d: iteration %d, termination detected\n", test->id, i);
889             test->result_pass   = 0;
890             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
891                      "Target, bulk IN transfer on endpoint %d : terminated on iteration %d, packet_size %d\n",
892                      endpoint_number, i, packet_size);
893             break;
894         }
895
896         // If an error occurred, abort this run
897         if (transferred < 0) {
898             test->result_pass   = 0;
899             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
900                      "Target, bulk IN transfer on endpoint %d: transfer failed with %d", endpoint_number, transferred);
901             VERBOSE(2, "Bulk IN test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
902             break;
903         }
904
905         // No need to check the transfer size, the USB code is only
906         // allowed to send the exact amount of data requested.
907
908         if (0 != test->test_params.bulk.tx_delay) {
909             VERBOSE(2, "Bulk IN test %d: iteration %d, sleeping for %d nanoseconds\n", test->id, i, \
910                     test->test_params.bulk.tx_delay);
911             usbs_nanosleep(test->test_params.bulk.tx_delay);
912         }
913         
914         // Move on to the next transfer
915         USBTEST_BULK_NEXT(test->test_params.bulk);
916     }
917
918     // Always unlock the endpoint on completion
919     unlock_endpoint(endpoint_number, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
920
921     // If all the packets have been transferred this test has passed.
922     if (i >= test->test_params.bulk.number_packets) {
923         test->result_pass   = 1;
924     }
925     
926     VERBOSE(1, "Test %d bulk IN on endpoint %d, result %d\n", test->id, endpoint_number, test->result_pass);
927 }
928
929 /*}}}*/
930
931 /*}}}*/
932 /*{{{  Control IN transfers                                     */
933
934 // Control-IN transfers. These have to be handled a little bit differently
935 // from bulk transfers. The target never actually initiates anything. Instead
936 // the host will send reserved control messages which are handled at DSR
937 // level and passed to handle_reserved_control_messages() below. Assuming
938 // a control-IN test is in progress, that will take appropriate action. The
939 // thread will be woken up only once all packets have been transferred, or
940 // on abnormal termination.
941
942 // Is a control-IN test currently in progress?
943 static UsbTest* control_in_test    = 0;
944
945 // What is the expected packet size?
946 static int      control_in_test_packet_size = 0;
947
948 // How many packets have been transferred so far?
949 static int      control_in_packets_transferred  = 0;
950
951 // Cancel a control-in test. handle_test_control_in() will have updated the static
952 // control_in_test so that handle_reserved_control_messages() knows what to do.
953 // If the test is not actually going to be run then system consistency demands
954 // that this update be undone. Also, the endpoint will have been locked to
955 // detect concurrent tests on the control endpoint.
956 static void
957 cancel_test_control_in(UsbTest* test)
958 {
959     CYG_ASSERTC(test == control_in_test);
960     control_in_test = (UsbTest*) 0;
961     control_in_test_packet_size = 0;
962     control_in_packets_transferred = 0;
963     unlock_endpoint(0, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
964     test->cancel_fn = (void (*)(UsbTest*)) 0;
965 }
966
967 // Prepare for a control-IN transfer test.
968 static usbs_control_return
969 handle_test_control_in(usb_devreq* req)
970 {
971     UsbTest*    test;
972     int         index   = 0;
973
974     CYG_ASSERTC((UsbTest*)0 == control_in_test);
975                 
976     test = pool_allocate();
977     unpack_usbtest_control_in(&(test->test_params.control_in), class_request, &index);
978
979     lock_endpoint(0, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
980     test->which_test            = usbtest_control_in;
981     test->recovery.endpoint     = 0;
982     test->recovery.protocol     = USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL;
983     test->recovery.size         = 0;    // Does not actually matter
984     test->cancel_fn             = &cancel_test_control_in;
985
986     // Assume a pass. Failures are easy to detect.
987     test->result_pass   = 1;
988     
989     control_in_test = test;
990     control_in_test_packet_size = test->test_params.control_in.packet_size_initial;
991     control_in_packets_transferred  = 0;
992
993     return USBS_CONTROL_RETURN_HANDLED;
994 }
995     
996 // The thread for a control-in test. Actually all the hard work is done at DSR
997 // level, so this thread serves simply to detect when the test has completed
998 // and to perform some clean-ups.
999 static void
1000 run_test_control_in(UsbTest* test)
1001 {
1002     CYG_ASSERTC(test == control_in_test);
1003     
1004     cyg_semaphore_wait(&(test->sem));
1005
1006     // The DSR has detected that the test is complete.
1007     control_in_test = (UsbTest*) 0;
1008     control_in_test_packet_size = 0;
1009     control_in_packets_transferred = 0;
1010     test->cancel_fn = (void (*)(UsbTest*)) 0;
1011     unlock_endpoint(0, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
1012 }
1013
1014 // ----------------------------------------------------------------------------
1015 // This is installed from inside main() as the handler for reserved
1016 // control messages.
1017 static usbs_control_return
1018 handle_reserved_control_messages(usbs_control_endpoint* endpoint, void* data)
1019 {
1020     usb_devreq*         req = (usb_devreq*) endpoint->control_buffer;
1021     usbs_control_return result = USBS_CONTROL_RETURN_UNKNOWN;
1022
1023     CYG_ASSERT(endpoint == control_endpoint, "control endpoint mismatch");
1024     switch(req->request) {
1025       case USBTEST_RESERVED_CONTROL_IN:
1026         {
1027             unsigned char*  buf;
1028             int             len;
1029             
1030             if ((UsbTest*)0 == control_in_test) {
1031                 result = USBS_CONTROL_RETURN_STALL;
1032                 break;
1033             }
1034
1035             // Is this test over? If so indicate a failure because we
1036             // cannot have received all the control packets.
1037             if (current_tests_terminated) {
1038                 control_in_test->result_pass   = 0;
1039                 snprintf(control_in_test->result_message, USBTEST_MAX_MESSAGE,
1040                          "Target, control IN transfer: not all packets received.");
1041                 cyg_semaphore_post(&(control_in_test->sem));
1042                 control_in_test = (UsbTest*) 0;
1043                 result = USBS_CONTROL_RETURN_STALL;
1044                 break;
1045             }
1046             
1047             // A control-IN test is indeed in progress, and the current state is
1048             // held in control_in_test and control_in_test_packet_size. Check that
1049             // the packet size matches up, i.e. that host and target are in sync.
1050             len = (req->length_hi << 8) || req->length_lo;
1051             if (control_in_test_packet_size != len) {
1052                 control_in_test->result_pass   = 0;
1053                 snprintf(control_in_test->result_message, USBTEST_MAX_MESSAGE,
1054                          "Target, control IN transfer : the host only requested %d bytes instead of %d",
1055                          len, control_in_test_packet_size);
1056                 cyg_semaphore_post(&(control_in_test->sem));
1057                 control_in_test = (UsbTest*) 0;
1058                 result = USBS_CONTROL_RETURN_STALL;
1059                 break;
1060             }
1061
1062             // Prepare a suitable reply buffer. This is happening at
1063             // DSR level so runtime is important, but with an upper
1064             // bound of 255 bytes the buffer should be small enough.
1065             buf = control_in_test->buffer;
1066             usbtest_fill_buffer(&(control_in_test->test_params.control_in.data), buf, control_in_test_packet_size);
1067             control_endpoint->buffer_size   = control_in_test_packet_size;
1068             control_endpoint->buffer        = buf;
1069             USBTEST_CONTROL_NEXT_PACKET_SIZE(control_in_test_packet_size, control_in_test->test_params.control_in);
1070
1071             // Have all the packets been transferred?
1072             control_in_packets_transferred++;
1073             if (control_in_packets_transferred == control_in_test->test_params.control_in.number_packets) {
1074                 cyg_semaphore_post(&(control_in_test->sem));
1075                 control_in_test = (UsbTest*) 0;
1076             }
1077             result = USBS_CONTROL_RETURN_HANDLED;
1078             break;
1079       }
1080       default:
1081         CYG_FAIL("Unexpected reserved control message");
1082         break;
1083     }
1084     
1085     return result;
1086 }
1087
1088 /*}}}*/
1089
1090 // FIXME: add more tests.
1091
1092 // This utility is invoked from a thread in the thread pool whenever there is
1093 // work to be done. It simply dispatches to the appropriate handler.
1094 static void
1095 run_test(UsbTest* test)
1096 {
1097     switch(test->which_test)
1098     {
1099       case usbtest_bulk_out :       run_test_bulk_out(test); break;
1100       case usbtest_bulk_in :        run_test_bulk_in(test); break;
1101       case usbtest_control_in:      run_test_control_in(test); break;
1102       default:
1103         CYG_TEST_FAIL_EXIT("Internal error, attempt to run unknown test.\n");
1104         break;
1105     }
1106 }
1107
1108 /*}}}*/
1109 /*{{{  The thread pool                                          */
1110
1111 // ----------------------------------------------------------------------------
1112 // Just like on the host side, it is desirable to have a pool of
1113 // threads available to perform test operations. Strictly speaking
1114 // some tests will run without needing a separate thread, since many
1115 // operations can be performed at DSR level. However typical
1116 // application code will involve threads and it is desirable for test
1117 // code to behave the same way. Also, some operations like validating
1118 // the transferred data are expensive, and best done in thread context.
1119
1120 typedef struct PoolEntry {
1121     cyg_sem_t           wakeup;
1122     cyg_thread          thread_data;
1123     cyg_handle_t        thread_handle;
1124     char                thread_name[16];
1125     char                thread_stack[2 * CYGNUM_HAL_STACK_SIZE_TYPICAL];
1126     cyg_bool            in_use;
1127     cyg_bool            running;
1128     UsbTest             test;
1129 } PoolEntry;
1130
1131 // This array must be uninitialized, or the executable size would
1132 // be ludicrous.
1133 PoolEntry  pool[USBTEST_MAX_CONCURRENT_TESTS];
1134
1135 // The entry point for every thread in the pool. It just loops forever,
1136 // waiting until it is supposed to run a test.
1137 static void
1138 pool_thread_function(cyg_addrword_t arg)
1139 {
1140     PoolEntry*  pool_entry  = (PoolEntry*) arg;
1141
1142     for ( ; ; ) {
1143         cyg_semaphore_wait(&(pool_entry->wakeup));
1144         run_test(&(pool_entry->test));
1145         pool_entry->running = 0;
1146     }
1147 }
1148
1149 // Initialize all threads in the pool.
1150 static void
1151 pool_initialize(void)
1152 {
1153     int i;
1154     for (i = 0; i < USBTEST_MAX_CONCURRENT_TESTS; i++) {
1155         cyg_semaphore_init(&(pool[i].wakeup), 0);
1156         pool[i].in_use  = 0;
1157         pool[i].running = 0;
1158         sprintf(pool[i].thread_name, "worker%d", i);
1159         cyg_thread_create( 0, &pool_thread_function, (cyg_addrword_t) &(pool[i]),
1160                            pool[i].thread_name, pool[i].thread_stack, 2 * CYGNUM_HAL_STACK_SIZE_TYPICAL,
1161                            &(pool[i].thread_handle), &(pool[i].thread_data));
1162         cyg_thread_resume(pool[i].thread_handle);
1163     }
1164 }
1165
1166 // Allocate a single entry in the thread pool
1167 static UsbTest*
1168 pool_allocate(void)
1169 {
1170     UsbTest*    result  = (UsbTest*) 0;
1171
1172     if (thread_counter == USBTEST_MAX_CONCURRENT_TESTS) {
1173         CYG_TEST_FAIL_EXIT("Internal error, thread resources exhaused.\n");
1174     }
1175     
1176     result = &(pool[thread_counter].test);
1177     thread_counter++;
1178     reset_usbtest(result);
1179     return result;
1180 }
1181
1182 // Start all the threads that are supposed to be running tests.
1183 static void
1184 pool_start(void)
1185 {
1186     int i;
1187     for (i = 0; i < thread_counter; i++) {
1188         pool[i].running = 1;
1189         cyg_semaphore_post(&(pool[i].wakeup));
1190     }
1191 }
1192
1193 /*}}}*/
1194 /*{{{  Class control messages                                   */
1195
1196 // ----------------------------------------------------------------------------
1197 // Handle class control messages. These provide the primary form of
1198 // communication between host and target. There are requests to find out
1199 // the number of endpoints, details of each endpoint, prepare a test run,
1200 // abort a test run, get status, terminate the target-side, and so on.
1201 // The handlers for starting specific test cases are kept alongside
1202 // the test cases themselves.
1203 //
1204 // Note that these handlers will typically be invoked from DSR context
1205 // and hence they are subject to the usual DSR restrictions.
1206 //
1207 // Problems have been experienced in some hosts sending control messages
1208 // that involve additional host->target data. An ugly workaround is
1209 // in place whereby any such data is sent in advance using separate
1210 // control messages.
1211
1212 /*{{{  endpoint count                                           */
1213
1214 // How many endpoints are supported by this device? That information is
1215 // determined during initialization.
1216 static usbs_control_return
1217 handle_endpoint_count(usb_devreq* req)
1218 {
1219     CYG_ASSERTC((1 == req->length_lo) && (0 == req->length_hi) && \
1220                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1221     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1222     
1223     class_reply[0]                  = (unsigned char) number_endpoints;
1224     control_endpoint->buffer        = class_reply;
1225     control_endpoint->buffer_size   = 1;
1226     return USBS_CONTROL_RETURN_HANDLED;
1227 }
1228
1229 /*}}}*/
1230 /*{{{  endpoint details                                         */
1231
1232 // The host wants to know the details of a specific USB endpoint.
1233 // The format is specified in protocol.h
1234 static usbs_control_return
1235 handle_endpoint_details(usb_devreq* req)
1236 {
1237     int buf_index;
1238
1239     CYG_ASSERTC((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN);
1240     CYG_ASSERTC((USBTEST_MAX_CONTROL_DATA == req->length_lo) && (0 == req->length_hi));
1241     CYG_ASSERTC(req->index_lo < number_endpoints);
1242     CYG_ASSERTC((0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1243     
1244     class_reply[0]  = (unsigned char) usbs_testing_endpoints[req->index_lo].endpoint_type;
1245     class_reply[1]  = (unsigned char) usbs_testing_endpoints[req->index_lo].endpoint_number;
1246     class_reply[2]  = (unsigned char) usbs_testing_endpoints[req->index_lo].endpoint_direction;
1247     class_reply[3]  = (unsigned char) usbs_testing_endpoints[req->index_lo].max_in_padding;
1248     buf_index = 4;
1249     pack_int(usbs_testing_endpoints[req->index_lo].min_size, class_reply, &buf_index);
1250     pack_int(usbs_testing_endpoints[req->index_lo].max_size, class_reply, &buf_index);
1251     if (NULL == usbs_testing_endpoints[req->index_lo].devtab_entry) {
1252         class_reply[buf_index]    = '\0';
1253         control_endpoint->buffer_size   = buf_index + 1;
1254     } else {
1255         int len = strlen(usbs_testing_endpoints[req->index_lo].devtab_entry) + buf_index + 1;
1256         if (len > USBTEST_MAX_CONTROL_DATA) {
1257             return USBS_CONTROL_RETURN_STALL;
1258         } else {
1259             strcpy(&(class_reply[buf_index]), usbs_testing_endpoints[req->index_lo].devtab_entry);
1260             control_endpoint->buffer_size   = len;
1261         }
1262     }
1263     control_endpoint->buffer        = class_reply;
1264     return USBS_CONTROL_RETURN_HANDLED;
1265 }
1266
1267 /*}}}*/
1268 /*{{{  sync                                                     */
1269
1270 // The host wants to know whether or not the target is currently busy doing
1271 // stuff. This information is held in a static.
1272 static usbs_control_return
1273 handle_sync(usb_devreq* req)
1274 {
1275     CYG_ASSERTC((1 == req->length_lo) && (0 == req->length_hi) && \
1276                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1277     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1278     CYG_ASSERT(0 == class_request_size, "A sync operation should not involve any data");
1279     
1280     class_reply[0]                  = (unsigned char) idle;
1281     control_endpoint->buffer        = class_reply;
1282     control_endpoint->buffer_size   = 1;
1283     return USBS_CONTROL_RETURN_HANDLED;
1284 }
1285
1286 /*}}}*/
1287 /*{{{  pass/fail                                                */
1288
1289 // Allow the host to generate some pass or fail messages, and
1290 // optionally terminate the test. These are synchronous requests
1291 // so the data can be left in class_request.
1292
1293 static int passfail_request   = 0;
1294
1295 // Invoked from thread context
1296 static void
1297 handle_passfail_action(void)
1298 {
1299     switch (passfail_request) {
1300       case USBTEST_PASS:
1301         CYG_TEST_PASS(class_request);
1302         break;
1303       case USBTEST_PASS_EXIT:
1304         CYG_TEST_PASS(class_request);
1305         CYG_TEST_EXIT("Exiting normally as requested by the host");
1306         break;
1307       case USBTEST_FAIL:
1308         CYG_TEST_FAIL(class_request);
1309         break;
1310       case USBTEST_FAIL_EXIT:
1311         CYG_TEST_FAIL(class_request);
1312         CYG_TEST_EXIT("Exiting normally as requested by the host");
1313         break;
1314       default:
1315         CYG_FAIL("Bogus invocation of usbtest_main_passfail");
1316         break;
1317     }
1318 }
1319
1320 // Invoked from DSR context
1321 static usbs_control_return
1322 handle_passfail(usb_devreq* req)
1323 {
1324     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1325     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1326     CYG_ASSERT(class_request_size > 0, "A pass/fail message should be supplied");
1327     CYG_ASSERT(idle, "Pass/fail messages are only allowed when idle");
1328     CYG_ASSERT((void (*)(void))0 == main_thread_action, "No thread operation should be pending.");
1329     
1330     passfail_request    = req->request;
1331     idle                = false;
1332     main_thread_action  = &handle_passfail_action;
1333     cyg_semaphore_post(&main_wakeup);
1334
1335     return USBS_CONTROL_RETURN_HANDLED;
1336 }
1337
1338 /*}}}*/
1339 /*{{{  abort                                                    */
1340
1341 // The host has concluded that there is no easy way to get both target and
1342 // host back to a sensible state. For example there may be a thread that
1343 // is blocked waiting for some I/O that is not going to complete. The abort
1344 // should be handled at thread level, not DSR level, so that the host
1345 // still sees the low-level USB handshake.
1346
1347 static void
1348 handle_abort_action(void)
1349 {
1350     CYG_TEST_FAIL_EXIT("Test abort requested by host application");
1351 }
1352
1353 static usbs_control_return
1354 handle_abort(usb_devreq* req)
1355 {
1356     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1357     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1358     CYG_ASSERT(idle, "Abort messages are only allowed when idle");
1359     CYG_ASSERT((void (*)(void))0 == main_thread_action, "No thread operation should be pending.");
1360     
1361     idle                = false;
1362     main_thread_action  = &handle_abort_action;
1363     cyg_semaphore_post(&main_wakeup);
1364     
1365     return USBS_CONTROL_RETURN_HANDLED;
1366 }
1367
1368 /*}}}*/
1369 /*{{{  cancel                                                   */
1370
1371 // Invoked from thread context
1372 // Cancelling pending test cases simply involves iterating over the allocated
1373 // entries in the pool, invoking any cancellation functions that have been
1374 // defined, and then resetting the tread count. The actual tests have not
1375 // yet started so none of the threads will be active.
1376 static void
1377 handle_cancel_action(void)
1378 {
1379     int i;
1380     for (i = 0; i < thread_counter; i++) {
1381         if ((void (*)(UsbTest*))0 != pool[i].test.cancel_fn) {
1382             (*(pool[i].test.cancel_fn))(&(pool[i].test));
1383             pool[i].test.cancel_fn  = (void (*)(UsbTest*)) 0;
1384         }
1385     }
1386     thread_counter    = 0;
1387 }
1388
1389 // Invoked from DSR context
1390 static usbs_control_return
1391 handle_cancel(usb_devreq* req)
1392 {
1393     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1394     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1395     CYG_ASSERT(0 == class_request_size, "A cancel operation should not involve any data");
1396     CYG_ASSERT(idle, "Cancel requests are only allowed when idle");
1397     CYG_ASSERT(!running, "Cancel requests cannot be sent once the system is running");
1398     CYG_ASSERT((void (*)(void))0 == main_thread_action, "No thread operation should be pending.");
1399     
1400     idle                = false;
1401     main_thread_action = &handle_cancel_action;
1402     cyg_semaphore_post(&main_wakeup);
1403
1404     return USBS_CONTROL_RETURN_HANDLED;
1405 }
1406
1407 /*}}}*/
1408 /*{{{  start                                                    */
1409
1410 // Start the tests running. This just involves waking up the pool threads
1411 // and setting the running flag, with the latter serving primarily for
1412 // assertions. 
1413
1414 static usbs_control_return
1415 handle_start(usb_devreq* req)
1416 {
1417     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1418     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1419     CYG_ASSERT(0 == class_request_size, "A start operation should not involve any data");
1420     CYG_ASSERT(!running, "Start requests cannot be sent if the system is already running");
1421
1422     current_tests_terminated = false;
1423     running = true;
1424     pool_start();
1425     
1426     return USBS_CONTROL_RETURN_HANDLED;
1427 }
1428
1429 /*}}}*/
1430 /*{{{  finished                                                 */
1431
1432 // Have all the tests finished? This involves checking all the threads
1433 // involved in the current batch of tests and seeing whether or not
1434 // their running flag is still set.
1435
1436 static usbs_control_return
1437 handle_finished(usb_devreq* req)
1438 {
1439     int i;
1440     int result = 1;
1441     
1442     CYG_ASSERTC((1 == req->length_lo) && (0 == req->length_hi) && \
1443                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1444     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1445     CYG_ASSERT(0 == class_request_size, "A finished operation should not involve any data");
1446     CYG_ASSERT(running, "Finished requests can only be sent if the system is already running");
1447     
1448     for (i = 0; i < thread_counter; i++) {
1449         if (pool[i].running) {
1450             result = 0;
1451             break;
1452         }
1453     }
1454     class_reply[0]                  = (unsigned char) result;
1455     control_endpoint->buffer        = class_reply;
1456     control_endpoint->buffer_size   = 1;
1457     return USBS_CONTROL_RETURN_HANDLED;
1458 }
1459
1460 /*}}}*/
1461 /*{{{  set terminated                                           */
1462
1463 // A timeout has occurred, or there is some other failure. The first step
1464 // in recovery is to set the terminated flag so that as recovery action
1465 // takes place and the threads wake up they make no attempt to continue
1466 // doing more transfers.
1467
1468 static usbs_control_return
1469 handle_set_terminated(usb_devreq* req)
1470 {
1471     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1472     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1473     CYG_ASSERT(0 == class_request_size, "A set-terminated operation should not involve any data");
1474     CYG_ASSERT(running, "The terminated flag can only be set when there are running tests");
1475
1476     current_tests_terminated = 1;
1477     
1478     return USBS_CONTROL_RETURN_HANDLED;
1479 }
1480
1481 /*}}}*/
1482 /*{{{  get recovery                                             */
1483
1484 // Return the recovery information for one of the threads involved in the
1485 // current batch of tests, so that the host can perform a USB operation
1486 // that will sort out that thread.
1487 static usbs_control_return
1488 handle_get_recovery(usb_devreq* req)
1489 {
1490     int buffer_index;
1491     
1492     CYG_ASSERT(current_tests_terminated, "Recovery should only be attempted when the terminated flag is set");
1493     CYG_ASSERT(running, "If there are no tests running then recovery is impossible");
1494     CYG_ASSERTC((12 == req->length_lo) && (0 == req->length_hi) && \
1495                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1496     CYG_ASSERTC(req->index_lo <= thread_counter);
1497     CYG_ASSERTC((0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1498     CYG_ASSERT(0 == class_request_size, "A get-recovery operation should not involve any data");
1499
1500     control_endpoint->buffer        = class_reply;
1501     if (!pool[req->index_lo].running) {
1502         // Actually, this particular thread has terminated so no recovery is needed.
1503         control_endpoint->buffer_size   = 0;
1504     } else {
1505         buffer_index    = 0;
1506         pack_usbtest_recovery(&(pool[req->index_lo].test.recovery), class_reply, &buffer_index);
1507         control_endpoint->buffer_size   = buffer_index;
1508     }
1509     
1510     return USBS_CONTROL_RETURN_HANDLED;
1511 }
1512
1513 /*}}}*/
1514 /*{{{  perform recovery                                         */
1515
1516 // The host has identified a course of action that could unlock a thread
1517 // on the host-side that is currently blocked performing a USB operation.
1518 // Typically this involves either sending or accepting some data. If the
1519 // endpoint is still locked, in other words if there is a still a local
1520 // thread attempting to communicate on the specified endpoint, then
1521 // things are messed up: both sides are trying to communicate, but nothing
1522 // is happening. The eCos USB API is such that attempting multiple
1523 // concurrent operations on a single endpoint is disallowed, so
1524 // the recovery request has to be ignored. If things do not sort themselves
1525 // out then the whole test run will have to be aborted.
1526
1527 // A dummy completion function for when a recovery operation has completed.
1528 static void
1529 recovery_callback(void* callback_arg, int transferred)
1530 {
1531     CYG_UNUSED_PARAM(void*, callback_arg);
1532     CYG_UNUSED_PARAM(int, transferred);
1533 }
1534     
1535 static usbs_control_return
1536 handle_perform_recovery(usb_devreq* req)
1537 {
1538     int                 buffer_index;
1539     int                 endpoint_number;
1540     int                 endpoint_direction;
1541     UsbTest_Recovery    recovery;
1542     
1543     CYG_ASSERT(current_tests_terminated, "Recovery should only be attempted when the terminated flag is set");
1544     CYG_ASSERT(running, "If there are no tests running then recovery is impossible");
1545     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1546     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1547     CYG_ASSERT(12 == class_request_size, "A perform-recovery operation requires recovery data");
1548
1549     buffer_index = 0;
1550     unpack_usbtest_recovery(&recovery, class_request, &buffer_index);
1551     endpoint_number     = recovery.endpoint & ~USB_DEVREQ_DIRECTION_MASK;
1552     endpoint_direction  = recovery.endpoint & USB_DEVREQ_DIRECTION_MASK;
1553
1554     if (!is_endpoint_locked(endpoint_number, endpoint_direction)) {
1555         // Locking the endpoint here would be good, but the endpoint would then
1556         // have to be unlocked again - probably in the recovery callback.
1557         // This complication is ignored for now.
1558
1559         if (USB_ENDPOINT_DESCRIPTOR_ATTR_BULK == recovery.protocol) {
1560             int ep_index = lookup_endpoint(endpoint_number, endpoint_direction, USB_ENDPOINT_DESCRIPTOR_ATTR_BULK);
1561             CYG_ASSERTC(-1 != ep_index);
1562
1563             if (USB_DEVREQ_DIRECTION_IN == endpoint_direction) {
1564                 // The host wants some data. Supply it. A single byte will do fine to
1565                 // complete the transfer.
1566                 usbs_start_tx_buffer((usbs_tx_endpoint*) usbs_testing_endpoints[ep_index].endpoint,
1567                                      recovery_buffer, 1, &recovery_callback, (void*) 0);
1568             } else {
1569                 // The host is trying to send some data. Accept all of it.
1570                 usbs_start_rx_buffer((usbs_rx_endpoint*) usbs_testing_endpoints[ep_index].endpoint,
1571                                      recovery_buffer, recovery.size, &recovery_callback, (void*) 0);
1572             }
1573         }
1574
1575         // No support for isochronous or interrupt transfers yet.
1576         // handle_reserved_control_messages() should generate stalls which
1577         // have the desired effect.
1578     }
1579     
1580     return USBS_CONTROL_RETURN_HANDLED;
1581 }
1582
1583 /*}}}*/
1584 /*{{{  get result                                               */
1585
1586 // Return the result of one the tests. This can be a single byte for
1587 // a pass, or a single byte plus a message for a failure.
1588
1589 static usbs_control_return
1590 handle_get_result(usb_devreq* req)
1591 {
1592     CYG_ASSERTC((USBTEST_MAX_CONTROL_DATA == req->length_lo) && (0 == req->length_hi) && \
1593                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1594     CYG_ASSERTC(req->index_lo <= thread_counter);
1595     CYG_ASSERTC((0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1596     CYG_ASSERT(0 == class_request_size, "A get-result operation should not involve any data");
1597     CYG_ASSERT(running, "Results can only be sent if a run is in progress");
1598     CYG_ASSERT(!pool[req->index_lo].running, "Cannot request results for a test that has not completed");
1599
1600     class_reply[0]  = pool[req->index_lo].test.result_pass;
1601     if (class_reply[0]) {
1602         control_endpoint->buffer_size = 1;
1603     } else {
1604         strncpy(&(class_reply[1]), pool[req->index_lo].test.result_message, USBTEST_MAX_CONTROL_DATA - 2);
1605         class_reply[USBTEST_MAX_CONTROL_DATA - 1] = '\0';
1606         control_endpoint->buffer_size = 1 + strlen(&(class_reply[1])) + 1;
1607     }
1608     control_endpoint->buffer = class_reply;
1609     return USBS_CONTROL_RETURN_HANDLED;
1610 }
1611
1612 /*}}}*/
1613 /*{{{  batch done                                               */
1614
1615 // A batch of test has been completed - at least, the host thinks so.
1616 // If the host is correct then all that is required here is to reset
1617 // the thread pool and clear the global running flag - that is sufficient
1618 // to allow a new batch of tests to be started.
1619
1620 static usbs_control_return
1621 handle_batch_done(usb_devreq* req)
1622 {
1623     int i;
1624     
1625     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1626     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1627     CYG_ASSERT(0 == class_request_size, "A batch-done operation should not involve any data");
1628     CYG_ASSERT(running, "There must be a current batch of tests");
1629
1630     for (i = 0; i < thread_counter; i++) {
1631         CYG_ASSERTC(!pool[i].running);
1632     }
1633     thread_counter  = 0;
1634     running         = false;
1635     
1636     return USBS_CONTROL_RETURN_HANDLED;
1637
1638 }
1639
1640 /*}}}*/
1641 /*{{{  verbosity                                                */
1642
1643 static usbs_control_return
1644 handle_verbose(usb_devreq* req)
1645 {
1646     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1647     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi));
1648     CYG_ASSERT(0 == class_request_size, "A set-verbosity operation should not involve any data");
1649
1650     verbose = (req->value_hi << 8) + req->value_lo;
1651     
1652     return USBS_CONTROL_RETURN_HANDLED;
1653 }
1654
1655 /*}}}*/
1656 /*{{{  initialise bulk out endpoint                             */
1657
1658 // ----------------------------------------------------------------------------
1659 // Accept an initial endpoint on a bulk endpoint. This avoids problems
1660 // on some hardware such as the SA11x0 which can start to accept data
1661 // before the software is ready for it.
1662
1663 static void handle_init_callback(void* arg, int result)
1664 {
1665     idle = true;
1666 }
1667
1668 static usbs_control_return
1669 handle_init_bulk_out(usb_devreq* req)
1670 {
1671     static char         buf[64];
1672     int                 ep_index;
1673     usbs_rx_endpoint*   endpoint;
1674     
1675     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1676     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi));
1677     CYG_ASSERTC((0 == req->value_hi) && (0 < req->value_lo) && (req->value_lo < 16));
1678     CYG_ASSERT(0 == class_request_size, "An init_bulk_out operation should not involve any data");
1679
1680     ep_index = lookup_endpoint(req->value_lo, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT, USB_ENDPOINT_DESCRIPTOR_ATTR_BULK);
1681     CYG_ASSERTC(-1 != ep_index);
1682     endpoint = (usbs_rx_endpoint*) usbs_testing_endpoints[ep_index].endpoint;
1683     
1684     idle = false;
1685     usbs_start_rx_buffer(endpoint, buf, 64, &handle_init_callback, (void*) 0);
1686     
1687     return USBS_CONTROL_RETURN_HANDLED;
1688 }
1689
1690 /*}}}*/
1691 /*{{{  additional control data                                  */
1692
1693 // Accumulate some more data in the control buffer, ahead of an upcoming
1694 // request.
1695 static usbs_control_return
1696 handle_control_data(usb_devreq* req)
1697 {
1698     class_request[class_request_size + 0] = req->value_hi;
1699     class_request[class_request_size + 1] = req->value_lo;
1700     class_request[class_request_size + 2] = req->index_hi;
1701     class_request[class_request_size + 3] = req->index_lo;
1702
1703     switch(req->request) {
1704       case USBTEST_CONTROL_DATA1 : class_request_size += 1; break;
1705       case USBTEST_CONTROL_DATA2 : class_request_size += 2; break;
1706       case USBTEST_CONTROL_DATA3 : class_request_size += 3; break;
1707       case USBTEST_CONTROL_DATA4 : class_request_size += 4; break;
1708     }
1709
1710     return USBS_CONTROL_RETURN_HANDLED;
1711 }
1712
1713 /*}}}*/
1714
1715 typedef struct class_handler {
1716     int     request;
1717     usbs_control_return (*handler)(usb_devreq*);
1718 } class_handler;
1719 static class_handler class_handlers[] = {
1720     { USBTEST_ENDPOINT_COUNT,   &handle_endpoint_count },
1721     { USBTEST_ENDPOINT_DETAILS, &handle_endpoint_details },
1722     { USBTEST_PASS,             &handle_passfail },
1723     { USBTEST_PASS_EXIT,        &handle_passfail },
1724     { USBTEST_FAIL,             &handle_passfail },
1725     { USBTEST_FAIL_EXIT,        &handle_passfail },
1726     { USBTEST_SYNCH,            &handle_sync },
1727     { USBTEST_ABORT,            &handle_abort },
1728     { USBTEST_CANCEL,           &handle_cancel },
1729     { USBTEST_START,            &handle_start },
1730     { USBTEST_FINISHED,         &handle_finished },
1731     { USBTEST_SET_TERMINATED,   &handle_set_terminated },
1732     { USBTEST_GET_RECOVERY,     &handle_get_recovery },
1733     { USBTEST_PERFORM_RECOVERY, &handle_perform_recovery },
1734     { USBTEST_GET_RESULT,       &handle_get_result },
1735     { USBTEST_BATCH_DONE,       &handle_batch_done },
1736     { USBTEST_VERBOSE,          &handle_verbose },
1737     { USBTEST_INIT_BULK_OUT,    &handle_init_bulk_out },
1738     { USBTEST_TEST_BULK,        &handle_test_bulk },
1739     { USBTEST_TEST_CONTROL_IN,  &handle_test_control_in },
1740     { USBTEST_CONTROL_DATA1,    &handle_control_data },
1741     { USBTEST_CONTROL_DATA2,    &handle_control_data },
1742     { USBTEST_CONTROL_DATA3,    &handle_control_data },
1743     { USBTEST_CONTROL_DATA4,    &handle_control_data },
1744     { -1,                       (usbs_control_return (*)(usb_devreq*)) 0 }
1745 };
1746
1747 static usbs_control_return
1748 handle_class_control_messages(usbs_control_endpoint* endpoint, void* data)
1749 {
1750     usb_devreq*         req = (usb_devreq*) endpoint->control_buffer;
1751     int                 request = req->request;
1752     usbs_control_return result;
1753     int                 i;
1754
1755     VERBOSE(3, "Received control message %02x\n", request);
1756     
1757     CYG_ASSERT(endpoint == control_endpoint, "control endpoint mismatch");
1758     result  = USBS_CONTROL_RETURN_UNKNOWN;
1759     for (i = 0; (usbs_control_return (*)(usb_devreq*))0 != class_handlers[i].handler; i++) {
1760         if (request == class_handlers[i].request) {
1761             result = (*(class_handlers[i].handler))(req);
1762             if ((USBTEST_CONTROL_DATA1 != request) &&
1763                 (USBTEST_CONTROL_DATA2 != request) &&
1764                 (USBTEST_CONTROL_DATA3 != request) &&
1765                 (USBTEST_CONTROL_DATA4 != request)) {
1766                 // Reset the request data buffer after all normal requests.
1767                 class_request_size = 0;
1768             }
1769             break;
1770         }
1771     }
1772     CYG_UNUSED_PARAM(void*, data);
1773     if (USBS_CONTROL_RETURN_HANDLED != result) {
1774         VERBOSE(1, "Control message %02x not handled\n", request);
1775     }
1776     
1777     return result;
1778 }
1779
1780 /*}}}*/
1781 /*{{{  main()                                                   */
1782
1783 // ----------------------------------------------------------------------------
1784 // Initialization.
1785 int
1786 main(int argc, char** argv)
1787 {
1788     int i;
1789
1790     CYG_TEST_INIT();
1791
1792     // The USB device driver should have provided an array of endpoint
1793     // descriptors, usbs_testing_endpoints(). One entry in this array
1794     // should be a control endpoint, which is needed for initialization.
1795     // It is also useful to know how many endpoints there are.
1796     for (i = 0; !USBS_TESTING_ENDPOINTS_IS_TERMINATOR(usbs_testing_endpoints[i]); i++) {
1797         if ((0 == usbs_testing_endpoints[i].endpoint_number) &&
1798             (USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL== usbs_testing_endpoints[i].endpoint_type)) {
1799             CYG_ASSERT((usbs_control_endpoint*)0 == control_endpoint, "There should be only one control endpoint");
1800             control_endpoint = (usbs_control_endpoint*) usbs_testing_endpoints[i].endpoint;
1801         }
1802     }
1803     if ((usbs_control_endpoint*)0 == control_endpoint) {
1804         CYG_TEST_FAIL_EXIT("Unable to find a USB control endpoint");
1805     }
1806     number_endpoints = i;
1807     CYG_ASSERT(number_endpoints <= USBTEST_MAX_ENDPOINTS, "impossible number of endpoints");
1808
1809     // Some of the information provided may not match the actual capabilities
1810     // of the testing code, e.g. max_size limits.
1811     fix_driver_endpoint_data();
1812     
1813     // This semaphore is used for communication between the DSRs that process control
1814     // messages and the main thread
1815     cyg_semaphore_init(&main_wakeup, 0);
1816
1817     // Take care of the pool of threads and related data.
1818     pool_initialize();
1819
1820     // Start the heartbeat thread, to make sure that the gdb session stays
1821     // alive.
1822     start_heartbeat();
1823     
1824     // Now it is possible to start up the USB device driver. The host can detect
1825     // this, connect, get the enumeration data, and then testing will proceed
1826     // in response to class control messages.
1827     provide_endpoint_enumeration_data();
1828     control_endpoint->enumeration_data      = &usb_enum_data;
1829     control_endpoint->class_control_fn      = &handle_class_control_messages;
1830     control_endpoint->reserved_control_fn   = &handle_reserved_control_messages;
1831     usbs_start(control_endpoint);
1832
1833     // Now it is over to the host to detect this target and start performing tests.
1834     // Much of this is handled at DSR level, in response to USB control messages.
1835     // Some of those control messages require action at thread level, and that is
1836     // achieved by signalling a semaphore and waking up this thread. A static
1837     // function pointer is used to keep track of what operation is actually required.
1838     for (;;) {
1839         void (*handler)(void);
1840
1841         cyg_semaphore_wait(&main_wakeup);
1842         handler = main_thread_action;
1843         main_thread_action   = 0;
1844         CYG_CHECK_FUNC_PTR(handler, "Main thread woken up when there is nothing to be done");
1845         (*handler)();
1846         idle = true;
1847     }
1848 }
1849
1850 /*}}}*/