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