Debian Codegraph @

src/jtag2usb.cc

raw symbols SCIP
1 /*
2 * avarice - The "avarice" program.
3 * Copyright (C) 2005, 2007, 2012 Joerg Wunsch
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License Version 2
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
17 *
18 * This file implements the libusb-based USB connection to a JTAG ICE
19 * mkII. It is also used by the JTAGICE3.
20 *
21 * $Id: jtag2usb.cc 423 2022-01-16 16:13:51Z joerg_wunsch $
22 */
23
24
25 #include "avarice.h"
26
27 #ifdef HAVE_LIBUSB
28
29 #include <stdarg.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <fcntl.h>
41 #include <signal.h>
42 #include <string.h>
43 #include <errno.h>
44
45 #ifdef HAVE_LIBUSB_2_0
46 # include <libusb20.h>
47 # include <libusb20_desc.h>
48 # include <poll.h>
49 #else
50 # include <usb.h>
51 #endif
52
53 #ifdef HAVE_LIBHIDAPI
54 # include <poll.h>
55 # include <hidapi/hidapi.h>
56 #endif
57
58 #include <pthread.h>
59
60 #ifdef __FreeBSD__
61 # include <pthread_np.h>
62 #endif
63
64 #include "jtag.h"
65
66 #define USB_VENDOR_ATMEL 1003
67 #define USB_DEVICE_JTAGICEMKII 0x2103
68 #define USB_DEVICE_AVRDRAGON 0x2107
69 #define USB_DEVICE_JTAGICE3 0x2110
70 #define USB_DEVICE_EDBG 0x2111
71
72 /* JTAGICEmkII */
73 #define USBDEV_BULK_EP_WRITE_MKII 0x02
74 #define USBDEV_BULK_EP_READ_MKII 0x82
75 #define USBDEV_MAX_XFER_MKII 64
76
77 /* JTAGICE3 */
78 #define USBDEV_BULK_EP_WRITE_3 0x01
79 #define USBDEV_BULK_EP_READ_3 0x82
80 #define USBDEV_EVT_EP_READ_3 0x83
81 #define USBDEV_MAX_XFER_3 512
82 #define USBDEV_MAX_EVT_3 64
83
84 /* EDBG (JTAGICE3 3.x, Atmel-ICE, Integrated EDBG */
85 #define USBDEV_INTERRUPT_EP_WRITE_EDBG 0x01
86 #define USBDEV_INTERRUPT_EP_READ_EDBG 0X82
87 #define USBDEV_MAX_XFER_EDBG 512
88
89 #define MAX_MESSAGE 512
90
91 #ifdef HAVE_LIBHIDAPI
92 struct hid_thread_data
93 {
94 unsigned int max_pkt_size;
95 };
96 #endif
97
98 static int read_ep, write_ep, event_ep, max_xfer;
99 #ifdef HAVE_LIBUSB_2_0
100 typedef struct libusb20_device usb_dev_t;
101 #else
102 typedef usb_dev_handle usb_dev_t;
103 #endif
104
105 static usb_dev_t *udev = NULL;
106 #ifdef HAVE_LIBHIDAPI
107 static hid_device *hdev = NULL;
108 static pthread_t htid;
109 #endif
110 static int pype[2];
111
112 #ifdef HAVE_LIBUSB_2_0
113 static pthread_t utid;
114 static struct libusb20_backend *be;
115 static struct libusb20_transfer *xfr_out;
116 static struct libusb20_transfer *xfr_in;
117 static struct libusb20_transfer *xfr_evt;
118 #else
119 static pthread_t rtid, wtid, etid;
120 #endif
121 static int usb_interface;
122
123 #ifdef HAVE_LIBUSB_2_0
124 /* convert LIBUSB20_ERROR into textual description */
125 static const char *
126 usb_error(int r)
127 {
128 const char *msg = "UNKNOWN";
129
130 switch ((enum libusb20_error)r)
131 {
132 case LIBUSB20_SUCCESS:
133 msg = "success";
134 break;
135
136 case LIBUSB20_ERROR_IO:
137 msg = "IO error";
138 break;
139
140 case LIBUSB20_ERROR_INVALID_PARAM:
141 msg = "Invalid parameter";
142 break;
143
144 case LIBUSB20_ERROR_ACCESS:
145 msg = "Access denied";
146 break;
147
148 case LIBUSB20_ERROR_NO_DEVICE:
149 msg = "No such device";
150 break;
151
152 case LIBUSB20_ERROR_NOT_FOUND:
153 msg = "Entity not found";
154 break;
155
156 case LIBUSB20_ERROR_BUSY:
157 msg = "Resource busy";
158 break;
159
160 case LIBUSB20_ERROR_TIMEOUT:
161 msg = "Operation timed out";
162 break;
163
164 case LIBUSB20_ERROR_OVERFLOW:
165 msg = "Overflow";
166 break;
167
168 case LIBUSB20_ERROR_PIPE:
169 msg = "Pipe error";
170 break;
171
172 case LIBUSB20_ERROR_INTERRUPTED:
173 msg = "System call interrupted";
174 break;
175
176 case LIBUSB20_ERROR_NO_MEM:
177 msg = "Insufficient memory";
178 break;
179
180 case LIBUSB20_ERROR_NOT_SUPPORTED:
181 msg = "Operation not supported";
182 break;
183
184 case LIBUSB20_ERROR_OTHER:
185 msg = "Other error";
186 break;
187 }
188
189 return msg;
190 }
191
192 /* same, for LIBUSB20_TRANSFER_XXX */
193 static const char *
194 usb_transfer_msg(uint8_t r)
195 {
196 const char *msg = "UNKNOWN";
197
198 switch ((enum libusb20_transfer_status)r)
199 {
200 case LIBUSB20_TRANSFER_COMPLETED:
201 msg = "completed (no error)";
202 break;
203
204 case LIBUSB20_TRANSFER_START:
205 msg = "start transfer";
206 break;
207
208 case LIBUSB20_TRANSFER_DRAINED:
209 msg = "transfer drained";
210 break;
211
212 case LIBUSB20_TRANSFER_ERROR:
213 msg = "transfer failed";
214 break;
215
216 case LIBUSB20_TRANSFER_TIMED_OUT:
217 msg = "transfer timed out";
218 break;
219
220 case LIBUSB20_TRANSFER_CANCELLED:
221 msg = "transfer cancelled";
222 break;
223
224 case LIBUSB20_TRANSFER_STALL:
225 msg = "endpoint stalled, or control request not supported";
226 break;
227
228 case LIBUSB20_TRANSFER_NO_DEVICE:
229 msg = "device disconnected";
230 break;
231
232 case LIBUSB20_TRANSFER_OVERFLOW:
233 msg = "transfer overflow";
234 break;
235 }
236
237 return msg;
238 }
239
240 static void usb20_cleanup(usb_dev_t *d)
241 {
242 libusb20_dev_close(d);
243 libusb20_be_free(be);
244 }
245 #endif
246
247
248 /*
249 * Walk down all USB devices, and see whether we can find our emulator
250 * device.
251 */
252 static usb_dev_t *opendev(const char *jtagDeviceName, emulator emu_type,
253 int &usb_interface)
254 {
255 char string[256];
256 #ifndef HAVE_LIBUSB_2_0
257 struct usb_bus *bus;
258 struct usb_device *dev;
259 #endif
260 usb_dev_t *pdev;
261 char *devnamecopy, *serno, *cp2;
262 uint16_t pid;
263 size_t x;
264
265 switch (emu_type)
266 {
267 case EMULATOR_JTAGICE:
268 pid = USB_DEVICE_JTAGICEMKII;
269 read_ep = USBDEV_BULK_EP_READ_MKII;
270 write_ep = USBDEV_BULK_EP_WRITE_MKII;
271 event_ep = 0;
272 max_xfer = USBDEV_MAX_XFER_MKII;
273 break;
274
275 case EMULATOR_DRAGON:
276 pid = USB_DEVICE_AVRDRAGON;
277 read_ep = USBDEV_BULK_EP_READ_MKII;
278 write_ep = USBDEV_BULK_EP_WRITE_MKII;
279 event_ep = 0;
280 max_xfer = USBDEV_MAX_XFER_MKII;
281 break;
282
283 case EMULATOR_JTAGICE3:
284 pid = USB_DEVICE_JTAGICE3;
285 read_ep = USBDEV_BULK_EP_READ_3;
286 write_ep = USBDEV_BULK_EP_WRITE_3;
287 event_ep = USBDEV_EVT_EP_READ_3;
288 max_xfer = USBDEV_MAX_XFER_3;
289 break;
290
291 default:
292 // should not happen
293 return NULL;
294 }
295
296 devnamecopy = new char[x = strlen(jtagDeviceName) + 1];
297 memcpy(devnamecopy, jtagDeviceName, x);
298
299 /*
300 * The syntax for usb devices is defined as:
301 *
302 * -P usb[:serialnumber]
303 *
304 * See if we've got a serial number passed here. The serial number
305 * might contain colons which we remove below, and we compare it
306 * right-to-left, so only the least significant nibbles need to be
307 * specified.
308 */
309 if ((serno = strchr(devnamecopy, ':')) != NULL)
310 {
311 /* first, drop all colons there if any */
312 cp2 = ++serno;
313
314 while ((cp2 = strchr(cp2, ':')) != NULL)
315 {
316 x = strlen(cp2) - 1;
317 memmove(cp2, cp2 + 1, x);
318 cp2[x] = '\0';
319 }
320
321 if (strlen(serno) > 12)
322 {
323 fprintf(stderr, "invalid serial number \"%s\"", serno);
324 delete [] devnamecopy;
325 return NULL;
326 }
327 }
328
329 #ifdef HAVE_LIBUSB_2_0
330 if ((be = libusb20_be_alloc_default()) == NULL)
331 {
332 perror("libusb20_be_alloc()");
333 return NULL;
334 }
335 #else
336 usb_init();
337
338 usb_find_busses();
339 usb_find_devices();
340 #endif
341
342 pdev = NULL;
343 bool found = false;
344 #ifdef HAVE_LIBUSB_2_0
345 (void)usb_interface;
346 while ((pdev = libusb20_be_device_foreach(be, pdev)) != NULL)
347 {
348 struct LIBUSB20_DEVICE_DESC_DECODED *ddp =
349 libusb20_dev_get_device_desc(pdev);
350
351 if (ddp->idVendor == USB_VENDOR_ATMEL &&
352 ddp->idProduct == pid)
353 {
354 int rv = libusb20_dev_open(pdev, 3);
355 if (rv < 0)
356 {
357 fprintf(stderr, "cannot open device \"%s\"",
358 usb_error(rv));
359 libusb20_be_free(be);
360 return NULL;
361 }
362
363 /* yeah, we found something */
364 rv = libusb20_dev_req_string_simple_sync(pdev,
365 ddp->iSerialNumber,
366 string, sizeof(string));
367 if (rv < 0)
368 {
369 fprintf(stderr, "cannot read serial number \"%s\"",
370 usb_error(rv));
371 usb20_cleanup(pdev);
372 return NULL;
373 }
374
375 debugOut("Found JTAG ICE, serno: %s\n", string);
376 if (serno != NULL)
377 {
378 /*
379 * See if the serial number requested by the
380 * user matches what we found, matching
381 * right-to-left.
382 */
383 x = strlen(string) - strlen(serno);
384 if (strcasecmp(string + x, serno) != 0)
385 {
386 debugOut("serial number doesn't match\n");
387 libusb20_dev_close(pdev);
388 continue;
389 }
390 }
391
392 // we found what we want
393 found = true;
394 break;
395 }
396 }
397 #else // !HAVE_LIBUSB_2_0
398 for (bus = usb_get_busses(); !found && bus; bus = bus->next)
399 {
400 for (dev = bus->devices; !found && dev; dev = dev->next)
401 {
402 pdev = usb_open(dev);
403 if (pdev)
404 {
405 if (dev->descriptor.idVendor == USB_VENDOR_ATMEL &&
406 dev->descriptor.idProduct == pid)
407 {
408 /* yeah, we found something */
409 int rv = usb_get_string_simple(pdev,
410 dev->descriptor.iSerialNumber,
411 string, sizeof(string));
412 if (rv < 0)
413 {
414 fprintf(stderr, "cannot read serial number \"%s\"",
415 usb_strerror());
416 return NULL;
417 }
418
419 debugOut("Found JTAG ICE, serno: %s\n", string);
420 if (serno != NULL)
421 {
422 /*
423 * See if the serial number requested by the
424 * user matches what we found, matching
425 * right-to-left.
426 */
427 x = strlen(string) - strlen(serno);
428 if (strcasecmp(string + x, serno) != 0)
429 {
430 debugOut("serial number doesn't match\n");
431 usb_close(pdev);
432 continue;
433 }
434 }
435
436 // we found what we want
437 found = true;
438 break;
439 }
440 usb_close(pdev);
441 }
442 }
443 }
444 #endif // HAVE_LIBUSB_2_0
445
446 delete [] devnamecopy;
447 if (!found)
448 {
449 printf("did not find any%s USB device \"%s\"\n",
450 serno? " (matching)": "", jtagDeviceName);
451 return NULL;
452 }
453
454 #ifdef HAVE_LIBUSB_2_0
455 int rv;
456
457 if ((rv = libusb20_dev_set_config_index(pdev, 0)) != 0)
458 {
459 fprintf(stderr, "libusb20_dev_set_config_index: %s\n", usb_error(rv));
460 usb20_cleanup(pdev);
461 return NULL;
462 }
463 /*
464 * Two transfers have been requested in libusb20_dev_open() above;
465 * obtain the corresponding transfer struct pointers.
466 */
467 xfr_out = libusb20_tr_get_pointer(pdev, 0);
468 xfr_in = libusb20_tr_get_pointer(pdev, 1);
469 if (event_ep != 0)
470 xfr_evt = libusb20_tr_get_pointer(pdev, 2);
471
472 if (xfr_in == NULL || xfr_out == NULL)
473 {
474 fprintf(stderr, "libusb20_tr_get_pointer: %s\n", usb_error(rv));
475 usb20_cleanup(pdev);
476 return NULL;
477 }
478
479 /*
480 * Open all transfers, the "out" one for the write endpoint, the
481 * "in" one for the read endpoint (ep | 0x80), and the event EP
482 * for the JTAGICE3 events.
483 */
484 if ((rv = libusb20_tr_open(xfr_out, 0, 1, write_ep)) != 0)
485 {
486 fprintf(stderr, "libusb20_tr_open: %s\n", usb_error(rv));
487 usb20_cleanup(pdev);
488 return NULL;
489 }
490 uint32_t max_packet_l;
491 if ((max_packet_l = libusb20_tr_get_max_packet_length(xfr_out)) < (unsigned)max_xfer)
492 {
493 statusOut("downgrading max_xfer from %d to %d due to EP 0x%02x's wMaxPacketSize\n",
494 max_xfer, max_packet_l, write_ep);
495 max_xfer = max_packet_l;
496 }
497 if ((rv = libusb20_tr_open(xfr_in, 0, 1, read_ep)) != 0)
498 {
499 fprintf(stderr, "libusb20_tr_open: %s\n", usb_error(rv));
500 usb20_cleanup(pdev);
501 return NULL;
502 }
503 if ((max_packet_l = libusb20_tr_get_max_packet_length(xfr_in)) < (unsigned)max_xfer)
504 {
505 statusOut("downgrading max_xfer from %d to %d due to EP 0x%02x's wMaxPacketSize\n",
506 max_xfer, max_packet_l, read_ep);
507 max_xfer = max_packet_l;
508 }
509 if (event_ep != 0 &&
510 (rv = libusb20_tr_open(xfr_evt, 0, 1, event_ep)) != 0)
511 {
512 fprintf(stderr, "libusb20_tr_open: %s\n", usb_error(rv));
513 usb20_cleanup(pdev);
514 return NULL;
515 }
516 #else
517 if (dev->config == NULL)
518 {
519 statusOut("USB device has no configuration\n");
520 fail:
521 usb_close(pdev);
522 return NULL;
523 }
524 if (usb_set_configuration(pdev, dev->config[0].bConfigurationValue))
525 {
526 statusOut("error setting configuration %d: %s\n",
527 dev->config[0].bConfigurationValue,
528 usb_strerror());
529 goto fail;
530 }
531 usb_interface = dev->config[0].interface[0].altsetting[0].bInterfaceNumber;
532 if (usb_claim_interface(pdev, usb_interface))
533 {
534 statusOut("error claiming interface %d: %s\n",
535 usb_interface, usb_strerror());
536 goto fail;
537 }
538 struct usb_endpoint_descriptor *epp = dev->config[0].interface[0].altsetting[0].endpoint;
539 for (int i = 0; i < dev->config[0].interface[0].altsetting[0].bNumEndpoints; i++)
540 {
541 if ((epp[i].bEndpointAddress == read_ep || epp[i].bEndpointAddress == write_ep) &&
542 epp[i].wMaxPacketSize < max_xfer)
543 {
544 statusOut("downgrading max_xfer from %d to %d due to EP 0x%02x's wMaxPacketSize\n",
545 max_xfer, epp[i].wMaxPacketSize, epp[i].bEndpointAddress);
546 max_xfer = epp[i].wMaxPacketSize;
547 }
548 }
549 #endif
550
551 /*
552 * As of, at least, firmware 2.12, the JTAGICE3 does not handle
553 * splitting large packets into smaller chunks correctly when being
554 * operated on an USB 1.1 connection where wMaxPacketSize is
555 * downgraded from 512 to 64 bytes. The initial packets are sent
556 * correctly, but subsequent packets contain wrong data.
557 *
558 * Performing the check below in a version-dependent manner is
559 * possible (obtaining the firmware version only requires small
560 * reply packets), but some means would have to be added to
561 * communicate the information below back to the next higher layers.
562 * As long as no fixed firmware is known, simply bail out here
563 * instead.
564 */
565 if (event_ep != 0 &&
566 max_xfer < USBDEV_MAX_XFER_3)
567 {
568 statusOut("Sorry, the JTAGICE3's firmware is broken on USB 1.1 connections\n");
569 #ifdef HAVE_LIBUSB_2_0
570 usb20_cleanup(pdev);
571 #else
572 usb_close(pdev);
573 #endif
574 return NULL;
575 }
576
577 return pdev;
578 }
579
580 #ifdef HAVE_LIBHIDAPI
581 /*
582 * Open HID, used for CMSIS-DAP (EDBG) devices
583 */
584 static hid_device *openhid(const char *jtagDeviceName, unsigned int &max_pkt_size)
585 {
586 hid_device *pdev;
587 char *devnamecopy, *serno, *cp2;
588 size_t x;
589 wchar_t wserno[15];
590 size_t serlen = 0;
591
592 devnamecopy = new char[x = strlen(jtagDeviceName) + 1];
593 memcpy(devnamecopy, jtagDeviceName, x);
594
595 /*
596 * The syntax for usb devices is defined as:
597 *
598 * -P usb[:serialnumber]
599 *
600 * See if we've got a serial number passed here. The serial number
601 * might contain colons which we remove below, and we compare it
602 * right-to-left, so only the least significant nibbles need to be
603 * specified.
604 */
605 if ((serno = strchr(devnamecopy, ':')) != NULL)
606 {
607 /* first, drop all colons there if any */
608 cp2 = ++serno;
609
610 while ((cp2 = strchr(cp2, ':')) != NULL)
611 {
612 x = strlen(cp2) - 1;
613 memmove(cp2, cp2 + 1, x);
614 cp2[x] = '\0';
615 }
616
617 serlen = strlen(serno);
618 if (serlen > 12)
619 {
620 fprintf(stderr, "invalid serial number \"%s\"", serno);
621 delete [] devnamecopy;
622 return NULL;
623 }
624 mbstowcs(wserno, serno, 15);
625 }
626 delete [] devnamecopy;
627
628 pdev = NULL;
629
630 /*
631 * Find any Atmel device which is a HID. Then, look at the product
632 * string whether it contains the mandatory substring "CMSIS-DAP".
633 * (This distinguishes the ICEs from e.g. a keyboard or mouse demo
634 * using the Atmel VID.)
635 *
636 * If a serial number has been asked for, try to match it as well.
637 */
638 struct hid_device_info *list, *walk;
639 list = hid_enumerate(USB_VENDOR_ATMEL, 0);
640 if (list == NULL)
641 return NULL;
642
643 walk = list;
644 while (walk)
645 {
646 if (walk->product_string != nullptr &&
647 wcsstr(walk->product_string, L"CMSIS-DAP") != NULL)
648 {
649 debugOut("Found HID PID:VID 0x%04x:0x%04x, serno %ls\n",
650 walk->vendor_id, walk->product_id,
651 walk->serial_number);
652 // Atmel CMSID-DAP device found
653 // If no serial number requested, we are done.
654 if (serlen == 0)
655 break;
656 // Otherwise, match the serial number
657 size_t slen = wcslen(walk->serial_number);
658 if (slen >= serlen)
659 {
660 if (wcscmp(walk->serial_number + slen - serlen, wserno) == 0)
661 {
662 // found matching serial number
663 debugOut("...matched\n");
664 break;
665 }
666 }
667 // else: proceed to next device
668 }
669 walk = walk->next;
670 }
671 if (walk == NULL)
672 {
673 fprintf(stderr, "No (matching) HID found\n");
674 hid_free_enumeration(list);
675 return NULL;
676 }
677
678 pdev = hid_open_path(walk->path);
679 hid_free_enumeration(list);
680 if (pdev == NULL)
681 // can't happen?
682 return NULL;
683
684 hid_set_nonblocking(pdev, 1);
685
686 /*
687 * Probe for the endpoint size. Atmel tools are very picky about
688 * always being talked to with full-sized packets. Alas, libhidapi
689 * has no API function to obtain the endpoint size, so we first send
690 * an inquiry in 64 bytes (for mEDBG), and if we don't get a timely
691 * response, provide another 448 bytes to complete the 512-byte
692 * packet (JTAGICE3, Atmel-ICE, full EDBG).
693 */
694 debugOut("Probing for HID max. packet size\n");
695 max_pkt_size = 64; // first guess
696 unsigned char probebuf[512 + 1] = {
697 0, // no HID report number used
698 0, // DAP_info command
699 0xFF, // get max. packet size
700 };
701 hid_write(pdev, probebuf, 64 + 1);
702 int res = hid_read_timeout(pdev, probebuf, 10 /* bytes */, 50 /* milliseconds */);
703 if (res == 0)
704 {
705 // no timely response, assume 512 byte size
706 hid_write(pdev, probebuf, (512 - 64) + 1);
707 max_pkt_size = 512;
708 res = hid_read_timeout(pdev, probebuf, 10, 50);
709 }
710 if (res <= 0)
711 {
712 fprintf(stderr, "openhid(): device not responding to DAP_Info\n");
713 hid_close(pdev);
714 return NULL;
715 }
716 if (probebuf[0] != 0 || probebuf[1] != 2)
717 {
718 debugOut("Unexpected DAP_Info response 0x%02x 0x%02x\n",
719 probebuf[0], probebuf[1]);
720 }
721 else
722 {
723 unsigned int probesize = probebuf[2] + (probebuf[3] << 8);
724 if (probesize != 64 && probesize != 512)
725 {
726 debugOut("Unexpected max. packet size %u, proceeding with %u\n",
727 probesize, max_pkt_size);
728 }
729 else
730 {
731 debugOut("Setting max. packet size to %u from DAP_Info\n",
732 probesize);
733 max_pkt_size = probesize;
734 }
735 }
736
737 return pdev;
738 }
739 #endif // HAVE_LIBHIDAPI
740
741 #ifdef HAVE_LIBUSB_2_0
742 /* USB thread */
743 static void *usb_thread(void * data __attribute__((unused)))
744 {
745 struct pollfd fds[2];
746
747 fds[0].fd = pype[0];
748 fds[0].events = POLLIN | POLLRDNORM;
749 fds[1].fd = libusb20_dev_get_fd(udev);
750 // should we also poll for possible USB OUT transfers when splitting
751 // one message into multiple packets?
752 fds[1].events = POLLIN | POLLRDNORM;
753
754 while (1)
755 {
756 char buf[MAX_MESSAGE];
757 char rbuf[MAX_MESSAGE + sizeof(unsigned int)];
758 char ebuf[USBDEV_MAX_EVT_3 + sizeof(unsigned int)];
759 int rv;
760
761 if (!libusb20_tr_pending(xfr_in))
762 {
763 // setup and start new bulk IN transfer
764 libusb20_tr_setup_bulk(xfr_in, rbuf + sizeof(unsigned int),
765 max_xfer, 0);
766 libusb20_tr_start(xfr_in);
767 }
768
769 if (event_ep != 0 &&
770 !libusb20_tr_pending(xfr_evt))
771 {
772 // setup and start new bulk IN transfer
773 libusb20_tr_setup_bulk(xfr_evt, ebuf + sizeof(unsigned int),
774 USBDEV_MAX_EVT_3, 0);
775 libusb20_tr_start(xfr_evt);
776 }
777
778 fds[0].revents = fds[1].revents = 0;
779 rv = poll(fds, 2, INFTIM);
780 if (rv < 0)
781 {
782 if (errno != EINTR)
783 perror("poll()");
784 continue;
785 }
786 if (rv == 0)
787 // why did poll() return?
788 continue;
789
790 if ((fds[0].revents & POLLERR) != 0 ||
791 (fds[1].revents & POLLERR) != 0)
792 {
793 fprintf(stderr, "poll() returned POLLERR, why?\n");
794 fds[0].revents &= ~POLLERR;
795 fds[1].revents &= ~POLLERR;
796 }
797 if ((fds[0].revents & (POLLNVAL | POLLHUP)) != 0 ||
798 (fds[1].revents & (POLLNVAL | POLLHUP)) != 0)
799 // fd is closed
800 pthread_exit((void *)0);
801
802 if (fds[0].revents != 0)
803 {
804 // something is in the pipe there
805 if ((rv = read(pype[0], buf, MAX_MESSAGE)) > 0)
806 {
807 int offset = 0;
808
809 libusb20_tr_stop(xfr_in);
810
811 while (rv != 0)
812 {
813 uint32_t amnt, result;
814
815 if (rv > max_xfer)
816 amnt = max_xfer;
817 else
818 amnt = rv;
819 // right now, we run the bulk writes synchronously
820 uint8_t xfrstatus;
821
822 xfrstatus = libusb20_tr_bulk_intr_sync(xfr_out, buf + offset, amnt,
823 &result, 5000);
824 if (xfrstatus !=
825 (enum libusb20_transfer_status)LIBUSB20_TRANSFER_COMPLETED)
826 {
827 fprintf(stderr, "USB bulk write error: %s\n",
828 usb_transfer_msg(xfrstatus));
829 pthread_exit((void *)1);
830 }
831 if (result != amnt)
832 {
833 fprintf(stderr, "USB bulk short write: %u != %u\n",
834 result, amnt);
835 pthread_exit((void *)1);
836 }
837 if (rv == max_xfer)
838 {
839 /* send ZLP */
840 libusb20_tr_bulk_intr_sync(xfr_out, buf, 0,
841 &result, 5000);
842 }
843 rv -= amnt;
844 offset += amnt;
845 }
846
847 libusb20_tr_setup_bulk(xfr_in, rbuf + sizeof(unsigned int),
848 max_xfer, 0);
849 libusb20_tr_start(xfr_in);
850 }
851 else if (errno != EINTR && errno != EAGAIN)
852 {
853 fprintf(stderr, "read error from AVaRICE: %s\n",
854 strerror(errno));
855 pthread_exit((void *)1);
856 }
857 }
858
859 if (fds[1].revents != 0)
860 {
861 // something's available on USB
862 if ((rv = libusb20_dev_process(udev)) != 0)
863 // what's up?
864 continue;
865
866 if (!libusb20_tr_pending(xfr_in))
867 {
868
869 uint32_t result = libusb20_tr_get_actual_length(xfr_in);
870 uint8_t xfrstatus = libusb20_tr_get_status(xfr_in);
871
872 if (xfrstatus !=
873 (enum libusb20_transfer_status)LIBUSB20_TRANSFER_COMPLETED)
874 {
875 fprintf(stderr, "USB bulk read error: %s\n",
876 usb_transfer_msg(xfrstatus));
877 pthread_exit((void *)1);
878 }
879 /*
880 * We read a packet from USB. If it's been a partial
881 * one (result matches the endpoint size), see to get
882 * more, until we have either a short read, or a ZLP.
883 *
884 * We do it synchronously right now.
885 */
886 unsigned int pkt_len = result;
887 bool needmore = result == (unsigned)max_xfer;
888
889 /* OK, if there is more to read, do so. */
890 while (needmore)
891 {
892 int maxlen = MAX_MESSAGE - pkt_len;
893 if (maxlen > max_xfer)
894 maxlen = max_xfer;
895 xfrstatus = libusb20_tr_bulk_intr_sync(xfr_in,
896 rbuf + sizeof(unsigned int) + pkt_len,
897 maxlen, &result, 100);
898
899 if (xfrstatus !=
900 (enum libusb20_transfer_status)LIBUSB20_TRANSFER_COMPLETED)
901 {
902 fprintf(stderr, "USB bulk read error in continuation block: %s\n",
903 usb_transfer_msg(xfrstatus));
904 pthread_exit((void *)1);
905 }
906 if (result == 0)
907 {
908 /* Zero-length packet: we are done. */
909 break;
910 }
911
912 needmore = rv == max_xfer;
913 pkt_len += rv;
914 if (pkt_len == MAX_MESSAGE)
915 {
916 /* should not happen */
917 fprintf(stderr, "Message too big in USB receive.\n");
918 break;
919 }
920 }
921
922 unsigned int writesize = pkt_len;
923 char *writep = rbuf + sizeof(unsigned int);
924 if (event_ep != 0)
925 {
926 /*
927 * On the JTAGICE3, we prepend the length, so the
928 * parent knows how much data to expect from the
929 * pipe.
930 */
931 memcpy(rbuf, &pkt_len, sizeof(unsigned int));
932 writep -= sizeof(unsigned int);
933 writesize += sizeof(unsigned int);
934 }
935
936 if (write(pype[0], writep, writesize) != writesize)
937 {
938 fprintf(stderr, "short write to AVaRICE: %s\n",
939 strerror(errno));
940 pthread_exit((void *)1);
941 }
942 }
943
944 if (event_ep != 0 &&
945 !libusb20_tr_pending(xfr_evt))
946 {
947
948 uint32_t result = libusb20_tr_get_actual_length(xfr_evt);
949 uint8_t xfrstatus = libusb20_tr_get_status(xfr_evt);
950
951 if (xfrstatus !=
952 (enum libusb20_transfer_status)LIBUSB20_TRANSFER_COMPLETED)
953 {
954 fprintf(stderr, "USB bulk read error: %s\n",
955 usb_transfer_msg(xfrstatus));
956 pthread_exit((void *)1);
957 }
958
959 if (result != 0)
960 {
961 /* No partial packet handling needed on the event EP */
962
963 if (ebuf[0] != TOKEN)
964 {
965 fprintf(stderr,
966 "usb_daemon(): first byte of event message is not TOKEN but 0x%02x\n",
967 ebuf[0]);
968 }
969 else
970 {
971 unsigned int pkt_len = result;
972
973 /*
974 * On the JTAGICE3, we prepend the message length, so
975 * the parent knows how much data to expect from the
976 * pipe.
977 */
978 memcpy(ebuf, &pkt_len, sizeof(unsigned int));
979
980 ebuf[sizeof(unsigned int)] = TOKEN_EVT3;
981
982 if (write(pype[0], ebuf, pkt_len + sizeof(unsigned int))
983 != pkt_len + sizeof(unsigned int))
984 {
985 fprintf(stderr, "short write to AVaRICE: %s\n",
986 strerror(errno));
987 pthread_exit((void *)1);
988 }
989 }
990 }
991 }
992
993 }
994 }
995 }
996
997 #else
998
999 /* USB writer thread */
1000 static void *usb_thread_write(void * data)
1001 {
1002 while (1)
1003 {
1004 char buf[MAX_MESSAGE];
1005 int rv;
1006
1007 if ((rv = read(pype[0], buf, MAX_MESSAGE)) > 0)
1008 {
1009 int offset = 0;
1010
1011 while (rv != 0)
1012 {
1013 int amnt, result;
1014
1015 if (rv > max_xfer)
1016 amnt = max_xfer;
1017 else
1018 amnt = rv;
1019 result = usb_bulk_write(udev, write_ep,
1020 buf + offset, amnt, 5000);
1021 if (result != amnt)
1022 {
1023 fprintf(stderr, "USB bulk write error: %s\n",
1024 usb_strerror());
1025 pthread_exit((void *)1);
1026 }
1027 if (rv == max_xfer)
1028 {
1029 /* send ZLP */
1030 usb_bulk_write(udev, write_ep, buf, 0, 5000);
1031 }
1032 rv -= amnt;
1033 offset += amnt;
1034 }
1035 continue;
1036 }
1037 else if (errno != EINTR && errno != EAGAIN)
1038 {
1039 fprintf(stderr, "read error from AVaRICE: %s\n",
1040 strerror(errno));
1041 pthread_exit((void *)1);
1042 }
1043 }
1044 }
1045
1046 /* USB event reader thread (JTAGICE3 only) */
1047 static void *usb_thread_read(void *data)
1048 {
1049 while (1)
1050 {
1051 char buf[MAX_MESSAGE + sizeof(unsigned int)];
1052 int rv;
1053
1054 rv = usb_bulk_read(udev, read_ep, buf + sizeof(unsigned int),
1055 max_xfer, 0);
1056 if (rv == 0 || rv == -EINTR || rv == -EAGAIN || rv == -ETIMEDOUT)
1057 {
1058 /* OK, try again */
1059 }
1060 else if (rv < 0)
1061 {
1062 fprintf(stderr, "USB bulk read error: %s (%d)\n",
1063 usb_strerror(), rv);
1064 pthread_exit((void *)1);
1065 }
1066 else
1067 {
1068 /*
1069 * We read a packet from USB. If it's been a partial
1070 * one (result matches the endpoint size), see to get
1071 * more, until we have either a short read, or a ZLP.
1072 */
1073 unsigned int pkt_len = rv;
1074 bool needmore = rv == max_xfer;
1075
1076 /* OK, if there is more to read, do so. */
1077 while (needmore)
1078 {
1079 int maxlen = MAX_MESSAGE - pkt_len;
1080 if (maxlen > max_xfer)
1081 maxlen = max_xfer;
1082 rv = usb_bulk_read(udev, read_ep, buf + sizeof(unsigned int) + pkt_len,
1083 maxlen, 100);
1084
1085 if (rv == -EINTR || rv == -EAGAIN || rv == -ETIMEDOUT)
1086 {
1087 continue;
1088 }
1089 if (rv == 0)
1090 {
1091 /* Zero-length packet: we are done. */
1092 break;
1093 }
1094 if (rv < 0)
1095 {
1096 fprintf(stderr,
1097 "USB bulk read error in continuation block: %s\n",
1098 usb_strerror());
1099 pthread_exit((void *)1);
1100 }
1101
1102 needmore = rv == max_xfer;
1103 pkt_len += rv;
1104 if (pkt_len == MAX_MESSAGE)
1105 {
1106 /* should not happen */
1107 fprintf(stderr, "Message too big in USB receive.\n");
1108 break;
1109 }
1110 }
1111
1112 unsigned int writesize = pkt_len;
1113 char *writep = buf + sizeof(unsigned int);
1114 if (event_ep != 0)
1115 {
1116 /*
1117 * On the JTAGICE3, we prepend the message length, so
1118 * the parent knows how much data to expect from the
1119 * pipe.
1120 */
1121 memcpy(buf, &pkt_len, sizeof(unsigned int));
1122 writep -= sizeof(unsigned int);
1123 writesize += sizeof(unsigned int);
1124 }
1125
1126 if (write(pype[0], writep, writesize) != writesize)
1127 {
1128 fprintf(stderr, "short write to AVaRICE: %s\n",
1129 strerror(errno));
1130 pthread_exit((void *)1);
1131 }
1132 }
1133 }
1134 }
1135
1136 /* USB reader thread */
1137 static void *usb_thread_event(void *data)
1138 {
1139 while (1)
1140 {
1141 /*
1142 * Events are shorter than regular data packets, so no
1143 * reassembly and ZLP handling is needed here.
1144 */
1145 char buf[USBDEV_MAX_EVT_3 + sizeof(unsigned int)];
1146 int rv;
1147
1148 rv = usb_bulk_read(udev, event_ep, buf + sizeof(unsigned int),
1149 USBDEV_MAX_EVT_3, 0);
1150 if (rv == 0 || rv == -EINTR || rv == -EAGAIN || rv == -ETIMEDOUT)
1151 {
1152 /* OK, try again */
1153 }
1154 else if (rv < 0)
1155 {
1156 fprintf(stderr, "USB event read error: %s (%d)\n",
1157 usb_strerror(), rv);
1158 pthread_exit((void *)1);
1159 }
1160 else
1161 {
1162 if (buf[sizeof(unsigned int)] != TOKEN)
1163 {
1164 fprintf(stderr,
1165 "usb_daemon(): first byte of event message is not TOKEN but 0x%02x\n",
1166 buf[sizeof(unsigned int)]);
1167 }
1168 else
1169 {
1170 unsigned int pkt_len = rv;
1171
1172 /*
1173 * On the JTAGICE3, we prepend the message length first,
1174 * the parent knows how much data to expect from the
1175 * pipe.
1176 */
1177 memcpy(buf, &pkt_len, sizeof(unsigned int));
1178
1179 buf[sizeof(unsigned int)] = TOKEN_EVT3;
1180 if (write(pype[0], buf, pkt_len + sizeof(unsigned int)) !=
1181 pkt_len + sizeof(unsigned int))
1182 {
1183 fprintf(stderr, "short write to AVaRICE: %s\n",
1184 strerror(errno));
1185 pthread_exit((void *)1);
1186 }
1187 }
1188 }
1189 }
1190 }
1191 #endif
1192
1193 void jtag::resetUSB(void)
1194 {
1195 #ifndef HAVE_LIBUSB_2_0
1196 if (udev)
1197 {
1198 usb_resetep(udev, read_ep);
1199 usb_resetep(udev, write_ep);
1200 if (event_ep != 0)
1201 usb_resetep(udev, event_ep);
1202 }
1203 #endif
1204 }
1205
1206 #ifdef HAVE_LIBHIDAPI
1207 static void *hid_thread(void * data)
1208 {
1209 struct pollfd fds[1];
1210 struct hid_thread_data *hdata = (struct hid_thread_data *)data;
1211
1212 fds[0].fd = pype[0];
1213 fds[0].events = POLLIN | POLLRDNORM;
1214
1215 debugOut("HID thread started\n");
1216
1217 while (1)
1218 {
1219 // One additional byte is for libhidapi to tell we don't use HID
1220 // report numbers. Four bytes are wrapping overhead.
1221 unsigned char buf[MAX_MESSAGE + 5];
1222 int rv;
1223
1224 // Poll for data from main thread.
1225 // Wait for at most 50 ms, so we can regularly
1226 // ping for events even if no upstream activity
1227 // is present.
1228 fds[0].revents = 0;
1229 rv = poll(fds, 1, 50);
1230 if (rv < 0)
1231 {
1232 if (errno != EINTR)
1233 perror("poll()");
1234 continue;
1235 }
1236 if (rv == 0)
1237 {
1238 // timed out, so just ping for event
1239 buf[0] = 0;
1240 buf[1] = EDBG_VENDOR_AVR_EVT;
1241 rv = hid_write(hdev, buf, hdata->max_pkt_size + 1);
1242 if (rv < 0)
1243 throw jtag_exception("Querying for event: hid_write() failed");
1244
1245 rv = hid_read_timeout(hdev, buf, hdata->max_pkt_size + 1, 200);
1246 if (rv <= 0)
1247 {
1248 debugOut("Querying for event: hid_read() failed (%d)\n",
1249 rv);
1250 continue;
1251 }
1252 // Now examine whether the reply actually contained an event.
1253 if (buf[0] != EDBG_VENDOR_AVR_EVT)
1254 {
1255 debugOut("Querying for event: unexpected response (0x%02x)\n",
1256 buf[0]);
1257 continue;
1258 }
1259 if (buf[1] == 0 && buf[2] == 0)
1260 // nothing returned
1261 continue;
1262 unsigned int len = buf[1] * 256 + buf[2];
1263 if (len > MAX_MESSAGE - 10)
1264 {
1265 debugOut("Querying for event: insane event size %u\n",
1266 len);
1267 continue;
1268 }
1269 // tag this as an event packet
1270 buf[3] = TOKEN_EVT3;
1271 // make room to prepend packet length
1272 memmove(buf + sizeof(unsigned int), buf + 3, len);
1273 memcpy(buf, &len, sizeof(unsigned int));
1274 // pass event upstream
1275 write(pype[0], buf, len + sizeof(unsigned int));
1276 continue;
1277 }
1278
1279 if ((fds[0].revents & POLLERR) != 0)
1280 {
1281 fprintf(stderr, "poll() returned POLLERR, why?\n");
1282 fds[0].revents &= ~POLLERR;
1283 }
1284 if ((fds[0].revents & (POLLNVAL | POLLHUP)) != 0)
1285 // fd is closed
1286 pthread_exit((void *)0);
1287
1288 if (fds[0].revents != 0)
1289 {
1290 // something is in the pipe there, presumably a command
1291 // read to offset 5 to leave room for the wrapper
1292 if ((rv = read(pype[0], buf + 5, MAX_MESSAGE)) > 0)
1293 {
1294 if (rv < 6)
1295 {
1296 debugOut("Reading command from AVaRICE failed\n");
1297 continue;
1298 }
1299
1300 // used in both, request and reply data
1301 unsigned int npackets =
1302 (rv + hdata->max_pkt_size - 1) /
1303 hdata->max_pkt_size;
1304 unsigned int thispacket = 1;
1305 unsigned int len = rv;
1306 // used in reassembling reply data
1307 size_t offset = sizeof(unsigned int);
1308 unsigned int totlength = 0;
1309
1310 while (thispacket <= npackets)
1311 {
1312 if (thispacket != 1)
1313 memmove(buf + 5,
1314 buf + (hdata->max_pkt_size - 4) + 5,
1315 len);
1316
1317 buf[0] = 0; // libhidapi: no report ID
1318 buf[1] = EDBG_VENDOR_AVR_CMD;
1319 buf[2] = (thispacket << 4) | npackets;
1320 unsigned int cursize =
1321 (len > hdata->max_pkt_size - 4)?
1322 hdata->max_pkt_size - 4: len;
1323 buf[3] = cursize >> 8;
1324 buf[4] = cursize;
1325 rv = hid_write(hdev, buf, hdata->max_pkt_size + 1);
1326 if ((unsigned)rv != hdata->max_pkt_size + 1)
1327 {
1328 debugOut("hid_write: short write, %u vs. %d\n",
1329 hdata->max_pkt_size + 1, rv);
1330 goto done;
1331 }
1332
1333 rv = hid_read_timeout(hdev, buf, hdata->max_pkt_size + 1, 200);
1334 if (rv < 0)
1335 throw jtag_exception("Error reading HID");
1336
1337 thispacket++;
1338 len -= cursize;
1339 }
1340
1341 // Query response
1342 for (npackets = 0, thispacket = 0; thispacket <= npackets; thispacket++)
1343 {
1344 buf[offset] = 0;
1345 buf[offset + 1] = EDBG_VENDOR_AVR_RSP;
1346 rv = hid_write(hdev, buf + offset, hdata->max_pkt_size + 1);
1347 if (rv < 0)
1348 throw jtag_exception("Querying for response: hid_write() failed");
1349
1350 rv = hid_read_timeout(hdev, buf + offset, hdata->max_pkt_size + 1, 500);
1351 if (rv <= 0)
1352 {
1353 debugOut("Querying for response: hid_read() failed (%d)\n",
1354 rv);
1355 goto done;
1356 }
1357 debugOut("Received 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n",
1358 buf[offset], buf[offset + 1], buf[offset + 2],
1359 buf[offset + 3], buf[offset + 4], buf[offset + 5]);
1360 // Now examine whether the reply actually contained a response.
1361 if (buf[offset] != EDBG_VENDOR_AVR_RSP)
1362 {
1363 debugOut("Querying for response: unexpected response (0x%02x)\n",
1364 buf[0]);
1365 goto done;
1366 }
1367 if (npackets == 0)
1368 {
1369 // first fragment arriving
1370 npackets = buf[offset + 1] & 0x0F;
1371 thispacket = 1;
1372 }
1373 if ((buf[offset + 1] >> 4) != thispacket)
1374 {
1375 debugOut("Wrong fragment: got %d, expected %d\n",
1376 (buf[offset + 1] >> 4), thispacket);
1377 goto done;
1378 }
1379 unsigned int len = buf[offset + 2] * 256 + buf[offset + 3];
1380 if (len < 5 || len > hdata->max_pkt_size)
1381 {
1382 debugOut("Querying for response: insane event size %u\n",
1383 len);
1384 goto done;
1385 }
1386 totlength += len;
1387 if (totlength > MAX_MESSAGE)
1388 {
1389 debugOut("reply size too large: %u\n", totlength);
1390 goto done;
1391 }
1392 // Update length field to pass (later) upstream
1393 memcpy(buf, &totlength, sizeof(unsigned int));
1394 // skip wrapper data in payload
1395 memmove(buf + offset, buf + offset + 4, len);
1396 offset += len;
1397 }
1398 // pass reply upstream
1399 write(pype[0], buf, totlength + sizeof(unsigned int));
1400 done:
1401 ;
1402 }
1403 else if (errno != EINTR && errno != EAGAIN)
1404 {
1405 fprintf(stderr, "read error from AVaRICE: %s\n",
1406 strerror(errno));
1407 pthread_exit((void *)1);
1408 }
1409 }
1410 }
1411 }
1412
1413 static void
1414 cleanup_hid(void)
1415 {
1416 hid_close(hdev);
1417 hdev = NULL;
1418 }
1419 #endif
1420
1421 static void
1422 cleanup_usb(void)
1423 {
1424 #ifdef HAVE_LIBUSB_2_0
1425 usb20_cleanup(udev);
1426 #else
1427 usb_release_interface(udev, usb_interface);
1428 usb_close(udev);
1429 #endif
1430 }
1431
1432
1433 void jtag::openUSB(const char *jtagDeviceName)
1434 {
1435 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pype) < 0)
1436 throw jtag_exception("cannot create pipe");
1437
1438 if (emu_type == EMULATOR_EDBG)
1439 {
1440 #ifdef HAVE_LIBHIDAPI
1441 static struct hid_thread_data hdata;
1442 hdev = openhid(jtagDeviceName, hdata.max_pkt_size = 512);
1443 if (hdev == NULL)
1444 throw jtag_exception("cannot open HID");
1445
1446 pthread_create(&htid, NULL, hid_thread, &hdata);
1447 # ifdef __FreeBSD__
1448 pthread_set_name_np(htid, "HID thread");
1449 # endif
1450 atexit(cleanup_hid);
1451 #else // !HAVE_LIBHIDAPI
1452 throw jtag_exception("EDBG/CMSIS-DAP devices require libhidapi support");
1453 #endif
1454 }
1455 else
1456 {
1457 udev = opendev(jtagDeviceName, emu_type, usb_interface);
1458 if (udev == NULL)
1459 throw jtag_exception("cannot open USB device");
1460
1461 #ifdef HAVE_LIBUSB_2_0
1462 pthread_create(&utid, NULL, usb_thread, NULL);
1463 # ifdef __FreeBSD__
1464 pthread_set_name_np(utid, "USB thread");
1465 # endif
1466 #else
1467 pthread_create(&rtid, NULL, usb_thread_read, NULL);
1468 pthread_create(&wtid, NULL, usb_thread_write, NULL);
1469 if (event_ep != 0)
1470 pthread_create(&etid, NULL, usb_thread_event, NULL);
1471 # ifdef __FreeBSD__
1472 pthread_set_name_np(rtid, "USB reader thread");
1473 pthread_set_name_np(wtid, "USB writer thread");
1474 if (event_ep != 0)
1475 pthread_set_name_np(etid, "USB event thread");
1476 # endif
1477 #endif
1478
1479 atexit(cleanup_usb);
1480 }
1481
1482 jtagBox = pype[1];
1483 }
1484
1485 #endif /* HAVE_LIBUSB */