drivers/jlink: Revert old workaround
[fw/openocd] / src / jtag / drivers / jlink.c
1 /***************************************************************************
2  *   Copyright (C) 2007 by Juergen Stuber <juergen@jstuber.net>            *
3  *   based on Dominic Rath's and Benedikt Sauter's usbprog.c               *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   Copyright (C) 2011 by Jean-Christophe PLAGNIOL-VIILARD                *
9  *   plagnioj@jcrosoft.com                                                 *
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  *   This program is distributed in the hope that it will be useful,       *
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
19  *   GNU General Public License for more details.                          *
20  *                                                                         *
21  *   You should have received a copy of the GNU General Public License     *
22  *   along with this program; if not, write to the                         *
23  *   Free Software Foundation, Inc.,                                       *
24  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
25  ***************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <jtag/interface.h>
32 #include <jtag/swd.h>
33 #include <jtag/commands.h>
34 #include "libusb_common.h"
35
36 /* See Segger's public documentation:
37  * Reference manual for J-Link USB Protocol
38  * Document RM08001-R6 Date: June 16, 2009
39  * (Or newer, with some SWD information).
40  * http://www.segger.com/cms/admin/uploads/productDocs/RM08001_JLinkUSBProtocol.pdf
41  */
42
43 /*
44  * The default pid of the segger is 0x0101
45  * But when you change the USB Address it will also
46  *
47  * pid = ( usb_address > 0x4) ? 0x0101 : (0x101 + usb_address)
48  */
49
50 #define JLINK_OB_PID  0x0105
51
52 #define JLINK_WRITE_ENDPOINT    0x02
53 #define JLINK_READ_ENDPOINT             0x81
54
55 #define JLINK_OB_WRITE_ENDPOINT 0x06
56 #define JLINK_OB_READ_ENDPOINT  0x85
57
58 static unsigned int jlink_write_ep = JLINK_WRITE_ENDPOINT;
59 static unsigned int jlink_read_ep = JLINK_READ_ENDPOINT;
60 static unsigned int jlink_hw_jtag_version = 2;
61
62 #define JLINK_USB_TIMEOUT 1000
63
64 /* See Section 3.3.2 of the Segger JLink USB protocol manual */
65 /* 2048 is the max value we can use here */
66 #define JLINK_TAP_BUFFER_SIZE 2048
67 /*#define JLINK_TAP_BUFFER_SIZE 256*/
68 /*#define JLINK_TAP_BUFFER_SIZE 384*/
69
70 #define JLINK_IN_BUFFER_SIZE                    (2048 + 1)
71 #define JLINK_OUT_BUFFER_SIZE                   (2*2048 + 4)
72
73 /* Global USB buffers */
74 static uint8_t usb_in_buffer[JLINK_IN_BUFFER_SIZE];
75 static uint8_t usb_out_buffer[JLINK_OUT_BUFFER_SIZE];
76
77 /* Constants for JLink command */
78 #define EMU_CMD_VERSION                 0x01
79 #define EMU_CMD_RESET_TRST              0x02
80 #define EMU_CMD_RESET_TARGET    0x03
81 #define EMU_CMD_SET_SPEED               0x05
82 #define EMU_CMD_GET_STATE               0x07
83 #define EMU_CMD_SET_KS_POWER    0x08
84 #define EMU_CMD_GET_SPEEDS              0xc0
85 #define EMU_CMD_GET_HW_INFO             0xc1
86 #define EMU_CMD_GET_COUNTERS    0xc2
87 #define EMU_CMD_SELECT_IF               0xc7
88 #define EMU_CMD_HW_CLOCK                0xc8
89 #define EMU_CMD_HW_TMS0                 0xc9
90 #define EMU_CMD_HW_TMS1                 0xca
91 #define EMU_CMD_HW_DATA0                0xcb
92 #define EMU_CMD_HW_DATA1                0xcc
93 #define EMU_CMD_HW_JTAG                 0xcd
94 #define EMU_CMD_HW_JTAG2                0xce
95 #define EMU_CMD_HW_JTAG3                0xcf
96 #define EMU_CMD_HW_RELEASE_RESET_STOP_EX 0xd0
97 #define EMU_CMD_HW_RELEASE_RESET_STOP_TIMED 0xd1
98 #define EMU_CMD_GET_MAX_MEM_BLOCK       0xd4
99 #define EMU_CMD_HW_JTAG_WRITE           0xd5
100 #define EMU_CMD_HW_JTAG_GET_RESULT      0xd6
101 #define EMU_CMD_HW_RESET0               0xdc
102 #define EMU_CMD_HW_RESET1               0xdd
103 #define EMU_CMD_HW_TRST0                0xde
104 #define EMU_CMD_HW_TRST1                0xdf
105 #define EMU_CMD_GET_CAPS                0xe8
106 #define EMU_CMD_GET_CPU_CAPS    0xe9
107 #define EMU_CMD_EXEC_CPU_CMD    0xea
108 #define EMU_CMD_GET_CAPS_EX             0xed
109 #define EMU_CMD_GET_HW_VERSION  0xf0
110 #define EMU_CMD_WRITE_DCC               0xf1
111 #define EMU_CMD_READ_CONFIG             0xf2
112 #define EMU_CMD_WRITE_CONFIG            0xf3
113 #define EMU_CMD_WRITE_MEM                       0xf4
114 #define EMU_CMD_READ_MEM                        0xf5
115 #define EMU_CMD_MEASURE_RTCK_REACT      0xf6
116 #define EMU_CMD_WRITE_MEM_ARM79         0xf7
117 #define EMU_CMD_READ_MEM_ARM79          0xf8
118
119 /* bits return from EMU_CMD_GET_CAPS */
120 #define EMU_CAP_RESERVED_1              0
121 #define EMU_CAP_GET_HW_VERSION          1
122 #define EMU_CAP_WRITE_DCC               2
123 #define EMU_CAP_ADAPTIVE_CLOCKING       3
124 #define EMU_CAP_READ_CONFIG             4
125 #define EMU_CAP_WRITE_CONFIG            5
126 #define EMU_CAP_TRACE                   6
127 #define EMU_CAP_WRITE_MEM               7
128 #define EMU_CAP_READ_MEM                8
129 #define EMU_CAP_SPEED_INFO              9
130 #define EMU_CAP_EXEC_CODE               10
131 #define EMU_CAP_GET_MAX_BLOCK_SIZE      11
132 #define EMU_CAP_GET_HW_INFO             12
133 #define EMU_CAP_SET_KS_POWER            13
134 #define EMU_CAP_RESET_STOP_TIMED        14
135 #define EMU_CAP_RESERVED_2              15
136 #define EMU_CAP_MEASURE_RTCK_REACT      16
137 #define EMU_CAP_SELECT_IF               17
138 #define EMU_CAP_RW_MEM_ARM79            18
139 #define EMU_CAP_GET_COUNTERS            19
140 #define EMU_CAP_READ_DCC                20
141 #define EMU_CAP_GET_CPU_CAPS            21
142 #define EMU_CAP_EXEC_CPU_CMD            22
143 #define EMU_CAP_SWO                     23
144 #define EMU_CAP_WRITE_DCC_EX            24
145 #define EMU_CAP_UPDATE_FIRMWARE_EX      25
146 #define EMU_CAP_FILE_IO                 26
147 #define EMU_CAP_REGISTER                27
148 #define EMU_CAP_INDICATORS              28
149 #define EMU_CAP_TEST_NET_SPEED          29
150 #define EMU_CAP_RAWTRACE                30
151 #define EMU_CAP_RESERVED_3              31
152
153 static char *jlink_cap_str[] = {
154         "Always 1.",
155         "Supports command EMU_CMD_GET_HARDWARE_VERSION",
156         "Supports command EMU_CMD_WRITE_DCC",
157         "Supports adaptive clocking",
158         "Supports command EMU_CMD_READ_CONFIG",
159         "Supports command EMU_CMD_WRITE_CONFIG",
160         "Supports trace commands",
161         "Supports command EMU_CMD_WRITE_MEM",
162         "Supports command EMU_CMD_READ_MEM",
163         "Supports command EMU_CMD_GET_SPEED",
164         "Supports command EMU_CMD_CODE_...",
165         "Supports command EMU_CMD_GET_MAX_BLOCK_SIZE",
166         "Supports command EMU_CMD_GET_HW_INFO",
167         "Supports command EMU_CMD_SET_KS_POWER",
168         "Supports command EMU_CMD_HW_RELEASE_RESET_STOP_TIMED",
169         "Reserved",
170         "Supports command EMU_CMD_MEASURE_RTCK_REACT",
171         "Supports command EMU_CMD_HW_SELECT_IF",
172         "Supports command EMU_CMD_READ/WRITE_MEM_ARM79",
173         "Supports command EMU_CMD_GET_COUNTERS",
174         "Supports command EMU_CMD_READ_DCC",
175         "Supports command EMU_CMD_GET_CPU_CAPS",
176         "Supports command EMU_CMD_EXEC_CPU_CMD",
177         "Supports command EMU_CMD_SWO",
178         "Supports command EMU_CMD_WRITE_DCC_EX",
179         "Supports command EMU_CMD_UPDATE_FIRMWARE_EX",
180         "Supports command EMU_CMD_FILE_IO",
181         "Supports command EMU_CMD_REGISTER",
182         "Supports command EMU_CMD_INDICATORS",
183         "Supports command EMU_CMD_TEST_NET_SPEED",
184         "Supports command EMU_CMD_RAWTRACE",
185         "Reserved",
186 };
187
188 /* max speed 12MHz v5.0 jlink */
189 #define JLINK_MAX_SPEED 12000
190
191 /* J-Link hardware versions */
192 #define JLINK_HW_TYPE_JLINK     0
193 #define JLINK_HW_TYPE_JTRACE    1
194 #define JLINK_HW_TYPE_FLASHER   2
195 #define JLINK_HW_TYPE_JLINK_PRO 3
196 #define JLINK_HW_TYPE_MAX       4
197
198 static char *jlink_hw_type_str[] = {
199         "J-Link",
200         "J-Trace",
201         "Flasher",
202         "J-Link Pro",
203 };
204
205 #define JLINK_TIF_JTAG          0
206 #define JLINK_TIF_SWD           1
207 #define JLINK_SWD_DIR_IN        0
208 #define JLINK_SWD_DIR_OUT       1
209
210 /* Queue command functions */
211 static void jlink_end_state(tap_state_t state);
212 static void jlink_state_move(void);
213 static void jlink_path_move(int num_states, tap_state_t *path);
214 static void jlink_runtest(int num_cycles);
215 static void jlink_scan(bool ir_scan, enum scan_type type, uint8_t *buffer,
216                 int scan_size, struct scan_command *command);
217 static void jlink_reset(int trst, int srst);
218 static void jlink_simple_command(uint8_t command);
219 static int jlink_get_status(void);
220 static int jlink_swd_run_queue(struct adiv5_dap *dap);
221 static void jlink_swd_queue_cmd(struct adiv5_dap *dap, uint8_t cmd, uint32_t *dst, uint32_t data);
222 static int jlink_swd_switch_seq(struct adiv5_dap *dap, enum swd_special_seq seq);
223
224 /* J-Link tap buffer functions */
225 static void jlink_tap_init(void);
226 static int jlink_tap_execute(void);
227 static void jlink_tap_ensure_space(int scans, int bits);
228 static void jlink_tap_append_step(int tms, int tdi);
229 static void jlink_tap_append_scan(int length, uint8_t *buffer,
230                 struct scan_command *command);
231
232 /* Jlink lowlevel functions */
233 struct jlink {
234         struct jtag_libusb_device_handle *usb_handle;
235 };
236
237 static struct jlink *jlink_usb_open(void);
238 static void jlink_usb_close(struct jlink *jlink);
239 static int jlink_usb_message(struct jlink *jlink, int out_length, int in_length);
240 static int jlink_usb_io(struct jlink *jlink, int out_length, int in_length);
241 static int jlink_usb_write(struct jlink *jlink, int out_length);
242 static int jlink_usb_read(struct jlink *jlink, int expected_size);
243
244 /* helper functions */
245 static int jlink_get_version_info(void);
246
247 #ifdef _DEBUG_USB_COMMS_
248 static void jlink_debug_buffer(uint8_t *buffer, int length);
249 #else
250 static inline void jlink_debug_buffer(uint8_t *buffer, int length)
251 {
252 }
253 #endif
254
255 static enum tap_state jlink_last_state = TAP_RESET;
256
257 static struct jlink *jlink_handle;
258
259 /* pid could be specified at runtime */
260 static uint16_t vids[] = { 0x1366, 0x1366, 0x1366, 0x1366, 0x1366, 0 };
261 static uint16_t pids[] = { 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0 };
262
263 static uint32_t jlink_caps;
264 static uint32_t jlink_hw_type;
265
266 static int queued_retval;
267 static bool swd_mode;
268
269 /* 256 byte non-volatile memory */
270 struct jlink_config {
271         uint8_t usb_address;
272         /* 0ffset 0x01 to 0x03 */
273         uint8_t reserved_1[3];
274         uint32_t kickstart_power_on_jtag_pin_19;
275         /* 0ffset 0x08 to 0x1f */
276         uint8_t reserved_2[24];
277         /* IP only for J-Link Pro */
278         uint8_t ip_address[4];
279         uint8_t subnet_mask[4];
280         /* 0ffset 0x28 to 0x2f */
281         uint8_t reserved_3[8];
282         uint8_t mac_address[6];
283         /* 0ffset 0x36 to 0xff */
284         uint8_t reserved_4[202];
285 } __attribute__ ((packed));
286 struct jlink_config jlink_cfg;
287
288 /***************************************************************************/
289 /* External interface implementation */
290
291 static void jlink_execute_runtest(struct jtag_command *cmd)
292 {
293         DEBUG_JTAG_IO("runtest %i cycles, end in %i",
294                         cmd->cmd.runtest->num_cycles,
295                         cmd->cmd.runtest->end_state);
296
297         jlink_end_state(cmd->cmd.runtest->end_state);
298
299         jlink_runtest(cmd->cmd.runtest->num_cycles);
300 }
301
302 static void jlink_execute_statemove(struct jtag_command *cmd)
303 {
304         DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
305
306         jlink_end_state(cmd->cmd.statemove->end_state);
307         jlink_state_move();
308 }
309
310 static void jlink_execute_pathmove(struct jtag_command *cmd)
311 {
312         DEBUG_JTAG_IO("pathmove: %i states, end in %i",
313                 cmd->cmd.pathmove->num_states,
314                 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
315
316         jlink_path_move(cmd->cmd.pathmove->num_states,
317                         cmd->cmd.pathmove->path);
318 }
319
320 static void jlink_execute_scan(struct jtag_command *cmd)
321 {
322         int scan_size;
323         enum scan_type type;
324         uint8_t *buffer;
325
326         DEBUG_JTAG_IO("scan end in %s", tap_state_name(cmd->cmd.scan->end_state));
327
328         jlink_end_state(cmd->cmd.scan->end_state);
329
330         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
331         DEBUG_JTAG_IO("scan input, length = %d", scan_size);
332
333         jlink_debug_buffer(buffer, (scan_size + 7) / 8);
334         type = jtag_scan_type(cmd->cmd.scan);
335         jlink_scan(cmd->cmd.scan->ir_scan,
336                         type, buffer, scan_size, cmd->cmd.scan);
337 }
338
339 static void jlink_execute_reset(struct jtag_command *cmd)
340 {
341         DEBUG_JTAG_IO("reset trst: %i srst %i",
342                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
343
344         jlink_tap_execute();
345         jlink_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
346         jlink_tap_execute();
347 }
348
349 static void jlink_execute_sleep(struct jtag_command *cmd)
350 {
351         DEBUG_JTAG_IO("sleep %" PRIi32 "", cmd->cmd.sleep->us);
352         jlink_tap_execute();
353         jtag_sleep(cmd->cmd.sleep->us);
354 }
355
356 static void jlink_execute_command(struct jtag_command *cmd)
357 {
358         switch (cmd->type) {
359                 case JTAG_RUNTEST:
360                         jlink_execute_runtest(cmd);
361                         break;
362                 case JTAG_TLR_RESET:
363                         jlink_execute_statemove(cmd);
364                         break;
365                 case JTAG_PATHMOVE:
366                         jlink_execute_pathmove(cmd);
367                         break;
368                 case JTAG_SCAN:
369                         jlink_execute_scan(cmd);
370                         break;
371                 case JTAG_RESET:
372                         jlink_execute_reset(cmd);
373                         break;
374                 case JTAG_SLEEP:
375                         jlink_execute_sleep(cmd);
376                         break;
377                 default:
378                         LOG_ERROR("BUG: unknown JTAG command type encountered");
379                         exit(-1);
380         }
381 }
382
383 static int jlink_execute_queue(void)
384 {
385         struct jtag_command *cmd = jtag_command_queue;
386
387         while (cmd != NULL) {
388                 jlink_execute_command(cmd);
389                 cmd = cmd->next;
390         }
391
392         return jlink_tap_execute();
393 }
394
395 /* Sets speed in kHz. */
396 static int jlink_speed(int speed)
397 {
398         int result;
399
400         if (speed > JLINK_MAX_SPEED) {
401                 LOG_INFO("reduce speed request: %dkHz to %dkHz maximum",
402                                 speed, JLINK_MAX_SPEED);
403                 speed = JLINK_MAX_SPEED;
404         }
405
406         /* check for RTCK setting */
407         if (speed == 0)
408                 speed = -1;
409
410         usb_out_buffer[0] = EMU_CMD_SET_SPEED;
411         usb_out_buffer[1] = (speed >> 0) & 0xff;
412         usb_out_buffer[2] = (speed >> 8) & 0xff;
413
414         result = jlink_usb_write(jlink_handle, 3);
415         if (result != 3) {
416                 LOG_ERROR("J-Link setting speed failed (%d)", result);
417                 return ERROR_JTAG_DEVICE_ERROR;
418         }
419
420         return ERROR_OK;
421 }
422
423 static int jlink_speed_div(int speed, int *khz)
424 {
425         *khz = speed;
426
427         return ERROR_OK;
428 }
429
430 static int jlink_khz(int khz, int *jtag_speed)
431 {
432         *jtag_speed = khz;
433
434         return ERROR_OK;
435 }
436
437 /*
438  * select transport interface
439  *
440  * @param       iface [0..31] currently: 0=JTAG, 1=SWD
441  * @returns     ERROR_OK or ERROR_ code
442  *
443  * @pre jlink_handle must be opened
444  * @pre function may be called only for devices, that have
445  *              EMU_CAP_SELECT_IF capability enabled
446  */
447 static int jlink_select_interface(int iface)
448 {
449         /* According to Segger's document RM08001-R7 Date: October 8, 2010,
450          * http://www.segger.com/admin/uploads/productDocs/RM08001_JLinkUSBProtocol.pdf
451          * section 5.5.3 EMU_CMD_SELECT_IF
452          * > SubCmd 1..31 to select interface (0..31)
453          *
454          * The table below states:
455          *  0 TIF_JTAG
456          *  1 TIF_SWD
457          *
458          * This obviosly means that to select TIF_JTAG one should write SubCmd = 1.
459          *
460          * In fact, JTAG interface operates when SubCmd=0
461          *
462          * It looks like a typo in documentation, because interfaces 0..31 could not
463          * be selected by 1..31 range command.
464          */
465         assert(iface >= 0 && iface < 32);
466         int result;
467
468         /* get available interfaces */
469         usb_out_buffer[0] = EMU_CMD_SELECT_IF;
470         usb_out_buffer[1] = 0xff;
471
472         result = jlink_usb_io(jlink_handle, 2, 4);
473         if (result != ERROR_OK) {
474                 LOG_ERROR("J-Link query interface failed (%d)", result);
475                 return ERROR_JTAG_DEVICE_ERROR;
476         }
477
478         uint32_t iface_mask = buf_get_u32(usb_in_buffer, 0, 32);
479
480         if (!(iface_mask & (1<<iface))) {
481                 LOG_ERROR("J-Link requesting to select unsupported interface (%" PRIx32 ")", iface_mask);
482                 return ERROR_JTAG_DEVICE_ERROR;
483         }
484
485         /* Select interface */
486         usb_out_buffer[0] = EMU_CMD_SELECT_IF;
487         usb_out_buffer[1] = iface;
488
489         result = jlink_usb_io(jlink_handle, 2, 4);
490         if (result != ERROR_OK) {
491                 LOG_ERROR("J-Link interface select failed (%d)", result);
492                 return ERROR_JTAG_DEVICE_ERROR;
493         }
494
495         return ERROR_OK;
496 }
497
498 static int jlink_init(void)
499 {
500         int i;
501
502         jlink_handle = jlink_usb_open();
503
504         if (jlink_handle == 0) {
505                 LOG_ERROR("Cannot find jlink Interface! Please check "
506                                 "connection and permissions.");
507                 return ERROR_JTAG_INIT_FAILED;
508         }
509
510         jlink_hw_jtag_version = 2;
511
512         if (jlink_get_version_info() == ERROR_OK) {
513                 /* attempt to get status */
514                 jlink_get_status();
515         }
516
517         /*
518          * Some versions of Segger's software do not select JTAG interface by default.
519          *
520          * Segger recommends to select interface necessarily as a part of init process,
521          * in case any previous session leaves improper interface selected.
522          */
523         int retval;
524         if (jlink_caps & (1<<EMU_CAP_SELECT_IF))
525                 retval = jlink_select_interface(swd_mode ? JLINK_TIF_SWD : JLINK_TIF_JTAG);
526         else
527                 retval = swd_mode ? ERROR_JTAG_DEVICE_ERROR : ERROR_OK;
528
529         if (retval != ERROR_OK) {
530                 LOG_ERROR("Selected transport mode is not supported.");
531                 return ERROR_JTAG_INIT_FAILED;
532         }
533
534         LOG_INFO("J-Link JTAG Interface ready");
535
536         jlink_reset(0, 0);
537         jtag_sleep(3000);
538         jlink_tap_init();
539
540         jlink_speed(jtag_get_speed_khz());
541
542         if (!swd_mode) {
543                 /* v5/6 jlink seems to have an issue if the first tap move
544                  * is not divisible by 8, so we send a TLR on first power up */
545                 for (i = 0; i < 8; i++)
546                         jlink_tap_append_step(1, 0);
547                 jlink_tap_execute();
548         }
549
550         if (swd_mode)
551                 jlink_swd_switch_seq(NULL, JTAG_TO_SWD);
552         else
553                 jlink_swd_switch_seq(NULL, SWD_TO_JTAG);
554         jlink_swd_run_queue(NULL);
555
556         return ERROR_OK;
557 }
558
559 static int jlink_quit(void)
560 {
561         jlink_usb_close(jlink_handle);
562         return ERROR_OK;
563 }
564
565 /***************************************************************************/
566 /* Queue command implementations */
567
568 static void jlink_end_state(tap_state_t state)
569 {
570         if (tap_is_state_stable(state))
571                 tap_set_end_state(state);
572         else {
573                 LOG_ERROR("BUG: %i is not a valid end state", state);
574                 exit(-1);
575         }
576 }
577
578 /* Goes to the end state. */
579 static void jlink_state_move(void)
580 {
581         int i;
582         int tms = 0;
583         uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
584         uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
585
586         for (i = 0; i < tms_scan_bits; i++) {
587                 tms = (tms_scan >> i) & 1;
588                 jlink_tap_append_step(tms, 0);
589         }
590
591         tap_set_state(tap_get_end_state());
592 }
593
594 static void jlink_path_move(int num_states, tap_state_t *path)
595 {
596         int i;
597
598         for (i = 0; i < num_states; i++) {
599                 if (path[i] == tap_state_transition(tap_get_state(), false))
600                         jlink_tap_append_step(0, 0);
601                 else if (path[i] == tap_state_transition(tap_get_state(), true))
602                         jlink_tap_append_step(1, 0);
603                 else {
604                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
605                                         tap_state_name(tap_get_state()), tap_state_name(path[i]));
606                         exit(-1);
607                 }
608
609                 tap_set_state(path[i]);
610         }
611
612         tap_set_end_state(tap_get_state());
613 }
614
615 static void jlink_runtest(int num_cycles)
616 {
617         int i;
618
619         tap_state_t saved_end_state = tap_get_end_state();
620
621         jlink_tap_ensure_space(1, num_cycles + 16);
622
623         /* only do a state_move when we're not already in IDLE */
624         if (tap_get_state() != TAP_IDLE) {
625                 jlink_end_state(TAP_IDLE);
626                 jlink_state_move();
627                 /* num_cycles--; */
628         }
629
630         /* execute num_cycles */
631         for (i = 0; i < num_cycles; i++)
632                 jlink_tap_append_step(0, 0);
633
634         /* finish in end_state */
635         jlink_end_state(saved_end_state);
636         if (tap_get_state() != tap_get_end_state())
637                 jlink_state_move();
638 }
639
640 static void jlink_scan(bool ir_scan, enum scan_type type, uint8_t *buffer,
641                 int scan_size, struct scan_command *command)
642 {
643         tap_state_t saved_end_state;
644
645         jlink_tap_ensure_space(1, scan_size + 16);
646
647         saved_end_state = tap_get_end_state();
648
649         /* Move to appropriate scan state */
650         jlink_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
651
652         /* Only move if we're not already there */
653         if (tap_get_state() != tap_get_end_state())
654                 jlink_state_move();
655
656         jlink_end_state(saved_end_state);
657
658         /* Scan */
659         jlink_tap_append_scan(scan_size, buffer, command);
660
661         /* We are in Exit1, go to Pause */
662         jlink_tap_append_step(0, 0);
663
664         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
665
666         if (tap_get_state() != tap_get_end_state())
667                 jlink_state_move();
668 }
669
670 static void jlink_reset(int trst, int srst)
671 {
672         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
673
674         /* Signals are active low */
675         if (srst == 0)
676                 jlink_simple_command(EMU_CMD_HW_RESET1);
677
678         if (srst == 1)
679                 jlink_simple_command(EMU_CMD_HW_RESET0);
680
681         if (trst == 1)
682                 jlink_simple_command(EMU_CMD_HW_TRST0);
683
684         if (trst == 0)
685                 jlink_simple_command(EMU_CMD_HW_TRST1);
686 }
687
688 static void jlink_simple_command(uint8_t command)
689 {
690         int result;
691
692         DEBUG_JTAG_IO("0x%02x", command);
693
694         usb_out_buffer[0] = command;
695         result = jlink_usb_write(jlink_handle, 1);
696
697         if (result != 1)
698                 LOG_ERROR("J-Link command 0x%02x failed (%d)", command, result);
699 }
700
701 static int jlink_get_status(void)
702 {
703         int result;
704
705         jlink_simple_command(EMU_CMD_GET_STATE);
706
707         result = jlink_usb_read(jlink_handle, 8);
708         if (result != 8) {
709                 LOG_ERROR("J-Link command EMU_CMD_GET_STATE failed (%d)", result);
710                 return ERROR_JTAG_DEVICE_ERROR;
711         }
712
713         int vref = usb_in_buffer[0] + (usb_in_buffer[1] << 8);
714         LOG_INFO("Vref = %d.%d TCK = %d TDI = %d TDO = %d TMS = %d SRST = %d TRST = %d", \
715                 vref / 1000, vref % 1000, \
716                 usb_in_buffer[2], usb_in_buffer[3], usb_in_buffer[4], \
717                 usb_in_buffer[5], usb_in_buffer[6], usb_in_buffer[7]);
718
719         if (vref < 1500)
720                 LOG_ERROR("Vref too low. Check Target Power");
721
722         return ERROR_OK;
723 }
724
725 #define jlink_dump_printf(context, expr ...) \
726         do { \
727                 if (context) \
728                         command_print(context, expr); \
729                         else \
730                         LOG_INFO(expr); \
731         } while (0);
732
733 static void jlink_caps_dump(struct command_context *ctx)
734 {
735         int i;
736
737         jlink_dump_printf(ctx, "J-Link Capabilities");
738
739         for (i = 1; i < 31; i++)
740                 if (jlink_caps & (1 << i))
741                         jlink_dump_printf(ctx, "%s", jlink_cap_str[i]);
742 }
743
744 static void jlink_config_usb_address_dump(struct command_context *ctx, struct jlink_config *cfg)
745 {
746         if (!cfg)
747                 return;
748
749         jlink_dump_printf(ctx, "USB-Address: 0x%x", cfg->usb_address);
750 }
751
752 static void jlink_config_kickstart_dump(struct command_context *ctx, struct jlink_config *cfg)
753 {
754         if (!cfg)
755                 return;
756
757         jlink_dump_printf(ctx, "Kickstart power on JTAG-pin 19: 0x%" PRIx32,
758                 cfg->kickstart_power_on_jtag_pin_19);
759 }
760
761 static void jlink_config_mac_address_dump(struct command_context *ctx, struct jlink_config *cfg)
762 {
763         if (!cfg)
764                 return;
765
766         jlink_dump_printf(ctx, "MAC Address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x",
767                 cfg->mac_address[5], cfg->mac_address[4],
768                 cfg->mac_address[3], cfg->mac_address[2],
769                 cfg->mac_address[1], cfg->mac_address[0]);
770 }
771
772 static void jlink_config_ip_dump(struct command_context *ctx, struct jlink_config *cfg)
773 {
774         if (!cfg)
775                 return;
776
777         jlink_dump_printf(ctx, "IP Address: %d.%d.%d.%d",
778                 cfg->ip_address[3], cfg->ip_address[2],
779                 cfg->ip_address[1], cfg->ip_address[0]);
780         jlink_dump_printf(ctx, "Subnet Mask: %d.%d.%d.%d",
781                 cfg->subnet_mask[3], cfg->subnet_mask[2],
782                 cfg->subnet_mask[1], cfg->subnet_mask[0]);
783 }
784
785 static void jlink_config_dump(struct command_context *ctx, struct jlink_config *cfg)
786 {
787         if (!cfg)
788                 return;
789
790         jlink_dump_printf(ctx, "J-Link configuration");
791         jlink_config_usb_address_dump(ctx, cfg);
792         jlink_config_kickstart_dump(ctx, cfg);
793
794         if (jlink_hw_type == JLINK_HW_TYPE_JLINK_PRO) {
795                 jlink_config_ip_dump(ctx, cfg);
796                 jlink_config_mac_address_dump(ctx, cfg);
797         }
798 }
799
800 static int jlink_get_config(struct jlink_config *cfg)
801 {
802         int result;
803         int size = sizeof(struct jlink_config);
804
805         usb_out_buffer[0] = EMU_CMD_READ_CONFIG;
806         result = jlink_usb_io(jlink_handle, 1, size);
807
808         if (result != ERROR_OK) {
809                 LOG_ERROR("jlink_usb_read failed (requested=%d, result=%d)", size, result);
810                 return ERROR_FAIL;
811         }
812
813         memcpy(cfg, usb_in_buffer, size);
814         return ERROR_OK;
815 }
816
817 static int jlink_set_config(struct jlink_config *cfg)
818 {
819         int result;
820         int size = sizeof(struct jlink_config);
821
822         jlink_simple_command(EMU_CMD_WRITE_CONFIG);
823
824         memcpy(usb_out_buffer, cfg, size);
825
826         result = jlink_usb_write(jlink_handle, size);
827         if (result != size) {
828                 LOG_ERROR("jlink_usb_write failed (requested=%d, result=%d)", 256, result);
829                 return ERROR_FAIL;
830         }
831
832         return ERROR_OK;
833 }
834
835 /*
836  * List of unsupported version string markers.
837  *
838  * The firmware versions does not correspond directly with
839  * "Software and documentation pack for Windows", it may be
840  * distinguished by the "compile" date in the information string.
841  *
842  * For example, version string is:
843  *   "J-Link ARM V8 compiled May  3 2012 18:36:22"
844  * Marker sould be:
845  *   "May  3 2012"
846  *
847  * The list must be terminated by NULL string.
848  */
849 static const char * const unsupported_versions[] = {
850         "Jan 31 2011",
851         "JAN 31 2011",
852         NULL                    /* End of list */
853 };
854
855 static void jlink_check_supported(const char *str)
856 {
857         const char * const *p = unsupported_versions;
858         while (*p) {
859                 if (NULL != strstr(str, *p)) {
860                         LOG_WARNING(
861                         "Unsupported J-Link firmware version.\n"
862                         "       Please check http://www.segger.com/j-link-older-versions.html for updates");
863                         return;
864                 }
865                 p++;
866         }
867 }
868
869 static int jlink_get_version_info(void)
870 {
871         int result;
872         int len;
873         uint32_t jlink_max_size;
874
875         /* query hardware version */
876         jlink_simple_command(EMU_CMD_VERSION);
877
878         result = jlink_usb_read(jlink_handle, 2);
879         if (2 != result) {
880                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)", result);
881                 return ERROR_JTAG_DEVICE_ERROR;
882         }
883
884         len = buf_get_u32(usb_in_buffer, 0, 16);
885         if (len > JLINK_IN_BUFFER_SIZE) {
886                 LOG_ERROR("J-Link command EMU_CMD_VERSION impossible return length 0x%0x", len);
887                 len = JLINK_IN_BUFFER_SIZE;
888         }
889
890         result = jlink_usb_read(jlink_handle, len);
891         if (result != len) {
892                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)", result);
893                 return ERROR_JTAG_DEVICE_ERROR;
894         }
895
896         usb_in_buffer[result] = 0;
897         LOG_INFO("%s", (char *)usb_in_buffer);
898         jlink_check_supported((char *)usb_in_buffer);
899
900         /* query hardware capabilities */
901         jlink_simple_command(EMU_CMD_GET_CAPS);
902
903         result = jlink_usb_read(jlink_handle, 4);
904         if (4 != result) {
905                 LOG_ERROR("J-Link command EMU_CMD_GET_CAPS failed (%d)", result);
906                 return ERROR_JTAG_DEVICE_ERROR;
907         }
908
909         jlink_caps = buf_get_u32(usb_in_buffer, 0, 32);
910         LOG_INFO("J-Link caps 0x%x", (unsigned)jlink_caps);
911
912         if (jlink_caps & (1 << EMU_CAP_GET_HW_VERSION)) {
913                 /* query hardware version */
914                 jlink_simple_command(EMU_CMD_GET_HW_VERSION);
915
916                 result = jlink_usb_read(jlink_handle, 4);
917                 if (4 != result) {
918                         LOG_ERROR("J-Link command EMU_CMD_GET_HW_VERSION failed (%d)", result);
919                         return ERROR_JTAG_DEVICE_ERROR;
920                 }
921
922                 uint32_t jlink_hw_version = buf_get_u32(usb_in_buffer, 0, 32);
923                 uint32_t major_revision = (jlink_hw_version / 10000) % 100;
924                 jlink_hw_type = (jlink_hw_version / 1000000) % 100;
925                 if (major_revision >= 5)
926                         jlink_hw_jtag_version = 3;
927
928                 LOG_INFO("J-Link hw version %i", (int)jlink_hw_version);
929
930                 if (jlink_hw_type >= JLINK_HW_TYPE_MAX)
931                         LOG_INFO("J-Link hw type uknown 0x%" PRIx32, jlink_hw_type);
932                 else
933                         LOG_INFO("J-Link hw type %s", jlink_hw_type_str[jlink_hw_type]);
934         }
935
936         if (jlink_caps & (1 << EMU_CAP_GET_MAX_BLOCK_SIZE)) {
937                 /* query hardware maximum memory block */
938                 jlink_simple_command(EMU_CMD_GET_MAX_MEM_BLOCK);
939
940                 result = jlink_usb_read(jlink_handle, 4);
941                 if (4 != result) {
942                         LOG_ERROR("J-Link command EMU_CMD_GET_MAX_MEM_BLOCK failed (%d)", result);
943                         return ERROR_JTAG_DEVICE_ERROR;
944                 }
945
946                 jlink_max_size = buf_get_u32(usb_in_buffer, 0, 32);
947                 LOG_INFO("J-Link max mem block %i", (int)jlink_max_size);
948         }
949
950         if (jlink_caps & (1 << EMU_CAP_READ_CONFIG)) {
951                 if (jlink_get_config(&jlink_cfg) != ERROR_OK)
952                         return ERROR_JTAG_DEVICE_ERROR;
953
954                 jlink_config_dump(NULL, &jlink_cfg);
955         }
956
957         return ERROR_OK;
958 }
959
960 COMMAND_HANDLER(jlink_pid_command)
961 {
962         if (CMD_ARGC != 1) {
963                 LOG_ERROR("Need exactly one argument to jlink_pid");
964                 return ERROR_FAIL;
965         }
966
967         pids[0] = strtoul(CMD_ARGV[0], NULL, 16);
968         pids[1] = 0;
969         vids[1] = 0;
970
971         return ERROR_OK;
972 }
973
974 COMMAND_HANDLER(jlink_handle_jlink_info_command)
975 {
976         if (jlink_get_version_info() == ERROR_OK) {
977                 /* attempt to get status */
978                 jlink_get_status();
979         }
980
981         return ERROR_OK;
982 }
983
984 COMMAND_HANDLER(jlink_handle_jlink_caps_command)
985 {
986         jlink_caps_dump(CMD_CTX);
987
988         return ERROR_OK;
989 }
990
991 COMMAND_HANDLER(jlink_handle_jlink_hw_jtag_command)
992 {
993         switch (CMD_ARGC) {
994                 case 0:
995                         command_print(CMD_CTX, "J-Link hw jtag  %i", jlink_hw_jtag_version);
996                         break;
997                 case 1: {
998                         int request_version = atoi(CMD_ARGV[0]);
999                         switch (request_version) {
1000                                 case 2:
1001                                 case 3:
1002                                         jlink_hw_jtag_version = request_version;
1003                                         break;
1004                                 default:
1005                                         return ERROR_COMMAND_SYNTAX_ERROR;
1006                         }
1007                         break;
1008                 }
1009                 default:
1010                         return ERROR_COMMAND_SYNTAX_ERROR;
1011         }
1012
1013         return ERROR_OK;
1014 }
1015
1016 COMMAND_HANDLER(jlink_handle_jlink_kickstart_command)
1017 {
1018         uint32_t kickstart;
1019
1020         if (CMD_ARGC < 1) {
1021                 jlink_config_kickstart_dump(CMD_CTX, &jlink_cfg);
1022                 return ERROR_OK;
1023         }
1024
1025         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], kickstart);
1026
1027         jlink_cfg.kickstart_power_on_jtag_pin_19 = kickstart;
1028         return ERROR_OK;
1029 }
1030
1031 COMMAND_HANDLER(jlink_handle_jlink_mac_address_command)
1032 {
1033         uint8_t addr[6];
1034         int i;
1035         char *e;
1036         const char *str;
1037
1038         if (CMD_ARGC < 1) {
1039                 jlink_config_mac_address_dump(CMD_CTX, &jlink_cfg);
1040                 return ERROR_OK;
1041         }
1042
1043         str = CMD_ARGV[0];
1044
1045         if ((strlen(str) != 17) || (str[2] != ':' || str[5] != ':' || str[8] != ':' ||
1046                 str[11] != ':' || str[14] != ':')) {
1047                 command_print(CMD_CTX, "ethaddr miss format ff:ff:ff:ff:ff:ff");
1048                 return ERROR_COMMAND_SYNTAX_ERROR;
1049         }
1050
1051         for (i = 5; i >= 0; i--) {
1052                 addr[i] = strtoul(str, &e, 16);
1053                 str = e + 1;
1054         }
1055
1056         if (!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5])) {
1057                 command_print(CMD_CTX, "invalid it's zero mac_address");
1058                 return ERROR_COMMAND_SYNTAX_ERROR;
1059         }
1060
1061         if (!(0x01 & addr[0])) {
1062                 command_print(CMD_CTX, "invalid it's a multicat mac_address");
1063                 return ERROR_COMMAND_SYNTAX_ERROR;
1064         }
1065
1066         memcpy(jlink_cfg.mac_address, addr, sizeof(addr));
1067
1068         return ERROR_OK;
1069 }
1070
1071 static int string_to_ip(const char *s, uint8_t *ip, int *pos)
1072 {
1073         uint8_t lip[4];
1074         char *e;
1075         const char *s_save = s;
1076         int i;
1077
1078         if (!s)
1079                 return -EINVAL;
1080
1081         for (i = 0; i < 4; i++) {
1082                 lip[i] = strtoul(s, &e, 10);
1083
1084                 if (*e != '.' && i != 3)
1085                         return -EINVAL;
1086
1087                 s = e + 1;
1088         }
1089
1090         *pos = e - s_save;
1091
1092         memcpy(ip, lip, sizeof(lip));
1093         return ERROR_OK;
1094 }
1095
1096 static void cpy_ip(uint8_t *dst, uint8_t *src)
1097 {
1098         int i, j;
1099
1100         for (i = 0, j = 3; i < 4; i++, j--)
1101                 dst[i] = src[j];
1102 }
1103
1104 COMMAND_HANDLER(jlink_handle_jlink_ip_command)
1105 {
1106         uint32_t ip_address;
1107         uint32_t subnet_mask = 0;
1108         int i, len;
1109         int ret;
1110         uint8_t subnet_bits = 24;
1111
1112         if (CMD_ARGC < 1) {
1113                 jlink_config_ip_dump(CMD_CTX, &jlink_cfg);
1114                 return ERROR_OK;
1115         }
1116
1117         ret = string_to_ip(CMD_ARGV[0], (uint8_t *)&ip_address, &i);
1118         if (ret != ERROR_OK)
1119                 return ret;
1120
1121         len = strlen(CMD_ARGV[0]);
1122
1123         /* check for this format A.B.C.D/E */
1124
1125         if (i < len) {
1126                 if (CMD_ARGV[0][i] != '/')
1127                         return ERROR_COMMAND_SYNTAX_ERROR;
1128
1129                 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[0] + i + 1, subnet_bits);
1130         } else {
1131                 if (CMD_ARGC > 1) {
1132                         ret = string_to_ip(CMD_ARGV[1], (uint8_t *)&subnet_mask, &i);
1133                         if (ret != ERROR_OK)
1134                                 return ret;
1135                 }
1136         }
1137
1138         if (!subnet_mask)
1139                 subnet_mask = (uint32_t)(subnet_bits < 32 ?
1140                                 ((1ULL << subnet_bits) - 1) : 0xffffffff);
1141
1142         cpy_ip(jlink_cfg.ip_address, (uint8_t *)&ip_address);
1143         cpy_ip(jlink_cfg.subnet_mask, (uint8_t *)&subnet_mask);
1144
1145         return ERROR_OK;
1146 }
1147
1148 COMMAND_HANDLER(jlink_handle_jlink_reset_command)
1149 {
1150         memset(&jlink_cfg, 0xff, sizeof(jlink_cfg));
1151         return ERROR_OK;
1152 }
1153
1154 COMMAND_HANDLER(jlink_handle_jlink_save_command)
1155 {
1156         if (!(jlink_caps & (1 << EMU_CAP_WRITE_CONFIG))) {
1157                 command_print(CMD_CTX, "J-Link write emulator configuration not supported");
1158                 return ERROR_OK;
1159         }
1160
1161         command_print(CMD_CTX, "The J-Link need to be unpluged and repluged ta have the config effective");
1162         return jlink_set_config(&jlink_cfg);
1163 }
1164
1165 COMMAND_HANDLER(jlink_handle_jlink_usb_address_command)
1166 {
1167         uint32_t address;
1168
1169         if (CMD_ARGC < 1) {
1170                 jlink_config_usb_address_dump(CMD_CTX, &jlink_cfg);
1171                 return ERROR_OK;
1172         }
1173
1174         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
1175
1176         if (address > 0x3 && address != 0xff) {
1177                 command_print(CMD_CTX, "USB Address must be between 0x00 and 0x03 or 0xff");
1178                 return ERROR_COMMAND_SYNTAX_ERROR;
1179         }
1180
1181         jlink_cfg.usb_address = address;
1182         return ERROR_OK;
1183 }
1184
1185 COMMAND_HANDLER(jlink_handle_jlink_config_command)
1186 {
1187         struct jlink_config cfg;
1188         int ret = ERROR_OK;
1189
1190         if (CMD_ARGC == 0) {
1191                 if (!(jlink_caps & (1 << EMU_CAP_READ_CONFIG))) {
1192                         command_print(CMD_CTX, "J-Link read emulator configuration not supported");
1193                         goto exit;
1194                 }
1195
1196                 ret = jlink_get_config(&cfg);
1197
1198                 if (ret != ERROR_OK)
1199                         command_print(CMD_CTX, "J-Link read emulator configuration failled");
1200                 else
1201                         jlink_config_dump(CMD_CTX, &jlink_cfg);
1202         }
1203
1204 exit:
1205         return ret;
1206 }
1207
1208 static const struct command_registration jlink_config_subcommand_handlers[] = {
1209         {
1210                 .name = "kickstart",
1211                 .handler = &jlink_handle_jlink_kickstart_command,
1212                 .mode = COMMAND_EXEC,
1213                 .help = "set Kickstart power on JTAG-pin 19.",
1214                 .usage = "[val]",
1215         },
1216         {
1217                 .name = "mac_address",
1218                 .handler = &jlink_handle_jlink_mac_address_command,
1219                 .mode = COMMAND_EXEC,
1220                 .help = "set the MAC Address",
1221                 .usage = "[ff:ff:ff:ff:ff:ff]",
1222         },
1223         {
1224                 .name = "ip",
1225                 .handler = &jlink_handle_jlink_ip_command,
1226                 .mode = COMMAND_EXEC,
1227                 .help = "set the ip address of the J-Link Pro, "
1228                         "where A.B.C.D is the ip, "
1229                         "E the bit of the subnet mask, "
1230                         "F.G.H.I the subnet mask",
1231                 .usage = "[A.B.C.D[/E] [F.G.H.I]]",
1232         },
1233         {
1234                 .name = "reset",
1235                 .handler = &jlink_handle_jlink_reset_command,
1236                 .mode = COMMAND_EXEC,
1237                 .help = "reset the current config",
1238         },
1239         {
1240                 .name = "save",
1241                 .handler = &jlink_handle_jlink_save_command,
1242                 .mode = COMMAND_EXEC,
1243                 .help = "save the current config",
1244         },
1245         {
1246                 .name = "usb_address",
1247                 .handler = &jlink_handle_jlink_usb_address_command,
1248                 .mode = COMMAND_EXEC,
1249                 .help = "set the USB-Address, "
1250                         "This will change the product id",
1251                 .usage = "[0x00 to 0x03 or 0xff]",
1252         },
1253         COMMAND_REGISTRATION_DONE
1254 };
1255
1256 static const struct command_registration jlink_subcommand_handlers[] = {
1257         {
1258                 .name = "caps",
1259                 .handler = &jlink_handle_jlink_caps_command,
1260                 .mode = COMMAND_EXEC,
1261                 .help = "show jlink capabilities",
1262         },
1263         {
1264                 .name = "info",
1265                 .handler = &jlink_handle_jlink_info_command,
1266                 .mode = COMMAND_EXEC,
1267                 .help = "show jlink info",
1268         },
1269         {
1270                 .name = "hw_jtag",
1271                 .handler = &jlink_handle_jlink_hw_jtag_command,
1272                 .mode = COMMAND_EXEC,
1273                 .help = "access J-Link HW JTAG command version",
1274                 .usage = "[2|3]",
1275         },
1276         {
1277                 .name = "config",
1278                 .handler = &jlink_handle_jlink_config_command,
1279                 .mode = COMMAND_EXEC,
1280                 .help = "access J-Link configuration, "
1281                         "if no argument this will dump the config",
1282                 .chain = jlink_config_subcommand_handlers,
1283         },
1284         {
1285                 .name = "pid",
1286                 .handler = &jlink_pid_command,
1287                 .mode = COMMAND_CONFIG,
1288                 .help = "set the pid of the interface we want to use",
1289         },
1290         COMMAND_REGISTRATION_DONE
1291 };
1292
1293 static const struct command_registration jlink_command_handlers[] = {
1294         {
1295                 .name = "jlink",
1296                 .mode = COMMAND_ANY,
1297                 .help = "perform jlink management",
1298                 .chain = jlink_subcommand_handlers,
1299         },
1300         COMMAND_REGISTRATION_DONE
1301 };
1302
1303 static int jlink_swd_init(void)
1304 {
1305         LOG_INFO("JLink SWD mode enabled");
1306         swd_mode = true;
1307
1308         return ERROR_OK;
1309 }
1310
1311 static void jlink_swd_write_reg(struct adiv5_dap *dap, uint8_t cmd, uint32_t value)
1312 {
1313         assert(!(cmd & SWD_CMD_RnW));
1314         jlink_swd_queue_cmd(dap, cmd, NULL, value);
1315 }
1316
1317 static void jlink_swd_read_reg(struct adiv5_dap *dap, uint8_t cmd, uint32_t *value)
1318 {
1319         assert(cmd & SWD_CMD_RnW);
1320         jlink_swd_queue_cmd(dap, cmd, value, 0);
1321 }
1322
1323 static int_least32_t jlink_swd_frequency(struct adiv5_dap *dap, int_least32_t hz)
1324 {
1325         if (hz > 0)
1326                 jlink_speed(hz / 1000);
1327
1328         return hz;
1329 }
1330
1331 static const struct swd_driver jlink_swd = {
1332         .init = jlink_swd_init,
1333         .frequency = jlink_swd_frequency,
1334         .switch_seq = jlink_swd_switch_seq,
1335         .read_reg = jlink_swd_read_reg,
1336         .write_reg = jlink_swd_write_reg,
1337         .run = jlink_swd_run_queue,
1338 };
1339
1340 static const char * const jlink_transports[] = { "jtag", "swd", NULL };
1341
1342 struct jtag_interface jlink_interface = {
1343         .name = "jlink",
1344         .commands = jlink_command_handlers,
1345         .transports = jlink_transports,
1346         .swd = &jlink_swd,
1347
1348         .execute_queue = jlink_execute_queue,
1349         .speed = jlink_speed,
1350         .speed_div = jlink_speed_div,
1351         .khz = jlink_khz,
1352         .init = jlink_init,
1353         .quit = jlink_quit,
1354 };
1355
1356 /***************************************************************************/
1357 /* J-Link tap functions */
1358
1359
1360 static unsigned tap_length;
1361 /* In SWD mode use tms buffer for direction control */
1362 static uint8_t tms_buffer[JLINK_TAP_BUFFER_SIZE];
1363 static uint8_t tdi_buffer[JLINK_TAP_BUFFER_SIZE];
1364 static uint8_t tdo_buffer[JLINK_TAP_BUFFER_SIZE];
1365
1366 struct pending_scan_result {
1367         int first;      /* First bit position in tdo_buffer to read */
1368         int length; /* Number of bits to read */
1369         struct scan_command *command; /* Corresponding scan command */
1370         void *buffer;
1371 };
1372
1373 #define MAX_PENDING_SCAN_RESULTS 256
1374
1375 static int pending_scan_results_length;
1376 static struct pending_scan_result pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
1377
1378 static void jlink_tap_init(void)
1379 {
1380         tap_length = 0;
1381         pending_scan_results_length = 0;
1382 }
1383
1384 static void jlink_tap_ensure_space(int scans, int bits)
1385 {
1386         int available_scans = MAX_PENDING_SCAN_RESULTS - pending_scan_results_length;
1387         int available_bits = JLINK_TAP_BUFFER_SIZE * 8 - tap_length - 32;
1388
1389         if (scans > available_scans || bits > available_bits)
1390                 jlink_tap_execute();
1391 }
1392
1393 static void jlink_tap_append_step(int tms, int tdi)
1394 {
1395         int index_var = tap_length / 8;
1396
1397         assert(index_var < JLINK_TAP_BUFFER_SIZE);
1398
1399         int bit_index = tap_length % 8;
1400         uint8_t bit = 1 << bit_index;
1401
1402         /* we do not pad TMS, so be sure to initialize all bits */
1403         if (0 == bit_index)
1404                 tms_buffer[index_var] = tdi_buffer[index_var] = 0;
1405
1406         if (tms)
1407                 tms_buffer[index_var] |= bit;
1408         else
1409                 tms_buffer[index_var] &= ~bit;
1410
1411         if (tdi)
1412                 tdi_buffer[index_var] |= bit;
1413         else
1414                 tdi_buffer[index_var] &= ~bit;
1415
1416         tap_length++;
1417 }
1418
1419 static void jlink_tap_append_scan(int length, uint8_t *buffer,
1420                 struct scan_command *command)
1421 {
1422         struct pending_scan_result *pending_scan_result =
1423                 &pending_scan_results_buffer[pending_scan_results_length];
1424         int i;
1425
1426         pending_scan_result->first = tap_length;
1427         pending_scan_result->length = length;
1428         pending_scan_result->command = command;
1429         pending_scan_result->buffer = buffer;
1430
1431         for (i = 0; i < length; i++) {
1432                 int tms = (i < (length - 1)) ? 0 : 1;
1433                 int tdi = (buffer[i / 8] & (1 << (i % 8))) != 0;
1434                 jlink_tap_append_step(tms, tdi);
1435         }
1436         pending_scan_results_length++;
1437 }
1438
1439 /* Pad and send a tap sequence to the device, and receive the answer.
1440  * For the purpose of padding we assume that we are in idle or pause state. */
1441 static int jlink_tap_execute(void)
1442 {
1443         int byte_length;
1444         int i;
1445         int result;
1446
1447         if (!tap_length)
1448                 return ERROR_OK;
1449
1450         /* JLink returns an extra NULL in packet when size of incoming
1451          * message is a multiple of 64, creates problems with USB comms.
1452          * WARNING: This will interfere with tap state counting. */
1453         while ((DIV_ROUND_UP(tap_length, 8) % 64) == 0)
1454                 jlink_tap_append_step((tap_get_state() == TAP_RESET) ? 1 : 0, 0);
1455
1456         /* number of full bytes (plus one if some would be left over) */
1457         byte_length = DIV_ROUND_UP(tap_length, 8);
1458
1459         bool use_jtag3 = jlink_hw_jtag_version >= 3;
1460         usb_out_buffer[0] = use_jtag3 ? EMU_CMD_HW_JTAG3 : EMU_CMD_HW_JTAG2;
1461         usb_out_buffer[1] = 0;
1462         usb_out_buffer[2] = (tap_length >> 0) & 0xff;
1463         usb_out_buffer[3] = (tap_length >> 8) & 0xff;
1464         memcpy(usb_out_buffer + 4, tms_buffer, byte_length);
1465         memcpy(usb_out_buffer + 4 + byte_length, tdi_buffer, byte_length);
1466
1467         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
1468                         tap_length, jlink_last_state);
1469
1470         result = jlink_usb_message(jlink_handle, 4 + 2 * byte_length,
1471                         use_jtag3 ? byte_length + 1 : byte_length);
1472         if (result != ERROR_OK) {
1473                 LOG_ERROR("jlink_tap_execute failed USB io (%d)", result);
1474                 jlink_tap_init();
1475                 return ERROR_JTAG_QUEUE_FAILED;
1476         }
1477
1478         result = use_jtag3 ? usb_in_buffer[byte_length] : 0;
1479         if (result != 0) {
1480                 LOG_ERROR("jlink_tap_execute failed, result %d (%s)", result,
1481                           result == 1 ? "adaptive clocking timeout" : "unknown");
1482                 jlink_tap_init();
1483                 return ERROR_JTAG_QUEUE_FAILED;
1484         }
1485
1486         memcpy(tdo_buffer, usb_in_buffer, byte_length);
1487
1488         for (i = 0; i < pending_scan_results_length; i++) {
1489                 struct pending_scan_result *pending_scan_result = &pending_scan_results_buffer[i];
1490                 uint8_t *buffer = pending_scan_result->buffer;
1491                 int length = pending_scan_result->length;
1492                 int first = pending_scan_result->first;
1493                 struct scan_command *command = pending_scan_result->command;
1494
1495                 /* Copy to buffer */
1496                 buf_set_buf(tdo_buffer, first, buffer, 0, length);
1497
1498                 DEBUG_JTAG_IO("pending scan result, length = %d", length);
1499
1500                 jlink_debug_buffer(buffer, DIV_ROUND_UP(length, 8));
1501
1502                 if (jtag_read_buffer(buffer, command) != ERROR_OK) {
1503                         jlink_tap_init();
1504                         return ERROR_JTAG_QUEUE_FAILED;
1505                 }
1506
1507                 if (pending_scan_result->buffer != NULL)
1508                         free(pending_scan_result->buffer);
1509         }
1510
1511         jlink_tap_init();
1512         return ERROR_OK;
1513 }
1514
1515 static void fill_buffer(uint8_t *buf, uint32_t val, uint32_t len)
1516 {
1517         unsigned int tap_pos = tap_length;
1518
1519         while (len > 32) {
1520                 buf_set_u32(buf, tap_pos, 32, val);
1521                 len -= 32;
1522                 tap_pos += 32;
1523         }
1524         if (len)
1525                 buf_set_u32(buf, tap_pos, len, val);
1526 }
1527
1528 static void jlink_queue_data_out(const uint8_t *data, uint32_t len)
1529 {
1530         const uint32_t dir_out = 0xffffffff;
1531
1532         if (data)
1533                 bit_copy(tdi_buffer, tap_length, data, 0, len);
1534         else
1535                 fill_buffer(tdi_buffer, 0, len);
1536         fill_buffer(tms_buffer, dir_out, len);
1537         tap_length += len;
1538 }
1539
1540 static void jlink_queue_data_in(uint32_t len)
1541 {
1542         const uint32_t dir_in = 0;
1543
1544         fill_buffer(tms_buffer, dir_in, len);
1545         tap_length += len;
1546 }
1547
1548 static int jlink_swd_switch_seq(struct adiv5_dap *dap, enum swd_special_seq seq)
1549 {
1550         const uint8_t *s;
1551         unsigned int s_len;
1552
1553         switch (seq) {
1554         case LINE_RESET:
1555                 LOG_DEBUG("SWD line reset");
1556                 s = swd_seq_line_reset;
1557                 s_len = swd_seq_line_reset_len;
1558                 break;
1559         case JTAG_TO_SWD:
1560                 LOG_DEBUG("JTAG-to-SWD");
1561                 s = swd_seq_jtag_to_swd;
1562                 s_len = swd_seq_jtag_to_swd_len;
1563                 break;
1564         case SWD_TO_JTAG:
1565                 LOG_DEBUG("SWD-to-JTAG");
1566                 s = swd_seq_swd_to_jtag;
1567                 s_len = swd_seq_swd_to_jtag_len;
1568                 break;
1569         default:
1570                 LOG_ERROR("Sequence %d not supported", seq);
1571                 return ERROR_FAIL;
1572         }
1573
1574         jlink_queue_data_out(s, s_len);
1575
1576         return ERROR_OK;
1577 }
1578
1579 static int jlink_swd_run_queue(struct adiv5_dap *dap)
1580 {
1581         LOG_DEBUG("Executing %d queued transactions", pending_scan_results_length);
1582         int retval;
1583
1584         if (queued_retval != ERROR_OK) {
1585                 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
1586                 goto skip;
1587         }
1588
1589         /* A transaction must be followed by another transaction or at least 8 idle cycles to
1590          * ensure that data is clocked through the AP. */
1591         jlink_queue_data_out(NULL, 8);
1592
1593         size_t byte_length = DIV_ROUND_UP(tap_length, 8);
1594
1595         /* There's a comment in jlink_tap_execute saying JLink returns
1596          * an extra NULL in packet when size of incoming message is a
1597          * multiple of 64. Someone should verify if that's still the
1598          * case with the current jlink firmware */
1599
1600         usb_out_buffer[0] = EMU_CMD_HW_JTAG3;
1601         usb_out_buffer[1] = 0;
1602         usb_out_buffer[2] = (tap_length >> 0) & 0xff;
1603         usb_out_buffer[3] = (tap_length >> 8) & 0xff;
1604         memcpy(usb_out_buffer + 4, tms_buffer, byte_length);
1605         memcpy(usb_out_buffer + 4 + byte_length, tdi_buffer, byte_length);
1606
1607         retval = jlink_usb_message(jlink_handle, 4 + 2 * byte_length,
1608                                    byte_length + 1);
1609         if (retval != ERROR_OK) {
1610                 LOG_ERROR("jlink_swd_run_queue failed USB io (%d)", retval);
1611                 goto skip;
1612         }
1613
1614         retval = usb_in_buffer[byte_length];
1615         if (retval) {
1616                 LOG_ERROR("jlink_swd_run_queue failed, result %d", retval);
1617                 goto skip;
1618         }
1619
1620         for (int i = 0; i < pending_scan_results_length; i++) {
1621                 int ack = buf_get_u32(usb_in_buffer, pending_scan_results_buffer[i].first, 3);
1622
1623                 if (ack != SWD_ACK_OK) {
1624                         LOG_ERROR("SWD ack not OK: %d %s", ack,
1625                                   ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
1626                         queued_retval = ack;
1627                         goto skip;
1628                 } else if (pending_scan_results_buffer[i].length) {
1629                         uint32_t data = buf_get_u32(usb_in_buffer, 3 + pending_scan_results_buffer[i].first, 32);
1630                         int parity = buf_get_u32(usb_in_buffer, 3 + 32 + pending_scan_results_buffer[i].first, 1);
1631
1632                         if (parity != parity_u32(data)) {
1633                                 LOG_ERROR("SWD Read data parity mismatch");
1634                                 queued_retval = ERROR_FAIL;
1635                                 goto skip;
1636                         }
1637
1638                         if (pending_scan_results_buffer[i].buffer)
1639                                 *(uint32_t *)pending_scan_results_buffer[i].buffer = data;
1640                 }
1641         }
1642
1643 skip:
1644         jlink_tap_init();
1645         retval = queued_retval;
1646         queued_retval = ERROR_OK;
1647
1648         return retval;
1649 }
1650
1651 static void jlink_swd_queue_cmd(struct adiv5_dap *dap, uint8_t cmd, uint32_t *dst, uint32_t data)
1652 {
1653         uint8_t data_parity_trn[DIV_ROUND_UP(32 + 1, 8)];
1654         if (tap_length + 46 + 8 + dap->memaccess_tck >= sizeof(tdi_buffer) * 8 ||
1655             pending_scan_results_length == MAX_PENDING_SCAN_RESULTS) {
1656                 /* Not enough room in the queue. Run the queue. */
1657                 queued_retval = jlink_swd_run_queue(dap);
1658         }
1659
1660         if (queued_retval != ERROR_OK)
1661                 return;
1662
1663         cmd |= SWD_CMD_START | SWD_CMD_PARK;
1664
1665         jlink_queue_data_out(&cmd, 8);
1666
1667         pending_scan_results_buffer[pending_scan_results_length].first = tap_length;
1668
1669         if (cmd & SWD_CMD_RnW) {
1670                 /* Queue a read transaction */
1671                 pending_scan_results_buffer[pending_scan_results_length].length = 32;
1672                 pending_scan_results_buffer[pending_scan_results_length].buffer = dst;
1673
1674                 jlink_queue_data_in(1 + 3 + 32 + 1 + 1);
1675         } else {
1676                 /* Queue a write transaction */
1677                 pending_scan_results_buffer[pending_scan_results_length].length = 0;
1678                 jlink_queue_data_in(1 + 3 + 1);
1679
1680                 buf_set_u32(data_parity_trn, 0, 32, data);
1681                 buf_set_u32(data_parity_trn, 32, 1, parity_u32(data));
1682
1683                 jlink_queue_data_out(data_parity_trn, 32 + 1);
1684         }
1685
1686         pending_scan_results_length++;
1687
1688         /* Insert idle cycles after AP accesses to avoid WAIT */
1689         if (cmd & SWD_CMD_APnDP)
1690                 jlink_queue_data_out(NULL, dap->memaccess_tck);
1691 }
1692
1693 /*****************************************************************************/
1694 /* JLink USB low-level functions */
1695
1696 static struct jlink *jlink_usb_open()
1697 {
1698         struct jtag_libusb_device_handle *devh;
1699         if (jtag_libusb_open(vids, pids, &devh) != ERROR_OK)
1700                 return NULL;
1701
1702         /* BE ***VERY CAREFUL*** ABOUT MAKING CHANGES IN THIS
1703          * AREA!!!!!!!!!!!  The behavior of libusb is not completely
1704          * consistent across Windows, Linux, and Mac OS X platforms.
1705          * The actions taken in the following compiler conditionals may
1706          * not agree with published documentation for libusb, but were
1707          * found to be necessary through trials and tribulations.  Even
1708          * little tweaks can break one or more platforms, so if you do
1709          * make changes test them carefully on all platforms before
1710          * committing them!
1711          */
1712
1713 #if IS_WIN32 == 0
1714
1715         jtag_libusb_reset_device(devh);
1716
1717 #if IS_DARWIN == 0
1718
1719         int timeout = 5;
1720         /* reopen jlink after usb_reset
1721          * on win32 this may take a second or two to re-enumerate */
1722         int retval;
1723         while ((retval = jtag_libusb_open(vids, pids, &devh)) != ERROR_OK) {
1724                 usleep(1000);
1725                 timeout--;
1726                 if (!timeout)
1727                         break;
1728         }
1729         if (ERROR_OK != retval)
1730                 return NULL;
1731 #endif
1732
1733 #endif
1734
1735         /* usb_set_configuration required under win32 */
1736         struct jtag_libusb_device *udev = jtag_libusb_get_device(devh);
1737         jtag_libusb_set_configuration(devh, 0);
1738         jtag_libusb_claim_interface(devh, 0);
1739
1740 #if 0
1741         /*
1742          * This makes problems under Mac OS X. And is not needed
1743          * under Windows. Hopefully this will not break a linux build
1744          */
1745         usb_set_altinterface(result->usb_handle, 0);
1746 #endif
1747
1748         /* Use the OB endpoints if the JLink we matched is a Jlink-OB adapter */
1749         uint16_t matched_pid;
1750         if (jtag_libusb_get_pid(udev, &matched_pid) == ERROR_OK) {
1751                 if (matched_pid == JLINK_OB_PID) {
1752                         jlink_read_ep = JLINK_OB_WRITE_ENDPOINT;
1753                         jlink_write_ep = JLINK_OB_READ_ENDPOINT;
1754                 }
1755         }
1756
1757         jtag_libusb_get_endpoints(udev, &jlink_read_ep, &jlink_write_ep);
1758
1759         struct jlink *result = malloc(sizeof(struct jlink));
1760         result->usb_handle = devh;
1761         return result;
1762 }
1763
1764 static void jlink_usb_close(struct jlink *jlink)
1765 {
1766         jtag_libusb_close(jlink->usb_handle);
1767         free(jlink);
1768 }
1769
1770 /* Send a message and receive the reply. */
1771 static int jlink_usb_message(struct jlink *jlink, int out_length, int in_length)
1772 {
1773         int result;
1774
1775         result = jlink_usb_write(jlink, out_length);
1776         if (result != out_length) {
1777                 LOG_ERROR("usb_bulk_write failed (requested=%d, result=%d)",
1778                                 out_length, result);
1779                 return ERROR_JTAG_DEVICE_ERROR;
1780         }
1781
1782         result = jlink_usb_read(jlink, in_length);
1783         if (result != in_length) {
1784                 LOG_ERROR("usb_bulk_read failed (requested=%d, result=%d)",
1785                                 in_length, result);
1786                 return ERROR_JTAG_DEVICE_ERROR;
1787         }
1788         return ERROR_OK;
1789 }
1790
1791 /* calls the given usb_bulk_* function, allowing for the data to
1792  * trickle in with some timeouts  */
1793 static int usb_bulk_with_retries(
1794                 int (*f)(jtag_libusb_device_handle *, int, char *, int, int),
1795                 jtag_libusb_device_handle *dev, int ep,
1796                 char *bytes, int size, int timeout)
1797 {
1798         int tries = 3, count = 0;
1799
1800         while (tries && (count < size)) {
1801                 int result = f(dev, ep, bytes + count, size - count, timeout);
1802                 if (result > 0)
1803                         count += result;
1804                 else if ((-ETIMEDOUT != result) || !--tries)
1805                         return result;
1806         }
1807         return count;
1808 }
1809
1810 static int wrap_usb_bulk_write(jtag_libusb_device_handle *dev, int ep,
1811                 char *buff, int size, int timeout)
1812 {
1813         /* usb_bulk_write() takes const char *buff */
1814         return jtag_libusb_bulk_write(dev, ep, buff, size, timeout);
1815 }
1816
1817 static inline int usb_bulk_write_ex(jtag_libusb_device_handle *dev, int ep,
1818                 char *bytes, int size, int timeout)
1819 {
1820         return usb_bulk_with_retries(&wrap_usb_bulk_write,
1821                         dev, ep, bytes, size, timeout);
1822 }
1823
1824 static inline int usb_bulk_read_ex(jtag_libusb_device_handle *dev, int ep,
1825                 char *bytes, int size, int timeout)
1826 {
1827         return usb_bulk_with_retries(&jtag_libusb_bulk_read,
1828                         dev, ep, bytes, size, timeout);
1829 }
1830
1831 /* Write data from out_buffer to USB. */
1832 static int jlink_usb_write(struct jlink *jlink, int out_length)
1833 {
1834         int result;
1835
1836         if (out_length > JLINK_OUT_BUFFER_SIZE) {
1837                 LOG_ERROR("jlink_write illegal out_length=%d (max=%d)",
1838                                 out_length, JLINK_OUT_BUFFER_SIZE);
1839                 return -1;
1840         }
1841
1842         result = usb_bulk_write_ex(jlink->usb_handle, jlink_write_ep,
1843                 (char *)usb_out_buffer, out_length, JLINK_USB_TIMEOUT);
1844
1845         DEBUG_JTAG_IO("jlink_usb_write, out_length = %d, result = %d",
1846                         out_length, result);
1847
1848         jlink_debug_buffer(usb_out_buffer, out_length);
1849         return result;
1850 }
1851
1852 /* Read data from USB into in_buffer. */
1853 static int jlink_usb_read(struct jlink *jlink, int expected_size)
1854 {
1855         int result = usb_bulk_read_ex(jlink->usb_handle, jlink_read_ep,
1856                 (char *)usb_in_buffer, expected_size, JLINK_USB_TIMEOUT);
1857
1858         DEBUG_JTAG_IO("jlink_usb_read, result = %d", result);
1859
1860         jlink_debug_buffer(usb_in_buffer, result);
1861         return result;
1862 }
1863
1864 /*
1865  * Send a message and receive the reply - simple messages.
1866  *
1867  * @param jlink pointer to driver data
1868  * @param out_length data length in @c usb_out_buffer
1869  * @param in_length data length to be read to @c usb_in_buffer
1870  */
1871 static int jlink_usb_io(struct jlink *jlink, int out_length, int in_length)
1872 {
1873         int result;
1874
1875         result = jlink_usb_write(jlink, out_length);
1876         if (result != out_length) {
1877                 LOG_ERROR("usb_bulk_write failed (requested=%d, result=%d)",
1878                                 out_length, result);
1879                 return ERROR_JTAG_DEVICE_ERROR;
1880         }
1881
1882         result = jlink_usb_read(jlink, in_length);
1883         if (result != in_length) {
1884                 LOG_ERROR("usb_bulk_read failed (requested=%d, result=%d)",
1885                                 in_length, result);
1886                 return ERROR_JTAG_DEVICE_ERROR;
1887         }
1888
1889         /*
1890          * Section 4.2.4 IN-transaction:
1891          * read dummy 0-byte packet if transaction size is
1892          * multiple of 64 bytes but not max. size of 0x8000
1893          */
1894         if ((in_length % 64) == 0 && in_length != 0x8000) {
1895                 char dummy_buffer;
1896                 result = usb_bulk_read_ex(jlink->usb_handle, jlink_read_ep,
1897                         &dummy_buffer, 1, JLINK_USB_TIMEOUT);
1898                 if (result != 0) {
1899                         LOG_ERROR("dummy byte read failed");
1900                         return ERROR_JTAG_DEVICE_ERROR;
1901                 }
1902         }
1903         return ERROR_OK;
1904 }
1905
1906 #ifdef _DEBUG_USB_COMMS_
1907 #define BYTES_PER_LINE  16
1908
1909 static void jlink_debug_buffer(uint8_t *buffer, int length)
1910 {
1911         char line[81];
1912         char s[4];
1913         int i;
1914         int j;
1915
1916         for (i = 0; i < length; i += BYTES_PER_LINE) {
1917                 snprintf(line, 5, "%04x", i);
1918                 for (j = i; j < i + BYTES_PER_LINE && j < length; j++) {
1919                         snprintf(s, 4, " %02x", buffer[j]);
1920                         strcat(line, s);
1921                 }
1922                 LOG_DEBUG("%s", line);
1923         }
1924 }
1925 #endif