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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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 0x03A1: /// HID GET_PROTOCOL
  517. #ifdef UART_DEBUG
  518. print("GET_PROTOCOL - ");
  519. printHex( setup.wValue );
  520. print(" - ");
  521. printHex( USBKeys_Protocol );
  522. print(NL);
  523. #endif
  524. reply_buffer[0] = USBKeys_Protocol;
  525. datalen = 1;
  526. goto send;
  527. // case 0xC940:
  528. default:
  529. #ifdef UART_DEBUG_UNKNOWN
  530. print("UNKNOWN");
  531. print(NL);
  532. #endif
  533. endpoint0_stall();
  534. return;
  535. }
  536. send:
  537. #ifdef UART_DEBUG
  538. print("setup send ");
  539. printHex32( (uint32_t)data );
  540. print(",");
  541. for ( uint8_t c = 0; c < datalen; c++ )
  542. {
  543. printHex( data[c] );
  544. print(" ");
  545. }
  546. print(",");
  547. printHex( datalen );
  548. print( NL );
  549. #endif
  550. if ( datalen > setup.wLength )
  551. datalen = setup.wLength;
  552. size = datalen;
  553. if ( size > EP0_SIZE )
  554. size = EP0_SIZE;
  555. endpoint0_transmit(data, size);
  556. data += size;
  557. datalen -= size;
  558. // See if transmit has finished
  559. if ( datalen == 0 && size < EP0_SIZE )
  560. return;
  561. size = datalen;
  562. if ( size > EP0_SIZE )
  563. size = EP0_SIZE;
  564. endpoint0_transmit(data, size);
  565. data += size;
  566. datalen -= size;
  567. // See if transmit has finished
  568. if ( datalen == 0 && size < EP0_SIZE )
  569. return;
  570. // Save rest of transfer for later? XXX
  571. ep0_tx_ptr = data;
  572. ep0_tx_len = datalen;
  573. }
  574. //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
  575. //experiences any configuration event (configuration events are explained in
  576. //Sections 9.1.1.5 and 9.4.5).
  577. //Configuring a device or changing an alternate setting causes all of the status
  578. //and configuration values associated with endpoints in the affected interfaces
  579. //to be set to their default values. This includes setting the data toggle of
  580. //any endpoint using data toggles to the value DATA0.
  581. //For endpoints using data toggle, regardless of whether an endpoint has the
  582. //Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
  583. //data toggle being reinitialized to DATA0.
  584. static void usb_control( uint32_t stat )
  585. {
  586. #ifdef UART_DEBUG
  587. print("CONTROL - ");
  588. #endif
  589. bdt_t *b;
  590. uint32_t pid, size;
  591. uint8_t *buf;
  592. const uint8_t *data;
  593. b = stat2bufferdescriptor( stat );
  594. pid = BDT_PID( b->desc );
  595. buf = b->addr;
  596. #ifdef UART_DEBUG
  597. print("pid:");
  598. printHex(pid);
  599. print(", count:");
  600. printHex32(b->desc);
  601. print(" - ");
  602. #endif
  603. switch (pid)
  604. {
  605. case 0x0D: // Setup received from host
  606. //serial_print("PID=Setup\n");
  607. //if (count != 8) ; // panic?
  608. // grab the 8 byte setup info
  609. setup.word1 = *(uint32_t *)(buf);
  610. setup.word2 = *(uint32_t *)(buf + 4);
  611. // give the buffer back
  612. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  613. //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
  614. //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
  615. // clear any leftover pending IN transactions
  616. ep0_tx_ptr = NULL;
  617. if ( ep0_tx_data_toggle )
  618. {
  619. }
  620. //if (table[index(0, TX, EVEN)].desc & 0x80) {
  621. //serial_print("leftover tx even\n");
  622. //}
  623. //if (table[index(0, TX, ODD)].desc & 0x80) {
  624. //serial_print("leftover tx odd\n");
  625. //}
  626. table[index(0, TX, EVEN)].desc = 0;
  627. table[index(0, TX, ODD)].desc = 0;
  628. // first IN after Setup is always DATA1
  629. ep0_tx_data_toggle = 1;
  630. #ifdef UART_DEBUG_UNKNOWN
  631. print("bmRequestType:");
  632. printHex(setup.bmRequestType);
  633. print(", bRequest:");
  634. printHex(setup.bRequest);
  635. print(", wValue:");
  636. printHex(setup.wValue);
  637. print(", wIndex:");
  638. printHex(setup.wIndex);
  639. print(", len:");
  640. printHex(setup.wLength);
  641. print(" -- ");
  642. printHex32(setup.word1);
  643. print(" ");
  644. printHex32(setup.word2);
  645. print(NL);
  646. #endif
  647. // actually "do" the setup request
  648. usb_setup();
  649. // unfreeze the USB, now that we're ready
  650. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  651. break;
  652. case 0x01: // OUT transaction received from host
  653. case 0x02:
  654. #ifdef UART_DEBUG_UNKNOWN
  655. print("PID=OUT wRequestAndType:");
  656. printHex(setup.wRequestAndType);
  657. print(", wValue:");
  658. printHex(setup.wValue);
  659. print(", wIndex:");
  660. printHex(setup.wIndex);
  661. print(", len:");
  662. printHex(setup.wLength);
  663. print(" -- ");
  664. printHex32(setup.word1);
  665. print(" ");
  666. printHex32(setup.word2);
  667. print(NL);
  668. #endif
  669. // CDC Interface
  670. if ( setup.wRequestAndType == 0x2021 /*CDC_SET_LINE_CODING*/ )
  671. {
  672. int i;
  673. uint8_t *dst = (uint8_t *)usb_cdc_line_coding;
  674. //serial_print("set line coding ");
  675. for ( i = 0; i < 7; i++ )
  676. {
  677. //serial_phex(*buf);
  678. *dst++ = *buf++;
  679. }
  680. //serial_phex32(usb_cdc_line_coding[0]);
  681. //serial_print("\n");
  682. if ( usb_cdc_line_coding[0] == 134 )
  683. usb_reboot_timer = 15;
  684. endpoint0_transmit( NULL, 0 );
  685. }
  686. // Keyboard SET_REPORT
  687. if ( setup.wRequestAndType == 0x921 && setup.wValue & 0x200 )
  688. {
  689. // Interface
  690. switch ( setup.wIndex & 0xFF )
  691. {
  692. // Keyboard Interface
  693. case KEYBOARD_INTERFACE:
  694. USBKeys_LEDs = buf[0];
  695. endpoint0_transmit( NULL, 0 );
  696. break;
  697. // NKRO Keyboard Interface
  698. case NKRO_KEYBOARD_INTERFACE:
  699. // Only use 2nd byte, first byte is the report id
  700. USBKeys_LEDs = buf[1];
  701. endpoint0_transmit( NULL, 0 );
  702. break;
  703. default:
  704. warn_msg("Unknown interface - ");
  705. printHex( setup.wIndex );
  706. print( NL );
  707. break;
  708. }
  709. #ifdef UART_DEBUG
  710. for ( size_t len = 0; len < setup.wLength; len++ )
  711. {
  712. printHex( buf[ len ] );
  713. print(" ");
  714. }
  715. print( NL );
  716. #endif
  717. }
  718. // give the buffer back
  719. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  720. break;
  721. case 0x09: // IN transaction completed to host
  722. #ifdef UART_DEBUG
  723. print("PID=IN:");
  724. printHex(stat);
  725. print(NL);
  726. #endif
  727. // send remaining data, if any...
  728. data = ep0_tx_ptr;
  729. if ( data )
  730. {
  731. size = ep0_tx_len;
  732. if (size > EP0_SIZE) size = EP0_SIZE;
  733. endpoint0_transmit(data, size);
  734. data += size;
  735. ep0_tx_len -= size;
  736. ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
  737. }
  738. if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
  739. {
  740. setup.bRequest = 0;
  741. #ifdef UART_DEBUG
  742. print("set address: ");
  743. printHex(setup.wValue);
  744. print(NL);
  745. #endif
  746. USB0_ADDR = setup.wValue;
  747. }
  748. break;
  749. default:
  750. #ifdef UART_DEBUG
  751. print("PID=unknown:");
  752. printHex(pid);
  753. print(NL);
  754. #endif
  755. break;
  756. }
  757. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  758. }
  759. usb_packet_t *usb_rx( uint32_t endpoint )
  760. {
  761. //print("USB RX");
  762. usb_packet_t *ret;
  763. endpoint--;
  764. if ( endpoint >= NUM_ENDPOINTS )
  765. return NULL;
  766. __disable_irq();
  767. ret = rx_first[endpoint];
  768. if ( ret )
  769. rx_first[ endpoint ] = ret->next;
  770. usb_rx_byte_count_data[ endpoint ] -= ret->len;
  771. __enable_irq();
  772. //serial_print("rx, epidx=");
  773. //serial_phex(endpoint);
  774. //serial_print(", packet=");
  775. //serial_phex32(ret);
  776. //serial_print("\n");
  777. return ret;
  778. }
  779. static uint32_t usb_queue_byte_count( const usb_packet_t *p )
  780. {
  781. uint32_t count=0;
  782. __disable_irq();
  783. for ( ; p; p = p->next )
  784. {
  785. count += p->len;
  786. }
  787. __enable_irq();
  788. return count;
  789. }
  790. uint32_t usb_tx_byte_count( uint32_t endpoint )
  791. {
  792. endpoint--;
  793. if ( endpoint >= NUM_ENDPOINTS )
  794. return 0;
  795. return usb_queue_byte_count( tx_first[ endpoint ] );
  796. }
  797. uint32_t usb_tx_packet_count( uint32_t endpoint )
  798. {
  799. const usb_packet_t *p;
  800. uint32_t count=0;
  801. endpoint--;
  802. if ( endpoint >= NUM_ENDPOINTS )
  803. return 0;
  804. __disable_irq();
  805. for ( p = tx_first[ endpoint ]; p; p = p->next )
  806. count++;
  807. __enable_irq();
  808. return count;
  809. }
  810. // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
  811. // receive endpoints are starving for memory. The intention is to give
  812. // endpoints needing receive memory priority over the user's code, which is
  813. // likely calling usb_malloc to obtain memory for transmitting. When the
  814. // user is creating data very quickly, their consumption could starve reception
  815. // without this prioritization. The packet buffer (input) is assigned to the
  816. // first endpoint needing memory.
  817. //
  818. void usb_rx_memory( usb_packet_t *packet )
  819. {
  820. //print("USB RX MEMORY");
  821. unsigned int i;
  822. const uint8_t *cfg;
  823. cfg = usb_endpoint_config_table;
  824. //serial_print("rx_mem:");
  825. __disable_irq();
  826. for ( i = 1; i <= NUM_ENDPOINTS; i++ )
  827. {
  828. if ( *cfg++ & USB_ENDPT_EPRXEN )
  829. {
  830. if ( table[ index( i, RX, EVEN ) ].desc == 0 )
  831. {
  832. table[ index( i, RX, EVEN ) ].addr = packet->buf;
  833. table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
  834. usb_rx_memory_needed--;
  835. __enable_irq();
  836. //serial_phex(i);
  837. //serial_print(",even\n");
  838. return;
  839. }
  840. if ( table[ index( i, RX, ODD ) ].desc == 0 )
  841. {
  842. table[ index( i, RX, ODD ) ].addr = packet->buf;
  843. table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
  844. usb_rx_memory_needed--;
  845. __enable_irq();
  846. //serial_phex(i);
  847. //serial_print(",odd\n");
  848. return;
  849. }
  850. }
  851. }
  852. __enable_irq();
  853. // we should never reach this point. If we get here, it means
  854. // usb_rx_memory_needed was set greater than zero, but no memory
  855. // was actually needed.
  856. usb_rx_memory_needed = 0;
  857. usb_free( packet );
  858. return;
  859. }
  860. //#define index(endpoint, tx, odd) (((endpoint) << 2) | ((tx) << 1) | (odd))
  861. //#define stat2bufferdescriptor(stat) (table + ((stat) >> 2))
  862. void usb_tx( uint32_t endpoint, usb_packet_t *packet )
  863. {
  864. // Since we are transmitting data, USB will be brought out of sleep/suspend
  865. // if it's in that state
  866. // Use the currently set descriptor value
  867. Output_update_usb_current( *usb_bMaxPower * 2 );
  868. bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
  869. uint8_t next;
  870. endpoint--;
  871. if ( endpoint >= NUM_ENDPOINTS )
  872. return;
  873. __disable_irq();
  874. //serial_print("txstate=");
  875. //serial_phex(tx_state[ endpoint ]);
  876. //serial_print("\n");
  877. switch ( tx_state[ endpoint ] )
  878. {
  879. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  880. next = TX_STATE_ODD_FREE;
  881. break;
  882. case TX_STATE_BOTH_FREE_ODD_FIRST:
  883. b++;
  884. next = TX_STATE_EVEN_FREE;
  885. break;
  886. case TX_STATE_EVEN_FREE:
  887. next = TX_STATE_NONE_FREE_ODD_FIRST;
  888. break;
  889. case TX_STATE_ODD_FREE:
  890. b++;
  891. next = TX_STATE_NONE_FREE_EVEN_FIRST;
  892. break;
  893. default:
  894. if (tx_first[ endpoint ] == NULL)
  895. {
  896. tx_first[ endpoint ] = packet;
  897. }
  898. else
  899. {
  900. tx_last[ endpoint ]->next = packet;
  901. }
  902. tx_last[ endpoint ] = packet;
  903. __enable_irq();
  904. return;
  905. }
  906. tx_state[ endpoint ] = next;
  907. b->addr = packet->buf;
  908. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  909. __enable_irq();
  910. }
  911. void usb_device_reload()
  912. {
  913. // MCHCK
  914. // Kiibohd mk20dx256vlh7
  915. #if defined(_mk20dx128vlf5_) || defined(_mk20dx256vlh7_)
  916. // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
  917. for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
  918. (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
  919. SOFTWARE_RESET();
  920. // Teensy 3.0 and 3.1
  921. #else
  922. asm volatile("bkpt");
  923. #endif
  924. }
  925. void usb_isr()
  926. {
  927. uint8_t status, stat, t;
  928. //serial_print("isr");
  929. //status = USB0_ISTAT;
  930. //serial_phex(status);
  931. //serial_print("\n");
  932. restart:
  933. status = USB0_ISTAT;
  934. /*
  935. print("USB ISR STATUS: ");
  936. printHex( status );
  937. print( NL );
  938. */
  939. if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
  940. {
  941. if ( usb_configuration )
  942. {
  943. t = usb_reboot_timer;
  944. if ( t )
  945. {
  946. usb_reboot_timer = --t;
  947. if ( !t )
  948. usb_device_reload();
  949. }
  950. // CDC Interface
  951. t = usb_cdc_transmit_flush_timer;
  952. if ( t )
  953. {
  954. usb_cdc_transmit_flush_timer = --t;
  955. if ( t == 0 )
  956. usb_serial_flush_callback();
  957. }
  958. }
  959. USB0_ISTAT = USB_INTEN_SOFTOKEN;
  960. }
  961. if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
  962. {
  963. uint8_t endpoint;
  964. stat = USB0_STAT;
  965. //serial_print("token: ep=");
  966. //serial_phex(stat >> 4);
  967. //serial_print(stat & 0x08 ? ",tx" : ",rx");
  968. //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
  969. endpoint = stat >> 4;
  970. if ( endpoint == 0 )
  971. {
  972. usb_control( stat );
  973. }
  974. else
  975. {
  976. bdt_t *b = stat2bufferdescriptor(stat);
  977. usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
  978. #if 0
  979. serial_print("ep:");
  980. serial_phex(endpoint);
  981. serial_print(", pid:");
  982. serial_phex(BDT_PID(b->desc));
  983. serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
  984. serial_print(", count:");
  985. serial_phex(b->desc >> 16);
  986. serial_print("\n");
  987. #endif
  988. endpoint--; // endpoint is index to zero-based arrays
  989. if ( stat & 0x08 )
  990. { // transmit
  991. usb_free( packet );
  992. packet = tx_first[ endpoint ];
  993. if ( packet )
  994. {
  995. //serial_print("tx packet\n");
  996. tx_first[endpoint] = packet->next;
  997. b->addr = packet->buf;
  998. switch ( tx_state[ endpoint ] )
  999. {
  1000. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  1001. tx_state[ endpoint ] = TX_STATE_ODD_FREE;
  1002. break;
  1003. case TX_STATE_BOTH_FREE_ODD_FIRST:
  1004. tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
  1005. break;
  1006. case TX_STATE_EVEN_FREE:
  1007. tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
  1008. break;
  1009. case TX_STATE_ODD_FREE:
  1010. tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
  1011. break;
  1012. default:
  1013. break;
  1014. }
  1015. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1016. } else {
  1017. //serial_print("tx no packet\n");
  1018. switch ( tx_state[ endpoint ] )
  1019. {
  1020. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  1021. case TX_STATE_BOTH_FREE_ODD_FIRST:
  1022. break;
  1023. case TX_STATE_EVEN_FREE:
  1024. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  1025. break;
  1026. case TX_STATE_ODD_FREE:
  1027. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
  1028. break;
  1029. default:
  1030. tx_state[ endpoint ] = ((uint32_t)b & 8)
  1031. ? TX_STATE_ODD_FREE
  1032. : TX_STATE_EVEN_FREE;
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. else
  1038. { // receive
  1039. packet->len = b->desc >> 16;
  1040. if ( packet->len > 0 )
  1041. {
  1042. packet->index = 0;
  1043. packet->next = NULL;
  1044. if ( rx_first[ endpoint ] == NULL )
  1045. {
  1046. //serial_print("rx 1st, epidx=");
  1047. //serial_phex(endpoint);
  1048. //serial_print(", packet=");
  1049. //serial_phex32((uint32_t)packet);
  1050. //serial_print("\n");
  1051. rx_first[ endpoint ] = packet;
  1052. }
  1053. else
  1054. {
  1055. //serial_print("rx Nth, epidx=");
  1056. //serial_phex(endpoint);
  1057. //serial_print(", packet=");
  1058. //serial_phex32((uint32_t)packet);
  1059. //serial_print("\n");
  1060. rx_last[ endpoint ]->next = packet;
  1061. }
  1062. rx_last[ endpoint ] = packet;
  1063. usb_rx_byte_count_data[ endpoint ] += packet->len;
  1064. // TODO: implement a per-endpoint maximum # of allocated packets
  1065. // so a flood of incoming data on 1 endpoint doesn't starve
  1066. // the others if the user isn't reading it regularly
  1067. packet = usb_malloc();
  1068. if ( packet )
  1069. {
  1070. b->addr = packet->buf;
  1071. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1072. }
  1073. else
  1074. {
  1075. //serial_print("starving ");
  1076. //serial_phex(endpoint + 1);
  1077. //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
  1078. b->desc = 0;
  1079. usb_rx_memory_needed++;
  1080. }
  1081. }
  1082. else
  1083. {
  1084. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1085. }
  1086. }
  1087. }
  1088. USB0_ISTAT = USB_ISTAT_TOKDNE;
  1089. goto restart;
  1090. }
  1091. if ( status & USB_ISTAT_USBRST /* 01 */ )
  1092. {
  1093. //serial_print("reset\n");
  1094. // initialize BDT toggle bits
  1095. USB0_CTL = USB_CTL_ODDRST;
  1096. ep0_tx_bdt_bank = 0;
  1097. // set up buffers to receive Setup and OUT packets
  1098. table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  1099. table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
  1100. table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  1101. table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
  1102. table[index( 0, TX, EVEN ) ].desc = 0;
  1103. table[index( 0, TX, ODD ) ].desc = 0;
  1104. // activate endpoint 0
  1105. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1106. // clear all ending interrupts
  1107. USB0_ERRSTAT = 0xFF;
  1108. USB0_ISTAT = 0xFF;
  1109. // set the address to zero during enumeration
  1110. USB0_ADDR = 0;
  1111. // enable other interrupts
  1112. USB0_ERREN = 0xFF;
  1113. USB0_INTEN = USB_INTEN_TOKDNEEN |
  1114. USB_INTEN_SOFTOKEN |
  1115. USB_INTEN_STALLEN |
  1116. USB_INTEN_ERROREN |
  1117. USB_INTEN_USBRSTEN |
  1118. USB_INTEN_SLEEPEN;
  1119. // is this necessary?
  1120. USB0_CTL = USB_CTL_USBENSOFEN;
  1121. return;
  1122. }
  1123. if ( (status & USB_ISTAT_STALL /* 80 */ ) )
  1124. {
  1125. //serial_print("stall:\n");
  1126. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1127. USB0_ISTAT = USB_ISTAT_STALL;
  1128. }
  1129. if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
  1130. {
  1131. uint8_t err = USB0_ERRSTAT;
  1132. USB0_ERRSTAT = err;
  1133. //serial_print("err:");
  1134. //serial_phex(err);
  1135. //serial_print("\n");
  1136. USB0_ISTAT = USB_ISTAT_ERROR;
  1137. }
  1138. // USB Host signalling device to enter 'sleep' state
  1139. // The USB Module triggers this interrupt when it detects the bus has been idle for 3 ms
  1140. if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
  1141. {
  1142. info_print("Host has requested USB sleep/suspend state");
  1143. Output_update_usb_current( 100 ); // Set to 100 mA
  1144. USB0_ISTAT = USB_ISTAT_SLEEP;
  1145. }
  1146. }
  1147. uint8_t usb_init()
  1148. {
  1149. #ifdef UART_DEBUG
  1150. print("USB INIT"NL);
  1151. #endif
  1152. // Clear out endpoints table
  1153. for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
  1154. {
  1155. table[i].desc = 0;
  1156. table[i].addr = 0;
  1157. }
  1158. // this basically follows the flowchart in the Kinetis
  1159. // Quick Reference User Guide, Rev. 1, 03/2012, page 141
  1160. // assume 48 MHz clock already running
  1161. // SIM - enable clock
  1162. SIM_SCGC4 |= SIM_SCGC4_USBOTG;
  1163. // reset USB module
  1164. USB0_USBTRC0 = USB_USBTRC_USBRESET;
  1165. while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
  1166. // set desc table base addr
  1167. USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
  1168. USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
  1169. USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
  1170. // clear all ISR flags
  1171. USB0_ISTAT = 0xFF;
  1172. USB0_ERRSTAT = 0xFF;
  1173. USB0_OTGISTAT = 0xFF;
  1174. USB0_USBTRC0 |= 0x40; // undocumented bit
  1175. // enable USB
  1176. USB0_CTL = USB_CTL_USBENSOFEN;
  1177. USB0_USBCTRL = 0;
  1178. // enable reset interrupt
  1179. USB0_INTEN = USB_INTEN_USBRSTEN;
  1180. // enable interrupt in NVIC...
  1181. NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
  1182. NVIC_ENABLE_IRQ( IRQ_USBOTG );
  1183. // enable d+ pullup
  1184. USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
  1185. // Do not check for power negotiation delay until Get Configuration Descriptor
  1186. power_neg_delay = 0;
  1187. return 1;
  1188. }
  1189. // return 0 if the USB is not configured, or the configuration
  1190. // number selected by the HOST
  1191. uint8_t usb_configured()
  1192. {
  1193. return usb_configuration;
  1194. }