关键词:linux、驱动、usb、usb hub、集线器、热插拔
每当有设备连接到USB接口时,USB总线在查询hub状态信息的时候会触发hub的中断服务程序hub_irq, 在该函数中置位event_bits,运行工作队列。进入hub_event函数,该函数用来处理端口变化的事件。然后通过一个for循环来检测每个端口的状态信息。利用usb_port_status获取端口信息,如果发生变化就调用hub_port_connect_change函数来配置端口等。
usb设备插入hub的流程
usb hub热插拔
参见文档<<Linux那些事儿之我是USB Core.pdf>>。
hub_configure 调用了 usb_fill_int_urb()函数,并且把 hub_irq 作为一个参数传递了进去,最终把 urb->complete 赋值为 hub_irq。然后,主机控制器会定期询问 hub,每当 hub端口上有一个设备插入或者拔除时,它就会通过USB中断传输的方式向主机控制器打小报告。具体来说,从硬件的角度看,就是Hub 会向主机控制器返回一些信息,或者说 Data,这个 Data 被称作“ Hub and Port Status Change Bitmap”,而从软件角度来看, 主机控制器的驱动程序接下来会在处理好这个过程的 urb 之后, 调用该 urb 的 complete函数,对于 Hub 来说,这个函数就是 hub_irq()。
以USB2.0主机控制器ehci 为例,根集线器和子集线器的驱动 static struct usb_driver hub_driver 的探测函数 hub_probe() 会创建一个中断传输的 urb 并通过函数usb_hcd_submit_urb()->ehci_urb_enqueue() 提交给主机控制器 :
int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)->
INIT_WORK(&hub->events, hub_event); //用于处理hub的事件INIT_WORK(&hub->events, hub_event);
hub_configure(hub, endpoint)->
usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,hub, endpoint->bInterval)->
hub_activate(hub, HUB_INIT)->
usb_submit_urb(hub->urb, GFP_NOIO)-> //提交urb,等执行完成就会回调hub_irq
return usb_hcd_submit_urb(urb, mem_flags)-> //将 hub->urb 提交给主机控制器,urb 传输完成时会调用函数 hub_irq
if (is_root_hub(urb->dev)) //是否为根集线器
{
status = rh_urb_enqueue(hcd, urb)->
return rh_queue_status (hcd, urb);
}
else //子集线器或其它 USB 设备
{
status = map_urb_for_dma(hcd, urb, mem_flags);
hcd->driver->urb_enqueue(hcd, urb, mem_flags);
//对于 ehci 主机控制器 hcd->driver->urb_enqueue = struct hc_driver ehci_hc_driver.urb_enqueue =ehci_urb_enqueue
static int ehci_urb_enqueue ();
}
具体过程如下:
int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)->
INIT_WORK(&hub->events, hub_event); //用于处理hub的事件INIT_WORK(&hub->events, hub_event);
hub_configure(hub, endpoint)->
usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,hub, endpoint->bInterval)->
urb->dev = dev;
urb->pipe = pipe;
urb->transfer_buffer = transfer_buffer;
urb->transfer_buffer_length = buffer_length;
urb->complete = complete_fn = hub_irq;
urb->context = context;
//高速USB设备USB_SPEED_HIGH对应USB2.0协议
if (dev->speed == USB_SPEED_HIGH || dev->speed == USB_SPEED_SUPER)
{
/* make sure interval is within allowed range */
interval = clamp(interval, 1, 16); //高速USB设备的中断传输的时间间隔限制为 2^16 微帧,一微帧=1ms/8=0.125ms
urb->interval = 1 << (interval - 1);
} else {
urb->interval = interval;
}
urb->start_frame = -1;
hub_activate(hub, HUB_INIT)->
usb_submit_urb(hub->urb, GFP_NOIO)-> //提交urb,等执行完成就会回调hub_irq
struct usb_host_endpoint *ep = usb_pipe_endpoint(dev, urb->pipe);
switch (xfertype) {
case USB_ENDPOINT_XFER_ISOC:
case USB_ENDPOINT_XFER_INT:
/* too big? */
switch (dev->speed) {
case USB_SPEED_HIGH: //对应 USB2.0协议 /* units are microframes:单位是微帧,即 1ms/8 = 0.125ms */
/* NOTE usb handles 2^15 = 32768*/
if (urb->interval > (1024 * 8))
urb->interval = 1024 * 8;
max = 1024 * 8;
break;
case USB_SPEED_FULL: /* units are frames/msec :单位是 ms */
case USB_SPEED_LOW:
if (xfertype == USB_ENDPOINT_XFER_INT) {
if (urb->interval > 255)
return -EINVAL;
/* NOTE ohci only handles up to 32 */
max = 128;
} else {
if (urb->interval > 1024)
urb->interval = 1024;
/* NOTE usb and ohci handle up to 2^15 */
max = 1024;
}
break;
default:
return -EINVAL;
}
if (dev->speed != USB_SPEED_WIRELESS) {
/* Round down to a power of 2, no more than max */
urb->interval = min(max, 1 << ilog2(urb->interval));
}
}
return usb_hcd_submit_urb(urb, mem_flags)->
if (is_root_hub(urb->dev)) //是否为根集线器
{
status = rh_urb_enqueue(hcd, urb)->
return rh_queue_status (hcd, urb);
}
else //子集线器或其它 USB 设备
{
status = map_urb_for_dma(hcd, urb, mem_flags);
hcd->driver->urb_enqueue(hcd, urb, mem_flags);
//对于 ehci 主机控制器 hcd->driver->urb_enqueue = struct hc_driver ehci_hc_driver.urb_enqueue =ehci_urb_enqueue
static int ehci_urb_enqueue ()->
switch (usb_pipetype (urb->pipe))
{
case PIPE_INTERRUPT: //中断传输
qh_urb_transaction (ehci, urb, &qtd_list, mem_flags)->
struct ehci_qtd *qtd = ehci_qtd_alloc (ehci, flags);
list_add_tail (&qtd->qtd_list, head); //加入到主机控制器的相关链表
return intr_submit(ehci, urb, &qtd_list, mem_flags)->
epnum = urb->ep->desc.bEndpointAddress;
usb_hcd_link_urb_to_ep(ehci_to_hcd(ehci), urb);
qh = qh_append_tds(ehci, urb, &empty, epnum, &urb->ep->hcpriv);
qh_schedule (ehci, qh);
qh_append_tds(ehci, urb, qtd_list, epnum, &urb->ep->hcpriv);
}
}
如果将函数hub_configure(hub, endpoint) 下如下的代码的代码屏蔽,那么即使有 USB 设备插入集线器,USB 主机控制器有不会有任何反应:
usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,hub, endpoint->bInterval);
当子集线器 hub端口上有一个设备插入或者拔除时,子集线器会向主机控制器发送中断传输消息,主机控制器会产生中断,例如EHCI 的 interrupt 在 HCD 中被分为了 6 种类型,如下宏定义:
// these STS_* flags are also intr_enable bits (USBINTR)
#define STS_IAA (1<<5) /* Interrupted on async advance 当要从asynchronous schedule传输队列中移除一个QH时*/
#define STS_FATAL (1<<4) /* such as some PCI access errors */
#define STS_FLR (1<<3) /* frame list rolled over */
#define STS_PCD (1<<2) /* port change detect:root hub上某个端口上有设备插入或拔出所产生的中断,
需要进一步的读取root hub上各port对应的register判断是插入还是拔出。 */
#define STS_ERR (1<<1) /* "error" completion (overflow, ...) */
#define STS_INT (1<<0) /* "normal" completion (short, ...) 正确完成一次数据传输后所发出的中断*/
对于 USB2.0主机控制器 ehci,其中断处理函数在usb_add_hcd()中设置为 usb_hcd_irq,在函数usb_hcd_irq() 中再调用不同主机控制器驱动的中断函数,例如 struct hc_driver ehci_hc_driver.irq = ehci_irq(hdc):
int usb_add_hcd(struct usb_hcd *hcd, unsigned int irqnum, unsigned long irqflags)->
usb_hcd_request_irqs(hcd, irqnum, irqflags)->
request_irq(irqnum, &usb_hcd_irq, irqflags, hcd->irq_descr, hcd);
irqreturn_t usb_hcd_irq (int irq, void *__hcd)->
hcd->driver->irq(hcd) = struct hc_driver ehci_hc_driver.irq = ehci_irq(hdc);
/*
EHCI 的 interrupt 在 HCD 中被分为了 6 种类型,如下宏定义:
// these STS_* flags are also intr_enable bits (USBINTR)
#define STS_IAA (1<<5) /* Interrupted on async advance 当要从asynchronous schedule传输队列中移除一个QH时*/
#define STS_FATAL (1<<4) /* such as some PCI access errors */
#define STS_FLR (1<<3) /* frame list rolled over */
#define STS_PCD (1<<2) /* port change detect:root hub上某个端口上有设备插入或拔出所产生的中断,
需要进一步的读取root hub上各port对应的register判断是插入还是拔出。 */
#define STS_ERR (1<<1) /* "error" completion (overflow, ...) */
#define STS_INT (1<<0) /* "normal" completion (short, ...) 正确完成一次数据传输后所发出的中断*/
*/
status = ehci_readl(ehci, &ehci->regs->status); //读取主机控制器的寄存器
masked_status = status & (INTR_MASK | STS_FLR); //#define INTR_MASK (STS_IAA | STS_FATAL | STS_PCD | STS_ERR | STS_INT)
ehci_writel(ehci, masked_status, &ehci->regs->status);/* clear (just) interrupts:清除中断标志位。 */
/* remote wakeup [4.3.1] */
if (status & STS_PCD) // port change detect
{
unsigned i = HCS_N_PORTS (ehci->hcs_params);
u32 ppcd = ~0;
/* kick root hub later */
pcd_status = status;
/* resume root hub? */
if (ehci->rh_state == EHCI_RH_SUSPENDED)
usb_hcd_resume_root_hub(hcd);
/* get per-port change detect bits */
if (ehci->has_ppcd)
ppcd = status >> 16;
while (i--)
{
int pstatus;
ehci_dbg (ehci, "port %d remote wakeup\n", i + 1);
usb_hcd_start_port_resume(&hcd->self, i);
mod_timer(&hcd->rh_timer, ehci->reset_done[i])->
expires = apply_slack(timer, expires);
return __mod_timer(timer, expires, false, TIMER_NOT_PINNED);
}
}
ehci_work (ehci)->
ehci->scanning = true;
if (ehci->intr_count > 0)
{
scan_intr(ehci)->
qh_completions(ehci, qh)->
list_entry (entry, struct ehci_qtd, qtd_list);
ehci_urb_done(ehci, last->urb, last_status)->
//ehci-platform 101c0000.usb: ehci_urb_done 1 urb ee71e780 ep1in status 0 len 1/1
ehci_dbg (ehci,
"%s %s urb %p ep%d%s status %d len %d/%d\n",
__func__, urb->dev->devpath, urb,
usb_pipeendpoint (urb->pipe),
usb_pipein (urb->pipe) ? "in" : "out",
status,
urb->actual_length, urb->transfer_buffer_length);
usb_hcd_giveback_urb(ehci_to_hcd(ehci), urb, status)->//主机控制器hcd返还giveback urb
//usb_pipeint用于判断是否属于中断传输
//USB子设备插入集线器时会通过中断传输向主机控制器报告
if (usb_pipeisoc(urb->pipe) || usb_pipeint(urb->pipe))
{
bh = &hcd->high_prio_bh;
high_prio_bh = true;
}
if (high_prio_bh)
{
tasklet_hi_schedule(&bh->bh)->__tasklet_hi_schedule(t)->
raise_softirq_irqoff(HI_SOFTIRQ); //触发软中断
//在函数usb_add_hcd()->init_giveback_urb_bh(&hcd->high_prio_bh)中设置
// tasklet_init(&bh->bh, usb_giveback_urb_bh, (unsigned long)bh);
static void usb_giveback_urb_bh(unsigned long param)->
urb = list_entry(local_list.next, struct urb, urb_list);
list_del_init(&urb->urb_list);
bh->completing_ep = urb->ep;
__usb_hcd_giveback_urb(urb)->
urb->complete(urb);//urb->complete =hub_irq
}
}
USB硬件上的热拔插
USB设备热拔插hot_plug 主要由集线器完成,集线器最多可以有31端口,集线器会监测每个端口的信号线(D+和D-)的电压,集线器的端口上每条线上都有15k欧姆的下拉电阻,而USB设备有900~1575欧姆的上拉电阻。假如有USB设备连接到集线器的端口,集线器就可以探测到电压,然后通过探测哪端拥有上拉电阻来决定USB设备的通信速度。
集线器的硬件有专门的寄存器存放集线器及其端口的当前状态信息,其中寄存器wHubStatus 存放集线器的状态,参见USB2.0协议的Tabel 11-19
集线器的寄存器wHubChange 存放集线器的状态变化信息,,参见USB2.0协议的Tabel 11-20:
集线器的寄存器wPortStatus存放集线器上端口的当前状态信息,参见USB2.0协议的Tabel 11-21:
集线器的寄存器wPortChange存放集线器上端口的状态变化信息,,参见USB2.0协议的Tabel 11-22:
集线器集线器的请求块struct usb_hub *hub 有一专属的请求块hub->urb用于查询连接在集线器的端口的状态变化信息,集线器的请求块hub->urb在函数hub_configure()中创建:
hub->urb = usb_alloc_urb(0, GFP_KERNEL);
usb_fill_int_urb(hub->urb,hdev,pipe,*hub->buffer,maxp,hub_irq,hub, endpoint->bInterval)->
hub->urb->complete = hub_irq;
hub->urb->transfer_buffer = *hub->buffer;
hub_activate(hub)->
status = usb_submit_urb(hub->urb, GFP_NOIO)->
ep = usb_pipe_endpoint(dev, urb->pipe);
return usb_hcd_submit_urb(urb, mem_flags)->
if (is_root_hub(urb->dev)) //判断 是否为根集线器
{
status = rh_urb_enqueue(hcd, urb);
}
else
{
status = map_urb_for_dma(hcd, urb, mem_flags);
status = hcd->driver->urb_enqueue(hcd, urb, mem_flags) = ehci_urb_enqueue
}
USB子设备插入集线器的处理过程
每当 hub端口上有一个设备插入或者拔除时的处理过程如下:
USB设备分为USB子设备 struct usb_device 和USB接口设备struct usb_interface ,USB子设备 struct usb_device 和USB接口设备struct usb_interface对应的驱动结构体都是 struct usb_driver,使用 usb_register() 或者 module_usb_driver()注册,并赋值 for_devices=0,所有的USB子设备 struct usb_device对应的都是通用USB子设备驱动 struct usb_device_driver usb_generic_driver ,其使用usb_register_device_driver(&usb_generic_driver, THIS_MODULE) 注册,因为整个内核源码在函数usb_device_match() 中只有 struct usb_device_driver usb_generic_driver 的 is_usb_device_driver()->return container_of(drv, struct usbdrv_wrap, driver)->for_devices =1 ,
需要驱动开发者开发的只有USB接口设备struct usb_interface 的驱动程序,例如 struct usb_driver hub_driver、struct usb_driver skel_driver、struct usb_driver usb_serial_driver 以及 USB wifi 驱动struct rtw_usb_drv usb_drv ,参见下图:
每当 hub端口上有一个设备插入或者拔除时,通过各级中断处理函数最终会调用到函数 huq_irq()。
如果将函数hub_configure(hub, endpoint) 下如下的代码的代码屏蔽,那么即使有 USB 设备插入集线器,USB 主机控制器有不会有任何反应:
usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,hub, endpoint->bInterval);
每当有设备连接到USB接口时,USB总线在查询hub状态信息的时候会触发hub的中断服务程序hub_irq ,并最终调用 hub_event:
/* completion function, fires on port status changes and various faults */
static void hub_irq(struct urb *urb)->
struct usb_hub *hub = urb->context;
int status = urb->status;
switch (status)
{
case -ENOENT: /* synchronous unlink */
case -ECONNRESET: /* async unlink */
case -ESHUTDOWN: /* hardware going away */
return;
default: /* presumably an error */
/* Cause a hub reset after 10 consecutive errors */
dev_dbg(hub->intfdev, "transfer --> %d\n", status);
if ((++hub->nerrors < 10) || hub->error)
goto resubmit;
hub->error = status;
/* FALL THROUGH */
/* let hub_wq handle things */
case 0: /* we got data: port status changed */
bits = 0;
for (i = 0; i < urb->actual_length; ++i)
bits |= ((unsigned long) ((*hub->buffer)[i]))<< (i*8);
hub->event_bits[0] = bits;
break;
}
hub->nerrors = 0;
/* Something happened, let hub_wq figure it out */
kick_hub_wq(hub)->
queue_work(hub_wq, &hub->events)->//INIT_WORK(&hub->events, hub_event);
static void hub_event(struct work_struct *work)
usb_submit_urb(hub->urb, GFP_ATOMIC); //重新向主机控制器提交中断传输请求 hub->urb
集线器的热插拔处理与集线器驱动hub_driver
每当有设备连接到USB接口时,USB总线在查询hub状态信息的时候会触发hub的中断服务程序hub_irq ,并最终调用 hub_event:
static void hub_event(struct work_struct *work)
struct usb_hub *hub = container_of(work, struct usb_hub, events);
struct usb_device *hdev = hub->hdev;
struct device *hub_dev = hub->intfdev;
struct usb_interface *intf = to_usb_interface(hub_dev);
//对于USB2.0 的 root hub 实际打印:hub 2-0:1.0: state 7 ports 1 chg 0002 evt 0000
//对于 GL852G 集线器有4个端口,实际打印:hub 2-1:1.0: state 7 ports 4 chg 0000 evt 0002
dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
hdev->state, hdev->maxchild,
/* NOTE: expects max 15 ports... */
(u16) hub->change_bits[0],
(u16) hub->event_bits[0]);
for (i = 1; i <= hdev->maxchild; i++) //遍历集线器的每个端口
{
struct usb_port *port_dev = hub->ports[i - 1];
if (test_bit(i, hub->event_bits)
|| test_bit(i, hub->change_bits)
|| test_bit(i, hub->wakeup_bits)) //如果这几个条件都满足,就port_event
{
port_event(hub, i)->
struct usb_port *port_dev = hub->ports[port1 - 1];
struct usb_device *udev = port_dev->child;
struct usb_device *hdev = hub->hdev;
connect_change = test_bit(port1, hub->change_bits);
clear_bit(port1, hub->event_bits);
clear_bit(port1, hub->wakeup_bits);
hub_port_status(hub, port1, &portstatus, &portchange)->
get_port_status(hub->hdev, port1, &hub->status->port)->
for (i = 0; i < USB_STS_RETRIES && //尝试读取5次: #define USB_STS_RETRIES 5
(status == -ETIMEDOUT || status == -EPIPE); i++) {
status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port1,
data, sizeof(*data), USB_STS_TIMEOUT);
}
if (portchange & USB_PORT_STAT_C_CONNECTION) {
usb_clear_port_feature(hdev, port1, USB_PORT_FEAT_C_CONNECTION);
connect_change = 1;
}
if (connect_change) //集线器上的端口状态发生变化
{
hub_port_connect_change(hub, port1, portstatus, portchange)->//处理端口改变的情况
struct usb_port *port_dev = hub->ports[port1 - 1];
struct usb_device *udev = port_dev->child;
//对于USB2.0 的 root hub 实际打印:usb usb2-port1: status 0501, change 0000, 480 Mb/s
dev_dbg(&port_dev->dev, "status %04x, change %04x, %s\n", portstatus,
portchange, portspeed(hub, portstatus));
hub_port_connect(hub, port1, portstatus, portchange)->
struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
struct usb_port *port_dev = hub->ports[port1 - 1];
/* Disconnect any existing devices under this port */
if (udev)
{
//断开该端口设备的连接:如果是root hub,挂接在控制器上的,则断开该端口下的设备。
if (hcd->usb_phy && !hdev->parent)
usb_phy_notify_disconnect(hcd->usb_phy, udev->speed);
usb_disconnect(&port_dev->child);
}
//static bool use_both_schemes = 1;
for (i = 0; i < SET_CONFIG_TRIES; i++) //#define SET_CONFIG_TRIES (2 * (use_both_schemes + 1))
{
/* reallocate for each attempt, since references
* to the previous one can escape in various ways
*/
//分配usb设备内存并初始化bus、type、group、设备在系统中的路径(dev->path)、ep0的属性并设置设备状态为attached。
udev = usb_alloc_dev(hdev, hdev->bus, port1)->
struct usb_hcd *usb_hcd = bus_to_hcd(bus);
struct usb_device *dev = kzalloc(sizeof(*dev), GFP_KERNEL);
device_initialize(&dev->dev);
dev->dev.bus = &usb_bus_type;
dev->dev.type = &usb_device_type; //代表USB子设备,而非USB接口interface,is_usb_device(dev)
dev->dev.groups = usb_device_groups;
dev->dev.dma_mask = bus->controller->dma_mask;
set_dev_node(&dev->dev, dev_to_node(bus->controller));
dev->state = USB_STATE_ATTACHED;
dev->lpm_disable_count = 1;
atomic_set(&dev->urbnum, 0);
INIT_LIST_HEAD(&dev->ep0.urb_list);
dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
/* ep0 maxpacket comes later, from device descriptor */
usb_enable_endpoint(dev, &dev->ep0, false);
dev->can_submit = 1;
/* Save readable and stable topology id, distinguishing devices
* by location for diagnostics, tools, driver model, etc. The
* string is a path along hub ports, from the root. Each device's
* dev->devpath will be stable until USB is re-cabled, and hubs
* are often labeled with these port numbers. The name isn't
* as stable: bus->busnum changes easily from modprobe order,
* cardbus or pci hotplugging, and so on.
*/
if (unlikely(!parent))
{
dev->devpath[0] = '0';
dev->route = 0;
dev->dev.parent = bus->controller;
dev_set_name(&dev->dev, "usb%d", bus->busnum);
root_hub = 1;
}
else
{
/* match any labeling on the hubs; it's one-based */
if (parent->devpath[0] == '0')
{
snprintf(dev->devpath, sizeof dev->devpath,"%d", port1);
/* Root ports are not counted in route string */
dev->route = 0;
}
else
{
snprintf(dev->devpath, sizeof dev->devpath, "%s.%d", parent->devpath, port1);
/* Route string assumes hubs have less than 16 ports */
if (port1 < 15)
dev->route = parent->route +(port1 << ((parent->level - 1)*4));
else
dev->route = parent->route +(15 << ((parent->level - 1)*4));
}
dev->dev.parent = &parent->dev;
dev_set_name(&dev->dev, "%d-%s", bus->busnum, dev->devpath);
/* hub driver sets up TT records */
}
dev->portnum = port1;
dev->bus = bus;
dev->parent = parent;
INIT_LIST_HEAD(&dev->filelist);
if (root_hub) /* Root hub always ok [and always wired] */
dev->authorized = 1;
else
{
dev->authorized = !!HCD_DEV_AUTHORIZED(usb_hcd);
dev->wusb = usb_bus_is_wusb(bus) ? 1 : 0;
}
usb_set_device_state(udev, USB_STATE_POWERED);
udev->bus_mA = hub->mA_per_port;
udev->level = hdev->level + 1;
udev->wusb = hub_is_wusb(hub);
/* Devices connected to SuperSpeed hubs are USB 3.0 or later */
if (hub_is_superspeed(hub->hdev))//判断速度是否为高速
udev->speed = USB_SPEED_SUPER;
else
udev->speed = USB_SPEED_UNKNOWN;
choose_devnum(udev)->//获取设备号,在usbfs中,设备号被用作文件名.
devnum = find_next_zero_bit(bus->devmap.devicemap, 128, bus->devnum_next);
/* reset (non-USB 3.0 devices) and get descriptor */
status = hub_port_init(hub, udev, port1, i)->//初始化设备,设置地址,读取设备描述符
struct usb_device *hdev = hub->hdev;
struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
const char *speed = usb_speed_string(udev->speed);
/*
static const char *const speed_names[] = {
[USB_SPEED_UNKNOWN] = "UNKNOWN",
[USB_SPEED_LOW] = "low-speed",
[USB_SPEED_FULL] = "full-speed",
[USB_SPEED_HIGH] = "high-speed",
[USB_SPEED_WIRELESS] = "wireless",
[USB_SPEED_SUPER] = "super-speed",
[USB_SPEED_SUPER_PLUS] = "super-speed-plus",
};
*/
if (speed < 0 || speed >= ARRAY_SIZE(speed_names))
{
speed = USB_SPEED_UNKNOWN;
}
return speed_names[speed];
//对于连接在 USB2.0 的 root hub 上的 GL852G hub 芯片,
//实际打印:usb 2-1: new high-speed USB device number 2 using ehci-platform
dev_info(&udev->dev,
"%s %s USB device number %d using %s\n",
(udev->config) ? "reset" : "new", speed,
devnum, udev->bus->controller->driver->name);
for (retries = 0; retries < GET_DESCRIPTOR_TRIES; (++retries, msleep(100)))
{
/*
scheme,方案,计划的意思。那么 old scheme, both scheme 这两个词组
似乎已经反映出来说有两个方案,一个旧的,一个新的。这是怎么回事?
什么方面的方案?一个是来自Linux 的方案,一个是来自 Windows 的方案,
目的是为了获得设备的描述符。
*/
if (use_new_scheme(udev, retry_counter))->return USE_NEW_SCHEME(retry);
{
struct usb_device_descriptor *buf;
int r = 0;
did_new_scheme = true;
retval = hub_enable_device(udev);
#define GET_DESCRIPTOR_BUFSIZE 64
buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
for (operations = 0; operations < 3; ++operations)
{
buf->bMaxPacketSize0 = 0;
r = usb_control_msg(udev, usb_rcvaddr0pipe(),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
USB_DT_DEVICE << 8, 0,
buf, GET_DESCRIPTOR_BUFSIZE,
initial_descriptor_timeout);
switch (buf->bMaxPacketSize0) {
case 8: case 16: case 32: case 64: case 255:
if (buf->bDescriptorType ==
USB_DT_DEVICE) {
r = 0;
break;
}
}
}
udev->descriptor.bMaxPacketSize0 = buf->bMaxPacketSize0;
#undef GET_DESCRIPTOR_BUFSIZE
}
}
//获取USB子设备描述符struct usb_device_descriptor
usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE)->
struct usb_device_descriptor *desc = kmalloc(sizeof(*desc), GFP_NOIO);
usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size)->
usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
(type << 8) + index, 0, buf, size,
USB_CTRL_GET_TIMEOUT);
memcpy(&dev->descriptor, desc, size);
usb_detect_quirks(udev)->//找出怪胎
udev->quirks = __usb_detect_quirks(udev, usb_quirk_list);
/* Run it through the hoops (find a driver, etc) */
status = usb_new_device(udev)->
usb_enumerate_device(udev)-> /* Read descriptors */
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
usb_get_configuration(udev);
/* read the standard strings and cache them if present */
udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
udev->manufacturer = usb_cache_string(udev, udev->descriptor.iManufacturer);
udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
err = usb_enumerate_device_otg(udev);
usb_detect_interface_quirks(udev);
//对于 USB2.0 root hub 下接的 GL852G hub 芯片,实际打印:usb 2-1: udev 2, busnum 2, minor = 129
dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
udev->devnum, udev->bus->busnum,
(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
/* export the usbdev device-node for libusb */
//#define USB_DEVICE_MAJOR 189
udev->dev.devt=MKDEV(USB_DEVICE_MAJOR, (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
announce_device(udev)-> /* Tell the world! 告诉全世界我诞生了 */
/*
对于 USB2.0 的 root hub 实际打印:
usb 2-1: New USB device found, idVendor=05e3, idProduct=0610
usb 2-1: New USB device strings: Mfr=0, Product=1, SerialNumber=0
usb 2-1: Product: USB2.0 Hub
*/
dev_info(&udev->dev, "New USB device found, idVendor=%04x, idProduct=%04x\n",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct));
dev_info(&udev->dev,
"New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
udev->descriptor.iManufacturer,
udev->descriptor.iProduct,
udev->descriptor.iSerialNumber);
show_string(udev, "Product", udev->product);
show_string(udev, "Manufacturer", udev->manufacturer);
show_string(udev, "SerialNumber", udev->serial);
device_enable_async_suspend(&udev->dev);
device_add(&udev->dev);
if (hcd->usb_phy && !hdev->parent)
{
usb_phy_notify_connect(hcd->usb_phy,udev->speed);
}
status = hub_power_remaining(hub);
}
当USB子设备连接到集线器hub 的某个端口时,会读取USB子设备的描述符,以便确定USB子设备的类型,然后调用usb_alloc_dev()和usb_new_device() 创建struct usb_device *dev :
udev = usb_alloc_dev(hdev, hdev->bus, port1)->
struct usb_device *dev = kzalloc(sizeof(*dev), GFP_KERNEL);
dev->dev.bus = &usb_bus_type; //代表USB子设备,而非USB接口interface,is_usb_device(dev)
dev->dev.type = &usb_device_type;
status = usb_new_device(udev)->
usb_enumerate_device(udev)-> /* Read descriptors */
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
usb_get_configuration(udev);
/* read the standard strings and cache them if present */
udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
udev->manufacturer = usb_cache_string(udev, udev->descriptor.iManufacturer);
udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
err = usb_enumerate_device_otg(udev);
usb_detect_interface_quirks(udev);
//对于 USB2.0 root hub 下接的 GL852G hub 芯片,实际打印:usb 2-1: udev 2, busnum 2, minor = 129
dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
udev->devnum, udev->bus->busnum,
(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
/* export the usbdev device-node for libusb */
//#define USB_DEVICE_MAJOR 189
udev->dev.devt = MKDEV(USB_DEVICE_MAJOR, (((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
announce_device(udev); /* Tell the world! 告诉全世界我诞生了 */
device_enable_async_suspend(&udev->dev);
device_add(&udev->dev);
函数usb_new_device() 最终调用device_add() 在 USB 总线 struct bus_type usb_bus_type 上注册的驱动程序,在USB 总线 struct bus_type usb_bus_type 存在一个特殊的USB通用驱动struct usb_device_driver usb_generic_driver,所有的USB子设备 struct usb_device对应的都是通用USB子设备驱动 struct usb_device_driver usb_generic_driver,注意其中的 new_udriver->drvwrap.for_devices = 1 ,在函数is_usb_device_driver() 中会判断 for_devices 的值 ,使用 usb_register() 或者 module_usb_driver()注册的USB接口设备struct usb_interface 的驱动程序会赋值new_udriver->drvwrap.for_devices = 0,例如 struct usb_driver hub_driver、struct usb_driver skel_driver、struct usb_driver usb_serial_driver 以及 USB wifi 驱动struct rtw_usb_drv usb_drv :
int usb_register_device_driver(struct usb_device_driver *new_udriver, struct module *owner)
{
new_udriver->drvwrap.for_devices = 1; //在函数is_usb_device_driver() 中会判断 for_devices 的值
new_udriver->drvwrap.driver.name = new_udriver->name;
new_udriver->drvwrap.driver.bus = &usb_bus_type;
new_udriver->drvwrap.driver.probe = usb_probe_device;
new_udriver->drvwrap.driver.remove = usb_unbind_device;
new_udriver->drvwrap.driver.owner = owner;
}
创建USB子设备 struct usb_device 匹配的就是驱动程序 struct usb_device_driver usb_generic_driver,当执行 device_add() 是调用的是其探测函数为 generic_probe :
struct usb_device_driver usb_generic_driver = {
.name = "usb",
.probe = generic_probe,
.disconnect = generic_disconnect,
.suspend = generic_suspend,
.resume = generic_resume,
.supports_autosuspend = 1,
};
USB子设备 struct usb_device 执行 device_add()的过程中匹配的驱动程序是struct usb_device_driver usb_generic_driver, 如下:
struct usb_device_driver usb_generic_driver = {
.name = "usb",
.probe = generic_probe,
.disconnect = generic_disconnect,
.suspend = generic_suspend,
.resume = generic_resume,
.supports_autosuspend = 1,
};
USB子设备 struct usb_device 执行 device_add()的过程中匹配的驱动程序是struct usb_device_driver usb_generic_driver, 如下:
udev = usb_alloc_dev(hdev, hdev->bus, port1)->
struct usb_device *dev = kzalloc(sizeof(*dev), GFP_KERNEL);
dev->dev.bus = &usb_bus_type; //代表USB子设备,而非USB接口interface,is_usb_device(dev)
dev->dev.type = &usb_device_type;
status = usb_new_device(udev)->
usb_enumerate_device(udev)-> /* Read descriptors */
announce_device(udev); /* Tell the world! 告诉全世界我诞生了 */
device_enable_async_suspend(&udev->dev);
device_add(&udev->dev)->
dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
// 对于 USB2.0 的 root hub 实际打印:device: 'usb2': device_add
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
error = bus_add_device(dev)->
struct bus_type *bus = bus_get(dev->bus);
//对于 USB2.0 的 root hub 实际打印: bus: 'usb': add device usb2
pr_debug("bus: '%s': add device %s\n", bus->name, dev_name(dev));
error = sysfs_create_link(&dev->kobj, &dev->bus->p->subsys.kobj, "subsystem");
klist_add_tail(&dev->p->knode_bus, &bus->p->klist_devices);
blocking_notifier_call_chain(&dev->bus->p->bus_notifier, BUS_NOTIFY_ADD_DEVICE, dev);
kobject_uevent(&dev->kobj, KOBJ_ADD);
bus_probe_device(dev)->device_initial_probe(dev)->__device_attach(dev, true)->
bus_for_each_drv(dev->bus, NULL, &data, _device_attach_driver)-> //在 USB 总线 struct bus_type usb_bus_type 上注册的驱动程序
while ((drv = next_driver(&i)) && !error) //在 USB 总线 struct bus_type usb_bus_type 上注册的驱动程序
{
error = fn(drv, data)=_device_attach_driver;
static int __device_attach_driver(struct device_driver *drv, void *_data)->
if (!driver_match_device(drv, dev))-> //在 USB 总线 struct bus_type usb_bus_type 上匹配到驱动时返回值 为 1
return drv->bus->match ? drv->bus->match(dev, drv) : 1;
struct bus_type usb_bus_type.match = usb_device_match,
// usb_device_match 有匹配的驱动时返回值为 1
//在函数usb_alloc_dev() 中设置 dev->dev.type = &usb_device_type;
static int usb_device_match(struct device *dev, struct device_driver *drv)
{
/* devices and interfaces are handled separately */
//对于 usb子设备 ,is_usb_device(dev) 的返回值为 true
//在函数usb_alloc_dev() 中设置 dev->dev.type = &usb_device_type;
if (is_usb_device(dev)) //return dev->type == &usb_device_type;
{
/* interface drivers never match devices */
//对于 USB通用驱动struct usb_device_driver usb_generic_driver, is_usb_device_driver() 返回值为1
if (!is_usb_device_driver(drv))->
return container_of(drv, struct usbdrv_wrap, driver)->for_devices;
{
return 0;
}
/* TODO: Add real matching code */
return 1;
}
//在函数usb_set_configuration()中设置:intf->dev.type = &usb_if_device_type;
else if (is_usb_interface(dev)) -> return dev->type == &usb_if_device_type; // 匹配USB接口设备的驱动
{
struct usb_interface *intf;
struct usb_driver *usb_drv;
const struct usb_device_id *id;
/* device drivers never match interfaces */
if (is_usb_device_driver(drv))
return 0;
intf = to_usb_interface(dev);
usb_drv = to_usb_driver(drv);
id = usb_match_id(intf, usb_drv->id_table);
if (id)
return 1;
id = usb_match_dynamic_id(intf, usb_drv);
if (id)
return 1;
}
return 0;
}
{
return 0;
}
return driver_probe_device(drv, dev)-> //在 USB 总线 struct bus_type usb_bus_type 上匹配到驱动时执行到这里
//对于 USB2.0 的 root hub 实际打印: bus: 'usb': driver_probe_device: matched device usb2 with driver usb
pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
drv->bus->name, __func__, dev_name(dev), drv->name);
really_probe(dev, drv)->
//对于 USB2.0 的 root hub 实际打印: bus: 'usb': driver_probe_device: matched device usb2 with driver usb
pr_debug("bus: '%s': %s: probing driver %s with device %s\n",
drv->bus->name, __func__, drv->name, dev_name(dev));
dev->driver = drv;
// 所有USB子设备struct usb_device和USB接口设备struct usb_interface 都挂在USB总线上struct struct bus_type usb_bus_type
if (dev->bus->probe) //struct struct bus_type usb_bus_type.probe = NULL
{
/*
struct bus_type usb_bus_type = {
.name = "usb",
.match = usb_device_match,
.uevent = usb_uevent,
.need_parent_lock = true,
};
*/
ret = dev->bus->probe(dev);
}
else if (drv->probe) //USB子设备 struct usb_device 驱动的情况
{
/*
struct bus_type usb_bus_type = {
.name = "usb",
.match = usb_device_match,
.uevent = usb_uevent,
.need_parent_lock = true,
};
*/
ret = drv->probe(dev); //匹配到USB通用驱动struct usb_device_driver usb_generic_driver
static int generic_probe(struct usb_device *udev)->
usb_choose_configuration(udev)->
num_configs = udev->descriptor.bNumConfigurations;
usb_get_max_power(udev, c);
i = best->desc.bConfigurationValue;
//对于 USB2.0 的 root hub 连接的 GL852G hub 芯片打印:usb 2-1: configuration #1 chosen from 1 choice
dev_dbg(&udev->dev, "configuration #%d chosen from %d choice%s\n",
i, num_configs, plural(num_configs));
usb_set_configuration(udev, c)->
int nintf = cp->desc.bNumInterfaces;
struct usb_interface **new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
i = dev->bus_mA - usb_get_max_power(dev, cp);
usb_autoresume_device(dev);
usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
struct usb_host_interface *alt = usb_altnum_to_altsetting(intf, 0);
struct usb_interface *intf->cur_altsetting = alt;
usb_enable_interface(dev, intf, true);
intf->dev.parent = &dev->dev;
intf->dev.driver = NULL;
intf->dev.bus = &usb_bus_type;
intf->dev.type = &usb_if_device_type; //USB 子设备
intf->dev.groups = usb_interface_groups;
intf->dev.dma_mask = dev->dev.dma_mask;
INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
/*
static void __usb_queue_reset_device(struct work_struct *ws)->
usb_reset_device(udev)-> usb_reset_and_verify_device(udev)->
usb_ep0_reinit(udev);
descriptors_changed(udev, &descriptor, bos)->
usb_string(udev, udev->descriptor.iSerialNumber,buf, serial_len)->
usb_get_langid(dev, tbuf)->
//对于 GL852G hub 芯片实际打印:usb 2-1: default language 0x0409
usb_string_sub(dev, dev->string_langid, index, tbuf);
usb_string_sub(dev, dev->string_langid, index, tbuf);
*/
intf->minor = -1;
device_initialize(&intf->dev);
pm_runtime_no_callbacks(&intf->dev);
dev_set_name(&intf->dev, "%d-%s:%d.%d",
dev->bus->busnum, dev->devpath,
configuration, alt->desc.bInterfaceNumber);
usb_get_dev(dev);
usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
usb_set_device_state(dev, USB_STATE_CONFIGURED);
for (i = 0; i < nintf; ++i)
{
struct usb_interface *intf = cp->interface[i];
/*
对于 USB2.0 的 root hub 连接的 GL852G hub 芯片实际打印:
usb 2-1: adding 2-1:1.0 (config #1, interface 0)
root@mxlos:/sys/bus/usb/drivers/usb/usb2/2-1/2-1:1.0# ls
2-1-port1 2-1-port3 authorized
bInterfaceClass bInterfaceProtocol bNumEndpoints
ep_81 power supports_autosuspend
2-1-port2 2-1-port4 bAlternateSetting
bInterfaceNumber bInterfaceSubClass driver
modalias subsystem uevent
root@mxlos:/sys/bus/usb/drivers/usb/usb2/2-1/2-1:1.0# cat modalias
usb:v05E3p0610d6160dc09dsc00dp02ic09isc00ip02in00
root@mxlos:/sys/bus/usb/drivers/usb/usb2/2-1/2-1:1.0# cat bInterfaceClass
09
root@mxlos:/sys/bus/usb/drivers/usb/usb2/2-1/2-1:1.0# cat uevent
DEVTYPE=usb_interface
DRIVER=hub
PRODUCT=5e3/610/6160
TYPE=9/0/2
INTERFACE=9/0/2
MODALIAS=usb:v05E3p0610d6160dc09dsc00dp02ic09isc00ip02in00
root@mxlos:/sys/bus/usb/drivers/usb/usb2/2-1/2-1:1.0#
*/
dev_dbg(&dev->dev,
"adding %s (config #%d, interface %d)\n",
dev_name(&intf->dev), configuration,
intf->cur_altsetting->desc.bInterfaceNumber);
device_enable_async_suspend(&intf->dev);
ret = device_add(&intf->dev)->
dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
//对于USB2.0 的 root hub 的 interface 0 实际打印: device: '2-0:1.0': device_add
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
kobject_uevent(&dev->kobj, KOBJ_ADD);
bus_probe_device(dev);
create_intf_ep_devs(intf);
}
usb_notify_add_device(udev)->
blocking_notifier_call_chain(&usb_notifier_list, USB_DEVICE_ADD, udev);
}
}
else if (drv->probe) //USB接口子设备 struct usb_interface 驱动的情况
{
//对于 usb hub 驱动 struct usb_driver hub_driver hub.drvwrap.driver.probe = usb_probe_interface
ret = drv->probe(dev)=usb_probe_interface;
static int usb_probe_interface(struct device *dev)->
struct usb_device_id *id = usb_match_dynamic_id(intf, driver);
if (!id)
{
id = usb_match_id(intf, driver->id_table)->
for (; id->idVendor || id->idProduct || id->bDeviceClass ||
id->bInterfaceClass || id->driver_info; id++) {
if (usb_match_one_id(interface, id))->
intf = interface->cur_altsetting;
dev = interface_to_usbdev(interface);
if (!usb_match_device(dev, id))
return 0;
return usb_match_one_id_intf(dev, intf, id);
{
return id;
}
}
}
dev_dbg(dev, "%s - got id\n", __func__);
driver->probe(intf, id);//对于 usb hub 驱动 struct usb_driver hub_driver.probe = hub_probe
static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)->
dev_info(&intf->dev, "USB hub found\n");/* We found a hub */
struct usb_hub *hub = kzalloc(sizeof(*hub), GFP_KERNEL);
hub->intfdev = &intf->dev;
hub->hdev = hdev;
INIT_DELAYED_WORK(&hub->leds, led_work);
INIT_DELAYED_WORK(&hub->init_work, NULL);
INIT_WORK(&hub->events, hub_event);
usb_get_intf(intf);
usb_get_dev(hdev);
usb_set_intfdata(intf, hub);
intf->needs_remote_wakeup = 1;
hub_configure(hub, endpoint)->
struct usb_hub *hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
hub->descriptor = kzalloc(sizeof(*hub->descriptor), GFP_KERNEL);
get_hub_descriptor(hdev, hub->descriptor); //Request the entire hub descriptor.
maxchild = hub->descriptor->bNbrPorts;
//对于 USB2.0 的 root hub 实际打印: hub 2-0:1.0: 1 port detected
dev_info(hub_dev, "%d port%s detected\n", maxchild, (maxchild == 1) ? "" : "s");
hub->ports = kzalloc(maxchild * sizeof(struct usb_port *), GFP_KERNEL);
wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
//对于 USB2.0 的 root hub 实际打印:hub 2-0:1.0: standalone hub
dev_dbg(hub_dev, "standalone hub\n");
switch (wHubCharacteristics & HUB_CHAR_LPSM)
{
case HUB_CHAR_COMMON_LPSM:
dev_dbg(hub_dev, "ganged power switching\n");
break;
case HUB_CHAR_INDV_PORT_LPSM:
//对USB2.0 的 root hub 实际打印:hub 2-0:1.0: individual port power switching
dev_dbg(hub_dev, "individual port power switching\n");
break;
case HUB_CHAR_NO_LPSM:
case HUB_CHAR_LPSM:
dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
break;
}
switch (wHubCharacteristics & HUB_CHAR_OCPM) {
case HUB_CHAR_COMMON_OCPM:
dev_dbg(hub_dev, "global over-current protection\n");
break;
case HUB_CHAR_INDV_PORT_OCPM:
//对USB2.0 的 root hub 打印:hub 2-0:1.0: individual port over-current protection
dev_dbg(hub_dev, "individual port over-current protection\n");
break;
case HUB_CHAR_NO_OCPM:
case HUB_CHAR_OCPM:
dev_dbg(hub_dev, "no over-current protection\n");
break;
}
INIT_LIST_HEAD(&hub->tt.clear_list);
INIT_WORK(&hub->tt.clear_work, hub_tt_work);
//对于 USB2.0 的 root hub 实际打印:hub 2-0:1.0: power on to power good time: 20ms
dev_dbg(hub_dev, "power on to power good time: %dms\n",
hub->descriptor->bPwrOn2PwrGood * 2);
usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
hcd = bus_to_hcd(hdev->bus);
hub_hub_status(hub, &hubstatus, &hubchange);
//对于 USB2.0 的 root hub 实际打印:hub 2-0:1.0: local power source is good
dev_dbg(hub_dev, "local power source is %s\n",
(hubstatus & HUB_STATUS_LOCAL_POWER)
? "lost (inactive)" : "good");
hub->urb = usb_alloc_urb(0, GFP_KERNEL);
usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq, hub, endpoint->bInterval);
for (i = 0; i < maxchild; i++)
{
ret = usb_hub_create_port_device(hub, i + 1)->
struct usb_port *port_dev = kzalloc(sizeof(*port_dev), GFP_KERNEL);
port_dev->req = kzalloc(sizeof(*(port_dev->req)), GFP_KERNEL);
hub->ports[port1 - 1] = port_dev;
port_dev->portnum = port1;
set_bit(port1, hub->power_bits);
port_dev->dev.parent = hub->intfdev;
port_dev->dev.groups = port_dev_group;
port_dev->dev.type = &usb_port_device_type;
port_dev->dev.driver = &usb_port_driver;
//对于 USB2.0 的 root hub 上的第一个USB子设备名为 : usb2-port1
dev_set_name(&port_dev->dev, "%s-port%d",
dev_name(&hub->hdev->dev), port1);
device_register(&port_dev->dev)->
device_initialize(dev);
return device_add(dev);
}
hub_activate(hub, HUB_INIT)->
delay = hub_power_on_good_delay(hub);
hub_power_on(hub, false)->
//对于 USB2.0 的 root hub 实际打印:hub 2-0:1.0: enabling power on all ports
dev_dbg(hub->intfdev, "enabling power on all ports\n");
INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
init3:
usb_submit_urb(hub->urb, GFP_NOIO); //提交urb,等执行完成就会回调hub_irq
/* Scan all ports that need attention */
kick_hub_wq(hub)->
intf = to_usb_interface(hub->intfdev);
//INIT_WORK(&hub->events, hub_event);
queue_work(hub_wq, &hub->events)//把hub_event加入工作队列,开始运行
intf->condition = USB_INTERFACE_BOUND;
}
driver_bound(dev);
//对于 USB2.0 的 root hub 实际打印: bus: 'usb': really_probe: bound device usb2 to driver usb
pr_debug("bus: '%s': %s: bound device %s to driver %s\n",
drv->bus->name, __func__, dev_name(dev), drv->name);
}
普通USB子设备的热插拔处理
设备 (struct usb_device) 、配置 (struct usb_host_config) 、接口 (struct usb_interface)、 设置(struct usb_host_interface)、端点 (struct usb_host_endpoint) 之间的关系如下:
USB子设备struct usb_device 是由一些配置 (struct usb_host_config) 、接口 (struct usb_interface)、 设置(struct usb_host_interface)、端点 (struct usb_host_endpoint)组成,即一个USB设备可以含有一个或多个配置,在每个配置中可含有一个或多个接口,在每个接口中可含有若干个端点。一个USB设备驱动可能包含多个子驱动。一个USB设备子驱动程序对应一个USB接口,而非整个USB设备。
- 设备 (struct usb_device) :就是一个实实在在的USB设备,比如集线器Hub、鼠标、键盘、打印机、U盘。
- 配置 (struct usb_host_config):一个USB设备可以有一种或者几种配置。没见过具体的USB设备?那么手机见过吧,每个手机都会有多种配置,或者说“设定”。比如,我的这款Nokia 6300手机,手机语言可以设定为English、繁体中文、简体中文,一旦选择了其中一种,那么手机里边所显示的所有的信息都是该种语言/字体。再举一个最简单的例子,操作模式也有好几种,标准、无声、会议等。如果我设为“会议”模式,那么就是只振动不发声,要是设为“无声”模式,那么就啥动静也不会有,只能凭感觉了,以前去公司面试的话通常就是设为“无声”模式,因为觉得振动也不好,让人家面试官听到了还是不合适。那么USB设备的配置也是如此,不同的USB设备当然有不同的配置了,或者说需要配置哪些东西也会不一样。比如4G上网卡就有2种配置:U盘、上网卡。第1次把4G上网卡插入电脑时,它是一个U盘,可以安装里面的程序。装好程序后,把它再次插入电脑,它就是一个上网卡。驱动程序可以选择让它工作于哪种配置,同一时间只能有一种配置有效。大多数的USB设备只有一种配置。
- 接口 (struct usb_interface):每个配置下可以有多个接口,这个接口不是硬件上的接口,可以把这个接口理解为功能,一个接口就代表该设备当前支持的一种功能。
- 端点 (struct usb_host_endpoint) :每个接口可以有多个端点。USB主机和设备就是通过端点进行数据交互的。每个端点地址对应一个方向,例如端点2-IN,端点2-OUT,这两个含义完全不同。
设备 (struct usb_device) 、配置 (struct usb_host_config) 、接口 (struct usb_interface)、 设置(struct usb_host_interface)、端点 (struct usb_host_endpoint) 之间的关系如下:
普通USB子设备(非集线器)struct usb_device 插入集线器 hub 端口后的处理过程如下:
普通USB子设备(非集线器)struct usb_device 插入集线器 hub 端口触发中断调用 hub_event ,并调用usb_get_device_descriptor() 读取USB子设备 struct usb_device 的设备描述符 struct usb_device_descriptor,并最终调用函数usb_alloc_dev()和usb_new_device() 创建USB子设备 struct usb_device ,usb_new_device() 创建USB子设备 struct usb_device 的最后一步调用 device_add() 在总线 struct bus_type usb_bus_type上寻找匹配的驱动 struct usb_device_driver usb_generic_driver,并执行 generic_probe()->usb_set_configuration(udev, c) 创建USB接口设备 struct usb_interface ,并再次调用 device_add() 在总线 struct bus_type usb_bus_type上寻找匹配的驱动 struct usb_device_driver :
static void hub_event(struct work_struct *work)
struct usb_hub *hub = container_of(work, struct usb_hub, events);
struct usb_device *hdev = hub->hdev;
struct device *hub_dev = hub->intfdev;
struct usb_interface *intf = to_usb_interface(hub_dev);
port_event(hub, i)->
hub_port_status(hub, port1, &portstatus, &portchange);
hub_port_connect_change(hub, port1, portstatus, portchange)->//处理端口改变的情况
hub_port_connect(hub, port1, portstatus, portchange)->
udev = usb_alloc_dev(hdev, hdev->bus, port1);
status = hub_port_init(hub, udev, port1, i)->//初始化设备,设置地址,读取设备描述符
//获取USB子设备描述符struct usb_device_descriptor
usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
memcpy(&dev->descriptor, desc, size);
/* Run it through the hoops (find a driver, etc) */
status = usb_new_device(udev)->
usb_enumerate_device(udev)-> /* Read descriptors */
announce_device(udev)-> /* Tell the world! 告诉全世界我诞生了 */
device_add(&udev->dev)->
bus_probe_device(dev)->device_initial_probe(dev)->__device_attach()->
return driver_probe_device(drv, dev)->
static int generic_probe(struct usb_device *udev)->
usb_choose_configuration(udev);
usb_set_configuration(udev, c)->
struct usb_interface *intf->dev.parent = &dev->dev;
intf->dev.driver = NULL;
intf->dev.bus = &usb_bus_type;
intf->dev.type = &usb_if_device_type; //USB接口设备
device_add(&intf->dev)
usb_new_device() 创建USB子设备 struct usb_device 的最后一步调用 device_add() 在总线 struct bus_type usb_bus_type上寻找匹配的的驱动 struct usb_driver:
device_add(&udev->dev)->
dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
// 对于 USB2.0 的 root hub 实际打印:device: 'usb2': device_add
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
error = bus_add_device(dev)->
struct bus_type *bus = bus_get(dev->bus);
//对于 usb-skeketon.c 驱动实际打印: bus: 'usb': add driver skeleton
pr_debug("bus: '%s': add device %s\n", bus->name, dev_name(dev));
error = sysfs_create_link(&dev->kobj, &dev->bus->p->subsys.kobj, "subsystem");
klist_add_tail(&dev->p->knode_bus, &bus->p->klist_devices);
blocking_notifier_call_chain(&dev->bus->p->bus_notifier, BUS_NOTIFY_ADD_DEVICE, dev);
kobject_uevent(&dev->kobj, KOBJ_ADD);
bus_probe_device(dev)->device_initial_probe(dev)->__device_attach(dev, true)->
bus_for_each_drv(dev->bus, NULL, &data, _device_attach_driver)-> //在 USB 总线 struct bus_type usb_bus_type 上注册的驱动程序
while ((drv = next_driver(&i)) && !error) //在 USB 总线 struct bus_type usb_bus_type 上注册的驱动程序
{
error = fn(drv, data)=_device_attach_driver;
static int __device_attach_driver(struct device_driver *drv, void *_data)->
if (!driver_match_device(drv, dev))-> //在 USB 总线 struct bus_type usb_bus_type 上匹配到驱动时返回值 为 1
return drv->bus->match ? drv->bus->match(dev, drv) : 1;
struct bus_type usb_bus_type.match = usb_device_match,
// usb_device_match 有匹配的驱动时返回值为 1
//在函数usb_alloc_dev() 中设置 dev->dev.type = &usb_device_type;
static int usb_device_match(struct device *dev, struct device_driver *drv)
{
/* devices and interfaces are handled separately */
//对于 usb子设备 ,is_usb_device(dev) 的返回值为 true
//在函数usb_alloc_dev() 中设置 dev->dev.type = &usb_device_type;
if (is_usb_device(dev)) //return dev->type == &usb_device_type;
{
/* interface drivers never match devices */
//对于 USB通用驱动struct usb_device_driver usb_generic_driver, is_usb_device_driver() 返回值为1
if (!is_usb_device_driver(drv))->
return container_of(drv, struct usbdrv_wrap, driver)->for_devices;
{
return 0;
}
/* TODO: Add real matching code */
return 1;
}
//在函数usb_set_configuration()中设置:intf->dev.type = &usb_if_device_type;
else if (is_usb_interface(dev)) -> return dev->type == &usb_if_device_type; // 匹配USB接口设备的驱动
{
struct usb_interface *intf;
struct usb_driver *usb_drv;
const struct usb_device_id *id;
/* device drivers never match interfaces */
if (is_usb_device_driver(drv))
return 0;
intf = to_usb_interface(dev);
usb_drv = to_usb_driver(drv);
id = usb_match_id(intf, driver->id_table)->
for (; id->idVendor || id->idProduct || id->bDeviceClass ||
id->bInterfaceClass || id->driver_info; id++) {
if (usb_match_one_id(interface, id))->
intf = interface->cur_altsetting;
dev = interface_to_usbdev(interface);
if (!usb_match_device(dev, id))
return 0;
return usb_match_one_id_intf(dev, intf, id);
{
return id;
}
}
if (id)
return 1;
id = usb_match_dynamic_id(intf, usb_drv);
if (id)
return 1;
}
return 0;
}
{
return 0;
}
return driver_probe_device(drv, dev)-> //在 USB 总线 struct bus_type usb_bus_type 上匹配到驱动时执行到这里
//对于 USB2.0 的 root hub 实际打印: bus: 'usb': driver_probe_device: matched device usb2 with driver usb
pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
drv->bus->name, __func__, dev_name(dev), drv->name);
really_probe(dev, drv)->
//对于 USB2.0 的 root hub 实际打印: bus: 'usb': driver_probe_device: matched device usb2 with driver usb
pr_debug("bus: '%s': %s: probing driver %s with device %s\n",
drv->bus->name, __func__, drv->name, dev_name(dev));
dev->driver = drv;
// 所有USB子设备struct usb_device和USB接口设备struct usb_interface 都挂在USB总线上struct struct bus_type usb_bus_type
if (dev->bus->probe) //struct struct bus_type usb_bus_type.probe = NULL
{
/*
struct bus_type usb_bus_type = {
.name = "usb",
.match = usb_device_match,
.uevent = usb_uevent,
.need_parent_lock = true,
};
*/
ret = dev->bus->probe(dev);
}
else if (drv->probe) //USB接口子设备 struct usb_interface 驱动的情况
{
//对于驱动 struct usb_driver drv.drvwrap.driver.probe = usb_probe_interface
//使用 usb_register() 或者 module_usb_driver()注册struct usb_driver drv,
// 其struct usb_driver drv.drvwrap.driver.probe = usb_probe_interface
ret = drv->probe(dev)=usb_probe_interface;
static int usb_probe_interface(struct device *dev)->
struct usb_device_id *id = usb_match_dynamic_id(intf, driver);
if (!id)
{
id = usb_match_id(intf, driver->id_table)->
for (; id->idVendor || id->idProduct || id->bDeviceClass ||
id->bInterfaceClass || id->driver_info; id++) {
if (usb_match_one_id(interface, id))->
intf = interface->cur_altsetting;
dev = interface_to_usbdev(interface);
if (!usb_match_device(dev, id))
return 0;
return usb_match_one_id_intf(dev, intf, id);
{
return id;
}
}
}
dev_dbg(dev, "%s - got id\n", __func__);
//对于 usb-skeletion.c 驱动 struct usb_driver skel_driver.probe = skel_probe
//对于 usb serial 驱动,struct usb_driver usb_serial_driver.probe = usb_serial_probe
driver->probe(intf, id);
static int usb_serial_probe(struct usb_interface *interface, const struct usb_device_id *id)->
type = search_serial_device(interface);
serial = create_serial(dev, interface, type);
iface_desc = interface->cur_altsetting;
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i)
{
endpoint = &iface_desc->endpoint[i].desc;
if (usb_endpoint_is_bulk_in(endpoint)) {
/* we found a bulk in endpoint */
dev_dbg(ddev, "found bulk in on endpoint %d\n", i);
if (num_bulk_in < MAX_NUM_PORTS) {
bulk_in_endpoint[num_bulk_in] = endpoint;
++num_bulk_in;
}
}
if (usb_endpoint_is_bulk_out(endpoint)) {
/* we found a bulk out endpoint */
dev_dbg(ddev, "found bulk out on endpoint %d\n", i);
if (num_bulk_out < MAX_NUM_PORTS) {
bulk_out_endpoint[num_bulk_out] = endpoint;
++num_bulk_out;
}
}
if (usb_endpoint_is_int_in(endpoint)) {
/* we found a interrupt in endpoint */
dev_dbg(ddev, "found interrupt in on endpoint %d\n", i);
if (num_interrupt_in < MAX_NUM_PORTS) {
interrupt_in_endpoint[num_interrupt_in] =
endpoint;
++num_interrupt_in;
}
}
if (usb_endpoint_is_int_out(endpoint)) {
/* we found an interrupt out endpoint */
dev_dbg(ddev, "found interrupt out on endpoint %d\n", i);
if (num_interrupt_out < MAX_NUM_PORTS) {
interrupt_out_endpoint[num_interrupt_out] =
endpoint;
++num_interrupt_out;
}
}
}
dev_info(ddev, "%s converter detected\n", type->description);
for (i = 0; i < max_endpoints; ++i)
{
port = kzalloc(sizeof(struct usb_serial_port), GFP_KERNEL);
tty_port_init(&port->port);
port->port.ops = &serial_port_ops;
port->serial = serial;
spin_lock_init(&port->lock);
/* Keep this for private driver use for the moment but
should probably go away */
INIT_WORK(&port->work, usb_serial_port_work);
serial->port[i] = port;
port->dev.parent = &interface->dev;
port->dev.driver = NULL;
port->dev.bus = &usb_serial_bus_type;
port->dev.release = &usb_serial_port_release;
port->dev.groups = usb_serial_port_groups;
device_initialize(&port->dev);
}
usb_set_intfdata(interface, serial);
/* register all of the individual ports with the driver core */
for (i = 0; i < num_ports; ++i)
{
port = serial->port[i];
dev_set_name(&port->dev, "ttyUSB%d", port->minor); //对应设备 /dev/ttyUSB0
dev_dbg(ddev, "registering %s\n", dev_name(&port->dev));
device_enable_async_suspend(&port->dev);
retval = device_add(&port->dev);
}
if (num_ports > 0)
usb_serial_console_init(serial->port[0]->minor);
对于 usb-skeletion.c 驱动 struct usb_driver skel_driver.probe = skel_probe :
static int skel_probe(struct usb_interface *interface,
const struct usb_device_id *id)->
struct usb_skel *dev = kzalloc(sizeof(*dev), GFP_KERNEL);
dev->udev = usb_get_dev(interface_to_usbdev(interface));
retval = usb_get_device_descriptor(dev->udev, USB_DT_DEVICE_SIZE);
iface_desc = interface->cur_altsetting;
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
/* we found a bulk in endpoint */
buffer_size = usb_endpoint_maxp(endpoint);
dev->bulk_in_size = buffer_size;
dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
dev->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);
dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);
}
usb_set_intfdata(interface, dev);
usb_register_dev(interface, &skel_class)->
init_usb_class();
intf->usb_dev = device_create(usb_class->class, &intf->dev,
MKDEV(USB_MAJOR, minor), class_driver,
"%s", temp);
dev_info(&interface->dev,
"USB Skeleton device now attached to USBSkel-%d",
interface->minor);