import part of teensy3 lib
[teensytas.git] / teensy3 / usb_dev.c
1 /* Teensyduino Core Library
2  * http://www.pjrc.com/teensy/
3  * Copyright (c) 2013 PJRC.COM, LLC.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * 1. The above copyright notice and this permission notice shall be 
14  * included in all copies or substantial portions of the Software.
15  *
16  * 2. If the Software is incorporated into a build system that allows 
17  * selection among a list of target devices, then similar target
18  * devices manufactured by PJRC.COM must be included in the list of
19  * target devices and selectable in the same manner.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
25  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
26  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
27  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28  * SOFTWARE.
29  */
30
31 #include "mk20dx128.h"
32 //#include "HardwareSerial.h"
33 #include "usb_dev.h"
34 #include "usb_mem.h"
35
36 // buffer descriptor table
37
38 typedef struct {
39         uint32_t desc;
40         void * addr;
41 } bdt_t;
42
43 __attribute__ ((section(".usbdescriptortable"), used))
44 static bdt_t table[(NUM_ENDPOINTS+1)*4];
45
46 static usb_packet_t *rx_first[NUM_ENDPOINTS];
47 static usb_packet_t *rx_last[NUM_ENDPOINTS];
48 static usb_packet_t *tx_first[NUM_ENDPOINTS];
49 static usb_packet_t *tx_last[NUM_ENDPOINTS];
50 uint16_t usb_rx_byte_count_data[NUM_ENDPOINTS];
51
52 static uint8_t tx_state[NUM_ENDPOINTS];
53 #define TX_STATE_BOTH_FREE_EVEN_FIRST   0
54 #define TX_STATE_BOTH_FREE_ODD_FIRST    1
55 #define TX_STATE_EVEN_FREE              2
56 #define TX_STATE_ODD_FREE               3
57 #define TX_STATE_NONE_FREE_EVEN_FIRST   4
58 #define TX_STATE_NONE_FREE_ODD_FIRST    5
59
60 #define BDT_OWN         0x80
61 #define BDT_DATA1       0x40
62 #define BDT_DATA0       0x00
63 #define BDT_DTS         0x08
64 #define BDT_STALL       0x04
65 #define BDT_PID(n)      (((n) >> 2) & 15)
66
67 #define BDT_DESC(count, data)   (BDT_OWN | BDT_DTS \
68                                 | ((data) ? BDT_DATA1 : BDT_DATA0) \
69                                 | ((count) << 16))
70
71 #define TX   1
72 #define RX   0
73 #define ODD  1
74 #define EVEN 0
75 #define DATA0 0
76 #define DATA1 1
77 #define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
78 #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
79
80
81 static union {
82  struct {
83   union {
84    struct {
85         uint8_t bmRequestType;
86         uint8_t bRequest;
87    };
88         uint16_t wRequestAndType;
89   };
90         uint16_t wValue;
91         uint16_t wIndex;
92         uint16_t wLength;
93  };
94  struct {
95         uint32_t word1;
96         uint32_t word2;
97  };
98 } setup;
99
100
101 #define GET_STATUS              0
102 #define CLEAR_FEATURE           1
103 #define SET_FEATURE             3
104 #define SET_ADDRESS             5
105 #define GET_DESCRIPTOR          6
106 #define SET_DESCRIPTOR          7
107 #define GET_CONFIGURATION       8
108 #define SET_CONFIGURATION       9
109 #define GET_INTERFACE           10
110 #define SET_INTERFACE           11
111 #define SYNCH_FRAME             12
112
113 // SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
114 // transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
115 // Status stage uses a DATA1 PID.
116
117 static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
118 static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
119 static const uint8_t *ep0_tx_ptr = NULL;
120 static uint16_t ep0_tx_len;
121 static uint8_t ep0_tx_bdt_bank = 0;
122 static uint8_t ep0_tx_data_toggle = 0;
123 uint8_t usb_rx_memory_needed = 0;
124
125 volatile uint8_t usb_configuration = 0;
126 volatile uint8_t usb_reboot_timer = 0;
127
128
129 static void endpoint0_stall(void)
130 {
131         USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
132 }
133
134
135 static void endpoint0_transmit(const void *data, uint32_t len)
136 {
137 #if 0
138         serial_print("tx0:");
139         serial_phex32((uint32_t)data);
140         serial_print(",");
141         serial_phex16(len);
142         serial_print(ep0_tx_bdt_bank ? ", odd" : ", even");
143         serial_print(ep0_tx_data_toggle ? ", d1\n" : ", d0\n");
144 #endif
145         table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
146         table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
147         ep0_tx_data_toggle ^= 1;
148         ep0_tx_bdt_bank ^= 1;
149 }
150
151 static uint8_t reply_buffer[8];
152
153 static void usb_setup(void)
154 {
155         const uint8_t *data = NULL;
156         uint32_t datalen = 0;
157         const usb_descriptor_list_t *list;
158         uint32_t size;
159         volatile uint8_t *reg;
160         uint8_t epconf;
161         const uint8_t *cfg;
162         int i;
163
164         switch (setup.wRequestAndType) {
165           case 0x0500: // SET_ADDRESS
166                 break;
167           case 0x0900: // SET_CONFIGURATION
168                 //serial_print("configure\n");
169                 usb_configuration = setup.wValue;
170                 reg = &USB0_ENDPT1;
171                 cfg = usb_endpoint_config_table;
172                 // clear all BDT entries, free any allocated memory...
173                 for (i=4; i < (NUM_ENDPOINTS+1)*4; i++) {
174                         if (table[i].desc & BDT_OWN) {
175                                 usb_free((usb_packet_t *)((uint8_t *)(table[i].addr) - 8));
176                         }
177                 }
178                 // free all queued packets
179                 for (i=0; i < NUM_ENDPOINTS; i++) {
180                         usb_packet_t *p, *n;
181                         p = rx_first[i];
182                         while (p) {
183                                 n = p->next;
184                                 usb_free(p);
185                                 p = n;
186                         }
187                         rx_first[i] = NULL;
188                         rx_last[i] = NULL;
189                         p = tx_first[i];
190                         while (p) {
191                                 n = p->next;
192                                 usb_free(p);
193                                 p = n;
194                         }
195                         tx_first[i] = NULL;
196                         tx_last[i] = NULL;
197                         usb_rx_byte_count_data[i] = 0;
198                         switch (tx_state[i]) {
199                           case TX_STATE_EVEN_FREE:
200                           case TX_STATE_NONE_FREE_EVEN_FIRST:
201                                 tx_state[i] = TX_STATE_BOTH_FREE_EVEN_FIRST;
202                                 break;
203                           case TX_STATE_ODD_FREE:
204                           case TX_STATE_NONE_FREE_ODD_FIRST:
205                                 tx_state[i] = TX_STATE_BOTH_FREE_ODD_FIRST;
206                                 break;
207                           default:
208                                 break;
209                         }
210                 }
211                 usb_rx_memory_needed = 0;
212                 for (i=1; i <= NUM_ENDPOINTS; i++) {
213                         epconf = *cfg++;
214                         *reg = epconf;
215                         reg += 4;
216                         if (epconf & USB_ENDPT_EPRXEN) {
217                                 usb_packet_t *p;
218                                 p = usb_malloc();
219                                 if (p) {
220                                         table[index(i, RX, EVEN)].addr = p->buf;
221                                         table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
222                                 } else {
223                                         table[index(i, RX, EVEN)].desc = 0;
224                                         usb_rx_memory_needed++;
225                                 }
226                                 p = usb_malloc();
227                                 if (p) {
228                                         table[index(i, RX, ODD)].addr = p->buf;
229                                         table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
230                                 } else {
231                                         table[index(i, RX, ODD)].desc = 0;
232                                         usb_rx_memory_needed++;
233                                 }
234                         }
235                         table[index(i, TX, EVEN)].desc = 0;
236                         table[index(i, TX, ODD)].desc = 0;
237                 }
238                 break;
239           case 0x0880: // GET_CONFIGURATION
240                 reply_buffer[0] = usb_configuration;
241                 datalen = 1;
242                 data = reply_buffer;
243                 break;
244           case 0x0080: // GET_STATUS (device)
245                 reply_buffer[0] = 0;
246                 reply_buffer[1] = 0;
247                 datalen = 2;
248                 data = reply_buffer;
249                 break;
250           case 0x0082: // GET_STATUS (endpoint)
251                 if (setup.wIndex > NUM_ENDPOINTS) {
252                         // TODO: do we need to handle IN vs OUT here?
253                         endpoint0_stall();
254                         return;
255                 }
256                 reply_buffer[0] = 0;
257                 reply_buffer[1] = 0;
258                 if (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02) reply_buffer[0] = 1;
259                 data = reply_buffer;
260                 datalen = 2;
261                 break;
262           case 0x0102: // CLEAR_FEATURE (endpoint)
263                 i = setup.wIndex & 0x7F;
264                 if (i > NUM_ENDPOINTS || setup.wValue != 0) {
265                         // TODO: do we need to handle IN vs OUT here?
266                         endpoint0_stall();
267                         return;
268                 }
269                 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
270                 // TODO: do we need to clear the data toggle here?
271                 break;
272           case 0x0302: // SET_FEATURE (endpoint)
273                 i = setup.wIndex & 0x7F;
274                 if (i > NUM_ENDPOINTS || setup.wValue != 0) {
275                         // TODO: do we need to handle IN vs OUT here?
276                         endpoint0_stall();
277                         return;
278                 }
279                 (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
280                 // TODO: do we need to clear the data toggle here?
281                 break;
282           case 0x0680: // GET_DESCRIPTOR
283           case 0x0681:
284                 //serial_print("desc:");
285                 //serial_phex16(setup.wValue);
286                 //serial_print("\n");
287                 for (list = usb_descriptor_list; 1; list++) {
288                         if (list->addr == NULL) break;
289                         //if (setup.wValue == list->wValue && 
290                         //(setup.wIndex == list->wIndex) || ((setup.wValue >> 8) == 3)) {
291                         if (setup.wValue == list->wValue && setup.wIndex == list->wIndex) {
292                                 data = list->addr;
293                                 if ((setup.wValue >> 8) == 3) {
294                                         // for string descriptors, use the descriptor's
295                                         // length field, allowing runtime configured
296                                         // length.
297                                         datalen = *(list->addr);
298                                 } else {
299                                         datalen = list->length;
300                                 }
301 #if 0
302                                 serial_print("Desc found, ");
303                                 serial_phex32((uint32_t)data);
304                                 serial_print(",");
305                                 serial_phex16(datalen);
306                                 serial_print(",");
307                                 serial_phex(data[0]);
308                                 serial_phex(data[1]);
309                                 serial_phex(data[2]);
310                                 serial_phex(data[3]);
311                                 serial_phex(data[4]);
312                                 serial_phex(data[5]);
313                                 serial_print("\n");
314 #endif
315                                 goto send;
316                         }
317                 }
318                 //serial_print("desc: not found\n");
319                 endpoint0_stall();
320                 return;
321 #if defined(CDC_STATUS_INTERFACE)
322           case 0x2221: // CDC_SET_CONTROL_LINE_STATE
323                 usb_cdc_line_rtsdtr = setup.wValue;
324                 //serial_print("set control line state\n");
325                 break;
326           case 0x2321: // CDC_SEND_BREAK
327                 break;
328           case 0x2021: // CDC_SET_LINE_CODING
329                 //serial_print("set coding, waiting...\n");
330                 return;
331 #endif
332
333 // TODO: this does not work... why?
334 #if defined(SEREMU_INTERFACE) || defined(KEYBOARD_INTERFACE)
335           case 0x0921: // HID SET_REPORT
336                 //serial_print(":)\n");
337                 return;
338           case 0x0A21: // HID SET_IDLE
339                 break;
340           // case 0xC940:
341 #endif
342           default:
343                 endpoint0_stall();
344                 return;
345         }
346         send:
347         //serial_print("setup send ");
348         //serial_phex32(data);
349         //serial_print(",");
350         //serial_phex16(datalen);
351         //serial_print("\n");
352
353         if (datalen > setup.wLength) datalen = setup.wLength;
354         size = datalen;
355         if (size > EP0_SIZE) size = EP0_SIZE;
356         endpoint0_transmit(data, size);
357         data += size;
358         datalen -= size;
359         if (datalen == 0 && size < EP0_SIZE) return;
360
361         size = datalen;
362         if (size > EP0_SIZE) size = EP0_SIZE;
363         endpoint0_transmit(data, size);
364         data += size;
365         datalen -= size;
366         if (datalen == 0 && size < EP0_SIZE) return;
367
368         ep0_tx_ptr = data;
369         ep0_tx_len = datalen;
370 }
371
372
373
374 //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
375 //experiences any configuration event (configuration events are explained in
376 //Sections 9.1.1.5 and 9.4.5).
377
378 //Configuring a device or changing an alternate setting causes all of the status
379 //and configuration values associated with endpoints in the affected interfaces
380 //to be set to their default values. This includes setting the data toggle of
381 //any endpoint using data toggles to the value DATA0.
382
383 //For endpoints using data toggle, regardless of whether an endpoint has the
384 //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
385 //data toggle being reinitialized to DATA0.
386
387
388
389 // #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
390
391 static void usb_control(uint32_t stat)
392 {
393         bdt_t *b;
394         uint32_t pid, size;
395         uint8_t *buf;
396         const uint8_t *data;
397
398         b = stat2bufferdescriptor(stat);
399         pid = BDT_PID(b->desc);
400         //count = b->desc >> 16;
401         buf = b->addr;
402         //serial_print("pid:");
403         //serial_phex(pid);
404         //serial_print(", count:");
405         //serial_phex(count);
406         //serial_print("\n");
407
408         switch (pid) {
409         case 0x0D: // Setup received from host
410                 //serial_print("PID=Setup\n");
411                 //if (count != 8) ; // panic?
412                 // grab the 8 byte setup info
413                 setup.word1 = *(uint32_t *)(buf);
414                 setup.word2 = *(uint32_t *)(buf + 4);
415
416                 // give the buffer back
417                 b->desc = BDT_DESC(EP0_SIZE, DATA1);
418                 //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
419                 //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
420
421                 // clear any leftover pending IN transactions
422                 ep0_tx_ptr = NULL;
423                 if (ep0_tx_data_toggle) {
424                 }
425                 //if (table[index(0, TX, EVEN)].desc & 0x80) {
426                         //serial_print("leftover tx even\n");
427                 //}
428                 //if (table[index(0, TX, ODD)].desc & 0x80) {
429                         //serial_print("leftover tx odd\n");
430                 //}
431                 table[index(0, TX, EVEN)].desc = 0;
432                 table[index(0, TX, ODD)].desc = 0;
433                 // first IN after Setup is always DATA1
434                 ep0_tx_data_toggle = 1;
435
436 #if 0
437                 serial_print("bmRequestType:");
438                 serial_phex(setup.bmRequestType);
439                 serial_print(", bRequest:");
440                 serial_phex(setup.bRequest);
441                 serial_print(", wValue:");
442                 serial_phex16(setup.wValue);
443                 serial_print(", wIndex:");
444                 serial_phex16(setup.wIndex);
445                 serial_print(", len:");
446                 serial_phex16(setup.wLength);
447                 serial_print("\n");
448 #endif
449                 // actually "do" the setup request
450                 usb_setup();
451                 // unfreeze the USB, now that we're ready
452                 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
453                 break;
454         case 0x01:  // OUT transaction received from host
455         case 0x02:
456                 //serial_print("PID=OUT\n");
457 #ifdef CDC_STATUS_INTERFACE
458                 if (setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/) {
459                         int i;
460                         uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
461                         //serial_print("set line coding ");
462                         for (i=0; i<7; i++) {
463                                 //serial_phex(*buf);
464                                 *dst++ = *buf++;
465                         }
466                         //serial_phex32(usb_cdc_line_coding[0]);
467                         //serial_print("\n");
468                         if (usb_cdc_line_coding[0] == 134) usb_reboot_timer = 15;
469                         endpoint0_transmit(NULL, 0);
470                 }
471 #endif
472 #ifdef KEYBOARD_INTERFACE
473                 if (setup.word1 == 0x02000921 && setup.word2 == ((1<<16)|KEYBOARD_INTERFACE)) {
474                         keyboard_leds = buf[0];
475                         endpoint0_transmit(NULL, 0);
476                 }
477 #endif
478 #ifdef SEREMU_INTERFACE
479                 if (setup.word1 == 0x03000921 && setup.word2 == ((4<<16)|SEREMU_INTERFACE)
480                   && buf[0] == 0xA9 && buf[1] == 0x45 && buf[2] == 0xC2 && buf[3] == 0x6B) {
481                         usb_reboot_timer = 5;
482                         endpoint0_transmit(NULL, 0);
483                 }
484 #endif
485                 // give the buffer back
486                 b->desc = BDT_DESC(EP0_SIZE, DATA1);
487                 break;
488
489         case 0x09: // IN transaction completed to host
490                 //serial_print("PID=IN:");
491                 //serial_phex(stat);
492                 //serial_print("\n");
493
494                 // send remaining data, if any...
495                 data = ep0_tx_ptr;
496                 if (data) {
497                         size = ep0_tx_len;
498                         if (size > EP0_SIZE) size = EP0_SIZE;
499                         endpoint0_transmit(data, size);
500                         data += size;
501                         ep0_tx_len -= size;
502                         ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
503                 }
504
505                 if (setup.bRequest == 5 && setup.bmRequestType == 0) {
506                         setup.bRequest = 0;
507                         //serial_print("set address: ");
508                         //serial_phex16(setup.wValue);
509                         //serial_print("\n");
510                         USB0_ADDR = setup.wValue;
511                 }
512
513                 break;
514         //default:
515                 //serial_print("PID=unknown:");
516                 //serial_phex(pid);
517                 //serial_print("\n");
518         }
519         USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
520 }
521
522
523
524
525
526
527 usb_packet_t *usb_rx(uint32_t endpoint)
528 {
529         usb_packet_t *ret;
530         endpoint--;
531         if (endpoint >= NUM_ENDPOINTS) return NULL;
532         __disable_irq();
533         ret = rx_first[endpoint];
534         if (ret) {
535                 rx_first[endpoint] = ret->next;
536                 usb_rx_byte_count_data[endpoint] -= ret->len;
537         }
538         __enable_irq();
539         //serial_print("rx, epidx=");
540         //serial_phex(endpoint);
541         //serial_print(", packet=");
542         //serial_phex32(ret);
543         //serial_print("\n");
544         return ret;
545 }
546
547 static uint32_t usb_queue_byte_count(const usb_packet_t *p)
548 {
549         uint32_t count=0;
550
551         __disable_irq();
552         for ( ; p; p = p->next) {
553                 count += p->len;
554         }
555         __enable_irq();
556         return count;
557 }
558
559 // TODO: make this an inline function...
560 /*
561 uint32_t usb_rx_byte_count(uint32_t endpoint)
562 {
563         endpoint--;
564         if (endpoint >= NUM_ENDPOINTS) return 0;
565         return usb_rx_byte_count_data[endpoint];
566         //return usb_queue_byte_count(rx_first[endpoint]);
567 }
568 */
569
570 uint32_t usb_tx_byte_count(uint32_t endpoint)
571 {
572         endpoint--;
573         if (endpoint >= NUM_ENDPOINTS) return 0;
574         return usb_queue_byte_count(tx_first[endpoint]);
575 }
576
577 uint32_t usb_tx_packet_count(uint32_t endpoint)
578 {
579         const usb_packet_t *p;
580         uint32_t count=0;
581
582         endpoint--;
583         if (endpoint >= NUM_ENDPOINTS) return 0;
584         __disable_irq();
585         for (p = tx_first[endpoint]; p; p = p->next) count++;
586         __enable_irq();
587         return count;
588 }
589
590
591 // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
592 // receive endpoints are starving for memory.  The intention is to give
593 // endpoints needing receive memory priority over the user's code, which is
594 // likely calling usb_malloc to obtain memory for transmitting.  When the
595 // user is creating data very quickly, their consumption could starve reception
596 // without this prioritization.  The packet buffer (input) is assigned to the
597 // first endpoint needing memory.
598 //
599 void usb_rx_memory(usb_packet_t *packet)
600 {
601         unsigned int i;
602         const uint8_t *cfg;
603
604         cfg = usb_endpoint_config_table;
605         //serial_print("rx_mem:");
606         __disable_irq();
607         for (i=1; i <= NUM_ENDPOINTS; i++) {
608                 if (*cfg++ & USB_ENDPT_EPRXEN) {
609                         if (table[index(i, RX, EVEN)].desc == 0) {
610                                 table[index(i, RX, EVEN)].addr = packet->buf;
611                                 table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
612                                 usb_rx_memory_needed--;
613                                 __enable_irq();
614                                 //serial_phex(i);
615                                 //serial_print(",even\n");
616                                 return;
617                         }
618                         if (table[index(i, RX, ODD)].desc == 0) {
619                                 table[index(i, RX, ODD)].addr = packet->buf;
620                                 table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
621                                 usb_rx_memory_needed--;
622                                 __enable_irq();
623                                 //serial_phex(i);
624                                 //serial_print(",odd\n");
625                                 return;
626                         }
627                 }
628         }
629         __enable_irq();
630         // we should never reach this point.  If we get here, it means
631         // usb_rx_memory_needed was set greater than zero, but no memory
632         // was actually needed.  
633         usb_rx_memory_needed = 0;
634         usb_free(packet);
635         return;
636 }
637
638 //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
639 //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
640
641 void usb_tx(uint32_t endpoint, usb_packet_t *packet)
642 {
643         bdt_t *b = &table[index(endpoint, TX, EVEN)];
644         uint8_t next;
645
646         endpoint--;
647         if (endpoint >= NUM_ENDPOINTS) return;
648         __disable_irq();
649         //serial_print("txstate=");
650         //serial_phex(tx_state[endpoint]);
651         //serial_print("\n");
652         switch (tx_state[endpoint]) {
653           case TX_STATE_BOTH_FREE_EVEN_FIRST:
654                 next = TX_STATE_ODD_FREE;
655                 break;
656           case TX_STATE_BOTH_FREE_ODD_FIRST:
657                 b++;
658                 next = TX_STATE_EVEN_FREE;
659                 break;
660           case TX_STATE_EVEN_FREE:
661                 next = TX_STATE_NONE_FREE_ODD_FIRST;
662                 break;
663           case TX_STATE_ODD_FREE:
664                 b++;
665                 next = TX_STATE_NONE_FREE_EVEN_FIRST;
666                 break;
667           default:
668                 if (tx_first[endpoint] == NULL) {
669                         tx_first[endpoint] = packet;
670                 } else {
671                         tx_last[endpoint]->next = packet;
672                 }
673                 tx_last[endpoint] = packet;
674                 __enable_irq();
675                 return;
676         }
677         tx_state[endpoint] = next;
678         b->addr = packet->buf;
679         b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
680         __enable_irq();
681 }
682
683
684
685
686
687
688 void _reboot_Teensyduino_(void)
689 {
690         // TODO: initialize R0 with a code....
691         asm volatile("bkpt");
692 }
693
694
695
696 void usb_isr(void)
697 {
698         uint8_t status, stat, t;
699
700         //serial_print("isr");
701         //status = USB0_ISTAT;
702         //serial_phex(status);
703         //serial_print("\n");
704         restart:
705         status = USB0_ISTAT;
706
707         if ((status & USB_INTEN_SOFTOKEN /* 04 */ )) {
708                 if (usb_configuration) {
709                         t = usb_reboot_timer;
710                         if (t) {
711                                 usb_reboot_timer = --t;
712                                 if (!t) _reboot_Teensyduino_();
713                         }
714 #ifdef CDC_DATA_INTERFACE
715                         t = usb_cdc_transmit_flush_timer;
716                         if (t) {
717                                 usb_cdc_transmit_flush_timer = --t;
718                                 if (t == 0) usb_serial_flush_callback();
719                         }
720 #endif
721 #ifdef SEREMU_INTERFACE
722                         t = usb_seremu_transmit_flush_timer;
723                         if (t) {
724                                 usb_seremu_transmit_flush_timer = --t;
725                                 if (t == 0) usb_seremu_flush_callback();
726                         }
727 #endif
728 #ifdef MIDI_INTERFACE
729                         usb_midi_flush_output();
730 #endif
731 #ifdef FLIGHTSIM_INTERFACE
732                         usb_flightsim_flush_callback();
733 #endif
734                 }
735                 USB0_ISTAT = USB_INTEN_SOFTOKEN;
736         }
737
738         if ((status & USB_ISTAT_TOKDNE /* 08 */ )) {
739                 uint8_t endpoint;
740                 stat = USB0_STAT;
741                 //serial_print("token: ep=");
742                 //serial_phex(stat >> 4);
743                 //serial_print(stat & 0x08 ? ",tx" : ",rx");
744                 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
745                 endpoint = stat >> 4;
746                 if (endpoint == 0) {
747                         usb_control(stat);
748                 } else {
749                         bdt_t *b = stat2bufferdescriptor(stat);
750                         usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
751 #if 0
752                         serial_print("ep:");
753                         serial_phex(endpoint);
754                         serial_print(", pid:");
755                         serial_phex(BDT_PID(b->desc));
756                         serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
757                         serial_print(", count:");
758                         serial_phex(b->desc >> 16);
759                         serial_print("\n");
760 #endif
761                         endpoint--;     // endpoint is index to zero-based arrays
762
763                         if (stat & 0x08) { // transmit
764                                 usb_free(packet);
765                                 packet = tx_first[endpoint];
766                                 if (packet) {
767                                         //serial_print("tx packet\n");
768                                         tx_first[endpoint] = packet->next;
769                                         b->addr = packet->buf;
770                                         switch (tx_state[endpoint]) {
771                                           case TX_STATE_BOTH_FREE_EVEN_FIRST:
772                                                 tx_state[endpoint] = TX_STATE_ODD_FREE;
773                                                 break;
774                                           case TX_STATE_BOTH_FREE_ODD_FIRST:
775                                                 tx_state[endpoint] = TX_STATE_EVEN_FREE;
776                                                 break;
777                                           case TX_STATE_EVEN_FREE:
778                                                 tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
779                                                 break;
780                                           case TX_STATE_ODD_FREE:
781                                                 tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
782                                                 break;
783                                           default:
784                                                 break;
785                                         }
786                                         b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
787                                 } else {
788                                         //serial_print("tx no packet\n");
789                                         switch (tx_state[endpoint]) {
790                                           case TX_STATE_BOTH_FREE_EVEN_FIRST:
791                                           case TX_STATE_BOTH_FREE_ODD_FIRST:
792                                                 break;
793                                           case TX_STATE_EVEN_FREE:
794                                                 tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
795                                                 break;
796                                           case TX_STATE_ODD_FREE:
797                                                 tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
798                                                 break;
799                                           default:
800                                                 tx_state[endpoint] = ((uint32_t)b & 8) ?
801                                                   TX_STATE_ODD_FREE : TX_STATE_EVEN_FREE;
802                                                 break;
803                                         }
804                                 }
805                         } else { // receive
806                                 packet->len = b->desc >> 16;
807                                 if (packet->len > 0) {
808                                         packet->index = 0;
809                                         packet->next = NULL;
810                                         if (rx_first[endpoint] == NULL) {
811                                                 //serial_print("rx 1st, epidx=");
812                                                 //serial_phex(endpoint);
813                                                 //serial_print(", packet=");
814                                                 //serial_phex32((uint32_t)packet);
815                                                 //serial_print("\n");
816                                                 rx_first[endpoint] = packet;
817                                         } else {
818                                                 //serial_print("rx Nth, epidx=");
819                                                 //serial_phex(endpoint);
820                                                 //serial_print(", packet=");
821                                                 //serial_phex32((uint32_t)packet);
822                                                 //serial_print("\n");
823                                                 rx_last[endpoint]->next = packet;
824                                         }
825                                         rx_last[endpoint] = packet;
826                                         usb_rx_byte_count_data[endpoint] += packet->len;
827                                         // TODO: implement a per-endpoint maximum # of allocated packets
828                                         // so a flood of incoming data on 1 endpoint doesn't starve
829                                         // the others if the user isn't reading it regularly
830                                         packet = usb_malloc();
831                                         if (packet) {
832                                                 b->addr = packet->buf;
833                                                 b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
834                                         } else {
835                                                 //serial_print("starving ");
836                                                 //serial_phex(endpoint + 1);
837                                                 //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
838                                                 b->desc = 0;
839                                                 usb_rx_memory_needed++;
840                                         }
841                                 } else {
842                                         b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
843                                 }
844                         }
845
846
847
848
849                 }
850                 USB0_ISTAT = USB_ISTAT_TOKDNE;
851                 goto restart;
852         }
853
854
855
856         if (status & USB_ISTAT_USBRST /* 01 */ ) {
857                 //serial_print("reset\n");
858
859                 // initialize BDT toggle bits
860                 USB0_CTL = USB_CTL_ODDRST;
861                 ep0_tx_bdt_bank = 0;
862
863                 // set up buffers to receive Setup and OUT packets
864                 table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
865                 table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
866                 table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
867                 table[index(0, RX, ODD)].addr = ep0_rx1_buf;
868                 table[index(0, TX, EVEN)].desc = 0;
869                 table[index(0, TX, ODD)].desc = 0;
870                 
871                 // activate endpoint 0
872                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
873
874                 // clear all ending interrupts
875                 USB0_ERRSTAT = 0xFF;
876                 USB0_ISTAT = 0xFF;
877
878                 // set the address to zero during enumeration
879                 USB0_ADDR = 0;
880
881                 // enable other interrupts
882                 USB0_ERREN = 0xFF;
883                 USB0_INTEN = USB_INTEN_TOKDNEEN |
884                         USB_INTEN_SOFTOKEN |
885                         USB_INTEN_STALLEN |
886                         USB_INTEN_ERROREN |
887                         USB_INTEN_USBRSTEN |
888                         USB_INTEN_SLEEPEN;
889
890                 // is this necessary?
891                 USB0_CTL = USB_CTL_USBENSOFEN;
892                 return;
893         }
894
895
896         if ((status & USB_ISTAT_STALL /* 80 */ )) {
897                 //serial_print("stall:\n");
898                 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
899                 USB0_ISTAT = USB_ISTAT_STALL;
900         }
901         if ((status & USB_ISTAT_ERROR /* 02 */ )) {
902                 uint8_t err = USB0_ERRSTAT;
903                 USB0_ERRSTAT = err;
904                 //serial_print("err:");
905                 //serial_phex(err);
906                 //serial_print("\n");
907                 USB0_ISTAT = USB_ISTAT_ERROR;
908         }
909
910         if ((status & USB_ISTAT_SLEEP /* 10 */ )) {
911                 //serial_print("sleep\n");
912                 USB0_ISTAT = USB_ISTAT_SLEEP;
913         }
914
915 }
916
917
918
919 void usb_init(void)
920 {
921         int i;
922
923         //serial_begin(BAUD2DIV(115200));
924         //serial_print("usb_init\n");
925
926         usb_init_serialnumber();
927
928         for (i=0; i <= NUM_ENDPOINTS*4; i++) {
929                 table[i].desc = 0;
930                 table[i].addr = 0;
931         }
932
933         // this basically follows the flowchart in the Kinetis
934         // Quick Reference User Guide, Rev. 1, 03/2012, page 141
935
936         // assume 48 MHz clock already running
937         // SIM - enable clock
938         SIM_SCGC4 |= SIM_SCGC4_USBOTG;
939
940         // reset USB module
941         USB0_USBTRC0 = USB_USBTRC_USBRESET;
942         while ((USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0) ; // wait for reset to end
943
944         // set desc table base addr
945         USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
946         USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
947         USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
948
949         // clear all ISR flags
950         USB0_ISTAT = 0xFF;
951         USB0_ERRSTAT = 0xFF;
952         USB0_OTGISTAT = 0xFF;
953
954         USB0_USBTRC0 |= 0x40; // undocumented bit
955
956         // enable USB
957         USB0_CTL = USB_CTL_USBENSOFEN;
958         USB0_USBCTRL = 0;
959
960         // enable reset interrupt
961         USB0_INTEN = USB_INTEN_USBRSTEN;
962
963         // enable interrupt in NVIC...
964         NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
965         NVIC_ENABLE_IRQ(IRQ_USBOTG);
966
967         // enable d+ pullup
968         USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
969 }
970
971
972