]> git.karo-electronics.de Git - karo-tx-redboot.git/blob - packages/io/usb/slave/v2_0/host/usbhost.c
2aa47f5e50bc8ad464e4bbce056eedfd697151fb
[karo-tx-redboot.git] / packages / io / usb / slave / v2_0 / host / usbhost.c
1 /*{{{  Banner                                                   */
2
3 //=================================================================
4 //
5 //        host.c
6 //
7 //        USB testing - host-side
8 //
9 //==========================================================================
10 //####ECOSGPLCOPYRIGHTBEGIN####
11 // -------------------------------------------
12 // This file is part of eCos, the Embedded Configurable Operating System.
13 // Copyright (C) 2005 eCosCentric Ltd.
14 // Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
15 //
16 // eCos is free software; you can redistribute it and/or modify it under
17 // the terms of the GNU General Public License as published by the Free
18 // Software Foundation; either version 2 or (at your option) any later version.
19 //
20 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
21 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
22 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
23 // for more details.
24 //
25 // You should have received a copy of the GNU General Public License along
26 // with eCos; if not, write to the Free Software Foundation, Inc.,
27 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
28 //
29 // As a special exception, if other files instantiate templates or use macros
30 // or inline functions from this file, or you compile this file and link it
31 // with other works to produce a work based on this file, this file does not
32 // by itself cause the resulting work to be covered by the GNU General Public
33 // License. However the source code for this file must still be made available
34 // in accordance with section (3) of the GNU General Public License.
35 //
36 // This exception does not invalidate any other reasons why a work based on
37 // this file might be covered by the GNU General Public License.
38 //
39 // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
40 // at http://sources.redhat.com/ecos/ecos-license/
41 // -------------------------------------------
42 //####ECOSGPLCOPYRIGHTEND####
43 //==========================================================================
44 //#####DESCRIPTIONBEGIN####
45 //
46 // Author(s):     bartv
47 // Date:          2001-07-04
48 //####DESCRIPTIONEND####
49 //==========================================================================
50
51 // The overall architecture is as follows.
52 //
53 // The target hardware runs a special application which provides a
54 // particular type of USB application, "Red Hat eCos USB testing".
55 // This will not be recognised by any device driver, so the Linux
56 // kernel will pretty much ignore the device (other host OS's are not
57 // considered at this time).
58 //
59 // This program is the only supported way to interact with that service.
60 // It acts as an extended Tcl interpreter, providing a number of new
61 // Tcl commands for interacting with the target. All test cases can
62 // then be written as Tcl scripts which invoke a series of these commands.
63 // These Tcl commands operate essentially though the LINUX usb devfs
64 // service which allows ordinary application code to perform USB operations
65 // via ioctl()'s.
66
67 /*}}}*/
68 /*{{{  #include's                                               */
69
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <ctype.h>
74 #include <limits.h>
75 #include <errno.h>
76 #include <sys/types.h>
77 #include <sys/stat.h>
78 #include <unistd.h>
79 #include <fcntl.h>
80 #include <sys/ioctl.h>
81 #include <time.h>
82 #include <pthread.h>
83 #include <semaphore.h>
84 // Avoid compatibility problems with Tcl 8.4 vs. earlier
85 #define USE_NON_CONST
86 #include <tcl.h>
87 #include <linux/usb.h>
88 #include <linux/usbdevice_fs.h>
89 #include "../tests/protocol.h"
90 #include "config.h"
91
92 /*}}}*/
93
94 /*{{{  Backwards compatibility                                  */
95
96 // The header file <linux/usbdevice_fs.h> has changed in an incompatible
97 // way. This is detected by autoconf
98 #ifndef CYGBLD_USE_NEW_FIELD_NAMES
99 # define bRequestType   requesttype
100 # define bRequest       request
101 # define wValue         value
102 # define wIndex         index
103 # define wLength        length
104 #endif
105
106 /*}}}*/
107 /*{{{  Statics                                                  */
108
109 // ----------------------------------------------------------------------------
110 // Statics.
111
112 // Has the current batch of tests actually terminated? This flag is
113 // checked by the various test handlers at appropriate intervals, and
114 // helps to handle the case where one of the side has terminated early
115 // because an error has been detected.
116 static int          current_tests_terminated = 0;
117
118 // The next local thread to be allocated for testing. This variable can also
119 // be used to find out how many threads are involved in the current test.
120 // This counter should always be reset to 0 at the end of every test run.
121 static int          local_thread_count      = 0;
122
123 // A similar counter for remote threads.
124 static int          remote_thread_count     = 0;
125
126 // A file handle for manipulating the USB device at a low level
127 static int          usb_master_fd  = -1;
128
129 /*}}}*/
130 /*{{{  Logging                                                  */
131
132 // ----------------------------------------------------------------------------
133 // The user can provide one or more -V/--verbose arguments to increase
134 // the amount of output generated.
135
136 static int verbose = 0;
137
138 #define VERBOSE(_level_, _format_, _args_...)   \
139     do {                                        \
140         if (verbose >= _level_) {               \
141             printf(_format_, ## _args_);        \
142         }                                       \
143     } while (0);
144
145 /*}}}*/
146 /*{{{  Low-level USB access                                     */
147
148 // ----------------------------------------------------------------------------
149 // Low-level access to a USB device.
150 //
151 // The various ioctl() calls require a file handle which corresponds to one
152 // of the /proc/bus/usb/<abc>/<def> entries. <abc> is a bus number,
153 // typically 001 or 001, and <def> is a device number on that bus,
154 // e.g. 003. Figuring out <abc> and <def> requires scanning
155 // /proc/bus/usb/devices, which is a somewhat complicated text file.
156 //
157 // This is all somewhat vulnerable to incompatible changes in the
158 // Linux kernel, specifically the implementation of the /proc/bus/usb.
159 // An alternative approach would be to write a new Linux device driver
160 // and interact with that, but that approach is vulnerable to any
161 // internal kernel API changes affecting USB device drivers.
162
163 // How to access USB devices from userland
164 #define USB_ROOT        "/proc/bus/usb/"
165
166 // How to identify the eCos test case
167 #define PRODUCT_STRING    "Red Hat eCos USB test"
168
169 // Scan through /proc/bus/usb/devices looking for an entry that
170 // matches what we are after, specifically a line
171 //   S:  Product=Red Hat eCos USB testcase
172 // The required information can then be obtained from the previous
173 // line:
174 //   T:  Bus=<abc> ... Dev#= <def> ...
175 //
176 // Of course the T: line is going to come first, so it is necessary
177 // to keep track of the current bus and device numbers.
178 //
179 // Note: this code is duplicated in usbchmod.c. Any changes here
180 // should be propagated. For now the routine is too small to warrant
181 // a separate source file.
182
183 static int
184 usb_scan_devices(int* bus, int* dev)
185 {
186     FILE*       devs_file;
187     int         current_bus     = -1;
188     int         current_dev     = -1;
189     int         ch;
190
191     *bus = -1;
192     *dev = -1;
193
194     VERBOSE(1, "Searching " USB_ROOT "devices for the eCos USB test code\n");
195     
196     devs_file = fopen(USB_ROOT "devices", "r");
197     if (NULL == devs_file) {
198         fprintf(stderr, "usbhost: error, unable to access " USB_ROOT "devices\n");
199         return 0;
200     }
201     ch = getc(devs_file);
202     while (EOF != ch) {
203         if ('T' == ch) {
204             if (2 !=fscanf(devs_file, ":  Bus=%d %*[^D\n]Dev#=%d", &current_bus, &current_dev)) { 
205                 current_bus = -1;
206                 current_dev = -1;
207             }
208         } else if ('S' == ch) {
209             int start = 0, end = 0;
210             if (EOF != fscanf(devs_file, ":  Product=%n" PRODUCT_STRING "%n", &start, &end)) {
211                 if (start < end) {
212                     *bus = current_bus;
213                     *dev = current_dev;
214                     break;
215                 }
216             } 
217         }
218         // Move to the end of the current line.
219         do {
220             ch = getc(devs_file);
221         } while ((EOF != ch) && ('\n' != ch));
222         if (EOF != ch) {
223             ch = getc(devs_file);
224         }
225     }
226     
227     fclose(devs_file);
228     if ((-1 != *bus) && (-1 != *dev)) {
229         VERBOSE(1, "Found eCos USB test code on bus %d, device %d\n", *bus, *dev);
230         return 1;
231     }
232     fprintf(stderr, "usbhost: error, failed to find a USB device \"" PRODUCT_STRING "\"\n");
233     return 0;
234 }
235
236 // Actually open the USB device, allowing subsequent ioctl() operations.
237 //
238 // Typically /proc/bus/usb/... will not allow ordinary applications
239 // to perform ioctl()'s. Instead root privileges are required. To work
240 // around this there is a little utility usbchmod, installed suid,
241 // which can be used to get access to the raw device.
242 static int
243 usb_open_device(void)
244 {
245     char devname[_POSIX_PATH_MAX];
246     static int  bus = -1;
247     static int  dev = -1;
248     int         result;
249     
250     if ((-1 == bus) || (-1 == dev)) {
251         if (!usb_scan_devices(&bus, &dev)) {
252             return -1;
253         }
254     }
255     
256     if (_POSIX_PATH_MAX == snprintf(devname, _POSIX_PATH_MAX, USB_ROOT "%03d/%03d", bus, dev)) {
257         fprintf(stderr, "usbhost: internal error, buffer overflow\n");
258         exit(EXIT_FAILURE);
259     }
260
261     VERBOSE(1, "Attempting to access USB target via %s\n", devname);
262     
263     result = open(devname, O_RDWR);
264     if (-1 == result) {
265         // Check for access right problems. If so, try to work around them
266         // by invoking usbchmod. Always look for this in the install tree,
267         // since it is only that version which is likely to have been
268         // chown'ed and chmod'ed to be suid root.
269         if (EACCES == errno) {
270             char command_name[_POSIX_PATH_MAX];
271
272             VERBOSE(1, "Insufficient access to USB target, running usbchmod\n");
273             if (_POSIX_PATH_MAX == snprintf(command_name, _POSIX_PATH_MAX, "%s/usbchmod %d %d", USBAUXDIR, bus, dev)) {
274                 fprintf(stderr, "usbhost: internal error, buffer overflow\n");
275                 exit(EXIT_FAILURE);
276             }
277             (void) system(command_name);
278             result = open(devname, O_RDWR);
279         }
280     }
281     if (-1 == result) {
282         fprintf(stderr, "usbhost: error, failed to open \"%s\", errno %d\n", devname, errno);
283     }
284
285     VERBOSE(1, "USB device now accessible via file descriptor %d\n", result);
286     
287     // Also perform a set-configuration call, to avoid warnings from
288     // the Linux kernel. Target-side testing is always configuration 1
289     // because only a single configuration is supported.
290     (void) ioctl(result, USBDEVFS_SETCONFIGURATION, 1);
291     return result;
292 }
293
294 // Exchange a control message with the host. The return value should
295 // be 0, or a small positive number indicating the actual number of
296 // bytes received which may be less than requested.
297 //
298 // There appear to be problems with some hosts, manifesting itself as
299 // an inability to send control messages that involve additional data
300 // from host->target. These problems are not yet well-understood. For
301 // now the workaround is to send multiple packets, each with up to
302 // four bytes encoded in the index and length fields.
303 static int
304 usb_control_message(int fd, int request_type, int request, int value, int index, int length, void* data)
305 {
306     struct usbdevfs_ctrltransfer        transfer;
307     int         result = 0;
308
309     VERBOSE(3, "usb_control_message, request %02x, len %d\n", request, length);
310     
311     if (length > USBTEST_MAX_CONTROL_DATA) {
312         fprintf(stderr, "usbhost: internal error, control message involves too much data.\n");
313         exit(EXIT_FAILURE);
314     }
315
316 #if 1
317     // Workaround - send additional data in the index and length fields.
318     if ((length > 0) && (USB_DIR_OUT == (USB_ENDPOINT_DIR_MASK & request_type))) {
319         int i;
320         unsigned char*  buf = (unsigned char*) data;
321         
322         for (i = 0; i < length; i+= 4) {
323             int this_len = length - 1;
324             int ioctl_result;
325             
326             transfer.bRequestType   = USB_TYPE_CLASS | USB_RECIP_DEVICE;
327             if (this_len > 4) {
328                 this_len = 4;
329             }
330             switch (this_len) {
331               case 1: transfer.bRequest = USBTEST_CONTROL_DATA1; break;
332               case 2: transfer.bRequest = USBTEST_CONTROL_DATA2; break;
333               case 3: transfer.bRequest = USBTEST_CONTROL_DATA3; break;
334               case 4: transfer.bRequest = USBTEST_CONTROL_DATA4; break;
335               default:
336                 fprintf(stderr, "usbhost: internal error, confusion about transfer length.\n");
337                 exit(EXIT_FAILURE);
338             }
339             transfer.wValue     = (buf[i]   << 8) | buf[i+1];   // Possible read beyond end of buffer,
340             transfer.wIndex     = (buf[i+2] << 8) | buf[i+3];   // but not worth worrying about.
341             transfer.wLength    = 0;
342             transfer.timeout    = 10 * 1000; // ten seconds, the target should always accept data faster than this.
343             transfer.data       = NULL;
344
345             // This is too strict, deciding what to do about errors should be
346             // handled by higher-level code. However it will do for now.
347             ioctl_result = ioctl(fd, USBDEVFS_CONTROL, &transfer);
348             if (0 != ioctl_result) {
349                 fprintf(stderr, "usbhost: error, failed to send control message (data) to target.\n");
350                 exit(EXIT_FAILURE);
351             }
352         }
353         // There is no more data to be transferred.
354         length = 0;
355     }
356 #endif    
357     transfer.bRequestType       = request_type;
358     transfer.bRequest           = request;
359     transfer.wValue             = value;
360     transfer.wIndex             = index;
361     transfer.wLength            = length;
362     transfer.timeout            = 10000;
363     transfer.data               = data;
364
365     result = ioctl(fd, USBDEVFS_CONTROL, &transfer);
366     return result;
367 }
368
369 // A variant of the above which can be called when the target should always respond
370 // correctly. This can be used for class control messages.
371 static int
372 usb_reliable_control_message(int fd, int request_type, int request, int value, int index, int length, void* data)
373 {
374     int result = usb_control_message(fd, request_type, request, value, index, length, data);
375     if (-1 == result) {
376         fprintf(stderr, "usbhost: error, failed to send control message %02x to target.\n", request);
377         fprintf(stderr, "       : errno %d (%s)\n", errno, strerror(errno));
378         exit(EXIT_FAILURE);
379     }
380     return result;
381 }
382
383     
384 // Either send or receive a single bulk message. The top bit of the endpoint
385 // number indicates the direction.
386 static int
387 usb_bulk_message(int fd, int endpoint, unsigned char* buffer, int length)
388 {
389     struct  usbdevfs_bulktransfer    transfer;
390     int     result;
391     
392     transfer.ep         = endpoint;
393     transfer.len        = length;
394     transfer.timeout    = 60 * 60 * 1000;
395     // An hour. These operations should not time out because that
396     // leaves the system in a confused state. Instead there is
397     // higher-level recovery code that should ensure the operation
398     // really does complete, and the return value here is used
399     // by the calling code to determine whether the operation
400     // was successful or whether there was an error and the recovery
401     // code was invoked.
402     transfer.data       = buffer;
403     errno               = 0;
404     result = ioctl(fd, USBDEVFS_BULK, &transfer);
405     return result;
406 }
407
408
409 // Synchronise with the target. This can be used after the host has sent a request that
410 // may take a bit of time, e.g. it may involve waking up a thread. The host will send
411 // synch requests at regular intervals, until the target is ready.
412 //
413 // The limit argument can be used to avoid locking up. -1 means loop forever, otherwise
414 // it means that many iterations of 100ms apiece.
415 static int
416 usb_sync(int fd, int limit)
417 {
418     unsigned char   buf[1];
419     struct timespec delay;
420     int             loops   = 0;
421     int             result  = 0;
422
423     VERBOSE(2, "Synchronizing with target\n");
424     
425     while (1) {
426         buf[0]  = 0;
427         usb_reliable_control_message(fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN, USBTEST_SYNCH, 0, 0, 1, buf);
428         if (buf[0]) {
429             result = 1;
430             break;
431         } else {
432             if ((-1 != limit) && (++loops > limit)) {
433                 break;
434             } else {
435                 VERBOSE(3, "Not yet synchronized, sleeping\n");
436                 delay.tv_sec    = 0;
437                 delay.tv_nsec   = 100000000;    // 100 ms
438                 nanosleep(&delay, NULL);
439             }
440         }
441     }
442     VERBOSE(2, "%s\n", result ? "Synchronized" : "Not synchronized");
443     return result;
444 }
445
446 // Abort the target. Things seem to be completely messed up and there is no easy
447 // way to restore sanity to both target and host.
448 static void
449 usb_abort(int fd)
450 {
451     VERBOSE(2, "Target-side abort operation invoked\n");
452     usb_reliable_control_message(fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_ABORT, 0, 0, 0, (void*)0);
453 }
454
455 /*}}}*/
456 /*{{{  Initialise endpoints                                     */
457
458 // ----------------------------------------------------------------------------
459 // On power-up some endpoints may not be in a sensible state. For example,
460 // with the SA11x0 the hardware may start accepting bulk OUT transfers
461 // before the target-side software has started a receive operation,
462 // so if the host sends a bulk packet before the target is ready then
463 // things get messy. This is especially troublesome if the target-side
464 // attempts any diagnostic output because of verbosity.
465 //
466 // This code loops through the various endpoints and makes sure that
467 // they are all in a reasonable state, before any real tests get run
468 // That means known hardware flaws do not show up as test failures,
469 // but of course they are still documented and application software
470 // will have to do the right thing.
471
472 static void
473 usb_initialise_control_endpoint(int min_size, int max_size)
474 {
475     // At this time there are no known problems on any hardware
476     // that would need to be addressed
477 }
478
479 static void
480 usb_initialise_isochronous_in_endpoint(int number, int min_size, int max_size)
481 {
482     // At this time there are no known problems on any hardware
483     // that would need to be addressed
484 }
485
486 static void
487 usb_initialise_isochronous_out_endpoint(int number, int min_size, int max_size)
488 {
489     // At this time there are no known problems on any hardware
490     // that would need to be addressed
491 }
492
493 static void
494 usb_initialise_bulk_in_endpoint(int number, int min_size, int max_size, int padding)
495 {
496     // At this time there are no known problems on any hardware
497     // that would need to be addressed
498 }
499
500 static void
501 usb_initialise_bulk_out_endpoint(int number, int min_size, int max_size)
502 {
503     char buf[1];
504     
505     // On the SA1110 the hardware comes up with a bogus default value,
506     // causing the hardware to accept packets before the software has
507     // set up DMA or in any way prepared for incoming data. This is
508     // a problem. It is worked around by making the target receive
509     // a single packet, sending that packet, and then performing a
510     // sync.
511     VERBOSE(2, "Performing bulk OUT initialization on endpoint %d\n", number);
512     
513     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN,
514                                  USBTEST_INIT_BULK_OUT, number, 0, 0, (void*) 0);
515     usb_bulk_message(usb_master_fd, number, buf, 1);
516     usb_sync(usb_master_fd, 10);
517 }
518
519 static void
520 usb_initialise_interrupt_in_endpoint(int number, int min_size, int max_size)
521 {
522     // At this time there are no known problems on any hardware
523     // that would need to be addressed
524 }
525
526 static void
527 usb_initialise_interrupt_out_endpoint(int number, int min_size, int max_size)
528 {
529     // At this time there are no known problems on any hardware
530     // that would need to be addressed
531 }
532
533 /*}}}*/
534 /*{{{  Host/target common code                                  */
535
536 #define HOST
537 #include "../tests/common.c"
538
539 /*}}}*/
540 /*{{{  The test cases themselves                                */
541
542 /*{{{  UsbTest definition                                       */
543
544 // ----------------------------------------------------------------------------
545 // All the data associated with a single test.
546
547 typedef struct UsbTest {
548
549     // A "unique" identifier to make verbose output easier to understand.
550     int                 id;          
551     // Which file descriptor should be used to access USB.
552     int                 fd;
553     
554     // Which test should be run.
555     usbtest             which_test;
556
557     // Test-specific details.
558     union {
559         UsbTest_Bulk        bulk;
560         UsbTest_ControlIn   control_in;
561     } test_params;
562
563     // How to recover from any problems. Specifically, what kind of message
564     // could the target send or receive that would unlock the thread on this
565     // side.
566     UsbTest_Recovery    recovery;
567
568     int                 result_pass;
569     char                result_message[USBTEST_MAX_MESSAGE];
570     unsigned char       buffer[USBTEST_MAX_BULK_DATA + USBTEST_MAX_BULK_DATA_EXTRA];
571 } UsbTest;
572
573 // Reset the information in a given test. This is used by the pool allocation
574 // code. The data union is left alone, filling in the appropriate union
575 // member is left to other code.
576 static void
577 reset_usbtest(UsbTest* test)
578 {
579     static int next_id = 1;
580     test->id                    = next_id++;
581     test->which_test            = usbtest_invalid;
582     usbtest_recovery_reset(&(test->recovery));
583     test->result_pass           = 0;
584     test->result_message[0]     = '\0';
585 }
586
587 /*}}}*/
588 /*{{{  bulk OUT                                                 */
589
590 static void
591 run_test_bulk_out(UsbTest* test)
592 {
593     unsigned char*  buf     = test->buffer;
594     int             i;
595
596     VERBOSE(1, "Starting test %d, bulk OUT on endpoint %d\n", test->id, test->test_params.bulk.endpoint);
597     
598     for (i = 0; i < test->test_params.bulk.number_packets; i++) {
599         int transferred;
600         int packet_size = test->test_params.bulk.tx_size;
601
602         test->recovery.endpoint     = test->test_params.bulk.endpoint;
603         test->recovery.protocol     = USB_ENDPOINT_XFER_BULK;
604         test->recovery.size         = packet_size;
605         
606         usbtest_fill_buffer(&(test->test_params.bulk.data), buf, packet_size);
607         if (verbose < 3) {
608             VERBOSE(2, "Bulk OUT test %d: iteration %d, packet size %d\n", test->id, i, packet_size);
609         } else {
610             // Output the first 32 bytes of data as well.
611             char msg[256];
612             int  index;
613             int  j;
614             index = snprintf(msg, 255, "Bulk OUT test %d: iteration %d, packet size %d\n    Data %s:",
615                              test->id, i, packet_size,
616                              (usbtestdata_none == test->test_params.bulk.data.format) ? "(uninitialized)" : "");
617
618             for (j = 0; ((j + 3) < packet_size) && (j < 32); j+= 4) {
619                 index += snprintf(msg+index, 255-index, " %02x%02x%02x%02x",
620                                   buf[j], buf[j+1], buf[j+2], buf[j+3]);
621             }
622             if (j < 32) {
623                 index += snprintf(msg+index, 255-index, " ");
624                 for ( ; j < packet_size; j++) {
625                     index += snprintf(msg+index, 255-index, "%02x", buf[j]);
626                 }
627                 
628             }
629             VERBOSE(3, "%s\n", msg);
630         }
631
632         transferred = usb_bulk_message(test->fd, test->test_params.bulk.endpoint, buf, packet_size);
633         
634         // Has this test run been aborted for some reason?
635         if (current_tests_terminated) {
636             VERBOSE(2, "Bulk OUT test %d: iteration %d, termination detected\n", test->id, i);
637             test->result_pass = 0;
638             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
639                      "Host, bulk OUT transfer on endpoint %d: aborted after %d iterations\n",
640                      test->test_params.bulk.endpoint & USB_ENDPOINT_NUMBER_MASK, i);
641             return;
642         }
643
644         // If an error occurred, abort this run.
645         if (-1 == transferred) {
646             char    errno_buf[USBTEST_MAX_MESSAGE];
647             test->result_pass  = 0;
648             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
649                      "Host, bulk OUT transfer on endpoint %d : host ioctl() system call failed\n    errno %d (%s)",
650                      test->test_params.bulk.endpoint & USB_ENDPOINT_NUMBER_MASK, errno,
651                      strerror_r(errno, errno_buf, USBTEST_MAX_MESSAGE));
652             VERBOSE(2, "Bulk OUT test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
653             break;
654         }
655
656         if (0 != test->test_params.bulk.tx_delay) {
657             struct timespec delay;
658             
659             VERBOSE(2, "Bulk OUT test %d: iteration %d, sleeping for %d nanoseconds\n", test->id, \
660                     i, test->test_params.bulk.tx_delay);
661             // Note that nanosleep() can return early due to incoming signals,
662             // with the unelapsed time returned in a second argument. This
663             // allows for a retry loop. In practice this does not seem
664             // worthwhile, the delays are approximate anyway.
665             delay.tv_sec  = test->test_params.bulk.tx_delay / 1000000000;
666             delay.tv_nsec = test->test_params.bulk.tx_delay % 1000000000;
667             nanosleep(&delay, NULL);
668         }
669
670         // Now move on to the next transfer
671         USBTEST_BULK_NEXT(test->test_params.bulk);
672     }
673
674     // If all the packets have been transferred this test has passed.
675     if (i >= test->test_params.bulk.number_packets) {
676         test->result_pass   = 1;
677     }
678     
679     VERBOSE(1, "Test %d bulk OUT on endpoint %d, result %d\n", test->id, test->test_params.bulk.endpoint, test->result_pass);
680 }
681
682 /*}}}*/
683 /*{{{  bulk IN                                                  */
684
685 static void
686 run_test_bulk_in(UsbTest* test)
687 {
688     unsigned char*  buf     = test->buffer;
689     int             i;
690
691     VERBOSE(1, "Starting test %d bulk IN on endpoint %d\n", test->id, test->test_params.bulk.endpoint);
692     
693     for (i = 0; i < test->test_params.bulk.number_packets; i++) {
694         int transferred;
695         int tx_size             = test->test_params.bulk.tx_size;
696         int rx_size             = test->test_params.bulk.rx_size;
697         int size_plus_padding;
698         
699         VERBOSE(2, "Bulk IN test %d: iteration %d, rx size %d, tx size %d\n", test->id, i, rx_size, tx_size);
700         
701         if (rx_size < tx_size) {
702             rx_size = tx_size;
703             VERBOSE(2, "Bulk IN test %d: iteration %d, packet size reset to %d to match tx size\n",
704                     test->id, i, rx_size);
705         }
706         test->recovery.endpoint     = test->test_params.bulk.endpoint;
707         test->recovery.protocol     = USB_ENDPOINT_XFER_BULK;
708         test->recovery.size         = rx_size;
709
710         // Make sure there is no old data lying around
711         if (usbtestdata_none != test->test_params.bulk.data.format) {
712             memset(buf, 0, rx_size);
713         }
714
715         // And do the actual transfer.
716         size_plus_padding = rx_size;
717         if (size_plus_padding < (tx_size + test->test_params.bulk.rx_padding)) {
718             size_plus_padding += test->test_params.bulk.rx_padding;
719         }
720         do {
721             transferred = usb_bulk_message(test->fd, test->test_params.bulk.endpoint, buf, size_plus_padding);
722         } while (0 == transferred);
723         
724         // Has this test run been aborted for some reason?
725         if (current_tests_terminated) {
726             VERBOSE(2, "Bulk IN test %d: iteration %d, termination detected\n", test->id, i);
727             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
728                      "Host, bulk IN transfer on endpoint %d: aborted after %d iterations\n",
729                      test->test_params.bulk.endpoint & USB_ENDPOINT_NUMBER_MASK, i);
730             return;
731         }
732
733         // If an error occurred, abort this run.
734         if (-1 == transferred) {
735             char    errno_buf[USBTEST_MAX_MESSAGE];
736             test->result_pass  = 0;
737             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
738                      "Host, bulk IN transfer on endpoint %d : host ioctl() system call failed\n    errno %d (%s)",
739                      test->test_params.bulk.endpoint & USB_ENDPOINT_NUMBER_MASK, errno,
740                      strerror_r(errno, errno_buf, USBTEST_MAX_MESSAGE));
741             VERBOSE(2, "Bulk IN test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
742             break;
743         }
744
745         // Did the target send the expected amount of data?
746         if (transferred < tx_size) {
747             test->result_pass   = 0;
748             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
749                      "Host, bulk IN transfer on endpoint %d : the target only sent %d bytes when %d were expected",
750                      test->test_params.bulk.endpoint & USB_ENDPOINT_NUMBER_MASK, transferred, tx_size);
751             VERBOSE(2, "Bulk IN test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
752             break;
753         }
754         
755         if (verbose >= 3) {
756             // Output the first 32 bytes of data
757             char msg[256];
758             int  index;
759             int  j;
760             index = snprintf(msg, 255, "Bulk IN test %d: iteration %d, transferred %d\n    Data %s:",
761                              test->id, i, transferred,
762                              (usbtestdata_none == test->test_params.bulk.data.format) ? "(uninitialized)" : "");
763
764             for (j = 0; ((j + 3) < transferred) && (j < 32); j+= 4) {
765                 index += snprintf(msg+index, 255-index, " %02x%02x%02x%02x",
766                                   buf[j], buf[j+1], buf[j+2], buf[j+3]);
767             }
768             if (j < 32) {
769                 index += snprintf(msg+index, 255-index, " ");
770                 for ( ; j < transferred; j++) {
771                     index += snprintf(msg+index, 255-index, "%02x", buf[j]);
772                 }
773                 
774             }
775             VERBOSE(3, "%s\n", msg);
776         }
777         
778         // Is the data correct?
779         if (!usbtest_check_buffer(&(test->test_params.bulk.data), buf, tx_size)) {
780             test->result_pass   = 0;
781             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
782                      "Host, bulk IN transfer on endpoint %d : mismatch between received and expected data",
783                      test->test_params.bulk.endpoint & USB_ENDPOINT_NUMBER_MASK);
784             VERBOSE(2, "Bulk IN test %d: iteration %d, error:\n    %s\n", test->id, i, test->result_message);
785             break;
786         }
787         
788         if (0 != test->test_params.bulk.rx_delay) {
789             struct timespec delay;
790             
791             VERBOSE(2, "Bulk IN test %d: iteration %d, sleeping for %d nanoseconds\n", test->id, \
792                     i, test->test_params.bulk.tx_delay);
793             // Note that nanosleep() can return early due to incoming signals,
794             // with the unelapsed time returned in a second argument. This
795             // allows for a retry loop. In practice this does not seem
796             // worthwhile, the delays are approximate anyway.
797             delay.tv_sec  = test->test_params.bulk.rx_delay / 1000000000;
798             delay.tv_nsec = test->test_params.bulk.rx_delay % 1000000000;
799             nanosleep(&delay, NULL);
800         }
801         
802         USBTEST_BULK_NEXT(test->test_params.bulk);
803     }
804
805     
806     // If all the packets have been transferred this test has passed.
807     if (i >= test->test_params.bulk.number_packets) {
808         test->result_pass   = 1;
809     }
810
811     VERBOSE(1, "Test %d bulk IN on endpoint %d, result %d\n", test->id, test->test_params.bulk.endpoint, test->result_pass);
812 }
813
814 /*}}}*/
815 /*{{{  control IN                                               */
816
817 // Receive appropriate packets via the control endpoint. This is somewhat
818 // different from bulk transfers. It is implemented using reserved control
819 // messages.
820 //
821 // Note: it is not entirely clear that this test is safe. There will be
822 // concurrent control traffic to detect test termination and the like,
823 // and these control messages may interfere with each other. It is not
824 // entirely clear how the Linux kernel handles concurrent control
825 // operations.
826
827 static void
828 run_test_control_in(UsbTest* test)
829 {
830     unsigned char*  buf     = test->buffer;
831     int             packet_size;
832     int             i;
833
834     packet_size = test->test_params.control_in.packet_size_initial;
835     for (i = 0; i < test->test_params.control_in.number_packets; i++) {
836         int transferred;
837         
838         test->recovery.endpoint     = 0;
839         test->recovery.protocol     = USB_ENDPOINT_XFER_CONTROL;
840         test->recovery.size         = packet_size;
841
842         // Make sure there is no old data lying around
843         if (usbtestdata_none != test->test_params.control_in.data.format) {
844             memset(buf, 0, packet_size);
845         }
846
847         // And do the actual transfer.
848         transferred = usb_control_message(test->fd, USB_TYPE_RESERVED | USB_RECIP_DEVICE | USB_DIR_IN, USBTEST_RESERVED_CONTROL_IN,
849                                           0, 0, packet_size, buf);
850
851         // Has this test run been aborted for some reason?
852         if (current_tests_terminated) {
853             return;
854         }
855
856         // If an error occurred, abort this run.
857         if (-1 == transferred) {
858             char    errno_buf[USBTEST_MAX_MESSAGE];
859             test->result_pass  = 0;
860             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
861                      "Host, control IN transfer: host ioctl() system call failed\n    errno %d (%s)",
862                      errno, strerror_r(errno, errno_buf, USBTEST_MAX_MESSAGE));
863             break;
864         }
865
866         // Did the target send the expected amount of data?
867         if (transferred < packet_size) {
868             test->result_pass   = 0;
869             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
870                      "Host, control IN transfer: the target only sent %d bytes when %d were expected",
871                      transferred, packet_size);
872             break;
873         }
874         
875         // Is the data correct?
876         if (!usbtest_check_buffer(&(test->test_params.control_in.data), buf, packet_size)) {
877             test->result_pass   = 0;
878             snprintf(test->result_message, USBTEST_MAX_MESSAGE,
879                      "Host, control IN transfer: mismatch between received and expected data");
880             break;
881         }
882         
883         USBTEST_CONTROL_NEXT_PACKET_SIZE(packet_size, test->test_params.control_in);
884     }
885
886     // If all the packets have been transferred this test has passed.
887     if (i >= test->test_params.control_in.number_packets) {
888         test->result_pass   = 1;
889     }
890 }
891
892 /*}}}*/
893
894 // FIXME: add more tests
895
896 /*{{{  run_test()                                               */
897
898 // This utility is invoked from a thread in the thread pool whenever there is
899 // work to be done. It simply dispatches to the appropriate handler.
900 static void
901 run_test(UsbTest* test)
902 {
903     switch (test->which_test) {
904       case usbtest_bulk_out:    run_test_bulk_out(test); break;
905       case usbtest_bulk_in:     run_test_bulk_in(test); break;
906       case usbtest_control_in:  run_test_control_in(test); break;
907       default:
908         fprintf(stderr, "usbhost: internal error, attempt to execute an unknown test.\n");
909         exit(EXIT_FAILURE);
910     }
911 }
912
913 /*}}}*/
914
915 /*}}}*/
916 /*{{{  The thread pool                                          */
917
918 // ----------------------------------------------------------------------------
919 // A pool of threads and buffers which do the real work. The number of possible
920 // concurrent tests is defined in protocol.h. Each one requires a separate
921 // thread, transfer buffer, semaphore, and some state information.
922 //
923 // Although the application is multi-threaded, in practice there is little
924 // need for synchronization. Tests will only be started while the pool threads
925 // are idle. When the pool threads are running the main thread will be waiting
926 // for them all to finish, with a bit of polling to detect error conditions.
927 // The pool threads do not share any data, apart from the file descriptor for
928 // the USB device.
929
930 typedef struct PoolEntry {
931     pthread_t       thread;
932     sem_t           wakeup;
933     int             running;
934     UsbTest         test;
935 } PoolEntry;
936
937 static PoolEntry pool[USBTEST_MAX_CONCURRENT_TESTS];
938
939 // This is the entry point for every thread in the pool. It just loops forever,
940 // waiting until it is supposed to run a test. These threads never actually
941 // exit, instead there should be a call to exit() somewhere.
942 static void*
943 pool_function(void* arg)
944 {
945     PoolEntry*  pool_entry  = (PoolEntry*) arg;
946     for ( ; ; ) {
947         sem_wait(&(pool_entry->wakeup));
948         run_test(&(pool_entry->test));
949         pool_entry->running = 0;
950     }
951
952     return NULL;
953 }
954
955 // Initialize all threads in the pool.
956 static void
957 pool_initialize(void)
958 {
959     int i;
960     for (i = 0; i < USBTEST_MAX_CONCURRENT_TESTS; i++) {
961         pool[i].running = 0;
962         pool[i].test.fd = dup(usb_master_fd);
963         if (0 != sem_init(&(pool[i].wakeup), 0, 0)) {
964             fprintf(stderr, "usbhost: internal error, failed to initialize all semaphores.\n");
965             exit(EXIT_FAILURE);
966         }
967         if (0 != pthread_create(&(pool[i].thread), NULL, &pool_function, (void*) &(pool[i]))) {
968             fprintf(stderr, "usbhost: internal error, failed to start all threads.\n");
969             exit(EXIT_FAILURE);
970         }
971     }
972 }
973
974 // Allocate a single entry in the thread pool.
975 static UsbTest*
976 pool_allocate(void)
977 {
978     UsbTest* result = (UsbTest*) 0;
979
980     if (local_thread_count == USBTEST_MAX_CONCURRENT_TESTS) {
981         fprintf(stderr, "usbhost: internal error, thread resource exhausted.\n");
982         exit(EXIT_FAILURE);
983     }
984
985     result = &(pool[local_thread_count].test);
986     local_thread_count++;
987     reset_usbtest(result);
988     return result;
989 }
990
991 // Start all the threads that are supposed to be running tests.
992 static void
993 pool_start(void)
994 {
995     int i;
996     for (i = 0; i < local_thread_count; i++) {
997         pool[i].running = 1;
998         sem_post(&(pool[i].wakeup));
999     }
1000 }
1001
1002 /*}}}*/
1003 /*{{{  Tcl routines                                             */
1004
1005 // ----------------------------------------------------------------------------
1006 // Tcl routines to provide access to the USB device from inside Tcl
1007 // scripts, plus some general utilities. These routines deal mostly
1008 // with preparing a test run. The actual work is done in C: the
1009 // ioctl() operations are not readily accessible from Tcl, and
1010 // operations like filling in buffers and calculating checksums are
1011 // cpu-intensive.
1012
1013 /*{{{  pass/fail/abort                                          */
1014
1015 // ----------------------------------------------------------------------------
1016 // Some simple routines accessible from Tcl to get the target to report pass/fail or
1017 // to make the target abort.
1018
1019 static int
1020 tcl_target_pass(ClientData     clientData  __attribute__ ((unused)),
1021                 Tcl_Interp*    interp,
1022                 int            argc,
1023                 char**         argv)
1024 {
1025     if (2 != argc) {
1026         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_pass <message>\"", TCL_STATIC);
1027         return TCL_ERROR;
1028     }
1029     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_PASS, 0, 0, strlen(argv[1]) + 1, argv[1]);
1030     usb_sync(usb_master_fd, -1);
1031     return TCL_OK;
1032 }
1033
1034 static int
1035 tcl_target_fail(ClientData     clientData  __attribute__ ((unused)),
1036                 Tcl_Interp*    interp,
1037                 int            argc,
1038                 char**         argv)
1039 {
1040     if (2 != argc) {
1041         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_fail <message>\"", TCL_STATIC);
1042         return TCL_ERROR;
1043     }
1044     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_FAIL, 0, 0, strlen(argv[1]) + 1, argv[1]);
1045     usb_sync(usb_master_fd, -1);
1046     return TCL_OK;
1047 }
1048
1049 // The next three routines cause the target to exit, so a usb_sync() is inappropriate.
1050 static int
1051 tcl_target_pass_exit(ClientData     clientData  __attribute__ ((unused)),
1052                      Tcl_Interp*    interp,
1053                      int            argc,
1054                      char**         argv)
1055 {
1056     if (2 != argc) {
1057         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_pass_exit <message>\"", TCL_STATIC);
1058         return TCL_ERROR;
1059     }
1060     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_PASS_EXIT, 0, 0,
1061                                  strlen(argv[1]) + 1, argv[1]);
1062     return TCL_OK;
1063 }
1064
1065
1066 static int
1067 tcl_target_fail_exit(ClientData     clientData  __attribute__ ((unused)),
1068                      Tcl_Interp*    interp,
1069                      int            argc,
1070                      char**         argv)
1071 {
1072     if (2 != argc) {
1073         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_fail_exit <message>\"", TCL_STATIC);
1074         return TCL_ERROR;
1075     }
1076     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_FAIL_EXIT, 0, 0,
1077                                  strlen(argv[1]) + 1, argv[1]);
1078     return TCL_OK;
1079 }
1080
1081 static int
1082 tcl_target_abort(ClientData     clientData  __attribute__ ((unused)),
1083                  Tcl_Interp*    interp,
1084                  int            argc,
1085                  char**         argv        __attribute__ ((unused)) )
1086 {
1087     if (1 != argc) {
1088         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_abort\"", TCL_STATIC);
1089         return TCL_ERROR;
1090     }
1091     usb_abort(usb_master_fd);
1092     return TCL_OK;
1093 }
1094
1095 /*}}}*/
1096 /*{{{  start bulk test                                          */
1097
1098 // ----------------------------------------------------------------------------
1099 // Start a bulk test. The real Tcl interface to this functionality is
1100 // implemented in Tcl: it takes care of figuring out sensible default
1101 // arguments, validating the data, etc. All that this code does is
1102 // allocate a thread and fill in the appropriate data, plus request
1103 // the target-side to do the same thing.
1104
1105 static int
1106 tcl_test_bulk(ClientData     clientData  __attribute__ ((unused)),
1107               Tcl_Interp*    interp,
1108               int            argc,
1109               char**         argv)
1110 {
1111     int             i;
1112     int             tmp;
1113     UsbTest*        test;
1114     unsigned char   request[USBTEST_MAX_CONTROL_DATA];
1115     int             request_index;
1116
1117     // The data consists of 28 numbers for UsbTest_Bulk itself, and
1118     // another 10 numbers for the test data definition.
1119     if (39 != argc) {
1120         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::_test_bulk <message>\"", TCL_STATIC);
1121         return TCL_ERROR;
1122     }
1123     for (i = 1; i < 39; i++) {
1124         int discard;
1125         if (TCL_OK != Tcl_GetInt(interp, argv[i], &discard)) {
1126             Tcl_SetResult(interp, "invalid argument: all arguments should be numbers", TCL_STATIC);
1127             return TCL_ERROR;
1128         }
1129     }
1130
1131     test = pool_allocate();
1132     Tcl_GetInt(interp, argv[1], &(test->test_params.bulk.number_packets));
1133     Tcl_GetInt(interp, argv[2], &(test->test_params.bulk.endpoint));
1134     test->which_test = (USB_DIR_IN == (test->test_params.bulk.endpoint & USB_ENDPOINT_DIR_MASK))
1135         ? usbtest_bulk_in : usbtest_bulk_out;
1136     Tcl_GetInt(interp, argv[ 3], &(test->test_params.bulk.tx_size));
1137     Tcl_GetInt(interp, argv[ 4], &(test->test_params.bulk.tx_size_min));
1138     Tcl_GetInt(interp, argv[ 5], &(test->test_params.bulk.tx_size_max));
1139     Tcl_GetInt(interp, argv[ 6], &(test->test_params.bulk.tx_size_multiplier));
1140     Tcl_GetInt(interp, argv[ 7], &(test->test_params.bulk.tx_size_divisor));
1141     Tcl_GetInt(interp, argv[ 8], &(test->test_params.bulk.tx_size_increment));
1142     Tcl_GetInt(interp, argv[ 9], &(test->test_params.bulk.rx_size));
1143     Tcl_GetInt(interp, argv[10], &(test->test_params.bulk.rx_size_min));
1144     Tcl_GetInt(interp, argv[11], &(test->test_params.bulk.rx_size_max));
1145     Tcl_GetInt(interp, argv[12], &(test->test_params.bulk.rx_size_multiplier));
1146     Tcl_GetInt(interp, argv[13], &(test->test_params.bulk.rx_size_divisor));
1147     Tcl_GetInt(interp, argv[14], &(test->test_params.bulk.rx_size_increment));
1148     Tcl_GetInt(interp, argv[15], &(test->test_params.bulk.rx_padding));
1149     Tcl_GetInt(interp, argv[16], &(test->test_params.bulk.tx_delay));
1150     Tcl_GetInt(interp, argv[17], &(test->test_params.bulk.tx_delay_min));
1151     Tcl_GetInt(interp, argv[18], &(test->test_params.bulk.tx_delay_max));
1152     Tcl_GetInt(interp, argv[19], &(test->test_params.bulk.tx_delay_multiplier));
1153     Tcl_GetInt(interp, argv[20], &(test->test_params.bulk.tx_delay_divisor));
1154     Tcl_GetInt(interp, argv[21], &(test->test_params.bulk.tx_delay_increment));
1155     Tcl_GetInt(interp, argv[22], &(test->test_params.bulk.rx_delay));
1156     Tcl_GetInt(interp, argv[23], &(test->test_params.bulk.rx_delay_min));
1157     Tcl_GetInt(interp, argv[24], &(test->test_params.bulk.rx_delay_max));
1158     Tcl_GetInt(interp, argv[25], &(test->test_params.bulk.rx_delay_multiplier));
1159     Tcl_GetInt(interp, argv[26], &(test->test_params.bulk.rx_delay_divisor));
1160     Tcl_GetInt(interp, argv[27], &(test->test_params.bulk.rx_delay_increment));
1161     Tcl_GetInt(interp, argv[28], &tmp);
1162     test->test_params.bulk.io_mechanism = (usb_io_mechanism) tmp;
1163     Tcl_GetInt(interp, argv[29], &tmp);
1164     test->test_params.bulk.data.format = (usbtestdata) tmp;
1165     Tcl_GetInt(interp, argv[30], &(test->test_params.bulk.data.seed));
1166     Tcl_GetInt(interp, argv[31], &(test->test_params.bulk.data.multiplier));
1167     Tcl_GetInt(interp, argv[32], &(test->test_params.bulk.data.increment));
1168     Tcl_GetInt(interp, argv[33], &(test->test_params.bulk.data.transfer_seed_multiplier));
1169     Tcl_GetInt(interp, argv[34], &(test->test_params.bulk.data.transfer_seed_increment));
1170     Tcl_GetInt(interp, argv[35], &(test->test_params.bulk.data.transfer_multiplier_multiplier));
1171     Tcl_GetInt(interp, argv[36], &(test->test_params.bulk.data.transfer_multiplier_increment));
1172     Tcl_GetInt(interp, argv[37], &(test->test_params.bulk.data.transfer_increment_multiplier));
1173     Tcl_GetInt(interp, argv[38], &(test->test_params.bulk.data.transfer_increment_increment));
1174
1175     VERBOSE(3, "Preparing USB bulk test on endpoint %d, direction %s, for %d packets\n", \
1176             test->test_params.bulk.endpoint, \
1177             (usbtest_bulk_in == test->which_test) ? "IN" : "OUT", \
1178             test->test_params.bulk.number_packets);
1179     VERBOSE(3, "  I/O mechanism is %s\n", \
1180             (usb_io_mechanism_usb == test->test_params.bulk.io_mechanism) ? "low-level USB" : \
1181             (usb_io_mechanism_dev == test->test_params.bulk.io_mechanism) ? "devtab" : "<invalid>");
1182     VERBOSE(3, "  Data format %s, data1 %d, data* %d, data+ %d, data1* %d, data1+ %d, data** %d, data*+ %d, data+* %d, data++ %d\n",\
1183             (usbtestdata_none     == test->test_params.bulk.data.format) ? "none" :     \
1184             (usbtestdata_bytefill == test->test_params.bulk.data.format) ? "bytefill" : \
1185             (usbtestdata_wordfill == test->test_params.bulk.data.format) ? "wordfill" : \
1186             (usbtestdata_byteseq  == test->test_params.bulk.data.format) ? "byteseq"  : \
1187             (usbtestdata_wordseq  == test->test_params.bulk.data.format) ? "wordseq"  : "<invalid>", \
1188             test->test_params.bulk.data.seed,                            \
1189             test->test_params.bulk.data.multiplier,                      \
1190             test->test_params.bulk.data.increment,                       \
1191             test->test_params.bulk.data.transfer_seed_multiplier,        \
1192             test->test_params.bulk.data.transfer_seed_increment,         \
1193             test->test_params.bulk.data.transfer_multiplier_multiplier,  \
1194             test->test_params.bulk.data.transfer_multiplier_increment,   \
1195             test->test_params.bulk.data.transfer_increment_multiplier,   \
1196             test->test_params.bulk.data.transfer_increment_increment);
1197     VERBOSE(3, "  txsize1 %d, txsize>= %d, txsize<= %d, txsize* %d, txsize/ %d, txsize+ %d\n", \
1198             test->test_params.bulk.tx_size,         test->test_params.bulk.tx_size_min,        \
1199             test->test_params.bulk.tx_size_max,     test->test_params.bulk.tx_size_multiplier, \
1200             test->test_params.bulk.tx_size_divisor, test->test_params.bulk.tx_size_increment);
1201     VERBOSE(3, "  rxsize1 %d, rxsize>= %d, rxsize<= %d, rxsize* %d, rxsize/ %d, rxsize+ %d\n", \
1202             test->test_params.bulk.rx_size,         test->test_params.bulk.rx_size_min,        \
1203             test->test_params.bulk.rx_size_max,     test->test_params.bulk.rx_size_multiplier, \
1204             test->test_params.bulk.rx_size_divisor, test->test_params.bulk.rx_size_increment);
1205     VERBOSE(3, "  txdelay1 %d, txdelay>= %d, txdelay<= %d, txdelay* %d, txdelay/ %d, txdelay+ %d\n", \
1206             test->test_params.bulk.tx_delay,         test->test_params.bulk.tx_delay_min,            \
1207             test->test_params.bulk.tx_delay_max,     test->test_params.bulk.tx_delay_multiplier,     \
1208             test->test_params.bulk.tx_delay_divisor, test->test_params.bulk.tx_delay_increment);
1209     VERBOSE(3, "  rxdelay1 %d, rxdelay>= %d, rxdelay<= %d, rxdelay* %d, rxdelay/ %d, rxdelay+ %d\n", \
1210             test->test_params.bulk.rx_delay,         test->test_params.bulk.rx_delay_min,            \
1211             test->test_params.bulk.rx_delay_max,     test->test_params.bulk.rx_delay_multiplier,     \
1212             test->test_params.bulk.rx_delay_divisor, test->test_params.bulk.rx_delay_increment);
1213             
1214     
1215     // That is all the data converted from Tcl to C, and a local thread is set up to handle this
1216     // request. Also set up a thread on the target.
1217     request_index = 0;
1218     pack_usbtest_bulk(&(test->test_params.bulk), request, &request_index);
1219     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_TEST_BULK, 0, 0, request_index, request);
1220     remote_thread_count++;
1221     
1222     return TCL_OK;
1223 }
1224
1225 /*}}}*/
1226 /*{{{  start control-in test                                    */
1227
1228 // ----------------------------------------------------------------------------
1229 // Start a control-in test. The real Tcl interface to this
1230 // functionality is implemented in Tcl: it takes care of figuring out
1231 // sensible default arguments, validating the data, etc. All that this
1232 // code does is allocate a thread and fill in the appropriate data,
1233 // plus request the target-side to do the same thing.
1234
1235 static int
1236 tcl_test_control_in(ClientData     clientData  __attribute__ ((unused)),
1237                     Tcl_Interp*    interp,
1238                     int            argc,
1239                     char**         argv)
1240 {
1241     int             i;
1242     int             tmp;
1243     UsbTest*        test;
1244     unsigned char   request[USBTEST_MAX_CONTROL_DATA];
1245     int             request_index;
1246         
1247     // The data consists of 6 numbers for UsbTest_ControlIn itself, and
1248     // another 10 numbers for the test data definition.
1249     if (17 != argc) {
1250         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::_test_control_in <message>\"", TCL_STATIC);
1251         return TCL_ERROR;
1252     }
1253     for (i = 1; i < 17; i++) {
1254         int discard;
1255         if (TCL_OK != Tcl_GetInt(interp, argv[i], &discard)) {
1256             Tcl_SetResult(interp, "invalid argument: all arguments should be numbers", TCL_STATIC);
1257             return TCL_ERROR;
1258         }
1259     }
1260
1261     test                = pool_allocate();
1262     test->which_test    = usbtest_control_in;
1263     Tcl_GetInt(interp, argv[1], &(test->test_params.control_in.number_packets));
1264     Tcl_GetInt(interp, argv[2], &(test->test_params.control_in.packet_size_initial));
1265     Tcl_GetInt(interp, argv[3], &(test->test_params.control_in.packet_size_min));
1266     Tcl_GetInt(interp, argv[4], &(test->test_params.control_in.packet_size_max));
1267     Tcl_GetInt(interp, argv[5], &(test->test_params.control_in.packet_size_multiplier));
1268     Tcl_GetInt(interp, argv[6], &(test->test_params.control_in.packet_size_increment));
1269     Tcl_GetInt(interp, argv[7], &tmp);
1270     test->test_params.bulk.data.format = (usbtestdata) tmp;
1271     Tcl_GetInt(interp, argv[ 8], &(test->test_params.control_in.data.seed));
1272     Tcl_GetInt(interp, argv[ 9], &(test->test_params.control_in.data.multiplier));
1273     Tcl_GetInt(interp, argv[10], &(test->test_params.control_in.data.increment));
1274     Tcl_GetInt(interp, argv[11], &(test->test_params.control_in.data.transfer_seed_multiplier));
1275     Tcl_GetInt(interp, argv[12], &(test->test_params.control_in.data.transfer_seed_increment));
1276     Tcl_GetInt(interp, argv[13], &(test->test_params.control_in.data.transfer_multiplier_multiplier));
1277     Tcl_GetInt(interp, argv[14], &(test->test_params.control_in.data.transfer_multiplier_increment));
1278     Tcl_GetInt(interp, argv[15], &(test->test_params.control_in.data.transfer_increment_multiplier));
1279     Tcl_GetInt(interp, argv[16], &(test->test_params.control_in.data.transfer_increment_increment));
1280
1281     // That is all the data converted from Tcl to C, and a local thread is set up to handle this
1282     // request. Also set up a thread on the target.
1283     request_index = 0;
1284     pack_usbtest_control_in(&(test->test_params.control_in), request, &request_index);
1285     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_TEST_CONTROL_IN, 0, 0,
1286                                  request_index, request);
1287     remote_thread_count++;
1288     
1289     return TCL_OK;
1290 }
1291
1292 /*}}}*/
1293 /*{{{  Cancel the current batch of tests                        */
1294
1295 static int
1296 tcl_cancel(ClientData     clientData    __attribute__ ((unused)),
1297            Tcl_Interp*    interp,
1298            int            argc,
1299            char**         argv          __attribute__ ((unused)) )
1300 {
1301     if (1 != argc) {
1302         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::cancel\"", TCL_STATIC);
1303         return TCL_ERROR;
1304     }
1305
1306     // Send the request on to the target.
1307     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_CANCEL, 0, 0, 0, (void*)0);
1308
1309     // Now cancel all the local tests. This can be done by resetting the counter
1310     // of allocated threads: no actual work will have been started yet.
1311     local_thread_count = 0;
1312
1313     // And synchronise with the target
1314     if (!usb_sync(usb_master_fd, 30)) {
1315         fprintf(stderr, "usbhost: error, target has failed to process test cancel request.\n");
1316         exit(EXIT_FAILURE);
1317         
1318     }
1319     remote_thread_count     = 0;
1320     
1321     return TCL_OK;
1322 }
1323
1324 /*}}}*/
1325 /*{{{  Run a batch of tests                                     */
1326
1327 // ----------------------------------------------------------------------------
1328 // This code does an awful lot of the hard work. Start with various utilities.
1329
1330 // Has the current batch finished as far as the local threads are concerned?
1331 static int
1332 local_batch_finished(void)
1333 {
1334     int result = 1;
1335     int i;
1336
1337     for (i = 0; i < local_thread_count; i++) {
1338         if (pool[i].running) {
1339             result = 0;
1340             break;
1341         }
1342     }
1343     return result;
1344 }
1345
1346 // Has the current batch finished as far as remote threads are concerned?
1347 static int
1348 remote_batch_finished(void)
1349 {
1350     char buf[1];
1351     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN, USBTEST_FINISHED,
1352                                  0, 0, 1, (void*) buf);
1353     return buf[0];
1354 }
1355
1356 // Perform recovery for a thread on the target. This involves asking the
1357 // target for recovery information, then performing an appropriate
1358 // action. If no data is returned then no recovery is needed for this thread.
1359 static void
1360 recover_remote(int index)
1361 {
1362     unsigned char       buffer[USBTEST_MAX_CONTROL_DATA];
1363     int                 buffer_index;
1364     UsbTest_Recovery    recovery;
1365     int                 i;
1366
1367     if (0 != usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN,
1368                                           USBTEST_GET_RECOVERY, 0, index, 12, buffer)) {
1369         // There is work to be done
1370         buffer_index = 0;
1371         unpack_usbtest_recovery(&recovery, buffer, &buffer_index);
1372
1373         // We have an endpoint, a protocol, and a size.
1374         if (0 == recovery.endpoint) {
1375             // The target just needs a dummy reserved control message
1376             usb_reliable_control_message(usb_master_fd, USB_TYPE_RESERVED | USB_RECIP_DEVICE, USBTEST_RESERVED_CONTROL_IN,
1377                                          0, 0, 0, (void*) 0);
1378         } else if (USB_ENDPOINT_XFER_BULK == recovery.protocol) {
1379             // Either we need to send some data to the target, or we need to accept some data.
1380             static unsigned char recovery_buffer[USBTEST_MAX_BULK_DATA + USBTEST_MAX_BULK_DATA_EXTRA];
1381             
1382             struct  usbdevfs_bulktransfer    transfer;
1383             transfer.ep         = recovery.endpoint;
1384             transfer.timeout    = 2000; // Two seconds.  Should be plenty, even for a large bulk transfer.
1385             transfer.data       = recovery_buffer;
1386             if (USB_DIR_IN == (recovery.endpoint & USB_ENDPOINT_DIR_MASK)) {
1387                 transfer.len = recovery.size;
1388             } else {
1389                 transfer.len = 1;
1390             }
1391             errno = 0;
1392             i = ioctl(usb_master_fd, USBDEVFS_BULK, &transfer);
1393         }
1394
1395         // There is no recovery support yet for other protocols.
1396     }
1397 }
1398
1399 // Perform recovery for a local thread. This involves extracting the
1400 // recovery information from the local thread and asking the target
1401 // to take appropriate action.
1402 static void
1403 recover_local(int index)
1404 {
1405     unsigned char   buffer[USBTEST_MAX_CONTROL_DATA];
1406     int             buffer_index;
1407
1408     if (pool[index].running) {
1409         buffer_index = 0;
1410         pack_usbtest_recovery(&(pool[index].test.recovery), buffer, &buffer_index);
1411         usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_PERFORM_RECOVERY,
1412                                      0, 0, buffer_index, (void*) buffer);
1413     }
1414 }
1415
1416 // All done, time for a clean-up on both target and host. The latter
1417 // is achieved simply by resetting the thread pool, which actually
1418 // just means resetting the counter since all the threads are blocked
1419 // waiting for the next batch.
1420 static void
1421 run_done(void)
1422 {
1423     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_BATCH_DONE, 0, 0, 0, (void*) NULL);
1424     local_thread_count = 0;
1425     remote_thread_count = 0;
1426 }
1427
1428 // The main routine, as invoked from Tcl. This takes a single
1429 // argument, a timeout in seconds.
1430 static int
1431 tcl_run(ClientData     clientData    __attribute__ ((unused)),
1432         Tcl_Interp*    interp,
1433         int            argc,
1434         char**         argv          __attribute__ ((unused)) )
1435 {
1436     struct timespec delay;
1437     int             timeout;
1438     time_t          start;
1439     time_t          now;
1440     int             i, j;
1441     unsigned char   result_buf[USBTEST_MAX_CONTROL_DATA];
1442     int             all_ok;
1443     
1444     if (2 != argc) {
1445         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::_run <timeout>\"", TCL_STATIC);
1446         return TCL_ERROR;
1447     }
1448     if (TCL_OK != Tcl_GetInt(interp, argv[1], &timeout)) {
1449         Tcl_SetResult(interp, "invalid argument: timeout should be numeric", TCL_STATIC);
1450         return TCL_ERROR;
1451     }
1452     
1453     VERBOSE(2, "Starting a testrun, timeout %d seconds\n", timeout);
1454     
1455     // Start the tests running on the target. The target USB hardware
1456     // will not actually do anything except in response to packets
1457     // from the host, so it is better to start the target before the
1458     // local threads.
1459     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_START, 0, 0, 0, (void*) 0);
1460
1461     // Now the local threads can get going.
1462     current_tests_terminated = 0;
1463     pool_start();
1464
1465     // Now leave the various testing threads to do their thing until
1466     // either side believes that the batch has finished, or until the
1467     // timeout expires. Note that if one side decides that the batch
1468     // has finished but the other disagrees, that in itself indicates
1469     // a test failure of sorts.
1470     //
1471     // There is a question of polling frequency. Once a second avoids
1472     // excessive polling traffic on the USB bus, and should not impose
1473     // intolerable delays for short-duration tests.
1474     start = time(NULL);
1475     do {
1476         VERBOSE(3, "The tests are running, waiting for termination\n");
1477         delay.tv_sec    = 1;
1478         delay.tv_nsec   = 0;
1479         nanosleep(&delay, NULL);
1480         now = time(NULL);
1481     } while (((start + timeout) > now) && !local_batch_finished() && !remote_batch_finished());
1482
1483     VERBOSE(2, "Termination detected, time elapsed %ld\n", (long) now - start);
1484
1485     // If either side believes that testing is not complete, things
1486     // get messy. Start by setting the terminated flag. Any tests that
1487     // are actually still running happily but have not finished within
1488     // the timeout should detect this and stop.
1489     if (!local_batch_finished() || !remote_batch_finished()) {
1490         VERBOSE(2, "Testing is not yet complete, setting TERMINATED flag\n");
1491         current_tests_terminated    = 1;
1492         usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_SET_TERMINATED, 0, 0, 0, (void*) 0);
1493         // And another delay, to give threads a chance to detect the
1494         // flag's update
1495         delay.tv_sec    = 1;
1496         delay.tv_nsec   = 0;
1497         nanosleep(&delay, NULL);
1498     }
1499
1500     // If there is still are unfinished threads, recovery action
1501     // is needed. It is not clear whether it is better to unlock
1502     // the local threads first, or the remote threads. For now the
1503     // latter approach is taken.
1504     if (!remote_batch_finished()) {
1505         int i;
1506         VERBOSE(2, "Remote threads still running, performing remote recovery\n");
1507         for (i = 0; i < remote_thread_count; i++) {
1508             recover_remote(i);
1509         }
1510         // Allow the recovery actions to take effect
1511         delay.tv_sec    = 1;
1512         delay.tv_nsec   = 0;
1513         nanosleep(&delay, NULL);
1514     }
1515
1516     if (!local_batch_finished()) {
1517         int i;
1518         VERBOSE(2, "Local threads still running, performing local recovery\n");
1519         for (i = 0; i < local_thread_count; i++) {
1520             recover_local(i);
1521         }
1522         // Allow the recovery actions to take effect
1523         delay.tv_sec    = 1;
1524         delay.tv_nsec   = 0;
1525         nanosleep(&delay, NULL);
1526     }
1527
1528     // One last check to make sure that everything is finished. If not,
1529     // testing has broken down and it is necessary to abort.
1530     if (!local_batch_finished() || !remote_batch_finished()) {
1531         VERBOSE(2, "Giving local and remote threads another chance to finish.\n");
1532         // Allow the recovery actions to take effect
1533         delay.tv_sec    = 5;
1534         delay.tv_nsec   = 0;
1535         nanosleep(&delay, NULL);
1536         if (!local_batch_finished() || !remote_batch_finished()) {
1537             // OK, normality has not been restored.
1538             // It would be nice to get hold of and display any error messages.
1539             usb_abort(usb_master_fd);
1540             fprintf(stderr, "Fatal error: the host test program and the remote target are out of synch.\n");
1541             fprintf(stderr, "             recovery has been attempted, without success.\n");
1542             fprintf(stderr, "             USB testing cannot continue.\n");
1543             exit(EXIT_FAILURE);
1544         }
1545     }
1546
1547     VERBOSE(2, "Local and remote threads are in synch, collecting results.\n");
1548     
1549     // The world is in a coherent state. Time to collect the results.
1550     // The return value of this function is a simple boolean. More
1551     // detailed results will be held in a Tcl variable as a list of
1552     // messages. It is desirable to keep both local and remote results
1553     // in order.
1554     for (i = 0; i < ((local_thread_count < remote_thread_count) ? local_thread_count : remote_thread_count); i++) {
1555         if (!pool[i].test.result_pass) {
1556             Tcl_SetVar(interp, "usbtest::results", pool[i].test.result_message,
1557                        all_ok ? (TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT) : (TCL_GLOBAL_ONLY | TCL_APPEND_VALUE | TCL_LIST_ELEMENT));
1558             all_ok = 0;
1559         }
1560         usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN, USBTEST_GET_RESULT,
1561                                      0, i, USBTEST_MAX_CONTROL_DATA, (void*) result_buf);
1562         if (!result_buf[0]) {
1563             Tcl_SetVar(interp, "usbtest::results", &(result_buf[1]),
1564                        all_ok ? TCL_GLOBAL_ONLY : (TCL_GLOBAL_ONLY | TCL_APPEND_VALUE | TCL_LIST_ELEMENT));
1565             all_ok = 0;
1566         }
1567     }
1568     for (j = i; j < local_thread_count; j++) {
1569         if (!pool[j].test.result_pass) {
1570             Tcl_SetVar(interp, "usbtest::results", pool[j].test.result_message,
1571                        all_ok ? TCL_GLOBAL_ONLY : (TCL_GLOBAL_ONLY | TCL_APPEND_VALUE | TCL_LIST_ELEMENT));
1572             all_ok = 0;
1573         }
1574     }
1575     for (j = i; j < remote_thread_count; j++) {
1576         usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN, USBTEST_GET_RESULT,
1577                                      0, i, USBTEST_MAX_CONTROL_DATA, (void*) result_buf);
1578         if (!result_buf[0]) {
1579             Tcl_SetVar(interp, "usbtest::results", &(result_buf[1]),
1580                        all_ok ? TCL_GLOBAL_ONLY : (TCL_GLOBAL_ONLY | TCL_APPEND_VALUE | TCL_LIST_ELEMENT));
1581             all_ok = 0;
1582         }
1583     }
1584     VERBOSE(2, "Overall test result %d\n", all_ok);
1585     
1586     Tcl_SetResult(interp, all_ok ? "1" : "0", TCL_STATIC);
1587     
1588     run_done();
1589     
1590     return TCL_OK;
1591 }
1592
1593 /*}}}*/
1594 /*{{{  Set verbosity                                            */
1595
1596 // ----------------------------------------------------------------------------
1597 // Allow Tcl scripts to control verbosity levels for both host and target
1598 static int
1599 tcl_host_verbose(ClientData     clientData    __attribute__ ((unused)),
1600                   Tcl_Interp*    interp,
1601                   int            argc,
1602                   char**         argv)
1603 {
1604     int level;
1605     
1606     if (2 != argc) {
1607         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::host_verbose <level>\"", TCL_STATIC);
1608         return TCL_ERROR;
1609     }
1610     if (TCL_OK != Tcl_GetInt(interp, argv[1], &level)) {
1611         Tcl_SetResult(interp, "invalid argument: verbosity level should be numeric", TCL_STATIC);
1612         return TCL_ERROR;
1613     }
1614
1615     verbose = level;
1616     return TCL_OK;
1617 }
1618
1619 static int
1620 tcl_target_verbose(ClientData     clientData    __attribute__ ((unused)),
1621                    Tcl_Interp*    interp,
1622                    int            argc,
1623                    char**         argv)
1624 {
1625     int level;
1626     
1627     if (2 != argc) {
1628         Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_verbose <level>\"", TCL_STATIC);
1629         return TCL_ERROR;
1630     }
1631     if (TCL_OK != Tcl_GetInt(interp, argv[1], &level)) {
1632         Tcl_SetResult(interp, "invalid argument: verbosity level should be numeric", TCL_STATIC);
1633         return TCL_ERROR;
1634     }
1635     
1636     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_VERBOSE, level, 0, 0, NULL);
1637     usb_sync(usb_master_fd, -1);
1638
1639     return TCL_OK;
1640 }
1641
1642 /*}}}*/
1643
1644 /*}}}*/
1645 /*{{{  AppInit()                                                */
1646
1647 // ----------------------------------------------------------------------------
1648 // Application-specific initialization. We have a bare Tcl interpreter ready
1649 // to start executing scripts that define various test cases. However some
1650 // additional functions will have to be added to the interpreter, plus
1651 // information about the various endpoints.
1652
1653 static int
1654 usbhost_appinit(Tcl_Interp* interp)
1655 {
1656     unsigned char   buf[USBTEST_MAX_CONTROL_DATA];
1657     int             number_of_endpoints;
1658     int             i;
1659     char*           location;
1660     
1661     // Start by creating a usbtest namespace, for use by the various functions
1662     // and variables.
1663     if (TCL_OK != Tcl_Eval(interp,
1664                            "namespace eval usbtest {\n"
1665                            "    variable number_of_endpoints 0\n"
1666                            "    array set endpoint [list]\n"
1667                            "}\n")) {
1668         fprintf(stderr, "usbhost: internal error, failed to create Tcl usbtest:: namespace\n");
1669         fprintf(stderr, "         Please check Tcl version (8.0b1 or later required).\n");
1670         exit(EXIT_FAILURE);
1671     }
1672
1673     // Add some information about the install path so that the
1674     // main Tcl script can find and execute test scripts.
1675     location = getenv("USBHOSTDIR");
1676     if (NULL == location) {
1677         location = USBAUXDIR;
1678     }
1679     Tcl_SetVar(interp, "usbtest::USBAUXDIR", location, TCL_GLOBAL_ONLY);
1680
1681     // Also set the verbosity level correctly
1682     Tcl_SetVar2Ex(interp, "usbtest::verbose", NULL, Tcl_NewIntObj(verbose), TCL_GLOBAL_ONLY);
1683     
1684     // Next we need to know the number of endpoints, and for each
1685     // endpoint we want additional information such as type. The
1686     // results are placed in a Tcl array.
1687     usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN, USBTEST_ENDPOINT_COUNT,
1688                                  0, 0, 1, buf);
1689     number_of_endpoints = buf[0];
1690     Tcl_SetVar2Ex(interp, "usbtest::endpoint_count", NULL, Tcl_NewIntObj(number_of_endpoints), TCL_GLOBAL_ONLY);
1691     
1692     for (i = 0; i < number_of_endpoints; i++) {
1693         char            varname[256];
1694         int             result;
1695         int             endpoint_min_size;
1696         int             endpoint_max_size;
1697         int             index;
1698         
1699         memset(buf, 0, USBTEST_MAX_CONTROL_DATA);
1700         result = usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN,
1701                                               USBTEST_ENDPOINT_DETAILS, 0, i, USBTEST_MAX_CONTROL_DATA, buf);
1702         if (result < 13) {
1703             fprintf(stderr, "usbhost: error, received insufficient endpoint data back from the target.\n");
1704             exit(EXIT_FAILURE);
1705         }
1706
1707         // See protocol.h for the encoding used.
1708         sprintf(varname, "usbtest::endpoint_data(%d,type)", i);
1709         switch(buf[0]) {
1710           case USB_ENDPOINT_XFER_CONTROL    : Tcl_SetVar(interp, varname, "control",     TCL_GLOBAL_ONLY); break;
1711           case USB_ENDPOINT_XFER_ISOC       : Tcl_SetVar(interp, varname, "isochronous", TCL_GLOBAL_ONLY); break;
1712           case USB_ENDPOINT_XFER_BULK       : Tcl_SetVar(interp, varname, "bulk",        TCL_GLOBAL_ONLY); break;
1713           case USB_ENDPOINT_XFER_INT        : Tcl_SetVar(interp, varname, "interrupt",   TCL_GLOBAL_ONLY); break;
1714         }
1715
1716         sprintf(varname, "usbtest::endpoint_data(%d,number)", i);
1717         Tcl_SetVar2Ex(interp, varname, NULL, Tcl_NewIntObj((int) buf[1]), TCL_GLOBAL_ONLY);
1718
1719         sprintf(varname, "usbtest::endpoint_data(%d,direction)", i);
1720         if (USB_DIR_OUT == buf[2]) {
1721             Tcl_SetVar(interp, varname, "out", TCL_GLOBAL_ONLY);
1722         } else {
1723             Tcl_SetVar(interp, varname, "in", TCL_GLOBAL_ONLY);
1724         }
1725
1726         sprintf(varname, "usbtest::endpoint_data(%d,max_in_padding)", i);
1727         Tcl_SetVar2Ex(interp, varname, NULL, Tcl_NewIntObj((int) buf[3]), TCL_GLOBAL_ONLY);
1728
1729         sprintf(varname, "usbtest::endpoint_data(%d,min_size)", i);
1730         index               = 4;
1731         endpoint_min_size   = unpack_int(buf, &index);
1732         Tcl_SetVar2Ex(interp, varname, NULL, Tcl_NewIntObj(endpoint_min_size), TCL_GLOBAL_ONLY);
1733             
1734         sprintf(varname, "usbtest::endpoint_data(%d,max_size)", i);
1735         endpoint_max_size   = unpack_int(buf, &index);
1736         if (USB_ENDPOINT_XFER_CONTROL == buf[0]) {
1737             if (endpoint_max_size > USBTEST_MAX_CONTROL_DATA) {
1738                 endpoint_max_size = USBTEST_MAX_CONTROL_DATA;
1739             }
1740         } else {
1741             if ((-1 == endpoint_max_size) || (endpoint_max_size > USBTEST_MAX_BULK_DATA)) {
1742                 endpoint_max_size = USBTEST_MAX_BULK_DATA;
1743             }
1744         }
1745         Tcl_SetVar2Ex(interp, varname, NULL, Tcl_NewIntObj(endpoint_max_size), TCL_GLOBAL_ONLY);
1746
1747         sprintf(varname, "usbtest::endpoint_data(%d,devtab)", i);
1748         Tcl_SetVar(interp, varname, (char*) &(buf[12]), TCL_GLOBAL_ONLY);
1749
1750         // Perform any additional endpoint-specific initialization to make
1751         // sure host and target can actually communicate via this endpoint.
1752         switch(buf[0]) {
1753           case USB_ENDPOINT_XFER_CONTROL    :
1754           {
1755               usb_initialise_control_endpoint(endpoint_min_size, endpoint_max_size);
1756               break;
1757           }
1758           case USB_ENDPOINT_XFER_ISOC       :
1759           {
1760               if (USB_DIR_OUT == buf[2]) {
1761                   usb_initialise_isochronous_out_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1762               } else {
1763                   usb_initialise_isochronous_in_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1764               }
1765               break;
1766           }
1767           case USB_ENDPOINT_XFER_BULK       :
1768           {
1769               if (USB_DIR_OUT == buf[2]) {
1770                   usb_initialise_bulk_out_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1771               } else {
1772                   usb_initialise_bulk_in_endpoint(buf[1], endpoint_min_size, endpoint_max_size, buf[3]);
1773               }
1774               
1775               break;
1776           }
1777           case USB_ENDPOINT_XFER_INT        :
1778           {
1779               if (USB_DIR_OUT == buf[2]) {
1780                   usb_initialise_interrupt_out_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1781               } else {
1782                   usb_initialise_interrupt_in_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1783               }
1784               break;
1785           }
1786         }
1787     }
1788
1789     // Register appropriate commands with the Tcl interpreter
1790     Tcl_CreateCommand(interp, "usbtest::target_pass",       &tcl_target_pass,       (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1791     Tcl_CreateCommand(interp, "usbtest::target_pass_exit",  &tcl_target_pass_exit,  (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1792     Tcl_CreateCommand(interp, "usbtest::target_fail",       &tcl_target_fail,       (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1793     Tcl_CreateCommand(interp, "usbtest::target_fail_exit",  &tcl_target_fail_exit,  (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1794     Tcl_CreateCommand(interp, "usbtest::target_abort",      &tcl_target_abort,      (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1795     Tcl_CreateCommand(interp, "usbtest::_test_bulk",        &tcl_test_bulk,         (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1796     Tcl_CreateCommand(interp, "usbtest::_test_control_in",  &tcl_test_control_in,   (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1797     Tcl_CreateCommand(interp, "usbtest::_cancel",           &tcl_cancel,            (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1798     Tcl_CreateCommand(interp, "usbtest::_run",              &tcl_run,               (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1799     Tcl_CreateCommand(interp, "usbtest::host_verbose",      &tcl_host_verbose,      (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1800     Tcl_CreateCommand(interp, "usbtest::target_verbose",    &tcl_target_verbose,    (ClientData) NULL, (Tcl_CmdDeleteProc*) NULL);
1801
1802     return TCL_OK;
1803 }
1804
1805 /*}}}*/
1806 /*{{{  main()                                                   */
1807
1808 // ----------------------------------------------------------------------------
1809 // System start-up. After argument processing this code checks that
1810 // there is a suitable USB target attached - if not then there is no
1811 // point in proceeding. Otherwise further initialization is performed
1812 // and then control is passed to a Tcl interpreter.
1813
1814 static void
1815 usage(void)
1816 {
1817     printf("usbhost: usage, usbhost [-V|--verbose] [-v|--version] [-h|--help] <test> [args]\n");
1818     printf("    -V, --verbose    Make the host-side output additional information\n");
1819     printf("                     during test runs. This argument can be repeated to\n");
1820     printf("                     increase verbosity.\n");
1821     printf("    -v, --version    Output version information for usbhost.\n");
1822     printf("    -h, --help       Output this help information.\n");
1823     printf("    <test>           The name of a USB test case, for example list.tcl\n");
1824     printf("    [args]           Optional additional arguments for the testcase.\n");
1825     exit(0);
1826 }
1827
1828 static void
1829 version(void)
1830 {
1831     printf("usbhost: version %s\n", USBHOST_VERSION);
1832     printf("       : built from USB slave package version %s\n", PKGVERSION);
1833     printf("       : support files installed in %s\n", USBAUXDIR);
1834     exit(0);
1835 }
1836
1837 int
1838 main(int argc, char** argv)
1839 {
1840     char*   interpreter = argv[0];
1841     char**  new_argv;
1842     char    path[_POSIX_PATH_MAX];
1843     char*   location;
1844     int     i;
1845
1846     // Argument processing
1847     for (i = 1; i < argc; i++) {
1848         if ((0 == strcmp("-h", argv[i])) || (0 == strcmp("-H", argv[i])) || (0 == strcmp("--help", argv[i]))) {
1849             usage();
1850         }
1851         if ((0 == strcmp("-v", argv[i])) || (0 == strcmp("--version", argv[i]))) {
1852             version();
1853         }
1854         if ((0 == strcmp("-V", argv[i])) || (0 == strcmp("--verbose", argv[i]))) {
1855             verbose++;
1856             continue;
1857         }
1858
1859         // The first unrecognised argument should correspond to the test script.
1860         break;
1861     }
1862     argc  = (argc - i) + 1;
1863     argv  = (argv + i) - 1;
1864
1865     if (1 == argc) {
1866         fprintf(stderr, "usbhost: at least one test script must be specified on the command line.\n");
1867         exit(EXIT_FAILURE);
1868     }
1869
1870     usb_master_fd = usb_open_device();
1871     if (-1 == usb_master_fd) {
1872         return EXIT_FAILURE;
1873     }
1874
1875     // There is a valid USB target. Initialize the pool of threads etc.
1876     pool_initialize();
1877
1878     // Now start a Tcl interpreter. Tcl_Main() will interpret the
1879     // first argument as the name of a Tcl script to execute,
1880     // i.e. usbhost.tcl. This can be found in the install tree,
1881     // but during development it is inconvenient to run
1882     // "make install" every time the Tcl script is edited so an
1883     // environment variable can be used to override the location.
1884     new_argv = malloc((argc + 2) * sizeof(char*));
1885     if (NULL == new_argv) {
1886         fprintf(stderr, "usbhost: internal error, out of memory.\n");
1887         exit(EXIT_FAILURE);
1888     }
1889     new_argv[0] = interpreter;
1890
1891     location = getenv("USBHOSTDIR");
1892     if (NULL == location) {
1893         location = USBAUXDIR;
1894     }
1895     snprintf(path, _POSIX_PATH_MAX, "%s/usbhost.tcl", location);
1896     if (0 != access(path, R_OK)) {
1897         fprintf(stderr, "usbhost: cannot find or access required Tcl script\n");
1898         fprintf(stderr, "       : %s\n", path);
1899         exit(EXIT_FAILURE);
1900     }
1901     new_argv[1] = path;
1902
1903     for (i = 1; i < argc; i++) {
1904         new_argv[i+1] = argv[i];
1905     }
1906     new_argv[i+1]   = NULL;
1907
1908     Tcl_Main(i+1, new_argv, &usbhost_appinit);
1909     
1910     return EXIT_SUCCESS;
1911 }
1912
1913 /*}}}*/