blob: cb8d430db5be8606d7864a0abce538d216e17639 [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
Mike Lockwood30ff2c72010-05-09 16:23:47 -040079struct usb_device {
80 char dev_name[64];
Mike Lockwoodec9e7b12011-01-22 09:17:07 -080081 unsigned char desc[4096];
Mike Lockwood30ff2c72010-05-09 16:23:47 -040082 int desc_length;
83 int fd;
84 int writeable;
85};
86
Mike Lockwood30ff2c72010-05-09 16:23:47 -040087static inline int badname(const char *name)
88{
89 while(*name) {
90 if(!isdigit(*name++)) return 1;
91 }
92 return 0;
93}
94
Benoit Goby6cc883c2012-07-31 19:22:06 -070095static int find_existing_devices_bus(char *busname,
96 usb_device_added_cb added_cb,
97 void *client_data)
98{
99 char devname[32];
100 DIR *devdir;
101 struct dirent *de;
102 int done = 0;
103
104 devdir = opendir(busname);
105 if(devdir == 0) return 0;
106
107 while ((de = readdir(devdir)) && !done) {
108 if(badname(de->d_name)) continue;
109
110 snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
111 done = added_cb(devname, client_data);
112 } // end of devdir while
113 closedir(devdir);
114
115 return done;
116}
117
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400118/* returns true if one of the callbacks indicates we are done */
119static int find_existing_devices(usb_device_added_cb added_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400120 void *client_data)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400121{
Benoit Goby6cc883c2012-07-31 19:22:06 -0700122 char busname[32];
123 DIR *busdir;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400124 struct dirent *de;
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400125 int done = 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400126
127 busdir = opendir(USB_FS_DIR);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700128 if(busdir == 0) return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400129
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400130 while ((de = readdir(busdir)) != 0 && !done) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400131 if(badname(de->d_name)) continue;
132
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200133 snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
Benoit Goby6cc883c2012-07-31 19:22:06 -0700134 done = find_existing_devices_bus(busname, added_cb,
135 client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200136 } //end of busdir while
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400137 closedir(busdir);
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400138
139 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400140}
141
Benoit Gobyf4de0782012-08-01 18:54:02 -0700142static void watch_existing_subdirs(struct usb_host_context *context,
143 int *wds, int wd_count)
144{
145 char path[100];
146 int i, ret;
147
148 wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
149 if (wds[0] < 0)
150 return;
151
152 /* watch existing subdirectories of USB_FS_DIR */
153 for (i = 1; i < wd_count; i++) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200154 snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700155 ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
156 if (ret >= 0)
157 wds[i] = ret;
158 }
159}
160
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400161struct usb_host_context *usb_host_init()
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400162{
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400163 struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
164 if (!context) {
165 fprintf(stderr, "out of memory in usb_host_context\n");
166 return NULL;
167 }
168 context->fd = inotify_init();
169 if (context->fd < 0) {
170 fprintf(stderr, "inotify_init failed\n");
171 free(context);
172 return NULL;
173 }
174 return context;
175}
176
177void usb_host_cleanup(struct usb_host_context *context)
178{
179 close(context->fd);
180 free(context);
181}
182
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200183int usb_host_get_fd(struct usb_host_context *context)
184{
185 return context->fd;
186} /* usb_host_get_fd() */
187
188int usb_host_load(struct usb_host_context *context,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400189 usb_device_added_cb added_cb,
190 usb_device_removed_cb removed_cb,
Mike Lockwooda8055192010-07-19 20:15:15 -0400191 usb_discovery_done_cb discovery_done_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400192 void *client_data)
193{
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200194 int done = 0;
195 int i;
196
197 context->cb_added = added_cb;
198 context->cb_removed = removed_cb;
199 context->data = client_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400200
201 D("Created device discovery thread\n");
202
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400203 /* watch for files added and deleted within USB_FS_DIR */
Ziv Hendela306ced2013-08-07 19:29:17 +0300204 context->wddbus = -1;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200205 for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
206 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700207
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400208 /* watch the root for new subdirectories */
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200209 context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
210 if (context->wdd < 0) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400211 fprintf(stderr, "inotify_add_watch failed\n");
Mike Lockwoode8849d12010-07-20 16:31:42 -0400212 if (discovery_done_cb)
213 discovery_done_cb(client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200214 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400215 }
216
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200217 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400218
219 /* check for existing devices first, after we have inotify set up */
Benoit Goby6cc883c2012-07-31 19:22:06 -0700220 done = find_existing_devices(added_cb, client_data);
Mike Lockwooda8055192010-07-19 20:15:15 -0400221 if (discovery_done_cb)
222 done |= discovery_done_cb(client_data);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400223
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200224 return done;
225} /* usb_host_load() */
226
227int usb_host_read_event(struct usb_host_context *context)
228{
229 struct inotify_event* event;
230 char event_buf[512];
231 char path[100];
232 int i, ret, done = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200233 int offset = 0;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200234 int wd;
235
236 ret = read(context->fd, event_buf, sizeof(event_buf));
237 if (ret >= (int)sizeof(struct inotify_event)) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300238 while (offset < ret && !done) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200239 event = (struct inotify_event*)&event_buf[offset];
240 done = 0;
241 wd = event->wd;
242 if (wd == context->wdd) {
243 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300244 context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
245 if (context->wddbus < 0) {
246 done = 1;
247 } else {
248 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
249 done = find_existing_devices(context->cb_added, context->data);
250 }
251 }
252 } else if (wd == context->wddbus) {
253 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200254 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
255 done = find_existing_devices(context->cb_added, context->data);
Ziv Hendela306ced2013-08-07 19:29:17 +0300256 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200257 for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
258 if (context->wds[i] >= 0) {
259 inotify_rm_watch(context->fd, context->wds[i]);
260 context->wds[i] = -1;
261 }
262 }
263 }
264 } else if (wd == context->wds[0]) {
265 i = atoi(event->name);
266 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
267 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
268 "new" : "gone", path, i);
269 if (i > 0 && i < MAX_USBFS_WD_COUNT) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800270 int local_ret = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200271 if (event->mask & IN_CREATE) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800272 local_ret = inotify_add_watch(context->fd, path,
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200273 IN_CREATE | IN_DELETE);
Bo Huang3c1d7b32014-01-21 14:25:22 +0800274 if (local_ret >= 0)
275 context->wds[i] = local_ret;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200276 done = find_existing_devices_bus(path, context->cb_added,
277 context->data);
278 } else if (event->mask & IN_DELETE) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200279 inotify_rm_watch(context->fd, context->wds[i]);
280 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700281 }
282 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200283 } else {
284 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
285 if (wd == context->wds[i]) {
286 snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
287 if (event->mask == IN_CREATE) {
288 D("new device %s\n", path);
289 done = context->cb_added(path, context->data);
290 } else if (event->mask == IN_DELETE) {
291 D("gone device %s\n", path);
292 done = context->cb_removed(path, context->data);
293 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400294 }
295 }
296 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200297
298 offset += sizeof(struct inotify_event) + event->len;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400299 }
300 }
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200301
302 return done;
303} /* usb_host_read_event() */
304
305void usb_host_run(struct usb_host_context *context,
306 usb_device_added_cb added_cb,
307 usb_device_removed_cb removed_cb,
308 usb_discovery_done_cb discovery_done_cb,
309 void *client_data)
310{
311 int done;
312
313 done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
314
315 while (!done) {
316
317 done = usb_host_read_event(context);
318 }
319} /* usb_host_run() */
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400320
321struct usb_device *usb_device_open(const char *dev_name)
322{
Andrew Chant3af9e402017-11-01 17:32:35 -0700323 int fd, attempts, writeable = 1;
324 const int SLEEP_BETWEEN_ATTEMPTS_US = 100000; /* 100 ms */
325 const int64_t MAX_ATTEMPTS = 10; /* 1s */
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800326 D("usb_device_open %s\n", dev_name);
327
Andrew Chant3af9e402017-11-01 17:32:35 -0700328 /* Hack around waiting for permissions to be set on the USB device node.
329 * Should really be a timeout instead of attempt count, and should REALLY
330 * be triggered by the perm change via inotify rather than polling.
331 */
332 for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) {
333 if (access(dev_name, R_OK | W_OK) == 0) {
334 writeable = 1;
335 break;
336 } else {
337 if (access(dev_name, R_OK) == 0) {
338 /* double check that write permission didn't just come along too! */
339 writeable = (access(dev_name, R_OK | W_OK) == 0);
340 break;
341 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400342 }
Andrew Chant3af9e402017-11-01 17:32:35 -0700343 /* not writeable or readable - sleep and try again. */
344 D("usb_device_open no access sleeping\n");
345 usleep(SLEEP_BETWEEN_ATTEMPTS_US);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400346 }
347
Andrew Chant3af9e402017-11-01 17:32:35 -0700348 if (writeable) {
349 fd = open(dev_name, O_RDWR);
350 } else {
351 fd = open(dev_name, O_RDONLY);
352 }
353 D("usb_device_open open returned %d writeable %d errno %d\n", fd, writeable, errno);
354 if (fd < 0) return NULL;
355
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800356 struct usb_device* result = usb_device_new(dev_name, fd);
357 if (result)
358 result->writeable = writeable;
359 return result;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400360}
361
362void usb_device_close(struct usb_device *device)
363{
364 close(device->fd);
365 free(device);
366}
367
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800368struct usb_device *usb_device_new(const char *dev_name, int fd)
369{
370 struct usb_device *device = calloc(1, sizeof(struct usb_device));
371 int length;
372
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800373 D("usb_device_new %s fd: %d\n", dev_name, fd);
374
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800375 if (lseek(fd, 0, SEEK_SET) != 0)
376 goto failed;
377 length = read(fd, device->desc, sizeof(device->desc));
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800378 D("usb_device_new read returned %d errno %d\n", length, errno);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800379 if (length < 0)
380 goto failed;
381
Mike Lockwood93aff722010-12-15 12:58:04 -0800382 strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800383 device->fd = fd;
384 device->desc_length = length;
385 // assume we are writeable, since usb_device_get_fd will only return writeable fds
386 device->writeable = 1;
387 return device;
388
389failed:
390 close(fd);
391 free(device);
392 return NULL;
393}
394
395static int usb_device_reopen_writeable(struct usb_device *device)
396{
397 if (device->writeable)
398 return 1;
399
400 int fd = open(device->dev_name, O_RDWR);
401 if (fd >= 0) {
402 close(device->fd);
403 device->fd = fd;
404 device->writeable = 1;
405 return 1;
406 }
407 D("usb_device_reopen_writeable failed errno %d\n", errno);
408 return 0;
409}
410
411int usb_device_get_fd(struct usb_device *device)
412{
413 if (!usb_device_reopen_writeable(device))
414 return -1;
415 return device->fd;
416}
417
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400418const char* usb_device_get_name(struct usb_device *device)
419{
420 return device->dev_name;
421}
422
Mike Lockwood203f1022010-05-27 10:12:03 -0400423int usb_device_get_unique_id(struct usb_device *device)
424{
425 int bus = 0, dev = 0;
426 sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
427 return bus * 1000 + dev;
428}
429
Mike Lockwood07eb4af2010-07-27 19:05:33 -0400430int usb_device_get_unique_id_from_name(const char* name)
431{
432 int bus = 0, dev = 0;
433 sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
434 return bus * 1000 + dev;
435}
436
Mike Lockwood7d700f82010-12-29 08:47:29 -0500437char* usb_device_get_name_from_unique_id(int id)
438{
439 int bus = id / 1000;
440 int dev = id % 1000;
441 char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
442 snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
443 return result;
444}
445
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400446uint16_t usb_device_get_vendor_id(struct usb_device *device)
447{
448 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
449 return __le16_to_cpu(desc->idVendor);
450}
451
452uint16_t usb_device_get_product_id(struct usb_device *device)
453{
454 struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
455 return __le16_to_cpu(desc->idProduct);
456}
457
Mike Lockwood50372072010-12-13 10:15:25 -0800458const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device)
459{
460 return (struct usb_device_descriptor*)device->desc;
461}
462
Andrew Chant8ea81012017-12-07 16:51:49 -0800463/* Returns a USB descriptor string for the given string ID.
464 * Return value: < 0 on error. 0 on success.
465 * The string is returned in ucs2_out in USB-native UCS-2 encoding.
466 *
467 * parameters:
468 * id - the string descriptor index.
469 * timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
470 * ucs2_out - Must point to null on call.
471 * Will be filled in with a buffer on success.
472 * If this is non-null on return, it must be free()d.
473 * response_size - size, in bytes, of ucs-2 string in ucs2_out.
474 * The size isn't guaranteed to include null termination.
475 * Call free() to free the result when you are done with it.
476 */
477int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
478 size_t* response_size) {
Mike Lockwood0dd1aab2015-06-18 13:38:31 -0700479 __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
Andrew Chant8ea81012017-12-07 16:51:49 -0800480 char response[MAX_STRING_DESCRIPTOR_LENGTH];
481 int result;
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400482 int languageCount = 0;
483
Andrew Chant8ea81012017-12-07 16:51:49 -0800484 if (id == 0) return -1;
485 if (*ucs2_out != NULL) return -1;
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800486
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400487 memset(languages, 0, sizeof(languages));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400488
489 // read list of supported languages
Mike Lockwood120b57a2011-01-27 10:46:19 -0800490 result = usb_device_control_transfer(device,
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400491 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700492 (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
493 timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400494 if (result > 0)
495 languageCount = (result - 2) / 2;
496
Andrew Chant8ea81012017-12-07 16:51:49 -0800497 for (int i = 1; i <= languageCount; i++) {
498 memset(response, 0, sizeof(response));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400499
Andrew Chant8ea81012017-12-07 16:51:49 -0800500 result = usb_device_control_transfer(
501 device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
502 (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
503 if (result >= 2) { // string contents begin at offset 2.
504 int descriptor_len = result - 2;
505 char* out = malloc(descriptor_len + 3);
506 if (out == NULL) {
507 return -1;
508 }
509 memcpy(out, response + 2, descriptor_len);
510 // trail with three additional NULLs, so that there's guaranteed
511 // to be a UCS-2 NULL character beyond whatever USB returned.
512 // The returned string length is still just what USB returned.
513 memset(out + descriptor_len, '\0', 3);
514 *ucs2_out = (void*)out;
515 *response_size = descriptor_len;
516 return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400517 }
518 }
Andrew Chant8ea81012017-12-07 16:51:49 -0800519 return -1;
520}
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400521
Andrew Chant8ea81012017-12-07 16:51:49 -0800522/* Warning: previously this blindly returned the lower 8 bits of
523 * every UCS-2 character in a USB descriptor. Now it will replace
524 * values > 127 with ascii '?'.
525 */
526char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
527 char* ascii_string = NULL;
528 size_t raw_string_len = 0;
529 size_t i;
530 if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
531 return NULL;
532 if (ascii_string == NULL) return NULL;
533 for (i = 0; i < raw_string_len / 2; ++i) {
534 // wire format for USB is always little-endian.
535 char lower = ascii_string[2 * i];
536 char upper = ascii_string[2 * i + 1];
537 if (upper || (lower & 0x80)) {
538 ascii_string[i] = '?';
539 } else {
540 ascii_string[i] = lower;
541 }
542 }
543 ascii_string[i] = '\0';
544 return ascii_string;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400545}
546
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700547char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400548{
549 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700550 return usb_device_get_string(device, desc->iManufacturer, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400551}
552
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700553char* usb_device_get_product_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400554{
555 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700556 return usb_device_get_string(device, desc->iProduct, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400557}
558
Mike Lockwoodf68600a2015-04-29 13:04:10 -0700559int usb_device_get_version(struct usb_device *device)
560{
561 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
562 return desc->bcdUSB;
563}
564
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700565char* usb_device_get_serial(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400566{
567 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700568 return usb_device_get_string(device, desc->iSerialNumber, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400569}
570
571int usb_device_is_writeable(struct usb_device *device)
572{
573 return device->writeable;
574}
575
576void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
577{
578 iter->config = device->desc;
579 iter->config_end = device->desc + device->desc_length;
580 iter->curr_desc = device->desc;
581}
582
583struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
584{
585 struct usb_descriptor_header* next;
586 if (iter->curr_desc >= iter->config_end)
587 return NULL;
588 next = (struct usb_descriptor_header*)iter->curr_desc;
589 iter->curr_desc += next->bLength;
590 return next;
591}
592
593int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
594{
595 return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
596}
597
598int usb_device_release_interface(struct usb_device *device, unsigned int interface)
599{
600 return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
601}
602
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800603int usb_device_connect_kernel_driver(struct usb_device *device,
604 unsigned int interface, int connect)
605{
606 struct usbdevfs_ioctl ctl;
607
608 ctl.ifno = interface;
609 ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
610 ctl.data = NULL;
611 return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
612}
613
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800614int usb_device_set_configuration(struct usb_device *device, int configuration)
615{
616 return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration);
617}
618
619int usb_device_set_interface(struct usb_device *device, unsigned int interface,
620 unsigned int alt_setting)
621{
622 struct usbdevfs_setinterface ctl;
623
624 ctl.interface = interface;
625 ctl.altsetting = alt_setting;
626 return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl);
627}
628
Mike Lockwood120b57a2011-01-27 10:46:19 -0800629int usb_device_control_transfer(struct usb_device *device,
630 int requestType,
631 int request,
632 int value,
633 int index,
634 void* buffer,
635 int length,
636 unsigned int timeout)
637{
638 struct usbdevfs_ctrltransfer ctrl;
639
640 // this usually requires read/write permission
641 if (!usb_device_reopen_writeable(device))
642 return -1;
643
644 memset(&ctrl, 0, sizeof(ctrl));
645 ctrl.bRequestType = requestType;
646 ctrl.bRequest = request;
647 ctrl.wValue = value;
648 ctrl.wIndex = index;
649 ctrl.wLength = length;
650 ctrl.data = buffer;
651 ctrl.timeout = timeout;
652 return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
653}
654
655int usb_device_bulk_transfer(struct usb_device *device,
656 int endpoint,
657 void* buffer,
Philip P. Moltmann9879bb22016-09-20 14:11:26 -0700658 unsigned int length,
Mike Lockwood120b57a2011-01-27 10:46:19 -0800659 unsigned int timeout)
660{
661 struct usbdevfs_bulktransfer ctrl;
662
663 memset(&ctrl, 0, sizeof(ctrl));
664 ctrl.ep = endpoint;
665 ctrl.len = length;
666 ctrl.data = buffer;
667 ctrl.timeout = timeout;
668 return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
669}
670
Keun-young Parkf6411fa2016-01-12 18:22:36 -0800671int usb_device_reset(struct usb_device *device)
672{
673 return ioctl(device->fd, USBDEVFS_RESET);
674}
675
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500676struct usb_request *usb_request_new(struct usb_device *dev,
677 const struct usb_endpoint_descriptor *ep_desc)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400678{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500679 struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
680 if (!urb)
681 return NULL;
682
683 if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
684 urb->type = USBDEVFS_URB_TYPE_BULK;
685 else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
686 urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
687 else {
688 D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
689 free(urb);
690 return NULL;
691 }
692 urb->endpoint = ep_desc->bEndpointAddress;
693
694 struct usb_request *req = calloc(1, sizeof(struct usb_request));
695 if (!req) {
696 free(urb);
697 return NULL;
698 }
699
700 req->dev = dev;
701 req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
702 req->private_data = urb;
Mike Lockwoodb5d68a32011-02-14 08:05:40 -0500703 req->endpoint = urb->endpoint;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500704 urb->usercontext = req;
705
706 return req;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400707}
708
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500709void usb_request_free(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400710{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500711 free(req->private_data);
712 free(req);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400713}
714
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500715int usb_request_queue(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400716{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500717 struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400718 int res;
719
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400720 urb->status = -1;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500721 urb->buffer = req->buffer;
Jerry Zhang3be61d32018-02-06 18:25:44 -0800722 urb->buffer_length = req->buffer_length;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400723
724 do {
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500725 res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400726 } while((res < 0) && (errno == EINTR));
727
728 return res;
729}
730
Philip P. Moltmann36952852016-10-17 16:57:43 -0700731struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400732{
Philip P. Moltmann36952852016-10-17 16:57:43 -0700733 // Poll until a request becomes available if there is a timeout
734 if (timeoutMillis > 0) {
735 struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400736
Philip P. Moltmann36952852016-10-17 16:57:43 -0700737 int res = poll(&p, 1, timeoutMillis);
738
739 if (res != 1 || p.revents != POLLOUT) {
740 D("[ poll - event %d, error %d]\n", p.revents, errno);
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500741 return NULL;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400742 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400743 }
Philip P. Moltmann36952852016-10-17 16:57:43 -0700744
745 // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
746 // two threads are reading usb requests at the same time and only a single request is available.
747 struct usbdevfs_urb *urb = NULL;
748 int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
749 USBDEVFS_REAPURBNDELAY, &urb));
750 D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
751
752 if (res < 0) {
753 D("[ reap urb - error %d]\n", errno);
754 return NULL;
755 } else {
756 D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
757
758 struct usb_request *req = (struct usb_request*)urb->usercontext;
759 req->actual_length = urb->actual_length;
760
761 return req;
762 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400763}
764
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500765int usb_request_cancel(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400766{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500767 struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
Badhri Jagan Sridharanef4087b2014-08-06 12:34:30 -0700768 return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400769}