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