3 //=================================================================
7 // USB testing - host-side
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.
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.
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
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.
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.
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.
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####
48 //####DESCRIPTIONEND####
49 //==========================================================================
51 // The overall architecture is as follows.
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).
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
76 #include <sys/types.h>
80 #include <sys/ioctl.h>
83 #include <semaphore.h>
84 // Avoid compatibility problems with Tcl 8.4 vs. earlier
87 #include <linux/usb.h>
88 #include <linux/usbdevice_fs.h>
89 #include "../tests/protocol.h"
94 /*{{{ Backwards compatibility */
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
109 // ----------------------------------------------------------------------------
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;
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;
123 // A similar counter for remote threads.
124 static int remote_thread_count = 0;
126 // A file handle for manipulating the USB device at a low level
127 static int usb_master_fd = -1;
132 // ----------------------------------------------------------------------------
133 // The user can provide one or more -V/--verbose arguments to increase
134 // the amount of output generated.
136 static int verbose = 0;
138 #define VERBOSE(_level_, _format_, _args_...) \
140 if (verbose >= _level_) { \
141 printf(_format_, ## _args_); \
146 /*{{{ Low-level USB access */
148 // ----------------------------------------------------------------------------
149 // Low-level access to a USB device.
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.
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.
163 // How to access USB devices from userland
164 #define USB_ROOT "/proc/bus/usb/"
166 // How to identify the eCos test case
167 #define PRODUCT_STRING "Red Hat eCos USB test"
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
174 // T: Bus=<abc> ... Dev#= <def> ...
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.
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.
184 usb_scan_devices(int* bus, int* dev)
187 int current_bus = -1;
188 int current_dev = -1;
194 VERBOSE(1, "Searching " USB_ROOT "devices for the eCos USB test code\n");
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");
201 ch = getc(devs_file);
204 if (2 !=fscanf(devs_file, ": Bus=%d %*[^D\n]Dev#=%d", ¤t_bus, ¤t_dev)) {
208 } else if ('S' == ch) {
209 int start = 0, end = 0;
210 if (EOF != fscanf(devs_file, ": Product=%n" PRODUCT_STRING "%n", &start, &end)) {
218 // Move to the end of the current line.
220 ch = getc(devs_file);
221 } while ((EOF != ch) && ('\n' != ch));
223 ch = getc(devs_file);
228 if ((-1 != *bus) && (-1 != *dev)) {
229 VERBOSE(1, "Found eCos USB test code on bus %d, device %d\n", *bus, *dev);
232 fprintf(stderr, "usbhost: error, failed to find a USB device \"" PRODUCT_STRING "\"\n");
236 // Actually open the USB device, allowing subsequent ioctl() operations.
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.
243 usb_open_device(void)
245 char devname[_POSIX_PATH_MAX];
250 if ((-1 == bus) || (-1 == dev)) {
251 if (!usb_scan_devices(&bus, &dev)) {
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");
261 VERBOSE(1, "Attempting to access USB target via %s\n", devname);
263 result = open(devname, O_RDWR);
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];
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");
277 (void) system(command_name);
278 result = open(devname, O_RDWR);
282 fprintf(stderr, "usbhost: error, failed to open \"%s\", errno %d\n", devname, errno);
285 VERBOSE(1, "USB device now accessible via file descriptor %d\n", result);
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);
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.
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.
304 usb_control_message(int fd, int request_type, int request, int value, int index, int length, void* data)
306 struct usbdevfs_ctrltransfer transfer;
309 VERBOSE(3, "usb_control_message, request %02x, len %d\n", request, length);
311 if (length > USBTEST_MAX_CONTROL_DATA) {
312 fprintf(stderr, "usbhost: internal error, control message involves too much data.\n");
317 // Workaround - send additional data in the index and length fields.
318 if ((length > 0) && (USB_DIR_OUT == (USB_ENDPOINT_DIR_MASK & request_type))) {
320 unsigned char* buf = (unsigned char*) data;
322 for (i = 0; i < length; i+= 4) {
323 int this_len = length - 1;
326 transfer.bRequestType = USB_TYPE_CLASS | USB_RECIP_DEVICE;
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;
336 fprintf(stderr, "usbhost: internal error, confusion about transfer length.\n");
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;
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");
353 // There is no more data to be transferred.
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;
365 result = ioctl(fd, USBDEVFS_CONTROL, &transfer);
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.
372 usb_reliable_control_message(int fd, int request_type, int request, int value, int index, int length, void* data)
374 int result = usb_control_message(fd, request_type, request, value, index, length, data);
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));
384 // Either send or receive a single bulk message. The top bit of the endpoint
385 // number indicates the direction.
387 usb_bulk_message(int fd, int endpoint, unsigned char* buffer, int length)
389 struct usbdevfs_bulktransfer transfer;
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
402 transfer.data = buffer;
404 result = ioctl(fd, USBDEVFS_BULK, &transfer);
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.
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.
416 usb_sync(int fd, int limit)
418 unsigned char buf[1];
419 struct timespec delay;
423 VERBOSE(2, "Synchronizing with target\n");
427 usb_reliable_control_message(fd, USB_TYPE_CLASS | USB_RECIP_DEVICE | USB_DIR_IN, USBTEST_SYNCH, 0, 0, 1, buf);
432 if ((-1 != limit) && (++loops > limit)) {
435 VERBOSE(3, "Not yet synchronized, sleeping\n");
437 delay.tv_nsec = 100000000; // 100 ms
438 nanosleep(&delay, NULL);
442 VERBOSE(2, "%s\n", result ? "Synchronized" : "Not synchronized");
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.
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);
456 /*{{{ Initialise endpoints */
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.
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.
473 usb_initialise_control_endpoint(int min_size, int max_size)
475 // At this time there are no known problems on any hardware
476 // that would need to be addressed
480 usb_initialise_isochronous_in_endpoint(int number, int min_size, int max_size)
482 // At this time there are no known problems on any hardware
483 // that would need to be addressed
487 usb_initialise_isochronous_out_endpoint(int number, int min_size, int max_size)
489 // At this time there are no known problems on any hardware
490 // that would need to be addressed
494 usb_initialise_bulk_in_endpoint(int number, int min_size, int max_size, int padding)
496 // At this time there are no known problems on any hardware
497 // that would need to be addressed
501 usb_initialise_bulk_out_endpoint(int number, int min_size, int max_size)
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
511 VERBOSE(2, "Performing bulk OUT initialization on endpoint %d\n", number);
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);
520 usb_initialise_interrupt_in_endpoint(int number, int min_size, int max_size)
522 // At this time there are no known problems on any hardware
523 // that would need to be addressed
527 usb_initialise_interrupt_out_endpoint(int number, int min_size, int max_size)
529 // At this time there are no known problems on any hardware
530 // that would need to be addressed
534 /*{{{ Host/target common code */
537 #include "../tests/common.c"
540 /*{{{ The test cases themselves */
542 /*{{{ UsbTest definition */
544 // ----------------------------------------------------------------------------
545 // All the data associated with a single test.
547 typedef struct UsbTest {
549 // A "unique" identifier to make verbose output easier to understand.
551 // Which file descriptor should be used to access USB.
554 // Which test should be run.
557 // Test-specific details.
560 UsbTest_ControlIn control_in;
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
566 UsbTest_Recovery recovery;
569 char result_message[USBTEST_MAX_MESSAGE];
570 unsigned char buffer[USBTEST_MAX_BULK_DATA + USBTEST_MAX_BULK_DATA_EXTRA];
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.
577 reset_usbtest(UsbTest* test)
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';
591 run_test_bulk_out(UsbTest* test)
593 unsigned char* buf = test->buffer;
596 VERBOSE(1, "Starting test %d, bulk OUT on endpoint %d\n", test->id, test->test_params.bulk.endpoint);
598 for (i = 0; i < test->test_params.bulk.number_packets; i++) {
600 int packet_size = test->test_params.bulk.tx_size;
602 test->recovery.endpoint = test->test_params.bulk.endpoint;
603 test->recovery.protocol = USB_ENDPOINT_XFER_BULK;
604 test->recovery.size = packet_size;
606 usbtest_fill_buffer(&(test->test_params.bulk.data), buf, packet_size);
608 VERBOSE(2, "Bulk OUT test %d: iteration %d, packet size %d\n", test->id, i, packet_size);
610 // Output the first 32 bytes of data as well.
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)" : "");
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]);
623 index += snprintf(msg+index, 255-index, " ");
624 for ( ; j < packet_size; j++) {
625 index += snprintf(msg+index, 255-index, "%02x", buf[j]);
629 VERBOSE(3, "%s\n", msg);
632 transferred = usb_bulk_message(test->fd, test->test_params.bulk.endpoint, buf, packet_size);
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);
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);
656 if (0 != test->test_params.bulk.tx_delay) {
657 struct timespec delay;
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);
670 // Now move on to the next transfer
671 USBTEST_BULK_NEXT(test->test_params.bulk);
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;
679 VERBOSE(1, "Test %d bulk OUT on endpoint %d, result %d\n", test->id, test->test_params.bulk.endpoint, test->result_pass);
686 run_test_bulk_in(UsbTest* test)
688 unsigned char* buf = test->buffer;
691 VERBOSE(1, "Starting test %d bulk IN on endpoint %d\n", test->id, test->test_params.bulk.endpoint);
693 for (i = 0; i < test->test_params.bulk.number_packets; i++) {
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;
699 VERBOSE(2, "Bulk IN test %d: iteration %d, rx size %d, tx size %d\n", test->id, i, rx_size, tx_size);
701 if (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);
706 test->recovery.endpoint = test->test_params.bulk.endpoint;
707 test->recovery.protocol = USB_ENDPOINT_XFER_BULK;
708 test->recovery.size = rx_size;
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);
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;
721 transferred = usb_bulk_message(test->fd, test->test_params.bulk.endpoint, buf, size_plus_padding);
722 } while (0 == transferred);
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);
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);
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);
756 // Output the first 32 bytes of data
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)" : "");
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]);
769 index += snprintf(msg+index, 255-index, " ");
770 for ( ; j < transferred; j++) {
771 index += snprintf(msg+index, 255-index, "%02x", buf[j]);
775 VERBOSE(3, "%s\n", msg);
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);
788 if (0 != test->test_params.bulk.rx_delay) {
789 struct timespec delay;
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);
802 USBTEST_BULK_NEXT(test->test_params.bulk);
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;
811 VERBOSE(1, "Test %d bulk IN on endpoint %d, result %d\n", test->id, test->test_params.bulk.endpoint, test->result_pass);
817 // Receive appropriate packets via the control endpoint. This is somewhat
818 // different from bulk transfers. It is implemented using reserved control
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
828 run_test_control_in(UsbTest* test)
830 unsigned char* buf = test->buffer;
834 packet_size = test->test_params.control_in.packet_size_initial;
835 for (i = 0; i < test->test_params.control_in.number_packets; i++) {
838 test->recovery.endpoint = 0;
839 test->recovery.protocol = USB_ENDPOINT_XFER_CONTROL;
840 test->recovery.size = packet_size;
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);
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);
851 // Has this test run been aborted for some reason?
852 if (current_tests_terminated) {
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));
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);
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");
883 USBTEST_CONTROL_NEXT_PACKET_SIZE(packet_size, test->test_params.control_in);
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;
894 // FIXME: add more tests
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.
901 run_test(UsbTest* test)
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;
908 fprintf(stderr, "usbhost: internal error, attempt to execute an unknown test.\n");
916 /*{{{ The thread pool */
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.
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
930 typedef struct PoolEntry {
937 static PoolEntry pool[USBTEST_MAX_CONCURRENT_TESTS];
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.
943 pool_function(void* arg)
945 PoolEntry* pool_entry = (PoolEntry*) arg;
947 sem_wait(&(pool_entry->wakeup));
948 run_test(&(pool_entry->test));
949 pool_entry->running = 0;
955 // Initialize all threads in the pool.
957 pool_initialize(void)
960 for (i = 0; i < USBTEST_MAX_CONCURRENT_TESTS; i++) {
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");
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");
974 // Allocate a single entry in the thread pool.
978 UsbTest* result = (UsbTest*) 0;
980 if (local_thread_count == USBTEST_MAX_CONCURRENT_TESTS) {
981 fprintf(stderr, "usbhost: internal error, thread resource exhausted.\n");
985 result = &(pool[local_thread_count].test);
986 local_thread_count++;
987 reset_usbtest(result);
991 // Start all the threads that are supposed to be running tests.
996 for (i = 0; i < local_thread_count; i++) {
998 sem_post(&(pool[i].wakeup));
1003 /*{{{ Tcl routines */
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
1013 /*{{{ pass/fail/abort */
1015 // ----------------------------------------------------------------------------
1016 // Some simple routines accessible from Tcl to get the target to report pass/fail or
1017 // to make the target abort.
1020 tcl_target_pass(ClientData clientData __attribute__ ((unused)),
1026 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_pass <message>\"", TCL_STATIC);
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);
1035 tcl_target_fail(ClientData clientData __attribute__ ((unused)),
1041 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_fail <message>\"", TCL_STATIC);
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);
1049 // The next three routines cause the target to exit, so a usb_sync() is inappropriate.
1051 tcl_target_pass_exit(ClientData clientData __attribute__ ((unused)),
1057 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_pass_exit <message>\"", TCL_STATIC);
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]);
1067 tcl_target_fail_exit(ClientData clientData __attribute__ ((unused)),
1073 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_fail_exit <message>\"", TCL_STATIC);
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]);
1082 tcl_target_abort(ClientData clientData __attribute__ ((unused)),
1085 char** argv __attribute__ ((unused)) )
1088 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_abort\"", TCL_STATIC);
1091 usb_abort(usb_master_fd);
1096 /*{{{ start bulk test */
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.
1106 tcl_test_bulk(ClientData clientData __attribute__ ((unused)),
1114 unsigned char request[USBTEST_MAX_CONTROL_DATA];
1117 // The data consists of 28 numbers for UsbTest_Bulk itself, and
1118 // another 10 numbers for the test data definition.
1120 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::_test_bulk <message>\"", TCL_STATIC);
1123 for (i = 1; i < 39; i++) {
1125 if (TCL_OK != Tcl_GetInt(interp, argv[i], &discard)) {
1126 Tcl_SetResult(interp, "invalid argument: all arguments should be numbers", TCL_STATIC);
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));
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);
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.
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++;
1226 /*{{{ start control-in test */
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.
1236 tcl_test_control_in(ClientData clientData __attribute__ ((unused)),
1244 unsigned char request[USBTEST_MAX_CONTROL_DATA];
1247 // The data consists of 6 numbers for UsbTest_ControlIn itself, and
1248 // another 10 numbers for the test data definition.
1250 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::_test_control_in <message>\"", TCL_STATIC);
1253 for (i = 1; i < 17; i++) {
1255 if (TCL_OK != Tcl_GetInt(interp, argv[i], &discard)) {
1256 Tcl_SetResult(interp, "invalid argument: all arguments should be numbers", TCL_STATIC);
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));
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.
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++;
1293 /*{{{ Cancel the current batch of tests */
1296 tcl_cancel(ClientData clientData __attribute__ ((unused)),
1299 char** argv __attribute__ ((unused)) )
1302 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::cancel\"", TCL_STATIC);
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);
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;
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");
1319 remote_thread_count = 0;
1325 /*{{{ Run a batch of tests */
1327 // ----------------------------------------------------------------------------
1328 // This code does an awful lot of the hard work. Start with various utilities.
1330 // Has the current batch finished as far as the local threads are concerned?
1332 local_batch_finished(void)
1337 for (i = 0; i < local_thread_count; i++) {
1338 if (pool[i].running) {
1346 // Has the current batch finished as far as remote threads are concerned?
1348 remote_batch_finished(void)
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);
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.
1360 recover_remote(int index)
1362 unsigned char buffer[USBTEST_MAX_CONTROL_DATA];
1364 UsbTest_Recovery recovery;
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
1371 unpack_usbtest_recovery(&recovery, buffer, &buffer_index);
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];
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;
1392 i = ioctl(usb_master_fd, USBDEVFS_BULK, &transfer);
1395 // There is no recovery support yet for other protocols.
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.
1403 recover_local(int index)
1405 unsigned char buffer[USBTEST_MAX_CONTROL_DATA];
1408 if (pool[index].running) {
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);
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.
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;
1428 // The main routine, as invoked from Tcl. This takes a single
1429 // argument, a timeout in seconds.
1431 tcl_run(ClientData clientData __attribute__ ((unused)),
1434 char** argv __attribute__ ((unused)) )
1436 struct timespec delay;
1441 unsigned char result_buf[USBTEST_MAX_CONTROL_DATA];
1445 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::_run <timeout>\"", TCL_STATIC);
1448 if (TCL_OK != Tcl_GetInt(interp, argv[1], &timeout)) {
1449 Tcl_SetResult(interp, "invalid argument: timeout should be numeric", TCL_STATIC);
1453 VERBOSE(2, "Starting a testrun, timeout %d seconds\n", timeout);
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
1459 usb_reliable_control_message(usb_master_fd, USB_TYPE_CLASS | USB_RECIP_DEVICE, USBTEST_START, 0, 0, 0, (void*) 0);
1461 // Now the local threads can get going.
1462 current_tests_terminated = 0;
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.
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.
1476 VERBOSE(3, "The tests are running, waiting for termination\n");
1479 nanosleep(&delay, NULL);
1481 } while (((start + timeout) > now) && !local_batch_finished() && !remote_batch_finished());
1483 VERBOSE(2, "Termination detected, time elapsed %ld\n", (long) now - start);
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
1497 nanosleep(&delay, NULL);
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()) {
1506 VERBOSE(2, "Remote threads still running, performing remote recovery\n");
1507 for (i = 0; i < remote_thread_count; i++) {
1510 // Allow the recovery actions to take effect
1513 nanosleep(&delay, NULL);
1516 if (!local_batch_finished()) {
1518 VERBOSE(2, "Local threads still running, performing local recovery\n");
1519 for (i = 0; i < local_thread_count; i++) {
1522 // Allow the recovery actions to take effect
1525 nanosleep(&delay, NULL);
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
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");
1547 VERBOSE(2, "Local and remote threads are in synch, collecting results.\n");
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
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));
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));
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));
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));
1584 VERBOSE(2, "Overall test result %d\n", all_ok);
1586 Tcl_SetResult(interp, all_ok ? "1" : "0", TCL_STATIC);
1594 /*{{{ Set verbosity */
1596 // ----------------------------------------------------------------------------
1597 // Allow Tcl scripts to control verbosity levels for both host and target
1599 tcl_host_verbose(ClientData clientData __attribute__ ((unused)),
1607 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::host_verbose <level>\"", TCL_STATIC);
1610 if (TCL_OK != Tcl_GetInt(interp, argv[1], &level)) {
1611 Tcl_SetResult(interp, "invalid argument: verbosity level should be numeric", TCL_STATIC);
1620 tcl_target_verbose(ClientData clientData __attribute__ ((unused)),
1628 Tcl_SetResult(interp, "wrong # args: should be \"usbtest::target_verbose <level>\"", TCL_STATIC);
1631 if (TCL_OK != Tcl_GetInt(interp, argv[1], &level)) {
1632 Tcl_SetResult(interp, "invalid argument: verbosity level should be numeric", TCL_STATIC);
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);
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.
1654 usbhost_appinit(Tcl_Interp* interp)
1656 unsigned char buf[USBTEST_MAX_CONTROL_DATA];
1657 int number_of_endpoints;
1661 // Start by creating a usbtest namespace, for use by the various functions
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"
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");
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;
1679 Tcl_SetVar(interp, "usbtest::USBAUXDIR", location, TCL_GLOBAL_ONLY);
1681 // Also set the verbosity level correctly
1682 Tcl_SetVar2Ex(interp, "usbtest::verbose", NULL, Tcl_NewIntObj(verbose), TCL_GLOBAL_ONLY);
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,
1689 number_of_endpoints = buf[0];
1690 Tcl_SetVar2Ex(interp, "usbtest::endpoint_count", NULL, Tcl_NewIntObj(number_of_endpoints), TCL_GLOBAL_ONLY);
1692 for (i = 0; i < number_of_endpoints; i++) {
1695 int endpoint_min_size;
1696 int endpoint_max_size;
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);
1703 fprintf(stderr, "usbhost: error, received insufficient endpoint data back from the target.\n");
1707 // See protocol.h for the encoding used.
1708 sprintf(varname, "usbtest::endpoint_data(%d,type)", i);
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;
1716 sprintf(varname, "usbtest::endpoint_data(%d,number)", i);
1717 Tcl_SetVar2Ex(interp, varname, NULL, Tcl_NewIntObj((int) buf[1]), TCL_GLOBAL_ONLY);
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);
1723 Tcl_SetVar(interp, varname, "in", TCL_GLOBAL_ONLY);
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);
1729 sprintf(varname, "usbtest::endpoint_data(%d,min_size)", i);
1731 endpoint_min_size = unpack_int(buf, &index);
1732 Tcl_SetVar2Ex(interp, varname, NULL, Tcl_NewIntObj(endpoint_min_size), TCL_GLOBAL_ONLY);
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;
1741 if ((-1 == endpoint_max_size) || (endpoint_max_size > USBTEST_MAX_BULK_DATA)) {
1742 endpoint_max_size = USBTEST_MAX_BULK_DATA;
1745 Tcl_SetVar2Ex(interp, varname, NULL, Tcl_NewIntObj(endpoint_max_size), TCL_GLOBAL_ONLY);
1747 sprintf(varname, "usbtest::endpoint_data(%d,devtab)", i);
1748 Tcl_SetVar(interp, varname, (char*) &(buf[12]), TCL_GLOBAL_ONLY);
1750 // Perform any additional endpoint-specific initialization to make
1751 // sure host and target can actually communicate via this endpoint.
1753 case USB_ENDPOINT_XFER_CONTROL :
1755 usb_initialise_control_endpoint(endpoint_min_size, endpoint_max_size);
1758 case USB_ENDPOINT_XFER_ISOC :
1760 if (USB_DIR_OUT == buf[2]) {
1761 usb_initialise_isochronous_out_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1763 usb_initialise_isochronous_in_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1767 case USB_ENDPOINT_XFER_BULK :
1769 if (USB_DIR_OUT == buf[2]) {
1770 usb_initialise_bulk_out_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1772 usb_initialise_bulk_in_endpoint(buf[1], endpoint_min_size, endpoint_max_size, buf[3]);
1777 case USB_ENDPOINT_XFER_INT :
1779 if (USB_DIR_OUT == buf[2]) {
1780 usb_initialise_interrupt_out_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
1782 usb_initialise_interrupt_in_endpoint(buf[1], endpoint_min_size, endpoint_max_size);
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);
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.
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");
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);
1838 main(int argc, char** argv)
1840 char* interpreter = argv[0];
1842 char path[_POSIX_PATH_MAX];
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]))) {
1851 if ((0 == strcmp("-v", argv[i])) || (0 == strcmp("--version", argv[i]))) {
1854 if ((0 == strcmp("-V", argv[i])) || (0 == strcmp("--verbose", argv[i]))) {
1859 // The first unrecognised argument should correspond to the test script.
1862 argc = (argc - i) + 1;
1863 argv = (argv + i) - 1;
1866 fprintf(stderr, "usbhost: at least one test script must be specified on the command line.\n");
1870 usb_master_fd = usb_open_device();
1871 if (-1 == usb_master_fd) {
1872 return EXIT_FAILURE;
1875 // There is a valid USB target. Initialize the pool of threads etc.
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");
1889 new_argv[0] = interpreter;
1891 location = getenv("USBHOSTDIR");
1892 if (NULL == location) {
1893 location = USBAUXDIR;
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);
1903 for (i = 1; i < argc; i++) {
1904 new_argv[i+1] = argv[i];
1906 new_argv[i+1] = NULL;
1908 Tcl_Main(i+1, new_argv, &usbhost_appinit);
1910 return EXIT_SUCCESS;