xhci.c 63 KB

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