Kiibohd Controller
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
Это архивный репозиторий. Вы можете его клонировать или просматривать файлы, но не вносить изменения или открывать задачи/запросы на слияние.

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