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