Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

usb_dev.c 32KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. /* Teensyduino Core Library
  2. * http://www.pjrc.com/teensy/
  3. * Copyright (c) 2013 PJRC.COM, LLC.
  4. * Modifications by Jacob Alexander (2013-2016)
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining
  7. * a copy of this software and associated documentation files (the
  8. * "Software"), to deal in the Software without restriction, including
  9. * without limitation the rights to use, copy, modify, merge, publish,
  10. * distribute, sublicense, and/or sell copies of the Software, and to
  11. * permit persons to whom the Software is furnished to do so, subject to
  12. * the following conditions:
  13. *
  14. * 1. The above copyright notice and this permission notice shall be
  15. * included in all copies or substantial portions of the Software.
  16. *
  17. * 2. If the Software is incorporated into a build system that allows
  18. * selection among a list of target devices, then similar target
  19. * devices manufactured by PJRC.COM must be included in the list of
  20. * target devices and selectable in the same manner.
  21. *
  22. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  26. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  27. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  28. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29. * SOFTWARE.
  30. */
  31. // ----- Includes -----
  32. // Project Includes
  33. #include <Lib/OutputLib.h>
  34. #include <print.h>
  35. #include <kll_defs.h>
  36. // Local Includes
  37. #include "usb_dev.h"
  38. #include "usb_mem.h"
  39. // ----- Defines -----
  40. // DEBUG Mode
  41. // XXX - Only use when using usbMuxUart Module
  42. // Delay causes issues initializing more than 1 hid device (i.e. NKRO keyboard)
  43. //#define UART_DEBUG 1
  44. // Debug Unknown USB requests, usually what you want to debug USB issues
  45. //#define UART_DEBUG_UNKNOWN 1
  46. #define TX_STATE_BOTH_FREE_EVEN_FIRST 0
  47. #define TX_STATE_BOTH_FREE_ODD_FIRST 1
  48. #define TX_STATE_EVEN_FREE 2
  49. #define TX_STATE_ODD_FREE 3
  50. #define TX_STATE_NONE_FREE_EVEN_FIRST 4
  51. #define TX_STATE_NONE_FREE_ODD_FIRST 5
  52. #define BDT_OWN 0x80
  53. #define BDT_DATA1 0x40
  54. #define BDT_DATA0 0x00
  55. #define BDT_DTS 0x08
  56. #define BDT_STALL 0x04
  57. #define TX 1
  58. #define RX 0
  59. #define ODD 1
  60. #define EVEN 0
  61. #define DATA0 0
  62. #define DATA1 1
  63. #define GET_STATUS 0
  64. #define CLEAR_FEATURE 1
  65. #define SET_FEATURE 3
  66. #define SET_ADDRESS 5
  67. #define GET_DESCRIPTOR 6
  68. #define SET_DESCRIPTOR 7
  69. #define GET_CONFIGURATION 8
  70. #define SET_CONFIGURATION 9
  71. #define GET_INTERFACE 10
  72. #define SET_INTERFACE 11
  73. #define SYNCH_FRAME 12
  74. #define TX_STATE_BOTH_FREE_EVEN_FIRST 0
  75. #define TX_STATE_BOTH_FREE_ODD_FIRST 1
  76. #define TX_STATE_EVEN_FREE 2
  77. #define TX_STATE_ODD_FREE 3
  78. #define TX_STATE_NONE_FREE 4
  79. // ----- Macros -----
  80. #define BDT_PID(n) (((n) >> 2) & 15)
  81. #define BDT_DESC(count, data) (BDT_OWN | BDT_DTS \
  82. | ((data) ? BDT_DATA1 : BDT_DATA0) \
  83. | ((count) << 16))
  84. #define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  85. #define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  86. // ----- Structs -----
  87. // buffer descriptor table
  88. typedef struct {
  89. uint32_t desc;
  90. void * addr;
  91. } bdt_t;
  92. static union {
  93. struct {
  94. union {
  95. struct {
  96. uint8_t bmRequestType;
  97. uint8_t bRequest;
  98. };
  99. uint16_t wRequestAndType;
  100. };
  101. uint16_t wValue;
  102. uint16_t wIndex;
  103. uint16_t wLength;
  104. };
  105. struct {
  106. uint32_t word1;
  107. uint32_t word2;
  108. };
  109. } setup;
  110. // ----- Variables -----
  111. __attribute__ ((section(".usbdescriptortable"), used))
  112. static bdt_t table[ (NUM_ENDPOINTS + 1) * 4 ];
  113. static usb_packet_t *rx_first [ NUM_ENDPOINTS ];
  114. static usb_packet_t *rx_last [ NUM_ENDPOINTS ];
  115. static usb_packet_t *tx_first [ NUM_ENDPOINTS ];
  116. static usb_packet_t *tx_last [ NUM_ENDPOINTS ];
  117. uint16_t usb_rx_byte_count_data[ NUM_ENDPOINTS ];
  118. static uint8_t tx_state[NUM_ENDPOINTS];
  119. // SETUP always uses a DATA0 PID for the data field of the SETUP transaction.
  120. // transactions in the data phase start with DATA1 and toggle (figure 8-12, USB1.1)
  121. // Status stage uses a DATA1 PID.
  122. static uint8_t ep0_rx0_buf[EP0_SIZE] __attribute__ ((aligned (4)));
  123. static uint8_t ep0_rx1_buf[EP0_SIZE] __attribute__ ((aligned (4)));
  124. static const uint8_t *ep0_tx_ptr = NULL;
  125. static uint16_t ep0_tx_len;
  126. static uint8_t ep0_tx_bdt_bank = 0;
  127. static uint8_t ep0_tx_data_toggle = 0;
  128. uint8_t usb_rx_memory_needed = 0;
  129. volatile uint8_t usb_configuration = 0;
  130. volatile uint8_t usb_reboot_timer = 0;
  131. static uint8_t reply_buffer[8];
  132. static uint8_t power_neg_delay;
  133. static uint32_t power_neg_time;
  134. // ----- Functions -----
  135. static void endpoint0_stall()
  136. {
  137. #ifdef UART_DEBUG_UNKNOWN
  138. print("STALL" NL );
  139. #endif
  140. USB0_ENDPT0 = USB_ENDPT_EPSTALL | USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  141. }
  142. static void endpoint0_transmit( const void *data, uint32_t len )
  143. {
  144. table[index(0, TX, ep0_tx_bdt_bank)].addr = (void *)data;
  145. table[index(0, TX, ep0_tx_bdt_bank)].desc = BDT_DESC(len, ep0_tx_data_toggle);
  146. ep0_tx_data_toggle ^= 1;
  147. ep0_tx_bdt_bank ^= 1;
  148. }
  149. // Used to check any USB state changes that may not have a proper interrupt
  150. // Called once per scan loop, should take minimal processing time or it may affect other modules
  151. void usb_device_check()
  152. {
  153. // Check to see if we're still waiting for the next USB request after Get Configuration Descriptor
  154. // If still waiting, restart the USB initialization with a lower power requirement
  155. if ( power_neg_delay )
  156. {
  157. // Check if 100 ms has elapsed
  158. if ( systick_millis_count - power_neg_time > 100 )
  159. {
  160. // Update bMaxPower
  161. // The value set is in increments of 2 mA
  162. // So 50 * 2 mA = 100 mA
  163. // XXX Currently only transitions to 100 mA
  164. // It may be possible to transition down again to 20 mA
  165. *usb_bMaxPower = 50;
  166. // Re-initialize USB
  167. power_neg_delay = 0;
  168. usb_configuration = 0; // Clear USB configuration if we have one
  169. USB0_CONTROL = 0; // Disable D+ Pullup to simulate disconnect
  170. delay(10); // Delay is necessary to simulate disconnect
  171. usb_init();
  172. }
  173. }
  174. }
  175. static void usb_setup()
  176. {
  177. const uint8_t *data = NULL;
  178. uint32_t datalen = 0;
  179. const usb_descriptor_list_t *list;
  180. uint32_t size;
  181. volatile uint8_t *reg;
  182. uint8_t epconf;
  183. const uint8_t *cfg;
  184. int i;
  185. // If another request is made, disable the power negotiation check
  186. // See GET_DESCRIPTOR - Configuration
  187. if ( power_neg_delay )
  188. {
  189. power_neg_delay = 0;
  190. }
  191. switch ( setup.wRequestAndType )
  192. {
  193. case 0x0500: // SET_ADDRESS
  194. goto send;
  195. case 0x0900: // SET_CONFIGURATION
  196. #ifdef UART_DEBUG
  197. print("CONFIGURE - ");
  198. #endif
  199. usb_configuration = setup.wValue;
  200. Output_Available = usb_configuration;
  201. reg = &USB0_ENDPT1;
  202. cfg = usb_endpoint_config_table;
  203. // Now configured so we can utilize bMaxPower now
  204. Output_update_usb_current( *usb_bMaxPower * 2 );
  205. // clear all BDT entries, free any allocated memory...
  206. for ( i = 4; i < ( NUM_ENDPOINTS + 1) * 4; i++ )
  207. {
  208. if ( table[i].desc & BDT_OWN )
  209. {
  210. usb_free( (usb_packet_t *)((uint8_t *)(table[ i ].addr) - 8) );
  211. }
  212. }
  213. // free all queued packets
  214. for ( i = 0; i < NUM_ENDPOINTS; i++ )
  215. {
  216. usb_packet_t *p, *n;
  217. p = rx_first[i];
  218. while ( p )
  219. {
  220. n = p->next;
  221. usb_free(p);
  222. p = n;
  223. }
  224. rx_first[ i ] = NULL;
  225. rx_last[ i ] = NULL;
  226. p = tx_first[i];
  227. while (p)
  228. {
  229. n = p->next;
  230. usb_free(p);
  231. p = n;
  232. }
  233. tx_first[ i ] = NULL;
  234. tx_last[ i ] = NULL;
  235. usb_rx_byte_count_data[i] = 0;
  236. switch ( tx_state[ i ] )
  237. {
  238. case TX_STATE_EVEN_FREE:
  239. case TX_STATE_NONE_FREE_EVEN_FIRST:
  240. tx_state[ i ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  241. break;
  242. case TX_STATE_ODD_FREE:
  243. case TX_STATE_NONE_FREE_ODD_FIRST:
  244. tx_state[ i ] = TX_STATE_BOTH_FREE_ODD_FIRST;
  245. break;
  246. default:
  247. break;
  248. }
  249. }
  250. usb_rx_memory_needed = 0;
  251. for ( i = 1; i <= NUM_ENDPOINTS; i++ )
  252. {
  253. epconf = *cfg++;
  254. *reg = epconf;
  255. reg += 4;
  256. if ( epconf & USB_ENDPT_EPRXEN )
  257. {
  258. usb_packet_t *p;
  259. p = usb_malloc();
  260. if ( p )
  261. {
  262. table[ index( i, RX, EVEN ) ].addr = p->buf;
  263. table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
  264. }
  265. else
  266. {
  267. table[ index( i, RX, EVEN ) ].desc = 0;
  268. usb_rx_memory_needed++;
  269. }
  270. p = usb_malloc();
  271. if ( p )
  272. {
  273. table[ index( i, RX, ODD ) ].addr = p->buf;
  274. table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
  275. }
  276. else
  277. {
  278. table[ index( i, RX, ODD ) ].desc = 0;
  279. usb_rx_memory_needed++;
  280. }
  281. }
  282. table[ index( i, TX, EVEN ) ].desc = 0;
  283. table[ index( i, TX, ODD ) ].desc = 0;
  284. }
  285. goto send;
  286. case 0x0880: // GET_CONFIGURATION
  287. reply_buffer[0] = usb_configuration;
  288. datalen = 1;
  289. data = reply_buffer;
  290. goto send;
  291. case 0x0080: // GET_STATUS (device)
  292. reply_buffer[0] = 0;
  293. reply_buffer[1] = 0;
  294. datalen = 2;
  295. data = reply_buffer;
  296. goto send;
  297. case 0x0082: // GET_STATUS (endpoint)
  298. if ( setup.wIndex > NUM_ENDPOINTS )
  299. {
  300. // TODO: do we need to handle IN vs OUT here?
  301. endpoint0_stall();
  302. return;
  303. }
  304. reply_buffer[0] = 0;
  305. reply_buffer[1] = 0;
  306. if ( *(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4) & 0x02 )
  307. reply_buffer[0] = 1;
  308. data = reply_buffer;
  309. datalen = 2;
  310. goto send;
  311. case 0x0100: // CLEAR_FEATURE (device)
  312. switch ( setup.wValue )
  313. {
  314. // CLEAR_FEATURE(DEVICE_REMOTE_WAKEUP)
  315. // See SET_FEATURE(DEVICE_REMOTE_WAKEUP) for details
  316. case 0x1:
  317. goto send;
  318. }
  319. warn_msg("SET_FEATURE - Device wValue(");
  320. printHex( setup.wValue );
  321. print( ")" NL );
  322. endpoint0_stall();
  323. return;
  324. case 0x0101: // CLEAR_FEATURE (interface)
  325. // TODO: Currently ignoring, perhaps useful? -HaaTa
  326. warn_msg("CLEAR_FEATURE - Interface wValue(");
  327. printHex( setup.wValue );
  328. print(") wIndex(");
  329. printHex( setup.wIndex );
  330. print( ")" NL );
  331. endpoint0_stall();
  332. return;
  333. case 0x0102: // CLEAR_FEATURE (endpoint)
  334. i = setup.wIndex & 0x7F;
  335. if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
  336. {
  337. endpoint0_stall();
  338. return;
  339. }
  340. (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) &= ~0x02;
  341. // TODO: do we need to clear the data toggle here?
  342. goto send;
  343. case 0x0300: // SET_FEATURE (device)
  344. switch ( setup.wValue )
  345. {
  346. // SET_FEATURE(DEVICE_REMOTE_WAKEUP)
  347. // XXX: Only used to confirm Remote Wake
  348. // Used on Mac OSX and Windows not on Linux
  349. // Good post on the behaviour:
  350. // http://community.silabs.com/t5/8-bit-MCU/Remote-wakeup-HID/m-p/74957#M30802
  351. case 0x1:
  352. goto send;
  353. }
  354. warn_msg("SET_FEATURE - Device wValue(");
  355. printHex( setup.wValue );
  356. print( ")" NL );
  357. endpoint0_stall();
  358. return;
  359. case 0x0301: // SET_FEATURE (interface)
  360. // TODO: Currently ignoring, perhaps useful? -HaaTa
  361. warn_msg("SET_FEATURE - Interface wValue(");
  362. printHex( setup.wValue );
  363. print(") wIndex(");
  364. printHex( setup.wIndex );
  365. print( ")" NL );
  366. endpoint0_stall();
  367. return;
  368. case 0x0302: // SET_FEATURE (endpoint)
  369. i = setup.wIndex & 0x7F;
  370. if ( i > NUM_ENDPOINTS || setup.wValue != 0 )
  371. {
  372. // TODO: do we need to handle IN vs OUT here?
  373. endpoint0_stall();
  374. return;
  375. }
  376. (*(uint8_t *)(&USB0_ENDPT0 + setup.wIndex * 4)) |= 0x02;
  377. // TODO: do we need to clear the data toggle here?
  378. goto send;
  379. case 0x0680: // GET_DESCRIPTOR
  380. case 0x0681:
  381. #ifdef UART_DEBUG
  382. print("desc:");
  383. printHex( setup.wValue );
  384. print( NL );
  385. #endif
  386. for ( list = usb_descriptor_list; 1; list++ )
  387. {
  388. if ( list->addr == NULL )
  389. break;
  390. if ( setup.wValue == list->wValue && setup.wIndex == list->wIndex )
  391. {
  392. data = list->addr;
  393. if ( (setup.wValue >> 8) == 3 )
  394. {
  395. // for string descriptors, use the descriptor's
  396. // length field, allowing runtime configured
  397. // length.
  398. datalen = *(list->addr);
  399. }
  400. else
  401. {
  402. datalen = list->length;
  403. }
  404. // XXX Power negotiation hack -HaaTa
  405. // Some devices such as the Apple Ipad do not support bMaxPower greater than 100 mA
  406. // However, there is no provision in the basic USB 2.0 stack for power negotiation
  407. // To get around this:
  408. // * Attempt to set bMaxPower to 500 mA first
  409. // * If more than 100 ms passes since retrieving a Get Configuration Descriptor
  410. // (Descriptor with bMaxPower in it)
  411. // * Change usb_bMaxPower to 50 (100 mA)
  412. // * Restart the USB init process
  413. // According to notes online, it says that some Apple devices can only do 20 mA
  414. // However, in my testing this hasn't been the case
  415. // (you can also draw as much current as you want if you just lie in the descriptor :P)
  416. // If this becomes an issue we can use this hack a second time to negotiate down to 20 mA
  417. // (which should be fine for just the mcu)
  418. if ( setup.wValue == 0x0200 && setup.wIndex == 0x0 )
  419. {
  420. power_neg_delay = 1;
  421. power_neg_time = systick_millis_count;
  422. }
  423. #if UART_DEBUG
  424. print("Desc found, ");
  425. printHex32( (uint32_t)data );
  426. print(",");
  427. printHex( datalen );
  428. print(",");
  429. printHex_op( data[0], 2 );
  430. printHex_op( data[1], 2 );
  431. printHex_op( data[2], 2 );
  432. printHex_op( data[3], 2 );
  433. printHex_op( data[4], 2 );
  434. printHex_op( data[5], 2 );
  435. print( NL );
  436. #endif
  437. goto send;
  438. }
  439. }
  440. #ifdef UART_DEBUG
  441. print( "desc: not found" NL );
  442. #endif
  443. endpoint0_stall();
  444. return;
  445. case 0x2221: // CDC_SET_CONTROL_LINE_STATE
  446. usb_cdc_line_rtsdtr = setup.wValue;
  447. //serial_print("set control line state\n");
  448. goto send;
  449. case 0x21A1: // CDC_GET_LINE_CODING
  450. data = (uint8_t*)usb_cdc_line_coding;
  451. datalen = sizeof( usb_cdc_line_coding );
  452. goto send;
  453. case 0x2021: // CDC_SET_LINE_CODING
  454. // XXX Needed?
  455. //serial_print("set coding, waiting...\n");
  456. return;
  457. case 0x0921: // HID SET_REPORT
  458. // Interface
  459. switch ( setup.wIndex & 0xFF )
  460. {
  461. // Keyboard Interface
  462. case KEYBOARD_INTERFACE:
  463. break;
  464. // NKRO Keyboard Interface
  465. case NKRO_KEYBOARD_INTERFACE:
  466. break;
  467. default:
  468. warn_msg("Unknown interface - ");
  469. printHex( setup.wIndex );
  470. print( NL );
  471. endpoint0_stall();
  472. break;
  473. }
  474. return;
  475. case 0x01A1: // HID GET_REPORT
  476. #ifdef UART_DEBUG
  477. print("GET_REPORT - ");
  478. printHex( setup.wIndex );
  479. print(NL);
  480. #endif
  481. // Search through descriptors returning necessary info
  482. for ( list = usb_descriptor_list; 1; list++ )
  483. {
  484. if ( list->addr == NULL )
  485. break;
  486. if ( list->wValue != 0x2200 )
  487. continue;
  488. if ( setup.wIndex == list->wIndex )
  489. {
  490. data = list->addr;
  491. datalen = list->length;
  492. goto send;
  493. }
  494. }
  495. endpoint0_stall();
  496. return;
  497. case 0x0A21: // HID SET_IDLE
  498. #ifdef UART_DEBUG
  499. print("SET_IDLE - ");
  500. printHex( setup.wValue );
  501. print(NL);
  502. #endif
  503. USBKeys_Idle_Config = (setup.wValue >> 8);
  504. USBKeys_Idle_Count = 0;
  505. goto send;
  506. case 0x0B21: // HID SET_PROTOCOL
  507. #ifdef UART_DEBUG
  508. print("SET_PROTOCOL - ");
  509. printHex( setup.wValue );
  510. print(" - ");
  511. printHex( setup.wValue & 0xFF );
  512. print(NL);
  513. #endif
  514. USBKeys_Protocol = setup.wValue & 0xFF; // 0 - Boot Mode, 1 - NKRO Mode
  515. goto send;
  516. // case 0xC940:
  517. default:
  518. #ifdef UART_DEBUG_UNKNOWN
  519. print("UNKNOWN");
  520. #endif
  521. endpoint0_stall();
  522. return;
  523. }
  524. send:
  525. #ifdef UART_DEBUG
  526. print("setup send ");
  527. printHex32( (uint32_t)data );
  528. print(",");
  529. for ( uint8_t c = 0; c < datalen; c++ )
  530. {
  531. printHex( data[c] );
  532. print(" ");
  533. }
  534. print(",");
  535. printHex( datalen );
  536. print( NL );
  537. #endif
  538. if ( datalen > setup.wLength )
  539. datalen = setup.wLength;
  540. size = datalen;
  541. if ( size > EP0_SIZE )
  542. size = EP0_SIZE;
  543. endpoint0_transmit(data, size);
  544. data += size;
  545. datalen -= size;
  546. // See if transmit has finished
  547. if ( datalen == 0 && size < EP0_SIZE )
  548. return;
  549. size = datalen;
  550. if ( size > EP0_SIZE )
  551. size = EP0_SIZE;
  552. endpoint0_transmit(data, size);
  553. data += size;
  554. datalen -= size;
  555. // See if transmit has finished
  556. if ( datalen == 0 && size < EP0_SIZE )
  557. return;
  558. // Save rest of transfer for later? XXX
  559. ep0_tx_ptr = data;
  560. ep0_tx_len = datalen;
  561. }
  562. //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
  563. //experiences any configuration event (configuration events are explained in
  564. //Sections 9.1.1.5 and 9.4.5).
  565. //Configuring a device or changing an alternate setting causes all of the status
  566. //and configuration values associated with endpoints in the affected interfaces
  567. //to be set to their default values. This includes setting the data toggle of
  568. //any endpoint using data toggles to the value DATA0.
  569. //For endpoints using data toggle, regardless of whether an endpoint has the
  570. //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
  571. //data toggle being reinitialized to DATA0.
  572. static void usb_control( uint32_t stat )
  573. {
  574. #ifdef UART_DEBUG
  575. print("CONTROL - ");
  576. #endif
  577. bdt_t *b;
  578. uint32_t pid, size;
  579. uint8_t *buf;
  580. const uint8_t *data;
  581. b = stat2bufferdescriptor( stat );
  582. pid = BDT_PID( b->desc );
  583. buf = b->addr;
  584. #ifdef UART_DEBUG
  585. print("pid:");
  586. printHex(pid);
  587. print(", count:");
  588. printHex32(b->desc);
  589. print(" - ");
  590. #endif
  591. switch (pid)
  592. {
  593. case 0x0D: // Setup received from host
  594. //serial_print("PID=Setup\n");
  595. //if (count != 8) ; // panic?
  596. // grab the 8 byte setup info
  597. setup.word1 = *(uint32_t *)(buf);
  598. setup.word2 = *(uint32_t *)(buf + 4);
  599. // give the buffer back
  600. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  601. //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
  602. //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
  603. // clear any leftover pending IN transactions
  604. ep0_tx_ptr = NULL;
  605. if ( ep0_tx_data_toggle )
  606. {
  607. }
  608. //if (table[index(0, TX, EVEN)].desc & 0x80) {
  609. //serial_print("leftover tx even\n");
  610. //}
  611. //if (table[index(0, TX, ODD)].desc & 0x80) {
  612. //serial_print("leftover tx odd\n");
  613. //}
  614. table[index(0, TX, EVEN)].desc = 0;
  615. table[index(0, TX, ODD)].desc = 0;
  616. // first IN after Setup is always DATA1
  617. ep0_tx_data_toggle = 1;
  618. #ifdef UART_DEBUG_UNKNOWN
  619. print("bmRequestType:");
  620. printHex(setup.bmRequestType);
  621. print(", bRequest:");
  622. printHex(setup.bRequest);
  623. print(", wValue:");
  624. printHex(setup.wValue);
  625. print(", wIndex:");
  626. printHex(setup.wIndex);
  627. print(", len:");
  628. printHex(setup.wLength);
  629. print(" -- ");
  630. printHex32(setup.word1);
  631. print(" ");
  632. printHex32(setup.word2);
  633. print(NL);
  634. #endif
  635. // actually "do" the setup request
  636. usb_setup();
  637. // unfreeze the USB, now that we're ready
  638. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  639. break;
  640. case 0x01: // OUT transaction received from host
  641. case 0x02:
  642. #ifdef UART_DEBUG_UNKNOWN
  643. print("PID=OUT wRequestAndType:");
  644. printHex(setup.wRequestAndType);
  645. print(", wValue:");
  646. printHex(setup.wValue);
  647. print(", wIndex:");
  648. printHex(setup.wIndex);
  649. print(", len:");
  650. printHex(setup.wLength);
  651. print(" -- ");
  652. printHex32(setup.word1);
  653. print(" ");
  654. printHex32(setup.word2);
  655. print(NL);
  656. #endif
  657. // CDC Interface
  658. if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
  659. {
  660. int i;
  661. uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
  662. //serial_print("set line coding ");
  663. for ( i = 0; i < 7; i++ )
  664. {
  665. //serial_phex(*buf);
  666. *dst++ = *buf++;
  667. }
  668. //serial_phex32(usb_cdc_line_coding[0]);
  669. //serial_print("\n");
  670. if ( usb_cdc_line_coding[0] == 134 )
  671. usb_reboot_timer = 15;
  672. endpoint0_transmit( NULL, 0 );
  673. }
  674. // Keyboard SET_REPORT
  675. if ( setup.wRequestAndType == 0x921 && setup.wValue & 0x200 )
  676. {
  677. // Interface
  678. switch ( setup.wIndex & 0xFF )
  679. {
  680. // Keyboard Interface
  681. case KEYBOARD_INTERFACE:
  682. USBKeys_LEDs = buf[0];
  683. endpoint0_transmit( NULL, 0 );
  684. break;
  685. // NKRO Keyboard Interface
  686. case NKRO_KEYBOARD_INTERFACE:
  687. // Only use 2nd byte, first byte is the report id
  688. USBKeys_LEDs = buf[1];
  689. endpoint0_transmit( NULL, 0 );
  690. break;
  691. default:
  692. warn_msg("Unknown interface - ");
  693. printHex( setup.wIndex );
  694. print( NL );
  695. break;
  696. }
  697. #ifdef UART_DEBUG
  698. for ( size_t len = 0; len < setup.wLength; len++ )
  699. {
  700. printHex( buf[ len ] );
  701. print(" ");
  702. }
  703. print( NL );
  704. #endif
  705. }
  706. // give the buffer back
  707. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  708. break;
  709. case 0x09: // IN transaction completed to host
  710. #ifdef UART_DEBUG
  711. print("PID=IN:");
  712. printHex(stat);
  713. print(NL);
  714. #endif
  715. // send remaining data, if any...
  716. data = ep0_tx_ptr;
  717. if ( data )
  718. {
  719. size = ep0_tx_len;
  720. if (size > EP0_SIZE) size = EP0_SIZE;
  721. endpoint0_transmit(data, size);
  722. data += size;
  723. ep0_tx_len -= size;
  724. ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
  725. }
  726. if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
  727. {
  728. setup.bRequest = 0;
  729. #ifdef UART_DEBUG
  730. print("set address: ");
  731. printHex(setup.wValue);
  732. print(NL);
  733. #endif
  734. USB0_ADDR = setup.wValue;
  735. }
  736. break;
  737. default:
  738. #ifdef UART_DEBUG
  739. print("PID=unknown:");
  740. printHex(pid);
  741. print(NL);
  742. #endif
  743. break;
  744. }
  745. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  746. }
  747. usb_packet_t *usb_rx( uint32_t endpoint )
  748. {
  749. //print("USB RX");
  750. usb_packet_t *ret;
  751. endpoint--;
  752. if ( endpoint >= NUM_ENDPOINTS )
  753. return NULL;
  754. __disable_irq();
  755. ret = rx_first[endpoint];
  756. if ( ret )
  757. rx_first[ endpoint ] = ret->next;
  758. usb_rx_byte_count_data[ endpoint ] -= ret->len;
  759. __enable_irq();
  760. //serial_print("rx, epidx=");
  761. //serial_phex(endpoint);
  762. //serial_print(", packet=");
  763. //serial_phex32(ret);
  764. //serial_print("\n");
  765. return ret;
  766. }
  767. static uint32_t usb_queue_byte_count( const usb_packet_t *p )
  768. {
  769. uint32_t count=0;
  770. __disable_irq();
  771. for ( ; p; p = p->next )
  772. {
  773. count += p->len;
  774. }
  775. __enable_irq();
  776. return count;
  777. }
  778. uint32_t usb_tx_byte_count( uint32_t endpoint )
  779. {
  780. endpoint--;
  781. if ( endpoint >= NUM_ENDPOINTS )
  782. return 0;
  783. return usb_queue_byte_count( tx_first[ endpoint ] );
  784. }
  785. uint32_t usb_tx_packet_count( uint32_t endpoint )
  786. {
  787. const usb_packet_t *p;
  788. uint32_t count=0;
  789. endpoint--;
  790. if ( endpoint >= NUM_ENDPOINTS )
  791. return 0;
  792. __disable_irq();
  793. for ( p = tx_first[ endpoint ]; p; p = p->next )
  794. count++;
  795. __enable_irq();
  796. return count;
  797. }
  798. // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
  799. // receive endpoints are starving for memory. The intention is to give
  800. // endpoints needing receive memory priority over the user's code, which is
  801. // likely calling usb_malloc to obtain memory for transmitting. When the
  802. // user is creating data very quickly, their consumption could starve reception
  803. // without this prioritization. The packet buffer (input) is assigned to the
  804. // first endpoint needing memory.
  805. //
  806. void usb_rx_memory( usb_packet_t *packet )
  807. {
  808. //print("USB RX MEMORY");
  809. unsigned int i;
  810. const uint8_t *cfg;
  811. cfg = usb_endpoint_config_table;
  812. //serial_print("rx_mem:");
  813. __disable_irq();
  814. for ( i = 1; i <= NUM_ENDPOINTS; i++ )
  815. {
  816. if ( *cfg++ & USB_ENDPT_EPRXEN )
  817. {
  818. if ( table[ index( i, RX, EVEN ) ].desc == 0 )
  819. {
  820. table[ index( i, RX, EVEN ) ].addr = packet->buf;
  821. table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
  822. usb_rx_memory_needed--;
  823. __enable_irq();
  824. //serial_phex(i);
  825. //serial_print(",even\n");
  826. return;
  827. }
  828. if ( table[ index( i, RX, ODD ) ].desc == 0 )
  829. {
  830. table[ index( i, RX, ODD ) ].addr = packet->buf;
  831. table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
  832. usb_rx_memory_needed--;
  833. __enable_irq();
  834. //serial_phex(i);
  835. //serial_print(",odd\n");
  836. return;
  837. }
  838. }
  839. }
  840. __enable_irq();
  841. // we should never reach this point. If we get here, it means
  842. // usb_rx_memory_needed was set greater than zero, but no memory
  843. // was actually needed.
  844. usb_rx_memory_needed = 0;
  845. usb_free( packet );
  846. return;
  847. }
  848. //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  849. //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  850. void usb_tx( uint32_t endpoint, usb_packet_t *packet )
  851. {
  852. // Since we are transmitting data, USB will be brought out of sleep/suspend
  853. // if it's in that state
  854. // Use the currently set descriptor value
  855. Output_update_usb_current( *usb_bMaxPower * 2 );
  856. bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
  857. uint8_t next;
  858. endpoint--;
  859. if ( endpoint >= NUM_ENDPOINTS )
  860. return;
  861. __disable_irq();
  862. //serial_print("txstate=");
  863. //serial_phex(tx_state[ endpoint ]);
  864. //serial_print("\n");
  865. switch ( tx_state[ endpoint ] )
  866. {
  867. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  868. next = TX_STATE_ODD_FREE;
  869. break;
  870. case TX_STATE_BOTH_FREE_ODD_FIRST:
  871. b++;
  872. next = TX_STATE_EVEN_FREE;
  873. break;
  874. case TX_STATE_EVEN_FREE:
  875. next = TX_STATE_NONE_FREE_ODD_FIRST;
  876. break;
  877. case TX_STATE_ODD_FREE:
  878. b++;
  879. next = TX_STATE_NONE_FREE_EVEN_FIRST;
  880. break;
  881. default:
  882. if (tx_first[ endpoint ] == NULL)
  883. {
  884. tx_first[ endpoint ] = packet;
  885. }
  886. else
  887. {
  888. tx_last[ endpoint ]->next = packet;
  889. }
  890. tx_last[ endpoint ] = packet;
  891. __enable_irq();
  892. return;
  893. }
  894. tx_state[ endpoint ] = next;
  895. b->addr = packet->buf;
  896. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  897. __enable_irq();
  898. }
  899. void usb_device_reload()
  900. {
  901. // MCHCK
  902. // Kiibohd mk20dx256vlh7
  903. #if defined(_mk20dx128vlf5_) || defined(_mk20dx256vlh7_)
  904. // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
  905. for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
  906. (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
  907. SOFTWARE_RESET();
  908. // Teensy 3.0 and 3.1
  909. #else
  910. asm volatile("bkpt");
  911. #endif
  912. }
  913. void usb_isr()
  914. {
  915. uint8_t status, stat, t;
  916. //serial_print("isr");
  917. //status = USB0_ISTAT;
  918. //serial_phex(status);
  919. //serial_print("\n");
  920. restart:
  921. status = USB0_ISTAT;
  922. /*
  923. print("USB ISR STATUS: ");
  924. printHex( status );
  925. print( NL );
  926. */
  927. if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
  928. {
  929. if ( usb_configuration )
  930. {
  931. t = usb_reboot_timer;
  932. if ( t )
  933. {
  934. usb_reboot_timer = --t;
  935. if ( !t )
  936. usb_device_reload();
  937. }
  938. // CDC Interface
  939. t = usb_cdc_transmit_flush_timer;
  940. if ( t )
  941. {
  942. usb_cdc_transmit_flush_timer = --t;
  943. if ( t == 0 )
  944. usb_serial_flush_callback();
  945. }
  946. }
  947. USB0_ISTAT = USB_INTEN_SOFTOKEN;
  948. }
  949. if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
  950. {
  951. uint8_t endpoint;
  952. stat = USB0_STAT;
  953. //serial_print("token: ep=");
  954. //serial_phex(stat >> 4);
  955. //serial_print(stat & 0x08 ? ",tx" : ",rx");
  956. //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
  957. endpoint = stat >> 4;
  958. if ( endpoint == 0 )
  959. {
  960. usb_control( stat );
  961. }
  962. else
  963. {
  964. bdt_t *b = stat2bufferdescriptor(stat);
  965. usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
  966. #if 0
  967. serial_print("ep:");
  968. serial_phex(endpoint);
  969. serial_print(", pid:");
  970. serial_phex(BDT_PID(b->desc));
  971. serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
  972. serial_print(", count:");
  973. serial_phex(b->desc >> 16);
  974. serial_print("\n");
  975. #endif
  976. endpoint--; // endpoint is index to zero-based arrays
  977. if ( stat & 0x08 )
  978. { // transmit
  979. usb_free( packet );
  980. packet = tx_first[ endpoint ];
  981. if ( packet )
  982. {
  983. //serial_print("tx packet\n");
  984. tx_first[endpoint] = packet->next;
  985. b->addr = packet->buf;
  986. switch ( tx_state[ endpoint ] )
  987. {
  988. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  989. tx_state[ endpoint ] = TX_STATE_ODD_FREE;
  990. break;
  991. case TX_STATE_BOTH_FREE_ODD_FIRST:
  992. tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
  993. break;
  994. case TX_STATE_EVEN_FREE:
  995. tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
  996. break;
  997. case TX_STATE_ODD_FREE:
  998. tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
  999. break;
  1000. default:
  1001. break;
  1002. }
  1003. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1004. } else {
  1005. //serial_print("tx no packet\n");
  1006. switch ( tx_state[ endpoint ] )
  1007. {
  1008. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  1009. case TX_STATE_BOTH_FREE_ODD_FIRST:
  1010. break;
  1011. case TX_STATE_EVEN_FREE:
  1012. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  1013. break;
  1014. case TX_STATE_ODD_FREE:
  1015. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
  1016. break;
  1017. default:
  1018. tx_state[ endpoint ] = ((uint32_t)b & 8)
  1019. ? TX_STATE_ODD_FREE
  1020. : TX_STATE_EVEN_FREE;
  1021. break;
  1022. }
  1023. }
  1024. }
  1025. else
  1026. { // receive
  1027. packet->len = b->desc >> 16;
  1028. if ( packet->len > 0 )
  1029. {
  1030. packet->index = 0;
  1031. packet->next = NULL;
  1032. if ( rx_first[ endpoint ] == NULL )
  1033. {
  1034. //serial_print("rx 1st, epidx=");
  1035. //serial_phex(endpoint);
  1036. //serial_print(", packet=");
  1037. //serial_phex32((uint32_t)packet);
  1038. //serial_print("\n");
  1039. rx_first[ endpoint ] = packet;
  1040. }
  1041. else
  1042. {
  1043. //serial_print("rx Nth, epidx=");
  1044. //serial_phex(endpoint);
  1045. //serial_print(", packet=");
  1046. //serial_phex32((uint32_t)packet);
  1047. //serial_print("\n");
  1048. rx_last[ endpoint ]->next = packet;
  1049. }
  1050. rx_last[ endpoint ] = packet;
  1051. usb_rx_byte_count_data[ endpoint ] += packet->len;
  1052. // TODO: implement a per-endpoint maximum # of allocated packets
  1053. // so a flood of incoming data on 1 endpoint doesn't starve
  1054. // the others if the user isn't reading it regularly
  1055. packet = usb_malloc();
  1056. if ( packet )
  1057. {
  1058. b->addr = packet->buf;
  1059. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1060. }
  1061. else
  1062. {
  1063. //serial_print("starving ");
  1064. //serial_phex(endpoint + 1);
  1065. //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
  1066. b->desc = 0;
  1067. usb_rx_memory_needed++;
  1068. }
  1069. }
  1070. else
  1071. {
  1072. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1073. }
  1074. }
  1075. }
  1076. USB0_ISTAT = USB_ISTAT_TOKDNE;
  1077. goto restart;
  1078. }
  1079. if ( status & USB_ISTAT_USBRST /* 01 */ )
  1080. {
  1081. //serial_print("reset\n");
  1082. // initialize BDT toggle bits
  1083. USB0_CTL = USB_CTL_ODDRST;
  1084. ep0_tx_bdt_bank = 0;
  1085. // set up buffers to receive Setup and OUT packets
  1086. table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  1087. table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
  1088. table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  1089. table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
  1090. table[index( 0, TX, EVEN ) ].desc = 0;
  1091. table[index( 0, TX, ODD ) ].desc = 0;
  1092. // activate endpoint 0
  1093. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1094. // clear all ending interrupts
  1095. USB0_ERRSTAT = 0xFF;
  1096. USB0_ISTAT = 0xFF;
  1097. // set the address to zero during enumeration
  1098. USB0_ADDR = 0;
  1099. // enable other interrupts
  1100. USB0_ERREN = 0xFF;
  1101. USB0_INTEN = USB_INTEN_TOKDNEEN |
  1102. USB_INTEN_SOFTOKEN |
  1103. USB_INTEN_STALLEN |
  1104. USB_INTEN_ERROREN |
  1105. USB_INTEN_USBRSTEN |
  1106. USB_INTEN_SLEEPEN;
  1107. // is this necessary?
  1108. USB0_CTL = USB_CTL_USBENSOFEN;
  1109. return;
  1110. }
  1111. if ( (status & USB_ISTAT_STALL /* 80 */ ) )
  1112. {
  1113. //serial_print("stall:\n");
  1114. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1115. USB0_ISTAT = USB_ISTAT_STALL;
  1116. }
  1117. if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
  1118. {
  1119. uint8_t err = USB0_ERRSTAT;
  1120. USB0_ERRSTAT = err;
  1121. //serial_print("err:");
  1122. //serial_phex(err);
  1123. //serial_print("\n");
  1124. USB0_ISTAT = USB_ISTAT_ERROR;
  1125. }
  1126. // USB Host signalling device to enter 'sleep' state
  1127. // The USB Module triggers this interrupt when it detects the bus has been idle for 3 ms
  1128. if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
  1129. {
  1130. info_print("Host has requested USB sleep/suspend state");
  1131. Output_update_usb_current( 100 ); // Set to 100 mA
  1132. USB0_ISTAT = USB_ISTAT_SLEEP;
  1133. }
  1134. }
  1135. uint8_t usb_init()
  1136. {
  1137. #ifdef UART_DEBUG
  1138. print("USB INIT"NL);
  1139. #endif
  1140. // Clear out endpoints table
  1141. for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
  1142. {
  1143. table[i].desc = 0;
  1144. table[i].addr = 0;
  1145. }
  1146. // this basically follows the flowchart in the Kinetis
  1147. // Quick Reference User Guide, Rev. 1, 03/2012, page 141
  1148. // assume 48 MHz clock already running
  1149. // SIM - enable clock
  1150. SIM_SCGC4 |= SIM_SCGC4_USBOTG;
  1151. // reset USB module
  1152. USB0_USBTRC0 = USB_USBTRC_USBRESET;
  1153. while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
  1154. // set desc table base addr
  1155. USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
  1156. USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
  1157. USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
  1158. // clear all ISR flags
  1159. USB0_ISTAT = 0xFF;
  1160. USB0_ERRSTAT = 0xFF;
  1161. USB0_OTGISTAT = 0xFF;
  1162. USB0_USBTRC0 |= 0x40; // undocumented bit
  1163. // enable USB
  1164. USB0_CTL = USB_CTL_USBENSOFEN;
  1165. USB0_USBCTRL = 0;
  1166. // enable reset interrupt
  1167. USB0_INTEN = USB_INTEN_USBRSTEN;
  1168. // enable interrupt in NVIC...
  1169. NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
  1170. NVIC_ENABLE_IRQ( IRQ_USBOTG );
  1171. // enable d+ pullup
  1172. USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
  1173. // Do not check for power negotiation delay until Get Configuration Descriptor
  1174. power_neg_delay = 0;
  1175. return 1;
  1176. }
  1177. // return 0 if the USB is not configured, or the configuration
  1178. // number selected by the HOST
  1179. uint8_t usb_configured()
  1180. {
  1181. return usb_configuration;
  1182. }