hcd.c 102 KB

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