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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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. // Force Boot Mode if defined by KLL
  572. if ( USBProtocol_define == 0 )
  573. {
  574. USBKeys_Protocol = USBProtocol_define;
  575. }
  576. goto send;
  577. case 0x03A1: /// HID GET_PROTOCOL
  578. #ifdef UART_DEBUG
  579. print("GET_PROTOCOL - ");
  580. printHex( setup.wValue );
  581. print(" - ");
  582. printHex( USBKeys_Protocol );
  583. print(NL);
  584. #endif
  585. reply_buffer[0] = USBKeys_Protocol;
  586. data = reply_buffer;
  587. datalen = 1;
  588. goto send;
  589. // case 0xC940:
  590. default:
  591. #ifdef UART_DEBUG_UNKNOWN
  592. print("UNKNOWN: ");
  593. printInt32( systick_millis_count - USBInit_TimeStart );
  594. print(" ms");
  595. print(NL);
  596. #endif
  597. endpoint0_stall();
  598. return;
  599. }
  600. send:
  601. #ifdef UART_DEBUG
  602. print("setup send ");
  603. printHex32( (uint32_t)data );
  604. print(",");
  605. for ( uint8_t c = 0; c < datalen; c++ )
  606. {
  607. printHex( data[c] );
  608. print(" ");
  609. }
  610. print(",");
  611. printHex( datalen );
  612. print( NL );
  613. #endif
  614. if ( datalen > setup.wLength )
  615. datalen = setup.wLength;
  616. size = datalen;
  617. if ( size > EP0_SIZE )
  618. size = EP0_SIZE;
  619. endpoint0_transmit( data, size );
  620. data += size;
  621. datalen -= size;
  622. // See if transmit has finished
  623. if ( datalen == 0 && size < EP0_SIZE )
  624. return;
  625. size = datalen;
  626. if ( size > EP0_SIZE )
  627. size = EP0_SIZE;
  628. endpoint0_transmit( data, size );
  629. data += size;
  630. datalen -= size;
  631. // See if transmit has finished
  632. if ( datalen == 0 && size < EP0_SIZE )
  633. return;
  634. // Save rest of transfer for later? XXX
  635. ep0_tx_ptr = data;
  636. ep0_tx_len = datalen;
  637. }
  638. //A bulk endpoint's toggle sequence is initialized to DATA0 when the endpoint
  639. //experiences any configuration event (configuration events are explained in
  640. //Sections 9.1.1.5 and 9.4.5).
  641. //Configuring a device or changing an alternate setting causes all of the status
  642. //and configuration values associated with endpoints in the affected interfaces
  643. //to be set to their default values. This includes setting the data toggle of
  644. //any endpoint using data toggles to the value DATA0.
  645. // For endpoints using data toggle, regardless of whether an endpoint has the
  646. // Halt feature set, a ClearFeature(ENDPOINT_HALT) request always results in the
  647. // data toggle being reinitialized to DATA0.
  648. static void usb_control( uint32_t stat )
  649. {
  650. #ifdef UART_DEBUG
  651. print("CONTROL - ");
  652. #endif
  653. bdt_t *b;
  654. uint32_t pid, size;
  655. uint8_t *buf;
  656. const uint8_t *data;
  657. b = stat2bufferdescriptor( stat );
  658. pid = BDT_PID( b->desc );
  659. buf = b->addr;
  660. #ifdef UART_DEBUG
  661. print("pid:");
  662. printHex(pid);
  663. print(", count:");
  664. printHex32(b->desc);
  665. print(" - ");
  666. #endif
  667. switch ( pid )
  668. {
  669. case 0x0D: // Setup received from host
  670. // grab the 8 byte setup info
  671. setup.word1 = *(uint32_t *)(buf);
  672. setup.word2 = *(uint32_t *)(buf + 4);
  673. // give the buffer back
  674. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  675. //table[index(0, RX, EVEN)].desc = BDT_DESC(EP0_SIZE, 1);
  676. //table[index(0, RX, ODD)].desc = BDT_DESC(EP0_SIZE, 1);
  677. // clear any leftover pending IN transactions
  678. ep0_tx_ptr = NULL;
  679. if ( ep0_tx_data_toggle )
  680. {
  681. }
  682. //if (table[index(0, TX, EVEN)].desc & 0x80) {
  683. //serial_print("leftover tx even\n");
  684. //}
  685. //if (table[index(0, TX, ODD)].desc & 0x80) {
  686. //serial_print("leftover tx odd\n");
  687. //}
  688. table[index(0, TX, EVEN)].desc = 0;
  689. table[index(0, TX, ODD)].desc = 0;
  690. // first IN after Setup is always DATA1
  691. ep0_tx_data_toggle = 1;
  692. #ifdef UART_DEBUG_UNKNOWN
  693. printHex( stat );
  694. print(" PID=SETUP wRequestAndType:");
  695. printHex(setup.wRequestAndType);
  696. print(", wValue:");
  697. printHex(setup.wValue);
  698. print(", wIndex:");
  699. printHex(setup.wIndex);
  700. print(", len:");
  701. printHex(setup.wLength);
  702. print(" -- ");
  703. printHex32(setup.word1);
  704. print(" ");
  705. printHex32(setup.word2);
  706. print(": ");
  707. printInt32( systick_millis_count - USBInit_TimeStart );
  708. print(" ms");
  709. print(NL);
  710. #endif
  711. // actually "do" the setup request
  712. usb_setup();
  713. // unfreeze the USB, now that we're ready
  714. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  715. break;
  716. case 0x01: // OUT transaction received from host
  717. case 0x02:
  718. #ifdef UART_DEBUG_UNKNOWN
  719. printHex( stat );
  720. print(" PID=OUT wRequestAndType:");
  721. printHex(setup.wRequestAndType);
  722. print(", wValue:");
  723. printHex(setup.wValue);
  724. print(", wIndex:");
  725. printHex(setup.wIndex);
  726. print(", len:");
  727. printHex(setup.wLength);
  728. print(" -- ");
  729. printHex32(setup.word1);
  730. print(" ");
  731. printHex32(setup.word2);
  732. print(": ");
  733. printInt32( systick_millis_count - USBInit_TimeStart );
  734. print(" ms");
  735. print(NL);
  736. #endif
  737. // CDC Interface
  738. #if enableVirtualSerialPort_define == 1
  739. // CDC_SET_LINE_CODING - PID=OUT
  740. // XXX - Getting lots of NAKs in Linux
  741. if ( setup.wRequestAndType == 0x2021 )
  742. {
  743. // Copy over new line coding
  744. memcpy( (void*)&usb_cdc_line_coding, buf, 7 );
  745. #ifdef UART_DEBUG
  746. // - Unused, but for the readers info -
  747. print("dwDTERate(");
  748. printInt32( usb_cdc_line_coding.dwDTERate );
  749. print(")bCharFormat(");
  750. printHex( usb_cdc_line_coding.bCharFormat );
  751. print(")bParityType(");
  752. printHex( usb_cdc_line_coding.bParityType );
  753. print(")bDataBits(");
  754. printHex( usb_cdc_line_coding.bDataBits );
  755. print(")");
  756. print( NL );
  757. #endif
  758. // XXX ZLP causes timeout/delay, why? -HaaTa
  759. //endpoint0_transmit( NULL, 0 );
  760. }
  761. #endif
  762. // Keyboard HID SET_REPORT - PID=OUT
  763. #if enableKeyboard_define == 1
  764. // XXX - Getting lots of NAKs in Linux
  765. if ( setup.wRequestAndType == 0x0921 && setup.wValue & 0x200 )
  766. {
  767. #ifdef UART_DEBUG
  768. print("report_type(");
  769. printHex( setup.wValue >> 8 );
  770. print(")report_id(");
  771. printHex( setup.wValue & 0xFF );
  772. print(")interface(");
  773. printHex( setup.wIndex );
  774. print(")len(");
  775. printHex( setup.wLength );
  776. print(")[");
  777. for ( size_t len = 0; len < setup.wLength; len++ )
  778. {
  779. printHex( buf[ len ] );
  780. print(" ");
  781. }
  782. print("]");
  783. print( NL );
  784. #endif
  785. // Interface
  786. switch ( setup.wIndex & 0xFF )
  787. {
  788. // Keyboard Interface
  789. case KEYBOARD_INTERFACE:
  790. USBKeys_LEDs = buf[0];
  791. break;
  792. // NKRO Keyboard Interface
  793. case NKRO_KEYBOARD_INTERFACE:
  794. // Already set with the control sequence
  795. // Only use 2nd byte, first byte is the report id
  796. USBKeys_LEDs = buf[1];
  797. break;
  798. default:
  799. warn_msg("Unknown interface - ");
  800. printHex( setup.wIndex );
  801. print( NL );
  802. break;
  803. }
  804. // XXX ZLP causes timeout/delay, why? -HaaTa
  805. //endpoint0_transmit( NULL, 0 );
  806. }
  807. #endif
  808. // give the buffer back
  809. b->desc = BDT_DESC( EP0_SIZE, DATA1 );
  810. break;
  811. case 0x09: // IN transaction completed to host
  812. data = ep0_tx_ptr;
  813. #ifdef UART_DEBUG_UNKNOWN
  814. printHex( stat );
  815. print(" PID=IN wRequestAndType:");
  816. printHex(setup.wRequestAndType);
  817. print(", wValue:");
  818. printHex(setup.wValue);
  819. print(", wIndex:");
  820. printHex(setup.wIndex);
  821. print(", len:");
  822. printHex(setup.wLength);
  823. print(" -- ");
  824. printHex32(setup.word1);
  825. print(" ");
  826. printHex32(setup.word2);
  827. print(": ");
  828. printInt32( systick_millis_count - USBInit_TimeStart );
  829. print(" ms");
  830. if ( data ) print(" DATA ");
  831. print(NL);
  832. #endif
  833. // send remaining data, if any...
  834. if ( data )
  835. {
  836. size = ep0_tx_len;
  837. if (size > EP0_SIZE)
  838. {
  839. size = EP0_SIZE;
  840. }
  841. endpoint0_transmit( data, size );
  842. data += size;
  843. ep0_tx_len -= size;
  844. ep0_tx_ptr = (ep0_tx_len > 0 || size == EP0_SIZE) ? data : NULL;
  845. }
  846. if ( setup.bRequest == 5 && setup.bmRequestType == 0 )
  847. {
  848. setup.bRequest = 0;
  849. #ifdef UART_DEBUG
  850. print("set address: ");
  851. printHex(setup.wValue);
  852. print(NL);
  853. #endif
  854. USB0_ADDR = setup.wValue;
  855. }
  856. // CDC_SET_LINE_CODING - PID=IN
  857. #if enableVirtualSerialPort_define == 1
  858. if ( setup.wRequestAndType == 0x2021 )
  859. {
  860. // XXX ZLP causes timeout/delay, why? -HaaTa
  861. //endpoint0_transmit( NULL, 0 );
  862. }
  863. #endif
  864. // Keyboard HID SET_REPORT - PID=IN
  865. #if enableKeyboard_define == 1
  866. // XXX - Getting lots of NAKs in Linux
  867. if ( setup.wRequestAndType == 0x0921 && setup.wValue & 0x200 )
  868. {
  869. // XXX ZLP causes timeout/delay, why? -HaaTa
  870. //endpoint0_transmit( NULL, 0 );
  871. }
  872. #endif
  873. break;
  874. default:
  875. #ifdef UART_DEBUG_UNKNOWN
  876. print("PID=unknown: ");
  877. printHex(pid);
  878. print(": ");
  879. printInt32( systick_millis_count - USBInit_TimeStart );
  880. print(" ms");
  881. print(NL);
  882. #endif
  883. break;
  884. }
  885. USB0_CTL = USB_CTL_USBENSOFEN; // clear TXSUSPENDTOKENBUSY bit
  886. }
  887. usb_packet_t *usb_rx( uint32_t endpoint )
  888. {
  889. //print("USB RX");
  890. usb_packet_t *ret;
  891. endpoint--;
  892. // Make sure this is a valid endpoint
  893. if ( endpoint >= NUM_ENDPOINTS )
  894. {
  895. return NULL;
  896. }
  897. __disable_irq();
  898. // Receive packet, check pointer
  899. ret = rx_first[endpoint];
  900. if ( ret )
  901. {
  902. rx_first[ endpoint ] = ret->next;
  903. usb_rx_byte_count_data[ endpoint ] -= ret->len;
  904. }
  905. __enable_irq();
  906. //serial_print("rx, epidx=");
  907. //serial_phex(endpoint);
  908. //serial_print(", packet=");
  909. //serial_phex32(ret);
  910. //serial_print("\n");
  911. return ret;
  912. }
  913. static uint32_t usb_queue_byte_count( const usb_packet_t *p )
  914. {
  915. uint32_t count=0;
  916. __disable_irq();
  917. for ( ; p; p = p->next )
  918. {
  919. count += p->len;
  920. }
  921. __enable_irq();
  922. return count;
  923. }
  924. uint32_t usb_tx_byte_count( uint32_t endpoint )
  925. {
  926. endpoint--;
  927. if ( endpoint >= NUM_ENDPOINTS )
  928. return 0;
  929. return usb_queue_byte_count( tx_first[ endpoint ] );
  930. }
  931. uint32_t usb_tx_packet_count( uint32_t endpoint )
  932. {
  933. const usb_packet_t *p;
  934. uint32_t count=0;
  935. endpoint--;
  936. if ( endpoint >= NUM_ENDPOINTS )
  937. return 0;
  938. __disable_irq();
  939. for ( p = tx_first[ endpoint ]; p; p = p->next )
  940. count++;
  941. __enable_irq();
  942. return count;
  943. }
  944. // Called from usb_free, but only when usb_rx_memory_needed > 0, indicating
  945. // receive endpoints are starving for memory. The intention is to give
  946. // endpoints needing receive memory priority over the user's code, which is
  947. // likely calling usb_malloc to obtain memory for transmitting. When the
  948. // user is creating data very quickly, their consumption could starve reception
  949. // without this prioritization. The packet buffer (input) is assigned to the
  950. // first endpoint needing memory.
  951. //
  952. void usb_rx_memory( usb_packet_t *packet )
  953. {
  954. //print("USB RX MEMORY");
  955. unsigned int i;
  956. const uint8_t *cfg;
  957. cfg = usb_endpoint_config_table;
  958. //serial_print("rx_mem:");
  959. __disable_irq();
  960. for ( i = 1; i <= NUM_ENDPOINTS; i++ )
  961. {
  962. if ( *cfg++ & USB_ENDPT_EPRXEN )
  963. {
  964. if ( table[ index( i, RX, EVEN ) ].desc == 0 )
  965. {
  966. table[ index( i, RX, EVEN ) ].addr = packet->buf;
  967. table[ index( i, RX, EVEN ) ].desc = BDT_DESC( 64, 0 );
  968. usb_rx_memory_needed--;
  969. __enable_irq();
  970. //serial_phex(i);
  971. //serial_print(",even\n");
  972. return;
  973. }
  974. if ( table[ index( i, RX, ODD ) ].desc == 0 )
  975. {
  976. table[ index( i, RX, ODD ) ].addr = packet->buf;
  977. table[ index( i, RX, ODD ) ].desc = BDT_DESC( 64, 1 );
  978. usb_rx_memory_needed--;
  979. __enable_irq();
  980. //serial_phex(i);
  981. //serial_print(",odd\n");
  982. return;
  983. }
  984. }
  985. }
  986. __enable_irq();
  987. // we should never reach this point. If we get here, it means
  988. // usb_rx_memory_needed was set greater than zero, but no memory
  989. // was actually needed.
  990. usb_rx_memory_needed = 0;
  991. usb_free( packet );
  992. return;
  993. }
  994. // Call whenever there's an action that may wake the host device
  995. void usb_resume()
  996. {
  997. // If we have been sleeping, try to wake up host
  998. if ( usb_dev_sleep && usb_configured() )
  999. {
  1000. #if enableUSBResume_define == 1
  1001. #if enableVirtualSerialPort_define != 1
  1002. info_print("Attempting to resume the host");
  1003. #endif
  1004. // Force wake-up for 10 ms
  1005. // According to the USB Spec a device must hold resume for at least 1 ms but no more than 15 ms
  1006. USB0_CTL |= USB_CTL_RESUME;
  1007. delay(10);
  1008. USB0_CTL &= ~(USB_CTL_RESUME);
  1009. delay(50); // Wait for at least 50 ms to make sure the bus is clear
  1010. usb_dev_sleep = 0; // Make sure we don't call this again, may crash system
  1011. #else
  1012. warn_print("Host Resume Disabled");
  1013. #endif
  1014. }
  1015. }
  1016. void usb_tx( uint32_t endpoint, usb_packet_t *packet )
  1017. {
  1018. // Update expiry counter
  1019. USBKeys_Idle_Expiry = systick_millis_count;
  1020. // Since we are transmitting data, USB will be brought out of sleep/suspend
  1021. // if it's in that state
  1022. // Use the currently set descriptor value
  1023. Output_update_usb_current( *usb_bMaxPower * 2 );
  1024. bdt_t *b = &table[ index( endpoint, TX, EVEN ) ];
  1025. uint8_t next;
  1026. endpoint--;
  1027. if ( endpoint >= NUM_ENDPOINTS )
  1028. return;
  1029. __disable_irq();
  1030. //serial_print("txstate=");
  1031. //serial_phex(tx_state[ endpoint ]);
  1032. //serial_print("\n");
  1033. switch ( tx_state[ endpoint ] )
  1034. {
  1035. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  1036. next = TX_STATE_ODD_FREE;
  1037. break;
  1038. case TX_STATE_BOTH_FREE_ODD_FIRST:
  1039. b++;
  1040. next = TX_STATE_EVEN_FREE;
  1041. break;
  1042. case TX_STATE_EVEN_FREE:
  1043. next = TX_STATE_NONE_FREE_ODD_FIRST;
  1044. break;
  1045. case TX_STATE_ODD_FREE:
  1046. b++;
  1047. next = TX_STATE_NONE_FREE_EVEN_FIRST;
  1048. break;
  1049. default:
  1050. if (tx_first[ endpoint ] == NULL)
  1051. {
  1052. tx_first[ endpoint ] = packet;
  1053. }
  1054. else
  1055. {
  1056. tx_last[ endpoint ]->next = packet;
  1057. }
  1058. tx_last[ endpoint ] = packet;
  1059. __enable_irq();
  1060. return;
  1061. }
  1062. tx_state[ endpoint ] = next;
  1063. b->addr = packet->buf;
  1064. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1065. __enable_irq();
  1066. }
  1067. void usb_device_reload()
  1068. {
  1069. // MCHCK
  1070. // Kiibohd mk20dx256vlh7
  1071. #if defined(_mk20dx128vlf5_) || defined(_mk20dx256vlh7_)
  1072. // Copies variable into the VBAT register, must be identical to the variable in the bootloader to jump to the bootloader flash mode
  1073. for ( int pos = 0; pos < sizeof(sys_reset_to_loader_magic); pos++ )
  1074. (&VBAT)[ pos ] = sys_reset_to_loader_magic[ pos ];
  1075. SOFTWARE_RESET();
  1076. // Teensy 3.0 and 3.1
  1077. #else
  1078. asm volatile("bkpt");
  1079. #endif
  1080. }
  1081. void usb_isr()
  1082. {
  1083. uint8_t status, stat, t;
  1084. restart:
  1085. status = USB0_ISTAT;
  1086. /*
  1087. print(" ISR(");
  1088. printHex( status );
  1089. print(") ");
  1090. */
  1091. if ( (status & USB_INTEN_SOFTOKEN /* 04 */ ) )
  1092. {
  1093. if ( usb_configuration )
  1094. {
  1095. t = usb_reboot_timer;
  1096. if ( t )
  1097. {
  1098. usb_reboot_timer = --t;
  1099. if ( !t )
  1100. usb_device_reload();
  1101. }
  1102. // CDC Interface
  1103. #if enableVirtualSerialPort_define == 1
  1104. t = usb_cdc_transmit_flush_timer;
  1105. if ( t )
  1106. {
  1107. usb_cdc_transmit_flush_timer = --t;
  1108. if ( t == 0 )
  1109. usb_serial_flush_callback();
  1110. }
  1111. #endif
  1112. }
  1113. USB0_ISTAT = USB_INTEN_SOFTOKEN;
  1114. }
  1115. if ( (status & USB_ISTAT_TOKDNE /* 08 */ ) )
  1116. {
  1117. uint8_t endpoint;
  1118. stat = USB0_STAT;
  1119. //serial_print("token: ep=");
  1120. //serial_phex(stat >> 4);
  1121. //serial_print(stat & 0x08 ? ",tx" : ",rx");
  1122. //serial_print(stat & 0x04 ? ",odd\n" : ",even\n");
  1123. endpoint = stat >> 4;
  1124. if ( endpoint == 0 )
  1125. {
  1126. usb_control( stat );
  1127. }
  1128. else
  1129. {
  1130. bdt_t *b = stat2bufferdescriptor(stat);
  1131. usb_packet_t *packet = (usb_packet_t *)((uint8_t *)(b->addr) - 8);
  1132. #if 0
  1133. serial_print("ep:");
  1134. serial_phex(endpoint);
  1135. serial_print(", pid:");
  1136. serial_phex(BDT_PID(b->desc));
  1137. serial_print(((uint32_t)b & 8) ? ", odd" : ", even");
  1138. serial_print(", count:");
  1139. serial_phex(b->desc >> 16);
  1140. serial_print("\n");
  1141. #endif
  1142. endpoint--; // endpoint is index to zero-based arrays
  1143. if ( stat & 0x08 )
  1144. { // transmit
  1145. usb_free( packet );
  1146. packet = tx_first[ endpoint ];
  1147. if ( packet )
  1148. {
  1149. //serial_print("tx packet\n");
  1150. tx_first[endpoint] = packet->next;
  1151. b->addr = packet->buf;
  1152. switch ( tx_state[ endpoint ] )
  1153. {
  1154. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  1155. tx_state[ endpoint ] = TX_STATE_ODD_FREE;
  1156. break;
  1157. case TX_STATE_BOTH_FREE_ODD_FIRST:
  1158. tx_state[ endpoint ] = TX_STATE_EVEN_FREE;
  1159. break;
  1160. case TX_STATE_EVEN_FREE:
  1161. tx_state[ endpoint ] = TX_STATE_NONE_FREE_ODD_FIRST;
  1162. break;
  1163. case TX_STATE_ODD_FREE:
  1164. tx_state[ endpoint ] = TX_STATE_NONE_FREE_EVEN_FIRST;
  1165. break;
  1166. default:
  1167. break;
  1168. }
  1169. b->desc = BDT_DESC( packet->len, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1170. } else {
  1171. //serial_print("tx no packet\n");
  1172. switch ( tx_state[ endpoint ] )
  1173. {
  1174. case TX_STATE_BOTH_FREE_EVEN_FIRST:
  1175. case TX_STATE_BOTH_FREE_ODD_FIRST:
  1176. break;
  1177. case TX_STATE_EVEN_FREE:
  1178. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_EVEN_FIRST;
  1179. break;
  1180. case TX_STATE_ODD_FREE:
  1181. tx_state[ endpoint ] = TX_STATE_BOTH_FREE_ODD_FIRST;
  1182. break;
  1183. default:
  1184. tx_state[ endpoint ] = ((uint32_t)b & 8)
  1185. ? TX_STATE_ODD_FREE
  1186. : TX_STATE_EVEN_FREE;
  1187. break;
  1188. }
  1189. }
  1190. }
  1191. else
  1192. { // receive
  1193. packet->len = b->desc >> 16;
  1194. if ( packet->len > 0 )
  1195. {
  1196. packet->index = 0;
  1197. packet->next = NULL;
  1198. if ( rx_first[ endpoint ] == NULL )
  1199. {
  1200. //serial_print("rx 1st, epidx=");
  1201. //serial_phex(endpoint);
  1202. //serial_print(", packet=");
  1203. //serial_phex32((uint32_t)packet);
  1204. //serial_print("\n");
  1205. rx_first[ endpoint ] = packet;
  1206. }
  1207. else
  1208. {
  1209. //serial_print("rx Nth, epidx=");
  1210. //serial_phex(endpoint);
  1211. //serial_print(", packet=");
  1212. //serial_phex32((uint32_t)packet);
  1213. //serial_print("\n");
  1214. rx_last[ endpoint ]->next = packet;
  1215. }
  1216. rx_last[ endpoint ] = packet;
  1217. usb_rx_byte_count_data[ endpoint ] += packet->len;
  1218. // TODO: implement a per-endpoint maximum # of allocated packets
  1219. // so a flood of incoming data on 1 endpoint doesn't starve
  1220. // the others if the user isn't reading it regularly
  1221. packet = usb_malloc();
  1222. if ( packet )
  1223. {
  1224. b->addr = packet->buf;
  1225. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1226. }
  1227. else
  1228. {
  1229. //serial_print("starving ");
  1230. //serial_phex(endpoint + 1);
  1231. //serial_print(((uint32_t)b & 8) ? ",odd\n" : ",even\n");
  1232. b->desc = 0;
  1233. usb_rx_memory_needed++;
  1234. }
  1235. }
  1236. else
  1237. {
  1238. b->desc = BDT_DESC( 64, ((uint32_t)b & 8) ? DATA1 : DATA0 );
  1239. }
  1240. }
  1241. }
  1242. USB0_ISTAT = USB_ISTAT_TOKDNE;
  1243. goto restart;
  1244. }
  1245. if ( status & USB_ISTAT_USBRST /* 01 */ )
  1246. {
  1247. //serial_print("reset\n");
  1248. // initialize BDT toggle bits
  1249. USB0_CTL = USB_CTL_ODDRST;
  1250. ep0_tx_bdt_bank = 0;
  1251. // set up buffers to receive Setup and OUT packets
  1252. table[index( 0, RX, EVEN ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  1253. table[index( 0, RX, EVEN ) ].addr = ep0_rx0_buf;
  1254. table[index( 0, RX, ODD ) ].desc = BDT_DESC( EP0_SIZE, 0 );
  1255. table[index( 0, RX, ODD ) ].addr = ep0_rx1_buf;
  1256. table[index( 0, TX, EVEN ) ].desc = 0;
  1257. table[index( 0, TX, ODD ) ].desc = 0;
  1258. // activate endpoint 0
  1259. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1260. // clear all ending interrupts
  1261. USB0_ERRSTAT = 0xFF;
  1262. USB0_ISTAT = 0xFF;
  1263. // set the address to zero during enumeration
  1264. USB0_ADDR = 0;
  1265. // enable other interrupts
  1266. USB0_ERREN = 0xFF;
  1267. USB0_INTEN = USB_INTEN_TOKDNEEN |
  1268. USB_INTEN_SOFTOKEN |
  1269. USB_INTEN_STALLEN |
  1270. USB_INTEN_ERROREN |
  1271. USB_INTEN_USBRSTEN |
  1272. USB_INTEN_RESUMEEN |
  1273. USB_INTEN_SLEEPEN;
  1274. // is this necessary?
  1275. USB0_CTL = USB_CTL_USBENSOFEN;
  1276. return;
  1277. }
  1278. if ( (status & USB_ISTAT_STALL /* 80 */ ) )
  1279. {
  1280. //serial_print("stall:\n");
  1281. USB0_ENDPT0 = USB_ENDPT_EPRXEN | USB_ENDPT_EPTXEN | USB_ENDPT_EPHSHK;
  1282. USB0_ISTAT = USB_ISTAT_STALL;
  1283. }
  1284. if ( (status & USB_ISTAT_ERROR /* 02 */ ) )
  1285. {
  1286. uint8_t err = USB0_ERRSTAT;
  1287. USB0_ERRSTAT = err;
  1288. //serial_print("err:");
  1289. //serial_phex(err);
  1290. //serial_print("\n");
  1291. USB0_ISTAT = USB_ISTAT_ERROR;
  1292. }
  1293. // USB Host signalling device to enter 'sleep' state
  1294. // The USB Module triggers this interrupt when it detects the bus has been idle for 3 ms
  1295. if ( (status & USB_ISTAT_SLEEP /* 10 */ ) )
  1296. {
  1297. #if enableUSBSuspend_define == 1
  1298. // Can cause issues with the virtual serial port
  1299. #if enableVirtualSerialPort_define != 1
  1300. info_print("Host has requested USB sleep/suspend state");
  1301. #endif
  1302. Output_update_usb_current( 100 ); // Set to 100 mA
  1303. usb_dev_sleep = 1;
  1304. #else
  1305. info_print("USB Suspend Detected - Firmware USB Suspend Disabled");
  1306. #endif
  1307. USB0_ISTAT |= USB_ISTAT_SLEEP;
  1308. }
  1309. // On USB Resume, unset the usb_dev_sleep so we don't keep sending resume signals
  1310. if ( (status & USB_ISTAT_RESUME /* 20 */ ) )
  1311. {
  1312. // Can cause issues with the virtual serial port
  1313. #if enableVirtualSerialPort_define != 1
  1314. info_print("Host has woken-up/resumed from sleep/suspend state");
  1315. #endif
  1316. Output_update_usb_current( *usb_bMaxPower * 2 );
  1317. usb_dev_sleep = 0;
  1318. USB0_ISTAT |= USB_ISTAT_RESUME;
  1319. }
  1320. }
  1321. uint8_t usb_init()
  1322. {
  1323. #ifdef UART_DEBUG
  1324. print("USB INIT"NL);
  1325. #endif
  1326. USBInit_TimeStart = systick_millis_count;
  1327. USBInit_Ticks = 0;
  1328. // XXX Set wTotalLength here instead of using defines
  1329. // Simplifies defines considerably
  1330. usb_set_config_descriptor_size();
  1331. #if defined(_mk20dx128_) || defined(_mk20dx128vlf5_) || defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
  1332. // Write the unique id to the USB Descriptor memory location
  1333. // It's split up into 4 32 bit registers
  1334. // 1) Read out register
  1335. // 2) Convert to UTF-16-LE
  1336. // 3) Write to USB Descriptor Memory (space is pre-allocated)
  1337. extern struct usb_string_descriptor_struct usb_string_serial_number_default;
  1338. hex32ToStr16( SIM_UIDH, &(usb_string_serial_number_default.wString[0]), 8 );
  1339. hex32ToStr16( SIM_UIDMH, &(usb_string_serial_number_default.wString[8]), 8 );
  1340. hex32ToStr16( SIM_UIDML, &(usb_string_serial_number_default.wString[16]), 8 );
  1341. hex32ToStr16( SIM_UIDL, &(usb_string_serial_number_default.wString[24]), 8 );
  1342. #endif
  1343. // Clear out endpoints table
  1344. for ( int i = 0; i <= NUM_ENDPOINTS * 4; i++ )
  1345. {
  1346. table[i].desc = 0;
  1347. table[i].addr = 0;
  1348. }
  1349. // this basically follows the flowchart in the Kinetis
  1350. // Quick Reference User Guide, Rev. 1, 03/2012, page 141
  1351. // assume 48 MHz clock already running
  1352. // SIM - enable clock
  1353. SIM_SCGC4 |= SIM_SCGC4_USBOTG;
  1354. // reset USB module
  1355. USB0_USBTRC0 = USB_USBTRC_USBRESET;
  1356. while ( (USB0_USBTRC0 & USB_USBTRC_USBRESET) != 0 ); // wait for reset to end
  1357. // set desc table base addr
  1358. USB0_BDTPAGE1 = ((uint32_t)table) >> 8;
  1359. USB0_BDTPAGE2 = ((uint32_t)table) >> 16;
  1360. USB0_BDTPAGE3 = ((uint32_t)table) >> 24;
  1361. // clear all ISR flags
  1362. USB0_ISTAT = 0xFF;
  1363. USB0_ERRSTAT = 0xFF;
  1364. USB0_OTGISTAT = 0xFF;
  1365. USB0_USBTRC0 |= 0x40; // undocumented bit
  1366. // enable USB
  1367. USB0_CTL = USB_CTL_USBENSOFEN;
  1368. USB0_USBCTRL = 0;
  1369. // enable reset interrupt
  1370. USB0_INTEN = USB_INTEN_USBRSTEN;
  1371. // enable interrupt in NVIC...
  1372. NVIC_SET_PRIORITY( IRQ_USBOTG, 112 );
  1373. NVIC_ENABLE_IRQ( IRQ_USBOTG );
  1374. // enable d+ pullup
  1375. USB0_CONTROL = USB_CONTROL_DPPULLUPNONOTG;
  1376. // Do not check for power negotiation delay until Get Configuration Descriptor
  1377. power_neg_delay = 0;
  1378. // During initialization host isn't sleeping
  1379. usb_dev_sleep = 0;
  1380. return 1;
  1381. }
  1382. // return 0 if the USB is not configured, or the configuration
  1383. // number selected by the HOST
  1384. uint8_t usb_configured()
  1385. {
  1386. return usb_configuration;
  1387. }