xhci.c 63 KB

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