blob: d57ca5dbd82195608864ef1c1635c3bc1cb9d51a [file] [log] [blame]
Brian Silverman099196d2017-06-21 23:26:02 -07001/* Teensyduino Core Library
2 * http://www.pjrc.com/teensy/
3 * Copyright (c) 2017 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 * Trying to understand this rather complex code?
31 *
32 * Kevin Cuzner wrote a simpler version, and a great blog article:
33 * http://kevincuzner.com/2014/12/12/teensy-3-1-bare-metal-writing-a-usb-driver/
34 * https://github.com/kcuzner/teensy-oscilloscope/blob/master/scope-teensy/src/usb.c
35 *
36 * Andy Payne wrote another relatively simple USB example for Freescale Kinetis
37 * https://github.com/payne92/bare-metal-arm
38 */
39
40#include "usb_dev.h"
41#if F_CPU >= 20000000 && defined(NUM_ENDPOINTS)
42
43#include "kinetis.h"
44//#include "HardwareSerial.h"
45#include "usb_mem.h"
46#include <string.h> // for memset
47
48// buffer descriptor table
49
50typedef struct {
51 uint32_t desc;
52 void * addr;
53} bdt_t;
54
55__attribute__ ((section(".usbdescriptortable"), used))
56static bdt_t table[(NUM_ENDPOINTS+1)*4];
57
58static usb_packet_t *rx_first[NUM_ENDPOINTS];
59static usb_packet_t *rx_last[NUM_ENDPOINTS];
60static usb_packet_t *tx_first[NUM_ENDPOINTS];
61static usb_packet_t *tx_last[NUM_ENDPOINTS];
62uint16_t usb_rx_byte_count_data[NUM_ENDPOINTS];
63
64static uint8_t tx_state[NUM_ENDPOINTS];
65#define TX_STATE_BOTH_FREE_EVEN_FIRST 0
66#define TX_STATE_BOTH_FREE_ODD_FIRST 1
67#define TX_STATE_EVEN_FREE 2
68#define TX_STATE_ODD_FREE 3
69#define TX_STATE_NONE_FREE_EVEN_FIRST 4
70#define TX_STATE_NONE_FREE_ODD_FIRST 5
71
72#define BDT_OWN 0x80
73#define BDT_DATA1 0x40
74#define BDT_DATA0 0x00
75#define BDT_DTS 0x08
76#define BDT_STALL 0x04
77#define BDT_PID(n) (((n) >> 2) & 15)
78
79#define BDT_DESC(count, data) (BDT_OWN | BDT_DTS \
80 | ((data) ? BDT_DATA1 : BDT_DATA0) \
81 | ((count) << 16))
82
83#define TX 1
84#define RX 0
85#define ODD 1
86#define EVEN 0
87#define DATA0 0
88#define DATA1 1
89#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
90#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
91
92
93static union {
94 struct {
95 union {
96 struct {
97 uint8_t bmRequestType;
98 uint8_t bRequest;
99 };
100 uint16_t wRequestAndType;
101 };
102 uint16_t wValue;
103 uint16_t wIndex;
104 uint16_t wLength;
105 };
106 struct {
107 uint32_t word1;
108 uint32_t word2;
109 };
110} setup;
111
112
113#define GET_STATUS 0
114#define CLEAR_FEATURE 1
115#define SET_FEATURE 3
116#define SET_ADDRESS 5
117#define GET_DESCRIPTOR 6
118#define SET_DESCRIPTOR 7
119#define GET_CONFIGURATION 8
120#define SET_CONFIGURATION 9
121#define GET_INTERFACE 10
122#define SET_INTERFACE 11
123#define SYNCH_FRAME 12
124
125// SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
126// transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
127// Status stage uses a DATA1 PID.
128
129static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
130static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
131static const uint8_t *ep0_tx_ptr = NULL;
132static uint16_t ep0_tx_len;
133static uint8_t ep0_tx_bdt_bank = 0;
134static uint8_t ep0_tx_data_toggle = 0;
135uint8_t usb_rx_memory_needed = 0;
136
137volatile uint8_t usb_configuration = 0;
138volatile uint8_t usb_reboot_timer = 0;
139
140
141static void endpoint0_stall(void)
142{
143 USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
144}
145
146
147static void endpoint0_transmit(const void *data, uint32_t len)
148{
149#if 0
150 serial_print("tx0:");
151 serial_phex32((uint32_t)data);
152 serial_print(",");
153 serial_phex16(len);
154 serial_print(ep0_tx_bdt_bank ? ", odd" : ", even");
155 serial_print(ep0_tx_data_toggle ? ", d1\n" : ", d0\n");
156#endif
157 table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
158 table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
159 ep0_tx_data_toggle ^= 1;
160 ep0_tx_bdt_bank ^= 1;
161}
162
163static uint8_t reply_buffer[8];
164
165static void usb_setup(void)
166{
167 const uint8_t *data = NULL;
168 uint32_t datalen = 0;
169 const usb_descriptor_list_t *list;
170 uint32_t size;
171 volatile uint8_t *reg;
172 uint8_t epconf;
173 const uint8_t *cfg;
174 int i;
175
176 switch (setup.wRequestAndType) {
177 case 0x0500: // SET_ADDRESS
178 break;
179 case 0x0900: // SET_CONFIGURATION
180 //serial_print("configure\n");
181 usb_configuration = setup.wValue;
182 reg = &USB0_ENDPT1;
183 cfg = usb_endpoint_config_table;
184 // clear all BDT entries, free any allocated memory...
185 for (i=4; i < (NUM_ENDPOINTS+1)*4; i++) {
186 if (table[i].desc & BDT_OWN) {
187 usb_free((usb_packet_t *)((uint8_t *)(table[i].addr) - 8));
188 }
189 }
190 // free all queued packets
191 for (i=0; i < NUM_ENDPOINTS; i++) {
192 usb_packet_t *p, *n;
193 p = rx_first[i];
194 while (p) {
195 n = p->next;
196 usb_free(p);
197 p = n;
198 }
199 rx_first[i] = NULL;
200 rx_last[i] = NULL;
201 p = tx_first[i];
202 while (p) {
203 n = p->next;
204 usb_free(p);
205 p = n;
206 }
207 tx_first[i] = NULL;
208 tx_last[i] = NULL;
209 usb_rx_byte_count_data[i] = 0;
210 switch (tx_state[i]) {
211 case TX_STATE_EVEN_FREE:
212 case TX_STATE_NONE_FREE_EVEN_FIRST:
213 tx_state[i] = TX_STATE_BOTH_FREE_EVEN_FIRST;
214 break;
215 case TX_STATE_ODD_FREE:
216 case TX_STATE_NONE_FREE_ODD_FIRST:
217 tx_state[i] = TX_STATE_BOTH_FREE_ODD_FIRST;
218 break;
219 default:
220 break;
221 }
222 }
223 usb_rx_memory_needed = 0;
224 for (i=1; i <= NUM_ENDPOINTS; i++) {
225 epconf = *cfg++;
226 *reg = epconf;
227 reg += 4;
228#ifdef AUDIO_INTERFACE
229 if (i == AUDIO_RX_ENDPOINT) {
230 table[index(i, RX, EVEN)].addr = usb_audio_receive_buffer;
231 table[index(i, RX, EVEN)].desc = (AUDIO_RX_SIZE<<16) | BDT_OWN;
232 table[index(i, RX, ODD)].addr = usb_audio_receive_buffer;
233 table[index(i, RX, ODD)].desc = (AUDIO_RX_SIZE<<16) | BDT_OWN;
234 } else
235#endif
236 if (epconf & USB_ENDPT_EPRXEN) {
237 usb_packet_t *p;
238 p = usb_malloc();
239 if (p) {
240 table[index(i, RX, EVEN)].addr = p->buf;
241 table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
242 } else {
243 table[index(i, RX, EVEN)].desc = 0;
244 usb_rx_memory_needed++;
245 }
246 p = usb_malloc();
247 if (p) {
248 table[index(i, RX, ODD)].addr = p->buf;
249 table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
250 } else {
251 table[index(i, RX, ODD)].desc = 0;
252 usb_rx_memory_needed++;
253 }
254 }
255 table[index(i, TX, EVEN)].desc = 0;
256 table[index(i, TX, ODD)].desc = 0;
257#ifdef AUDIO_INTERFACE
258 if (i == AUDIO_SYNC_ENDPOINT) {
259 table[index(i, TX, EVEN)].addr = &usb_audio_sync_feedback;
260 table[index(i, TX, EVEN)].desc = (3<<16) | BDT_OWN;
261 }
262#endif
263 }
264 break;
265 case 0x0880: // GET_CONFIGURATION
266 reply_buffer[0] = usb_configuration;
267 datalen = 1;
268 data = reply_buffer;
269 break;
270 case 0x0080: // GET_STATUS (device)
271 reply_buffer[0] = 0;
272 reply_buffer[1] = 0;
273 datalen = 2;
274 data = reply_buffer;
275 break;
276 case 0x0082: // GET_STATUS (endpoint)
277 i = setup.wIndex & 0x7F;
278 if (i > NUM_ENDPOINTS) {
279 // TODO: do we need to handle IN vs OUT here?
280 endpoint0_stall();
281 return;
282 }
283 reply_buffer[0] = 0;
284 reply_buffer[1] = 0;
285 if (*(uint8_t *)(&USB0_ENDPT0 + i * 4) & 0x02) reply_buffer[0] = 1;
286 data = reply_buffer;
287 datalen = 2;
288 break;
289 case 0x0102: // CLEAR_FEATURE (endpoint)
290 i = setup.wIndex & 0x7F;
291 if (i > NUM_ENDPOINTS || setup.wValue != 0) {
292 // TODO: do we need to handle IN vs OUT here?
293 endpoint0_stall();
294 return;
295 }
296 (*(uint8_t *)(&USB0_ENDPT0 + i * 4)) &= ~0x02;
297 // TODO: do we need to clear the data toggle here?
298 break;
299 case 0x0302: // SET_FEATURE (endpoint)
300 i = setup.wIndex & 0x7F;
301 if (i > NUM_ENDPOINTS || setup.wValue != 0) {
302 // TODO: do we need to handle IN vs OUT here?
303 endpoint0_stall();
304 return;
305 }
306 (*(uint8_t *)(&USB0_ENDPT0 + i * 4)) |= 0x02;
307 // TODO: do we need to clear the data toggle here?
308 break;
309 case 0x0680: // GET_DESCRIPTOR
310 case 0x0681:
311 //serial_print("desc:");
312 //serial_phex16(setup.wValue);
313 //serial_print("\n");
314 for (list = usb_descriptor_list; 1; list++) {
315 if (list->addr == NULL) break;
316 //if (setup.wValue == list->wValue &&
317 //(setup.wIndex == list->wIndex) || ((setup.wValue >> 8) == 3)) {
318 if (setup.wValue == list->wValue && setup.wIndex == list->wIndex) {
319 data = list->addr;
320 if ((setup.wValue >> 8) == 3) {
321 // for string descriptors, use the descriptor's
322 // length field, allowing runtime configured
323 // length.
324 datalen = *(list->addr);
325 } else {
326 datalen = list->length;
327 }
328#if 0
329 serial_print("Desc found, ");
330 serial_phex32((uint32_t)data);
331 serial_print(",");
332 serial_phex16(datalen);
333 serial_print(",");
334 serial_phex(data[0]);
335 serial_phex(data[1]);
336 serial_phex(data[2]);
337 serial_phex(data[3]);
338 serial_phex(data[4]);
339 serial_phex(data[5]);
340 serial_print("\n");
341#endif
342 goto send;
343 }
344 }
345 //serial_print("desc: not found\n");
346 endpoint0_stall();
347 return;
348#if defined(CDC_STATUS_INTERFACE)
349 case 0x2221: // CDC_SET_CONTROL_LINE_STATE
350 usb_cdc_line_rtsdtr_millis = systick_millis_count;
351 usb_cdc_line_rtsdtr = setup.wValue;
352 //serial_print("set control line state\n");
353 break;
354 case 0x2321: // CDC_SEND_BREAK
355 break;
356 case 0x2021: // CDC_SET_LINE_CODING
357 //serial_print("set coding, waiting...\n");
358 return;
359#endif
360
361#if defined(MTP_INTERFACE)
362 case 0x64A1: // Cancel Request (PTP spec, 5.2.1, page 8)
363 // TODO: required by PTP spec
364 endpoint0_stall();
365 return;
366 case 0x66A1: // Device Reset (PTP spec, 5.2.3, page 10)
367 // TODO: required by PTP spec
368 endpoint0_stall();
369 return;
370 case 0x67A1: // Get Device Statis (PTP spec, 5.2.4, page 10)
371 // For now, always respond with status ok.
372 reply_buffer[0] = 0x4;
373 reply_buffer[1] = 0;
374 reply_buffer[2] = 0x01;
375 reply_buffer[3] = 0x20;
376 data = reply_buffer;
377 datalen = 4;
378 break;
379#endif
380
381// TODO: this does not work... why?
382#if defined(SEREMU_INTERFACE) || defined(KEYBOARD_INTERFACE)
383 case 0x0921: // HID SET_REPORT
384 //serial_print(":)\n");
385 return;
386 case 0x0A21: // HID SET_IDLE
387 break;
388 // case 0xC940:
389#endif
390
391#if defined(AUDIO_INTERFACE)
392 case 0x0B01: // SET_INTERFACE (alternate setting)
393 if (setup.wIndex == AUDIO_INTERFACE+1) {
394 usb_audio_transmit_setting = setup.wValue;
395 if (usb_audio_transmit_setting > 0) {
396 bdt_t *b = &table[index(AUDIO_TX_ENDPOINT, TX, EVEN)];
397 uint8_t state = tx_state[AUDIO_TX_ENDPOINT-1];
398 if (state) b++;
399 if (!(b->desc & BDT_OWN)) {
400 memset(usb_audio_transmit_buffer, 0, 176);
401 b->addr = usb_audio_transmit_buffer;
402 b->desc = (176 << 16) | BDT_OWN;
403 tx_state[AUDIO_TX_ENDPOINT-1] = state ^ 1;
404 }
405 }
406 } else if (setup.wIndex == AUDIO_INTERFACE+2) {
407 usb_audio_receive_setting = setup.wValue;
408 } else {
409 endpoint0_stall();
410 return;
411 }
412 break;
413 case 0x0A81: // GET_INTERFACE (alternate setting)
414 datalen = 1;
415 data = reply_buffer;
416 if (setup.wIndex == AUDIO_INTERFACE+1) {
417 reply_buffer[0] = usb_audio_transmit_setting;
418 } else if (setup.wIndex == AUDIO_INTERFACE+2) {
419 reply_buffer[0] = usb_audio_receive_setting;
420 } else {
421 endpoint0_stall();
422 return;
423 }
424 break;
425 case 0x0121: // SET FEATURE
426 case 0x0221:
427 case 0x0321:
428 case 0x0421:
429 // handle these on the next packet. See usb_audio_set_feature()
430 return;
431 case 0x81A1: // GET FEATURE
432 case 0x82A1:
433 case 0x83A1:
434 case 0x84A1:
435 if (usb_audio_get_feature(&setup, reply_buffer, &datalen)) {
436 data = reply_buffer;
437 }
438 else {
439 endpoint0_stall();
440 return;
441 }
442 break;
443
444 case 0x81A2: // GET_CUR (wValue=0, wIndex=interface, wLength=len)
445 if (setup.wLength >= 3) {
446 reply_buffer[0] = 44100 & 255;
447 reply_buffer[1] = 44100 >> 8;
448 reply_buffer[2] = 0;
449 datalen = 3;
450 data = reply_buffer;
451 } else {
452 endpoint0_stall();
453 return;
454 }
455 break;
456#endif
457
458#if defined(MULTITOUCH_INTERFACE)
459 case 0x01A1:
460 if (setup.wValue == 0x0300 && setup.wIndex == MULTITOUCH_INTERFACE) {
461 reply_buffer[0] = MULTITOUCH_FINGERS;
462 data = reply_buffer;
463 datalen = 1;
464 } else {
465 endpoint0_stall();
466 return;
467 }
468 break;
469#endif
470 default:
471 endpoint0_stall();
472 return;
473 }
474 send:
475 //serial_print("setup send ");
476 //serial_phex32(data);
477 //serial_print(",");
478 //serial_phex16(datalen);
479 //serial_print("\n");
480
481 if (datalen > setup.wLength) datalen = setup.wLength;
482 size = datalen;
483 if (size > EP0_SIZE) size = EP0_SIZE;
484 endpoint0_transmit(data, size);
485 data += size;
486 datalen -= size;
487 if (datalen == 0 && size < EP0_SIZE) return;
488
489 size = datalen;
490 if (size > EP0_SIZE) size = EP0_SIZE;
491 endpoint0_transmit(data, size);
492 data += size;
493 datalen -= size;
494 if (datalen == 0 && size < EP0_SIZE) return;
495
496 ep0_tx_ptr = data;
497 ep0_tx_len = datalen;
498}
499
500
501
502//A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
503//experiences any configuration event (configuration events are explained in
504//Sections 9.1.1.5 and 9.4.5).
505
506//Configuring a device or changing an alternate setting causes all of the status
507//and configuration values associated with endpoints in the affected interfaces
508//to be set to their default values. This includes setting the data toggle of
509//any endpoint using data toggles to the value DATA0.
510
511//For endpoints using data toggle, regardless of whether an endpoint has the
512//Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
513//data toggle being reinitialized to DATA0.
514
515
516
517// #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
518
519static void usb_control(uint32_t stat)
520{
521 bdt_t *b;
522 uint32_t pid, size;
523 uint8_t *buf;
524 const uint8_t *data;
525
526 b = stat2bufferdescriptor(stat);
527 pid = BDT_PID(b->desc);
528 //count = b->desc >> 16;
529 buf = b->addr;
530 //serial_print("pid:");
531 //serial_phex(pid);
532 //serial_print(", count:");
533 //serial_phex(count);
534 //serial_print("\n");
535
536 switch (pid) {
537 case 0x0D: // Setup received from host
538 //serial_print("PID=Setup\n");
539 //if (count != 8) ; // panic?
540 // grab the 8 byte setup info
541 setup.word1 = *(uint32_t *)(buf);
542 setup.word2 = *(uint32_t *)(buf + 4);
543
544 // give the buffer back
545 b->desc = BDT_DESC(EP0_SIZE, DATA1);
546 //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
547 //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
548
549 // clear any leftover pending IN transactions
550 ep0_tx_ptr = NULL;
551 if (ep0_tx_data_toggle) {
552 }
553 //if (table[index(0, TX, EVEN)].desc & 0x80) {
554 //serial_print("leftover tx even\n");
555 //}
556 //if (table[index(0, TX, ODD)].desc & 0x80) {
557 //serial_print("leftover tx odd\n");
558 //}
559 table[index(0, TX, EVEN)].desc = 0;
560 table[index(0, TX, ODD)].desc = 0;
561 // first IN after Setup is always DATA1
562 ep0_tx_data_toggle = 1;
563
564#if 0
565 serial_print("bmRequestType:");
566 serial_phex(setup.bmRequestType);
567 serial_print(", bRequest:");
568 serial_phex(setup.bRequest);
569 serial_print(", wValue:");
570 serial_phex16(setup.wValue);
571 serial_print(", wIndex:");
572 serial_phex16(setup.wIndex);
573 serial_print(", len:");
574 serial_phex16(setup.wLength);
575 serial_print("\n");
576#endif
577 // actually "do" the setup request
578 usb_setup();
579 // unfreeze the USB, now that we're ready
580 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
581 break;
582 case 0x01: // OUT transaction received from host
583 case 0x02:
584 //serial_print("PID=OUT\n");
585#ifdef CDC_STATUS_INTERFACE
586 if (setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/) {
587 int i;
588 uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
589 //serial_print("set line coding ");
590 for (i=0; i<7; i++) {
591 //serial_phex(*buf);
592 *dst++ = *buf++;
593 }
594 //serial_phex32(usb_cdc_line_coding[0]);
595 //serial_print("\n");
596 if (usb_cdc_line_coding[0] == 134) usb_reboot_timer = 15;
597 endpoint0_transmit(NULL, 0);
598 }
599#endif
600#ifdef KEYBOARD_INTERFACE
601 if (setup.word1 == 0x02000921 && setup.word2 == ((1<<16)|KEYBOARD_INTERFACE)) {
602 keyboard_leds = buf[0];
603 endpoint0_transmit(NULL, 0);
604 }
605#endif
606#ifdef SEREMU_INTERFACE
607 if (setup.word1 == 0x03000921 && setup.word2 == ((4<<16)|SEREMU_INTERFACE)
608 && buf[0] == 0xA9 && buf[1] == 0x45 && buf[2] == 0xC2 && buf[3] == 0x6B) {
609 usb_reboot_timer = 5;
610 endpoint0_transmit(NULL, 0);
611 }
612#endif
613#ifdef AUDIO_INTERFACE
614 if (usb_audio_set_feature(&setup, buf)) {
615 endpoint0_transmit(NULL, 0);
616 }
617#endif
618 // give the buffer back
619 b->desc = BDT_DESC(EP0_SIZE, DATA1);
620 break;
621
622 case 0x09: // IN transaction completed to host
623 //serial_print("PID=IN:");
624 //serial_phex(stat);
625 //serial_print("\n");
626
627 // send remaining data, if any...
628 data = ep0_tx_ptr;
629 if (data) {
630 size = ep0_tx_len;
631 if (size > EP0_SIZE) size = EP0_SIZE;
632 endpoint0_transmit(data, size);
633 data += size;
634 ep0_tx_len -= size;
635 ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
636 }
637
638 if (setup.bRequest == 5 && setup.bmRequestType == 0) {
639 setup.bRequest = 0;
640 //serial_print("set address: ");
641 //serial_phex16(setup.wValue);
642 //serial_print("\n");
643 USB0_ADDR = setup.wValue;
644 }
645
646 break;
647 //default:
648 //serial_print("PID=unknown:");
649 //serial_phex(pid);
650 //serial_print("\n");
651 }
652 USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
653}
654
655
656
657
658
659
660usb_packet_t *usb_rx(uint32_t endpoint)
661{
662 usb_packet_t *ret;
663 endpoint--;
664 if (endpoint >= NUM_ENDPOINTS) return NULL;
665 __disable_irq();
666 ret = rx_first[endpoint];
667 if (ret) {
668 rx_first[endpoint] = ret->next;
669 usb_rx_byte_count_data[endpoint] -= ret->len;
670 }
671 __enable_irq();
672 //serial_print("rx, epidx=");
673 //serial_phex(endpoint);
674 //serial_print(", packet=");
675 //serial_phex32(ret);
676 //serial_print("\n");
677 return ret;
678}
679
680static uint32_t usb_queue_byte_count(const usb_packet_t *p)
681{
682 uint32_t count=0;
683
684 __disable_irq();
685 for ( ; p; p = p->next) {
686 count += p->len;
687 }
688 __enable_irq();
689 return count;
690}
691
692// TODO: make this an inline function...
693/*
694uint32_t usb_rx_byte_count(uint32_t endpoint)
695{
696 endpoint--;
697 if (endpoint >= NUM_ENDPOINTS) return 0;
698 return usb_rx_byte_count_data[endpoint];
699 //return usb_queue_byte_count(rx_first[endpoint]);
700}
701*/
702
703uint32_t usb_tx_byte_count(uint32_t endpoint)
704{
705 endpoint--;
706 if (endpoint >= NUM_ENDPOINTS) return 0;
707 return usb_queue_byte_count(tx_first[endpoint]);
708}
709
710uint32_t usb_tx_packet_count(uint32_t endpoint)
711{
712 const usb_packet_t *p;
713 uint32_t count=0;
714
715 endpoint--;
716 if (endpoint >= NUM_ENDPOINTS) return 0;
717 __disable_irq();
718 for (p = tx_first[endpoint]; p; p = p->next) count++;
719 __enable_irq();
720 return count;
721}
722
723
724// Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
725// receive endpoints are starving for memory. The intention is to give
726// endpoints needing receive memory priority over the user's code, which is
727// likely calling usb_malloc to obtain memory for transmitting. When the
728// user is creating data very quickly, their consumption could starve reception
729// without this prioritization. The packet buffer (input) is assigned to the
730// first endpoint needing memory.
731//
732void usb_rx_memory(usb_packet_t *packet)
733{
734 unsigned int i;
735 const uint8_t *cfg;
736
737 cfg = usb_endpoint_config_table;
738 //serial_print("rx_mem:");
739 __disable_irq();
740 for (i=1; i <= NUM_ENDPOINTS; i++) {
741#ifdef AUDIO_INTERFACE
742 if (i == AUDIO_RX_ENDPOINT) continue;
743#endif
744 if (*cfg++ & USB_ENDPT_EPRXEN) {
745 if (table[index(i, RX, EVEN)].desc == 0) {
746 table[index(i, RX, EVEN)].addr = packet->buf;
747 table[index(i, RX, EVEN)].desc = BDT_DESC(64, 0);
748 usb_rx_memory_needed--;
749 __enable_irq();
750 //serial_phex(i);
751 //serial_print(",even\n");
752 return;
753 }
754 if (table[index(i, RX, ODD)].desc == 0) {
755 table[index(i, RX, ODD)].addr = packet->buf;
756 table[index(i, RX, ODD)].desc = BDT_DESC(64, 1);
757 usb_rx_memory_needed--;
758 __enable_irq();
759 //serial_phex(i);
760 //serial_print(",odd\n");
761 return;
762 }
763 }
764 }
765 __enable_irq();
766 // we should never reach this point. If we get here, it means
767 // usb_rx_memory_needed was set greater than zero, but no memory
768 // was actually needed.
769 usb_rx_memory_needed = 0;
770 usb_free(packet);
771 return;
772}
773
774//#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
775//#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
776
777void usb_tx(uint32_t endpoint, usb_packet_t *packet)
778{
779 bdt_t *b = &table[index(endpoint, TX, EVEN)];
780 uint8_t next;
781
782 endpoint--;
783 if (endpoint >= NUM_ENDPOINTS) return;
784 __disable_irq();
785 //serial_print("txstate=");
786 //serial_phex(tx_state[endpoint]);
787 //serial_print("\n");
788 switch (tx_state[endpoint]) {
789 case TX_STATE_BOTH_FREE_EVEN_FIRST:
790 next = TX_STATE_ODD_FREE;
791 break;
792 case TX_STATE_BOTH_FREE_ODD_FIRST:
793 b++;
794 next = TX_STATE_EVEN_FREE;
795 break;
796 case TX_STATE_EVEN_FREE:
797 next = TX_STATE_NONE_FREE_ODD_FIRST;
798 break;
799 case TX_STATE_ODD_FREE:
800 b++;
801 next = TX_STATE_NONE_FREE_EVEN_FIRST;
802 break;
803 default:
804 if (tx_first[endpoint] == NULL) {
805 tx_first[endpoint] = packet;
806 } else {
807 tx_last[endpoint]->next = packet;
808 }
809 tx_last[endpoint] = packet;
810 __enable_irq();
811 return;
812 }
813 tx_state[endpoint] = next;
814 b->addr = packet->buf;
815 b->desc = BDT_DESC(packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0);
816 __enable_irq();
817}
818
819void usb_tx_isochronous(uint32_t endpoint, void *data, uint32_t len)
820{
821 bdt_t *b = &table[index(endpoint, TX, EVEN)];
822 uint8_t next, state;
823
824 endpoint--;
825 if (endpoint >= NUM_ENDPOINTS) return;
826 __disable_irq();
827 state = tx_state[endpoint];
828 if (state == 0) {
829 next = 1;
830 } else {
831 b++;
832 next = 0;
833 }
834 tx_state[endpoint] = next;
835 b->addr = data;
836 b->desc = (len << 16) | BDT_OWN;
837 __enable_irq();
838}
839
840
841
842
843void _reboot_Teensyduino_(void)
844{
845 // TODO: initialize R0 with a code....
846 __asm__ volatile("bkpt");
847}
848
849
850
851void usb_isr(void)
852{
853 uint8_t status, stat, t;
854
855 //serial_print("isr");
856 //status = USB0_ISTAT;
857 //serial_phex(status);
858 //serial_print("\n");
859 restart:
860 status = USB0_ISTAT;
861
862 if ((status & USB_ISTAT_SOFTOK /* 04 */ )) {
863 if (usb_configuration) {
864 t = usb_reboot_timer;
865 if (t) {
866 usb_reboot_timer = --t;
867 if (!t) _reboot_Teensyduino_();
868 }
869#ifdef CDC_DATA_INTERFACE
870 t = usb_cdc_transmit_flush_timer;
871 if (t) {
872 usb_cdc_transmit_flush_timer = --t;
873 if (t == 0) usb_serial_flush_callback();
874 }
875#endif
876#ifdef SEREMU_INTERFACE
877 t = usb_seremu_transmit_flush_timer;
878 if (t) {
879 usb_seremu_transmit_flush_timer = --t;
880 if (t == 0) usb_seremu_flush_callback();
881 }
882#endif
883#ifdef MIDI_INTERFACE
884 usb_midi_flush_output();
885#endif
886#ifdef FLIGHTSIM_INTERFACE
887 usb_flightsim_flush_callback();
888#endif
889#ifdef MULTITOUCH_INTERFACE
890 usb_touchscreen_update_callback();
891#endif
892 }
893 USB0_ISTAT = USB_ISTAT_SOFTOK;
894 }
895
896 if ((status & USB_ISTAT_TOKDNE /* 08 */ )) {
897 uint8_t endpoint;
898 stat = USB0_STAT;
899 //serial_print("token: ep=");
900 //serial_phex(stat >> 4);
901 //serial_print(stat & 0x08 ? ",tx" : ",rx");
902 //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
903 endpoint = stat >> 4;
904 if (endpoint == 0) {
905 usb_control(stat);
906 } else {
907 bdt_t *b = stat2bufferdescriptor(stat);
908 usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
909#if 0
910 serial_print("ep:");
911 serial_phex(endpoint);
912 serial_print(", pid:");
913 serial_phex(BDT_PID(b->desc));
914 serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
915 serial_print(", count:");
916 serial_phex(b->desc >> 16);
917 serial_print("\n");
918#endif
919 endpoint--; // endpoint is index to zero-based arrays
920
921#ifdef AUDIO_INTERFACE
922 if ((endpoint == AUDIO_TX_ENDPOINT-1) && (stat & 0x08)) {
923 unsigned int len;
924 len = usb_audio_transmit_callback();
925 if (len > 0) {
926 b = (bdt_t *)((uint32_t)b ^ 8);
927 b->addr = usb_audio_transmit_buffer;
928 b->desc = (len << 16) | BDT_OWN;
929 tx_state[endpoint] ^= 1;
930 }
931 } else if ((endpoint == AUDIO_RX_ENDPOINT-1) && !(stat & 0x08)) {
932 usb_audio_receive_callback(b->desc >> 16);
933 b->addr = usb_audio_receive_buffer;
934 b->desc = (AUDIO_RX_SIZE << 16) | BDT_OWN;
935 } else if ((endpoint == AUDIO_SYNC_ENDPOINT-1) && (stat & 0x08)) {
936 b = (bdt_t *)((uint32_t)b ^ 8);
937 b->addr = &usb_audio_sync_feedback;
938 b->desc = (3 << 16) | BDT_OWN;
939 tx_state[endpoint] ^= 1;
940 } else
941#endif
942 if (stat & 0x08) { // transmit
943 usb_free(packet);
944 packet = tx_first[endpoint];
945 if (packet) {
946 //serial_print("tx packet\n");
947 tx_first[endpoint] = packet->next;
948 b->addr = packet->buf;
949 switch (tx_state[endpoint]) {
950 case TX_STATE_BOTH_FREE_EVEN_FIRST:
951 tx_state[endpoint] = TX_STATE_ODD_FREE;
952 break;
953 case TX_STATE_BOTH_FREE_ODD_FIRST:
954 tx_state[endpoint] = TX_STATE_EVEN_FREE;
955 break;
956 case TX_STATE_EVEN_FREE:
957 tx_state[endpoint] = TX_STATE_NONE_FREE_ODD_FIRST;
958 break;
959 case TX_STATE_ODD_FREE:
960 tx_state[endpoint] = TX_STATE_NONE_FREE_EVEN_FIRST;
961 break;
962 default:
963 break;
964 }
965 b->desc = BDT_DESC(packet->len,
966 ((uint32_t)b & 8) ? DATA1 : DATA0);
967 } else {
968 //serial_print("tx no packet\n");
969 switch (tx_state[endpoint]) {
970 case TX_STATE_BOTH_FREE_EVEN_FIRST:
971 case TX_STATE_BOTH_FREE_ODD_FIRST:
972 break;
973 case TX_STATE_EVEN_FREE:
974 tx_state[endpoint] = TX_STATE_BOTH_FREE_EVEN_FIRST;
975 break;
976 case TX_STATE_ODD_FREE:
977 tx_state[endpoint] = TX_STATE_BOTH_FREE_ODD_FIRST;
978 break;
979 default:
980 tx_state[endpoint] = ((uint32_t)b & 8) ?
981 TX_STATE_ODD_FREE : TX_STATE_EVEN_FREE;
982 break;
983 }
984 }
985 } else { // receive
986 packet->len = b->desc >> 16;
987 if (packet->len > 0) {
988 packet->index = 0;
989 packet->next = NULL;
990 if (rx_first[endpoint] == NULL) {
991 //serial_print("rx 1st, epidx=");
992 //serial_phex(endpoint);
993 //serial_print(", packet=");
994 //serial_phex32((uint32_t)packet);
995 //serial_print("\n");
996 rx_first[endpoint] = packet;
997 } else {
998 //serial_print("rx Nth, epidx=");
999 //serial_phex(endpoint);
1000 //serial_print(", packet=");
1001 //serial_phex32((uint32_t)packet);
1002 //serial_print("\n");
1003 rx_last[endpoint]->next = packet;
1004 }
1005 rx_last[endpoint] = packet;
1006 usb_rx_byte_count_data[endpoint] += packet->len;
1007 // TODO: implement a per-endpoint maximum # of allocated
1008 // packets, so a flood of incoming data on 1 endpoint
1009 // doesn't starve the others if the user isn't reading
1010 // it regularly
1011 packet = usb_malloc();
1012 if (packet) {
1013 b->addr = packet->buf;
1014 b->desc = BDT_DESC(64,
1015 ((uint32_t)b & 8) ? DATA1 : DATA0);
1016 } else {
1017 //serial_print("starving ");
1018 //serial_phex(endpoint + 1);
1019 b->desc = 0;
1020 usb_rx_memory_needed++;
1021 }
1022 } else {
1023 b->desc = BDT_DESC(64, ((uint32_t)b & 8) ? DATA1 : DATA0);
1024 }
1025 }
1026
1027 }
1028 USB0_ISTAT = USB_ISTAT_TOKDNE;
1029 goto restart;
1030 }
1031
1032
1033
1034 if (status & USB_ISTAT_USBRST /* 01 */ ) {
1035 //serial_print("reset\n");
1036
1037 // initialize BDT toggle bits
1038 USB0_CTL = USB_CTL_ODDRST;
1039 ep0_tx_bdt_bank = 0;
1040
1041 // set up buffers to receive Setup and OUT packets
1042 table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 0);
1043 table[index(0, RX, EVEN)].addr = ep0_rx0_buf;
1044 table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 0);
1045 table[index(0, RX, ODD)].addr = ep0_rx1_buf;
1046 table[index(0, TX, EVEN)].desc = 0;
1047 table[index(0, TX, ODD)].desc = 0;
1048
1049 // activate endpoint 0
1050 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1051
1052 // clear all ending interrupts
1053 USB0_ERRSTAT = 0xFF;
1054 USB0_ISTAT = 0xFF;
1055
1056 // set the address to zero during enumeration
1057 USB0_ADDR = 0;
1058
1059 // enable other interrupts
1060 USB0_ERREN = 0xFF;
1061 USB0_INTEN = USB_INTEN_TOKDNEEN |
1062 USB_INTEN_SOFTOKEN |
1063 USB_INTEN_STALLEN |
1064 USB_INTEN_ERROREN |
1065 USB_INTEN_USBRSTEN |
1066 USB_INTEN_SLEEPEN;
1067
1068 // is this necessary?
1069 USB0_CTL = USB_CTL_USBENSOFEN;
1070 return;
1071 }
1072
1073
1074 if ((status & USB_ISTAT_STALL /* 80 */ )) {
1075 //serial_print("stall:\n");
1076 USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
1077 USB0_ISTAT = USB_ISTAT_STALL;
1078 }
1079 if ((status & USB_ISTAT_ERROR /* 02 */ )) {
1080 uint8_t err = USB0_ERRSTAT;
1081 USB0_ERRSTAT = err;
1082 //serial_print("err:");
1083 //serial_phex(err);
1084 //serial_print("\n");
1085 USB0_ISTAT = USB_ISTAT_ERROR;
1086 }
1087
1088 if ((status & USB_ISTAT_SLEEP /* 10 */ )) {
1089 //serial_print("sleep\n");
1090 USB0_ISTAT = USB_ISTAT_SLEEP;
1091 }
1092
1093}
1094
1095
1096
1097void usb_init(void)
1098{
1099 int i;
1100
1101 //serial_begin(BAUD2DIV(115200));
1102 //serial_print("usb_init\n");
1103
1104 usb_init_serialnumber();
1105
1106 for (i=0; i <= NUM_ENDPOINTS*4; i++) {
1107 table[i].desc = 0;
1108 table[i].addr = 0;
1109 }
1110
1111 // this basically follows the flowchart in the Kinetis
1112 // Quick Reference User Guide, Rev. 1, 03/2012, page 141
1113
1114 // assume 48 MHz clock already running
1115 // SIM - enable clock
1116 SIM_SCGC4 |= SIM_SCGC4_USBOTG;
1117#ifdef HAS_KINETIS_MPU
1118 MPU_RGDAAC0 |= 0x03000000;
1119#endif
1120#if F_CPU == 180000000 || F_CPU == 216000000
1121 // if using IRC48M, turn on the USB clock recovery hardware
1122 USB0_CLK_RECOVER_IRC_EN = USB_CLK_RECOVER_IRC_EN_IRC_EN | USB_CLK_RECOVER_IRC_EN_REG_EN;
1123 USB0_CLK_RECOVER_CTRL = USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN |
1124 USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN;
1125#endif
1126 // reset USB module
1127 //USB0_USBTRC0 = USB_USBTRC_USBRESET;
1128 //while ((USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0) ; // wait for reset to end
1129
1130 // set desc table base addr
1131 USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
1132 USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
1133 USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
1134
1135 // clear all ISR flags
1136 USB0_ISTAT = 0xFF;
1137 USB0_ERRSTAT = 0xFF;
1138 USB0_OTGISTAT = 0xFF;
1139
1140 //USB0_USBTRC0 |= 0x40; // undocumented bit
1141
1142 // enable USB
1143 USB0_CTL = USB_CTL_USBENSOFEN;
1144 USB0_USBCTRL = 0;
1145
1146 // enable reset interrupt
1147 USB0_INTEN = USB_INTEN_USBRSTEN;
1148
1149 // enable interrupt in NVIC...
1150 NVIC_SET_PRIORITY(IRQ_USBOTG, 112);
1151 NVIC_ENABLE_IRQ(IRQ_USBOTG);
1152
1153 // enable d+ pullup
1154 USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
1155}
1156
1157
1158#else // F_CPU < 20 MHz && defined(NUM_ENDPOINTS)
1159
1160void usb_init(void)
1161{
1162}
1163
1164#endif // F_CPU >= 20 MHz && defined(NUM_ENDPOINTS)