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 33KB

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