usb.c 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214
  1. #include <string.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. #define CONFIG_USB_STORAGE
  6. #include "usb_os_adapter.h"
  7. #include "trace.h"
  8. #include <linux/usb/ch9.h>
  9. #include "usb.h"
  10. #include "dwc2_compat.h"
  11. #include <linux/errno.h>
  12. #include "ark_dwc2.h"
  13. #include "timer.h"
  14. #include "ff_usbdisk.h"
  15. #include "usb_uvc.h"
  16. #include "board.h"
  17. #include "task.h"
  18. #include "queue.h"
  19. #include "timers.h"
  20. #include "semphr.h"
  21. #include "chip.h"
  22. #define USB_WAIT_DEV_TIMEOUT 30000
  23. #define USB_MOUNT_PATH "/usb"
  24. extern int hub_status_data(char buf[8]);
  25. void usb_stor_disconnect();
  26. static char gconnect_flag = 0;
  27. static FF_Disk_t *usb_disk = NULL;
  28. static int usb_mode; //0:usb_host 1:usb_device
  29. static char connect_status = 0;
  30. static TaskHandle_t scan_usb_dev_task;
  31. static TimerHandle_t usbPortScanTimer;
  32. static QueueHandle_t wait_new_dev;
  33. static QueueHandle_t usb_stor_dev_pluged;
  34. static SemaphoreHandle_t dev_lock;
  35. #define mainTIMER_SCAN_FREQUENCY_MS pdMS_TO_TICKS( 1000UL )
  36. #ifndef SendUartString
  37. #define SendUartString printf
  38. #endif
  39. #define USB_BUFSIZ 512
  40. #define HUB_SHORT_RESET_TIME 20
  41. #define HUB_LONG_RESET_TIME 200
  42. #define PORT_OVERCURRENT_MAX_SCAN_COUNT 3
  43. #ifndef CONFIG_USB_MAX_CONTROLLER_COUNT
  44. #define CONFIG_USB_MAX_CONTROLLER_COUNT 1
  45. #endif
  46. static int asynch_allowed;
  47. char usb_started; /* flag for the started/stopped USB status */
  48. static struct usb_device usb_dev[USB_MAX_DEVICE];
  49. static int dev_index;
  50. struct usb_device_scan {
  51. ListItem_t list;
  52. struct usb_device *dev; /* USB hub device to scan */
  53. struct usb_hub_device *hub; /* USB hub struct */
  54. int port; /* USB port to scan */
  55. };
  56. static List_t usb_scan_list;
  57. static struct usb_hub_device hub_dev[USB_MAX_HUB];
  58. static int usb_hub_index;
  59. void usb_hub_reset(void)
  60. {
  61. usb_hub_index = 0;
  62. /* Zero out global hub_dev in case its re-used again */
  63. memset(hub_dev, 0, sizeof(hub_dev));
  64. }
  65. static struct usb_hub_device *usb_hub_allocate(void)
  66. {
  67. if (usb_hub_index < USB_MAX_HUB)
  68. return &hub_dev[usb_hub_index++];
  69. return NULL;
  70. }
  71. /*-------------------------------------------------------------------
  72. * Max Packet stuff
  73. */
  74. /*
  75. * returns the max packet size, depending on the pipe direction and
  76. * the configurations values
  77. */
  78. int usb_maxpacket(struct usb_device *dev, unsigned long pipe)
  79. {
  80. /* direction is out -> use emaxpacket out */
  81. if ((pipe & USB_DIR_IN) == 0)
  82. return dev->epmaxpacketout[((pipe>>15) & 0xf)];
  83. else
  84. return dev->epmaxpacketin[((pipe>>15) & 0xf)];
  85. }
  86. /*
  87. * The routine usb_set_maxpacket_ep() is extracted from the loop of routine
  88. * usb_set_maxpacket(), because the optimizer of GCC 4.x chokes on this routine
  89. * when it is inlined in 1 single routine. What happens is that the register r3
  90. * is used as loop-count 'i', but gets overwritten later on.
  91. * This is clearly a compiler bug, but it is easier to workaround it here than
  92. * to update the compiler (Occurs with at least several GCC 4.{1,2},x
  93. * CodeSourcery compilers like e.g. 2007q3, 2008q1, 2008q3 lite editions on ARM)
  94. *
  95. * NOTE: Similar behaviour was observed with GCC4.6 on ARMv5.
  96. */
  97. static void usb_set_maxpacket_ep(struct usb_device *dev, int if_idx, int alt_idx, int ep_idx)
  98. {
  99. int b;
  100. struct usb_endpoint_descriptor *ep;
  101. u16 ep_wMaxPacketSize;
  102. unsigned char *tmp;
  103. struct usb_interface *if_desc = &dev->config.if_desc[if_idx];
  104. if (if_desc->num_altsetting <= 1)
  105. ep = &dev->config.if_desc[if_idx].ep_desc[ep_idx];
  106. else if (if_desc->num_altsetting > 1) {
  107. ep = &if_desc->alt_intf[alt_idx].ep_desc[ep_idx];
  108. }
  109. b = ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
  110. tmp = (unsigned char*)&ep->wMaxPacketSize;
  111. ep_wMaxPacketSize = (tmp[1] << 8) | tmp[0];//get_unaligned(&ep->wMaxPacketSize);
  112. USB_UNUSED(ep_wMaxPacketSize);
  113. if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
  114. USB_ENDPOINT_XFER_CONTROL) {
  115. /* Control => bidirectional */
  116. dev->epmaxpacketout[b] = ep_wMaxPacketSize;
  117. dev->epmaxpacketin[b] = ep_wMaxPacketSize;
  118. /* debug("##Control EP epmaxpacketout/in[%d] = %d\n",
  119. b, dev->epmaxpacketin[b]); */
  120. } else {
  121. if ((ep->bEndpointAddress & 0x80) == 0) {
  122. /* OUT Endpoint */
  123. if (ep_wMaxPacketSize > dev->epmaxpacketout[b]) {
  124. dev->epmaxpacketout[b] = ep_wMaxPacketSize;
  125. /* debug("##EP epmaxpacketout[%d] = %d\n",
  126. b, dev->epmaxpacketout[b]); */
  127. }
  128. } else {
  129. /* IN Endpoint */
  130. if (ep_wMaxPacketSize > dev->epmaxpacketin[b]) {
  131. dev->epmaxpacketin[b] = ep_wMaxPacketSize;
  132. /* debug("##EP epmaxpacketin[%d] = %d\n",
  133. b, dev->epmaxpacketin[b]); */
  134. }
  135. } /* if out */
  136. } /* if control */
  137. }
  138. void usb_set_maxpacket_ep_ex(struct usb_device *dev, int if_idx, int alt_idx, int ep_idx)
  139. {
  140. usb_set_maxpacket_ep(dev, if_idx, alt_idx, ep_idx);
  141. }
  142. /*
  143. * set the max packed value of all endpoints in the given configuration
  144. */
  145. static int usb_set_maxpacket(struct usb_device *dev)
  146. {
  147. int i, ii;
  148. for (i = 0; i < dev->config.desc.bNumInterfaces; i++) {
  149. //struct usb_interface *if_desc = &dev->config.if_desc[i];
  150. struct usb_alt_interface *alt_if = &dev->config.if_desc[i].alt_intf[0];
  151. //for (ii = 0; ii < dev->config.if_desc[i].desc.bNumEndpoints; ii++)
  152. // usb_set_maxpacket_ep(dev, i, ii);
  153. for (ii = 0; ii < alt_if->desc.bNumEndpoints; ii++) {
  154. usb_set_maxpacket_ep(dev, i, 0, ii);
  155. }
  156. }
  157. return 0;
  158. }
  159. /*-------------------------------------------------------------------
  160. * Message wrappers.
  161. *
  162. */
  163. /*
  164. * submits an Interrupt Message
  165. */
  166. int usb_submit_int_msg(struct usb_device *dev, unsigned long pipe,
  167. void *buffer, int transfer_len, int interval)
  168. {
  169. if (0 == gconnect_flag && dev->parent != NULL) {
  170. return -1;
  171. }
  172. return submit_int_msg(dev, pipe, buffer, transfer_len, interval);
  173. }
  174. /*
  175. * submits a control message and waits for comletion (at least timeout * 1ms)
  176. * If timeout is 0, we don't wait for completion (used as example to set and
  177. * clear keyboards LEDs). For data transfers, (storage transfers) we don't
  178. * allow control messages with 0 timeout, by previousely resetting the flag
  179. * asynch_allowed (usb_disable_asynch(1)).
  180. * returns the transferred length if OK or -1 if error. The transferred length
  181. * and the current status are stored in the dev->act_len and dev->status.
  182. */
  183. int usb_control_msg(struct usb_device *dev, unsigned int pipe,
  184. unsigned char request, unsigned char requesttype,
  185. unsigned short value, unsigned short index,
  186. void *data, unsigned short size, int timeout)
  187. {
  188. ALLOC_CACHE_ALIGN_BUFFER(struct devrequest, setup_packet, 1);
  189. int err;
  190. if ((timeout == 0) && (!asynch_allowed)) {
  191. /* request for a asynch control pipe is not allowed */
  192. return -EINVAL;
  193. }
  194. /* set setup command */
  195. setup_packet->requesttype = requesttype;
  196. setup_packet->request = request;
  197. setup_packet->value = value;
  198. setup_packet->index = index;
  199. setup_packet->length = size;
  200. /* debug("usb_control_msg: request: 0x%X, requesttype: 0x%X, " \
  201. "value 0x%X index 0x%X length 0x%X\n",
  202. request, requesttype, value, index, size); */
  203. xSemaphoreTake(dev_lock, portMAX_DELAY);
  204. if (0 == gconnect_flag && dev->parent != NULL) {
  205. xSemaphoreGive(dev_lock);
  206. return -1;
  207. }
  208. dev->status = USB_ST_NOT_PROC; /*not yet processed */
  209. err = submit_control_msg(dev, pipe, data, size, setup_packet, timeout);
  210. if (err < 0) {
  211. err = -1;
  212. }
  213. if (dev->status) {
  214. err = -1;
  215. }
  216. xSemaphoreGive(dev_lock);
  217. return err;
  218. }
  219. /*-------------------------------------------------------------------
  220. * submits bulk message, and waits for completion. returns 0 if Ok or
  221. * negative if Error.
  222. * synchronous behavior
  223. */
  224. #define BULK_BUF_LEN 4096
  225. int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,
  226. void *data, int len, int *actual_length, int timeout)
  227. {
  228. #if 1
  229. int err;
  230. ALLOC_CACHE_ALIGN_BUFFER(char, dma_buf, BULK_BUF_LEN);
  231. int transfer_len = 0, total_len = 0, act_len = 0;
  232. unsigned int addr = 0;
  233. int is_in = usb_pipein(pipe);
  234. if (len < 0)
  235. return -EINVAL;
  236. if (((int)data) % ARCH_DMA_MINALIGN == 0) {
  237. err = submit_bulk_msg(dev, pipe, data, len, &act_len, timeout);
  238. if (dev->status || (err < 0))
  239. return -1;
  240. *actual_length = act_len;
  241. return 0;
  242. }
  243. while(len > 0) {
  244. dev->status = USB_ST_NOT_PROC; /*not yet processed */
  245. if (len < BULK_BUF_LEN)
  246. transfer_len = len;
  247. else
  248. transfer_len = BULK_BUF_LEN;
  249. if (is_in == 0) {
  250. memcpy(dma_buf, data, transfer_len);
  251. }
  252. if (0 == gconnect_flag && dev->parent != NULL) {
  253. dev->status = -1;
  254. break;
  255. }
  256. err = submit_bulk_msg(dev, pipe, dma_buf, transfer_len, &act_len, timeout);
  257. if (err < 0)
  258. break;
  259. if (is_in) {
  260. memcpy(data, dma_buf, transfer_len);
  261. }
  262. total_len += act_len;
  263. addr = (unsigned int)data + transfer_len;
  264. data = (void *)addr;
  265. len -= transfer_len;
  266. }
  267. if (len == 0)
  268. *actual_length = total_len;
  269. else
  270. *actual_length = 0;
  271. if (dev->status)
  272. return -1;
  273. return 0;
  274. #else
  275. int err;
  276. if (len < 0)
  277. return -EINVAL;
  278. dev->status = USB_ST_NOT_PROC; /*not yet processed */
  279. err = submit_bulk_msg(dev, pipe, data, len, timeout);
  280. if (err < 0)
  281. return err;
  282. *actual_length = dev->act_len;
  283. if (dev->status)
  284. return -1;
  285. return 0;
  286. #endif
  287. }
  288. int usb_iso_msg(struct usb_device *dev, unsigned int pipe,
  289. void *data, int len, int *actual_length, int timeout)
  290. {
  291. return submit_iso_msg(dev, pipe, data, len, actual_length, timeout);
  292. }
  293. /*******************************************************************************
  294. * Parse the config, located in buffer, and fills the dev->config structure.
  295. * Note that all little/big endian swapping are done automatically.
  296. * (wTotalLength has already been swapped and sanitized when it was read.)
  297. */
  298. static int usb_parse_config(struct usb_device *dev,
  299. unsigned char *buffer, int cfgno)
  300. {
  301. struct usb_descriptor_header *head;
  302. int index, ifno, epno, curr_if_num, cur_alt_if_num, alt_if_ep_idx;
  303. u16 ep_wMaxPacketSize;
  304. unsigned char *tmp;
  305. struct usb_interface *if_desc = NULL;
  306. struct usb_alt_interface *alt_if = NULL;
  307. ifno = -1;
  308. epno = -1;
  309. curr_if_num = -1;
  310. dev->configno = cfgno;
  311. head = (struct usb_descriptor_header *) &buffer[0];
  312. if (head->bDescriptorType != USB_DT_CONFIG) {
  313. /* printf(" ERROR: NOT USB_CONFIG_DESC %x\n",
  314. head->bDescriptorType); */
  315. return -EINVAL;
  316. }
  317. if (head->bLength != USB_DT_CONFIG_SIZE) {
  318. //printf("ERROR: Invalid USB CFG length (%d)\n", head->bLength);
  319. return -EINVAL;
  320. }
  321. memcpy(&dev->config, head, USB_DT_CONFIG_SIZE);
  322. dev->config.no_of_if = 0;
  323. index = dev->config.desc.bLength;
  324. /* Ok the first entry must be a configuration entry,
  325. * now process the others */
  326. head = (struct usb_descriptor_header *) &buffer[index];
  327. while (index + 1 < dev->config.desc.wTotalLength && head->bLength) {
  328. switch (head->bDescriptorType) {
  329. case USB_DT_INTERFACE:
  330. if (head->bLength != USB_DT_INTERFACE_SIZE) {
  331. /* printf("ERROR: Invalid USB IF length (%d)\n",
  332. head->bLength); */
  333. break;
  334. }
  335. if (index + USB_DT_INTERFACE_SIZE >
  336. dev->config.desc.wTotalLength) {
  337. //puts("USB IF descriptor overflowed buffer!\n");
  338. break;
  339. }
  340. if (((struct usb_interface_descriptor *) \
  341. head)->bInterfaceNumber != curr_if_num) {
  342. /* this is a new interface, copy new desc */
  343. ifno = dev->config.no_of_if;
  344. if (ifno >= USB_MAXINTERFACES) {
  345. //puts("Too many USB interfaces!\n");
  346. /* try to go on with what we have */
  347. return -EINVAL;
  348. }
  349. if_desc = &dev->config.if_desc[ifno];
  350. dev->config.no_of_if++;
  351. memcpy(if_desc, head,
  352. USB_DT_INTERFACE_SIZE);
  353. if_desc->no_of_ep = 0;
  354. if_desc->num_altsetting = 1;
  355. alt_if = &if_desc->alt_intf[0];
  356. memcpy(alt_if, head, USB_DT_INTERFACE_SIZE);
  357. curr_if_num =
  358. if_desc->desc.bInterfaceNumber;
  359. cur_alt_if_num = 0;
  360. } else {
  361. /* found alternate setting for the interface */
  362. if (ifno >= 0) {
  363. if_desc = &dev->config.if_desc[ifno];
  364. alt_if = &if_desc->alt_intf[if_desc->num_altsetting];
  365. memcpy(alt_if, head, USB_DT_INTERFACE_SIZE);
  366. cur_alt_if_num = if_desc->num_altsetting;
  367. alt_if_ep_idx = 0;
  368. if_desc->num_altsetting++;
  369. }
  370. }
  371. break;
  372. case USB_DT_ENDPOINT:
  373. if (head->bLength != USB_DT_ENDPOINT_SIZE &&
  374. head->bLength != USB_DT_ENDPOINT_AUDIO_SIZE) {
  375. /* printf("ERROR: Invalid USB EP length (%d)\n",
  376. head->bLength); */
  377. break;
  378. }
  379. if (index + head->bLength >
  380. dev->config.desc.wTotalLength) {
  381. //puts("USB EP descriptor overflowed buffer!\n");
  382. break;
  383. }
  384. if (ifno < 0) {
  385. //puts("Endpoint descriptor out of order!\n");
  386. break;
  387. }
  388. epno = dev->config.if_desc[ifno].no_of_ep;
  389. if_desc = &dev->config.if_desc[ifno];
  390. if (epno >= USB_MAXENDPOINTS) {
  391. /* printf("Interface %d has too many endpoints!\n",
  392. if_desc->desc.bInterfaceNumber); */
  393. return -EINVAL;
  394. }
  395. /* found an endpoint */
  396. if_desc->no_of_ep++;
  397. memcpy(&if_desc->ep_desc[epno], head,
  398. USB_DT_ENDPOINT_SIZE);
  399. /* ep_wMaxPacketSize = get_unaligned(&dev->config.\
  400. if_desc[ifno].\
  401. ep_desc[epno].\
  402. wMaxPacketSize); */
  403. tmp = (unsigned char*)&dev->config.if_desc[ifno].ep_desc[epno].wMaxPacketSize;
  404. ep_wMaxPacketSize = (tmp[1] << 8) | tmp[0];
  405. USB_UNUSED(ep_wMaxPacketSize);
  406. if (if_desc->num_altsetting > 1) {
  407. memcpy(&if_desc->alt_intf[cur_alt_if_num].ep_desc[alt_if_ep_idx++], head,
  408. USB_DT_ENDPOINT_SIZE);
  409. if_desc->alt_intf[cur_alt_if_num].ep_desc[alt_if_ep_idx++].wMaxPacketSize = ep_wMaxPacketSize;
  410. }
  411. /* put_unaligned(le16_to_cpu(ep_wMaxPacketSize),
  412. &dev->config.\
  413. if_desc[ifno].\
  414. ep_desc[epno].\
  415. wMaxPacketSize); */
  416. //debug("if %d, ep %d\n", ifno, epno);
  417. break;
  418. case USB_DT_SS_ENDPOINT_COMP:
  419. if (head->bLength != USB_DT_SS_EP_COMP_SIZE) {
  420. /* printf("ERROR: Invalid USB EPC length (%d)\n",
  421. head->bLength); */
  422. break;
  423. }
  424. if (index + USB_DT_SS_EP_COMP_SIZE >
  425. dev->config.desc.wTotalLength) {
  426. //puts("USB EPC descriptor overflowed buffer!\n");
  427. break;
  428. }
  429. if (ifno < 0 || epno < 0) {
  430. //puts("EPC descriptor out of order!\n");
  431. break;
  432. }
  433. if_desc = &dev->config.if_desc[ifno];
  434. memcpy(&if_desc->ss_ep_comp_desc[epno], head,
  435. USB_DT_SS_EP_COMP_SIZE);
  436. break;
  437. default:
  438. if (head->bLength == 0)
  439. return -EINVAL;
  440. /* debug("unknown Description Type : %x\n",
  441. head->bDescriptorType); */
  442. #ifdef DEBUG
  443. {
  444. unsigned char *ch = (unsigned char *)head;
  445. int i;
  446. for (i = 0; i < head->bLength; i++)
  447. debug("%02X ", *ch++);
  448. debug("\n\n\n");
  449. }
  450. #endif
  451. break;
  452. }
  453. index += head->bLength;
  454. head = (struct usb_descriptor_header *)&buffer[index];
  455. }
  456. return 0;
  457. }
  458. /********************************************************************
  459. * get string index in buffer
  460. */
  461. static int usb_get_string(struct usb_device *dev, unsigned short langid,
  462. unsigned char index, void *buf, int size)
  463. {
  464. int i;
  465. int result;
  466. for (i = 0; i < 3; ++i) {
  467. /* some devices are flaky */
  468. result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  469. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  470. (USB_DT_STRING << 8) + index, langid, buf, size,
  471. USB_CNTL_TIMEOUT);
  472. if (result > 0)
  473. break;
  474. }
  475. return result;
  476. }
  477. static void usb_try_string_workarounds(unsigned char *buf, int *length)
  478. {
  479. int newlength, oldlength = *length;
  480. for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
  481. if (!isprint(buf[newlength]) || buf[newlength + 1])
  482. break;
  483. if (newlength > 2) {
  484. buf[0] = newlength;
  485. *length = newlength;
  486. }
  487. }
  488. static int usb_string_sub(struct usb_device *dev, unsigned int langid,
  489. unsigned int index, unsigned char *buf)
  490. {
  491. int rc;
  492. /* Try to read the string descriptor by asking for the maximum
  493. * possible number of bytes */
  494. rc = usb_get_string(dev, langid, index, buf, 255);
  495. /* If that failed try to read the descriptor length, then
  496. * ask for just that many bytes */
  497. if (rc < 2) {
  498. rc = usb_get_string(dev, langid, index, buf, 2);
  499. if (rc == 2)
  500. rc = usb_get_string(dev, langid, index, buf, buf[0]);
  501. }
  502. if (rc >= 2) {
  503. if (!buf[0] && !buf[1])
  504. usb_try_string_workarounds(buf, &rc);
  505. /* There might be extra junk at the end of the descriptor */
  506. if (buf[0] < rc)
  507. rc = buf[0];
  508. rc = rc - (rc & 1); /* force a multiple of two */
  509. }
  510. if (rc < 2)
  511. rc = -EINVAL;
  512. return rc;
  513. }
  514. /********************************************************************
  515. * usb_string:
  516. * Get string index and translate it to ascii.
  517. * returns string length (> 0) or error (< 0)
  518. */
  519. int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
  520. {
  521. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, mybuf, USB_BUFSIZ);
  522. unsigned char *tbuf;
  523. int err;
  524. unsigned int u, idx;
  525. if (size <= 0 || !buf || !index)
  526. return -EINVAL;
  527. buf[0] = 0;
  528. tbuf = &mybuf[0];
  529. /* get langid for strings if it's not yet known */
  530. if (!dev->have_langid) {
  531. err = usb_string_sub(dev, 0, 0, tbuf);
  532. if (err < 0) {
  533. /* debug("error getting string descriptor 0 " \
  534. "(error=%lx)\n", dev->status); */
  535. return -EIO;
  536. } else if (tbuf[0] < 4) {
  537. //debug("string descriptor 0 too short\n");
  538. return -EIO;
  539. } else {
  540. dev->have_langid = -1;
  541. dev->string_langid = tbuf[2] | (tbuf[3] << 8);
  542. /* always use the first langid listed */
  543. /* debug("USB device number %d default " \
  544. "language ID 0x%x\n",
  545. dev->devnum, dev->string_langid); */
  546. }
  547. }
  548. err = usb_string_sub(dev, dev->string_langid, index, tbuf);
  549. if (err < 0)
  550. return err;
  551. size--; /* leave room for trailing NULL char in output buffer */
  552. for (idx = 0, u = 2; u < err; u += 2) {
  553. if (idx >= size)
  554. break;
  555. if (tbuf[u+1]) /* high byte */
  556. buf[idx++] = '?'; /* non-ASCII character */
  557. else
  558. buf[idx++] = tbuf[u];
  559. }
  560. buf[idx] = 0;
  561. err = idx;
  562. return err;
  563. }
  564. struct usb_device *usb_get_dev_index(int index)
  565. {
  566. if (usb_dev[index].devnum == -1)
  567. return NULL;
  568. else
  569. return &usb_dev[index];
  570. }
  571. void usb_free_device(void *controller)
  572. {
  573. dev_index--;
  574. //debug("Freeing device node: %d\n", dev_index);
  575. memset(&usb_dev[dev_index], 0, sizeof(struct usb_device));
  576. usb_dev[dev_index].devnum = -1;
  577. }
  578. int usb_alloc_device(struct usb_device *udev)
  579. {
  580. return 0;
  581. }
  582. /***********************************************************************
  583. * Clears an endpoint
  584. * endp: endpoint number in bits 0-3;
  585. * direction flag in bit 7 (1 = IN, 0 = OUT)
  586. */
  587. int usb_clear_halt(struct usb_device *dev, int pipe)
  588. {
  589. int result;
  590. int endp = usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
  591. result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  592. USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0,
  593. endp, NULL, 0, USB_CNTL_TIMEOUT * 3);
  594. /* don't clear if failed */
  595. if (result < 0)
  596. return result;
  597. /*
  598. * NOTE: we do not get status and verify reset was successful
  599. * as some devices are reported to lock up upon this check..
  600. */
  601. usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
  602. /* toggle is reset on clear */
  603. usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
  604. return 0;
  605. }
  606. /**********************************************************************
  607. * get_descriptor type
  608. */
  609. static int usb_get_descriptor(struct usb_device *dev, unsigned char type,
  610. unsigned char index, void *buf, int size)
  611. {
  612. return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  613. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
  614. (type << 8) + index, 0, buf, size,
  615. USB_CNTL_TIMEOUT);
  616. }
  617. /**********************************************************************
  618. * gets len of configuration cfgno
  619. */
  620. int usb_get_configuration_len(struct usb_device *dev, int cfgno)
  621. {
  622. int result;
  623. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, 9);
  624. struct usb_config_descriptor *config;
  625. config = (struct usb_config_descriptor *)&buffer[0];
  626. result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 9);
  627. if (result < 9) {
  628. if (result < 0)
  629. ;/* printf("unable to get descriptor, error %lX\n",
  630. dev->status); */
  631. else
  632. ;/* printf("config descriptor too short " \
  633. "(expected %i, got %i)\n", 9, result); */
  634. return -EIO;
  635. }
  636. return config->wTotalLength;
  637. }
  638. /**********************************************************************
  639. * gets configuration cfgno and store it in the buffer
  640. */
  641. int usb_get_configuration_no(struct usb_device *dev, int cfgno,
  642. unsigned char *buffer, int length)
  643. {
  644. int result;
  645. struct usb_config_descriptor *config;
  646. config = (struct usb_config_descriptor *)&buffer[0];
  647. result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, length);
  648. /* debug("get_conf_no %d Result %d, wLength %d\n", cfgno, result,
  649. le16_to_cpu(config->wTotalLength)); */
  650. config->wTotalLength = result; /* validated, with CPU byte order */
  651. return result;
  652. }
  653. static int get_descriptor_len(struct usb_device *dev, int len, int expect_len)
  654. {
  655. struct usb_device_descriptor *desc;
  656. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, tmpbuf, USB_BUFSIZ);
  657. int err;
  658. desc = (struct usb_device_descriptor *)tmpbuf;
  659. err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, len);
  660. if (err < expect_len) {
  661. if (err < 0) {
  662. /* printf("unable to get device descriptor (error=%d)\n",
  663. err); */
  664. return err;
  665. } else {
  666. /* printf("USB device descriptor short read (expected %i, got %i)\n",
  667. expect_len, err); */
  668. return -EIO;
  669. }
  670. }
  671. memcpy(&dev->descriptor, tmpbuf, sizeof(dev->descriptor));
  672. return 0;
  673. }
  674. /********************************************************************
  675. * set address of a device to the value in dev->devnum.
  676. * This can only be done by addressing the device via the default address (0)
  677. */
  678. static int usb_set_address(struct usb_device *dev)
  679. {
  680. //debug("set address %d\n", dev->devnum);
  681. return usb_control_msg(dev, usb_snddefctrl(dev), USB_REQ_SET_ADDRESS,
  682. 0, (dev->devnum), 0, NULL, 0, USB_CNTL_TIMEOUT);
  683. }
  684. /********************************************************************
  685. * set interface number to interface
  686. */
  687. int usb_set_interface(struct usb_device *dev, int interface, int alternate)
  688. {
  689. struct usb_interface *if_face = NULL;
  690. int ret, i;
  691. for (i = 0; i < dev->config.desc.bNumInterfaces; i++) {
  692. if (dev->config.if_desc[i].desc.bInterfaceNumber == interface) {
  693. if_face = &dev->config.if_desc[i];
  694. break;
  695. }
  696. }
  697. if (!if_face) {
  698. //printf("selecting invalid interface %d", interface);
  699. return -EINVAL;
  700. }
  701. /*
  702. * We should return now for devices with only one alternate setting.
  703. * According to 9.4.10 of the Universal Serial Bus Specification
  704. * Revision 2.0 such devices can return with a STALL. This results in
  705. * some USB sticks timeouting during initialization and then being
  706. * unusable in U-Boot.
  707. */
  708. if (if_face->num_altsetting == 1)
  709. return 0;
  710. if (if_face->num_altsetting > 1) {
  711. int i;
  712. struct usb_alt_interface *alt_if = &if_face->alt_intf[alternate];
  713. for (i = 0; i < alt_if->desc.bNumEndpoints; i++) {
  714. usb_set_maxpacket_ep(dev, interface, alternate, i);
  715. }
  716. }
  717. ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  718. USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
  719. alternate, interface, NULL, 0,
  720. USB_CNTL_TIMEOUT * 5);
  721. if (ret < 0)
  722. return ret;
  723. return 0;
  724. }
  725. /********************************************************************
  726. * set configuration number to configuration
  727. */
  728. static int usb_set_configuration(struct usb_device *dev, int configuration)
  729. {
  730. int res;
  731. //debug("set configuration %d\n", configuration);
  732. /* set setup command */
  733. res = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  734. USB_REQ_SET_CONFIGURATION, 0,
  735. configuration, 0,
  736. NULL, 0, USB_CNTL_TIMEOUT);
  737. if (res == 0) {
  738. dev->toggle[0] = 0;
  739. dev->toggle[1] = 0;
  740. return 0;
  741. } else
  742. return -EIO;
  743. }
  744. static int usb_setup_descriptor(struct usb_device *dev, bool do_read)
  745. {
  746. /*
  747. * This is a Windows scheme of initialization sequence, with double
  748. * reset of the device (Linux uses the same sequence)
  749. * Some equipment is said to work only with such init sequence; this
  750. * patch is based on the work by Alan Stern:
  751. * http://sourceforge.net/mailarchive/forum.php?
  752. * thread_id=5729457&forum_id=5398
  753. */
  754. /*
  755. * send 64-byte GET-DEVICE-DESCRIPTOR request. Since the descriptor is
  756. * only 18 bytes long, this will terminate with a short packet. But if
  757. * the maxpacket size is 8 or 16 the device may be waiting to transmit
  758. * some more, or keeps on retransmitting the 8 byte header.
  759. */
  760. if (dev->speed == USB_SPEED_LOW) {
  761. dev->descriptor.bMaxPacketSize0 = 8;
  762. dev->maxpacketsize = PACKET_SIZE_8;
  763. } else {
  764. dev->descriptor.bMaxPacketSize0 = 64;
  765. dev->maxpacketsize = PACKET_SIZE_64;
  766. }
  767. dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
  768. dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
  769. if (do_read && dev->speed == USB_SPEED_FULL) {
  770. int err;
  771. /*
  772. * Validate we've received only at least 8 bytes, not that
  773. * we've received the entire descriptor. The reasoning is:
  774. * - The code only uses fields in the first 8 bytes, so
  775. * that's all we need to have fetched at this stage.
  776. * - The smallest maxpacket size is 8 bytes. Before we know
  777. * the actual maxpacket the device uses, the USB controller
  778. * may only accept a single packet. Consequently we are only
  779. * guaranteed to receive 1 packet (at least 8 bytes) even in
  780. * a non-error case.
  781. *
  782. * At least the DWC2 controller needs to be programmed with
  783. * the number of packets in addition to the number of bytes.
  784. * A request for 64 bytes of data with the maxpacket guessed
  785. * as 64 (above) yields a request for 1 packet.
  786. */
  787. err = get_descriptor_len(dev, 64, 8);
  788. if (err)
  789. return err;
  790. }
  791. dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
  792. dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
  793. switch (dev->descriptor.bMaxPacketSize0) {
  794. case 8:
  795. dev->maxpacketsize = PACKET_SIZE_8;
  796. break;
  797. case 16:
  798. dev->maxpacketsize = PACKET_SIZE_16;
  799. break;
  800. case 32:
  801. dev->maxpacketsize = PACKET_SIZE_32;
  802. break;
  803. case 64:
  804. dev->maxpacketsize = PACKET_SIZE_64;
  805. break;
  806. default:
  807. //printf("%s: invalid max packet size\n", __func__);
  808. return -EIO;
  809. }
  810. return 0;
  811. }
  812. int usb_alloc_new_device(void *controller, struct usb_device **devp)
  813. {
  814. int i;
  815. if (dev_index == USB_MAX_DEVICE) {
  816. SendUartString("ERROR, too many USB Devices\n");
  817. return -ENOSPC;
  818. }
  819. /* default Address is 0, real addresses start with 1 */
  820. usb_dev[dev_index].devnum = dev_index + 1;
  821. usb_dev[dev_index].maxchild = 0;
  822. for (i = 0; i < USB_MAXCHILDREN; i++)
  823. usb_dev[dev_index].children[i] = NULL;
  824. usb_dev[dev_index].parent = NULL;
  825. usb_dev[dev_index].controller = controller;
  826. dev_index++;
  827. *devp = &usb_dev[dev_index - 1];
  828. return 0;
  829. }
  830. static int usb_prepare_device(struct usb_device *dev, int addr, bool do_read,
  831. struct usb_device *parent)
  832. {
  833. int err;
  834. /*
  835. * Allocate usb 3.0 device context.
  836. * USB 3.0 (xHCI) protocol tries to allocate device slot
  837. * and related data structures first. This call does that.
  838. * Refer to sec 4.3.2 in xHCI spec rev1.0
  839. */
  840. err = usb_alloc_device(dev);
  841. if (err) {
  842. //printf("Cannot allocate device context to get SLOT_ID\n");
  843. return err;
  844. }
  845. err = usb_setup_descriptor(dev, do_read);
  846. if (err)
  847. return err;
  848. /* err = usb_hub_port_reset(dev, parent);
  849. if (err)
  850. return err; */
  851. dev->devnum = addr;printf("hub_set_address:4294\r\n");
  852. err = usb_set_address(dev); /* set address */
  853. if (err < 0) {
  854. /* printf("\n USB device not accepting new address " \
  855. "(error=%lX)\n", dev->status); */
  856. return err;
  857. }printf("hub_set_address:4297\r\n");
  858. mdelay(10); /* Let the SET_ADDRESS settle */
  859. /*
  860. * If we haven't read device descriptor before, read it here
  861. * after device is assigned an address. This is only applicable
  862. * to xHCI so far.
  863. */
  864. if (!do_read) {
  865. err = usb_setup_descriptor(dev, true);
  866. if (err)
  867. return err;
  868. }
  869. return 0;
  870. }
  871. int usb_select_config(struct usb_device *dev)
  872. {
  873. unsigned char *rawtmpbuf = NULL, *tmpbuf = NULL;
  874. int err;
  875. err = get_descriptor_len(dev, USB_DT_DEVICE_SIZE, USB_DT_DEVICE_SIZE);
  876. if (err)
  877. return err;
  878. /*
  879. * Kingston DT Ultimate 32GB USB 3.0 seems to be extremely sensitive
  880. * about this first Get Descriptor request. If there are any other
  881. * requests in the first microframe, the stick crashes. Wait about
  882. * one microframe duration here (1mS for USB 1.x , 125uS for USB 2.0).
  883. */
  884. mdelay(1);
  885. /* only support for one config for now */
  886. err = usb_get_configuration_len(dev, 0);
  887. if (err >= 0) {
  888. rawtmpbuf = (unsigned char *)malloc(err + ARCH_DMA_MINALIGN - 1);
  889. if (!rawtmpbuf)
  890. err = -ENOMEM;
  891. else {
  892. tmpbuf = (unsigned char*)ALIGN((uintptr_t)rawtmpbuf, ARCH_DMA_MINALIGN);
  893. err = usb_get_configuration_no(dev, 0, tmpbuf, err);
  894. }
  895. }
  896. if (err < 0) {
  897. /* printf("usb_new_device: Cannot read configuration, " \
  898. "skipping device %04x:%04x\n",
  899. dev->descriptor.idVendor, dev->descriptor.idProduct); */
  900. if (rawtmpbuf)
  901. free(rawtmpbuf);
  902. return err;
  903. }
  904. usb_parse_config(dev, tmpbuf, 0);
  905. free(rawtmpbuf);
  906. usb_set_maxpacket(dev);
  907. /*
  908. * we set the default configuration here
  909. * This seems premature. If the driver wants a different configuration
  910. * it will need to select itself.
  911. */
  912. err = usb_set_configuration(dev, dev->config.desc.bConfigurationValue);
  913. if (err < 0) {
  914. /* printf("failed to set default configuration " \
  915. "len %d, status %lX\n", dev->act_len, dev->status); */
  916. return err;
  917. }
  918. /*
  919. * Wait until the Set Configuration request gets processed by the
  920. * device. This is required by at least SanDisk Cruzer Pop USB 2.0
  921. * and Kingston DT Ultimate 32GB USB 3.0 on DWC2 OTG controller.
  922. */
  923. mdelay(10);
  924. /* debug("new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
  925. dev->descriptor.iManufacturer, dev->descriptor.iProduct,
  926. dev->descriptor.iSerialNumber); */
  927. memset(dev->mf, 0, sizeof(dev->mf));
  928. memset(dev->prod, 0, sizeof(dev->prod));
  929. memset(dev->serial, 0, sizeof(dev->serial));
  930. if (dev->descriptor.iManufacturer)
  931. usb_string(dev, dev->descriptor.iManufacturer,
  932. dev->mf, sizeof(dev->mf));
  933. if (dev->descriptor.iProduct)
  934. usb_string(dev, dev->descriptor.iProduct,
  935. dev->prod, sizeof(dev->prod));
  936. if (dev->descriptor.iSerialNumber)
  937. usb_string(dev, dev->descriptor.iSerialNumber,
  938. dev->serial, sizeof(dev->serial));
  939. //debug("Manufacturer %s\n", dev->mf);
  940. //debug("Product %s\n", dev->prod);
  941. //debug("SerialNumber %s\n", dev->serial);
  942. return 0;
  943. }
  944. int usb_setup_device(struct usb_device *dev, bool do_read,
  945. struct usb_device *parent)
  946. {
  947. int addr;
  948. int ret;
  949. /* We still haven't set the Address yet */
  950. addr = dev->devnum;
  951. dev->devnum = 0;
  952. ret = usb_prepare_device(dev, addr, do_read, parent);
  953. if (ret)
  954. return ret;
  955. ret = usb_select_config(dev);
  956. return ret;
  957. }
  958. bool usb_device_has_child_on_port(struct usb_device *parent, int port)
  959. {
  960. return parent->children[port] != NULL;
  961. }
  962. static inline bool usb_hub_is_superspeed(struct usb_device *hdev)
  963. {
  964. return hdev->descriptor.bDeviceProtocol == 3;
  965. }
  966. static int usb_get_hub_descriptor(struct usb_device *dev, void *data, int size)
  967. {
  968. unsigned short dtype = USB_DT_HUB;
  969. if (usb_hub_is_superspeed(dev))
  970. dtype = USB_DT_SS_HUB;
  971. return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  972. USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
  973. dtype << 8, 0, data, size, USB_CNTL_TIMEOUT);
  974. }
  975. static struct usb_hub_device *usb_get_hub_device(struct usb_device *dev)
  976. {
  977. struct usb_hub_device *hub;
  978. /* "allocate" Hub device */
  979. hub = usb_hub_allocate();
  980. return hub;
  981. }
  982. static int usb_get_hub_status(struct usb_device *dev, void *data)
  983. {
  984. return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  985. USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
  986. data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
  987. }
  988. static int usb_clear_port_feature(struct usb_device *dev, int port, int feature)
  989. {
  990. return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  991. USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature,
  992. port, NULL, 0, USB_CNTL_TIMEOUT);
  993. }
  994. static int usb_set_port_feature(struct usb_device *dev, int port, int feature)
  995. {
  996. return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
  997. USB_REQ_SET_FEATURE, USB_RT_PORT, feature,
  998. port, NULL, 0, USB_CNTL_TIMEOUT);
  999. }
  1000. int usb_get_port_status(struct usb_device *dev, int port, void *data)
  1001. {
  1002. int ret;
  1003. ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
  1004. USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port,
  1005. data, sizeof(struct usb_port_status), USB_CNTL_TIMEOUT);
  1006. return ret;
  1007. }
  1008. static void usb_hub_power_on(struct usb_hub_device *hub)
  1009. {
  1010. int i;
  1011. struct usb_device *dev;
  1012. unsigned pgood_delay = hub->desc.bPwrOn2PwrGood * 2;
  1013. //const char *env;
  1014. dev = hub->pusb_dev;
  1015. //debug("enabling power on all ports\n");
  1016. for (i = 0; i < dev->maxchild; i++) {
  1017. usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_POWER);
  1018. //debug("port %d returns %lX\n", i + 1, dev->status);
  1019. }
  1020. /*
  1021. * Wait for power to become stable,
  1022. * plus spec-defined max time for device to connect
  1023. * but allow this time to be increased via env variable as some
  1024. * devices break the spec and require longer warm-up times
  1025. */
  1026. /* env = env_get("usb_pgood_delay");
  1027. if (env)
  1028. pgood_delay = max(pgood_delay,
  1029. (unsigned)simple_strtol(env, NULL, 0));
  1030. debug("pgood_delay=%dms\n", pgood_delay); */
  1031. /*
  1032. * Do a minimum delay of the larger value of 100ms or pgood_delay
  1033. * so that the power can stablize before the devices are queried
  1034. */
  1035. hub->query_delay = xTaskGetTickCount() + pdMS_TO_TICKS(max(100, (int)pgood_delay));
  1036. /*
  1037. * Record the power-on timeout here. The max. delay (timeout)
  1038. * will be done based on this value in the USB port loop in
  1039. * usb_hub_configure() later.
  1040. */
  1041. hub->connect_timeout = hub->query_delay + pdMS_TO_TICKS(1000);
  1042. /* debug("devnum=%d poweron: query_delay=%d connect_timeout=%d\n",
  1043. dev->devnum, max(100, (int)pgood_delay),
  1044. max(100, (int)pgood_delay) + 1000); */
  1045. }
  1046. #define MAX_TRIES 5
  1047. /**
  1048. * usb_hub_port_reset() - reset a port given its usb_device pointer
  1049. *
  1050. * Reset a hub port and see if a device is present on that port, providing
  1051. * sufficient time for it to show itself. The port status is returned.
  1052. *
  1053. * @dev: USB device to reset
  1054. * @port: Port number to reset (note ports are numbered from 0 here)
  1055. * @portstat: Returns port status
  1056. */
  1057. static int usb_hub_port_reset(struct usb_device *dev, int port,
  1058. unsigned short *portstat)
  1059. {
  1060. int err, tries;
  1061. ALLOC_CACHE_ALIGN_BUFFER(struct usb_port_status, portsts, 1);
  1062. unsigned short portstatus, portchange;
  1063. int delay = HUB_SHORT_RESET_TIME; /* start with short reset delay */
  1064. //debug("%s: resetting port %d...\n", __func__, port + 1);
  1065. for (tries = 0; tries < MAX_TRIES; tries++) {
  1066. err = usb_set_port_feature(dev, port + 1, USB_PORT_FEAT_RESET);
  1067. if (err < 0)
  1068. return err;
  1069. mdelay(delay);
  1070. if (usb_get_port_status(dev, port + 1, portsts) < 0) {
  1071. /* debug("get_port_status failed status %lX\n",
  1072. dev->status); */
  1073. return -1;
  1074. }
  1075. portstatus = le16_to_cpu(portsts->wPortStatus);
  1076. portchange = le16_to_cpu(portsts->wPortChange);
  1077. USB_UNUSED(portchange);
  1078. /* debug("portstatus %x, change %x, %s\n", portstatus, portchange,
  1079. portspeed(portstatus));
  1080. debug("STAT_C_CONNECTION = %d STAT_CONNECTION = %d" \
  1081. " USB_PORT_STAT_ENABLE %d\n",
  1082. (portchange & USB_PORT_STAT_C_CONNECTION) ? 1 : 0,
  1083. (portstatus & USB_PORT_STAT_CONNECTION) ? 1 : 0,
  1084. (portstatus & USB_PORT_STAT_ENABLE) ? 1 : 0); */
  1085. /*
  1086. * Perhaps we should check for the following here:
  1087. * - C_CONNECTION hasn't been set.
  1088. * - CONNECTION is still set.
  1089. *
  1090. * Doing so would ensure that the device is still connected
  1091. * to the bus, and hasn't been unplugged or replaced while the
  1092. * USB bus reset was going on.
  1093. *
  1094. * However, if we do that, then (at least) a San Disk Ultra
  1095. * USB 3.0 16GB device fails to reset on (at least) an NVIDIA
  1096. * Tegra Jetson TK1 board. For some reason, the device appears
  1097. * to briefly drop off the bus when this second bus reset is
  1098. * executed, yet if we retry this loop, it'll eventually come
  1099. * back after another reset or two.
  1100. */
  1101. if (portstatus & USB_PORT_STAT_ENABLE)
  1102. break;
  1103. /* Switch to long reset delay for the next round */
  1104. delay = HUB_LONG_RESET_TIME;
  1105. }
  1106. if (tries == MAX_TRIES) {
  1107. /* debug("Cannot enable port %i after %i retries, " \
  1108. "disabling port.\n", port + 1, MAX_TRIES);
  1109. debug("Maybe the USB cable is bad?\n"); */
  1110. return -1;
  1111. }
  1112. usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_RESET);
  1113. if (portstat)
  1114. *portstat = portstatus;
  1115. return 0;
  1116. }
  1117. int usb_new_device(struct usb_device *dev);
  1118. int usb_hub_port_connect_change(struct usb_device *dev, int port)
  1119. {
  1120. ALLOC_CACHE_ALIGN_BUFFER(struct usb_port_status, portsts, 1);
  1121. unsigned short portstatus;
  1122. int ret, speed;
  1123. /* Check status */
  1124. ret = usb_get_port_status(dev, port + 1, portsts);
  1125. if (ret < 0) {
  1126. //debug("get_port_status failed\n");
  1127. return ret;
  1128. }
  1129. portstatus = portsts->wPortStatus;
  1130. /* debug("portstatus %x, change %x, %s\n",
  1131. portstatus,
  1132. le16_to_cpu(portsts->wPortChange),
  1133. portspeed(portstatus)); */
  1134. /* Clear the connection change status */
  1135. usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_CONNECTION);
  1136. /* Disconnect any existing devices under this port */
  1137. if (((!(portstatus & USB_PORT_STAT_CONNECTION)) &&
  1138. (!(portstatus & USB_PORT_STAT_ENABLE))) ||
  1139. usb_device_has_child_on_port(dev, port)) {
  1140. //debug("usb_disconnect(&hub->children[port]);\n");
  1141. /* Return now if nothing is connected */
  1142. if (!(portstatus & USB_PORT_STAT_CONNECTION))
  1143. return -ENOTCONN;
  1144. }
  1145. /* Reset the port */
  1146. ret = usb_hub_port_reset(dev, port, &portstatus);
  1147. if (ret < 0) {
  1148. if (ret != -ENXIO)
  1149. ;//printf("cannot reset port %i!?\n", port + 1);
  1150. return ret;
  1151. }
  1152. switch (portstatus & USB_PORT_STAT_SPEED_MASK) {
  1153. case USB_PORT_STAT_SUPER_SPEED:
  1154. speed = USB_SPEED_SUPER;
  1155. break;
  1156. case USB_PORT_STAT_HIGH_SPEED:
  1157. speed = USB_SPEED_HIGH;
  1158. break;
  1159. case USB_PORT_STAT_LOW_SPEED:
  1160. speed = USB_SPEED_LOW;
  1161. break;
  1162. default:
  1163. speed = USB_SPEED_FULL;
  1164. break;
  1165. }
  1166. #ifdef USB_TEST_EYE_DIAGRAM
  1167. if (1) {
  1168. usb_set_port_feature(dev, (4 << 8), 21);
  1169. while(1)
  1170. vTaskDelay(100);
  1171. }
  1172. #endif
  1173. struct usb_device *usb;
  1174. ret = usb_alloc_new_device(dev->controller, &usb);
  1175. if (ret) {
  1176. //printf("cannot create new device: ret=%d", ret);
  1177. return ret;
  1178. }
  1179. dev->children[port] = usb;
  1180. usb->speed = speed;
  1181. usb->parent = dev;
  1182. usb->portnr = port + 1;
  1183. /* Run it through the hoops (find a driver, etc) */
  1184. ret = usb_new_device(usb);
  1185. if (ret < 0) {
  1186. /* Woops, disable the port */
  1187. usb_free_device(dev->controller);
  1188. dev->children[port] = NULL;
  1189. }
  1190. if (ret < 0) {
  1191. //debug("hub: disabling port %d\n", port + 1);
  1192. usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_ENABLE);
  1193. }
  1194. return ret;
  1195. }
  1196. static int usb_scan_port(struct usb_device_scan *usb_scan)
  1197. {
  1198. ALLOC_CACHE_ALIGN_BUFFER(struct usb_port_status, portsts, 1);
  1199. unsigned short portstatus;
  1200. unsigned short portchange;
  1201. struct usb_device *dev;
  1202. struct usb_hub_device *hub;
  1203. int ret = 0;
  1204. int i;
  1205. dev = usb_scan->dev;
  1206. hub = usb_scan->hub;
  1207. i = usb_scan->port;
  1208. /*
  1209. * Don't talk to the device before the query delay is expired.
  1210. * This is needed for voltages to stabalize.
  1211. */
  1212. if (xTaskGetTickCount() < hub->query_delay)
  1213. return 0;
  1214. list_del(&usb_scan->list);
  1215. ret = usb_get_port_status(dev, i + 1, portsts);
  1216. if (ret < 0) {
  1217. //debug("get_port_status failed\n");
  1218. if (xTaskGetTickCount() >= hub->connect_timeout) {
  1219. /* debug("devnum=%d port=%d: timeout\n",
  1220. dev->devnum, i + 1); */
  1221. /* Remove this device from scanning list */
  1222. //list_del(&usb_scan->list);
  1223. free(usb_scan);
  1224. return -1;
  1225. }
  1226. return 0;
  1227. }
  1228. portstatus = portsts->wPortStatus;
  1229. portchange = portsts->wPortChange;
  1230. USB_UNUSED(portchange);
  1231. //debug("Port %d Status %X Change %X\n", i + 1, portstatus, portchange);
  1232. /*
  1233. * No connection change happened, wait a bit more.
  1234. *
  1235. * For some situation, the hub reports no connection change but a
  1236. * device is connected to the port (eg: CCS bit is set but CSC is not
  1237. * in the PORTSC register of a root hub), ignore such case.
  1238. */
  1239. if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
  1240. !(portstatus & USB_PORT_STAT_CONNECTION)) {
  1241. if (xTaskGetTickCount() >= hub->connect_timeout) {
  1242. /* debug("devnum=%d port=%d: timeout\n",
  1243. dev->devnum, i + 1); */
  1244. /* Remove this device from scanning list */
  1245. //list_del(&usb_scan->list);
  1246. free(usb_scan);
  1247. return -1;
  1248. }
  1249. return 0;
  1250. }
  1251. if (portchange & USB_PORT_STAT_C_RESET) {
  1252. //debug("port %d reset change\n", i + 1);
  1253. usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_RESET);
  1254. }
  1255. if ((portchange & USB_SS_PORT_STAT_C_BH_RESET) &&
  1256. usb_hub_is_superspeed(dev)) {
  1257. //debug("port %d BH reset change\n", i + 1);
  1258. usb_clear_port_feature(dev, i + 1, USB_SS_PORT_FEAT_C_BH_RESET);
  1259. }
  1260. /* A new USB device is ready at this point */
  1261. //debug("devnum=%d port=%d: USB dev found\n", dev->devnum, i + 1);
  1262. ret = usb_hub_port_connect_change(dev, i);
  1263. if (ret < 0) {
  1264. printf("usb port change err at line:%d\r\n", __LINE__);
  1265. goto exit;
  1266. }
  1267. if (portchange & USB_PORT_STAT_C_ENABLE) {
  1268. //debug("port %d enable change, status %x\n", i + 1, portstatus);
  1269. usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_ENABLE);
  1270. /*
  1271. * The following hack causes a ghost device problem
  1272. * to Faraday EHCI
  1273. */
  1274. /*
  1275. * EM interference sometimes causes bad shielded USB
  1276. * devices to be shutdown by the hub, this hack enables
  1277. * them again. Works at least with mouse driver
  1278. */
  1279. if (!(portstatus & USB_PORT_STAT_ENABLE) &&
  1280. (portstatus & USB_PORT_STAT_CONNECTION) &&
  1281. usb_device_has_child_on_port(dev, i)) {
  1282. /* debug("already running port %i disabled by hub (EMI?), re-enabling...\n",
  1283. i + 1); */
  1284. ret = usb_hub_port_connect_change(dev, i);
  1285. if (ret < 0) {
  1286. printf("usb port change err at line:%d\r\n", __LINE__);
  1287. goto exit;
  1288. }
  1289. }
  1290. }
  1291. if (portstatus & USB_PORT_STAT_SUSPEND) {
  1292. //debug("port %d suspend change\n", i + 1);
  1293. usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_SUSPEND);
  1294. }
  1295. if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
  1296. //debug("port %d over-current change\n", i + 1);
  1297. usb_clear_port_feature(dev, i + 1,
  1298. USB_PORT_FEAT_C_OVER_CURRENT);
  1299. /* Only power-on this one port */
  1300. usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_POWER);
  1301. hub->overcurrent_count[i]++;
  1302. /*
  1303. * If the max-scan-count is not reached, return without removing
  1304. * the device from scan-list. This will re-issue a new scan.
  1305. */
  1306. if (hub->overcurrent_count[i] <=
  1307. PORT_OVERCURRENT_MAX_SCAN_COUNT)
  1308. return 0;
  1309. /* Otherwise the device will get removed */
  1310. /* printf("Port %d over-current occurred %d times\n", i + 1,
  1311. hub->overcurrent_count[i]); */
  1312. }
  1313. /*
  1314. * We're done with this device, so let's remove this device from
  1315. * scanning list
  1316. */
  1317. ret = 0;
  1318. exit:
  1319. free(usb_scan);printf("usb_scan_port ret:%d\r\n", ret);
  1320. return ret;
  1321. }
  1322. static int usb_device_list_scan(void)
  1323. {
  1324. struct usb_device_scan *usb_scan;
  1325. //struct usb_device_scan *tmp;
  1326. //static int running;
  1327. int ret = 0;
  1328. ListItem_t *pxListItem, *nListItem;
  1329. /* Only run this loop once for each controller */
  1330. //if (running)
  1331. // return 0;
  1332. //running = 1;
  1333. while (1) {
  1334. /* We're done, once the list is empty again */
  1335. if (list_empty(&usb_scan_list))
  1336. goto out;
  1337. list_for_each_entry_safe(pxListItem, nListItem, usb_scan, &usb_scan_list) {
  1338. int ret;
  1339. /* Scan this port */
  1340. ret = usb_scan_port(usb_scan);
  1341. if (ret) {
  1342. continue;
  1343. }
  1344. ret = usb_stor_scan(0);
  1345. #ifdef USB_UVC_SUPPORT
  1346. ret = usb_uvc_scan();
  1347. #endif
  1348. }
  1349. }
  1350. ret = 0;
  1351. out:
  1352. /*
  1353. * This USB controller has finished scanning all its connected
  1354. * USB devices. Set "running" back to 0, so that other USB controllers
  1355. * will scan their devices too.
  1356. */
  1357. //running = 0;
  1358. return ret;
  1359. }
  1360. static int usb_hub_configure(struct usb_device *dev)
  1361. {
  1362. int i, length;
  1363. ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, USB_BUFSIZ);
  1364. unsigned char *bitmap;
  1365. short hubCharacteristics;
  1366. struct usb_hub_descriptor *descriptor;
  1367. struct usb_hub_device *hub;
  1368. struct usb_hub_status *hubsts;
  1369. unsigned char *tmp;
  1370. unsigned short tmpval;
  1371. int ret;
  1372. hub = usb_get_hub_device(dev);
  1373. if (hub == NULL)
  1374. return -ENOMEM;
  1375. hub->pusb_dev = dev;
  1376. /* Get the the hub descriptor */
  1377. ret = usb_get_hub_descriptor(dev, buffer, 4);
  1378. if (ret < 0) {
  1379. /* debug("usb_hub_configure: failed to get hub " \
  1380. "descriptor, giving up %lX\n", dev->status); */
  1381. return ret;
  1382. }
  1383. descriptor = (struct usb_hub_descriptor *)buffer;
  1384. length = min(descriptor->bLength,
  1385. sizeof(struct usb_hub_descriptor));
  1386. ret = usb_get_hub_descriptor(dev, buffer, length);
  1387. if (ret < 0) {
  1388. /* debug("usb_hub_configure: failed to get hub " \
  1389. "descriptor 2nd giving up %lX\n", dev->status); */
  1390. return ret;
  1391. }
  1392. memcpy((unsigned char *)&hub->desc, buffer, length);
  1393. /* adjust 16bit values */
  1394. /* put_unaligned(le16_to_cpu(get_unaligned(
  1395. &descriptor->wHubCharacteristics)),
  1396. &hub->desc.wHubCharacteristics); */
  1397. tmp = (unsigned char*)&descriptor->wHubCharacteristics;
  1398. tmpval = (tmp[1] << 8) | tmp[0];
  1399. tmp = (unsigned char*)&hub->desc.wHubCharacteristics;
  1400. tmp[0] = tmpval & 0xff;
  1401. tmp[1] = (tmpval >> 8) & 0xff;
  1402. /* set the bitmap */
  1403. bitmap = (unsigned char *)&hub->desc.u.hs.DeviceRemovable[0];
  1404. /* devices not removable by default */
  1405. memset(bitmap, 0xff, (USB_MAXCHILDREN+1+7)/8);
  1406. bitmap = (unsigned char *)&hub->desc.u.hs.PortPowerCtrlMask[0];
  1407. memset(bitmap, 0xff, (USB_MAXCHILDREN+1+7)/8); /* PowerMask = 1B */
  1408. for (i = 0; i < ((hub->desc.bNbrPorts + 1 + 7)/8); i++)
  1409. hub->desc.u.hs.DeviceRemovable[i] =
  1410. descriptor->u.hs.DeviceRemovable[i];
  1411. for (i = 0; i < ((hub->desc.bNbrPorts + 1 + 7)/8); i++)
  1412. hub->desc.u.hs.PortPowerCtrlMask[i] =
  1413. descriptor->u.hs.PortPowerCtrlMask[i];
  1414. dev->maxchild = descriptor->bNbrPorts;
  1415. //debug("%d ports detected\n", dev->maxchild);
  1416. tmp = (unsigned char*)&hub->desc.wHubCharacteristics;
  1417. hubCharacteristics = (tmp[1] << 8) | tmp[0];//get_unaligned(&hub->desc.wHubCharacteristics);
  1418. switch (hubCharacteristics & HUB_CHAR_LPSM) {
  1419. case 0x00:
  1420. //debug("ganged power switching\n");
  1421. break;
  1422. case 0x01:
  1423. //debug("individual port power switching\n");
  1424. break;
  1425. case 0x02:
  1426. case 0x03:
  1427. //debug("unknown reserved power switching mode\n");
  1428. break;
  1429. }
  1430. if (hubCharacteristics & HUB_CHAR_COMPOUND)
  1431. ;//debug("part of a compound device\n");
  1432. else
  1433. ;//debug("standalone hub\n");
  1434. switch (hubCharacteristics & HUB_CHAR_OCPM) {
  1435. case 0x00:
  1436. //debug("global over-current protection\n");
  1437. break;
  1438. case 0x08:
  1439. //debug("individual port over-current protection\n");
  1440. break;
  1441. case 0x10:
  1442. case 0x18:
  1443. //debug("no over-current protection\n");
  1444. break;
  1445. }
  1446. switch (dev->descriptor.bDeviceProtocol) {
  1447. case USB_HUB_PR_FS:
  1448. break;
  1449. case USB_HUB_PR_HS_SINGLE_TT:
  1450. //debug("Single TT\n");
  1451. break;
  1452. case USB_HUB_PR_HS_MULTI_TT:
  1453. ret = usb_set_interface(dev, 0, 1);
  1454. if (ret == 0) {
  1455. //debug("TT per port\n");
  1456. hub->tt.multi = true;
  1457. } else {
  1458. ;//debug("Using single TT (err %d)\n", ret);
  1459. }
  1460. break;
  1461. case USB_HUB_PR_SS:
  1462. /* USB 3.0 hubs don't have a TT */
  1463. break;
  1464. default:
  1465. /* debug("Unrecognized hub protocol %d\n",
  1466. dev->descriptor.bDeviceProtocol); */
  1467. break;
  1468. }
  1469. /* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
  1470. switch (hubCharacteristics & HUB_CHAR_TTTT) {
  1471. case HUB_TTTT_8_BITS:
  1472. if (dev->descriptor.bDeviceProtocol != 0) {
  1473. hub->tt.think_time = 666;
  1474. /* debug("TT requires at most %d FS bit times (%d ns)\n",
  1475. 8, hub->tt.think_time); */
  1476. }
  1477. break;
  1478. case HUB_TTTT_16_BITS:
  1479. hub->tt.think_time = 666 * 2;
  1480. /* debug("TT requires at most %d FS bit times (%d ns)\n",
  1481. 16, hub->tt.think_time); */
  1482. break;
  1483. case HUB_TTTT_24_BITS:
  1484. hub->tt.think_time = 666 * 3;
  1485. /* debug("TT requires at most %d FS bit times (%d ns)\n",
  1486. 24, hub->tt.think_time); */
  1487. break;
  1488. case HUB_TTTT_32_BITS:
  1489. hub->tt.think_time = 666 * 4;
  1490. /* debug("TT requires at most %d FS bit times (%d ns)\n",
  1491. 32, hub->tt.think_time); */
  1492. break;
  1493. }
  1494. /* debug("power on to power good time: %dms\n",
  1495. descriptor->bPwrOn2PwrGood * 2);
  1496. debug("hub controller current requirement: %dmA\n",
  1497. descriptor->bHubContrCurrent);
  1498. for (i = 0; i < dev->maxchild; i++)
  1499. debug("port %d is%s removable\n", i + 1,
  1500. hub->desc.u.hs.DeviceRemovable[(i + 1) / 8] & \
  1501. (1 << ((i + 1) % 8)) ? " not" : ""); */
  1502. if (sizeof(struct usb_hub_status) > USB_BUFSIZ) {
  1503. /* debug("usb_hub_configure: failed to get Status - " \
  1504. "too long: %d\n", descriptor->bLength); */
  1505. return -EFBIG;
  1506. }
  1507. ret = usb_get_hub_status(dev, buffer);
  1508. if (ret < 0) {
  1509. /* debug("usb_hub_configure: failed to get Status %lX\n",
  1510. dev->status); */
  1511. return ret;
  1512. }
  1513. hubsts = (struct usb_hub_status *)buffer;
  1514. USB_UNUSED(hubsts);
  1515. /* debug("get_hub_status returned status %X, change %X\n",
  1516. le16_to_cpu(hubsts->wHubStatus),
  1517. le16_to_cpu(hubsts->wHubChange));
  1518. debug("local power source is %s\n",
  1519. (le16_to_cpu(hubsts->wHubStatus) & HUB_STATUS_LOCAL_POWER) ? \
  1520. "lost (inactive)" : "good");
  1521. debug("%sover-current condition exists\n",
  1522. (le16_to_cpu(hubsts->wHubStatus) & HUB_STATUS_OVERCURRENT) ? \
  1523. "" : "no "); */
  1524. usb_hub_power_on(hub);
  1525. if (hub->pusb_dev && hub->pusb_dev->parent) {// not root hub
  1526. printf("usb hub found, but not root\r\n");
  1527. //for (i = 0; i < dev->maxchild; i++) {
  1528. for (i = 0; i < 1; i++) {
  1529. struct usb_device_scan *usb_scan;
  1530. usb_scan = malloc(sizeof(*usb_scan));
  1531. if (!usb_scan) {
  1532. //printf("Can't allocate memory for USB device!\n");
  1533. return -1;
  1534. }
  1535. memset(usb_scan, 0, sizeof(struct usb_device_scan));
  1536. usb_scan->dev = dev;
  1537. usb_scan->hub = hub;
  1538. usb_scan->port = i;
  1539. INIT_LIST_ITEM(&usb_scan->list);
  1540. //listSET_LIST_ITEM_OWNER(usb_scan->list.pvOwner, usb_scan);
  1541. usb_scan->list.pvOwner = (void*)usb_scan;
  1542. list_add_tail(&usb_scan->list, &usb_scan_list);
  1543. }
  1544. xQueueSend(wait_new_dev, NULL, 0);
  1545. }
  1546. return ret;
  1547. }
  1548. static int usb_hub_check(struct usb_device *dev, int ifnum)
  1549. {
  1550. struct usb_interface *iface;
  1551. struct usb_endpoint_descriptor *ep = NULL;
  1552. iface = &dev->config.if_desc[ifnum];
  1553. /* Is it a hub? */
  1554. if (iface->desc.bInterfaceClass != USB_CLASS_HUB)
  1555. goto err;
  1556. /* Some hubs have a subclass of 1, which AFAICT according to the */
  1557. /* specs is not defined, but it works */
  1558. if ((iface->desc.bInterfaceSubClass != 0) &&
  1559. (iface->desc.bInterfaceSubClass != 1))
  1560. goto err;
  1561. /* Multiple endpoints? What kind of mutant ninja-hub is this? */
  1562. if (iface->desc.bNumEndpoints != 1)
  1563. goto err;
  1564. ep = &iface->ep_desc[0];
  1565. /* Output endpoint? Curiousier and curiousier.. */
  1566. if (!(ep->bEndpointAddress & USB_DIR_IN))
  1567. goto err;
  1568. /* If it's not an interrupt endpoint, we'd better punt! */
  1569. if ((ep->bmAttributes & 3) != 3)
  1570. goto err;
  1571. /* We found a hub */
  1572. //debug("USB hub found\n");
  1573. return 0;
  1574. err:
  1575. /* debug("USB hub not found: bInterfaceClass=%d, bInterfaceSubClass=%d, bNumEndpoints=%d\n",
  1576. iface->desc.bInterfaceClass, iface->desc.bInterfaceSubClass,
  1577. iface->desc.bNumEndpoints);
  1578. if (ep) {
  1579. debug(" bEndpointAddress=%#x, bmAttributes=%d",
  1580. ep->bEndpointAddress, ep->bmAttributes);
  1581. } */
  1582. return -ENOENT;
  1583. }
  1584. int usb_hub_probe(struct usb_device *dev, int ifnum)
  1585. {
  1586. int ret;
  1587. ret = usb_hub_check(dev, ifnum);
  1588. if (ret)
  1589. return 0;
  1590. ret = usb_hub_configure(dev);
  1591. return ret;
  1592. }
  1593. int usb_new_device(struct usb_device *dev)
  1594. {
  1595. bool do_read = true;
  1596. int err;
  1597. err = usb_setup_device(dev, do_read, dev->parent);
  1598. if (err)
  1599. return err;
  1600. /* Now probe if the device is a hub */
  1601. err = usb_hub_probe(dev, 0);
  1602. if (err < 0)
  1603. return err;
  1604. return 0;
  1605. }
  1606. void usb_connect_state_notify_cb(void* ctx, int state)
  1607. {
  1608. }
  1609. /***************************************************************************
  1610. * Init USB Device
  1611. */
  1612. int usb_init(void)
  1613. {
  1614. void *ctrl;
  1615. struct usb_device *dev;
  1616. int i, start_index = 0;
  1617. int controllers_initialized = 0;
  1618. int ret;
  1619. dev_index = 0;
  1620. asynch_allowed = 1;
  1621. usb_hub_reset();
  1622. /* first make all devices unknown */
  1623. for (i = 0; i < USB_MAX_DEVICE; i++) {
  1624. memset(&usb_dev[i], 0, sizeof(struct usb_device));
  1625. usb_dev[i].devnum = -1;
  1626. }
  1627. /* init low_level USB */
  1628. for (i = 0; i < CONFIG_USB_MAX_CONTROLLER_COUNT; i++) {
  1629. /* init low_level USB */
  1630. #if 0
  1631. ret = usb_lowlevel_init(i, USB_INIT_HOST, &ctrl);
  1632. if (ret == -ENODEV) { /* No such device. */
  1633. SendUartString("Port not available.\n");
  1634. controllers_initialized++;
  1635. continue;
  1636. }
  1637. if (ret) { /* Other error. */
  1638. SendUartString("lowlevel init failed\n");
  1639. continue;
  1640. }
  1641. #endif
  1642. /*
  1643. * lowlevel init is OK, now scan the bus for devices
  1644. * i.e. search HUBs and configure them
  1645. */
  1646. controllers_initialized++;
  1647. start_index = dev_index;
  1648. ret = usb_alloc_new_device(ctrl, &dev);
  1649. if (ret)
  1650. break;
  1651. /*
  1652. * device 0 is always present
  1653. * (root hub, so let it analyze)
  1654. */
  1655. ret = usb_new_device(dev);
  1656. if (ret)
  1657. usb_free_device(dev->controller);
  1658. if (start_index == dev_index) {
  1659. SendUartString("No USB Device found\n");
  1660. continue;
  1661. } else {
  1662. SendUartString("USB Device(s) found\n");
  1663. }
  1664. usb_started = 1;
  1665. }
  1666. /* if we were not able to find at least one working bus, bail out */
  1667. if (controllers_initialized == 0)
  1668. SendUartString("USB error: all controllers failed lowlevel init\n");
  1669. return usb_started ? 0 : -ENODEV;
  1670. }
  1671. /*
  1672. * disables the asynch behaviour of the control message. This is used for data
  1673. * transfers that uses the exclusiv access to the control and bulk messages.
  1674. * Returns the old value so it can be restored later.
  1675. */
  1676. int usb_disable_asynch(int disable)
  1677. {
  1678. int old_value = asynch_allowed;
  1679. asynch_allowed = !disable;
  1680. return old_value;
  1681. }
  1682. void usb_find_usb2_hub_address_port(struct usb_device *udev,
  1683. uint8_t *hub_address, uint8_t *hub_port)
  1684. {
  1685. /* Find out the nearest parent which is high speed */
  1686. while (udev->parent->parent != NULL)
  1687. if (udev->parent->speed != USB_SPEED_HIGH) {
  1688. udev = udev->parent;
  1689. } else {
  1690. *hub_address = udev->parent->devnum;
  1691. *hub_port = udev->portnr;
  1692. return;
  1693. }
  1694. *hub_address = 0;
  1695. *hub_port = 0;
  1696. }
  1697. extern int dwc2_disconnect_flag;
  1698. static void notify_new_dev_attach()
  1699. {
  1700. int i;
  1701. struct usb_hub_device *hub = NULL;
  1702. struct usb_device *dev = NULL;
  1703. //int ret;
  1704. hub = &hub_dev[0];
  1705. if (NULL == hub)
  1706. return;
  1707. dev = hub->pusb_dev;
  1708. for (i = 0; i < dev->maxchild; i++) {
  1709. struct usb_device_scan *usb_scan;
  1710. usb_scan = malloc(sizeof(*usb_scan));
  1711. if (!usb_scan) {
  1712. //printf("Can't allocate memory for USB device!\n");
  1713. return;
  1714. }
  1715. memset(usb_scan, 0, sizeof(struct usb_device_scan));
  1716. usb_scan->dev = dev;
  1717. usb_scan->hub = hub;
  1718. usb_scan->port = i;
  1719. INIT_LIST_ITEM(&usb_scan->list);
  1720. //listSET_LIST_ITEM_OWNER(usb_scan->list.pvOwner, usb_scan);
  1721. usb_scan->list.pvOwner = (void*)usb_scan;
  1722. list_add_tail(&usb_scan->list, &usb_scan_list);
  1723. }
  1724. dwc2_disconnect_flag = 0;
  1725. xQueueSend(wait_new_dev, NULL, 0);
  1726. }
  1727. static void usb_dev_scan_proc(void *pvParameters)
  1728. {
  1729. //struct usb_hub_device *hub;
  1730. //struct usb_device *dev = (struct usb_device *)pvParameters;
  1731. int ret;
  1732. //hub = usb_get_hub_device(dev);
  1733. while(usb_started) {
  1734. ret = xQueueReceive(wait_new_dev, NULL, portMAX_DELAY);
  1735. if (pdFALSE == ret) {
  1736. continue;
  1737. }
  1738. xTimerStop(usbPortScanTimer, 0);
  1739. //xSemaphoreTake(list_lock, portMAX_DELAY);
  1740. usb_disable_endpoint();
  1741. ret = usb_device_list_scan();
  1742. //xSemaphoreGive(list_lock);
  1743. xTimerStart( usbPortScanTimer, 0 );
  1744. }
  1745. vTaskDelete(NULL);
  1746. }
  1747. void hub_usb_dev_reset(void)
  1748. {
  1749. int i;
  1750. struct usb_device *dev;
  1751. struct usb_hub_device* hub;
  1752. //usb_disable_endpoint();
  1753. reset_usb_phy();
  1754. usb_clear_port_feature(&usb_dev[0], 1, USB_PORT_FEAT_C_ENABLE);
  1755. xSemaphoreTake(dev_lock, portMAX_DELAY);
  1756. for (i = 1; i < USB_MAX_DEVICE; i++) {
  1757. dev = &usb_dev[i];
  1758. if (dev->devnum != -1) {
  1759. memset(dev, 0, sizeof(struct usb_device));
  1760. dev->devnum = -1;
  1761. if (dev_index > 0)
  1762. dev_index--;
  1763. }
  1764. }
  1765. for (i = 1; i < USB_MAX_HUB; i++) {
  1766. hub = &hub_dev[i];
  1767. if (hub->pusb_dev != NULL) {printf("free hub\r\n");
  1768. hub->pusb_dev = NULL;
  1769. if (usb_hub_index > 1)
  1770. usb_hub_index--;
  1771. }
  1772. }
  1773. xSemaphoreGive(dev_lock);
  1774. }
  1775. static void prvUsbPortScanTimerCallback( TimerHandle_t xTimerHandle )
  1776. {
  1777. char buf[8] = {0};
  1778. int ret = 1;
  1779. char status = 0;
  1780. ret = hub_status_data(buf);
  1781. status = (buf[0] >> 1) & 0x1;
  1782. if (connect_status != status) {
  1783. printf("state:%d ret:%d usb state changed now!\r\n", buf[0], ret);
  1784. connect_status = status;
  1785. if (status) {
  1786. gconnect_flag = 1;
  1787. notify_new_dev_attach();
  1788. } else {
  1789. usb_stor_disconnect();
  1790. #ifdef USB_UVC_SUPPORT
  1791. usb_uvc_disconnect();
  1792. #endif
  1793. hub_usb_dev_reset();
  1794. dwc2_disconnect_flag = 0;
  1795. }
  1796. }
  1797. }
  1798. int usb_send_stor_dev_pluged(uint8_t pluged)
  1799. {
  1800. if (xQueueSend(usb_stor_dev_pluged, &pluged, 0) != pdPASS)
  1801. return -1;
  1802. return 0;
  1803. }
  1804. int usb_send_stor_dev_pluged_isr(uint8_t pluged)
  1805. {
  1806. if (pluged == 0)
  1807. gconnect_flag = 0;
  1808. if (xQueueSendFromISR(usb_stor_dev_pluged, &pluged, 0) != pdPASS)
  1809. return -1;
  1810. return 0;
  1811. }
  1812. int usb_wait_stor_dev_pluged(uint32_t timeout)
  1813. {
  1814. uint8_t pluged = 0;
  1815. uint32_t stick = xTaskGetTickCount();
  1816. while (!usb_stor_dev_pluged) {
  1817. if (xTaskGetTickCount() - stick > timeout)
  1818. return -1;
  1819. vTaskDelay(10);
  1820. }
  1821. if (usb_stor_dev_pluged && xQueueReceive(usb_stor_dev_pluged, &pluged, timeout) == pdPASS)
  1822. {
  1823. if(pluged)
  1824. {
  1825. usb_disk = FF_USBDiskInit(USB_MOUNT_PATH);
  1826. if (usb_disk)
  1827. return USB_DEV_PLUGED;
  1828. else
  1829. return USB_DEV_UNPLUGED;
  1830. }
  1831. else
  1832. {
  1833. if (usb_disk) {
  1834. FF_USBDiskDelete(usb_disk);
  1835. usb_disk = NULL;
  1836. }
  1837. return USB_DEV_UNPLUGED;
  1838. }
  1839. }
  1840. return -1;
  1841. }
  1842. int g_zero_register(const char *name);
  1843. int g_ncm_register(const char *name);
  1844. int ark_usb_init()
  1845. {
  1846. void *ctrl = NULL;
  1847. struct usb_device *dev;
  1848. int i, start_index = 0;
  1849. int controllers_initialized = 0;
  1850. int ret;
  1851. #if USB_MODE_ID && USB_MODE_ID != -1
  1852. vSysctlConfigure(SYS_PAD_CTRL06, 0, 0xff, 0);
  1853. gpio_request(USB_MODE_ID);
  1854. gpio_direction_input(USB_MODE_ID);
  1855. usb_mode = gpio_get_value(USB_MODE_ID);
  1856. #else
  1857. usb_mode = 0;
  1858. #endif
  1859. wait_new_dev = xQueueCreate(1, 0);
  1860. usb_stor_dev_pluged = xQueueCreate(1, 1);
  1861. dev_lock = xSemaphoreCreateMutex();
  1862. //USB_UNUSED(list_lock);
  1863. #ifdef USB_UVC_SUPPORT
  1864. usb_uvc_init();
  1865. #endif
  1866. usb_sysctrl_init();
  1867. dev_index = 0;
  1868. asynch_allowed = 1;
  1869. usb_hub_reset();
  1870. USB_UNUSED(start_index);
  1871. vListInitialise(&usb_scan_list);
  1872. /* first make all devices unknown */
  1873. for (i = 0; i < USB_MAX_DEVICE; i++) {
  1874. memset(&usb_dev[i], 0, sizeof(struct usb_device));
  1875. usb_dev[i].devnum = -1;
  1876. }
  1877. /* init low_level USB */
  1878. ret = usb_dwc2_lowlevel_init();
  1879. if (ret) {
  1880. SendUartString("lowlevel init failed\n");
  1881. return -ENODEV;
  1882. }
  1883. /*
  1884. * lowlevel init is OK, now scan the bus for devices
  1885. * i.e. search HUBs and configure them
  1886. */
  1887. controllers_initialized++;
  1888. start_index = dev_index;
  1889. ret = usb_alloc_new_device(ctrl, &dev);//usb 0 for root hub
  1890. if (ret)
  1891. return -ENODEV;
  1892. if (get_usb_mode()) {
  1893. //g_zero_register("zero");
  1894. usb_started = 1;
  1895. //g_ncm_register("ncm");
  1896. } else {
  1897. /*
  1898. * device 0 is always present
  1899. * (root hub, so let it analyze)
  1900. */
  1901. ret = usb_new_device(dev);
  1902. if (ret)
  1903. usb_free_device(dev->controller);
  1904. usb_started = 1;
  1905. #ifdef USB_TEST_EYE_DIAGRAM
  1906. if (0) {
  1907. int port = 0;
  1908. unsigned short portstatus = 0;
  1909. //usb_hub_port_reset(dev, port, &portstatus);
  1910. usb_set_port_feature(dev, (4 << 8), 21);
  1911. while(1)
  1912. vTaskDelay(100);
  1913. }
  1914. #endif
  1915. usbPortScanTimer = xTimerCreate( "Timer",
  1916. mainTIMER_SCAN_FREQUENCY_MS, /* The period of the software timer in ticks. */
  1917. pdTRUE, /* xAutoReload is set to pdFALSE, so this is a one-shot timer. */
  1918. NULL, /* The timer's ID is not used. */
  1919. prvUsbPortScanTimerCallback );
  1920. xTaskCreate(usb_dev_scan_proc, "usb_scan", configMINIMAL_STACK_SIZE * 3, (void*)dev, configMAX_PRIORITIES, &scan_usb_dev_task);
  1921. xTimerStart( usbPortScanTimer, 0 );
  1922. }
  1923. return usb_started ? 0 : -ENODEV;
  1924. }
  1925. int get_usb_mode(void)
  1926. {
  1927. return usb_mode;
  1928. }