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