version up to 2.1.0
[platform/core/system/sdbd.git] / src / usb_linux.c
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <string.h>
21
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <sys/time.h>
25 #include <dirent.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <ctype.h>
29
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>
34 #else
35 #include <linux/usb_ch9.h>
36 #endif
37 #include <asm/byteorder.h>
38
39 #include "sysdeps.h"
40
41 #define   TRACE_TAG  TRACE_USB
42 #include "sdb.h"
43
44
45 /* usb scan debugging is waaaay too verbose */
46 #define DBGX(x...)
47
48 SDB_MUTEX_DEFINE( usb_lock );
49
50 struct usb_handle
51 {
52     usb_handle *prev;
53     usb_handle *next;
54
55     char fname[64];
56     int desc;
57     unsigned char ep_in;
58     unsigned char ep_out;
59
60     unsigned zero_mask;
61     unsigned writeable;
62
63     struct usbdevfs_urb urb_in;
64     struct usbdevfs_urb urb_out;
65
66     int urb_in_busy;
67     int urb_out_busy;
68     int dead;
69
70     sdb_cond_t notify;
71     sdb_mutex_t lock;
72
73     // for garbage collecting disconnected devices
74     int mark;
75
76     // ID of thread currently in REAPURB
77     pthread_t reaper_thread;
78 };
79
80 static usb_handle handle_list = {
81     .prev = &handle_list,
82     .next = &handle_list,
83 };
84
85 static int known_device(const char *dev_name)
86 {
87     usb_handle *usb;
88
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
93             usb->mark = 1;
94             sdb_mutex_unlock(&usb_lock);
95             return 1;
96         }
97     }
98     sdb_mutex_unlock(&usb_lock);
99     return 0;
100 }
101
102 static void kick_disconnected_devices()
103 {
104     usb_handle *usb;
105
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) {
110             usb_kick(usb);
111         } else {
112             usb->mark = 0;
113         }
114     }
115     sdb_mutex_unlock(&usb_lock);
116
117 }
118
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);
121
122 static inline int badname(const char *name)
123 {
124     while(*name) {
125         if(!isdigit(*name++)) return 1;
126     }
127     return 0;
128 }
129
130 static void find_usb_device(const char *base,
131         void (*register_device_callback)
132                 (const char *, unsigned char, unsigned char, int, int, unsigned))
133 {
134     char busname[32], devname[32];
135     unsigned char local_ep_in, local_ep_out;
136     DIR *busdir , *devdir ;
137     struct dirent *de;
138     int fd ;
139
140     busdir = opendir(base);
141     if(busdir == 0) return;
142
143     while((de = readdir(busdir)) != 0) {
144         if(badname(de->d_name)) continue;
145
146         snprintf(busname, sizeof busname, "%s/%s", base, de->d_name);
147         devdir = opendir(busname);
148         if(devdir == 0) continue;
149
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;
160             unsigned vid, pid;
161             unsigned int desclength;
162
163             if(badname(de->d_name)) continue;
164             snprintf(devname, sizeof devname, "%s/%s", busname, de->d_name);
165
166             if(known_device(devname)) {
167                 DBGX("skipping %s\n", devname);
168                 continue;
169             }
170
171 //            DBGX("[ scanning %s ]\n", devname);
172             if((fd = unix_open(devname, O_RDONLY)) < 0) {
173                 continue;
174             }
175
176             desclength = sdb_read(fd, devdesc, sizeof(devdesc));
177             bufend = bufptr + desclength;
178
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);
182                 sdb_close(fd);
183                 continue;
184             }
185
186             device = (struct usb_device_descriptor*)bufptr;
187             bufptr += USB_DT_DEVICE_SIZE;
188
189             if((device->bLength != USB_DT_DEVICE_SIZE) || (device->bDescriptorType != USB_DT_DEVICE)) {
190                 sdb_close(fd);
191                 continue;
192             }
193
194             vid = device->idVendor;
195             pid = device->idProduct;
196             DBGX("[ %s is V:%04x P:%04x ]\n", devname, vid, pid);
197
198                 // should have config descriptor next
199             config = (struct usb_config_descriptor *)bufptr;
200
201             /* tizen specific */
202             if (device->bNumConfigurations > 1) {
203                 bufptr += config->wTotalLength;
204                 config = (struct usb_config_descriptor *)bufptr;
205                 bufend = bufptr + config->wTotalLength;
206             }
207
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");
211                 sdb_close(fd);
212                 continue;
213             }
214
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];
219
220                 if (type == USB_DT_INTERFACE) {
221                     interface = (struct usb_interface_descriptor *)bufptr;
222                     bufptr += length;
223
224                     if (length != USB_DT_INTERFACE_SIZE) {
225                         D("interface descriptor has wrong size\n");
226                         break;
227                     }
228
229                     DBGX("bInterfaceClass: %d,  bInterfaceSubClass: %d,"
230                          "bInterfaceProtocol: %d, bNumEndpoints: %d\n",
231                          interface->bInterfaceClass, interface->bInterfaceSubClass,
232                          interface->bInterfaceProtocol, interface->bNumEndpoints);
233
234                     if (interface->bNumEndpoints == 2 &&
235                             is_sdb_interface(vid, pid, interface->bInterfaceClass,
236                             interface->bInterfaceSubClass, interface->bInterfaceProtocol))  {
237
238                         D("looking for bulk endpoints\n");
239                             // looks like SDB...
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;
244
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");
251                             break;
252                         }
253
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");
258                             continue;
259                         }
260                             /* aproto 01 needs 0 termination */
261                         if(interface->bInterfaceProtocol == 0x01) {
262                             zero_mask = ep1->wMaxPacketSize - 1;
263                         }
264
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;
269                         } else {
270                             local_ep_in = ep2->bEndpointAddress;
271                             local_ep_out = ep1->bEndpointAddress;
272                         }
273
274                         register_device_callback(devname, local_ep_in, local_ep_out,
275                                 interface->bInterfaceNumber, device->iSerialNumber, zero_mask);
276                         break;
277                     }
278                 } else {
279                     bufptr += length;
280                 }
281             } // end of while
282
283             sdb_close(fd);
284         } // end of devdir while
285         closedir(devdir);
286     } //end of busdir while
287     closedir(busdir);
288 }
289
290 void usb_cleanup()
291 {
292 }
293
294 static int usb_bulk_write(usb_handle *h, const void *data, int len)
295 {
296     struct usbdevfs_urb *urb = &h->urb_out;
297     int res;
298     struct timeval tv;
299     struct timespec ts;
300
301     memset(urb, 0, sizeof(*urb));
302     urb->type = USBDEVFS_URB_TYPE_BULK;
303     urb->endpoint = h->ep_out;
304     urb->status = -1;
305     urb->buffer = (void*) data;
306     urb->buffer_length = len;
307
308     D("++ write ++\n");
309
310     sdb_mutex_lock(&h->lock);
311     if(h->dead) {
312         res = -1;
313         goto fail;
314     }
315     do {
316         res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
317     } while((res < 0) && (errno == EINTR));
318
319     if(res < 0) {
320         goto fail;
321     }
322
323     res = -1;
324     h->urb_out_busy = 1;
325     for(;;) {
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) {
332             break;
333         }
334         if(h->urb_out_busy == 0) {
335             if(urb->status == 0) {
336                 res = urb->actual_length;
337             }
338             break;
339         }
340     }
341 fail:
342     sdb_mutex_unlock(&h->lock);
343     D("-- write --\n");
344     return res;
345 }
346
347 static int usb_bulk_read(usb_handle *h, void *data, int len)
348 {
349     struct usbdevfs_urb *urb = &h->urb_in;
350     struct usbdevfs_urb *out = NULL;
351     int res;
352
353     memset(urb, 0, sizeof(*urb));
354     urb->type = USBDEVFS_URB_TYPE_BULK;
355     urb->endpoint = h->ep_in;
356     urb->status = -1;
357     urb->buffer = data;
358     urb->buffer_length = len;
359
360
361     sdb_mutex_lock(&h->lock);
362     if(h->dead) {
363         res = -1;
364         goto fail;
365     }
366     do {
367         res = ioctl(h->desc, USBDEVFS_SUBMITURB, urb);
368     } while((res < 0) && (errno == EINTR));
369
370     if(res < 0) {
371         goto fail;
372     }
373
374     h->urb_in_busy = 1;
375     for(;;) {
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;
383         if(h->dead) {
384             res = -1;
385             break;
386         }
387         if(res < 0) {
388             if(saved_errno == EINTR) {
389                 continue;
390             }
391             D("[ reap urb - error ]\n");
392             break;
393         }
394         D("[ urb @%p status = %d, actual = %d ]\n",
395             out, out->status, out->actual_length);
396
397         if(out == &h->urb_in) {
398             D("[ reap urb - IN complete ]\n");
399             h->urb_in_busy = 0;
400             if(urb->status == 0) {
401                 res = urb->actual_length;
402             } else {
403                 res = -1;
404             }
405             break;
406         }
407         if(out == &h->urb_out) {
408             D("[ reap urb - OUT compelete ]\n");
409             h->urb_out_busy = 0;
410             sdb_cond_broadcast(&h->notify);
411         }
412     }
413 fail:
414     sdb_mutex_unlock(&h->lock);
415     return res;
416 }
417
418
419 int usb_write(usb_handle *h, const void *_data, int len)
420 {
421     unsigned char *data = (unsigned char*) _data;
422     int n;
423     int need_zero = 0;
424
425     if(h->zero_mask) {
426             /* if we need 0-markers and our transfer
427             ** is an even multiple of the packet size,
428             ** we make note of it
429             */
430         if(!(len & h->zero_mask)) {
431             need_zero = 1;
432         }
433     }
434
435     while(len > 0) {
436         int xfer = (len > 4096) ? 4096 : len;
437
438         n = usb_bulk_write(h, data, xfer);
439         if(n != xfer) {
440             D("ERROR: n = %d, errno = %d (%s)\n",
441                 n, errno, strerror(errno));
442             return -1;
443         }
444
445         len -= xfer;
446         data += xfer;
447     }
448
449     if(need_zero){
450         n = usb_bulk_write(h, _data, 0);
451         return n;
452     }
453
454     return 0;
455 }
456
457 int usb_read(usb_handle *h, void *_data, int len)
458 {
459     unsigned char *data = (unsigned char*) _data;
460     int n;
461
462     D("++ usb_read ++\n");
463     while(len > 0) {
464         int xfer = (len > 4096) ? 4096 : len;
465
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);
469         if(n != xfer) {
470             if((errno == ETIMEDOUT) && (h->desc != -1)) {
471                 D("[ timeout ]\n");
472                 if(n > 0){
473                     data += n;
474                     len -= n;
475                 }
476                 continue;
477             }
478             D("ERROR: n = %d, errno = %d (%s)\n",
479                 n, errno, strerror(errno));
480             return -1;
481         }
482
483         len -= xfer;
484         data += xfer;
485     }
486
487     D("-- usb_read --\n");
488     return 0;
489 }
490
491 void usb_kick(usb_handle *h)
492 {
493     D("[ kicking %p (fd = %d) ]\n", h, h->desc);
494     sdb_mutex_lock(&h->lock);
495     if(h->dead == 0) {
496         h->dead = 1;
497
498         if (h->writeable) {
499             /* HACK ALERT!
500             ** Sometimes we get stuck in ioctl(USBDEVFS_REAPURB).
501             ** This is a workaround for that problem.
502             */
503             if (h->reaper_thread) {
504                 pthread_kill(h->reaper_thread, SIGALRM);
505             }
506
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
511             */
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;
516             h->urb_in_busy = 0;
517             h->urb_out_busy = 0;
518             sdb_cond_broadcast(&h->notify);
519         } else {
520             unregister_usb_transport(h);
521         }
522     }
523     sdb_mutex_unlock(&h->lock);
524 }
525
526 int usb_close(usb_handle *h)
527 {
528     D("[ usb close ... ]\n");
529     sdb_mutex_lock(&usb_lock);
530     h->next->prev = h->prev;
531     h->prev->next = h->next;
532     h->prev = 0;
533     h->next = 0;
534
535     sdb_close(h->desc);
536     D("[ usb closed %p (fd = %d) ]\n", h, h->desc);
537     sdb_mutex_unlock(&usb_lock);
538
539     free(h);
540     return 0;
541 }
542
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)
546 {
547     usb_handle* usb = 0;
548     int n = 0;
549     char serial[256];
550     int bConfigurationValue = 2; /* tizen specific : sdb needs 2nd configruation */
551
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.
556         **
557         ** If we have a usb_handle on the list 'o handles with a matching
558         ** name, we have no further work to do.
559         */
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);
564             return;
565         }
566     }
567     sdb_mutex_unlock(&usb_lock);
568
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);
573     usb->ep_in = ep_in;
574     usb->ep_out = ep_out;
575     usb->zero_mask = zero_mask;
576     usb->writeable = 1;
577
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 */
581     usb->mark = 1;
582     usb->reaper_thread = 0;
583
584     usb->desc = unix_open(usb->fname, O_RDWR);
585     if(usb->desc < 0) {
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;
589         usb->writeable = 0;
590         D("[ usb open read-only %s fd = %d]\n", usb->fname, usb->desc);
591     } else {
592         D("[ usb open %s fd = %d]\n", usb->fname, usb->desc);
593         /* tizen specific */
594         n = ioctl(usb->desc, USBDEVFS_RESET);
595         if(n != 0) {
596             D("[ usb reset failed %s fd = %d]\n", usb->fname, usb->desc);
597             goto fail;
598         }
599         n = ioctl(usb->desc, USBDEVFS_SETCONFIGURATION, &bConfigurationValue);
600         if (n != 0) {
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);
603         }
604
605         n = ioctl(usb->desc, USBDEVFS_CLAIMINTERFACE, &interface);
606         if(n != 0) {
607             D("[ usb claim failed %s fd = %d]\n", usb->fname, usb->desc);
608             goto fail;
609         }
610     }
611
612         /* read the device's serial number */
613     serial[0] = 0;
614     memset(serial, 0, sizeof(serial));
615     if (serial_index) {
616         struct usbdevfs_ctrltransfer  ctrl;
617         __u16 buffer[128];
618         __u16 languages[128];
619         int i, result;
620         int languageCount = 0;
621
622         memset(languages, 0, sizeof(languages));
623         memset(&ctrl, 0, sizeof(ctrl));
624
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;
629         ctrl.wIndex = 0;
630         ctrl.wLength = sizeof(languages);
631         ctrl.data = languages;
632         ctrl.timeout = 1000;
633
634         result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
635         if (result > 0)
636             languageCount = (result - 2) / 2;
637
638         for (i = 1; i <= languageCount; i++) {
639             memset(buffer, 0, sizeof(buffer));
640             memset(&ctrl, 0, sizeof(ctrl));
641
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);
647             ctrl.data = buffer;
648             ctrl.timeout = 1000;
649
650             result = ioctl(usb->desc, USBDEVFS_CONTROL, &ctrl);
651             if (result > 0) {
652                 int i;
653                 // skip first word, and copy the rest to the serial string, changing shorts to bytes.
654                 result /= 2;
655                 for (i = 1; i < result; i++)
656                     serial[i - 1] = __le16_to_cpu(buffer[i]);
657                 serial[i - 1] = 0;
658                 break;
659             }
660         }
661     }
662
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);
670
671     register_usb_transport(usb, serial, usb->writeable);
672     return;
673
674 fail:
675     D("[ usb open %s error=%d, err_str = %s]\n",
676         usb->fname,  errno, strerror(errno));
677     if(usb->desc >= 0) {
678         sdb_close(usb->desc);
679     }
680     free(usb);
681 }
682
683 void* device_poll_thread(void* unused)
684 {
685     D("Created device thread\n");
686     for(;;) {
687             /* XXX use inotify */
688         find_usb_device("/dev/bus/usb", register_device);
689         kick_disconnected_devices();
690         sleep(1);
691     }
692     return NULL;
693 }
694
695 static void sigalrm_handler(int signo)
696 {
697     // don't need to do anything here
698 }
699
700 void usb_init()
701 {
702     sdb_thread_t tid;
703     struct sigaction    actions;
704
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);
710
711     if(sdb_thread_create(&tid, device_poll_thread, NULL)){
712         fatal_errno("cannot create input thread");
713     }
714 }