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