]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/devs/usb/sa11x0/v2_0/src/usbs_sa11x0.c
Initial revision
[karo-tx-redboot.git] / packages / devs / usb / sa11x0 / v2_0 / src / usbs_sa11x0.c
1 //==========================================================================
2 //
3 //      usbs_sa11x0.c
4 //
5 //      Device driver for the SA11x0 USB port.
6 //
7 //==========================================================================
8 //####ECOSGPLCOPYRIGHTBEGIN####
9 // -------------------------------------------
10 // This file is part of eCos, the Embedded Configurable Operating System.
11 // Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
12 //
13 // eCos is free software; you can redistribute it and/or modify it under
14 // the terms of the GNU General Public License as published by the Free
15 // Software Foundation; either version 2 or (at your option) any later version.
16 //
17 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
18 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 // for more details.
21 //
22 // You should have received a copy of the GNU General Public License along
23 // with eCos; if not, write to the Free Software Foundation, Inc.,
24 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
25 //
26 // As a special exception, if other files instantiate templates or use macros
27 // or inline functions from this file, or you compile this file and link it
28 // with other works to produce a work based on this file, this file does not
29 // by itself cause the resulting work to be covered by the GNU General Public
30 // License. However the source code for this file must still be made available
31 // in accordance with section (3) of the GNU General Public License.
32 //
33 // This exception does not invalidate any other reasons why a work based on
34 // this file might be covered by the GNU General Public License.
35 //
36 // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
37 // at http://sources.redhat.com/ecos/ecos-license/
38 // -------------------------------------------
39 //####ECOSGPLCOPYRIGHTEND####
40 //==========================================================================
41 //#####DESCRIPTIONBEGIN####
42 //
43 // Author(s):    bartv
44 // Contributors: bartv
45 // Date:         2000-10-04
46 //
47 // This code implements support for the on-chip USB port on the SA11x0
48 // family of processors. The code has been developed on the SA1110 and
49 // may or may not work on other members of the SA11x0 family. There
50 // have problems with the USB support on certain revisions of the silicon,
51 // so the errata sheet appropriate to the specific processor being used
52 // should be consulted. There also appear to be problems which do not
53 // appear on any errata, which this code attempts to work around.
54 //
55 //####DESCRIPTIONEND####
56 //==========================================================================
57
58 #include <cyg/infra/cyg_type.h>
59 #include <cyg/infra/cyg_ass.h>
60 #include <cyg/infra/cyg_trac.h>
61 #include <cyg/infra/diag.h>
62
63 #include <pkgconf/hal_arm.h>
64 #include <pkgconf/devs_usb_sa11x0.h>
65
66 #include <cyg/hal/drv_api.h>
67 #include <cyg/hal/hal_arch.h>
68 #include <cyg/hal/hal_io.h>
69 #include <cyg/hal/hal_cache.h>
70 #include <cyg/hal/hal_sa11x0.h>
71 #include <cyg/error/codes.h>
72
73 #include <cyg/io/usb/usb.h>
74 #include <cyg/io/usb/usbs.h>
75
76 // Debugging support. By default this driver operates mostly at
77 // DSR level, with the ISR doing a minimal amount of processing.
78 // However is also possible to run most of the code at thread-level,
79 // This is subject to some restrictions because the USB standard
80 // imposes timing constraints, e.g. some control operations such
81 // as SET-ADDRESS have to complete within 50ms. However it is
82 // very useful for debugging, specifically it allows you to put
83 // printf()'s in various places.
84 //
85 // Right now these configuration options are not exported to the
86 // user because running at DSR level is likely to be good enough
87 // for everybody not actively debugging this code. The options
88 // could be exported if necessary.
89 //#define CYGPKG_DEVS_USB_SA11X0_THREAD
90 #undef CYGPKG_DEVS_USB_SA11X0_THREAD
91 #ifdef CYGPKG_DEVS_USB_SA11X0_THREAD
92   // Default stack size should be CYGNUM_HAL_STACK_SIZE_TYPICAL
93 # define CYGNUM_DEVS_USB_SA11X0_THREAD_STACK_SIZE       4096
94 # define CYGNUM_DEVS_USB_SA11X0_THREAD_PRIORITY         7
95 # include <cyg/kernel/kapi.h>
96 #endif
97
98 #if 0
99 # define DBG(a) diag_printf a
100 #else
101 # define DBG(a)
102 #endif
103
104 #undef FAILURES
105 #ifdef FAILURES
106 static volatile int ep1_failure = 7;
107 #endif
108
109 #undef STATS
110 #ifdef STATS
111 int ep1_receives = 0;
112 int ep1_errors = 0;
113 int ep2_transmits = 0;
114 int ep2_errors = 0;
115 # define INCR_STAT(a) (a) += 1
116 # define SET_STAT(a, b) (a) = (b)
117 #else
118 # define INCR_STAT(a)
119 # define SET_STAT(a, b)
120 #endif
121
122 // ----------------------------------------------------------------------------
123 // Serial port 0 on the SA11x0 provides a USB slave connection (aka a
124 // USB device controller or UDC). The functionality is somewhat
125 // limited, there are just three endpoints.
126 //
127 // Endpoint 0 can only be used for control messages. It has an 8 byte
128 // fifo which cannot be connected to a DMA engine. Hence incoming
129 // control packets have to be limited to 8 bytes by the enumeration
130 // data. The endpoint has to be managed at a low-level, i.e. the
131 // incoming request has to be extracted from the fifo, processed, and
132 // any response put back into the fifo within the permitted USB
133 // response times.
134 //
135 // Endpoint 1 can only be used for host->slave bulk OUT transfers. It
136 // has a 20 byte receive fifo, and it can be hooked up to any of the
137 // six DMA engines. Since bulk transfers will typically involve 64
138 // byte packets, most applications will require the use of DMA.
139 //
140 // Endpoint 2 can only be used for slave-host bulk IN transfers. There
141 // is a 16 byte transmit fifo so small messages can be transferred in
142 // software. The fifo can also be hooked up to DMA, which is a more
143 // likely scenario.
144 //
145 // Start with definitions of the hardware. The use of a structure and
146 // a const base pointer should allow the compiler to do base/offset
147 // addressing and keep the hardware base address in a register. This
148 // is better than defining each hardware register via a separate
149 // address. Although the registers are only a byte wide, the peripheral
150 // bus only supports word accesses.
151 //
152 // The USBS_CONTROL etc. macros allow for an alternative way of
153 // accessing the hardware if a better approach is presented, without
154 // having to rewrite all the code. Macros that correspond to registers
155 // are actually addresses, making it easier in the code to distinguish
156 // them from bit values: the & and * operators will just cancel out.
157
158 typedef struct usbs_sa11x0_hardware {
159     volatile int control;
160     volatile int address;
161     volatile int out_size;
162     volatile int in_size;
163     volatile int ep0_control;
164     volatile int ep1_control;
165     volatile int ep2_control;
166     volatile int ep0_data;
167     volatile int ep0_write_count;
168              int dummy1;
169     volatile int fifo;
170              int dummy2;
171     volatile int status;
172 } usbs_sa11x0_hardware;
173
174 static usbs_sa11x0_hardware* const usbs_sa11x0_base = (usbs_sa11x0_hardware* const) 0x80000000;
175 #define USBS_CONTROL    (&(usbs_sa11x0_base->control))
176 #define USBS_ADDRESS    (&(usbs_sa11x0_base->address))
177 #define USBS_OUT_SIZE   (&(usbs_sa11x0_base->out_size))
178 #define USBS_IN_SIZE    (&(usbs_sa11x0_base->in_size))
179 #define EP0_CONTROL     (&(usbs_sa11x0_base->ep0_control))
180 #define EP1_CONTROL     (&(usbs_sa11x0_base->ep1_control))
181 #define EP2_CONTROL     (&(usbs_sa11x0_base->ep2_control))
182 #define EP0_DATA        (&(usbs_sa11x0_base->ep0_data))
183 #define EP0_WRITE_COUNT (&(usbs_sa11x0_base->ep0_write_count))
184 #define EP1_DATA        (&(usbs_sa11x0_base->fifo))
185 #define EP2_DATA        (&(usbs_sa11x0_base->fifo))
186 #define USBS_STATUS     (&(usbs_sa11x0_base->status))
187
188 #define CONTROL_DISABLE                 (1 << 0)
189 #define CONTROL_ACTIVE                  (1 << 1)
190 // The meaning of bit 2 changed, see errata
191 #define CONTROL_RESUME_INTR             (1 << 2)
192 #define CONTROL_EP0_INTR                (1 << 3)
193 #define CONTROL_EP1_INTR                (1 << 4)
194 #define CONTROL_EP2_INTR                (1 << 5)
195 // The meaning of bit 6 also changed, see errata
196 #define CONTROL_SUSPEND_INTR            (1 << 6)
197 #define CONTROL_RESET_INTR              (1 << 7)
198
199 // Getting the control register settings right is a little bit tricky.
200 // Bit 0 is the disable bit so touching that is dangerous, and the
201 // other bits have inverted meanings i.e. 0 enables interrupts. The
202 // following macro encapsulates this.
203 #define CONTROL_ALL_INTR                0x00FC
204 #define CONTROL_INTR_ENABLE(bits)  ((~(bits)) & CONTROL_ALL_INTR)
205 #define CONTROL_INTR_CLEAR(bits)   ((bits) & CONTROL_ALL_INTR)
206
207 // All the endpoint interrupt numbers can be handled en masse,
208 // but some of the endpoints may be disabled.
209 #if defined(CYGPKG_DEVS_USB_SA11X0_EP1) && defined(CYGPKG_DEVS_USB_SA11X0_EP2)
210 # define CONTROL_EP_INTR_BITS      (CONTROL_EP0_INTR | CONTROL_EP1_INTR | CONTROL_EP2_INTR)
211 #elif defined(CYGPKG_DEVS_USB_SA11X0_EP1)
212 # define CONTROL_EP_INTR_BITS      (CONTROL_EP0_INTR | CONTROL_EP1_INTR)
213 #elif defined(CYGPKG_DEVS_USB_SA11X0_EP2)
214 # define CONTROL_EP_INTR_BITS      (CONTROL_EP0_INTR | CONTROL_EP2_INTR)
215 #else
216 # define CONTROL_EP_INTR_BITS      (CONTROL_EP0_INTR)
217 #endif
218
219 #define EP0_OUT_READY                   (1 << 0)
220 #define EP0_IN_READY                    (1 << 1)
221 #define EP0_SENT_STALL                  (1 << 2)
222 #define EP0_FORCE_STALL                 (1 << 3)
223 #define EP0_DATA_END                    (1 << 4)
224 #define EP0_SETUP_END                   (1 << 5)
225 #define EP0_SERVICED_OPR                (1 << 6)
226 #define EP0_SERVICED_SETUP_END          (1 << 7)
227
228 #define EP1_FIFO_SERVICE                (1 << 0)
229 #define EP1_PACKET_COMPLETE             (1 << 1)
230 #define EP1_PACKET_ERROR                (1 << 2)
231 #define EP1_SENT_STALL                  (1 << 3)
232 #define EP1_FORCE_STALL                 (1 << 4)
233 #define EP1_FIFO_NOT_EMPTY              (1 << 5)
234
235 #define EP2_FIFO_SERVICE                (1 << 0)
236 #define EP2_PACKET_COMPLETE             (1 << 1)
237 #define EP2_PACKET_ERROR                (1 << 2)
238 #define EP2_PACKET_UNDERRUN             (1 << 3)
239 #define EP2_SENT_STALL                  (1 << 4)
240 #define EP2_FORCE_STALL                 (1 << 5)
241
242 #define STATUS_EP0_INTR                 (1 << 0)
243 #define STATUS_EP1_INTR                 (1 << 1)
244 #define STATUS_EP2_INTR                 (1 << 2)
245 #define STATUS_SUSPEND_INTR             (1 << 3)
246 #define STATUS_RESUME_INTR              (1 << 4)
247 #define STATUS_RESET_INTR               (1 << 5)
248
249 #define EP0_FIFO_SIZE                     8
250 #define EP0_MTU                           8
251
252 #define EP1_FIFO_SIZE                   20
253 #ifdef CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL
254 # define EP1_MTU                        64
255 #else
256 # define EP1_MTU                        16
257 #endif
258
259 #define EP2_FIFO_SIZE                   16
260 #ifdef CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL
261 # define EP2_MTU                        64
262 #else
263 # define EP2_MTU                        16
264 #endif
265
266 #if defined(CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL) || defined(CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL)
267 typedef struct usbs_sa11x0_dma {
268     volatile int                address;
269     volatile int                control_set;
270     volatile int                control_clear;
271     volatile int                status;
272     volatile int                buf_a_address;  // Absolute, not remapped
273     volatile int                buf_a_size;
274     volatile int                buf_b_address;  // Absolute, not remapped
275     volatile int                buf_b_size;
276 } usbs_sa11x0_dma;
277
278 #define DMA_CONTROL_RUN                 (1 << 0)
279 #define DMA_CONTROL_INTR_ENABLE         (1 << 1)
280 #define DMA_STATUS_ERROR                (1 << 2)
281 #define DMA_STATUS_DONE_A               (1 << 3)
282 #define DMA_CONTROL_START_A             (1 << 4)
283 #define DMA_STATUS_DONE_B               (1 << 5)
284 #define DMA_CONTROL_START_B             (1 << 6)
285 #define DMA_STATUS_BUFFER_IN_USE        (1 << 7)
286 // All the bits that are useful to clear. BUFFER_IN_USE is read-only.
287 #define DMA_CONTROL_CLEAR_ALL           (DMA_CONTROL_RUN | DMA_CONTROL_INTR_ENABLE | DMA_STATUS_ERROR | \
288                                          DMA_STATUS_DONE_A | DMA_CONTROL_START_A | DMA_STATUS_DONE_B | DMA_CONTROL_START_B)
289
290 // The DMA engines operate eight-bytes at a time. This affects issues
291 // such as alignment.
292 #define DMA_BURST_SIZE                  8
293
294 // The DMA engines bypass the cache and MMU, accessing physical
295 // memory directly. Newer HALS should provide appropriate macros.
296 #ifndef HAL_VIRT_TO_PHYS_ADDRESS
297 # error HAL macros for translating between virtual and physical memory are required.
298 #endif
299
300 // Make absolutely sure that the two endpoints use different
301 // DMA channels. Right now this check cannot be done easily
302 // at the CDL level.
303 # if defined(CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL) && defined(CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL)
304 #  if (CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL == CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL)
305 #   error Different DMA channels must be selected for the two endpoints.
306 #  endif
307 # endif
308
309 # ifdef CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL
310 static usbs_sa11x0_dma* const ep1_dma_base = (usbs_sa11x0_dma* const)(0xB0000000 | (0x20 * CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL));
311 #  define EP1_DMA_ADDRESS        (&(ep1_dma_base->address))
312 #  define EP1_DMA_CONTROL_SET    (&(ep1_dma_base->control_set))
313 #  define EP1_DMA_CONTROL_CLEAR  (&(ep1_dma_base->control_clear))
314 #  define EP1_DMA_STATUS         (&(ep1_dma_base->status))
315 #  define EP1_DMA_BUF_A_ADDRESS  (&(ep1_dma_base->buf_a_address))
316 #  define EP1_DMA_BUF_A_SIZE     (&(ep1_dma_base->buf_a_size))
317 #  define EP1_DMA_BUF_B_ADDRESS  (&(ep1_dma_base->buf_b_address))
318 #  define EP1_DMA_BUF_B_SIZE     (&(ep1_dma_base->buf_b_size))
319
320 // The correct value for the DMA address register is fixed for USB transfers
321 // See table 11.6 of the SA1110 Advanced Developer's Manual
322 //   Device datum width == 1 byte
323 //   Device burst size  == 8 bytes
324 //   Device transfer direction == read (device->memory)
325 //   Endianness is controlled by the ARM architectural HAL package
326 #  ifdef CYGHWR_HAL_ARM_BIGENDIAN
327 #   define EP1_DMA_ADDRESS_VALUE        (0x80000A00 | 0x10 | 0x0 | 0x4 | 0x2 | 0x1)
328 #  else
329 #   define EP1_DMA_ADDRESS_VALUE        (0x80000A00 | 0x10 | 0x0 | 0x4 | 0x0 | 0x1)
330 #  endif
331 # endif // EP1_DMA
332
333 # ifdef CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL
334
335 static usbs_sa11x0_dma* const ep2_dma_base = (usbs_sa11x0_dma* const)(0xB0000000 | (0x20 * CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL));
336 #  define EP2_DMA_ADDRESS        (&(ep2_dma_base->address))
337 #  define EP2_DMA_CONTROL_SET    (&(ep2_dma_base->control_set))
338 #  define EP2_DMA_CONTROL_CLEAR  (&(ep2_dma_base->control_clear))
339 #  define EP2_DMA_STATUS         (&(ep2_dma_base->status))
340 #  define EP2_DMA_BUF_A_ADDRESS  (&(ep2_dma_base->buf_a_address))
341 #  define EP2_DMA_BUF_A_SIZE     (&(ep2_dma_base->buf_a_size))
342 #  define EP2_DMA_BUF_B_ADDRESS  (&(ep2_dma_base->buf_b_address))
343 #  define EP2_DMA_BUF_B_SIZE     (&(ep2_dma_base->buf_b_size))
344
345 #  ifdef CYGHWR_HAL_ARM_BIGENDIAN
346 #   define EP2_DMA_ADDRESS_VALUE        (0x80000A00 | 0x00 | 0x0 | 0x4 | 0x2 | 0x0)
347 #  else
348 #   define EP2_DMA_ADDRESS_VALUE        (0x80000A00 | 0x00 | 0x0 | 0x4 | 0x0 | 0x0)
349 #  endif
350 # endif // EP2_DMA
351
352 #endif  // EP1_DMA || EP2_DMA
353
354 // ----------------------------------------------------------------------------
355 // Static data. There is a data structure for each endpoint. The
356 // implementation is essentially a private class that inherits from
357 // common classes for control and data endpoints, but device drivers
358 // are supposed to be written in C so some ugliness is required.
359 //
360 // Devtab entries are defined in usbs_sa11x0_data.cxx to make sure
361 // that the linker does not garbage-collect them.
362
363 // Support for the interrupt handling code.
364 static cyg_interrupt usbs_sa11x0_intr_data;
365 static cyg_handle_t  usbs_sa11x0_intr_handle;
366 static volatile int  isr_status_bits    = 0;
367
368 // Endpoint 0 is always present, this module would not get compiled
369 // otherwise.
370 static void usbs_sa11x0_ep0_start(usbs_control_endpoint*);
371 static void usbs_sa11x0_poll(usbs_control_endpoint*);
372
373 typedef enum ep0_state {
374     EP0_STATE_IDLE      = 0,
375     EP0_STATE_IN        = 1,
376     EP0_STATE_OUT       = 2
377 } ep0_state;
378
379 typedef struct ep0_impl {
380     usbs_control_endpoint   common;
381     ep0_state               ep_state;
382     int                     length;
383     int                     transmitted;
384 } ep0_impl;
385
386 static ep0_impl ep0 = {
387     common:
388     {
389         state:                  USBS_STATE_POWERED, // The hardware does not distinguish  between detached, attached and powered.
390         enumeration_data:       (usbs_enumeration_data*) 0,
391         start_fn:               &usbs_sa11x0_ep0_start,
392         poll_fn:                &usbs_sa11x0_poll,
393         interrupt_vector:       SA11X0_IRQ_USB_SERVICE_REQUEST,
394         control_buffer:         { 0, 0, 0, 0, 0, 0, 0, 0 },
395         state_change_fn:        (void (*)(usbs_control_endpoint*, void*, usbs_state_change, int)) 0,
396         state_change_data:      (void*) 0,
397         standard_control_fn:    (usbs_control_return (*)(usbs_control_endpoint*, void*)) 0,
398         standard_control_data:  (void*) 0,
399         class_control_fn:       (usbs_control_return (*)(usbs_control_endpoint*, void*)) 0,
400         class_control_data:     (void*) 0,
401         vendor_control_fn:      (usbs_control_return (*)(usbs_control_endpoint*, void*)) 0,
402         vendor_control_data:    (void*) 0,
403         reserved_control_fn:    (usbs_control_return (*)(usbs_control_endpoint*, void*)) 0,
404         reserved_control_data:  (void*) 0,
405         buffer:                 (unsigned char*) 0,
406         buffer_size:            0,
407         fill_buffer_fn:         (void (*)(usbs_control_endpoint*)) 0,
408         fill_data:              (void*) 0,
409         fill_index:             0,
410         complete_fn:            (usbs_control_return (*)(usbs_control_endpoint*, int)) 0
411     },
412     ep_state:           EP0_STATE_IDLE,
413     length:             0,
414     transmitted:        0
415 };
416
417 extern usbs_control_endpoint usbs_sa11x0_ep0 __attribute__((alias ("ep0")));
418
419 // Endpoint 1 is optional. If the application only involves control
420 // messages or only slave->host transfers then the endpoint 1
421 // support can be disabled.
422 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
423
424 typedef struct ep1_impl {
425     usbs_rx_endpoint    common;
426     int                 fetched;
427     cyg_bool            using_buf_a;
428 } ep1_impl;
429
430 static void ep1_start_rx(usbs_rx_endpoint*);
431 static void ep1_set_halted(usbs_rx_endpoint*, cyg_bool);
432
433 static ep1_impl ep1 = {
434     common: {
435         start_rx_fn:        &ep1_start_rx,
436         set_halted_fn:      &ep1_set_halted,
437         complete_fn:        (void (*)(void*, int)) 0,
438         complete_data:      (void*) 0,
439         buffer:             (unsigned char*) 0,
440         buffer_size:        0,
441         halted:             0,
442     },
443     fetched:            0,
444     using_buf_a:        0
445 };
446
447 extern usbs_rx_endpoint usbs_sa11x0_ep1 __attribute__((alias ("ep1")));
448 #endif
449
450 // Endpoint 2 is optional. If the application only involves control
451 // messages or only host->slave transfers then the endpoint 2 support
452 // can be disabled.
453 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
454
455 typedef struct ep2_impl {
456     usbs_tx_endpoint        common;
457     int                     transmitted;
458     int                     pkt_size;
459 } ep2_impl;
460
461 static void ep2_start_tx(usbs_tx_endpoint*);
462 static void ep2_set_halted(usbs_tx_endpoint*, cyg_bool);
463
464 static ep2_impl ep2 = {
465     common: {
466         start_tx_fn:        &ep2_start_tx,
467         set_halted_fn:      &ep2_set_halted,
468         complete_fn:        (void (*)(void*, int)) 0,
469         complete_data:      (void*) 0,
470         buffer:             (const unsigned char*) 0,
471         buffer_size:        0,
472         halted:             0,
473     }, 
474     transmitted:        0,
475     pkt_size:           0
476 };
477
478 extern usbs_tx_endpoint usbs_sa11x0_ep2 __attribute__ ((alias ("ep2")));
479
480 #endif
481
482 // ----------------------------------------------------------------------------
483 // Hardware problem: experiments indicate that manipulating the USB
484 // controller registers does not always work as expected. The control
485 // fifo is especially badly affected, with e.g. writes just being lost
486 // completely. It is necessary to work around these problems using
487 // retry loops. MAX_RETRIES controls the total number of attempts to
488 // access a register. MAX_CHECKS controls the number of times a
489 // register is checked to determine whether or not the attempt has
490 // been succesful. These constants are used to access the data fifo,
491 // so MAX_RETRIES has to be > 20 bytes.
492 #define MAX_RETRIES     32
493 #define MAX_CHECKS       8
494
495 // Write one or more bits to a register. This should result in some
496 // bits ending up set and other bits ending up clear. Some register
497 // bits are write-1-to-clear or may have side effects.
498 static cyg_bool
499 usbs_sa11x0_poke(volatile int* addr, int value, int should_be_set, int should_be_clear)
500 {
501     cyg_bool    result  = false;
502     int         retries, checks;
503         
504     for (retries = 0; !result && (retries < MAX_RETRIES); retries++) {
505         *addr = value;
506         (void) *addr;   // The first read is always invalid.
507         for (checks = 0; !result && (checks < MAX_CHECKS); checks++) {
508             int current_value = *addr;
509             if (should_be_set != (should_be_set & current_value)) {
510                 continue;
511             }
512             if ((0 != should_be_clear) && (0 != (should_be_clear & current_value))) {
513                 continue;
514             }
515             result = true;
516         }
517     }
518     if (!result) {
519         DBG(("usbs_sa11x0_poke failed: addr %x, value %x, should_be_set %x, should_be_clear %x, actual %x\n", \
520              (int) addr, value, should_be_set, should_be_clear, *addr));
521     }
522     return result;
523 }
524
525 // Write a whole value to a register, rather than just manipulating
526 // individual bits.
527 static cyg_bool
528 usbs_sa11x0_poke_value(volatile int* addr, int value)
529 {
530     cyg_bool    result  = false;
531     int         retries, checks;
532         
533     for (retries = 0; !result && (retries < MAX_RETRIES); retries++) {
534         *addr = value;
535         (void) *addr;   // The first read is always invalid.
536         for (checks = 0; !result && (checks < MAX_CHECKS); checks++) {
537             if (value == *addr) {
538                 result = true;
539             }
540         }
541     }
542     if (!result) {
543         DBG(("usbs_sa11x0_poke_value failed: addr %x, value %x, actual %x\n", (int) addr, value, *addr));
544     }
545     return result;
546 }
547
548
549 // ----------------------------------------------------------------------------
550 // Control transfers
551 //
552 // Endpoint 0 is rather more complicated than the others. This is
553 // partly due to the nature of the control protocol, for example it is
554 // bidirectional and transfer sizes are unpredictable.
555 //
556 // The USB standard imposes some timing constraints on endpoint 0, see
557 // section 9.2.6 of the spec. For example the set-address operation is
558 // supposed to take at most 50ms. In general the timings are reasonably
559 // generous so no special action is taken here. There could be problems
560 // when debugging, but that is pretty much inevitable.
561 //
562 // It is necessary to maintain a state for the control endpoint, the
563 // default state being idle. Control operations involve roughly the
564 // following sequence of events:
565 //
566 // 1) the host transmits a special setup token, indicating the start
567 //    of a control operation and possibly cancelling any existing control
568 //    operation that may be in progress. USB peripherals cannot NAK this
569 //    even if they are busy.
570 //
571 // 2) the setup operation is followed by an eight-byte packet from the host
572 //    that describes the specific control operation. This fits into the
573 //    SA11X0's eight-byte control fifo. There will be an endpoint 0
574 //    interrupt with the out-packet-ready bit set. If the setup token
575 //    was sent while a previous control operation was also in progress
576 //    then the setup-end bit will be set as well.
577 //
578 // 3) the eight-byte packet is described in section 9.3 of the USB spec.
579 //    The first byte holds three fields, with the top bit indicating the
580 //    direction of subsequent data transfer. There are also two bytes
581 //    specifying the size of the subsequent transfer. Obviously the
582 //    packet also contains information such as the request type.
583 //
584 //    If the specified size is zero then the endpoint will remain in
585 //    its idle state. Otherwise the endpoint will switch to either
586 //    IN or OUT state, depending on the direction of subsequent
587 //    transfers.
588 // 
589 // 4) some standard control operations can be handled by the code
590 //    here. Set-address involves poking the address register and
591 //    a change of state. Set-feature and clear-feature on the
592 //    data endpoints can be used in conjunction with endpoint-halt.
593 //    Get-status on the data endpoints tests the halt condition.
594 //    It is also possible for the hardware-specific code to
595 //    implement set-feature, clear-feature and get-status
596 //    for the device as a whole since the SA11x0 always has to
597 //    be self-powered and is incapable of initiating a remote
598 //    wakeup.
599 //
600 //    Other standard control operations will be handled by the
601 //    application-specific installed handler, if any, or by the
602 //    default handler usbs_handle_standard_control(). Class-specific
603 //    and vendor-specific functions require appropriate handlers to be
604 //    installed as well, If a particular request is not recognized
605 //    then a stall condition should be raised. This will not prevent
606 //    subsequent control operations, just the current one.
607 //
608 //    Data transfers on endpoint 0 involve at most eight bytes at
609 //    a time. More data will only be accepted if the out-packet-ready
610 //    bit has been cleared via the serviced-opr bit, with the
611 //    hardware nak'ing OUT requests. To send data back to the host
612 //    the FIFO should be filled and then the in-packet-ready bit
613 //    should be set.
614 //
615 // It looks like processing all control packets at DSR level should be
616 // sufficient. During the data phase the hardware will NAK IN and
617 // OUT requests if the fifo is still empty/full, so timing is not
618 // an issue. Timing after receipt of the initial control message
619 // may be more important, e.g. the 50ms upper limit on processing
620 // the set-address control message, but this should still be ok.
621 // This decision may have to be re-examined in the light of
622 // experience.
623
624 // Init may get called during system startup or following a reset.
625 // During startup no work is needed since the hardware will
626 // have been reset and everything should be fine. After a reset
627 // the hardware will also be ok but there may be state information
628 // in ep0 that needs to be reset.
629 static void
630 usbs_sa11x0_ep0_init(void)
631 {
632     if ((EP0_STATE_IDLE != ep0.ep_state) &&
633         ((usbs_control_return (*)(usbs_control_endpoint*, int)) 0 != ep0.common.complete_fn)) {
634         (*ep0.common.complete_fn)(&ep0.common, -EPIPE);
635     }
636     ep0.common.state            = USBS_STATE_POWERED;
637     memset(ep0.common.control_buffer, 0, 8);
638     ep0.common.buffer           = (unsigned char*) 0;
639     ep0.common.buffer_size      = 0;
640     ep0.common.fill_buffer_fn   = (void (*)(usbs_control_endpoint*)) 0;
641     ep0.common.fill_data        = (void*) 0;
642     ep0.common.fill_index       = 0;
643     ep0.common.complete_fn      = (usbs_control_return (*)(usbs_control_endpoint*, int)) 0;
644     ep0.ep_state                = EP0_STATE_IDLE;
645     ep0.length                  = 0;
646     ep0.transmitted             = 0;
647 }
648
649 // The start function is called by higher-level code when things have
650 // been set up, i.e. the enumeration data is available, appropriate
651 // handlers have been installed for the different types of control
652 // messages, and communication with the host is allowed to start. The
653 // next event that should happen is a reset operation from the host,
654 // so all other interrupts should be blocked. However it is likely
655 // that the hardware will detect a suspend state before the reset
656 // arrives, and hence the reset will act as a resume as well as a
657 // reset.
658 static void
659 usbs_sa11x0_ep0_start(usbs_control_endpoint* endpoint)
660 {
661     CYG_ASSERT( endpoint == &ep0.common, "USB startup involves the wrong endpoint");
662     
663     // Activate the hardware. Write a 0 to the enable/disable bit 0.
664     // Bit 1 is read-only. The other bits are set to 1 to disable
665     // the corresponding interrupt source.
666     usbs_sa11x0_poke(USBS_CONTROL, CONTROL_ALL_INTR, CONTROL_ALL_INTR, 0);
667
668     // If there is additional platform-specific initialization to
669     // perform, do it now. This macro can come from the platform HAL.
670 #ifdef SA11X0_USB_PLATFORM_INIT
671     SA11X0_USB_PLATFORM_INIT;
672 #endif
673         
674     // Clear any pending interrupts. There should not be any, but just
675     // in case. Note: passing 0x00FF as the should_be_clear argument
676     // is a race condition, an external event can happen at any time,
677     // so we may loop unnecessarily and lose an interrupt. However
678     // the initial reset should last for 10ms.
679     usbs_sa11x0_poke(USBS_STATUS, 0x00FF, 0x00, 0x00FF);
680
681     // The only interrupt really of interest right now is reset, but
682     // it is likely to be preceded by a resume. 
683     usbs_sa11x0_poke(USBS_CONTROL,
684                      CONTROL_INTR_ENABLE(CONTROL_RESET_INTR | CONTROL_RESUME_INTR),
685                      0,
686                      CONTROL_INTR_CLEAR(CONTROL_RESET_INTR | CONTROL_RESUME_INTR));
687 }
688
689
690 // Filling the fifo with a reply to the host. This can be called
691 // immediately at the end of a control message, to prepare for
692 // the next IN token. It will also get called after each subsequent
693 // IN operation when the fifo has been emptied.
694 //
695 // Experiments have indicated serious problems with the control fifo:
696 // some writes to the fifo just get lost completely. The failure rate
697 // is sufficiently high that more often than not the host will be
698 // unable to read all the enumeration data. However, the write-count
699 // register appears to give a valid indication of the current fifo
700 // contents. This means the code can retry stuffing a particular byte
701 // into the fifo until the write-count goes up.
702
703 static void
704 usbs_sa11x0_ep0_fill_fifo(void)
705 {
706     cyg_bool ok     = true;
707     int filled      = 0;
708     int max;
709     int fifo_count  = *EP0_WRITE_COUNT;
710     int bits_to_set = 0;
711     
712     // The host can interrupt the current control message at any time
713     // with a new one. In practice this is unlikely, things could get
714     // rather confused on the host side. However if a control message
715     // has been received then the fifo should obviously not be filled.
716     // A new control message is indicated by the SETUP_END bit.
717     //
718     // The hardware design means that there is a race condition: the
719     // new control message can come in at any time, even in the middle
720     // of filling the fifo. Checking the SETUP_END more often would
721     // reduce the probability of things getting messed up, but not
722     // eliminate it.
723     //
724     // There is a check for SETUP_END at the start of the DSR, so
725     // the setting of this bit should have resulted in another ISR
726     // and another DSR being scheduled. Hence there is no need for
727     // special action here.
728     if (0 != (*EP0_CONTROL & EP0_SETUP_END)) {
729         DBG(("EP0_fill_fifo(), interrupted by SETUP_END\n"));
730         return;
731     }
732
733     // There should never be any data in the fifo. Any such data could
734     // be the remnant of a previous transfer to the host, but that
735     // should all have gone out already. Alternatively it could be
736     // incoming data, but that means a new control message.
737     if (0 != fifo_count) {
738         DBG(("EP0_fill_fifo(), fifo already contains %d bytes", fifo_count));
739         return;
740     }
741
742     // The IN_READY bit should never be set on entry. It can only get
743     // set by a previous call to fill_fifo(), and the data should
744     // have gone out before we get back here.
745     if (0 != (*EP0_CONTROL & EP0_IN_READY)) {
746         DBG(("EP0 fill_fifo(), in-packet-ready bit already set, state %x\n", *EP0_CONTROL));
747         return;
748     }
749
750     // Now put up to another eight bytes into the fifo.
751     max = ((ep0.length - ep0.transmitted) > EP0_FIFO_SIZE) ? EP0_FIFO_SIZE : (ep0.length - ep0.transmitted);
752     while (ok && (filled < max)) {
753         if (0 != ep0.common.buffer_size) {
754             int         datum;
755             int         retries, checks;
756             cyg_bool    written;
757
758             datum       = *ep0.common.buffer++;
759             ep0.common.buffer_size--;
760             written     = false;
761             
762             for (retries = 0; ok && !written && (retries < MAX_RETRIES); retries++) {
763                 if (filled != *EP0_WRITE_COUNT) {
764                     DBG(("EP0 fill_fifo, inconsistency, written %d but write count %d\n", filled, *EP0_WRITE_COUNT));
765                     ok = false;
766                 }
767                 *EP0_DATA = datum;
768                 // The write-count may take a few cycles to settle down.
769                 for (checks = 0; !written && (checks < MAX_CHECKS); checks++) {
770                     if (filled < *EP0_WRITE_COUNT) {
771                         filled++;
772                         written = true;
773                         // DBG(("Transferred %d byte (%x) after %d checks, %d retries\n", filled - 1, datum, checks, retries));
774                     }
775                 }
776             }
777         } else if ((void (*)(usbs_control_endpoint*))0 != ep0.common.fill_buffer_fn) {
778             (*ep0.common.fill_buffer_fn)(&ep0.common);
779         } else {
780             break;
781         }
782     }
783
784     // At this point either it has proved impossible to fill the fifo,
785     // e.g. because of a new control message, or up to another eight
786     // bytes have been sent. 
787     if (!ok) {
788         if (0 == (EP0_SETUP_END & *EP0_CONTROL)) {
789             // There is something seriously wrong.
790             DBG(("ep0_fill_fifo(), failed, only filled %d bytes, status %x\n", filled, *EP0_CONTROL));
791             usbs_sa11x0_poke(EP0_CONTROL, EP0_FORCE_STALL, EP0_FORCE_STALL, 0);
792         }
793         return;
794     }
795
796     // The following conditions are possible:
797     // 1) amount transferred == amount requested, transfer complete.
798     // 2) amount transferred < amount requested, this fill involved
799     //    <eight bytes, transfer complete by definition of the protocol.
800     // 3) amount transferred < amount requested but exactly eight
801     //    bytes were sent this time. It will be necessary to send
802     //    another packet of zero bytes to complete the transfer.
803     ep0.transmitted += filled;
804     if ((ep0.transmitted == ep0.length) || (filled < EP0_FIFO_SIZE)) {
805
806         ep0.ep_state    = EP0_STATE_IDLE;
807         if ((usbs_control_return (*)(usbs_control_endpoint*, int))0 != ep0.common.complete_fn) {
808             (void) (*ep0.common.complete_fn)(&ep0.common, 0);
809         }
810         ep0.common.buffer               = (unsigned char*) 0;
811         ep0.common.buffer_size          = 0;
812         ep0.common.fill_buffer_fn       = (void (*)(usbs_control_endpoint*)) 0;
813
814         // This informs the hardware that the control message has been
815         // handled.
816         bits_to_set = EP0_DATA_END;
817     }
818     
819     // This allows another IN operation to empty the fifo.
820     bits_to_set |= EP0_IN_READY;
821     usbs_sa11x0_poke(EP0_CONTROL, bits_to_set, bits_to_set, 0);
822 }
823
824 // Another utility function to empty the fifo. This involves similar
825 // hardware problems to writing, it is possible to read a byte without
826 // changing the fifo state so that next time the same byte would be
827 // read again. Again there is a possible race condition if another
828 // control message arrives while emptying the fifo.
829 static int
830 usbs_sa11x0_ep0_empty_fifo(unsigned char* buf)
831 {
832     int         count   = *EP0_WRITE_COUNT & 0x00FF;
833     int         emptied = 0;
834     cyg_bool    ok      = true;
835
836     CYG_ASSERT( (count >= 0) & (count <= 8), "EP0 write count must be in range");
837
838     while (ok && (emptied < count)) {
839         int      retries, checks;
840         cyg_bool read   = false;
841
842         for (retries = 0; !read && (retries < MAX_RETRIES); retries++) {
843             if ((count - emptied) != *EP0_WRITE_COUNT) {
844                 DBG(("EP0_empty_fifo, inconsistency, read %d bytes of %d, but fifo count %d\n", emptied, count, *EP0_WRITE_COUNT));
845                 ok = false;
846             } else {
847                 buf[emptied] = *EP0_DATA;
848                 for (checks = 0; !read && (checks < MAX_CHECKS); checks++) {
849                     if ((count - emptied) > *EP0_WRITE_COUNT) {
850                         //DBG(("Read %d byte (%x) after %d checks, %d retries\n", emptied, buf[emptied], checks, retries));
851                         read = true;
852                         emptied++;
853                     }
854                 }
855             }
856         }
857         if (ok && !read) {
858             DBG(("EP0 empty fifo, failed to read byte from fifo\n"));
859             ok = false;
860         }
861     }
862     
863     return emptied;
864 }
865
866 // This is where all the hard work happens. It is a very large routine
867 // for a DSR, but in practice nearly all of it is nested if's and very
868 // little code actually gets executed. Note that there may be
869 // invocations of callback functions and the driver has no control
870 // over how much time those will take, but those callbacks should be
871 // simple.
872 static void
873 usbs_sa11x0_ep0_dsr(void)
874 {
875     int hw_state = *EP0_CONTROL;
876
877     // Handle the stall bits.
878     //
879     // Force-stall should not be a problem. It is set by the code here
880     // if the host needs to be told that the control message was
881     // unacceptable and is cleared automatically by the hardware after
882     // the stall is sent.
883     // NOTE: it is not clear the hardware actually works in this
884     // respect. The FORCE_STALL bit has been observed still set during
885     // the next interrupt, and the host appears to receive spurious
886     // data back in response to the next control packet.
887     //
888     // Sent-stall is set by the hardware following a protocol
889     // violation, e.g. if there is an IN token when a new control
890     // message is expected. There is nothing the software can do about
891     // this. However if we are in the middle of an IN or OUT transfer
892     // then those are not going to complete successfully.
893     if (0 != (hw_state & EP0_SENT_STALL)) {
894         if (EP0_STATE_IDLE != ep0.ep_state) {
895             if ((usbs_control_return (*)(usbs_control_endpoint*, int))0 != ep0.common.complete_fn) {
896                 (*ep0.common.complete_fn)(&ep0.common, -EIO);
897             }
898             ep0.ep_state                = EP0_STATE_IDLE;
899             ep0.common.buffer           = (unsigned char*) 0;
900             ep0.common.buffer_size      = 0;
901             ep0.common.fill_buffer_fn   = 0;
902             ep0.common.complete_fn      = (usbs_control_return (*)(usbs_control_endpoint*, int)) 0;
903         }
904         usbs_sa11x0_poke(EP0_CONTROL, EP0_SENT_STALL, 0, EP0_SENT_STALL);
905     }   // STALL condition
906     
907     // Next, check whether we have received a new control message
908     // while still busy processing an old one.
909     if (0 != (hw_state & EP0_SETUP_END)) {
910         if (EP0_STATE_IDLE != ep0.ep_state) {
911             if ((usbs_control_return (*)(usbs_control_endpoint*, int)) 0 != ep0.common.complete_fn) {
912                 (*ep0.common.complete_fn)(&ep0.common, -EIO);
913             }
914             ep0.ep_state                = EP0_STATE_IDLE;
915             ep0.common.buffer           = (unsigned char*) 0;
916             ep0.common.buffer_size      = 0;
917             ep0.common.fill_buffer_fn   = 0;
918             ep0.common.complete_fn      = (usbs_control_return (*)(usbs_control_endpoint*, int)) 0;
919         }
920         // We are now back in idle state so the control message will be
921         // extracted and processed.
922         usbs_sa11x0_poke(EP0_CONTROL, EP0_SERVICED_SETUP_END, 0, EP0_SETUP_END);
923     }   // Interrupted control transaction
924
925     // The endpoint can be in one of three states: IN, OUT, or IDLE.
926     // For the first two it should mean that there is more data to be
927     // transferred, which is pretty straightforward. IDLE means
928     // that a new control message has arrived.
929     if ((EP0_STATE_IN == ep0.ep_state) && (0 == (EP0_IN_READY & hw_state)))  {
930         
931         usbs_sa11x0_ep0_fill_fifo();
932         
933     } else if ((EP0_STATE_OUT == ep0.ep_state) && (0 != (EP0_OUT_READY & hw_state))) {
934
935         // A host->device transfer. Higher level code must have
936         // provided a suitable buffer.
937         CYG_ASSERT( (unsigned char*)0 != ep0.common.buffer, "A receive buffer should have been provided" );
938
939         ep0.transmitted += usbs_sa11x0_ep0_empty_fifo(ep0.common.buffer + ep0.transmitted);
940
941         if (ep0.transmitted != ep0.length) {
942             // The host is not allowed to send more data than it
943             // indicated in the original control message, and all
944             // messages until the last one should be full size.
945             CYG_ASSERT( ep0.transmitted < ep0.length, "The host must not send more data than expected");
946             CYG_ASSERT( 0 == (ep0.transmitted % EP0_FIFO_SIZE), "All OUT packets until the last one should be full-size");
947
948             usbs_sa11x0_poke(EP0_CONTROL, EP0_SERVICED_OPR, 0, EP0_OUT_READY);
949         } else {
950             // The whole transfer is now complete. Invoke the
951             // completion function, and based on its return value
952             // either generate a stall or complete the message.
953             usbs_control_return result;
954             
955             CYG_ASSERT( (usbs_control_return (*)(usbs_control_endpoint*, int))0 != ep0.common.complete_fn, \
956                         "A completion function should be provided for OUT control messages");
957
958             result = (*ep0.common.complete_fn)(&ep0.common, 0);
959             ep0.common.buffer           = (unsigned char*) 0;
960             ep0.common.buffer_size      = 0;
961             ep0.common.complete_fn      = (usbs_control_return (*)(usbs_control_endpoint*, int)) 0;
962             
963             if (USBS_CONTROL_RETURN_HANDLED == result) {
964                 usbs_sa11x0_poke(EP0_CONTROL,
965                                  EP0_SERVICED_OPR | EP0_DATA_END,
966                                  EP0_DATA_END,
967                                  EP0_OUT_READY);
968             } else {
969                 usbs_sa11x0_poke(EP0_CONTROL,
970                                  EP0_SERVICED_OPR | EP0_DATA_END | EP0_FORCE_STALL,
971                                  EP0_FORCE_STALL,
972                                  EP0_OUT_READY);
973             }
974             // Also remember to switch back to IDLE state 
975             ep0.ep_state = EP0_STATE_IDLE;
976         }
977         
978     } else if (0 != (EP0_OUT_READY & hw_state)) {
979
980         int emptied = usbs_sa11x0_ep0_empty_fifo(ep0.common.control_buffer);
981         
982         if (8 != emptied) {
983             // This indicates a serious problem somewhere. Respond by
984             // stalling. Hopefully the host will take some action that
985             // sorts out the mess.
986             usbs_sa11x0_poke(EP0_CONTROL,
987                              EP0_SERVICED_OPR | EP0_DATA_END | EP0_FORCE_STALL,
988                              EP0_FORCE_STALL,
989                              EP0_OUT_READY);
990             
991         } else {
992             usbs_control_return result  = USBS_CONTROL_RETURN_UNKNOWN;
993             usb_devreq*         req     = (usb_devreq*) ep0.common.control_buffer;
994             int length, direction, protocol, recipient;
995             
996             // Now we need to do some decoding of the data. A non-zero
997             // length field indicates that there will be a subsequent
998             // IN or OUT phase. The direction is controlled by the
999             // top bit of the first byte. The protocol is determined
1000             // by other bits of the top byte.
1001             length      = (req->length_hi << 8) | req->length_lo;
1002             direction   = req->type & USB_DEVREQ_DIRECTION_MASK;
1003             protocol    = req->type & USB_DEVREQ_TYPE_MASK;
1004             recipient   = req->type & USB_DEVREQ_RECIPIENT_MASK;
1005
1006 #if 0
1007             DBG(("ep0, new control request: type %x, code %x\n", req->type, req->request));
1008             DBG(("     %s, length %d, value hi %x lo %x, index hi %x lo %x\n",
1009                  (USB_DEVREQ_DIRECTION_OUT == direction) ? "out" : "in",
1010                  length, req->value_hi, req->value_lo, req->index_hi, req->index_lo));
1011 #endif            
1012             if (0 != length){
1013                 // Clear the fifo straightaway. There is no harm in
1014                 // doing this here. It may or may not do some good.
1015                 usbs_sa11x0_poke(EP0_CONTROL, EP0_SERVICED_OPR, 0, EP0_OUT_READY);
1016             }
1017             
1018             if (USB_DEVREQ_TYPE_STANDARD == protocol) {
1019                 
1020                 // First see if the request can be handled entirely in
1021                 // this module.
1022                 if (USB_DEVREQ_SET_ADDRESS == req->request) {
1023                     // The USB device address should be in value_lo.
1024                     // No more data is expected. 
1025                     int address = req->value_lo;
1026                     if ((0 != length) || (address > 127)) {
1027                         result = USBS_CONTROL_RETURN_STALL;
1028                     } else {
1029                         // poke_value() cannot be used here because
1030                         // setting the address does not take effect
1031                         // until the status phase.
1032                         *USBS_ADDRESS = address;
1033                         result = USBS_CONTROL_RETURN_HANDLED;
1034                     }
1035                 } else if (USB_DEVREQ_GET_STATUS == req->request) {
1036                     // GET_STATUS on the device as a whole is used to
1037                     // check the remote-wakeup and self-powered bits.
1038                     // GET_STATUS on an endpoint is used to determine
1039                     // the halted condition.
1040                     // GET_STATUS on anything else has to be left to
1041                     // other code.
1042                     if (USB_DEVREQ_RECIPIENT_DEVICE == recipient) {
1043                         // The host should expect two bytes back.
1044                         if ((2 == length) && (USB_DEVREQ_DIRECTION_IN == direction)) {
1045                             ep0.common.control_buffer[0] = 0;   // Not self-powered, no remote wakeup
1046                             ep0.common.control_buffer[1] = 0;
1047                             ep0.common.buffer            = ep0.common.control_buffer;
1048                             ep0.common.buffer_size       = 2;
1049                             result                       = USBS_CONTROL_RETURN_HANDLED;
1050                         } else {
1051                             result = USBS_CONTROL_RETURN_STALL;
1052                         }
1053                         
1054                     } else if (USB_DEVREQ_RECIPIENT_ENDPOINT == recipient) {
1055                         if ((2 == length) && (USB_DEVREQ_DIRECTION_IN == direction)) {
1056                             int endpoint = req->index_lo;
1057                             if (0 == endpoint) {
1058                                 // get-status on endpoint 0 is either undefined or always valid.
1059                                 // endpoint 0 is always up.
1060                                 ep0.common.control_buffer[0] = 0;
1061                                 result = USBS_CONTROL_RETURN_HANDLED;
1062                             }
1063 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
1064                             else if (((USB_DEVREQ_INDEX_DIRECTION_OUT | 1) == endpoint) &&
1065                                        (USBS_STATE_CONFIGURED == (ep0.common.state & USBS_STATE_MASK))) {
1066                                 
1067                                 ep0.common.control_buffer[0] = ep1.common.halted;
1068                                 result = USBS_CONTROL_RETURN_HANDLED;
1069
1070                             }
1071 #endif                            
1072 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
1073                             else if (((USB_DEVREQ_INDEX_DIRECTION_IN | 2) == endpoint) &&
1074                                        (USBS_STATE_CONFIGURED == (ep0.common.state & USBS_STATE_MASK))) {
1075
1076                                 ep0.common.control_buffer[0] = ep2.common.halted;
1077                                 result = USBS_CONTROL_RETURN_HANDLED;
1078                                 
1079                             }
1080 #endif                            
1081                             else {
1082                                 // An invalid endpoint has been specified or the
1083                                 // endpoint can only be examined in configured state.
1084                                 result = USBS_CONTROL_RETURN_STALL;
1085                             }
1086                             if (USBS_CONTROL_RETURN_HANDLED == result) {
1087                                 ep0.common.control_buffer[1] = 0;
1088                                 ep0.common.buffer            = ep0.common.control_buffer;
1089                                 ep0.common.buffer_size       = 2;
1090                             }
1091                         } else {
1092                             result = USBS_CONTROL_RETURN_STALL;
1093                         }
1094                     } // Endpoint or device get-status
1095                     
1096                 } else if (USB_DEVREQ_CLEAR_FEATURE == req->request) {
1097
1098                     // CLEAR_FEATURE operates in much the same way as
1099                     // GET_STATUS
1100                     if (USB_DEVREQ_RECIPIENT_DEVICE == recipient) {
1101                         
1102                         // No data should be transferred, and only remote-wakeup can be cleared.
1103                         if ((0 != length) || (USB_DEVREQ_FEATURE_DEVICE_REMOTE_WAKEUP != req->value_lo)) {
1104                             result = USBS_CONTROL_RETURN_STALL;
1105                         } else {
1106                             // Clearing remote-wakeup is a no-op.
1107                             result = USBS_CONTROL_RETURN_HANDLED;
1108                         }
1109
1110                     } else if (USB_DEVREQ_RECIPIENT_ENDPOINT == recipient) {
1111                         // The only feature that can be cleared is endpoint-halt, no data should be transferred.
1112                         if ((0 != length) || (USB_DEVREQ_FEATURE_ENDPOINT_HALT != req->value_lo)) {
1113                             result = USBS_CONTROL_RETURN_STALL;
1114                         } else {
1115                             int endpoint = req->index_lo;
1116                             if (0 == endpoint) {
1117                                 // Clearing halt on endpoint 0 is always a no-op since that endpoint cannot be halted
1118                             }
1119 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
1120                             else if (((USB_DEVREQ_INDEX_DIRECTION_OUT | 1) == endpoint) &&
1121                                        (USBS_STATE_CONFIGURED == (ep0.common.state & USBS_STATE_MASK))) {
1122                                 ep1_set_halted(&ep1.common, false);
1123                                 result = USBS_CONTROL_RETURN_HANDLED;
1124                                 
1125                             }
1126 #endif
1127 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
1128                             else if (((USB_DEVREQ_INDEX_DIRECTION_IN | 2) == endpoint) &&
1129                                        (USBS_STATE_CONFIGURED == (ep0.common.state & USBS_STATE_MASK))) {
1130                                 ep2_set_halted(&ep2.common, false);
1131                                 result = USBS_CONTROL_RETURN_HANDLED;
1132                                     
1133                             }
1134 #endif
1135                             else {
1136                                 // Invalid endpoint or not in configured state.
1137                                 result = USBS_CONTROL_RETURN_STALL;
1138                             }
1139                         }
1140                     }   // Endpoing or device clear-feature
1141                     
1142                 } else if (USB_DEVREQ_SET_FEATURE == req->request) {
1143
1144                     // SET_FEATURE also operates in much the same way as
1145                     // GET_STATUS
1146                     if (USB_DEVREQ_RECIPIENT_DEVICE == recipient) {
1147                         
1148                         // The only valid feature that can be set is remote-wakeup,
1149                         // which is not supported by the hardware.
1150                         result = USBS_CONTROL_RETURN_STALL;
1151                         
1152                     } else if (USB_DEVREQ_RECIPIENT_ENDPOINT == recipient) {
1153
1154                         // Only the halt condition can be set, and no data should be transferred.
1155                         // Halting endpoint 0 should probably be disallowed although the
1156                         // standard does not explicitly say so.
1157                         if ((0 != length) ||
1158                             (USB_DEVREQ_FEATURE_ENDPOINT_HALT != req->value_lo) ||
1159                             (USBS_STATE_CONFIGURED != (ep0.common.state & USBS_STATE_MASK))) {
1160                             
1161                             result = USBS_CONTROL_RETURN_STALL;
1162                             
1163                         } else {
1164                             int endpoint = req->index_lo;
1165                             if (0) {
1166                             }
1167 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
1168                             else if ((USB_DEVREQ_INDEX_DIRECTION_OUT | 1) == endpoint) {
1169                                 ep1_set_halted(&ep1.common, true);
1170                                 result = USBS_CONTROL_RETURN_HANDLED;
1171                             }
1172 #endif                            
1173 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
1174                             else if ((USB_DEVREQ_INDEX_DIRECTION_IN | 2) == endpoint) {
1175                                 ep2_set_halted(&ep2.common, true);
1176                                 result = USBS_CONTROL_RETURN_HANDLED;
1177                             }
1178 #endif                            
1179                             else {
1180                                 result = USBS_CONTROL_RETURN_STALL;
1181                             }
1182                         }
1183                     } // Endpoint or device set-feature
1184                 }
1185
1186                 // If the result has not been handled yet, pass it to
1187                 // the installed callback function (if any).
1188                 if (USBS_CONTROL_RETURN_UNKNOWN == result) {
1189                     if ((usbs_control_return (*)(usbs_control_endpoint*, void*))0 != ep0.common.standard_control_fn) {
1190                         result = (*ep0.common.standard_control_fn)(&ep0.common, ep0.common.standard_control_data);
1191                     }
1192                 }
1193                 
1194 #if 1                
1195                 if ((USBS_CONTROL_RETURN_UNKNOWN == result) &&
1196                     (USB_DEVREQ_SET_INTERFACE == req->request)) {
1197                     
1198                     // This code should not be necessary. For
1199                     // non-trivial applications which involve
1200                     // alternate interfaces and the like, this request
1201                     // should be handled by the application itself.
1202                     // For other applications, the default handler
1203                     // will ignore this request so we end up falling
1204                     // through without actually handling the request
1205                     // and hence returning a stall condition. That
1206                     // is legitimate behaviour according to the standard.
1207                     //
1208                     // However, there are appear to be problems with
1209                     // the SA1110 USB hardware when it comes to stall
1210                     // conditions: they appear to affect some
1211                     // subsequent messages from target to host as
1212                     // well. Hence rather than returning a stall
1213                     // condition this code instead generates a dummy
1214                     // reply, which is also valid according to the
1215                     // standard. This avoids complications with certain
1216                     // USB compliance testers.
1217                     if ((0 != length) ||
1218                         (0 != req->value_hi) || (0 != req->index_hi) ||
1219                         (USBS_STATE_CONFIGURED != (ep0.common.state & USBS_STATE_MASK))) {
1220                         
1221                         result = USBS_CONTROL_RETURN_STALL;
1222                     } else {
1223                         int interface_id;
1224                         int alternate;
1225             
1226                         CYG_ASSERT( (1 == ep0.common.enumeration_data->device.number_configurations) && \
1227                                     (1 == ep0.common.enumeration_data->total_number_interfaces),       \
1228                                     "Higher level code should have handled this request");
1229             
1230                         interface_id = req->index_lo;
1231                         alternate    = req->value_lo;
1232                         if ((interface_id != ep0.common.enumeration_data->interfaces[0].interface_id) ||
1233                             (alternate  != ep0.common.enumeration_data->interfaces[0].alternate_setting)) {
1234
1235                             result = USBS_CONTROL_RETURN_STALL;
1236                         } else {
1237                             result = USBS_CONTROL_RETURN_HANDLED;
1238                         }
1239                         
1240                     }
1241                 }
1242 #endif
1243                 
1244                 // If the result has still not been handled, leave it to
1245                 // the default implementation in the USB slave common package
1246                 if (USBS_CONTROL_RETURN_UNKNOWN == result) {
1247                     result = usbs_handle_standard_control(&ep0.common);
1248                 }
1249                 
1250             } else {
1251                 // The other three types of control message can be
1252                 // handled by similar code.
1253                 usbs_control_return (*callback_fn)(usbs_control_endpoint*, void*);
1254                 void* callback_arg;
1255                 //DBG(("non-standard control request %x", req->request));
1256                 
1257                 if (USB_DEVREQ_TYPE_CLASS == protocol) {
1258                     callback_fn  = ep0.common.class_control_fn;
1259                     callback_arg = ep0.common.class_control_data;
1260                 } else if (USB_DEVREQ_TYPE_VENDOR == protocol) {
1261                     callback_fn  = ep0.common.vendor_control_fn;
1262                     callback_arg = ep0.common.vendor_control_data;
1263                 } else {
1264                     callback_fn  = ep0.common.reserved_control_fn;
1265                     callback_arg = ep0.common.reserved_control_data;
1266                 }
1267
1268                 if ((usbs_control_return (*)(usbs_control_endpoint*, void*)) 0 == callback_fn) {
1269                     result = USBS_CONTROL_RETURN_STALL;
1270                 } else {
1271                     result = (*callback_fn)(&ep0.common, callback_arg);
1272                 }
1273             }
1274             //DBG(("Control request done, %d\n", result));
1275
1276             if (USBS_CONTROL_RETURN_HANDLED != result) {
1277                 // This control request cannot be handled. Generate a stall.
1278                 usbs_sa11x0_poke(EP0_CONTROL,
1279                                  EP0_FORCE_STALL | EP0_SERVICED_OPR | EP0_DATA_END,
1280                                  EP0_FORCE_STALL,
1281                                  EP0_OUT_READY);
1282             } else {
1283                 // The control request has been handled. Is there any more
1284                 // data to be transferred?
1285                 if (0 == length) {
1286                     usbs_sa11x0_poke(EP0_CONTROL,
1287                                      EP0_SERVICED_OPR | EP0_DATA_END,
1288                                      EP0_DATA_END,
1289                                      EP0_OUT_READY);
1290                 } else {
1291                     // The endpoint should now go into IN or OUT mode while the
1292                     // remaining data is transferred.
1293                     ep0.transmitted     = 0;
1294                     ep0.length          = length;
1295                     if (USB_DEVREQ_DIRECTION_OUT == direction) {
1296                         // Wait for the next packet from the host.
1297                         ep0.ep_state = EP0_STATE_OUT;
1298                         CYG_ASSERT( (unsigned char*) 0 != ep0.common.buffer, "A receive buffer should have been provided");
1299                         CYG_ASSERT( (usbs_control_return (*)(usbs_control_endpoint*, int))0 != ep0.common.complete_fn, \
1300                                     "A completion function should be provided for OUT control messages");
1301                     } else {
1302                         ep0.ep_state = EP0_STATE_IN;
1303                         usbs_sa11x0_ep0_fill_fifo();
1304                     }
1305                 }
1306             }   // Control message handled
1307         }       // Received 8-byte control message
1308     }           // Idle state, i.e. control message
1309 }               // ep0_dsr
1310
1311 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
1312 // ----------------------------------------------------------------------------
1313 // Endpoint 1 is used for OUT transfers, i.e. receive operations. Only
1314 // the bulk protocol is supported by the hardware. The semantics allow
1315 // for two different modes of operation: higher-level code can ask for
1316 // exactly one or more bulk packets of 64 bytes each, allowing buffer
1317 // requirements to be determined from a header; alternatively the
1318 // rx request can just supply a large buffer. Processing the first
1319 // packet of a larger transfer separately does not introduce any
1320 // special problems at the protocol level.
1321 //
1322 // It is not legal to receive just part of a packet and expect the
1323 // hardware or the driver to buffer the rest. Not all hardware will
1324 // be capable of doing this buffering, and there should not be
1325 // a driver design requirement to provide buffering space.
1326 //
1327 //
1328 // The hardware design for endpoint 1 is flawed in a number of
1329 // respects. The receive fifo is only 20 bytes, less than the packet
1330 // size, so it is essential to use DMA (there is a configuration
1331 // option to allow for communication protocols where packets will
1332 // never exceed 16 bytes, but that is not the normal case). The DMA
1333 // engine is triggered by a receive-fifo-service high-water mark
1334 // bit. DMA transfers operate in bursts of eight bytes. Therefore
1335 // it would make sense if the high-water mark was set when the
1336 // receive fifo contained eight bytes or more.
1337 //
1338 // Instead the high-water mark is set when the fifo contains twelve
1339 // bytes or more. Worse, there is no way of measuring how many bytes
1340 // there are left in the fifo without actually extracting those bytes.
1341 //
1342 // For a full-size 64-byte packet, the first 56 bytes will be
1343 // transferred by DMA and the remainder will remain in the fifo. For a
1344 // partial packet of between 56 and 63 bytes, the first 56 bytes will
1345 // be transferred by DMA and the remainder will remain in the fifo. There
1346 // is no way to distinguish between these scenarios without emptying
1347 // the fifo.
1348 //
1349 // The result is that there is never any point in attempting a DMA
1350 // transfer of more than 56 bytes, and for every endpoint 1 interrupt
1351 // it is necessary to read the remainder from the fifo. This adds
1352 // a lot of software overhead, and it is not clear that DMA is
1353 // particularly useful. It is still necessary because of the limited
1354 // fifo size.
1355 //
1356 //
1357 // Because DMA involves the use of physical rather than virtual
1358 // memory, there are also cache interaction problems. Specifically it
1359 // would be necessary to invalidate cache lines after a DMA transfer
1360 // has completed, but that only works sensibly if the buffer is
1361 // aligned to a cache-line boundary and is a multiple of the
1362 // cache-line size. Imposing such restrictions on higher-level code
1363 // is undesirable. Also the DMA engines have an apparently undocumented
1364 // restriction that the buffer must be eight-byte aligned.
1365 //
1366 // To work around all these problems, the receive code works in terms
1367 // of a small private buffer. After a packet has been received, data
1368 // will be copied from this private buffer to the destination. Obviously
1369 // this copy operation is overhead and, because the code is expected
1370 // to run at DSR level, However the copy operation is limited to at
1371 // most 64 bytes, which is not good but not disastrous either.
1372 //
1373 // For data transfers the entry points are:
1374 //
1375 // 1) ep1_start_rx_packet() - prepare to receive another packet from
1376 //    the host.
1377 // 2) ep1_clear_error() - an error condition has occurred (CRC,
1378 //    bit-stuffing, fifo overrun). It appears that the only way
1379 //    to clear this is to clear the receive-packet-complete bit,
1380 //    which unfortunately allows in another packet from the host
1381 //    before we are ready for it. Doing anything else while
1382 //    the error bit is set does not work, for example it is not
1383 //    possible to empty the fifo by hand.
1384 // 3) ep1_process_packet() - a whole packet has been received
1385 //    and now needs to be moved into application space.
1386 //
1387 // These three routines are called by the start_rx() routine and
1388 // by the DSR. There are different implementations for DMA and
1389 // non-DMA.
1390 //
1391 // There is another hardware problem: the receive-packet-complete bit
1392 // comes up with the wrong default value, allowing the host to start
1393 // transmitting before the target is ready to receive. Unfortunately
1394 // there is not much that can be done about this: the
1395 // receive-packet-complete bit cannot be set by software and the OUT
1396 // max register has a minimum size of eight bytes. Fortunately for
1397 // many protocols the target-side code has a chance to start a receive
1398 // before the host is allowed to send, so this problem is mostly
1399 // ignored for now.
1400 //
1401 // Another potential problem arises if the host sends more data than
1402 // is expected for a given transfer. It would be possible to address
1403 // this by manipulating the OUT max packet register and getting the
1404 // hardware to generate protocol violation stalls. This would also
1405 // eliminate the need to test for buffer overflows. For now it is
1406 // left to higher-level code to sort it all out.
1407
1408 #ifdef CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL
1409
1410 // DMA needs an area of physical memory. To avoid conflicts with
1411 // the cached shadow of this memory, this area needs to start at
1412 // a cache line boundary and there must be padding at the end
1413 // to the next cache line boundary, thus ensuring that the
1414 // processor will not accidentally overwrite the physical
1415 // memory because it is manipulating some other variable.
1416 //
1417 // NOTE: at the time of writing the toolchain has a problem with
1418 // the aligned attribute, so instead the start alignment has
1419 // to be handled in software.
1420
1421 # define EP1_DMA_MTU            56
1422 # define EP1_DMA_BUFSIZE        ((EP1_DMA_MTU + HAL_DCACHE_LINE_SIZE - 1) - \
1423                                  ((EP1_DMA_MTU + HAL_DCACHE_LINE_SIZE - 1) % HAL_DCACHE_LINE_SIZE))
1424 # define EP1_DMA_ALLOCSIZE      (EP1_DMA_BUFSIZE + HAL_DCACHE_LINE_SIZE - 1)
1425
1426 static unsigned char    ep1_dma_data[EP1_DMA_ALLOCSIZE];
1427
1428 // This variable cannot be initialized statically, instead it is
1429 // set by ep1_init(). It corresponds to the physical address
1430 // for the buffer.
1431 static unsigned char*   ep1_dma_buf;
1432
1433 static void
1434 ep1_start_rx_packet(void)
1435 {
1436     int dma_size = EP1_DMA_MTU;
1437
1438     // This assertion does not always hold: clearing an error condition
1439     // involves the packet-complete bit so another message may have
1440     // started to arrive.
1441     // CYG_ASSERT( 0 == (EP1_FIFO_NOT_EMPTY & *EP1_CONTROL), "The receive fifo should be empty");
1442     
1443     CYG_ASSERT( 0 == ((DMA_CONTROL_RUN | DMA_CONTROL_START_A) & *EP1_DMA_STATUS), "EP1 DMA should be inactive");
1444
1445 #ifdef FAILURES
1446     ep1_failure = (ep1_failure + 1) % 32;
1447     if (0 == ep1_failure) {
1448         dma_size = 8;
1449     }
1450 #endif
1451     
1452     // The full flexibility of the DMA engines is not required here,
1453     // specifically the automatic chaining between buffers A and B.
1454     // Instead always using buffer A is sufficient. To avoid the
1455     // However the hardware still requires the software to alternate
1456     // between A and B. To avoid switching between buffers during a
1457     // transfer an excessive size field is used, EP1_MTU rather than
1458     // EP1_DMA_MTU, and hence the DMA transfer will never complete.
1459     //
1460     // With some silicon revisions writing to the DMA registers does
1461     // not always work either, so a retry is in order. Possibly
1462     // some short delays immediately after the clear and before the
1463     // set would be sufficient.
1464     *EP1_DMA_CONTROL_CLEAR  = DMA_CONTROL_CLEAR_ALL;
1465     if (0 == (DMA_STATUS_BUFFER_IN_USE & *EP1_DMA_STATUS)) {
1466         ep1.using_buf_a = true;
1467         usbs_sa11x0_poke_value(EP1_DMA_BUF_A_ADDRESS, (unsigned int) ep1_dma_buf);
1468         usbs_sa11x0_poke_value(EP1_DMA_BUF_A_SIZE, dma_size);
1469         *EP1_DMA_CONTROL_SET = DMA_CONTROL_RUN | DMA_CONTROL_START_A;
1470     } else {
1471         ep1.using_buf_a = false;
1472         usbs_sa11x0_poke_value(EP1_DMA_BUF_B_ADDRESS, (unsigned int) ep1_dma_buf);
1473         usbs_sa11x0_poke_value(EP1_DMA_BUF_B_SIZE, dma_size);
1474         *EP1_DMA_CONTROL_SET = DMA_CONTROL_RUN | DMA_CONTROL_START_B;
1475     }
1476
1477     // This should not be necessary, but occasionally the equivalent
1478     // operation during ep1_init() fails. Strictly speaking it should
1479     // be calling poke_value(), but the added overheads for that are
1480     // not worthwhile.
1481     *USBS_OUT_SIZE      = EP1_MTU - 1;
1482     
1483     // Now allow the host to send the packet.
1484     usbs_sa11x0_poke(EP1_CONTROL, EP1_PACKET_COMPLETE | EP1_SENT_STALL, 0,
1485                      EP1_PACKET_COMPLETE | EP1_SENT_STALL | EP1_FORCE_STALL);
1486 }
1487
1488 // Clear an error condition following a CRC, bit stuffing or overrun
1489 // error. The only reliable way to do this is to halt DMA and clear
1490 // the packet-complete bit. Unfortunately this allows the host to send
1491 // another packet immediately, before start_rx_packet can be called,
1492 // introducing another race condition. The hardware does not appear
1493 // to offer any alternatives.
1494 static void
1495 ep1_clear_error(void)
1496 {
1497     *EP1_DMA_CONTROL_CLEAR = DMA_CONTROL_CLEAR_ALL;
1498     usbs_sa11x0_poke(EP1_CONTROL, EP1_PACKET_COMPLETE | EP1_SENT_STALL, 0,
1499                      EP1_PACKET_COMPLETE | EP1_PACKET_ERROR | EP1_SENT_STALL | EP1_FORCE_STALL | EP1_FIFO_NOT_EMPTY);
1500     
1501     // Clearing the packet-complete bit may cause the host to send
1502     // another packet, immediately causing another error, so this
1503     // assertion does not hold.
1504     // CYG_ASSERT( 0 == (*EP1_CONTROL & (EP1_PACKET_ERROR | EP1_FIFO_NOT_EMPTY)), "Receive error should have been cleared");
1505 }
1506
1507 // A packet has been received. Some of it may still be in the fifo
1508 // and must be extracted by hand. The data then has to copied to
1509 // a higher-level buffer.
1510 static int
1511 ep1_process_packet(void)
1512 {
1513     int pkt_size;
1514
1515     // First, work out how much data has been processed by the DMA
1516     // engine. This is the amount originally poked into the size
1517     // register minus its current value.
1518     *EP1_DMA_CONTROL_CLEAR = DMA_CONTROL_CLEAR_ALL;
1519     if (ep1.using_buf_a) {
1520         pkt_size = EP1_DMA_MTU - *EP1_DMA_BUF_A_SIZE;
1521     } else {
1522         pkt_size = EP1_DMA_MTU - *EP1_DMA_BUF_B_SIZE;
1523     }
1524     CYG_ASSERT( 0 == (pkt_size % DMA_BURST_SIZE), "DMA transfers must be in multiples of the burst size");
1525     
1526     // Move these bytes from physical memory to the target buffer.
1527     if ((pkt_size > 0) && ((ep1.fetched + pkt_size) < ep1.common.buffer_size)) {
1528         memcpy(ep1.common.buffer + ep1.fetched, ep1_dma_buf, pkt_size);
1529     } 
1530
1531     // Copy remaining bytes into the target buffer directly.
1532     // The DMA buffer could be used instead, moving the memcpy()
1533     // down and avoiding the need for a buffer overflow check
1534     // inside the loop, but at the cost of accessing physical
1535     // memory every time. That cost is too high.
1536     while (1) {
1537         int status = *EP1_CONTROL;
1538         if ((EP1_PACKET_COMPLETE | EP1_PACKET_ERROR) == ((EP1_PACKET_COMPLETE | EP1_PACKET_ERROR) & status)) {
1539             break;
1540         } else if (0 == (EP1_FIFO_NOT_EMPTY & status)) {
1541             break;
1542         } else {
1543             int datum = *EP1_DATA;
1544             if (ep1.fetched < ep1.common.buffer_size) {
1545                 ep1.common.buffer[ep1.fetched + pkt_size] = datum;
1546             }
1547             pkt_size++;
1548         }
1549     }
1550     ep1.fetched += pkt_size;
1551     return pkt_size;
1552 }
1553
1554 #else
1555
1556 // Transfers not involving DMA. Obviously these are much simpler
1557 // but restricted to packets of 16 bytes.
1558 static void
1559 ep1_start_rx_packet(void)
1560 {
1561     // Nothing to be done, just let the host send a packet and it will
1562     // end up in the fifo.
1563     usbs_sa11x0_poke(EP1_CONTROL, EP1_PACKET_COMPLETE | EP1_SENT_STALL, 0,
1564                      EP1_PACKET_COMPLETE | EP1_SENT_STALL | EP1_FORCE_STALL);
1565 }
1566
1567 static void
1568 ep1_clear_error(void)
1569 {
1570     usbs_sa11x0_poke(EP1_CONTROL, EP1_PACKET_COMPLETE | EP1_SENT_STALL, 0,
1571                      EP1_PACKET_COMPLETE | EP1_SENT_STALL | EP1_FORCE_STALL);
1572 }
1573
1574 static int
1575 ep1_process_packet(void)
1576 {
1577     int pkt_size = 0;
1578     while (0 != (*EP1_CONTROL & EP1_FIFO_NOT_EMPTY)) {
1579         int datum = *EP1_DATA;
1580         pkt_size++;
1581         if (ep1.fetched < ep1.common.buffer_size) {
1582             ep1.common.buffer[ep1.fetched + pkt_size] = datum;
1583         }
1584     }
1585     return pkt_size;
1586 }
1587 #endif
1588
1589 // Complete a transfer. This takes care of invoking the completion
1590 // callback and resetting the buffer.
1591 static void
1592 ep1_rx_complete(int result)
1593 {
1594     void (*complete_fn)(void*, int)  = ep1.common.complete_fn;
1595     void* complete_data = ep1.common.complete_data;
1596     
1597     ep1.common.buffer           = (unsigned char*) 0;
1598     ep1.common.buffer_size      = 0;
1599     ep1.common.complete_fn      = (void (*)(void*, int)) 0;
1600     ep1.common.complete_data    = (void*) 0;
1601
1602     if ((void (*)(void*, int))0 != complete_fn) {
1603         (*complete_fn)(complete_data, result);
1604     }
1605 }
1606
1607 // Start a transmission. This functionality is overloaded to cope with
1608 // waiting for stalls to complete.
1609 static void
1610 ep1_start_rx(usbs_rx_endpoint* endpoint)
1611 {
1612     CYG_ASSERT( endpoint == &ep1.common, "USB data transfer involves the wrong endpoint");
1613
1614     // Is this endpoint currently stalled? If so then a size of 0 can
1615     // be used to block until the stall condition is clear, anything
1616     // else should result in an immediate callback.
1617     if (ep1.common.halted) {
1618         if (0 != ep1.common.buffer_size) {
1619             ep1_rx_complete(-EAGAIN);
1620         }
1621     } else if (0 == ep1.common.buffer_size) {
1622         // A check to see if the endpoint is halted. It isn't.
1623         ep1_rx_complete(0);
1624     } else {
1625         int status      = *EP1_CONTROL;
1626
1627         CYG_ASSERT((void*) 0 != ep1.common.buffer, "USB receives should not override the interrupt vectors");
1628         
1629         // This indicates the start of a transfer.
1630         ep1.fetched     = 0;
1631
1632         // The sent-stall bit may get set by hardware because of
1633         // a protocol violation. If so it must be cleared here.
1634         if (0 != (status & EP1_SENT_STALL)) {
1635             usbs_sa11x0_poke(EP1_CONTROL, EP1_SENT_STALL, 0, EP1_SENT_STALL | EP1_FORCE_STALL);
1636             status = *EP1_CONTROL;
1637         }
1638
1639         // The bogus initial value for the receive-packet-complete
1640         // bit means that we may start off with an error condition.
1641         if ((EP1_PACKET_COMPLETE | EP1_PACKET_ERROR) == (status & (EP1_PACKET_COMPLETE | EP1_PACKET_ERROR))) {
1642             ep1_clear_error();
1643             ep1_start_rx_packet();
1644         } else if (0 != (status & EP1_FIFO_NOT_EMPTY)) {
1645             // No error but data in the fifo. This implies a small
1646             // initial packet, all held in the fifo.
1647 #ifdef CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL
1648             *EP1_DMA_BUF_A_SIZE = EP1_MTU;
1649             ep1.using_buf_a     = true;
1650 #endif
1651             (void) ep1_process_packet();
1652             ep1_rx_complete(ep1.fetched);
1653         } else {
1654             // Start a new transfer.
1655             ep1_start_rx_packet();
1656         }
1657     }
1658 }
1659
1660 static void
1661 ep1_set_halted(usbs_rx_endpoint* endpoint, cyg_bool new_value)
1662 {
1663     CYG_ASSERT( endpoint == &ep1.common, "USB set-stall operation involves the wrong endpoint");
1664
1665     if (ep1.common.halted == new_value) {
1666         return;
1667     }
1668     if (new_value) {
1669         // The endpoint should be stalled. There is a potential race
1670         // condition here with a current transfer. Updating the
1671         // stalled flag means that the dsr will do nothing.
1672         ep1.common.halted = true;
1673         HAL_REORDER_BARRIER();
1674
1675         // Now perform the actual stall. If we are in the middle of a
1676         // transfer then the stall bit may not get set for a while, so
1677         // poke() is inappropriate.
1678         *EP1_CONTROL = EP1_FORCE_STALL;
1679     } else {
1680         // The stall condition should be cleared. First take care of
1681         // things at the hardware level so that a new transfer is
1682         // allowed.
1683         usbs_sa11x0_poke(EP1_CONTROL, EP1_SENT_STALL, 0, EP1_SENT_STALL | EP1_FORCE_STALL);
1684         
1685         // Now allow new transfers to begin.
1686         ep1.common.halted = false;
1687     }
1688 }
1689
1690 // The DSR is invoked following an interrupt. According to the docs an
1691 // endpoint 1 interrupt can only happen if the receive-packet-complete
1692 // bit is set.
1693 static void
1694 usbs_sa11x0_ep1_dsr(void)
1695 {
1696     int status = *EP1_CONTROL;
1697
1698     // This assertion does not always hold. During long runs
1699     // spurious interrupts have been observed.
1700     // CYG_ASSERT( 0 != (status & EP1_PACKET_COMPLETE), "ep1 dsr should only be invoked when there is data");
1701     if (0 == (status & EP1_PACKET_COMPLETE)) {
1702         return;
1703     }
1704     
1705     if (ep1.common.halted) {
1706         // Do nothing. What may have happened is that a transfer
1707         // was in progress when the stall bit was set. The
1708         // set_halted() call above will have taken care of things.
1709         return;
1710     }
1711
1712     // The sent-stall bit should never get set, since we always
1713     // accept full-size 64-byte packets. Just in case...
1714     if (0 != (status & EP1_SENT_STALL)) {
1715         DBG(("ep1_dsr(), sent-stall bit\n"));
1716         usbs_sa11x0_poke(EP1_CONTROL, EP1_SENT_STALL, 0, EP1_SENT_STALL | EP1_FORCE_STALL);
1717     }
1718
1719     // Was there a receive error (CRC, bit-stuffing, fifo-overrun?).
1720     // Whichever bits of the current packet have been received must be
1721     // discarded, and the current packet must be retried.
1722     if (0 != (status & EP1_PACKET_ERROR)) {
1723         INCR_STAT(ep1_errors);
1724         ep1_clear_error();
1725         ep1_start_rx_packet();
1726     } else {
1727         // Another packet has been received. Process it, which may
1728         // complete the transfer or it may leave more to be done.
1729         //
1730         // The hardware starts with the wrong default value for
1731         // the receive-packet-complete bit, so a packet may arrive
1732         // even though no rx operation has started yet. The
1733         // packets must be ignored for now. start_rx_packet()
1734         // will detect data in the fifo and do the right thing.
1735         int pkt_size;
1736
1737         if ((unsigned char*)0 != ep1.common.buffer) {
1738             
1739             pkt_size = ep1_process_packet();
1740             INCR_STAT(ep1_receives);
1741             if (0 != (EP1_PACKET_ERROR & *EP1_CONTROL)) {
1742                 CYG_ASSERT( 0, "an error has occurred inside ep1_process_packet()\n");
1743
1744             } else if ((ep1.fetched != ep1.common.buffer_size) && (0 != pkt_size) && (0 == (ep1.fetched % EP1_MTU))) {
1745                 ep1_start_rx_packet();
1746             } else if (ep1.fetched > ep1.common.buffer_size) {
1747                 // The host has sent too much data.
1748                 ep1_rx_complete(-EMSGSIZE);
1749             } else {
1750 #if 0
1751                 int i;
1752                 diag_printf("------------------------------------------------------\n");
1753                 diag_printf("rx: buf %x, total size %d\n", ep1.common.buffer, ep1.fetched);
1754                 for (i = 0; (i < ep1.fetched) && (i < 128); i+= 8) {
1755                     diag_printf("rx %x %x %x %x %x %x %x %x\n",
1756                                 ep1.common.buffer[i+0], ep1.common.buffer[i+1], ep1.common.buffer[i+2], ep1.common.buffer[i+3], 
1757                                 ep1.common.buffer[i+4], ep1.common.buffer[i+5], ep1.common.buffer[i+6], ep1.common.buffer[i+7]);
1758                 }
1759                 diag_printf("------------------------------------------------------\n");
1760 #endif
1761                 ep1_rx_complete(ep1.fetched);
1762             }
1763         }
1764     }
1765 }
1766
1767 // Initialization.
1768 //
1769 // This may get called during system start-up or following a reset
1770 // from the host.
1771 static void
1772 usbs_sa11x0_ep1_init(void)
1773 {
1774 #ifdef CYGNUM_DEVS_USB_SA11X0_EP1_DMA_CHANNEL
1775     // What is the physical address that should be used for
1776     // transfers?
1777     unsigned int phys;
1778     HAL_VIRT_TO_PHYS_ADDRESS( ep1_dma_data, phys);
1779     phys += (HAL_DCACHE_LINE_SIZE - 1);
1780     phys -= (phys % HAL_DCACHE_LINE_SIZE);
1781     CYG_ASSERT( 0 == (phys % HAL_DCACHE_LINE_SIZE), "DMA buffer must be aligned to a cache-line boundary");
1782     ep1_dma_buf = (unsigned char*)phys;
1783
1784     // Clear the DMA channel and fix the DMA address register. The
1785     // value is determined above. 
1786     *EP1_DMA_CONTROL_CLEAR      = DMA_CONTROL_CLEAR_ALL;
1787     *EP1_DMA_ADDRESS            = EP1_DMA_ADDRESS_VALUE;
1788 #endif
1789
1790     // Always allow the host to send full-size packets. If there is a
1791     // protocol problem and the host sends packets that are too large,
1792     // it will have to be handled at a level above the device driver.
1793     //
1794     // With some silicon revisions reading back the register does not
1795     // work, so poke_value() is not applicable. This may be an issue
1796     // with reset timing.
1797     *USBS_OUT_SIZE      = EP1_MTU - 1;
1798
1799     // Endpoints should never be halted during a start-up.
1800     ep1.common.halted           = false;
1801
1802     // If there has been a reset and there was a receive in progress,
1803     // abort it. This also takes care of sorting out the endpoint
1804     // fields ready for the next rx.
1805     ep1_rx_complete(-EPIPE);
1806 }
1807
1808 #endif  // CYGPKG_DEVS_USB_SA11X0_EP1
1809
1810
1811 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
1812 // ----------------------------------------------------------------------------
1813 // Endpoint 2 is used for IN transfers, i.e. transmitting data to the
1814 // host. The code is mostly similar to that for endpoint 1, although
1815 // a little bit simpler (e.g. there is no need to worry about
1816 // buffer overflow, that is the host's problem). 
1817 //
1818 // There is a flaw in the hardware design. If the transfer involves an
1819 // exact multiple of 64 bytes then according to the USB spec there
1820 // should be a terminating packet of 0 bytes. However the size of the
1821 // current outgoing packet is determined by the IN_SIZE register and
1822 // that only allows for packets between 1 and 256 bytes - even though
1823 // USB bulk transfers can only go up to 64 bytes. This can be worked
1824 // around at this level by transmitting an extra byte, at the risk of
1825 // upsetting host-side device drivers. Both higher-level and host-side
1826 // code need to be aware of this problem.
1827 //
1828 // Again there appear to be problems with the DMA engine. This time it
1829 // appears that the transmit-fifo-service bit does not always work
1830 // correctly. If you set up a DMA transfer for more than the packet
1831 // size than once the packet has gone out the fifo-service bit just
1832 // remains set, the DMA engine continues to fill the fifo, and the
1833 // data gets lost. Instead DMA can only happen one packet at a time.
1834 // The same issues regarding cache line alignment etc. arise, so
1835 // using a small buffer here is convenient.
1836 //
1837 // 1) process_packet moves a packet from the main transmit buffer
1838 //    into the dma buffer.
1839 // 2) start_tx_packet() starts a transfer to the host
1840 // 3) clear_error() copes with error conditions.
1841
1842 #ifdef CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL
1843 // See the equivalent EP1 DMA definitions.
1844 # define EP2_DMA_MTU   64
1845 # define EP2_DMA_BUFSIZE        ((EP2_DMA_MTU + HAL_DCACHE_LINE_SIZE - 1) - \
1846                                  ((EP2_DMA_MTU + HAL_DCACHE_LINE_SIZE - 1) % HAL_DCACHE_LINE_SIZE))
1847 # define EP2_DMA_ALLOCSIZE      (EP2_DMA_BUFSIZE + HAL_DCACHE_LINE_SIZE - 1)
1848
1849 static unsigned char  ep2_dma_data[EP2_DMA_ALLOCSIZE];
1850 static unsigned char* ep2_dma_buf;
1851
1852 static void
1853 ep2_process_packet(void)
1854 {
1855     ep2.pkt_size = ep2.common.buffer_size - ep2.transmitted;
1856     if (ep2.pkt_size > EP2_MTU) {
1857         ep2.pkt_size = EP2_MTU;
1858     }
1859     // Work around the hardware's inability to send a zero-byte packet.
1860     if (0 == ep2.pkt_size) {
1861         ep2.pkt_size = 1;
1862         ep2_dma_buf[0] = 0;
1863     } else {
1864         memcpy(ep2_dma_buf, ep2.common.buffer + ep2.transmitted, ep2.pkt_size);
1865     }
1866 }
1867
1868 static void
1869 ep2_tx_packet(void)
1870 {
1871     int dma_size, dma_control_settings;
1872     
1873     // CYG_ASSERT( 0 != (*EP2_CONTROL & EP2_FIFO_SERVICE), "Fifo should be empty");
1874
1875     // Halt any DMA that may still be going on (there should not
1876     // be any). Then work out the desired DMA settings for the
1877     // current packet. The DMA engine needs to transfer a multiple
1878     // of the burst size. If the packet size is not a multiple of
1879     // the burst size, this presents a minor problem. The chances
1880     // of an interrupt handler running in time to put the
1881     // remaining bytes into the fifo by hand are not good, so
1882     // instead more data is DMA'd in then is absolutely necessary
1883     // and the surplus bytes will be cleared out during the next
1884     // tx_packet.
1885     //
1886     // A possible optimisation is to detect small packets of
1887     // less than the fifo size and byte-stuff those, bypassing
1888     // DMA. It is not clear that would give any performance benefits.
1889     *EP2_DMA_CONTROL_CLEAR      = DMA_CONTROL_CLEAR_ALL;
1890     
1891     dma_size    = ep2.pkt_size + DMA_BURST_SIZE - 1;
1892     dma_size   -= (dma_size % DMA_BURST_SIZE);
1893
1894     CYG_ASSERT(dma_size > 0, "DMA calculations should result in a transfer of at least 8 bytes");
1895     
1896     // Now clear the fifo, after DMA has stopped.
1897     usbs_sa11x0_poke(EP2_CONTROL, EP2_SENT_STALL, 0, EP2_SENT_STALL);
1898
1899     // Should we be using buf_a or buf_b for this transfer?
1900     // Getting this wrong means that the DMA engine just idles.
1901     if (0 == (*EP2_DMA_STATUS & DMA_STATUS_BUFFER_IN_USE)) {
1902         usbs_sa11x0_poke_value(EP2_DMA_BUF_A_ADDRESS, (int) ep2_dma_buf);
1903         usbs_sa11x0_poke_value(EP2_DMA_BUF_A_SIZE, dma_size);
1904         dma_control_settings    = DMA_CONTROL_RUN | DMA_CONTROL_START_A;
1905     } else {
1906         usbs_sa11x0_poke_value(EP2_DMA_BUF_B_ADDRESS, (int) ep2_dma_buf);
1907         usbs_sa11x0_poke_value(EP2_DMA_BUF_B_SIZE, dma_size);
1908         dma_control_settings    = DMA_CONTROL_RUN | DMA_CONTROL_START_B;
1909     }
1910
1911     // Poke the tx size register while the fifo is clearing.
1912     // This operation must be reliable or the host will get
1913     // confused by funny-sized packets.
1914     usbs_sa11x0_poke_value(USBS_IN_SIZE, ep2.pkt_size - 1);
1915
1916     // The USB hardware must be updated before the DMA engine
1917     // starts filling the fifo. Otherwise ~48% of outgoing
1918     // packets fail with a DMA underrun. When called from
1919     // start_tx() there is a race condition: if the host
1920     // request comes in before the DMA starts then an
1921     // error interrupt will be raised, to be processed by
1922     // the DSR, and then the DMA engine gets updated again.
1923     // Locking the scheduler eliminates this race.
1924     cyg_drv_dsr_lock();
1925     usbs_sa11x0_poke(EP2_CONTROL, EP2_PACKET_COMPLETE, 0, EP2_PACKET_COMPLETE | EP2_PACKET_ERROR | EP2_PACKET_UNDERRUN);
1926     *EP2_DMA_CONTROL_SET        = dma_control_settings;
1927     cyg_drv_dsr_unlock();
1928     
1929     // CYG_ASSERT(0 == (*EP2_CONTROL & EP2_FIFO_SERVICE), "DMA engine should have filled up the fifo by now");
1930 }
1931
1932 // Clearing an error should be a no-op when DMA is involved.
1933 // In practice clearing the packet-complete bit appears to
1934 // have some desirable effects, at the risk of the host
1935 // getting bogus data. This should only happen when there
1936 // is a real transfer in progress: an error early on is
1937 // likely because the PACKET_COMPLETE bit has a bogus initial
1938 // value.
1939 static void
1940 ep2_clear_error(void)
1941 {
1942     usbs_sa11x0_poke(EP2_CONTROL, EP2_PACKET_COMPLETE, 0, EP2_PACKET_COMPLETE | EP2_PACKET_ERROR | EP2_PACKET_UNDERRUN);
1943 }
1944
1945 #else   // EP2_DMA
1946
1947 // When not using DMA, process_packet() is responsible for filling the
1948 // fifo and keeping a shadow copy in a static buffer. clear_error()
1949 // refills the fifo using the shadow copy. tx_packet() starts the
1950 // actual transfer.
1951 static unsigned char ep2_tx_buf[EP2_MTU];
1952
1953 static void
1954 ep2_process_packet()
1955 {
1956     int i;
1957     
1958     // Clear the fifo, just in case.
1959     usbs_sa11x0_poke(EP2_CONTROL, EP2_SENT_STALL, 0, EP2_SENT_STALL);
1960
1961     ep2.pkt_size = ep2.common.buffer_size - ep2.transmitted;
1962     if (ep2.pkt_size > EP2_MTU) {
1963         ep2.pkt_size = EP2_MTU;
1964     }
1965     if (0 == ep2.pkt_size) {
1966         ep2.pkt_size    = 1;
1967         ep2_tx_buf[i]   = 0;
1968         *EP2_DATA       = 0;
1969     } else {
1970         for (i = 0; i < ep2.pkt_size; i++) {
1971             unsigned int datum = ep2.common.buffer[ep2.transmitted + i];
1972             ep2_tx_buf[i]   = datum;
1973             *EP2_DATA       = datum;
1974         }
1975     }
1976 }
1977
1978 static void
1979 ep2_tx_packet()
1980 {
1981     usbs_sa11x0_poke_value(USBS_IN_SIZE, ep2.pkt_size - 1);
1982     usbs_sa11x0_poke(EP2_CONTROL, EP2_PACKET_COMPLETE, 0, EP2_PACKET_COMPLETE | EP2_PACKET_ERROR | EP2_PACKET_UNDERRUN);
1983 }
1984
1985 static void
1986 ep2_clear_error()
1987 {
1988     int i;
1989     // Clear the fifo, just in case.
1990     usbs_sa11x0_poke(EP2_CONTROL, EP2_SENT_STALL, 0, EP2_SENT_STALL);
1991     for (i = 0; i < ep2.pkt_size; i++) {
1992         *EP2_DATA       = ep2_tx_buf[i];
1993     }
1994 }
1995
1996 #endif  // !EP2_DMA
1997
1998 // A utility routine for completing a transfer. This takes care of the
1999 // callback as well as resetting the buffer.
2000 static void
2001 ep2_tx_complete(int result)
2002 {
2003     void (*complete_fn)(void*, int)  = ep2.common.complete_fn;
2004     void* complete_data = ep2.common.complete_data;
2005     
2006     ep2.common.buffer           = (unsigned char*) 0;
2007     ep2.common.buffer_size      = 0;
2008     ep2.common.complete_fn      = (void (*)(void*, int)) 0;
2009     ep2.common.complete_data    = (void*) 0;
2010
2011     if ((void (*)(void*, int))0 != complete_fn) {
2012         (*complete_fn)(complete_data, result);
2013     }
2014 }
2015
2016
2017 // The exported interface to start a transmission.
2018 static void
2019 ep2_start_tx(usbs_tx_endpoint* endpoint)
2020 {
2021     CYG_ASSERT( endpoint == &ep2.common, "USB data transfer involves the wrong endpoint");
2022
2023     // Is this endpoint currently stalled? If so then a size of 0 can
2024     // be used to block until the stall condition is clear, anything
2025     // else should result in an immediate callback.
2026     if (ep2.common.halted) {
2027         if (0 != ep2.common.buffer_size) {
2028             ep2_tx_complete(-EAGAIN);
2029         }
2030     } else if (0 == ep2.common.buffer_size) {
2031         // A check to see if the endpoint is halted. It isn't.
2032         ep2_tx_complete(0);
2033     } else {
2034         // There should not be any errors at the start of a
2035         // transmission, but if there is one then there is no safe way
2036         // to recover. process_packet() and tx_packet() will hopefully
2037         // do the right thing.
2038         CYG_ASSERT((void*) 0 != ep2.common.buffer, "Transmitting the interrupt vectors is unlikely to be useful");
2039 #if 0
2040         {
2041             int i;
2042             diag_printf("----------------------------------------------\n");
2043             diag_printf("ep2_start_tx: buf %x, %d bytes\n", ep2.common.buffer, ep2.common.buffer_size);
2044             for (i = 0; (i < ep2.common.buffer_size) && (i < 128); i+= 8) {
2045                 diag_printf("tx: %x %x %x %x %x %x %x %x\n",
2046                             ep2.common.buffer[i+0], ep2.common.buffer[i+1], ep2.common.buffer[i+2], ep2.common.buffer[i+3],
2047                             ep2.common.buffer[i+4], ep2.common.buffer[i+5], ep2.common.buffer[i+6], ep2.common.buffer[i+7]);
2048             }
2049             diag_printf("----------------------------------------------\n");
2050         }
2051 #endif
2052
2053         // Prepare the first packet for transmission, then send it.
2054         ep2.transmitted = 0;
2055         ep2_process_packet();
2056         ep2_tx_packet();
2057     }
2058 }
2059
2060 static void
2061 ep2_set_halted(usbs_tx_endpoint* endpoint, cyg_bool new_value)
2062 {
2063     CYG_ASSERT(endpoint == &ep2.common, "USB set-stall operation involves the wrong endpoint");
2064
2065     if (ep2.common.halted == new_value) {
2066         return;
2067     }
2068     if (new_value) {
2069         // The endpoint should be stalled. There is a potential race
2070         // condition here with the current transfer and DSR invocation.
2071         // Updating the stalled flag means that the DSR will do nothing.
2072         ep2.common.halted = true;
2073         HAL_REORDER_BARRIER();
2074
2075         // Now perform the actual stall. This may be delayed by the hardware
2076         // so poke() cannot be used.
2077         *EP2_CONTROL = EP2_FORCE_STALL;
2078
2079         // If in the middle of a transfer then that cannot be aborted,
2080         // the DMA engines etc. would get very confused.
2081     } else {
2082         // Take care of the hardware so that a new transfer is allowed. 
2083         usbs_sa11x0_poke(EP2_CONTROL, EP2_SENT_STALL, 0, EP2_SENT_STALL | EP2_FORCE_STALL);
2084         ep2.common.halted = false;
2085     }
2086 }
2087
2088 // The dsr will be invoked when the transmit-packet-complete bit is
2089 // set. Typically this happens when a packet has been completed
2090 // (surprise surprise) but it can also happen for error conditions.
2091 static void
2092 usbs_sa11x0_ep2_dsr(void)
2093 {
2094     int status = *EP2_CONTROL;
2095     // This assertion does not always hold - spurious interrupts have
2096     // been observed if you run for a few hours.
2097     // CYG_ASSERT( 0 != (status & EP2_PACKET_COMPLETE), "ep2 dsr should only be invoked when the packet-complete bit is set");
2098
2099     if (0 == (status & EP2_PACKET_COMPLETE)) {
2100         // Spurious interrupt, do nothing.
2101     } else if (ep2.common.halted) {
2102         // There is a possible race condition between a packet
2103         // completing and the stalled condition being set.
2104         // set_halted() above does everything that is needed.
2105     } else if (0 == ep2.pkt_size) {
2106         // This can happen because of the initial value for the
2107         // packet-complete bit, allowing the host to retrieve data
2108         // before the target is ready. The correct action is to do
2109         // nothing.
2110     } else if (0 != (status & (EP2_PACKET_ERROR | EP2_PACKET_UNDERRUN))) {
2111         // A transmit error occurred, the details are not important.
2112         INCR_STAT(ep2_errors);
2113         ep2_clear_error();
2114         ep2_tx_packet();
2115     } else {
2116         // Another packet has gone out.
2117         INCR_STAT(ep2_transmits);
2118         ep2.transmitted += ep2.pkt_size;
2119         if ((ep2.transmitted < ep2.common.buffer_size) ||
2120             ((ep2.transmitted == ep2.common.buffer_size) && (0 == (ep2.common.buffer_size % EP2_MTU)))) {
2121             ep2_process_packet();
2122             ep2_tx_packet();
2123         } else {
2124             ep2_tx_complete(ep2.transmitted);
2125         }
2126     }
2127 }
2128
2129 // Endpoint 2 initialization.
2130 //
2131 // This may be called during system start-up or following a reset
2132 // from the host.
2133 static void
2134 usbs_sa11x0_ep2_init(void)
2135 {
2136 #ifdef CYGNUM_DEVS_USB_SA11X0_EP2_DMA_CHANNEL
2137     // What is the physical address that should be used for
2138     // transfers?
2139     unsigned int phys;
2140     HAL_VIRT_TO_PHYS_ADDRESS(ep2_dma_data, phys);
2141     phys += (HAL_DCACHE_LINE_SIZE - 1);
2142     phys -= (phys % HAL_DCACHE_LINE_SIZE);
2143     CYG_ASSERT(0 == (phys % HAL_DCACHE_LINE_SIZE), "DMA buffer must be aligned to a cache-line boundary");
2144     ep2_dma_buf = (unsigned char*) phys;
2145     
2146     // Clear the DMA channel completely, otherwise it may not be
2147     // possible to write the ADDRESS register. Then set the DMA
2148     // address register. The value is determined above.
2149     *EP2_DMA_CONTROL_CLEAR      = DMA_CONTROL_CLEAR_ALL;
2150     *EP2_DMA_ADDRESS            = EP2_DMA_ADDRESS_VALUE;
2151 #endif
2152
2153     // Endpoints should never be halted after a reset
2154     ep2.common.halted   = false;
2155
2156     // If there has been a reset and there was a receive in progress,
2157     // abort it. This also takes care of clearing the endpoint
2158     // structure fields.
2159     ep2_tx_complete(-EPIPE);
2160 }
2161
2162 #endif // CYGPKG_DEVS_USB_SA11X0_EP2
2163
2164 // ----------------------------------------------------------------------------
2165 // Interrupt handling
2166 //
2167 // As much work as possible is deferred to the DSR (or to the debug
2168 // thread). Interrupts for the endpoints are never a problem: the
2169 // variuos packet-complete etc. bits ensure that the endpoints
2170 // remain quiescent until the relevant interrupt has been serviced.
2171 // Suspend and resume are more complicated. A suspend means that
2172 // there has been no activity for 3ms, which should be enough
2173 // time for the whole thing to be handled. A resume means that there
2174 // has been bus activity after a suspend, and again it is infrequent.
2175 //
2176 // Reset appears to be much more complicated. A reset means that the
2177 // host is holding the USB lines to a specific state for 10ms. This is
2178 // detected by the hardware, causing the USB controller to be reset
2179 // (i.e. any pending transfers are discarded, etc.). The reset bit in
2180 // the status register will be set, and an interrupt will be raised.
2181 // Now, in theory the correct thing to do is to process this
2182 // interrupt, block reset interrupts for the duration of these 10ms,
2183 // and wait for further activity such as the control message to set
2184 // the address.
2185 //
2186 // In practice this does not seem to work. Possibly the USB controller
2187 // gets reset continuously while the external reset signal is applied,
2188 // but I have not been able to confirm this. Messing about with the
2189 // reset interrupt control bit causes the system to go off into
2190 // never-never land. 10ms is too short a time to allow for manual
2191 // debugging of what happens. So for now the interrupt source is
2192 // blocked at the interrupt mask level and the dsr will do the
2193 // right thing. This causes a significant number of spurious interrupts
2194 // for the duration of the reset signal and not a lot else can happen.
2195
2196
2197 // Perform reset operations on all endpoints that have been
2198 // configured in. It is convenient to keep this in a separate
2199 // routine to allow for polling, where manipulating the
2200 // interrupt controller mask is a bad idea.
2201 static void
2202 usbs_sa11x0_handle_reset(void)
2203 {
2204     int old_state = ep0.common.state;
2205
2206     // Any state change must be reported to higher-level code
2207     ep0.common.state = USBS_STATE_DEFAULT;
2208     if ((void (*)(usbs_control_endpoint*, void*, usbs_state_change, int))0 != ep0.common.state_change_fn) {
2209         (*ep0.common.state_change_fn)(&ep0.common, ep0.common.state_change_data,
2210                                       USBS_STATE_CHANGE_RESET, old_state);
2211     }
2212
2213     // Reinitialize all the endpoints that have been configured in.
2214     usbs_sa11x0_ep0_init();
2215 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
2216     usbs_sa11x0_ep1_init();
2217 #endif    
2218 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
2219     usbs_sa11x0_ep2_init();
2220 #endif    
2221
2222     // After a reset we need to handle endpoint interrupts, reset
2223     // interrupts, and suspend interrupts. There should not be a
2224     // resume since we have not suspended, but leaving resume
2225     // interrupts enabled appears to be desirable with some hardware.
2226     //
2227     // With some silicon revisions it appears that a longer delay
2228     // is needed after reset, so this poke() may not work.
2229     if (!usbs_sa11x0_poke(USBS_CONTROL,
2230                           CONTROL_INTR_ENABLE(CONTROL_EP_INTR_BITS|CONTROL_RESET_INTR|CONTROL_SUSPEND_INTR|CONTROL_RESUME_INTR),
2231                           0,
2232                           CONTROL_INTR_CLEAR(CONTROL_EP_INTR_BITS|CONTROL_RESET_INTR|CONTROL_SUSPEND_INTR|CONTROL_RESUME_INTR))) {
2233         // DBG(("usbs_sa11x0_handle_reset(), update of control register failed, status %x\n", *USBS_STATUS));
2234     }
2235 }
2236
2237 // The DSR. This can be invoked directly by poll(), or via the usual
2238 // interrupt subsystem. It acts as per the current value of
2239 // isr_status_bits. If another interrupt goes off while this
2240 // DSR is running, there will be another invocation of the DSR and
2241 // the status bits will be updated.
2242 static void
2243 usbs_sa11x0_dsr(cyg_vector_t vector, cyg_ucount32 count, cyg_addrword_t data)
2244 {
2245     int status = 0;
2246     
2247     CYG_ASSERT(SA11X0_IRQ_USB_SERVICE_REQUEST == vector, "USB DSR should only be invoked for USB interrupts" );
2248     CYG_ASSERT(0 == data, "The SA11X0 USB DSR needs no global data pointer");
2249
2250     // There is no atomic swap support, so interrupts have to be
2251     // blocked. It might be possible to do this via the USBS_CONTROL
2252     // register, but at the risk of messing up the status register
2253     // if another interrupt comes in. Blocking interrupts at the
2254     // processor level is less intrusive on the USB code.
2255
2256     cyg_drv_isr_lock();
2257     status = isr_status_bits;
2258     isr_status_bits = 0;
2259     cyg_drv_isr_unlock();
2260
2261     // Reset is special, since it invalidates everything else.
2262     // If the reset is still ongoing then do not attempt any
2263     // further processing, there will just be another interrupt.
2264     // Otherwise handle_reset() does the hard work. Unmasking
2265     // the interrupt means that another interrupt will occur
2266     // immediately if reset is still asserted, i.e. no threads
2267     // will run, but there is no easy way of triggering action
2268     // at the end of reset.
2269     if (0 != (status & STATUS_RESET_INTR)) {
2270         
2271         int new_status = *USBS_STATUS; 
2272         if (0 == (new_status & STATUS_RESET_INTR)) {
2273             usbs_sa11x0_handle_reset();
2274         } 
2275         // This unmask is likely to cause another interrupt immediately
2276         cyg_drv_interrupt_unmask(SA11X0_IRQ_USB_SERVICE_REQUEST);
2277         
2278     } else {
2279         // Process resume first. Ignore any resumes when we are not
2280         // actually suspended yet, this happens mainly during system
2281         // startup. If there has been a state change to suspended
2282         // then we need a matching state change to resumed.
2283         if (0 != (status & STATUS_RESUME_INTR)) {
2284             int old_state       = ep0.common.state;
2285             if (0 != (old_state & USBS_STATE_SUSPENDED)) {
2286                 ep0.common.state   &= ~USBS_STATE_SUSPENDED;
2287                 if ((void (*)(usbs_control_endpoint*, void*, usbs_state_change, int))0 != ep0.common.state_change_fn) {
2288                     (*ep0.common.state_change_fn)(&ep0.common, ep0.common.state_change_data,
2289                                               USBS_STATE_CHANGE_RESUMED, old_state);
2290                 }
2291                 // After a resume, all interrupts should be enabled.
2292                 // In theory there is no need to worry about further
2293                 // resume interrupts, but strange hardware behaviour
2294                 // has been observed if resume interrupts are left
2295                 // disabled.
2296                 usbs_sa11x0_poke(USBS_CONTROL,
2297                                  CONTROL_INTR_ENABLE(CONTROL_EP_INTR_BITS|CONTROL_RESET_INTR|CONTROL_SUSPEND_INTR|CONTROL_RESUME_INTR),
2298                                  0,
2299                                  CONTROL_INTR_CLEAR(CONTROL_EP_INTR_BITS|CONTROL_RESET_INTR|CONTROL_SUSPEND_INTR|CONTROL_RESUME_INTR));
2300             }
2301         }
2302
2303         // Now process endpoint interrupts. Control operations on
2304         // endpoint 0 may have side effects on the other endpoints
2305         // so it is better to leave them until last.
2306 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1    
2307         if (0 != (status & STATUS_EP1_INTR)) {
2308             usbs_sa11x0_ep1_dsr();
2309         }
2310 #endif    
2311 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
2312         if (0 != (status & STATUS_EP2_INTR)) {
2313             usbs_sa11x0_ep2_dsr();
2314         }
2315 #endif
2316         if (0 != (status & STATUS_EP0_INTR)) {
2317             usbs_sa11x0_ep0_dsr();
2318         }
2319         
2320         // Process suspend last, but only if there has not also been
2321         // a resume. A suspend immediately followed by a resume should
2322         // be ignored. A resume immediately followed by a suspend
2323         // would be unfortunate, but suspend means that there has been
2324         // at least 3ms of inactivity so the DSR latency would have
2325         // to be pretty bad.
2326         //
2327         // Total robustness is possible but requires more work in the ISR.
2328         if ((0 != (status & STATUS_SUSPEND_INTR)) && (0 == (status & STATUS_RESUME_INTR))) {
2329             int old_state       = ep0.common.state;
2330             ep0.common.state   |= USBS_STATE_SUSPENDED;
2331             if ((void (*)(usbs_control_endpoint*, void*, usbs_state_change, int))0 != ep0.common.state_change_fn) {
2332                 (*ep0.common.state_change_fn)(&ep0.common, ep0.common.state_change_data,
2333                                               USBS_STATE_CHANGE_SUSPENDED, old_state);
2334             }
2335             // We are no longer interested in further suspend interrupts,
2336             // which could happen every 3 ms, but resume has become
2337             // very interesting.
2338             usbs_sa11x0_poke(USBS_CONTROL,
2339                              CONTROL_INTR_ENABLE(CONTROL_EP_INTR_BITS | CONTROL_RESET_INTR | CONTROL_RESUME_INTR),
2340                              0,
2341                              CONTROL_INTR_CLEAR(CONTROL_EP_INTR_BITS | CONTROL_RESET_INTR | CONTROL_RESUME_INTR));
2342         }
2343     }
2344 }
2345
2346 // ----------------------------------------------------------------------------
2347 // Optionally the USB code can do most of its processing in a thread
2348 // rather than in a DSR.
2349 #ifdef CYGPKG_DEVS_USB_SA11X0_THREAD
2350 static unsigned char usbs_sa11x0_thread_stack[CYGNUM_DEVS_USB_SA11X0_THREAD_STACK_SIZE];
2351 static cyg_thread    usbs_sa11x0_thread;
2352 static cyg_handle_t  usbs_sa11x0_thread_handle;
2353 static cyg_sem_t     usbs_sa11x0_sem;
2354
2355
2356 static void
2357 usbs_sa11x0_thread_fn(cyg_addrword_t param)
2358 {
2359     for (;;) {
2360         cyg_semaphore_wait(&usbs_sa11x0_sem);
2361         usbs_sa11x0_dsr(SA11X0_IRQ_USB_SERVICE_REQUEST, 0, 0);
2362     }
2363     CYG_UNUSED_PARAM(cyg_addrword_t, param);
2364 }
2365
2366 static void
2367 usbs_sa11x0_thread_dsr(cyg_vector_t vector, cyg_ucount32 count, cyg_addrword_t data)
2368 {
2369     CYG_ASSERT( 0 != isr_status_bits, "DSR's should only be scheduled when there is work to do");
2370     cyg_semaphore_post(&usbs_sa11x0_sem);
2371     
2372     CYG_UNUSED_PARAM(cyg_vector_t, vector);
2373     CYG_UNUSED_PARAM(cyg_ucount32, count);
2374     CYG_UNUSED_PARAM(cyg_addrword_t, data);
2375 }
2376
2377 #endif
2378
2379 // ----------------------------------------------------------------------------
2380 // The interrupt handler. This does as little as possible.
2381 static cyg_uint32
2382 usbs_sa11x0_isr(cyg_vector_t vector, cyg_addrword_t data)
2383 {
2384     int old_status_bits = isr_status_bits;
2385     int status_bits;
2386
2387     CYG_ASSERT(SA11X0_IRQ_USB_SERVICE_REQUEST == vector, "USB ISR should only be invoked for USB interrupts" );
2388     CYG_ASSERT(0 == data, "The SA11X0 USB ISR needs no global data pointer" );
2389
2390     // Read the current status. Reset is special, it means that the
2391     // whole chip has been reset apart from the one bit in the status
2392     // register. Nothing should be done about this until the DSR sets
2393     // the endpoints back to a consistent state and re-enables
2394     // interrupts in the control register.
2395     status_bits         = *USBS_STATUS;
2396     
2397     if (0 != (status_bits & STATUS_RESET_INTR)) {
2398         isr_status_bits = STATUS_RESET_INTR;
2399         *USBS_STATUS = status_bits;
2400         cyg_drv_interrupt_mask(SA11X0_IRQ_USB_SERVICE_REQUEST);
2401     } else {
2402         *USBS_STATUS    = status_bits;
2403         isr_status_bits |= status_bits;
2404     }
2405
2406     // Now keep the rest of the system happy.
2407     cyg_drv_interrupt_acknowledge(vector);
2408     return (old_status_bits != isr_status_bits) ? CYG_ISR_CALL_DSR : CYG_ISR_HANDLED;
2409 }
2410
2411 // ----------------------------------------------------------------------------
2412 // Polling support. This acts mostly like the interrupt handler: it
2413 // sets the isr status bits and causes the dsr to run. Reset has to be
2414 // handled specially: polling does nothing as long as reset is asserted.
2415
2416 static void
2417 usbs_sa11x0_poll(usbs_control_endpoint* endpoint)
2418 {
2419     CYG_ASSERT( endpoint == &ep0.common, "USB poll involves the wrong endpoint");
2420     
2421     if (0 != (isr_status_bits & STATUS_RESET_INTR)) {
2422         // Reset was detected the last time poll() was invoked. If
2423         // reset is still active, do nothing. Once the reset has
2424         // completed things can continue.
2425         if (0 == (STATUS_RESET_INTR & *USBS_STATUS)) {
2426             isr_status_bits = 0;
2427             usbs_sa11x0_handle_reset();
2428         }
2429     } else {
2430         isr_status_bits = *USBS_STATUS;
2431         if (0 != (STATUS_RESET_INTR & isr_status_bits)) {
2432             // Reset has just been asserted. Do nothing, just continue
2433             // polling for the duration of the reset signal.
2434         } else if (0 != isr_status_bits) {
2435             usbs_sa11x0_dsr(SA11X0_IRQ_USB_SERVICE_REQUEST, 0, (cyg_addrword_t) 0);
2436         }
2437     }
2438 }
2439
2440
2441 // ----------------------------------------------------------------------------
2442 // Initialization.
2443
2444 void
2445 usbs_sa11x0_init(void)
2446 {
2447     // Start by disabling/resetting the hardware. This is easy.
2448     *USBS_CONTROL       = CONTROL_DISABLE;
2449     *USBS_CONTROL       = CONTROL_DISABLE;
2450     *USBS_CONTROL       = CONTROL_DISABLE;
2451
2452     // The USB bus is now tristated, preventing any communications.
2453     // This is a good thing, the situation should change only when
2454     // higher-level code has provided the enumeration data and done an
2455     // explicit start. 
2456     usbs_sa11x0_ep0_init();
2457 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
2458     usbs_sa11x0_ep1_init();
2459 #endif
2460 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
2461     usbs_sa11x0_ep2_init();
2462 #endif
2463
2464     // If processing is supposed to happen in a thread rather
2465     // than in DSR, initialize the threads.
2466 #ifdef CYGPKG_DEVS_USB_SA11X0_THREAD
2467     cyg_semaphore_init(&usbs_sa11x0_sem, 0);
2468     cyg_thread_create(CYGNUM_DEVS_USB_SA11X0_THREAD_PRIORITY,
2469                       &usbs_sa11x0_thread_fn,
2470                       0,
2471                       "SA11X0 USB support",
2472                       usbs_sa11x0_thread_stack,
2473                       CYGNUM_DEVS_USB_SA11X0_THREAD_STACK_SIZE,
2474                       &usbs_sa11x0_thread_handle,
2475                       &usbs_sa11x0_thread
2476         );
2477     cyg_thread_resume(usbs_sa11x0_thread_handle);
2478 #endif
2479     
2480     // It is also possible and desirable to install the interrupt
2481     // handler here, even though there will be no interrupts for a
2482     // while yet.
2483     cyg_drv_interrupt_create(SA11X0_IRQ_USB_SERVICE_REQUEST,
2484                              99,        // priority
2485                              0,         // data
2486                              &usbs_sa11x0_isr,
2487 #ifdef CYGPKG_DEVS_USB_SA11X0_THREAD
2488                              &usbs_sa11x0_thread_dsr,
2489 #else                             
2490                              &usbs_sa11x0_dsr,
2491 #endif                             
2492                              &usbs_sa11x0_intr_handle,
2493                              &usbs_sa11x0_intr_data);
2494     cyg_drv_interrupt_attach(usbs_sa11x0_intr_handle);
2495     cyg_drv_interrupt_unmask(SA11X0_IRQ_USB_SERVICE_REQUEST);
2496 }
2497
2498 // ----------------------------------------------------------------------------
2499 // Testing support.
2500 usbs_testing_endpoint usbs_testing_endpoints[] = {
2501     {
2502         endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL, 
2503         endpoint_number     : 0,
2504         endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN,
2505         endpoint            : (void*) &ep0.common,
2506 #ifdef CYGVAR_DEVS_USB_SA11X0_EP0_DEVTAB_ENTRY
2507         devtab_entry        : CYGDAT_DEVS_USB_SA11X0_DEVTAB_BASENAME "0c",
2508 #else        
2509         devtab_entry        : (const char*) 0,
2510 #endif        
2511         min_size            : 1,            // zero-byte control transfers are meaningless
2512         max_size            : 0x0FFFF,      // limit imposed by protocol
2513         max_in_padding      : 0,
2514         alignment           : 0
2515     },
2516 #ifdef CYGPKG_DEVS_USB_SA11X0_EP1
2517     {
2518         endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_BULK,
2519         endpoint_number     : 1,
2520         endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT,
2521         endpoint            : (void*) &ep1.common,
2522 #ifdef CYGVAR_DEVS_USB_SA11X0_EP1_DEVTAB_ENTRY
2523         devtab_entry        : CYGDAT_DEVS_USB_SA11X0_DEVTAB_BASENAME "1r",
2524 #else        
2525         devtab_entry        : (const char*) 0,
2526 #endif        
2527         min_size            : 1,
2528         max_size            : -1,           // No hardware or driver limitation
2529         max_in_padding      : 0,
2530         alignment           : 0
2531     },
2532 #endif
2533 #ifdef CYGPKG_DEVS_USB_SA11X0_EP2
2534     {
2535         endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_BULK,
2536         endpoint_number     : 2,
2537         endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN,
2538         endpoint            : (void*) &ep2.common,
2539 #ifdef CYGVAR_DEVS_USB_SA11X0_EP2_DEVTAB_ENTRY
2540         devtab_entry        : CYGDAT_DEVS_USB_SA11X0_DEVTAB_BASENAME "2w",
2541 #else        
2542         devtab_entry        : (const char*) 0,
2543 #endif        
2544         min_size            : 1,
2545         max_size            : -1,           // No hardware or driver limitation
2546         max_in_padding      : 1,            // hardware limitation
2547         alignment           : 0
2548     },
2549 #endif
2550     USBS_TESTING_ENDPOINTS_TERMINATOR
2551 };