USB——usb host controller driver初始化 - awokezhou/LinuxPage GitHub Wiki

概述

本文对USB驱动中的HCD(主机控制器驱动,Host Controller Driver)初始化代码进行分析,梳理总结其中涉及到的重要数据结构和处理流程。HCD驱动代码根据USB标准分为OHCI、UHCI、EHCI和XHCI,本文以EHCI标准为主,进行分析,选取freescale驱动代码

初始化代码分析

HCD驱动是CPU上USB主机控制器的抽象,HCD驱动代码位于driver/usb/host路径下,入口为ehci_hcd.c

static int __init ehci_hcd_init(void)
{
	int retval = 0;

	set_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
	if (test_bit(USB_UHCI_LOADED, &usb_hcds_loaded) ||
			test_bit(USB_OHCI_LOADED, &usb_hcds_loaded))
		printk(KERN_WARNING "Warning! ehci_hcd should always be loaded"
				" before uhci_hcd and ohci_hcd, not after\n");

	pr_debug("%s: block sizes: qh %Zd qtd %Zd itd %Zd sitd %Zd\n",
		 hcd_name,
		 sizeof(struct ehci_qh), sizeof(struct ehci_qtd),
		 sizeof(struct ehci_itd), sizeof(struct ehci_sitd));

#ifdef DEBUG
	ehci_debug_root = debugfs_create_dir("ehci", NULL);
	if (!ehci_debug_root) {
		retval = -ENOENT;
		goto err_debug;
	}
#endif

#ifdef PLATFORM_DRIVER
	retval = platform_driver_register(&PLATFORM_DRIVER);
	if (retval < 0)
		goto clean0;
#endif

#ifdef PCI_DRIVER
	retval = pci_register_driver(&PCI_DRIVER);
	if (retval < 0)
		goto clean1;
#endif

#ifdef PS3_SYSTEM_BUS_DRIVER
	retval = ps3_ehci_driver_register(&PS3_SYSTEM_BUS_DRIVER);
	if (retval < 0)
		goto clean2;
#endif

#ifdef OF_PLATFORM_DRIVER
	retval = of_register_platform_driver(&OF_PLATFORM_DRIVER);
	if (retval < 0)
		goto clean3;
#endif
	return retval;

#ifdef OF_PLATFORM_DRIVER
	/* of_unregister_platform_driver(&OF_PLATFORM_DRIVER); */
clean3:
#endif
#ifdef PS3_SYSTEM_BUS_DRIVER
	ps3_ehci_driver_unregister(&PS3_SYSTEM_BUS_DRIVER);
clean2:
#endif
#ifdef PCI_DRIVER
	pci_unregister_driver(&PCI_DRIVER);
clean1:
#endif
#ifdef PLATFORM_DRIVER
	platform_driver_unregister(&PLATFORM_DRIVER);
clean0:
#endif
#ifdef DEBUG
	debugfs_remove(ehci_debug_root);
	ehci_debug_root = NULL;
err_debug:
#endif
	clear_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
	return retval;
}
module_init(ehci_hcd_init);

该函数其实并没有做什么实质性的工作,根据宏定义进入具体设备的驱动程序中,以freescale芯片来分析的话,会调用()向系统注册ehci_fsl_driver驱动,驱动内容如下

static struct platform_driver ehci_fsl_driver = {
	.probe = ehci_fsl_drv_probe,
	.remove = ehci_fsl_drv_remove,
	.shutdown = usb_hcd_platform_shutdown,
	.driver = {
		   .name = "fsl-ehci",
	},
};

其probe函数为ehci_fsl_probe,驱动名称为"fsl-ehci"。那么驱动注册了,怎么才会调用probe函数呢?当然是要有设备注册。那么设备是什么时候注册的呢?主机控制器设备属于CPU片上资源,这些片上资源一般都是在内核启动的时候注册到系统的,在arch/powerpc/sysdev/fsl_soc.c文件中,对设备进行了注册操作

usb_dev_mph =
    platform_device_register_simple("fsl-ehci", i, r, 2);
    if (IS_ERR(usb_dev_mph)) {
        ret = PTR_ERR(usb_dev_mph);
	    goto err;
    }

代码中通过调用platform_device_register_simple()向系统中注册名为fsl-ehci的设备。现在就清楚了,不管是设备先注册还是驱动先注册,现在设备和驱动刚好对应起来了,所以ehci_fsl_drv_probe会马上调用起来。

在分析echi_fsl_drv_probe之前,我们先来分析一下设备结构以及内容。fsl_soc.c文件中通过调用fsl_usb_of_init()函数来注册USB主机控制器设备,其设备信息和资源从哪里来的呢?看代码

	for_each_compatible_node(np, NULL, "fsl-usb2-mph") {
		struct resource r[2];
		struct fsl_usb2_platform_data usb_data;
		const unsigned char *prop = NULL;

		memset(&r, 0, sizeof(r));
		memset(&usb_data, 0, sizeof(usb_data));

		ret = of_address_to_resource(np, 0, &r[0]);
		if (ret)
			goto err;

		of_irq_to_resource(np, 0, &r[1]);

		usb_dev_mph =
		    platform_device_register_simple("fsl-ehci", i, r, 2);
		if (IS_ERR(usb_dev_mph)) {
			ret = PTR_ERR(usb_dev_mph);
			goto err;
		}

这里通过调用for_each_compatible_node(),其实要涉及到linux设备树的概念,这里不展开说明。简单说就是通过平台文件里的一个xxx.dts文件中读取名字为fsl-usb2-mph的设备树结构,从中拿到硬件资源和信息,所以我们主要分析清楚这些资源和信息就行。从arch/powerpc/boot/dts/mpc834x_mds.dts文件中找到这样一段描述

		usb@22000 {
			compatible = "fsl-usb2-mph";
			reg = <0x22000 0x1000>;
			#address-cells = <1>;
			#size-cells = <0>;
			interrupt-parent = <&ipic>;
			interrupts = <39 0x8>;
			phy_type = "ulpi";
			port1;
		};

可以看到寄存器的初始地址为0x22000,长度为1000,中断号为39,有一个port。

HCD probe

下面来分析ehci_fsl_drv_probe()函数,里面返回的是一个usb_hcd_fsl_probe()函数,传递了pdev和一个ehci_fsl_hc_driver

static int ehci_fsl_drv_probe(struct platform_device *pdev)
{
	if (usb_disabled())
		return -ENODEV;

	/* FIXME we only want one one probe() not two */
	return usb_hcd_fsl_probe(&ehci_fsl_hc_driver, pdev);
}

pdev就是前面分析的向系统注册的主机控制器设备“fsl-ehci”,但是ehci_fsl_hc_driver又是什么呢?

首先,它的类型是struct hc_driver,然后它是一个static类型的静态变量,其内容如代码

static const struct hc_driver ehci_fsl_hc_driver = {
	.description = hcd_name,
	.product_desc = "Freescale On-Chip EHCI Host Controller",
	.hcd_priv_size = sizeof(struct ehci_hcd),

	/*
	 * generic hardware linkage
	 */
	.irq = ehci_irq,
	.flags = HCD_USB2,

	/*
	 * basic lifecycle operations
	 */
	.reset = ehci_fsl_setup,
	.start = ehci_run,
	.stop = ehci_stop,
	.shutdown = ehci_shutdown,

	/*
	 * managing i/o requests and associated device resources
	 */
	.urb_enqueue = ehci_urb_enqueue,
	.urb_dequeue = ehci_urb_dequeue,
	.endpoint_disable = ehci_endpoint_disable,

	/*
	 * scheduling support
	 */
	.get_frame_number = ehci_get_frame,

	/*
	 * root hub support
	 */
	.hub_status_data = ehci_hub_status_data,
	.hub_control = ehci_hub_control,
	.bus_suspend = ehci_bus_suspend,
	.bus_resume = ehci_bus_resume,
	.relinquish_port = ehci_relinquish_port,
	.port_handed_over = ehci_port_handed_over,
};

这个ehci_fsl_hc_driver很重要,主要是挂接了很多函数,其中尤其是irq、start、urb_enqueue、urb_dequeue、hub_status_data和hub_control尤为重要,理解清楚什么时候什么情况下会调用到这些函数,以及这些函数主要完成什么操作,基本上就把USB驱动搞清楚了。当然,下面的任务就是分析这些内容。

先抛开这些具体函数接口,回头分析一下usb_hcd_fsl_probe()这个函数。它传入了两个参数,一个是ehci_fsl_hc_driver,另一个是主机控制器设备。

int usb_hcd_fsl_probe(const struct hc_driver *driver,
		      struct platform_device *pdev)
{
	struct fsl_usb2_platform_data *pdata;
	struct usb_hcd *hcd;
	struct resource *res;
	int irq;
	int retval;
	unsigned int temp;

	pr_debug("initializing FSL-SOC USB Controller\n");

	/* Need platform data for setup */
	pdata = (struct fsl_usb2_platform_data *)pdev->dev.platform_data;
	if (!pdata) {
		dev_err(&pdev->dev,
			"No platform data for %s.\n", dev_name(&pdev->dev));
		return -ENODEV;
	}

	/*
	 * This is a host mode driver, verify that we're supposed to be
	 * in host mode.
	 */
	if (!((pdata->operating_mode == FSL_USB2_DR_HOST) ||
	      (pdata->operating_mode == FSL_USB2_MPH_HOST) ||
	      (pdata->operating_mode == FSL_USB2_DR_OTG))) {
		dev_err(&pdev->dev,
			"Non Host Mode configured for %s. Wrong driver linked.\n",
			dev_name(&pdev->dev));
		return -ENODEV;
	}

	res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
	if (!res) {
		dev_err(&pdev->dev,
			"Found HC with no IRQ. Check %s setup!\n",
			dev_name(&pdev->dev));
		return -ENODEV;
	}
	irq = res->start;

	hcd = usb_create_hcd(driver, &pdev->dev, dev_name(&pdev->dev));
	if (!hcd) {
		retval = -ENOMEM;
		goto err1;
	}

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res) {
		dev_err(&pdev->dev,
			"Found HC with no register addr. Check %s setup!\n",
			dev_name(&pdev->dev));
		retval = -ENODEV;
		goto err2;
	}
	hcd->rsrc_start = res->start;
	hcd->rsrc_len = res->end - res->start + 1;
	if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len,
				driver->description)) {
		dev_dbg(&pdev->dev, "controller already in use\n");
		retval = -EBUSY;
		goto err2;
	}
	hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len);

	if (hcd->regs == NULL) {
		dev_dbg(&pdev->dev, "error mapping memory\n");
		retval = -EFAULT;
		goto err3;
	}

	/* Enable USB controller */
	temp = in_be32(hcd->regs + 0x500);
	out_be32(hcd->regs + 0x500, temp | 0x4);

	/* Set to Host mode */
	temp = in_le32(hcd->regs + 0x1a8);
	out_le32(hcd->regs + 0x1a8, temp | 0x3);

	retval = usb_add_hcd(hcd, irq, IRQF_DISABLED | IRQF_SHARED);
	if (retval != 0)
		goto err4;
	return retval;

      err4:
	iounmap(hcd->regs);
      err3:
	release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
      err2:
	usb_put_hcd(hcd);
      err1:
	dev_err(&pdev->dev, "init %s fail, %d\n", dev_name(&pdev->dev), retval);
	return retval;
}

这个函数并不复杂,通过调用platform_get_resource()获取设备的中断号和寄存器起始地址。调用usb_create_hcd()创建了一个struct usb_hcd类型的hcd,也就是主机控制器数据结构。然后调用ioremap()完成了寄存器的I/O映射。设置了两个寄存器,使能USB功能,并设备为主机模式。最后调用了usb_add_hcd()。其中的重点在usb_create_hcd()和usb_add_hcd()这两个函数上。

创建hcd

创建hcd代码为

struct usb_hcd *usb_create_hcd (const struct hc_driver *driver,
		struct device *dev, const char *bus_name)
{
	struct usb_hcd *hcd;

	hcd = kzalloc(sizeof(*hcd) + driver->hcd_priv_size, GFP_KERNEL);
	if (!hcd) {
		dev_dbg (dev, "hcd alloc failed\n");
		return NULL;
	}
	dev_set_drvdata(dev, hcd);
	kref_init(&hcd->kref);

	usb_bus_init(&hcd->self);
	hcd->self.controller = dev;
	hcd->self.bus_name = bus_name;
	hcd->self.uses_dma = (dev->dma_mask != NULL);

	init_timer(&hcd->rh_timer);
	hcd->rh_timer.function = rh_timer_func;
	hcd->rh_timer.data = (unsigned long) hcd;
#ifdef CONFIG_PM
	INIT_WORK(&hcd->wakeup_work, hcd_resume_work);
#endif

	hcd->driver = driver;
	hcd->product_desc = (driver->product_desc) ? driver->product_desc :
			"USB Host Controller";
	return hcd;
}

首先通过kzalloc()为hcd分配内存空间,这里有一点需要注意,分配的大小并不是usb_hcd结构体的大小,而是多分配了一个driver->hcd_priv_size,这部分多大呢?前面ehci_fsl_hc_driver的内容中写的很明白

.hcd_priv_size = sizeof(struct ehci_hcd)

也就是分配了一个sizeof(struct usb_hcd) + sizeof(ehci_hcd)的空间,其实在驱动编写中有很多这种写法,一部分是通用结构体,另一部分是私有结构体,对于usb core来说,usb_hcd是通用的,其中的一些属性和成员在整个USB子系统的处理和调度中都可能会用到的,而另一部分私有空间ehci_hcd仅仅在EHCI标准的USB处理中才会使用到。

调用usb_bus_init()对hcd的self成员进行了初始化,还对self的一些参数进行了赋值。然后创建了一个定时器任务rh_timer_func,但是还没有触发。

这部分涉及到一些数据结构,来梳理一下。

  • hcd_driver,有一个static的全局结构体ehci_fsl_hc_driver,上面挂接了很多重要的处理函数

  • usb_hcd,这是描述一个主机控制器的通用型数据结构

  • ehci_hcd,这是用于描述一个EHCI接口标准主机控制器的私有型数据结构

从数据结构的角度来看,hcd的创建都做了什么呢?分配了一个内存空间,包括一个usb_hcd和ehci_hcd,这个空间的指针为hcd,给hcd的self成员赋值,如下图

hcd通过指针连接的方式把ehci_fsl_hc_driver的所有操作函数关联起来

hcd添加

usb_add_hcd()这个名称其实有些误导,该函数里面执行的过程很重要,不仅仅是一个添加操作,代码如下

int usb_add_hcd(struct usb_hcd *hcd,
		unsigned int irqnum, unsigned long irqflags)
{
	int retval;
	struct usb_device *rhdev;

	dev_info(hcd->self.controller, "%s\n", hcd->product_desc);

	hcd->authorized_default = hcd->wireless? 0 : 1;
	set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);

	/* HC is in reset state, but accessible.  Now do the one-time init,
	 * bottom up so that hcds can customize the root hubs before khubd
	 * starts talking to them.  (Note, bus id is assigned early too.)
	 */
	if ((retval = hcd_buffer_create(hcd)) != 0) {
		dev_dbg(hcd->self.controller, "pool alloc failed\n");
		return retval;
	}

	if ((retval = usb_register_bus(&hcd->self)) < 0)
		goto err_register_bus;

	if ((rhdev = usb_alloc_dev(NULL, &hcd->self, 0)) == NULL) {
		dev_err(hcd->self.controller, "unable to allocate root hub\n");
		retval = -ENOMEM;
		goto err_allocate_root_hub;
	}
	rhdev->speed = (hcd->driver->flags & HCD_USB2) ? USB_SPEED_HIGH :
			USB_SPEED_FULL;
	hcd->self.root_hub = rhdev;

	/* wakeup flag init defaults to "everything works" for root hubs,
	 * but drivers can override it in reset() if needed, along with
	 * recording the overall controller's system wakeup capability.
	 */
	device_init_wakeup(&rhdev->dev, 1);

	/* "reset" is misnamed; its role is now one-time init. the controller
	 * should already have been reset (and boot firmware kicked off etc).
	 */
	if (hcd->driver->reset && (retval = hcd->driver->reset(hcd)) < 0) {
		dev_err(hcd->self.controller, "can't setup\n");
		goto err_hcd_driver_setup;
	}

	/* NOTE: root hub and controller capabilities may not be the same */
	if (device_can_wakeup(hcd->self.controller)
			&& device_can_wakeup(&hcd->self.root_hub->dev))
		dev_dbg(hcd->self.controller, "supports USB remote wakeup\n");

	/* enable irqs just before we start the controller */
	if (hcd->driver->irq) {

		/* IRQF_DISABLED doesn't work as advertised when used together
		 * with IRQF_SHARED. As usb_hcd_irq() will always disable
		 * interrupts we can remove it here.
		 */
		if (irqflags & IRQF_SHARED)
			irqflags &= ~IRQF_DISABLED;

		snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
				hcd->driver->description, hcd->self.busnum);
		if ((retval = request_irq(irqnum, &usb_hcd_irq, irqflags,
				hcd->irq_descr, hcd)) != 0) {
			dev_err(hcd->self.controller,
					"request interrupt %d failed\n", irqnum);
			goto err_request_irq;
		}
		hcd->irq = irqnum;
		dev_info(hcd->self.controller, "irq %d, %s 0x%08llx\n", irqnum,
				(hcd->driver->flags & HCD_MEMORY) ?
					"io mem" : "io base",
					(unsigned long long)hcd->rsrc_start);
	} else {
		hcd->irq = -1;
		if (hcd->rsrc_start)
			dev_info(hcd->self.controller, "%s 0x%08llx\n",
					(hcd->driver->flags & HCD_MEMORY) ?
					"io mem" : "io base",
					(unsigned long long)hcd->rsrc_start);
	}

	if ((retval = hcd->driver->start(hcd)) < 0) {
		dev_err(hcd->self.controller, "startup error %d\n", retval);
		goto err_hcd_driver_start;
	}

	/* starting here, usbcore will pay attention to this root hub */
	rhdev->bus_mA = min(500u, hcd->power_budget);
	if ((retval = register_root_hub(hcd)) != 0)
		goto err_register_root_hub;

	retval = sysfs_create_group(&rhdev->dev.kobj, &usb_bus_attr_group);
	if (retval < 0) {
		printk(KERN_ERR "Cannot register USB bus sysfs attributes: %d\n",
		       retval);
		goto error_create_attr_group;
	}
	if (hcd->uses_new_polling && hcd->poll_rh)
		usb_hcd_poll_rh_status(hcd);
	return retval;

error_create_attr_group:
	mutex_lock(&usb_bus_list_lock);
	usb_disconnect(&hcd->self.root_hub);
	mutex_unlock(&usb_bus_list_lock);
err_register_root_hub:
	hcd->driver->stop(hcd);
err_hcd_driver_start:
	if (hcd->irq >= 0)
		free_irq(irqnum, hcd);
err_request_irq:
err_hcd_driver_setup:
	hcd->self.root_hub = NULL;
	usb_put_dev(rhdev);
err_allocate_root_hub:
	usb_deregister_bus(&hcd->self);
err_register_bus:
	hcd_buffer_destroy(hcd);
	return retval;
} 

第一件事情就是调用hcd_buffer_create()分配一些buffer

int hcd_buffer_create(struct usb_hcd *hcd)
{
	char		name[16];
	int 		i, size;

	if (!hcd->self.controller->dma_mask &&
	    !(hcd->driver->flags & HCD_LOCAL_MEM))
		return 0;

	for (i = 0; i < HCD_BUFFER_POOLS; i++) {
		size = pool_max[i];
		if (!size)
			continue;
		snprintf(name, sizeof name, "buffer-%d", size);
		hcd->pool[i] = dma_pool_create(name, hcd->self.controller,
				size, size, 0);
		if (!hcd->pool [i]) {
			hcd_buffer_destroy(hcd);
			return -ENOMEM;
		}
	}
	return 0;
}

hcd有一个dma池结构,

#define HCD_BUFFER_POOLS	4
	struct dma_pool		*pool [HCD_BUFFER_POOLS];

pool是一个由4个指针构成的dma池数组,分配过程是循环为这个4个dma池分配dma空间,而每个空间的大小又是由pool_max[]数组决定的,

static const size_t	pool_max [HCD_BUFFER_POOLS] = {
	/* platforms without dma-friendly caches might need to
	 * prevent cacheline sharing...
	 */
	32,
	128,
	512,
	PAGE_SIZE / 2
	/* bigger --> allocate pages */
};

pool_max数组由四个值组成,32、128、512、PAGE_SIZE/2,所以4个dma池大小分别为32、128、512和PAGE_SIZE

分配完了dma池之后,调用usb_register_bus()对hcd的self做了注册,

static int usb_register_bus(struct usb_bus *bus)
{
	int result = -E2BIG;
	int busnum;

	mutex_lock(&usb_bus_list_lock);
	busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
	if (busnum >= USB_MAXBUS) {
		printk (KERN_ERR "%s: too many buses\n", usbcore_name);
		goto error_find_busnum;
	}
	set_bit (busnum, busmap.busmap);
	bus->busnum = busnum;

	bus->dev = device_create_drvdata(usb_host_class, bus->controller,
					 MKDEV(0, 0), bus,
					 "usb_host%d", busnum);
	result = PTR_ERR(bus->dev);
	if (IS_ERR(bus->dev))
		goto error_create_class_dev;

	/* Add it to the local list of buses */
	list_add (&bus->bus_list, &usb_bus_list);
	mutex_unlock(&usb_bus_list_lock);

	usb_notify_add_bus(bus);

	dev_info (bus->controller, "new USB bus registered, assigned bus "
		  "number %d\n", bus->busnum);
	return 0;

error_create_class_dev:
	clear_bit(busnum, busmap.busmap);
error_find_busnum:
	mutex_unlock(&usb_bus_list_lock);
	return result;
}

其实就是做了一些私有数据创建,然后把self挂到usb_bus_list这个链表上

接下来调用usb_alloc_dev()进行了一个usb_device结构的分配,这里的操作非常重要,这个操作就是在为root hub根集线器做内存分配和一些初始化。

struct usb_device *usb_alloc_dev(struct usb_device *parent,
				 struct usb_bus *bus, unsigned port1)
{
	struct usb_device *dev;
	struct usb_hcd *usb_hcd = container_of(bus, struct usb_hcd, self);
	unsigned root_hub = 0;

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (!dev)
		return NULL;

	if (!usb_get_hcd(bus_to_hcd(bus))) {
		kfree(dev);
		return NULL;
	}

	device_initialize(&dev->dev);
	dev->dev.bus = &usb_bus_type;
	dev->dev.type = &usb_device_type;
	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;
	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);
	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->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);
		else
			snprintf(dev->devpath, sizeof dev->devpath,
				"%s.%d", parent->devpath, port1);

		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);

#ifdef	CONFIG_PM
	mutex_init(&dev->pm_mutex);
	INIT_DELAYED_WORK(&dev->autosuspend, usb_autosuspend_work);
	dev->autosuspend_delay = usb_autosuspend_delay * HZ;
	dev->connect_time = jiffies;
	dev->active_duration = -jiffies;
#endif
	if (root_hub)	/* Root hub always ok [and always wired] */
		dev->authorized = 1;
	else {
		dev->authorized = usb_hcd->authorized_default;
		dev->wusb = usb_bus_is_wusb(bus)? 1 : 0;
	}
	return dev;
}

首先调用kzalloc()为根集线器分配内存空间,然后调用device_initialize()对根集线器的通用设备结构dev进行初始化,指定其总线类型和设备类型,以及dma功能,将根集线器的状态设置为未接入。然后对根集线器的端点进行了初始化,下面重点分析。

根集线器端点初始化

分析代码之前,先简单介绍一下端点的概念。在USB标准规定中,端点是用于进行USB通信的基本单位,像管道一样,端点有两个方向,一个是由主机向设备(OUT),一个是由设备向主机。端点的种类有4种,分别为控制(controller)、中断(interrupt)、块(bluk)和等时(isochronous)。内核中使用struct usb_host_endpoint结构来描述一个端点,其中包含一个struct usb_endpoint_descriptor结构用来描述端点的实际信息,如端点地址、方向、类型、最大包大小和间隔,如下图

又因为每个设备默认情况下都必须有一个控制端点“endpoint0”,所以在根集线器的数据结构0号端点是一个结构体实例,而其他端点只有指针

	struct usb_host_endpoint ep0;

	struct device dev;

	struct usb_device_descriptor descriptor;
	struct usb_host_config *config;

	struct usb_host_config *actconfig;
	struct usb_host_endpoint *ep_in[16];
	struct usb_host_endpoint *ep_out[16];

这里的ep0就是0号端点,并且初始化过程主要就是对ep0进行初始化。代码中首先初始化了ep0中的一个链表urb_list,这个urb_list和数据传输有关,现在先不做分析。指定了ep0的长度和类型,类型为中断。然后调用了usb_enable_endpoint()

void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
{
	int epnum = usb_endpoint_num(&ep->desc);
	int is_out = usb_endpoint_dir_out(&ep->desc);
	int is_control = usb_endpoint_xfer_control(&ep->desc);

	if (is_out || is_control) {
		usb_settoggle(dev, epnum, 1, 0);
		dev->ep_out[epnum] = ep;
	}
	if (!is_out || is_control) {
		usb_settoggle(dev, epnum, 0, 0);
		dev->ep_in[epnum] = ep;
	}
	ep->enabled = 1;
}

首先调用usb_endpoint_num()获取端点号,这里显然是0号端点,然后调用usb_endpoint_dir_out()获取端点方向,因为bEndpointAddress现在是全0,所以方向为OUT,调用usb_endpoint_xfer_control()判断端点是否为控制端点,因为bmAttributes也为全0,所以是控制端点。如果是方向是OUT或者是控制端点会走第一个if,如果方向不是OUT或者是控制端点会走第二个if,所以这里两个if都会执行。

两个if中都有一个usb_settoggle()操作,

#define usb_settoggle(dev, ep, out, bit) \
		((dev)->toggle[out] = ((dev)->toggle[out] & ~(1 << (ep))) | \
		 ((bit) << (ep)))

其实就是为ep0的toggle[2]中的两个成员赋值。然后将dev->ep_out[0]和dev->ep_in[0]这两个指针指向ep0。ep_in和ep_out是usb_device中的输入和输入端点的指针,各16个,说明usb设备最多有16个输入输出端点。

下一步判断了函数传入的参数parent是否存在,这里函数传入的parent参数为NULL,所以不存在。因为是根集线器,所以不存在父设备。又有一些结构体指针的关联,还是用图来说明

简单来说就是将根集线器数据结构usb_device与主机控制器数据结构usb_hcd进行了关联,怎么关联的呢?将根集线器的通用设备成员device dev的父对象设置为usb总线的控制器,也就是主机控制器fsl-ehci,然后将根集线器的总线指针usb_bus *bus指向主机控制器的总线成员self。

至此,usb_alloc_dev()函数执行完成,已经分配好一个根集线器数据结构,并进行了一些初始化工作,但是到目前为止,根集线器设备仍然没有被注册到系统,所以其probe函数仍然没有被调用。

接下来调用了hcd驱动的reset函数,向系统注册了usb_hcd_irq()作为主机控制器的中断例程,调用hcd的start函数。调用register_root_hub()向系统注册根集线器,调用usb_hcd_poll_rh_status()启动轮询端口状态。这些部分内容比较多,关系比较复杂,我们先上一张图从主机控制和根集线器两条线来看整个过程和它们之间的关系

后文分别分析register_root_hub()、hcd的reset和start、hcd的中断函数usb_hcd_irq()以及定时器函数rh_timer_func()主要作用。

⚠️ **GitHub.com Fallback** ⚠️