UsbHostManager 监测USB总线

        用inotify机制监测 /dev/bus/usb文件夹下面的变化,对添加的节点的内存进行解析,从而获得添加/删除 设备的改变。

        我的一个疑惑是:当用USB反向充电时,有一种情况是:一侧是 source,device组合,另外一侧是 sink ,host 组合,此时mtp,仅充电、ptp等选项界面会在sink ,host 组合侧出现(基本的规律是,sink侧会出现该界面)。此时进行,mtp等选项切换时,两侧的UsbHostManager均不能探测到usb config的变化。为什么?

        该界面是设置当设备当作从设备时,该设备作为mtp,ptp设备功能的设置。所以虽然能设置成功,但是并没有连接成功,因为当前该设备组合是( sink ,host)是作为一个主设备而存在的。要连接成功,可以把当前设备切换成从设备。或者在对端设置成对应的功能(mtp,ptp等),此时对端虽然没有选择界面弹出(这是android的一个BUG),但是可以通过svc usb setFunctions mtp等命令切换功能。

frameworks/base/services/usb/java/com/android/server/usb/UsbHostManager.java
    public void systemReady() {
        synchronized (mLock) {
            // Create a thread to call into native code to wait for USB host events.
            // This thread will call us back on usbDeviceAdded and usbDeviceRemoved.
            Runnable runnable = this::monitorUsbHostBus;
            new Thread(null, runnable, "UsbService host thread").start();
        }
    }

    private native void monitorUsbHostBus();
    private native ParcelFileDescriptor nativeOpenDevice(String deviceAddress);

frameworks/base/services/core/jni/com_android_server_UsbHostManager.cpp

static const JNINativeMethod method_table[] = {
    { "monitorUsbHostBus", "()V", (void*)android_server_UsbHostManager_monitorUsbHostBus },
    { "nativeOpenDevice",  "(Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;",
                                  (void*)android_server_UsbHostManager_openDevice },
};

static void android_server_UsbHostManager_monitorUsbHostBus(JNIEnv* /* env */, jobject thiz)
{
    struct usb_host_context* context = usb_host_init();
    if (!context) {
        ALOGE("usb_host_init failed");
        return;
    }
    // this will never return so it is safe to pass thiz directly
    usb_host_run(context, usb_device_added, usb_device_removed, NULL, (void *)thiz);
}

static int usb_device_added(const char *devAddress, void* clientData) {
    struct usb_device *device = usb_device_open(devAddress); //打开设备节点,具体看后面的实现
    if (!device) {
        ALOGE("usb_device_open failed\n");
        return 0;
    }

    const usb_device_descriptor* deviceDesc = usb_device_get_device_descriptor(device);
    int classID = deviceDesc->bDeviceClass;
    int subClassID = deviceDesc->bDeviceSubClass;

    // get the raw descriptors
    int numBytes = usb_device_get_descriptors_length(device);
    if (numBytes > 0) {
        JNIEnv* env = AndroidRuntime::getJNIEnv();
        jobject thiz = (jobject)clientData;
        jstring deviceAddress = env->NewStringUTF(devAddress);

        jbyteArray descriptorsArray = env->NewByteArray(numBytes);
        const jbyte* rawDescriptors = (const jbyte*)usb_device_get_raw_descriptors(device);
        env->SetByteArrayRegion(descriptorsArray, 0, numBytes, rawDescriptors);

        env->CallBooleanMethod(thiz, method_usbDeviceAdded,
                deviceAddress, classID, subClassID, descriptorsArray);

        env->DeleteLocalRef(descriptorsArray);
        env->DeleteLocalRef(deviceAddress);

        checkAndClearExceptionFromCallback(env, __FUNCTION__);
    } else {
        // TODO return an error code here?
        ALOGE("error reading descriptors\n");
    }

    usb_device_close(device);

    return 0;
}

static int usb_device_removed(const char *devAddress, void* clientData) {
    JNIEnv* env = AndroidRuntime::getJNIEnv();
    jobject thiz = (jobject)clientData;

    jstring deviceAddress = env->NewStringUTF(devAddress);
    env->CallVoidMethod(thiz, method_usbDeviceRemoved, deviceAddress);
    env->DeleteLocalRef(deviceAddress);
    checkAndClearExceptionFromCallback(env, __FUNCTION__);
    return 0;
}

system/core/libusbhost/usbhost.c
struct usb_host_context *usb_host_init()
{
    struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
    if (!context) {
        fprintf(stderr, "out of memory in usb_host_context\n");
        return NULL;
    }
    //inotify是文件系统变化通知机制,在监听到文件系统变化后,会向相应的应用程序发送事件
    //inotify_add_watch 添加要监控的路径
    context->fd = inotify_init();
    if (context->fd < 0) {
        fprintf(stderr, "inotify_init failed\n");
        free(context);
        return NULL;
    }
    return context;
}

void usb_host_run(struct usb_host_context *context,
                  usb_device_added_cb added_cb,
                  usb_device_removed_cb removed_cb,
                  usb_discovery_done_cb discovery_done_cb,
                  void *client_data)
{
    int done;

    done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);

    while (!done) {

        done = usb_host_read_event(context);
    }
} /* usb_host_run() */

#define DEV_DIR             "/dev"
#define DEV_BUS_DIR         DEV_DIR "/bus"
#define USB_FS_DIR          DEV_BUS_DIR "/usb"
#define USB_FS_ID_SCANNER   USB_FS_DIR "/%d/%d"
#define USB_FS_ID_FORMAT    USB_FS_DIR "/%03d/%03d"

int usb_host_load(struct usb_host_context *context,
                  usb_device_added_cb added_cb,
                  usb_device_removed_cb removed_cb,
                  usb_discovery_done_cb discovery_done_cb,
                  void *client_data)
{
    int done = 0;
    int i;

    context->cb_added = added_cb;
    context->cb_removed = removed_cb;
    context->data = client_data;

    D("Created device discovery thread\n");

    /* watch for files added and deleted within USB_FS_DIR */
    context->wddbus = -1;
    for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
        context->wds[i] = -1;

    /* watch the root for new subdirectories */
    context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
    if (context->wdd < 0) {
        fprintf(stderr, "inotify_add_watch failed\n");
        if (discovery_done_cb)
            discovery_done_cb(client_data);
        return done;
    }

    watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);

    /* check for existing devices first, after we have inotify set up */
    done = find_existing_devices(added_cb, client_data);
    if (discovery_done_cb)
        done |= discovery_done_cb(client_data);

    return done;
} /* usb_host_load() */

static void watch_existing_subdirs(struct usb_host_context *context,
                                   int *wds, int wd_count)
{
    char path[100];
    int i, ret;

    //USB_FS_DIR --> /dev/bus/usb
    wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
    if (wds[0] < 0)
        return;

    /* watch existing subdirectories of USB_FS_DIR */
    for (i = 1; i < wd_count; i++) {
        snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
        ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
        if (ret >= 0)
            wds[i] = ret;
    }
}

static int find_existing_devices_bus(char *busname,
                                     usb_device_added_cb added_cb,
                                     void *client_data)
{
    char devname[32];
    DIR *devdir;
    struct dirent *de;
    int done = 0;

    devdir = opendir(busname);
    if(devdir == 0) return 0;

    while ((de = readdir(devdir)) && !done) {
        if(badname(de->d_name)) continue;

        snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
        done = added_cb(devname, client_data);
    } // end of devdir while
    closedir(devdir);

    return done;
}

/* returns true if one of the callbacks indicates we are done */
static int find_existing_devices(usb_device_added_cb added_cb,
                                  void *client_data)
{
    char busname[32];
    DIR *busdir;
    struct dirent *de;
    int done = 0;

    busdir = opendir(USB_FS_DIR);
    if(busdir == 0) return 0;

    while ((de = readdir(busdir)) != 0 && !done) {
        if(badname(de->d_name)) continue;

        snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
        done = find_existing_devices_bus(busname, added_cb,
                                         client_data);
    } //end of busdir while
    closedir(busdir);

    return done;
}

打开设备,读取设备描述符

system/core/libusbhost/usbhost.c
int usb_host_read_event(struct usb_host_context *context)
{
    struct inotify_event* event;
    char event_buf[512];
    char path[100];
    int i, ret, done = 0;
    int offset = 0;
    int wd;

    ret = read(context->fd, event_buf, sizeof(event_buf));
    if (ret >= (int)sizeof(struct inotify_event)) {
        while (offset < ret && !done) {
            event = (struct inotify_event*)&event_buf[offset];
            done = 0;
            wd = event->wd;
            if (wd == context->wdd) {
                if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
                    context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
                    if (context->wddbus < 0) {
                        done = 1;
                    } else {
                        watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
                        done = find_existing_devices(context->cb_added, context->data);
                    }
                }
            } else if (wd == context->wddbus) {
                if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
                    watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
                    done = find_existing_devices(context->cb_added, context->data);
                } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
                    for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
                        if (context->wds[i] >= 0) {
                            inotify_rm_watch(context->fd, context->wds[i]);
                            context->wds[i] = -1;
                        }
                    }
                }
            } else if (wd == context->wds[0]) {
                i = atoi(event->name);
                snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
                D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
                        "new" : "gone", path, i);
                if (i > 0 && i < MAX_USBFS_WD_COUNT) {
                    int local_ret = 0;
                    if (event->mask & IN_CREATE) {
                        local_ret = inotify_add_watch(context->fd, path,
                                IN_CREATE | IN_DELETE);
                        if (local_ret >= 0)
                            context->wds[i] = local_ret;
                        done = find_existing_devices_bus(path, context->cb_added,
                                context->data);
                    } else if (event->mask & IN_DELETE) {
                        inotify_rm_watch(context->fd, context->wds[i]);
                        context->wds[i] = -1;
                    }
                }
            } else {
                for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
                    if (wd == context->wds[i]) {
                        snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
                        if (event->mask == IN_CREATE) {
                            D("new device %s\n", path);
                            done = context->cb_added(path, context->data);
                        } else if (event->mask == IN_DELETE) {
                            D("gone device %s\n", path);
                            done = context->cb_removed(path, context->data);
                        }
                    }
                }
            }

            offset += sizeof(struct inotify_event) + event->len;
        }
    }

    return done;
} /* usb_host_read_event() */

struct usb_device *usb_device_open(const char *dev_name)
{
    int fd, attempts, writeable = 1;
    const int SLEEP_BETWEEN_ATTEMPTS_US = 100000; /* 100 ms */
    const int64_t MAX_ATTEMPTS = 10;              /* 1s */
    D("usb_device_open %s\n", dev_name);

    /* Hack around waiting for permissions to be set on the USB device node.
     * Should really be a timeout instead of attempt count, and should REALLY
     * be triggered by the perm change via inotify rather than polling.
     */
    for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) {
        if (access(dev_name, R_OK | W_OK) == 0) {
            writeable = 1;
            break;
        } else {
            if (access(dev_name, R_OK) == 0) {
                /* double check that write permission didn't just come along too! */
                writeable = (access(dev_name, R_OK | W_OK) == 0);
                break;
            }
        }
        /* not writeable or readable - sleep and try again. */
        D("usb_device_open no access sleeping\n");
        usleep(SLEEP_BETWEEN_ATTEMPTS_US);
    }

    if (writeable) {
        fd = open(dev_name, O_RDWR);
    } else {
        fd = open(dev_name, O_RDONLY);
    }
    D("usb_device_open open returned %d writeable %d errno %d\n", fd, writeable, errno);
    if (fd < 0) return NULL;

    struct usb_device* result = usb_device_new(dev_name, fd);
    if (result)
        result->writeable = writeable;
    return result;
}

struct usb_device *usb_device_new(const char *dev_name, int fd)
{
    struct usb_device *device = calloc(1, sizeof(struct usb_device));
    int length;

    D("usb_device_new %s fd: %d\n", dev_name, fd);

    if (lseek(fd, 0, SEEK_SET) != 0)
        goto failed;
    length = read(fd, device->desc, sizeof(device->desc));
    D("usb_device_new read returned %d errno %d\n", length, errno);
    if (length < 0)
        goto failed;

    strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
    device->fd = fd;
    device->desc_length = length;
    // assume we are writeable, since usb_device_get_fd will only return writeable fds
    device->writeable = 1;
    return device;

failed:
    // TODO It would be more appropriate to have callers do this
    // since this function doesn't "own" this file descriptor.
    close(fd);
    free(device);
    return NULL;
}

USB设备接入报文分析

linux系统路径:/sys/bus/usb/devices

1-0:1.0    2-1.1:1.0  2-1.5:1.0  2-1.5:1.4  3-0:1.0    usb3
2-0:1.0    2-1.1:1.1  2-1.5:1.1  2-1.6        4-0:1.0    usb4
2-1          2-1.1:1.2  2-1.5:1.2  2-1.6:1.0  usb1
2-1.1       2-1.5        2-1.5:1.3  2-1:1.0    usb2

A. 其中usb1、usb2、usb3、usb4表示MCU上接了4条USB总线,即4个USB主机控制器(4个RootHub);

B. 2-1   2号总线的1号端口(物理端口,真实的USB口)设备,即Root Hub
C. 2-1.1    2-1为RootHub,".1"表示RootHub的1号端口设备连接了一个Hub
D. 2-1.1:1.0  2-1为RootHub,".1"表示RootHub的1号端口设备连接了一个Hub,":1"表示1号配置,".0"表示接口号,1个接口即表示一种功能
E. 2-1.1:1.1  2-1为RootHub,".1"表示RootHub的1号端口设备连接了一个Hub,":1"表示1号配置,".1"表示接口号,1个接口即表示一种功能

USB设备报文枚举过程分析:

[10196.531727] ehci_irq: highspeed device disconnect
[10196.536973] ehci_irq: highspeed device connect

//1-1 RootHub 1号总线1号端口
[10196.541713] usb 1-1: USB disconnect, device number 2 
[10196.543288] ehci_irq: highspeed device disconnect
[17227.295188] ehci_irq: highspeed device connect

//2-1 RootHub 2号总线1号端口
[17227.530065] usb 2-1: new high-speed USB device number 2 using sunxi-ehci
[17227.681173] usb 2-1: New USB device found, idVendor=0424, idProduct=2517
[17227.688561] usb 2-1: New USB device strings: Mfr=0, Product=0, SerialNumber=0

//2-1:1.0  RootHub 2号总线1号端口,1号配置,0号接口
[17227.699690] hub 2-1:1.0: USB hub found
[17227.704257] hub 2-1:1.0: 7 ports detected

//2-1.1  RootHub为2-1,在RootHub 1号端口上级联了hub,并且使用级联hub的1号端口
[17227.990506] usb 2-1.1: new full-speed USB device number 3 using sunxi-ehci
[17228.090313] usb 2-1.1: device descriptor read/64, error -32
[17228.280520] usb 2-1.1: device descriptor read/64, error -32
[17228.470637] usb 2-1.1: new full-speed USB device number 4 using sunxi-ehci
[17228.570508] usb 2-1.1: device descriptor read/64, error -32
[17228.760635] usb 2-1.1: device descriptor read/64, error -32
[17228.950494] usb 2-1.1: new full-speed USB device number 5 using sunxi-ehci
[17229.370289] usb 2-1.1: device not accepting address 5, error -32

//2-1.6  RootHub为2-1,在RootHub 1号端口上级联了hub,并且使用级联hub的6号端口
[17229.490500] usb 2-1.6: new high-speed USB device number 7 using sunxi-ehci
[17229.622282] usb 2-1.6: New USB device found, idVendor=0b95, idProduct=772b
[17229.629862] usb 2-1.6: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[17229.638246] usb 2-1.6: Product: AX88772B
[17229.642696] usb 2-1.6: Manufacturer: ASIX Elec. Corp.
[17229.648246] usb 2-1.6: SerialNumber: 000001
[17229.976571] asix 2-1.6:1.0 eth1: register 'asix' at usb-sunxi-ehci-1.6, ASIX AX88772B USB 2.0 Ethernet, 00:0e:c6:87:72:01

[17230.220645] usb 2-1.1: new full-speed USB device number 8 using sunxi-ehci
[17230.352509] usb 2-1.1: config 1 has an invalid descriptor of length 0, skipping remainder of the config
[17230.364405] usb 2-1.1: New USB device found, idVendor=0483, idProduct=5740
[17230.372160] usb 2-1.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[17230.380321] usb 2-1.1: Product: Composite HID CDC
[17230.385501] usb 2-1.1: Manufacturer: STMicroelectronics
[17230.391462] usb 2-1.1: SerialNumber: 395B35563137
[17230.405648] hid-generic 0003:0483:5740.0001: hiddev0,hidraw0: USB HID v1.11 Device [STMicroelectronics Composite HID CDC] on usb-sunxi-ehci-1.1/input0
[17230.425804] cdc_acm 2-1.1:1.1: This device cannot do calls on its own. It is not a modem.
[17230.443286] cdc_acm 2-1.1:1.1: ttyACM0: USB ACM device

[17236.810364] usb 2-1.4: new high-speed USB device number 9 using sunxi-ehci
[17236.950567] usb 2-1.4: New USB device found, idVendor=3763, idProduct=3c93
[17236.958148] usb 2-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[17236.966518] usb 2-1.4: Product: Android
[17236.970879] usb 2-1.4: Manufacturer: Android

//2-1.4:1.0  RootHub为2-1,在RootHub 1号端口上级联了hub,并且使用级联hub的4号端口,1号配置,0号端口
[17236.978885] option 2-1.4:1.0: GSM modem (1-port) converter detected
[17236.988588] usb 2-1.4: GSM modem (1-port) converter now attached to ttyUSB0

//2-1.4:1.0  RootHub为2-1,在RootHub 1号端口上级联了hub,并且使用级联hub的4号端口,1号配置,1号端口
[17236.997837] option 2-1.4:1.1: GSM modem (1-port) converter detected
[17237.007254] usb 2-1.4: GSM modem (1-port) converter now attached to ttyUSB1

//2-1.4:1.0  RootHub为2-1,在RootHub 1号端口上级联了hub,并且使用级联hub的4号端口,1号配置,2号端口
[17237.016753] option 2-1.4:1.2: GSM modem (1-port) converter detected
[17237.026222] usb 2-1.4: GSM modem (1-port) converter now attached to ttyUSB2

//2-1.4:1.0  RootHub为2-1,在RootHub 1号端口上级联了hub,并且使用级联hub的4号端口,1号配置,3号端口
[17237.042223] cdc_ether 2-1.4:1.3 usb0: register 'cdc_ether' at usb-sunxi-ehci-1.4, CDC Ethernet Device, 9e:08:f0:10:ff:04

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值