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