jtag: drivers: provide initial support for usb path filtering
[fw/openocd] / src / jtag / drivers / libusb1_common.c
1 /***************************************************************************
2  *   Copyright (C) 2009 by Zachary T Welch <zw@superlucidity.net>          *
3  *                                                                         *
4  *   Copyright (C) 2011 by Mauro Gamba <maurillo71@gmail.com>              *
5  *                                                                         *
6  *   This program is free software; you can redistribute it and/or modify  *
7  *   it under the terms of the GNU General Public License as published by  *
8  *   the Free Software Foundation; either version 2 of the License, or     *
9  *   (at your option) any later version.                                   *
10  *                                                                         *
11  *   This program is distributed in the hope that it will be useful,       *
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14  *   GNU General Public License for more details.                          *
15  *                                                                         *
16  *   You should have received a copy of the GNU General Public License     *
17  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
18  ***************************************************************************/
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23 #include <jtag/drivers/jtag_usb_common.h>
24 #include "libusb1_common.h"
25 #include "log.h"
26
27 /*
28  * comment from libusb:
29  * As per the USB 3.0 specs, the current maximum limit for the depth is 7.
30  */
31 #define MAX_USB_PORTS   7
32
33 static struct libusb_context *jtag_libusb_context; /**< Libusb context **/
34 static libusb_device **devs; /**< The usb device list **/
35
36 static bool jtag_libusb_match(struct libusb_device_descriptor *dev_desc,
37                 const uint16_t vids[], const uint16_t pids[])
38 {
39         for (unsigned i = 0; vids[i]; i++) {
40                 if (dev_desc->idVendor == vids[i] &&
41                         dev_desc->idProduct == pids[i]) {
42                         return true;
43                 }
44         }
45         return false;
46 }
47
48 #ifdef HAVE_LIBUSB_GET_PORT_NUMBERS
49 static bool jtag_libusb_location_equal(libusb_device *device)
50 {
51         uint8_t port_path[MAX_USB_PORTS];
52         uint8_t dev_bus;
53         int path_len;
54
55         path_len = libusb_get_port_numbers(device, port_path, MAX_USB_PORTS);
56         if (path_len == LIBUSB_ERROR_OVERFLOW) {
57                 LOG_WARNING("cannot determine path to usb device! (more than %i ports in path)\n",
58                         MAX_USB_PORTS);
59                 return false;
60         }
61         dev_bus = libusb_get_bus_number(device);
62
63         return jtag_usb_location_equal(dev_bus, port_path, path_len);
64 }
65 #else /* HAVE_LIBUSB_GET_PORT_NUMBERS */
66 static bool jtag_libusb_location_equal(libusb_device *device)
67 {
68         return true;
69 }
70 #endif /* HAVE_LIBUSB_GET_PORT_NUMBERS */
71
72
73 /* Returns true if the string descriptor indexed by str_index in device matches string */
74 static bool string_descriptor_equal(libusb_device_handle *device, uint8_t str_index,
75                                                                         const char *string)
76 {
77         int retval;
78         bool matched;
79         char desc_string[256+1]; /* Max size of string descriptor */
80
81         if (str_index == 0)
82                 return false;
83
84         retval = libusb_get_string_descriptor_ascii(device, str_index,
85                         (unsigned char *)desc_string, sizeof(desc_string)-1);
86         if (retval < 0) {
87                 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %d", retval);
88                 return false;
89         }
90
91         /* Null terminate descriptor string in case it needs to be logged. */
92         desc_string[sizeof(desc_string)-1] = '\0';
93
94         matched = strncmp(string, desc_string, sizeof(desc_string)) == 0;
95         if (!matched)
96                 LOG_DEBUG("Device serial number '%s' doesn't match requested serial '%s'",
97                         desc_string, string);
98         return matched;
99 }
100
101 int jtag_libusb_open(const uint16_t vids[], const uint16_t pids[],
102                 const char *serial,
103                 struct jtag_libusb_device_handle **out)
104 {
105         int cnt, idx, errCode;
106         int retval = ERROR_FAIL;
107         bool serial_mismatch = false;
108         struct jtag_libusb_device_handle *libusb_handle = NULL;
109
110         if (libusb_init(&jtag_libusb_context) < 0)
111                 return ERROR_FAIL;
112
113         cnt = libusb_get_device_list(jtag_libusb_context, &devs);
114
115         for (idx = 0; idx < cnt; idx++) {
116                 struct libusb_device_descriptor dev_desc;
117
118                 if (libusb_get_device_descriptor(devs[idx], &dev_desc) != 0)
119                         continue;
120
121                 if (!jtag_libusb_match(&dev_desc, vids, pids))
122                         continue;
123
124                 if (jtag_usb_get_location() && !jtag_libusb_location_equal(devs[idx]))
125                         continue;
126
127                 errCode = libusb_open(devs[idx], &libusb_handle);
128
129                 if (errCode) {
130                         LOG_ERROR("libusb_open() failed with %s",
131                                   libusb_error_name(errCode));
132                         continue;
133                 }
134
135                 /* Device must be open to use libusb_get_string_descriptor_ascii. */
136                 if (serial != NULL &&
137                                 !string_descriptor_equal(libusb_handle, dev_desc.iSerialNumber, serial)) {
138                         serial_mismatch = true;
139                         libusb_close(libusb_handle);
140                         continue;
141                 }
142
143                 /* Success. */
144                 *out = libusb_handle;
145                 retval = ERROR_OK;
146                 serial_mismatch = false;
147                 break;
148         }
149         if (cnt >= 0)
150                 libusb_free_device_list(devs, 1);
151
152         if (serial_mismatch)
153                 LOG_INFO("No device matches the serial string");
154
155         return retval;
156 }
157
158 void jtag_libusb_close(jtag_libusb_device_handle *dev)
159 {
160         /* Close device */
161         libusb_close(dev);
162
163         libusb_exit(jtag_libusb_context);
164 }
165
166 int jtag_libusb_control_transfer(jtag_libusb_device_handle *dev, uint8_t requestType,
167                 uint8_t request, uint16_t wValue, uint16_t wIndex, char *bytes,
168                 uint16_t size, unsigned int timeout)
169 {
170         int transferred = 0;
171
172         transferred = libusb_control_transfer(dev, requestType, request, wValue, wIndex,
173                                 (unsigned char *)bytes, size, timeout);
174
175         if (transferred < 0)
176                 transferred = 0;
177
178         return transferred;
179 }
180
181 int jtag_libusb_bulk_write(jtag_libusb_device_handle *dev, int ep, char *bytes,
182                 int size, int timeout)
183 {
184         int transferred = 0;
185
186         libusb_bulk_transfer(dev, ep, (unsigned char *)bytes, size,
187                              &transferred, timeout);
188         return transferred;
189 }
190
191 int jtag_libusb_bulk_read(jtag_libusb_device_handle *dev, int ep, char *bytes,
192                 int size, int timeout)
193 {
194         int transferred = 0;
195
196         libusb_bulk_transfer(dev, ep, (unsigned char *)bytes, size,
197                              &transferred, timeout);
198         return transferred;
199 }
200
201 int jtag_libusb_set_configuration(jtag_libusb_device_handle *devh,
202                 int configuration)
203 {
204         struct jtag_libusb_device *udev = jtag_libusb_get_device(devh);
205         int retCode = -99;
206
207         struct libusb_config_descriptor *config = NULL;
208         int current_config = -1;
209
210         retCode = libusb_get_configuration(devh, &current_config);
211         if (retCode != 0)
212                 return retCode;
213
214         retCode = libusb_get_config_descriptor(udev, configuration, &config);
215         if (retCode != 0 || config == NULL)
216                 return retCode;
217
218         /* Only change the configuration if it is not already set to the
219            same one. Otherwise this issues a lightweight reset and hangs
220            LPC-Link2 with JLink firmware. */
221         if (current_config != config->bConfigurationValue)
222                 retCode = libusb_set_configuration(devh, config->bConfigurationValue);
223
224         libusb_free_config_descriptor(config);
225
226         return retCode;
227 }
228
229 int jtag_libusb_choose_interface(struct jtag_libusb_device_handle *devh,
230                 unsigned int *usb_read_ep,
231                 unsigned int *usb_write_ep,
232                 int bclass, int subclass, int protocol, int trans_type)
233 {
234         struct jtag_libusb_device *udev = jtag_libusb_get_device(devh);
235         const struct libusb_interface *inter;
236         const struct libusb_interface_descriptor *interdesc;
237         const struct libusb_endpoint_descriptor *epdesc;
238         struct libusb_config_descriptor *config;
239
240         *usb_read_ep = *usb_write_ep = 0;
241
242         libusb_get_config_descriptor(udev, 0, &config);
243         for (int i = 0; i < (int)config->bNumInterfaces; i++) {
244                 inter = &config->interface[i];
245
246                 interdesc = &inter->altsetting[0];
247                 for (int k = 0;
248                      k < (int)interdesc->bNumEndpoints; k++) {
249                         if ((bclass > 0 && interdesc->bInterfaceClass != bclass) ||
250                             (subclass > 0 && interdesc->bInterfaceSubClass != subclass) ||
251                             (protocol > 0 && interdesc->bInterfaceProtocol != protocol))
252                                 continue;
253
254                         epdesc = &interdesc->endpoint[k];
255                         if (trans_type > 0 && (epdesc->bmAttributes & 0x3) != trans_type)
256                                 continue;
257
258                         uint8_t epnum = epdesc->bEndpointAddress;
259                         bool is_input = epnum & 0x80;
260                         LOG_DEBUG("usb ep %s %02x",
261                                   is_input ? "in" : "out", epnum);
262
263                         if (is_input)
264                                 *usb_read_ep = epnum;
265                         else
266                                 *usb_write_ep = epnum;
267
268                         if (*usb_read_ep && *usb_write_ep) {
269                                 LOG_DEBUG("Claiming interface %d", (int)interdesc->bInterfaceNumber);
270                                 libusb_claim_interface(devh, (int)interdesc->bInterfaceNumber);
271                                 libusb_free_config_descriptor(config);
272                                 return ERROR_OK;
273                         }
274                 }
275         }
276         libusb_free_config_descriptor(config);
277
278         return ERROR_FAIL;
279 }
280
281 int jtag_libusb_get_pid(struct jtag_libusb_device *dev, uint16_t *pid)
282 {
283         struct libusb_device_descriptor dev_desc;
284
285         if (libusb_get_device_descriptor(dev, &dev_desc) == 0) {
286                 *pid = dev_desc.idProduct;
287
288                 return ERROR_OK;
289         }
290
291         return ERROR_FAIL;
292 }