jlink: add capability dumper and command
[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  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include <jtag/interface.h>
29 #include <jtag/commands.h>
30 #include "usb_common.h"
31
32 /* See Segger's public documentation:
33  *      Reference manual for J-Link USB Protocol
34  *      Document RM08001-R6 Date: June 16, 2009
35  *      (Or newer, with some SWD information).
36  
37 http://www.segger.com/cms/admin/uploads/productDocs/RM08001_JLinkUSBProtocol.pdf
38  */
39
40 /*
41  * The default pid of the segger is 0x0101
42  * But when you change the USB Address it will also
43  *
44  * pid = ( usb_address > 0x4) ? 0x0101 : (0x101 + usb_address)
45  */
46 #define VID 0x1366, 0x1366, 0x1366, 0x1366
47 #define PID 0x0101, 0x0102, 0x0103, 0x0104
48
49 #define JLINK_WRITE_ENDPOINT    0x02
50 #define JLINK_READ_ENDPOINT             0x81
51
52 static unsigned int jlink_write_ep = JLINK_WRITE_ENDPOINT;
53 static unsigned int jlink_read_ep = JLINK_READ_ENDPOINT;
54 static unsigned int jlink_hw_jtag_version = 2;
55
56 #define JLINK_USB_TIMEOUT               1000
57
58 // See Section 1.3.2 of the Segger JLink USB protocol manual
59 /* 2048 is the max value we can use here */
60 //#define JLINK_TAP_BUFFER_SIZE 2048
61 #define JLINK_TAP_BUFFER_SIZE 256
62 //#define JLINK_TAP_BUFFER_SIZE 384
63
64 #define JLINK_IN_BUFFER_SIZE                    2048
65 #define JLINK_OUT_BUFFER_SIZE                   2*2048 + 4
66 #define JLINK_EMU_RESULT_BUFFER_SIZE    64
67
68 /* Global USB buffers */
69 static uint8_t usb_in_buffer[JLINK_IN_BUFFER_SIZE];
70 static uint8_t usb_out_buffer[JLINK_OUT_BUFFER_SIZE];
71 static uint8_t usb_emu_result_buffer[JLINK_EMU_RESULT_BUFFER_SIZE];
72
73 /* Constants for JLink command */
74 #define EMU_CMD_VERSION                 0x01
75 #define EMU_CMD_SET_SPEED               0x05
76 #define EMU_CMD_GET_STATE               0x07
77 #define EMU_CMD_HW_CLOCK                0xc8
78 #define EMU_CMD_HW_TMS0                 0xc9
79 #define EMU_CMD_HW_TMS1                 0xca
80 #define EMU_CMD_HW_JTAG2                0xce
81 #define EMU_CMD_HW_JTAG3                0xcf
82 #define EMU_CMD_GET_MAX_MEM_BLOCK       0xd4
83 #define EMU_CMD_HW_RESET0               0xdc
84 #define EMU_CMD_HW_RESET1               0xdd
85 #define EMU_CMD_HW_TRST0                0xde
86 #define EMU_CMD_HW_TRST1                0xdf
87 #define EMU_CMD_GET_CAPS                0xe8
88 #define EMU_CMD_GET_HW_VERSION  0xf0
89
90 /* bits return from EMU_CMD_GET_CAPS */
91 #define EMU_CAP_RESERVED_1              0
92 #define EMU_CAP_GET_HW_VERSION          1
93 #define EMU_CAP_WRITE_DCC               2
94 #define EMU_CAP_ADAPTIVE_CLOCKING       3
95 #define EMU_CAP_READ_CONFIG             4
96 #define EMU_CAP_WRITE_CONFIG            5
97 #define EMU_CAP_TRACE                   6
98 #define EMU_CAP_WRITE_MEM               7
99 #define EMU_CAP_READ_MEM                8
100 #define EMU_CAP_SPEED_INFO              9
101 #define EMU_CAP_EXEC_CODE               10
102 #define EMU_CAP_GET_MAX_BLOCK_SIZE      11
103 #define EMU_CAP_GET_HW_INFO             12
104 #define EMU_CAP_SET_KS_POWER            13
105 #define EMU_CAP_RESET_STOP_TIMED        14
106 #define EMU_CAP_RESERVED_2              15
107 #define EMU_CAP_MEASURE_RTCK_REACT      16
108 #define EMU_CAP_SELECT_IF               17
109 #define EMU_CAP_RW_MEM_ARM79            18
110 #define EMU_CAP_GET_COUNTERS            19
111 #define EMU_CAP_READ_DCC                20
112 #define EMU_CAP_GET_CPU_CAPS            21
113 #define EMU_CAP_EXEC_CPU_CMD            22
114 #define EMU_CAP_SWO                     23
115 #define EMU_CAP_WRITE_DCC_EX            24
116 #define EMU_CAP_UPDATE_FIRMWARE_EX      25
117 #define EMU_CAP_FILE_IO                 26
118 #define EMU_CAP_REGISTER                27
119 #define EMU_CAP_INDICATORS              28
120 #define EMU_CAP_TEST_NET_SPEED          29
121 #define EMU_CAP_RAWTRACE                30
122 #define EMU_CAP_RESERVED_3              31
123
124 static char *jlink_cap_str[] = {
125         "Always 1.",
126         "Supports command EMU_CMD_GET_HARDWARE_VERSION",
127         "Supports command EMU_CMD_WRITE_DCC",
128         "Supports adaptive clocking",
129         "Supports command EMU_CMD_READ_CONFIG",
130         "Supports command EMU_CMD_WRITE_CONFIG",
131         "Supports trace commands",
132         "Supports command EMU_CMD_WRITE_MEM",
133         "Supports command EMU_CMD_READ_MEM",
134         "Supports command EMU_CMD_GET_SPEED",
135         "Supports command EMU_CMD_CODE_...",
136         "Supports command EMU_CMD_GET_MAX_BLOCK_SIZE",
137         "Supports command EMU_CMD_GET_HW_INFO",
138         "Supports command EMU_CMD_SET_KS_POWER",
139         "Supports command EMU_CMD_HW_RELEASE_RESET_STOP_TIMED",
140         "Reserved",
141         "Supports command EMU_CMD_MEASURE_RTCK_REACT",
142         "Supports command EMU_CMD_HW_SELECT_IF",
143         "Supports command EMU_CMD_READ/WRITE_MEM_ARM79",
144         "Supports command EMU_CMD_GET_COUNTERS",
145         "Supports command EMU_CMD_READ_DCC",
146         "Supports command EMU_CMD_GET_CPU_CAPS",
147         "Supports command EMU_CMD_EXEC_CPU_CMD",
148         "Supports command EMU_CMD_SWO",
149         "Supports command EMU_CMD_WRITE_DCC_EX",
150         "Supports command EMU_CMD_UPDATE_FIRMWARE_EX",
151         "Supports command EMU_CMD_FILE_IO",
152         "Supports command EMU_CMD_REGISTER",
153         "Supports command EMU_CMD_INDICATORS",
154         "Supports command EMU_CMD_TEST_NET_SPEED",
155         "Supports command EMU_CMD_RAWTRACE",
156         "Reserved",
157 };
158
159 /* max speed 12MHz v5.0 jlink */
160 #define JLINK_MAX_SPEED 12000
161
162 /* Queue command functions */
163 static void jlink_end_state(tap_state_t state);
164 static void jlink_state_move(void);
165 static void jlink_path_move(int num_states, tap_state_t *path);
166 static void jlink_runtest(int num_cycles);
167 static void jlink_scan(bool ir_scan, enum scan_type type, uint8_t *buffer,
168                 int scan_size, struct scan_command *command);
169 static void jlink_reset(int trst, int srst);
170 static void jlink_simple_command(uint8_t command);
171 static int jlink_get_status(void);
172
173 /* J-Link tap buffer functions */
174 static void jlink_tap_init(void);
175 static int jlink_tap_execute(void);
176 static void jlink_tap_ensure_space(int scans, int bits);
177 static void jlink_tap_append_step(int tms, int tdi);
178 static void jlink_tap_append_scan(int length, uint8_t *buffer,
179                 struct scan_command *command);
180
181 /* Jlink lowlevel functions */
182 struct jlink {
183         struct usb_dev_handle* usb_handle;
184 };
185
186 static struct jlink *jlink_usb_open(void);
187 static void jlink_usb_close(struct jlink *jlink);
188 static int jlink_usb_message(struct jlink *jlink, int out_length, int in_length);
189 static int jlink_usb_write(struct jlink *jlink, int out_length);
190 static int jlink_usb_read(struct jlink *jlink, int expected_size);
191 static int jlink_usb_read_emu_result(struct jlink *jlink);
192
193 /* helper functions */
194 static int jlink_get_version_info(void);
195
196 #ifdef _DEBUG_USB_COMMS_
197 static void jlink_debug_buffer(uint8_t *buffer, int length);
198 #endif
199
200 static enum tap_state jlink_last_state = TAP_RESET;
201
202 static struct jlink* jlink_handle;
203
204 /* pid could be specified at runtime */
205 static uint16_t vids[] = { VID, 0 };
206 static uint16_t pids[] = { PID, 0 };
207
208 static uint32_t jlink_caps;
209
210 /***************************************************************************/
211 /* External interface implementation */
212
213 static void jlink_execute_runtest(struct jtag_command *cmd)
214 {
215         DEBUG_JTAG_IO("runtest %i cycles, end in %i",
216                         cmd->cmd.runtest->num_cycles,
217                         cmd->cmd.runtest->end_state);
218
219         jlink_end_state(cmd->cmd.runtest->end_state);
220
221         jlink_runtest(cmd->cmd.runtest->num_cycles);
222 }
223
224 static void jlink_execute_statemove(struct jtag_command *cmd)
225 {
226         DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
227
228         jlink_end_state(cmd->cmd.statemove->end_state);
229         jlink_state_move();
230 }
231
232 static void jlink_execute_pathmove(struct jtag_command *cmd)
233 {
234         DEBUG_JTAG_IO("pathmove: %i states, end in %i",
235                 cmd->cmd.pathmove->num_states,
236                 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
237
238         jlink_path_move(cmd->cmd.pathmove->num_states,
239                         cmd->cmd.pathmove->path);
240 }
241
242 static void jlink_execute_scan(struct jtag_command *cmd)
243 {
244         int scan_size;
245         enum scan_type type;
246         uint8_t *buffer;
247
248         DEBUG_JTAG_IO("scan end in %s", tap_state_name(cmd->cmd.scan->end_state));
249
250         jlink_end_state(cmd->cmd.scan->end_state);
251
252         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
253         DEBUG_JTAG_IO("scan input, length = %d", scan_size);
254
255 #ifdef _DEBUG_USB_COMMS_
256         jlink_debug_buffer(buffer, (scan_size + 7) / 8);
257 #endif
258         type = jtag_scan_type(cmd->cmd.scan);
259         jlink_scan(cmd->cmd.scan->ir_scan,
260                         type, buffer, scan_size, cmd->cmd.scan);
261 }
262
263 static void jlink_execute_reset(struct jtag_command *cmd)
264 {
265         DEBUG_JTAG_IO("reset trst: %i srst %i",
266                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
267
268         jlink_tap_execute();
269         jlink_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
270         jlink_tap_execute();
271 }
272
273 static void jlink_execute_sleep(struct jtag_command *cmd)
274 {
275         DEBUG_JTAG_IO("sleep %" PRIi32 "", cmd->cmd.sleep->us);
276         jlink_tap_execute();
277         jtag_sleep(cmd->cmd.sleep->us);
278 }
279
280 static void jlink_execute_command(struct jtag_command *cmd)
281 {
282         switch (cmd->type)
283         {
284         case JTAG_RUNTEST:   jlink_execute_runtest(cmd); break;
285         case JTAG_TLR_RESET: jlink_execute_statemove(cmd); break;
286         case JTAG_PATHMOVE:  jlink_execute_pathmove(cmd); break;
287         case JTAG_SCAN:      jlink_execute_scan(cmd); break;
288         case JTAG_RESET:     jlink_execute_reset(cmd); break;
289         case JTAG_SLEEP:     jlink_execute_sleep(cmd); break;
290         default:
291                 LOG_ERROR("BUG: unknown JTAG command type encountered");
292                 exit(-1);
293         }
294 }
295
296 static int jlink_execute_queue(void)
297 {
298         struct jtag_command *cmd = jtag_command_queue;
299
300         while (cmd != NULL)
301         {
302                 jlink_execute_command(cmd);
303                 cmd = cmd->next;
304         }
305
306         return jlink_tap_execute();
307 }
308
309 /* Sets speed in kHz. */
310 static int jlink_speed(int speed)
311 {
312         int result;
313
314         if (speed > JLINK_MAX_SPEED)
315         {
316                 LOG_INFO("reduce speed request: %dkHz to %dkHz maximum",
317                                 speed, JLINK_MAX_SPEED);
318                 speed = JLINK_MAX_SPEED;
319         }
320
321         /* check for RTCK setting */
322         if (speed == 0)
323                 speed = -1;
324
325         usb_out_buffer[0] = EMU_CMD_SET_SPEED;
326         usb_out_buffer[1] = (speed >> 0) & 0xff;
327         usb_out_buffer[2] = (speed >> 8) & 0xff;
328
329         result = jlink_usb_write(jlink_handle, 3);
330         if (result != 3)
331         {
332                 LOG_ERROR("J-Link setting speed failed (%d)", result);
333                 return ERROR_JTAG_DEVICE_ERROR;
334         }
335
336         return ERROR_OK;
337 }
338
339 static int jlink_speed_div(int speed, int* khz)
340 {
341         *khz = speed;
342
343         return ERROR_OK;
344 }
345
346 static int jlink_khz(int khz, int *jtag_speed)
347 {
348         *jtag_speed = khz;
349
350         return ERROR_OK;
351 }
352
353 static int jlink_init(void)
354 {
355         int i;
356
357         jlink_handle = jlink_usb_open();
358
359         if (jlink_handle == 0)
360         {
361                 LOG_ERROR("Cannot find jlink Interface! Please check "
362                                 "connection and permissions.");
363                 return ERROR_JTAG_INIT_FAILED;
364         }
365
366         /*
367          * The next three instructions were added after discovering a problem
368          * while using an oscilloscope.
369          * For the V8 SAM-ICE dongle (and likely other j-link device variants),
370          * the reset line to the target microprocessor was found to cycle only
371          * intermittently during emulator startup (even after encountering the
372          * downstream reset instruction later in the code).
373          * This was found to create two issues:
374          * 1) In general it is a bad practice to not reset a CPU to a known
375          * state when starting an emulator and
376          * 2) something critical happens inside the dongle when it does the
377          * first read following a new USB session.
378          * Keeping the processor in reset during the first read collecting
379          * version information seems to prevent errant
380          * "J-Link command EMU_CMD_VERSION failed" issues.
381          */
382
383         LOG_INFO("J-Link initialization started / target CPU reset initiated");
384         jlink_simple_command(EMU_CMD_HW_TRST0);
385         jlink_simple_command(EMU_CMD_HW_RESET0);
386         usleep(1000);
387
388         jlink_hw_jtag_version = 2;
389
390         if (jlink_get_version_info() == ERROR_OK)
391         {
392                 /* attempt to get status */
393                 jlink_get_status();
394         }
395
396         LOG_INFO("J-Link JTAG Interface ready");
397
398         jlink_reset(0, 0);
399         jtag_sleep(3000);
400         jlink_tap_init();
401         int jtag_speed_var;
402         int retval = jtag_get_speed(&jtag_speed_var);
403         if (retval != ERROR_OK)
404                 return retval;
405         jlink_speed(jtag_speed_var);
406
407         /* v5/6 jlink seems to have an issue if the first tap move
408          * is not divisible by 8, so we send a TLR on first power up */
409         for (i = 0; i < 8; i++) {
410                 jlink_tap_append_step(1, 0);
411         }
412         jlink_tap_execute();
413
414         return ERROR_OK;
415 }
416
417 static int jlink_quit(void)
418 {
419         jlink_usb_close(jlink_handle);
420         return ERROR_OK;
421 }
422
423 /***************************************************************************/
424 /* Queue command implementations */
425
426 static void jlink_end_state(tap_state_t state)
427 {
428         if (tap_is_state_stable(state))
429         {
430                 tap_set_end_state(state);
431         }
432         else
433         {
434                 LOG_ERROR("BUG: %i is not a valid end state", state);
435                 exit(-1);
436         }
437 }
438
439 /* Goes to the end state. */
440 static void jlink_state_move(void)
441 {
442         int i;
443         int tms = 0;
444         uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
445         uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
446
447         for (i = 0; i < tms_scan_bits; i++)
448         {
449                 tms = (tms_scan >> i) & 1;
450                 jlink_tap_append_step(tms, 0);
451         }
452
453         tap_set_state(tap_get_end_state());
454 }
455
456 static void jlink_path_move(int num_states, tap_state_t *path)
457 {
458         int i;
459
460         for (i = 0; i < num_states; i++)
461         {
462                 if (path[i] == tap_state_transition(tap_get_state(), false))
463                 {
464                         jlink_tap_append_step(0, 0);
465                 }
466                 else if (path[i] == tap_state_transition(tap_get_state(), true))
467                 {
468                         jlink_tap_append_step(1, 0);
469                 }
470                 else
471                 {
472                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
473                                         tap_state_name(tap_get_state()), tap_state_name(path[i]));
474                         exit(-1);
475                 }
476
477                 tap_set_state(path[i]);
478         }
479
480         tap_set_end_state(tap_get_state());
481 }
482
483 static void jlink_runtest(int num_cycles)
484 {
485         int i;
486
487         tap_state_t saved_end_state = tap_get_end_state();
488
489         jlink_tap_ensure_space(1,num_cycles + 16);
490
491         /* only do a state_move when we're not already in IDLE */
492         if (tap_get_state() != TAP_IDLE)
493         {
494                 jlink_end_state(TAP_IDLE);
495                 jlink_state_move();
496 //              num_cycles--;
497         }
498
499         /* execute num_cycles */
500         for (i = 0; i < num_cycles; i++)
501         {
502                 jlink_tap_append_step(0, 0);
503         }
504
505         /* finish in end_state */
506         jlink_end_state(saved_end_state);
507         if (tap_get_state() != tap_get_end_state())
508         {
509                 jlink_state_move();
510         }
511 }
512
513 static void jlink_scan(bool ir_scan, enum scan_type type, uint8_t *buffer,
514                 int scan_size, struct scan_command *command)
515 {
516         tap_state_t saved_end_state;
517
518         jlink_tap_ensure_space(1, scan_size + 16);
519
520         saved_end_state = tap_get_end_state();
521
522         /* Move to appropriate scan state */
523         jlink_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
524
525         /* Only move if we're not already there */
526         if (tap_get_state() != tap_get_end_state())
527                 jlink_state_move();
528
529         jlink_end_state(saved_end_state);
530
531         /* Scan */
532         jlink_tap_append_scan(scan_size, buffer, command);
533
534         /* We are in Exit1, go to Pause */
535         jlink_tap_append_step(0, 0);
536
537         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
538
539         if (tap_get_state() != tap_get_end_state())
540         {
541                 jlink_state_move();
542         }
543 }
544
545 static void jlink_reset(int trst, int srst)
546 {
547         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
548
549         /* Signals are active low */
550         if (srst == 0)
551         {
552                 jlink_simple_command(EMU_CMD_HW_RESET1);
553         }
554         if (srst == 1)
555         {
556                 jlink_simple_command(EMU_CMD_HW_RESET0);
557         }
558
559         if (trst == 1)
560         {
561                 jlink_simple_command(EMU_CMD_HW_TRST0);
562         }
563
564         if (trst == 0)
565         {
566                 jlink_simple_command(EMU_CMD_HW_TRST1);
567         }
568 }
569
570 static void jlink_simple_command(uint8_t command)
571 {
572         int result;
573
574         DEBUG_JTAG_IO("0x%02x", command);
575
576         usb_out_buffer[0] = command;
577         result = jlink_usb_write(jlink_handle, 1);
578
579         if (result != 1)
580         {
581                 LOG_ERROR("J-Link command 0x%02x failed (%d)", command, result);
582         }
583 }
584
585 static int jlink_get_status(void)
586 {
587         int result;
588
589         jlink_simple_command(EMU_CMD_GET_STATE);
590
591         result = jlink_usb_read(jlink_handle, 8);
592         if (result != 8)
593         {
594                 LOG_ERROR("J-Link command EMU_CMD_GET_STATE failed (%d)", result);
595                 return ERROR_JTAG_DEVICE_ERROR;
596         }
597
598         int vref = usb_in_buffer[0] + (usb_in_buffer[1] << 8);
599         LOG_INFO("Vref = %d.%d TCK = %d TDI = %d TDO = %d TMS = %d SRST = %d TRST = %d", \
600                 vref / 1000, vref % 1000, \
601                 usb_in_buffer[2], usb_in_buffer[3], usb_in_buffer[4], \
602                 usb_in_buffer[5], usb_in_buffer[6], usb_in_buffer[7]);
603
604         if (vref < 1500)
605                 LOG_ERROR("Vref too low. Check Target Power");
606
607         return ERROR_OK;
608 }
609
610 #define jlink_dump_printf(context, expr ...)    \
611         do {                                    \
612         if (context)                            \
613                 command_print(context, expr);   \
614         else                                    \
615                 LOG_INFO(expr);                 \
616         } while(0);
617
618
619 static void jlink_caps_dump(struct command_context *ctx)
620 {
621         int i;
622
623         jlink_dump_printf(ctx, "J-Link Capabilities");
624
625         for (i = 1; i < 31; i++)
626                 if (jlink_caps & (1 << i))
627                         jlink_dump_printf(ctx, "%s", jlink_cap_str[i]);
628 }
629
630 static int jlink_get_version_info(void)
631 {
632         int result;
633         int len;
634         uint32_t jlink_max_size;
635
636         /* query hardware version */
637         jlink_simple_command(EMU_CMD_VERSION);
638
639         result = jlink_usb_read(jlink_handle, 2);
640         if (2 != result)
641         {
642                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)", result);
643                 return ERROR_JTAG_DEVICE_ERROR;
644         }
645
646         len = buf_get_u32(usb_in_buffer, 0, 16);
647         if (len > JLINK_IN_BUFFER_SIZE)
648         {
649                 LOG_ERROR("J-Link command EMU_CMD_VERSION impossible return length 0x%0x", len);
650                 len = JLINK_IN_BUFFER_SIZE;
651         }
652
653         result = jlink_usb_read(jlink_handle, len);
654         if (result != len)
655         {
656                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)", result);
657                 return ERROR_JTAG_DEVICE_ERROR;
658         }
659
660         usb_in_buffer[result] = 0;
661         LOG_INFO("%s", (char *)usb_in_buffer);
662
663         /* query hardware capabilities */
664         jlink_simple_command(EMU_CMD_GET_CAPS);
665
666         result = jlink_usb_read(jlink_handle, 4);
667         if (4 != result)
668         {
669                 LOG_ERROR("J-Link command EMU_CMD_GET_CAPS failed (%d)", result);
670                 return ERROR_JTAG_DEVICE_ERROR;
671         }
672
673         jlink_caps = buf_get_u32(usb_in_buffer, 0, 32);
674         LOG_INFO("J-Link caps 0x%x", (unsigned)jlink_caps);
675
676         if (jlink_caps & (1 << EMU_CAP_GET_HW_VERSION))
677         {
678                 /* query hardware version */
679                 jlink_simple_command(EMU_CMD_GET_HW_VERSION);
680
681                 result = jlink_usb_read(jlink_handle, 4);
682                 if (4 != result)
683                 {
684                         LOG_ERROR("J-Link command EMU_CMD_GET_HW_VERSION failed (%d)", result);
685                         return ERROR_JTAG_DEVICE_ERROR;
686                 }
687
688                 uint32_t jlink_hw_version = buf_get_u32(usb_in_buffer, 0, 32);
689                 uint32_t major_revision = (jlink_hw_version / 10000) % 100;
690                 if (major_revision >= 5)
691                         jlink_hw_jtag_version = 3;
692
693                 LOG_INFO("J-Link hw version %i", (int)jlink_hw_version);
694         }
695
696         if (jlink_caps & (1 << EMU_CAP_GET_MAX_BLOCK_SIZE))
697         {
698                 /* query hardware maximum memory block */
699                 jlink_simple_command(EMU_CMD_GET_MAX_MEM_BLOCK);
700
701                 result = jlink_usb_read(jlink_handle, 4);
702                 if (4 != result)
703                 {
704                         LOG_ERROR("J-Link command EMU_CMD_GET_MAX_MEM_BLOCK failed (%d)", result);
705                         return ERROR_JTAG_DEVICE_ERROR;
706                 }
707
708                 jlink_max_size = buf_get_u32(usb_in_buffer, 0, 32);
709                 LOG_INFO("J-Link max mem block %i", (int)jlink_max_size);
710         }
711
712         return ERROR_OK;
713 }
714
715 COMMAND_HANDLER(jlink_pid_command)
716 {
717         if (CMD_ARGC != 1)
718         {
719                 LOG_ERROR("Need exactly one argument to jlink_pid");
720                 return ERROR_FAIL;
721         }
722
723         pids[0] = strtoul(CMD_ARGV[0], NULL, 16);
724         pids[1] = 0;
725         vids[1] = 0;
726
727         return ERROR_OK;
728 }
729
730 COMMAND_HANDLER(jlink_handle_jlink_info_command)
731 {
732         if (jlink_get_version_info() == ERROR_OK)
733         {
734                 /* attempt to get status */
735                 jlink_get_status();
736         }
737
738         return ERROR_OK;
739 }
740
741 COMMAND_HANDLER(jlink_handle_jlink_caps_command)
742 {
743         jlink_caps_dump(CMD_CTX);
744
745         return ERROR_OK;
746 }
747
748 COMMAND_HANDLER(jlink_handle_jlink_hw_jtag_command)
749 {
750         switch (CMD_ARGC) {
751         case 0:
752                 command_print(CMD_CTX, "J-Link hw jtag  %i", jlink_hw_jtag_version);
753                 break;
754         case 1: {
755                 int request_version = atoi(CMD_ARGV[0]);
756                 switch (request_version) {
757                 case 2: case 3:
758                         jlink_hw_jtag_version = request_version;
759                         break;
760                 default:
761                         return ERROR_COMMAND_SYNTAX_ERROR;
762                 }
763                 break;
764         }
765         default:
766                 return ERROR_COMMAND_SYNTAX_ERROR;
767         }
768
769         return ERROR_OK;
770 }
771
772 static const struct command_registration jlink_subcommand_handlers[] = {
773         {
774                 .name = "caps",
775                 .handler = &jlink_handle_jlink_caps_command,
776                 .mode = COMMAND_EXEC,
777                 .help = "show jlink capabilities",
778         },
779         {
780                 .name = "info",
781                 .handler = &jlink_handle_jlink_info_command,
782                 .mode = COMMAND_EXEC,
783                 .help = "show jlink info",
784         },
785         {
786                 .name = "hw_jtag",
787                 .handler = &jlink_handle_jlink_hw_jtag_command,
788                 .mode = COMMAND_EXEC,
789                 .help = "access J-Link HW JTAG command version",
790                 .usage = "[2|3]",
791         },
792         {
793                 .name = "pid",
794                 .handler = &jlink_pid_command,
795                 .mode = COMMAND_CONFIG,
796                 .help = "set the pid of the interface we want to use",
797         },
798         COMMAND_REGISTRATION_DONE
799 };
800
801 static const struct command_registration jlink_command_handlers[] = {
802         {
803                 .name = "jlink",
804                 .mode = COMMAND_ANY,
805                 .help = "perform jlink management",
806                 .chain = jlink_subcommand_handlers,
807         },
808         COMMAND_REGISTRATION_DONE
809 };
810
811 struct jtag_interface jlink_interface = {
812         .name = "jlink",
813         .commands = jlink_command_handlers,
814
815         .execute_queue = jlink_execute_queue,
816         .speed = jlink_speed,
817         .speed_div = jlink_speed_div,
818         .khz = jlink_khz,
819         .init = jlink_init,
820         .quit = jlink_quit,
821 };
822
823 /***************************************************************************/
824 /* J-Link tap functions */
825
826
827 static unsigned tap_length = 0;
828 static uint8_t tms_buffer[JLINK_TAP_BUFFER_SIZE];
829 static uint8_t tdi_buffer[JLINK_TAP_BUFFER_SIZE];
830 static uint8_t tdo_buffer[JLINK_TAP_BUFFER_SIZE];
831
832 struct pending_scan_result {
833         int first;      /* First bit position in tdo_buffer to read */
834         int length; /* Number of bits to read */
835         struct scan_command *command; /* Corresponding scan command */
836         uint8_t *buffer;
837 };
838
839 #define MAX_PENDING_SCAN_RESULTS 256
840
841 static int pending_scan_results_length;
842 static struct pending_scan_result pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
843
844 static void jlink_tap_init(void)
845 {
846         tap_length = 0;
847         pending_scan_results_length = 0;
848 }
849
850 static void jlink_tap_ensure_space(int scans, int bits)
851 {
852         int available_scans = MAX_PENDING_SCAN_RESULTS - pending_scan_results_length;
853         int available_bits = JLINK_TAP_BUFFER_SIZE * 8 - tap_length - 32;
854
855         if (scans > available_scans || bits > available_bits)
856         {
857                 jlink_tap_execute();
858         }
859 }
860
861 static void jlink_tap_append_step(int tms, int tdi)
862 {
863         int index_var = tap_length / 8;
864
865         if (index_var >= JLINK_TAP_BUFFER_SIZE)
866         {
867                 LOG_ERROR("jlink_tap_append_step: overflow");
868                 *(uint32_t *)0xFFFFFFFF = 0;
869                 exit(-1);
870         }
871
872         int bit_index = tap_length % 8;
873         uint8_t bit = 1 << bit_index;
874
875         // we do not pad TMS, so be sure to initialize all bits
876         if (0 == bit_index)
877         {
878                 tms_buffer[index_var] = tdi_buffer[index_var] = 0;
879         }
880
881         if (tms)
882                 tms_buffer[index_var] |= bit;
883         else
884                 tms_buffer[index_var] &= ~bit;
885
886         if (tdi)
887                 tdi_buffer[index_var] |= bit;
888         else
889                 tdi_buffer[index_var] &= ~bit;
890
891         tap_length++;
892 }
893
894 static void jlink_tap_append_scan(int length, uint8_t *buffer,
895                 struct scan_command *command)
896 {
897         struct pending_scan_result *pending_scan_result =
898                 &pending_scan_results_buffer[pending_scan_results_length];
899         int i;
900
901         pending_scan_result->first = tap_length;
902         pending_scan_result->length = length;
903         pending_scan_result->command = command;
904         pending_scan_result->buffer = buffer;
905
906         for (i = 0; i < length; i++)
907         {
908                 int tms = (i < (length - 1)) ? 0 : 1;
909                 int tdi = (buffer[i / 8] & (1 << (i % 8))) != 0;
910                 jlink_tap_append_step(tms, tdi);
911         }
912         pending_scan_results_length++;
913 }
914
915 /* Pad and send a tap sequence to the device, and receive the answer.
916  * For the purpose of padding we assume that we are in idle or pause state. */
917 static int jlink_tap_execute(void)
918 {
919         int byte_length;
920         int i;
921         int result;
922
923         if (!tap_length)
924                 return ERROR_OK;
925
926         /* JLink returns an extra NULL in packet when size of incoming
927          * message is a multiple of 64, creates problems with USB comms.
928          * WARNING: This will interfere with tap state counting. */
929         while ((DIV_ROUND_UP(tap_length, 8) % 64) == 0)
930         {
931                 jlink_tap_append_step((tap_get_state() == TAP_RESET) ? 1 : 0, 0);
932         }
933
934         // number of full bytes (plus one if some would be left over)
935         byte_length = DIV_ROUND_UP(tap_length, 8);
936
937         bool use_jtag3 = jlink_hw_jtag_version >= 3;
938         usb_out_buffer[0] = use_jtag3 ? EMU_CMD_HW_JTAG3 : EMU_CMD_HW_JTAG2;
939         usb_out_buffer[1] = 0;
940         usb_out_buffer[2] = (tap_length >> 0) & 0xff;
941         usb_out_buffer[3] = (tap_length >> 8) & 0xff;
942         memcpy(usb_out_buffer + 4, tms_buffer, byte_length);
943         memcpy(usb_out_buffer + 4 + byte_length, tdi_buffer, byte_length);
944
945         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
946                         tap_length, jlink_last_state);
947
948         result = jlink_usb_message(jlink_handle, 4 + 2 * byte_length, byte_length);
949         if (result != byte_length)
950         {
951                 LOG_ERROR("jlink_tap_execute, wrong result %d (expected %d)",
952                                 result, byte_length);
953                 jlink_tap_init();
954                 return ERROR_JTAG_QUEUE_FAILED;
955         }
956
957         memcpy(tdo_buffer, usb_in_buffer, byte_length);
958
959         for (i = 0; i < pending_scan_results_length; i++)
960         {
961                 struct pending_scan_result *pending_scan_result = &pending_scan_results_buffer[i];
962                 uint8_t *buffer = pending_scan_result->buffer;
963                 int length = pending_scan_result->length;
964                 int first = pending_scan_result->first;
965                 struct scan_command *command = pending_scan_result->command;
966
967                 /* Copy to buffer */
968                 buf_set_buf(tdo_buffer, first, buffer, 0, length);
969
970                 DEBUG_JTAG_IO("pending scan result, length = %d", length);
971
972 #ifdef _DEBUG_USB_COMMS_
973                 jlink_debug_buffer(buffer, DIV_ROUND_UP(length, 8));
974 #endif
975
976                 if (jtag_read_buffer(buffer, command) != ERROR_OK)
977                 {
978                         jlink_tap_init();
979                         return ERROR_JTAG_QUEUE_FAILED;
980                 }
981
982                 if (pending_scan_result->buffer != NULL)
983                 {
984                         free(pending_scan_result->buffer);
985                 }
986         }
987
988         jlink_tap_init();
989         return ERROR_OK;
990 }
991
992 /*****************************************************************************/
993 /* JLink USB low-level functions */
994
995 static struct jlink* jlink_usb_open()
996 {
997         usb_init();
998
999         struct usb_dev_handle *dev;
1000         if (jtag_usb_open(vids, pids, &dev) != ERROR_OK)
1001                 return NULL;
1002
1003         /* BE ***VERY CAREFUL*** ABOUT MAKING CHANGES IN THIS
1004          * AREA!!!!!!!!!!!  The behavior of libusb is not completely
1005          * consistent across Windows, Linux, and Mac OS X platforms.
1006          * The actions taken in the following compiler conditionals may
1007          * not agree with published documentation for libusb, but were
1008          * found to be necessary through trials and tribulations.  Even
1009          * little tweaks can break one or more platforms, so if you do
1010          * make changes test them carefully on all platforms before
1011          * committing them!
1012          */
1013
1014 #if IS_WIN32 == 0
1015
1016         usb_reset(dev);
1017
1018 #if IS_DARWIN == 0
1019
1020         int timeout = 5;
1021         /* reopen jlink after usb_reset
1022          * on win32 this may take a second or two to re-enumerate */
1023         int retval;
1024         while ((retval = jtag_usb_open(vids, pids, &dev)) != ERROR_OK)
1025         {
1026                 usleep(1000);
1027                 timeout--;
1028                 if (!timeout) {
1029                         break;
1030                 }
1031         }
1032         if (ERROR_OK != retval)
1033                 return NULL;
1034 #endif
1035
1036 #endif
1037
1038         /* usb_set_configuration required under win32 */
1039         struct usb_device *udev = usb_device(dev);
1040         usb_set_configuration(dev, udev->config[0].bConfigurationValue);
1041         usb_claim_interface(dev, 0);
1042
1043 #if 0
1044         /*
1045          * This makes problems under Mac OS X. And is not needed
1046          * under Windows. Hopefully this will not break a linux build
1047          */
1048         usb_set_altinterface(result->usb_handle, 0);
1049 #endif
1050         struct usb_interface *iface = udev->config->interface;
1051         struct usb_interface_descriptor *desc = iface->altsetting;
1052         for (int i = 0; i < desc->bNumEndpoints; i++)
1053         {
1054                 uint8_t epnum = desc->endpoint[i].bEndpointAddress;
1055                 bool is_input = epnum & 0x80;
1056                 LOG_DEBUG("usb ep %s %02x", is_input ? "in" : "out", epnum);
1057                 if (is_input)
1058                         jlink_read_ep = epnum;
1059                 else
1060                         jlink_write_ep = epnum;
1061         }
1062
1063         struct jlink *result = malloc(sizeof(struct jlink));
1064         result->usb_handle = dev;
1065         return result;
1066 }
1067
1068 static void jlink_usb_close(struct jlink *jlink)
1069 {
1070         usb_close(jlink->usb_handle);
1071         free(jlink);
1072 }
1073
1074 /* Send a message and receive the reply. */
1075 static int jlink_usb_message(struct jlink *jlink, int out_length, int in_length)
1076 {
1077         int result;
1078
1079         result = jlink_usb_write(jlink, out_length);
1080         if (result != out_length)
1081         {
1082                 LOG_ERROR("usb_bulk_write failed (requested=%d, result=%d)",
1083                                 out_length, result);
1084                 return ERROR_JTAG_DEVICE_ERROR;
1085         }
1086
1087         result = jlink_usb_read(jlink, in_length);
1088         if ((result != in_length) && (result != (in_length + 1)))
1089         {
1090                 LOG_ERROR("usb_bulk_read failed (requested=%d, result=%d)",
1091                                 in_length, result);
1092                 return ERROR_JTAG_DEVICE_ERROR;
1093         }
1094
1095         if (jlink_hw_jtag_version < 3)
1096                 return result;
1097
1098         int result2 = ERROR_OK;
1099         if (result == in_length)
1100         {
1101                 /* Must read the result from the EMU too */
1102                 result2 = jlink_usb_read_emu_result(jlink);
1103                 if (1 != result2)
1104                 {
1105                         LOG_ERROR("jlink_usb_read_emu_result retried requested = 1, "
1106                                         "result=%d, in_length=%i", result2, in_length);
1107                         /* Try again once, should only happen if (in_length%64 == 0) */
1108                         result2 = jlink_usb_read_emu_result(jlink);
1109                         if (1 != result2)
1110                         {
1111                                 LOG_ERROR("jlink_usb_read_emu_result failed "
1112                                         "(requested = 1, result=%d)", result2);
1113                                 return ERROR_JTAG_DEVICE_ERROR;
1114                         }
1115                 }
1116
1117                 /* Check the result itself */
1118                 result2 = usb_emu_result_buffer[0];
1119         }
1120         else
1121         {
1122                 /* Save the result, then remove it from return value */
1123                 result2 = usb_in_buffer[result--];
1124         }
1125
1126         if (result2)
1127         {
1128                 LOG_ERROR("jlink_usb_message failed with result=%d)", result2);
1129                 return ERROR_JTAG_DEVICE_ERROR;
1130         }
1131
1132         return result;
1133 }
1134
1135 /* calls the given usb_bulk_* function, allowing for the data to
1136  * trickle in with some timeouts  */
1137 static int usb_bulk_with_retries(
1138                 int (*f)(usb_dev_handle *, int, char *, int, int),
1139                 usb_dev_handle *dev, int ep,
1140                 char *bytes, int size, int timeout)
1141 {
1142         int tries = 3, count = 0;
1143
1144         while (tries && (count < size))
1145         {
1146                 int result = f(dev, ep, bytes + count, size - count, timeout);
1147                 if (result > 0)
1148                         count += result;
1149                 else if ((-ETIMEDOUT != result) || !--tries)
1150                         return result;
1151         }
1152         return count;
1153 }
1154
1155 static int wrap_usb_bulk_write(usb_dev_handle *dev, int ep,
1156                                char *buff, int size, int timeout)
1157 {
1158         /* usb_bulk_write() takes const char *buff */
1159         return usb_bulk_write(dev, ep, buff, size, timeout);
1160 }
1161
1162 static inline int usb_bulk_write_ex(usb_dev_handle *dev, int ep,
1163                 char *bytes, int size, int timeout)
1164 {
1165         return usb_bulk_with_retries(&wrap_usb_bulk_write,
1166                         dev, ep, bytes, size, timeout);
1167 }
1168
1169 static inline int usb_bulk_read_ex(usb_dev_handle *dev, int ep,
1170                 char *bytes, int size, int timeout)
1171 {
1172         return usb_bulk_with_retries(&usb_bulk_read,
1173                         dev, ep, bytes, size, timeout);
1174 }
1175
1176 /* Write data from out_buffer to USB. */
1177 static int jlink_usb_write(struct jlink *jlink, int out_length)
1178 {
1179         int result;
1180
1181         if (out_length > JLINK_OUT_BUFFER_SIZE)
1182         {
1183                 LOG_ERROR("jlink_write illegal out_length=%d (max=%d)",
1184                                 out_length, JLINK_OUT_BUFFER_SIZE);
1185                 return -1;
1186         }
1187
1188         result = usb_bulk_write_ex(jlink->usb_handle, jlink_write_ep,
1189                 (char *)usb_out_buffer, out_length, JLINK_USB_TIMEOUT);
1190
1191         DEBUG_JTAG_IO("jlink_usb_write, out_length = %d, result = %d",
1192                         out_length, result);
1193
1194 #ifdef _DEBUG_USB_COMMS_
1195         jlink_debug_buffer(usb_out_buffer, out_length);
1196 #endif
1197         return result;
1198 }
1199
1200 /* Read data from USB into in_buffer. */
1201 static int jlink_usb_read(struct jlink *jlink, int expected_size)
1202 {
1203         int result = usb_bulk_read_ex(jlink->usb_handle, jlink_read_ep,
1204                 (char *)usb_in_buffer, expected_size, JLINK_USB_TIMEOUT);
1205
1206         DEBUG_JTAG_IO("jlink_usb_read, result = %d", result);
1207
1208 #ifdef _DEBUG_USB_COMMS_
1209         jlink_debug_buffer(usb_in_buffer, result);
1210 #endif
1211         return result;
1212 }
1213
1214 /* Read the result from the previous EMU cmd into result_buffer. */
1215 static int jlink_usb_read_emu_result(struct jlink *jlink)
1216 {
1217         int result = usb_bulk_read_ex(jlink->usb_handle, jlink_read_ep,
1218                 (char *)usb_emu_result_buffer, 1 /* JLINK_EMU_RESULT_BUFFER_SIZE */,
1219                 JLINK_USB_TIMEOUT);
1220
1221         DEBUG_JTAG_IO("jlink_usb_read_result, result = %d", result);
1222
1223 #ifdef _DEBUG_USB_COMMS_
1224         jlink_debug_buffer(usb_emu_result_buffer, result);
1225 #endif
1226         return result;
1227 }
1228
1229 #ifdef _DEBUG_USB_COMMS_
1230 #define BYTES_PER_LINE  16
1231
1232 static void jlink_debug_buffer(uint8_t *buffer, int length)
1233 {
1234         char line[81];
1235         char s[4];
1236         int i;
1237         int j;
1238
1239         for (i = 0; i < length; i += BYTES_PER_LINE)
1240         {
1241                 snprintf(line, 5, "%04x", i);
1242                 for (j = i; j < i + BYTES_PER_LINE && j < length; j++)
1243                 {
1244                         snprintf(s, 4, " %02x", buffer[j]);
1245                         strcat(line, s);
1246                 }
1247                 LOG_DEBUG("%s", line);
1248         }
1249 }
1250 #endif