OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [rtos/] [ecos-3.0/] [packages/] [io/] [usb/] [slave/] [current/] [tests/] [usbtarget.c] - Blame information for rev 786

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.