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