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         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         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                 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     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     int retval = pci_enable_msi(&msi_desc);
644 
645     return 0;
646 }
647 
xhci_hc_irq_uninstall(uint64_t irq_num)648 void xhci_hc_irq_uninstall(uint64_t irq_num)
649 {
650     // todo
651     int cid = xhci_find_hcid_by_irq_num(irq_num);
652     io_mfence();
653     if (WARN_ON(cid == -1))
654         return;
655     xhci_hc_stop(cid);
656     io_mfence();
657 }
658 /**
659  * @brief xhci主机控制器的中断处理函数
660  *
661  * @param irq_num 中断向量号
662  * @param cid 控制器号
663  * @param regs 寄存器值
664  */
xhci_hc_irq_handler(uint64_t irq_num,uint64_t cid,struct pt_regs * regs)665 void xhci_hc_irq_handler(uint64_t irq_num, uint64_t cid, struct pt_regs *regs)
666 {
667     // kdebug("USB irq received.");
668     /*
669         写入usb status寄存器,以表明当前收到了中断,清除usb status寄存器中的EINT位
670         需要先清除这个位,再清除interrupter中的pending bit)
671     */
672     xhci_write_op_reg32(cid, XHCI_OPS_USBSTS, xhci_read_op_reg32(cid, XHCI_OPS_USBSTS));
673 
674     // 读取第0个usb interrupter的intr management寄存器
675     const uint32_t iman0 = xhci_read_intr_reg32(cid, 0, XHCI_IR_MAN);
676     uint64_t dequeue_reg = xhci_read_intr_reg64(cid, 0, XHCI_IR_DEQUEUE);
677 
678     if (((iman0 & 3) == 3) || (dequeue_reg & 8)) // 中断被启用,且pending不为0
679     {
680         // kdebug("to handle");
681         // 写入1以清除该interrupter的pending bit
682         xhci_write_intr_reg32(cid, 0, XHCI_IR_MAN, iman0 | 3);
683         io_mfence();
684         struct xhci_TRB_t event_trb, origin_trb; // event ring trb以及其对应的command trb
685         uint64_t origin_vaddr;
686         // 暂存当前trb的起始地址
687         uint64_t last_event_ring_vaddr = xhci_hc[cid].current_event_ring_vaddr;
688         xhci_get_trb(&event_trb, xhci_hc[cid].current_event_ring_vaddr);
689 
690         {
691             struct xhci_TRB_cmd_complete_t *event_trb_ptr = (struct xhci_TRB_cmd_complete_t *)&event_trb;
692             // kdebug("TRB_type=%d, comp_code=%d", event_trb_ptr->TRB_type, event_trb_ptr->code);
693         }
694         while ((event_trb.command & 1) == xhci_hc[cid].current_event_ring_cycle) // 循环处理处于当前周期的所有event ring
695         {
696 
697             struct xhci_TRB_cmd_complete_t *event_trb_ptr = (struct xhci_TRB_cmd_complete_t *)&event_trb;
698             // kdebug("TRB_type=%d, comp_code=%d", event_trb_ptr->TRB_type, event_trb_ptr->code);
699             if ((event_trb.command & (1 << 2)) == 0) // 当前event trb不是由于short packet产生的
700             {
701                 // kdebug("event_trb_ptr->code=%d", event_trb_ptr->code);
702                 // kdebug("event_trb_ptr->TRB_type=%d", event_trb_ptr->TRB_type);
703                 switch (event_trb_ptr->code) // 判断它的完成码
704                 {
705                 case TRB_COMP_TRB_SUCCESS: // trb执行成功,则将结果返回到对应的command ring的trb里面
706 
707                     switch (event_trb_ptr->TRB_type) // 根据event trb类型的不同,采取不同的措施
708                     {
709                     case TRB_TYPE_COMMAND_COMPLETION: // 命令已经完成
710                         origin_vaddr = (uint64_t)phys_2_virt(event_trb.param);
711                         // 获取对应的command trb
712                         xhci_get_trb(&origin_trb, origin_vaddr);
713 
714                         switch (((struct xhci_TRB_normal_t *)&origin_trb)->TRB_type)
715                         {
716                         case TRB_TYPE_ENABLE_SLOT: // 源命令为enable slot
717                             // 将slot id返回到命令TRB的command字段中
718                             origin_trb.command &= 0x00ffffff;
719                             origin_trb.command |= (event_trb.command & 0xff000000);
720                             origin_trb.status = event_trb.status;
721                             break;
722                         default:
723                             origin_trb.status = event_trb.status;
724                             break;
725                         }
726 
727                         // 标记该命令已经执行完成
728                         origin_trb.status |= XHCI_IRQ_DONE;
729                         // 将command trb写入到表中
730                         xhci_set_trb(&origin_trb, origin_vaddr);
731                         // kdebug("set origin:%#018lx", origin_vaddr);
732                         break;
733                     }
734                     break;
735 
736                 default:
737                     break;
738                 }
739             }
740             else // 当前TRB是由short packet产生的
741             {
742                 switch (event_trb_ptr->TRB_type)
743                 {
744                 case TRB_TYPE_TRANS_EVENT: // 当前 event trb是 transfer event TRB
745                     // If SPD was encountered in this TD, comp_code will be SPD, else it should be SUCCESS
746                     // (specs 4.10.1.1)
747                     __write4b((uint64_t)phys_2_virt(event_trb.param),
748                               (event_trb.status | XHCI_IRQ_DONE)); // return code + bytes *not* transferred
749                     break;
750 
751                 default:
752                     break;
753                 }
754             }
755 
756             // 获取下一个event ring TRB
757             last_event_ring_vaddr = xhci_hc[cid].current_event_ring_vaddr;
758             xhci_hc[cid].current_event_ring_vaddr += sizeof(struct xhci_TRB_t);
759             xhci_get_trb(&event_trb, xhci_hc[cid].current_event_ring_vaddr);
760             if (((struct xhci_TRB_normal_t *)&event_trb)->TRB_type == TRB_TYPE_LINK)
761             {
762                 xhci_hc[cid].current_event_ring_vaddr = xhci_hc[cid].event_ring_vaddr;
763                 xhci_get_trb(&event_trb, xhci_hc[cid].current_event_ring_vaddr);
764             }
765         }
766 
767         // 当前event ring cycle的TRB处理结束
768         // 更新dequeue指针, 并清除event handler busy标志位
769         xhci_write_intr_reg64(cid, 0, XHCI_IR_DEQUEUE, virt_2_phys(last_event_ring_vaddr) | (1 << 3));
770         io_mfence();
771     }
772 }
773 /**
774  * @brief 重置端口
775  *
776  * @param id 控制器id
777  * @param port 端口id
778  * @return int
779  */
xhci_reset_port(const int id,const int port)780 static int xhci_reset_port(const int id, const int port)
781 {
782     int retval = 0;
783     // 相对于op寄存器基地址的偏移量
784     uint64_t port_status_offset = XHCI_OPS_PRS + port * 16;
785 
786     io_mfence();
787     // 检查端口电源状态
788     if ((xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC) & (1 << 9)) == 0)
789     {
790         kdebug("port is power off, starting...");
791         io_mfence();
792         xhci_write_cap_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9));
793         io_mfence();
794         usleep(2000);
795         // 检测端口是否被启用, 若未启用,则报错
796         if ((xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC) & (1 << 9)) == 0)
797         {
798             kdebug("cannot power on %d", port);
799             return -EAGAIN;
800         }
801     }
802     // kdebug("port:%d, power check ok", port);
803     io_mfence();
804     // 确保端口的status被清0
805     xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | XHCI_PORTUSB_CHANGE_BITS);
806     // kdebug("to reset timeout;");
807     io_mfence();
808     // 重置当前端口
809     if (XHCI_PORT_IS_USB3(id, port))
810         xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | (1U << 31));
811     else
812         xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | (1 << 4));
813 
814     retval = -ETIMEDOUT;
815     // kdebug("to wait reset timeout;");
816     // 等待portsc的port reset change位被置位,说明reset完成
817     int timeout = 100;
818     while (timeout)
819     {
820         io_mfence();
821         uint32_t val = xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC);
822         io_mfence();
823         if (val & (1 << 21))
824             break;
825             // QEMU对usb的模拟有bug,因此需要检测这里
826 #ifdef __QEMU_EMULATION__
827 
828         if (XHCI_PORT_IS_USB3(id, port) && (val & (1U << 31)) == 0)
829             break;
830         else if (XHCI_PORT_IS_USB2(id, port) && (val & (1 << 4)) == 0)
831             break;
832 #endif
833         --timeout;
834         usleep(500);
835     }
836     // kdebug("timeout= %d", timeout);
837 
838     if (timeout > 0)
839     {
840         // 等待恢复
841         usleep(USB_TIME_RST_REC * 100);
842         uint32_t val = xhci_read_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC);
843         io_mfence();
844 
845         // kdebug("to check if reset ok, val=%#010lx", val);
846 
847         // 如果reset之后,enable bit仍然是1,那么说明reset成功
848         if (val & (1 << 1))
849         {
850             // kdebug("reset ok");
851             retval = 0;
852             io_mfence();
853             // 清除status change bit
854             xhci_write_op_reg32(id, port_status_offset + XHCI_PORT_PORTSC, (1 << 9) | XHCI_PORTUSB_CHANGE_BITS);
855             io_mfence();
856         }
857         else
858             retval = -1;
859     }
860     // kdebug("reset ok!");
861     // 如果usb2端口成功reset,则处理该端口的active状态
862     if (retval == 0 && XHCI_PORT_IS_USB2(id, port))
863     {
864         xhci_hc[id].ports[port].flags |= XHCI_PROTOCOL_ACTIVE;
865         if (XHCI_PORT_HAS_PAIR(id, port)) // 如果有对应的usb3端口,则将usb3端口设置为未激活
866             xhci_hc[id].ports[xhci_hc[id].ports[port].paired_port_num].flags &= ~(XHCI_PROTOCOL_ACTIVE);
867     }
868 
869     // 如果usb3端口reset失败,则启用与之配对的usb2端口
870     if (retval != 0 && XHCI_PORT_IS_USB3(id, port))
871     {
872         xhci_hc[id].ports[port].flags &= ~XHCI_PROTOCOL_ACTIVE;
873         xhci_hc[id].ports[xhci_hc[id].ports[port].paired_port_num].flags |= XHCI_PROTOCOL_ACTIVE;
874     }
875 
876     return retval;
877 }
878 
879 /**
880  * @brief 初始化设备slot的上下文,并将其写入dcbaap中的上下文index数组
881  * - at this time, we don't know if the device is a hub or not, so we don't
882  *   set the slot->hub, ->mtt, ->ttt, ->etc, items.
883  *
884  * @param id 控制器id
885  * @param port 端口号
886  * @param speed 端口速度
887  * @param max_packet 最大数据包大小
888  * @return uint64_t 初始化好的设备上下文空间的虚拟地址
889  */
xhci_initialize_slot(const int id,const int port,const int speed,const int max_packet)890 static uint64_t xhci_initialize_slot(const int id, const int port, const int speed, const int max_packet)
891 {
892     // 为所有的endpoint分配上下文空间
893     // todo: 按需分配上下文空间
894     uint64_t device_context_vaddr = (uint64_t)kzalloc(xhci_hc[id].context_size * 32, 0);
895     // kdebug("slot id=%d, device_context_vaddr=%#018lx, port=%d", slot_id, device_context_vaddr, port);
896     // 写到数组中
897     __write8b(xhci_hc[id].dcbaap_vaddr + (xhci_hc[id].ports[port].slot_id * sizeof(uint64_t)),
898               virt_2_phys(device_context_vaddr));
899     struct xhci_slot_context_t slot_ctx = {0};
900     slot_ctx.entries = 1;
901     slot_ctx.speed = speed;
902     slot_ctx.route_string = 0;
903     slot_ctx.rh_port_num = port + 1; // 由于xhci控制器是1-base的,因此把驱动程序中存储的端口号加1,才是真实的端口号
904     slot_ctx.max_exit_latency = 0; // 稍后会计算这个值
905     slot_ctx.int_target = 0;       // 当前全部使用第0个interrupter
906     slot_ctx.slot_state = XHCI_SLOT_STATE_DISABLED_OR_ENABLED;
907     slot_ctx.device_address = 0;
908 
909     // 将slot信息写入上下文空间
910     __write_slot(device_context_vaddr, &slot_ctx);
911 
912     // 初始化控制端点
913     xhci_initialize_ep(id, device_context_vaddr, port, XHCI_EP_CONTROL, max_packet, 0, USB_EP_CONTROL, 0, speed, 0);
914 
915     return device_context_vaddr;
916 }
917 
918 /**
919  * @brief 初始化endpoint
920  *
921  * @param id 控制器id
922  * @param slot_vaddr slot上下文的虚拟地址
923  * @param port_id 插槽id
924  * @param ep_num 端点上下文在slot上下文区域内的编号
925  * @param max_packet 最大数据包大小
926  * @param type 端点类型
927  * @param direction 传输方向
928  * @param speed 传输速度
929  * @param ep_interval 端点的连续请求间隔
930  */
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)931 static void xhci_initialize_ep(const int id, const uint64_t slot_vaddr, const int port_id, const int ep_num,
932                                const int max_packet, const int max_burst, const int type, const int direction,
933                                const int speed, const int ep_interval)
934 {
935     // 由于目前只实现获取设备的描述符,因此暂时只支持control ep
936     if (type != USB_EP_CONTROL && type != USB_EP_INTERRUPT)
937         return;
938     struct xhci_ep_context_t ep_ctx = {0};
939     memset(&ep_ctx, 0, sizeof(struct xhci_ep_context_t));
940 
941     xhci_hc[id].ports[port_id].ep_info[ep_num].ep_ring_vbase = xhci_create_ring(XHCI_TRBS_PER_RING);
942     // 申请ep的 transfer ring
943     ep_ctx.tr_dequeue_ptr = virt_2_phys(xhci_hc[id].ports[port_id].ep_info[ep_num].ep_ring_vbase);
944     xhci_ep_set_dequeue_cycle_state(&ep_ctx, XHCI_TRB_CYCLE_ON);
945 
946     xhci_hc[id].ports[port_id].ep_info[ep_num].current_ep_ring_vaddr =
947         xhci_hc[id].ports[port_id].ep_info[ep_num].ep_ring_vbase;
948     xhci_hc[id].ports[port_id].ep_info[ep_num].current_ep_ring_cycle = xhci_ep_get_dequeue_cycle_state(&ep_ctx);
949     // kdebug("ep_ctx.tr_dequeue_ptr = %#018lx", ep_ctx.tr_dequeue_ptr);
950     // kdebug("xhci_hc[id].control_ep_info.current_ep_ring_cycle  = %d",
951     // xhci_hc[id].control_ep_info.current_ep_ring_cycle);
952     kdebug("max_packet=%d, max_burst=%d", max_packet, max_burst);
953     switch (type)
954     {
955     case USB_EP_CONTROL: // Control ep
956         // 设置初始值
957         ep_ctx.max_packet_size = max_packet;
958         ep_ctx.linear_stream_array = 0;
959         ep_ctx.max_primary_streams = 0;
960         ep_ctx.mult = 0;
961         ep_ctx.ep_state = XHCI_EP_STATE_DISABLED;
962         ep_ctx.hid = 0;
963         ep_ctx.ep_type = XHCI_EP_TYPE_CONTROL;
964         ep_ctx.average_trb_len = 8; // 所有的control ep的该值均为8
965         ep_ctx.err_cnt = 3;
966         ep_ctx.max_burst_size = max_burst;
967         ep_ctx.interval = ep_interval;
968 
969         break;
970     case USB_EP_INTERRUPT:
971         ep_ctx.max_packet_size = max_packet & 0x7ff;
972         ep_ctx.max_burst_size = max_burst;
973         ep_ctx.ep_state = XHCI_EP_STATE_DISABLED;
974         ep_ctx.mult = 0;
975         ep_ctx.err_cnt = 3;
976         ep_ctx.max_esti_payload_hi = ((max_packet * (max_burst + 1)) >> 8) & 0xff;
977         ep_ctx.max_esti_payload_lo = ((max_packet * (max_burst + 1))) & 0xff;
978         ep_ctx.interval = ep_interval;
979         ep_ctx.average_trb_len = 8; // todo: It's not sure how much to fill in this value
980         // ep_ctx.ep_type = XHCI_EP_TYPE_INTR_IN;
981         ep_ctx.ep_type = ((ep_num % 2) ? XHCI_EP_TYPE_INTR_IN : XHCI_EP_TYPE_INTR_OUT);
982 
983         break;
984     default:
985         break;
986     }
987 
988     // 将ep的信息写入到slot上下文中对应的ep的块中
989     __write_ep(id, slot_vaddr, ep_num, &ep_ctx);
990 }
991 
992 /**
993  * @brief 向usb控制器发送 address_device命令
994  *
995  * @param id 主机控制器id
996  * @param slot_vaddr 插槽上下文的虚拟基地址
997  * @param slot_id 插槽id
998  * @param block 是否阻断 set address 信息向usb设备的传输
999  * @return int 错误码
1000  */
xhci_set_address(const int id,const uint64_t slot_vaddr,const int slot_id,const bool block)1001 static int xhci_set_address(const int id, const uint64_t slot_vaddr, const int slot_id, const bool block)
1002 {
1003     int retval = 0;
1004     struct xhci_slot_context_t slot;
1005     struct xhci_ep_context_t ep;
1006     // 创建输入上下文缓冲区
1007     uint64_t input_ctx_buffer = (uint64_t)kzalloc(xhci_hc[id].context_size * 33, 0);
1008 
1009     // 置位input control context和slot context的add bit
1010     __write4b(input_ctx_buffer + 4, 0x3);
1011 
1012     // 拷贝slot上下文和control ep上下文到输入上下文中
1013 
1014     //  __write_ep(id, input_ctx_buffer, 2, &ep_ctx);
1015     __read_from_slot(&slot, slot_vaddr);
1016     __read_from_ep(id, slot_vaddr, 1, &ep);
1017     ep.err_cnt = 3;
1018     kdebug("slot.slot_state=%d, speed=%d, root hub port num=%d", slot.slot_state, slot.speed, slot.rh_port_num);
1019     kdebug("ep.type=%d, max_packet=%d, dequeue_ptr=%#018lx", ep.ep_type, ep.max_packet_size, ep.tr_dequeue_ptr);
1020 
1021     __write_slot(input_ctx_buffer + xhci_hc[id].context_size, &slot);
1022     __write_ep(id, input_ctx_buffer, 2, &ep);
1023 
1024     struct xhci_TRB_normal_t trb = {0};
1025     trb.buf_paddr = virt_2_phys(input_ctx_buffer);
1026     trb.bei = (block ? 1 : 0);
1027     trb.TRB_type = TRB_TYPE_ADDRESS_DEVICE;
1028     trb.intr_target = 0;
1029     trb.cycle = xhci_hc[id].cmd_trb_cycle;
1030     trb.Reserved |= ((slot_id << 8) & 0xffff);
1031 
1032     retval = xhci_send_command(id, (struct xhci_TRB_t *)&trb, true);
1033     if (unlikely(retval != 0))
1034     {
1035         kerror("slotid:%d, address device failed", slot_id);
1036         goto failed;
1037     }
1038 
1039     struct xhci_TRB_cmd_complete_t *trb_done = (struct xhci_TRB_cmd_complete_t *)&trb;
1040     if (trb_done->code == TRB_COMP_TRB_SUCCESS) // 成功执行
1041     {
1042         // 如果要从控制器获取刚刚设置的设备地址的话,可以在这里读取slot context
1043         ksuccess("slot %d successfully addressed.", slot_id);
1044 
1045         retval = 0;
1046     }
1047     else
1048         retval = -EAGAIN;
1049 done:;
1050 failed:;
1051     kfree((void *)input_ctx_buffer);
1052     return retval;
1053 }
1054 
1055 /**
1056  * @brief 在指定的端点的ring中,写入一个setup stage TRB
1057  *
1058  * @param ep 端点信息结构体
1059  * @param packet usb请求包
1060  * @param direction 传输的方向
1061  * @return int 产生的TRB数量
1062  */
xhci_setup_stage(struct xhci_ep_info_t * ep,const struct usb_request_packet_t * packet,const uint8_t direction)1063 static int xhci_setup_stage(struct xhci_ep_info_t *ep, const struct usb_request_packet_t *packet,
1064                             const uint8_t direction)
1065 {
1066     // kdebug("ep->current_ep_ring_cycle=%d", ep->current_ep_ring_cycle);
1067     struct xhci_TRB_setup_stage_t trb = {0};
1068     trb.bmRequestType = packet->request_type;
1069     trb.bRequest = packet->request;
1070     trb.wValue = packet->value;
1071     trb.wIndex = packet->index;
1072     trb.wLength = packet->length;
1073     trb.transfer_legth = 8;
1074     trb.intr_target = 0; // 使用第0个interrupter
1075     trb.cycle = ep->current_ep_ring_cycle;
1076     trb.ioc = 0;
1077     trb.idt = 1;
1078     trb.TRB_type = TRB_TYPE_SETUP_STAGE;
1079     trb.trt = direction;
1080 
1081     // 将setup stage trb拷贝到ep的transfer ring中
1082     __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
1083     return 1;
1084 }
1085 
1086 /**
1087  * @brief 向指定的端点中写入data stage trb
1088  *
1089  * @param ep 端点信息结构体
1090  * @param buf_vaddr 数据缓冲区虚拟地址
1091  * @param trb_type trb类型
1092  * @param size 要传输的数据大小
1093  * @param direction 传输方向
1094  * @param max_packet 最大请求包大小
1095  * @param status_vaddr event data TRB的缓冲区(4字节,且地址按照16字节对齐)
1096  * @return int 产生的TRB数量
1097  */
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)1098 static int xhci_data_stage(struct xhci_ep_info_t *ep, uint64_t buf_vaddr, uint8_t trb_type, const uint32_t size,
1099                            uint8_t direction, const int max_packet, const uint64_t status_vaddr)
1100 {
1101     if (size == 0)
1102         return 0;
1103     int64_t remain_bytes = size;
1104     uint32_t remain_packets = (size + max_packet - 1) / max_packet;
1105     struct xhci_TRB_data_stage_t trb = {0};
1106     int count_packets = 0;
1107     // 分多个trb来执行
1108     while (remain_bytes > 0)
1109     {
1110         --remain_packets;
1111 
1112         trb.buf_paddr = virt_2_phys(buf_vaddr);
1113         trb.intr_target = 0;
1114         trb.TD_size = remain_packets;
1115         trb.transfer_length = (remain_bytes < max_packet ? size : max_packet);
1116         trb.dir = direction;
1117         trb.TRB_type = trb_type;
1118         trb.chain = 1;
1119         trb.ent = (remain_packets == 0);
1120         trb.cycle = ep->current_ep_ring_cycle;
1121         trb.ioc = 0;
1122 
1123         // 将data stage trb拷贝到ep的transfer ring中
1124         __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
1125 
1126         buf_vaddr += max_packet;
1127         remain_bytes -= max_packet;
1128         ++count_packets;
1129 
1130         // 对于data stage trb而言,除了第一个trb以外,剩下的trb都是NORMAL的,并且dir是无用的
1131         trb_type = TRB_TYPE_NORMAL;
1132         direction = 0;
1133     }
1134 
1135     // 写入data event trb, 待完成后,完成信息将会存到status_vaddr指向的地址中
1136     memset(&trb, 0, sizeof(struct xhci_TRB_data_stage_t *));
1137     trb.buf_paddr = virt_2_phys(status_vaddr);
1138     trb.intr_target = 0;
1139     trb.cycle = ep->current_ep_ring_cycle;
1140     trb.ioc = 1;
1141     trb.TRB_type = TRB_TYPE_EVENT_DATA;
1142     __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
1143 
1144     return count_packets + 1;
1145 }
1146 
1147 /**
1148  * @brief 填写xhci status stage TRB到control ep的transfer ring
1149  *
1150  * @param ep 端点信息结构体
1151  * @param direction 方向:(h2d:0, d2h:1)
1152  * @param status_buf_vaddr
1153  * @return int 创建的TRB数量
1154  */
xhci_status_stage(struct xhci_ep_info_t * ep,uint8_t direction,uint64_t status_buf_vaddr)1155 static int xhci_status_stage(struct xhci_ep_info_t *ep, uint8_t direction, uint64_t status_buf_vaddr)
1156 {
1157     // kdebug("write status stage trb");
1158 
1159     {
1160         struct xhci_TRB_status_stage_t trb = {0};
1161 
1162         // 写入status stage trb
1163         trb.intr_target = 0;
1164         trb.cycle = ep->current_ep_ring_cycle;
1165         trb.ent = 0;
1166         trb.ioc = 1;
1167         trb.TRB_type = TRB_TYPE_STATUS_STAGE;
1168         trb.dir = direction;
1169         __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
1170     }
1171 
1172     {
1173         // 写入event data TRB
1174         struct xhci_TRB_data_stage_t trb = {0};
1175         trb.buf_paddr = virt_2_phys(status_buf_vaddr);
1176         trb.intr_target = 0;
1177         trb.TRB_type = TRB_TYPE_EVENT_DATA;
1178         trb.ioc = 1;
1179 
1180         trb.cycle = ep->current_ep_ring_cycle;
1181 
1182         __xhci_write_trb(ep, (struct xhci_TRB_t *)&trb);
1183     }
1184 
1185     return 2;
1186 }
1187 
1188 /**
1189  * @brief 等待状态数据被拷贝到status缓冲区中
1190  *
1191  * @param id 主机控制器id
1192  * @param status_vaddr status 缓冲区
1193  * @return int 错误码
1194  */
xhci_wait_for_interrupt(const int id,uint64_t status_vaddr)1195 static int xhci_wait_for_interrupt(const int id, uint64_t status_vaddr)
1196 {
1197     int timer = 500;
1198     while (timer)
1199     {
1200         if (__read4b(status_vaddr) & XHCI_IRQ_DONE)
1201         {
1202             uint32_t status = __read4b(status_vaddr);
1203             // 判断完成码
1204             switch (xhci_get_comp_code(status))
1205             {
1206             case TRB_COMP_TRB_SUCCESS:
1207             case TRB_COMP_SHORT_PACKET:
1208                 return 0;
1209                 break;
1210             case TRB_COMP_STALL_ERROR:
1211             case TRB_COMP_DATA_BUFFER_ERROR:
1212             case TRB_COMP_BABBLE_DETECTION:
1213                 return -EINVAL;
1214             default:
1215                 kerror("xhci wait interrupt: status=%#010x, complete_code=%d", status, xhci_get_comp_code(status));
1216                 return -EIO;
1217             }
1218         }
1219         --timer;
1220         usleep(1000);
1221     }
1222 
1223     kerror(" USB xHCI Interrupt wait timed out.");
1224     return -ETIMEDOUT;
1225 }
1226 
1227 /**
1228  * @brief 从指定插槽的control endpoint读取信息
1229  *
1230  * @param id 主机控制器id
1231  * @param packet usb数据包
1232  * @param target 读取到的信息存放到的位置
1233  * @param port_id 端口id
1234  * @param max_packet 最大数据包大小
1235  * @return int 读取到的数据的大小
1236  */
xhci_control_in(const int id,struct usb_request_packet_t * packet,void * target,const int port_id,const int max_packet)1237 static int xhci_control_in(const int id, struct usb_request_packet_t *packet, void *target, const int port_id,
1238                            const int max_packet)
1239 {
1240 
1241     uint64_t status_buf_vaddr =
1242         (uint64_t)kzalloc(16, 0); // 本来是要申请4bytes的buffer的,但是因为xhci控制器需要16bytes对齐,因此申请16bytes
1243     uint64_t data_buf_vaddr = 0;
1244     int retval = 0;
1245 
1246     // 往control ep写入一个setup stage trb
1247     xhci_setup_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], packet, XHCI_DIR_IN);
1248     if (packet->length)
1249     {
1250         data_buf_vaddr = (uint64_t)kzalloc(packet->length, 0);
1251         xhci_data_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], data_buf_vaddr, TRB_TYPE_DATA_STAGE,
1252                         packet->length, XHCI_DIR_IN_BIT, max_packet, status_buf_vaddr);
1253     }
1254 
1255 /*
1256     QEMU doesn't quite handle SETUP/DATA/STATUS transactions correctly.
1257     It will wait for the STATUS TRB before it completes the transfer.
1258     Technically, you need to check for a good transfer before you send the
1259     STATUS TRB.  However, since QEMU doesn't update the status until after
1260     the STATUS TRB, waiting here will not complete a successful transfer.
1261     Bochs and real hardware handles this correctly, however QEMU does not.
1262     If you are using QEMU, do not ring the doorbell here.  Ring the doorbell
1263     *after* you place the STATUS TRB on the ring.
1264     (See bug report: https://bugs.launchpad.net/qemu/+bug/1859378 )
1265 */
1266 #ifndef __QEMU_EMULATION__
1267     // 如果不是qemu虚拟机,则可以直接发起传输
1268     // kdebug(" not qemu");
1269     __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
1270     retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
1271     if (unlikely(retval != 0))
1272         goto failed;
1273 #endif
1274     memset((void *)status_buf_vaddr, 0, 16);
1275     xhci_status_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], XHCI_DIR_OUT_BIT, status_buf_vaddr);
1276 
1277     __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
1278 
1279     retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
1280 
1281     if (unlikely(retval != 0))
1282         goto failed;
1283 
1284     // 将读取到的数据拷贝到目标区域
1285     if (packet->length)
1286         memcpy(target, (void *)data_buf_vaddr, packet->length);
1287     retval = packet->length;
1288     goto done;
1289 
1290 failed:;
1291     kdebug("wait 4 interrupt failed");
1292     retval = 0;
1293 done:;
1294     // 释放内存
1295     kfree((void *)status_buf_vaddr);
1296     if (packet->length)
1297         kfree((void *)data_buf_vaddr);
1298     return retval;
1299 }
1300 
1301 /**
1302  * @brief 向指定插槽的control ep输出信息
1303  *
1304  * @param id 主机控制器id
1305  * @param packet usb数据包
1306  * @param target 返回的数据存放的位置
1307  * @param port_id 端口id
1308  * @param max_packet 最大数据包大小
1309  * @return int 读取到的数据的大小
1310  */
xhci_control_out(const int id,struct usb_request_packet_t * packet,void * target,const int port_id,const int max_packet)1311 static int xhci_control_out(const int id, struct usb_request_packet_t *packet, void *target, const int port_id,
1312                             const int max_packet)
1313 {
1314     uint64_t status_buf_vaddr = (uint64_t)kzalloc(16, 0);
1315     uint64_t data_buf_vaddr = 0;
1316     int retval = 0;
1317 
1318     // 往control ep写入一个setup stage trb
1319     xhci_setup_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], packet, XHCI_DIR_OUT);
1320 
1321     if (packet->length)
1322     {
1323         data_buf_vaddr = (uint64_t)kzalloc(packet->length, 0);
1324         xhci_data_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], data_buf_vaddr, TRB_TYPE_DATA_STAGE,
1325                         packet->length, XHCI_DIR_OUT_BIT, max_packet, status_buf_vaddr);
1326     }
1327 
1328 #ifndef __QEMU_EMULATION__
1329     // 如果不是qemu虚拟机,则可以直接发起传输
1330     __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
1331     retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
1332     if (unlikely(retval != 0))
1333         goto failed;
1334 #endif
1335 
1336     memset((void *)status_buf_vaddr, 0, 16);
1337     xhci_status_stage(&xhci_hc[id].ports[port_id].ep_info[XHCI_EP_CONTROL], XHCI_DIR_IN_BIT, status_buf_vaddr);
1338 
1339     __xhci_write_doorbell(id, xhci_hc[id].ports[port_id].slot_id, XHCI_EP_CONTROL);
1340 #ifndef __QEMU_EMULATION__
1341     // qemu对于这个操作的处理有问题,status_buf并不会被修改。而真机不存在该问题
1342     retval = xhci_wait_for_interrupt(id, status_buf_vaddr);
1343 #endif
1344 
1345     if (unlikely(retval != 0))
1346         goto failed;
1347 
1348     // 将读取到的数据拷贝到目标区域
1349     if (packet->length)
1350         memcpy(target, (void *)data_buf_vaddr, packet->length);
1351     retval = packet->length;
1352     goto done;
1353 failed:;
1354     kdebug("wait 4 interrupt failed");
1355     retval = 0;
1356 done:;
1357     // 释放内存
1358     kfree((void *)status_buf_vaddr);
1359     if (packet->length)
1360         kfree((void *)data_buf_vaddr);
1361     return retval;
1362 }
1363 
1364 /**
1365  * @brief 获取描述符
1366  *
1367  * @param id 控制器号
1368  * @param port_id 端口号
1369  * @param target 获取到的数据要拷贝到的地址
1370  * @param desc_type 描述符类型
1371  * @param desc_index 描述符的索引号
1372  * @param lang_id 语言id(默认为0)
1373  * @param length 要传输的数据长度
1374  * @return int 错误码
1375  */
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)1376 static inline int xhci_get_desc(const int id, const int port_id, void *target, const uint16_t desc_type,
1377                                 const uint8_t desc_index, const uint16_t lang_id, const uint16_t length)
1378 {
1379     struct usb_device_desc *dev_desc = xhci_hc[id].ports[port_id].dev_desc;
1380     int count;
1381 
1382     BUG_ON(dev_desc == NULL);
1383     // 设备端口没有对应的描述符
1384     if (unlikely(dev_desc == NULL))
1385         return -EINVAL;
1386 
1387     uint8_t req_type = USB_REQ_TYPE_GET_REQUEST;
1388     if (desc_type == USB_DT_HID_REPORT)
1389         req_type = USB_REQ_TYPE_GET_INTERFACE_REQUEST;
1390 
1391     DECLARE_USB_PACKET(ctrl_in_packet, req_type, USB_REQ_GET_DESCRIPTOR, (desc_type << 8) | desc_index, lang_id,
1392                        length);
1393     count = xhci_control_in(id, &ctrl_in_packet, target, port_id, dev_desc->max_packet_size);
1394     if (unlikely(count == 0))
1395         return -EAGAIN;
1396     return 0;
1397 }
1398 
xhci_set_configuration(const int id,const int port_id,const uint8_t conf_value)1399 static inline int xhci_set_configuration(const int id, const int port_id, const uint8_t conf_value)
1400 {
1401     struct usb_device_desc *dev_desc = xhci_hc[id].ports[port_id].dev_desc;
1402     int count;
1403 
1404     BUG_ON(dev_desc == NULL);
1405     // 设备端口没有对应的描述符
1406     if (unlikely(dev_desc == NULL))
1407         return -EINVAL;
1408     DECLARE_USB_PACKET(ctrl_out_packet, USB_REQ_TYPE_SET_REQUEST, USB_REQ_SET_CONFIGURATION, conf_value & 0xff, 0, 0);
1409     // kdebug("set conf: to control out");
1410     count = xhci_control_out(id, &ctrl_out_packet, NULL, port_id, dev_desc->max_packet_size);
1411     // kdebug("set conf: count=%d", count);
1412     return 0;
1413 }
1414 
1415 /**
1416  * @brief 获取usb 设备的config_desc
1417  *
1418  * @param id 主机控制器id
1419  * @param port_id 端口id
1420  * @param conf_desc 要获取的conf_desc
1421  * @return int 错误码
1422  */
xhci_get_config_desc(const int id,const int port_id,struct usb_config_desc * conf_desc)1423 static int xhci_get_config_desc(const int id, const int port_id, struct usb_config_desc *conf_desc)
1424 {
1425     if (unlikely(conf_desc == NULL))
1426         return -EINVAL;
1427 
1428     kdebug("to get conf for port %d", port_id);
1429     int retval = xhci_get_desc(id, port_id, conf_desc, USB_DT_CONFIG, 0, 0, 9);
1430     if (unlikely(retval != 0))
1431         return retval;
1432     kdebug("port %d got conf ok. type=%d, len=%d, total_len=%d, num_interfaces=%d, max_power=%dmA", port_id,
1433            conf_desc->type, conf_desc->len, conf_desc->total_len, conf_desc->num_interfaces,
1434            (xhci_get_port_speed(id, port_id) == XHCI_PORT_SPEED_SUPER) ? (conf_desc->max_power * 8)
1435                                                                        : (conf_desc->max_power * 2));
1436     return 0;
1437 }
1438 
1439 /**
1440  * @brief 获取完整的config desc(包含conf、interface、endpoint)
1441  *
1442  * @param id 控制器id
1443  * @param port_id 端口id
1444  * @param conf_desc 之前已经获取好的config_desc
1445  * @param target 最终结果要拷贝到的地址
1446  * @return int 错误码
1447  */
xhci_get_config_desc_full(const int id,const int port_id,const struct usb_config_desc * conf_desc,void * target)1448 static inline int xhci_get_config_desc_full(const int id, const int port_id, const struct usb_config_desc *conf_desc,
1449                                             void *target)
1450 {
1451     if (unlikely(conf_desc == NULL || target == NULL))
1452         return -EINVAL;
1453 
1454     return xhci_get_desc(id, port_id, target, USB_DT_CONFIG, 0, 0, conf_desc->total_len);
1455 }
1456 
1457 /**
1458  * @brief 从完整的conf_desc数据中获取指定的interface_desc的指针
1459  *
1460  * @param in_buf 存储了完整的conf_desc的缓冲区
1461  * @param if_num 接口号
1462  * @param if_desc 返回的指向接口结构体的指针
1463  * @return int 错误码
1464  */
xhci_get_interface_desc(const void * in_buf,const uint8_t if_num,struct usb_interface_desc ** if_desc)1465 static int xhci_get_interface_desc(const void *in_buf, const uint8_t if_num, struct usb_interface_desc **if_desc)
1466 {
1467     if (unlikely(if_desc == NULL || in_buf == NULL))
1468         return -EINVAL;
1469     // 判断接口index是否合理
1470     if (if_num >= ((struct usb_config_desc *)in_buf)->num_interfaces)
1471         return -EINVAL;
1472     uint32_t total_len = ((struct usb_config_desc *)in_buf)->total_len;
1473     uint32_t pos = 0;
1474     while (pos < total_len)
1475     {
1476         struct usb_interface_desc *ptr = (struct usb_interface_desc *)(in_buf + pos);
1477         if (ptr->type != USB_DT_INTERFACE)
1478         {
1479             pos += ptr->len;
1480             continue;
1481         }
1482 
1483         if (ptr->interface_number == if_num) // 找到目标interface desc
1484         {
1485             kdebug("get interface desc ok. interface_number=%d, num_endpoints=%d, class=%d, subclass=%d",
1486                    ptr->interface_number, ptr->num_endpoints, ptr->interface_class, ptr->interface_sub_class);
1487             *if_desc = ptr;
1488             return 0;
1489         }
1490         pos += ptr->len;
1491     }
1492 
1493     return -EINVAL;
1494 }
1495 
1496 /**
1497  * @brief 获取端点描述符
1498  *
1499  * @param if_desc 接口描述符
1500  * @param ep_num 端点号
1501  * @param ep_desc 返回的指向端点描述符的指针
1502  * @return int 错误码
1503  */
xhci_get_endpoint_desc(const struct usb_interface_desc * if_desc,const uint8_t ep_num,struct usb_endpoint_desc ** ep_desc)1504 static inline int xhci_get_endpoint_desc(const struct usb_interface_desc *if_desc, const uint8_t ep_num,
1505                                          struct usb_endpoint_desc **ep_desc)
1506 {
1507     if (unlikely(if_desc == NULL || ep_desc == NULL))
1508         return -EINVAL;
1509     BUG_ON(ep_num >= if_desc->num_endpoints);
1510 
1511     *ep_desc = (struct usb_endpoint_desc *)((uint64_t)(if_desc + 1) + ep_num * sizeof(struct usb_endpoint_desc));
1512     kdebug("get endpoint desc: ep_addr=%d, max_packet=%d, attr=%#06x, interval=%d", (*ep_desc)->endpoint_addr,
1513            (*ep_desc)->max_packet, (*ep_desc)->attributes, (*ep_desc)->interval);
1514     return 0;
1515 }
1516 
1517 /**
1518  * @brief 初始化设备端口,并获取端口的描述信息
1519  *
1520  * @param id 主机控制器id
1521  * @param port_id 端口id
1522  * @param dev_desc 设备描述符
1523  * @return int 错误码
1524  */
xhci_get_descriptor(const int id,const int port_id,struct usb_device_desc * dev_desc)1525 static int xhci_get_descriptor(const int id, const int port_id, struct usb_device_desc *dev_desc)
1526 {
1527     int retval = 0;
1528     int count = 0;
1529     if (unlikely(dev_desc == NULL))
1530         return -EINVAL;
1531     // 读取端口速度。 full=1, low=2, high=3, super=4
1532     uint32_t speed = xhci_get_port_speed(id, port_id);
1533 
1534     /*
1535      * Some devices will only send the first 8 bytes of the device descriptor
1536      *  while in the default state.  We must request the first 8 bytes, then reset
1537      *  the port, set address, then request all 18 bytes.
1538      */
1539     struct xhci_TRB_normal_t trb = {0};
1540     trb.TRB_type = TRB_TYPE_ENABLE_SLOT;
1541     // kdebug("to enable slot");
1542     if (xhci_send_command(id, (struct xhci_TRB_t *)&trb, true) != 0)
1543     {
1544         kerror("portid:%d: send enable slot failed", port_id);
1545         return -ETIMEDOUT;
1546     }
1547     // kdebug("send enable slot ok");
1548 
1549     uint32_t slot_id = ((struct xhci_TRB_cmd_complete_t *)&trb)->slot_id;
1550     int16_t max_packet;
1551     if (slot_id != 0) // slot id不为0时,是合法的slot id
1552     {
1553         // 为不同速度的设备确定最大的数据包大小
1554         switch (speed)
1555         {
1556         case XHCI_PORT_SPEED_LOW:
1557             max_packet = 8;
1558             break;
1559         case XHCI_PORT_SPEED_FULL:
1560         case XHCI_PORT_SPEED_HI:
1561             max_packet = 64;
1562             break;
1563         case XHCI_PORT_SPEED_SUPER:
1564             max_packet = 512;
1565             break;
1566         }
1567     }
1568     else
1569         return -EAGAIN; // slot id 不合法
1570 
1571     xhci_hc[id].ports[port_id].slot_id = slot_id;
1572     // kdebug("speed=%d", speed);
1573     // 初始化接口的上下文
1574     uint64_t slot_vaddr = xhci_initialize_slot(id, port_id, speed, max_packet);
1575 
1576     retval = xhci_set_address(id, slot_vaddr, slot_id, true);
1577     // kdebug("set addr again");
1578     // 再次发送 set_address命令
1579     // kdebug("to set addr again");
1580     retval = xhci_set_address(id, slot_vaddr, slot_id, false);
1581     if (retval != 0)
1582         return retval;
1583 
1584     memset(dev_desc, 0, sizeof(struct usb_device_desc));
1585     DECLARE_USB_PACKET(ctrl_in_packet, USB_REQ_TYPE_GET_REQUEST, USB_REQ_GET_DESCRIPTOR, (USB_DT_DEVICE << 8), 0, 18);
1586     count = xhci_control_in(id, &ctrl_in_packet, dev_desc, port_id, max_packet);
1587     if (unlikely(count == 0))
1588         return -EAGAIN;
1589     /*
1590         TODO: if the dev_desc->max_packet was different than what we have as max_packet,
1591           you would need to change it here and in the slot context by doing a
1592           evaluate_slot_context call.
1593     */
1594 
1595     xhci_hc[id].ports[port_id].dev_desc = dev_desc;
1596 
1597     // print the descriptor
1598     printk("  Found USB Device:\n"
1599            "                port: %i\n"
1600            "                 len: %i\n"
1601            "                type: %i\n"
1602            "             version: %01X.%02X\n"
1603            "               class: %i\n"
1604            "            subclass: %i\n"
1605            "            protocol: %i\n"
1606            "     max packet size: %i\n"
1607            "           vendor id: 0x%04X\n"
1608            "          product id: 0x%04X\n"
1609            "         release ver: %i%i.%i%i\n"
1610            "   manufacture index: %i (index to a string)\n"
1611            "       product index: %i\n"
1612            "        serial index: %i\n"
1613            "   number of configs: %i\n",
1614            port_id, dev_desc->len, dev_desc->type, dev_desc->usb_version >> 8, dev_desc->usb_version & 0xFF,
1615            dev_desc->_class, dev_desc->subclass, dev_desc->protocol, dev_desc->max_packet_size, dev_desc->vendor_id,
1616            dev_desc->product_id, (dev_desc->device_rel & 0xF000) >> 12, (dev_desc->device_rel & 0x0F00) >> 8,
1617            (dev_desc->device_rel & 0x00F0) >> 4, (dev_desc->device_rel & 0x000F) >> 0, dev_desc->manufacturer_index,
1618            dev_desc->procuct_index, dev_desc->serial_index, dev_desc->config);
1619     return 0;
1620 }
1621 
1622 /**
1623  * @brief 启用xhci控制器的端口
1624  *
1625  * @param id 控制器id
1626  * @return int
1627  */
xhci_hc_start_ports(int id)1628 static int xhci_hc_start_ports(int id)
1629 {
1630     int cnt = 0;
1631     // 注意,这两个循环应该不能合并到一起,因为可能存在usb2端口offset在前,usb3端口在后的情况,那样的话就会出错
1632 
1633     // 循环启动所有的usb3端口
1634     for (int i = 0; i < xhci_hc[id].port_num; ++i)
1635     {
1636         if (XHCI_PORT_IS_USB3(id, i) && XHCI_PORT_IS_ACTIVE(id, i))
1637         {
1638             io_mfence();
1639             // kdebug("to reset port %d, rflags=%#018lx", id, get_rflags());
1640             int rst_ret = xhci_reset_port(id, i);
1641             // kdebug("reset done!, val=%d", rst_ret);
1642             // reset该端口
1643             if (likely(rst_ret == 0)) // 如果端口reset成功,就获取它的描述符
1644                                       // 否则,reset函数会把它给设置为未激活,并且标志配对的usb2端口是激活的
1645             {
1646                 // kdebug("reset port %d ok", id);
1647                 struct usb_device_desc dev_desc = {0};
1648                 if (xhci_get_descriptor(id, i, &dev_desc) == 0)
1649                 {
1650                     xhci_configure_port(id, i);
1651                     ++cnt;
1652                 }
1653                 kdebug("usb3 port %d get desc ok", i);
1654             }
1655         }
1656     }
1657     kdebug("Active usb3 ports:%d", cnt);
1658 
1659     // 循环启动所有的usb2端口
1660     for (int i = 0; i < xhci_hc[id].port_num; ++i)
1661     {
1662         if (XHCI_PORT_IS_USB2(id, i) && XHCI_PORT_IS_ACTIVE(id, i))
1663         {
1664             // kdebug("initializing usb2: %d", i);
1665             // reset该端口
1666             // kdebug("to reset port %d, rflags=%#018lx", i, get_rflags());
1667             if (likely(xhci_reset_port(id, i) ==
1668                        0)) // 如果端口reset成功,就获取它的描述符
1669                            // 否则,reset函数会把它给设置为未激活,并且标志配对的usb2端口是激活的
1670             {
1671                 // kdebug("reset port %d ok", id);
1672 
1673                 struct usb_device_desc dev_desc = {0};
1674                 if (xhci_get_descriptor(id, i, &dev_desc) == 0)
1675                 {
1676                     xhci_configure_port(id, i);
1677                     ++cnt;
1678                 }
1679                 kdebug("USB2 port %d get desc ok", i);
1680             }
1681         }
1682     }
1683     kinfo("xHCI controller %d: Started %d ports.", id, cnt);
1684     return 0;
1685 }
1686 
1687 /**
1688  * @brief 发送HID设备的IDLE数据包
1689  *
1690  * @param id 主机控制器号
1691  * @param port_id 端口号
1692  * @param if_desc 接口结构体
1693  * @return int
1694  */
xhci_hid_set_idle(const int id,const int port_id,struct usb_interface_desc * if_desc)1695 static int xhci_hid_set_idle(const int id, const int port_id, struct usb_interface_desc *if_desc)
1696 {
1697     struct usb_device_desc *dev_desc = xhci_hc[id].ports[port_id].dev_desc;
1698     if (unlikely(dev_desc) == NULL)
1699     {
1700         BUG_ON(1);
1701         return -EINVAL;
1702     }
1703 
1704     DECLARE_USB_PACKET(ctrl_out_packet, USB_REQ_TYPE_SET_CLASS_INTERFACE, 0x0a, 0, 0, 0);
1705     xhci_control_out(id, &ctrl_out_packet, NULL, port_id, dev_desc->max_packet_size);
1706     kdebug("xhci set idle done!");
1707     return 0;
1708 }
1709 
1710 /**
1711  * @brief 配置端点上下文,并发送configure endpoint命令
1712  *
1713  * @param id 主机控制器id
1714  * @param port_id 端口号
1715  * @param ep_num 端点号
1716  * @param ep_type 端点类型
1717  * @param ep_desc 端点描述符
1718  * @return int 错误码
1719  */
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)1720 static int xhci_configure_endpoint(const int id, const int port_id, const uint8_t ep_num, const uint8_t ep_type,
1721                                    struct usb_endpoint_desc *ep_desc)
1722 {
1723 
1724     int retval = 0;
1725     uint64_t slot_context_vaddr = xhci_get_device_context_vaddr(id, port_id);
1726 
1727     xhci_initialize_ep(id, slot_context_vaddr, port_id, ep_num, xhci_hc[id].ports[port_id].dev_desc->max_packet_size,
1728                        usb_get_max_burst_from_ep(ep_desc), ep_type, (ep_num % 2) ? XHCI_DIR_IN_BIT : XHCI_DIR_OUT_BIT,
1729                        xhci_get_port_speed(id, port_id), ep_desc->interval);
1730 
1731     struct xhci_slot_context_t slot;
1732     struct xhci_ep_context_t ep = {0};
1733     // 创建输入上下文缓冲区
1734     uint64_t input_ctx_buffer = (uint64_t)kzalloc(xhci_hc[id].context_size * 33, 0);
1735     // 置位对应的add bit
1736     __write4b(input_ctx_buffer + 4, (1 << ep_num) | 1);
1737     __write4b(input_ctx_buffer + 0x1c, 1);
1738 
1739     // 拷贝slot上下文
1740     __read_from_slot(&slot, slot_context_vaddr);
1741     // 设置该端口的最大端点号。注意,必须设置这里,否则会出错
1742     slot.entries = (ep_num > slot.entries) ? ep_num : slot.entries;
1743 
1744     __write_slot(input_ctx_buffer + xhci_hc[id].context_size, &slot);
1745 
1746     // __write_ep(id, input_ctx_buffer, 2, &ep);
1747     // kdebug("ep_num=%d", ep_num);
1748     // 拷贝将要被配置的端点的信息
1749     __read_from_ep(id, slot_context_vaddr, ep_num, &ep);
1750     // kdebug("ep.tr_dequeue_ptr=%#018lx", ep.tr_dequeue_ptr);
1751     ep.err_cnt = 3;
1752     // 加一是因为input_context头部比slot_context多了一个input_control_ctx
1753     __write_ep(id, input_ctx_buffer, ep_num + 1, &ep);
1754 
1755     struct xhci_TRB_normal_t trb = {0};
1756     trb.buf_paddr = virt_2_phys(input_ctx_buffer);
1757     trb.TRB_type = TRB_TYPE_CONFIG_EP;
1758     trb.cycle = xhci_hc[id].cmd_trb_cycle;
1759     trb.Reserved |= (((uint16_t)xhci_hc[id].ports[port_id].slot_id) << 8) & 0xffff;
1760 
1761     // kdebug("addr=%#018lx", ((struct xhci_TRB_t *)&trb)->param);
1762     // kdebug("status=%#018lx", ((struct xhci_TRB_t *)&trb)->status);
1763     // kdebug("command=%#018lx", ((struct xhci_TRB_t *)&trb)->command);
1764     retval = xhci_send_command(id, (struct xhci_TRB_t *)&trb, true);
1765 
1766     if (unlikely(retval != 0))
1767     {
1768         kerror("port_id:%d, configure endpoint %d failed", port_id, ep_num);
1769         goto failed;
1770     }
1771 
1772     struct xhci_TRB_cmd_complete_t *trb_done = (struct xhci_TRB_cmd_complete_t *)&trb;
1773     if (trb_done->code == TRB_COMP_TRB_SUCCESS) // 成功执行
1774     {
1775         // 如果要从控制器获取刚刚设置的设备地址的话,可以在这里读取slot context
1776         ksuccess("port_id:%d, ep:%d successfully configured.", port_id, ep_num);
1777         retval = 0;
1778     }
1779     else
1780         retval = -EAGAIN;
1781 done:;
1782 failed:;
1783     kfree((void *)input_ctx_buffer);
1784     return retval;
1785 }
1786 
1787 /**
1788  * @brief 配置连接在指定端口上的设备
1789  *
1790  * @param id 主机控制器id
1791  * @param port_id 端口id
1792  * @param full_conf 完整的config
1793  * @return int 错误码
1794  */
xhci_configure_port(const int id,const int port_id)1795 static int xhci_configure_port(const int id, const int port_id)
1796 {
1797     void *full_conf = NULL;
1798     struct usb_interface_desc *if_desc = NULL;
1799     struct usb_endpoint_desc *ep_desc = NULL;
1800     int retval = 0;
1801 
1802     // hint: 暂时只考虑对键盘的初始化
1803     // 获取完整的config
1804     {
1805         struct usb_config_desc conf_desc = {0};
1806         retval = xhci_get_config_desc(id, port_id, &conf_desc);
1807         if (unlikely(retval != 0))
1808             return retval;
1809 
1810         full_conf = kzalloc(conf_desc.total_len, 0);
1811         if (unlikely(full_conf == NULL))
1812             return -ENOMEM;
1813 
1814         retval = xhci_get_config_desc_full(id, port_id, &conf_desc, full_conf);
1815         if (unlikely(retval != 0))
1816             goto failed;
1817     }
1818 
1819     retval = xhci_get_interface_desc(full_conf, 0, &if_desc);
1820     if (unlikely(retval != 0))
1821         goto failed;
1822 
1823     if (if_desc->interface_class == USB_CLASS_HID)
1824     {
1825         // 由于暂时只支持键盘,因此把键盘的驱动也写在这里
1826         // todo: 分离usb键盘驱动
1827 
1828         retval = xhci_get_endpoint_desc(if_desc, 0, &ep_desc);
1829         if (unlikely(retval != 0))
1830             goto failed;
1831         // kdebug("to set conf, val=%#010lx", ((struct usb_config_desc *)full_conf)->value);
1832         retval = xhci_set_configuration(id, port_id, ((struct usb_config_desc *)full_conf)->value);
1833         if (unlikely(retval != 0))
1834             goto failed;
1835         // kdebug("set conf ok");
1836 
1837         // configure endpoint
1838         retval = xhci_configure_endpoint(id, port_id, ep_desc->endpoint_addr, USB_EP_INTERRUPT, ep_desc);
1839         if (unlikely(retval != 0))
1840             goto failed;
1841 
1842         retval = xhci_hid_set_idle(id, port_id, if_desc);
1843         if (unlikely(retval != 0))
1844             goto failed;
1845 
1846         struct usb_hid_desc *hid_desc = NULL;
1847         uint32_t hid_desc_len = 0;
1848         // 获取hid desc
1849         retval = xhci_get_hid_descriptor(id, port_id, full_conf, if_desc->interface_number, &hid_desc);
1850         if (unlikely(retval != 0))
1851             goto failed;
1852 
1853         // 获取hid report
1854         void *hid_report_data = kzalloc(hid_desc->report_desc_len, 0);
1855         if (unlikely(hid_report_data == NULL))
1856             goto failed;
1857         retval =
1858             xhci_get_hid_report(id, port_id, if_desc->interface_number, hid_report_data, hid_desc->report_desc_len);
1859         if (unlikely(retval != 0))
1860         {
1861             kfree(hid_report_data);
1862             goto failed;
1863         }
1864 
1865         kdebug("to parse hid report");
1866         // todo:这里的parse有问题,详见hid_parse函数的注释
1867         // hid_parse_report(hid_report_data, hid_desc->report_desc_len);
1868         kdebug("parse hid report done");
1869 
1870         // kdebug("to find object from hid path");
1871         // struct hid_data_t data = {0};
1872         // data.type = HID_ITEM_INPUT;
1873         // data.path.node[0].u_page = HID_USAGE_PAGE_GEN_DESKTOP;
1874         // data.path.node[0].usage = 0xff;
1875         // data.path.node[2].usage = USAGE_POINTER_Y;     // to get the Y Coordinate, comment X above and uncomment this
1876         // line data.path.node[2].usage = USAGE_POINTER_WHEEL; // to get the Wheel Coordinate, comment X above and
1877         // uncomment this line
1878         // data.path.size = 1;
1879         // hid_parse_find_object(hid_report_data, hid_desc->report_desc_len, &data);
1880         kfree(hid_report_data);
1881     }
1882     goto out;
1883 failed:;
1884     kerror("failed at xhci_configure_port, retval=%d", retval);
1885 out:;
1886     kfree(full_conf);
1887     return retval;
1888 }
1889 /**
1890  * @brief 初始化xhci主机控制器的中断控制
1891  *
1892  * @param id 主机控制器id
1893  * @return int 返回码
1894  */
xhci_hc_init_intr(int id)1895 static int xhci_hc_init_intr(int id)
1896 {
1897     uint64_t retval = 0;
1898 
1899     struct xhci_caps_HCSPARAMS1_reg_t hcs1;
1900     struct xhci_caps_HCSPARAMS2_reg_t hcs2;
1901     io_mfence();
1902     memcpy(&hcs1, xhci_get_ptr_cap_reg32(id, XHCI_CAPS_HCSPARAMS1), sizeof(struct xhci_caps_HCSPARAMS1_reg_t));
1903     io_mfence();
1904     memcpy(&hcs2, xhci_get_ptr_cap_reg32(id, XHCI_CAPS_HCSPARAMS2), sizeof(struct xhci_caps_HCSPARAMS2_reg_t));
1905     io_mfence();
1906 
1907     uint32_t max_segs = (1 << (uint32_t)(hcs2.ERST_Max));
1908     uint32_t max_interrupters = hcs1.max_intrs;
1909 
1910     // 创建 event ring
1911     retval = xhci_create_event_ring(4096, &xhci_hc[id].event_ring_vaddr);
1912     io_mfence();
1913     if (unlikely((int64_t)(retval) == -ENOMEM))
1914         return -ENOMEM;
1915     xhci_hc[id].event_ring_table_vaddr = retval;
1916     xhci_hc[id].current_event_ring_vaddr =
1917         xhci_hc[id].event_ring_vaddr; // 设置驱动程序要读取的下一个event ring trb的地址
1918     retval = 0;
1919 
1920     xhci_hc[id].current_event_ring_cycle = 1;
1921 
1922     // 写入第0个中断寄存器组
1923     io_mfence();
1924     xhci_write_intr_reg32(id, 0, XHCI_IR_MAN, 0x3); // 使能中断并清除pending位(这个pending位是写入1就清0的)
1925     io_mfence();
1926     xhci_write_intr_reg32(id, 0, XHCI_IR_MOD, 0); // 关闭中断管制
1927     io_mfence();
1928     xhci_write_intr_reg32(id, 0, XHCI_IR_TABLE_SIZE, 1); // 当前只有1个segment
1929     io_mfence();
1930     xhci_write_intr_reg64(id, 0, XHCI_IR_DEQUEUE,
1931                           virt_2_phys(xhci_hc[id].current_event_ring_vaddr) |
1932                               (1 << 3)); // 写入dequeue寄存器,并清除busy位(写1就会清除)
1933     io_mfence();
1934     xhci_write_intr_reg64(id, 0, XHCI_IR_TABLE_ADDR, virt_2_phys(xhci_hc[id].event_ring_table_vaddr)); // 写入table地址
1935     io_mfence();
1936 
1937     // 清除状态位
1938     xhci_write_op_reg32(id, XHCI_OPS_USBSTS, (1 << 10) | (1 << 4) | (1 << 3) | (1 << 2));
1939     io_mfence();
1940     // 开启usb中断
1941     // 注册中断处理程序
1942     struct xhci_hc_irq_install_info_t install_info;
1943     install_info.assert = 1;
1944     install_info.edge_trigger = 1;
1945     install_info.processor = 0; // 投递到bsp
1946 
1947     char *buf = (char *)kmalloc(16, 0);
1948     memset(buf, 0, 16);
1949     sprintk(buf, "xHCI HC%d", id);
1950     io_mfence();
1951     irq_register(xhci_controller_irq_num[id], &install_info, &xhci_hc_irq_handler, id, &xhci_hc_intr_controller, buf);
1952     io_mfence();
1953     kfree(buf);
1954 
1955     kdebug("xhci host controller %d: interrupt registered. irq num=%d", id, xhci_controller_irq_num[id]);
1956 
1957     return 0;
1958 }
1959 
1960 /**
1961  * @brief 往xhci控制器发送trb, 并将返回的数据存入原始的trb中
1962  *
1963  * @param id xhci控制器号
1964  * @param trb 传输请求块
1965  * @param do_ring 是否通知doorbell register
1966  * @return int 错误码
1967  */
xhci_send_command(int id,struct xhci_TRB_t * trb,const bool do_ring)1968 static int xhci_send_command(int id, struct xhci_TRB_t *trb, const bool do_ring)
1969 {
1970     uint64_t origin_trb_vaddr = xhci_hc[id].cmd_trb_vaddr;
1971 
1972     // 必须先写入参数和状态数据,最后写入command
1973     __write8b(xhci_hc[id].cmd_trb_vaddr, trb->param);                                    // 参数
1974     __write4b(xhci_hc[id].cmd_trb_vaddr + 8, trb->status);                               // 状态
1975     __write4b(xhci_hc[id].cmd_trb_vaddr + 12, trb->command | xhci_hc[id].cmd_trb_cycle); // 命令
1976 
1977     xhci_hc[id].cmd_trb_vaddr += sizeof(struct xhci_TRB_t); // 跳转到下一个trb
1978 
1979     {
1980         // 如果下一个trb是link trb,则将下一个要操作的地址是设置为第一个trb
1981         struct xhci_TRB_normal_t *ptr = (struct xhci_TRB_normal_t *)xhci_hc[id].cmd_trb_vaddr;
1982         if (ptr->TRB_type == TRB_TYPE_LINK)
1983         {
1984             ptr->cycle = xhci_hc[id].cmd_trb_cycle;
1985             xhci_hc[id].cmd_trb_vaddr = xhci_hc[id].cmd_ring_vaddr;
1986             xhci_hc[id].cmd_trb_cycle ^= 1;
1987         }
1988     }
1989 
1990     if (do_ring) // 按响命令门铃
1991     {
1992         __xhci_write_doorbell(id, 0, 0);
1993 
1994         // 等待中断产生
1995         int timer = 400;
1996         const uint32_t iman0 = xhci_read_intr_reg32(id, 0, XHCI_IR_MAN);
1997 
1998         // Now wait for the interrupt to happen
1999         // We use bit 31 of the command dword since it is reserved
2000         while (timer && ((__read4b(origin_trb_vaddr + 8) & XHCI_IRQ_DONE) == 0))
2001         {
2002             usleep(1000);
2003             --timer;
2004         }
2005         uint32_t x = xhci_read_cap_reg32(id, xhci_hc[id].rts_offset + 0x20);
2006         if (timer == 0)
2007             return -ETIMEDOUT;
2008         else
2009         {
2010             xhci_get_trb(trb, origin_trb_vaddr);
2011             trb->status &= (~XHCI_IRQ_DONE);
2012         }
2013     }
2014     return 0;
2015 }
2016 
2017 /**
2018  * @brief 获取接口的hid descriptor
2019  *
2020  * @param id 主机控制器号
2021  * @param port_id 端口号
2022  * @param full_conf 完整的cofig缓冲区
2023  * @param interface_number 接口号
2024  * @param ret_hid_desc 返回的指向hid描述符的指针
2025  * @return int 错误码
2026  */
xhci_get_hid_descriptor(int id,int port_id,const void * full_conf,int interface_number,struct usb_hid_desc ** ret_hid_desc)2027 static int xhci_get_hid_descriptor(int id, int port_id, const void *full_conf, int interface_number,
2028                                    struct usb_hid_desc **ret_hid_desc)
2029 {
2030     if (unlikely(ret_hid_desc == NULL || full_conf == NULL))
2031         return -EINVAL;
2032     kdebug("to get hid_descriptor.");
2033     // 判断接口index是否合理
2034     if (interface_number >= ((struct usb_config_desc *)full_conf)->num_interfaces)
2035         return -EINVAL;
2036     uint32_t total_len = ((struct usb_config_desc *)full_conf)->total_len;
2037     uint32_t pos = 0;
2038     while (pos < total_len)
2039     {
2040         struct usb_hid_desc *ptr = (struct usb_hid_desc *)(full_conf + pos);
2041         if (ptr->type != USB_DT_HID)
2042         {
2043             pos += ptr->len;
2044             continue;
2045         }
2046         // 找到目标hid描述符
2047         *ret_hid_desc = ptr;
2048         kdebug("Found hid descriptor for port:%d, if:%d, report_desc_len=%d", port_id, interface_number,
2049                ptr->report_desc_len);
2050         return 0;
2051     }
2052 
2053     return -EINVAL;
2054 }
2055 
2056 /**
2057  * @brief 发送get_hid_descriptor请求,将hid
2058  *
2059  * @param id 主机控制器号
2060  * @param port_id 端口号
2061  * @param interface_number 接口号
2062  * @param ret_hid_report hid report要拷贝到的地址
2063  * @param hid_report_len hid report的长度
2064  * @return int 错误码
2065  */
xhci_get_hid_report(int id,int port_id,int interface_number,void * ret_hid_report,uint32_t hid_report_len)2066 static int xhci_get_hid_report(int id, int port_id, int interface_number, void *ret_hid_report, uint32_t hid_report_len)
2067 {
2068     int retval = xhci_get_desc(id, port_id, ret_hid_report, USB_DT_HID_REPORT, 0, interface_number, hid_report_len);
2069     if (unlikely(retval != 0))
2070         kerror("xhci_get_hid_report failed: host_controller:%d, port:%d, interface %d", id, port_id, interface_number);
2071     return retval;
2072 }
2073 /**
2074  * @brief 初始化xhci控制器
2075  *
2076  * @param header 指定控制器的pci device头部
2077  */
xhci_init(struct pci_device_structure_general_device_t * dev_hdr)2078 void xhci_init(struct pci_device_structure_general_device_t *dev_hdr)
2079 {
2080 
2081     if (xhci_ctrl_count >= XHCI_MAX_HOST_CONTROLLERS)
2082     {
2083         kerror("Initialize xhci controller failed: exceed the limit of max controllers.");
2084         return;
2085     }
2086 
2087     spin_lock(&xhci_controller_init_lock);
2088     kinfo("Initializing xhci host controller: bus=%#02x, device=%#02x, func=%#02x, VendorID=%#04x, irq_line=%d, "
2089           "irq_pin=%d",
2090           dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, dev_hdr->header.Vendor_ID,
2091           dev_hdr->Interrupt_Line, dev_hdr->Interrupt_PIN);
2092     io_mfence();
2093     int cid = xhci_hc_find_available_id();
2094     if (cid < 0)
2095     {
2096         kerror("Initialize xhci controller failed: exceed the limit of max controllers.");
2097         goto failed_exceed_max;
2098     }
2099 
2100     memset(&xhci_hc[cid], 0, sizeof(struct xhci_host_controller_t));
2101     xhci_hc[cid].controller_id = cid;
2102     xhci_hc[cid].pci_dev_hdr = dev_hdr;
2103     io_mfence();
2104     {
2105         uint32_t tmp = pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x4);
2106         tmp |= 0x6;
2107         // mem I/O access enable and bus master enable
2108         pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x4, tmp);
2109     }
2110     io_mfence();
2111     // 为当前控制器映射寄存器地址空间
2112     xhci_hc[cid].vbase =
2113         SPECIAL_MEMOEY_MAPPING_VIRT_ADDR_BASE + XHCI_MAPPING_OFFSET + 65536 * xhci_hc[cid].controller_id;
2114     // kdebug("dev_hdr->BAR0 & (~0xf)=%#018lx", dev_hdr->BAR0 & (~0xf));
2115     mm_map_phys_addr(xhci_hc[cid].vbase, dev_hdr->BAR0 & (~0xf), 65536, PAGE_KERNEL_PAGE | PAGE_PWT | PAGE_PCD, true);
2116     io_mfence();
2117 
2118     // 计算operational registers的地址
2119     xhci_hc[cid].vbase_op = xhci_hc[cid].vbase + (xhci_read_cap_reg32(cid, XHCI_CAPS_CAPLENGTH) & 0xff);
2120     io_mfence();
2121     // 重置xhci控制器
2122     FAIL_ON_TO(xhci_hc_reset(cid), failed);
2123     io_mfence();
2124 
2125     // 读取xhci控制寄存器
2126     uint16_t iversion = *(uint16_t *)(xhci_hc[cid].vbase + XHCI_CAPS_HCIVERSION);
2127 
2128     struct xhci_caps_HCCPARAMS1_reg_t hcc1;
2129     struct xhci_caps_HCCPARAMS2_reg_t hcc2;
2130 
2131     struct xhci_caps_HCSPARAMS1_reg_t hcs1;
2132     struct xhci_caps_HCSPARAMS2_reg_t hcs2;
2133     memcpy(&hcc1, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCCPARAMS1), sizeof(struct xhci_caps_HCCPARAMS1_reg_t));
2134     memcpy(&hcc2, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCCPARAMS2), sizeof(struct xhci_caps_HCCPARAMS2_reg_t));
2135     memcpy(&hcs1, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCSPARAMS1), sizeof(struct xhci_caps_HCSPARAMS1_reg_t));
2136     memcpy(&hcs2, xhci_get_ptr_cap_reg32(cid, XHCI_CAPS_HCSPARAMS2), sizeof(struct xhci_caps_HCSPARAMS2_reg_t));
2137 
2138     xhci_hc[cid].db_offset = xhci_read_cap_reg32(cid, XHCI_CAPS_DBOFF) & (~0x3); // bits [1:0] reserved
2139     io_mfence();
2140     xhci_hc[cid].rts_offset = xhci_read_cap_reg32(cid, XHCI_CAPS_RTSOFF) & (~0x1f); // bits [4:0] reserved.
2141     io_mfence();
2142 
2143     xhci_hc[cid].ext_caps_off = 1UL * (hcc1.xECP) * 4;
2144     xhci_hc[cid].context_size = (hcc1.csz) ? 64 : 32;
2145 
2146     if (iversion < 0x95)
2147         kwarn("Unsupported/Unknowned xHCI controller version: %#06x. This may cause unexpected behavior.", iversion);
2148 
2149     {
2150 
2151         // Write to the FLADJ register incase the BIOS didn't
2152         uint32_t tmp = pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x60);
2153         tmp |= (0x20 << 8);
2154         pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0x60, tmp);
2155     }
2156     // if it is a Panther Point device, make sure sockets are xHCI controlled.
2157     if (((pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0) & 0xffff) == 0x8086) &&
2158         (((pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0) >> 16) & 0xffff) ==
2159          0x1E31) &&
2160         ((pci_read_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 8) & 0xff) == 4))
2161     {
2162         kdebug("Is a Panther Point device");
2163         pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0xd8, 0xffffffff);
2164         pci_write_config(dev_hdr->header.bus, dev_hdr->header.device, dev_hdr->header.func, 0xd0, 0xffffffff);
2165     }
2166     io_mfence();
2167     // 关闭legacy支持
2168     FAIL_ON_TO(xhci_hc_stop_legacy(cid), failed);
2169     io_mfence();
2170 
2171     // 端口配对
2172     FAIL_ON_TO(xhci_hc_pair_ports(cid), failed);
2173     io_mfence();
2174 
2175     // ========== 设置USB host controller =========
2176     // 获取页面大小
2177     xhci_hc[cid].page_size = (xhci_read_op_reg32(cid, XHCI_OPS_PAGESIZE) & 0xffff) << 12;
2178     io_mfence();
2179     // 获取设备上下文空间
2180     xhci_hc[cid].dcbaap_vaddr = (uint64_t)kzalloc(2048, 0); // 分配2KB的设备上下文地址数组空间
2181 
2182     io_mfence();
2183     // kdebug("dcbaap_vaddr=%#018lx", xhci_hc[cid].dcbaap_vaddr);
2184     if (unlikely(!xhci_is_aligned64(xhci_hc[cid].dcbaap_vaddr))) // 地址不是按照64byte对齐
2185     {
2186         kerror("dcbaap isn't 64 byte aligned.");
2187         goto failed_free_dyn;
2188     }
2189     // 写入dcbaap
2190     xhci_write_op_reg64(cid, XHCI_OPS_DCBAAP, virt_2_phys(xhci_hc[cid].dcbaap_vaddr));
2191     io_mfence();
2192 
2193     // 创建scratchpad buffer array
2194     uint32_t max_scratchpad_buf = (((uint32_t)hcs2.max_scratchpad_buf_HI5) << 5) | hcs2.max_scratchpad_buf_LO5;
2195     kdebug("max scratchpad buffer=%d", max_scratchpad_buf);
2196     if (max_scratchpad_buf > 0)
2197     {
2198         xhci_hc[cid].scratchpad_buf_array_vaddr = (uint64_t)kzalloc(sizeof(uint64_t) * max_scratchpad_buf, 0);
2199         __write8b(xhci_hc[cid].dcbaap_vaddr, virt_2_phys(xhci_hc[cid].scratchpad_buf_array_vaddr));
2200 
2201         // 创建scratchpad buffers
2202         for (int i = 0; i < max_scratchpad_buf; ++i)
2203         {
2204             uint64_t buf_vaddr = (uint64_t)kzalloc(xhci_hc[cid].page_size, 0);
2205             __write8b(xhci_hc[cid].scratchpad_buf_array_vaddr, virt_2_phys(buf_vaddr));
2206         }
2207     }
2208 
2209     // 创建command ring
2210     xhci_hc[cid].cmd_ring_vaddr = xhci_create_ring(XHCI_CMND_RING_TRBS);
2211     xhci_hc[cid].cmd_trb_vaddr = xhci_hc[cid].cmd_ring_vaddr;
2212 
2213     if (unlikely(!xhci_is_aligned64(xhci_hc[cid].cmd_ring_vaddr))) // 地址不是按照64byte对齐
2214     {
2215         kerror("cmd ring isn't 64 byte aligned.");
2216         goto failed_free_dyn;
2217     }
2218 
2219     // 设置初始cycle bit为1
2220     xhci_hc[cid].cmd_trb_cycle = XHCI_TRB_CYCLE_ON;
2221     io_mfence();
2222     // 写入command ring控制寄存器
2223     xhci_write_op_reg64(cid, XHCI_OPS_CRCR, virt_2_phys(xhci_hc[cid].cmd_ring_vaddr) | xhci_hc[cid].cmd_trb_cycle);
2224     // 写入配置寄存器
2225     uint32_t max_slots = hcs1.max_slots;
2226     // kdebug("max slots = %d", max_slots);
2227     io_mfence();
2228     xhci_write_op_reg32(cid, XHCI_OPS_CONFIG, max_slots);
2229     io_mfence();
2230     // 写入设备通知控制寄存器
2231     xhci_write_op_reg32(cid, XHCI_OPS_DNCTRL, (1 << 1)); // 目前只有N1被支持
2232     io_mfence();
2233 
2234     FAIL_ON_TO(xhci_hc_init_intr(cid), failed_free_dyn);
2235     io_mfence();
2236 
2237     ++xhci_ctrl_count;
2238     io_mfence();
2239     spin_unlock(&xhci_controller_init_lock);
2240     io_mfence();
2241 
2242     return;
2243 
2244 failed_free_dyn:; // 释放动态申请的内存
2245     if (xhci_hc[cid].dcbaap_vaddr)
2246         kfree((void *)xhci_hc[cid].dcbaap_vaddr);
2247 
2248     if (xhci_hc[cid].cmd_ring_vaddr)
2249         kfree((void *)xhci_hc[cid].cmd_ring_vaddr);
2250 
2251     if (xhci_hc[cid].event_ring_table_vaddr)
2252         kfree((void *)xhci_hc[cid].event_ring_table_vaddr);
2253 
2254     if (xhci_hc[cid].event_ring_vaddr)
2255         kfree((void *)xhci_hc[cid].event_ring_vaddr);
2256 
2257 failed:;
2258     io_mfence();
2259     // 取消地址映射
2260     mm_unmap_addr(xhci_hc[cid].vbase, 65536);
2261     io_mfence();
2262     // 清空数组
2263     memset((void *)&xhci_hc[cid], 0, sizeof(struct xhci_host_controller_t));
2264 
2265 failed_exceed_max:;
2266     kerror("Failed to initialize controller: bus=%d, dev=%d, func=%d", dev_hdr->header.bus, dev_hdr->header.device,
2267            dev_hdr->header.func);
2268     spin_unlock(&xhci_controller_init_lock);
2269 }