3308d8742c805d1e0ad08b3a45eda54d5bbb1381
[fw/openocd] / src / jtag / drivers / libusb_helper.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 <helper/log.h>
24 #include <jtag/drivers/jtag_usb_common.h>
25 #include "libusb_helper.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 struct libusb_device **devs; /**< The usb device list **/
35
36 static int jtag_libusb_error(int err)
37 {
38         switch (err) {
39         case LIBUSB_SUCCESS:
40                 return ERROR_OK;
41         case LIBUSB_ERROR_TIMEOUT:
42                 return ERROR_TIMEOUT_REACHED;
43         case LIBUSB_ERROR_IO:
44         case LIBUSB_ERROR_INVALID_PARAM:
45         case LIBUSB_ERROR_ACCESS:
46         case LIBUSB_ERROR_NO_DEVICE:
47         case LIBUSB_ERROR_NOT_FOUND:
48         case LIBUSB_ERROR_BUSY:
49         case LIBUSB_ERROR_OVERFLOW:
50         case LIBUSB_ERROR_PIPE:
51         case LIBUSB_ERROR_INTERRUPTED:
52         case LIBUSB_ERROR_NO_MEM:
53         case LIBUSB_ERROR_NOT_SUPPORTED:
54         case LIBUSB_ERROR_OTHER:
55                 return ERROR_FAIL;
56         default:
57                 return ERROR_FAIL;
58         }
59 }
60
61 static bool jtag_libusb_match_ids(struct libusb_device_descriptor *dev_desc,
62                 const uint16_t vids[], const uint16_t pids[])
63 {
64         for (unsigned i = 0; vids[i]; i++) {
65                 if (dev_desc->idVendor == vids[i] &&
66                         dev_desc->idProduct == pids[i]) {
67                         return true;
68                 }
69         }
70         return false;
71 }
72
73 #ifdef HAVE_LIBUSB_GET_PORT_NUMBERS
74 static bool jtag_libusb_location_equal(struct libusb_device *device)
75 {
76         uint8_t port_path[MAX_USB_PORTS];
77         uint8_t dev_bus;
78         int path_len;
79
80         path_len = libusb_get_port_numbers(device, port_path, MAX_USB_PORTS);
81         if (path_len == LIBUSB_ERROR_OVERFLOW) {
82                 LOG_WARNING("cannot determine path to usb device! (more than %i ports in path)\n",
83                         MAX_USB_PORTS);
84                 return false;
85         }
86         dev_bus = libusb_get_bus_number(device);
87
88         return jtag_usb_location_equal(dev_bus, port_path, path_len);
89 }
90 #else /* HAVE_LIBUSB_GET_PORT_NUMBERS */
91 static bool jtag_libusb_location_equal(struct libusb_device *device)
92 {
93         return true;
94 }
95 #endif /* HAVE_LIBUSB_GET_PORT_NUMBERS */
96
97
98 /* Returns true if the string descriptor indexed by str_index in device matches string */
99 static bool string_descriptor_equal(struct libusb_device_handle *device, uint8_t str_index,
100                                                                         const char *string)
101 {
102         int retval;
103         bool matched;
104         char desc_string[256+1]; /* Max size of string descriptor */
105
106         if (str_index == 0)
107                 return false;
108
109         retval = libusb_get_string_descriptor_ascii(device, str_index,
110                         (unsigned char *)desc_string, sizeof(desc_string)-1);
111         if (retval < 0) {
112                 LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %d", retval);
113                 return false;
114         }
115
116         /* Null terminate descriptor string in case it needs to be logged. */
117         desc_string[sizeof(desc_string)-1] = '\0';
118
119         matched = strncmp(string, desc_string, sizeof(desc_string)) == 0;
120         if (!matched)
121                 LOG_DEBUG("Device serial number '%s' doesn't match requested serial '%s'",
122                         desc_string, string);
123         return matched;
124 }
125
126 static bool jtag_libusb_match_serial(struct libusb_device_handle *device,
127                 struct libusb_device_descriptor *dev_desc, const char *serial,
128                 adapter_get_alternate_serial_fn adapter_get_alternate_serial)
129 {
130         if (string_descriptor_equal(device, dev_desc->iSerialNumber, serial))
131                 return true;
132
133         /* check the alternate serial helper */
134         if (!adapter_get_alternate_serial)
135                 return false;
136
137         /* get the alternate serial */
138         char *alternate_serial = adapter_get_alternate_serial(device, dev_desc);
139
140         /* check possible failures */
141         if (!alternate_serial)
142                 return false;
143
144         /* then compare and free the alternate serial */
145         bool match = false;
146         if (strcmp(serial, alternate_serial) == 0)
147                 match = true;
148         else
149                 LOG_DEBUG("Device alternate serial number '%s' doesn't match requested serial '%s'",
150                                 alternate_serial, serial);
151
152         free(alternate_serial);
153         return match;
154 }
155
156 int jtag_libusb_open(const uint16_t vids[], const uint16_t pids[],
157                 const char *serial,
158                 struct libusb_device_handle **out,
159                 adapter_get_alternate_serial_fn adapter_get_alternate_serial)
160 {
161         int cnt, idx, err_code;
162         int retval = ERROR_FAIL;
163         bool serial_mismatch = false;
164         struct libusb_device_handle *libusb_handle = NULL;
165
166         if (libusb_init(&jtag_libusb_context) < 0)
167                 return ERROR_FAIL;
168
169         cnt = libusb_get_device_list(jtag_libusb_context, &devs);
170
171         for (idx = 0; idx < cnt; idx++) {
172                 struct libusb_device_descriptor dev_desc;
173
174                 if (libusb_get_device_descriptor(devs[idx], &dev_desc) != 0)
175                         continue;
176
177                 if (!jtag_libusb_match_ids(&dev_desc, vids, pids))
178                         continue;
179
180                 if (jtag_usb_get_location() && !jtag_libusb_location_equal(devs[idx]))
181                         continue;
182
183                 err_code = libusb_open(devs[idx], &libusb_handle);
184
185                 if (err_code) {
186                         LOG_ERROR("libusb_open() failed with %s",
187                                   libusb_error_name(err_code));
188                         continue;
189                 }
190
191                 /* Device must be open to use libusb_get_string_descriptor_ascii. */
192                 if (serial &&
193                                 !jtag_libusb_match_serial(libusb_handle, &dev_desc, serial, adapter_get_alternate_serial)) {
194                         serial_mismatch = true;
195                         libusb_close(libusb_handle);
196                         continue;
197                 }
198
199                 /* Success. */
200                 *out = libusb_handle;
201                 retval = ERROR_OK;
202                 serial_mismatch = false;
203                 break;
204         }
205         if (cnt >= 0)
206                 libusb_free_device_list(devs, 1);
207
208         if (serial_mismatch)
209                 LOG_INFO("No device matches the serial string");
210
211         if (retval != ERROR_OK)
212                 libusb_exit(jtag_libusb_context);
213
214         return retval;
215 }
216
217 void jtag_libusb_close(struct libusb_device_handle *dev)
218 {
219         /* Close device */
220         libusb_close(dev);
221
222         libusb_exit(jtag_libusb_context);
223 }
224
225 int jtag_libusb_control_transfer(struct libusb_device_handle *dev, uint8_t request_type,
226                 uint8_t request, uint16_t value, uint16_t index, char *bytes,
227                 uint16_t size, unsigned int timeout)
228 {
229         int transferred = 0;
230
231         transferred = libusb_control_transfer(dev, request_type, request, value, index,
232                                 (unsigned char *)bytes, size, timeout);
233
234         if (transferred < 0)
235                 transferred = 0;
236
237         return transferred;
238 }
239
240 int jtag_libusb_bulk_write(struct libusb_device_handle *dev, int ep, char *bytes,
241                            int size, int timeout, int *transferred)
242 {
243         int ret;
244
245         *transferred = 0;
246
247         ret = libusb_bulk_transfer(dev, ep, (unsigned char *)bytes, size,
248                                    transferred, timeout);
249         if (ret != LIBUSB_SUCCESS) {
250                 LOG_ERROR("libusb_bulk_write error: %s", libusb_error_name(ret));
251                 return jtag_libusb_error(ret);
252         }
253
254         return ERROR_OK;
255 }
256
257 int jtag_libusb_bulk_read(struct libusb_device_handle *dev, int ep, char *bytes,
258                           int size, int timeout, int *transferred)
259 {
260         int ret;
261
262         *transferred = 0;
263
264         ret = libusb_bulk_transfer(dev, ep, (unsigned char *)bytes, size,
265                                    transferred, timeout);
266         if (ret != LIBUSB_SUCCESS) {
267                 LOG_ERROR("libusb_bulk_read error: %s", libusb_error_name(ret));
268                 return jtag_libusb_error(ret);
269         }
270
271         return ERROR_OK;
272 }
273
274 int jtag_libusb_set_configuration(struct libusb_device_handle *devh,
275                 int configuration)
276 {
277         struct libusb_device *udev = libusb_get_device(devh);
278         int retval = -99;
279
280         struct libusb_config_descriptor *config = NULL;
281         int current_config = -1;
282
283         retval = libusb_get_configuration(devh, &current_config);
284         if (retval != 0)
285                 return retval;
286
287         retval = libusb_get_config_descriptor(udev, configuration, &config);
288         if (retval != 0 || !config)
289                 return retval;
290
291         /* Only change the configuration if it is not already set to the
292            same one. Otherwise this issues a lightweight reset and hangs
293            LPC-Link2 with JLink firmware. */
294         if (current_config != config->bConfigurationValue)
295                 retval = libusb_set_configuration(devh, config->bConfigurationValue);
296
297         libusb_free_config_descriptor(config);
298
299         return retval;
300 }
301
302 int jtag_libusb_choose_interface(struct libusb_device_handle *devh,
303                 unsigned int *usb_read_ep,
304                 unsigned int *usb_write_ep,
305                 int bclass, int subclass, int protocol, int trans_type)
306 {
307         struct libusb_device *udev = libusb_get_device(devh);
308         const struct libusb_interface *inter;
309         const struct libusb_interface_descriptor *interdesc;
310         const struct libusb_endpoint_descriptor *epdesc;
311         struct libusb_config_descriptor *config;
312
313         *usb_read_ep = *usb_write_ep = 0;
314
315         libusb_get_config_descriptor(udev, 0, &config);
316         for (int i = 0; i < (int)config->bNumInterfaces; i++) {
317                 inter = &config->interface[i];
318
319                 interdesc = &inter->altsetting[0];
320                 for (int k = 0;
321                      k < (int)interdesc->bNumEndpoints; k++) {
322                         if ((bclass > 0 && interdesc->bInterfaceClass != bclass) ||
323                             (subclass > 0 && interdesc->bInterfaceSubClass != subclass) ||
324                             (protocol > 0 && interdesc->bInterfaceProtocol != protocol))
325                                 continue;
326
327                         epdesc = &interdesc->endpoint[k];
328                         if (trans_type > 0 && (epdesc->bmAttributes & 0x3) != trans_type)
329                                 continue;
330
331                         uint8_t epnum = epdesc->bEndpointAddress;
332                         bool is_input = epnum & 0x80;
333                         LOG_DEBUG("usb ep %s %02x",
334                                   is_input ? "in" : "out", epnum);
335
336                         if (is_input)
337                                 *usb_read_ep = epnum;
338                         else
339                                 *usb_write_ep = epnum;
340
341                         if (*usb_read_ep && *usb_write_ep) {
342                                 LOG_DEBUG("Claiming interface %d", (int)interdesc->bInterfaceNumber);
343                                 libusb_claim_interface(devh, (int)interdesc->bInterfaceNumber);
344                                 libusb_free_config_descriptor(config);
345                                 return ERROR_OK;
346                         }
347                 }
348         }
349         libusb_free_config_descriptor(config);
350
351         return ERROR_FAIL;
352 }
353
354 int jtag_libusb_get_pid(struct libusb_device *dev, uint16_t *pid)
355 {
356         struct libusb_device_descriptor dev_desc;
357
358         if (libusb_get_device_descriptor(dev, &dev_desc) == 0) {
359                 *pid = dev_desc.idProduct;
360
361                 return ERROR_OK;
362         }
363
364         return ERROR_FAIL;
365 }
366
367 int jtag_libusb_handle_events_completed(int *completed)
368 {
369         return libusb_handle_events_completed(jtag_libusb_context, completed);
370 }