本篇分析usb_linux_client.c中的usb_init(),它的代码如下:
- void usb_init()
- {
- if (access(USB_FFS_ADB_EP0, F_OK) == 0)
- {
- usb_ffs_init();
- }
- else{
- usb_adb_init();
- }
- }
- static void usb_adb_init()
- {
- usb_handle *h;
- adb_thread_t tid;
- int fd;
- h = calloc(1, sizeof(usb_handle));
- h->write = usb_adb_write;
- h->read = usb_adb_read;
- h->kick = usb_adb_kick;
- h->fd = -1;
- adb_cond_init(&h->notify, 0);
- adb_mutex_init(&h->lock, 0);
- // Open the file /dev/android_adb_enable to trigger
- // the enabling of the adb USB function in the kernel.
- // We never touch this file again - just leave it open
- // indefinitely so the kernel will know when we are running
- // and when we are not.
- fd = unix_open("/dev/android_adb_enable", O_RDWR);
- if (fd < 0) {
- D("failed to open /dev/android_adb_enable\n");
- } else {
- close_on_exec(fd);
- }
- D("[ usb_init - starting thread ]\n");
- if(adb_thread_create(&tid, usb_adb_open_thread, h)){
- fatal_errno("cannot create usb thread");
- }
- }
usb_adb_open_thread的代码如下:
- static void *usb_adb_open_thread(void *x)
- {
- struct usb_handle *usb = (struct usb_handle *)x;
- int fd;
- while (1) {
- // wait until the USB device needs opening
- adb_mutex_lock(&usb->lock);
- while (usb->fd != -1)
- adb_cond_wait(&usb->notify, &usb->lock);
- adb_mutex_unlock(&usb->lock);
- D("[ usb_thread - opening device ]\n");
- do {
- /* XXX use inotify? */
- fd = unix_open("/dev/android_adb", O_RDWR);
- if (fd < 0) {
- // to support older kernels
- fd = unix_open("/dev/android", O_RDWR);
- }
- if (fd < 0) {
- adb_sleep_ms(1000);
- }
- } while (fd < 0);
- D("[ opening device succeeded ]\n");
- close_on_exec(fd);
- usb->fd = fd;
- D("[ usb_thread - registering device ]\n");
- register_usb_transport(usb, 0, 0, 1);
- }
- // never gets here
- return 0;
- }
这个线程的作用是一进入立即打开/dev/android_adb或/dev/android,如果成功,则调用register_usb_transport()后再次循环,并阻塞在以下代码处
while(usb->fd != -1)
adb_cond_wait(&usb->notify, &usb->lock);
当usb->kick()调用后fd的值被赋为-1,并发送cond唤醒上面的代码。
联系客服