hcd_dwc.c 102 KB

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