2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
30 #include <linux/usbdevice_fs.h>
31 #include <linux/version.h>
32 #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
33 #include <linux/usb/ch9.h>
35 #include <linux/usb_ch9.h>
37 #include <asm/byteorder.h>
41 #define TRACE_TAG TRACE_USB
45 /* usb scan debugging is waaaay too verbose */
48 SDB_MUTEX_DEFINE( usb_lock );
63 struct usbdevfs_urb urb_in;
64 struct usbdevfs_urb urb_out;
73 // for garbage collecting disconnected devices
76 // ID of thread currently in REAPURB
77 pthread_t reaper_thread;
80 static usb_handle handle_list = {
85 static int known_device(const char *dev_name)
89 sdb_mutex_lock(&usb_lock);
90 for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
91 if(!strcmp(usb->fname, dev_name)) {
92 // set mark flag to indicate this device is still alive
94 sdb_mutex_unlock(&usb_lock);
98 sdb_mutex_unlock(&usb_lock);
102 static void kick_disconnected_devices()
106 sdb_mutex_lock(&usb_lock);
107 // kick any devices in the device list that were not found in the device scan
108 for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
109 if (usb->mark == 0) {
115 sdb_mutex_unlock(&usb_lock);
119 static void register_device(const char *dev_name, unsigned char ep_in, unsigned char ep_out,
120 int ifc, int serial_index, unsigned zero_mask);
122 static inline int badname(const char *name)
125 if(!isdigit(*name++)) return 1;
130 static void find_usb_device(const char *base,
131 void (*register_device_callback)
132 (const char *, unsigned char, unsigned char, int, int, unsigned))
134 char busname[32], devname[32];
135 unsigned char local_ep_in, local_ep_out;
136 DIR *busdir , *devdir ;
140 busdir = opendir(base);
141 if(busdir == 0) return;
143 while((de = readdir(busdir)) != 0) {
144 if(badname(de->d_name)) continue;
146 snprintf(busname, sizeof busname, "%s/%s", base, de->d_name);
147 devdir = opendir(busname);
148 if(devdir == 0) continue;
150 // DBGX("[ scanning %s ]\n", busname);
151 while((de = readdir(devdir))) {
152 unsigned char devdesc[4096];
153 unsigned char* bufptr = devdesc;
154 unsigned char* bufend;
155 struct usb_device_descriptor* device;
156 struct usb_config_descriptor* config;
157 struct usb_interface_descriptor* interface;
158 struct usb_endpoint_descriptor *ep1, *ep2;
159 unsigned zero_mask = 0;
161 unsigned int desclength;
163 if(badname(de->d_name)) continue;
164 snprintf(devname, sizeof devname, "%s/%s", busname, de->d_name);
166 if(known_device(devname)) {
167 DBGX("skipping %s\n", devname);
171 // DBGX("[ scanning %s ]\n", devname);
172 if((fd = unix_open(devname, O_RDONLY)) < 0) {
176 desclength = sdb_read(fd, devdesc, sizeof(devdesc));
177 bufend = bufptr + desclength;
179 // should have device and configuration descriptors, and atleast two endpoints
180 if (desclength < USB_DT_DEVICE_SIZE + USB_DT_CONFIG_SIZE) {
181 D("desclength %d is too small\n", desclength);
186 device = (struct usb_device_descriptor*)bufptr;
187 bufptr += USB_DT_DEVICE_SIZE;
189 if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
194 vid = device->idVendor;
195 pid = device->idProduct;
196 DBGX("[ %s is V:%04x P:%04x ]\n", devname, vid, pid);
198 // should have config descriptor next
199 config = (struct usb_config_descriptor *)bufptr;
202 if (device->bNumConfigurations > 1) {
203 bufptr += config->wTotalLength;
204 config = (struct usb_config_descriptor *)bufptr;
205 bufend = bufptr + config->wTotalLength;
208 bufptr += USB_DT_CONFIG_SIZE;
209 if (config->bLength != USB_DT_CONFIG_SIZE || config->bDescriptorType != USB_DT_CONFIG) {
210 D("usb_config_descriptor not found\n");
215 // loop through all the descriptors and look for the SDB interface
216 while (bufptr < bufend) {
217 unsigned char length = bufptr[0];
218 unsigned char type = bufptr[1];
220 if (type == USB_DT_INTERFACE) {
221 interface = (struct usb_interface_descriptor *)bufptr;
224 if (length != USB_DT_INTERFACE_SIZE) {
225 D("interface descriptor has wrong size\n");
229 DBGX("bInterfaceClass: %d, bInterfaceSubClass: %d,"
230 "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
231 interface->bInterfaceClass, interface->bInterfaceSubClass,
232 interface->bInterfaceProtocol, interface->bNumEndpoints);
234 if (interface->bNumEndpoints == 2 &&
235 is_sdb_interface(vid, pid, interface->bInterfaceClass,
236 interface->bInterfaceSubClass, interface->bInterfaceProtocol)) {
238 D("looking for bulk endpoints\n");
240 ep1 = (struct usb_endpoint_descriptor *)bufptr;
241 bufptr += USB_DT_ENDPOINT_SIZE;
242 ep2 = (struct usb_endpoint_descriptor *)bufptr;
243 bufptr += USB_DT_ENDPOINT_SIZE;
245 if (bufptr > devdesc + desclength ||
246 ep1->bLength != USB_DT_ENDPOINT_SIZE ||
247 ep1->bDescriptorType != USB_DT_ENDPOINT ||
248 ep2->bLength != USB_DT_ENDPOINT_SIZE ||
249 ep2->bDescriptorType != USB_DT_ENDPOINT) {
250 D("endpoints not found\n");
254 // both endpoints should be bulk
255 if (ep1->bmAttributes != USB_ENDPOINT_XFER_BULK ||
256 ep2->bmAttributes != USB_ENDPOINT_XFER_BULK) {
257 D("bulk endpoints not found\n");
260 /* aproto 01 needs 0 termination */
261 if(interface->bInterfaceProtocol == 0x01) {
262 zero_mask = ep1->wMaxPacketSize - 1;
265 // we have a match. now we just need to figure out which is in and which is out.
266 if (ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) {
267 local_ep_in = ep1->bEndpointAddress;
268 local_ep_out = ep2->bEndpointAddress;
270 local_ep_in = ep2->bEndpointAddress;
271 local_ep_out = ep1->bEndpointAddress;
274 register_device_callback(devname, local_ep_in, local_ep_out,
275 interface->bInterfaceNumber, device->iSerialNumber, zero_mask);
284 } // end of devdir while
286 } //end of busdir while
294 static int usb_bulk_write(usb_handle *h, const void *data, int len)
296 struct usbdevfs_urb *urb = &h->urb_out;
301 memset(urb, 0, sizeof(*urb));
302 urb->type = USBDEVFS_URB_TYPE_BULK;
303 urb->endpoint = h->ep_out;
305 urb->buffer = (void*) data;
306 urb->buffer_length = len;
310 sdb_mutex_lock(&h->lock);
316 res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
317 } while((res < 0) && (errno == EINTR));
326 /* time out after five seconds */
327 gettimeofday(&tv, NULL);
328 ts.tv_sec = tv.tv_sec + 5;
329 ts.tv_nsec = tv.tv_usec * 1000L;
330 res = pthread_cond_timedwait(&h->notify, &h->lock, &ts);
331 if(res < 0 || h->dead) {
334 if(h->urb_out_busy == 0) {
335 if(urb->status == 0) {
336 res = urb->actual_length;
342 sdb_mutex_unlock(&h->lock);
347 static int usb_bulk_read(usb_handle *h, void *data, int len)
349 struct usbdevfs_urb *urb = &h->urb_in;
350 struct usbdevfs_urb *out = NULL;
353 memset(urb, 0, sizeof(*urb));
354 urb->type = USBDEVFS_URB_TYPE_BULK;
355 urb->endpoint = h->ep_in;
358 urb->buffer_length = len;
361 sdb_mutex_lock(&h->lock);
367 res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
368 } while((res < 0) && (errno == EINTR));
376 D("[ reap urb - wait ]\n");
377 h->reaper_thread = pthread_self();
378 sdb_mutex_unlock(&h->lock);
379 res = ioctl(h->desc, USBDEVFS_REAPURB, &out);
380 int saved_errno = errno;
381 sdb_mutex_lock(&h->lock);
382 h->reaper_thread = 0;
388 if(saved_errno == EINTR) {
391 D("[ reap urb - error ]\n");
394 D("[ urb @%p status = %d, actual = %d ]\n",
395 out, out->status, out->actual_length);
397 if(out == &h->urb_in) {
398 D("[ reap urb - IN complete ]\n");
400 if(urb->status == 0) {
401 res = urb->actual_length;
407 if(out == &h->urb_out) {
408 D("[ reap urb - OUT compelete ]\n");
410 sdb_cond_broadcast(&h->notify);
414 sdb_mutex_unlock(&h->lock);
419 int usb_write(usb_handle *h, const void *_data, int len)
421 unsigned char *data = (unsigned char*) _data;
426 /* if we need 0-markers and our transfer
427 ** is an even multiple of the packet size,
428 ** we make note of it
430 if(!(len & h->zero_mask)) {
436 int xfer = (len > 4096) ? 4096 : len;
438 n = usb_bulk_write(h, data, xfer);
440 D("ERROR: n = %d, errno = %d (%s)\n",
441 n, errno, strerror(errno));
450 n = usb_bulk_write(h, _data, 0);
457 int usb_read(usb_handle *h, void *_data, int len)
459 unsigned char *data = (unsigned char*) _data;
462 D("++ usb_read ++\n");
464 int xfer = (len > 4096) ? 4096 : len;
466 D("[ usb read %d fd = %d], fname=%s\n", xfer, h->desc, h->fname);
467 n = usb_bulk_read(h, data, xfer);
468 D("[ usb read %d ] = %d, fname=%s\n", xfer, n, h->fname);
470 if((errno == ETIMEDOUT) && (h->desc != -1)) {
478 D("ERROR: n = %d, errno = %d (%s)\n",
479 n, errno, strerror(errno));
487 D("-- usb_read --\n");
491 void usb_kick(usb_handle *h)
493 D("[ kicking %p (fd = %d) ]\n", h, h->desc);
494 sdb_mutex_lock(&h->lock);
500 ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
501 ** This is a workaround for that problem.
503 if (h->reaper_thread) {
504 pthread_kill(h->reaper_thread, SIGALRM);
507 /* cancel any pending transactions
508 ** these will quietly fail if the txns are not active,
509 ** but this ensures that a reader blocked on REAPURB
510 ** will get unblocked
512 ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_in);
513 ioctl(h->desc, USBDEVFS_DISCARDURB, &h->urb_out);
514 h->urb_in.status = -ENODEV;
515 h->urb_out.status = -ENODEV;
518 sdb_cond_broadcast(&h->notify);
520 unregister_usb_transport(h);
523 sdb_mutex_unlock(&h->lock);
526 int usb_close(usb_handle *h)
528 D("[ usb close ... ]\n");
529 sdb_mutex_lock(&usb_lock);
530 h->next->prev = h->prev;
531 h->prev->next = h->next;
536 D("[ usb closed %p (fd = %d) ]\n", h, h->desc);
537 sdb_mutex_unlock(&usb_lock);
543 static void register_device(const char *dev_name,
544 unsigned char ep_in, unsigned char ep_out,
545 int interface, int serial_index, unsigned zero_mask)
550 int bConfigurationValue = 2; /* tizen specific : sdb needs 2nd configruation */
552 /* Since Linux will not reassign the device ID (and dev_name)
553 ** as long as the device is open, we can add to the list here
554 ** once we open it and remove from the list when we're finally
555 ** closed and everything will work out fine.
557 ** If we have a usb_handle on the list 'o handles with a matching
558 ** name, we have no further work to do.
560 sdb_mutex_lock(&usb_lock);
561 for(usb = handle_list.next; usb != &handle_list; usb = usb->next){
562 if(!strcmp(usb->fname, dev_name)) {
563 sdb_mutex_unlock(&usb_lock);
567 sdb_mutex_unlock(&usb_lock);
569 D("[ usb located new device %s (%d/%d/%d) ]\n",
570 dev_name, ep_in, ep_out, interface);
571 usb = calloc(1, sizeof(usb_handle));
572 strcpy(usb->fname, dev_name);
574 usb->ep_out = ep_out;
575 usb->zero_mask = zero_mask;
578 sdb_cond_init(&usb->notify, 0);
579 sdb_mutex_init(&usb->lock, 0);
580 /* initialize mark to 1 so we don't get garbage collected after the device scan */
582 usb->reaper_thread = 0;
584 usb->desc = unix_open(usb->fname, O_RDWR);
586 /* if we fail, see if have read-only access */
587 usb->desc = unix_open(usb->fname, O_RDONLY);
588 if(usb->desc < 0) goto fail;
590 D("[ usb open read-only %s fd = %d]\n", usb->fname, usb->desc);
592 D("[ usb open %s fd = %d]\n", usb->fname, usb->desc);
594 n = ioctl(usb->desc, USBDEVFS_RESET);
596 D("[ usb reset failed %s fd = %d]\n", usb->fname, usb->desc);
599 n = ioctl(usb->desc, USBDEVFS_SETCONFIGURATION, &bConfigurationValue);
601 D("[ usb set %d configuration failed %s fd = %d]\n", bConfigurationValue, usb->fname, usb->desc);
602 D("check kernel is supporting %dth configuration\n", bConfigurationValue);
605 n = ioctl(usb->desc, USBDEVFS_CLAIMINTERFACE, &interface);
607 D("[ usb claim failed %s fd = %d]\n", usb->fname, usb->desc);
612 /* read the device's serial number */
614 memset(serial, 0, sizeof(serial));
616 struct usbdevfs_ctrltransfer ctrl;
618 __u16 languages[128];
620 int languageCount = 0;
622 memset(languages, 0, sizeof(languages));
623 memset(&ctrl, 0, sizeof(ctrl));
625 // read list of supported languages
626 ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
627 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
628 ctrl.wValue = (USB_DT_STRING << 8) | 0;
630 ctrl.wLength = sizeof(languages);
631 ctrl.data = languages;
634 result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
636 languageCount = (result - 2) / 2;
638 for (i = 1; i <= languageCount; i++) {
639 memset(buffer, 0, sizeof(buffer));
640 memset(&ctrl, 0, sizeof(ctrl));
642 ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
643 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
644 ctrl.wValue = (USB_DT_STRING << 8) | serial_index;
645 ctrl.wIndex = __le16_to_cpu(languages[i]);
646 ctrl.wLength = sizeof(buffer);
650 result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
653 // skip first word, and copy the rest to the serial string, changing shorts to bytes.
655 for (i = 1; i < result; i++)
656 serial[i - 1] = __le16_to_cpu(buffer[i]);
663 /* add to the end of the active handles */
664 sdb_mutex_lock(&usb_lock);
665 usb->next = &handle_list;
666 usb->prev = handle_list.prev;
667 usb->prev->next = usb;
668 usb->next->prev = usb;
669 sdb_mutex_unlock(&usb_lock);
671 register_usb_transport(usb, serial, usb->writeable);
675 D("[ usb open %s error=%d, err_str = %s]\n",
676 usb->fname, errno, strerror(errno));
678 sdb_close(usb->desc);
683 void* device_poll_thread(void* unused)
685 D("Created device thread\n");
687 /* XXX use inotify */
688 find_usb_device("/dev/bus/usb", register_device);
689 kick_disconnected_devices();
695 static void sigalrm_handler(int signo)
697 // don't need to do anything here
703 struct sigaction actions;
705 memset(&actions, 0, sizeof(actions));
706 sigemptyset(&actions.sa_mask);
707 actions.sa_flags = 0;
708 actions.sa_handler = sigalrm_handler;
709 sigaction(SIGALRM,& actions, NULL);
711 if(sdb_thread_create(&tid, device_poll_thread, NULL)){
712 fatal_errno("cannot create input thread");