]> git.karo-electronics.de Git - karo-tx-redboot.git/blob - packages/io/usb/slave/v2_0/tests/usbtarget.c
0526aebec0254fc982cef8fdffc284a46a58051a
[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         // Make sure the buffer contains the data expected by the host
829         usbtest_fill_buffer(&(test->test_params.bulk.data), buf, packet_size);
830                             
831         if (verbose < 3) {
832             VERBOSE(2, "Bulk OUT test %d: iteration %d, packet size %d\n", test->id, i, packet_size);
833         } else {
834             // Output the first 32 bytes of data as well.
835             char msg[256];
836             int  index;
837             int  j;
838             index = snprintf(msg, 255, "Bulk IN test %d: iteration %d, packet size %d\n    Data %s:",
839                              test->id, i, packet_size,
840                              (usbtestdata_none == test->test_params.bulk.data.format) ? "(uninitialized)" : "");
841
842             for (j = 0; ((j + 3) < packet_size) && (j < 32); j+= 4) {
843                 index += snprintf(msg+index, 255-index, " %02x%02x%02x%02x",
844                                   buf[j], buf[j+1], buf[j+2], buf[j+3]);
845             }
846             if (j < 32) {
847                 index += snprintf(msg+index, 255-index, " ");
848                 for ( ; j < packet_size; j++) {
849                     index += snprintf(msg+index, 255-index, "%02x", buf[j]);
850                 }
851                 
852             }
853             VERBOSE(3, "%s\n", msg);
854         }
855         
856         // Do the actual transfer, using the I/O mechanism specified for this test.
857         switch (test->test_params.bulk.io_mechanism)
858         {
859           case usb_io_mechanism_usb :
860           {
861               test->transferred = 0;
862               usbs_start_tx_buffer(endpoint, buf, packet_size, &run_test_bulk_in_out_callback, (void*) test);
863               cyg_semaphore_wait(&(test->sem));
864               transferred = test->transferred;
865               break;
866           }
867
868           case usb_io_mechanism_dev :
869           {
870               int result;
871               transferred   = packet_size;
872               result = cyg_io_write(io_handle, (void*) buf, &transferred);
873               if (result < 0) {
874                   transferred = result;
875               }
876               break;
877           }
878
879           default:
880             CYG_FAIL("Invalid test mechanism specified");
881             break;
882         }
883
884         // Has this test been aborted for some reason?
885         if (current_tests_terminated) {
886             VERBOSE(2, "Bulk IN test %d: iteration %d, termination detected\n", test->id, i);
887             test->result_pass   = 0;
888             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
889                      "Target, bulk IN transfer on endpoint %d : terminated on iteration %d, packet_size %d\n",
890                      endpoint_number, i, packet_size);
891             break;
892         }
893
894         // If an error occurred, abort this run
895         if (transferred < 0) {
896             test->result_pass   = 0;
897             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
898                      "Target, bulk IN transfer on endpoint %d: transfer failed with %d", endpoint_number, transferred);
899             VERBOSE(2, "Bulk IN test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
900             break;
901         }
902
903         // No need to check the transfer size, the USB code is only
904         // allowed to send the exact amount of data requested.
905
906         if (0 != test->test_params.bulk.tx_delay) {
907             VERBOSE(2, "Bulk IN test %d: iteration %d, sleeping for %d nanoseconds\n", test->id, i, \
908                     test->test_params.bulk.tx_delay);
909             usbs_nanosleep(test->test_params.bulk.tx_delay);
910         }
911         
912         // Move on to the next transfer
913         USBTEST_BULK_NEXT(test->test_params.bulk);
914     }
915
916     // Always unlock the endpoint on completion
917     unlock_endpoint(endpoint_number, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
918
919     // If all the packets have been transferred this test has passed.
920     if (i >= test->test_params.bulk.number_packets) {
921         test->result_pass   = 1;
922     }
923     
924     VERBOSE(1, "Test %d bulk IN on endpoint %d, result %d\n", test->id, endpoint_number, test->result_pass);
925 }
926
927 /*}}}*/
928
929 /*}}}*/
930 /*{{{  Control IN transfers                                     */
931
932 // Control-IN transfers. These have to be handled a little bit differently
933 // from bulk transfers. The target never actually initiates anything. Instead
934 // the host will send reserved control messages which are handled at DSR
935 // level and passed to handle_reserved_control_messages() below. Assuming
936 // a control-IN test is in progress, that will take appropriate action. The
937 // thread will be woken up only once all packets have been transferred, or
938 // on abnormal termination.
939
940 // Is a control-IN test currently in progress?
941 static UsbTest* control_in_test    = 0;
942
943 // What is the expected packet size?
944 static int      control_in_test_packet_size = 0;
945
946 // How many packets have been transferred so far?
947 static int      control_in_packets_transferred  = 0;
948
949 // Cancel a control-in test. handle_test_control_in() will have updated the static
950 // control_in_test so that handle_reserved_control_messages() knows what to do.
951 // If the test is not actually going to be run then system consistency demands
952 // that this update be undone. Also, the endpoint will have been locked to
953 // detect concurrent tests on the control endpoint.
954 static void
955 cancel_test_control_in(UsbTest* test)
956 {
957     CYG_ASSERTC(test == control_in_test);
958     control_in_test = (UsbTest*) 0;
959     control_in_test_packet_size = 0;
960     control_in_packets_transferred = 0;
961     unlock_endpoint(0, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
962     test->cancel_fn = (void (*)(UsbTest*)) 0;
963 }
964
965 // Prepare for a control-IN transfer test.
966 static usbs_control_return
967 handle_test_control_in(usb_devreq* req)
968 {
969     UsbTest*    test;
970     int         index   = 0;
971
972     CYG_ASSERTC((UsbTest*)0 == control_in_test);
973                 
974     test = pool_allocate();
975     unpack_usbtest_control_in(&(test->test_params.control_in), class_request, &index);
976
977     lock_endpoint(0, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
978     test->which_test            = usbtest_control_in;
979     test->recovery.endpoint     = 0;
980     test->recovery.protocol     = USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL;
981     test->recovery.size         = 0;    // Does not actually matter
982     test->cancel_fn             = &cancel_test_control_in;
983
984     // Assume a pass. Failures are easy to detect.
985     test->result_pass   = 1;
986     
987     control_in_test = test;
988     control_in_test_packet_size = test->test_params.control_in.packet_size_initial;
989     control_in_packets_transferred  = 0;
990
991     return USBS_CONTROL_RETURN_HANDLED;
992 }
993     
994 // The thread for a control-in test. Actually all the hard work is done at DSR
995 // level, so this thread serves simply to detect when the test has completed
996 // and to perform some clean-ups.
997 static void
998 run_test_control_in(UsbTest* test)
999 {
1000     CYG_ASSERTC(test == control_in_test);
1001     
1002     cyg_semaphore_wait(&(test->sem));
1003
1004     // The DSR has detected that the test is complete.
1005     control_in_test = (UsbTest*) 0;
1006     control_in_test_packet_size = 0;
1007     control_in_packets_transferred = 0;
1008     test->cancel_fn = (void (*)(UsbTest*)) 0;
1009     unlock_endpoint(0, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN);
1010 }
1011
1012 // ----------------------------------------------------------------------------
1013 // This is installed from inside main() as the handler for reserved
1014 // control messages.
1015 static usbs_control_return
1016 handle_reserved_control_messages(usbs_control_endpoint* endpoint, void* data)
1017 {
1018     usb_devreq*         req = (usb_devreq*) endpoint->control_buffer;
1019     usbs_control_return result;
1020
1021     CYG_ASSERT(endpoint == control_endpoint, "control endpoint mismatch");
1022     switch(req->request) {
1023       case USBTEST_RESERVED_CONTROL_IN:
1024         {
1025             unsigned char*  buf;
1026             int             len;
1027             
1028             if ((UsbTest*)0 == control_in_test) {
1029                 result = USBS_CONTROL_RETURN_STALL;
1030                 break;
1031             }
1032
1033             // Is this test over? If so indicate a failure because we
1034             // cannot have received all the control packets.
1035             if (current_tests_terminated) {
1036                 control_in_test->result_pass   = 0;
1037                 snprintf(control_in_test->result_message, USBTEST_MAX_MESSAGE,
1038                          "Target, control IN transfer: not all packets received.");
1039                 cyg_semaphore_post(&(control_in_test->sem));
1040                 control_in_test = (UsbTest*) 0;
1041                 result = USBS_CONTROL_RETURN_STALL;
1042                 break;
1043             }
1044             
1045             // A control-IN test is indeed in progress, and the current state is
1046             // held in control_in_test and control_in_test_packet_size. Check that
1047             // the packet size matches up, i.e. that host and target are in sync.
1048             len = (req->length_hi << 8) || req->length_lo;
1049             if (control_in_test_packet_size != len) {
1050                 control_in_test->result_pass   = 0;
1051                 snprintf(control_in_test->result_message, USBTEST_MAX_MESSAGE,
1052                          "Target, control IN transfer on endpoint %d : the host only requested %d bytes instead of %d",
1053                          len, control_in_test_packet_size);
1054                 cyg_semaphore_post(&(control_in_test->sem));
1055                 control_in_test = (UsbTest*) 0;
1056                 result = USBS_CONTROL_RETURN_STALL;
1057                 break;
1058             }
1059
1060             // Prepare a suitable reply buffer. This is happening at
1061             // DSR level so runtime is important, but with an upper
1062             // bound of 255 bytes the buffer should be small enough.
1063             buf = control_in_test->buffer;
1064             usbtest_fill_buffer(&(control_in_test->test_params.control_in.data), buf, control_in_test_packet_size);
1065             control_endpoint->buffer_size   = control_in_test_packet_size;
1066             control_endpoint->buffer        = buf;
1067             USBTEST_CONTROL_NEXT_PACKET_SIZE(control_in_test_packet_size, control_in_test->test_params.control_in);
1068
1069             // Have all the packets been transferred?
1070             control_in_packets_transferred++;
1071             if (control_in_packets_transferred == control_in_test->test_params.control_in.number_packets) {
1072                 cyg_semaphore_post(&(control_in_test->sem));
1073                 control_in_test = (UsbTest*) 0;
1074             }
1075             result = USBS_CONTROL_RETURN_HANDLED;
1076             break;
1077       }
1078       default:
1079         CYG_FAIL("Unexpected reserved control message");
1080         break;
1081     }
1082     
1083     return result;
1084 }
1085
1086 /*}}}*/
1087
1088 // FIXME: add more tests.
1089
1090 // This utility is invoked from a thread in the thread pool whenever there is
1091 // work to be done. It simply dispatches to the appropriate handler.
1092 static void
1093 run_test(UsbTest* test)
1094 {
1095     switch(test->which_test)
1096     {
1097       case usbtest_bulk_out :       run_test_bulk_out(test); break;
1098       case usbtest_bulk_in :        run_test_bulk_in(test); break;
1099       case usbtest_control_in:      run_test_control_in(test); break;
1100       default:
1101         CYG_TEST_FAIL_EXIT("Internal error, attempt to run unknown test.\n");
1102         break;
1103     }
1104 }
1105
1106 /*}}}*/
1107 /*{{{  The thread pool                                          */
1108
1109 // ----------------------------------------------------------------------------
1110 // Just like on the host side, it is desirable to have a pool of
1111 // threads available to perform test operations. Strictly speaking
1112 // some tests will run without needing a separate thread, since many
1113 // operations can be performed at DSR level. However typical
1114 // application code will involve threads and it is desirable for test
1115 // code to behave the same way. Also, some operations like validating
1116 // the transferred data are expensive, and best done in thread context.
1117
1118 typedef struct PoolEntry {
1119     cyg_sem_t           wakeup;
1120     cyg_thread          thread_data;
1121     cyg_handle_t        thread_handle;
1122     char                thread_name[16];
1123     char                thread_stack[2 * CYGNUM_HAL_STACK_SIZE_TYPICAL];
1124     cyg_bool            in_use;
1125     cyg_bool            running;
1126     UsbTest             test;
1127 } PoolEntry;
1128
1129 // This array must be uninitialized, or the executable size would
1130 // be ludicrous.
1131 PoolEntry  pool[USBTEST_MAX_CONCURRENT_TESTS];
1132
1133 // The entry point for every thread in the pool. It just loops forever,
1134 // waiting until it is supposed to run a test.
1135 static void
1136 pool_thread_function(cyg_addrword_t arg)
1137 {
1138     PoolEntry*  pool_entry  = (PoolEntry*) arg;
1139
1140     for ( ; ; ) {
1141         cyg_semaphore_wait(&(pool_entry->wakeup));
1142         run_test(&(pool_entry->test));
1143         pool_entry->running = 0;
1144     }
1145 }
1146
1147 // Initialize all threads in the pool.
1148 static void
1149 pool_initialize(void)
1150 {
1151     int i;
1152     for (i = 0; i < USBTEST_MAX_CONCURRENT_TESTS; i++) {
1153         cyg_semaphore_init(&(pool[i].wakeup), 0);
1154         pool[i].in_use  = 0;
1155         pool[i].running = 0;
1156         sprintf(pool[i].thread_name, "worker%d", i);
1157         cyg_thread_create( 0, &pool_thread_function, (cyg_addrword_t) &(pool[i]),
1158                            pool[i].thread_name, pool[i].thread_stack, 2 * CYGNUM_HAL_STACK_SIZE_TYPICAL,
1159                            &(pool[i].thread_handle), &(pool[i].thread_data));
1160         cyg_thread_resume(pool[i].thread_handle);
1161     }
1162 }
1163
1164 // Allocate a single entry in the thread pool
1165 static UsbTest*
1166 pool_allocate(void)
1167 {
1168     UsbTest*    result  = (UsbTest*) 0;
1169
1170     if (thread_counter == USBTEST_MAX_CONCURRENT_TESTS) {
1171         CYG_TEST_FAIL_EXIT("Internal error, thread resources exhaused.\n");
1172     }
1173     
1174     result = &(pool[thread_counter].test);
1175     thread_counter++;
1176     reset_usbtest(result);
1177     return result;
1178 }
1179
1180 // Start all the threads that are supposed to be running tests.
1181 static void
1182 pool_start(void)
1183 {
1184     int i;
1185     for (i = 0; i < thread_counter; i++) {
1186         pool[i].running = 1;
1187         cyg_semaphore_post(&(pool[i].wakeup));
1188     }
1189 }
1190
1191 /*}}}*/
1192 /*{{{  Class control messages                                   */
1193
1194 // ----------------------------------------------------------------------------
1195 // Handle class control messages. These provide the primary form of
1196 // communication between host and target. There are requests to find out
1197 // the number of endpoints, details of each endpoint, prepare a test run,
1198 // abort a test run, get status, terminate the target-side, and so on.
1199 // The handlers for starting specific test cases are kept alongside
1200 // the test cases themselves.
1201 //
1202 // Note that these handlers will typically be invoked from DSR context
1203 // and hence they are subject to the usual DSR restrictions.
1204 //
1205 // Problems have been experienced in some hosts sending control messages
1206 // that involve additional host->target data. An ugly workaround is
1207 // in place whereby any such data is sent in advance using separate
1208 // control messages.
1209
1210 /*{{{  endpoint count                                           */
1211
1212 // How many endpoints are supported by this device? That information is
1213 // determined during initialization.
1214 static usbs_control_return
1215 handle_endpoint_count(usb_devreq* req)
1216 {
1217     CYG_ASSERTC((1 == req->length_lo) && (0 == req->length_hi) && \
1218                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1219     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1220     
1221     class_reply[0]                  = (unsigned char) number_endpoints;
1222     control_endpoint->buffer        = class_reply;
1223     control_endpoint->buffer_size   = 1;
1224     return USBS_CONTROL_RETURN_HANDLED;
1225 }
1226
1227 /*}}}*/
1228 /*{{{  endpoint details                                         */
1229
1230 // The host wants to know the details of a specific USB endpoint.
1231 // The format is specified in protocol.h
1232 static usbs_control_return
1233 handle_endpoint_details(usb_devreq* req)
1234 {
1235     int buf_index;
1236
1237     CYG_ASSERTC((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN);
1238     CYG_ASSERTC((USBTEST_MAX_CONTROL_DATA == req->length_lo) && (0 == req->length_hi));
1239     CYG_ASSERTC(req->index_lo < number_endpoints);
1240     CYG_ASSERTC((0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1241     
1242     class_reply[0]  = (unsigned char) usbs_testing_endpoints[req->index_lo].endpoint_type;
1243     class_reply[1]  = (unsigned char) usbs_testing_endpoints[req->index_lo].endpoint_number;
1244     class_reply[2]  = (unsigned char) usbs_testing_endpoints[req->index_lo].endpoint_direction;
1245     class_reply[3]  = (unsigned char) usbs_testing_endpoints[req->index_lo].max_in_padding;
1246     buf_index = 4;
1247     pack_int(usbs_testing_endpoints[req->index_lo].min_size, class_reply, &buf_index);
1248     pack_int(usbs_testing_endpoints[req->index_lo].max_size, class_reply, &buf_index);
1249     if (NULL == usbs_testing_endpoints[req->index_lo].devtab_entry) {
1250         class_reply[buf_index]    = '\0';
1251         control_endpoint->buffer_size   = buf_index + 1;
1252     } else {
1253         int len = strlen(usbs_testing_endpoints[req->index_lo].devtab_entry) + buf_index + 1;
1254         if (len > USBTEST_MAX_CONTROL_DATA) {
1255             return USBS_CONTROL_RETURN_STALL;
1256         } else {
1257             strcpy(&(class_reply[buf_index]), usbs_testing_endpoints[req->index_lo].devtab_entry);
1258             control_endpoint->buffer_size   = len;
1259         }
1260     }
1261     control_endpoint->buffer        = class_reply;
1262     return USBS_CONTROL_RETURN_HANDLED;
1263 }
1264
1265 /*}}}*/
1266 /*{{{  sync                                                     */
1267
1268 // The host wants to know whether or not the target is currently busy doing
1269 // stuff. This information is held in a static.
1270 static usbs_control_return
1271 handle_sync(usb_devreq* req)
1272 {
1273     CYG_ASSERTC((1 == req->length_lo) && (0 == req->length_hi) && \
1274                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1275     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1276     CYG_ASSERT(0 == class_request_size, "A sync operation should not involve any data");
1277     
1278     class_reply[0]                  = (unsigned char) idle;
1279     control_endpoint->buffer        = class_reply;
1280     control_endpoint->buffer_size   = 1;
1281     return USBS_CONTROL_RETURN_HANDLED;
1282 }
1283
1284 /*}}}*/
1285 /*{{{  pass/fail                                                */
1286
1287 // Allow the host to generate some pass or fail messages, and
1288 // optionally terminate the test. These are synchronous requests
1289 // so the data can be left in class_request.
1290
1291 static int passfail_request   = 0;
1292
1293 // Invoked from thread context
1294 static void
1295 handle_passfail_action(void)
1296 {
1297     switch (passfail_request) {
1298       case USBTEST_PASS:
1299         CYG_TEST_PASS(class_request);
1300         break;
1301       case USBTEST_PASS_EXIT:
1302         CYG_TEST_PASS(class_request);
1303         CYG_TEST_EXIT("Exiting normally as requested by the host");
1304         break;
1305       case USBTEST_FAIL:
1306         CYG_TEST_FAIL(class_request);
1307         break;
1308       case USBTEST_FAIL_EXIT:
1309         CYG_TEST_FAIL(class_request);
1310         CYG_TEST_EXIT("Exiting normally as requested by the host");
1311         break;
1312       default:
1313         CYG_FAIL("Bogus invocation of usbtest_main_passfail");
1314         break;
1315     }
1316 }
1317
1318 // Invoked from DSR context
1319 static usbs_control_return
1320 handle_passfail(usb_devreq* req)
1321 {
1322     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1323     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1324     CYG_ASSERT(class_request_size > 0, "A pass/fail message should be supplied");
1325     CYG_ASSERT(idle, "Pass/fail messages are only allowed when idle");
1326     CYG_ASSERT((void (*)(void))0 == main_thread_action, "No thread operation should be pending.");
1327     
1328     passfail_request    = req->request;
1329     idle                = false;
1330     main_thread_action  = &handle_passfail_action;
1331     cyg_semaphore_post(&main_wakeup);
1332
1333     return USBS_CONTROL_RETURN_HANDLED;
1334 }
1335
1336 /*}}}*/
1337 /*{{{  abort                                                    */
1338
1339 // The host has concluded that there is no easy way to get both target and
1340 // host back to a sensible state. For example there may be a thread that
1341 // is blocked waiting for some I/O that is not going to complete. The abort
1342 // should be handled at thread level, not DSR level, so that the host
1343 // still sees the low-level USB handshake.
1344
1345 static void
1346 handle_abort_action(void)
1347 {
1348     CYG_TEST_FAIL_EXIT("Test abort requested by host application");
1349 }
1350
1351 static usbs_control_return
1352 handle_abort(usb_devreq* req)
1353 {
1354     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1355     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1356     CYG_ASSERT(idle, "Abort messages are only allowed when idle");
1357     CYG_ASSERT((void (*)(void))0 == main_thread_action, "No thread operation should be pending.");
1358     
1359     idle                = false;
1360     main_thread_action  = &handle_abort_action;
1361     cyg_semaphore_post(&main_wakeup);
1362     
1363     return USBS_CONTROL_RETURN_HANDLED;
1364 }
1365
1366 /*}}}*/
1367 /*{{{  cancel                                                   */
1368
1369 // Invoked from thread context
1370 // Cancelling pending test cases simply involves iterating over the allocated
1371 // entries in the pool, invoking any cancellation functions that have been
1372 // defined, and then resetting the tread count. The actual tests have not
1373 // yet started so none of the threads will be active.
1374 static void
1375 handle_cancel_action(void)
1376 {
1377     int i;
1378     for (i = 0; i < thread_counter; i++) {
1379         if ((void (*)(UsbTest*))0 != pool[i].test.cancel_fn) {
1380             (*(pool[i].test.cancel_fn))(&(pool[i].test));
1381             pool[i].test.cancel_fn  = (void (*)(UsbTest*)) 0;
1382         }
1383     }
1384     thread_counter    = 0;
1385 }
1386
1387 // Invoked from DSR context
1388 static usbs_control_return
1389 handle_cancel(usb_devreq* req)
1390 {
1391     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1392     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1393     CYG_ASSERT(0 == class_request_size, "A cancel operation should not involve any data");
1394     CYG_ASSERT(idle, "Cancel requests are only allowed when idle");
1395     CYG_ASSERT(!running, "Cancel requests cannot be sent once the system is running");
1396     CYG_ASSERT((void (*)(void))0 == main_thread_action, "No thread operation should be pending.");
1397     
1398     idle                = false;
1399     main_thread_action = &handle_cancel_action;
1400     cyg_semaphore_post(&main_wakeup);
1401
1402     return USBS_CONTROL_RETURN_HANDLED;
1403 }
1404
1405 /*}}}*/
1406 /*{{{  start                                                    */
1407
1408 // Start the tests running. This just involves waking up the pool threads
1409 // and setting the running flag, with the latter serving primarily for
1410 // assertions. 
1411
1412 static usbs_control_return
1413 handle_start(usb_devreq* req)
1414 {
1415     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1416     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1417     CYG_ASSERT(0 == class_request_size, "A start operation should not involve any data");
1418     CYG_ASSERT(!running, "Start requests cannot be sent if the system is already running");
1419
1420     current_tests_terminated = false;
1421     running = true;
1422     pool_start();
1423     
1424     return USBS_CONTROL_RETURN_HANDLED;
1425 }
1426
1427 /*}}}*/
1428 /*{{{  finished                                                 */
1429
1430 // Have all the tests finished? This involves checking all the threads
1431 // involved in the current batch of tests and seeing whether or not
1432 // their running flag is still set.
1433
1434 static usbs_control_return
1435 handle_finished(usb_devreq* req)
1436 {
1437     int i;
1438     int result = 1;
1439     
1440     CYG_ASSERTC((1 == req->length_lo) && (0 == req->length_hi) && \
1441                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1442     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1443     CYG_ASSERT(0 == class_request_size, "A finished operation should not involve any data");
1444     CYG_ASSERT(running, "Finished requests can only be sent if the system is already running");
1445     
1446     for (i = 0; i < thread_counter; i++) {
1447         if (pool[i].running) {
1448             result = 0;
1449             break;
1450         }
1451     }
1452     class_reply[0]                  = (unsigned char) result;
1453     control_endpoint->buffer        = class_reply;
1454     control_endpoint->buffer_size   = 1;
1455     return USBS_CONTROL_RETURN_HANDLED;
1456 }
1457
1458 /*}}}*/
1459 /*{{{  set terminated                                           */
1460
1461 // A timeout has occurred, or there is some other failure. The first step
1462 // in recovery is to set the terminated flag so that as recovery action
1463 // takes place and the threads wake up they make no attempt to continue
1464 // doing more transfers.
1465
1466 static usbs_control_return
1467 handle_set_terminated(usb_devreq* req)
1468 {
1469     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1470     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1471     CYG_ASSERT(0 == class_request_size, "A set-terminated operation should not involve any data");
1472     CYG_ASSERT(running, "The terminated flag can only be set when there are running tests");
1473
1474     current_tests_terminated = 1;
1475     
1476     return USBS_CONTROL_RETURN_HANDLED;
1477 }
1478
1479 /*}}}*/
1480 /*{{{  get recovery                                             */
1481
1482 // Return the recovery information for one of the threads involved in the
1483 // current batch of tests, so that the host can perform a USB operation
1484 // that will sort out that thread.
1485 static usbs_control_return
1486 handle_get_recovery(usb_devreq* req)
1487 {
1488     int buffer_index;
1489     
1490     CYG_ASSERT(current_tests_terminated, "Recovery should only be attempted when the terminated flag is set");
1491     CYG_ASSERT(running, "If there are no tests running then recovery is impossible");
1492     CYG_ASSERTC((12 == req->length_lo) && (0 == req->length_hi) && \
1493                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1494     CYG_ASSERTC(req->index_lo <= thread_counter);
1495     CYG_ASSERTC((0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1496     CYG_ASSERT(0 == class_request_size, "A get-recovery operation should not involve any data");
1497
1498     control_endpoint->buffer        = class_reply;
1499     if (!pool[req->index_lo].running) {
1500         // Actually, this particular thread has terminated so no recovery is needed.
1501         control_endpoint->buffer_size   = 0;
1502     } else {
1503         buffer_index    = 0;
1504         pack_usbtest_recovery(&(pool[req->index_lo].test.recovery), class_reply, &buffer_index);
1505         control_endpoint->buffer_size   = buffer_index;
1506     }
1507     
1508     return USBS_CONTROL_RETURN_HANDLED;
1509 }
1510
1511 /*}}}*/
1512 /*{{{  perform recovery                                         */
1513
1514 // The host has identified a course of action that could unlock a thread
1515 // on the host-side that is currently blocked performing a USB operation.
1516 // Typically this involves either sending or accepting some data. If the
1517 // endpoint is still locked, in other words if there is a still a local
1518 // thread attempting to communicate on the specified endpoint, then
1519 // things are messed up: both sides are trying to communicate, but nothing
1520 // is happening. The eCos USB API is such that attempting multiple
1521 // concurrent operations on a single endpoint is disallowed, so
1522 // the recovery request has to be ignored. If things do not sort themselves
1523 // out then the whole test run will have to be aborted.
1524
1525 // A dummy completion function for when a recovery operation has completed.
1526 static void
1527 recovery_callback(void* callback_arg, int transferred)
1528 {
1529     CYG_UNUSED_PARAM(void*, callback_arg);
1530     CYG_UNUSED_PARAM(int, transferred);
1531 }
1532     
1533 static usbs_control_return
1534 handle_perform_recovery(usb_devreq* req)
1535 {
1536     int                 buffer_index;
1537     int                 endpoint_number;
1538     int                 endpoint_direction;
1539     UsbTest_Recovery    recovery;
1540     
1541     CYG_ASSERT(current_tests_terminated, "Recovery should only be attempted when the terminated flag is set");
1542     CYG_ASSERT(running, "If there are no tests running then recovery is impossible");
1543     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1544     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1545     CYG_ASSERT(12 == class_request_size, "A perform-recovery operation requires recovery data");
1546
1547     buffer_index = 0;
1548     unpack_usbtest_recovery(&recovery, class_request, &buffer_index);
1549     endpoint_number     = recovery.endpoint & ~USB_DEVREQ_DIRECTION_MASK;
1550     endpoint_direction  = recovery.endpoint & USB_DEVREQ_DIRECTION_MASK;
1551
1552     if (!is_endpoint_locked(endpoint_number, endpoint_direction)) {
1553         // Locking the endpoint here would be good, but the endpoint would then
1554         // have to be unlocked again - probably in the recovery callback.
1555         // This complication is ignored for now.
1556
1557         if (USB_ENDPOINT_DESCRIPTOR_ATTR_BULK == recovery.protocol) {
1558             int ep_index = lookup_endpoint(endpoint_number, endpoint_direction, USB_ENDPOINT_DESCRIPTOR_ATTR_BULK);
1559             CYG_ASSERTC(-1 != ep_index);
1560
1561             if (USB_DEVREQ_DIRECTION_IN == endpoint_direction) {
1562                 // The host wants some data. Supply it. A single byte will do fine to
1563                 // complete the transfer.
1564                 usbs_start_tx_buffer((usbs_tx_endpoint*) usbs_testing_endpoints[ep_index].endpoint,
1565                                      recovery_buffer, 1, &recovery_callback, (void*) 0);
1566             } else {
1567                 // The host is trying to send some data. Accept all of it.
1568                 usbs_start_rx_buffer((usbs_rx_endpoint*) usbs_testing_endpoints[ep_index].endpoint,
1569                                      recovery_buffer, recovery.size, &recovery_callback, (void*) 0);
1570             }
1571         }
1572
1573         // No support for isochronous or interrupt transfers yet.
1574         // handle_reserved_control_messages() should generate stalls which
1575         // have the desired effect.
1576     }
1577     
1578     return USBS_CONTROL_RETURN_HANDLED;
1579 }
1580
1581 /*}}}*/
1582 /*{{{  get result                                               */
1583
1584 // Return the result of one the tests. This can be a single byte for
1585 // a pass, or a single byte plus a message for a failure.
1586
1587 static usbs_control_return
1588 handle_get_result(usb_devreq* req)
1589 {
1590     CYG_ASSERTC((USBTEST_MAX_CONTROL_DATA == req->length_lo) && (0 == req->length_hi) && \
1591                 ((req->type & USB_DEVREQ_DIRECTION_MASK) == USB_DEVREQ_DIRECTION_IN));
1592     CYG_ASSERTC(req->index_lo <= thread_counter);
1593     CYG_ASSERTC((0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1594     CYG_ASSERT(0 == class_request_size, "A get-result operation should not involve any data");
1595     CYG_ASSERT(running, "Results can only be sent if a run is in progress");
1596     CYG_ASSERT(!pool[req->index_lo].running, "Cannot request results for a test that has not completed");
1597
1598     class_reply[0]  = pool[req->index_lo].test.result_pass;
1599     if (class_reply[0]) {
1600         control_endpoint->buffer_size = 1;
1601     } else {
1602         strncpy(&(class_reply[1]), pool[req->index_lo].test.result_message, USBTEST_MAX_CONTROL_DATA - 2);
1603         class_reply[USBTEST_MAX_CONTROL_DATA - 1] = '\0';
1604         control_endpoint->buffer_size = 1 + strlen(&(class_reply[1])) + 1;
1605     }
1606     control_endpoint->buffer = class_reply;
1607     return USBS_CONTROL_RETURN_HANDLED;
1608 }
1609
1610 /*}}}*/
1611 /*{{{  batch done                                               */
1612
1613 // A batch of test has been completed - at least, the host thinks so.
1614 // If the host is correct then all that is required here is to reset
1615 // the thread pool and clear the global running flag - that is sufficient
1616 // to allow a new batch of tests to be started.
1617
1618 static usbs_control_return
1619 handle_batch_done(usb_devreq* req)
1620 {
1621     int i;
1622     
1623     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1624     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi) && (0 == req->value_lo) && (0 == req->value_hi));
1625     CYG_ASSERT(0 == class_request_size, "A batch-done operation should not involve any data");
1626     CYG_ASSERT(running, "There must be a current batch of tests");
1627
1628     for (i = 0; i < thread_counter; i++) {
1629         CYG_ASSERTC(!pool[i].running);
1630     }
1631     thread_counter  = 0;
1632     running         = false;
1633     
1634     return USBS_CONTROL_RETURN_HANDLED;
1635
1636 }
1637
1638 /*}}}*/
1639 /*{{{  verbosity                                                */
1640
1641 static usbs_control_return
1642 handle_verbose(usb_devreq* req)
1643 {
1644     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1645     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi));
1646     CYG_ASSERT(0 == class_request_size, "A set-verbosity operation should not involve any data");
1647
1648     verbose = (req->value_hi << 8) + req->value_lo;
1649     
1650     return USBS_CONTROL_RETURN_HANDLED;
1651 }
1652
1653 /*}}}*/
1654 /*{{{  initialise bulk out endpoint                             */
1655
1656 // ----------------------------------------------------------------------------
1657 // Accept an initial endpoint on a bulk endpoint. This avoids problems
1658 // on some hardware such as the SA11x0 which can start to accept data
1659 // before the software is ready for it.
1660
1661 static void handle_init_callback(void* arg, int result)
1662 {
1663     idle = true;
1664 }
1665
1666 static usbs_control_return
1667 handle_init_bulk_out(usb_devreq* req)
1668 {
1669     static char         buf[64];
1670     int                 ep_index;
1671     usbs_rx_endpoint*   endpoint;
1672     
1673     CYG_ASSERTC((0 == req->length_lo) && (0 == req->length_hi));
1674     CYG_ASSERTC((0 == req->index_lo) && (0 == req->index_hi));
1675     CYG_ASSERTC((0 == req->value_hi) && (0 < req->value_lo) && (req->value_lo < 16));
1676     CYG_ASSERT(0 == class_request_size, "An init_bulk_out operation should not involve any data");
1677
1678     ep_index = lookup_endpoint(req->value_lo, USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT, USB_ENDPOINT_DESCRIPTOR_ATTR_BULK);
1679     CYG_ASSERTC(-1 != ep_index);
1680     endpoint = (usbs_rx_endpoint*) usbs_testing_endpoints[ep_index].endpoint;
1681     
1682     idle = false;
1683     usbs_start_rx_buffer(endpoint, buf, 64, &handle_init_callback, (void*) 0);
1684     
1685     return USBS_CONTROL_RETURN_HANDLED;
1686 }
1687
1688 /*}}}*/
1689 /*{{{  additional control data                                  */
1690
1691 // Accumulate some more data in the control buffer, ahead of an upcoming
1692 // request.
1693 static usbs_control_return
1694 handle_control_data(usb_devreq* req)
1695 {
1696     class_request[class_request_size + 0] = req->value_hi;
1697     class_request[class_request_size + 1] = req->value_lo;
1698     class_request[class_request_size + 2] = req->index_hi;
1699     class_request[class_request_size + 3] = req->index_lo;
1700
1701     switch(req->request) {
1702       case USBTEST_CONTROL_DATA1 : class_request_size += 1; break;
1703       case USBTEST_CONTROL_DATA2 : class_request_size += 2; break;
1704       case USBTEST_CONTROL_DATA3 : class_request_size += 3; break;
1705       case USBTEST_CONTROL_DATA4 : class_request_size += 4; break;
1706     }
1707
1708     return USBS_CONTROL_RETURN_HANDLED;
1709 }
1710
1711 /*}}}*/
1712
1713 typedef struct class_handler {
1714     int     request;
1715     usbs_control_return (*handler)(usb_devreq*);
1716 } class_handler;
1717 static class_handler class_handlers[] = {
1718     { USBTEST_ENDPOINT_COUNT,   &handle_endpoint_count },
1719     { USBTEST_ENDPOINT_DETAILS, &handle_endpoint_details },
1720     { USBTEST_PASS,             &handle_passfail },
1721     { USBTEST_PASS_EXIT,        &handle_passfail },
1722     { USBTEST_FAIL,             &handle_passfail },
1723     { USBTEST_FAIL_EXIT,        &handle_passfail },
1724     { USBTEST_SYNCH,            &handle_sync },
1725     { USBTEST_ABORT,            &handle_abort },
1726     { USBTEST_CANCEL,           &handle_cancel },
1727     { USBTEST_START,            &handle_start },
1728     { USBTEST_FINISHED,         &handle_finished },
1729     { USBTEST_SET_TERMINATED,   &handle_set_terminated },
1730     { USBTEST_GET_RECOVERY,     &handle_get_recovery },
1731     { USBTEST_PERFORM_RECOVERY, &handle_perform_recovery },
1732     { USBTEST_GET_RESULT,       &handle_get_result },
1733     { USBTEST_BATCH_DONE,       &handle_batch_done },
1734     { USBTEST_VERBOSE,          &handle_verbose },
1735     { USBTEST_INIT_BULK_OUT,    &handle_init_bulk_out },
1736     { USBTEST_TEST_BULK,        &handle_test_bulk },
1737     { USBTEST_TEST_CONTROL_IN,  &handle_test_control_in },
1738     { USBTEST_CONTROL_DATA1,    &handle_control_data },
1739     { USBTEST_CONTROL_DATA2,    &handle_control_data },
1740     { USBTEST_CONTROL_DATA3,    &handle_control_data },
1741     { USBTEST_CONTROL_DATA4,    &handle_control_data },
1742     { -1,                       (usbs_control_return (*)(usb_devreq*)) 0 }
1743 };
1744
1745 static usbs_control_return
1746 handle_class_control_messages(usbs_control_endpoint* endpoint, void* data)
1747 {
1748     usb_devreq*         req = (usb_devreq*) endpoint->control_buffer;
1749     int                 request = req->request;
1750     usbs_control_return result;
1751     int                 i;
1752
1753     VERBOSE(3, "Received control message %02x\n", request);
1754     
1755     CYG_ASSERT(endpoint == control_endpoint, "control endpoint mismatch");
1756     result  = USBS_CONTROL_RETURN_UNKNOWN;
1757     for (i = 0; (usbs_control_return (*)(usb_devreq*))0 != class_handlers[i].handler; i++) {
1758         if (request == class_handlers[i].request) {
1759             result = (*(class_handlers[i].handler))(req);
1760             if ((USBTEST_CONTROL_DATA1 != request) &&
1761                 (USBTEST_CONTROL_DATA2 != request) &&
1762                 (USBTEST_CONTROL_DATA3 != request) &&
1763                 (USBTEST_CONTROL_DATA4 != request)) {
1764                 // Reset the request data buffer after all normal requests.
1765                 class_request_size = 0;
1766             }
1767             break;
1768         }
1769     }
1770     CYG_UNUSED_PARAM(void*, data);
1771     if (USBS_CONTROL_RETURN_HANDLED != result) {
1772         VERBOSE(1, "Control message %02x not handled\n", request);
1773     }
1774     
1775     return result;
1776 }
1777
1778 /*}}}*/
1779 /*{{{  main()                                                   */
1780
1781 // ----------------------------------------------------------------------------
1782 // Initialization.
1783 int
1784 main(int argc, char** argv)
1785 {
1786     int i;
1787
1788     CYG_TEST_INIT();
1789
1790     // The USB device driver should have provided an array of endpoint
1791     // descriptors, usbs_testing_endpoints(). One entry in this array
1792     // should be a control endpoint, which is needed for initialization.
1793     // It is also useful to know how many endpoints there are.
1794     for (i = 0; !USBS_TESTING_ENDPOINTS_IS_TERMINATOR(usbs_testing_endpoints[i]); i++) {
1795         if ((0 == usbs_testing_endpoints[i].endpoint_number) &&
1796             (USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL== usbs_testing_endpoints[i].endpoint_type)) {
1797             CYG_ASSERT((usbs_control_endpoint*)0 == control_endpoint, "There should be only one control endpoint");
1798             control_endpoint = (usbs_control_endpoint*) usbs_testing_endpoints[i].endpoint;
1799         }
1800     }
1801     if ((usbs_control_endpoint*)0 == control_endpoint) {
1802         CYG_TEST_FAIL_EXIT("Unable to find a USB control endpoint");
1803     }
1804     number_endpoints = i;
1805     CYG_ASSERT(number_endpoints <= USBTEST_MAX_ENDPOINTS, "impossible number of endpoints");
1806
1807     // Some of the information provided may not match the actual capabilities
1808     // of the testing code, e.g. max_size limits.
1809     fix_driver_endpoint_data();
1810     
1811     // This semaphore is used for communication between the DSRs that process control
1812     // messages and the main thread
1813     cyg_semaphore_init(&main_wakeup, 0);
1814
1815     // Take care of the pool of threads and related data.
1816     pool_initialize();
1817
1818     // Start the heartbeat thread, to make sure that the gdb session stays
1819     // alive.
1820     start_heartbeat();
1821     
1822     // Now it is possible to start up the USB device driver. The host can detect
1823     // this, connect, get the enumeration data, and then testing will proceed
1824     // in response to class control messages.
1825     provide_endpoint_enumeration_data();
1826     control_endpoint->enumeration_data      = &usb_enum_data;
1827     control_endpoint->class_control_fn      = &handle_class_control_messages;
1828     control_endpoint->reserved_control_fn   = &handle_reserved_control_messages;
1829     usbs_start(control_endpoint);
1830
1831     // Now it is over to the host to detect this target and start performing tests.
1832     // Much of this is handled at DSR level, in response to USB control messages.
1833     // Some of those control messages require action at thread level, and that is
1834     // achieved by signalling a semaphore and waking up this thread. A static
1835     // function pointer is used to keep track of what operation is actually required.
1836     for (;;) {
1837         void (*handler)(void);
1838         
1839         cyg_semaphore_wait(&main_wakeup);
1840         handler = main_thread_action;
1841         main_thread_action   = 0;
1842         CYG_CHECK_FUNC_PTR(handler, "Main thread woken up when there is nothing to be done");
1843         (*handler)();
1844         idle = true;
1845     }
1846 }
1847
1848 /*}}}*/