Linux USB 3.0驅動分析(六)——USB主機控制器HCD分析


一.USB主機控制器HCD(Host Controller Device)簡介

USB的主機控制器(HCD),出現了多種不同的類型,即OHCI和UHCI,EHCI,和xHCI,不同USB控制器類型OHCI,UHCI,EHCI,xHCI的區別和聯系

USB采用樹形拓撲結構,主機側和設備側的USB控制器分別稱為主機控制器(Host Controller)和USB設備控制器(UDC),每條總線上只有一個主機控制器,負責協調主機和設備間的通信,設備不能主動向主機發送任何消息。


1.usb phy





二.USB主機控制器驅動

1.分析的usb主機控制器硬件情況

USB Host帶有Root Hub,第一個USB設備是一個根集線器(Root_hub)它控制連接到其上的整個USB總線。



鑒於現在大部分設備都已經支持usb3.0, 我們來分析xHCI主機控制器驅動代碼。

我手里的設備是imx8mq,用的DWC3 USB控制芯片

USB設備分為HOST(主設備)和SLAVE(從設備),只有當一台HOST與一台SLAVE連接時才能實現數據的傳輸,而OTG設備既能充當HOST,亦能充當SLAVE,也即DRD(Dual-role-devices).我現在只分析當主設備的情況。

2. usb主機控制器驅動分析
代碼位置: drivers\usb\dwc3\Core.c
首先是platform驅動的加載, 會通過of_dwc3_match配置dts
static struct platform_driver dwc3_driver = {
    .probe        = dwc3_probe,
    .remove        = dwc3_remove,
    .driver        = {
        .name    = "dwc3",
        .of_match_table    = of_match_ptr(of_dwc3_match),
        .acpi_match_table = ACPI_PTR(dwc3_acpi_match),
        .pm    = &dwc3_dev_pm_ops,
    },
};
module_platform_driver(dwc3_driver);
匹配成功后,會進入dwc3_probe函數。主要進行一些資源的分配,硬件的初始化等,這里化簡一下
static int dwc3_probe(struct platform_device *pdev)
{
    dwc3_get_properties(dwc); //獲取一些屬性,主要是讀取dts里面的配置,比如dr_mode可以配置為otg、host或者peripheral。
    dwc3_cache_hwparams(dwc); //讀取一些硬件參數

    ret = dwc3_core_init(dwc); //這里面是最重要的初始化,一些硬件初始化,包括USB PHY
    if (ret) {
        if (ret != -EPROBE_DEFER)
            dev_err(dev, "failed to initialize core: %d\n", ret);
        goto err4;
    }

    ret = dwc3_core_init_mode(dwc); //根據不同的模式進行初始化
    if (ret)
        goto err5;

    dwc3_debugfs_init(dwc); //調試節點,/sys/kernel/debug/38100000.usb/
}
dwc3_core_init_mode里面會進行不同模式的初始化,包括otg、host或者peripheral。
static int dwc3_core_init_mode(struct dwc3 *dwc)
{
    switch (dwc->dr_mode) {
    case USB_DR_MODE_PERIPHERAL: //外圍模式,也就是當從設備
        dwc3_set_prtcap(dwc, DWC3_GCTL_PRTCAP_DEVICE);
        if (dwc->usb2_phy)
            otg_set_vbus(dwc->usb2_phy->otg, false);
        phy_set_mode(dwc->usb2_generic_phy, PHY_MODE_USB_DEVICE);
        phy_set_mode(dwc->usb3_generic_phy, PHY_MODE_USB_DEVICE);
        ret = dwc3_gadget_init(dwc);
        if (ret) {
            if (ret != -EPROBE_DEFER)
                dev_err(dev, "failed to initialize gadget\n");
            return ret;
        }
        break;
    case USB_DR_MODE_HOST: //主機模式,也就是當主設備
        dwc3_set_prtcap(dwc, DWC3_GCTL_PRTCAP_HOST);
        if (dwc->usb2_phy)
            otg_set_vbus(dwc->usb2_phy->otg, true);
        phy_set_mode(dwc->usb2_generic_phy, PHY_MODE_USB_HOST);
        phy_set_mode(dwc->usb3_generic_phy, PHY_MODE_USB_HOST);
        ret = dwc3_host_init(dwc);
        if (ret) {
            if (ret != -EPROBE_DEFER)
                dev_err(dev, "failed to initialize host\n");
            return ret;
        }
        break;
    case USB_DR_MODE_OTG: //otg模式,OTG控制器可以做host,也能做device
        INIT_WORK(&dwc->drd_work, __dwc3_set_mode);
        ret = dwc3_drd_init(dwc);
        if (ret) {
            if (ret != -EPROBE_DEFER)
                dev_err(dev, "failed to initialize dual-role\n");
            return ret;
        }
        break;
    default:
        dev_err(dev, "Unsupported mode of operation %d\n", dwc->dr_mode);
        return -EINVAL;
    }
    return 0;
}
只做從設備的情況比較少,只做host或者otg的情況比較多。
我們先來分析當做host的情況
int dwc3_host_init(struct dwc3 *dwc)
{
    xhci = platform_device_alloc("xhci-hcd", PLATFORM_DEVID_AUTO); //創建一個平台設備,名字是xhci-hcd
    if (!xhci) {
        dev_err(dwc->dev, "couldn't allocate xHCI device\n");
        return -ENOMEM;
    }

    ret = platform_device_add_resources(xhci, dwc->xhci_resources,
                        DWC3_XHCI_RESOURCES_NUM); //添加資源到這個平台設備
    if (ret) {
        dev_err(dwc->dev, "couldn't add resources to xHCI device\n");
        goto err;
    }

    /**
     * WORKAROUND: dwc3 revisions <=3.00a have a limitation
     * where Port Disable command doesn't work.
     *
     * The suggested workaround is that we avoid Port Disable
     * completely.
     *
     * This following flag tells XHCI to do just that.
     */
    if (dwc->revision <= DWC3_REVISION_300A)
        props[prop_idx++].name = "quirk-broken-port-ped";

    if (prop_idx) {
        ret = platform_device_add_properties(xhci, props); //向平台設備添加內置屬性
        if (ret) {
            dev_err(dwc->dev, "failed to add properties to xHCI\n");
            goto err;
        }
    }

    ret = platform_device_add(xhci); //把這個平台設備加入到系統,這樣就可以與平台驅動匹配了
    if (ret) {
        dev_err(dwc->dev, "failed to register xHCI device\n");
        goto err;
    }
}


3.xHCI driver分析

前面已經分析到注冊平台設備,我們這里分析xHCI驅動

usb/host/xhci-plat.c

static struct platform_driver usb_xhci_driver = {
    .probe    = xhci_plat_probe, //后面會調用
    .remove    = xhci_plat_remove,
    .driver    = {
        .name = "xhci-hcd",
        .pm = &xhci_plat_pm_ops,
        .of_match_table = of_match_ptr(usb_xhci_of_match),
        .acpi_match_table = ACPI_PTR(usb_xhci_acpi_match),
    },
};

static int __init xhci_plat_init(void)
{
    xhci_init_driver(&xhci_plat_hc_driver, &xhci_plat_overrides);  //這里會初始化xhci_plat_hc_driver
    return platform_driver_register(&usb_xhci_driver); //這里注冊之后就會,根據name="xhci-hcd"匹配到之前的platform device后,執行xhci_plat_probe
}

我們先分析xhci_init_driver函數,看看做了什么

static const struct hc_driver xhci_hc_driver = { //大部分事情都是這里在干了
    .description =        "xhci-hcd",
    .product_desc =        "xHCI Host Controller",
    .hcd_priv_size =    sizeof(struct xhci_hcd),
    /*
     * generic hardware linkage
     */
    .irq =            xhci_irq,
    .flags =        HCD_MEMORY | HCD_DMA | HCD_USB3 | HCD_SHARED,
    /*
     * basic lifecycle operations
     */
    .reset =        NULL, /* set in xhci_init_driver() */
    .start =        xhci_run, //This function is called by the USB core when the HC driver is added
    .stop =            xhci_stop,
    .shutdown =        xhci_shutdown,
    /*
     * managing i/o requests and associated device resources
     */
    .map_urb_for_dma =      xhci_map_urb_for_dma,
    .urb_enqueue =        xhci_urb_enqueue,
    .urb_dequeue =        xhci_urb_dequeue,
    .alloc_dev =        xhci_alloc_dev,
    .free_dev =        xhci_free_dev,
    .alloc_streams =    xhci_alloc_streams,
    .free_streams =        xhci_free_streams,
    .add_endpoint =        xhci_add_endpoint,
    .drop_endpoint =    xhci_drop_endpoint,
    .endpoint_disable =    xhci_endpoint_disable,
    .endpoint_reset =    xhci_endpoint_reset,
    .check_bandwidth =    xhci_check_bandwidth,
    .reset_bandwidth =    xhci_reset_bandwidth,
    .address_device =    xhci_address_device,
    .enable_device =    xhci_enable_device,
    .update_hub_device =    xhci_update_hub_device,
    .reset_device =        xhci_discover_or_reset_device,
    /*
     * scheduling support
     */
    .get_frame_number =    xhci_get_frame,
    /*
     * root hub support
     */
    .hub_control =        xhci_hub_control,
    .hub_status_data =    xhci_hub_status_data,
    .bus_suspend =        xhci_bus_suspend,
    .bus_resume =        xhci_bus_resume,
    .get_resuming_ports =    xhci_get_resuming_ports,
    /*
     * call back when device connected and addressed
     */
    .update_device =        xhci_update_device,
    .set_usb2_hw_lpm =    xhci_set_usb2_hardware_lpm,
    .enable_usb3_lpm_timeout =    xhci_enable_usb3_lpm_timeout,
    .disable_usb3_lpm_timeout =    xhci_disable_usb3_lpm_timeout,
    .find_raw_port_number =    xhci_find_raw_port_number,
    .clear_tt_buffer_complete = xhci_clear_tt_buffer_complete,
    .submit_single_step_set_feature    = xhci_submit_single_step_set_feature,
};

void xhci_init_driver(struct hc_driver *drv,
              const struct xhci_driver_overrides *over)
{
    BUG_ON(!over);
    /* Copy the generic table to drv then apply the overrides */
    *drv = xhci_hc_driver; //賦值給drv
    if (over) {
        drv->hcd_priv_size += over->extra_priv_size;
        if (over->reset)
            drv->reset = over->reset;
        if (over->start)
            drv->start = over->start;
        if (over->bus_suspend)
            drv->bus_suspend = over->bus_suspend;
    }
}

我們現在分析一下xhci_plat_probe,主要是創建和注冊hcd

static int xhci_plat_probe(struct platform_device *pdev)
{
    hcd = __usb_create_hcd(driver, sysdev, &pdev->dev,
                   dev_name(&pdev->dev), NULL); //創建一個usb_hcd結構體,並進行一些賦值操作, usb2.0(main_hcd)
    if (!hcd) {
        ret = -ENOMEM;
        goto disable_runtime;
    }

    xhci = hcd_to_xhci(hcd);
    xhci->main_hcd = hcd;
    xhci->shared_hcd = __usb_create_hcd(driver, sysdev, &pdev->dev,
            dev_name(&pdev->dev), hcd); //對應usb3.0及以上(shared_hcd)。

    hcd->usb_phy = devm_usb_get_phy_by_phandle(sysdev, "usb-phy", 0);
    if (IS_ERR(hcd->usb_phy)) {
        ret = PTR_ERR(hcd->usb_phy);
        if (ret == -EPROBE_DEFER)
            goto put_usb3_hcd;
        hcd->usb_phy = NULL;
    } else {
        ret = usb_phy_init(hcd->usb_phy); //這里調用usb phy的初始化函數。imx8mq用的imx8mq_usb_phy_init。usb phy驅動比較簡單,我就不分析了
        if (ret)
            goto put_usb3_hcd;
    }

    ret = usb_add_hcd(hcd, irq, IRQF_SHARED); //完成通用HCD結構初始化和注冊,這里是usb2.0
    if (ret)
        goto disable_usb_phy;

    ret = usb_add_hcd(xhci->shared_hcd, irq, IRQF_SHARED); //完成通用HCD結構初始化和注冊,這里是usb3.0
    if (ret)
        goto dealloc_usb2_hcd;
}

我們來看看usb_add_hcd里面做了什么?主要是注冊分配roothub, 還有初始化usb phy,把usb總線加入到系統.

int usb_add_hcd(struct usb_hcd *hcd,
        unsigned int irqnum, unsigned long irqflags)
{
    if (!hcd->skip_phy_initialization && usb_hcd_is_primary_hcd(hcd)) {
        hcd->phy_roothub = usb_phy_roothub_alloc(hcd->self.sysdev); //分配一個usb_phy_roothub結構體,並加入到roothub_entry->list鏈表
        if (IS_ERR(hcd->phy_roothub))
            return PTR_ERR(hcd->phy_roothub);
        retval = usb_phy_roothub_init(hcd->phy_roothub); //初始化roothub,主要是調用imx8m_usb_phy_init
        if (retval)
            return retval;
        retval = usb_phy_roothub_set_mode(hcd->phy_roothub,
                          PHY_MODE_USB_HOST_SS); //看起來是什么都沒有做
        if (retval)
            retval = usb_phy_roothub_set_mode(hcd->phy_roothub,
                              PHY_MODE_USB_HOST); //看起來是什么都沒有做
        if (retval)
            goto err_usb_phy_roothub_power_on;
        retval = usb_phy_roothub_power_on(hcd->phy_roothub); //給roothub上電,調用imx8mq_phy_power_on
        if (retval)
            goto err_usb_phy_roothub_power_on;
    }
    /*此功能允許您控制在一個系統中是否使用一個USB設備。這個特性將允許您實現鎖定USB設備,完全由用戶空間控制。
	到目前為止,當一個USB設備連接后,經過配置,它會立即暴露給給用戶。使用這個特性時,只有root用戶授權后的設備才有可能被使用。*/
    switch (authorized_default) {
    case USB_AUTHORIZE_NONE:
        hcd->dev_policy = USB_DEVICE_AUTHORIZE_NONE;
        break;
    case USB_AUTHORIZE_ALL:
        hcd->dev_policy = USB_DEVICE_AUTHORIZE_ALL;
        break;
    case USB_AUTHORIZE_INTERNAL:
        hcd->dev_policy = USB_DEVICE_AUTHORIZE_INTERNAL;
        break;
    case USB_AUTHORIZE_WIRED:
    default:
        hcd->dev_policy = hcd->wireless ?
            USB_DEVICE_AUTHORIZE_NONE : USB_DEVICE_AUTHORIZE_ALL;
        break;
    }

    /* HC is in reset state, but accessible.  Now do the one-time init,
     * bottom up so that hcds can customize the root hubs before hub_wq
     * starts talking to them.  (Note, bus id is assigned early too.)
     */
    retval = hcd_buffer_create(hcd); //分配一個內存池給DMA用
    if (retval != 0) {
        dev_dbg(hcd->self.sysdev, "pool alloc failed\n");
        goto err_create_buf;
    }
    retval = usb_register_bus(&hcd->self); //使用USB核心注冊USB主機控制器,把usb總線加入到系統
    if (retval < 0)
        goto err_register_bus;

    rhdev = usb_alloc_dev(NULL, &hcd->self, 0); //分配一個hub設備
    if (rhdev == NULL) {
        dev_err(hcd->self.sysdev, "unable to allocate root hub\n");
        retval = -ENOMEM;
        goto err_allocate_root_hub;
    }

    mutex_lock(&usb_port_peer_mutex);
    hcd->self.root_hub = rhdev;
    mutex_unlock(&usb_port_peer_mutex);

    switch (hcd->speed) { //判斷屬於的usb速率
    case HCD_USB11:
        rhdev->speed = USB_SPEED_FULL;
        break;
    case HCD_USB2:
        rhdev->speed = USB_SPEED_HIGH;
        break;
    case HCD_USB25:
        rhdev->speed = USB_SPEED_WIRELESS;
        break;
    case HCD_USB3:
        rhdev->speed = USB_SPEED_SUPER;
        break;
    case HCD_USB32:
        rhdev->rx_lanes = 2;
        rhdev->tx_lanes = 2;
        /* fall through */
    case HCD_USB31:
        rhdev->speed = USB_SPEED_SUPER_PLUS;
        break;
    default:
        retval = -EINVAL;
        goto err_set_rh_speed;
    }

    /* initialize tasklets */
    init_giveback_urb_bh(&hcd->high_prio_bh); //初始化tasklet, usb_giveback_urb_bh
    init_giveback_urb_bh(&hcd->low_prio_bh);


    /* enable irqs just before we start the controller,
     * if the BIOS provides legacy PCI irqs.
     */
    if (usb_hcd_is_primary_hcd(hcd) && irqnum) {
        //xHCI規范說我們可以得到一個中斷,如果HC在某種情況出現了錯誤,我們可能會從事件環中獲取壞數據。這個中斷不是用來探測插入了設備的
        retval = usb_hcd_request_irqs(hcd, irqnum, irqflags); //申請中斷,中斷處理函數usb_hcd_irq,實際調用xhci_irq
        if (retval)
            goto err_request_irq;
    }
    retval = hcd->driver->start(hcd); //實際是調用xhci_run, 啟動xhci host controller
    if (retval < 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 */
    retval = register_root_hub(hcd); //注冊一個root hub
    if (retval != 0)
        goto err_register_root_hub;

    if (hcd->uses_new_polling && HCD_POLL_RH(hcd)) 
        //如果驅動請求roothub中斷傳輸,會用一個定時器輪詢;否則由驅動在事件發生時調用usb_hcd_poll_rh_status()。
        usb_hcd_poll_rh_status(hcd); 

    return retval;
}

我們來分析一下usb_hcd_poll_rh_status,這關系到一個usb設備插入的時候,如何通知hub。這個函數usb_hcd_poll_rh_status會一直使用定時器調用自己,如果讀取到hub有變化,而且有提交的urb,就返回。

void usb_hcd_poll_rh_status(struct usb_hcd *hcd)
{
    length = hcd->driver->hub_status_data(hcd, buffer); //這里會調用xhci_hub_status_data讀取roothub的寄存器,返回數據buffer和length
    if (length > 0) {
        /* try to complete the status urb */
        spin_lock_irqsave(&hcd_root_hub_lock, flags);
        urb = hcd->status_urb;
        if (urb) { //如果已經提交了獲取狀態的urb, 將狀態值拷貝進入urb,並把urb giveback
            clear_bit(HCD_FLAG_POLL_PENDING, &hcd->flags);
            hcd->status_urb = NULL;
            urb->actual_length = length;
            memcpy(urb->transfer_buffer, buffer, length); 
            usb_hcd_unlink_urb_from_ep(hcd, urb); //從它的端點隊列中移除一個URB
            usb_hcd_giveback_urb(hcd, urb, 0); 
        } else { //若此時沒有已經提交的urb,則設置poll_pending標志
            length = 0;
            set_bit(HCD_FLAG_POLL_PENDING, &hcd->flags);
        }
        spin_unlock_irqrestore(&hcd_root_hub_lock, flags);
    }
    /* The USB 2.0 spec says 256 ms.  This is close enough and won't
     * exceed that limit if HZ is 100. The math is more clunky than
     * maybe expected, this is to make sure that all timers for USB devices
     * fire at the same time to give the CPU a break in between */
    if (hcd->uses_new_polling ? HCD_POLL_RH(hcd) : //這里hcd->uses_new_polling=1  HCD_POLL_RH(hcd)如果不等於0,會一直調用mod_timer
            (length == 0 && hcd->status_urb != NULL)) 
        //此時開啟rh_timer.rh_timer的處理函數rh_timer_func,實際就是usb_hcd_poll_rh_status。
        mod_timer (&hcd->rh_timer, (jiffies/(HZ/4) + 1) * (HZ/4));
}


參考:

USB驅動框架_WuYujun's blog-CSDN博客_usb驅動框架

USB PHY芯片




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM