1 /***************************************************************************
2 * Copyright (C) 2007 by Juergen Stuber <juergen@jstuber.net> *
3 * based on Dominic Rath's and Benedikt Sauter's usbprog.c *
5 * Copyright (C) 2008 by Spencer Oliver *
6 * spen@spen-soft.co.uk *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
28 #include "interface.h"
37 #define JLINK_WRITE_ENDPOINT 0x02
38 #define JLINK_READ_ENDPOINT 0x81
40 static unsigned int jlink_write_ep = JLINK_WRITE_ENDPOINT;
41 static unsigned int jlink_read_ep = JLINK_READ_ENDPOINT;
42 static unsigned int jlink_hw_jtag_version = 2;
44 #define JLINK_USB_TIMEOUT 1000
46 // See Section 1.3.2 of the Segger JLink USB protocol manual
47 /* 2048 is the max value we can use here */
48 //#define JLINK_TAP_BUFFER_SIZE 2048
49 #define JLINK_TAP_BUFFER_SIZE 256
50 //#define JLINK_TAP_BUFFER_SIZE 384
52 #define JLINK_IN_BUFFER_SIZE 2048
53 #define JLINK_OUT_BUFFER_SIZE 2*2048 + 4
54 #define JLINK_EMU_RESULT_BUFFER_SIZE 64
56 /* Global USB buffers */
57 static uint8_t usb_in_buffer[JLINK_IN_BUFFER_SIZE];
58 static uint8_t usb_out_buffer[JLINK_OUT_BUFFER_SIZE];
59 static uint8_t usb_emu_result_buffer[JLINK_EMU_RESULT_BUFFER_SIZE];
61 /* Constants for JLink command */
62 #define EMU_CMD_VERSION 0x01
63 #define EMU_CMD_SET_SPEED 0x05
64 #define EMU_CMD_GET_STATE 0x07
65 #define EMU_CMD_HW_CLOCK 0xc8
66 #define EMU_CMD_HW_TMS0 0xc9
67 #define EMU_CMD_HW_TMS1 0xca
68 #define EMU_CMD_HW_JTAG2 0xce
69 #define EMU_CMD_HW_JTAG3 0xcf
70 #define EMU_CMD_GET_MAX_MEM_BLOCK 0xd4
71 #define EMU_CMD_HW_RESET0 0xdc
72 #define EMU_CMD_HW_RESET1 0xdd
73 #define EMU_CMD_HW_TRST0 0xde
74 #define EMU_CMD_HW_TRST1 0xdf
75 #define EMU_CMD_GET_CAPS 0xe8
76 #define EMU_CMD_GET_HW_VERSION 0xf0
78 /* bits return from EMU_CMD_GET_CAPS */
79 #define EMU_CAP_GET_HW_VERSION 1
80 #define EMU_CAP_GET_MAX_BLOCK_SIZE 11
82 /* max speed 12MHz v5.0 jlink */
83 #define JLINK_MAX_SPEED 12000
85 /* External interface functions */
86 static int jlink_execute_queue(void);
87 static int jlink_speed(int speed);
88 static int jlink_speed_div(int speed, int* khz);
89 static int jlink_khz(int khz, int *jtag_speed);
90 static int jlink_register_commands(struct command_context_s *cmd_ctx);
91 static int jlink_init(void);
92 static int jlink_quit(void);
94 /* CLI command handler functions */
95 static int jlink_handle_jlink_info_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
96 static int jlink_handle_jlink_hw_jtag_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
98 /* Queue command functions */
99 static void jlink_end_state(tap_state_t state);
100 static void jlink_state_move(void);
101 static void jlink_path_move(int num_states, tap_state_t *path);
102 static void jlink_runtest(int num_cycles);
103 static void jlink_scan(bool ir_scan, enum scan_type type, uint8_t *buffer, int scan_size, scan_command_t *command);
104 static void jlink_reset(int trst, int srst);
105 static void jlink_simple_command(uint8_t command);
106 static int jlink_get_status(void);
108 /* J-Link tap buffer functions */
109 static void jlink_tap_init(void);
110 static int jlink_tap_execute(void);
111 static void jlink_tap_ensure_space(int scans, int bits);
112 static void jlink_tap_append_step(int tms, int tdi);
113 static void jlink_tap_append_scan(int length, uint8_t *buffer, scan_command_t *command);
115 /* Jlink lowlevel functions */
116 typedef struct jlink_jtag
118 struct usb_dev_handle* usb_handle;
121 static jlink_jtag_t *jlink_usb_open(void);
122 static void jlink_usb_close(jlink_jtag_t *jlink_jtag);
123 static int jlink_usb_message(jlink_jtag_t *jlink_jtag, int out_length, int in_length);
124 static int jlink_usb_write(jlink_jtag_t *jlink_jtag, int out_length);
125 static int jlink_usb_read(jlink_jtag_t *jlink_jtag, int expected_size);
126 static int jlink_usb_read_emu_result(jlink_jtag_t *jlink_jtag);
128 /* helper functions */
129 static int jlink_get_version_info(void);
131 #ifdef _DEBUG_USB_COMMS_
132 static void jlink_debug_buffer(uint8_t *buffer, int length);
135 static enum tap_state jlink_last_state = TAP_RESET;
137 static jlink_jtag_t* jlink_jtag_handle;
139 /***************************************************************************/
140 /* External interface implementation */
142 jtag_interface_t jlink_interface =
145 .execute_queue = jlink_execute_queue,
146 .speed = jlink_speed,
147 .speed_div = jlink_speed_div,
149 .register_commands = jlink_register_commands,
154 static void jlink_execute_runtest(jtag_command_t *cmd)
156 DEBUG_JTAG_IO("runtest %i cycles, end in %i",
157 cmd->cmd.runtest->num_cycles,
158 cmd->cmd.runtest->end_state);
160 jlink_end_state(cmd->cmd.runtest->end_state);
162 jlink_runtest(cmd->cmd.runtest->num_cycles);
165 static void jlink_execute_statemove(jtag_command_t *cmd)
167 DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
169 jlink_end_state(cmd->cmd.statemove->end_state);
173 static void jlink_execute_pathmove(jtag_command_t *cmd)
175 DEBUG_JTAG_IO("pathmove: %i states, end in %i",
176 cmd->cmd.pathmove->num_states,
177 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
179 jlink_path_move(cmd->cmd.pathmove->num_states,
180 cmd->cmd.pathmove->path);
183 static void jlink_execute_scan(jtag_command_t *cmd)
189 DEBUG_JTAG_IO("scan end in %s", tap_state_name(cmd->cmd.scan->end_state));
191 jlink_end_state(cmd->cmd.scan->end_state);
193 scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
194 DEBUG_JTAG_IO("scan input, length = %d", scan_size);
196 #ifdef _DEBUG_USB_COMMS_
197 jlink_debug_buffer(buffer, (scan_size + 7) / 8);
199 type = jtag_scan_type(cmd->cmd.scan);
200 jlink_scan(cmd->cmd.scan->ir_scan,
201 type, buffer, scan_size, cmd->cmd.scan);
204 static void jlink_execute_reset(jtag_command_t *cmd)
206 DEBUG_JTAG_IO("reset trst: %i srst %i",
207 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
210 jlink_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
214 static void jlink_execute_sleep(jtag_command_t *cmd)
216 DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
218 jtag_sleep(cmd->cmd.sleep->us);
221 static void jlink_execute_command(jtag_command_t *cmd)
225 case JTAG_RUNTEST: jlink_execute_runtest(cmd); break;
226 case JTAG_STATEMOVE: jlink_execute_statemove(cmd); break;
227 case JTAG_PATHMOVE: jlink_execute_pathmove(cmd); break;
228 case JTAG_SCAN: jlink_execute_scan(cmd); break;
229 case JTAG_RESET: jlink_execute_reset(cmd); break;
230 case JTAG_SLEEP: jlink_execute_sleep(cmd); break;
232 LOG_ERROR("BUG: unknown JTAG command type encountered");
237 static int jlink_execute_queue(void)
239 jtag_command_t *cmd = jtag_command_queue;
243 jlink_execute_command(cmd);
247 return jlink_tap_execute();
250 /* Sets speed in kHz. */
251 static int jlink_speed(int speed)
255 if (speed > JLINK_MAX_SPEED)
257 LOG_INFO("Ignoring speed request: %dkHz exceeds %dkHz maximum",
258 speed, JLINK_MAX_SPEED);
262 /* check for RTCK setting */
266 usb_out_buffer[0] = EMU_CMD_SET_SPEED;
267 usb_out_buffer[1] = (speed >> 0) & 0xff;
268 usb_out_buffer[2] = (speed >> 8) & 0xff;
270 result = jlink_usb_write(jlink_jtag_handle, 3);
273 LOG_ERROR("J-Link setting speed failed (%d)", result);
274 return ERROR_JTAG_DEVICE_ERROR;
280 static int jlink_speed_div(int speed, int* khz)
287 static int jlink_khz(int khz, int *jtag_speed)
294 static int jlink_register_commands(struct command_context_s *cmd_ctx)
297 register_command(cmd_ctx, NULL, "jlink_info",
298 &jlink_handle_jlink_info_command, COMMAND_EXEC,
300 register_command(cmd_ctx, NULL, "jlink_hw_jtag",
301 &jlink_handle_jlink_hw_jtag_command, COMMAND_EXEC,
302 "set/get jlink hw jtag command version [2 | 3]");
306 static int jlink_init(void)
310 jlink_jtag_handle = jlink_usb_open();
312 if (jlink_jtag_handle == 0)
314 LOG_ERROR("Cannot find jlink Interface! Please check connection and permissions.");
315 return ERROR_JTAG_INIT_FAILED;
319 * The next three instructions were added after discovering a problem while using an oscilloscope. For the V8
320 * SAM-ICE dongle (and likely other j-link device variants), the reset line to the target microprocessor was found to
321 * cycle only intermittently during emulator startup (even after encountering the downstream reset instruction later
322 * in the code). This was found to create two issues: 1) In general it is a bad practice to not reset a CPU to a known
323 * state when starting an emulator and 2) something critical happens inside the dongle when it does the first read
324 * following a new USB session. Keeping the processor in reset during the first read collecting version information
325 * seems to prevent errant "J-Link command EMU_CMD_VERSION failed" issues.
328 LOG_INFO("J-Link initialization started / target CPU reset initiated");
329 jlink_simple_command(EMU_CMD_HW_TRST0);
330 jlink_simple_command(EMU_CMD_HW_RESET0);
333 jlink_hw_jtag_version = 2;
335 if (jlink_get_version_info() == ERROR_OK)
337 /* attempt to get status */
341 LOG_INFO("J-Link JTAG Interface ready");
346 jlink_speed(jtag_get_speed());
348 /* v5/6 jlink seems to have an issue if the first tap move
349 * is not divisible by 8, so we send a TLR on first power up */
350 for (i = 0; i < 8; i++) {
351 jlink_tap_append_step(1, 0);
358 static int jlink_quit(void)
360 jlink_usb_close(jlink_jtag_handle);
364 /***************************************************************************/
365 /* Queue command implementations */
367 static void jlink_end_state(tap_state_t state)
369 if (tap_is_state_stable(state))
371 tap_set_end_state(state);
375 LOG_ERROR("BUG: %i is not a valid end state", state);
380 /* Goes to the end state. */
381 static void jlink_state_move(void)
385 uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
386 uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
388 for (i = 0; i < tms_scan_bits; i++)
390 tms = (tms_scan >> i) & 1;
391 jlink_tap_append_step(tms, 0);
394 tap_set_state(tap_get_end_state());
397 static void jlink_path_move(int num_states, tap_state_t *path)
401 for (i = 0; i < num_states; i++)
403 if (path[i] == tap_state_transition(tap_get_state(), false))
405 jlink_tap_append_step(0, 0);
407 else if (path[i] == tap_state_transition(tap_get_state(), true))
409 jlink_tap_append_step(1, 0);
413 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition", tap_state_name(tap_get_state()), tap_state_name(path[i]));
417 tap_set_state(path[i]);
420 tap_set_end_state(tap_get_state());
423 static void jlink_runtest(int num_cycles)
427 tap_state_t saved_end_state = tap_get_end_state();
429 jlink_tap_ensure_space(1,num_cycles + 16);
431 /* only do a state_move when we're not already in IDLE */
432 if (tap_get_state() != TAP_IDLE)
434 jlink_end_state(TAP_IDLE);
439 /* execute num_cycles */
440 for (i = 0; i < num_cycles; i++)
442 jlink_tap_append_step(0, 0);
445 /* finish in end_state */
446 jlink_end_state(saved_end_state);
447 if (tap_get_state() != tap_get_end_state())
453 static void jlink_scan(bool ir_scan, enum scan_type type, uint8_t *buffer, int scan_size, scan_command_t *command)
455 tap_state_t saved_end_state;
457 jlink_tap_ensure_space(1, scan_size + 16);
459 saved_end_state = tap_get_end_state();
461 /* Move to appropriate scan state */
462 jlink_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
464 /* Only move if we're not already there */
465 if (tap_get_state() != tap_get_end_state())
468 jlink_end_state(saved_end_state);
471 jlink_tap_append_scan(scan_size, buffer, command);
473 /* We are in Exit1, go to Pause */
474 jlink_tap_append_step(0, 0);
476 tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
478 if (tap_get_state() != tap_get_end_state())
484 static void jlink_reset(int trst, int srst)
486 LOG_DEBUG("trst: %i, srst: %i", trst, srst);
488 /* Signals are active low */
491 jlink_simple_command(EMU_CMD_HW_RESET1);
495 jlink_simple_command(EMU_CMD_HW_RESET0);
500 jlink_simple_command(EMU_CMD_HW_TRST0);
504 jlink_simple_command(EMU_CMD_HW_TRST1);
506 jlink_end_state(TAP_RESET);
511 static void jlink_simple_command(uint8_t command)
515 DEBUG_JTAG_IO("0x%02x", command);
517 usb_out_buffer[0] = command;
518 result = jlink_usb_write(jlink_jtag_handle, 1);
522 LOG_ERROR("J-Link command 0x%02x failed (%d)", command, result);
526 static int jlink_get_status(void)
530 jlink_simple_command(EMU_CMD_GET_STATE);
532 result = jlink_usb_read(jlink_jtag_handle, 8);
535 LOG_ERROR("J-Link command EMU_CMD_GET_STATE failed (%d)\n", result);
536 return ERROR_JTAG_DEVICE_ERROR;
539 int vref = usb_in_buffer[0] + (usb_in_buffer[1] << 8);
540 LOG_INFO("Vref = %d.%d TCK = %d TDI = %d TDO = %d TMS = %d SRST = %d TRST = %d\n", \
541 vref / 1000, vref % 1000, \
542 usb_in_buffer[2], usb_in_buffer[3], usb_in_buffer[4], \
543 usb_in_buffer[5], usb_in_buffer[6], usb_in_buffer[7]);
546 LOG_ERROR("Vref too low. Check Target Power\n");
551 static int jlink_get_version_info(void)
555 uint32_t jlink_caps, jlink_max_size;
557 /* query hardware version */
558 jlink_simple_command(EMU_CMD_VERSION);
560 result = jlink_usb_read(jlink_jtag_handle, 2);
563 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)\n", result);
564 return ERROR_JTAG_DEVICE_ERROR;
567 len = buf_get_u32(usb_in_buffer, 0, 16);
568 if (len > JLINK_IN_BUFFER_SIZE)
570 LOG_ERROR("J-Link command EMU_CMD_VERSION impossible return length 0x%0x", len);
571 len = JLINK_IN_BUFFER_SIZE;
574 result = jlink_usb_read(jlink_jtag_handle, len);
577 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)\n", result);
578 return ERROR_JTAG_DEVICE_ERROR;
581 usb_in_buffer[result] = 0;
582 LOG_INFO("%s", (char *)usb_in_buffer);
584 /* query hardware capabilities */
585 jlink_simple_command(EMU_CMD_GET_CAPS);
587 result = jlink_usb_read(jlink_jtag_handle, 4);
590 LOG_ERROR("J-Link command EMU_CMD_GET_CAPS failed (%d)\n", result);
591 return ERROR_JTAG_DEVICE_ERROR;
594 jlink_caps = buf_get_u32(usb_in_buffer, 0, 32);
595 LOG_INFO("JLink caps 0x%x", (unsigned)jlink_caps);
597 if (jlink_caps & (1 << EMU_CAP_GET_HW_VERSION))
599 /* query hardware version */
600 jlink_simple_command(EMU_CMD_GET_HW_VERSION);
602 result = jlink_usb_read(jlink_jtag_handle, 4);
605 LOG_ERROR("J-Link command EMU_CMD_GET_HW_VERSION failed (%d)\n", result);
606 return ERROR_JTAG_DEVICE_ERROR;
609 uint32_t jlink_hw_version = buf_get_u32(usb_in_buffer, 0, 32);
610 uint32_t major_revision = (jlink_hw_version / 10000) % 100;
611 if (major_revision >= 5)
612 jlink_hw_jtag_version = 3;
614 LOG_INFO("JLink hw version %i", (int)jlink_hw_version);
617 if (jlink_caps & (1 << EMU_CAP_GET_MAX_BLOCK_SIZE))
619 /* query hardware maximum memory block */
620 jlink_simple_command(EMU_CMD_GET_MAX_MEM_BLOCK);
622 result = jlink_usb_read(jlink_jtag_handle, 4);
625 LOG_ERROR("J-Link command EMU_CMD_GET_MAX_MEM_BLOCK failed (%d)\n", result);
626 return ERROR_JTAG_DEVICE_ERROR;
629 jlink_max_size = buf_get_u32(usb_in_buffer, 0, 32);
630 LOG_INFO("JLink max mem block %i", (int)jlink_max_size);
636 static int jlink_handle_jlink_info_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
638 if (jlink_get_version_info() == ERROR_OK)
640 /* attempt to get status */
647 static int jlink_handle_jlink_hw_jtag_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
651 command_print(cmd_ctx, "jlink hw jtag %i", jlink_hw_jtag_version);
654 int request_version = atoi(args[0]);
655 switch (request_version) {
657 jlink_hw_jtag_version = request_version;
660 return ERROR_COMMAND_SYNTAX_ERROR;
665 return ERROR_COMMAND_SYNTAX_ERROR;
671 /***************************************************************************/
672 /* J-Link tap functions */
675 static unsigned tap_length = 0;
676 static uint8_t tms_buffer[JLINK_TAP_BUFFER_SIZE];
677 static uint8_t tdi_buffer[JLINK_TAP_BUFFER_SIZE];
678 static uint8_t tdo_buffer[JLINK_TAP_BUFFER_SIZE];
682 int first; /* First bit position in tdo_buffer to read */
683 int length; /* Number of bits to read */
684 scan_command_t *command; /* Corresponding scan command */
686 } pending_scan_result_t;
688 #define MAX_PENDING_SCAN_RESULTS 256
690 static int pending_scan_results_length;
691 static pending_scan_result_t pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
693 static void jlink_tap_init(void)
696 pending_scan_results_length = 0;
699 static void jlink_tap_ensure_space(int scans, int bits)
701 int available_scans = MAX_PENDING_SCAN_RESULTS - pending_scan_results_length;
702 int available_bits = JLINK_TAP_BUFFER_SIZE * 8 - tap_length - 32;
704 if (scans > available_scans || bits > available_bits)
710 static void jlink_tap_append_step(int tms, int tdi)
712 int index = tap_length / 8;
714 if (index >= JLINK_TAP_BUFFER_SIZE)
716 LOG_ERROR("jlink_tap_append_step: overflow");
717 *(uint32_t *)0xFFFFFFFF = 0;
721 int bit_index = tap_length % 8;
722 uint8_t bit = 1 << bit_index;
724 // we do not pad TMS, so be sure to initialize all bits
727 tms_buffer[index] = tdi_buffer[index] = 0;
731 tms_buffer[index] |= bit;
733 tms_buffer[index] &= ~bit;
736 tdi_buffer[index] |= bit;
738 tdi_buffer[index] &= ~bit;
743 static void jlink_tap_append_scan(int length, uint8_t *buffer, scan_command_t *command)
745 pending_scan_result_t *pending_scan_result =
746 &pending_scan_results_buffer[pending_scan_results_length];
749 pending_scan_result->first = tap_length;
750 pending_scan_result->length = length;
751 pending_scan_result->command = command;
752 pending_scan_result->buffer = buffer;
754 for (i = 0; i < length; i++)
756 int tms = (i < (length - 1)) ? 0 : 1;
757 int tdi = (buffer[i / 8] & (1 << (i % 8))) != 0;
758 jlink_tap_append_step(tms, tdi);
760 pending_scan_results_length++;
763 /* Pad and send a tap sequence to the device, and receive the answer.
764 * For the purpose of padding we assume that we are in idle or pause state. */
765 static int jlink_tap_execute(void)
774 /* JLink returns an extra NULL in packet when size of in message is a multiple of 64, creates problems with usb comms */
775 /* WARNING This will interfere with tap state counting */
776 while ((TAP_SCAN_BYTES(tap_length)%64) == 0)
778 jlink_tap_append_step((tap_get_state() == TAP_RESET)?1:0, 0);
781 // number of full bytes (plus one if some would be left over)
782 byte_length = TAP_SCAN_BYTES(tap_length);
784 bool use_jtag3 = jlink_hw_jtag_version >= 3;
785 usb_out_buffer[0] = use_jtag3 ? EMU_CMD_HW_JTAG3 : EMU_CMD_HW_JTAG2;
786 usb_out_buffer[1] = 0;
787 usb_out_buffer[2] = (tap_length >> 0) & 0xff;
788 usb_out_buffer[3] = (tap_length >> 8) & 0xff;
789 memcpy(usb_out_buffer + 4, tms_buffer, byte_length);
790 memcpy(usb_out_buffer + 4 + byte_length, tdi_buffer, byte_length);
792 jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
793 tap_length, jlink_last_state);
795 result = jlink_usb_message(jlink_jtag_handle, 4 + 2 * byte_length, byte_length);
796 if (result != byte_length)
798 LOG_ERROR("jlink_tap_execute, wrong result %d (expected %d)", result, byte_length);
800 return ERROR_JTAG_QUEUE_FAILED;
803 memcpy(tdo_buffer, usb_in_buffer, byte_length);
805 for (i = 0; i < pending_scan_results_length; i++)
807 pending_scan_result_t *pending_scan_result = &pending_scan_results_buffer[i];
808 uint8_t *buffer = pending_scan_result->buffer;
809 int length = pending_scan_result->length;
810 int first = pending_scan_result->first;
811 scan_command_t *command = pending_scan_result->command;
814 buf_set_buf(tdo_buffer, first, buffer, 0, length);
816 DEBUG_JTAG_IO("pending scan result, length = %d", length);
818 #ifdef _DEBUG_USB_COMMS_
819 jlink_debug_buffer(buffer, TAP_SCAN_BYTES(length));
822 if (jtag_read_buffer(buffer, command) != ERROR_OK)
825 return ERROR_JTAG_QUEUE_FAILED;
828 if (pending_scan_result->buffer != NULL)
830 free(pending_scan_result->buffer);
838 static struct usb_device* find_jlink_device(void)
840 struct usb_bus *busses;
842 struct usb_device *dev;
847 busses = usb_get_busses();
849 /* find jlink_jtag device in usb bus */
851 for (bus = busses; bus; bus = bus->next)
853 for (dev = bus->devices; dev; dev = dev->next)
855 if ((dev->descriptor.idVendor == VID) && (dev->descriptor.idProduct == PID)) {
864 /*****************************************************************************/
865 /* JLink USB low-level functions */
867 static jlink_jtag_t* jlink_usb_open()
869 struct usb_device *dev;
871 jlink_jtag_t *result;
873 result = (jlink_jtag_t*) malloc(sizeof(jlink_jtag_t));
877 if ((dev = find_jlink_device()) == NULL) {
882 result->usb_handle = usb_open(dev);
884 if (result->usb_handle)
887 /* BE ***VERY CAREFUL*** ABOUT MAKING CHANGES IN THIS AREA!!!!!!!!!!!
888 * The behavior of libusb is not completely consistent across Windows, Linux, and Mac OS X platforms. The actions taken
889 * in the following compiler conditionals may not agree with published documentation for libusb, but were found
890 * to be necessary through trials and tribulations. Even little tweaks can break one or more platforms, so if you do make changes
891 * test them carefully on all platforms before committing them!
896 usb_reset(result->usb_handle);
902 /* reopen jlink after usb_reset
903 * on win32 this may take a second or two to re-enumerate */
904 while ((dev = find_jlink_device()) == NULL)
919 result->usb_handle = usb_open(dev);
924 if (result->usb_handle)
926 /* usb_set_configuration required under win32 */
927 usb_set_configuration(result->usb_handle, dev->config[0].bConfigurationValue);
928 usb_claim_interface(result->usb_handle, 0);
932 * This makes problems under Mac OS X. And is not needed
933 * under Windows. Hopefully this will not break a linux build
935 usb_set_altinterface(result->usb_handle, 0);
937 struct usb_interface *iface = dev->config->interface;
938 struct usb_interface_descriptor *desc = iface->altsetting;
939 for (int i = 0; i < desc->bNumEndpoints; i++)
941 uint8_t epnum = desc->endpoint[i].bEndpointAddress;
942 bool is_input = epnum & 0x80;
943 LOG_DEBUG("usb ep %s %02x", is_input ? "in" : "out", epnum);
945 jlink_read_ep = epnum;
947 jlink_write_ep = epnum;
958 static void jlink_usb_close(jlink_jtag_t *jlink_jtag)
960 usb_close(jlink_jtag->usb_handle);
964 /* Send a message and receive the reply. */
965 static int jlink_usb_message(jlink_jtag_t *jlink_jtag, int out_length, int in_length)
969 result = jlink_usb_write(jlink_jtag, out_length);
970 if (result != out_length)
972 LOG_ERROR("usb_bulk_write failed (requested=%d, result=%d)",
974 return ERROR_JTAG_DEVICE_ERROR;
977 result = jlink_usb_read(jlink_jtag, in_length);
978 if ((result != in_length) && (result != (in_length + 1)))
980 LOG_ERROR("usb_bulk_read failed (requested=%d, result=%d)",
982 return ERROR_JTAG_DEVICE_ERROR;
985 if (jlink_hw_jtag_version < 3)
988 int result2 = ERROR_OK;
989 if (result == in_length)
991 /* Must read the result from the EMU too */
992 result2 = jlink_usb_read_emu_result(jlink_jtag);
995 LOG_ERROR("jlink_usb_read_emu_result retried requested = 1, result=%d, in_length=%i", result2,in_length);
996 /* Try again once, should only happen if (in_length%64 == 0) */
997 result2 = jlink_usb_read_emu_result(jlink_jtag);
1000 LOG_ERROR("jlink_usb_read_emu_result failed "
1001 "(requested = 1, result=%d)", result2);
1002 return ERROR_JTAG_DEVICE_ERROR;
1006 /* Check the result itself */
1007 result2 = usb_emu_result_buffer[0];
1011 /* Save the result, then remove it from return value */
1012 result2 = usb_in_buffer[result--];
1017 LOG_ERROR("jlink_usb_message failed with result=%d)", result2);
1018 return ERROR_JTAG_DEVICE_ERROR;
1024 /* calls the given usb_bulk_* function, allowing for the data to trickle in with some timeouts */
1025 static int usb_bulk_with_retries(
1026 int (*f)(usb_dev_handle *, int, char *, int, int),
1027 usb_dev_handle *dev, int ep,
1028 char *bytes, int size, int timeout)
1030 int tries = 3, count = 0;
1032 while (tries && (count < size))
1034 int result = f(dev, ep, bytes + count, size - count, timeout);
1037 else if ((-ETIMEDOUT != result) || !--tries)
1043 static int wrap_usb_bulk_write(usb_dev_handle *dev, int ep,
1044 char *buff, int size, int timeout)
1046 /* usb_bulk_write() takes const char *buff */
1047 return usb_bulk_write(dev, ep, buff, size, timeout);
1050 static inline int usb_bulk_write_ex(usb_dev_handle *dev, int ep,
1051 char *bytes, int size, int timeout)
1053 return usb_bulk_with_retries(&wrap_usb_bulk_write,
1054 dev, ep, bytes, size, timeout);
1057 static inline int usb_bulk_read_ex(usb_dev_handle *dev, int ep,
1058 char *bytes, int size, int timeout)
1060 return usb_bulk_with_retries(&usb_bulk_read,
1061 dev, ep, bytes, size, timeout);
1064 /* Write data from out_buffer to USB. */
1065 static int jlink_usb_write(jlink_jtag_t *jlink_jtag, int out_length)
1069 if (out_length > JLINK_OUT_BUFFER_SIZE)
1071 LOG_ERROR("jlink_jtag_write illegal out_length=%d (max=%d)", out_length, JLINK_OUT_BUFFER_SIZE);
1075 result = usb_bulk_write_ex(jlink_jtag->usb_handle, jlink_write_ep,
1076 (char *)usb_out_buffer, out_length, JLINK_USB_TIMEOUT);
1078 DEBUG_JTAG_IO("jlink_usb_write, out_length = %d, result = %d", out_length, result);
1080 #ifdef _DEBUG_USB_COMMS_
1081 jlink_debug_buffer(usb_out_buffer, out_length);
1086 /* Read data from USB into in_buffer. */
1087 static int jlink_usb_read(jlink_jtag_t *jlink_jtag, int expected_size)
1089 int result = usb_bulk_read_ex(jlink_jtag->usb_handle, jlink_read_ep,
1090 (char *)usb_in_buffer, expected_size, JLINK_USB_TIMEOUT);
1092 DEBUG_JTAG_IO("jlink_usb_read, result = %d", result);
1094 #ifdef _DEBUG_USB_COMMS_
1095 jlink_debug_buffer(usb_in_buffer, result);
1100 /* Read the result from the previous EMU cmd into result_buffer. */
1101 static int jlink_usb_read_emu_result(jlink_jtag_t *jlink_jtag)
1103 int result = usb_bulk_read_ex(jlink_jtag->usb_handle, jlink_read_ep,
1104 (char *)usb_emu_result_buffer, 1 /* JLINK_EMU_RESULT_BUFFER_SIZE */,
1107 DEBUG_JTAG_IO("jlink_usb_read_result, result = %d", result);
1109 #ifdef _DEBUG_USB_COMMS_
1110 jlink_debug_buffer(usb_emu_result_buffer, result);
1115 #ifdef _DEBUG_USB_COMMS_
1116 #define BYTES_PER_LINE 16
1118 static void jlink_debug_buffer(uint8_t *buffer, int length)
1125 for (i = 0; i < length; i += BYTES_PER_LINE)
1127 snprintf(line, 5, "%04x", i);
1128 for (j = i; j < i + BYTES_PER_LINE && j < length; j++)
1130 snprintf(s, 4, " %02x", buffer[j]);
1133 LOG_DEBUG("%s", line);