Kiibohd Controller
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
Tento repozitář je archivovaný. Můžete prohlížet soubory, klonovat, ale nemůžete nahrávat a vytvářet nové úkoly a požadavky na natažení.

usb_dev.c 34KB

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