xhci.c 81 KB

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