1
|
#include <stdlib.h>
|
2
|
#include <stdio.h>
|
3
|
#include <unistd.h>
|
4
|
#include <errno.h>
|
5
|
#include <usb.h>
|
6
|
#include <sys/ioctl.h>
|
7
|
#include "usb.h"
|
8
|
#include <linux/usbdevice_fs.h>
|
9
|
|
10
|
#define MAX_READ_WRITE 4096
|
11
|
|
12
|
#define USB_ERROR_STR(ret, x, args...) return ret
|
13
|
|
14
|
static int usb_get_fd(usb_dev_handle *uh)
|
15
|
{
|
16
|
return *((int *)uh);
|
17
|
}
|
18
|
|
19
|
int __usb_bulk_write(usb_dev_handle *dev, int ep, char *bytes, int length,
|
20
|
int timeout)
|
21
|
{
|
22
|
struct usbdevfs_bulktransfer bulk;
|
23
|
int ret, sent = 0;
|
24
|
|
25
|
/* Ensure the endpoint address is correct */
|
26
|
ep &= ~USB_ENDPOINT_IN;
|
27
|
|
28
|
do {
|
29
|
bulk.ep = ep;
|
30
|
bulk.len = length - sent;
|
31
|
if (bulk.len > MAX_READ_WRITE)
|
32
|
bulk.len = MAX_READ_WRITE;
|
33
|
bulk.timeout = timeout;
|
34
|
bulk.data = (unsigned char *)bytes + sent;
|
35
|
|
36
|
ret = ioctl(usb_get_fd(dev), USBDEVFS_BULK, &bulk);
|
37
|
if (ret < 0)
|
38
|
USB_ERROR_STR(ret,
|
39
|
"error writing to bulk endpoint %d: %s",
|
40
|
ep, strerror(errno));
|
41
|
|
42
|
sent += ret;
|
43
|
} while (ret > 0 && sent < length);
|
44
|
|
45
|
return sent;
|
46
|
}
|
47
|
|
48
|
int __usb_bulk_read(usb_dev_handle *dev, int ep, char *bytes, int size,
|
49
|
int timeout)
|
50
|
{
|
51
|
struct usbdevfs_bulktransfer bulk;
|
52
|
int ret, retrieved = 0, requested;
|
53
|
|
54
|
/* Ensure the endpoint address is correct */
|
55
|
ep |= USB_ENDPOINT_IN;
|
56
|
|
57
|
do {
|
58
|
bulk.ep = ep;
|
59
|
requested = size - retrieved;
|
60
|
if (requested > MAX_READ_WRITE)
|
61
|
requested = MAX_READ_WRITE;
|
62
|
bulk.len = requested;
|
63
|
bulk.timeout = timeout;
|
64
|
bulk.data = (unsigned char *)bytes + retrieved;
|
65
|
|
66
|
ret = ioctl(usb_get_fd(dev), USBDEVFS_BULK, &bulk);
|
67
|
if (ret < 0)
|
68
|
USB_ERROR_STR(ret,
|
69
|
"error reading from bulk endpoint 0x%x: %s",
|
70
|
ep, strerror(errno));
|
71
|
|
72
|
retrieved += ret;
|
73
|
} while (ret > 0 && retrieved < size && ret == requested);
|
74
|
|
75
|
return retrieved;
|
76
|
}
|
77
|
|
78
|
int __usb_reattach_kernel_driver_np(usb_dev_handle *dev, int interface)
|
79
|
{
|
80
|
struct usbdevfs_ioctl command;
|
81
|
|
82
|
command.ifno = interface;
|
83
|
command.ioctl_code = USBDEVFS_CONNECT;
|
84
|
command.data = NULL;
|
85
|
|
86
|
return ioctl(usb_get_fd(dev), USBDEVFS_IOCTL, &command);
|
87
|
}
|