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