hcd.c 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdint.h>
  7. #include <string.h>
  8. #include <sys/queue.h>
  9. #include "freertos/FreeRTOS.h"
  10. #include "freertos/task.h"
  11. #include "freertos/semphr.h"
  12. #include "esp_heap_caps.h"
  13. #include "esp_intr_alloc.h"
  14. #include "esp_timer.h"
  15. #include "esp_err.h"
  16. #include "esp_rom_gpio.h"
  17. #include "hal/usbh_hal.h"
  18. #include "hal/usb_types_private.h"
  19. #include "soc/gpio_pins.h"
  20. #include "soc/gpio_sig_map.h"
  21. #include "driver/periph_ctrl.h"
  22. #include "hcd.h"
  23. #include "usb_private.h"
  24. #include "usb/usb_types_ch9.h"
  25. // ----------------------------------------------------- Macros --------------------------------------------------------
  26. // --------------------- Constants -------------------------
  27. #define INIT_DELAY_MS 30 //A delay of at least 25ms to enter Host mode. Make it 30ms to be safe
  28. #define DEBOUNCE_DELAY_MS 250 //A debounce delay of 250ms
  29. #define RESET_HOLD_MS 30 //Spec requires at least 10ms. Make it 30ms to be safe
  30. #define RESET_RECOVERY_MS 30 //Reset recovery delay of 10ms (make it 30 ms to be safe) to allow for connected device to recover (and for port enabled interrupt to occur)
  31. #define RESUME_HOLD_MS 30 //Spec requires at least 20ms, Make it 30ms to be safe
  32. #define RESUME_RECOVERY_MS 20 //Resume recovery of at least 10ms. Make it 20 ms to be safe. This will include the 3 LS bit times of the EOP
  33. #define CTRL_EP_MAX_MPS_LS 8 //Largest Maximum Packet Size for Low Speed control endpoints
  34. #define CTRL_EP_MAX_MPS_FS 64 //Largest Maximum Packet Size for Full Speed control endpoints
  35. #define NUM_PORTS 1 //The controller only has one port.
  36. // ----------------------- Configs -------------------------
  37. typedef struct {
  38. int in_mps;
  39. int non_periodic_out_mps;
  40. int periodic_out_mps;
  41. } fifo_mps_limits_t;
  42. /**
  43. * @brief Default FIFO sizes (see 2.1.2.4 for programming guide)
  44. *
  45. * RXFIFO
  46. * - Recommended: ((LPS/4) * 2) + 2
  47. * - Actual: Whatever leftover size: USBH_HAL_FIFO_TOTAL_USABLE_LINES(200) - 48 - 48 = 104
  48. * - Worst case can accommodate two packets of 204 bytes, or one packet of 408
  49. * NPTXFIFO
  50. * - Recommended: (LPS/4) * 2
  51. * - Actual: Assume LPS is 64, and 3 packets: (64/4) * 3 = 48
  52. * - Worst case can accommodate three packets of 64 bytes or one packet of 192
  53. * PTXFIFO
  54. * - Recommended: (LPS/4) * 2
  55. * - Actual: Assume LPS is 64, and 3 packets: (64/4) * 3 = 48
  56. * - Worst case can accommodate three packets of 64 bytes or one packet of 192
  57. */
  58. const usbh_hal_fifo_config_t fifo_config_default = {
  59. .rx_fifo_lines = 104,
  60. .nptx_fifo_lines = 48,
  61. .ptx_fifo_lines = 48,
  62. };
  63. const fifo_mps_limits_t mps_limits_default = {
  64. .in_mps = 408,
  65. .non_periodic_out_mps = 192,
  66. .periodic_out_mps = 192,
  67. };
  68. /**
  69. * @brief FIFO sizes that bias to giving RX FIFO more capacity
  70. *
  71. * RXFIFO
  72. * - Recommended: ((LPS/4) * 2) + 2
  73. * - Actual: Whatever leftover size: USBH_HAL_FIFO_TOTAL_USABLE_LINES(200) - 32 - 16 = 152
  74. * - Worst case can accommodate two packets of 300 bytes or one packet of 600 bytes
  75. * NPTXFIFO
  76. * - Recommended: (LPS/4) * 2
  77. * - Actual: Assume LPS is 64, and 1 packets: (64/4) * 1 = 16
  78. * - Worst case can accommodate one packet of 64 bytes
  79. * PTXFIFO
  80. * - Recommended: (LPS/4) * 2
  81. * - Actual: Assume LPS is 64, and 3 packets: (64/4) * 2 = 32
  82. * - Worst case can accommodate two packets of 64 bytes or one packet of 128
  83. */
  84. const usbh_hal_fifo_config_t fifo_config_bias_rx = {
  85. .rx_fifo_lines = 152,
  86. .nptx_fifo_lines = 16,
  87. .ptx_fifo_lines = 32,
  88. };
  89. const fifo_mps_limits_t mps_limits_bias_rx = {
  90. .in_mps = 600,
  91. .non_periodic_out_mps = 64,
  92. .periodic_out_mps = 128,
  93. };
  94. /**
  95. * @brief FIFO sizes that bias to giving Periodic TX FIFO more capacity (i.e., ISOC OUT)
  96. *
  97. * RXFIFO
  98. * - Recommended: ((LPS/4) * 2) + 2
  99. * - Actual: Assume LPS is 64, and 2 packets: ((64/4) * 2) + 2 = 34
  100. * - Worst case can accommodate two packets of 64 bytes or one packet of 128
  101. * NPTXFIFO
  102. * - Recommended: (LPS/4) * 2
  103. * - Actual: Assume LPS is 64, and 1 packets: (64/4) * 1 = 16
  104. * - Worst case can accommodate one packet of 64 bytes
  105. * PTXFIFO
  106. * - Recommended: (LPS/4) * 2
  107. * - Actual: Whatever leftover size: USBH_HAL_FIFO_TOTAL_USABLE_LINES(200) - 34 - 16 = 150
  108. * - Worst case can accommodate two packets of 300 bytes or one packet of 600 bytes
  109. */
  110. const usbh_hal_fifo_config_t fifo_config_bias_ptx = {
  111. .rx_fifo_lines = 34,
  112. .nptx_fifo_lines = 16,
  113. .ptx_fifo_lines = 150,
  114. };
  115. const fifo_mps_limits_t mps_limits_bias_ptx = {
  116. .in_mps = 128,
  117. .non_periodic_out_mps = 64,
  118. .periodic_out_mps = 600,
  119. };
  120. #define FRAME_LIST_LEN USB_HAL_FRAME_LIST_LEN_32
  121. #define NUM_BUFFERS 2
  122. #define XFER_LIST_LEN_CTRL 3 //One descriptor for each stage
  123. #define XFER_LIST_LEN_BULK 2 //One descriptor for transfer, one to support an extra zero length packet
  124. #define XFER_LIST_LEN_INTR 32
  125. #define XFER_LIST_LEN_ISOC FRAME_LIST_LEN //Same length as the frame list makes it easier to schedule. Must be power of 2
  126. // ------------------------ Flags --------------------------
  127. /**
  128. * @brief Bit masks for the HCD to use in the URBs reserved_flags field
  129. *
  130. * The URB object has a reserved_flags member for host stack's internal use. The following flags will be set in
  131. * reserved_flags in order to keep track of state of an URB within the HCD.
  132. */
  133. #define URB_HCD_STATE_IDLE 0 //The URB is not enqueued in an HCD pipe
  134. #define URB_HCD_STATE_PENDING 1 //The URB is enqueued and pending execution
  135. #define URB_HCD_STATE_INFLIGHT 2 //The URB is currently in flight
  136. #define URB_HCD_STATE_DONE 3 //The URB has completed execution or is retired, and is waiting to be dequeued
  137. #define URB_HCD_STATE_SET(reserved_flags, state) (reserved_flags = (reserved_flags & ~URB_HCD_STATE_MASK) | state)
  138. #define URB_HCD_STATE_GET(reserved_flags) (reserved_flags & URB_HCD_STATE_MASK)
  139. // -------------------- Convenience ------------------------
  140. #define HCD_ENTER_CRITICAL_ISR() portENTER_CRITICAL_ISR(&hcd_lock)
  141. #define HCD_EXIT_CRITICAL_ISR() portEXIT_CRITICAL_ISR(&hcd_lock)
  142. #define HCD_ENTER_CRITICAL() portENTER_CRITICAL(&hcd_lock)
  143. #define HCD_EXIT_CRITICAL() portEXIT_CRITICAL(&hcd_lock)
  144. #define HCD_CHECK(cond, ret_val) ({ \
  145. if (!(cond)) { \
  146. return (ret_val); \
  147. } \
  148. })
  149. #define HCD_CHECK_FROM_CRIT(cond, ret_val) ({ \
  150. if (!(cond)) { \
  151. HCD_EXIT_CRITICAL(); \
  152. return ret_val; \
  153. } \
  154. })
  155. // ------------------------------------------------------ Types --------------------------------------------------------
  156. typedef struct pipe_obj pipe_t;
  157. typedef struct port_obj port_t;
  158. /**
  159. * @brief Object representing a single buffer of a pipe's multi buffer implementation
  160. */
  161. typedef struct {
  162. void *xfer_desc_list;
  163. urb_t *urb;
  164. union {
  165. struct {
  166. uint32_t data_stg_in: 1; //Data stage of the control transfer is IN
  167. uint32_t data_stg_skip: 1; //Control transfer has no data stage
  168. uint32_t cur_stg: 2; //Index of the current stage (e.g., 0 is setup stage, 2 is status stage)
  169. uint32_t reserved28: 28;
  170. } ctrl; //Control transfer related
  171. struct {
  172. uint32_t zero_len_packet: 1; //Bulk transfer should add a zero length packet at the end regardless
  173. uint32_t reserved31: 31;
  174. } bulk; //Bulk transfer related
  175. struct {
  176. uint32_t num_qtds: 8; //Number of transfer descriptors filled
  177. uint32_t reserved24: 24;
  178. } intr; //Interrupt transfer related
  179. struct {
  180. uint32_t num_qtds: 8; //Number of transfer descriptors filled (including NULL descriptors)
  181. uint32_t interval: 8; //Interval (in number of SOF i.e., ms)
  182. uint32_t start_idx: 8; //Index of the first transfer descriptor in the list
  183. uint32_t next_start_idx: 8; //Index for the first descriptor of the next buffer
  184. } isoc;
  185. uint32_t val;
  186. } flags;
  187. union {
  188. struct {
  189. uint32_t executing: 1; //The buffer is currently executing
  190. uint32_t was_canceled: 1; //Buffer was done due to a cancellation (i.e., a halt request)
  191. uint32_t reserved6: 6;
  192. uint32_t stop_idx: 8; //The descriptor index when the channel was halted
  193. hcd_pipe_event_t pipe_event: 8; //The pipe event when the buffer was done
  194. uint32_t reserved8: 8;
  195. };
  196. uint32_t val;
  197. } status_flags; //Status flags for the buffer
  198. } dma_buffer_block_t;
  199. /**
  200. * @brief Object representing a pipe in the HCD layer
  201. */
  202. struct pipe_obj {
  203. //URB queueing related
  204. TAILQ_HEAD(tailhead_urb_pending, urb_s) pending_urb_tailq;
  205. TAILQ_HEAD(tailhead_urb_done, urb_s) done_urb_tailq;
  206. int num_urb_pending;
  207. int num_urb_done;
  208. //Multi-buffer control
  209. dma_buffer_block_t *buffers[NUM_BUFFERS]; //Double buffering scheme
  210. union {
  211. struct {
  212. uint32_t buffer_num_to_fill: 2; //Number of buffers that can be filled
  213. uint32_t buffer_num_to_exec: 2; //Number of buffers that are filled and need to be executed
  214. uint32_t buffer_num_to_parse: 2;//Number of buffers completed execution and waiting to be parsed
  215. uint32_t reserved2: 2;
  216. uint32_t wr_idx: 1; //Index of the next buffer to fill. Bit width must allow NUM_BUFFERS to wrap automatically
  217. uint32_t rd_idx: 1; //Index of the current buffer in-flight. Bit width must allow NUM_BUFFERS to wrap automatically
  218. uint32_t fr_idx: 1; //Index of the next buffer to parse. Bit width must allow NUM_BUFFERS to wrap automatically
  219. uint32_t buffer_is_executing: 1;//One of the buffers is in flight
  220. uint32_t reserved20: 20;
  221. };
  222. uint32_t val;
  223. } multi_buffer_control;
  224. //HAL related
  225. usbh_hal_chan_t *chan_obj;
  226. usbh_hal_ep_char_t ep_char;
  227. //Port related
  228. port_t *port; //The port to which this pipe is routed through
  229. TAILQ_ENTRY(pipe_obj) tailq_entry; //TailQ entry for port's list of pipes
  230. //Pipe status/state/events related
  231. hcd_pipe_state_t state;
  232. hcd_pipe_event_t last_event;
  233. volatile TaskHandle_t task_waiting_pipe_notif; //Task handle used for internal pipe events. Set by waiter, cleared by notifier
  234. union {
  235. struct {
  236. uint32_t waiting_halt: 1;
  237. uint32_t pipe_cmd_processing: 1;
  238. uint32_t has_urb: 1; //Indicates there is at least one URB either pending, inflight, or done
  239. uint32_t persist: 1; //indicates that this pipe should persist through a run-time port reset
  240. uint32_t reset_lock: 1; //Indicates that this pipe is undergoing a run-time reset
  241. uint32_t reserved27: 27;
  242. };
  243. uint32_t val;
  244. } cs_flags;
  245. //Pipe callback and context
  246. hcd_pipe_callback_t callback;
  247. void *callback_arg;
  248. void *context;
  249. };
  250. /**
  251. * @brief Object representing a port in the HCD layer
  252. */
  253. struct port_obj {
  254. usbh_hal_context_t *hal;
  255. void *frame_list;
  256. //Pipes routed through this port
  257. TAILQ_HEAD(tailhead_pipes_idle, pipe_obj) pipes_idle_tailq;
  258. TAILQ_HEAD(tailhead_pipes_queued, pipe_obj) pipes_active_tailq;
  259. int num_pipes_idle;
  260. int num_pipes_queued;
  261. //Port status, state, and events
  262. hcd_port_state_t state;
  263. usb_speed_t speed;
  264. hcd_port_event_t last_event;
  265. volatile TaskHandle_t task_waiting_port_notif; //Task handle used for internal port events. Set by waiter, cleared by notifier
  266. union {
  267. struct {
  268. uint32_t event_pending: 1; //The port has an event that needs to be handled
  269. uint32_t event_processing: 1; //The port is current processing (handling) an event
  270. uint32_t cmd_processing: 1; //Used to indicate command handling is ongoing
  271. uint32_t disable_requested: 1;
  272. uint32_t conn_dev_ena: 1; //Used to indicate the port is connected to a device that has been reset
  273. uint32_t periodic_scheduling_enabled: 1;
  274. uint32_t reserved26: 26;
  275. };
  276. uint32_t val;
  277. } flags;
  278. bool initialized;
  279. //FIFO biasing related
  280. const usbh_hal_fifo_config_t *fifo_config;
  281. const fifo_mps_limits_t *fifo_mps_limits;
  282. //Port callback and context
  283. hcd_port_callback_t callback;
  284. void *callback_arg;
  285. SemaphoreHandle_t port_mux;
  286. void *context;
  287. };
  288. /**
  289. * @brief Object representing the HCD
  290. */
  291. typedef struct {
  292. //Ports (Hardware only has one)
  293. port_t *port_obj;
  294. intr_handle_t isr_hdl;
  295. } hcd_obj_t;
  296. static portMUX_TYPE hcd_lock = portMUX_INITIALIZER_UNLOCKED;
  297. static hcd_obj_t *s_hcd_obj = NULL; //Note: "s_" is for the static pointer
  298. // ------------------------------------------------- Forward Declare ---------------------------------------------------
  299. // ------------------- Buffer Control ----------------------
  300. /**
  301. * @brief Check if an inactive buffer can be filled with a pending URB
  302. *
  303. * @param pipe Pipe object
  304. * @return true There are one or more pending URBs, and the inactive buffer is yet to be filled
  305. * @return false Otherwise
  306. */
  307. static inline bool _buffer_can_fill(pipe_t *pipe)
  308. {
  309. //We can only fill if there are pending URBs and at least one unfilled buffer
  310. if (pipe->num_urb_pending > 0 && pipe->multi_buffer_control.buffer_num_to_fill > 0) {
  311. return true;
  312. } else {
  313. return false;
  314. }
  315. }
  316. /**
  317. * @brief Fill an empty buffer with
  318. *
  319. * This function will:
  320. * - Remove an URB from the pending tailq
  321. * - Fill that URB into the inactive buffer
  322. *
  323. * @note _buffer_can_fill() must return true before calling this function
  324. *
  325. * @param pipe Pipe object
  326. */
  327. static void _buffer_fill(pipe_t *pipe);
  328. /**
  329. * @brief Check if there are more filled buffers than can be executed
  330. *
  331. * @param pipe Pipe object
  332. * @return true There are more filled buffers to be executed
  333. * @return false No more buffers to execute
  334. */
  335. static inline bool _buffer_can_exec(pipe_t *pipe)
  336. {
  337. //We can only execute if there is not already a buffer executing and if there are filled buffers awaiting execution
  338. if (!pipe->multi_buffer_control.buffer_is_executing && pipe->multi_buffer_control.buffer_num_to_exec > 0) {
  339. return true;
  340. } else {
  341. return false;
  342. }
  343. }
  344. /**
  345. * @brief Execute the next filled buffer
  346. *
  347. * - Must have called _buffer_can_exec() before calling this function
  348. * - Will start the execution of the buffer
  349. *
  350. * @param pipe Pipe object
  351. */
  352. static void _buffer_exec(pipe_t *pipe);
  353. /**
  354. * @brief Check if a buffer as completed execution
  355. *
  356. * This should only be called after receiving a USBH_HAL_CHAN_EVENT_CPLT event to check if a buffer is actually
  357. * done.
  358. *
  359. * @param pipe Pipe object
  360. * @return true Buffer complete
  361. * @return false Buffer not complete
  362. */
  363. static inline bool _buffer_check_done(pipe_t *pipe)
  364. {
  365. if (pipe->ep_char.type != USB_PRIV_XFER_TYPE_CTRL) {
  366. return true;
  367. }
  368. //Only control transfers need to be continued
  369. dma_buffer_block_t *buffer_inflight = pipe->buffers[pipe->multi_buffer_control.rd_idx];
  370. return (buffer_inflight->flags.ctrl.cur_stg == 2);
  371. }
  372. /**
  373. * @brief Continue execution of a buffer
  374. *
  375. * This should only be called after checking if a buffer has completed execution using _buffer_check_done()
  376. *
  377. * @param pipe Pipe object
  378. */
  379. static void _buffer_exec_cont(pipe_t *pipe);
  380. /**
  381. * @brief Marks the last executed buffer as complete
  382. *
  383. * This should be called on a pipe that has confirmed that a buffer is completed via _buffer_check_done()
  384. *
  385. * @param pipe Pipe object
  386. * @param stop_idx Descriptor index when the buffer stopped execution
  387. * @param pipe_event Pipe event that caused the buffer to be complete. Use HCD_PIPE_EVENT_NONE for halt request of disconnections
  388. * @param canceled Whether the buffer was done due to a canceled (i.e., halt request). Must set pipe_event to HCD_PIPE_EVENT_NONE
  389. */
  390. static inline void _buffer_done(pipe_t *pipe, int stop_idx, hcd_pipe_event_t pipe_event, bool canceled)
  391. {
  392. //Store the stop_idx and pipe_event for later parsing
  393. dma_buffer_block_t *buffer_done = pipe->buffers[pipe->multi_buffer_control.rd_idx];
  394. buffer_done->status_flags.executing = 0;
  395. buffer_done->status_flags.was_canceled = canceled;
  396. buffer_done->status_flags.stop_idx = stop_idx;
  397. buffer_done->status_flags.pipe_event = pipe_event;
  398. pipe->multi_buffer_control.rd_idx++;
  399. pipe->multi_buffer_control.buffer_num_to_exec--;
  400. pipe->multi_buffer_control.buffer_num_to_parse++;
  401. pipe->multi_buffer_control.buffer_is_executing = 0;
  402. }
  403. /**
  404. * @brief Checks if a pipe has one or more completed buffers to parse
  405. *
  406. * @param pipe Pipe object
  407. * @return true There are one or more buffers to parse
  408. * @return false There are no more buffers to parse
  409. */
  410. static inline bool _buffer_can_parse(pipe_t *pipe)
  411. {
  412. if (pipe->multi_buffer_control.buffer_num_to_parse > 0) {
  413. return true;
  414. } else {
  415. return false;
  416. }
  417. }
  418. /**
  419. * @brief Parse a completed buffer
  420. *
  421. * This function will:
  422. * - Parse the results of an URB from a completed buffer
  423. * - Put the URB into the done tailq
  424. *
  425. * @note This function should only be called on the completion of a buffer
  426. *
  427. * @param pipe Pipe object
  428. * @param stop_idx (For INTR pipes only) The index of the descriptor that follows the last descriptor of the URB. Set to 0 otherwise
  429. */
  430. static void _buffer_parse(pipe_t *pipe);
  431. /**
  432. * @brief Marks all buffers pending execution as completed, then parses those buffers
  433. *
  434. * @note This should only be called on pipes do not have any currently executing buffers.
  435. *
  436. * @param pipe Pipe object
  437. * @param canceled Whether this flush is due to cancellation
  438. * @return true One or more buffers were flushed
  439. * @return false There were no buffers that needed to be flushed
  440. */
  441. static bool _buffer_flush_all(pipe_t *pipe, bool canceled);
  442. // ------------------------ Pipe ---------------------------
  443. /**
  444. * @brief Decode a HAL channel error to the corresponding pipe event
  445. *
  446. * @param chan_error The HAL channel error
  447. * @return hcd_pipe_event_t The corresponding pipe error event
  448. */
  449. static inline hcd_pipe_event_t pipe_decode_error_event(usbh_hal_chan_error_t chan_error);
  450. /**
  451. * @brief Halt a pipe
  452. *
  453. * - Attempts to halt a pipe. Pipe must be active in order to be halted
  454. * - If the underlying channel has an ongoing transfer, a halt will be requested, then the function will block until the
  455. * channel indicates it is halted
  456. * - If the channel is no on-going transfer, the pipe will simply be marked has halted (thus preventing any further URBs
  457. * from being enqueued)
  458. *
  459. * @note This function can block
  460. * @param pipe Pipe object
  461. * @return esp_err_t
  462. */
  463. static esp_err_t _pipe_cmd_halt(pipe_t *pipe);
  464. /**
  465. * @brief Flush a pipe
  466. *
  467. * - Flushing a pipe causes all of its pending URBs to be become done, thus allowing them to be dequeued
  468. * - The pipe must be halted in order to be flushed
  469. * - The pipe callback will be run if one or more URBs become done
  470. *
  471. * @param pipe Pipe object
  472. * @return esp_err_t
  473. */
  474. static esp_err_t _pipe_cmd_flush(pipe_t *pipe);
  475. /**
  476. * @brief Clear a pipe from its halt
  477. *
  478. * - Pipe must be halted in order to be cleared
  479. * - Clearing a pipe makes it active again
  480. * - If there are any enqueued URBs, they will executed
  481. *
  482. * @param pipe Pipe object
  483. * @return esp_err_t
  484. */
  485. static esp_err_t _pipe_cmd_clear(pipe_t *pipe);
  486. // ------------------------ Port ---------------------------
  487. /**
  488. * @brief Prepare persistent pipes for reset
  489. *
  490. * This function checks if all pipes are reset persistent and proceeds to free their underlying HAL channels for the
  491. * persistent pipes. This should be called before a run time reset
  492. *
  493. * @param port Port object
  494. * @return true All pipes are persistent and their channels are freed
  495. * @return false Not all pipes are persistent
  496. */
  497. static bool _port_persist_all_pipes(port_t *port);
  498. /**
  499. * @brief Recovers all persistent pipes after a reset
  500. *
  501. * This function will recover all persistent pipes after a reset and reallocate their underlying HAl channels. This
  502. * function should be called after a reset.
  503. *
  504. * @param port Port object
  505. */
  506. static void _port_recover_all_pipes(port_t *port);
  507. /**
  508. * @brief Checks if all pipes are in the halted state
  509. *
  510. * @param port Port object
  511. * @return true All pipes are halted
  512. * @return false Not all pipes are halted
  513. */
  514. static bool _port_check_all_pipes_halted(port_t *port);
  515. /**
  516. * @brief Debounce port after a connection or disconnection event
  517. *
  518. * This function should be called after a port connection or disconnect event. This function will execute a debounce
  519. * delay then check the actual connection/disconnections state.
  520. *
  521. * @note This function can block
  522. * @param port Port object
  523. * @return true A device is connected
  524. * @return false No device connected
  525. */
  526. static bool _port_debounce(port_t *port);
  527. /**
  528. * @brief Power ON the port
  529. *
  530. * @param port Port object
  531. * @return esp_err_t
  532. */
  533. static esp_err_t _port_cmd_power_on(port_t *port);
  534. /**
  535. * @brief Power OFF the port
  536. *
  537. * - If a device is currently connected, this function will cause a disconnect event
  538. *
  539. * @param port Port object
  540. * @return esp_err_t
  541. */
  542. static esp_err_t _port_cmd_power_off(port_t *port);
  543. /**
  544. * @brief Reset the port
  545. *
  546. * - This function issues a reset signal using the timings specified by the USB2.0 spec
  547. *
  548. * @note This function can block
  549. * @param port Port object
  550. * @return esp_err_t
  551. */
  552. static esp_err_t _port_cmd_reset(port_t *port);
  553. /**
  554. * @brief Suspend the port
  555. *
  556. * - Port must be enabled in order to to be suspended
  557. * - All pipes must be halted for the port to be suspended
  558. * - Suspending the port stops Keep Alive/SOF from being sent to the connected device
  559. *
  560. * @param port Port object
  561. * @return esp_err_t
  562. */
  563. static esp_err_t _port_cmd_bus_suspend(port_t *port);
  564. /**
  565. * @brief Resume the port
  566. *
  567. * - Port must be suspended in order to be resumed
  568. *
  569. * @note This function can block
  570. * @param port Port object
  571. * @return esp_err_t
  572. */
  573. static esp_err_t _port_cmd_bus_resume(port_t *port);
  574. /**
  575. * @brief Disable the port
  576. *
  577. * - All pipes must be halted for the port to be disabled
  578. * - The port must be enabled or suspended in order to be disabled
  579. *
  580. * @note This function can block
  581. * @param port Port object
  582. * @return esp_err_t
  583. */
  584. static esp_err_t _port_cmd_disable(port_t *port);
  585. // ----------------------- Events --------------------------
  586. /**
  587. * @brief Wait for an internal event from a port
  588. *
  589. * @note For each port, there can only be one thread/task waiting for an internal port event
  590. * @note This function is blocking (will exit and re-enter the critical section to do so)
  591. *
  592. * @param port Port object
  593. */
  594. static void _internal_port_event_wait(port_t *port);
  595. /**
  596. * @brief Notify (from an ISR context) the thread/task waiting for the internal port event
  597. *
  598. * @param port Port object
  599. * @return true A yield is required
  600. * @return false Whether a yield is required or not
  601. */
  602. static bool _internal_port_event_notify_from_isr(port_t *port);
  603. /**
  604. * @brief Wait for an internal event from a particular pipe
  605. *
  606. * @note For each pipe, there can only be one thread/task waiting for an internal port event
  607. * @note This function is blocking (will exit and re-enter the critical section to do so)
  608. *
  609. * @param pipe Pipe object
  610. */
  611. static void _internal_pipe_event_wait(pipe_t *pipe);
  612. /**
  613. * @brief Notify (from an ISR context) the thread/task waiting for an internal pipe event
  614. *
  615. * @param pipe Pipe object
  616. * @param from_isr Whether this is called from an ISR or not
  617. * @return true A yield is required
  618. * @return false Whether a yield is required or not. Always false when from_isr is also false
  619. */
  620. static bool _internal_pipe_event_notify(pipe_t *pipe, bool from_isr);
  621. // ----------------------------------------------- Interrupt Handling --------------------------------------------------
  622. // ------------------- Internal Event ----------------------
  623. static void _internal_port_event_wait(port_t *port)
  624. {
  625. //There must NOT be another thread/task already waiting for an internal event
  626. assert(port->task_waiting_port_notif == NULL);
  627. port->task_waiting_port_notif = xTaskGetCurrentTaskHandle();
  628. /* We need to loop as task notifications can come from anywhere. If we this
  629. was a port event notification, task_waiting_port_notif will have been cleared
  630. by the notifier. */
  631. while (port->task_waiting_port_notif != NULL) {
  632. HCD_EXIT_CRITICAL();
  633. //Wait to be notified from ISR
  634. ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  635. HCD_ENTER_CRITICAL();
  636. }
  637. }
  638. static bool _internal_port_event_notify_from_isr(port_t *port)
  639. {
  640. //There must be a thread/task waiting for an internal event
  641. assert(port->task_waiting_port_notif != NULL);
  642. TaskHandle_t task_to_unblock = port->task_waiting_port_notif;
  643. //Clear task_waiting_port_notif to indicate to the waiter that the unblock was indeed an port event notification
  644. port->task_waiting_port_notif = NULL;
  645. //Unblock the thread/task waiting for the notification
  646. BaseType_t xTaskWoken = pdFALSE;
  647. //Note: We don't exit the critical section to be atomic. vTaskNotifyGiveFromISR() doesn't block anyways
  648. vTaskNotifyGiveFromISR(task_to_unblock, &xTaskWoken);
  649. return (xTaskWoken == pdTRUE);
  650. }
  651. static void _internal_pipe_event_wait(pipe_t *pipe)
  652. {
  653. //There must NOT be another thread/task already waiting for an internal event
  654. assert(pipe->task_waiting_pipe_notif == NULL);
  655. pipe->task_waiting_pipe_notif = xTaskGetCurrentTaskHandle();
  656. /* We need to loop as task notifications can come from anywhere. If we this
  657. was a pipe event notification, task_waiting_pipe_notif will have been cleared
  658. by the notifier. */
  659. while (pipe->task_waiting_pipe_notif != NULL) {
  660. //Wait to be unblocked by notified
  661. HCD_EXIT_CRITICAL();
  662. ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  663. HCD_ENTER_CRITICAL();
  664. }
  665. }
  666. static bool _internal_pipe_event_notify(pipe_t *pipe, bool from_isr)
  667. {
  668. //There must be a thread/task waiting for an internal event
  669. assert(pipe->task_waiting_pipe_notif != NULL);
  670. TaskHandle_t task_to_unblock = pipe->task_waiting_pipe_notif;
  671. //Clear task_waiting_pipe_notif to indicate to the waiter that the unblock was indeed an pipe event notification
  672. pipe->task_waiting_pipe_notif = NULL;
  673. bool ret;
  674. if (from_isr) {
  675. BaseType_t xTaskWoken = pdFALSE;
  676. //Note: We don't exit the critical section to be atomic. vTaskNotifyGiveFromISR() doesn't block anyways
  677. //Unblock the thread/task waiting for the pipe notification
  678. vTaskNotifyGiveFromISR(task_to_unblock, &xTaskWoken);
  679. ret = (xTaskWoken == pdTRUE);
  680. } else {
  681. HCD_EXIT_CRITICAL();
  682. xTaskNotifyGive(task_to_unblock);
  683. HCD_ENTER_CRITICAL();
  684. ret = false;
  685. }
  686. return ret;
  687. }
  688. // ----------------- Interrupt Handlers --------------------
  689. /**
  690. * @brief Handle a HAL port interrupt and obtain the corresponding port event
  691. *
  692. * @param[in] port Port object
  693. * @param[in] hal_port_event The HAL port event
  694. * @param[out] yield Set to true if a yield is required as a result of handling the interrupt
  695. * @return hcd_port_event_t Returns a port event, or HCD_PORT_EVENT_NONE if no port event occurred
  696. */
  697. static hcd_port_event_t _intr_hdlr_hprt(port_t *port, usbh_hal_port_event_t hal_port_event, bool *yield)
  698. {
  699. hcd_port_event_t port_event = HCD_PORT_EVENT_NONE;
  700. switch (hal_port_event) {
  701. case USBH_HAL_PORT_EVENT_CONN: {
  702. //Don't update state immediately, we still need to debounce.
  703. port_event = HCD_PORT_EVENT_CONNECTION;
  704. break;
  705. }
  706. case USBH_HAL_PORT_EVENT_DISCONN: {
  707. port->state = HCD_PORT_STATE_RECOVERY;
  708. port_event = HCD_PORT_EVENT_DISCONNECTION;
  709. port->flags.conn_dev_ena = 0;
  710. break;
  711. }
  712. case USBH_HAL_PORT_EVENT_ENABLED: {
  713. usbh_hal_port_enable(port->hal); //Initialize remaining host port registers
  714. port->speed = (usbh_hal_port_get_conn_speed(port->hal) == USB_PRIV_SPEED_FULL) ? USB_SPEED_FULL : USB_SPEED_LOW;
  715. port->state = HCD_PORT_STATE_ENABLED;
  716. port->flags.conn_dev_ena = 1;
  717. //This was triggered by a command, so no event needs to be propagated.
  718. break;
  719. }
  720. case USBH_HAL_PORT_EVENT_DISABLED: {
  721. port->flags.conn_dev_ena = 0;
  722. //Disabled could be due to a disable request or reset request, or due to a port error
  723. if (port->state != HCD_PORT_STATE_RESETTING) { //Ignore the disable event if it's due to a reset request
  724. if (port->flags.disable_requested) {
  725. //Disabled by request (i.e. by port command). Generate an internal event
  726. port->state = HCD_PORT_STATE_DISABLED;
  727. port->flags.disable_requested = 0;
  728. *yield |= _internal_port_event_notify_from_isr(port);
  729. } else {
  730. //Disabled due to a port error
  731. port->state = HCD_PORT_STATE_RECOVERY;
  732. port_event = HCD_PORT_EVENT_ERROR;
  733. }
  734. }
  735. break;
  736. }
  737. case USBH_HAL_PORT_EVENT_OVRCUR:
  738. case USBH_HAL_PORT_EVENT_OVRCUR_CLR: { //Could occur if a quick overcurrent then clear happens
  739. if (port->state != HCD_PORT_STATE_NOT_POWERED) {
  740. //We need to power OFF the port to protect it
  741. usbh_hal_port_toggle_power(port->hal, false);
  742. port->state = HCD_PORT_STATE_RECOVERY;
  743. port_event = HCD_PORT_EVENT_OVERCURRENT;
  744. }
  745. port->flags.conn_dev_ena = 0;
  746. break;
  747. }
  748. default: {
  749. abort();
  750. break;
  751. }
  752. }
  753. return port_event;
  754. }
  755. /**
  756. * @brief Handles a HAL channel interrupt
  757. *
  758. * This function should be called on a HAL channel when it has an interrupt. Most HAL channel events will correspond to
  759. * to a pipe event, but not always. This function will store the pipe event and return a pipe object pointer if a pipe
  760. * event occurred, or return NULL otherwise.
  761. *
  762. * @param[in] chan_obj Pointer to HAL channel object with interrupt
  763. * @param[out] yield Set to true if a yield is required as a result of handling the interrupt
  764. * @return hcd_pipe_event_t The pipe event
  765. */
  766. static hcd_pipe_event_t _intr_hdlr_chan(pipe_t *pipe, usbh_hal_chan_t *chan_obj, bool *yield)
  767. {
  768. usbh_hal_chan_event_t chan_event = usbh_hal_chan_decode_intr(chan_obj);
  769. hcd_pipe_event_t event = HCD_PIPE_EVENT_NONE;
  770. switch (chan_event) {
  771. case USBH_HAL_CHAN_EVENT_CPLT: {
  772. if (!_buffer_check_done(pipe)) {
  773. _buffer_exec_cont(pipe);
  774. break;
  775. }
  776. pipe->last_event = HCD_PIPE_EVENT_URB_DONE;
  777. event = pipe->last_event;
  778. //Mark the buffer as done
  779. int stop_idx = usbh_hal_chan_get_qtd_idx(chan_obj);
  780. _buffer_done(pipe, stop_idx, pipe->last_event, false);
  781. //First check if there is another buffer we can execute. But we only want to execute if there's still a valid device
  782. if (_buffer_can_exec(pipe) && pipe->port->flags.conn_dev_ena) {
  783. //If the next buffer is filled and ready to execute, execute it
  784. _buffer_exec(pipe);
  785. }
  786. //Handle the previously done buffer
  787. _buffer_parse(pipe);
  788. //Check to see if we can fill another buffer. But we only want to fill if there is still a valid device
  789. if (_buffer_can_fill(pipe) && pipe->port->flags.conn_dev_ena) {
  790. //Now that we've parsed a buffer, see if another URB can be filled in its place
  791. _buffer_fill(pipe);
  792. }
  793. break;
  794. }
  795. case USBH_HAL_CHAN_EVENT_ERROR: {
  796. //Get and store the pipe error event
  797. usbh_hal_chan_error_t chan_error = usbh_hal_chan_get_error(chan_obj);
  798. pipe->last_event = pipe_decode_error_event(chan_error);
  799. event = pipe->last_event;
  800. pipe->state = HCD_PIPE_STATE_HALTED;
  801. //Mark the buffer as done with an error
  802. int stop_idx = usbh_hal_chan_get_qtd_idx(chan_obj);
  803. _buffer_done(pipe, stop_idx, pipe->last_event, false);
  804. //Parse the buffer
  805. _buffer_parse(pipe);
  806. break;
  807. }
  808. case USBH_HAL_CHAN_EVENT_HALT_REQ: {
  809. assert(pipe->cs_flags.waiting_halt);
  810. //We've halted a transfer, so we need to trigger the pipe callback
  811. pipe->last_event = HCD_PIPE_EVENT_URB_DONE;
  812. event = pipe->last_event;
  813. //Halt request event is triggered when packet is successful completed. But just treat all halted transfers as errors
  814. pipe->state = HCD_PIPE_STATE_HALTED;
  815. int stop_idx = usbh_hal_chan_get_qtd_idx(chan_obj);
  816. _buffer_done(pipe, stop_idx, HCD_PIPE_EVENT_NONE, true);
  817. //Parse the buffer
  818. _buffer_parse(pipe);
  819. //Notify the task waiting for the pipe halt
  820. *yield |= _internal_pipe_event_notify(pipe, true);
  821. break;
  822. }
  823. case USBH_HAL_CHAN_EVENT_NONE: {
  824. break; //Nothing to do
  825. }
  826. default:
  827. abort();
  828. break;
  829. }
  830. return event;
  831. }
  832. /**
  833. * @brief Main interrupt handler
  834. *
  835. * - Handle all HPRT (Host Port) related interrupts first as they may change the
  836. * state of the driver (e.g., a disconnect event)
  837. * - If any channels (pipes) have pending interrupts, handle them one by one
  838. * - The HCD has not blocking functions, so the user's ISR callback is run to
  839. * allow the users to send whatever OS primitives they need.
  840. *
  841. * @param arg Interrupt handler argument
  842. */
  843. static void intr_hdlr_main(void *arg)
  844. {
  845. port_t *port = (port_t *) arg;
  846. bool yield = false;
  847. HCD_ENTER_CRITICAL_ISR();
  848. usbh_hal_port_event_t hal_port_evt = usbh_hal_decode_intr(port->hal);
  849. if (hal_port_evt == USBH_HAL_PORT_EVENT_CHAN) {
  850. //Channel event. Cycle through each pending channel
  851. usbh_hal_chan_t *chan_obj = usbh_hal_get_chan_pending_intr(port->hal);
  852. while (chan_obj != NULL) {
  853. pipe_t *pipe = (pipe_t *)usbh_hal_chan_get_context(chan_obj);
  854. hcd_pipe_event_t event = _intr_hdlr_chan(pipe, chan_obj, &yield);
  855. //Run callback if a pipe event has occurred and the pipe also has a callback
  856. if (event != HCD_PIPE_EVENT_NONE && pipe->callback != NULL) {
  857. HCD_EXIT_CRITICAL_ISR();
  858. yield |= pipe->callback((hcd_pipe_handle_t)pipe, event, pipe->callback_arg, true);
  859. HCD_ENTER_CRITICAL_ISR();
  860. }
  861. //Check for more channels with pending interrupts. Returns NULL if there are no more
  862. chan_obj = usbh_hal_get_chan_pending_intr(port->hal);
  863. }
  864. } else if (hal_port_evt != USBH_HAL_PORT_EVENT_NONE) { //Port event
  865. hcd_port_event_t port_event = _intr_hdlr_hprt(port, hal_port_evt, &yield);
  866. if (port_event != HCD_PORT_EVENT_NONE) {
  867. port->last_event = port_event;
  868. port->flags.event_pending = 1;
  869. if (port->callback != NULL) {
  870. HCD_EXIT_CRITICAL_ISR();
  871. yield |= port->callback((hcd_port_handle_t)port, port_event, port->callback_arg, true);
  872. HCD_ENTER_CRITICAL_ISR();
  873. }
  874. }
  875. }
  876. HCD_EXIT_CRITICAL_ISR();
  877. if (yield) {
  878. portYIELD_FROM_ISR();
  879. }
  880. }
  881. // --------------------------------------------- Host Controller Driver ------------------------------------------------
  882. static port_t *port_obj_alloc(void)
  883. {
  884. port_t *port = calloc(1, sizeof(port_t));
  885. usbh_hal_context_t *hal = malloc(sizeof(usbh_hal_context_t));
  886. void *frame_list = heap_caps_aligned_calloc(USBH_HAL_FRAME_LIST_MEM_ALIGN, FRAME_LIST_LEN,sizeof(uint32_t), MALLOC_CAP_DMA);
  887. SemaphoreHandle_t port_mux = xSemaphoreCreateMutex();
  888. if (port == NULL || hal == NULL || frame_list == NULL || port_mux == NULL) {
  889. free(port);
  890. free(hal);
  891. free(frame_list);
  892. if (port_mux != NULL) {
  893. vSemaphoreDelete(port_mux);
  894. }
  895. return NULL;
  896. }
  897. port->hal = hal;
  898. port->frame_list = frame_list;
  899. port->port_mux = port_mux;
  900. return port;
  901. }
  902. static void port_obj_free(port_t *port)
  903. {
  904. if (port == NULL) {
  905. return;
  906. }
  907. vSemaphoreDelete(port->port_mux);
  908. free(port->frame_list);
  909. free(port->hal);
  910. free(port);
  911. }
  912. // ----------------------- Public --------------------------
  913. esp_err_t hcd_install(const hcd_config_t *config)
  914. {
  915. HCD_ENTER_CRITICAL();
  916. HCD_CHECK_FROM_CRIT(s_hcd_obj == NULL, ESP_ERR_INVALID_STATE);
  917. HCD_EXIT_CRITICAL();
  918. esp_err_t err_ret;
  919. //Allocate memory and resources for driver object and all port objects
  920. hcd_obj_t *p_hcd_obj_dmy = calloc(1, sizeof(hcd_obj_t));
  921. if (p_hcd_obj_dmy == NULL) {
  922. return ESP_ERR_NO_MEM;
  923. }
  924. //Allocate resources for each port (there's only one)
  925. p_hcd_obj_dmy->port_obj = port_obj_alloc();
  926. esp_err_t intr_alloc_ret = esp_intr_alloc(ETS_USB_INTR_SOURCE,
  927. config->intr_flags | ESP_INTR_FLAG_INTRDISABLED, //The interrupt must be disabled until the port is initialized
  928. intr_hdlr_main,
  929. (void *)p_hcd_obj_dmy->port_obj,
  930. &p_hcd_obj_dmy->isr_hdl);
  931. if (p_hcd_obj_dmy->port_obj == NULL) {
  932. err_ret = ESP_ERR_NO_MEM;
  933. }
  934. if (intr_alloc_ret != ESP_OK) {
  935. err_ret = intr_alloc_ret;
  936. goto err;
  937. }
  938. HCD_ENTER_CRITICAL();
  939. if (s_hcd_obj != NULL) {
  940. HCD_EXIT_CRITICAL();
  941. err_ret = ESP_ERR_INVALID_STATE;
  942. goto err;
  943. }
  944. s_hcd_obj = p_hcd_obj_dmy;
  945. //Set HW prerequisites for each port (there's only one)
  946. periph_module_enable(PERIPH_USB_MODULE);
  947. periph_module_reset(PERIPH_USB_MODULE);
  948. /*
  949. Configure GPIOS for Host mode operation using internal PHY
  950. - Forces ID to GND for A side
  951. - Forces B Valid to GND as we are A side host
  952. - Forces VBUS Valid to HIGH
  953. - Forces A Valid to HIGH
  954. */
  955. esp_rom_gpio_connect_in_signal(GPIO_MATRIX_CONST_ZERO_INPUT, USB_OTG_IDDIG_IN_IDX, false);
  956. esp_rom_gpio_connect_in_signal(GPIO_MATRIX_CONST_ZERO_INPUT, USB_SRP_BVALID_IN_IDX, false);
  957. esp_rom_gpio_connect_in_signal(GPIO_MATRIX_CONST_ONE_INPUT, USB_OTG_VBUSVALID_IN_IDX, false);
  958. esp_rom_gpio_connect_in_signal(GPIO_MATRIX_CONST_ONE_INPUT, USB_OTG_AVALID_IN_IDX, false);
  959. HCD_EXIT_CRITICAL();
  960. return ESP_OK;
  961. err:
  962. if (intr_alloc_ret == ESP_OK) {
  963. esp_intr_free(p_hcd_obj_dmy->isr_hdl);
  964. }
  965. port_obj_free(p_hcd_obj_dmy->port_obj);
  966. free(p_hcd_obj_dmy);
  967. return err_ret;
  968. }
  969. esp_err_t hcd_uninstall(void)
  970. {
  971. HCD_ENTER_CRITICAL();
  972. //Check that all ports have been disabled (there's only one port)
  973. if (s_hcd_obj == NULL || s_hcd_obj->port_obj->initialized) {
  974. HCD_EXIT_CRITICAL();
  975. return ESP_ERR_INVALID_STATE;
  976. }
  977. periph_module_disable(PERIPH_USB_MODULE);
  978. hcd_obj_t *p_hcd_obj_dmy = s_hcd_obj;
  979. s_hcd_obj = NULL;
  980. HCD_EXIT_CRITICAL();
  981. //Free resources
  982. port_obj_free(p_hcd_obj_dmy->port_obj);
  983. esp_intr_free(p_hcd_obj_dmy->isr_hdl);
  984. free(p_hcd_obj_dmy);
  985. return ESP_OK;
  986. }
  987. // ------------------------------------------------------ Port ---------------------------------------------------------
  988. // ----------------------- Helpers -------------------------
  989. static bool _port_persist_all_pipes(port_t *port)
  990. {
  991. if (port->num_pipes_queued > 0) {
  992. //All pipes must be idle before we run-time reset
  993. return false;
  994. }
  995. bool all_persist = true;
  996. pipe_t *pipe;
  997. //Check that each pipe is persistent
  998. TAILQ_FOREACH(pipe, &port->pipes_idle_tailq, tailq_entry) {
  999. if (!pipe->cs_flags.persist) {
  1000. all_persist = false;
  1001. break;
  1002. }
  1003. }
  1004. if (!all_persist) {
  1005. //At least one pipe is not persistent. All pipes must be freed or made persistent before we can reset
  1006. return false;
  1007. }
  1008. TAILQ_FOREACH(pipe, &port->pipes_idle_tailq, tailq_entry) {
  1009. pipe->cs_flags.reset_lock = 1;
  1010. usbh_hal_chan_free(port->hal, pipe->chan_obj);
  1011. }
  1012. return true;
  1013. }
  1014. static void _port_recover_all_pipes(port_t *port)
  1015. {
  1016. pipe_t *pipe;
  1017. TAILQ_FOREACH(pipe, &port->pipes_idle_tailq, tailq_entry) {
  1018. pipe->cs_flags.persist = 0;
  1019. pipe->cs_flags.reset_lock = 0;
  1020. usbh_hal_chan_alloc(port->hal, pipe->chan_obj, (void *)pipe);
  1021. usbh_hal_chan_set_ep_char(port->hal, pipe->chan_obj, &pipe->ep_char);
  1022. }
  1023. }
  1024. static bool _port_check_all_pipes_halted(port_t *port)
  1025. {
  1026. bool all_halted = true;
  1027. pipe_t *pipe;
  1028. TAILQ_FOREACH(pipe, &port->pipes_active_tailq, tailq_entry) {
  1029. if (pipe->state != HCD_PIPE_STATE_HALTED) {
  1030. all_halted = false;
  1031. break;
  1032. }
  1033. }
  1034. TAILQ_FOREACH(pipe, &port->pipes_idle_tailq, tailq_entry) {
  1035. if (pipe->state != HCD_PIPE_STATE_HALTED) {
  1036. all_halted = false;
  1037. break;
  1038. }
  1039. }
  1040. return all_halted;
  1041. }
  1042. static bool _port_debounce(port_t *port)
  1043. {
  1044. if (port->state == HCD_PORT_STATE_NOT_POWERED) {
  1045. //Disconnect event due to power off, no need to debounce or update port state.
  1046. return false;
  1047. }
  1048. HCD_EXIT_CRITICAL();
  1049. vTaskDelay(pdMS_TO_TICKS(DEBOUNCE_DELAY_MS));
  1050. HCD_ENTER_CRITICAL();
  1051. //Check the post-debounce state of the bus (i.e., whether it's actually connected/disconnected)
  1052. bool is_connected = usbh_hal_port_check_if_connected(port->hal);
  1053. if (is_connected) {
  1054. port->state = HCD_PORT_STATE_DISABLED;
  1055. } else {
  1056. port->state = HCD_PORT_STATE_DISCONNECTED;
  1057. }
  1058. //Disable debounce lock
  1059. usbh_hal_disable_debounce_lock(port->hal);
  1060. return is_connected;
  1061. }
  1062. // ---------------------- Commands -------------------------
  1063. static esp_err_t _port_cmd_power_on(port_t *port)
  1064. {
  1065. esp_err_t ret;
  1066. //Port can only be powered on if it's currently unpowered
  1067. if (port->state == HCD_PORT_STATE_NOT_POWERED) {
  1068. port->state = HCD_PORT_STATE_DISCONNECTED;
  1069. usbh_hal_port_init(port->hal);
  1070. usbh_hal_port_toggle_power(port->hal, true);
  1071. ret = ESP_OK;
  1072. } else {
  1073. ret = ESP_ERR_INVALID_STATE;
  1074. }
  1075. return ret;
  1076. }
  1077. static esp_err_t _port_cmd_power_off(port_t *port)
  1078. {
  1079. esp_err_t ret;
  1080. //Port can only be unpowered if already powered
  1081. if (port->state != HCD_PORT_STATE_NOT_POWERED) {
  1082. port->state = HCD_PORT_STATE_NOT_POWERED;
  1083. usbh_hal_port_deinit(port->hal);
  1084. usbh_hal_port_toggle_power(port->hal, false);
  1085. //If a device is currently connected, this should trigger a disconnect event
  1086. ret = ESP_OK;
  1087. } else {
  1088. ret = ESP_ERR_INVALID_STATE;
  1089. }
  1090. return ret;
  1091. }
  1092. static esp_err_t _port_cmd_reset(port_t *port)
  1093. {
  1094. esp_err_t ret;
  1095. //Port can only a reset when it is in the enabled or disabled states (in case of new connection)
  1096. if (port->state != HCD_PORT_STATE_ENABLED && port->state != HCD_PORT_STATE_DISABLED) {
  1097. ret = ESP_ERR_INVALID_STATE;
  1098. goto exit;
  1099. }
  1100. bool is_runtime_reset = (port->state == HCD_PORT_STATE_ENABLED) ? true : false;
  1101. if (is_runtime_reset && !_port_persist_all_pipes(port)) {
  1102. //If this is a run time reset, check all pipes that are still allocated can persist the reset
  1103. ret = ESP_ERR_INVALID_STATE;
  1104. goto exit;
  1105. }
  1106. //All pipes (if any_) are guaranteed to be persistent at this point. Proceed to resetting the bus
  1107. port->state = HCD_PORT_STATE_RESETTING;
  1108. //Put and hold the bus in the reset state. If the port was previously enabled, a disabled event will occur after this
  1109. usbh_hal_port_toggle_reset(port->hal, true);
  1110. HCD_EXIT_CRITICAL();
  1111. vTaskDelay(pdMS_TO_TICKS(RESET_HOLD_MS));
  1112. HCD_ENTER_CRITICAL();
  1113. if (port->state != HCD_PORT_STATE_RESETTING) {
  1114. //The port state has unexpectedly changed
  1115. ret = ESP_ERR_INVALID_RESPONSE;
  1116. goto bailout;
  1117. }
  1118. //Return the bus to the idle state and hold it for the required reset recovery time. Port enabled event should occur
  1119. usbh_hal_port_toggle_reset(port->hal, false);
  1120. HCD_EXIT_CRITICAL();
  1121. vTaskDelay(pdMS_TO_TICKS(RESET_RECOVERY_MS));
  1122. HCD_ENTER_CRITICAL();
  1123. if (port->state != HCD_PORT_STATE_ENABLED || !port->flags.conn_dev_ena) {
  1124. //The port state has unexpectedly changed
  1125. ret = ESP_ERR_INVALID_RESPONSE;
  1126. goto bailout;
  1127. }
  1128. //Set FIFO sizes based on the selected biasing
  1129. usbh_hal_set_fifo_size(port->hal, port->fifo_config);
  1130. //We start periodic scheduling only after a RESET command since SOFs only start after a reset
  1131. usbh_hal_port_set_frame_list(port->hal, port->frame_list, FRAME_LIST_LEN);
  1132. usbh_hal_port_periodic_enable(port->hal);
  1133. ret = ESP_OK;
  1134. bailout:
  1135. if (is_runtime_reset) {
  1136. _port_recover_all_pipes(port);
  1137. }
  1138. exit:
  1139. return ret;
  1140. }
  1141. static esp_err_t _port_cmd_bus_suspend(port_t *port)
  1142. {
  1143. esp_err_t ret;
  1144. //Port must have been previously enabled, and all pipes must already be halted
  1145. if (port->state == HCD_PORT_STATE_ENABLED && !_port_check_all_pipes_halted(port)) {
  1146. ret = ESP_ERR_INVALID_STATE;
  1147. goto exit;
  1148. }
  1149. //All pipes are guaranteed halted at this point. Proceed to suspend the port
  1150. usbh_hal_port_suspend(port->hal);
  1151. port->state = HCD_PORT_STATE_SUSPENDED;
  1152. ret = ESP_OK;
  1153. exit:
  1154. return ret;
  1155. }
  1156. static esp_err_t _port_cmd_bus_resume(port_t *port)
  1157. {
  1158. esp_err_t ret;
  1159. //Port can only be resumed if it was previously suspended
  1160. if (port->state != HCD_PORT_STATE_SUSPENDED) {
  1161. ret = ESP_ERR_INVALID_STATE;
  1162. goto exit;
  1163. }
  1164. //Put and hold the bus in the K state.
  1165. usbh_hal_port_toggle_resume(port->hal, true);
  1166. port->state = HCD_PORT_STATE_RESUMING;
  1167. HCD_EXIT_CRITICAL();
  1168. vTaskDelay(pdMS_TO_TICKS(RESUME_HOLD_MS));
  1169. HCD_ENTER_CRITICAL();
  1170. //Return and hold the bus to the J state (as port of the LS EOP)
  1171. usbh_hal_port_toggle_resume(port->hal, false);
  1172. if (port->state != HCD_PORT_STATE_RESUMING || !port->flags.conn_dev_ena) {
  1173. //Port state unexpectedly changed
  1174. ret = ESP_ERR_INVALID_RESPONSE;
  1175. goto exit;
  1176. }
  1177. HCD_EXIT_CRITICAL();
  1178. vTaskDelay(pdMS_TO_TICKS(RESUME_RECOVERY_MS));
  1179. HCD_ENTER_CRITICAL();
  1180. if (port->state != HCD_PORT_STATE_RESUMING || !port->flags.conn_dev_ena) {
  1181. //Port state unexpectedly changed
  1182. ret = ESP_ERR_INVALID_RESPONSE;
  1183. goto exit;
  1184. }
  1185. port->state = HCD_PORT_STATE_ENABLED;
  1186. ret = ESP_OK;
  1187. exit:
  1188. return ret;
  1189. }
  1190. static esp_err_t _port_cmd_disable(port_t *port)
  1191. {
  1192. esp_err_t ret;
  1193. if (port->state != HCD_PORT_STATE_ENABLED && port->state != HCD_PORT_STATE_SUSPENDED) {
  1194. ret = ESP_ERR_INVALID_STATE;
  1195. goto exit;
  1196. }
  1197. //All pipes must be halted before disabling the port
  1198. if (!_port_check_all_pipes_halted(port)){
  1199. ret = ESP_ERR_INVALID_STATE;
  1200. goto exit;
  1201. }
  1202. //All pipes are guaranteed to be halted or freed at this point. Proceed to disable the port
  1203. port->flags.disable_requested = 1;
  1204. usbh_hal_port_disable(port->hal);
  1205. _internal_port_event_wait(port);
  1206. if (port->state != HCD_PORT_STATE_DISABLED) {
  1207. //Port state unexpectedly changed
  1208. ret = ESP_ERR_INVALID_RESPONSE;
  1209. goto exit;
  1210. }
  1211. ret = ESP_OK;
  1212. exit:
  1213. return ret;
  1214. }
  1215. // ----------------------- Public --------------------------
  1216. esp_err_t hcd_port_init(int port_number, const hcd_port_config_t *port_config, hcd_port_handle_t *port_hdl)
  1217. {
  1218. HCD_CHECK(port_number > 0 && port_config != NULL && port_hdl != NULL, ESP_ERR_INVALID_ARG);
  1219. HCD_CHECK(port_number <= NUM_PORTS, ESP_ERR_NOT_FOUND);
  1220. //Get a pointer to the correct FIFO bias constant values
  1221. const usbh_hal_fifo_config_t *fifo_config;
  1222. const fifo_mps_limits_t *mps_limits;
  1223. switch (port_config->fifo_bias) {
  1224. case HCD_PORT_FIFO_BIAS_BALANCED:
  1225. fifo_config = &fifo_config_default;
  1226. mps_limits = &mps_limits_default;
  1227. break;
  1228. case HCD_PORT_FIFO_BIAS_RX:
  1229. fifo_config = &fifo_config_bias_rx;
  1230. mps_limits = &mps_limits_bias_rx;
  1231. break;
  1232. case HCD_PORT_FIFO_BIAS_PTX:
  1233. fifo_config = &fifo_config_bias_ptx;
  1234. mps_limits = &mps_limits_bias_ptx;
  1235. break;
  1236. default:
  1237. fifo_config = NULL;
  1238. mps_limits = NULL;
  1239. abort();
  1240. break;
  1241. }
  1242. HCD_ENTER_CRITICAL();
  1243. HCD_CHECK_FROM_CRIT(s_hcd_obj != NULL && !s_hcd_obj->port_obj->initialized, ESP_ERR_INVALID_STATE);
  1244. //Port object memory and resources (such as the mutex) already be allocated. Just need to initialize necessary fields only
  1245. port_t *port_obj = s_hcd_obj->port_obj;
  1246. TAILQ_INIT(&port_obj->pipes_idle_tailq);
  1247. TAILQ_INIT(&port_obj->pipes_active_tailq);
  1248. port_obj->state = HCD_PORT_STATE_NOT_POWERED;
  1249. port_obj->last_event = HCD_PORT_EVENT_NONE;
  1250. port_obj->fifo_config = fifo_config;
  1251. port_obj->fifo_mps_limits = mps_limits;
  1252. port_obj->callback = port_config->callback;
  1253. port_obj->callback_arg = port_config->callback_arg;
  1254. port_obj->context = port_config->context;
  1255. usbh_hal_init(port_obj->hal);
  1256. port_obj->initialized = true;
  1257. //Clear the frame list. We set the frame list register and enable periodic scheduling after a successful reset
  1258. memset(port_obj->frame_list, 0, FRAME_LIST_LEN * sizeof(uint32_t));
  1259. esp_intr_enable(s_hcd_obj->isr_hdl);
  1260. *port_hdl = (hcd_port_handle_t)port_obj;
  1261. HCD_EXIT_CRITICAL();
  1262. vTaskDelay(pdMS_TO_TICKS(INIT_DELAY_MS)); //Need a short delay before host mode takes effect
  1263. return ESP_OK;
  1264. }
  1265. esp_err_t hcd_port_deinit(hcd_port_handle_t port_hdl)
  1266. {
  1267. port_t *port = (port_t *)port_hdl;
  1268. HCD_ENTER_CRITICAL();
  1269. HCD_CHECK_FROM_CRIT(s_hcd_obj != NULL && port->initialized
  1270. && port->num_pipes_idle == 0 && port->num_pipes_queued == 0
  1271. && (port->state == HCD_PORT_STATE_NOT_POWERED || port->state == HCD_PORT_STATE_RECOVERY)
  1272. && port->task_waiting_port_notif == NULL,
  1273. ESP_ERR_INVALID_STATE);
  1274. port->initialized = false;
  1275. esp_intr_disable(s_hcd_obj->isr_hdl);
  1276. usbh_hal_deinit(port->hal);
  1277. HCD_EXIT_CRITICAL();
  1278. return ESP_OK;
  1279. }
  1280. esp_err_t hcd_port_command(hcd_port_handle_t port_hdl, hcd_port_cmd_t command)
  1281. {
  1282. esp_err_t ret = ESP_ERR_INVALID_STATE;
  1283. port_t *port = (port_t *)port_hdl;
  1284. xSemaphoreTake(port->port_mux, portMAX_DELAY);
  1285. HCD_ENTER_CRITICAL();
  1286. if (port->initialized && !port->flags.event_pending) { //Port events need to be handled first before issuing a command
  1287. port->flags.cmd_processing = 1;
  1288. switch (command) {
  1289. case HCD_PORT_CMD_POWER_ON: {
  1290. ret = _port_cmd_power_on(port);
  1291. break;
  1292. }
  1293. case HCD_PORT_CMD_POWER_OFF: {
  1294. ret = _port_cmd_power_off(port);
  1295. break;
  1296. }
  1297. case HCD_PORT_CMD_RESET: {
  1298. ret = _port_cmd_reset(port);
  1299. break;
  1300. }
  1301. case HCD_PORT_CMD_SUSPEND: {
  1302. ret = _port_cmd_bus_suspend(port);
  1303. break;
  1304. }
  1305. case HCD_PORT_CMD_RESUME: {
  1306. ret = _port_cmd_bus_resume(port);
  1307. break;
  1308. }
  1309. case HCD_PORT_CMD_DISABLE: {
  1310. ret = _port_cmd_disable(port);
  1311. break;
  1312. }
  1313. }
  1314. port->flags.cmd_processing = 0;
  1315. }
  1316. HCD_EXIT_CRITICAL();
  1317. xSemaphoreGive(port->port_mux);
  1318. return ret;
  1319. }
  1320. hcd_port_state_t hcd_port_get_state(hcd_port_handle_t port_hdl)
  1321. {
  1322. port_t *port = (port_t *)port_hdl;
  1323. hcd_port_state_t ret;
  1324. HCD_ENTER_CRITICAL();
  1325. ret = port->state;
  1326. HCD_EXIT_CRITICAL();
  1327. return ret;
  1328. }
  1329. esp_err_t hcd_port_get_speed(hcd_port_handle_t port_hdl, usb_speed_t *speed)
  1330. {
  1331. port_t *port = (port_t *)port_hdl;
  1332. HCD_CHECK(speed != NULL, ESP_ERR_INVALID_ARG);
  1333. HCD_ENTER_CRITICAL();
  1334. //Device speed is only valid if there is device connected to the port that has been reset
  1335. HCD_CHECK_FROM_CRIT(port->flags.conn_dev_ena, ESP_ERR_INVALID_STATE);
  1336. usb_priv_speed_t hal_speed = usbh_hal_port_get_conn_speed(port->hal);
  1337. if (hal_speed == USB_PRIV_SPEED_FULL) {
  1338. *speed = USB_SPEED_FULL;
  1339. } else {
  1340. *speed = USB_SPEED_LOW;
  1341. }
  1342. HCD_EXIT_CRITICAL();
  1343. return ESP_OK;
  1344. }
  1345. hcd_port_event_t hcd_port_handle_event(hcd_port_handle_t port_hdl)
  1346. {
  1347. port_t *port = (port_t *)port_hdl;
  1348. hcd_port_event_t ret = HCD_PORT_EVENT_NONE;
  1349. xSemaphoreTake(port->port_mux, portMAX_DELAY);
  1350. HCD_ENTER_CRITICAL();
  1351. if (port->initialized && port->flags.event_pending) {
  1352. port->flags.event_pending = 0;
  1353. port->flags.event_processing = 1;
  1354. ret = port->last_event;
  1355. switch (ret) {
  1356. case HCD_PORT_EVENT_CONNECTION: {
  1357. if (_port_debounce(port)) {
  1358. ret = HCD_PORT_EVENT_CONNECTION;
  1359. }
  1360. break;
  1361. }
  1362. case HCD_PORT_EVENT_DISCONNECTION:
  1363. case HCD_PORT_EVENT_ERROR:
  1364. case HCD_PORT_EVENT_OVERCURRENT: {
  1365. break;
  1366. }
  1367. default: {
  1368. break;
  1369. }
  1370. }
  1371. port->flags.event_processing = 0;
  1372. } else {
  1373. ret = HCD_PORT_EVENT_NONE;
  1374. }
  1375. HCD_EXIT_CRITICAL();
  1376. xSemaphoreGive(port->port_mux);
  1377. return ret;
  1378. }
  1379. esp_err_t hcd_port_recover(hcd_port_handle_t port_hdl)
  1380. {
  1381. port_t *port = (port_t *)port_hdl;
  1382. HCD_ENTER_CRITICAL();
  1383. HCD_CHECK_FROM_CRIT(s_hcd_obj != NULL && port->initialized && port->state == HCD_PORT_STATE_RECOVERY
  1384. && port->num_pipes_idle == 0 && port->num_pipes_queued == 0
  1385. && port->flags.val == 0 && port->task_waiting_port_notif == NULL,
  1386. ESP_ERR_INVALID_STATE);
  1387. //We are about to do a soft reset on the peripheral. Disable the peripheral throughout
  1388. esp_intr_disable(s_hcd_obj->isr_hdl);
  1389. usbh_hal_core_soft_reset(port->hal);
  1390. port->state = HCD_PORT_STATE_NOT_POWERED;
  1391. port->last_event = HCD_PORT_EVENT_NONE;
  1392. port->flags.val = 0;
  1393. //Soft reset wipes all registers so we need to reinitialize the HAL
  1394. usbh_hal_init(port->hal);
  1395. //Clear the frame list. We set the frame list register and enable periodic scheduling after a successful reset
  1396. memset(port->frame_list, 0, FRAME_LIST_LEN * sizeof(uint32_t));
  1397. esp_intr_enable(s_hcd_obj->isr_hdl);
  1398. HCD_EXIT_CRITICAL();
  1399. return ESP_OK;
  1400. }
  1401. void *hcd_port_get_context(hcd_port_handle_t port_hdl)
  1402. {
  1403. port_t *port = (port_t *)port_hdl;
  1404. void *ret;
  1405. HCD_ENTER_CRITICAL();
  1406. ret = port->context;
  1407. HCD_EXIT_CRITICAL();
  1408. return ret;
  1409. }
  1410. esp_err_t hcd_port_set_fifo_bias(hcd_port_handle_t port_hdl, hcd_port_fifo_bias_t bias)
  1411. {
  1412. esp_err_t ret;
  1413. //Get a pointer to the correct FIFO bias constant values
  1414. const usbh_hal_fifo_config_t *fifo_config;
  1415. const fifo_mps_limits_t *mps_limits;
  1416. switch (bias) {
  1417. case HCD_PORT_FIFO_BIAS_BALANCED:
  1418. fifo_config = &fifo_config_default;
  1419. mps_limits = &mps_limits_default;
  1420. break;
  1421. case HCD_PORT_FIFO_BIAS_RX:
  1422. fifo_config = &fifo_config_bias_rx;
  1423. mps_limits = &mps_limits_bias_rx;
  1424. break;
  1425. case HCD_PORT_FIFO_BIAS_PTX:
  1426. fifo_config = &fifo_config_bias_ptx;
  1427. mps_limits = &mps_limits_bias_ptx;
  1428. break;
  1429. default:
  1430. fifo_config = NULL;
  1431. mps_limits = NULL;
  1432. abort();
  1433. break;
  1434. }
  1435. //Configure the new FIFO sizes and store the pointers
  1436. port_t *port = (port_t *)port_hdl;
  1437. xSemaphoreTake(port->port_mux, portMAX_DELAY);
  1438. HCD_ENTER_CRITICAL();
  1439. //Check that port is in the correct state to update FIFO sizes
  1440. if (port->initialized && !port->flags.event_pending && port->num_pipes_idle == 0 && port->num_pipes_queued == 0) {
  1441. usbh_hal_set_fifo_size(port->hal, fifo_config);
  1442. port->fifo_config = fifo_config;
  1443. port->fifo_mps_limits = mps_limits;
  1444. ret = ESP_OK;
  1445. } else {
  1446. ret = ESP_ERR_INVALID_STATE;
  1447. }
  1448. HCD_EXIT_CRITICAL();
  1449. xSemaphoreGive(port->port_mux);
  1450. return ret;
  1451. }
  1452. // --------------------------------------------------- HCD Pipes -------------------------------------------------------
  1453. // ----------------------- Private -------------------------
  1454. static inline hcd_pipe_event_t pipe_decode_error_event(usbh_hal_chan_error_t chan_error)
  1455. {
  1456. hcd_pipe_event_t event = HCD_PIPE_EVENT_NONE;
  1457. switch (chan_error) {
  1458. case USBH_HAL_CHAN_ERROR_XCS_XACT:
  1459. event = HCD_PIPE_EVENT_ERROR_XFER;
  1460. break;
  1461. case USBH_HAL_CHAN_ERROR_BNA:
  1462. event = HCD_PIPE_EVENT_ERROR_URB_NOT_AVAIL;
  1463. break;
  1464. case USBH_HAL_CHAN_ERROR_PKT_BBL:
  1465. event = HCD_PIPE_EVENT_ERROR_OVERFLOW;
  1466. break;
  1467. case USBH_HAL_CHAN_ERROR_STALL:
  1468. event = HCD_PIPE_EVENT_ERROR_STALL;
  1469. break;
  1470. }
  1471. return event;
  1472. }
  1473. static dma_buffer_block_t *buffer_block_alloc(usb_transfer_type_t type)
  1474. {
  1475. int desc_list_len;
  1476. switch (type) {
  1477. case USB_TRANSFER_TYPE_CTRL:
  1478. desc_list_len = XFER_LIST_LEN_CTRL;
  1479. break;
  1480. case USB_TRANSFER_TYPE_ISOCHRONOUS:
  1481. desc_list_len = XFER_LIST_LEN_ISOC;
  1482. break;
  1483. case USB_TRANSFER_TYPE_BULK:
  1484. desc_list_len = XFER_LIST_LEN_BULK;
  1485. break;
  1486. default: //USB_TRANSFER_TYPE_INTR:
  1487. desc_list_len = XFER_LIST_LEN_INTR;
  1488. break;
  1489. }
  1490. dma_buffer_block_t *buffer = calloc(1, sizeof(dma_buffer_block_t));
  1491. void *xfer_desc_list = heap_caps_aligned_calloc(USBH_HAL_DMA_MEM_ALIGN, desc_list_len, sizeof(usbh_ll_dma_qtd_t), MALLOC_CAP_DMA);
  1492. if (buffer == NULL || xfer_desc_list == NULL) {
  1493. free(buffer);
  1494. heap_caps_free(xfer_desc_list);
  1495. return NULL;
  1496. }
  1497. buffer->xfer_desc_list = xfer_desc_list;
  1498. return buffer;
  1499. }
  1500. static void buffer_block_free(dma_buffer_block_t *buffer)
  1501. {
  1502. if (buffer == NULL) {
  1503. return;
  1504. }
  1505. heap_caps_free(buffer->xfer_desc_list);
  1506. free(buffer);
  1507. }
  1508. static bool pipe_alloc_check_args(const hcd_pipe_config_t *pipe_config, usb_speed_t port_speed, const fifo_mps_limits_t *mps_limits, usb_transfer_type_t type, bool is_default_pipe)
  1509. {
  1510. //Check if pipe can be supported
  1511. if (port_speed == USB_SPEED_LOW && pipe_config->dev_speed == USB_SPEED_FULL) {
  1512. //Low speed port does not supported full speed pipe
  1513. return false;
  1514. }
  1515. if (pipe_config->dev_speed == USB_SPEED_LOW && (type == USB_TRANSFER_TYPE_BULK || type == USB_TRANSFER_TYPE_ISOCHRONOUS)) {
  1516. //Low speed does not support Bulk or Isochronous pipes
  1517. return false;
  1518. }
  1519. //Check interval of pipe
  1520. if (type == USB_TRANSFER_TYPE_INTR &&
  1521. (pipe_config->ep_desc->bInterval > 0 && pipe_config->ep_desc->bInterval > 32)) {
  1522. //Interval not supported for interrupt pipe
  1523. return false;
  1524. }
  1525. if (type == USB_TRANSFER_TYPE_ISOCHRONOUS &&
  1526. (pipe_config->ep_desc->bInterval > 0 && pipe_config->ep_desc->bInterval > 6)) {
  1527. //Interval not supported for isochronous pipe (where 0 < 2^(bInterval - 1) <= 32)
  1528. return false;
  1529. }
  1530. if (is_default_pipe) {
  1531. return true;
  1532. }
  1533. int limit;
  1534. if (USB_EP_DESC_GET_EP_DIR(pipe_config->ep_desc)) { //IN
  1535. limit = mps_limits->in_mps;
  1536. } else { //OUT
  1537. if (type == USB_TRANSFER_TYPE_CTRL || type == USB_TRANSFER_TYPE_BULK) {
  1538. limit = mps_limits->non_periodic_out_mps;
  1539. } else {
  1540. limit = mps_limits->periodic_out_mps;
  1541. }
  1542. }
  1543. return (pipe_config->ep_desc->wMaxPacketSize <= limit);
  1544. }
  1545. static void pipe_set_ep_char(const hcd_pipe_config_t *pipe_config, usb_transfer_type_t type, bool is_default_pipe, int pipe_idx, usb_speed_t port_speed, usbh_hal_ep_char_t *ep_char)
  1546. {
  1547. //Initialize EP characteristics
  1548. usb_priv_xfer_type_t hal_xfer_type;
  1549. switch (type) {
  1550. case USB_TRANSFER_TYPE_CTRL:
  1551. hal_xfer_type = USB_PRIV_XFER_TYPE_CTRL;
  1552. break;
  1553. case USB_TRANSFER_TYPE_ISOCHRONOUS:
  1554. hal_xfer_type = USB_PRIV_XFER_TYPE_ISOCHRONOUS;
  1555. break;
  1556. case USB_TRANSFER_TYPE_BULK:
  1557. hal_xfer_type = USB_PRIV_XFER_TYPE_BULK;
  1558. break;
  1559. default: //USB_TRANSFER_TYPE_INTR
  1560. hal_xfer_type = USB_PRIV_XFER_TYPE_INTR;
  1561. break;
  1562. }
  1563. ep_char->type = hal_xfer_type;
  1564. if (is_default_pipe) {
  1565. ep_char->bEndpointAddress = 0;
  1566. //Set the default pipe's MPS to the worst case MPS for the device's speed
  1567. ep_char->mps = (pipe_config->dev_speed == USB_SPEED_FULL) ? CTRL_EP_MAX_MPS_FS : CTRL_EP_MAX_MPS_LS;
  1568. } else {
  1569. ep_char->bEndpointAddress = pipe_config->ep_desc->bEndpointAddress;
  1570. ep_char->mps = pipe_config->ep_desc->wMaxPacketSize;
  1571. }
  1572. ep_char->dev_addr = pipe_config->dev_addr;
  1573. ep_char->ls_via_fs_hub = (port_speed == USB_SPEED_FULL && pipe_config->dev_speed == USB_SPEED_LOW);
  1574. //Calculate the pipe's interval in terms of USB frames
  1575. if (type == USB_TRANSFER_TYPE_INTR || type == USB_TRANSFER_TYPE_ISOCHRONOUS) {
  1576. int interval_frames;
  1577. if (type == USB_TRANSFER_TYPE_INTR) {
  1578. interval_frames = pipe_config->ep_desc->bInterval;
  1579. } else {
  1580. interval_frames = (1 << (pipe_config->ep_desc->bInterval - 1));
  1581. }
  1582. //Round down interval to nearest power of 2
  1583. if (interval_frames >= 32) {
  1584. interval_frames = 32;
  1585. } else if (interval_frames >= 16) {
  1586. interval_frames = 16;
  1587. } else if (interval_frames >= 8) {
  1588. interval_frames = 8;
  1589. } else if (interval_frames >= 4) {
  1590. interval_frames = 4;
  1591. } else if (interval_frames >= 2) {
  1592. interval_frames = 2;
  1593. } else if (interval_frames >= 1) {
  1594. interval_frames = 1;
  1595. }
  1596. ep_char->periodic.interval = interval_frames;
  1597. //We are the Nth pipe to be allocated. Use N as a phase offset
  1598. ep_char->periodic.phase_offset_frames = pipe_idx & (XFER_LIST_LEN_ISOC - 1);
  1599. }else {
  1600. ep_char->periodic.interval = 0;
  1601. ep_char->periodic.phase_offset_frames = 0;
  1602. }
  1603. }
  1604. // ---------------------- Commands -------------------------
  1605. static esp_err_t _pipe_cmd_halt(pipe_t *pipe)
  1606. {
  1607. esp_err_t ret;
  1608. //If pipe is already halted, just return.
  1609. if (pipe->state == HCD_PIPE_STATE_HALTED) {
  1610. ret = ESP_OK;
  1611. goto exit;
  1612. }
  1613. //If the pipe's port is invalid, we just mark the pipe as halted without needing to halt the underlying channel
  1614. if (pipe->port->flags.conn_dev_ena //Skip halting the underlying channel if the port is invalid
  1615. && !usbh_hal_chan_request_halt(pipe->chan_obj)) { //Check if the channel is already halted
  1616. //Channel is not halted, we need to request and wait for a haltWe need to wait for channel to be halted.
  1617. pipe->cs_flags.waiting_halt = 1;
  1618. _internal_pipe_event_wait(pipe);
  1619. //State should have been updated in the ISR
  1620. assert(pipe->state == HCD_PIPE_STATE_HALTED);
  1621. } else {
  1622. //We are already halted, just need to update the state
  1623. usbh_hal_chan_mark_halted(pipe->chan_obj);
  1624. pipe->state = HCD_PIPE_STATE_HALTED;
  1625. }
  1626. ret = ESP_OK;
  1627. exit:
  1628. return ret;
  1629. }
  1630. static esp_err_t _pipe_cmd_flush(pipe_t *pipe)
  1631. {
  1632. esp_err_t ret;
  1633. //The pipe must be halted in order to be flushed
  1634. if (pipe->state != HCD_PIPE_STATE_HALTED) {
  1635. ret = ESP_ERR_INVALID_STATE;
  1636. goto exit;
  1637. }
  1638. //If the port is still valid, we are canceling transfers. Otherwise, we are flushing due to a port error
  1639. bool canceled = pipe->port->flags.conn_dev_ena;
  1640. bool call_pipe_cb;
  1641. //Flush any filled buffers
  1642. call_pipe_cb = _buffer_flush_all(pipe, canceled);
  1643. //Move all URBs from the pending tailq to the done tailq
  1644. if (pipe->num_urb_pending > 0) {
  1645. //Process all remaining pending URBs
  1646. urb_t *urb;
  1647. TAILQ_FOREACH(urb, &pipe->pending_urb_tailq, tailq_entry) {
  1648. //Update the URB's current state
  1649. urb->hcd_var = URB_HCD_STATE_DONE;
  1650. //URBs were never executed, Update the actual_num_bytes and status
  1651. urb->transfer.actual_num_bytes = 0;
  1652. urb->transfer.status = (canceled) ? USB_TRANSFER_STATUS_CANCELED : USB_TRANSFER_STATUS_NO_DEVICE;
  1653. if (pipe->ep_char.type == USB_PRIV_XFER_TYPE_ISOCHRONOUS) {
  1654. //Update the URB's isoc packet descriptors as well
  1655. for (int pkt_idx = 0; pkt_idx < urb->transfer.num_isoc_packets; pkt_idx++) {
  1656. urb->transfer.isoc_packet_desc[pkt_idx].actual_num_bytes = 0;
  1657. urb->transfer.isoc_packet_desc[pkt_idx].status = (canceled) ? USB_TRANSFER_STATUS_CANCELED : USB_TRANSFER_STATUS_NO_DEVICE;
  1658. }
  1659. }
  1660. }
  1661. //Concatenated pending tailq to the done tailq
  1662. TAILQ_CONCAT(&pipe->done_urb_tailq, &pipe->pending_urb_tailq, tailq_entry);
  1663. pipe->num_urb_done += pipe->num_urb_pending;
  1664. pipe->num_urb_pending = 0;
  1665. call_pipe_cb = true;
  1666. }
  1667. if (call_pipe_cb) {
  1668. //One or more URBs can be dequeued as a result of the flush. We need to call the callback
  1669. HCD_EXIT_CRITICAL();
  1670. pipe->callback((hcd_pipe_handle_t)pipe, HCD_PIPE_EVENT_URB_DONE, pipe->callback_arg, false);
  1671. HCD_ENTER_CRITICAL();
  1672. }
  1673. ret = ESP_OK;
  1674. exit:
  1675. return ret;
  1676. }
  1677. static esp_err_t _pipe_cmd_clear(pipe_t *pipe)
  1678. {
  1679. esp_err_t ret;
  1680. //Pipe must be in the halted state in order to be made active, and there must be an enabled device on the port
  1681. if (pipe->state != HCD_PIPE_STATE_HALTED || !pipe->port->flags.conn_dev_ena) {
  1682. ret = ESP_ERR_INVALID_STATE;
  1683. goto exit;
  1684. }
  1685. //Update the pipe's state
  1686. pipe->state = HCD_PIPE_STATE_ACTIVE;
  1687. if (pipe->num_urb_pending > 0) {
  1688. //Fill as many buffers as possible
  1689. while (_buffer_can_fill(pipe)) {
  1690. _buffer_fill(pipe);
  1691. }
  1692. }
  1693. //Execute any filled buffers
  1694. if (_buffer_can_exec(pipe)) {
  1695. _buffer_exec(pipe);
  1696. }
  1697. ret = ESP_OK;
  1698. exit:
  1699. return ret;
  1700. }
  1701. // ----------------------- Public --------------------------
  1702. esp_err_t hcd_pipe_alloc(hcd_port_handle_t port_hdl, const hcd_pipe_config_t *pipe_config, hcd_pipe_handle_t *pipe_hdl)
  1703. {
  1704. HCD_CHECK(port_hdl != NULL && pipe_config != NULL && pipe_hdl != NULL, ESP_ERR_INVALID_ARG);
  1705. port_t *port = (port_t *)port_hdl;
  1706. HCD_ENTER_CRITICAL();
  1707. //Can only allocate a pipe if the target port is initialized and connected to an enabled device
  1708. HCD_CHECK_FROM_CRIT(port->initialized && port->flags.conn_dev_ena, ESP_ERR_INVALID_STATE);
  1709. usb_speed_t port_speed = port->speed;
  1710. const fifo_mps_limits_t *mps_limits = port->fifo_mps_limits;
  1711. int pipe_idx = port->num_pipes_idle + port->num_pipes_queued;
  1712. HCD_EXIT_CRITICAL();
  1713. usb_transfer_type_t type;
  1714. bool is_default;
  1715. if (pipe_config->ep_desc == NULL) {
  1716. type = USB_TRANSFER_TYPE_CTRL;
  1717. is_default = true;
  1718. } else {
  1719. type = USB_EP_DESC_GET_XFERTYPE(pipe_config->ep_desc);
  1720. is_default = false;
  1721. }
  1722. //Check if pipe configuration can be supported
  1723. if (!pipe_alloc_check_args(pipe_config, port_speed, mps_limits, type, is_default)) {
  1724. return ESP_ERR_NOT_SUPPORTED;
  1725. }
  1726. esp_err_t ret;
  1727. //Allocate the pipe resources
  1728. pipe_t *pipe = calloc(1, sizeof(pipe_t));
  1729. usbh_hal_chan_t *chan_obj = calloc(1, sizeof(usbh_hal_chan_t));
  1730. dma_buffer_block_t *buffers[NUM_BUFFERS] = {0};
  1731. if (pipe == NULL|| chan_obj == NULL) {
  1732. ret = ESP_ERR_NO_MEM;
  1733. goto err;
  1734. }
  1735. for (int i = 0; i < NUM_BUFFERS; i++) {
  1736. buffers[i] = buffer_block_alloc(type);
  1737. if (buffers[i] == NULL) {
  1738. ret = ESP_ERR_NO_MEM;
  1739. goto err;
  1740. }
  1741. }
  1742. //Initialize pipe object
  1743. TAILQ_INIT(&pipe->pending_urb_tailq);
  1744. TAILQ_INIT(&pipe->done_urb_tailq);
  1745. for (int i = 0; i < NUM_BUFFERS; i++) {
  1746. pipe->buffers[i] = buffers[i];
  1747. }
  1748. pipe->multi_buffer_control.buffer_num_to_fill = NUM_BUFFERS;
  1749. pipe->port = port;
  1750. pipe->chan_obj = chan_obj;
  1751. usbh_hal_ep_char_t ep_char;
  1752. pipe_set_ep_char(pipe_config, type, is_default, pipe_idx, port_speed, &ep_char);
  1753. memcpy(&pipe->ep_char, &ep_char, sizeof(usbh_hal_ep_char_t));
  1754. pipe->state = HCD_PIPE_STATE_ACTIVE;
  1755. pipe->callback = pipe_config->callback;
  1756. pipe->callback_arg = pipe_config->callback_arg;
  1757. pipe->context = pipe_config->context;
  1758. //Allocate channel
  1759. HCD_ENTER_CRITICAL();
  1760. if (!port->initialized || !port->flags.conn_dev_ena) {
  1761. HCD_EXIT_CRITICAL();
  1762. ret = ESP_ERR_INVALID_STATE;
  1763. goto err;
  1764. }
  1765. bool chan_allocated = usbh_hal_chan_alloc(port->hal, pipe->chan_obj, (void *) pipe);
  1766. if (!chan_allocated) {
  1767. HCD_EXIT_CRITICAL();
  1768. ret = ESP_ERR_NOT_SUPPORTED;
  1769. goto err;
  1770. }
  1771. usbh_hal_chan_set_ep_char(port->hal, pipe->chan_obj, &pipe->ep_char);
  1772. //Add the pipe to the list of idle pipes in the port object
  1773. TAILQ_INSERT_TAIL(&port->pipes_idle_tailq, pipe, tailq_entry);
  1774. port->num_pipes_idle++;
  1775. HCD_EXIT_CRITICAL();
  1776. *pipe_hdl = (hcd_pipe_handle_t)pipe;
  1777. return ESP_OK;
  1778. err:
  1779. for (int i = 0; i < NUM_BUFFERS; i++) {
  1780. buffer_block_free(buffers[i]);
  1781. }
  1782. free(chan_obj);
  1783. free(pipe);
  1784. return ret;
  1785. }
  1786. esp_err_t hcd_pipe_free(hcd_pipe_handle_t pipe_hdl)
  1787. {
  1788. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1789. HCD_ENTER_CRITICAL();
  1790. //Check that all URBs have been removed and pipe has no pending events
  1791. HCD_CHECK_FROM_CRIT(!pipe->multi_buffer_control.buffer_is_executing
  1792. && !pipe->cs_flags.has_urb
  1793. && !pipe->cs_flags.reset_lock,
  1794. ESP_ERR_INVALID_STATE);
  1795. //Remove pipe from the list of idle pipes (it must be in the idle list because it should have no queued URBs)
  1796. TAILQ_REMOVE(&pipe->port->pipes_idle_tailq, pipe, tailq_entry);
  1797. pipe->port->num_pipes_idle--;
  1798. usbh_hal_chan_free(pipe->port->hal, pipe->chan_obj);
  1799. HCD_EXIT_CRITICAL();
  1800. //Free pipe resources
  1801. for (int i = 0; i < NUM_BUFFERS; i++) {
  1802. buffer_block_free(pipe->buffers[i]);
  1803. }
  1804. free(pipe->chan_obj);
  1805. free(pipe);
  1806. return ESP_OK;
  1807. }
  1808. esp_err_t hcd_pipe_update_mps(hcd_pipe_handle_t pipe_hdl, int mps)
  1809. {
  1810. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1811. HCD_ENTER_CRITICAL();
  1812. //Check if pipe is in the correct state to be updated
  1813. HCD_CHECK_FROM_CRIT(!pipe->cs_flags.pipe_cmd_processing &&
  1814. !pipe->cs_flags.has_urb &&
  1815. !pipe->cs_flags.reset_lock,
  1816. ESP_ERR_INVALID_STATE);
  1817. pipe->ep_char.mps = mps;
  1818. //Update the underlying channel's registers
  1819. usbh_hal_chan_set_ep_char(pipe->port->hal, pipe->chan_obj, &pipe->ep_char);
  1820. HCD_EXIT_CRITICAL();
  1821. return ESP_OK;
  1822. }
  1823. esp_err_t hcd_pipe_update_dev_addr(hcd_pipe_handle_t pipe_hdl, uint8_t dev_addr)
  1824. {
  1825. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1826. HCD_ENTER_CRITICAL();
  1827. //Check if pipe is in the correct state to be updated
  1828. HCD_CHECK_FROM_CRIT(!pipe->cs_flags.pipe_cmd_processing &&
  1829. !pipe->cs_flags.has_urb &&
  1830. !pipe->cs_flags.reset_lock,
  1831. ESP_ERR_INVALID_STATE);
  1832. pipe->ep_char.dev_addr = dev_addr;
  1833. //Update the underlying channel's registers
  1834. usbh_hal_chan_set_ep_char(pipe->port->hal, pipe->chan_obj, &pipe->ep_char);
  1835. HCD_EXIT_CRITICAL();
  1836. return ESP_OK;
  1837. }
  1838. esp_err_t hcd_pipe_update_callback(hcd_pipe_handle_t pipe_hdl, hcd_pipe_callback_t callback, void *user_arg)
  1839. {
  1840. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1841. HCD_ENTER_CRITICAL();
  1842. //Check if pipe is in the correct state to be updated
  1843. HCD_CHECK_FROM_CRIT(!pipe->cs_flags.pipe_cmd_processing &&
  1844. !pipe->cs_flags.has_urb &&
  1845. !pipe->cs_flags.reset_lock,
  1846. ESP_ERR_INVALID_STATE);
  1847. pipe->callback = callback;
  1848. pipe->callback_arg = user_arg;
  1849. HCD_EXIT_CRITICAL();
  1850. return ESP_OK;
  1851. }
  1852. esp_err_t hcd_pipe_set_persist_reset(hcd_pipe_handle_t pipe_hdl)
  1853. {
  1854. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1855. HCD_ENTER_CRITICAL();
  1856. //Check if pipe is in the correct state to be updated
  1857. HCD_CHECK_FROM_CRIT(!pipe->cs_flags.pipe_cmd_processing &&
  1858. !pipe->cs_flags.has_urb &&
  1859. !pipe->cs_flags.reset_lock,
  1860. ESP_ERR_INVALID_STATE);
  1861. pipe->cs_flags.persist = 1;
  1862. HCD_EXIT_CRITICAL();
  1863. return ESP_OK;
  1864. }
  1865. void *hcd_pipe_get_context(hcd_pipe_handle_t pipe_hdl)
  1866. {
  1867. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1868. void *ret;
  1869. HCD_ENTER_CRITICAL();
  1870. ret = pipe->context;
  1871. HCD_EXIT_CRITICAL();
  1872. return ret;
  1873. }
  1874. hcd_pipe_state_t hcd_pipe_get_state(hcd_pipe_handle_t pipe_hdl)
  1875. {
  1876. hcd_pipe_state_t ret;
  1877. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1878. HCD_ENTER_CRITICAL();
  1879. ret = pipe->state;
  1880. HCD_EXIT_CRITICAL();
  1881. return ret;
  1882. }
  1883. esp_err_t hcd_pipe_command(hcd_pipe_handle_t pipe_hdl, hcd_pipe_cmd_t command)
  1884. {
  1885. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1886. esp_err_t ret = ESP_OK;
  1887. HCD_ENTER_CRITICAL();
  1888. //Cannot execute pipe commands the pipe is already executing a command, or if the pipe or its port are no longer valid
  1889. if (pipe->cs_flags.reset_lock) {
  1890. ret = ESP_ERR_INVALID_STATE;
  1891. } else {
  1892. pipe->cs_flags.pipe_cmd_processing = 1;
  1893. switch (command) {
  1894. case HCD_PIPE_CMD_HALT: {
  1895. ret = _pipe_cmd_halt(pipe);
  1896. break;
  1897. }
  1898. case HCD_PIPE_CMD_FLUSH: {
  1899. ret = _pipe_cmd_flush(pipe);
  1900. break;
  1901. }
  1902. case HCD_PIPE_CMD_CLEAR: {
  1903. ret = _pipe_cmd_clear(pipe);
  1904. break;
  1905. }
  1906. }
  1907. pipe->cs_flags.pipe_cmd_processing = 0;
  1908. }
  1909. HCD_EXIT_CRITICAL();
  1910. return ret;
  1911. }
  1912. hcd_pipe_event_t hcd_pipe_get_event(hcd_pipe_handle_t pipe_hdl)
  1913. {
  1914. pipe_t *pipe = (pipe_t *)pipe_hdl;
  1915. hcd_pipe_event_t ret;
  1916. HCD_ENTER_CRITICAL();
  1917. ret = pipe->last_event;
  1918. pipe->last_event = HCD_PIPE_EVENT_NONE;
  1919. HCD_EXIT_CRITICAL();
  1920. return ret;
  1921. }
  1922. // ------------------------------------------------- Buffer Control ----------------------------------------------------
  1923. static inline void _buffer_fill_ctrl(dma_buffer_block_t *buffer, usb_transfer_t *transfer)
  1924. {
  1925. //Get information about the control transfer by analyzing the setup packet (the first 8 bytes of the URB's data)
  1926. usb_setup_packet_t *setup_pkt = (usb_setup_packet_t *)transfer->data_buffer;
  1927. bool data_stg_in = (setup_pkt->bmRequestType & USB_BM_REQUEST_TYPE_DIR_IN);
  1928. bool data_stg_skip = (setup_pkt->wLength == 0);
  1929. //Fill setup stage
  1930. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, 0, transfer->data_buffer, sizeof(usb_setup_packet_t),
  1931. USBH_HAL_XFER_DESC_FLAG_SETUP | USBH_HAL_XFER_DESC_FLAG_HOC);
  1932. //Fill data stage
  1933. if (data_stg_skip) {
  1934. //Not data stage. Fill with an empty descriptor
  1935. usbh_hal_xfer_desc_clear(buffer->xfer_desc_list, 1);
  1936. } else {
  1937. //Fill data stage
  1938. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, 1, transfer->data_buffer + sizeof(usb_setup_packet_t), setup_pkt->wLength,
  1939. ((data_stg_in) ? USBH_HAL_XFER_DESC_FLAG_IN : 0) | USBH_HAL_XFER_DESC_FLAG_HOC);
  1940. }
  1941. //Fill status stage (i.e., a zero length packet). If data stage is skipped, the status stage is always IN.
  1942. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, 2, NULL, 0,
  1943. ((data_stg_in && !data_stg_skip) ? 0 : USBH_HAL_XFER_DESC_FLAG_IN) | USBH_HAL_XFER_DESC_FLAG_HOC);
  1944. //Update buffer flags
  1945. buffer->flags.ctrl.data_stg_in = data_stg_in;
  1946. buffer->flags.ctrl.data_stg_skip = data_stg_skip;
  1947. buffer->flags.ctrl.cur_stg = 0;
  1948. }
  1949. static inline void _buffer_fill_bulk(dma_buffer_block_t *buffer, usb_transfer_t *transfer, bool is_in)
  1950. {
  1951. if (is_in) {
  1952. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, 0, transfer->data_buffer, transfer->num_bytes,
  1953. USBH_HAL_XFER_DESC_FLAG_IN | USBH_HAL_XFER_DESC_FLAG_HOC);
  1954. } else if (transfer->flags & USB_TRANSFER_FLAG_ZERO_PACK) {
  1955. //We need to add an extra zero length packet, so two descriptors are used
  1956. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, 0, transfer->data_buffer, transfer->num_bytes, 0);
  1957. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, 1, NULL, 0, USBH_HAL_XFER_DESC_FLAG_HOC);
  1958. } else {
  1959. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, 0, transfer->data_buffer, transfer->num_bytes, USBH_HAL_XFER_DESC_FLAG_HOC);
  1960. }
  1961. //Update buffer flags
  1962. buffer->flags.bulk.zero_len_packet = (is_in && (transfer->flags & USB_TRANSFER_FLAG_ZERO_PACK)) ? 1 : 0;
  1963. }
  1964. static inline void _buffer_fill_intr(dma_buffer_block_t *buffer, usb_transfer_t *transfer, bool is_in, int mps)
  1965. {
  1966. int num_qtds;
  1967. if (is_in) {
  1968. assert(transfer->num_bytes % mps == 0); //IN transfers MUST be integer multiple of MPS
  1969. num_qtds = transfer->num_bytes / mps;
  1970. } else {
  1971. num_qtds = transfer->num_bytes / mps; //Floor division for number of MPS packets
  1972. if (transfer->num_bytes % transfer->num_bytes > 0) {
  1973. num_qtds++; //For the last shot packet
  1974. }
  1975. }
  1976. assert(num_qtds <= XFER_LIST_LEN_INTR);
  1977. //Fill all but last descriptor
  1978. int bytes_filled = 0;
  1979. for (int i = 0; i < num_qtds - 1; i++) {
  1980. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, i, &transfer->data_buffer[bytes_filled], mps, (is_in) ? USBH_HAL_XFER_DESC_FLAG_IN : 0);
  1981. bytes_filled += mps;
  1982. }
  1983. //Fill in the last descriptor with HOC flag
  1984. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, num_qtds - 1, &transfer->data_buffer[bytes_filled], transfer->num_bytes - bytes_filled,
  1985. ((is_in) ? USBH_HAL_XFER_DESC_FLAG_IN : 0) | USBH_HAL_XFER_DESC_FLAG_HOC);
  1986. //Update buffer members and flags
  1987. buffer->flags.intr.num_qtds = num_qtds;
  1988. }
  1989. static inline void _buffer_fill_isoc(dma_buffer_block_t *buffer, usb_transfer_t *transfer, bool is_in, int mps, int interval, int start_idx)
  1990. {
  1991. assert(interval > 0);
  1992. int total_num_desc = transfer->num_isoc_packets * interval;
  1993. assert(total_num_desc <= XFER_LIST_LEN_ISOC);
  1994. int desc_idx = start_idx;
  1995. int bytes_filled = 0;
  1996. //For each packet, fill in a descriptor and a interval-1 blank descriptor after it
  1997. for (int pkt_idx = 0; pkt_idx < transfer->num_isoc_packets; pkt_idx++) {
  1998. int xfer_len = transfer->isoc_packet_desc[pkt_idx].num_bytes;
  1999. uint32_t flags = (is_in) ? USBH_HAL_XFER_DESC_FLAG_IN : 0;
  2000. if (pkt_idx == transfer->num_isoc_packets - 1) {
  2001. //Last packet, set the the HOC flag
  2002. flags |= USBH_HAL_XFER_DESC_FLAG_HOC;
  2003. }
  2004. usbh_hal_xfer_desc_fill(buffer->xfer_desc_list, desc_idx, &transfer->data_buffer[bytes_filled], xfer_len, flags);
  2005. bytes_filled += xfer_len;
  2006. if (++desc_idx >= XFER_LIST_LEN_ISOC) {
  2007. desc_idx = 0;
  2008. }
  2009. //Clear descriptors for unscheduled frames
  2010. for (int i = 0; i < interval - 1; i++) {
  2011. usbh_hal_xfer_desc_clear(buffer->xfer_desc_list, desc_idx);
  2012. if (++desc_idx >= XFER_LIST_LEN_ISOC) {
  2013. desc_idx = 0;
  2014. }
  2015. }
  2016. }
  2017. //Update buffer members and flags
  2018. buffer->flags.isoc.num_qtds = total_num_desc;
  2019. buffer->flags.isoc.interval = interval;
  2020. buffer->flags.isoc.start_idx = start_idx;
  2021. buffer->flags.isoc.next_start_idx = desc_idx;
  2022. }
  2023. static void _buffer_fill(pipe_t *pipe)
  2024. {
  2025. //Get an URB from the pending tailq
  2026. urb_t *urb = TAILQ_FIRST(&pipe->pending_urb_tailq);
  2027. assert(pipe->num_urb_pending > 0 && urb != NULL);
  2028. TAILQ_REMOVE(&pipe->pending_urb_tailq, urb, tailq_entry);
  2029. pipe->num_urb_pending--;
  2030. //Select the inactive buffer
  2031. assert(pipe->multi_buffer_control.buffer_num_to_exec <= NUM_BUFFERS);
  2032. dma_buffer_block_t *buffer_to_fill = pipe->buffers[pipe->multi_buffer_control.wr_idx];
  2033. buffer_to_fill->status_flags.val = 0; //Clear the buffer's status flags
  2034. assert(buffer_to_fill->urb == NULL);
  2035. bool is_in = pipe->ep_char.bEndpointAddress & USB_B_ENDPOINT_ADDRESS_EP_DIR_MASK;
  2036. int mps = pipe->ep_char.mps;
  2037. usb_transfer_t *transfer = &urb->transfer;
  2038. switch (pipe->ep_char.type) {
  2039. case USB_PRIV_XFER_TYPE_CTRL: {
  2040. _buffer_fill_ctrl(buffer_to_fill, transfer);
  2041. break;
  2042. }
  2043. case USB_PRIV_XFER_TYPE_ISOCHRONOUS: {
  2044. uint32_t start_idx;
  2045. if (pipe->multi_buffer_control.buffer_num_to_exec == 0) {
  2046. //There are no more previously filled buffers to execute. We need to calculate a new start index based on HFNUM and the pipe's schedule
  2047. uint32_t cur_frame_num = usbh_hal_port_get_cur_frame_num(pipe->port->hal);
  2048. uint32_t cur_mod_idx_no_offset = (cur_frame_num - pipe->ep_char.periodic.phase_offset_frames) & (XFER_LIST_LEN_ISOC - 1); //Get the modulated index (i.e., the Nth desc in the descriptor list)
  2049. //This is the non-offset modulated QTD index of the last scheduled interval
  2050. uint32_t last_interval_mod_idx_no_offset = (cur_mod_idx_no_offset / pipe->ep_char.periodic.interval) * pipe->ep_char.periodic.interval; //Floor divide and the multiply again
  2051. uint32_t next_interval_idx_no_offset = (last_interval_mod_idx_no_offset + pipe->ep_char.periodic.interval);
  2052. //We want at least a half interval or 2 frames of buffer space
  2053. if (next_interval_idx_no_offset - cur_mod_idx_no_offset > (pipe->ep_char.periodic.interval / 2)
  2054. && next_interval_idx_no_offset - cur_mod_idx_no_offset >= 2) {
  2055. start_idx = (next_interval_idx_no_offset + pipe->ep_char.periodic.phase_offset_frames) & (XFER_LIST_LEN_ISOC - 1);
  2056. } else {
  2057. //Not enough time until the next schedule, add another interval to it.
  2058. start_idx = (next_interval_idx_no_offset + pipe->ep_char.periodic.interval + pipe->ep_char.periodic.phase_offset_frames) & (XFER_LIST_LEN_ISOC - 1);
  2059. }
  2060. } else {
  2061. //Start index is based on previously filled buffer
  2062. uint32_t prev_buffer_idx = (pipe->multi_buffer_control.wr_idx - 1) & (NUM_BUFFERS - 1);
  2063. dma_buffer_block_t *prev_filled_buffer = pipe->buffers[prev_buffer_idx];
  2064. start_idx = prev_filled_buffer->flags.isoc.next_start_idx;
  2065. }
  2066. _buffer_fill_isoc(buffer_to_fill, transfer, is_in, mps, (int)pipe->ep_char.periodic.interval, start_idx);
  2067. break;
  2068. }
  2069. case USB_PRIV_XFER_TYPE_BULK: {
  2070. _buffer_fill_bulk(buffer_to_fill, transfer, is_in);
  2071. break;
  2072. }
  2073. case USB_PRIV_XFER_TYPE_INTR: {
  2074. _buffer_fill_intr(buffer_to_fill, transfer, is_in, mps);
  2075. break;
  2076. }
  2077. default: {
  2078. abort();
  2079. break;
  2080. }
  2081. }
  2082. buffer_to_fill->urb = urb;
  2083. urb->hcd_var = URB_HCD_STATE_INFLIGHT;
  2084. //Update multi buffer flags
  2085. pipe->multi_buffer_control.wr_idx++;
  2086. pipe->multi_buffer_control.buffer_num_to_fill--;
  2087. pipe->multi_buffer_control.buffer_num_to_exec++;
  2088. }
  2089. static void _buffer_exec(pipe_t *pipe)
  2090. {
  2091. assert(pipe->multi_buffer_control.rd_idx != pipe->multi_buffer_control.wr_idx || pipe->multi_buffer_control.buffer_num_to_exec > 0);
  2092. dma_buffer_block_t *buffer_to_exec = pipe->buffers[pipe->multi_buffer_control.rd_idx];
  2093. assert(buffer_to_exec->urb != NULL);
  2094. uint32_t start_idx;
  2095. int desc_list_len;
  2096. switch (pipe->ep_char.type) {
  2097. case USB_PRIV_XFER_TYPE_CTRL: {
  2098. start_idx = 0;
  2099. desc_list_len = XFER_LIST_LEN_CTRL;
  2100. //Set the channel's direction to OUT and PID to 0 respectively for the the setup stage
  2101. usbh_hal_chan_set_dir(pipe->chan_obj, false); //Setup stage is always OUT
  2102. usbh_hal_chan_set_pid(pipe->chan_obj, 0); //Setup stage always has a PID of DATA0
  2103. break;
  2104. }
  2105. case USB_PRIV_XFER_TYPE_ISOCHRONOUS: {
  2106. start_idx = buffer_to_exec->flags.isoc.start_idx;
  2107. desc_list_len = XFER_LIST_LEN_ISOC;
  2108. break;
  2109. }
  2110. case USB_PRIV_XFER_TYPE_BULK: {
  2111. start_idx = 0;
  2112. desc_list_len = (buffer_to_exec->flags.bulk.zero_len_packet) ? XFER_LIST_LEN_BULK : 1;
  2113. break;
  2114. }
  2115. case USB_PRIV_XFER_TYPE_INTR: {
  2116. start_idx = 0;
  2117. desc_list_len = buffer_to_exec->flags.intr.num_qtds;
  2118. break;
  2119. }
  2120. default: {
  2121. start_idx = 0;
  2122. desc_list_len = 0;
  2123. abort();
  2124. break;
  2125. }
  2126. }
  2127. //Update buffer and multi buffer flags
  2128. buffer_to_exec->status_flags.executing = 1;
  2129. pipe->multi_buffer_control.buffer_is_executing = 1;
  2130. usbh_hal_chan_activate(pipe->chan_obj, buffer_to_exec->xfer_desc_list, desc_list_len, start_idx);
  2131. }
  2132. static void _buffer_exec_cont(pipe_t *pipe)
  2133. {
  2134. //This should only ever be called on control transfers
  2135. assert(pipe->ep_char.type == USB_PRIV_XFER_TYPE_CTRL);
  2136. dma_buffer_block_t *buffer_inflight = pipe->buffers[pipe->multi_buffer_control.rd_idx];
  2137. bool next_dir_is_in;
  2138. int next_pid;
  2139. assert(buffer_inflight->flags.ctrl.cur_stg != 2);
  2140. if (buffer_inflight->flags.ctrl.cur_stg == 0) { //Just finished control stage
  2141. if (buffer_inflight->flags.ctrl.data_stg_skip) {
  2142. //Skipping data stage. Go straight to status stage
  2143. next_dir_is_in = true; //With no data stage, status stage must be IN
  2144. next_pid = 1; //Status stage always has a PID of DATA1
  2145. buffer_inflight->flags.ctrl.cur_stg = 2; //Skip over the null descriptor representing the skipped data stage
  2146. } else {
  2147. //Go to data stage
  2148. next_dir_is_in = buffer_inflight->flags.ctrl.data_stg_in;
  2149. next_pid = 1; //Data stage always starts with a PID of DATA1
  2150. buffer_inflight->flags.ctrl.cur_stg = 1;
  2151. }
  2152. } else { //cur_stg == 1. //Just finished data stage. Go to status stage
  2153. next_dir_is_in = !buffer_inflight->flags.ctrl.data_stg_in; //Status stage is always the opposite direction of data stage
  2154. next_pid = 1; //Status stage always has a PID of DATA1
  2155. buffer_inflight->flags.ctrl.cur_stg = 2;
  2156. }
  2157. //Continue the control transfer
  2158. usbh_hal_chan_set_dir(pipe->chan_obj, next_dir_is_in);
  2159. usbh_hal_chan_set_pid(pipe->chan_obj, next_pid);
  2160. usbh_hal_chan_activate(pipe->chan_obj, buffer_inflight->xfer_desc_list, XFER_LIST_LEN_CTRL, buffer_inflight->flags.ctrl.cur_stg);
  2161. }
  2162. static inline void _buffer_parse_ctrl(dma_buffer_block_t *buffer)
  2163. {
  2164. usb_transfer_t *transfer = &buffer->urb->transfer;
  2165. //Update URB's actual number of bytes
  2166. if (buffer->flags.ctrl.data_stg_skip) {
  2167. //There was no data stage. Just set the actual length to the size of the setup packet
  2168. transfer->actual_num_bytes = sizeof(usb_setup_packet_t);
  2169. } else {
  2170. //Parse the data stage for the remaining length
  2171. int rem_len;
  2172. int desc_status;
  2173. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, 1, &rem_len, &desc_status);
  2174. assert(desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS);
  2175. assert(rem_len <= (transfer->num_bytes - sizeof(usb_setup_packet_t)));
  2176. transfer->actual_num_bytes = transfer->num_bytes - rem_len;
  2177. }
  2178. //Update URB status
  2179. transfer->status = USB_TRANSFER_STATUS_COMPLETED;
  2180. //Clear the descriptor list
  2181. memset(buffer->xfer_desc_list, XFER_LIST_LEN_CTRL, sizeof(usbh_ll_dma_qtd_t));
  2182. }
  2183. static inline void _buffer_parse_bulk(dma_buffer_block_t *buffer)
  2184. {
  2185. usb_transfer_t *transfer = &buffer->urb->transfer;
  2186. //Update URB's actual number of bytes
  2187. int rem_len;
  2188. int desc_status;
  2189. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, 0, &rem_len, &desc_status);
  2190. assert(desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS);
  2191. assert(rem_len <= transfer->num_bytes);
  2192. transfer->actual_num_bytes = transfer->num_bytes - rem_len;
  2193. //Update URB's status
  2194. transfer->status = USB_TRANSFER_STATUS_COMPLETED;
  2195. //Clear the descriptor list
  2196. memset(buffer->xfer_desc_list, XFER_LIST_LEN_BULK, sizeof(usbh_ll_dma_qtd_t));
  2197. }
  2198. static inline void _buffer_parse_intr(dma_buffer_block_t *buffer, bool is_in, int mps)
  2199. {
  2200. usb_transfer_t *transfer = &buffer->urb->transfer;
  2201. int intr_stop_idx = buffer->status_flags.stop_idx;
  2202. if (is_in) {
  2203. if (intr_stop_idx > 0) { //This is an early stop (short packet)
  2204. assert(intr_stop_idx <= buffer->flags.intr.num_qtds);
  2205. int rem_len;
  2206. int desc_status;
  2207. for (int i = 0; i < intr_stop_idx - 1; i++) { //Check all packets before the short
  2208. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, i, &rem_len, &desc_status);
  2209. assert(rem_len == 0 && desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS);
  2210. }
  2211. //Check the short packet
  2212. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, intr_stop_idx - 1, &rem_len, &desc_status);
  2213. assert(rem_len > 0 && desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS);
  2214. //Update actual bytes
  2215. transfer->actual_num_bytes = (mps * intr_stop_idx - 2) + (mps - rem_len);
  2216. } else {
  2217. //Check that all but the last packet transmitted MPS
  2218. for (int i = 0; i < buffer->flags.intr.num_qtds - 1; i++) {
  2219. int rem_len;
  2220. int desc_status;
  2221. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, i, &rem_len, &desc_status);
  2222. assert(rem_len == 0 && desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS);
  2223. }
  2224. //Check the last packet
  2225. int last_packet_rem_len;
  2226. int last_packet_desc_status;
  2227. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, buffer->flags.intr.num_qtds - 1, &last_packet_rem_len, &last_packet_desc_status);
  2228. assert(last_packet_desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS);
  2229. //All packets except last MUST be MPS. So just deduct the remaining length of the last packet to get actual number of bytes
  2230. transfer->actual_num_bytes = transfer->num_bytes - last_packet_rem_len;
  2231. }
  2232. } else {
  2233. //OUT INTR transfers can only complete successfully if all MPS packets have been transmitted. Double check
  2234. for (int i = 0 ; i < buffer->flags.intr.num_qtds; i++) {
  2235. int rem_len;
  2236. int desc_status;
  2237. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, i, &rem_len, &desc_status);
  2238. assert(rem_len == 0 && desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS);
  2239. }
  2240. transfer->actual_num_bytes = transfer->num_bytes;
  2241. }
  2242. //Update URB's status
  2243. transfer->status = USB_TRANSFER_STATUS_COMPLETED;
  2244. //Clear the descriptor list
  2245. memset(buffer->xfer_desc_list, XFER_LIST_LEN_INTR, sizeof(usbh_ll_dma_qtd_t));
  2246. }
  2247. static inline void _buffer_parse_isoc(dma_buffer_block_t *buffer, bool is_in)
  2248. {
  2249. usb_transfer_t *transfer = &buffer->urb->transfer;
  2250. int desc_idx = buffer->flags.isoc.start_idx; //Descriptor index tracks which descriptor in the QTD list
  2251. int total_actual_num_bytes = 0;
  2252. for (int pkt_idx = 0; pkt_idx < transfer->num_isoc_packets; pkt_idx++) {
  2253. //Clear the filled descriptor
  2254. int rem_len;
  2255. int desc_status;
  2256. usbh_hal_xfer_desc_parse(buffer->xfer_desc_list, desc_idx, &rem_len, &desc_status);
  2257. usbh_hal_xfer_desc_clear(buffer->xfer_desc_list, desc_idx);
  2258. assert(rem_len == 0 || is_in);
  2259. assert(desc_status == USBH_HAL_XFER_DESC_STS_SUCCESS || USBH_HAL_XFER_DESC_STS_NOT_EXECUTED);
  2260. assert(rem_len <= transfer->isoc_packet_desc[pkt_idx].num_bytes); //Check for DMA errata
  2261. //Update ISO packet actual length and status
  2262. transfer->isoc_packet_desc[pkt_idx].actual_num_bytes = transfer->isoc_packet_desc[pkt_idx].num_bytes - rem_len;
  2263. total_actual_num_bytes += transfer->isoc_packet_desc[pkt_idx].actual_num_bytes;
  2264. transfer->isoc_packet_desc[pkt_idx].status = (desc_status == USBH_HAL_XFER_DESC_STS_NOT_EXECUTED) ? USB_TRANSFER_STATUS_SKIPPED : USB_TRANSFER_STATUS_COMPLETED;
  2265. //A descriptor is also allocated for unscheduled frames. We need to skip over them
  2266. desc_idx += buffer->flags.isoc.interval;
  2267. if (desc_idx >= XFER_LIST_LEN_INTR) {
  2268. desc_idx -= XFER_LIST_LEN_INTR;
  2269. }
  2270. }
  2271. //Write back the actual_num_bytes and statue of entire transfer
  2272. assert(total_actual_num_bytes <= transfer->num_bytes);
  2273. transfer->actual_num_bytes = total_actual_num_bytes;
  2274. transfer->status = USB_TRANSFER_STATUS_COMPLETED;
  2275. }
  2276. static inline void _buffer_parse_error(dma_buffer_block_t *buffer)
  2277. {
  2278. //The URB had an error in one of its packet, or a port error), so we the entire URB an error.
  2279. usb_transfer_t *transfer = &buffer->urb->transfer;
  2280. transfer->actual_num_bytes = 0;
  2281. //Update the overall status of URB. Status will depend on the pipe_event
  2282. switch (buffer->status_flags.pipe_event) {
  2283. case HCD_PIPE_EVENT_NONE:
  2284. transfer->status = (buffer->status_flags.was_canceled) ? USB_TRANSFER_STATUS_CANCELED : USB_TRANSFER_STATUS_NO_DEVICE;
  2285. break;
  2286. case HCD_PIPE_EVENT_ERROR_XFER:
  2287. transfer->status = USB_TRANSFER_STATUS_ERROR;
  2288. break;
  2289. case HCD_PIPE_EVENT_ERROR_OVERFLOW:
  2290. transfer->status = USB_TRANSFER_STATUS_OVERFLOW;
  2291. break;
  2292. case HCD_PIPE_EVENT_ERROR_STALL:
  2293. transfer->status = USB_TRANSFER_STATUS_STALL;
  2294. break;
  2295. default:
  2296. //HCD_PIPE_EVENT_URB_DONE and HCD_PIPE_EVENT_ERROR_URB_NOT_AVAIL should not occur here
  2297. abort();
  2298. break;
  2299. }
  2300. }
  2301. static void _buffer_parse(pipe_t *pipe)
  2302. {
  2303. assert(pipe->multi_buffer_control.buffer_num_to_parse > 0);
  2304. dma_buffer_block_t *buffer_to_parse = pipe->buffers[pipe->multi_buffer_control.fr_idx];
  2305. assert(buffer_to_parse->urb != NULL);
  2306. bool is_in = pipe->ep_char.bEndpointAddress & USB_B_ENDPOINT_ADDRESS_EP_DIR_MASK;
  2307. int mps = pipe->ep_char.mps;
  2308. //Parsing the buffer will update the buffer's corresponding URB
  2309. if (buffer_to_parse->status_flags.pipe_event == HCD_PIPE_EVENT_URB_DONE) {
  2310. //URB was successful
  2311. switch (pipe->ep_char.type) {
  2312. case USB_PRIV_XFER_TYPE_CTRL: {
  2313. _buffer_parse_ctrl(buffer_to_parse);
  2314. break;
  2315. }
  2316. case USB_PRIV_XFER_TYPE_ISOCHRONOUS: {
  2317. _buffer_parse_isoc(buffer_to_parse, is_in);
  2318. break;
  2319. }
  2320. case USB_PRIV_XFER_TYPE_BULK: {
  2321. _buffer_parse_bulk(buffer_to_parse);
  2322. break;
  2323. }
  2324. case USB_PRIV_XFER_TYPE_INTR: {
  2325. _buffer_parse_intr(buffer_to_parse, is_in, mps);
  2326. break;
  2327. }
  2328. default: {
  2329. abort();
  2330. break;
  2331. }
  2332. }
  2333. } else {
  2334. //URB failed
  2335. _buffer_parse_error(buffer_to_parse);
  2336. }
  2337. urb_t *urb = buffer_to_parse->urb;
  2338. urb->hcd_var = URB_HCD_STATE_DONE;
  2339. buffer_to_parse->urb = NULL;
  2340. buffer_to_parse->flags.val = 0; //Clear flags
  2341. //Move the URB to the done tailq
  2342. TAILQ_INSERT_TAIL(&pipe->done_urb_tailq, urb, tailq_entry);
  2343. pipe->num_urb_done++;
  2344. //Update multi buffer flags
  2345. pipe->multi_buffer_control.fr_idx++;
  2346. pipe->multi_buffer_control.buffer_num_to_parse--;
  2347. pipe->multi_buffer_control.buffer_num_to_fill++;
  2348. }
  2349. static bool _buffer_flush_all(pipe_t *pipe, bool canceled)
  2350. {
  2351. int cur_num_to_mark_done = pipe->multi_buffer_control.buffer_num_to_exec;
  2352. for (int i = 0; i < cur_num_to_mark_done; i++) {
  2353. //Mark any filled buffers as done
  2354. _buffer_done(pipe, 0, HCD_PIPE_EVENT_NONE, canceled);
  2355. }
  2356. int cur_num_to_parse = pipe->multi_buffer_control.buffer_num_to_parse;
  2357. for (int i = 0; i < cur_num_to_parse; i++) {
  2358. _buffer_parse(pipe);
  2359. }
  2360. //At this point, there should be no more filled buffers. Only URBs in the pending or done tailq
  2361. return (cur_num_to_parse > 0);
  2362. }
  2363. // ---------------------------------------------- HCD Transfer Descriptors ---------------------------------------------
  2364. // ----------------------- Public --------------------------
  2365. esp_err_t hcd_urb_enqueue(hcd_pipe_handle_t pipe_hdl, urb_t *urb)
  2366. {
  2367. //Check that URB has not already been enqueued
  2368. HCD_CHECK(urb->hcd_ptr == NULL && urb->hcd_var == URB_HCD_STATE_IDLE, ESP_ERR_INVALID_STATE);
  2369. pipe_t *pipe = (pipe_t *)pipe_hdl;
  2370. HCD_ENTER_CRITICAL();
  2371. //Check that pipe and port are in the correct state to receive URBs
  2372. HCD_CHECK_FROM_CRIT(pipe->port->state == HCD_PORT_STATE_ENABLED //The pipe's port must be in the correct state
  2373. && pipe->state == HCD_PIPE_STATE_ACTIVE //The pipe must be in the correct state
  2374. && !pipe->cs_flags.pipe_cmd_processing //Pipe cannot currently be processing a pipe command
  2375. && !pipe->cs_flags.reset_lock, //Pipe cannot be persisting through a port reset
  2376. ESP_ERR_INVALID_STATE);
  2377. //Use the URB's reserved_ptr to store the pipe's
  2378. urb->hcd_ptr = (void *)pipe;
  2379. //Add the URB to the pipe's pending tailq
  2380. urb->hcd_var = URB_HCD_STATE_PENDING;
  2381. TAILQ_INSERT_TAIL(&pipe->pending_urb_tailq, urb, tailq_entry);
  2382. pipe->num_urb_pending++;
  2383. //use the URB's reserved_flags to store the URB's current state
  2384. if (_buffer_can_fill(pipe)) {
  2385. _buffer_fill(pipe);
  2386. }
  2387. if (_buffer_can_exec(pipe)) {
  2388. _buffer_exec(pipe);
  2389. }
  2390. if (!pipe->cs_flags.has_urb) {
  2391. //This is the first URB to be enqueued into the pipe. Move the pipe to the list of active pipes
  2392. TAILQ_REMOVE(&pipe->port->pipes_idle_tailq, pipe, tailq_entry);
  2393. TAILQ_INSERT_TAIL(&pipe->port->pipes_active_tailq, pipe, tailq_entry);
  2394. pipe->port->num_pipes_idle--;
  2395. pipe->port->num_pipes_queued++;
  2396. pipe->cs_flags.has_urb = 1;
  2397. }
  2398. HCD_EXIT_CRITICAL();
  2399. return ESP_OK;
  2400. }
  2401. urb_t *hcd_urb_dequeue(hcd_pipe_handle_t pipe_hdl)
  2402. {
  2403. pipe_t *pipe = (pipe_t *)pipe_hdl;
  2404. urb_t *urb;
  2405. HCD_ENTER_CRITICAL();
  2406. if (pipe->num_urb_done > 0) {
  2407. urb = TAILQ_FIRST(&pipe->done_urb_tailq);
  2408. TAILQ_REMOVE(&pipe->done_urb_tailq, urb, tailq_entry);
  2409. pipe->num_urb_done--;
  2410. //Check the URB's reserved fields then reset them
  2411. assert(urb->hcd_ptr == (void *)pipe && urb->hcd_var == URB_HCD_STATE_DONE); //The URB's reserved field should have been set to this pipe
  2412. urb->hcd_ptr = NULL;
  2413. urb->hcd_var = URB_HCD_STATE_IDLE;
  2414. if (pipe->cs_flags.has_urb
  2415. && pipe->num_urb_pending == 0 && pipe->num_urb_done == 0
  2416. && pipe->multi_buffer_control.buffer_num_to_exec == 0 && pipe->multi_buffer_control.buffer_num_to_parse == 0) {
  2417. //This pipe has no more enqueued URBs. Move the pipe to the list of idle pipes
  2418. TAILQ_REMOVE(&pipe->port->pipes_active_tailq, pipe, tailq_entry);
  2419. TAILQ_INSERT_TAIL(&pipe->port->pipes_idle_tailq, pipe, tailq_entry);
  2420. pipe->port->num_pipes_idle++;
  2421. pipe->port->num_pipes_queued--;
  2422. pipe->cs_flags.has_urb = 0;
  2423. }
  2424. } else {
  2425. //No more URBs to dequeue from this pipe
  2426. urb = NULL;
  2427. }
  2428. HCD_EXIT_CRITICAL();
  2429. return urb;
  2430. }
  2431. esp_err_t hcd_urb_abort(urb_t *urb)
  2432. {
  2433. HCD_ENTER_CRITICAL();
  2434. //Check that the URB was enqueued to begin with
  2435. HCD_CHECK_FROM_CRIT(urb->hcd_ptr != NULL && urb->hcd_var != URB_HCD_STATE_IDLE, ESP_ERR_INVALID_STATE);
  2436. if (urb->hcd_var == URB_HCD_STATE_PENDING) {
  2437. //URB has not been executed so it can be aborted
  2438. pipe_t *pipe = (pipe_t *)urb->hcd_ptr;
  2439. //Remove it form the pending queue
  2440. TAILQ_REMOVE(&pipe->pending_urb_tailq, urb, tailq_entry);
  2441. pipe->num_urb_pending--;
  2442. //Add it to the done queue
  2443. TAILQ_INSERT_TAIL(&pipe->done_urb_tailq, urb, tailq_entry);
  2444. pipe->num_urb_done++;
  2445. //Update the URB's current state, status, and actual length
  2446. urb->hcd_var = URB_HCD_STATE_DONE;
  2447. if (urb->transfer.num_isoc_packets == 0) {
  2448. urb->transfer.actual_num_bytes = 0;
  2449. urb->transfer.status = USB_TRANSFER_STATUS_CANCELED;
  2450. } else {
  2451. //If this is an ISOC URB, update the ISO packet descriptors instead
  2452. for (int i = 0; i < urb->transfer.num_isoc_packets; i++) {
  2453. urb->transfer.isoc_packet_desc[i].actual_num_bytes = 0;
  2454. urb->transfer.isoc_packet_desc[i].status = USB_TRANSFER_STATUS_CANCELED;
  2455. }
  2456. }
  2457. } // Otherwise, the URB is in-flight or already done thus cannot be aborted
  2458. HCD_EXIT_CRITICAL();
  2459. return ESP_OK;
  2460. }