1/*
2 * Linux USB support
3 *
4 * Copyright (c) 2000-2003 Johannes Erdfelt <johannes@erdfelt.com>
5 *
6 * This library is covered by the LGPL, read LICENSE for details.
7 */
8
9#include <stdlib.h>	/* getenv, etc */
10#include <unistd.h>
11#include <string.h>
12#include <stdio.h>
13#include <fcntl.h>
14#include <errno.h>
15#include <sys/time.h>
16#include <dirent.h>
17
18#include "linux.h"
19#include "usbi.h"
20
21static char usb_path[PATH_MAX + 1] = "";
22
23static int device_open(struct usb_device *dev)
24{
25  char filename[PATH_MAX + 1];
26  int fd;
27
28  snprintf(filename, sizeof(filename) - 1, "%s/%s/%s",
29    usb_path, dev->bus->dirname, dev->filename);
30
31  fd = open(filename, O_RDWR);
32  if (fd < 0) {
33    fd = open(filename, O_RDONLY);
34    if (fd < 0)
35      USB_ERROR_STR(-errno, "failed to open %s: %s",
36	filename, strerror(errno));
37  }
38
39  return fd;
40}
41
42int usb_os_open(usb_dev_handle *dev)
43{
44  dev->fd = device_open(dev->device);
45
46  return 0;
47}
48
49int usb_os_close(usb_dev_handle *dev)
50{
51  if (dev->fd < 0)
52    return 0;
53
54  if (close(dev->fd) == -1)
55    /* Failing trying to close a file really isn't an error, so return 0 */
56    USB_ERROR_STR(0, "tried to close device fd %d: %s", dev->fd,
57	strerror(errno));
58
59  return 0;
60}
61
62int usb_set_configuration(usb_dev_handle *dev, int configuration)
63{
64  int ret;
65
66  ret = ioctl(dev->fd, IOCTL_USB_SETCONFIG, &configuration);
67  if (ret < 0)
68    USB_ERROR_STR(-errno, "could not set config %d: %s", configuration,
69	strerror(errno));
70
71  dev->config = configuration;
72
73  return 0;
74}
75
76int usb_claim_interface(usb_dev_handle *dev, int interface)
77{
78  int ret;
79
80  ret = ioctl(dev->fd, IOCTL_USB_CLAIMINTF, &interface);
81  if (ret < 0) {
82    if (errno == EBUSY && usb_debug > 0)
83      fprintf(stderr, "Check that you have permissions to write to %s/%s and, if you don't, that you set up hotplug (http://linux-hotplug.sourceforge.net/) correctly.\n", dev->bus->dirname, dev->device->filename);
84
85    USB_ERROR_STR(-errno, "could not claim interface %d: %s", interface,
86	strerror(errno));
87  }
88
89  dev->interface = interface;
90
91  return 0;
92}
93
94int usb_release_interface(usb_dev_handle *dev, int interface)
95{
96  int ret;
97
98  ret = ioctl(dev->fd, IOCTL_USB_RELEASEINTF, &interface);
99  if (ret < 0)
100    USB_ERROR_STR(-errno, "could not release intf %d: %s", interface,
101    	strerror(errno));
102
103  dev->interface = -1;
104
105  return 0;
106}
107
108int usb_set_altinterface(usb_dev_handle *dev, int alternate)
109{
110  int ret;
111  struct usb_setinterface setintf;
112
113  if (dev->interface < 0)
114    USB_ERROR(-EINVAL);
115
116  setintf.interface = dev->interface;
117  setintf.altsetting = alternate;
118
119  ret = ioctl(dev->fd, IOCTL_USB_SETINTF, &setintf);
120  if (ret < 0)
121    USB_ERROR_STR(-errno, "could not set alt intf %d/%d: %s",
122	dev->interface, alternate, strerror(errno));
123
124  dev->altsetting = alternate;
125
126  return 0;
127}
128
129/*
130 * Linux usbfs has a limit of one page size for synchronous bulk read/write.
131 * 4096 is the most portable maximum we can do for now.
132 * Linux usbfs has a limit of 16KB for the URB interface. We use this now
133 * to get better performance for USB 2.0 devices.
134 */
135#define MAX_READ_WRITE	(16 * 1024)
136
137int usb_control_msg(usb_dev_handle *dev, int requesttype, int request,
138	int value, int index, char *bytes, int size, int timeout)
139{
140  struct usb_ctrltransfer ctrl;
141  int ret;
142
143  ctrl.bRequestType = requesttype;
144  ctrl.bRequest = request;
145  ctrl.wValue = value;
146  ctrl.wIndex = index;
147  ctrl.wLength = size;
148
149  ctrl.data = bytes;
150  ctrl.timeout = timeout;
151
152  ret = ioctl(dev->fd, IOCTL_USB_CONTROL, &ctrl);
153  if (ret < 0)
154    USB_ERROR_STR(-errno, "error sending control message: %s", strerror(errno));
155
156  return ret;
157}
158
159#define URB_USERCONTEXT_COOKIE		((void *)0x1)
160
161/* Reading and writing are the same except for the endpoint */
162static int usb_urb_transfer(usb_dev_handle *dev, int ep, int urbtype,
163	char *bytes, int size, int timeout)
164{
165  struct usb_urb urb;
166  int bytesdone = 0, requested;
167  struct timeval tv, tv_ref, tv_now;
168  struct usb_urb *context;
169  int ret, waiting;
170
171  /*
172   * HACK: The use of urb.usercontext is a hack to get threaded applications
173   * sort of working again. Threaded support is still not recommended, but
174   * this should allow applications to work in the common cases. Basically,
175   * if we get the completion for an URB we're not waiting for, then we update
176   * the usercontext pointer to 1 for the other threads URB and it will see
177   * the change after it wakes up from the the timeout. Ugly, but it works.
178   */
179
180  /*
181   * Get actual time, and add the timeout value. The result is the absolute
182   * time where we have to quit waiting for an message.
183   */
184  gettimeofday(&tv_ref, NULL);
185  tv_ref.tv_sec = tv_ref.tv_sec + timeout / 1000;
186  tv_ref.tv_usec = tv_ref.tv_usec + (timeout % 1000) * 1000;
187
188  if (tv_ref.tv_usec > 1000000) {
189    tv_ref.tv_usec -= 1000000;
190    tv_ref.tv_sec++;
191  }
192
193  do {
194    fd_set writefds;
195
196    requested = size - bytesdone;
197    if (requested > MAX_READ_WRITE)
198      requested = MAX_READ_WRITE;
199
200    urb.type = urbtype;
201    urb.endpoint = ep;
202    urb.flags = 0;
203    urb.buffer = bytes + bytesdone;
204    urb.buffer_length = requested;
205    urb.signr = 0;
206    urb.actual_length = 0;
207    urb.number_of_packets = 0;	/* don't do isochronous yet */
208    urb.usercontext = NULL;
209
210    ret = ioctl(dev->fd, IOCTL_USB_SUBMITURB, &urb);
211    if (ret < 0) {
212      USB_ERROR_STR(-errno, "error submitting URB: %s", strerror(errno));
213      return ret;
214    }
215
216    FD_ZERO(&writefds);
217    FD_SET(dev->fd, &writefds);
218
219restart:
220    waiting = 1;
221    context = NULL;
222    while (!urb.usercontext && ((ret = ioctl(dev->fd, IOCTL_USB_REAPURBNDELAY, &context)) == -1) && waiting) {
223      tv.tv_sec = 0;
224      tv.tv_usec = 1000; // 1 msec
225      select(dev->fd + 1, NULL, &writefds, NULL, &tv); //sub second wait
226
227      if (timeout && timeout!=32767) {	// 32767 is a magic number for no timeout
228        /* compare with actual time, as the select timeout is not that precise */
229        gettimeofday(&tv_now, NULL);
230
231        if ((tv_now.tv_sec > tv_ref.tv_sec) ||
232            ((tv_now.tv_sec == tv_ref.tv_sec) && (tv_now.tv_usec >= tv_ref.tv_usec)))
233          waiting = 0;
234      }
235    }
236
237    if (context && context != &urb) {
238      context->usercontext = URB_USERCONTEXT_COOKIE;
239      /* We need to restart since we got a successful URB, but not ours */
240      goto restart;
241    }
242
243    /*
244     * If there was an error, that wasn't EAGAIN (no completion), then
245     * something happened during the reaping and we should return that
246     * error now
247     */
248    if (ret < 0 && !urb.usercontext && errno != EAGAIN)
249      USB_ERROR_STR(-errno, "error reaping URB: %s", strerror(errno));
250
251    bytesdone += urb.actual_length;
252  } while ((ret == 0 || urb.usercontext) && bytesdone < size && urb.actual_length == requested);
253
254  /* If the URB didn't complete in success or error, then let's unlink it */
255  if (ret < 0 && !urb.usercontext) {
256    int rc;
257
258    if (!waiting)
259      rc = -ETIMEDOUT;
260    else
261      rc = urb.status;
262
263    ret = ioctl(dev->fd, IOCTL_USB_DISCARDURB, &urb);
264    if (ret < 0 && errno != EINVAL && usb_debug >= 1)
265      fprintf(stderr, "error discarding URB: %s", strerror(errno));
266
267    /*
268     * When the URB is unlinked, it gets moved to the completed list and
269     * then we need to reap it or else the next time we call this function,
270     * we'll get the previous completion and exit early
271     */
272    ioctl(dev->fd, IOCTL_USB_REAPURB, &context);
273
274    return rc;
275  }
276
277  return bytesdone;
278}
279
280/* Reading and writing are the same except for the endpoint */
281static int usb_urb_transfer_sp(usb_dev_handle *dev, int ep, int urbtype,
282	char *bytes, int size, int timeout, int *actual_length, int max_rw)
283{
284  struct usb_urb urb;
285  int bytesdone = 0, requested;
286  struct timeval tv, tv_ref, tv_now;
287  struct usb_urb *context;
288  int ret, waiting;
289
290  /*
291   * HACK: The use of urb.usercontext is a hack to get threaded applications
292   * sort of working again. Threaded support is still not recommended, but
293   * this should allow applications to work in the common cases. Basically,
294   * if we get the completion for an URB we're not waiting for, then we update
295   * the usercontext pointer to 1 for the other threads URB and it will see
296   * the change after it wakes up from the the timeout. Ugly, but it works.
297   */
298
299  /*
300   * Get actual time, and add the timeout value. The result is the absolute
301   * time where we have to quit waiting for an message.
302   */
303  gettimeofday(&tv_ref, NULL);
304  tv_ref.tv_sec = tv_ref.tv_sec + timeout / 1000;
305  tv_ref.tv_usec = tv_ref.tv_usec + (timeout % 1000) * 1000;
306
307  if (tv_ref.tv_usec > 1000000) {
308    tv_ref.tv_usec -= 1000000;
309    tv_ref.tv_sec++;
310  }
311
312  do {
313    fd_set writefds;
314
315    requested = size - bytesdone;
316    if (requested > max_rw)
317      requested = max_rw;
318
319    urb.type = urbtype;
320    urb.endpoint = ep;
321    urb.flags = 0;
322    urb.buffer = bytes + bytesdone;
323    urb.buffer_length = requested;
324    urb.signr = 0;
325    urb.actual_length = 0;
326    urb.number_of_packets = 0;	/* don't do isochronous yet */
327    urb.usercontext = NULL;
328
329    ret = ioctl(dev->fd, IOCTL_USB_SUBMITURB, &urb);
330    if (ret < 0) {
331      USB_ERROR_STR(-errno, "error submitting URB: %s", strerror(errno));
332      return ret;
333    }
334
335    FD_ZERO(&writefds);
336    FD_SET(dev->fd, &writefds);
337
338restart:
339    waiting = 1;
340    context = NULL;
341    while (!urb.usercontext && ((ret = ioctl(dev->fd, IOCTL_USB_REAPURBNDELAY, &context)) == -1) && waiting) {
342      tv.tv_sec = 0;
343      tv.tv_usec = 1000; // 1 msec
344      select(dev->fd + 1, NULL, &writefds, NULL, &tv); //sub second wait
345
346      if (timeout) {
347        /* compare with actual time, as the select timeout is not that precise */
348        gettimeofday(&tv_now, NULL);
349
350        if ((tv_now.tv_sec > tv_ref.tv_sec) ||
351            ((tv_now.tv_sec == tv_ref.tv_sec) && (tv_now.tv_usec >= tv_ref.tv_usec)))
352          waiting = 0;
353      }
354    }
355
356    if (context && context != &urb) {
357      context->usercontext = URB_USERCONTEXT_COOKIE;
358      /* We need to restart since we got a successful URB, but not ours */
359      goto restart;
360    }
361
362    /*
363     * If there was an error, that wasn't EAGAIN (no completion), then
364     * something happened during the reaping and we should return that
365     * error now
366     */
367    if (ret < 0 && !urb.usercontext && errno != EAGAIN)
368      USB_ERROR_STR(-errno, "error reaping URB: %s", strerror(errno));
369
370    bytesdone += urb.actual_length;
371    *actual_length = bytesdone;
372  } while ((ret == 0 || urb.usercontext) && bytesdone < size && urb.actual_length == requested);
373
374  /* If the URB didn't complete in success or error, then let's unlink it */
375  if (ret < 0 && !urb.usercontext) {
376    int rc;
377
378    if (!waiting)
379      rc = -ETIMEDOUT;
380    else
381      rc = urb.status;
382
383    ret = ioctl(dev->fd, IOCTL_USB_DISCARDURB, &urb);
384    if (ret < 0 && errno != EINVAL && usb_debug >= 1)
385      fprintf(stderr, "error discarding URB: %s", strerror(errno));
386
387    /*
388     * When the URB is unlinked, it gets moved to the completed list and
389     * then we need to reap it or else the next time we call this function,
390     * we'll get the previous completion and exit early
391     */
392    ioctl(dev->fd, IOCTL_USB_REAPURB, &context);
393
394    return rc;
395  }
396
397  return bytesdone;
398}
399
400#if 0
401#define PAGE_SIZE (4 * 1024)
402
403static int usb_urb_transfer_sp(usb_dev_handle *dev, int ep, int urbtype,
404	char *bytes, int size, int timeout)
405{
406  struct usb_bulk bulk;
407  int ret;
408
409  bulk.ep = ep;
410  if (size > PAGE_SIZE)
411  	bulk.len = PAGE_SIZE;
412  else
413  	bulk.len = size;
414  bulk.timeout = timeout;
415  bulk.data = bytes;
416
417  ret = ioctl(dev->fd, IOCTL_USB_BULK, &bulk);
418
419  if (ret < 0)
420    return -errno;
421  else
422    return ret;
423}
424#endif
425int usb_bulk_write(usb_dev_handle *dev, int ep, char *bytes, int size,
426	int timeout)
427{
428  /* Ensure the endpoint address is correct */
429  return usb_urb_transfer(dev, ep, USB_URB_TYPE_BULK, bytes, size,
430		timeout);
431}
432
433int usb_bulk_write_sp(usb_dev_handle *dev, int ep, char *bytes, int size,
434	int timeout, int *actual_length, int max_rw)
435{
436  /* Ensure the endpoint address is correct */
437  return usb_urb_transfer_sp(dev, ep, USB_URB_TYPE_BULK, bytes, size,
438		timeout, actual_length, max_rw);
439}
440
441int usb_bulk_read(usb_dev_handle *dev, int ep, char *bytes, int size,
442	int timeout)
443{
444  /* Ensure the endpoint address is correct */
445  ep |= USB_ENDPOINT_IN;
446  return usb_urb_transfer(dev, ep, USB_URB_TYPE_BULK, bytes, size,
447		timeout);
448}
449
450/*
451 * FIXME: Packetize large buffers here. 2.4 HCDs (atleast, haven't checked
452 * 2.5 HCDs yet) don't handle multi-packet Interrupt transfers. So we need
453 * to lookup the endpoint packet size and packetize appropriately here.
454 */
455int usb_interrupt_write(usb_dev_handle *dev, int ep, char *bytes, int size,
456	int timeout)
457{
458  /* Ensure the endpoint address is correct */
459  return usb_urb_transfer(dev, ep, USB_URB_TYPE_INTERRUPT, bytes, size,
460		timeout);
461}
462
463int usb_interrupt_read(usb_dev_handle *dev, int ep, char *bytes, int size,
464	int timeout)
465{
466  /* Ensure the endpoint address is correct */
467  ep |= USB_ENDPOINT_IN;
468  return usb_urb_transfer(dev, ep, USB_URB_TYPE_INTERRUPT, bytes, size,
469		timeout);
470}
471
472int usb_os_find_busses(struct usb_bus **busses)
473{
474  struct usb_bus *fbus = NULL;
475  DIR *dir;
476  struct dirent *entry;
477
478  dir = opendir(usb_path);
479  if (!dir)
480    USB_ERROR_STR(-errno, "couldn't opendir(%s): %s", usb_path,
481	strerror(errno));
482
483  while ((entry = readdir(dir)) != NULL) {
484    struct usb_bus *bus;
485
486    /* Skip anything starting with a . */
487    if (entry->d_name[0] == '.')
488      continue;
489
490    if (!strchr("0123456789", entry->d_name[strlen(entry->d_name) - 1])) {
491      if (usb_debug >= 2)
492        fprintf(stderr, "usb_os_find_busses: Skipping non bus directory %s\n",
493		entry->d_name);
494      continue;
495    }
496
497    bus = malloc(sizeof(*bus));
498    if (!bus)
499      USB_ERROR(-ENOMEM);
500
501    memset((void *)bus, 0, sizeof(*bus));
502
503    strncpy(bus->dirname, entry->d_name, sizeof(bus->dirname) - 1);
504    bus->dirname[sizeof(bus->dirname) - 1] = 0;
505
506    LIST_ADD(fbus, bus);
507
508    if (usb_debug >= 2)
509       fprintf(stderr, "usb_os_find_busses: Found %s\n", bus->dirname);
510  }
511
512  closedir(dir);
513
514  *busses = fbus;
515
516  return 0;
517}
518
519int usb_os_find_devices(struct usb_bus *bus, struct usb_device **devices)
520{
521  struct usb_device *fdev = NULL;
522  DIR *dir;
523  struct dirent *entry;
524  char dirpath[PATH_MAX + 1];
525
526  snprintf(dirpath, PATH_MAX, "%s/%s", usb_path, bus->dirname);
527
528  dir = opendir(dirpath);
529  if (!dir)
530    USB_ERROR_STR(-errno, "couldn't opendir(%s): %s", dirpath,
531	strerror(errno));
532
533  while ((entry = readdir(dir)) != NULL) {
534    unsigned char device_desc[DEVICE_DESC_LENGTH];
535    char filename[PATH_MAX + 1];
536    struct usb_device *dev;
537    struct usb_connectinfo connectinfo;
538    int i, fd, ret;
539
540    /* Skip anything starting with a . */
541    if (entry->d_name[0] == '.')
542      continue;
543
544    dev = malloc(sizeof(*dev));
545    if (!dev)
546      USB_ERROR(-ENOMEM);
547
548    memset((void *)dev, 0, sizeof(*dev));
549
550    dev->bus = bus;
551
552    strncpy(dev->filename, entry->d_name, sizeof(dev->filename) - 1);
553    dev->filename[sizeof(dev->filename) - 1] = 0;
554
555    snprintf(filename, sizeof(filename) - 1, "%s/%s", dirpath, entry->d_name);
556    fd = open(filename, O_RDWR);
557    if (fd < 0) {
558      fd = open(filename, O_RDONLY);
559      if (fd < 0) {
560        if (usb_debug >= 2)
561          fprintf(stderr, "usb_os_find_devices: Couldn't open %s\n",
562                  filename);
563
564        free(dev);
565        continue;
566      }
567    }
568
569    /* Get the device number */
570    ret = ioctl(fd, IOCTL_USB_CONNECTINFO, &connectinfo);
571    if (ret < 0) {
572      if (usb_debug)
573        fprintf(stderr, "usb_os_find_devices: couldn't get connect info\n");
574    } else
575      dev->devnum = connectinfo.devnum;
576
577    ret = read(fd, (void *)device_desc, DEVICE_DESC_LENGTH);
578    if (ret < 0) {
579      if (usb_debug)
580        fprintf(stderr, "usb_os_find_devices: Couldn't read descriptor\n");
581
582      free(dev);
583
584      goto err;
585    }
586
587    /*
588     * Linux kernel converts the words in this descriptor to CPU endian, so
589     * we use the undocumented W character for usb_parse_descriptor() that
590     * doesn't convert endianess when parsing the descriptor
591     */
592    usb_parse_descriptor(device_desc, "bbWbbbbWWWbbbb", &dev->descriptor);
593
594    LIST_ADD(fdev, dev);
595
596    if (usb_debug >= 2)
597      fprintf(stderr, "usb_os_find_devices: Found %s on %s\n",
598		dev->filename, bus->dirname);
599
600    /* Now try to fetch the rest of the descriptors */
601    if (dev->descriptor.bNumConfigurations > USB_MAXCONFIG)
602      /* Silent since we'll try again later */
603      goto err;
604
605    if (dev->descriptor.bNumConfigurations < 1)
606      /* Silent since we'll try again later */
607      goto err;
608
609    dev->config = (struct usb_config_descriptor *)malloc(dev->descriptor.bNumConfigurations * sizeof(struct usb_config_descriptor));
610    if (!dev->config)
611      /* Silent since we'll try again later */
612      goto err;
613
614    memset(dev->config, 0, dev->descriptor.bNumConfigurations *
615          sizeof(struct usb_config_descriptor));
616
617    for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
618      unsigned char buffer[8], *bigbuffer;
619      struct usb_config_descriptor config;
620
621      /* Get the first 8 bytes so we can figure out what the total length is */
622      ret = read(fd, (void *)buffer, 8);
623      if (ret < 8) {
624        if (usb_debug >= 1) {
625          if (ret < 0)
626            fprintf(stderr, "Unable to get descriptor (%d)\n", ret);
627          else
628            fprintf(stderr, "Config descriptor too short (expected %d, got %d)\n", 8, ret);
629        }
630
631        goto err;
632      }
633
634      usb_parse_descriptor(buffer, "bbw", &config);
635
636      bigbuffer = malloc(config.wTotalLength);
637      if (!bigbuffer) {
638        if (usb_debug >= 1)
639          fprintf(stderr, "Unable to allocate memory for descriptors\n");
640        goto err;
641      }
642
643      /* Read the rest of the config descriptor */
644      memcpy(bigbuffer, buffer, 8);
645
646      ret = read(fd, (void *)(bigbuffer + 8), config.wTotalLength - 8);
647      if (ret < config.wTotalLength - 8) {
648        if (usb_debug >= 1) {
649          if (ret < 0)
650            fprintf(stderr, "Unable to get descriptor (%d)\n", ret);
651          else
652            fprintf(stderr, "Config descriptor too short (expected %d, got %d)\n", config.wTotalLength, ret);
653        }
654
655        free(bigbuffer);
656        goto err;
657      }
658
659      ret = usb_parse_configuration(&dev->config[i], bigbuffer);
660      if (usb_debug >= 2) {
661        if (ret > 0)
662          fprintf(stderr, "Descriptor data still left\n");
663        else if (ret < 0)
664          fprintf(stderr, "Unable to parse descriptors\n");
665      }
666
667      free(bigbuffer);
668    }
669
670err:
671    close(fd);
672  }
673
674  closedir(dir);
675
676  *devices = fdev;
677
678  return 0;
679}
680
681int usb_os_determine_children(struct usb_bus *bus)
682{
683  struct usb_device *dev, *devices[256];
684  struct usb_ioctl command;
685  int ret, i, i1;
686
687  /* Create a list of devices first */
688  memset(devices, 0, sizeof(devices));
689  for (dev = bus->devices; dev; dev = dev->next)
690    if (dev->devnum)
691      devices[dev->devnum] = dev;
692
693  /* Now fetch the children for each device */
694  for (dev = bus->devices; dev; dev = dev->next) {
695    struct usb_hub_portinfo portinfo;
696    int fd;
697
698    fd = device_open(dev);
699    if (fd < 0)
700      continue;
701
702    /* Query the hub driver for the children of this device */
703    if (dev->config && dev->config->interface && dev->config->interface->altsetting)
704      command.ifno = dev->config->interface->altsetting->bInterfaceNumber;
705    else
706      command.ifno = 0;
707    command.ioctl_code = IOCTL_USB_HUB_PORTINFO;
708    command.data = &portinfo;
709    ret = ioctl(fd, IOCTL_USB_IOCTL, &command);
710    if (ret < 0) {
711      /* errno == ENOSYS means the device probably wasn't a hub */
712      if (errno != ENOSYS && usb_debug > 1)
713        fprintf(stderr, "error obtaining child information: %s\n",
714		strerror(errno));
715
716      close(fd);
717      continue;
718    }
719
720    dev->num_children = 0;
721    for (i = 0; i < portinfo.numports; i++)
722      if (portinfo.port[i])
723        dev->num_children++;
724
725    /* Free any old children first */
726    free(dev->children);
727
728    dev->children = malloc(sizeof(struct usb_device *) * dev->num_children);
729    if (!dev->children) {
730      if (usb_debug > 1)
731        fprintf(stderr, "error allocating %zu bytes memory for dev->children\n",
732                sizeof(struct usb_device *) * dev->num_children);
733
734      dev->num_children = 0;
735      close(fd);
736      continue;
737    }
738
739    for (i = 0, i1 = 0; i < portinfo.numports; i++) {
740      if (!portinfo.port[i])
741        continue;
742
743      dev->children[i1++] = devices[portinfo.port[i]];
744
745      devices[portinfo.port[i]] = NULL;
746    }
747
748    close(fd);
749  }
750
751  /*
752   * There should be one device left in the devices list and that should be
753   * the root device
754   */
755  for (i = 0; i < sizeof(devices) / sizeof(devices[0]); i++) {
756    if (devices[i])
757      bus->root_dev = devices[i];
758  }
759
760  return 0;
761}
762
763static int check_usb_vfs(const char *dirname)
764{
765  DIR *dir;
766  struct dirent *entry;
767  int found = 0;
768
769  dir = opendir(dirname);
770  if (!dir)
771    return 0;
772
773  while ((entry = readdir(dir)) != NULL) {
774    /* Skip anything starting with a . */
775    if (entry->d_name[0] == '.')
776      continue;
777
778    /* We assume if we find any files that it must be the right place */
779    found = 1;
780    break;
781  }
782
783  closedir(dir);
784
785  return found;
786}
787
788void usb_os_init(void)
789{
790  /* Find the path to the virtual filesystem */
791  if (getenv("USB_DEVFS_PATH")) {
792    if (check_usb_vfs(getenv("USB_DEVFS_PATH"))) {
793      strncpy(usb_path, getenv("USB_DEVFS_PATH"), sizeof(usb_path) - 1);
794      usb_path[sizeof(usb_path) - 1] = 0;
795    } else if (usb_debug)
796      fprintf(stderr, "usb_os_init: couldn't find USB VFS in USB_DEVFS_PATH\n");
797  }
798
799  if (!usb_path[0]) {
800    if (check_usb_vfs("/dev/bus/usb")) {
801      strncpy(usb_path, "/dev/bus/usb", sizeof(usb_path) - 1);
802      usb_path[sizeof(usb_path) - 1] = 0;
803    } else if (check_usb_vfs("/proc/bus/usb")) {
804      strncpy(usb_path, "/proc/bus/usb", sizeof(usb_path) - 1);
805      usb_path[sizeof(usb_path) - 1] = 0;
806    } else
807      usb_path[0] = 0;	/* No path, no USB support */
808  }
809
810  if (usb_debug) {
811    if (usb_path[0])
812      fprintf(stderr, "usb_os_init: Found USB VFS at %s\n", usb_path);
813    else
814      fprintf(stderr, "usb_os_init: No USB VFS found, is it mounted?\n");
815  }
816}
817
818int usb_resetep(usb_dev_handle *dev, unsigned int ep)
819{
820  int ret;
821
822  ret = ioctl(dev->fd, IOCTL_USB_RESETEP, &ep);
823  if (ret)
824    USB_ERROR_STR(-errno, "could not reset ep %d: %s", ep,
825    	strerror(errno));
826
827  return 0;
828}
829
830int usb_clear_halt(usb_dev_handle *dev, unsigned int ep)
831{
832  int ret;
833
834  ret = ioctl(dev->fd, IOCTL_USB_CLEAR_HALT, &ep);
835  if (ret)
836    USB_ERROR_STR(-errno, "could not clear/halt ep %d: %s", ep,
837    	strerror(errno));
838
839  return 0;
840}
841
842int usb_reset(usb_dev_handle *dev)
843{
844  int ret;
845
846  ret = ioctl(dev->fd, IOCTL_USB_RESET, NULL);
847  if (ret)
848     USB_ERROR_STR(-errno, "could not reset: %s", strerror(errno));
849
850  return 0;
851}
852
853int usb_get_driver_np(usb_dev_handle *dev, int interface, char *name,
854	unsigned int namelen)
855{
856  struct usb_getdriver getdrv;
857  int ret;
858
859  getdrv.interface = interface;
860  ret = ioctl(dev->fd, IOCTL_USB_GETDRIVER, &getdrv);
861  if (ret)
862    USB_ERROR_STR(-errno, "could not get bound driver: %s", strerror(errno));
863
864  strncpy(name, getdrv.driver, namelen - 1);
865  name[namelen - 1] = 0;
866
867  return 0;
868}
869
870int usb_detach_kernel_driver_np(usb_dev_handle *dev, int interface)
871{
872  struct usb_ioctl command;
873  int ret;
874
875  command.ifno = interface;
876  command.ioctl_code = IOCTL_USB_DISCONNECT;
877  command.data = NULL;
878
879  ret = ioctl(dev->fd, IOCTL_USB_IOCTL, &command);
880  if (ret)
881    USB_ERROR_STR(-errno, "could not detach kernel driver from interface %d: %s",
882        interface, strerror(errno));
883
884  return 0;
885}
886
887