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