hcd.c 108 KB

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