adaa64090353e53d1ea7aceffd46275d2029e550
[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 "usb_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  
40 http://www.segger.com/cms/admin/uploads/productDocs/RM08001_JLinkUSBProtocol.pdf
41  */
42
43 /*
44  * The default pid of the segger is 0x0101
45  * But when you change the USB Address it will also
46  *
47  * pid = ( usb_address > 0x4) ? 0x0101 : (0x101 + usb_address)
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 usb_dev_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         {
325         case JTAG_RUNTEST:   jlink_execute_runtest(cmd); break;
326         case JTAG_TLR_RESET: jlink_execute_statemove(cmd); break;
327         case JTAG_PATHMOVE:  jlink_execute_pathmove(cmd); break;
328         case JTAG_SCAN:      jlink_execute_scan(cmd); break;
329         case JTAG_RESET:     jlink_execute_reset(cmd); break;
330         case JTAG_SLEEP:     jlink_execute_sleep(cmd); break;
331         default:
332                 LOG_ERROR("BUG: unknown JTAG command type encountered");
333                 exit(-1);
334         }
335 }
336
337 static int jlink_execute_queue(void)
338 {
339         struct jtag_command *cmd = jtag_command_queue;
340
341         while (cmd != NULL)
342         {
343                 jlink_execute_command(cmd);
344                 cmd = cmd->next;
345         }
346
347         return jlink_tap_execute();
348 }
349
350 /* Sets speed in kHz. */
351 static int jlink_speed(int speed)
352 {
353         int result;
354
355         if (speed > JLINK_MAX_SPEED)
356         {
357                 LOG_INFO("reduce speed request: %dkHz to %dkHz maximum",
358                                 speed, JLINK_MAX_SPEED);
359                 speed = JLINK_MAX_SPEED;
360         }
361
362         /* check for RTCK setting */
363         if (speed == 0)
364                 speed = -1;
365
366         usb_out_buffer[0] = EMU_CMD_SET_SPEED;
367         usb_out_buffer[1] = (speed >> 0) & 0xff;
368         usb_out_buffer[2] = (speed >> 8) & 0xff;
369
370         result = jlink_usb_write(jlink_handle, 3);
371         if (result != 3)
372         {
373                 LOG_ERROR("J-Link setting speed failed (%d)", result);
374                 return ERROR_JTAG_DEVICE_ERROR;
375         }
376
377         return ERROR_OK;
378 }
379
380 static int jlink_speed_div(int speed, int* khz)
381 {
382         *khz = speed;
383
384         return ERROR_OK;
385 }
386
387 static int jlink_khz(int khz, int *jtag_speed)
388 {
389         *jtag_speed = khz;
390
391         return ERROR_OK;
392 }
393
394 static int jlink_init(void)
395 {
396         int i;
397
398         jlink_handle = jlink_usb_open();
399
400         if (jlink_handle == 0)
401         {
402                 LOG_ERROR("Cannot find jlink Interface! Please check "
403                                 "connection and permissions.");
404                 return ERROR_JTAG_INIT_FAILED;
405         }
406
407         /*
408          * The next three instructions were added after discovering a problem
409          * while using an oscilloscope.
410          * For the V8 SAM-ICE dongle (and likely other j-link device variants),
411          * the reset line to the target microprocessor was found to cycle only
412          * intermittently during emulator startup (even after encountering the
413          * downstream reset instruction later in the code).
414          * This was found to create two issues:
415          * 1) In general it is a bad practice to not reset a CPU to a known
416          * state when starting an emulator and
417          * 2) something critical happens inside the dongle when it does the
418          * first read following a new USB session.
419          * Keeping the processor in reset during the first read collecting
420          * version information seems to prevent errant
421          * "J-Link command EMU_CMD_VERSION failed" issues.
422          */
423
424         LOG_INFO("J-Link initialization started / target CPU reset initiated");
425         jlink_simple_command(EMU_CMD_HW_TRST0);
426         jlink_simple_command(EMU_CMD_HW_RESET0);
427         usleep(1000);
428
429         jlink_hw_jtag_version = 2;
430
431         if (jlink_get_version_info() == ERROR_OK)
432         {
433                 /* attempt to get status */
434                 jlink_get_status();
435         }
436
437         LOG_INFO("J-Link JTAG Interface ready");
438
439         jlink_reset(0, 0);
440         jtag_sleep(3000);
441         jlink_tap_init();
442
443         /* v5/6 jlink seems to have an issue if the first tap move
444          * is not divisible by 8, so we send a TLR on first power up */
445         for (i = 0; i < 8; i++) {
446                 jlink_tap_append_step(1, 0);
447         }
448         jlink_tap_execute();
449
450         return ERROR_OK;
451 }
452
453 static int jlink_quit(void)
454 {
455         jlink_usb_close(jlink_handle);
456         return ERROR_OK;
457 }
458
459 /***************************************************************************/
460 /* Queue command implementations */
461
462 static void jlink_end_state(tap_state_t state)
463 {
464         if (tap_is_state_stable(state))
465         {
466                 tap_set_end_state(state);
467         }
468         else
469         {
470                 LOG_ERROR("BUG: %i is not a valid end state", state);
471                 exit(-1);
472         }
473 }
474
475 /* Goes to the end state. */
476 static void jlink_state_move(void)
477 {
478         int i;
479         int tms = 0;
480         uint8_t tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
481         uint8_t tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
482
483         for (i = 0; i < tms_scan_bits; i++)
484         {
485                 tms = (tms_scan >> i) & 1;
486                 jlink_tap_append_step(tms, 0);
487         }
488
489         tap_set_state(tap_get_end_state());
490 }
491
492 static void jlink_path_move(int num_states, tap_state_t *path)
493 {
494         int i;
495
496         for (i = 0; i < num_states; i++)
497         {
498                 if (path[i] == tap_state_transition(tap_get_state(), false))
499                 {
500                         jlink_tap_append_step(0, 0);
501                 }
502                 else if (path[i] == tap_state_transition(tap_get_state(), true))
503                 {
504                         jlink_tap_append_step(1, 0);
505                 }
506                 else
507                 {
508                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
509                                         tap_state_name(tap_get_state()), tap_state_name(path[i]));
510                         exit(-1);
511                 }
512
513                 tap_set_state(path[i]);
514         }
515
516         tap_set_end_state(tap_get_state());
517 }
518
519 static void jlink_runtest(int num_cycles)
520 {
521         int i;
522
523         tap_state_t saved_end_state = tap_get_end_state();
524
525         jlink_tap_ensure_space(1,num_cycles + 16);
526
527         /* only do a state_move when we're not already in IDLE */
528         if (tap_get_state() != TAP_IDLE)
529         {
530                 jlink_end_state(TAP_IDLE);
531                 jlink_state_move();
532 //              num_cycles--;
533         }
534
535         /* execute num_cycles */
536         for (i = 0; i < num_cycles; i++)
537         {
538                 jlink_tap_append_step(0, 0);
539         }
540
541         /* finish in end_state */
542         jlink_end_state(saved_end_state);
543         if (tap_get_state() != tap_get_end_state())
544         {
545                 jlink_state_move();
546         }
547 }
548
549 static void jlink_scan(bool ir_scan, enum scan_type type, uint8_t *buffer,
550                 int scan_size, struct scan_command *command)
551 {
552         tap_state_t saved_end_state;
553
554         jlink_tap_ensure_space(1, scan_size + 16);
555
556         saved_end_state = tap_get_end_state();
557
558         /* Move to appropriate scan state */
559         jlink_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
560
561         /* Only move if we're not already there */
562         if (tap_get_state() != tap_get_end_state())
563                 jlink_state_move();
564
565         jlink_end_state(saved_end_state);
566
567         /* Scan */
568         jlink_tap_append_scan(scan_size, buffer, command);
569
570         /* We are in Exit1, go to Pause */
571         jlink_tap_append_step(0, 0);
572
573         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
574
575         if (tap_get_state() != tap_get_end_state())
576         {
577                 jlink_state_move();
578         }
579 }
580
581 static void jlink_reset(int trst, int srst)
582 {
583         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
584
585         /* Signals are active low */
586         if (srst == 0)
587         {
588                 jlink_simple_command(EMU_CMD_HW_RESET1);
589         }
590         if (srst == 1)
591         {
592                 jlink_simple_command(EMU_CMD_HW_RESET0);
593         }
594
595         if (trst == 1)
596         {
597                 jlink_simple_command(EMU_CMD_HW_TRST0);
598         }
599
600         if (trst == 0)
601         {
602                 jlink_simple_command(EMU_CMD_HW_TRST1);
603         }
604 }
605
606 static void jlink_simple_command(uint8_t command)
607 {
608         int result;
609
610         DEBUG_JTAG_IO("0x%02x", command);
611
612         usb_out_buffer[0] = command;
613         result = jlink_usb_write(jlink_handle, 1);
614
615         if (result != 1)
616         {
617                 LOG_ERROR("J-Link command 0x%02x failed (%d)", command, result);
618         }
619 }
620
621 static int jlink_get_status(void)
622 {
623         int result;
624
625         jlink_simple_command(EMU_CMD_GET_STATE);
626
627         result = jlink_usb_read(jlink_handle, 8);
628         if (result != 8)
629         {
630                 LOG_ERROR("J-Link command EMU_CMD_GET_STATE failed (%d)", result);
631                 return ERROR_JTAG_DEVICE_ERROR;
632         }
633
634         int vref = usb_in_buffer[0] + (usb_in_buffer[1] << 8);
635         LOG_INFO("Vref = %d.%d TCK = %d TDI = %d TDO = %d TMS = %d SRST = %d TRST = %d", \
636                 vref / 1000, vref % 1000, \
637                 usb_in_buffer[2], usb_in_buffer[3], usb_in_buffer[4], \
638                 usb_in_buffer[5], usb_in_buffer[6], usb_in_buffer[7]);
639
640         if (vref < 1500)
641                 LOG_ERROR("Vref too low. Check Target Power");
642
643         return ERROR_OK;
644 }
645
646 #define jlink_dump_printf(context, expr ...)    \
647         do {                                    \
648         if (context)                            \
649                 command_print(context, expr);   \
650         else                                    \
651                 LOG_INFO(expr);                 \
652         } while(0);
653
654
655 static void jlink_caps_dump(struct command_context *ctx)
656 {
657         int i;
658
659         jlink_dump_printf(ctx, "J-Link Capabilities");
660
661         for (i = 1; i < 31; i++)
662                 if (jlink_caps & (1 << i))
663                         jlink_dump_printf(ctx, "%s", jlink_cap_str[i]);
664 }
665
666 static void jlink_config_usb_address_dump(struct command_context *ctx, struct jlink_config *cfg)
667 {
668         if (!cfg)
669                 return;
670
671         jlink_dump_printf(ctx, "USB-Address: 0x%x", cfg->usb_address);
672 }
673
674 static void jlink_config_kickstart_dump(struct command_context *ctx, struct jlink_config *cfg)
675 {
676         if (!cfg)
677                 return;
678
679         jlink_dump_printf(ctx, "Kickstart power on JTAG-pin 19: 0x%x",
680                 cfg->kickstart_power_on_jtag_pin_19);
681 }
682
683 static void jlink_config_mac_address_dump(struct command_context *ctx, struct jlink_config *cfg)
684 {
685         if (!cfg)
686                 return;
687
688         jlink_dump_printf(ctx, "MAC Address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x",
689                 cfg->mac_address[5], cfg->mac_address[4],
690                 cfg->mac_address[3], cfg->mac_address[2],
691                 cfg->mac_address[1], cfg->mac_address[0]);
692 }
693
694 static void jlink_config_ip_dump(struct command_context *ctx, struct jlink_config *cfg)
695 {
696         if (!cfg)
697                 return;
698
699         jlink_dump_printf(ctx, "IP Address: %d.%d.%d.%d",
700                 cfg->ip_address[3], cfg->ip_address[2],
701                 cfg->ip_address[1], cfg->ip_address[0]);
702         jlink_dump_printf(ctx, "Subnet Mask: %d.%d.%d.%d",
703                 cfg->subnet_mask[3], cfg->subnet_mask[2],
704                 cfg->subnet_mask[1], cfg->subnet_mask[0]);
705 }
706
707 static void jlink_config_dump(struct command_context *ctx, struct jlink_config *cfg)
708 {
709         if (!cfg)
710                 return;
711
712         jlink_dump_printf(ctx, "J-Link configuration");
713         jlink_config_usb_address_dump(ctx, cfg);
714         jlink_config_kickstart_dump(ctx, cfg);
715
716         if (jlink_hw_type == JLINK_HW_TYPE_JLINK_PRO)
717         {
718                 jlink_config_ip_dump(ctx, cfg);
719                 jlink_config_mac_address_dump(ctx, cfg);
720         }
721 }
722
723 static int jlink_get_config(struct jlink_config *cfg)
724 {
725         int result;
726         int size = sizeof(struct jlink_config);
727
728         jlink_simple_command(EMU_CMD_READ_CONFIG);
729
730         result = jlink_usb_read(jlink_handle, size);
731         if (size != result)
732         {
733                 LOG_ERROR("jlink_usb_read failed (requested=%d, result=%d)", size, result);
734                 return ERROR_FAIL;
735         }
736
737         memcpy(cfg, usb_in_buffer, size);
738
739         /*
740          * Section 4.2.4 IN-transaction
741          * read dummy 0-byte packet
742          */
743         jlink_usb_read(jlink_handle, 1);
744
745         return ERROR_OK;
746 }
747
748 static int jlink_set_config(struct jlink_config *cfg)
749 {
750         int result;
751         int size = sizeof(struct jlink_config);
752
753         jlink_simple_command(EMU_CMD_WRITE_CONFIG);
754
755         memcpy(usb_out_buffer, cfg, size);
756
757         result = jlink_usb_write(jlink_handle, size);
758         if (result != size)
759         {
760                 LOG_ERROR("jlink_usb_write failed (requested=%d, result=%d)", 256, result);
761                 return ERROR_FAIL;
762         }
763
764         return ERROR_OK;
765 }
766
767 static int jlink_get_version_info(void)
768 {
769         int result;
770         int len;
771         uint32_t jlink_max_size;
772
773         /* query hardware version */
774         jlink_simple_command(EMU_CMD_VERSION);
775
776         result = jlink_usb_read(jlink_handle, 2);
777         if (2 != result)
778         {
779                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)", result);
780                 return ERROR_JTAG_DEVICE_ERROR;
781         }
782
783         len = buf_get_u32(usb_in_buffer, 0, 16);
784         if (len > JLINK_IN_BUFFER_SIZE)
785         {
786                 LOG_ERROR("J-Link command EMU_CMD_VERSION impossible return length 0x%0x", len);
787                 len = JLINK_IN_BUFFER_SIZE;
788         }
789
790         result = jlink_usb_read(jlink_handle, len);
791         if (result != len)
792         {
793                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)", result);
794                 return ERROR_JTAG_DEVICE_ERROR;
795         }
796
797         usb_in_buffer[result] = 0;
798         LOG_INFO("%s", (char *)usb_in_buffer);
799
800         /* query hardware capabilities */
801         jlink_simple_command(EMU_CMD_GET_CAPS);
802
803         result = jlink_usb_read(jlink_handle, 4);
804         if (4 != result)
805         {
806                 LOG_ERROR("J-Link command EMU_CMD_GET_CAPS failed (%d)", result);
807                 return ERROR_JTAG_DEVICE_ERROR;
808         }
809
810         jlink_caps = buf_get_u32(usb_in_buffer, 0, 32);
811         LOG_INFO("J-Link caps 0x%x", (unsigned)jlink_caps);
812
813         if (jlink_caps & (1 << EMU_CAP_GET_HW_VERSION))
814         {
815                 /* query hardware version */
816                 jlink_simple_command(EMU_CMD_GET_HW_VERSION);
817
818                 result = jlink_usb_read(jlink_handle, 4);
819                 if (4 != result)
820                 {
821                         LOG_ERROR("J-Link command EMU_CMD_GET_HW_VERSION failed (%d)", result);
822                         return ERROR_JTAG_DEVICE_ERROR;
823                 }
824
825                 uint32_t jlink_hw_version = buf_get_u32(usb_in_buffer, 0, 32);
826                 uint32_t major_revision = (jlink_hw_version / 10000) % 100;
827                 jlink_hw_type = (jlink_hw_version / 1000000) % 100;
828                 if (major_revision >= 5)
829                         jlink_hw_jtag_version = 3;
830
831                 LOG_INFO("J-Link hw version %i", (int)jlink_hw_version);
832
833                 if (jlink_hw_type >= JLINK_HW_TYPE_MAX)
834                         LOG_INFO("J-Link hw type uknown 0x%x", jlink_hw_type);
835                 else
836                         LOG_INFO("J-Link hw type %s", jlink_hw_type_str[jlink_hw_type]);
837         }
838
839         if (jlink_caps & (1 << EMU_CAP_GET_MAX_BLOCK_SIZE))
840         {
841                 /* query hardware maximum memory block */
842                 jlink_simple_command(EMU_CMD_GET_MAX_MEM_BLOCK);
843
844                 result = jlink_usb_read(jlink_handle, 4);
845                 if (4 != result)
846                 {
847                         LOG_ERROR("J-Link command EMU_CMD_GET_MAX_MEM_BLOCK failed (%d)", result);
848                         return ERROR_JTAG_DEVICE_ERROR;
849                 }
850
851                 jlink_max_size = buf_get_u32(usb_in_buffer, 0, 32);
852                 LOG_INFO("J-Link max mem block %i", (int)jlink_max_size);
853         }
854
855         if (jlink_caps & (1 << EMU_CAP_READ_CONFIG))
856         {
857                 if (jlink_get_config(&jlink_cfg) != ERROR_OK)
858                         return ERROR_JTAG_DEVICE_ERROR;
859
860                 jlink_config_dump(NULL, &jlink_cfg);
861         }
862
863         return ERROR_OK;
864 }
865
866 COMMAND_HANDLER(jlink_pid_command)
867 {
868         if (CMD_ARGC != 1)
869         {
870                 LOG_ERROR("Need exactly one argument to jlink_pid");
871                 return ERROR_FAIL;
872         }
873
874         pids[0] = strtoul(CMD_ARGV[0], NULL, 16);
875         pids[1] = 0;
876         vids[1] = 0;
877
878         return ERROR_OK;
879 }
880
881 COMMAND_HANDLER(jlink_handle_jlink_info_command)
882 {
883         if (jlink_get_version_info() == ERROR_OK)
884         {
885                 /* attempt to get status */
886                 jlink_get_status();
887         }
888
889         return ERROR_OK;
890 }
891
892 COMMAND_HANDLER(jlink_handle_jlink_caps_command)
893 {
894         jlink_caps_dump(CMD_CTX);
895
896         return ERROR_OK;
897 }
898
899 COMMAND_HANDLER(jlink_handle_jlink_hw_jtag_command)
900 {
901         switch (CMD_ARGC) {
902         case 0:
903                 command_print(CMD_CTX, "J-Link hw jtag  %i", jlink_hw_jtag_version);
904                 break;
905         case 1: {
906                 int request_version = atoi(CMD_ARGV[0]);
907                 switch (request_version) {
908                 case 2: case 3:
909                         jlink_hw_jtag_version = request_version;
910                         break;
911                 default:
912                         return ERROR_COMMAND_SYNTAX_ERROR;
913                 }
914                 break;
915         }
916         default:
917                 return ERROR_COMMAND_SYNTAX_ERROR;
918         }
919
920         return ERROR_OK;
921 }
922
923 COMMAND_HANDLER(jlink_handle_jlink_kickstart_command)
924 {
925         uint32_t kickstart;
926
927         if (CMD_ARGC < 1)
928         {
929                 jlink_config_kickstart_dump(CMD_CTX, &jlink_cfg);
930                 return ERROR_OK;
931         }
932
933         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], kickstart);
934
935         jlink_cfg.kickstart_power_on_jtag_pin_19 = kickstart;
936         return ERROR_OK;
937 }
938
939 COMMAND_HANDLER(jlink_handle_jlink_mac_address_command)
940 {
941         uint8_t addr[6];
942         int i;
943         char *e;
944         const char *str;
945
946         if (CMD_ARGC < 1)
947         {
948                 jlink_config_mac_address_dump(CMD_CTX, &jlink_cfg);
949                 return ERROR_OK;
950         }
951
952         str = CMD_ARGV[0];
953
954         if ((strlen(str) != 17) || (str[2] != ':' || str[5] != ':' || str[8] != ':' ||
955                 str[11] != ':' || str[14] != ':'))
956         {
957                 command_print(CMD_CTX, "ethaddr miss format ff:ff:ff:ff:ff:ff");
958                 return ERROR_COMMAND_SYNTAX_ERROR;
959         }
960
961         for (i = 5; i >= 0; i--)
962         {
963                 addr[i] = strtoul(str, &e, 16);
964                 str = e + 1;
965         }
966
967         if (!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5]))
968         {
969                 command_print(CMD_CTX, "invalid it's zero mac_address");
970                 return ERROR_COMMAND_SYNTAX_ERROR;
971         }
972
973         if (!(0x01 & addr[0]))
974         {
975                 command_print(CMD_CTX, "invalid it's a multicat mac_address");
976                 return ERROR_COMMAND_SYNTAX_ERROR;
977         }
978
979         memcpy(jlink_cfg.mac_address, addr, sizeof(addr));
980
981         return ERROR_OK;
982 }
983
984 static int string_to_ip(const char *s, uint8_t *ip, int *pos)
985 {
986         uint8_t lip[4];
987         char *e;
988         const char *s_save = s;
989         int i;
990
991         if (!s)
992                 return -EINVAL;
993
994         for (i = 0; i < 4; i++) {
995                 lip[i] = strtoul(s, &e, 10);
996
997                 if (*e != '.' && i != 3)
998                         return -EINVAL;
999
1000                 s = e + 1;
1001         }
1002
1003         *pos = e - s_save;
1004
1005         memcpy(ip, lip, sizeof(lip));
1006         return ERROR_OK;
1007 }
1008
1009 static void cpy_ip(uint8_t *dst, uint8_t *src)
1010 {
1011         int i, j;
1012
1013         for (i = 0, j = 3; i < 4; i++, j--)
1014                 dst[i] = src[j];
1015 }
1016
1017 COMMAND_HANDLER(jlink_handle_jlink_ip_command)
1018 {
1019         uint32_t ip_address;
1020         uint32_t subnet_mask = 0;
1021         int i, len;
1022         int ret;
1023         uint8_t subnet_bits = 24;
1024
1025         if (CMD_ARGC < 1)
1026         {
1027                 jlink_config_ip_dump(CMD_CTX, &jlink_cfg);
1028                 return ERROR_OK;
1029         }
1030
1031         ret = string_to_ip(CMD_ARGV[0], (uint8_t*)&ip_address, &i);
1032         if (ret != ERROR_OK)
1033                 return ret;
1034
1035         len = strlen(CMD_ARGV[0]);
1036
1037         /* check for this format A.B.C.D/E */
1038
1039         if (i < len)
1040         {
1041                 if (CMD_ARGV[0][i] != '/')
1042                         return ERROR_COMMAND_SYNTAX_ERROR;
1043
1044                 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[0] + i + 1, subnet_bits);
1045         }
1046         else
1047         {
1048                 if (CMD_ARGC > 1)
1049                 {
1050                         ret = string_to_ip(CMD_ARGV[1], (uint8_t*)&subnet_mask, &i);
1051                         if (ret != ERROR_OK)
1052                                 return ret;
1053                 }
1054         }
1055
1056         if (!subnet_mask)
1057                 subnet_mask = (uint32_t)(subnet_bits < 32 ?
1058                                 ((1ULL << subnet_bits) -1) : 0xffffffff);
1059
1060         cpy_ip(jlink_cfg.ip_address, (uint8_t*)&ip_address);
1061         cpy_ip(jlink_cfg.subnet_mask, (uint8_t*)&subnet_mask);
1062
1063         return ERROR_OK;
1064 }
1065
1066 COMMAND_HANDLER(jlink_handle_jlink_reset_command)
1067 {
1068         memset(&jlink_cfg, 0xff, sizeof(jlink_cfg));
1069         return ERROR_OK;
1070 }
1071
1072 COMMAND_HANDLER(jlink_handle_jlink_save_command)
1073 {
1074         if (!(jlink_caps & (1 << EMU_CAP_WRITE_CONFIG)))
1075         {
1076                 command_print(CMD_CTX, "J-Link write emulator configuration not supported");
1077                 return ERROR_OK;
1078         }
1079
1080         command_print(CMD_CTX, "The J-Link need to be unpluged and repluged ta have the config effective");
1081         return jlink_set_config(&jlink_cfg);
1082 }
1083
1084 COMMAND_HANDLER(jlink_handle_jlink_usb_address_command)
1085 {
1086         uint32_t address;
1087
1088         if (CMD_ARGC < 1)
1089         {
1090                 jlink_config_usb_address_dump(CMD_CTX, &jlink_cfg);
1091                 return ERROR_OK;
1092         }
1093
1094         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], address);
1095
1096         if (address > 0x3 && address != 0xff)
1097         {
1098                 command_print(CMD_CTX, "USB Address must be between 0x00 and 0x03 or 0xff");
1099                 return ERROR_COMMAND_SYNTAX_ERROR;
1100         }
1101
1102         jlink_cfg.usb_address = address;
1103         return ERROR_OK;
1104 }
1105
1106 COMMAND_HANDLER(jlink_handle_jlink_config_command)
1107 {
1108         struct jlink_config cfg;
1109         int ret = ERROR_OK;
1110
1111         if (CMD_ARGC == 0)
1112         {
1113                 if (!(jlink_caps & (1 << EMU_CAP_READ_CONFIG)))
1114                 {
1115                         command_print(CMD_CTX, "J-Link read emulator configuration not supported");
1116                         goto exit;
1117                 }
1118
1119                 ret = jlink_get_config(&cfg);
1120
1121                 if ( ret != ERROR_OK)
1122                         command_print(CMD_CTX, "J-Link read emulator configuration failled");
1123                 else
1124                         jlink_config_dump(CMD_CTX, &jlink_cfg);
1125         }
1126
1127 exit:
1128         return ret;
1129 }
1130
1131 static const struct command_registration jlink_config_subcommand_handlers[] = {
1132         {
1133                 .name = "kickstart",
1134                 .handler = &jlink_handle_jlink_kickstart_command,
1135                 .mode = COMMAND_EXEC,
1136                 .help = "set Kickstart power on JTAG-pin 19.",
1137                 .usage = "[val]",
1138         },
1139         {
1140                 .name = "mac_address",
1141                 .handler = &jlink_handle_jlink_mac_address_command,
1142                 .mode = COMMAND_EXEC,
1143                 .help = "set the MAC Address",
1144                 .usage = "[ff:ff:ff:ff:ff:ff]",
1145         },
1146         {
1147                 .name = "ip",
1148                 .handler = &jlink_handle_jlink_ip_command,
1149                 .mode = COMMAND_EXEC,
1150                 .help = "set the ip address of the J-Link Pro, "
1151                         "where A.B.C.D is the ip, "
1152                         "E the bit of the subnet mask, "
1153                         "F.G.H.I the subnet mask",
1154                 .usage = "[A.B.C.D[/E] [F.G.H.I]]",
1155         },
1156         {
1157                 .name = "reset",
1158                 .handler = &jlink_handle_jlink_reset_command,
1159                 .mode = COMMAND_EXEC,
1160                 .help = "reset the current config",
1161         },
1162         {
1163                 .name = "save",
1164                 .handler = &jlink_handle_jlink_save_command,
1165                 .mode = COMMAND_EXEC,
1166                 .help = "save the current config",
1167         },
1168         {
1169                 .name = "usb_address",
1170                 .handler = &jlink_handle_jlink_usb_address_command,
1171                 .mode = COMMAND_EXEC,
1172                 .help = "set the USB-Address, "
1173                         "This will change the product id",
1174                 .usage = "[0x00 to 0x03 or 0xff]",
1175         },
1176         COMMAND_REGISTRATION_DONE
1177 };
1178
1179 static const struct command_registration jlink_subcommand_handlers[] = {
1180         {
1181                 .name = "caps",
1182                 .handler = &jlink_handle_jlink_caps_command,
1183                 .mode = COMMAND_EXEC,
1184                 .help = "show jlink capabilities",
1185         },
1186         {
1187                 .name = "info",
1188                 .handler = &jlink_handle_jlink_info_command,
1189                 .mode = COMMAND_EXEC,
1190                 .help = "show jlink info",
1191         },
1192         {
1193                 .name = "hw_jtag",
1194                 .handler = &jlink_handle_jlink_hw_jtag_command,
1195                 .mode = COMMAND_EXEC,
1196                 .help = "access J-Link HW JTAG command version",
1197                 .usage = "[2|3]",
1198         },
1199         {
1200                 .name = "config",
1201                 .handler = &jlink_handle_jlink_config_command,
1202                 .mode = COMMAND_EXEC,
1203                 .help = "access J-Link configuration, "
1204                         "if no argument this will dump the config",
1205                 .chain = jlink_config_subcommand_handlers,
1206         },
1207         {
1208                 .name = "pid",
1209                 .handler = &jlink_pid_command,
1210                 .mode = COMMAND_CONFIG,
1211                 .help = "set the pid of the interface we want to use",
1212         },
1213         COMMAND_REGISTRATION_DONE
1214 };
1215
1216 static const struct command_registration jlink_command_handlers[] = {
1217         {
1218                 .name = "jlink",
1219                 .mode = COMMAND_ANY,
1220                 .help = "perform jlink management",
1221                 .chain = jlink_subcommand_handlers,
1222         },
1223         COMMAND_REGISTRATION_DONE
1224 };
1225
1226 struct jtag_interface jlink_interface = {
1227         .name = "jlink",
1228         .commands = jlink_command_handlers,
1229
1230         .execute_queue = jlink_execute_queue,
1231         .speed = jlink_speed,
1232         .speed_div = jlink_speed_div,
1233         .khz = jlink_khz,
1234         .init = jlink_init,
1235         .quit = jlink_quit,
1236 };
1237
1238 /***************************************************************************/
1239 /* J-Link tap functions */
1240
1241
1242 static unsigned tap_length = 0;
1243 static uint8_t tms_buffer[JLINK_TAP_BUFFER_SIZE];
1244 static uint8_t tdi_buffer[JLINK_TAP_BUFFER_SIZE];
1245 static uint8_t tdo_buffer[JLINK_TAP_BUFFER_SIZE];
1246
1247 struct pending_scan_result {
1248         int first;      /* First bit position in tdo_buffer to read */
1249         int length; /* Number of bits to read */
1250         struct scan_command *command; /* Corresponding scan command */
1251         uint8_t *buffer;
1252 };
1253
1254 #define MAX_PENDING_SCAN_RESULTS 256
1255
1256 static int pending_scan_results_length;
1257 static struct pending_scan_result pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
1258
1259 static void jlink_tap_init(void)
1260 {
1261         tap_length = 0;
1262         pending_scan_results_length = 0;
1263 }
1264
1265 static void jlink_tap_ensure_space(int scans, int bits)
1266 {
1267         int available_scans = MAX_PENDING_SCAN_RESULTS - pending_scan_results_length;
1268         int available_bits = JLINK_TAP_BUFFER_SIZE * 8 - tap_length - 32;
1269
1270         if (scans > available_scans || bits > available_bits)
1271         {
1272                 jlink_tap_execute();
1273         }
1274 }
1275
1276 static void jlink_tap_append_step(int tms, int tdi)
1277 {
1278         int index_var = tap_length / 8;
1279
1280         if (index_var >= JLINK_TAP_BUFFER_SIZE)
1281         {
1282                 LOG_ERROR("jlink_tap_append_step: overflow");
1283                 *(uint32_t *)0xFFFFFFFF = 0;
1284                 exit(-1);
1285         }
1286
1287         int bit_index = tap_length % 8;
1288         uint8_t bit = 1 << bit_index;
1289
1290         // we do not pad TMS, so be sure to initialize all bits
1291         if (0 == bit_index)
1292         {
1293                 tms_buffer[index_var] = tdi_buffer[index_var] = 0;
1294         }
1295
1296         if (tms)
1297                 tms_buffer[index_var] |= bit;
1298         else
1299                 tms_buffer[index_var] &= ~bit;
1300
1301         if (tdi)
1302                 tdi_buffer[index_var] |= bit;
1303         else
1304                 tdi_buffer[index_var] &= ~bit;
1305
1306         tap_length++;
1307 }
1308
1309 static void jlink_tap_append_scan(int length, uint8_t *buffer,
1310                 struct scan_command *command)
1311 {
1312         struct pending_scan_result *pending_scan_result =
1313                 &pending_scan_results_buffer[pending_scan_results_length];
1314         int i;
1315
1316         pending_scan_result->first = tap_length;
1317         pending_scan_result->length = length;
1318         pending_scan_result->command = command;
1319         pending_scan_result->buffer = buffer;
1320
1321         for (i = 0; i < length; i++)
1322         {
1323                 int tms = (i < (length - 1)) ? 0 : 1;
1324                 int tdi = (buffer[i / 8] & (1 << (i % 8))) != 0;
1325                 jlink_tap_append_step(tms, tdi);
1326         }
1327         pending_scan_results_length++;
1328 }
1329
1330 /* Pad and send a tap sequence to the device, and receive the answer.
1331  * For the purpose of padding we assume that we are in idle or pause state. */
1332 static int jlink_tap_execute(void)
1333 {
1334         int byte_length;
1335         int i;
1336         int result;
1337
1338         if (!tap_length)
1339                 return ERROR_OK;
1340
1341         /* JLink returns an extra NULL in packet when size of incoming
1342          * message is a multiple of 64, creates problems with USB comms.
1343          * WARNING: This will interfere with tap state counting. */
1344         while ((DIV_ROUND_UP(tap_length, 8) % 64) == 0)
1345         {
1346                 jlink_tap_append_step((tap_get_state() == TAP_RESET) ? 1 : 0, 0);
1347         }
1348
1349         // number of full bytes (plus one if some would be left over)
1350         byte_length = DIV_ROUND_UP(tap_length, 8);
1351
1352         bool use_jtag3 = jlink_hw_jtag_version >= 3;
1353         usb_out_buffer[0] = use_jtag3 ? EMU_CMD_HW_JTAG3 : EMU_CMD_HW_JTAG2;
1354         usb_out_buffer[1] = 0;
1355         usb_out_buffer[2] = (tap_length >> 0) & 0xff;
1356         usb_out_buffer[3] = (tap_length >> 8) & 0xff;
1357         memcpy(usb_out_buffer + 4, tms_buffer, byte_length);
1358         memcpy(usb_out_buffer + 4 + byte_length, tdi_buffer, byte_length);
1359
1360         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
1361                         tap_length, jlink_last_state);
1362
1363         result = jlink_usb_message(jlink_handle, 4 + 2 * byte_length, byte_length);
1364         if (result != byte_length)
1365         {
1366                 LOG_ERROR("jlink_tap_execute, wrong result %d (expected %d)",
1367                                 result, byte_length);
1368                 jlink_tap_init();
1369                 return ERROR_JTAG_QUEUE_FAILED;
1370         }
1371
1372         memcpy(tdo_buffer, usb_in_buffer, byte_length);
1373
1374         for (i = 0; i < pending_scan_results_length; i++)
1375         {
1376                 struct pending_scan_result *pending_scan_result = &pending_scan_results_buffer[i];
1377                 uint8_t *buffer = pending_scan_result->buffer;
1378                 int length = pending_scan_result->length;
1379                 int first = pending_scan_result->first;
1380                 struct scan_command *command = pending_scan_result->command;
1381
1382                 /* Copy to buffer */
1383                 buf_set_buf(tdo_buffer, first, buffer, 0, length);
1384
1385                 DEBUG_JTAG_IO("pending scan result, length = %d", length);
1386
1387                 jlink_debug_buffer(buffer, DIV_ROUND_UP(length, 8));
1388
1389                 if (jtag_read_buffer(buffer, command) != ERROR_OK)
1390                 {
1391                         jlink_tap_init();
1392                         return ERROR_JTAG_QUEUE_FAILED;
1393                 }
1394
1395                 if (pending_scan_result->buffer != NULL)
1396                 {
1397                         free(pending_scan_result->buffer);
1398                 }
1399         }
1400
1401         jlink_tap_init();
1402         return ERROR_OK;
1403 }
1404
1405 /*****************************************************************************/
1406 /* JLink USB low-level functions */
1407
1408 static struct jlink* jlink_usb_open()
1409 {
1410         usb_init();
1411
1412         struct usb_dev_handle *dev;
1413         if (jtag_usb_open(vids, pids, &dev) != ERROR_OK)
1414                 return NULL;
1415
1416         /* BE ***VERY CAREFUL*** ABOUT MAKING CHANGES IN THIS
1417          * AREA!!!!!!!!!!!  The behavior of libusb is not completely
1418          * consistent across Windows, Linux, and Mac OS X platforms.
1419          * The actions taken in the following compiler conditionals may
1420          * not agree with published documentation for libusb, but were
1421          * found to be necessary through trials and tribulations.  Even
1422          * little tweaks can break one or more platforms, so if you do
1423          * make changes test them carefully on all platforms before
1424          * committing them!
1425          */
1426
1427 #if IS_WIN32 == 0
1428
1429         usb_reset(dev);
1430
1431 #if IS_DARWIN == 0
1432
1433         int timeout = 5;
1434         /* reopen jlink after usb_reset
1435          * on win32 this may take a second or two to re-enumerate */
1436         int retval;
1437         while ((retval = jtag_usb_open(vids, pids, &dev)) != ERROR_OK)
1438         {
1439                 usleep(1000);
1440                 timeout--;
1441                 if (!timeout) {
1442                         break;
1443                 }
1444         }
1445         if (ERROR_OK != retval)
1446                 return NULL;
1447 #endif
1448
1449 #endif
1450
1451         /* usb_set_configuration required under win32 */
1452         struct usb_device *udev = usb_device(dev);
1453         usb_set_configuration(dev, udev->config[0].bConfigurationValue);
1454         usb_claim_interface(dev, 0);
1455
1456 #if 0
1457         /*
1458          * This makes problems under Mac OS X. And is not needed
1459          * under Windows. Hopefully this will not break a linux build
1460          */
1461         usb_set_altinterface(result->usb_handle, 0);
1462 #endif
1463         struct usb_interface *iface = udev->config->interface;
1464         struct usb_interface_descriptor *desc = iface->altsetting;
1465         for (int i = 0; i < desc->bNumEndpoints; i++)
1466         {
1467                 uint8_t epnum = desc->endpoint[i].bEndpointAddress;
1468                 bool is_input = epnum & 0x80;
1469                 LOG_DEBUG("usb ep %s %02x", is_input ? "in" : "out", epnum);
1470                 if (is_input)
1471                         jlink_read_ep = epnum;
1472                 else
1473                         jlink_write_ep = epnum;
1474         }
1475
1476         struct jlink *result = malloc(sizeof(struct jlink));
1477         result->usb_handle = dev;
1478         return result;
1479 }
1480
1481 static void jlink_usb_close(struct jlink *jlink)
1482 {
1483         usb_close(jlink->usb_handle);
1484         free(jlink);
1485 }
1486
1487 /* Send a message and receive the reply. */
1488 static int jlink_usb_message(struct jlink *jlink, int out_length, int in_length)
1489 {
1490         int result;
1491
1492         result = jlink_usb_write(jlink, out_length);
1493         if (result != out_length)
1494         {
1495                 LOG_ERROR("usb_bulk_write failed (requested=%d, result=%d)",
1496                                 out_length, result);
1497                 return ERROR_JTAG_DEVICE_ERROR;
1498         }
1499
1500         result = jlink_usb_read(jlink, in_length);
1501         if ((result != in_length) && (result != (in_length + 1)))
1502         {
1503                 LOG_ERROR("usb_bulk_read failed (requested=%d, result=%d)",
1504                                 in_length, result);
1505                 return ERROR_JTAG_DEVICE_ERROR;
1506         }
1507
1508         if (jlink_hw_jtag_version < 3)
1509                 return result;
1510
1511         int result2 = ERROR_OK;
1512         if (result == in_length)
1513         {
1514                 /* Must read the result from the EMU too */
1515                 result2 = jlink_usb_read_emu_result(jlink);
1516                 if (1 != result2)
1517                 {
1518                         LOG_ERROR("jlink_usb_read_emu_result retried requested = 1, "
1519                                         "result=%d, in_length=%i", result2, in_length);
1520                         /* Try again once, should only happen if (in_length%64 == 0) */
1521                         result2 = jlink_usb_read_emu_result(jlink);
1522                         if (1 != result2)
1523                         {
1524                                 LOG_ERROR("jlink_usb_read_emu_result failed "
1525                                         "(requested = 1, result=%d)", result2);
1526                                 return ERROR_JTAG_DEVICE_ERROR;
1527                         }
1528                 }
1529
1530                 /* Check the result itself */
1531                 result2 = usb_emu_result_buffer[0];
1532         }
1533         else
1534         {
1535                 /* Save the result, then remove it from return value */
1536                 result2 = usb_in_buffer[result--];
1537         }
1538
1539         if (result2)
1540         {
1541                 LOG_ERROR("jlink_usb_message failed with result=%d)", result2);
1542                 return ERROR_JTAG_DEVICE_ERROR;
1543         }
1544
1545         return result;
1546 }
1547
1548 /* calls the given usb_bulk_* function, allowing for the data to
1549  * trickle in with some timeouts  */
1550 static int usb_bulk_with_retries(
1551                 int (*f)(usb_dev_handle *, int, char *, int, int),
1552                 usb_dev_handle *dev, int ep,
1553                 char *bytes, int size, int timeout)
1554 {
1555         int tries = 3, count = 0;
1556
1557         while (tries && (count < size))
1558         {
1559                 int result = f(dev, ep, bytes + count, size - count, timeout);
1560                 if (result > 0)
1561                         count += result;
1562                 else if ((-ETIMEDOUT != result) || !--tries)
1563                         return result;
1564         }
1565         return count;
1566 }
1567
1568 static int wrap_usb_bulk_write(usb_dev_handle *dev, int ep,
1569                                char *buff, int size, int timeout)
1570 {
1571         /* usb_bulk_write() takes const char *buff */
1572         return usb_bulk_write(dev, ep, buff, size, timeout);
1573 }
1574
1575 static inline int usb_bulk_write_ex(usb_dev_handle *dev, int ep,
1576                 char *bytes, int size, int timeout)
1577 {
1578         return usb_bulk_with_retries(&wrap_usb_bulk_write,
1579                         dev, ep, bytes, size, timeout);
1580 }
1581
1582 static inline int usb_bulk_read_ex(usb_dev_handle *dev, int ep,
1583                 char *bytes, int size, int timeout)
1584 {
1585         return usb_bulk_with_retries(&usb_bulk_read,
1586                         dev, ep, bytes, size, timeout);
1587 }
1588
1589 /* Write data from out_buffer to USB. */
1590 static int jlink_usb_write(struct jlink *jlink, int out_length)
1591 {
1592         int result;
1593
1594         if (out_length > JLINK_OUT_BUFFER_SIZE)
1595         {
1596                 LOG_ERROR("jlink_write illegal out_length=%d (max=%d)",
1597                                 out_length, JLINK_OUT_BUFFER_SIZE);
1598                 return -1;
1599         }
1600
1601         result = usb_bulk_write_ex(jlink->usb_handle, jlink_write_ep,
1602                 (char *)usb_out_buffer, out_length, JLINK_USB_TIMEOUT);
1603
1604         DEBUG_JTAG_IO("jlink_usb_write, out_length = %d, result = %d",
1605                         out_length, result);
1606
1607         jlink_debug_buffer(usb_out_buffer, out_length);
1608         return result;
1609 }
1610
1611 /* Read data from USB into in_buffer. */
1612 static int jlink_usb_read(struct jlink *jlink, int expected_size)
1613 {
1614         int result = usb_bulk_read_ex(jlink->usb_handle, jlink_read_ep,
1615                 (char *)usb_in_buffer, expected_size, JLINK_USB_TIMEOUT);
1616
1617         DEBUG_JTAG_IO("jlink_usb_read, result = %d", result);
1618
1619         jlink_debug_buffer(usb_in_buffer, result);
1620         return result;
1621 }
1622
1623 /* Read the result from the previous EMU cmd into result_buffer. */
1624 static int jlink_usb_read_emu_result(struct jlink *jlink)
1625 {
1626         int result = usb_bulk_read_ex(jlink->usb_handle, jlink_read_ep,
1627                 (char *)usb_emu_result_buffer, 1 /* JLINK_EMU_RESULT_BUFFER_SIZE */,
1628                 JLINK_USB_TIMEOUT);
1629
1630         DEBUG_JTAG_IO("jlink_usb_read_result, result = %d", result);
1631
1632         jlink_debug_buffer(usb_emu_result_buffer, result);
1633         return result;
1634 }
1635
1636 #ifdef _DEBUG_USB_COMMS_
1637 #define BYTES_PER_LINE  16
1638
1639 static void jlink_debug_buffer(uint8_t *buffer, int length)
1640 {
1641         char line[81];
1642         char s[4];
1643         int i;
1644         int j;
1645
1646         for (i = 0; i < length; i += BYTES_PER_LINE)
1647         {
1648                 snprintf(line, 5, "%04x", i);
1649                 for (j = i; j < i + BYTES_PER_LINE && j < length; j++)
1650                 {
1651                         snprintf(s, 4, " %02x", buffer[j]);
1652                         strcat(line, s);
1653                 }
1654                 LOG_DEBUG("%s", line);
1655         }
1656 }
1657 #endif