Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

usb_dev.c 38KB

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