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