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