xhci.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  1. #include "xhci.h"
  2. #include "internal.h"
  3. #include <common/kprint.h>
  4. #include <debug/bug.h>
  5. #include <common/spinlock.h>
  6. #include <mm/mm.h>
  7. #include <mm/slab.h>
  8. #include <debug/traceback/traceback.h>
  9. #include <common/time.h>
  10. #include <exception/irq.h>
  11. #include <driver/interrupt/apic/apic.h>
  12. // 由于xhci寄存器读取需要对齐,因此禁用GCC优化选项
  13. #pragma GCC optimize("O0")
  14. spinlock_t xhci_controller_init_lock = {0}; // xhci控制器初始化锁(在usb_init中被初始化)
  15. static int xhci_ctrl_count = 0; // xhci控制器计数
  16. static struct xhci_host_controller_t xhci_hc[XHCI_MAX_HOST_CONTROLLERS] = {0};
  17. void xhci_hc_irq_enable(uint64_t irq_num);
  18. void xhci_hc_irq_disable(uint64_t irq_num);
  19. uint64_t xhci_hc_irq_install(uint64_t irq_num, void *arg);
  20. void xhci_hc_irq_uninstall(uint64_t irq_num);
  21. static int xhci_hc_find_available_id();
  22. static int xhci_hc_stop(int id);
  23. static int xhci_hc_reset(int id);
  24. static int xhci_hc_stop_legacy(int id);
  25. static int xhci_hc_start_sched(int id);
  26. static int xhci_hc_stop_sched(int id);
  27. static uint32_t xhci_hc_get_protocol_offset(int id, uint32_t list_off, const int version, uint32_t *offset, uint32_t *count, uint16_t *protocol_flag);
  28. static int xhci_hc_pair_ports(int id);
  29. static uint64_t xhci_create_ring(int trbs);
  30. static uint64_t xhci_create_event_ring(int trbs, uint64_t *ret_ring_addr);
  31. void xhci_hc_irq_handler(uint64_t irq_num, uint64_t cid, struct pt_regs *regs);
  32. static int xhci_hc_init_intr(int id);
  33. static int xhci_hc_start_ports(int id);
  34. static int xhci_send_command(int id, struct xhci_TRB_t *trb, const bool do_ring);
  35. static uint64_t xhci_initialize_slot(const int id, const int port, const int speed, const int max_packet);
  36. static void xhci_initialize_ep(const int id, const uint64_t slot_vaddr, const int port_id, const int ep_num, const int max_packet, const int max_burst, const int type, const int direction, const int speed, const int ep_interval);
  37. static int xhci_set_address(const int id, const uint64_t slot_vaddr, const int slot_id, const bool block);
  38. static int xhci_control_in(const int id, struct usb_request_packet_t *packet, void *target, const int port_id, const int max_packet);
  39. static int xhci_control_out(const int id, struct usb_request_packet_t *packet, void *target, const int slot_id, const int max_packet);
  40. static int xhci_setup_stage(struct xhci_ep_info_t *ep, const struct usb_request_packet_t *packet, const uint8_t direction);
  41. static int xhci_data_stage(struct xhci_ep_info_t *ep, uint64_t buf_vaddr, uint8_t trb_type, const uint32_t size, uint8_t direction, const int max_packet, const uint64_t status_vaddr);
  42. static int xhci_status_stage(struct xhci_ep_info_t *ep, uint8_t direction, uint64_t status_buf_vaddr);
  43. static int xhci_wait_for_interrupt(const int id, uint64_t status_vaddr);
  44. static inline int xhci_get_desc(const int id, const int port_id, void *target, const uint16_t desc_type, const uint8_t desc_index, const uint16_t lang_id, const uint16_t length);
  45. static int xhci_get_config_desc(const int id, const int port_id, struct usb_config_desc *conf_desc);
  46. static inline int xhci_get_config_desc_full(const int id, const int port_id, const struct usb_config_desc *conf_desc, void *target);
  47. static int xhci_get_interface_desc(const void *in_buf, const uint8_t if_num, struct usb_interface_desc **if_desc);
  48. static inline int xhci_get_endpoint_desc(const struct usb_interface_desc *if_desc, const uint8_t ep_num, struct usb_endpoint_desc **ep_desc);
  49. static int xhci_get_descriptor(const int id, const int port_id, struct usb_device_desc *dev_desc);
  50. static int xhci_configure_port(const int id, const int port_id);
  51. static int xhci_configure_endpoint(const int id, const int port_id, const uint8_t ep_num, const uint8_t ep_type, struct usb_endpoint_desc *ep_desc);
  52. hardware_intr_controller xhci_hc_intr_controller =
  53. {
  54. .enable = xhci_hc_irq_enable,
  55. .disable = xhci_hc_irq_disable,
  56. .install = xhci_hc_irq_install,
  57. .uninstall = xhci_hc_irq_uninstall,
  58. .ack = apic_local_apic_edge_ack,
  59. };
  60. /**
  61. * @brief 在controller数组之中寻找可用插槽
  62. *
  63. * 注意:该函数只能被获得init锁的进程所调用
  64. * @return int 可用id(无空位时返回-1)
  65. */
  66. static int xhci_hc_find_available_id()
  67. {
  68. if (unlikely(xhci_ctrl_count >= XHCI_MAX_HOST_CONTROLLERS))
  69. return -1;
  70. for (int i = 0; i < XHCI_MAX_HOST_CONTROLLERS; ++i)
  71. {
  72. if (xhci_hc[i].pci_dev_hdr == NULL)
  73. return i;
  74. }
  75. return -1;
  76. }
  77. /**
  78. * @brief 从指定地址读取trb
  79. *
  80. * @param trb 要存储到的trb的地址
  81. * @param address 待读取trb的地址
  82. */
  83. static __always_inline void xhci_get_trb(struct xhci_TRB_t *trb, const uint64_t address)
  84. {
  85. trb->param = __read8b(address);
  86. trb->status = __read4b(address + 8);
  87. trb->command = __read4b(address + 12);
  88. }
  89. /**
  90. * @brief 将给定的trb写入指定的地址
  91. *
  92. * @param trb 源trb
  93. * @param address 拷贝的目标地址
  94. */
  95. static __always_inline void xhci_set_trb(struct xhci_TRB_t *trb, const uint64_t address)
  96. {
  97. __write8b(address, trb->param);
  98. __write4b(address + 8, trb->status);
  99. __write4b(address + 12, trb->command);
  100. }
  101. /**
  102. * @brief 将ep结构体写入到设备上下文中的对应块内
  103. *
  104. * @param id 主机控制器id
  105. * @param slot_vaddr 设备上下文虚拟地址
  106. * @param ep_num ep结构体要写入到哪个块中(在设备上下文中的块号)
  107. * @param ep 源数据
  108. */
  109. static __always_inline void __write_ep(int id, uint64_t slot_vaddr, int ep_num, struct xhci_ep_context_t *ep)
  110. {
  111. memcpy((void *)(slot_vaddr + ep_num * xhci_hc[id].context_size), ep, sizeof(struct xhci_ep_context_t));
  112. }
  113. /**
  114. * @brief 从设备上下文中的对应块内读取数据到ep结构体
  115. *
  116. * @param id 主机控制器id
  117. * @param slot_vaddr 设备上下文虚拟地址
  118. * @param ep_num 要从哪个块中读取(在设备上下文中的块号)
  119. * @param ep 目标地址
  120. */
  121. static __always_inline void __read_from_ep(int id, uint64_t slot_vaddr, int ep_num, struct xhci_ep_context_t *ep)
  122. {
  123. memcpy(ep, (void *)(slot_vaddr + ep_num * xhci_hc[id].context_size), sizeof(struct xhci_ep_context_t));
  124. }
  125. /**
  126. * @brief 将slot上下文数组结构体写入插槽的上下文空间
  127. *
  128. * @param vaddr 目标地址
  129. * @param slot_ctx slot上下文数组
  130. */
  131. static __always_inline void __write_slot(const uint64_t vaddr, struct xhci_slot_context_t *slot_ctx)
  132. {
  133. memcpy((void *)vaddr, slot_ctx, sizeof(struct xhci_slot_context_t));
  134. }
  135. /**
  136. * @brief 从指定地址读取slot context
  137. *
  138. * @param slot_ctx 目标地址
  139. * @param slot_vaddr 源地址
  140. * @return __always_inline
  141. */
  142. static __always_inline void __read_from_slot(struct xhci_slot_context_t *slot_ctx, uint64_t slot_vaddr)
  143. {
  144. memcpy(slot_ctx, (void *)slot_vaddr, sizeof(struct xhci_slot_context_t));
  145. }
  146. /**
  147. * @brief 写入doorbell寄存器
  148. *
  149. * @param id 主机控制器id
  150. * @param slot_id usb控制器插槽id(0用作命令门铃,其他的用于具体的设备的门铃)
  151. * @param value endpoint
  152. */
  153. static __always_inline void __xhci_write_doorbell(const int id, const uint16_t slot_id, const uint32_t value)
  154. {
  155. // 确保写入门铃寄存器之前,所有的写操作均已完成
  156. io_mfence();
  157. xhci_write_cap_reg32(id, xhci_hc[id].db_offset + slot_id * sizeof(uint32_t), value);
  158. io_mfence();
  159. }
  160. /**
  161. * @brief 将trb写入指定的ring中,并更新下一个要写入的地址的值
  162. *
  163. * @param ep_info 端点信息结构体
  164. * @param trb 待写入的trb
  165. */
  166. static __always_inline void __xhci_write_trb(struct xhci_ep_info_t *ep_info, struct xhci_TRB_t *trb)
  167. {
  168. memcpy((void *)ep_info->current_ep_ring_vaddr, trb, sizeof(struct xhci_TRB_t));
  169. ep_info->current_ep_ring_vaddr += sizeof(struct xhci_TRB_t);
  170. struct xhci_TRB_normal_t *ptr = (struct xhci_TRB_normal_t *)(ep_info->current_ep_ring_vaddr);
  171. // ring到头了,转换cycle,然后回到第一个trb
  172. if (unlikely(ptr->TRB_type == TRB_TYPE_LINK))
  173. {
  174. ptr->cycle = ep_info->current_ep_ring_cycle;
  175. ep_info->current_ep_ring_vaddr = ep_info->ep_ring_vbase;
  176. ep_info->current_ep_ring_cycle ^= 1;
  177. }
  178. }
  179. /**
  180. * @brief 获取设备上下文缓冲区的虚拟地址
  181. *
  182. * @param id 主机控制器id
  183. * @param port_id 端口id
  184. * @return 设备上下文缓冲区的虚拟地址
  185. */
  186. static __always_inline uint64_t xhci_get_device_context_vaddr(const int id, const int port_id)
  187. {
  188. return (uint64_t)phys_2_virt(__read8b(xhci_hc[id].dcbaap_vaddr + (xhci_hc[id].ports[port_id].slot_id * sizeof(uint64_t))));
  189. }
  190. /**
  191. * @brief 停止xhci主机控制器
  192. *
  193. * @param id 主机控制器id
  194. * @return int
  195. */
  196. static int xhci_hc_stop(int id)
  197. {
  198. // 判断是否已经停止
  199. if (unlikely((xhci_read_op_reg32(id, XHCI_OPS_USBSTS) & (1 << 0)) == 1))
  200. return 0;
  201. io_mfence();
  202. xhci_write_op_reg32(id, XHCI_OPS_USBCMD, 0x00000000);
  203. io_mfence();
  204. char timeout = 17;
  205. while ((xhci_read_op_reg32(id, XHCI_OPS_USBSTS) & (1 << 0)) == 0)
  206. {
  207. io_mfence();
  208. usleep(1000);
  209. if (--timeout == 0)
  210. return -ETIMEDOUT;
  211. }
  212. return 0;
  213. }
  214. /**
  215. * @brief reset xHCI主机控制器
  216. *
  217. * @param id 主机控制器id
  218. * @return int
  219. */
  220. static int xhci_hc_reset(int id)
  221. {
  222. int retval = 0;
  223. io_mfence();
  224. // 判断HCHalted是否置位
  225. if ((xhci_read_op_reg32(id, XHCI_OPS_USBSTS) & (1 << 0)) == 0)
  226. {
  227. io_mfence();
  228. kdebug("stopping usb hc...");
  229. // 未置位,需要先尝试停止usb主机控制器
  230. retval = xhci_hc_stop(id);
  231. if (unlikely(retval))
  232. return retval;
  233. }
  234. int timeout = 500; // wait 500ms
  235. // reset
  236. uint32_t cmd = xhci_read_op_reg32(id, XHCI_OPS_USBCMD);
  237. io_mfence();
  238. cmd |= (1 << 1);
  239. xhci_write_op_reg32(id, XHCI_OPS_USBCMD, cmd);
  240. io_mfence();
  241. io_mfence();
  242. while (xhci_read_op_reg32(id, XHCI_OPS_USBCMD) & (1 << 1))
  243. {
  244. io_mfence();
  245. usleep(1000);
  246. if (--timeout == 0)
  247. return -ETIMEDOUT;
  248. }
  249. return retval;
  250. }
  251. /**
  252. * @brief 停止指定xhci控制器的legacy support
  253. *
  254. * @param id 控制器id
  255. * @return int
  256. */
  257. static int xhci_hc_stop_legacy(int id)
  258. {
  259. uint64_t current_offset = xhci_hc[id].ext_caps_off;
  260. do
  261. {
  262. // 判断当前entry是否为legacy support entry
  263. if ((xhci_read_cap_reg32(id, current_offset) & 0xff) == XHCI_XECP_ID_LEGACY)
  264. {
  265. io_mfence();
  266. // 接管控制权
  267. xhci_write_cap_reg32(id, current_offset, xhci_read_cap_reg32(id, current_offset) | XHCI_XECP_LEGACY_OS_OWNED);
  268. io_mfence();
  269. // 等待响应完成
  270. int timeout = XHCI_XECP_LEGACY_TIMEOUT;
  271. while ((xhci_read_cap_reg32(id, current_offset) & XHCI_XECP_LEGACY_OWNING_MASK) != XHCI_XECP_LEGACY_OS_OWNED)
  272. {
  273. io_mfence();
  274. usleep(1000);
  275. if (--timeout == 0)
  276. {
  277. kerror("The BIOS doesn't stop legacy support.");
  278. return -ETIMEDOUT;
  279. }
  280. }
  281. // 处理完成
  282. return 0;
  283. }
  284. io_mfence();
  285. // 读取下一个entry的偏移增加量
  286. int next_off = ((xhci_read_cap_reg32(id, current_offset) & 0xff00) >> 8) << 2;
  287. io_mfence();
  288. // 将指针跳转到下一个entry
  289. current_offset = next_off ? (current_offset + next_off) : 0;
  290. } while (current_offset);
  291. // 当前controller不存在legacy支持,也问题不大,不影响
  292. return 0;
  293. }
  294. /**
  295. * @brief 启用指定xhci控制器的调度
  296. *
  297. * @param id 控制器id
  298. * @return int
  299. */
  300. static int xhci_hc_start_sched(int id)
  301. {
  302. io_mfence();
  303. xhci_write_op_reg32(id, XHCI_OPS_USBCMD, (1 << 0) | (1 << 2) | (1 << 3));
  304. io_mfence();
  305. usleep(100 * 1000);
  306. }
  307. /**
  308. * @brief 停止指定xhci控制器的调度
  309. *
  310. * @param id 控制器id
  311. * @return int
  312. */
  313. static int xhci_hc_stop_sched(int id)
  314. {
  315. io_mfence();
  316. xhci_write_op_reg32(id, XHCI_OPS_USBCMD, 0x00);
  317. io_mfence();
  318. }
  319. /**
  320. * @brief 在Ex capability list中寻找符合指定的协议号的寄存器offset、count、flag信息
  321. *
  322. * @param id 主机控制器id
  323. * @param list_off 列表项位置距离控制器虚拟基地址的偏移量
  324. * @param version 要寻找的端口版本号(2或3)
  325. * @param offset 返回的 Compatible Port Offset
  326. * @param count 返回的 Compatible Port Count
  327. * @param protocol_flag 返回的与协议相关的flag
  328. * @return uint32_t 下一个列表项的偏移量
  329. */
  330. static uint32_t xhci_hc_get_protocol_offset(int id, uint32_t list_off, const int version, uint32_t *offset, uint32_t *count, uint16_t *protocol_flag)
  331. {
  332. if (count)
  333. *count = 0;
  334. do
  335. {
  336. uint32_t dw0 = xhci_read_cap_reg32(id, list_off);
  337. io_mfence();
  338. uint32_t next_list_off = (dw0 >> 8) & 0xff;
  339. next_list_off = next_list_off ? (list_off + (next_list_off << 2)) : 0;
  340. if ((dw0 & 0xff) == XHCI_XECP_ID_PROTOCOL && ((dw0 & 0xff000000) >> 24) == version)
  341. {
  342. uint32_t dw2 = xhci_read_cap_reg32(id, list_off + 8);
  343. io_mfence();
  344. if (offset != NULL)
  345. *offset = (uint32_t)(dw2 & 0xff) - 1; // 使其转换为zero based
  346. if (count != NULL)
  347. *count = (uint32_t)((dw2 & 0xff00) >> 8);
  348. if (protocol_flag != NULL && version == 2)
  349. *protocol_flag = (uint16_t)((dw2 >> 16) & 0x0fff);
  350. return next_list_off;
  351. }
  352. list_off = next_list_off;
  353. } while (list_off);
  354. return 0;
  355. }
  356. /**
  357. * @brief 配对xhci主机控制器的usb2、usb3端口
  358. *
  359. * @param id 主机控制器id
  360. * @return int 返回码
  361. */
  362. static int xhci_hc_pair_ports(int id)
  363. {
  364. struct xhci_caps_HCSPARAMS1_reg_t hcs1;
  365. io_mfence();
  366. memcpy(&hcs1, xhci_get_ptr_cap_reg32(id, XHCI_CAPS_HCSPARAMS1), sizeof(struct xhci_caps_HCSPARAMS1_reg_t));
  367. io_mfence();
  368. // 从hcs1获取端口数量
  369. xhci_hc[id].port_num = hcs1.max_ports;
  370. // 找到所有的端口并标记其端口信息
  371. xhci_hc[id].port_num_u2 = 0;
  372. xhci_hc[id].port_num_u3 = 0;
  373. uint32_t next_off = xhci_hc[id].ext_caps_off;
  374. uint32_t offset, cnt;
  375. uint16_t protocol_flags = 0;
  376. // 寻找所有的usb2端口
  377. while (next_off)
  378. {
  379. io_mfence();
  380. next_off = xhci_hc_get_protocol_offset(id, next_off, 2, &offset, &cnt, &protocol_flags);
  381. io_mfence();
  382. if (cnt)
  383. {
  384. for (int i = 0; i < cnt; ++i)
  385. {
  386. io_mfence();
  387. xhci_hc[id].ports[offset + i].offset = xhci_hc[id].port_num_u2++;
  388. xhci_hc[id].ports[offset + i].flags = XHCI_PROTOCOL_USB2;
  389. io_mfence();
  390. // usb2 high speed only
  391. if (protocol_flags & 2)
  392. xhci_hc[id].ports[offset + i].flags |= XHCI_PROTOCOL_HSO;
  393. }
  394. }
  395. }
  396. // 寻找所有的usb3端口
  397. next_off = xhci_hc[id].ext_caps_off;
  398. while (next_off)
  399. {
  400. io_mfence();
  401. next_off = xhci_hc_get_protocol_offset(id, next_off, 3, &offset, &cnt, &protocol_flags);
  402. io_mfence();
  403. if (cnt)
  404. {
  405. for (int i = 0; i < cnt; ++i)
  406. {
  407. io_mfence();
  408. xhci_hc[id].ports[offset + i].offset = xhci_hc[id].port_num_u3++;
  409. xhci_hc[id].ports[offset + i].flags = XHCI_PROTOCOL_USB3;
  410. }
  411. }
  412. }
  413. // 将对应的USB2端口和USB3端口进行配对
  414. for (int i = 0; i < xhci_hc[id].port_num; ++i)
  415. {
  416. for (int j = 0; j < xhci_hc[id].port_num; ++j)
  417. {
  418. if (unlikely(i == j))
  419. continue;
  420. io_mfence();
  421. if ((xhci_hc[id].ports[i].offset == xhci_hc[id].ports[j].offset) &&
  422. ((xhci_hc[id].ports[i].flags & XHCI_PROTOCOL_INFO) != (xhci_hc[id].ports[j].flags & XHCI_PROTOCOL_INFO)))
  423. {
  424. xhci_hc[id].ports[i].paired_port_num = j;
  425. xhci_hc[id].ports[i].flags |= XHCI_PROTOCOL_HAS_PAIR;
  426. io_mfence();
  427. xhci_hc[id].ports[j].paired_port_num = i;
  428. xhci_hc[id].ports[j].flags |= XHCI_PROTOCOL_HAS_PAIR;
  429. }
  430. }
  431. }
  432. // 标记所有的usb3、单独的usb2端口为激活状态
  433. for (int i = 0; i < xhci_hc[id].port_num; ++i)
  434. {
  435. io_mfence();
  436. if (XHCI_PORT_IS_USB3(id, i) ||
  437. (XHCI_PORT_IS_USB2(id, i) && (!XHCI_PORT_HAS_PAIR(id, i))))
  438. xhci_hc[id].ports[i].flags |= XHCI_PROTOCOL_ACTIVE;
  439. }
  440. kinfo("Found %d ports on root hub, usb2 ports:%d, usb3 ports:%d", xhci_hc[id].port_num, xhci_hc[id].port_num_u2, xhci_hc[id].port_num_u3);
  441. /*
  442. // 打印配对结果
  443. for (int i = 1; i <= xhci_hc[id].port_num; ++i)
  444. {
  445. if (XHCI_PORT_IS_USB3(id, i))
  446. {
  447. kdebug("USB3 port %d, offset=%d, pair with usb2 port %d, current port is %s", i, xhci_hc[id].ports[i].offset,
  448. xhci_hc[id].ports[i].paired_port_num, XHCI_PORT_IS_ACTIVE(id, i) ? "active" : "inactive");
  449. }
  450. else if (XHCI_PORT_IS_USB2(id, i) && (!XHCI_PORT_HAS_PAIR(id, i))) // 单独的2.0接口
  451. {
  452. kdebug("Stand alone USB2 port %d, offset=%d, current port is %s", i, xhci_hc[id].ports[i].offset,
  453. XHCI_PORT_IS_ACTIVE(id, i) ? "active" : "inactive");
  454. }
  455. else if (XHCI_PORT_IS_USB2(id, i))
  456. {
  457. kdebug("USB2 port %d, offset=%d, current port is %s, has pair=%s", i, xhci_hc[id].ports[i].offset,
  458. XHCI_PORT_IS_ACTIVE(id, i) ? "active" : "inactive", XHCI_PORT_HAS_PAIR(id, i) ? "true" : "false");
  459. }
  460. }
  461. */
  462. return 0;
  463. }
  464. /**
  465. * @brief 创建ring,并将最后一个trb指向头一个trb
  466. *
  467. * @param trbs 要创建的trb数量
  468. * @return uint64_t trb数组的起始虚拟地址
  469. */
  470. static uint64_t xhci_create_ring(int trbs)
  471. {
  472. int total_size = trbs * sizeof(struct xhci_TRB_t);
  473. const uint64_t vaddr = (uint64_t)kmalloc(total_size, 0);
  474. io_mfence();
  475. memset((void *)vaddr, 0, total_size);
  476. io_mfence();
  477. // 设置最后一个trb为link trb
  478. xhci_TRB_set_link_cmd(vaddr + total_size - sizeof(struct xhci_TRB_t));
  479. io_mfence();
  480. return vaddr;
  481. }
  482. /**
  483. * @brief 创建新的event ring table和对应的ring segment
  484. *
  485. * @param trbs 包含的trb的数量
  486. * @param ret_ring_addr 返回的第一个event ring segment的基地址(虚拟)
  487. * @return uint64_t trb table的虚拟地址
  488. */
  489. static uint64_t xhci_create_event_ring(int trbs, uint64_t *ret_ring_addr)
  490. {
  491. const uint64_t table_vaddr = (const uint64_t)kmalloc(64, 0); // table支持8个segment
  492. io_mfence();
  493. if (unlikely(table_vaddr == NULL))
  494. return -ENOMEM;
  495. memset((void *)table_vaddr, 0, 64);
  496. // 暂时只创建1个segment
  497. const uint64_t seg_vaddr = (const uint64_t)kmalloc(trbs * sizeof(struct xhci_TRB_t), 0);
  498. io_mfence();
  499. if (unlikely(seg_vaddr == NULL))
  500. return -ENOMEM;
  501. memset((void *)seg_vaddr, 0, trbs * sizeof(struct xhci_TRB_t));
  502. io_mfence();
  503. // 将segment地址和大小写入table
  504. *(uint64_t *)(table_vaddr) = virt_2_phys(seg_vaddr);
  505. *(uint64_t *)(table_vaddr + 8) = trbs;
  506. *ret_ring_addr = seg_vaddr;
  507. return table_vaddr;
  508. }
  509. void xhci_hc_irq_enable(uint64_t irq_num)
  510. {
  511. int cid = xhci_find_hcid_by_irq_num(irq_num);
  512. io_mfence();
  513. if (WARN_ON(cid == -1))
  514. return;
  515. io_mfence();
  516. pci_start_msi(xhci_hc[cid].pci_dev_hdr);
  517. io_mfence();
  518. xhci_hc_start_sched(cid);
  519. io_mfence();
  520. xhci_hc_start_ports(cid);
  521. }
  522. void xhci_hc_irq_disable(uint64_t irq_num)
  523. {
  524. int cid = xhci_find_hcid_by_irq_num(irq_num);
  525. io_mfence();
  526. if (WARN_ON(cid == -1))
  527. return;
  528. xhci_hc_stop_sched(cid);
  529. io_mfence();
  530. pci_disable_msi(xhci_hc[cid].pci_dev_hdr);
  531. io_mfence();
  532. }
  533. /**
  534. * @brief xhci中断的安装函数
  535. *
  536. * @param irq_num 要安装的中断向量号
  537. * @param arg 参数
  538. * @return uint64_t 错误码
  539. */
  540. uint64_t xhci_hc_irq_install(uint64_t irq_num, void *arg)
  541. {
  542. int cid = xhci_find_hcid_by_irq_num(irq_num);
  543. io_mfence();
  544. if (WARN_ON(cid == -1))
  545. return -EINVAL;
  546. struct xhci_hc_irq_install_info_t *info = (struct xhci_hc_irq_install_info_t *)arg;
  547. struct msi_desc_t msi_desc;
  548. memset(&msi_desc, 0, sizeof(struct msi_desc_t));
  549. io_mfence();
  550. msi_desc.irq_num = irq_num;
  551. msi_desc.msi_index = 0;
  552. msi_desc.pci_dev = (struct pci_device_structure_header_t *)xhci_hc[cid].pci_dev_hdr;
  553. msi_desc.assert = info->assert;
  554. msi_desc.edge_trigger = info->edge_trigger;
  555. msi_desc.processor = info->processor;
  556. msi_desc.pci.msi_attribute.is_64 = 1;
  557. msi_desc.pci.msi_attribute.is_msix = 1;
  558. io_mfence();
  559. int retval = pci_enable_msi(&msi_desc);
  560. return 0;
  561. }
  562. void xhci_hc_irq_uninstall(uint64_t irq_num)
  563. {
  564. // todo
  565. int cid = xhci_find_hcid_by_irq_num(irq_num);
  566. io_mfence();
  567. if (WARN_ON(cid == -1))
  568. return;
  569. xhci_hc_stop(cid);
  570. io_mfence();
  571. }
  572. /**
  573. * @brief xhci主机控制器的中断处理函数
  574. *
  575. * @param irq_num 中断向量号
  576. * @param cid 控制器号
  577. * @param regs 寄存器值
  578. */
  579. void xhci_hc_irq_handler(uint64_t irq_num, uint64_t cid, struct pt_regs *regs)
  580. {
  581. // kdebug("USB irq received.");
  582. /*
  583. 写入usb status寄存器,以表明当前收到了中断,清除usb status寄存器中的EINT位
  584. 需要先清除这个位,再清除interrupter中的pending bit)
  585. */
  586. xhci_write_op_reg32(cid, XHCI_OPS_USBSTS, xhci_read_op_reg32(cid, XHCI_OPS_USBSTS));
  587. // 读取第0个usb interrupter的intr management寄存器
  588. const uint32_t iman0 = xhci_read_intr_reg32(cid, 0, XHCI_IR_MAN);
  589. uint64_t dequeue_reg = xhci_read_intr_reg64(cid, 0, XHCI_IR_DEQUEUE);
  590. if (((iman0 & 3) == 3) || (dequeue_reg & 8)) // 中断被启用,且pending不为0
  591. {
  592. // kdebug("to handle");
  593. // 写入1以清除该interrupter的pending bit
  594. xhci_write_intr_reg32(cid, 0, XHCI_IR_MAN, iman0 | 3);
  595. io_mfence();
  596. struct xhci_TRB_t event_trb, origin_trb; // event ring trb以及其对应的command trb
  597. uint64_t origin_vaddr;
  598. // 暂存当前trb的起始地址
  599. uint64_t last_event_ring_vaddr = xhci_hc[cid].current_event_ring_vaddr;
  600. xhci_get_trb(&event_trb, xhci_hc[cid].current_event_ring_vaddr);
  601. {
  602. struct xhci_TRB_cmd_complete_t *event_trb_ptr = (struct xhci_TRB_cmd_complete_t *)&event_trb;
  603. // kdebug("TRB_type=%d, comp_code=%d", event_trb_ptr->TRB_type, event_trb_ptr->code);
  604. }
  605. while ((event_trb.command & 1) == xhci_hc[cid].current_event_ring_cycle) // 循环处理处于当前周期的所有event ring
  606. {
  607. struct xhci_TRB_cmd_complete_t *event_trb_ptr = (struct xhci_TRB_cmd_complete_t *)&event_trb;
  608. // kdebug("TRB_type=%d, comp_code=%d", event_trb_ptr->TRB_type, event_trb_ptr->code);
  609. if ((event_trb.command & (1 << 2)) == 0) // 当前event trb不是由于short packet产生的
  610. {
  611. // kdebug("event_trb_ptr->code=%d", event_trb_ptr->code);
  612. // kdebug("event_trb_ptr->TRB_type=%d", event_trb_ptr->TRB_type);
  613. switch (event_trb_ptr->code) // 判断它的完成码
  614. {
  615. case TRB_COMP_TRB_SUCCESS: // trb执行成功,则将结果返回到对应的command ring的trb里面
  616. switch (event_trb_ptr->TRB_type) // 根据event trb类型的不同,采取不同的措施
  617. {
  618. case TRB_TYPE_COMMAND_COMPLETION: // 命令已经完成
  619. origin_vaddr = (uint64_t)phys_2_virt(event_trb.param);
  620. // 获取对应的command trb
  621. xhci_get_trb(&origin_trb, origin_vaddr);
  622. switch (((struct xhci_TRB_normal_t *)&origin_trb)->TRB_type)
  623. {
  624. case TRB_TYPE_ENABLE_SLOT: // 源命令为enable slot
  625. // 将slot id返回到命令TRB的command字段中
  626. origin_trb.command &= 0x00ffffff;
  627. origin_trb.command |= (event_trb.command & 0xff000000);
  628. origin_trb.status = event_trb.status;
  629. break;
  630. default:
  631. origin_trb.status = event_trb.status;
  632. break;
  633. }
  634. // 标记该命令已经执行完成
  635. origin_trb.status |= XHCI_IRQ_DONE;
  636. // 将command trb写入到表中
  637. xhci_set_trb(&origin_trb, origin_vaddr);
  638. // kdebug("set origin:%#018lx", origin_vaddr);
  639. break;
  640. }
  641. break;
  642. default:
  643. break;
  644. }
  645. }
  646. else // 当前TRB是由short packet产生的
  647. {
  648. switch (event_trb_ptr->TRB_type)
  649. {
  650. case TRB_TYPE_TRANS_EVENT: // 当前 event trb是 transfer event TRB
  651. // If SPD was encountered in this TD, comp_code will be SPD, else it should be SUCCESS (specs 4.10.1.1)
  652. __write4b((uint64_t)phys_2_virt(event_trb.param), (event_trb.status | XHCI_IRQ_DONE)); // return code + bytes *not* transferred
  653. break;
  654. default:
  655. break;
  656. }
  657. }
  658. // 获取下一个event ring TRB
  659. last_event_ring_vaddr = xhci_hc[cid].current_event_ring_vaddr;
  660. xhci_hc[cid].current_event_ring_vaddr += sizeof(struct xhci_TRB_t);
  661. xhci_get_trb(&event_trb, xhci_hc[cid].current_event_ring_vaddr);
  662. if (((struct xhci_TRB_normal_t *)&event_trb)->TRB_type == TRB_TYPE_LINK)
  663. {
  664. xhci_hc[cid].current_event_ring_vaddr = xhci_hc[cid].event_ring_vaddr;
  665. xhci_get_trb(&event_trb, xhci_hc[cid].current_event_ring_vaddr);
  666. }
  667. }
  668. // 当前event ring cycle的TRB处理结束
  669. // 更新dequeue指针, 并清除event handler busy标志位
  670. xhci_write_intr_reg64(cid, 0, XHCI_IR_DEQUEUE, virt_2_phys(last_event_ring_vaddr) | (1 << 3));
  671. io_mfence();
  672. }
  673. }
  674. /**
  675. * @brief 重置端口
  676. *
  677. * @param id 控制器id
  678. * @param port 端口id
  679. * @return int
  680. */
  681. static int xhci_reset_port(const int id, const int port)
  682. {
  683. int retval = 0;
  684. // 相对于op寄存器基地址的偏移量
  685. uint64_t port_status_offset = XHCI_OPS_PRS + port * 16;
  686. io_mfence();
  687. // 检查端口电源状态
  688. if ((xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC) & (1 << 9)) == 0)
  689. {
  690. kdebug("port is power off, starting...");
  691. io_mfence();
  692. xhci_write_cap_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9));
  693. io_mfence();
  694. usleep(2000);
  695. // 检测端口是否被启用, 若未启用,则报错
  696. if ((xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC) & (1 << 9)) == 0)
  697. {
  698. kdebug("cannot power on %d", port);
  699. return -EAGAIN;
  700. }
  701. }
  702. // kdebug("port:%d, power check ok", port);
  703. io_mfence();
  704. // 确保端口的status被清0
  705. xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | XHCI_PORTUSB_CHANGE_BITS);
  706. // kdebug("to reset timeout;");
  707. io_mfence();
  708. // 重置当前端口
  709. if (XHCI_PORT_IS_USB3(id, port))
  710. xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | (1 << 31));
  711. else
  712. xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | (1 << 4));
  713. retval = -ETIMEDOUT;
  714. // kdebug("to wait reset timeout;");
  715. // 等待portsc的port reset change位被置位,说明reset完成
  716. int timeout = 100;
  717. while (timeout)
  718. {
  719. io_mfence();
  720. uint32_t val = xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC);
  721. io_mfence();
  722. if (val & (1 << 21))
  723. break;
  724. // QEMU对usb的模拟有bug,因此需要检测这里
  725. #ifdef __QEMU_EMULATION__
  726. if (XHCI_PORT_IS_USB3(id, port) && (val & (1 << 31)) == 0)
  727. break;
  728. else if (XHCI_PORT_IS_USB2(id, port) && (val & (1 << 4)) == 0)
  729. break;
  730. #endif
  731. --timeout;
  732. usleep(500);
  733. }
  734. // kdebug("timeout= %d", timeout);
  735. if (timeout > 0)
  736. {
  737. // 等待恢复
  738. usleep(USB_TIME_RST_REC * 100);
  739. uint32_t val = xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC);
  740. io_mfence();
  741. // kdebug("to check if reset ok, val=%#010lx", val);
  742. // 如果reset之后,enable bit仍然是1,那么说明reset成功
  743. if (val & (1 << 1))
  744. {
  745. // kdebug("reset ok");
  746. retval = 0;
  747. io_mfence();
  748. // 清除status change bit
  749. xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | XHCI_PORTUSB_CHANGE_BITS);
  750. io_mfence();
  751. }
  752. else
  753. retval = -1;
  754. }
  755. // kdebug("reset ok!");
  756. // 如果usb2端口成功reset,则处理该端口的active状态
  757. if (retval == 0 && XHCI_PORT_IS_USB2(id, port))
  758. {
  759. xhci_hc[id].ports[port].flags |= XHCI_PROTOCOL_ACTIVE;
  760. if (XHCI_PORT_HAS_PAIR(id, port)) // 如果有对应的usb3端口,则将usb3端口设置为未激活
  761. xhci_hc[id].ports[xhci_hc[id].ports[port].paired_port_num].flags &= ~(XHCI_PROTOCOL_ACTIVE);
  762. }
  763. // 如果usb3端口reset失败,则启用与之配对的usb2端口
  764. if (retval != 0 && XHCI_PORT_IS_USB3(id, port))
  765. {
  766. xhci_hc[id].ports[port].flags &= ~XHCI_PROTOCOL_ACTIVE;
  767. xhci_hc[id].ports[xhci_hc[id].ports[port].paired_port_num].flags |= XHCI_PROTOCOL_ACTIVE;
  768. }
  769. return retval;
  770. }
  771. /**
  772. * @brief 初始化设备slot的上下文,并将其写入dcbaap中的上下文index数组
  773. * - at this time, we don't know if the device is a hub or not, so we don't
  774. * set the slot->hub, ->mtt, ->ttt, ->etc, items.
  775. *
  776. * @param id 控制器id
  777. * @param port 端口号
  778. * @param speed 端口速度
  779. * @param max_packet 最大数据包大小
  780. * @return uint64_t 初始化好的设备上下文空间的虚拟地址
  781. */
  782. static uint64_t xhci_initialize_slot(const int id, const int port, const int speed, const int max_packet)
  783. {
  784. // 为所有的endpoint分配上下文空间
  785. // todo: 按需分配上下文空间
  786. uint64_t device_context_vaddr = (uint64_t)kzalloc(xhci_hc[id].context_size * 32, 0);
  787. // kdebug("slot id=%d, device_context_vaddr=%#018lx, port=%d", slot_id, device_context_vaddr, port);
  788. // 写到数组中
  789. __write8b(xhci_hc[id].dcbaap_vaddr + (xhci_hc[id].ports[port].slot_id * sizeof(uint64_t)), virt_2_phys(device_context_vaddr));
  790. struct xhci_slot_context_t slot_ctx = {0};
  791. slot_ctx.entries = 1;
  792. slot_ctx.speed = speed;
  793. slot_ctx.route_string = 0;
  794. slot_ctx.rh_port_num = port + 1; // 由于xhci控制器是1-base的,因此把驱动程序中存储的端口号加1,才是真实的端口号
  795. slot_ctx.max_exit_latency = 0; // 稍后会计算这个值
  796. slot_ctx.int_target = 0; // 当前全部使用第0个interrupter
  797. slot_ctx.slot_state = XHCI_SLOT_STATE_DISABLED_OR_ENABLED;
  798. slot_ctx.device_address = 0;
  799. // 将slot信息写入上下文空间
  800. __write_slot(device_context_vaddr, &slot_ctx);
  801. // 初始化控制端点
  802. xhci_initialize_ep(id, device_context_vaddr, port, XHCI_EP_CONTROL, max_packet, 0, USB_EP_CONTROL, 0, speed, 0);
  803. return device_context_vaddr;
  804. }
  805. /**
  806. * @brief 初始化endpoint
  807. *
  808. * @param id 控制器id
  809. * @param slot_vaddr slot上下文的虚拟地址
  810. * @param port_id 插槽id
  811. * @param ep_num 端点上下文在slot上下文区域内的编号
  812. * @param max_packet 最大数据包大小
  813. * @param type 端点类型
  814. * @param direction 传输方向
  815. * @param speed 传输速度
  816. * @param ep_interval 端点的连续请求间隔
  817. */
  818. static void xhci_initialize_ep(const int id, const uint64_t slot_vaddr, const int port_id, const int ep_num, const int max_packet, const int max_burst, const int type, const int direction, const int speed, const int ep_interval)
  819. {
  820. // 由于目前只实现获取设备的描述符,因此暂时只支持control ep
  821. if (type != USB_EP_CONTROL && type != USB_EP_INTERRUPT)
  822. return;
  823. struct xhci_ep_context_t ep_ctx = {0};
  824. memset(&ep_ctx, 0, sizeof(struct xhci_ep_context_t));
  825. xhci_hc[id].ports[port_id].ep_info[ep_num].ep_ring_vbase = xhci_create_ring(XHCI_TRBS_PER_RING);
  826. // 申请ep的 transfer ring
  827. ep_ctx.tr_dequeue_ptr = virt_2_phys(xhci_hc[id].ports[port_id].ep_info[ep_num].ep_ring_vbase);
  828. xhci_ep_set_dequeue_cycle_state(&ep_ctx, XHCI_TRB_CYCLE_ON);
  829. xhci_hc[id].ports[port_id].ep_info[ep_num].current_ep_ring_vaddr = xhci_hc[id].ports[port_id].ep_info[ep_num].ep_ring_vbase;
  830. xhci_hc[id].ports[port_id].ep_info[ep_num].current_ep_ring_cycle = xhci_ep_get_dequeue_cycle_state(&ep_ctx);
  831. // kdebug("ep_ctx.tr_dequeue_ptr = %#018lx", ep_ctx.tr_dequeue_ptr);
  832. // kdebug("xhci_hc[id].control_ep_info.current_ep_ring_cycle = %d", xhci_hc[id].control_ep_info.current_ep_ring_cycle);
  833. kdebug("max_packet=%d, max_burst=%d", max_packet, max_burst);
  834. switch (type)
  835. {
  836. case USB_EP_CONTROL: // Control ep
  837. // 设置初始值
  838. ep_ctx.max_packet_size = max_packet;
  839. ep_ctx.linear_stream_array = 0;
  840. ep_ctx.max_primary_streams = 0;
  841. ep_ctx.mult = 0;
  842. ep_ctx.ep_state = XHCI_EP_STATE_DISABLED;
  843. ep_ctx.hid = 0;
  844. ep_ctx.ep_type = XHCI_EP_TYPE_CONTROL;
  845. ep_ctx.average_trb_len = 8; // 所有的control ep的该值均为8
  846. ep_ctx.err_cnt = 3;
  847. ep_ctx.max_burst_size = max_burst;
  848. ep_ctx.interval = ep_interval;
  849. break;
  850. case USB_EP_INTERRUPT:
  851. ep_ctx.max_packet_size = max_packet & 0x7ff;
  852. ep_ctx.max_burst_size = max_burst;
  853. ep_ctx.ep_state = XHCI_EP_STATE_DISABLED;
  854. ep_ctx.mult = 0;
  855. ep_ctx.err_cnt = 3;
  856. ep_ctx.max_esti_payload_hi = ((max_packet * (max_burst + 1)) >> 8) & 0xff;
  857. ep_ctx.max_esti_payload_lo = ((max_packet * (max_burst + 1))) & 0xff;
  858. ep_ctx.interval = ep_interval;
  859. ep_ctx.average_trb_len = 8; // todo: It's not sure how much to fill in this value
  860. // ep_ctx.ep_type = XHCI_EP_TYPE_INTR_IN;
  861. ep_ctx.ep_type = ((ep_num % 2) ? XHCI_EP_TYPE_INTR_IN : XHCI_EP_TYPE_INTR_OUT);
  862. break;
  863. default:
  864. break;
  865. }
  866. // 将ep的信息写入到slot上下文中对应的ep的块中
  867. __write_ep(id, slot_vaddr, ep_num, &ep_ctx);
  868. }
  869. /**
  870. * @brief 向usb控制器发送 address_device命令
  871. *
  872. * @param id 主机控制器id
  873. * @param slot_vaddr 插槽上下文的虚拟基地址
  874. * @param slot_id 插槽id
  875. * @param block 是否阻断 set address 信息向usb设备的传输
  876. * @return int 错误码
  877. */
  878. static int xhci_set_address(const int id, const uint64_t slot_vaddr, const int slot_id, const bool block)
  879. {
  880. int retval = 0;
  881. struct xhci_slot_context_t slot;
  882. struct xhci_ep_context_t ep;
  883. // 创建输入上下文缓冲区
  884. uint64_t input_ctx_buffer = (uint64_t)kzalloc(xhci_hc[id].context_size * 33, 0);
  885. // 置位input control context和slot context的add bit
  886. __write4b(input_ctx_buffer + 4, 0x3);
  887. // 拷贝slot上下文和control ep上下文到输入上下文中
  888. // __write_ep(id, input_ctx_buffer, 2, &ep_ctx);
  889. __read_from_slot(&slot, slot_vaddr);
  890. __read_from_ep(id, slot_vaddr, 1, &ep);
  891. ep.err_cnt = 3;
  892. kdebug("slot.slot_state=%d, speed=%d, root hub port num=%d", slot.slot_state, slot.speed, slot.rh_port_num);
  893. kdebug("ep.type=%d, max_packet=%d, dequeue_ptr=%#018lx", ep.ep_type, ep.max_packet_size, ep.tr_dequeue_ptr);
  894. __write_slot(input_ctx_buffer + xhci_hc[id].context_size, &slot);
  895. __write_ep(id, input_ctx_buffer, 2, &ep);
  896. struct xhci_TRB_normal_t trb = {0};
  897. trb.buf_paddr = virt_2_phys(input_ctx_buffer);
  898. trb.bei = (block ? 1 : 0);
  899. trb.TRB_type = TRB_TYPE_ADDRESS_DEVICE;
  900. trb.intr_target = 0;
  901. trb.cycle = xhci_hc[id].cmd_trb_cycle;
  902. trb.Reserved |= ((slot_id << 8) & 0xffff);
  903. retval = xhci_send_command(id, (struct xhci_TRB_t *)&trb, true);
  904. if (unlikely(retval != 0))
  905. {
  906. kerror("slotid:%d, address device failed", slot_id);
  907. goto failed;
  908. }
  909. struct xhci_TRB_cmd_complete_t *trb_done = (struct xhci_TRB_cmd_complete_t *)&trb;
  910. if (trb_done->code == TRB_COMP_TRB_SUCCESS) // 成功执行
  911. {
  912. // 如果要从控制器获取刚刚设置的设备地址的话,可以在这里读取slot context
  913. ksuccess("slot %d successfully addressed.", slot_id);
  914. retval = 0;
  915. }
  916. else
  917. retval = -EAGAIN;
  918. done:;
  919. failed:;
  920. kfree((void *)input_ctx_buffer);
  921. return retval;
  922. }
  923. /**
  924. * @brief 在指定的端点的ring中,写入一个setup stage TRB
  925. *
  926. * @param ep 端点信息结构体
  927. * @param packet usb请求包
  928. * @param direction 传输的方向
  929. * @return int 产生的TRB数量
  930. */
  931. static int xhci_setup_stage(struct xhci_ep_info_t *ep, const struct usb_request_packet_t *packet, const uint8_t direction)
  932. {
  933. // kdebug("ep->current_ep_ring_cycle=%d", ep->current_ep_ring_cycle);
  934. struct xhci_TRB_setup_stage_t trb = {0};
  935. trb.bmRequestType = packet->request_type;
  936. trb.bRequest = packet->request;
  937. trb.wValue = packet->value;
  938. trb.wIndex = packet->index;
  939. trb.wLength = packet->length;
  940. trb.transfer_legth = 8;
  941. trb.intr_target = 0; // 使用第0个interrupter
  942. trb.cycle = ep->current_ep_ring_cycle;
  943. trb.ioc = 0;
  944. trb.idt = 1;
  945. trb.TRB_type = TRB_TYPE_SETUP_STAGE;
  946. trb.trt = direction;
  947. // 将setup stage trb拷贝到ep的transfer ring中
  948. __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
  949. return 1;
  950. }
  951. /**
  952. * @brief 向指定的端点中写入data stage trb
  953. *
  954. * @param ep 端点信息结构体
  955. * @param buf_vaddr 数据缓冲区虚拟地址
  956. * @param trb_type trb类型
  957. * @param size 要传输的数据大小
  958. * @param direction 传输方向
  959. * @param max_packet 最大请求包大小
  960. * @param status_vaddr event data TRB的缓冲区(4字节,且地址按照16字节对齐)
  961. * @return int 产生的TRB数量
  962. */
  963. static int xhci_data_stage(struct xhci_ep_info_t *ep, uint64_t buf_vaddr, uint8_t trb_type, const uint32_t size, uint8_t direction, const int max_packet, const uint64_t status_vaddr)
  964. {
  965. if (size == 0)
  966. return 0;
  967. int64_t remain_bytes = size;
  968. uint32_t remain_packets = (size + max_packet - 1) / max_packet;
  969. struct xhci_TRB_data_stage_t trb = {0};
  970. int count_packets = 0;
  971. // 分多个trb来执行
  972. while (remain_bytes > 0)
  973. {
  974. --remain_packets;
  975. trb.buf_paddr = virt_2_phys(buf_vaddr);
  976. trb.intr_target = 0;
  977. trb.TD_size = remain_packets;
  978. trb.transfer_length = (remain_bytes < max_packet ? size : max_packet);
  979. trb.dir = direction;
  980. trb.TRB_type = trb_type;
  981. trb.chain = 1;
  982. trb.ent = (remain_packets == 0);
  983. trb.cycle = ep->current_ep_ring_cycle;
  984. trb.ioc = 0;
  985. // 将data stage trb拷贝到ep的transfer ring中
  986. __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
  987. buf_vaddr += max_packet;
  988. remain_bytes -= max_packet;
  989. ++count_packets;
  990. // 对于data stage trb而言,除了第一个trb以外,剩下的trb都是NORMAL的,并且dir是无用的
  991. trb_type = TRB_TYPE_NORMAL;
  992. direction = 0;
  993. }
  994. // 写入data event trb, 待完成后,完成信息将会存到status_vaddr指向的地址中
  995. memset(&trb, 0, sizeof(struct xhci_TRB_data_stage_t *));
  996. trb.buf_paddr = virt_2_phys(status_vaddr);
  997. trb.intr_target = 0;
  998. trb.cycle = ep->current_ep_ring_cycle;
  999. trb.ioc = 1;
  1000. trb.TRB_type = TRB_TYPE_EVENT_DATA;
  1001. __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
  1002. return count_packets + 1;
  1003. }
  1004. /**
  1005. * @brief 填写xhci status stage TRB到control ep的transfer ring
  1006. *
  1007. * @param ep 端点信息结构体
  1008. * @param direction 方向:(h2d:0, d2h:1)
  1009. * @param status_buf_vaddr
  1010. * @return int 创建的TRB数量
  1011. */
  1012. static int xhci_status_stage(struct xhci_ep_info_t *ep, uint8_t direction, uint64_t status_buf_vaddr)
  1013. {
  1014. // kdebug("write status stage trb");
  1015. {
  1016. struct xhci_TRB_status_stage_t trb = {0};
  1017. // 写入status stage trb
  1018. trb.intr_target = 0;
  1019. trb.cycle = ep->current_ep_ring_cycle;
  1020. trb.ent = 0;
  1021. trb.ioc = 1;
  1022. trb.TRB_type = TRB_TYPE_STATUS_STAGE;
  1023. trb.dir = direction;
  1024. __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
  1025. }
  1026. {
  1027. // 写入event data TRB
  1028. struct xhci_TRB_data_stage_t trb = {0};
  1029. trb.buf_paddr = virt_2_phys(status_buf_vaddr);
  1030. trb.intr_target = 0;
  1031. trb.TRB_type = TRB_TYPE_EVENT_DATA;
  1032. trb.ioc = 1;
  1033. trb.cycle = ep->current_ep_ring_cycle;
  1034. __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
  1035. }
  1036. return 2;
  1037. }
  1038. /**
  1039. * @brief 等待状态数据被拷贝到status缓冲区中
  1040. *
  1041. * @param id 主机控制器id
  1042. * @param status_vaddr status 缓冲区
  1043. * @return int 错误码
  1044. */
  1045. static int xhci_wait_for_interrupt(const int id, uint64_t status_vaddr)
  1046. {
  1047. int timer = 500;
  1048. while (timer)
  1049. {
  1050. if (__read4b(status_vaddr) & XHCI_IRQ_DONE)
  1051. {
  1052. uint32_t status = __read4b(status_vaddr);
  1053. // 判断完成码
  1054. switch (xhci_get_comp_code(status))
  1055. {
  1056. case TRB_COMP_TRB_SUCCESS:
  1057. case TRB_COMP_SHORT_PACKET:
  1058. return 0;
  1059. break;
  1060. case TRB_COMP_STALL_ERROR:
  1061. case TRB_COMP_DATA_BUFFER_ERROR:
  1062. case TRB_COMP_BABBLE_DETECTION:
  1063. return -EINVAL;
  1064. default:
  1065. kerror("xhci wait interrupt: status=%#010x, complete_code=%d", status, xhci_get_comp_code(status));
  1066. return -EIO;
  1067. }
  1068. }
  1069. --timer;
  1070. usleep(1000);
  1071. }
  1072. kerror(" USB xHCI Interrupt wait timed out.");
  1073. return -ETIMEDOUT;
  1074. }
  1075. /**
  1076. * @brief 从指定插槽的control endpoint读取信息
  1077. *
  1078. * @param id 主机控制器id
  1079. * @param packet usb数据包
  1080. * @param target 读取到的信息存放到的位置
  1081. * @param port_id 端口id
  1082. * @param max_packet 最大数据包大小
  1083. * @return int 读取到的数据的大小
  1084. */
  1085. static int xhci_control_in(const int id, struct usb_request_packet_t *packet, void *target, const int port_id, const int max_packet)
  1086. {
  1087. uint64_t status_buf_vaddr = (uint64_t)kzalloc(16, 0); // 本来是要申请4bytes的buffer的,但是因为xhci控制器需要16bytes对齐,因此申请16bytes
  1088. uint64_t data_buf_vaddr = 0;
  1089. int retval = 0;
  1090. // 往control ep写入一个setup stage trb
  1091. xhci_setup_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], packet, XHCI_DIR_IN);
  1092. if (packet->length)
  1093. {
  1094. data_buf_vaddr = (uint64_t)kzalloc(packet->length, 0);
  1095. xhci_data_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], data_buf_vaddr, TRB_TYPE_DATA_STAGE, packet->length, XHCI_DIR_IN_BIT, max_packet, status_buf_vaddr);
  1096. }
  1097. /*
  1098. QEMU doesn't quite handle SETUP/DATA/STATUS transactions correctly.
  1099. It will wait for the STATUS TRB before it completes the transfer.
  1100. Technically, you need to check for a good transfer before you send the
  1101. STATUS TRB. However, since QEMU doesn't update the status until after
  1102. the STATUS TRB, waiting here will not complete a successful transfer.
  1103. Bochs and real hardware handles this correctly, however QEMU does not.
  1104. If you are using QEMU, do not ring the doorbell here. Ring the doorbell
  1105. *after* you place the STATUS TRB on the ring.
  1106. (See bug report: https://bugs.launchpad.net/qemu/+bug/1859378 )
  1107. */
  1108. #ifndef __QEMU_EMULATION__
  1109. // 如果不是qemu虚拟机,则可以直接发起传输
  1110. // kdebug(" not qemu");
  1111. __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
  1112. retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
  1113. if (unlikely(retval != 0))
  1114. goto failed;
  1115. #endif
  1116. memset((void *)status_buf_vaddr, 0, 16);
  1117. xhci_status_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], XHCI_DIR_OUT_BIT, status_buf_vaddr);
  1118. __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
  1119. retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
  1120. if (unlikely(retval != 0))
  1121. goto failed;
  1122. // 将读取到的数据拷贝到目标区域
  1123. if (packet->length)
  1124. memcpy(target, (void *)data_buf_vaddr, packet->length);
  1125. retval = packet->length;
  1126. goto done;
  1127. failed:;
  1128. kdebug("wait 4 interrupt failed");
  1129. retval = 0;
  1130. done:;
  1131. // 释放内存
  1132. kfree((void *)status_buf_vaddr);
  1133. if (packet->length)
  1134. kfree((void *)data_buf_vaddr);
  1135. return retval;
  1136. }
  1137. /**
  1138. * @brief 向指定插槽的control ep输出信息
  1139. *
  1140. * @param id 主机控制器id
  1141. * @param packet usb数据包
  1142. * @param target 返回的数据存放的位置
  1143. * @param port_id 端口id
  1144. * @param max_packet 最大数据包大小
  1145. * @return int 读取到的数据的大小
  1146. */
  1147. static int xhci_control_out(const int id, struct usb_request_packet_t *packet, void *target, const int port_id, const int max_packet)
  1148. {
  1149. uint64_t status_buf_vaddr = (uint64_t)kzalloc(16, 0);
  1150. uint64_t data_buf_vaddr = 0;
  1151. int retval = 0;
  1152. // 往control ep写入一个setup stage trb
  1153. xhci_setup_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], packet, XHCI_DIR_OUT);
  1154. if (packet->length)
  1155. {
  1156. data_buf_vaddr = (uint64_t)kzalloc(packet->length, 0);
  1157. xhci_data_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], data_buf_vaddr, TRB_TYPE_DATA_STAGE, packet->length, XHCI_DIR_OUT_BIT, max_packet, status_buf_vaddr);
  1158. }
  1159. #ifndef __QEMU_EMULATION__
  1160. // 如果不是qemu虚拟机,则可以直接发起传输
  1161. __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
  1162. retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
  1163. if (unlikely(retval != 0))
  1164. goto failed;
  1165. #endif
  1166. memset((void *)status_buf_vaddr, 0, 16);
  1167. xhci_status_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], XHCI_DIR_IN_BIT, status_buf_vaddr);
  1168. __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
  1169. #ifndef __QEMU_EMULATION__
  1170. // qemu对于这个操作的处理有问题,status_buf并不会被修改。而真机不存在该问题
  1171. retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
  1172. #endif
  1173. if (unlikely(retval != 0))
  1174. goto failed;
  1175. // 将读取到的数据拷贝到目标区域
  1176. if (packet->length)
  1177. memcpy(target, (void *)data_buf_vaddr, packet->length);
  1178. retval = packet->length;
  1179. goto done;
  1180. failed:;
  1181. kdebug("wait 4 interrupt failed");
  1182. retval = 0;
  1183. done:;
  1184. // 释放内存
  1185. kfree((void *)status_buf_vaddr);
  1186. if (packet->length)
  1187. kfree((void *)data_buf_vaddr);
  1188. return retval;
  1189. }
  1190. /**
  1191. * @brief 获取描述符
  1192. *
  1193. * @param id 控制器号
  1194. * @param port_id 端口号
  1195. * @param target 获取到的数据要拷贝到的地址
  1196. * @param desc_type 描述符类型
  1197. * @param desc_index 描述符的索引号
  1198. * @param lang_id 语言id(默认为0)
  1199. * @param length 要传输的数据长度
  1200. * @return int 错误码
  1201. */
  1202. static inline int xhci_get_desc(const int id, const int port_id, void *target, const uint16_t desc_type, const uint8_t desc_index, const uint16_t lang_id, const uint16_t length)
  1203. {
  1204. struct usb_device_desc *dev_desc = xhci_hc[id].ports[port_id].dev_desc;
  1205. int count;
  1206. BUG_ON(dev_desc == NULL);
  1207. // 设备端口没有对应的描述符
  1208. if (unlikely(dev_desc == NULL))
  1209. return -EINVAL;
  1210. DECLARE_USB_PACKET(ctrl_in_packet, USB_REQ_TYPE_GET_REQUEST, USB_REQ_GET_DESCRIPTOR, (desc_type << 8) | desc_index, lang_id, length);
  1211. count = xhci_control_in(id, &ctrl_in_packet, target, port_id, dev_desc->max_packet_size);
  1212. if (unlikely(count == 0))
  1213. return -EAGAIN;
  1214. return 0;
  1215. }
  1216. static inline int xhci_set_configuration(const int id, const int port_id, const uint8_t conf_value)
  1217. {
  1218. struct usb_device_desc *dev_desc = xhci_hc[id].ports[port_id].dev_desc;
  1219. int count;
  1220. BUG_ON(dev_desc == NULL);
  1221. // 设备端口没有对应的描述符
  1222. if (unlikely(dev_desc == NULL))
  1223. return -EINVAL;
  1224. DECLARE_USB_PACKET(ctrl_out_packet, USB_REQ_TYPE_SET_REQUEST, USB_REQ_SET_CONFIGURATION, conf_value & 0xff, 0, 0);
  1225. kdebug("set conf: to control out");
  1226. count = xhci_control_out(id, &ctrl_out_packet, NULL, port_id, dev_desc->max_packet_size);
  1227. kdebug("set conf: count=%d", count);
  1228. return 0;
  1229. }
  1230. /**
  1231. * @brief 获取usb 设备的config_desc
  1232. *
  1233. * @param id 主机控制器id
  1234. * @param port_id 端口id
  1235. * @param conf_desc 要获取的conf_desc
  1236. * @return int 错误码
  1237. */
  1238. static int xhci_get_config_desc(const int id, const int port_id, struct usb_config_desc *conf_desc)
  1239. {
  1240. if (unlikely(conf_desc == NULL))
  1241. return -EINVAL;
  1242. kdebug("to get conf for port %d", port_id);
  1243. int retval = xhci_get_desc(id, port_id, conf_desc, USB_DT_CONFIG, 0, 0, 9);
  1244. if (unlikely(retval != 0))
  1245. return retval;
  1246. kdebug("port %d got conf ok. type=%d, len=%d, total_len=%d, num_interfaces=%d, max_power=%dmA", port_id, conf_desc->type, conf_desc->len, conf_desc->total_len, conf_desc->num_interfaces, (xhci_get_port_speed(id, port_id) == XHCI_PORT_SPEED_SUPER) ? (conf_desc->max_power * 8) : (conf_desc->max_power * 2));
  1247. return 0;
  1248. }
  1249. /**
  1250. * @brief 获取完整的config desc(包含conf、interface、endpoint)
  1251. *
  1252. * @param id 控制器id
  1253. * @param port_id 端口id
  1254. * @param conf_desc 之前已经获取好的config_desc
  1255. * @param target 最终结果要拷贝到的地址
  1256. * @return int 错误码
  1257. */
  1258. static inline int xhci_get_config_desc_full(const int id, const int port_id, const struct usb_config_desc *conf_desc, void *target)
  1259. {
  1260. if (unlikely(conf_desc == NULL || target == NULL))
  1261. return -EINVAL;
  1262. return xhci_get_desc(id, port_id, target, USB_DT_CONFIG, 0, 0, conf_desc->total_len);
  1263. }
  1264. /**
  1265. * @brief 从完整的conf_desc数据中获取指定的interface_desc的指针
  1266. *
  1267. * @param in_buf 存储了完整的conf_desc的缓冲区
  1268. * @param if_num 接口号
  1269. * @param if_desc 返回的指向接口结构体的指针
  1270. * @return int 错误码
  1271. */
  1272. static int xhci_get_interface_desc(const void *in_buf, const uint8_t if_num, struct usb_interface_desc **if_desc)
  1273. {
  1274. if (unlikely(if_desc == NULL || in_buf == NULL))
  1275. return -EINVAL;
  1276. kdebug("to get interface.");
  1277. // 判断接口index是否合理
  1278. if (if_num >= ((struct usb_config_desc *)in_buf)->num_interfaces)
  1279. return -EINVAL;
  1280. struct usb_interface_desc *ptr = (struct usb_interface_desc *)(in_buf + sizeof(struct usb_config_desc));
  1281. for (int i = 0; i < if_num; ++i)
  1282. {
  1283. ptr = (struct usb_interface_desc *)(((uint64_t)ptr) + sizeof(struct usb_interface_desc) + sizeof(struct usb_endpoint_desc) * ptr->num_endpoints);
  1284. }
  1285. // 返回结果
  1286. *if_desc = ptr;
  1287. kdebug("get interface desc ok. interface_number=%d, num_endpoints=%d, class=%d, subclass=%d", ptr->interface_number, ptr->num_endpoints, ptr->interface_class, ptr->interface_sub_class);
  1288. return 0;
  1289. }
  1290. /**
  1291. * @brief 获取端点描述符
  1292. *
  1293. * @param if_desc 接口描述符
  1294. * @param ep_num 端点号
  1295. * @param ep_desc 返回的指向端点描述符的指针
  1296. * @return int 错误码
  1297. */
  1298. static inline int xhci_get_endpoint_desc(const struct usb_interface_desc *if_desc, const uint8_t ep_num, struct usb_endpoint_desc **ep_desc)
  1299. {
  1300. if (unlikely(if_desc == NULL || ep_desc == NULL))
  1301. return -EINVAL;
  1302. BUG_ON(ep_num >= if_desc->num_endpoints);
  1303. *ep_desc = (struct usb_endpoint_desc *)((uint64_t)(if_desc + 1) + ep_num * sizeof(struct usb_endpoint_desc));
  1304. kdebug("get endpoint desc: ep_addr=%d, max_packet=%d, attr=%#06x, interval=%d", (*ep_desc)->endpoint_addr, (*ep_desc)->max_packet, (*ep_desc)->attributes, (*ep_desc)->interval);
  1305. return 0;
  1306. }
  1307. /**
  1308. * @brief 初始化设备端口,并获取端口的描述信息
  1309. *
  1310. * @param id 主机控制器id
  1311. * @param port_id 端口id
  1312. * @param dev_desc 设备描述符
  1313. * @return int 错误码
  1314. */
  1315. static int xhci_get_descriptor(const int id, const int port_id, struct usb_device_desc *dev_desc)
  1316. {
  1317. int retval = 0;
  1318. int count = 0;
  1319. if (unlikely(dev_desc == NULL))
  1320. return -EINVAL;
  1321. // 读取端口速度。 full=1, low=2, high=3, super=4
  1322. uint32_t speed = xhci_get_port_speed(id, port_id);
  1323. /*
  1324. * Some devices will only send the first 8 bytes of the device descriptor
  1325. * while in the default state. We must request the first 8 bytes, then reset
  1326. * the port, set address, then request all 18 bytes.
  1327. */
  1328. struct xhci_TRB_normal_t trb = {0};
  1329. trb.TRB_type = TRB_TYPE_ENABLE_SLOT;
  1330. // kdebug("to enable slot");
  1331. if (xhci_send_command(id, (struct xhci_TRB_t *)&trb, true) != 0)
  1332. {
  1333. kerror("portid:%d: send enable slot failed", port_id);
  1334. return -ETIMEDOUT;
  1335. }
  1336. // kdebug("send enable slot ok");
  1337. uint32_t slot_id = ((struct xhci_TRB_cmd_complete_t *)&trb)->slot_id;
  1338. int16_t max_packet;
  1339. if (slot_id != 0) // slot id不为0时,是合法的slot id
  1340. {
  1341. // 为不同速度的设备确定最大的数据包大小
  1342. switch (speed)
  1343. {
  1344. case XHCI_PORT_SPEED_LOW:
  1345. max_packet = 8;
  1346. break;
  1347. case XHCI_PORT_SPEED_FULL:
  1348. case XHCI_PORT_SPEED_HI:
  1349. max_packet = 64;
  1350. break;
  1351. case XHCI_PORT_SPEED_SUPER:
  1352. max_packet = 512;
  1353. break;
  1354. }
  1355. }
  1356. else
  1357. return -EAGAIN; // slot id 不合法
  1358. xhci_hc[id].ports[port_id].slot_id = slot_id;
  1359. // kdebug("speed=%d", speed);
  1360. // 初始化接口的上下文
  1361. uint64_t slot_vaddr = xhci_initialize_slot(id, port_id, speed, max_packet);
  1362. retval = xhci_set_address(id, slot_vaddr, slot_id, true);
  1363. // kdebug("set addr again");
  1364. // 再次发送 set_address命令
  1365. // kdebug("to set addr again");
  1366. retval = xhci_set_address(id, slot_vaddr, slot_id, false);
  1367. if (retval != 0)
  1368. return retval;
  1369. memset(dev_desc, 0, sizeof(struct usb_device_desc));
  1370. DECLARE_USB_PACKET(ctrl_in_packet, USB_REQ_TYPE_GET_REQUEST, USB_REQ_GET_DESCRIPTOR, (USB_DT_DEVICE << 8), 0, 18);
  1371. count = xhci_control_in(id, &ctrl_in_packet, dev_desc, port_id, max_packet);
  1372. if (unlikely(count == 0))
  1373. return -EAGAIN;
  1374. /*
  1375. TODO: if the dev_desc->max_packet was different than what we have as max_packet,
  1376. you would need to change it here and in the slot context by doing a
  1377. evaluate_slot_context call.
  1378. */
  1379. xhci_hc[id].ports[port_id].dev_desc = dev_desc;
  1380. // print the descriptor
  1381. printk(" Found USB Device:\n"
  1382. " port: %i\n"
  1383. " len: %i\n"
  1384. " type: %i\n"
  1385. " version: %01X.%02X\n"
  1386. " class: %i\n"
  1387. " subclass: %i\n"
  1388. " protocol: %i\n"
  1389. " max packet size: %i\n"
  1390. " vendor id: 0x%04X\n"
  1391. " product id: 0x%04X\n"
  1392. " release ver: %i%i.%i%i\n"
  1393. " manufacture index: %i (index to a string)\n"
  1394. " product index: %i\n"
  1395. " serial index: %i\n"
  1396. " number of configs: %i\n",
  1397. port_id, dev_desc->len, dev_desc->type, dev_desc->usb_version >> 8, dev_desc->usb_version & 0xFF, dev_desc->_class, dev_desc->subclass,
  1398. dev_desc->protocol, dev_desc->max_packet_size, dev_desc->vendor_id, dev_desc->product_id,
  1399. (dev_desc->device_rel & 0xF000) >> 12, (dev_desc->device_rel & 0x0F00) >> 8,
  1400. (dev_desc->device_rel & 0x00F0) >> 4, (dev_desc->device_rel & 0x000F) >> 0,
  1401. dev_desc->manufacturer_index, dev_desc->procuct_index, dev_desc->serial_index, dev_desc->config);
  1402. return 0;
  1403. }
  1404. /**
  1405. * @brief 启用xhci控制器的端口
  1406. *
  1407. * @param id 控制器id
  1408. * @return int
  1409. */
  1410. static int xhci_hc_start_ports(int id)
  1411. {
  1412. int cnt = 0;
  1413. // 注意,这两个循环应该不能合并到一起,因为可能存在usb2端口offset在前,usb3端口在后的情况,那样的话就会出错
  1414. // 循环启动所有的usb3端口
  1415. for (int i = 0; i < xhci_hc[id].port_num; ++i)
  1416. {
  1417. if (XHCI_PORT_IS_USB3(id, i) && XHCI_PORT_IS_ACTIVE(id, i))
  1418. {
  1419. io_mfence();
  1420. // kdebug("to reset port %d, rflags=%#018lx", id, get_rflags());
  1421. int rst_ret = xhci_reset_port(id, i);
  1422. // kdebug("reset done!, val=%d", rst_ret);
  1423. // reset该端口
  1424. if (likely(rst_ret == 0)) // 如果端口reset成功,就获取它的描述符
  1425. // 否则,reset函数会把它给设置为未激活,并且标志配对的usb2端口是激活的
  1426. {
  1427. // kdebug("reset port %d ok", id);
  1428. struct usb_device_desc dev_desc = {0};
  1429. if (xhci_get_descriptor(id, i, &dev_desc) == 0)
  1430. {
  1431. xhci_configure_port(id, i);
  1432. ++cnt;
  1433. }
  1434. kdebug("usb3 port %d get desc ok", i);
  1435. }
  1436. }
  1437. }
  1438. kdebug("Active usb3 ports:%d", cnt);
  1439. // 循环启动所有的usb2端口
  1440. for (int i = 0; i < xhci_hc[id].port_num; ++i)
  1441. {
  1442. if (XHCI_PORT_IS_USB2(id, i) && XHCI_PORT_IS_ACTIVE(id, i))
  1443. {
  1444. // kdebug("initializing usb2: %d", i);
  1445. // reset该端口
  1446. // kdebug("to reset port %d, rflags=%#018lx", i, get_rflags());
  1447. if (likely(xhci_reset_port(id, i) == 0)) // 如果端口reset成功,就获取它的描述符
  1448. // 否则,reset函数会把它给设置为未激活,并且标志配对的usb2端口是激活的
  1449. {
  1450. // kdebug("reset port %d ok", id);
  1451. struct usb_device_desc dev_desc = {0};
  1452. if (xhci_get_descriptor(id, i, &dev_desc) == 0)
  1453. {
  1454. xhci_configure_port(id, i);
  1455. ++cnt;
  1456. }
  1457. kdebug("USB2 port %d get desc ok", i);
  1458. }
  1459. }
  1460. }
  1461. kinfo("xHCI controller %d: Started %d ports.", id, cnt);
  1462. return 0;
  1463. }
  1464. /**
  1465. * @brief 发送HID设备的IDLE数据包
  1466. *
  1467. * @param id 主机控制器号
  1468. * @param port_id 端口号
  1469. * @param if_desc 接口结构体
  1470. * @return int
  1471. */
  1472. static int xhci_hid_set_idle(const int id, const int port_id, struct usb_interface_desc *if_desc)
  1473. {
  1474. struct usb_device_desc *dev_desc = xhci_hc[id].ports[port_id].dev_desc;
  1475. if (unlikely(dev_desc) == NULL)
  1476. {
  1477. BUG_ON(1);
  1478. return -EINVAL;
  1479. }
  1480. DECLARE_USB_PACKET(ctrl_out_packet, USB_REQ_TYPE_SET_CLASS_INTERFACE, 0x0a, 0, 0, 0);
  1481. xhci_control_out(id, &ctrl_out_packet, NULL, port_id, dev_desc->max_packet_size);
  1482. kdebug("xhci set idle done!");
  1483. return 0;
  1484. }
  1485. /**
  1486. * @brief 配置端点上下文,并发送configure endpoint命令
  1487. *
  1488. * @param id 主机控制器id
  1489. * @param port_id 端口号
  1490. * @param ep_num 端点号
  1491. * @param ep_type 端点类型
  1492. * @param ep_desc 端点描述符
  1493. * @return int 错误码
  1494. */
  1495. static int xhci_configure_endpoint(const int id, const int port_id, const uint8_t ep_num, const uint8_t ep_type, struct usb_endpoint_desc *ep_desc)
  1496. {
  1497. int retval = 0;
  1498. uint64_t slot_context_vaddr = xhci_get_device_context_vaddr(id, port_id);
  1499. xhci_initialize_ep(id, slot_context_vaddr, port_id, ep_num, xhci_hc[id].ports[port_id].dev_desc->max_packet_size,
  1500. usb_get_max_burst_from_ep(ep_desc), ep_type, (ep_num % 2) ? XHCI_DIR_IN_BIT : XHCI_DIR_OUT_BIT,
  1501. xhci_get_port_speed(id, port_id), ep_desc->interval);
  1502. struct xhci_slot_context_t slot;
  1503. struct xhci_ep_context_t ep = {0};
  1504. // 创建输入上下文缓冲区
  1505. uint64_t input_ctx_buffer = (uint64_t)kzalloc(xhci_hc[id].context_size * 33, 0);
  1506. // 置位对应的add bit
  1507. __write4b(input_ctx_buffer + 4, (1 << ep_num)|1);
  1508. __write4b(input_ctx_buffer + 0x1c, 1);
  1509. // 拷贝slot上下文
  1510. __read_from_slot(&slot, slot_context_vaddr);
  1511. // 设置该端口的最大端点号。注意,必须设置这里,否则会出错
  1512. slot.entries = (ep_num > slot.entries) ? ep_num : slot.entries;
  1513. __write_slot(input_ctx_buffer + xhci_hc[id].context_size, &slot);
  1514. // __write_ep(id, input_ctx_buffer, 2, &ep);
  1515. // kdebug("ep_num=%d", ep_num);
  1516. // 拷贝将要被配置的端点的信息
  1517. __read_from_ep(id, slot_context_vaddr, ep_num, &ep);
  1518. // kdebug("ep.tr_dequeue_ptr=%#018lx", ep.tr_dequeue_ptr);
  1519. ep.err_cnt = 3;
  1520. // 加一是因为input_context头部比slot_context多了一个input_control_ctx
  1521. __write_ep(id, input_ctx_buffer, ep_num + 1, &ep);
  1522. struct xhci_TRB_normal_t trb = {0};
  1523. trb.buf_paddr = virt_2_phys(input_ctx_buffer);
  1524. trb.TRB_type = TRB_TYPE_CONFIG_EP;
  1525. trb.cycle = xhci_hc[id].cmd_trb_cycle;
  1526. trb.Reserved |= (((uint16_t)xhci_hc[id].ports[port_id].slot_id) << 8) & 0xffff;
  1527. // kdebug("addr=%#018lx", ((struct xhci_TRB_t *)&trb)->param);
  1528. // kdebug("status=%#018lx", ((struct xhci_TRB_t *)&trb)->status);
  1529. // kdebug("command=%#018lx", ((struct xhci_TRB_t *)&trb)->command);
  1530. retval = xhci_send_command(id, (struct xhci_TRB_t *)&trb, true);
  1531. if (unlikely(retval != 0))
  1532. {
  1533. kerror("port_id:%d, configure endpoint %d failed", port_id, ep_num);
  1534. goto failed;
  1535. }
  1536. struct xhci_TRB_cmd_complete_t *trb_done = (struct xhci_TRB_cmd_complete_t *)&trb;
  1537. if (trb_done->code == TRB_COMP_TRB_SUCCESS) // 成功执行
  1538. {
  1539. // 如果要从控制器获取刚刚设置的设备地址的话,可以在这里读取slot context
  1540. ksuccess("port_id:%d, ep:%d successfully configured.", port_id, ep_num);
  1541. retval = 0;
  1542. }
  1543. else
  1544. retval = -EAGAIN;
  1545. done:;
  1546. failed:;
  1547. kfree((void *)input_ctx_buffer);
  1548. return retval;
  1549. }
  1550. /**
  1551. * @brief 配置连接在指定端口上的设备
  1552. *
  1553. * @param id 主机控制器id
  1554. * @param port_id 端口id
  1555. * @param full_conf 完整的config
  1556. * @return int 错误码
  1557. */
  1558. static int xhci_configure_port(const int id, const int port_id)
  1559. {
  1560. void *full_conf = NULL;
  1561. struct usb_interface_desc *if_desc = NULL;
  1562. struct usb_endpoint_desc *ep_desc = NULL;
  1563. // hint: 暂时只考虑对键盘的初始化
  1564. // 获取完整的config
  1565. {
  1566. struct usb_config_desc conf_desc = {0};
  1567. xhci_get_config_desc(id, port_id, &conf_desc);
  1568. full_conf = kzalloc(conf_desc.total_len, 0);
  1569. xhci_get_config_desc_full(id, port_id, &conf_desc, full_conf);
  1570. }
  1571. xhci_get_interface_desc(full_conf, 0, &if_desc);
  1572. if (if_desc->interface_class == USB_CLASS_HID)
  1573. {
  1574. // 由于暂时只支持键盘,因此把键盘的驱动也写在这里
  1575. // todo: 分离usb键盘驱动
  1576. xhci_get_endpoint_desc(if_desc, 0, &ep_desc);
  1577. // kdebug("to set conf, val=%#010lx", ((struct usb_config_desc *)full_conf)->value);
  1578. xhci_set_configuration(id, port_id, ((struct usb_config_desc *)full_conf)->value);
  1579. // kdebug("set conf ok");
  1580. // todo: configure endpoint
  1581. xhci_configure_endpoint(id, port_id, ep_desc->endpoint_addr, USB_EP_INTERRUPT, ep_desc);
  1582. xhci_hid_set_idle(id, port_id, if_desc);
  1583. // 获取report desc
  1584. // todo: parse hid report
  1585. }
  1586. kfree(full_conf);
  1587. return 0;
  1588. }
  1589. /**
  1590. * @brief 初始化xhci主机控制器的中断控制
  1591. *
  1592. * @param id 主机控制器id
  1593. * @return int 返回码
  1594. */
  1595. static int xhci_hc_init_intr(int id)
  1596. {
  1597. uint64_t retval = 0;
  1598. struct xhci_caps_HCSPARAMS1_reg_t hcs1;
  1599. struct xhci_caps_HCSPARAMS2_reg_t hcs2;
  1600. io_mfence();
  1601. memcpy(&hcs1, xhci_get_ptr_cap_reg32(id, XHCI_CAPS_HCSPARAMS1), sizeof(struct xhci_caps_HCSPARAMS1_reg_t));
  1602. io_mfence();
  1603. memcpy(&hcs2, xhci_get_ptr_cap_reg32(id, XHCI_CAPS_HCSPARAMS2), sizeof(struct xhci_caps_HCSPARAMS2_reg_t));
  1604. io_mfence();
  1605. uint32_t max_segs = (1 << (uint32_t)(hcs2.ERST_Max));
  1606. uint32_t max_interrupters = hcs1.max_intrs;
  1607. // 创建 event ring
  1608. retval = xhci_create_event_ring(4096, &xhci_hc[id].event_ring_vaddr);
  1609. io_mfence();
  1610. if (unlikely((int64_t)(retval) == -ENOMEM))
  1611. return -ENOMEM;
  1612. xhci_hc[id].event_ring_table_vaddr = retval;
  1613. xhci_hc[id].current_event_ring_vaddr = xhci_hc[id].event_ring_vaddr; // 设置驱动程序要读取的下一个event ring trb的地址
  1614. retval = 0;
  1615. xhci_hc[id].current_event_ring_cycle = 1;
  1616. // 写入第0个中断寄存器组
  1617. io_mfence();
  1618. xhci_write_intr_reg32(id, 0, XHCI_IR_MAN, 0x3); // 使能中断并清除pending位(这个pending位是写入1就清0的)
  1619. io_mfence();
  1620. xhci_write_intr_reg32(id, 0, XHCI_IR_MOD, 0); // 关闭中断管制
  1621. io_mfence();
  1622. xhci_write_intr_reg32(id, 0, XHCI_IR_TABLE_SIZE, 1); // 当前只有1个segment
  1623. io_mfence();
  1624. xhci_write_intr_reg64(id, 0, XHCI_IR_DEQUEUE, virt_2_phys(xhci_hc[id].current_event_ring_vaddr) | (1 << 3)); // 写入dequeue寄存器,并清除busy位(写1就会清除)
  1625. io_mfence();
  1626. xhci_write_intr_reg64(id, 0, XHCI_IR_TABLE_ADDR, virt_2_phys(xhci_hc[id].event_ring_table_vaddr)); // 写入table地址
  1627. io_mfence();
  1628. // 清除状态位
  1629. xhci_write_op_reg32(id, XHCI_OPS_USBSTS, (1 << 10) | (1 << 4) | (1 << 3) | (1 << 2));
  1630. io_mfence();
  1631. // 开启usb中断
  1632. // 注册中断处理程序
  1633. struct xhci_hc_irq_install_info_t install_info;
  1634. install_info.assert = 1;
  1635. install_info.edge_trigger = 1;
  1636. install_info.processor = 0; // 投递到bsp
  1637. char *buf = (char *)kmalloc(16, 0);
  1638. memset(buf, 0, 16);
  1639. sprintk(buf, "xHCI HC%d", id);
  1640. io_mfence();
  1641. irq_register(xhci_controller_irq_num[id], &install_info, &xhci_hc_irq_handler, id, &xhci_hc_intr_controller, buf);
  1642. io_mfence();
  1643. kfree(buf);
  1644. kdebug("xhci host controller %d: interrupt registered. irq num=%d", id, xhci_controller_irq_num[id]);
  1645. return 0;
  1646. }
  1647. /**
  1648. * @brief 往xhci控制器发送trb, 并将返回的数据存入原始的trb中
  1649. *
  1650. * @param id xhci控制器号
  1651. * @param trb 传输请求块
  1652. * @param do_ring 是否通知doorbell register
  1653. * @return int 错误码
  1654. */
  1655. static int xhci_send_command(int id, struct xhci_TRB_t *trb, const bool do_ring)
  1656. {
  1657. uint64_t origin_trb_vaddr = xhci_hc[id].cmd_trb_vaddr;
  1658. // 必须先写入参数和状态数据,最后写入command
  1659. __write8b(xhci_hc[id].cmd_trb_vaddr, trb->param); // 参数
  1660. __write4b(xhci_hc[id].cmd_trb_vaddr + 8, trb->status); // 状态
  1661. __write4b(xhci_hc[id].cmd_trb_vaddr + 12, trb->command | xhci_hc[id].cmd_trb_cycle); // 命令
  1662. xhci_hc[id].cmd_trb_vaddr += sizeof(struct xhci_TRB_t); // 跳转到下一个trb
  1663. {
  1664. // 如果下一个trb是link trb,则将下一个要操作的地址是设置为第一个trb
  1665. struct xhci_TRB_normal_t *ptr = (struct xhci_TRB_normal_t *)xhci_hc[id].cmd_trb_vaddr;
  1666. if (ptr->TRB_type == TRB_TYPE_LINK)
  1667. {
  1668. ptr->cycle = xhci_hc[id].cmd_trb_cycle;
  1669. xhci_hc[id].cmd_trb_vaddr = xhci_hc[id].cmd_ring_vaddr;
  1670. xhci_hc[id].cmd_trb_cycle ^= 1;
  1671. }
  1672. }
  1673. if (do_ring) // 按响命令门铃
  1674. {
  1675. __xhci_write_doorbell(id, 0, 0);
  1676. // 等待中断产生
  1677. int timer = 400;
  1678. const uint32_t iman0 = xhci_read_intr_reg32(id, 0, XHCI_IR_MAN);
  1679. // Now wait for the interrupt to happen
  1680. // We use bit 31 of the command dword since it is reserved
  1681. while (timer && ((__read4b(origin_trb_vaddr + 8) & XHCI_IRQ_DONE) == 0))
  1682. {
  1683. usleep(1000);
  1684. --timer;
  1685. }
  1686. uint32_t x = xhci_read_cap_reg32(id, xhci_hc[id].rts_offset + 0x20);
  1687. if (timer == 0)
  1688. return -ETIMEDOUT;
  1689. else
  1690. {
  1691. xhci_get_trb(trb, origin_trb_vaddr);
  1692. trb->status &= (~XHCI_IRQ_DONE);
  1693. }
  1694. }
  1695. return 0;
  1696. }
  1697. /**
  1698. * @brief 初始化xhci控制器
  1699. *
  1700. * @param header 指定控制器的pci device头部
  1701. */
  1702. void xhci_init(struct pci_device_structure_general_device_t *dev_hdr)
  1703. {
  1704. if (xhci_ctrl_count >= XHCI_MAX_HOST_CONTROLLERS)
  1705. {
  1706. kerror("Initialize xhci controller failed: exceed the limit of max controllers.");
  1707. return;
  1708. }
  1709. spin_lock(&xhci_controller_init_lock);
  1710. kinfo("Initializing xhci host controller: bus=%#02x, device=%#02x, func=%#02x, VendorID=%#04x, irq_line=%d, irq_pin=%d", dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, dev_hdr->header.Vendor_ID, dev_hdr->Interrupt_Line, dev_hdr->Interrupt_PIN);
  1711. io_mfence();
  1712. int cid = xhci_hc_find_available_id();
  1713. if (cid < 0)
  1714. {
  1715. kerror("Initialize xhci controller failed: exceed the limit of max controllers.");
  1716. goto failed_exceed_max;
  1717. }
  1718. memset(&xhci_hc[cid], 0, sizeof(struct xhci_host_controller_t));
  1719. xhci_hc[cid].controller_id = cid;
  1720. xhci_hc[cid].pci_dev_hdr = dev_hdr;
  1721. io_mfence();
  1722. {
  1723. uint32_t tmp = pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x4);
  1724. tmp |= 0x6;
  1725. // mem I/O access enable and bus master enable
  1726. pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x4, tmp);
  1727. }
  1728. io_mfence();
  1729. // 为当前控制器映射寄存器地址空间
  1730. xhci_hc[cid].vbase = SPECIAL_MEMOEY_MAPPING_VIRT_ADDR_BASE + XHCI_MAPPING_OFFSET + 65536 * xhci_hc[cid].controller_id;
  1731. // kdebug("dev_hdr->BAR0 & (~0xf)=%#018lx", dev_hdr->BAR0 & (~0xf));
  1732. mm_map_phys_addr(xhci_hc[cid].vbase, dev_hdr->BAR0 & (~0xf), 65536, PAGE_KERNEL_PAGE | PAGE_PWT | PAGE_PCD, true);
  1733. io_mfence();
  1734. // 计算operational registers的地址
  1735. xhci_hc[cid].vbase_op = xhci_hc[cid].vbase + (xhci_read_cap_reg32(cid, XHCI_CAPS_CAPLENGTH) & 0xff);
  1736. io_mfence();
  1737. // 重置xhci控制器
  1738. FAIL_ON_TO(xhci_hc_reset(cid), failed);
  1739. io_mfence();
  1740. // 读取xhci控制寄存器
  1741. uint16_t iversion = *(uint16_t *)(xhci_hc[cid].vbase + XHCI_CAPS_HCIVERSION);
  1742. struct xhci_caps_HCCPARAMS1_reg_t hcc1;
  1743. struct xhci_caps_HCCPARAMS2_reg_t hcc2;
  1744. struct xhci_caps_HCSPARAMS1_reg_t hcs1;
  1745. struct xhci_caps_HCSPARAMS2_reg_t hcs2;
  1746. memcpy(&hcc1, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCCPARAMS1), sizeof(struct xhci_caps_HCCPARAMS1_reg_t));
  1747. memcpy(&hcc2, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCCPARAMS2), sizeof(struct xhci_caps_HCCPARAMS2_reg_t));
  1748. memcpy(&hcs1, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCSPARAMS1), sizeof(struct xhci_caps_HCSPARAMS1_reg_t));
  1749. memcpy(&hcs2, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCSPARAMS2), sizeof(struct xhci_caps_HCSPARAMS2_reg_t));
  1750. xhci_hc[cid].db_offset = xhci_read_cap_reg32(cid, XHCI_CAPS_DBOFF) & (~0x3); // bits [1:0] reserved
  1751. io_mfence();
  1752. xhci_hc[cid].rts_offset = xhci_read_cap_reg32(cid, XHCI_CAPS_RTSOFF) & (~0x1f); // bits [4:0] reserved.
  1753. io_mfence();
  1754. xhci_hc[cid].ext_caps_off = 1UL * (hcc1.xECP) * 4;
  1755. xhci_hc[cid].context_size = (hcc1.csz) ? 64 : 32;
  1756. if (iversion < 0x95)
  1757. kwarn("Unsupported/Unknowned xHCI controller version: %#06x. This may cause unexpected behavior.", iversion);
  1758. {
  1759. // Write to the FLADJ register incase the BIOS didn't
  1760. uint32_t tmp = pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x60);
  1761. tmp |= (0x20 << 8);
  1762. pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x60, tmp);
  1763. }
  1764. // if it is a Panther Point device, make sure sockets are xHCI controlled.
  1765. if (((pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0) & 0xffff) == 0x8086) &&
  1766. (((pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0) >> 16) & 0xffff) == 0x1E31) &&
  1767. ((pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 8) & 0xff) == 4))
  1768. {
  1769. kdebug("Is a Panther Point device");
  1770. pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0xd8, 0xffffffff);
  1771. pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0xd0, 0xffffffff);
  1772. }
  1773. io_mfence();
  1774. // 关闭legacy支持
  1775. FAIL_ON_TO(xhci_hc_stop_legacy(cid), failed);
  1776. io_mfence();
  1777. // 端口配对
  1778. FAIL_ON_TO(xhci_hc_pair_ports(cid), failed);
  1779. io_mfence();
  1780. // ========== 设置USB host controller =========
  1781. // 获取页面大小
  1782. xhci_hc[cid].page_size = (xhci_read_op_reg32(cid, XHCI_OPS_PAGESIZE) & 0xffff) << 12;
  1783. io_mfence();
  1784. // 获取设备上下文空间
  1785. xhci_hc[cid].dcbaap_vaddr = (uint64_t)kzalloc(2048, 0); // 分配2KB的设备上下文地址数组空间
  1786. io_mfence();
  1787. // kdebug("dcbaap_vaddr=%#018lx", xhci_hc[cid].dcbaap_vaddr);
  1788. if (unlikely(!xhci_is_aligned64(xhci_hc[cid].dcbaap_vaddr))) // 地址不是按照64byte对齐
  1789. {
  1790. kerror("dcbaap isn't 64 byte aligned.");
  1791. goto failed_free_dyn;
  1792. }
  1793. // 写入dcbaap
  1794. xhci_write_op_reg64(cid, XHCI_OPS_DCBAAP, virt_2_phys(xhci_hc[cid].dcbaap_vaddr));
  1795. io_mfence();
  1796. // 创建scratchpad buffer array
  1797. uint32_t max_scratchpad_buf = (((uint32_t)hcs2.max_scratchpad_buf_HI5) << 5) | hcs2.max_scratchpad_buf_LO5;
  1798. kdebug("max scratchpad buffer=%d", max_scratchpad_buf);
  1799. if (max_scratchpad_buf > 0)
  1800. {
  1801. xhci_hc[cid].scratchpad_buf_array_vaddr = (uint64_t)kzalloc(sizeof(uint64_t) * max_scratchpad_buf, 0);
  1802. __write8b(xhci_hc[cid].dcbaap_vaddr, virt_2_phys(xhci_hc[cid].scratchpad_buf_array_vaddr));
  1803. // 创建scratchpad buffers
  1804. for (int i = 0; i < max_scratchpad_buf; ++i)
  1805. {
  1806. uint64_t buf_vaddr = (uint64_t)kzalloc(xhci_hc[cid].page_size, 0);
  1807. __write8b(xhci_hc[cid].scratchpad_buf_array_vaddr, virt_2_phys(buf_vaddr));
  1808. }
  1809. }
  1810. // 创建command ring
  1811. xhci_hc[cid].cmd_ring_vaddr = xhci_create_ring(XHCI_CMND_RING_TRBS);
  1812. xhci_hc[cid].cmd_trb_vaddr = xhci_hc[cid].cmd_ring_vaddr;
  1813. if (unlikely(!xhci_is_aligned64(xhci_hc[cid].cmd_ring_vaddr))) // 地址不是按照64byte对齐
  1814. {
  1815. kerror("cmd ring isn't 64 byte aligned.");
  1816. goto failed_free_dyn;
  1817. }
  1818. // 设置初始cycle bit为1
  1819. xhci_hc[cid].cmd_trb_cycle = XHCI_TRB_CYCLE_ON;
  1820. io_mfence();
  1821. // 写入command ring控制寄存器
  1822. xhci_write_op_reg64(cid, XHCI_OPS_CRCR, virt_2_phys(xhci_hc[cid].cmd_ring_vaddr) | xhci_hc[cid].cmd_trb_cycle);
  1823. // 写入配置寄存器
  1824. uint32_t max_slots = hcs1.max_slots;
  1825. // kdebug("max slots = %d", max_slots);
  1826. io_mfence();
  1827. xhci_write_op_reg32(cid, XHCI_OPS_CONFIG, max_slots);
  1828. io_mfence();
  1829. // 写入设备通知控制寄存器
  1830. xhci_write_op_reg32(cid, XHCI_OPS_DNCTRL, (1 << 1)); // 目前只有N1被支持
  1831. io_mfence();
  1832. FAIL_ON_TO(xhci_hc_init_intr(cid), failed_free_dyn);
  1833. io_mfence();
  1834. ++xhci_ctrl_count;
  1835. io_mfence();
  1836. spin_unlock(&xhci_controller_init_lock);
  1837. io_mfence();
  1838. return;
  1839. failed_free_dyn:; // 释放动态申请的内存
  1840. if (xhci_hc[cid].dcbaap_vaddr)
  1841. kfree((void *)xhci_hc[cid].dcbaap_vaddr);
  1842. if (xhci_hc[cid].cmd_ring_vaddr)
  1843. kfree((void *)xhci_hc[cid].cmd_ring_vaddr);
  1844. if (xhci_hc[cid].event_ring_table_vaddr)
  1845. kfree((void *)xhci_hc[cid].event_ring_table_vaddr);
  1846. if (xhci_hc[cid].event_ring_vaddr)
  1847. kfree((void *)xhci_hc[cid].event_ring_vaddr);
  1848. failed:;
  1849. io_mfence();
  1850. // 取消地址映射
  1851. mm_unmap_addr(xhci_hc[cid].vbase, 65536);
  1852. io_mfence();
  1853. // 清空数组
  1854. memset((void *)&xhci_hc[cid], 0, sizeof(struct xhci_host_controller_t));
  1855. failed_exceed_max:;
  1856. kerror("Failed to initialize controller: bus=%d, dev=%d, func=%d", dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func);
  1857. spin_unlock(&xhci_controller_init_lock);
  1858. }