aboutsummaryrefslogtreecommitdiffstats
path: root/at91sam7/host/usb.c
blob: 1d3aaf49aec0585fe9f1ebf1421b59acc553e2b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <usb.h>
#include <sys/ioctl.h>
#include "usb.h"
#include <linux/usbdevice_fs.h>

#define MAX_READ_WRITE	4096

#define USB_ERROR_STR(ret, x, args...)	return ret

static int usb_get_fd(usb_dev_handle *uh)
{
	return *((int *)uh);
}

int __usb_bulk_write(usb_dev_handle *dev, int ep, char *bytes, int length,
		     int timeout)
{
	struct usbdevfs_bulktransfer bulk;
	int ret, sent = 0;

	/* Ensure the endpoint address is correct */
	ep &= ~USB_ENDPOINT_IN;

	do {
		bulk.ep = ep;
		bulk.len = length - sent;
		if (bulk.len > MAX_READ_WRITE)
			bulk.len = MAX_READ_WRITE;
		bulk.timeout = timeout;
		bulk.data = (unsigned char *)bytes + sent;

		ret = ioctl(usb_get_fd(dev), USBDEVFS_BULK, &bulk);
		if (ret < 0)
			USB_ERROR_STR(ret,
				      "error writing to bulk endpoint %d: %s",
				      ep, strerror(errno));

		sent += ret;
	} while (ret > 0 && sent < length);

	return sent;
}

int __usb_bulk_read(usb_dev_handle *dev, int ep, char *bytes, int size,
		    int timeout)
{
	struct usbdevfs_bulktransfer bulk;
	int ret, retrieved = 0, requested;

	/* Ensure the endpoint address is correct */
	ep |= USB_ENDPOINT_IN;

	do {
		bulk.ep = ep;
		requested = size - retrieved;
		if (requested > MAX_READ_WRITE)
			requested = MAX_READ_WRITE;
		bulk.len = requested;
		bulk.timeout = timeout;
		bulk.data = (unsigned char *)bytes + retrieved;

		ret = ioctl(usb_get_fd(dev), USBDEVFS_BULK, &bulk);
		if (ret < 0)
			USB_ERROR_STR(ret,
				      "error reading from bulk endpoint 0x%x: %s",
				      ep, strerror(errno));

		retrieved += ret;
	} while (ret > 0 && retrieved < size && ret == requested);

	return retrieved;
}

int __usb_reattach_kernel_driver_np(usb_dev_handle *dev, int interface)
{
	struct usbdevfs_ioctl command;

	command.ifno = interface;
	command.ioctl_code = USBDEVFS_CONNECT;
	command.data = NULL;

	return ioctl(usb_get_fd(dev), USBDEVFS_IOCTL, &command);
}