blob: 07d60e912fdcab70a30311b53ad8871f73ad51ff [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
Mike Lockwoodc4c00d82011-03-12 12:25:11 -050067// From drivers/usb/core/devio.c
68// I don't know why this isn't in a kernel header
69#define MAX_USBFS_BUFFER_SIZE 16384
Mike Lockwood30ff2c72010-05-09 16:23:47 -040070
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020071#define MAX_USBFS_WD_COUNT 10
72
Mike Lockwood6ac3aa12010-05-25 08:10:02 -040073struct usb_host_context {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +020074 int fd;
75 usb_device_added_cb cb_added;
76 usb_device_removed_cb cb_removed;
77 void *data;
78 int wds[MAX_USBFS_WD_COUNT];
79 int wdd;
Ziv Hendela306ced2013-08-07 19:29:17 +030080 int wddbus;
Mike Lockwood6ac3aa12010-05-25 08:10:02 -040081};
82
Paul McLeanbaea1bd2017-11-06 10:22:51 -070083#define MAX_DESCRIPTORS_LENGTH 4096
84
Mike Lockwood30ff2c72010-05-09 16:23:47 -040085struct usb_device {
86 char dev_name[64];
Paul McLeanbaea1bd2017-11-06 10:22:51 -070087 unsigned char desc[MAX_DESCRIPTORS_LENGTH];
Mike Lockwood30ff2c72010-05-09 16:23:47 -040088 int desc_length;
89 int fd;
90 int writeable;
91};
92
Mike Lockwood30ff2c72010-05-09 16:23:47 -040093static inline int badname(const char *name)
94{
95 while(*name) {
96 if(!isdigit(*name++)) return 1;
97 }
98 return 0;
99}
100
Benoit Goby6cc883c2012-07-31 19:22:06 -0700101static int find_existing_devices_bus(char *busname,
102 usb_device_added_cb added_cb,
103 void *client_data)
104{
105 char devname[32];
106 DIR *devdir;
107 struct dirent *de;
108 int done = 0;
109
110 devdir = opendir(busname);
111 if(devdir == 0) return 0;
112
113 while ((de = readdir(devdir)) && !done) {
114 if(badname(de->d_name)) continue;
115
116 snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
117 done = added_cb(devname, client_data);
118 } // end of devdir while
119 closedir(devdir);
120
121 return done;
122}
123
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400124/* returns true if one of the callbacks indicates we are done */
125static int find_existing_devices(usb_device_added_cb added_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400126 void *client_data)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400127{
Benoit Goby6cc883c2012-07-31 19:22:06 -0700128 char busname[32];
129 DIR *busdir;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400130 struct dirent *de;
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400131 int done = 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400132
133 busdir = opendir(USB_FS_DIR);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700134 if(busdir == 0) return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400135
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400136 while ((de = readdir(busdir)) != 0 && !done) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400137 if(badname(de->d_name)) continue;
138
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200139 snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
Benoit Goby6cc883c2012-07-31 19:22:06 -0700140 done = find_existing_devices_bus(busname, added_cb,
141 client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200142 } //end of busdir while
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400143 closedir(busdir);
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400144
145 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400146}
147
Benoit Gobyf4de0782012-08-01 18:54:02 -0700148static void watch_existing_subdirs(struct usb_host_context *context,
149 int *wds, int wd_count)
150{
151 char path[100];
152 int i, ret;
153
154 wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
155 if (wds[0] < 0)
156 return;
157
158 /* watch existing subdirectories of USB_FS_DIR */
159 for (i = 1; i < wd_count; i++) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200160 snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700161 ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
162 if (ret >= 0)
163 wds[i] = ret;
164 }
165}
166
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400167struct usb_host_context *usb_host_init()
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400168{
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400169 struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
170 if (!context) {
171 fprintf(stderr, "out of memory in usb_host_context\n");
172 return NULL;
173 }
174 context->fd = inotify_init();
175 if (context->fd < 0) {
176 fprintf(stderr, "inotify_init failed\n");
177 free(context);
178 return NULL;
179 }
180 return context;
181}
182
183void usb_host_cleanup(struct usb_host_context *context)
184{
185 close(context->fd);
186 free(context);
187}
188
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200189int usb_host_get_fd(struct usb_host_context *context)
190{
191 return context->fd;
192} /* usb_host_get_fd() */
193
194int usb_host_load(struct usb_host_context *context,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400195 usb_device_added_cb added_cb,
196 usb_device_removed_cb removed_cb,
Mike Lockwooda8055192010-07-19 20:15:15 -0400197 usb_discovery_done_cb discovery_done_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400198 void *client_data)
199{
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200200 int done = 0;
201 int i;
202
203 context->cb_added = added_cb;
204 context->cb_removed = removed_cb;
205 context->data = client_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400206
207 D("Created device discovery thread\n");
208
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400209 /* watch for files added and deleted within USB_FS_DIR */
Ziv Hendela306ced2013-08-07 19:29:17 +0300210 context->wddbus = -1;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200211 for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
212 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700213
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400214 /* watch the root for new subdirectories */
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200215 context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
216 if (context->wdd < 0) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400217 fprintf(stderr, "inotify_add_watch failed\n");
Mike Lockwoode8849d12010-07-20 16:31:42 -0400218 if (discovery_done_cb)
219 discovery_done_cb(client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200220 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400221 }
222
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200223 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400224
225 /* check for existing devices first, after we have inotify set up */
Benoit Goby6cc883c2012-07-31 19:22:06 -0700226 done = find_existing_devices(added_cb, client_data);
Mike Lockwooda8055192010-07-19 20:15:15 -0400227 if (discovery_done_cb)
228 done |= discovery_done_cb(client_data);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400229
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200230 return done;
231} /* usb_host_load() */
232
233int usb_host_read_event(struct usb_host_context *context)
234{
235 struct inotify_event* event;
236 char event_buf[512];
237 char path[100];
238 int i, ret, done = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200239 int offset = 0;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200240 int wd;
241
242 ret = read(context->fd, event_buf, sizeof(event_buf));
243 if (ret >= (int)sizeof(struct inotify_event)) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300244 while (offset < ret && !done) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200245 event = (struct inotify_event*)&event_buf[offset];
246 done = 0;
247 wd = event->wd;
248 if (wd == context->wdd) {
249 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300250 context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
251 if (context->wddbus < 0) {
252 done = 1;
253 } else {
254 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
255 done = find_existing_devices(context->cb_added, context->data);
256 }
257 }
258 } else if (wd == context->wddbus) {
259 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200260 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
261 done = find_existing_devices(context->cb_added, context->data);
Ziv Hendela306ced2013-08-07 19:29:17 +0300262 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200263 for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
264 if (context->wds[i] >= 0) {
265 inotify_rm_watch(context->fd, context->wds[i]);
266 context->wds[i] = -1;
267 }
268 }
269 }
270 } else if (wd == context->wds[0]) {
271 i = atoi(event->name);
272 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
273 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
274 "new" : "gone", path, i);
275 if (i > 0 && i < MAX_USBFS_WD_COUNT) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800276 int local_ret = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200277 if (event->mask & IN_CREATE) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800278 local_ret = inotify_add_watch(context->fd, path,
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200279 IN_CREATE | IN_DELETE);
Bo Huang3c1d7b32014-01-21 14:25:22 +0800280 if (local_ret >= 0)
281 context->wds[i] = local_ret;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200282 done = find_existing_devices_bus(path, context->cb_added,
283 context->data);
284 } else if (event->mask & IN_DELETE) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200285 inotify_rm_watch(context->fd, context->wds[i]);
286 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700287 }
288 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200289 } else {
290 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
291 if (wd == context->wds[i]) {
292 snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
293 if (event->mask == IN_CREATE) {
294 D("new device %s\n", path);
295 done = context->cb_added(path, context->data);
296 } else if (event->mask == IN_DELETE) {
297 D("gone device %s\n", path);
298 done = context->cb_removed(path, context->data);
299 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400300 }
301 }
302 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200303
304 offset += sizeof(struct inotify_event) + event->len;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400305 }
306 }
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200307
308 return done;
309} /* usb_host_read_event() */
310
311void usb_host_run(struct usb_host_context *context,
312 usb_device_added_cb added_cb,
313 usb_device_removed_cb removed_cb,
314 usb_discovery_done_cb discovery_done_cb,
315 void *client_data)
316{
317 int done;
318
319 done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
320
321 while (!done) {
322
323 done = usb_host_read_event(context);
324 }
325} /* usb_host_run() */
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400326
327struct usb_device *usb_device_open(const char *dev_name)
328{
Andrew Chant3af9e402017-11-01 17:32:35 -0700329 int fd, attempts, writeable = 1;
330 const int SLEEP_BETWEEN_ATTEMPTS_US = 100000; /* 100 ms */
331 const int64_t MAX_ATTEMPTS = 10; /* 1s */
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800332 D("usb_device_open %s\n", dev_name);
333
Andrew Chant3af9e402017-11-01 17:32:35 -0700334 /* Hack around waiting for permissions to be set on the USB device node.
335 * Should really be a timeout instead of attempt count, and should REALLY
336 * be triggered by the perm change via inotify rather than polling.
337 */
338 for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) {
339 if (access(dev_name, R_OK | W_OK) == 0) {
340 writeable = 1;
341 break;
342 } else {
343 if (access(dev_name, R_OK) == 0) {
344 /* double check that write permission didn't just come along too! */
345 writeable = (access(dev_name, R_OK | W_OK) == 0);
346 break;
347 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400348 }
Andrew Chant3af9e402017-11-01 17:32:35 -0700349 /* not writeable or readable - sleep and try again. */
350 D("usb_device_open no access sleeping\n");
351 usleep(SLEEP_BETWEEN_ATTEMPTS_US);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400352 }
353
Andrew Chant3af9e402017-11-01 17:32:35 -0700354 if (writeable) {
355 fd = open(dev_name, O_RDWR);
356 } else {
357 fd = open(dev_name, O_RDONLY);
358 }
359 D("usb_device_open open returned %d writeable %d errno %d\n", fd, writeable, errno);
360 if (fd < 0) return NULL;
361
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800362 struct usb_device* result = usb_device_new(dev_name, fd);
363 if (result)
364 result->writeable = writeable;
365 return result;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400366}
367
368void usb_device_close(struct usb_device *device)
369{
370 close(device->fd);
371 free(device);
372}
373
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800374struct usb_device *usb_device_new(const char *dev_name, int fd)
375{
376 struct usb_device *device = calloc(1, sizeof(struct usb_device));
377 int length;
378
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800379 D("usb_device_new %s fd: %d\n", dev_name, fd);
380
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800381 if (lseek(fd, 0, SEEK_SET) != 0)
382 goto failed;
383 length = read(fd, device->desc, sizeof(device->desc));
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800384 D("usb_device_new read returned %d errno %d\n", length, errno);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800385 if (length < 0)
386 goto failed;
387
Mike Lockwood93aff722010-12-15 12:58:04 -0800388 strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800389 device->fd = fd;
390 device->desc_length = length;
391 // assume we are writeable, since usb_device_get_fd will only return writeable fds
392 device->writeable = 1;
393 return device;
394
395failed:
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700396 // TODO It would be more appropriate to have callers do this
397 // since this function doesn't "own" this file descriptor.
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800398 close(fd);
399 free(device);
400 return NULL;
401}
402
403static int usb_device_reopen_writeable(struct usb_device *device)
404{
405 if (device->writeable)
406 return 1;
407
408 int fd = open(device->dev_name, O_RDWR);
409 if (fd >= 0) {
410 close(device->fd);
411 device->fd = fd;
412 device->writeable = 1;
413 return 1;
414 }
415 D("usb_device_reopen_writeable failed errno %d\n", errno);
416 return 0;
417}
418
419int usb_device_get_fd(struct usb_device *device)
420{
421 if (!usb_device_reopen_writeable(device))
422 return -1;
423 return device->fd;
424}
425
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400426const char* usb_device_get_name(struct usb_device *device)
427{
428 return device->dev_name;
429}
430
Mike Lockwood203f1022010-05-27 10:12:03 -0400431int usb_device_get_unique_id(struct usb_device *device)
432{
433 int bus = 0, dev = 0;
434 sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
435 return bus * 1000 + dev;
436}
437
Mike Lockwood07eb4af2010-07-27 19:05:33 -0400438int usb_device_get_unique_id_from_name(const char* name)
439{
440 int bus = 0, dev = 0;
441 sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
442 return bus * 1000 + dev;
443}
444
Mike Lockwood7d700f82010-12-29 08:47:29 -0500445char* usb_device_get_name_from_unique_id(int id)
446{
447 int bus = id / 1000;
448 int dev = id % 1000;
449 char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
450 snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
451 return result;
452}
453
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400454uint16_t usb_device_get_vendor_id(struct usb_device *device)
455{
456 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
457 return __le16_to_cpu(desc->idVendor);
458}
459
460uint16_t usb_device_get_product_id(struct usb_device *device)
461{
462 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
463 return __le16_to_cpu(desc->idProduct);
464}
465
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700466const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device* device) {
Mike Lockwood50372072010-12-13 10:15:25 -0800467 return (struct usb_device_descriptor*)device->desc;
468}
469
Paul McLeanbaea1bd2017-11-06 10:22:51 -0700470size_t usb_device_get_descriptors_length(const struct usb_device* device) {
471 return device->desc_length;
472}
473
474const unsigned char* usb_device_get_raw_descriptors(const struct usb_device* device) {
475 return device->desc;
476}
477
Andrew Chant169742e2017-12-07 16:51:49 -0800478/* Returns a USB descriptor string for the given string ID.
479 * Return value: < 0 on error. 0 on success.
480 * The string is returned in ucs2_out in USB-native UCS-2 encoding.
481 *
482 * parameters:
483 * id - the string descriptor index.
484 * timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
485 * ucs2_out - Must point to null on call.
486 * Will be filled in with a buffer on success.
487 * If this is non-null on return, it must be free()d.
488 * response_size - size, in bytes, of ucs-2 string in ucs2_out.
489 * The size isn't guaranteed to include null termination.
490 * Call free() to free the result when you are done with it.
491 */
492int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
493 size_t* response_size) {
Mike Lockwood0dd1aab2015-06-18 13:38:31 -0700494 __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
Andrew Chant169742e2017-12-07 16:51:49 -0800495 char response[MAX_STRING_DESCRIPTOR_LENGTH];
496 int result;
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400497 int languageCount = 0;
498
Andrew Chant169742e2017-12-07 16:51:49 -0800499 if (id == 0) return -1;
500 if (*ucs2_out != NULL) return -1;
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800501
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400502 memset(languages, 0, sizeof(languages));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400503
504 // read list of supported languages
Mike Lockwood120b57a2011-01-27 10:46:19 -0800505 result = usb_device_control_transfer(device,
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400506 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700507 (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
508 timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400509 if (result > 0)
510 languageCount = (result - 2) / 2;
511
Andrew Chant169742e2017-12-07 16:51:49 -0800512 for (int i = 1; i <= languageCount; i++) {
513 memset(response, 0, sizeof(response));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400514
Andrew Chant169742e2017-12-07 16:51:49 -0800515 result = usb_device_control_transfer(
516 device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
517 (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
518 if (result >= 2) { // string contents begin at offset 2.
519 int descriptor_len = result - 2;
520 char* out = malloc(descriptor_len + 3);
521 if (out == NULL) {
522 return -1;
523 }
524 memcpy(out, response + 2, descriptor_len);
525 // trail with three additional NULLs, so that there's guaranteed
526 // to be a UCS-2 NULL character beyond whatever USB returned.
527 // The returned string length is still just what USB returned.
528 memset(out + descriptor_len, '\0', 3);
529 *ucs2_out = (void*)out;
530 *response_size = descriptor_len;
531 return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400532 }
533 }
Andrew Chant169742e2017-12-07 16:51:49 -0800534 return -1;
535}
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400536
Andrew Chant169742e2017-12-07 16:51:49 -0800537/* Warning: previously this blindly returned the lower 8 bits of
538 * every UCS-2 character in a USB descriptor. Now it will replace
539 * values > 127 with ascii '?'.
540 */
541char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
542 char* ascii_string = NULL;
543 size_t raw_string_len = 0;
544 size_t i;
545 if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
546 return NULL;
547 if (ascii_string == NULL) return NULL;
548 for (i = 0; i < raw_string_len / 2; ++i) {
549 // wire format for USB is always little-endian.
550 char lower = ascii_string[2 * i];
551 char upper = ascii_string[2 * i + 1];
552 if (upper || (lower & 0x80)) {
553 ascii_string[i] = '?';
554 } else {
555 ascii_string[i] = lower;
556 }
557 }
558 ascii_string[i] = '\0';
559 return ascii_string;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400560}
561
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700562char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400563{
564 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700565 return usb_device_get_string(device, desc->iManufacturer, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400566}
567
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700568char* usb_device_get_product_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400569{
570 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700571 return usb_device_get_string(device, desc->iProduct, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400572}
573
Mike Lockwoodf68600a2015-04-29 13:04:10 -0700574int usb_device_get_version(struct usb_device *device)
575{
576 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
577 return desc->bcdUSB;
578}
579
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700580char* usb_device_get_serial(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400581{
582 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700583 return usb_device_get_string(device, desc->iSerialNumber, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400584}
585
586int usb_device_is_writeable(struct usb_device *device)
587{
588 return device->writeable;
589}
590
591void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
592{
593 iter->config = device->desc;
594 iter->config_end = device->desc + device->desc_length;
595 iter->curr_desc = device->desc;
596}
597
598struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
599{
600 struct usb_descriptor_header* next;
601 if (iter->curr_desc >= iter->config_end)
602 return NULL;
603 next = (struct usb_descriptor_header*)iter->curr_desc;
604 iter->curr_desc += next->bLength;
605 return next;
606}
607
608int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
609{
610 return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
611}
612
613int usb_device_release_interface(struct usb_device *device, unsigned int interface)
614{
615 return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
616}
617
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800618int usb_device_connect_kernel_driver(struct usb_device *device,
619 unsigned int interface, int connect)
620{
621 struct usbdevfs_ioctl ctl;
622
623 ctl.ifno = interface;
624 ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
625 ctl.data = NULL;
626 return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
627}
628
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800629int usb_device_set_configuration(struct usb_device *device, int configuration)
630{
631 return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration);
632}
633
634int usb_device_set_interface(struct usb_device *device, unsigned int interface,
635 unsigned int alt_setting)
636{
637 struct usbdevfs_setinterface ctl;
638
639 ctl.interface = interface;
640 ctl.altsetting = alt_setting;
641 return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl);
642}
643
Mike Lockwood120b57a2011-01-27 10:46:19 -0800644int usb_device_control_transfer(struct usb_device *device,
645 int requestType,
646 int request,
647 int value,
648 int index,
649 void* buffer,
650 int length,
651 unsigned int timeout)
652{
653 struct usbdevfs_ctrltransfer ctrl;
654
655 // this usually requires read/write permission
656 if (!usb_device_reopen_writeable(device))
657 return -1;
658
659 memset(&ctrl, 0, sizeof(ctrl));
660 ctrl.bRequestType = requestType;
661 ctrl.bRequest = request;
662 ctrl.wValue = value;
663 ctrl.wIndex = index;
664 ctrl.wLength = length;
665 ctrl.data = buffer;
666 ctrl.timeout = timeout;
667 return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
668}
669
670int usb_device_bulk_transfer(struct usb_device *device,
671 int endpoint,
672 void* buffer,
Philip P. Moltmann9879bb22016-09-20 14:11:26 -0700673 unsigned int length,
Mike Lockwood120b57a2011-01-27 10:46:19 -0800674 unsigned int timeout)
675{
676 struct usbdevfs_bulktransfer ctrl;
677
Mike Lockwoodc4c00d82011-03-12 12:25:11 -0500678 // need to limit request size to avoid EINVAL
679 if (length > MAX_USBFS_BUFFER_SIZE)
680 length = MAX_USBFS_BUFFER_SIZE;
681
Mike Lockwood120b57a2011-01-27 10:46:19 -0800682 memset(&ctrl, 0, sizeof(ctrl));
683 ctrl.ep = endpoint;
684 ctrl.len = length;
685 ctrl.data = buffer;
686 ctrl.timeout = timeout;
687 return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
688}
689
Keun-young Parkf6411fa2016-01-12 18:22:36 -0800690int usb_device_reset(struct usb_device *device)
691{
692 return ioctl(device->fd, USBDEVFS_RESET);
693}
694
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500695struct usb_request *usb_request_new(struct usb_device *dev,
696 const struct usb_endpoint_descriptor *ep_desc)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400697{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500698 struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
699 if (!urb)
700 return NULL;
701
702 if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
703 urb->type = USBDEVFS_URB_TYPE_BULK;
704 else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
705 urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
706 else {
707 D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
708 free(urb);
709 return NULL;
710 }
711 urb->endpoint = ep_desc->bEndpointAddress;
712
713 struct usb_request *req = calloc(1, sizeof(struct usb_request));
714 if (!req) {
715 free(urb);
716 return NULL;
717 }
718
719 req->dev = dev;
720 req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
721 req->private_data = urb;
Mike Lockwoodb5d68a32011-02-14 08:05:40 -0500722 req->endpoint = urb->endpoint;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500723 urb->usercontext = req;
724
725 return req;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400726}
727
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500728void usb_request_free(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400729{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500730 free(req->private_data);
731 free(req);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400732}
733
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500734int usb_request_queue(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400735{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500736 struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400737 int res;
738
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400739 urb->status = -1;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500740 urb->buffer = req->buffer;
Mike Lockwoodc4c00d82011-03-12 12:25:11 -0500741 // need to limit request size to avoid EINVAL
742 if (req->buffer_length > MAX_USBFS_BUFFER_SIZE)
743 urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
744 else
745 urb->buffer_length = req->buffer_length;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400746
747 do {
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500748 res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400749 } while((res < 0) && (errno == EINTR));
750
751 return res;
752}
753
Philip P. Moltmann36952852016-10-17 16:57:43 -0700754struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400755{
Philip P. Moltmann36952852016-10-17 16:57:43 -0700756 // Poll until a request becomes available if there is a timeout
757 if (timeoutMillis > 0) {
758 struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400759
Philip P. Moltmann36952852016-10-17 16:57:43 -0700760 int res = poll(&p, 1, timeoutMillis);
761
762 if (res != 1 || p.revents != POLLOUT) {
763 D("[ poll - event %d, error %d]\n", p.revents, errno);
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500764 return NULL;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400765 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400766 }
Philip P. Moltmann36952852016-10-17 16:57:43 -0700767
768 // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
769 // two threads are reading usb requests at the same time and only a single request is available.
770 struct usbdevfs_urb *urb = NULL;
771 int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
772 USBDEVFS_REAPURBNDELAY, &urb));
773 D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
774
775 if (res < 0) {
776 D("[ reap urb - error %d]\n", errno);
777 return NULL;
778 } else {
779 D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
780
781 struct usb_request *req = (struct usb_request*)urb->usercontext;
782 req->actual_length = urb->actual_length;
783
784 return req;
785 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400786}
787
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500788int usb_request_cancel(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400789{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500790 struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
Badhri Jagan Sridharanef4087b2014-08-06 12:34:30 -0700791 return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400792}