hcd.c 99 KB

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