xhci.c 64 KB

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