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