hcd.c 103 KB

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