Kiibohd Controller
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
このリポジトリはアーカイブされています。 ファイルの閲覧とクローンは可能ですが、プッシュや、課題・プルリクエストのオープンはできません。

usb_dev.c 28KB

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