]> git.kernelconcepts.de Git - karo-tx-redboot.git/blob - packages/devs/usb/d12/v2_0/src/usbs_d12.c
Initial revision
[karo-tx-redboot.git] / packages / devs / usb / d12 / v2_0 / src / usbs_d12.c
1 //==========================================================================
2 //
3 //      usbs_d12.c
4 //
5 //      Driver for the D12 USB Slave Board
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 // Copyright (C) 2006 eCosCentric Ltd
13 //
14 // eCos is free software; you can redistribute it and/or modify it under
15 // the terms of the GNU General Public License as published by the Free
16 // Software Foundation; either version 2 or (at your option) any later version.
17 //
18 // eCos is distributed in the hope that it will be useful, but WITHOUT ANY
19 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
20 // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
21 // for more details.
22 //
23 // You should have received a copy of the GNU General Public License along
24 // with eCos; if not, write to the Free Software Foundation, Inc.,
25 // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
26 //
27 // As a special exception, if other files instantiate templates or use macros
28 // or inline functions from this file, or you compile this file and link it
29 // with other works to produce a work based on this file, this file does not
30 // by itself cause the resulting work to be covered by the GNU General Public
31 // License. However the source code for this file must still be made available
32 // in accordance with section (3) of the GNU General Public License.
33 //
34 // This exception does not invalidate any other reasons why a work based on
35 // this file might be covered by the GNU General Public License.
36 // -------------------------------------------
37 //####ECOSGPLCOPYRIGHTEND####
38 //==========================================================================
39 //#####DESCRIPTIONBEGIN####
40 //
41 // Author(s):    Frank M. Pagliughi (fmp)
42 // Date:         2004-05-22
43 //
44 // This code is a device driver for the SoRo Systems USB-D12-104, a PC/104
45 // (ISA) Full-Speed USB slave board, which turns a PC/104 stack into a USB
46 // slave device. The board contains a Philips PDIUSBD12 Peripheral Controller
47 // Chip mapped into the PC's I/O space, with jumper-selectable I/O base 
48 // address, IRQ, and DMA settings. The eCos config tool is used to adjust
49 // settings for this driver to match the physical jumper settings. The chip
50 // could run in polled mode without an IRQ, but this wouldn't be a great idea
51 // other than maybe a debug environment. 
52 //
53 // The board supports DMA transfers over the Main endpoint, but I temporarily
54 // removed that code to make the driver portable to other platforms.
55 //
56 // *** This driver should also work with the Philips ISA Eval Board
57 //     for the D12, but I couldn't get one of them from Philips, so
58 //     I couldn't test it.
59 //
60 // The D12 uses an indexed register set, which it describes as "commands." 
61 // You first write a command (index) to the command register then you can
62 // read or write data to that register. Each multi-byte command read or write
63 // must be dione atomically, so all access to the chip must be serialized.
64 // 
65 // The D12 requests service through a single interrupt. The driver can
66 // be configured to service the chip through a DSR or a thread. In either
67 // case, the "service" code assumes it has unfettered access to the chip.
68 // The interrupt, therefore never touches the chip. It just schedules the
69 // DSR or service thread.
70 // Currently, the code gets exclusive access to the chip by locking the
71 // scheduler. This is suboptimal (locking the whole OS to touch one I/O 
72 // chip), and better method should be explored.
73 //
74 // This version of the driver does not support Isocronous transfers.
75 // 
76 // Additional notes on the D12:
77 //
78 // - The D12 has 4 endpoints (2 IN, and 2 OUT) in addition to the main 
79 //   control endpoint:
80 //   - Endp 0 (Control In & Out, 16 byte buffer)
81 //   - Endp 1 (IN & OUT, Bulk or Interrupt, 16 byte ea)
82 //   - Endp 2 (IN and/or OUT, Bulk, Interrupt, or Isoc, 64 bytes ea)
83 //
84 // - The "main" endpoint (as Philips calls it) is Endp 2. It's double
85 //   buffered and has a DMA interface, and thus, is suited for high
86 //   throughput. For applications that perform either Isoc In or Out,
87 //   the buffers for Endp 2 can be combined for a 128 byte space.
88 //   This driver, however, currently does not support this.
89 //
90 // - There may be a flaw in the double buffering of the rx main endpoint. 
91 //   According to the documentation it should be invisible to the software,
92 //   but if both buffers fill (on an rx/OUT), they must both be read 
93 //   together, otherwise it appears that the buffers/packets are returned
94 //   in reverse order. ReadMainEndpointBuf() returns the data properly.
95 //
96 // - All the interrupt sources on the chip - individual endpoints, bus reset,
97 //   suspend, and DMA - are OR'ed together and can be checked via the 
98 //   interrupt status register. When using edge-sensitive interrupts, as
99 //   we do here, the ISR/DSR must be sure all interrupts are cleared before
100 //   returning otherwise no new interrupts will be latched.
101 //
102 // - If the DMA controller is not used for the Main Endpoint, you MUST enable
103 //   the main endpoint interrupts in the DMA register (bits 6 & 7).
104 //   Personally, I think this should be the default at reset, to make it
105 //   compatible with the other endpoints, but Philips didn't see it that
106 //   way.
107 // 
108 // - When a Setup (Device Request) packet arrives in the control endpoint, a
109 //   bit is set in the endpoint's status register indicating the packet is
110 //   setup and not data. By the USB standard, a setup packet can not be
111 //   NAK'ed or STALL'ed, so when the chip receives a setup packet, it 
112 //   flushes the Ctrl (EP0) IN buffer and disables the Validate and Clear
113 //   Buffer commands. We must send an "acknowledge setup" to both
114 //   EP0 IN and OUT before a Validate or Clear Buffer command is effective.
115 //   See ReadSetupPacket().
116 //
117 //####DESCRIPTIONEND####
118 //==========================================================================
119
120 #include <cyg/infra/cyg_type.h>
121 #include <cyg/infra/cyg_ass.h>
122 #include <cyg/infra/cyg_trac.h>
123 #include <cyg/infra/diag.h>
124
125 #include <pkgconf/devs_usb_d12.h>
126
127 #include <cyg/hal/drv_api.h>
128 #include <cyg/hal/hal_arch.h>
129 #include <cyg/hal/hal_io.h>
130 #include <cyg/hal/hal_cache.h>
131 #include <cyg/error/codes.h>
132
133 #include <cyg/io/usb/usb.h>
134 #include <cyg/io/usb/usbs.h>
135
136 #include <string.h>
137
138 // --------------------------------------------------------------------------
139 // Common Types
140 // --------------------------------------------------------------------------
141
142 typedef cyg_uint8       byte;
143 typedef cyg_uint8       uint8;
144 typedef cyg_int16       int16;
145 typedef cyg_uint16      uint16;
146 typedef cyg_int32       int32;
147 typedef cyg_uint32      uint32;
148
149 // --------------------------------------------------------------------------
150 // Tracing & Debug
151 // --------------------------------------------------------------------------
152 // If the driver is configured to use a thread to service the chip, then it
153 // can also be configured to dump a lot of debug output.
154 // Care must be taken that USB timing requirements are not violated by 
155 // dumping debug info. If the data is sent to a serial port, it should use
156 // a hardware driver and have a large output buffer (115200 baud & 2kB
157 // buffer works for me).
158
159 #if defined(CYGFUN_DEVS_USB_D12_DEBUG) && CYGFUN_DEVS_USB_D12_DEBUG
160 #define TRACE_D12 diag_printf
161 #else
162 #define TRACE_D12 (1) ? (void)0 : diag_printf
163 #endif
164
165 #if defined(CYGSEM_DEVS_USB_D12_DEBUG_DUMP_EP0_BUFS) && CYGSEM_DEVS_USB_D12_DEBUG_DUMP_EP0_BUFS
166 #define TRACE_EP0       1
167 #endif
168
169 #if defined(CYGSEM_DEVS_USB_D12_DEBUG_DUMP_BUFS) && CYGSEM_DEVS_USB_D12_DEBUG_DUMP_BUFS
170 #define TRACE_EP        1
171 #endif
172
173 #if defined(TRACE_EP0) || defined(TRACE_EP)
174 static void _trace_buf(const char *hdr, const byte* buf, unsigned n)
175 {
176   unsigned i;
177   
178   if (buf != 0 && n != 0) {
179     if (hdr && hdr[0])
180       TRACE_D12("%s ", hdr);
181     
182     TRACE_D12("[");
183     for (i=0; i<n; i++) 
184       TRACE_D12(" x%02X", buf[i]);
185     TRACE_D12("]\n");
186   }
187 }
188 #endif
189
190 #if defined(TRACE_EP0)
191 #define TRACE_BUF0      _trace_buf
192 #else   
193 #define TRACE_BUF0(hdr, buf, n)
194 #endif
195
196 #if defined(TRACE_EP)
197 #define TRACE_BUF       _trace_buf
198 #else   
199 #define TRACE_BUF(hdr, buf, n)
200 #endif
201
202 // ==========================================================================
203 // Chip Wrapper
204 // ==========================================================================
205
206 // This section contains functions that wrapper the low-level access to the 
207 // chip. There's a function around each register access on the chip, and then
208 // some.
209
210 #if defined(CYGSEM_DEVS_USB_D12_IO_MAPPED)
211 typedef void* d12_addr_type;
212 #else
213 typedef byte* d12_addr_type;
214 #endif
215
216 #define D12_BASE_ADDR   ((d12_addr_type) CYGNUM_DEVS_USB_D12_BASEADDR)
217
218 #define D12_ENDP0_SIZE       16 // Size of Ctrl Endp
219 #define D12_MAIN_ENDP         2 // The D12's "Main" Endp is special, double buffered
220 #define D12_MAIN_ENDP_SIZE   64 // Size of each main endp buffer
221 #define D12_MAX_PACKET_SIZE 128 // Max packet is actually double main endp
222
223 #define D12_CHIP_ID      0x1012 // Value that's returned by a read of
224                                 //the D12's Chip ID register
225
226 // ----- Endpoint Indices -----
227
228 enum {
229   D12_ENDP_INVALID = 0xFF,
230   D12_ENDP_MIN     = 0,
231   
232   D12_RX_CTRL_ENDP = D12_ENDP_MIN,                // Rx/Tx Nomenclature
233   D12_TX_CTRL_ENDP,
234   
235   D12_RX_ENDP0     = D12_ENDP_MIN,
236   D12_TX_ENDP0,
237   D12_RX_ENDP1,
238   D12_TX_ENDP1,
239   D12_RX_ENDP2,
240   D12_TX_ENDP2,
241   D12_RX_MAIN_ENDP = D12_RX_ENDP2,
242   D12_TX_MAIN_ENDP = D12_TX_ENDP2,
243   
244   
245   D12_CTRL_ENDP_OUT = D12_ENDP_MIN,               // IN/OUT Nomenclature
246   D12_CTRL_ENDP_IN,
247   
248   D12_ENDP0_OUT     = D12_ENDP_MIN,
249   D12_ENDP0_IN,
250   D12_ENDP1_OUT,
251   D12_ENDP1_IN,
252   D12_ENDP2_OUT,
253   D12_ENDP2_IN,
254   D12_MAIN_ENDP_OUT = D12_ENDP2_OUT,
255   D12_MAIN_ENDP_IN  = D12_ENDP2_IN,
256   
257   D12_ENDP_INSERT_BEFORE,
258   D12_ENDP_MAX      = D12_ENDP_INSERT_BEFORE-1
259 };
260
261 // ----- Set Mode Reg configuration byte -----
262
263 enum {  
264   D12_MODE_CFG_NO_LAZYCLOCK       = 0x02,
265   D12_MODE_CFG_CLOCK_RUNNING      = 0x04,
266   D12_MODE_CFG_INTERRUPT          = 0x08,
267   D12_MODE_CFG_SOFT_CONNECT       = 0x10,
268   
269   D12_MODE_CFG_NON_ISO            = 0x00,
270   D12_MODE_CFG_ISO_OUT            = 0x40,
271   D12_MODE_CFG_ISO_IN             = 0x80,
272   D12_MODE_CFG_ISO_IO             = 0xC0,
273   
274   D12_MODE_CFG_DFLT               = (D12_MODE_CFG_NO_LAZYCLOCK |
275                                      D12_MODE_CFG_CLOCK_RUNNING | 
276                                      D12_MODE_CFG_NON_ISO)
277 };
278
279 // ----- Set Mode Reg clock div factor -----
280
281 enum {
282   D12_MODE_CLK_24_MHZ                     = 1,
283   D12_MODE_CLK_16_MHZ                     = 2,
284   D12_MODE_CLK_12_MHZ                     = 3,
285   D12_MODE_CLK_8_MHZ                      = 5,
286   D12_MODE_CLK_6_MHZ                      = 7,
287   D12_MODE_CLK_4_MHZ                      = 11,
288   
289   D12_MODE_CLK_DIV_MASK                   = 0x0F,
290   
291   D12_MODE_CLK_SET_TO_ONE                 = 0x40,
292   D12_MODE_CLK_SOF_ONLY_INTR              = 0x80,
293   
294   D12_MODE_CLK_DFLT                       = (D12_MODE_CLK_4_MHZ | 
295                                              D12_MODE_CLK_SET_TO_ONE)
296 };
297
298 // ----- Set DMA Register -----
299
300 enum {
301   D12_DMA_SINGLE_CYCLE,
302   D12_DMA_BURST_4_CYCLE,
303   D12_DMA_BURST_8_CYCLE,
304   D12_DMA_BURST_16_CYCLE,
305   
306   D12_DMA_ENABLE                          = 0x04,
307   D12_DMA_DIR_WRITE                       = 0x08,
308   D12_DMA_DIR_READ                        = 0x00,
309   D12_DMA_AUTO_RELOAD                     = 0x10,
310   D12_DMA_INTR_PIN_MODE                   = 0x20,
311   
312   D12_DMA_MAIN_ENDP_OUT_INTR_ENABLE       = 0x40,
313   D12_DMA_MAIN_RX_ENDP_INTR_ENABLE        = 0x40,
314   
315   D12_DMA_MAIN_ENDP_IN_INTR_ENABLE        = 0x80,
316   D12_DMA_MAIN_TX_ENDP_INTR_ENABLE        = 0x80,
317   
318   D12_DMA_MAIN_ENDP_INTR_ENABLE           = 0xC0  // Enables IN & OUT Intr
319 };
320
321 // ----- Interrupt Register Bits -----
322
323 enum {
324   D12_INTR_RX_CTRL_ENDP           = 0x0001,
325   D12_INTR_TX_CTRL_ENDP           = 0x0002,
326   
327   D12_INTR_RX_ENDP0               = D12_INTR_RX_CTRL_ENDP,
328   D12_INTR_TX_ENDP0               = D12_INTR_TX_CTRL_ENDP,
329   D12_INTR_RX_ENDP1               = 0x0004,
330   D12_INTR_TX_ENDP1               = 0x0008,
331   D12_INTR_RX_ENDP2               = 0x0010,
332   D12_INTR_TX_ENDP2               = 0x0020,
333   
334   D12_INTR_BUS_RESET              = 0x0040,
335   D12_INTR_SUSPEND_CHANGE         = 0x0080,
336   D12_INTR_DMA_EOT                = 0x0100
337 };
338
339 // ----- Read Endpoint Status -----
340
341 enum {
342   D12_ENDP_STAT_SETUP_PACKET      = 0x04,
343   D12_ENDP_STAT_BUF0_FULL         = 0x20,
344   D12_ENDP_STAT_BUF1_FULL         = 0x40,
345   D12_ENDP_STAT_ANY_BUF_FULL      = 0x60,
346   D12_ENDP_STAT_BOTH_BUF_FULL     = 0x60,
347   D12_ENDP_STAT_STALL             = 0x80,
348 };
349
350 // ----- Last Transaction Status Bits -----
351
352 enum {
353   D12_LAST_TRANS_DATA_SUCCESS             = 0x01,
354   D12_LAST_TRANS_ERR_CODE_MASK            = 0x1E,
355   D12_LAST_TRANS_SETUP_PACKET             = 0x20,
356   D12_LAST_TRANS_DATA1_PACKET             = 0x40,
357   D12_LAST_TRANS_PREV_STAT_NOT_READ       = 0x80
358 };
359
360 static const byte RX_ENDP_INDEX[] = 
361   { D12_RX_ENDP0, D12_RX_ENDP1, D12_RX_ENDP2 };
362 static const byte TX_ENDP_INDEX[] = 
363   { D12_TX_ENDP0, D12_TX_ENDP1, D12_TX_ENDP2 };
364
365 static const int RX_ENDP_SIZE[] = { 16, 16, 64 };
366 static const int TX_ENDP_SIZE[] = { 16, 16, 64 };
367
368 typedef void (*completion_fn)(void*, int);
369
370 #ifndef USB_SETUP_PACKET_LEN 
371 #define USB_SETUP_PACKET_LEN    8
372 #endif
373
374 // ----- Command Definitions -----
375
376 enum {  
377   CMD_SET_ADDR_EN                 = 0xD0,   // Write 1 byte
378   CMD_SET_ENDP_EN                 = 0xD8,   // Write 1 byte
379   CMD_SET_MODE                    = 0xF3,   // Write 2 bytes
380   CMD_SET_DMA                     = 0xFB,   // Write/Read 1 byte
381   CMD_READ_INTR_REG               = 0xF4,   // Read 2 bytes
382   CMD_SEL_ENDP                    = 0x00,   // (+ Endp Index) Read 1 byte (opt)
383   CMD_READ_LAST_TRANS_STAT        = 0x40,   // (+ Endp Index) Read 1 byte (opt)
384   CMD_READ_ENDP_STAT              = 0x80,   // (+ Endp Index) Read 1 byte
385   CMD_READ_BUF                    = 0xF0,   // Read n bytes
386   CMD_WRITE_BUF                   = 0xF0,   // Write n bytes
387   CMD_SET_ENDP_STAT               = 0x40,   // (+ Endp Index) Write 1 byte
388   CMD_ACK_SETUP                   = 0xF1,   // None
389   CMD_CLEAR_BUF                   = 0xF2,   // None
390   CMD_VALIDATE_BUF                = 0xFA,   // None
391   CMD_SEND_RESUME                 = 0xF6,   // None
392   CMD_READ_CURR_FRAME_NUM         = 0xF5,   // Read 1 or 2 bytes
393   CMD_READ_CHIP_ID                = 0xFD    // Read 2 bytes
394 };
395
396 // ----- Set Endpoint Enable Register -----
397
398 enum {
399   ENDP_DISABLE,
400   ENDP_ENABLE
401 };
402
403 // ----- Select Endpoint Results -----
404
405 enum {
406   SEL_ENDP_FULL   = 0x01,
407   SEL_ENDP_STALL  = 0x02
408 };
409
410 // ----- Error Codes from ReadLastTrans (need to be bit shifter) -----
411
412 enum {
413   ERROR_NO_ERROR,
414   ERROR_PID_ENCODING,
415   ERROR_PID_UNKNOWN,
416   ERROR_UNEXPECTED_PACKET,
417   ERROR_TOKEN_CRC,
418   ERROR_DATA_CRC,
419   ERROR_TIMEOUT,
420   ERROR_BABBLE,
421   ERROR_UNEXPECTED_EOP,
422   ERROR_NAK,
423   ERROR_PACKET_ON_STALL,
424   ERROR_OVERFLOW,
425   ERROR_BITSTUFF,
426   ERROR_WRONG_DATA_PID
427 };
428
429 // ------------------------------------------------------------------------
430 // Routines to access the D12 registers. The hardware specific driver 
431 // provides 8bit access functions and block access functions.
432
433 #include CYGIMP_DEVS_USB_D12_HW_ACCESS_HEADER
434
435
436 static inline uint16 
437 make_word(byte hi, byte lo)
438 {
439   return ((uint16) hi << 8) | lo;
440 }
441
442 // These routines read or write 16 bit values to the data area.
443
444 static inline uint16 
445 d12_read_data_word(d12_addr_type base_addr)
446 {
447   uint16 val = d12_read_data_byte(base_addr);
448   val |= ((uint16) d12_read_data_byte(base_addr)) << 8;
449   return val;
450 }
451
452 static inline void 
453 d12_write_data_word(d12_addr_type base_addr, uint16 val)
454 {
455   d12_write_data_byte(base_addr, (byte) val);
456   d12_write_data_byte(base_addr, (byte) (val >> 8));
457 }
458
459 // ------------------------------------------------------------------------
460 // Command & Data I/O
461 // ------------------------------------------------------------------------
462 //
463 // These routines read & write the registers in the D12. The procedure is
464 // to write a register/command value to the command address (A0=1) then
465 // read or write any required data a byte at a time to the data address
466 // (A0=0). The data can be one byte or two. If two, the low byte is read/
467 // written first.
468
469 // NOTE: These MUST be atomic operations. It's up to the caller 
470 //       to insure this.
471
472 // The hardware specific driver provides the basic access function.
473 //      
474
475 static inline void 
476 d12_write_byte(d12_addr_type base_addr, byte cmd, byte val)
477 {
478   d12_write_cmd(base_addr, cmd);
479   d12_write_data_byte(base_addr, val);
480 }
481
482 static inline void 
483 d12_write_word(d12_addr_type base_addr, byte cmd, uint16 val)
484 {
485   d12_write_cmd(base_addr, cmd);
486   d12_write_data_word(base_addr, val);
487 }
488
489 static inline byte 
490 d12_read_byte(d12_addr_type base_addr, byte cmd)
491 {
492   d12_write_cmd(base_addr, cmd);
493   return d12_read_data_byte(base_addr);
494 }
495
496 static inline uint16 
497 d12_read_word(d12_addr_type base_addr, byte cmd)
498 {
499   d12_write_cmd(base_addr, cmd);
500   return d12_read_data_word(base_addr);
501 }
502
503 // ------------------------------------------------------------------------
504 // Higher Level Commands
505 // ------------------------------------------------------------------------
506
507 // Stalls or Unstalls the endpoint. Bit0=1 for stall, =0 to unstall.
508
509 static inline void 
510 d12_set_endp_status(d12_addr_type base_addr, byte endp_idx, byte stat)
511 {
512   d12_write_byte(base_addr, CMD_SET_ENDP_STAT + endp_idx, stat);
513 }
514
515 // ------------------------------------------------------------------------
516 // Stalls the control endpoint (both in & out).
517
518 static void 
519 d12_stall_ctrl_endp(d12_addr_type base_addr, bool stall)
520 {
521   d12_set_endp_status(base_addr, D12_TX_CTRL_ENDP, stall ? 1 : 0);
522   d12_set_endp_status(base_addr, D12_RX_CTRL_ENDP, stall ? 1 : 0);
523 }
524
525 // ------------------------------------------------------------------------
526 // Stalls/unstalls the specified endpoint. 
527
528 void inline 
529 d12_stall_endp(d12_addr_type base_addr, byte endp_idx, bool stall)
530 {
531   d12_set_endp_status(base_addr, endp_idx, stall ? 1 : 0);
532 }
533
534 // ------------------------------------------------------------------------ */
535 // Tells the chip that the selected endpoint buffer has been completely
536 // read. This should be called after the application reads all the data
537 // from an endpoint.  While there's data in the buffer the chip will 
538 // automatically NAK any additional OUT packets from the host. 
539
540 static inline void 
541 d12_clear_buffer(d12_addr_type base_addr)
542 {
543   d12_write_cmd(base_addr, CMD_CLEAR_BUF);
544 }
545
546 // ------------------------------------------------------------------------
547 // Tells the chip that the data in the selected endpoint buffer is complete
548 // and ready to be sent to the host.
549
550 static inline void 
551 d12_validate_buffer(d12_addr_type base_addr)
552 {
553   d12_write_cmd(base_addr, CMD_VALIDATE_BUF);
554 }
555
556 // ------------------------------------------------------------------------
557 // Sends an upstream resume signal for 10ms. This command is normally 
558 // issued when the device is in suspend.
559
560 static inline void 
561 d12_send_resume(d12_addr_type base_addr)
562 {
563   d12_write_cmd(base_addr, CMD_SEND_RESUME);
564 }
565
566 // ------------------------------------------------------------------------
567 // Gets the frame number of the last successfully received 
568 // start-of-frame (SOF).
569
570 static inline uint16 
571 d12_read_curr_frame_num(d12_addr_type base_addr)
572 {
573   return d12_read_word(base_addr, CMD_READ_CURR_FRAME_NUM);
574 }
575
576 // ------------------------------------------------------------------------
577 // This routine acknowledges a setup packet by writing an Ack Setup command
578 // to the currently selected Endpoint. This must be done for both EP0 out
579 // and EP0 IN whenever a setup packet is received.
580
581 static inline void 
582 d12_ack_setup(d12_addr_type base_addr)
583 {
584   d12_write_cmd(base_addr, CMD_ACK_SETUP);
585 }
586
587 // ------------------------------------------------------------------------
588 // Gets the value of the 16-bit interrupt register, which indicates the 
589 // source of an interrupt (if interrupts are not used, this reg can be 
590 // polled to find when service is required).
591
592 static inline uint16 
593 d12_read_intr_reg(d12_addr_type base_addr)
594 {
595   return d12_read_word(base_addr, CMD_READ_INTR_REG) & 0x01FF;
596 }
597
598 // ------------------------------------------------------------------------
599 // Gets/Sets the contents of the DMA register.
600
601 static inline byte 
602 d12_get_dma(d12_addr_type base_addr)
603 {
604   return d12_read_byte(base_addr, CMD_SET_DMA);
605 }
606
607 static inline void 
608 d12_set_dma(d12_addr_type base_addr, byte mode)
609 {
610   d12_write_byte(base_addr, CMD_SET_DMA, mode);
611 }
612
613 // ------------------------------------------------------------------------
614 // Sends the "Select Endpoint" command (0x00 - 0x0D) to the chip.
615 // This command initializes an internal pointer to the start of the 
616 // selected buffer.
617 // 
618 // Returns: Bitfield containing status of the endpoint
619
620 static byte 
621 d12_select_endp(d12_addr_type base_addr, byte endp_idx)
622 {
623   return d12_read_byte(base_addr, CMD_SEL_ENDP + endp_idx);
624 }
625
626 // ------------------------------------------------------------------------
627 // Gets the status of the last transaction of the endpoint. It also resets 
628 // the corresponding interrupt flag in the interrupt register, and clears 
629 // the status, indicating that it was read.
630 //
631 // Returns: Bitfield containing the last transaction status.
632
633 static inline byte 
634 d12_read_last_trans_status(d12_addr_type base_addr, byte endp_idx)
635 {
636   return d12_read_byte(base_addr, CMD_READ_LAST_TRANS_STAT + endp_idx);
637 }
638
639 // ------------------------------------------------------------------------
640 // Reads the status of the requested endpoint. 
641 // Just for the heck of it, we mask off the reserved bits.
642 //
643 // Returns: Bitfield containing the endpoint status.
644
645 static inline byte 
646 d12_read_endp_status(d12_addr_type base_addr, byte endp_idx)
647 {
648   return d12_read_byte(base_addr, CMD_READ_ENDP_STAT + endp_idx) & 0xE4;
649 }
650
651 // ------------------------------------------------------------------------
652 // Returns true if there is data available in the specified endpoint's
653 // ram buffer. This is determined by the buf full flags in the endp status
654 // register.
655
656 static inline bool 
657 d12_data_available(d12_addr_type base_addr, byte endp_idx)
658 {
659   byte by = d12_read_endp_status(base_addr, endp_idx);
660   return (bool) (by & D12_ENDP_STAT_ANY_BUF_FULL);
661 }
662
663 // ------------------------------------------------------------------------
664 // Clears the transaction status for each of the endpoints by calling the
665 // d12_read_last_trans_status() function for each. 
666
667 static void 
668 d12_clear_all_intr(d12_addr_type base_addr)
669 {
670   uint8 endp;
671   
672   d12_read_intr_reg(base_addr);
673   
674   for (endp=D12_ENDP_MIN; endp<=D12_ENDP_MAX; ++endp)
675     d12_read_last_trans_status(base_addr, endp);
676 }
677
678 // ------------------------------------------------------------------------
679 // Loads a value into the Set Address / Enable register. This sets the 
680 // device's USB address (lower 7 bits) and enables/disables the function
681 // (msb).
682
683 static void 
684 d12_set_addr_enable(d12_addr_type base_addr, byte usb_addr, bool enable)
685 {
686   if (enable) 
687     usb_addr |= 0x80;
688   
689   d12_write_byte(base_addr, CMD_SET_ADDR_EN, usb_addr);
690 }
691
692 // ------------------------------------------------------------------------
693 // Enables/disables the generic endpoints.
694
695 static inline void 
696 d12_set_endp_enable(d12_addr_type base_addr, bool enable)
697 {
698   d12_write_byte(base_addr, CMD_SET_ENDP_EN, 
699                  (enable) ? ENDP_ENABLE : ENDP_DISABLE);
700 }
701
702 // ------------------------------------------------------------------------
703 // Sets the device's configuration and CLKOUT frequency.
704
705 static void 
706 d12_set_mode(d12_addr_type base_addr, byte config, byte clk_div)
707 {
708   uint16 w = make_word(clk_div, config);
709   d12_write_word(base_addr, CMD_SET_MODE, w);
710 }
711
712 // ------------------------------------------------------------------------
713 // Reads a setup packet from the control endpoint. This procedure is 
714 // somewhat different than reading a data packet. By the USB standard, a 
715 // setup packet can not be NAK'ed or STALL'ed, so when the chip receives a 
716 // setup packet, it flushes the Ctrl (EP0) IN buffer and disables the 
717 // Validate and Clear Buffer commands. The processor must send an 
718 // acknowledge setup to both EP0 IN and OUT before a Validate or Clear
719 // Buffer command is effective.
720 //
721 // Parameters:
722 //      buf     buffer to receive the contents of the setup packet. Must
723 //              be at least 8 bytes.
724 // Returns:
725 //      true    if there are 8 bytes waiting in the EP0 OUT RAM buffer
726 //              on the D12 (i.e., true if successful)
727 //      false   otherwise
728
729 static bool 
730 d12_read_setup_packet(d12_addr_type base_addr, byte *buf)
731 {
732   uint8 n;
733   
734   d12_select_endp(base_addr, D12_RX_CTRL_ENDP);
735   
736   d12_read_byte(base_addr, CMD_READ_BUF);   // Read & discard reserved byte
737   n = d12_read_data_byte(base_addr);        // # bytes available
738   
739   if (n > USB_SETUP_PACKET_LEN) {
740     //TRACE("* Warning: Setup Packet too large: %u *\n", (unsigned) n);
741     n = USB_SETUP_PACKET_LEN;
742   }
743   
744   n = d12_read_data(base_addr, buf, n);
745   
746   d12_ack_setup(base_addr);
747   d12_clear_buffer(base_addr);
748   
749   // ----- Ack Setup to EP0 IN ------
750   
751   d12_select_endp(base_addr, D12_TX_CTRL_ENDP);
752   d12_ack_setup(base_addr);
753   
754   return n == USB_SETUP_PACKET_LEN;
755 }
756
757 // ------------------------------------------------------------------------
758 // Reads the contents of the currently selected endpoint's RAM buffer into 
759 // the buf[] array.
760 //
761 // The D12's buffer comes in as follows:
762 //     [0]     junk ("reserved" - can be anything). Just disregard
763 //     [1]     # data bytes to follow
764 //     [2] data byte 0, ...
765 //     up to
766 //     [N+2] data byte N-1
767 //
768 // Parameters:
769 //      buf  byte array to receive data. This MUST be at least the size
770 //           of the chip's RAM buffer for the currently selected endpoint.
771 //           If buf is NULL, the data is read & discarded.
772 //
773 // Returns: the actual number of bytes read (could be <= n)
774
775 static uint8 
776 d12_read_selected_endp_buf(d12_addr_type base_addr, byte *buf)
777 {
778   uint8 n;
779
780   d12_read_byte(base_addr, CMD_READ_BUF);   // Read & discard reserved byte
781   n = d12_read_data_byte(base_addr);        // # bytes in chip's buf
782   d12_read_data(base_addr, buf, n);
783   d12_clear_buffer(base_addr);
784
785   return n;
786 }
787
788 // ------------------------------------------------------------------------
789 // Selects the specified endpoint and reads the contents of it's RAM buffer
790 // into the buf[] array. For the Main OUT endpoint, it will check whether 
791 // both buffers are full, and if so, read them both.
792 //
793 // Side Effects:
794 //              - Leaves endp_idx as the currently selected endpoint.
795 //
796 // Parameters:
797 //      endp_idx    the endpoint from which to read
798 //      buf         buffer to receive the data. This MUST be at least the size
799 //                  of the chip's RAM buffer for the specified endpoint.
800 //                  For the Main endp, it must be 2x the buffer size (128 total)
801 //
802 // Returns: the # of bytes read.
803
804 static uint8 
805 d12_read_endp_buf(d12_addr_type base_addr, byte endp_idx, byte *buf)
806 {
807   return (d12_select_endp(base_addr, endp_idx) & SEL_ENDP_FULL)
808     ? d12_read_selected_endp_buf(base_addr, buf) : 0;
809 }
810
811 // ------------------------------------------------------------------------
812 // Does a read of the "main" endpoint (#2). Since it's double buffered,
813 // this will check if both buffers are full, and if so it will read them
814 // both. Thus the caller's buffer, buf, must be large enough to hold all
815 // the data - 128 bytes total.
816 // 
817 // If either buffer contains less than the full amount, the done flag
818 // is set indicating that a Bulk OUT transfer is complete.
819 // 
820 // This determines if a bulk transfer is done, since the caller can't 
821 // necessarily determine this from the size of the return buffer.
822 // If either buffer is less than full, '*done' is set to a non-zero value.
823
824 static uint8 
825 d12_read_main_endp_buf(d12_addr_type base_addr, byte *buf, int *done)
826 {
827   int             nBuf = 1;
828   uint8   n = 0;
829   byte    stat = d12_read_endp_status(base_addr, D12_RX_MAIN_ENDP) & 
830     D12_ENDP_STAT_ANY_BUF_FULL;
831   
832   if (stat == 0)
833     return 0;
834   
835   if (stat == D12_ENDP_STAT_BOTH_BUF_FULL)
836     nBuf++;
837   
838   *done = false;
839   
840   while (nBuf--) {
841     if (d12_select_endp(base_addr, D12_RX_MAIN_ENDP) & SEL_ENDP_FULL) {
842       uint8 n1 = d12_read_selected_endp_buf(base_addr, buf+n);
843       n += n1;
844       if (n1 < D12_MAIN_ENDP_SIZE) {
845         *done = true;
846         break;
847       }
848     }
849     else
850       *done = true;
851   }
852   return n;
853 }
854
855 // ------------------------------------------------------------------------
856 // Writes the contents of the buf[] array to the currently selected 
857 // endpoint's RAM buffer. The host will get the data on the on the next IN
858 // packet from the endpoint.
859 //
860 // Note:
861 //      - The length of the buffer, n, must be no more than the size of the
862 //      endpoint's RAM space, though, currently, this is not checked.
863 //      - It's feasible that the application needs to send an empty (NULL) 
864 //      packet. It's valid for 'n' to be zero, and/or buf NULL.
865
866 static uint8 
867 d12_write_selected_endp_buf(d12_addr_type base_addr, const byte *buf, uint8 n)
868 {
869   d12_write_byte(base_addr, CMD_WRITE_BUF, 0);
870   d12_write_data_byte(base_addr, n);
871   d12_write_data(base_addr, buf, n);
872   d12_validate_buffer(base_addr);
873   
874   return n;
875 }
876
877 // ------------------------------------------------------------------------
878 // Writes the contents of the buf[] array to the specified endoint's RAM
879 // buffer. The host will get this data on the next IN packet from the 
880 // endpoint.
881 //
882 // Side Effects:
883 //      - Leaves endp_idx as the currently selected endpoint.
884
885 static uint8 
886 d12_write_endp_buf(d12_addr_type base_addr, byte endp_idx, 
887                    const byte *buf, uint8 n)
888 {
889   d12_select_endp(base_addr, endp_idx);
890   return d12_write_selected_endp_buf(base_addr, buf, n);
891 }
892
893 // ------------------------------------------------------------------------
894 // Reads & returns the contents of the Chip ID register.
895
896 static inline uint16 
897 d12_read_chip_id(d12_addr_type base_addr)
898 {
899   return d12_read_word(base_addr, CMD_READ_CHIP_ID);
900 }
901
902
903 // ==========================================================================
904 // eCos-Specific Device Driver Code
905 // ==========================================================================
906
907 static void usbs_d12_reset(void);
908
909 // Make some abbreviations for the configuration options.
910
911 #if defined(CYGPKG_DEVS_USB_D12_RX_EP1)
912 #define _RX_EP1
913 #endif
914
915 #if defined(CYGPKG_DEVS_USB_D12_TX_EP1)
916 #define _TX_EP1
917 #endif
918
919 #if defined(CYGPKG_DEVS_USB_D12_RX_EP2)
920 #define _RX_EP2
921 #endif
922
923 #if defined(CYGPKG_DEVS_USB_D12_TX_EP2)
924 #define _TX_EP2
925 #endif
926
927 // --------------------------------------------------------------------------
928 // Endpoint 0 Data
929 // --------------------------------------------------------------------------
930
931 static cyg_interrupt    usbs_d12_intr_data;
932 static cyg_handle_t     usbs_d12_intr_handle;
933
934 static byte ep0_tx_buffer[CYGNUM_DEVS_USB_D12_EP0_TXBUFSIZE];
935
936 static void usbs_d12_start(usbs_control_endpoint*);
937 static void usbs_d12_poll(usbs_control_endpoint*);
938
939 typedef enum endp_state {
940   ENDP_STATE_IDLE,
941   ENDP_STATE_IN,
942   ENDP_STATE_OUT
943 } endp_state;
944
945 typedef struct ep0_impl {
946   usbs_control_endpoint   common;
947   endp_state              ep_state;
948   int                     length;
949   int                     transmitted;
950   bool                    tx_empty;
951 } ep0_impl;
952
953 static ep0_impl ep0 = {
954  common:
955  {
956  state:                  USBS_STATE_POWERED,
957  enumeration_data:       (usbs_enumeration_data*) 0,
958  start_fn:               &usbs_d12_start,
959  poll_fn:                &usbs_d12_poll,
960  interrupt_vector:       CYGNUM_DEVS_USB_D12_IRQ,
961  control_buffer:         { 0, 0, 0, 0, 0, 0, 0, 0 },
962  state_change_fn:        0,
963  state_change_data:      0,
964  standard_control_fn:    0,
965  standard_control_data:  0,
966  class_control_fn:       0,
967  class_control_data:     0,
968  vendor_control_fn:      0,
969  vendor_control_data:    0,
970  reserved_control_fn:    0,
971  reserved_control_data:  0,
972  buffer:                 0,
973  buffer_size:            0,
974  fill_buffer_fn:         0,
975  fill_data:              0,
976  fill_index:             0,
977  complete_fn:            0
978  },
979  ep_state:               ENDP_STATE_IDLE,
980  length:                 0,
981  transmitted:    0,
982  tx_empty:               0
983 };
984
985 extern usbs_control_endpoint usbs_d12_ep0 __attribute__((alias ("ep0")));
986
987 // --------------------------------------------------------------------------
988 // Rx Endpoints 1 & 2 Data
989 // --------------------------------------------------------------------------
990
991 #if defined(_RX_EP1) || defined(_RX_EP2)
992
993 typedef struct rx_endpoint {
994   usbs_rx_endpoint        common;
995   int                     endp, received;
996 } rx_endpoint;
997
998 static void usbs_d12_api_start_rx_ep(usbs_rx_endpoint*);
999 static void usbs_d12_api_stall_rx_ep(usbs_rx_endpoint*, cyg_bool);
1000
1001 static void usbs_d12_ep_rx_complete(rx_endpoint *ep, int result);
1002 static void usbs_d12_stall_rx_ep(rx_endpoint*, cyg_bool);
1003
1004 #endif
1005
1006
1007 #if defined(_RX_EP1)
1008
1009 static rx_endpoint rx_ep1 = {
1010  common: {
1011   start_rx_fn:    &usbs_d12_api_start_rx_ep,
1012   set_halted_fn:  &usbs_d12_api_stall_rx_ep,
1013   halted:         0
1014  },
1015  endp:            1
1016 };
1017
1018 extern usbs_rx_endpoint usbs_d12_rx_ep1 __attribute__((alias ("rx_ep1")));
1019
1020 #endif
1021
1022
1023 #if defined(_RX_EP2)
1024
1025 static rx_endpoint rx_ep2 = {
1026  common: {
1027   start_rx_fn:    &usbs_d12_api_start_rx_ep,
1028   set_halted_fn:  &usbs_d12_api_stall_rx_ep,
1029   halted:         0
1030  },
1031  endp:            2
1032 };
1033
1034 extern usbs_rx_endpoint usbs_d12_rx_ep2 __attribute__((alias ("rx_ep2")));
1035
1036 #endif
1037
1038 // --------------------------------------------------------------------------
1039 // Tx Endpoints 1 & 2 Data
1040 // --------------------------------------------------------------------------
1041
1042 #if defined(_TX_EP1) || defined(_TX_EP2)
1043
1044 typedef struct tx_endpoint {
1045   usbs_tx_endpoint        common;
1046   int                     endp, transmitted;
1047   bool                    tx_empty;
1048 } tx_endpoint;
1049
1050 static void usbs_d12_api_start_tx_ep(usbs_tx_endpoint*);
1051 static void usbs_d12_api_stall_tx_ep(usbs_tx_endpoint*, cyg_bool);
1052
1053 static void usbs_d12_ep_tx_complete(tx_endpoint *ep, int result);
1054 static void usbs_d12_stall_tx_ep(tx_endpoint*, cyg_bool);
1055 #endif
1056
1057 #if defined(_TX_EP1)
1058
1059 static tx_endpoint tx_ep1 = {
1060  common: {
1061   start_tx_fn:    &usbs_d12_api_start_tx_ep,
1062   set_halted_fn:  &usbs_d12_api_stall_tx_ep,
1063   halted:         0
1064  },
1065  endp:            1
1066 };
1067
1068 extern usbs_tx_endpoint usbs_d12_tx_ep1 __attribute__((alias ("tx_ep1")));
1069 #endif
1070
1071 #if defined(_TX_EP2)
1072
1073 static tx_endpoint tx_ep2 = {
1074  common: {
1075   start_tx_fn:    &usbs_d12_api_start_tx_ep,
1076   set_halted_fn:  &usbs_d12_api_stall_tx_ep,
1077   halted:         0
1078  },
1079  endp:            2
1080 };
1081
1082 extern usbs_tx_endpoint usbs_d12_tx_ep2 __attribute__((alias ("tx_ep2")));
1083
1084 #endif
1085
1086 // --------------------------------------------------------------------------
1087 // Synchronization
1088
1089 static inline void usbs_d12_lock(void)          { cyg_scheduler_lock(); }
1090 static inline void usbs_d12_unlock(void)        { cyg_scheduler_unlock(); }
1091
1092 // --------------------------------------------------------------------------
1093 // Control Endpoint
1094 // --------------------------------------------------------------------------
1095
1096 // Fills the EP0 transmit buffer with a packet. Partial data packets are 
1097 // retrieved by repeatedly calling the fill function.
1098
1099 static int 
1100 ep0_fill_tx_buffer(void)
1101 {
1102   int nFilled = 0;
1103   
1104   while (nFilled < CYGNUM_DEVS_USB_D12_EP0_TXBUFSIZE) {
1105     if (ep0.common.buffer_size != 0) {
1106       if ((nFilled + ep0.common.buffer_size) < 
1107           CYGNUM_DEVS_USB_D12_EP0_TXBUFSIZE) {
1108         memcpy(&ep0_tx_buffer[nFilled], ep0.common.buffer, 
1109                ep0.common.buffer_size);
1110         nFilled += ep0.common.buffer_size;
1111         ep0.common.buffer_size = 0;
1112       }
1113       else {
1114         break;
1115       }
1116     }
1117     else if (ep0.common.fill_buffer_fn) {
1118       (*ep0.common.fill_buffer_fn)(&ep0.common);
1119     }
1120     else {
1121       break;
1122     }
1123   }
1124   CYG_ASSERT((ep0.common.buffer_size == 0) && (!ep0.common.fill_buffer_fn), 
1125              "EP0 transmit buffer overflow");
1126   TRACE_D12("EP0: Filled Tx Buf with %d bytes\n", nFilled);
1127   
1128   ep0.length = nFilled;
1129   
1130   ep0.common.fill_buffer_fn       = 0;
1131   ep0.common.fill_data            = 0;
1132   ep0.common.fill_index           = 0;
1133   
1134   return nFilled;
1135 }
1136
1137 // --------------------------------------------------------------------------
1138 // Called when a transfer is complete on the control endpoint EP0. 
1139 // It resets the endpoint's data structure and calls the completion function,
1140 // if any.
1141 //
1142 // PARAMETERS:
1143 // result          0, on success
1144 //                 -EPIPE or -EIO to indicate a cancellation
1145
1146 static usbs_control_return 
1147 usbs_d12_ep0_complete(int result)
1148 {
1149   usbs_control_return ret = USBS_CONTROL_RETURN_UNKNOWN;
1150   
1151   ep0.ep_state = ENDP_STATE_IDLE;
1152   
1153   if (ep0.common.complete_fn)
1154     ret = (*ep0.common.complete_fn)(&ep0.common, result);
1155   
1156   ep0.common.buffer                       = 0;
1157   ep0.common.buffer_size          = 0;
1158   ep0.common.complete_fn          = 0;
1159   //ep0.common.fill_buffer_fn     = 0;
1160   
1161   return ret;
1162 }
1163
1164 // --------------------------------------------------------------------------
1165 // This routine is called when we want to send the next packet to the tx ep0
1166 // on the chip. It is used to start a new transfer, and is also called when
1167 // the chip interrupts to indicate that the ep0 tx buffer is empty and ready
1168 // to receive a new packet.
1169 //
1170 // NOTE:
1171 //      On the D12, when you send a zero-length packet to a tx endpoint, the
1172 //      chip transmits the empty packet to the host, but doesn't interrupt 
1173 //      indicating that it is complete. So immediately after sending the
1174 //      empty packet we complete the transfer.
1175
1176 static void 
1177 usbs_d12_ep0_tx(void)
1178 {
1179   int     nRemaining = ep0.length - ep0.transmitted;
1180   uint8   n;
1181   
1182   // ----- Intermittent interrupt? Get out -----
1183   
1184   if (!ep0.common.buffer) {
1185     TRACE_D12("EP0: Tx no buffer (%d)\n", nRemaining);
1186     return;
1187   }
1188   
1189   // ----- If prev packet was last, signal that we're done -----
1190   
1191   if (nRemaining == 0 && !ep0.tx_empty) {
1192     TRACE_D12("\tEP0: Tx Complete (%d) %p\n", ep0.transmitted, 
1193               ep0.common.complete_fn);
1194     usbs_d12_ep0_complete(0);
1195     return;
1196   }
1197   
1198   // ----- Load the next tx packet onto the chip -----
1199   
1200   if (nRemaining < D12_ENDP0_SIZE) {
1201     n = (uint8) nRemaining;
1202     ep0.tx_empty = false;
1203   }
1204   else
1205     n = D12_ENDP0_SIZE;
1206   
1207   d12_write_endp_buf(D12_BASE_ADDR, D12_TX_ENDP0, 
1208                      &ep0_tx_buffer[ep0.transmitted], n);
1209   
1210   TRACE_D12("EP0: Wrote %u bytes\n", (unsigned) n);
1211   TRACE_BUF0("\t", &ep0_tx_buffer[ep0.transmitted], n);
1212   
1213   ep0.transmitted += n;
1214   
1215   // ----- If empty packet, D12 won't interrupt, so end now ----- */
1216   
1217   if (n == 0) {
1218     TRACE_D12("\tEP0: Tx Complete (%d) %p\n", ep0.transmitted, 
1219               ep0.common.complete_fn);
1220     usbs_d12_ep0_complete(0);
1221   }
1222 }
1223
1224 // --------------------------------------------------------------------------
1225 // This function is called when a packet has been successfully sent on the
1226 // primary control endpoint (ep0). It indicates that the chip is ready for 
1227 // another packet. We read the LastTransStatus for the endpoint to clear 
1228 // the interrupt bit, then call ep0_tx() to continue the transfer.
1229
1230 static void 
1231 usbs_d12_ep0_tx_intr(void)
1232 {
1233   d12_read_last_trans_status(D12_BASE_ADDR, D12_TX_ENDP0);
1234   usbs_d12_ep0_tx();
1235 }
1236
1237 // --------------------------------------------------------------------------
1238 // Try to handle standard requests. This is a three step process:
1239 //     1.   If it's something we should handle internally we take care of it.
1240 //          Currently we can handle SET_ADDRESS requests, and a few others.
1241 //     2.   If the upper level code has installed a standard control handler
1242 //          we let that function have a crack at it.
1243 //     3.   If neither of those handle the packet we let 
1244 //          usbs_handle_standard_control() have a last try at it.
1245 //
1246 // Locally:
1247 //          SET_ADDRESS: The host is demanding that we change our USB address.
1248 //          This is done by updating the Address/Enable register on the D12. 
1249 //          Note, however that the USB protocol requires us to ack at the old 
1250 //          address, change address, and then accept the next control message
1251 //          at the new      address. The D12 address reg is buffered to do this 
1252 //          automatically for us. The updated address on the chip won't take
1253 //          affect until after the empty ack is sent. Nice.
1254 //
1255
1256 static usbs_control_return 
1257 usbs_d12_handle_std_req(usb_devreq *req)
1258 {
1259   usbs_control_return result = USBS_CONTROL_RETURN_UNKNOWN;
1260   int recipient = req->type & USB_DEVREQ_RECIPIENT_MASK;
1261
1262   if (req->request == USB_DEVREQ_SET_ADDRESS) {
1263     TRACE_D12("Setting Addr: %u\n", (unsigned) req->value_lo);
1264     d12_set_addr_enable(D12_BASE_ADDR, req->value_lo, true);
1265     result = USBS_CONTROL_RETURN_HANDLED;
1266   }
1267   else if (req->request == USB_DEVREQ_GET_STATUS) {
1268     if (recipient == USB_DEVREQ_RECIPIENT_DEVICE) {
1269       const usbs_enumeration_data *enum_data = ep0.common.enumeration_data;
1270       if (enum_data && enum_data->device.number_configurations == 1 &&
1271           enum_data->configurations) {
1272         ep0.common.control_buffer[0]  = 
1273           (enum_data->configurations[0].attributes
1274            & USB_CONFIGURATION_DESCRIPTOR_ATTR_SELF_POWERED) ? 1 : 0;
1275         ep0.common.control_buffer[0] |= 
1276           (enum_data->configurations[0].attributes
1277            & USB_CONFIGURATION_DESCRIPTOR_ATTR_REMOTE_WAKEUP) ? 2 : 0;
1278         ep0.common.control_buffer[1] = 0;
1279         result = USBS_CONTROL_RETURN_HANDLED;
1280       }
1281     }
1282     else if (recipient == USB_DEVREQ_RECIPIENT_ENDPOINT) {
1283       bool halted = false;
1284       result = USBS_CONTROL_RETURN_HANDLED;
1285
1286       switch (req->index_lo) {
1287 #if defined(_RX_EP1)
1288       case 0x01 : halted = rx_ep1.common.halted;      break;
1289 #endif
1290 #if defined(_TX_EP1)
1291       case 0x81 : halted = tx_ep1.common.halted;      break;
1292 #endif
1293 #if defined(_RX_EP2)
1294       case 0x02 : halted = rx_ep2.common.halted;      break;
1295 #endif
1296 #if defined(_TX_EP2)
1297       case 0x82 : halted = tx_ep2.common.halted;      break;
1298 #endif
1299
1300       default:
1301         result = USBS_CONTROL_RETURN_STALL;
1302       }
1303
1304       TRACE_D12("Get Status: Endp [0x%02X] %s\n", (unsigned) req->index_lo, 
1305                 halted ? "Halt" : "Unhalt");
1306       if (result == USBS_CONTROL_RETURN_HANDLED) {
1307         ep0.common.control_buffer[0] = (halted) ? 1 : 0;
1308         ep0.common.control_buffer[1] = 0;
1309       }
1310     }
1311
1312     if (result == USBS_CONTROL_RETURN_HANDLED) {
1313       ep0.common.buffer                       = ep0.common.control_buffer;
1314       ep0.common.buffer_size                  = 2;
1315       ep0.common.fill_buffer_fn               = 0;
1316       ep0.common.complete_fn                  = 0;
1317     }
1318   }
1319   else if ((req->request == USB_DEVREQ_SET_FEATURE || 
1320             req->request == USB_DEVREQ_CLEAR_FEATURE) && 
1321            recipient == USB_DEVREQ_RECIPIENT_ENDPOINT) {
1322     
1323     bool halt = (req->request == USB_DEVREQ_SET_FEATURE);
1324     result = USBS_CONTROL_RETURN_HANDLED;
1325     TRACE_D12("Endpoint [0x%02X] %s\n", (unsigned) req->index_lo, 
1326               halt ? "Halt" : "Unhalt");
1327
1328     switch (req->index_lo) {
1329 #if defined(_RX_EP1)
1330     case 0x01 :     usbs_d12_stall_rx_ep(&rx_ep1, halt);    break;
1331 #endif
1332 #if defined(_TX_EP1)
1333     case 0x81 : usbs_d12_stall_tx_ep(&tx_ep1, halt);        break;
1334 #endif
1335 #if defined(_RX_EP2)
1336     case 0x02 :     usbs_d12_stall_rx_ep(&rx_ep2, halt);    break;
1337 #endif
1338 #if defined(_TX_EP2)
1339     case 0x82 : usbs_d12_stall_tx_ep(&tx_ep2, halt);        break;
1340 #endif
1341       
1342     default:
1343       result = USBS_CONTROL_RETURN_STALL;
1344     }
1345   }
1346   else if (ep0.common.standard_control_fn != 0) {
1347     result = (*ep0.common.standard_control_fn)
1348       (&ep0.common,
1349        ep0.common.standard_control_data);
1350   }
1351   
1352   if (result == USBS_CONTROL_RETURN_UNKNOWN)
1353     result = usbs_handle_standard_control(&ep0.common);
1354   
1355   return result;
1356 }
1357
1358 // --------------------------------------------------------------------------
1359 // Handler for the receipt of a setup (dev request) packet from the host.
1360 // We examine the packet to determine what function(s) should get a crack
1361 // at trying to handle it, then pass control to the proper function. If
1362 // the function handles the message we either ACK (len==0) or prepare for
1363 // an IN or OUT data phase. If no one handled the message, we stall the
1364 // control endpoint.
1365
1366 static void 
1367 usbs_d12_ep0_setup_packet(usb_devreq* req)
1368 {
1369   int             len, dir, protocol, recipient;
1370   usbs_control_return     result = USBS_CONTROL_RETURN_UNKNOWN;
1371   
1372   // ----- See who should take the request -----
1373   
1374   len = make_word(req->length_hi, req->length_lo);
1375   
1376   dir                     = req->type & USB_DEVREQ_DIRECTION_MASK;
1377   protocol    = req->type & USB_DEVREQ_TYPE_MASK;
1378   recipient   = req->type & USB_DEVREQ_RECIPIENT_MASK;
1379   
1380   TRACE_BUF0("DevReq: ", ep0.common.control_buffer, sizeof(usb_devreq));
1381   
1382   if (protocol == USB_DEVREQ_TYPE_STANDARD)
1383     result = usbs_d12_handle_std_req(req);
1384   else {
1385     // Pass on non-standard requests to registered handlers
1386     
1387     usbs_control_return     (*callback_fn)(usbs_control_endpoint*, void*);
1388     void *callback_arg;
1389     
1390     if (protocol == USB_DEVREQ_TYPE_CLASS) {
1391       callback_fn  = ep0.common.class_control_fn;
1392       callback_arg = ep0.common.class_control_data;
1393     }
1394     else if (protocol == USB_DEVREQ_TYPE_VENDOR) {
1395       callback_fn  = ep0.common.vendor_control_fn;
1396       callback_arg = ep0.common.vendor_control_data;
1397     }
1398     else {
1399       callback_fn  = ep0.common.reserved_control_fn;
1400       callback_arg = ep0.common.reserved_control_data;
1401     }
1402     
1403     result = (callback_fn)  ? (*callback_fn)(&ep0.common, callback_arg)
1404       : USBS_CONTROL_RETURN_STALL;
1405   }
1406   
1407   // ----- If handled prep/handle data phase, otherwise stall -----
1408   
1409   if (result == USBS_CONTROL_RETURN_HANDLED) {
1410     if (len == 0) {
1411       TRACE_D12("\tCtrl ACK\n");
1412       d12_write_endp_buf(D12_BASE_ADDR, D12_TX_ENDP0, 0, 0);
1413     }
1414     else {
1415       // Set EP0 state to  IN or OUT mode for data phase
1416       ep0.transmitted = 0;
1417       ep0.length = len;
1418       
1419       if (dir == USB_DEVREQ_DIRECTION_OUT) {
1420         // Wait for the next packet from the host.
1421         ep0.ep_state = ENDP_STATE_OUT;
1422         CYG_ASSERT(ep0.common.buffer != 0, 
1423                    "A rx buffer should have been provided for EP0");
1424         CYG_ASSERT(ep0.common.complete_fn != 0, 
1425                    "A completion function should be provided for EP0 OUT control messages");
1426       }
1427       else {
1428         ep0.tx_empty = true;
1429         ep0.ep_state = ENDP_STATE_IN;
1430         ep0_fill_tx_buffer();
1431         usbs_d12_ep0_tx();
1432       }
1433     }
1434   }
1435   else {
1436     TRACE_D12("\t*** Unhandled Device Request ***\n");
1437     // The request wasn't handled, so stall control endpoint
1438     d12_stall_ctrl_endp(D12_BASE_ADDR, true);
1439   }
1440 }
1441
1442 // --------------------------------------------------------------------------
1443 // This is called when the chip indicates that a packet has been received
1444 // on control endpoint 0. If it's a setup packet, we handle it accordingly,
1445 // otherwise it's a data packet coming in on ep0.
1446 //
1447
1448 static void 
1449 usbs_d12_ep0_rx_intr(void)
1450 {
1451   byte byStat = d12_read_last_trans_status(D12_BASE_ADDR, D12_RX_ENDP0);
1452   TRACE_D12("\tEP0 Status: 0x%02X\n", (unsigned) byStat);
1453   
1454   if (byStat & D12_LAST_TRANS_SETUP_PACKET) {
1455     usb_devreq *req = (usb_devreq *) ep0.common.control_buffer;
1456     
1457     if (!d12_read_setup_packet(D12_BASE_ADDR, (byte*) req)) {
1458       TRACE_D12("ep0_rx_dsr: Error reading setup packet\n");
1459       d12_stall_ctrl_endp(D12_BASE_ADDR, true);
1460     }
1461     else
1462       usbs_d12_ep0_setup_packet(req);
1463   }
1464   else {
1465     if (ep0.common.buffer) {
1466       uint8 n = d12_read_endp_buf(D12_BASE_ADDR, D12_RX_ENDP0, 
1467                                   ep0.common.buffer + ep0.transmitted);
1468       ep0.transmitted += n;
1469       
1470       TRACE_D12("EP0: Received %d bytes\n", (unsigned) n);
1471       
1472       if (n < D12_ENDP0_SIZE || 
1473           ep0.common.buffer_size - ep0.transmitted < D12_ENDP0_SIZE) {
1474         TRACE_D12("\tEP0: Rx Complete (%d) %p\n", 
1475                   ep0.transmitted, ep0.common.complete_fn);
1476         
1477         if (usbs_d12_ep0_complete(0) == USBS_CONTROL_RETURN_HANDLED)
1478           d12_write_endp_buf(D12_BASE_ADDR, D12_TX_ENDP0, 0, 0);
1479         else
1480           d12_stall_ctrl_endp(D12_BASE_ADDR, true);
1481       }
1482     }
1483     else {
1484       TRACE_D12("EP0: No Rx buffer. Discarding packet\n");
1485       d12_read_endp_buf(D12_BASE_ADDR, D12_RX_ENDP0, NULL);
1486     }
1487   }
1488 }
1489
1490 // --------------------------------------------------------------------------
1491 // Handler for when the device is put into or taken out of suspend mode.
1492 // It updates the state variable in the control endpoint and calls the
1493 // registered state change function, if any.
1494
1495 // TODO: Put the chip into low power mode??? Stop clocks, etc???
1496
1497 static void 
1498 usbs_d12_suspend(bool suspended)
1499 {
1500   int                     old_state = ep0.common.state;
1501   usbs_state_change       state_change;
1502   
1503   if (suspended) {
1504     ep0.common.state |= USBS_STATE_SUSPENDED;
1505     state_change = USBS_STATE_CHANGE_SUSPENDED;
1506   }
1507   else {
1508     ep0.common.state &= USBS_STATE_MASK;
1509     state_change = USBS_STATE_CHANGE_RESUMED;
1510   }
1511   
1512   if (ep0.common.state_change_fn) {
1513     (*ep0.common.state_change_fn)(&ep0.common, ep0.common.state_change_data,
1514                                   state_change, old_state);
1515   }
1516 }
1517
1518 // --------------------------------------------------------------------------
1519 // Common Rx Endpoint 1 & 2
1520 // --------------------------------------------------------------------------
1521
1522 #if defined(_RX_EP1) || defined(_RX_EP2)
1523
1524 static void usbs_d12_clear_rx_ep(rx_endpoint *ep)
1525 {
1526   ep->common.buffer               = 0;
1527   ep->common.buffer_size          = 0;
1528   ep->common.complete_fn          = 0;
1529   ep->common.complete_data        = 0;
1530   
1531   ep->received                    = 0;
1532 }
1533
1534 // --------------------------------------------------------------------------
1535 // This is called when an rx operation is completed. It resets the endpoint
1536 // vars and calls the registered completion function.
1537 //
1538
1539 static void 
1540 usbs_d12_ep_rx_complete(rx_endpoint *ep, int result)
1541 {
1542   completion_fn fn = ep->common.complete_fn;
1543   void *data = ep->common.complete_data;
1544   
1545   usbs_d12_clear_rx_ep(ep);
1546   
1547   if (fn)
1548     (*fn)(data, result);
1549 }
1550
1551 // --------------------------------------------------------------------------
1552 // This routine is called when an rx buffer in the chip is full and ready to
1553 // be read. If there's an endpoint buffer available and room to hold the data
1554 // we read it in, otherwise we call the completion function, but leave the 
1555 // data in the chip. The hardware will automatically NAK packages from the
1556 // host until the app calls another start read to continue receiving data.
1557 //
1558 // CONTEXT:
1559 //         Called from either the DSR or application thread, via start rx.
1560 //         In either case, it's assumed that the chip is locked.
1561 //              
1562
1563 static void 
1564 usbs_d12_ep_rx(rx_endpoint *ep)
1565 {
1566   int             n, ep_size, buf_remaining, endp = ep->endp;
1567   bool    done;
1568   
1569   // The main endp is double buffered and we need to be prepared
1570   // to read both simultaneously.
1571   ep_size = (endp == D12_MAIN_ENDP) ? (2 * D12_MAIN_ENDP_SIZE) 
1572     : RX_ENDP_SIZE[endp];
1573   
1574   buf_remaining = ep->common.buffer_size - ep->received;
1575   
1576   // ----- If no space left in buffer, call completion fn -----
1577   
1578   if (!ep->common.buffer || buf_remaining < ep_size) {
1579     int ret = ep->received;
1580     
1581     // See if caller requested a read smaller than the endp. Read &
1582     // throw away extra
1583     if (ep->common.buffer_size < ep_size) {
1584       byte tmp_buf[D12_MAX_PACKET_SIZE];
1585       
1586       if (endp == D12_MAIN_ENDP)
1587         n = d12_read_main_endp_buf(D12_BASE_ADDR, tmp_buf, &done);
1588       else
1589         n = d12_read_endp_buf(D12_BASE_ADDR, RX_ENDP_INDEX[endp], tmp_buf);
1590       
1591       if (n > ep->common.buffer_size) {
1592         n = ep->received = ep->common.buffer_size;
1593         ret = -ENOMEM;
1594         TRACE_D12("\tEP%d: *** Rx Buffer too small. Data Lost ***\n", endp);
1595       }
1596       else
1597         ret = ep->received = n;
1598       
1599       memcpy(ep->common.buffer, tmp_buf, n);
1600       buf_remaining = ep->common.buffer_size - n;
1601     }
1602     
1603     TRACE_D12("\tEP%d: Rx Complete. Buffer (nearly) full. [%d]\n", 
1604               endp, buf_remaining);
1605     usbs_d12_ep_rx_complete(ep, ret);
1606     return;
1607   }
1608   
1609   // ----- Read the data from the chip -----
1610   
1611   if (endp == D12_MAIN_ENDP)
1612     n = d12_read_main_endp_buf(D12_BASE_ADDR, 
1613                                ep->common.buffer + ep->received, &done);
1614   else {
1615     n = d12_read_endp_buf(D12_BASE_ADDR, RX_ENDP_INDEX[endp],
1616                           ep->common.buffer + ep->received);
1617     done = (n < RX_ENDP_SIZE[endp]);
1618   }
1619   
1620   ep->received += n;
1621   buf_remaining = ep->common.buffer_size - ep->received;
1622   
1623   done = done || (buf_remaining < ep_size);
1624   
1625   TRACE_D12("EP%d: Received %d bytes.\n", endp, n);
1626   TRACE_BUF("\t", ep->common.buffer + ep->received-n, n);
1627   
1628   // ----- If we're done, complete the receive -----
1629   
1630   if (done) {
1631     TRACE_D12("\tEP%d Rx Complete (%d)  %p\n", endp, 
1632               ep->received, ep->common.complete_fn);
1633     usbs_d12_ep_rx_complete(ep, ep->received);
1634   }
1635 }
1636
1637 // --------------------------------------------------------------------------
1638 // Stalls/unstalls the specified endpoint.
1639
1640 static void 
1641 usbs_d12_stall_rx_ep(rx_endpoint *ep, cyg_bool halt)
1642 {
1643   ep->common.halted = halt;
1644   d12_stall_endp(D12_BASE_ADDR, RX_ENDP_INDEX[ep->endp], halt);
1645 }
1646
1647 // --------------------------------------------------------------------------
1648 // Handler for an Rx endpoint full interrupt. It clears the interrupt on the
1649 // D12 by reading the endpoint's status register then calls the routine to
1650 // read the data into the buffer.
1651 //
1652 // Called from the DSR context only.
1653 //
1654
1655 static void 
1656 usbs_d12_ep_rx_intr(rx_endpoint *ep)
1657 {
1658   d12_read_last_trans_status(D12_BASE_ADDR, RX_ENDP_INDEX[ep->endp]);
1659   usbs_d12_ep_rx(ep);
1660 }
1661
1662 #endif
1663
1664 // --------------------------------------------------------------------------
1665 // Common Tx Endpoint 1 & 2
1666 // --------------------------------------------------------------------------
1667
1668 #if defined(_TX_EP1) || defined(_TX_EP2)
1669
1670 // Clears out the endpoint data structure before/after a tx is complete.
1671
1672 static void usbs_d12_clear_tx_ep(tx_endpoint *ep)
1673 {
1674   ep->common.buffer = 0;
1675   ep->common.buffer_size = 0;
1676   ep->common.complete_fn = 0;
1677   ep->common.complete_data = 0;
1678   
1679   ep->transmitted = 0;
1680   ep->tx_empty = false;
1681 }
1682
1683 // --------------------------------------------------------------------------
1684 // This is called when a transmit is completed. It resets the endpoint vars
1685 // and calls the registered completion function, if any.
1686 //
1687 // CONTEXT:
1688 //         Called from either the DSR or the app thread that started tx. 
1689
1690 static void usbs_d12_ep_tx_complete(tx_endpoint *ep, int result)
1691 {
1692   completion_fn fn = ep->common.complete_fn;
1693   void *data = ep->common.complete_data;
1694   
1695   usbs_d12_clear_tx_ep(ep);
1696   
1697   if (fn)
1698     (*fn)(data, result);
1699 }
1700
1701 // --------------------------------------------------------------------------
1702 // The routine writes data to the chip and updates the endpoint's counters. 
1703 // It gets called at the start of a transfer operation to prime the device
1704 // and then gets called each time the chip finishes sending a packet to the
1705 // host and is ready for more data. If the amount of data remaining is 
1706 // smaller than can fit in the chip's endpoint buffer, then this is the last
1707 // packet to send, so we call the completion function.
1708 //
1709 // CONTEXT:
1710 //        Called from either the DSR or the app thread that started the tx
1711 //        In either case, it's assumed the chip is locked.
1712
1713 static void 
1714 usbs_d12_ep_tx(tx_endpoint *ep)
1715 {
1716   int n, nRemaining;
1717   
1718   // ----- Already done. Intermittent interrupt, so get out -----
1719   
1720   if (!ep->common.buffer)
1721     return;
1722   
1723   // ----- See how many bytes remaining in buffer -----
1724   
1725   nRemaining = ep->common.buffer_size - ep->transmitted;
1726   
1727   TRACE_D12("EP%d: Tx %p, %d Done, %d Remaining\n", ep->endp, 
1728             ep->common.buffer, ep->transmitted, nRemaining);
1729   
1730   // ----- If prev packet was last, signal that we're done -----
1731   
1732   if (nRemaining == 0 && !ep->tx_empty) {
1733     TRACE_D12("\tEP%d: Tx complete (%d)  %p\n", ep->endp, 
1734               ep->transmitted, ep->common.complete_fn);
1735     usbs_d12_ep_tx_complete(ep, ep->transmitted);
1736     return;
1737   }
1738   
1739   // ----- Write the next packet to chip -----
1740   
1741   if (nRemaining < TX_ENDP_SIZE[ep->endp]) {
1742     n = nRemaining;
1743     ep->tx_empty = false;
1744   }
1745   else
1746     n = TX_ENDP_SIZE[ep->endp];
1747   
1748   TRACE_D12("EP%d: Writing %d bytes. %s\n", ep->endp, 
1749             n, (n == 0) ? "DONE" : "");
1750   TRACE_BUF("\t", ep->common.buffer + ep->transmitted, n);
1751   
1752   d12_write_endp_buf(D12_BASE_ADDR, TX_ENDP_INDEX[ep->endp], 
1753                      ep->common.buffer + ep->transmitted, (uint8) n);
1754   
1755   ep->transmitted += n;
1756   
1757   // ----- If empty packet, complete now -----
1758   
1759   if (n == 0) {
1760     TRACE_D12("\tEP%d: Tx complete (%d)  %p\n", ep->endp, 
1761               ep->transmitted, ep->common.complete_fn);
1762     usbs_d12_ep_tx_complete(ep, ep->transmitted);
1763     return;
1764   }
1765 }
1766
1767 // --------------------------------------------------------------------------
1768 // Stalls/unstalls the specified tx endpoint.
1769
1770 static void 
1771 usbs_d12_stall_tx_ep(tx_endpoint *ep, cyg_bool halt)
1772 {
1773   ep->common.halted = halt;
1774   d12_stall_endp(D12_BASE_ADDR, TX_ENDP_INDEX[ep->endp], halt);
1775 }
1776
1777 // --------------------------------------------------------------------------
1778 // Handler for when the chip's tx RAM for an endoint has just been emptied 
1779 // (sent to the host) and the chip is ready for more data.
1780 // We read the endpoint's last trans status register to clear the interrupt
1781 // on the D12, then call the tx function to send the next packet or 
1782 // complete the transfer.
1783
1784 static void 
1785 usbs_d12_ep_tx_intr(tx_endpoint *ep)
1786 {
1787   d12_read_last_trans_status(D12_BASE_ADDR, TX_ENDP_INDEX[ep->endp]);
1788   usbs_d12_ep_tx(ep);
1789 }
1790
1791 #endif // defined(_TX_EP1) || defined(_TX_EP2)
1792
1793 // --------------------------------------------------------------------------
1794 // Application Program Interface (API)
1795 // --------------------------------------------------------------------------
1796
1797 #if defined(_RX_EP1) || defined(_RX_EP2)
1798 // Starts a receive operation on the specified endpoint. If the buffer size
1799 // is zero the completion function is called immediately. The routine checks
1800 // if tehre is data in the chip's endpoint buffer, and if so it will call
1801 // ep_rx() to start reading the data out of the chip.
1802 //
1803 // If the endpoint is currently stalled, a read size of zero can be used to 
1804 // block the calling thread until the stall is cleared. If the read size is
1805 // non-zero and the endpoint is stalled the completion function is called
1806 // immediately with an error result.
1807
1808 static void 
1809 usbs_d12_api_start_rx_ep(usbs_rx_endpoint *ep)
1810 {
1811   rx_endpoint *epx = (rx_endpoint *) ep;
1812   
1813   if (ep->halted) {
1814     if (ep->buffer_size != 0)
1815       usbs_d12_ep_rx_complete(epx, -EAGAIN);
1816   }
1817   else if (ep->buffer_size == 0) {
1818     usbs_d12_ep_rx_complete(epx, 0);
1819   }
1820   else {
1821     TRACE_D12("EP%d: Starting Rx, %p, %d\n", epx->endp, ep->buffer,
1822               ep->buffer_size);
1823     usbs_d12_lock();
1824     
1825     epx->received = 0;
1826     if (d12_data_available(D12_BASE_ADDR, RX_ENDP_INDEX[epx->endp]))
1827       usbs_d12_ep_rx(epx);
1828     
1829     usbs_d12_unlock();
1830   }
1831 }
1832
1833 // --------------------------------------------------------------------------
1834 // Halts/unhalts one of the generic rx (OUT) endpoints.
1835 //
1836
1837 static void usbs_d12_api_stall_rx_ep(usbs_rx_endpoint *ep, cyg_bool halt)
1838 {
1839   usbs_d12_lock();
1840   usbs_d12_stall_rx_ep((rx_endpoint*) ep, halt);
1841   usbs_d12_unlock();
1842 }
1843
1844 #endif // defined(_RX_EP1) || defined(_RX_EP2)
1845
1846 // --------------------------------------------------------------------------
1847 // Tx API
1848 // --------------------------------------------------------------------------
1849
1850 #if defined(_TX_EP1) || defined(_TX_EP2)
1851
1852 // This starts a transmit on one of the data endpoints. If the endpoint is
1853 // stalled a buffer size of zero can be used to block until the stall is
1854 // cleared. Any other size on a stalled endpoint will result in an error
1855 // callback immediately. The first packet is sent to the chip immediately,
1856 // in the application context. If the chip's buffer can contain the whole
1857 // transfer, the completion function will be called immediately, again,
1858 // still in the application context.
1859 //
1860 // If an empty packet is requested we send one from here and call the 
1861 // completion function. This should not cause an intr on the D12.
1862 //
1863 // CONTEXT:
1864 //        Called from an application thread
1865
1866 static void usbs_d12_api_start_tx_ep(usbs_tx_endpoint *ep)
1867 {
1868   tx_endpoint *epx = (tx_endpoint*) ep;
1869   
1870   if (ep->halted) {
1871     if (ep->buffer_size != 0) 
1872       usbs_d12_ep_tx_complete(epx, -EAGAIN);
1873   }
1874   else if (ep->buffer_size == 0) {
1875     usbs_d12_lock();
1876     
1877     d12_write_endp_buf(D12_BASE_ADDR, TX_ENDP_INDEX[epx->endp], 0, 0);
1878     usbs_d12_ep_tx_complete(epx, 0);
1879     
1880     usbs_d12_unlock();
1881   }
1882   else {
1883     TRACE_D12("EP%d: Starting Tx, %p, %d\n", epx->endp, ep->buffer,
1884               ep->buffer_size);
1885     usbs_d12_lock();
1886     
1887     epx->tx_empty = true;
1888     epx->transmitted = 0;
1889     usbs_d12_ep_tx(epx);
1890     
1891     usbs_d12_unlock();
1892   }
1893 }
1894
1895 // --------------------------------------------------------------------------
1896 // Halts/unhalts one of the generic endpoints.
1897
1898 static void 
1899 usbs_d12_api_stall_tx_ep(usbs_tx_endpoint *ep, cyg_bool halt)
1900 {
1901   usbs_d12_lock();
1902   usbs_d12_stall_tx_ep((tx_endpoint*) ep, halt);
1903   usbs_d12_unlock();
1904 }
1905
1906 #endif // defined(_TX_ENDP1) || defined(_TX_EP2)
1907
1908 // --------------------------------------------------------------------------
1909 // DSR
1910 // --------------------------------------------------------------------------
1911
1912 // The DSR for the D12 chip. This is normally called in the DSR context when
1913 // the D12 has raised its interrupt flag indicating that it needs to be 
1914 // serviced. The interrupt register contains bit flags that are OR'ed togther
1915 // indicating what items need to be serviced. There are flags for the 
1916 // following:
1917 //              - The endpoints (one bit for each)
1918 //              - Bus Reset
1919 //              - Suspend Change
1920 //              - DMA (terminal count)
1921 //
1922 // Care must be taken in that the D12's interrupt output is level-sensitive
1923 // (in that the interrupt sources are OR'ed together and not all cleared 
1924 // atomically in a single operation). Platforms (such as the PC) may be 
1925 // expecting edge-triggered interrupts, so we must work around that.
1926 // So, we loop on the interrupt register. Even though, in each loop, we
1927 // perform all of the required operations to clear the interrupts, a new
1928 // one may have arrived before we finished clearing the previous ones.
1929 // So we read the intr reg again. Once the intr reg gives a zero reading
1930 // we know that the D12 has dropped its IRQ line.
1931 //
1932 // Note, if we're configured to use a thread, this routine is called from
1933 // within a thread context (not a DSR context).
1934 //
1935
1936 static void 
1937 usbs_d12_dsr(cyg_vector_t vector, cyg_ucount32 count, 
1938                                                  cyg_addrword_t data)
1939 {
1940   uint16  status;
1941   bool    suspended;
1942   
1943   CYG_ASSERT(vector == CYGNUM_DEVS_USB_D12_INT,
1944              "DSR should only be invoked for D12 interrupts");
1945   
1946   while ((status = d12_read_intr_reg(D12_BASE_ADDR)) != 0) {
1947     TRACE_D12("Intr Status: 0x%04X\n", (unsigned) status);
1948     
1949     if (status & D12_INTR_BUS_RESET) {
1950       TRACE_D12("\n>>> Bus Reset <<<\n");
1951       usbs_d12_reset();
1952     }
1953     else {
1954       
1955       // ----- Suspend Change -----
1956       
1957       suspended = (bool) (ep0.common.state & USBS_STATE_SUSPENDED);
1958       
1959       if (status & D12_INTR_SUSPEND_CHANGE) {
1960         if (!suspended && (status & ~D12_INTR_SUSPEND_CHANGE) == 0)
1961           usbs_d12_suspend(true);
1962       }
1963       else if (suspended)
1964         usbs_d12_suspend(false);
1965       
1966       // ----- Bulk Endpoints -----
1967       
1968 #ifdef _TX_EP2
1969       if (status & D12_INTR_TX_ENDP2)
1970         usbs_d12_ep_tx_intr(&tx_ep2);
1971 #endif
1972       
1973 #ifdef _RX_EP2
1974       if (status & D12_INTR_RX_ENDP2)
1975         usbs_d12_ep_rx_intr(&rx_ep2);
1976 #endif
1977       
1978       // ----- Interrupt Endpoints -----
1979       
1980 #ifdef _TX_EP1
1981       if (status & D12_INTR_TX_ENDP1)
1982         usbs_d12_ep_tx_intr(&tx_ep1);
1983 #endif
1984       
1985 #ifdef _RX_EP1
1986       if (status & D12_INTR_RX_ENDP1)
1987         usbs_d12_ep_rx_intr(&rx_ep1);
1988 #endif
1989       
1990       // ----- Control Endpoint -----
1991       
1992       if (status & D12_INTR_TX_CTRL_ENDP)
1993         usbs_d12_ep0_tx_intr();
1994       
1995       if (status & D12_INTR_RX_CTRL_ENDP)
1996         usbs_d12_ep0_rx_intr();
1997     }
1998   }
1999   
2000   cyg_drv_interrupt_unmask(vector);
2001 }
2002
2003 // --------------------------------------------------------------------------
2004 // Interrupt
2005 // --------------------------------------------------------------------------
2006
2007 // Here, the ISR does nothing but schedule the DSR to run. The ISR's/DSR's
2008 // are serialized. The CPU won't process another ISR until after the DSR
2009 // completes.
2010
2011 static uint32 
2012 usbs_d12_isr(cyg_vector_t vector, cyg_addrword_t data)
2013 {
2014   CYG_ASSERT(CYGNUM_DEVS_USB_D12_INT == vector, 
2015              "usbs_isr: Incorrect interrupt");
2016   
2017   // Prevent another interrupt until DSR completes
2018   cyg_drv_interrupt_mask(vector);
2019   cyg_drv_interrupt_acknowledge(vector);
2020   
2021   return CYG_ISR_HANDLED | CYG_ISR_CALL_DSR;
2022 }
2023
2024 // --------------------------------------------------------------------------
2025 // Polling
2026 // --------------------------------------------------------------------------
2027
2028 static void 
2029 usbs_d12_poll(usbs_control_endpoint *endp)
2030 {
2031   CYG_ASSERT(endp == &ep0.common, "usbs_poll: wrong endpoint");
2032   
2033   usbs_d12_lock();
2034   usbs_d12_dsr(CYGNUM_DEVS_USB_D12_INT, 0, 0);
2035   usbs_d12_unlock();
2036 }
2037
2038 // --------------------------------------------------------------------------
2039 // Thread Processing
2040 // --------------------------------------------------------------------------
2041
2042 // The user can opt to configure the driver to service the D12 using a high
2043 // priority thread. The thread's priority MUST be greater than the priority
2044 // of any application thread making calls into the driver.
2045 // When we use a thread, the DSR simply signals a semaphore tio wake the
2046 // thread up. The thread, in turn, calls the the routine to service the D12,
2047 // now in a thread context. This allows for greater debug options, including
2048 // tracing.
2049
2050 #ifdef CYGPKG_DEVS_USB_D12_THREAD
2051
2052 static byte usbs_d12_thread_stack[CYGNUM_DEVS_USB_D12_THREAD_STACK_SIZE];
2053 static cyg_thread   usbs_d12_thread;
2054 static cyg_handle_t usbs_d12_thread_handle;
2055 static cyg_sem_t    usbs_d12_sem;
2056
2057 static void 
2058 usbs_d12_thread_dsr(cyg_vector_t vector, cyg_ucount32 count,
2059                     cyg_addrword_t data)
2060 {
2061   cyg_semaphore_post(&usbs_d12_sem);
2062   
2063   CYG_UNUSED_PARAM(cyg_vector_t, vector);
2064   CYG_UNUSED_PARAM(cyg_ucount32, count);
2065   CYG_UNUSED_PARAM(cyg_addrword_t, data);
2066 }
2067
2068
2069 static void 
2070 usbs_d12_thread_fn(cyg_addrword_t param)
2071 {
2072   while (1) {
2073     cyg_semaphore_wait(&usbs_d12_sem);
2074     usbs_d12_poll(&ep0.common);
2075   }
2076   
2077   CYG_UNUSED_PARAM(cyg_addrword_t, param);
2078 }
2079
2080
2081 static void 
2082 usbs_d12_thread_init(void)
2083 {
2084   cyg_semaphore_init(&usbs_d12_sem, 0);
2085   
2086   cyg_thread_create(CYGNUM_DEVS_USB_D12_THREAD_PRIORITY,
2087                     &usbs_d12_thread_fn, 0, "D12 USB Driver Thread",
2088                     usbs_d12_thread_stack, 
2089                     CYGNUM_DEVS_USB_D12_THREAD_STACK_SIZE,
2090                     &usbs_d12_thread_handle, &usbs_d12_thread);
2091   cyg_thread_resume(usbs_d12_thread_handle);
2092 }
2093
2094 #endif  // CYGPKG_DEVS_USB_D12_THREAD
2095
2096 // --------------------------------------------------------------------------
2097 // Start/Reset
2098 // --------------------------------------------------------------------------
2099
2100 // Chip initialization and handler for a USB Bus Reset. This gets called at
2101 // system startup and after a USB Bus Reset. It puts the chip into the
2102 // default state, with USB Address 0, connected to the bus (i.e. 
2103 // "SoftConnect" asserted). Interrupts to the main endpoint  are turned on
2104 // via the DMA register. 
2105
2106 static void 
2107 usbs_d12_reset(void)
2108 {
2109   int old_state = ep0.common.state;
2110   ep0.common.state = USBS_STATE_DEFAULT;
2111   
2112   if (ep0.common.state_change_fn) {
2113     (*ep0.common.state_change_fn)(&ep0.common, ep0.common.state_change_data,
2114                                   USBS_STATE_CHANGE_RESET, old_state);
2115   }
2116   
2117   d12_set_addr_enable(D12_BASE_ADDR, 0, true);
2118   d12_set_endp_enable(D12_BASE_ADDR, true);
2119   d12_set_dma(D12_BASE_ADDR, D12_DMA_MAIN_ENDP_INTR_ENABLE);
2120   d12_set_mode(D12_BASE_ADDR, D12_MODE_CFG_DFLT | D12_MODE_CFG_SOFT_CONNECT,
2121                D12_MODE_CLK_DFLT);
2122   
2123   // If any endpoints were going, signal the end of transfers
2124   
2125 #if defined(_TX_EP2)
2126   usbs_d12_ep_tx_complete(&tx_ep2, -EPIPE);
2127 #endif
2128   
2129 #if defined(_RX_EP2)
2130   usbs_d12_ep_rx_complete(&rx_ep2, -EPIPE);
2131 #endif
2132   
2133 #if defined(_TX_EP1)
2134   usbs_d12_ep_tx_complete(&tx_ep1, -EPIPE);
2135 #endif
2136   
2137 #if defined(_RX_EP1)
2138   usbs_d12_ep_rx_complete(&rx_ep1, -EPIPE);
2139 #endif
2140 }
2141
2142 // --------------------------------------------------------------------------
2143 // The start function is called indirectly by the application when 
2144 // initialization is complete. By this time, the enumeration data has been
2145 // assigned to the control endpoint and we're ready to connect to the host.
2146 // Within the reset function the D12's SoftConnect line is asserted which
2147 // allows the host (hub) to see us on the USB bus. If connected, the host 
2148 // should start the enumeration process.
2149 //
2150
2151 static void usbs_d12_start(usbs_control_endpoint *endpoint)
2152 {
2153 #if defined(_TRACE) && !defined(_TRACE_STDOUT)
2154   TRACE_OPEN(TRACE_SINK);
2155 #endif
2156   
2157   CYG_ASSERT(endpoint == &ep0.common, "ep0 start: wrong endpoint");
2158   TRACE_D12("USBS D12: Starting.\n");
2159   
2160   d12_clear_all_intr(D12_BASE_ADDR);
2161   usbs_d12_reset();
2162 }       
2163
2164 // --------------------------------------------------------------------------
2165 // Initialization
2166 // --------------------------------------------------------------------------
2167
2168 // This routine is called early in the program's startup, possibly before
2169 // main (from within a C++ object initialization). We want to put this chip
2170 // and driver in a neutral, but ready, state until the application gets 
2171 // control, initializes itself and calls the usb start function.
2172 //
2173 // The D12 has a "Soft Connect" feature to tristate the USB bus, making it
2174 // appear that the USB device is not connected to the bus. We initially
2175 // keep seperated from the bus to allow for initialization.
2176
2177 void 
2178 usbs_d12_init(void)
2179 {
2180   cyg_DSR_t *pdsr;
2181   
2182   d12_set_mode(D12_BASE_ADDR, D12_MODE_CFG_DFLT & ~D12_MODE_CFG_SOFT_CONNECT, 
2183                D12_MODE_CLK_DFLT);
2184   
2185   d12_set_addr_enable(D12_BASE_ADDR, 0, false);
2186   d12_set_endp_enable(D12_BASE_ADDR, false);
2187   
2188   // ----- Clear the endpoints -----
2189   
2190 #if defined(_TX_EP2)
2191   usbs_d12_clear_tx_ep(&tx_ep2);
2192 #endif
2193   
2194 #if defined(_RX_EP2)
2195   usbs_d12_clear_rx_ep(&rx_ep2);
2196 #endif
2197   
2198 #if defined(_TX_EP1)
2199   usbs_d12_clear_tx_ep(&tx_ep1);
2200 #endif
2201   
2202 #if defined(_RX_EP1)
2203   usbs_d12_clear_rx_ep(&rx_ep1);
2204 #endif
2205   
2206   // ----- Start the thread (if we're using it) -----
2207   
2208 #ifdef CYGPKG_DEVS_USB_D12_THREAD
2209   usbs_d12_thread_init();
2210   pdsr = &usbs_d12_thread_dsr;
2211 #else
2212   pdsr = &usbs_d12_dsr;
2213 #endif
2214   
2215   // ----- Attach the ISR -----
2216   
2217   cyg_drv_interrupt_create(CYGNUM_DEVS_USB_D12_INT, 
2218                            0, 0, &usbs_d12_isr, pdsr,
2219                            &usbs_d12_intr_handle, &usbs_d12_intr_data);
2220   
2221   cyg_drv_interrupt_attach(usbs_d12_intr_handle);
2222   cyg_drv_interrupt_unmask(CYGNUM_DEVS_USB_D12_INT);
2223 }
2224
2225 // ----------------------------------------------------------------------------
2226 // Testing support.
2227
2228 usbs_testing_endpoint usbs_testing_endpoints[] = {
2229   {
2230   endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_CONTROL, 
2231   endpoint_number     : 0,
2232   endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN,
2233   endpoint            : (void*) &ep0.common,
2234 #ifdef CYGVAR_DEVS_USB_D12_EP0_DEVTAB_ENTRY
2235   devtab_entry        : CYGDAT_DEVS_USB_D12_DEVTAB_BASENAME "0c",
2236 #else        
2237   devtab_entry        : (const char*) 0,
2238 #endif        
2239   min_size            : 1,
2240   max_size            : CYGNUM_DEVS_USB_D12_EP0_TXBUFSIZE,
2241   max_in_padding      : 0,
2242   alignment           : 0
2243   },
2244   
2245   /*
2246 #ifdef _TX_EP1
2247   {   
2248   endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_INTERRUPT,
2249   endpoint_number     : 1,
2250   endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN,
2251   endpoint            : (void*) &tx_ep1.common,
2252 # ifdef CYGVAR_DEVS_USB_D12_TX_EP2_DEVTAB_ENTRY
2253   devtab_entry        : CYGDAT_DEVS_USB_D12_DEVTAB_BASENAME "1w",
2254 # else        
2255   devtab_entry        : (const char*) 0,
2256 # endif        
2257   min_size            : 0,
2258   max_size            : 0x0FFFF,      // Driver limitation, only a single 
2259                                       // buffer descriptor is used
2260   max_in_padding      : 0,
2261   alignment           : HAL_DCACHE_LINE_SIZE
2262   },
2263 #endif
2264   
2265 #ifdef _RX_EP1
2266   {
2267   endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_INTERRUPT,
2268   endpoint_number     : 1,
2269   endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT,
2270   endpoint            : (void*) &rx_ep1.common,
2271 # ifdef CYGVAR_DEVS_USB_D12_RX_EP2_DEVTAB_ENTRY
2272   devtab_entry        : CYGDAT_DEVS_USB_D12_DEVTAB_BASENAME "1r",
2273 # else        
2274   devtab_entry        : (const char*) 0,
2275 # endif        
2276   min_size            : 1,
2277   max_size            : 0x0FFFF,      // Driver limitation
2278   max_in_padding      : 0,
2279   alignment           : HAL_DCACHE_LINE_SIZE
2280   },
2281 #endif
2282   */
2283   
2284 #ifdef _TX_EP2
2285   {
2286   endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_BULK,
2287   endpoint_number     : 2,
2288   endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_IN,
2289   endpoint            : (void*) &tx_ep2.common,
2290 # ifdef CYGVAR_DEVS_USB_D12_TX_EP2_DEVTAB_ENTRY
2291   devtab_entry        : CYGDAT_DEVS_USB_D12_DEVTAB_BASENAME "2w",
2292 # else        
2293   devtab_entry        : (const char*) 0,
2294 # endif        
2295   min_size            : 0,
2296   max_size            : 0x1000,   // 4k for testing
2297   max_in_padding      : 0,
2298   alignment           : HAL_DCACHE_LINE_SIZE
2299   },
2300 #endif
2301   
2302 #ifdef _RX_EP2
2303   {
2304   endpoint_type       : USB_ENDPOINT_DESCRIPTOR_ATTR_BULK,
2305   endpoint_number     : 2,
2306   endpoint_direction  : USB_ENDPOINT_DESCRIPTOR_ENDPOINT_OUT,
2307   endpoint            : (void*) &rx_ep2.common,
2308 # ifdef CYGVAR_DEVS_USB_D12_RX_EP2_DEVTAB_ENTRY
2309   devtab_entry        : CYGDAT_DEVS_USB_D12_DEVTAB_BASENAME "2r",
2310 # else        
2311   devtab_entry        : (const char*) 0,
2312 # endif        
2313   min_size            : 1,
2314   max_size            : 0x1000,           // 4k for testing
2315   max_in_padding      : 0,
2316   alignment           : HAL_DCACHE_LINE_SIZE
2317   },
2318 #endif
2319   
2320   USBS_TESTING_ENDPOINTS_TERMINATOR
2321 };
2322