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