hcd.c 102 KB

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