blob: fa0191bf868094f46eb005aeaf23e25ff2af5b93 [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
Mike Lockwood30ff2c72010-05-09 16:23:47 -040083struct usb_device {
84 char dev_name[64];
Mike Lockwoodec9e7b12011-01-22 09:17:07 -080085 unsigned char desc[4096];
Mike Lockwood30ff2c72010-05-09 16:23:47 -040086 int desc_length;
87 int fd;
88 int writeable;
89};
90
Mike Lockwood30ff2c72010-05-09 16:23:47 -040091static inline int badname(const char *name)
92{
93 while(*name) {
94 if(!isdigit(*name++)) return 1;
95 }
96 return 0;
97}
98
Benoit Goby6cc883c2012-07-31 19:22:06 -070099static int find_existing_devices_bus(char *busname,
100 usb_device_added_cb added_cb,
101 void *client_data)
102{
103 char devname[32];
104 DIR *devdir;
105 struct dirent *de;
106 int done = 0;
107
108 devdir = opendir(busname);
109 if(devdir == 0) return 0;
110
111 while ((de = readdir(devdir)) && !done) {
112 if(badname(de->d_name)) continue;
113
114 snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
115 done = added_cb(devname, client_data);
116 } // end of devdir while
117 closedir(devdir);
118
119 return done;
120}
121
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400122/* returns true if one of the callbacks indicates we are done */
123static int find_existing_devices(usb_device_added_cb added_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400124 void *client_data)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400125{
Benoit Goby6cc883c2012-07-31 19:22:06 -0700126 char busname[32];
127 DIR *busdir;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400128 struct dirent *de;
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400129 int done = 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400130
131 busdir = opendir(USB_FS_DIR);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700132 if(busdir == 0) return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400133
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400134 while ((de = readdir(busdir)) != 0 && !done) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400135 if(badname(de->d_name)) continue;
136
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200137 snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
Benoit Goby6cc883c2012-07-31 19:22:06 -0700138 done = find_existing_devices_bus(busname, added_cb,
139 client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200140 } //end of busdir while
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400141 closedir(busdir);
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400142
143 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400144}
145
Benoit Gobyf4de0782012-08-01 18:54:02 -0700146static void watch_existing_subdirs(struct usb_host_context *context,
147 int *wds, int wd_count)
148{
149 char path[100];
150 int i, ret;
151
152 wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
153 if (wds[0] < 0)
154 return;
155
156 /* watch existing subdirectories of USB_FS_DIR */
157 for (i = 1; i < wd_count; i++) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200158 snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
Benoit Gobyf4de0782012-08-01 18:54:02 -0700159 ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
160 if (ret >= 0)
161 wds[i] = ret;
162 }
163}
164
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400165struct usb_host_context *usb_host_init()
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400166{
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400167 struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
168 if (!context) {
169 fprintf(stderr, "out of memory in usb_host_context\n");
170 return NULL;
171 }
172 context->fd = inotify_init();
173 if (context->fd < 0) {
174 fprintf(stderr, "inotify_init failed\n");
175 free(context);
176 return NULL;
177 }
178 return context;
179}
180
181void usb_host_cleanup(struct usb_host_context *context)
182{
183 close(context->fd);
184 free(context);
185}
186
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200187int usb_host_get_fd(struct usb_host_context *context)
188{
189 return context->fd;
190} /* usb_host_get_fd() */
191
192int usb_host_load(struct usb_host_context *context,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400193 usb_device_added_cb added_cb,
194 usb_device_removed_cb removed_cb,
Mike Lockwooda8055192010-07-19 20:15:15 -0400195 usb_discovery_done_cb discovery_done_cb,
Mike Lockwood7a96ba42010-07-01 11:33:41 -0400196 void *client_data)
197{
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200198 int done = 0;
199 int i;
200
201 context->cb_added = added_cb;
202 context->cb_removed = removed_cb;
203 context->data = client_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400204
205 D("Created device discovery thread\n");
206
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400207 /* watch for files added and deleted within USB_FS_DIR */
Ziv Hendela306ced2013-08-07 19:29:17 +0300208 context->wddbus = -1;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200209 for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
210 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700211
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400212 /* watch the root for new subdirectories */
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200213 context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
214 if (context->wdd < 0) {
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400215 fprintf(stderr, "inotify_add_watch failed\n");
Mike Lockwoode8849d12010-07-20 16:31:42 -0400216 if (discovery_done_cb)
217 discovery_done_cb(client_data);
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200218 return done;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400219 }
220
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200221 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400222
223 /* check for existing devices first, after we have inotify set up */
Benoit Goby6cc883c2012-07-31 19:22:06 -0700224 done = find_existing_devices(added_cb, client_data);
Mike Lockwooda8055192010-07-19 20:15:15 -0400225 if (discovery_done_cb)
226 done |= discovery_done_cb(client_data);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400227
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200228 return done;
229} /* usb_host_load() */
230
231int usb_host_read_event(struct usb_host_context *context)
232{
233 struct inotify_event* event;
234 char event_buf[512];
235 char path[100];
236 int i, ret, done = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200237 int offset = 0;
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200238 int wd;
239
240 ret = read(context->fd, event_buf, sizeof(event_buf));
241 if (ret >= (int)sizeof(struct inotify_event)) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300242 while (offset < ret && !done) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200243 event = (struct inotify_event*)&event_buf[offset];
244 done = 0;
245 wd = event->wd;
246 if (wd == context->wdd) {
247 if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
Ziv Hendela306ced2013-08-07 19:29:17 +0300248 context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
249 if (context->wddbus < 0) {
250 done = 1;
251 } else {
252 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
253 done = find_existing_devices(context->cb_added, context->data);
254 }
255 }
256 } else if (wd == context->wddbus) {
257 if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200258 watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
259 done = find_existing_devices(context->cb_added, context->data);
Ziv Hendela306ced2013-08-07 19:29:17 +0300260 } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200261 for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
262 if (context->wds[i] >= 0) {
263 inotify_rm_watch(context->fd, context->wds[i]);
264 context->wds[i] = -1;
265 }
266 }
267 }
268 } else if (wd == context->wds[0]) {
269 i = atoi(event->name);
270 snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
271 D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
272 "new" : "gone", path, i);
273 if (i > 0 && i < MAX_USBFS_WD_COUNT) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800274 int local_ret = 0;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200275 if (event->mask & IN_CREATE) {
Bo Huang3c1d7b32014-01-21 14:25:22 +0800276 local_ret = inotify_add_watch(context->fd, path,
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200277 IN_CREATE | IN_DELETE);
Bo Huang3c1d7b32014-01-21 14:25:22 +0800278 if (local_ret >= 0)
279 context->wds[i] = local_ret;
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200280 done = find_existing_devices_bus(path, context->cb_added,
281 context->data);
282 } else if (event->mask & IN_DELETE) {
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200283 inotify_rm_watch(context->fd, context->wds[i]);
284 context->wds[i] = -1;
Benoit Gobyf4de0782012-08-01 18:54:02 -0700285 }
286 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200287 } else {
288 for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
289 if (wd == context->wds[i]) {
290 snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
291 if (event->mask == IN_CREATE) {
292 D("new device %s\n", path);
293 done = context->cb_added(path, context->data);
294 } else if (event->mask == IN_DELETE) {
295 D("gone device %s\n", path);
296 done = context->cb_removed(path, context->data);
297 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400298 }
299 }
300 }
Ziv Hendelf75ea8d2013-03-24 18:10:52 +0200301
302 offset += sizeof(struct inotify_event) + event->len;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400303 }
304 }
Guillaume Ranquetdea46b62012-10-23 17:11:44 +0200305
306 return done;
307} /* usb_host_read_event() */
308
309void usb_host_run(struct usb_host_context *context,
310 usb_device_added_cb added_cb,
311 usb_device_removed_cb removed_cb,
312 usb_discovery_done_cb discovery_done_cb,
313 void *client_data)
314{
315 int done;
316
317 done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
318
319 while (!done) {
320
321 done = usb_host_read_event(context);
322 }
323} /* usb_host_run() */
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400324
325struct usb_device *usb_device_open(const char *dev_name)
326{
Andrew Chant3af9e402017-11-01 17:32:35 -0700327 int fd, attempts, writeable = 1;
328 const int SLEEP_BETWEEN_ATTEMPTS_US = 100000; /* 100 ms */
329 const int64_t MAX_ATTEMPTS = 10; /* 1s */
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800330 D("usb_device_open %s\n", dev_name);
331
Andrew Chant3af9e402017-11-01 17:32:35 -0700332 /* Hack around waiting for permissions to be set on the USB device node.
333 * Should really be a timeout instead of attempt count, and should REALLY
334 * be triggered by the perm change via inotify rather than polling.
335 */
336 for (attempts = 0; attempts < MAX_ATTEMPTS; ++attempts) {
337 if (access(dev_name, R_OK | W_OK) == 0) {
338 writeable = 1;
339 break;
340 } else {
341 if (access(dev_name, R_OK) == 0) {
342 /* double check that write permission didn't just come along too! */
343 writeable = (access(dev_name, R_OK | W_OK) == 0);
344 break;
345 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400346 }
Andrew Chant3af9e402017-11-01 17:32:35 -0700347 /* not writeable or readable - sleep and try again. */
348 D("usb_device_open no access sleeping\n");
349 usleep(SLEEP_BETWEEN_ATTEMPTS_US);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400350 }
351
Andrew Chant3af9e402017-11-01 17:32:35 -0700352 if (writeable) {
353 fd = open(dev_name, O_RDWR);
354 } else {
355 fd = open(dev_name, O_RDONLY);
356 }
357 D("usb_device_open open returned %d writeable %d errno %d\n", fd, writeable, errno);
358 if (fd < 0) return NULL;
359
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800360 struct usb_device* result = usb_device_new(dev_name, fd);
361 if (result)
362 result->writeable = writeable;
363 return result;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400364}
365
366void usb_device_close(struct usb_device *device)
367{
368 close(device->fd);
369 free(device);
370}
371
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800372struct usb_device *usb_device_new(const char *dev_name, int fd)
373{
374 struct usb_device *device = calloc(1, sizeof(struct usb_device));
375 int length;
376
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800377 D("usb_device_new %s fd: %d\n", dev_name, fd);
378
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800379 if (lseek(fd, 0, SEEK_SET) != 0)
380 goto failed;
381 length = read(fd, device->desc, sizeof(device->desc));
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800382 D("usb_device_new read returned %d errno %d\n", length, errno);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800383 if (length < 0)
384 goto failed;
385
Mike Lockwood93aff722010-12-15 12:58:04 -0800386 strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
Mike Lockwoodcd185f22010-12-12 14:17:02 -0800387 device->fd = fd;
388 device->desc_length = length;
389 // assume we are writeable, since usb_device_get_fd will only return writeable fds
390 device->writeable = 1;
391 return device;
392
393failed:
394 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
Mike Lockwood50372072010-12-13 10:15:25 -0800462const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device)
463{
464 return (struct usb_device_descriptor*)device->desc;
465}
466
Andrew Chant8ea81012017-12-07 16:51:49 -0800467/* Returns a USB descriptor string for the given string ID.
468 * Return value: < 0 on error. 0 on success.
469 * The string is returned in ucs2_out in USB-native UCS-2 encoding.
470 *
471 * parameters:
472 * id - the string descriptor index.
473 * timeout - in milliseconds (see Documentation/driver-api/usb/usb.rst)
474 * ucs2_out - Must point to null on call.
475 * Will be filled in with a buffer on success.
476 * If this is non-null on return, it must be free()d.
477 * response_size - size, in bytes, of ucs-2 string in ucs2_out.
478 * The size isn't guaranteed to include null termination.
479 * Call free() to free the result when you are done with it.
480 */
481int usb_device_get_string_ucs2(struct usb_device* device, int id, int timeout, void** ucs2_out,
482 size_t* response_size) {
Mike Lockwood0dd1aab2015-06-18 13:38:31 -0700483 __u16 languages[MAX_STRING_DESCRIPTOR_LENGTH / sizeof(__u16)];
Andrew Chant8ea81012017-12-07 16:51:49 -0800484 char response[MAX_STRING_DESCRIPTOR_LENGTH];
485 int result;
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400486 int languageCount = 0;
487
Andrew Chant8ea81012017-12-07 16:51:49 -0800488 if (id == 0) return -1;
489 if (*ucs2_out != NULL) return -1;
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800490
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400491 memset(languages, 0, sizeof(languages));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400492
493 // read list of supported languages
Mike Lockwood120b57a2011-01-27 10:46:19 -0800494 result = usb_device_control_transfer(device,
Mike Lockwood1b7d9912010-07-24 13:57:21 -0400495 USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700496 (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages),
497 timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400498 if (result > 0)
499 languageCount = (result - 2) / 2;
500
Andrew Chant8ea81012017-12-07 16:51:49 -0800501 for (int i = 1; i <= languageCount; i++) {
502 memset(response, 0, sizeof(response));
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400503
Andrew Chant8ea81012017-12-07 16:51:49 -0800504 result = usb_device_control_transfer(
505 device, USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
506 (USB_DT_STRING << 8) | id, languages[i], response, sizeof(response), timeout);
507 if (result >= 2) { // string contents begin at offset 2.
508 int descriptor_len = result - 2;
509 char* out = malloc(descriptor_len + 3);
510 if (out == NULL) {
511 return -1;
512 }
513 memcpy(out, response + 2, descriptor_len);
514 // trail with three additional NULLs, so that there's guaranteed
515 // to be a UCS-2 NULL character beyond whatever USB returned.
516 // The returned string length is still just what USB returned.
517 memset(out + descriptor_len, '\0', 3);
518 *ucs2_out = (void*)out;
519 *response_size = descriptor_len;
520 return 0;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400521 }
522 }
Andrew Chant8ea81012017-12-07 16:51:49 -0800523 return -1;
524}
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400525
Andrew Chant8ea81012017-12-07 16:51:49 -0800526/* Warning: previously this blindly returned the lower 8 bits of
527 * every UCS-2 character in a USB descriptor. Now it will replace
528 * values > 127 with ascii '?'.
529 */
530char* usb_device_get_string(struct usb_device* device, int id, int timeout) {
531 char* ascii_string = NULL;
532 size_t raw_string_len = 0;
533 size_t i;
534 if (usb_device_get_string_ucs2(device, id, timeout, (void**)&ascii_string, &raw_string_len) < 0)
535 return NULL;
536 if (ascii_string == NULL) return NULL;
537 for (i = 0; i < raw_string_len / 2; ++i) {
538 // wire format for USB is always little-endian.
539 char lower = ascii_string[2 * i];
540 char upper = ascii_string[2 * i + 1];
541 if (upper || (lower & 0x80)) {
542 ascii_string[i] = '?';
543 } else {
544 ascii_string[i] = lower;
545 }
546 }
547 ascii_string[i] = '\0';
548 return ascii_string;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400549}
550
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700551char* usb_device_get_manufacturer_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400552{
553 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700554 return usb_device_get_string(device, desc->iManufacturer, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400555}
556
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700557char* usb_device_get_product_name(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400558{
559 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700560 return usb_device_get_string(device, desc->iProduct, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400561}
562
Mike Lockwoodf68600a2015-04-29 13:04:10 -0700563int usb_device_get_version(struct usb_device *device)
564{
565 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
566 return desc->bcdUSB;
567}
568
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700569char* usb_device_get_serial(struct usb_device *device, int timeout)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400570{
571 struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
Vitalii Tomkivdfd21b82016-10-14 10:19:26 -0700572 return usb_device_get_string(device, desc->iSerialNumber, timeout);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400573}
574
575int usb_device_is_writeable(struct usb_device *device)
576{
577 return device->writeable;
578}
579
580void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
581{
582 iter->config = device->desc;
583 iter->config_end = device->desc + device->desc_length;
584 iter->curr_desc = device->desc;
585}
586
587struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
588{
589 struct usb_descriptor_header* next;
590 if (iter->curr_desc >= iter->config_end)
591 return NULL;
592 next = (struct usb_descriptor_header*)iter->curr_desc;
593 iter->curr_desc += next->bLength;
594 return next;
595}
596
597int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
598{
599 return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
600}
601
602int usb_device_release_interface(struct usb_device *device, unsigned int interface)
603{
604 return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
605}
606
Mike Lockwoodec9e7b12011-01-22 09:17:07 -0800607int usb_device_connect_kernel_driver(struct usb_device *device,
608 unsigned int interface, int connect)
609{
610 struct usbdevfs_ioctl ctl;
611
612 ctl.ifno = interface;
613 ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
614 ctl.data = NULL;
615 return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
616}
617
Mike Lockwoodd2e798b2014-01-13 09:54:13 -0800618int usb_device_set_configuration(struct usb_device *device, int configuration)
619{
620 return ioctl(device->fd, USBDEVFS_SETCONFIGURATION, &configuration);
621}
622
623int usb_device_set_interface(struct usb_device *device, unsigned int interface,
624 unsigned int alt_setting)
625{
626 struct usbdevfs_setinterface ctl;
627
628 ctl.interface = interface;
629 ctl.altsetting = alt_setting;
630 return ioctl(device->fd, USBDEVFS_SETINTERFACE, &ctl);
631}
632
Mike Lockwood120b57a2011-01-27 10:46:19 -0800633int usb_device_control_transfer(struct usb_device *device,
634 int requestType,
635 int request,
636 int value,
637 int index,
638 void* buffer,
639 int length,
640 unsigned int timeout)
641{
642 struct usbdevfs_ctrltransfer ctrl;
643
644 // this usually requires read/write permission
645 if (!usb_device_reopen_writeable(device))
646 return -1;
647
648 memset(&ctrl, 0, sizeof(ctrl));
649 ctrl.bRequestType = requestType;
650 ctrl.bRequest = request;
651 ctrl.wValue = value;
652 ctrl.wIndex = index;
653 ctrl.wLength = length;
654 ctrl.data = buffer;
655 ctrl.timeout = timeout;
656 return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
657}
658
659int usb_device_bulk_transfer(struct usb_device *device,
660 int endpoint,
661 void* buffer,
Philip P. Moltmann9879bb22016-09-20 14:11:26 -0700662 unsigned int length,
Mike Lockwood120b57a2011-01-27 10:46:19 -0800663 unsigned int timeout)
664{
665 struct usbdevfs_bulktransfer ctrl;
666
Mike Lockwoodc4c00d82011-03-12 12:25:11 -0500667 // need to limit request size to avoid EINVAL
668 if (length > MAX_USBFS_BUFFER_SIZE)
669 length = MAX_USBFS_BUFFER_SIZE;
670
Mike Lockwood120b57a2011-01-27 10:46:19 -0800671 memset(&ctrl, 0, sizeof(ctrl));
672 ctrl.ep = endpoint;
673 ctrl.len = length;
674 ctrl.data = buffer;
675 ctrl.timeout = timeout;
676 return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
677}
678
Keun-young Parkf6411fa2016-01-12 18:22:36 -0800679int usb_device_reset(struct usb_device *device)
680{
681 return ioctl(device->fd, USBDEVFS_RESET);
682}
683
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500684struct usb_request *usb_request_new(struct usb_device *dev,
685 const struct usb_endpoint_descriptor *ep_desc)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400686{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500687 struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
688 if (!urb)
689 return NULL;
690
691 if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
692 urb->type = USBDEVFS_URB_TYPE_BULK;
693 else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
694 urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
695 else {
696 D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
697 free(urb);
698 return NULL;
699 }
700 urb->endpoint = ep_desc->bEndpointAddress;
701
702 struct usb_request *req = calloc(1, sizeof(struct usb_request));
703 if (!req) {
704 free(urb);
705 return NULL;
706 }
707
708 req->dev = dev;
709 req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
710 req->private_data = urb;
Mike Lockwoodb5d68a32011-02-14 08:05:40 -0500711 req->endpoint = urb->endpoint;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500712 urb->usercontext = req;
713
714 return req;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400715}
716
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500717void usb_request_free(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400718{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500719 free(req->private_data);
720 free(req);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400721}
722
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500723int usb_request_queue(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400724{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500725 struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400726 int res;
727
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400728 urb->status = -1;
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500729 urb->buffer = req->buffer;
Mike Lockwoodc4c00d82011-03-12 12:25:11 -0500730 // need to limit request size to avoid EINVAL
731 if (req->buffer_length > MAX_USBFS_BUFFER_SIZE)
732 urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
733 else
734 urb->buffer_length = req->buffer_length;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400735
736 do {
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500737 res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400738 } while((res < 0) && (errno == EINTR));
739
740 return res;
741}
742
Philip P. Moltmann36952852016-10-17 16:57:43 -0700743struct usb_request *usb_request_wait(struct usb_device *dev, int timeoutMillis)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400744{
Philip P. Moltmann36952852016-10-17 16:57:43 -0700745 // Poll until a request becomes available if there is a timeout
746 if (timeoutMillis > 0) {
747 struct pollfd p = {.fd = dev->fd, .events = POLLOUT, .revents = 0};
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400748
Philip P. Moltmann36952852016-10-17 16:57:43 -0700749 int res = poll(&p, 1, timeoutMillis);
750
751 if (res != 1 || p.revents != POLLOUT) {
752 D("[ poll - event %d, error %d]\n", p.revents, errno);
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500753 return NULL;
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400754 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400755 }
Philip P. Moltmann36952852016-10-17 16:57:43 -0700756
757 // Read the request. This should usually succeed as we polled before, but it can fail e.g. when
758 // two threads are reading usb requests at the same time and only a single request is available.
759 struct usbdevfs_urb *urb = NULL;
760 int res = TEMP_FAILURE_RETRY(ioctl(dev->fd, timeoutMillis == -1 ? USBDEVFS_REAPURB :
761 USBDEVFS_REAPURBNDELAY, &urb));
762 D("%s returned %d\n", timeoutMillis == -1 ? "USBDEVFS_REAPURB" : "USBDEVFS_REAPURBNDELAY", res);
763
764 if (res < 0) {
765 D("[ reap urb - error %d]\n", errno);
766 return NULL;
767 } else {
768 D("[ urb @%p status = %d, actual = %d ]\n", urb, urb->status, urb->actual_length);
769
770 struct usb_request *req = (struct usb_request*)urb->usercontext;
771 req->actual_length = urb->actual_length;
772
773 return req;
774 }
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400775}
776
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500777int usb_request_cancel(struct usb_request *req)
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400778{
Mike Lockwoode533c5f2011-01-04 20:04:36 -0500779 struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
Badhri Jagan Sridharanef4087b2014-08-06 12:34:30 -0700780 return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, urb);
Mike Lockwood30ff2c72010-05-09 16:23:47 -0400781}