blob: 415488fc078771e1ca6a40ba82f1a0c78bb72b10 [file] [log] [blame]
Mike Lockwood30ff2c72010-05-09 16:23:47 -04001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Philip P. Moltmann36952852016-10-17 16:57:43 -070017#ifndef _GNU_SOURCE
18#define _GNU_SOURCE
19#endif
20
Mike Lockwoode15af092010-06-10 10:20:49 -040021// #define DEBUG 1
22#if DEBUG
23
24#ifdef USE_LIBLOG
25#define LOG_TAG "usbhost"
Dan Willemsena5c60172017-04-20 08:32:35 -070026#include "log/log.h"
Steve Block8d66c492011-12-20 16:07:45 +000027#define D ALOGD
Mike Lockwoode15af092010-06-10 10:20:49 -040028#else
29#define D printf
30#endif
31
32#else
33#define D(...)
34#endif
35
Mike Lockwood30ff2c72010-05-09 16:23:47 -040036#include <stdio.h>
37#include <stdlib.h>
38#include <unistd.h>
39#include <string.h>
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020040#include <stddef.h>
Mike Lockwood30ff2c72010-05-09 16:23:47 -040041
42#include <sys/ioctl.h>
43#include <sys/types.h>
44#include <sys/time.h>
45#include <sys/inotify.h>
46#include <dirent.h>
47#include <fcntl.h>
48#include <errno.h>
49#include <ctype.h>
Philip P. Moltmann36952852016-10-17 16:57:43 -070050#include <poll.h>
Mike Lockwood30ff2c72010-05-09 16:23:47 -040051#include <pthread.h>
52
53#include <linux/usbdevice_fs.h>
Mike Lockwood30ff2c72010-05-09 16:23:47 -040054#include <asm/byteorder.h>
55
56#include "usbhost/usbhost.h"
57
Benoit Gobyf4de0782012-08-01 18:54:02 -070058#define DEV_DIR "/dev"
Ziv Hendela306ced2013-08-07 19:29:17 +030059#define DEV_BUS_DIR DEV_DIR "/bus"
60#define USB_FS_DIR DEV_BUS_DIR "/usb"
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020061#define USB_FS_ID_SCANNER USB_FS_DIR "/%d/%d"
62#define USB_FS_ID_FORMAT USB_FS_DIR "/%03d/%03d"
Mike Lockwood30ff2c72010-05-09 16:23:47 -040063
Mike Lockwood0dd1aab2015-06-18 13:38:31 -070064// Some devices fail to send string descriptors if we attempt reading > 255 bytes
65#define MAX_STRING_DESCRIPTOR_LENGTH 255
66
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020067#define MAX_USBFS_WD_COUNT 10
68
Mike Lockwood6ac3aa12010-05-25 08:10:02 -040069struct usb_host_context {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020070 int fd;
71 usb_device_added_cb cb_added;
72 usb_device_removed_cb cb_removed;
73 void *data;
74 int wds[MAX_USBFS_WD_COUNT];
75 int wdd;
Ziv Hendela306ced2013-08-07 19:29:17 +030076 int wddbus;
Mike Lockwood6ac3aa12010-05-25 08:10:02 -040077};
78
Paul McLeanbaea1bd2017-11-06 10:22:51 -070079#define MAX_DESCRIPTORS_LENGTH 4096
80
Mike Lockwood30ff2c72010-05-09 16:23:47 -040081struct usb_device {
82 char dev_name[64];
Paul McLeanbaea1bd2017-11-06 10:22:51 -070083 unsigned char desc[MAX_DESCRIPTORS_LENGTH];
Mike Lockwood30ff2c72010-05-09 16:23:47 -040084 int desc_length;
85 int fd;
86 int writeable;
87};
88
Mike Lockwood30ff2c72010-05-09 16:23:47 -040089static inline int badname(const char *name)
90{
91 while(*name) {
92 if(!isdigit(*name++)) return 1;
93 }
94 return 0;
95}
96
Benoit Goby6cc883c2012-07-31 19:22:06 -070097static int find_existing_devices_bus(char *busname,
98 usb_device_added_cb added_cb,
99 void *client_data)
100{
101 char devname[32];
102 DIR *devdir;
103 struct dirent *de;
104 int done = 0;
105
106 devdir = opendir(busname);
107 if(devdir == 0) return 0;
108
109 while ((de = readdir(devdir)) && !done) {
110 if(badname(de->d_name)) continue;
111
112 snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
113 done = added_cb(devname, client_data);
114 } // end of devdir while
115 closedir(devdir);
116
117 return done;
118}
119
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400120/* returns true if one of the callbacks indicates we are done */
121static int find_existing_devices(usb_device_added_cb added_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400122 void *client_data)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400123{
Benoit Goby6cc883c2012-07-31 19:22:06 -0700124 char busname[32];
125 DIR *busdir;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400126 struct dirent *de;
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400127 int done = 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400128
129 busdir = opendir(USB_FS_DIR);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700130 if(busdir == 0) return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400131
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400132 while ((de = readdir(busdir)) != 0 && !done) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400133 if(badname(de->d_name)) continue;
134
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200135 snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
Benoit Goby6cc883c2012-07-31 19:22:06 -0700136 done = find_existing_devices_bus(busname, added_cb,
137 client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200138 } //end of busdir while
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400139 closedir(busdir);
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400140
141 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400142}
143
Benoit Gobyf4de0782012-08-01 18:54:02 -0700144static void watch_existing_subdirs(struct usb_host_context *context,
145 int *wds, int wd_count)
146{
147 char path[100];
148 int i, ret;
149
150 wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
151 if (wds[0] < 0)
152 return;
153
154 /* watch existing subdirectories of USB_FS_DIR */
155 for (i = 1; i < wd_count; i++) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200156 snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700157 ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
158 if (ret >= 0)
159 wds[i] = ret;
160 }
161}
162
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400163struct usb_host_context *usb_host_init()
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400164{
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400165 struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
166 if (!context) {
167 fprintf(stderr, "out of memory in usb_host_context\n");
168 return NULL;
169 }
170 context->fd = inotify_init();
171 if (context->fd < 0) {
172 fprintf(stderr, "inotify_init failed\n");
173 free(context);
174 return NULL;
175 }
176 return context;
177}
178
179void usb_host_cleanup(struct usb_host_context *context)
180{
181 close(context->fd);
182 free(context);
183}
184
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200185int usb_host_get_fd(struct usb_host_context *context)
186{
187 return context->fd;
188} /* usb_host_get_fd() */
189
190int usb_host_load(struct usb_host_context *context,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400191 usb_device_added_cb added_cb,
192 usb_device_removed_cb removed_cb,
Mike Lockwooda8055192010-07-19 20:15:15 -0400193 usb_discovery_done_cb discovery_done_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400194 void *client_data)
195{
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200196 int done = 0;
197 int i;
198
199 context->cb_added = added_cb;
200 context->cb_removed = removed_cb;
201 context->data = client_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400202
203 D("Created device discovery thread\n");
204
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400205 /* watch for files added and deleted within USB_FS_DIR */
Ziv Hendela306ced2013-08-07 19:29:17 +0300206 context->wddbus = -1;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200207 for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
208 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700209
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400210 /* watch the root for new subdirectories */
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200211 context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
212 if (context->wdd < 0) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400213 fprintf(stderr, "inotify_add_watch failed\n");
Mike Lockwoode8849d12010-07-20 16:31:42 -0400214 if (discovery_done_cb)
215 discovery_done_cb(client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200216 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400217 }
218
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200219 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400220
221 /* check for existing devices first, after we have inotify set up */
Benoit Goby6cc883c2012-07-31 19:22:06 -0700222 done = find_existing_devices(added_cb, client_data);
Mike Lockwooda8055192010-07-19 20:15:15 -0400223 if (discovery_done_cb)
224 done |= discovery_done_cb(client_data);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400225
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200226 return done;
227} /* usb_host_load() */
228
229int usb_host_read_event(struct usb_host_context *context)
230{
231 struct inotify_event* event;
232 char event_buf[512];
233 char path[100];
234 int i, ret, done = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200235 int offset = 0;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200236 int wd;
237
238 ret = read(context->fd, event_buf, sizeof(event_buf));
239 if (ret >= (int)sizeof(struct inotify_event)) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300240 while (offset < ret && !done) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200241 event = (struct inotify_event*)&event_buf[offset];
242 done = 0;
243 wd = event->wd;
244 if (wd == context->wdd) {
245 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300246 context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
247 if (context->wddbus < 0) {
248 done = 1;
249 } else {
250 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
251 done = find_existing_devices(context->cb_added, context->data);
252 }
253 }
254 } else if (wd == context->wddbus) {
255 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200256 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
257 done = find_existing_devices(context->cb_added, context->data);
Ziv Hendela306ced2013-08-07 19:29:17 +0300258 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200259 for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
260 if (context->wds[i] >= 0) {
261 inotify_rm_watch(context->fd, context->wds[i]);
262 context->wds[i] = -1;
263 }
264 }
265 }
266 } else if (wd == context->wds[0]) {
267 i = atoi(event->name);
268 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
269 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
270 "new" : "gone", path, i);
271 if (i > 0 && i < MAX_USBFS_WD_COUNT) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800272 int local_ret = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200273 if (event->mask & IN_CREATE) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800274 local_ret = inotify_add_watch(context->fd, path,
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200275 IN_CREATE | IN_DELETE);
Bo Huang3c1d7b32014-01-21 14:25:22 +0800276 if (local_ret >= 0)
277 context->wds[i] = local_ret;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200278 done = find_existing_devices_bus(path, context->cb_added,
279 context->data);
280 } else if (event->mask & IN_DELETE) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200281 inotify_rm_watch(context->fd, context->wds[i]);
282 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700283 }
284 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200285 } else {
286 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
287 if (wd == context->wds[i]) {
288 snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
289 if (event->mask == IN_CREATE) {
290 D("new device %s\n", path);
291 done = context->cb_added(path, context->data);
292 } else if (event->mask == IN_DELETE) {
293 D("gone device %s\n", path);
294 done = context->cb_removed(path, context->data);
295 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400296 }
297 }
298 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200299
300 offset += sizeof(struct inotify_event) + event->len;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400301 }
302 }
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200303
304 return done;
305} /* usb_host_read_event() */
306
307void usb_host_run(struct usb_host_context *context,
308 usb_device_added_cb added_cb,
309 usb_device_removed_cb removed_cb,
310 usb_discovery_done_cb discovery_done_cb,
311 void *client_data)
312{
313 int done;
314
315 done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
316
317 while (!done) {
318
319 done = usb_host_read_event(context);
320 }
321} /* usb_host_run() */
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400322
323struct usb_device *usb_device_open(const char *dev_name)
324{
Andrew Chant3af9e402017-11-01 17:32:35 -0700325 int fd, attempts, writeable = 1;
326 const int SLEEP_BETWEEN_ATTEMPTS_US = 100000; /* 100 ms */
327 const int64_t MAX_ATTEMPTS = 10; /* 1s */
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800328 D("usb_device_open %s\n", dev_name);
329
Andrew Chant3af9e402017-11-01 17:32:35 -0700330 /* Hack around waiting for permissions to be set on the USB device node.
331 * Should really be a timeout instead of attempt count, and should REALLY
332 * be triggered by the perm change via inotify rather than polling.
333 */
334 for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) {
335 if (access(dev_name, R_OK | W_OK) == 0) {
336 writeable = 1;
337 break;
338 } else {
339 if (access(dev_name, R_OK) == 0) {
340 /* double check that write permission didn't just come along too! */
341 writeable = (access(dev_name, R_OK | W_OK) == 0);
342 break;
343 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400344 }
Andrew Chant3af9e402017-11-01 17:32:35 -0700345 /* not writeable or readable - sleep and try again. */
346 D("usb_device_open no access sleeping\n");
347 usleep(SLEEP_BETWEEN_ATTEMPTS_US);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400348 }
349
Andrew Chant3af9e402017-11-01 17:32:35 -0700350 if (writeable) {
351 fd = open(dev_name, O_RDWR);
352 } else {
353 fd = open(dev_name, O_RDONLY);
354 }
355 D("usb_device_open open returned %d writeable %d errno %d\n", fd, writeable, errno);
356 if (fd < 0) return NULL;
357
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800358 struct usb_device* result = usb_device_new(dev_name, fd);
359 if (result)
360 result->writeable = writeable;
361 return result;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400362}
363
364void usb_device_close(struct usb_device *device)
365{
366 close(device->fd);
367 free(device);
368}
369
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800370struct usb_device *usb_device_new(const char *dev_name, int fd)
371{
372 struct usb_device *device = calloc(1, sizeof(struct usb_device));
373 int length;
374
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800375 D("usb_device_new %s fd: %d\n", dev_name, fd);
376
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800377 if (lseek(fd, 0, SEEK_SET) != 0)
378 goto failed;
379 length = read(fd, device->desc, sizeof(device->desc));
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800380 D("usb_device_new read returned %d errno %d\n", length, errno);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800381 if (length < 0)
382 goto failed;
383
Mike Lockwood93aff722010-12-15 12:58:04 -0800384 strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800385 device->fd = fd;
386 device->desc_length = length;
387 // assume we are writeable, since usb_device_get_fd will only return writeable fds
388 device->writeable = 1;
389 return device;
390
391failed:
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700392 // TODO It would be more appropriate to have callers do this
393 // since this function doesn't "own" this file descriptor.
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800394 close(fd);
395 free(device);
396 return NULL;
397}
398
399static int usb_device_reopen_writeable(struct usb_device *device)
400{
401 if (device->writeable)
402 return 1;
403
404 int fd = open(device->dev_name, O_RDWR);
405 if (fd >= 0) {
406 close(device->fd);
407 device->fd = fd;
408 device->writeable = 1;
409 return 1;
410 }
411 D("usb_device_reopen_writeable failed errno %d\n", errno);
412 return 0;
413}
414
415int usb_device_get_fd(struct usb_device *device)
416{
417 if (!usb_device_reopen_writeable(device))
418 return -1;
419 return device->fd;
420}
421
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400422const char* usb_device_get_name(struct usb_device *device)
423{
424 return device->dev_name;
425}
426
Mike Lockwood203f1022010-05-27 10:12:03 -0400427int usb_device_get_unique_id(struct usb_device *device)
428{
429 int bus = 0, dev = 0;
430 sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
431 return bus * 1000 + dev;
432}
433
Mike Lockwood07eb4af2010-07-27 19:05:33 -0400434int usb_device_get_unique_id_from_name(const char* name)
435{
436 int bus = 0, dev = 0;
437 sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
438 return bus * 1000 + dev;
439}
440
Mike Lockwood7d700f82010-12-29 08:47:29 -0500441char* usb_device_get_name_from_unique_id(int id)
442{
443 int bus = id / 1000;
444 int dev = id % 1000;
445 char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
446 snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
447 return result;
448}
449
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400450uint16_t usb_device_get_vendor_id(struct usb_device *device)
451{
452 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
453 return __le16_to_cpu(desc->idVendor);
454}
455
456uint16_t usb_device_get_product_id(struct usb_device *device)
457{
458 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
459 return __le16_to_cpu(desc->idProduct);
460}
461
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700462const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device* device) {
Mike Lockwood50372072010-12-13 10:15:25 -0800463 return (struct usb_device_descriptor*)device->desc;
464}
465
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700466size_t usb_device_get_descriptors_length(const struct usb_device* device) {
467 return device->desc_length;
468}
469
470const unsigned char* usb_device_get_raw_descriptors(const struct usb_device* device) {
471 return device->desc;
472}
473
Andrew Chant169742e2017-12-07 16:51:49 -0800474/* Returns a USB descriptor string for the given string ID.
475 * Return value: < 0 on error. 0 on success.
476 * The string is returned in ucs2_out in USB-native UCS-2 encoding.
477 *
478 * parameters:
479 * id - the string descriptor index.
480 * timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
481 * ucs2_out - Must point to null on call.
482 * Will be filled in with a buffer on success.
483 * If this is non-null on return, it must be free()d.
484 * response_size - size, in bytes, of ucs-2 string in ucs2_out.
485 * The size isn't guaranteed to include null termination.
486 * Call free() to free the result when you are done with it.
487 */
488int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
489 size_t* response_size) {
Mike Lockwood0dd1aab2015-06-18 13:38:31 -0700490 __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
Andrew Chant169742e2017-12-07 16:51:49 -0800491 char response[MAX_STRING_DESCRIPTOR_LENGTH];
492 int result;
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400493 int languageCount = 0;
494
Andrew Chant169742e2017-12-07 16:51:49 -0800495 if (id == 0) return -1;
496 if (*ucs2_out != NULL) return -1;
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800497
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400498 memset(languages, 0, sizeof(languages));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400499
500 // read list of supported languages
Mike Lockwood120b57a2011-01-27 10:46:19 -0800501 result = usb_device_control_transfer(device,
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400502 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700503 (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
504 timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400505 if (result > 0)
506 languageCount = (result - 2) / 2;
507
Andrew Chant169742e2017-12-07 16:51:49 -0800508 for (int i = 1; i <= languageCount; i++) {
509 memset(response, 0, sizeof(response));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400510
Andrew Chant169742e2017-12-07 16:51:49 -0800511 result = usb_device_control_transfer(
512 device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
513 (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
514 if (result >= 2) { // string contents begin at offset 2.
515 int descriptor_len = result - 2;
516 char* out = malloc(descriptor_len + 3);
517 if (out == NULL) {
518 return -1;
519 }
520 memcpy(out, response + 2, descriptor_len);
521 // trail with three additional NULLs, so that there's guaranteed
522 // to be a UCS-2 NULL character beyond whatever USB returned.
523 // The returned string length is still just what USB returned.
524 memset(out + descriptor_len, '\0', 3);
525 *ucs2_out = (void*)out;
526 *response_size = descriptor_len;
527 return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400528 }
529 }
Andrew Chant169742e2017-12-07 16:51:49 -0800530 return -1;
531}
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400532
Andrew Chant169742e2017-12-07 16:51:49 -0800533/* Warning: previously this blindly returned the lower 8 bits of
534 * every UCS-2 character in a USB descriptor. Now it will replace
535 * values > 127 with ascii '?'.
536 */
537char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
538 char* ascii_string = NULL;
539 size_t raw_string_len = 0;
540 size_t i;
541 if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
542 return NULL;
543 if (ascii_string == NULL) return NULL;
544 for (i = 0; i < raw_string_len / 2; ++i) {
545 // wire format for USB is always little-endian.
546 char lower = ascii_string[2 * i];
547 char upper = ascii_string[2 * i + 1];
548 if (upper || (lower & 0x80)) {
549 ascii_string[i] = '?';
550 } else {
551 ascii_string[i] = lower;
552 }
553 }
554 ascii_string[i] = '\0';
555 return ascii_string;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400556}
557
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700558char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400559{
560 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700561 return usb_device_get_string(device, desc->iManufacturer, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400562}
563
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700564char* usb_device_get_product_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400565{
566 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700567 return usb_device_get_string(device, desc->iProduct, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400568}
569
Mike Lockwoodf68600a2015-04-29 13:04:10 -0700570int usb_device_get_version(struct usb_device *device)
571{
572 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
573 return desc->bcdUSB;
574}
575
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700576char* usb_device_get_serial(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400577{
578 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700579 return usb_device_get_string(device, desc->iSerialNumber, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400580}
581
582int usb_device_is_writeable(struct usb_device *device)
583{
584 return device->writeable;
585}
586
587void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
588{
589 iter->config = device->desc;
590 iter->config_end = device->desc + device->desc_length;
591 iter->curr_desc = device->desc;
592}
593
594struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
595{
596 struct usb_descriptor_header* next;
597 if (iter->curr_desc >= iter->config_end)
598 return NULL;
599 next = (struct usb_descriptor_header*)iter->curr_desc;
600 iter->curr_desc += next->bLength;
601 return next;
602}
603
604int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
605{
606 return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
607}
608
609int usb_device_release_interface(struct usb_device *device, unsigned int interface)
610{
611 return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
612}
613
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800614int usb_device_connect_kernel_driver(struct usb_device *device,
615 unsigned int interface, int connect)
616{
617 struct usbdevfs_ioctl ctl;
618
619 ctl.ifno = interface;
620 ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
621 ctl.data = NULL;
622 return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
623}
624
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800625int usb_device_set_configuration(struct usb_device *device, int configuration)
626{
627 return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration);
628}
629
630int usb_device_set_interface(struct usb_device *device, unsigned int interface,
631 unsigned int alt_setting)
632{
633 struct usbdevfs_setinterface ctl;
634
635 ctl.interface = interface;
636 ctl.altsetting = alt_setting;
637 return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl);
638}
639
Mike Lockwood120b57a2011-01-27 10:46:19 -0800640int usb_device_control_transfer(struct usb_device *device,
641 int requestType,
642 int request,
643 int value,
644 int index,
645 void* buffer,
646 int length,
647 unsigned int timeout)
648{
649 struct usbdevfs_ctrltransfer ctrl;
650
651 // this usually requires read/write permission
652 if (!usb_device_reopen_writeable(device))
653 return -1;
654
655 memset(&ctrl, 0, sizeof(ctrl));
656 ctrl.bRequestType = requestType;
657 ctrl.bRequest = request;
658 ctrl.wValue = value;
659 ctrl.wIndex = index;
660 ctrl.wLength = length;
661 ctrl.data = buffer;
662 ctrl.timeout = timeout;
663 return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
664}
665
666int usb_device_bulk_transfer(struct usb_device *device,
667 int endpoint,
668 void* buffer,
Philip P. Moltmann9879bb22016-09-20 14:11:26 -0700669 unsigned int length,
Mike Lockwood120b57a2011-01-27 10:46:19 -0800670 unsigned int timeout)
671{
672 struct usbdevfs_bulktransfer ctrl;
673
674 memset(&ctrl, 0, sizeof(ctrl));
675 ctrl.ep = endpoint;
676 ctrl.len = length;
677 ctrl.data = buffer;
678 ctrl.timeout = timeout;
679 return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
680}
681
Keun-young Parkf6411fa2016-01-12 18:22:36 -0800682int usb_device_reset(struct usb_device *device)
683{
684 return ioctl(device->fd, USBDEVFS_RESET);
685}
686
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500687struct usb_request *usb_request_new(struct usb_device *dev,
688 const struct usb_endpoint_descriptor *ep_desc)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400689{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500690 struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
691 if (!urb)
692 return NULL;
693
694 if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
695 urb->type = USBDEVFS_URB_TYPE_BULK;
696 else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
697 urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
698 else {
699 D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
700 free(urb);
701 return NULL;
702 }
703 urb->endpoint = ep_desc->bEndpointAddress;
704
705 struct usb_request *req = calloc(1, sizeof(struct usb_request));
706 if (!req) {
707 free(urb);
708 return NULL;
709 }
710
711 req->dev = dev;
712 req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
713 req->private_data = urb;
Mike Lockwoodb5d68a32011-02-14 08:05:40 -0500714 req->endpoint = urb->endpoint;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500715 urb->usercontext = req;
716
717 return req;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400718}
719
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500720void usb_request_free(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400721{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500722 free(req->private_data);
723 free(req);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400724}
725
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500726int usb_request_queue(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400727{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500728 struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400729 int res;
730
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400731 urb->status = -1;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500732 urb->buffer = req->buffer;
Jerry Zhang3be61d32018-02-06 18:25:44 -0800733 urb->buffer_length = req->buffer_length;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400734
735 do {
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500736 res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400737 } while((res < 0) && (errno == EINTR));
738
739 return res;
740}
741
Philip P. Moltmann36952852016-10-17 16:57:43 -0700742struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400743{
Philip P. Moltmann36952852016-10-17 16:57:43 -0700744 // Poll until a request becomes available if there is a timeout
745 if (timeoutMillis > 0) {
746 struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400747
Philip P. Moltmann36952852016-10-17 16:57:43 -0700748 int res = poll(&p, 1, timeoutMillis);
749
750 if (res != 1 || p.revents != POLLOUT) {
751 D("[ poll - event %d, error %d]\n", p.revents, errno);
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500752 return NULL;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400753 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400754 }
Philip P. Moltmann36952852016-10-17 16:57:43 -0700755
756 // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
757 // two threads are reading usb requests at the same time and only a single request is available.
758 struct usbdevfs_urb *urb = NULL;
759 int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
760 USBDEVFS_REAPURBNDELAY, &urb));
761 D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
762
763 if (res < 0) {
764 D("[ reap urb - error %d]\n", errno);
765 return NULL;
766 } else {
767 D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
768
769 struct usb_request *req = (struct usb_request*)urb->usercontext;
770 req->actual_length = urb->actual_length;
771
772 return req;
773 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400774}
775
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500776int usb_request_cancel(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400777{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500778 struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
Badhri Jagan Sridharanef4087b2014-08-06 12:34:30 -0700779 return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400780}