]> git.sur5r.net Git - openocd/blob - src/jtag/jlink.c
98e3111072d0add7ebbe1733dd150449e445766c
[openocd] / src / jtag / jlink.c
1 /***************************************************************************
2  *   Copyright (C) 2007 by Juergen Stuber <juergen@jstuber.net>            *
3  *   based on Dominic Rath's and Benedikt Sauter's usbprog.c               *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include "replacements.h"
29
30 #include "jtag.h"
31
32 #include <usb.h>
33 #include <string.h>
34
35 #include "log.h"
36
37 #define VID 0x1366
38 #define PID 0x0101
39
40 #define JLINK_WRITE_ENDPOINT    0x02
41 #define JLINK_READ_ENDPOINT             0x81
42
43 #define JLINK_USB_TIMEOUT               1000
44
45 // See Section 1.3.2 of the Segger JLink USB protocol manual
46 #define JLINK_IN_BUFFER_SIZE                    2048
47 #define JLINK_OUT_BUFFER_SIZE                   2*2048+4
48 #define JLINK_EMU_RESULT_BUFFER_SIZE    64
49
50 /* Global USB buffers */
51 static u8 usb_in_buffer[JLINK_IN_BUFFER_SIZE];
52 static u8 usb_out_buffer[JLINK_OUT_BUFFER_SIZE];
53 static u8 usb_emu_result_buffer[JLINK_EMU_RESULT_BUFFER_SIZE];
54
55 /* Constants for JLink command */
56 #define EMU_CMD_VERSION                 0x01
57 #define EMU_CMD_SET_SPEED               0x05
58 #define EMU_CMD_GET_STATE               0x07
59 #define EMU_CMD_HW_JTAG3                0xcf
60 #define EMU_CMD_GET_MAX_MEM_BLOCK   0xd4
61 #define EMU_CMD_HW_RESET0               0xdc
62 #define EMU_CMD_HW_RESET1               0xdd
63 #define EMU_CMD_HW_TRST0                0xde
64 #define EMU_CMD_HW_TRST1                0xdf
65 #define EMU_CMD_GET_CAPS                0xe8
66
67 /* max speed 12MHz v5.0 jlink */
68 #define JLINK_MAX_SPEED 12000
69
70 /* External interface functions */
71 static int jlink_execute_queue(void);
72 static int jlink_speed(int speed);
73 static int jlink_speed_div(int speed, int* khz);
74 static int jlink_khz(int khz, int *jtag_speed);
75 static int jlink_register_commands(struct command_context_s *cmd_ctx);
76 static int jlink_init(void);
77 static int jlink_quit(void);
78
79 /* CLI command handler functions */
80 static int jlink_handle_jlink_info_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
81
82 /* Queue command functions */
83 static void jlink_end_state(tap_state_t state);
84 static void jlink_state_move(void);
85 static void jlink_path_move(int num_states, tap_state_t *path);
86 static void jlink_runtest(int num_cycles);
87 static void jlink_scan(int ir_scan, enum scan_type type, u8 *buffer, int scan_size, scan_command_t *command);
88 static void jlink_reset(int trst, int srst);
89 static void jlink_simple_command(u8 command);
90 static int jlink_get_status(void);
91
92 /* J-Link tap buffer functions */
93 static void jlink_tap_init(void);
94 static int jlink_tap_execute(void);
95 static void jlink_tap_ensure_space(int scans, int bits);
96 static void jlink_tap_append_step(int tms, int tdi);
97 static void jlink_tap_append_scan(int length, u8 *buffer, scan_command_t *command);
98
99 /* Jlink lowlevel functions */
100 typedef struct jlink_jtag
101 {
102         struct usb_dev_handle* usb_handle;
103 } jlink_jtag_t;
104
105 static jlink_jtag_t *jlink_usb_open(void);
106 static void jlink_usb_close(jlink_jtag_t *jlink_jtag);
107 static int jlink_usb_message(jlink_jtag_t *jlink_jtag, int out_length, int in_length);
108 static int jlink_usb_write(jlink_jtag_t *jlink_jtag, int out_length);
109 static int jlink_usb_read(jlink_jtag_t *jlink_jtag, int expected_size);
110 static int jlink_usb_read_emu_result(jlink_jtag_t *jlink_jtag);
111
112 /* helper functions */
113 static int jlink_get_version_info(void);
114
115 #ifdef _DEBUG_USB_COMMS_
116 static void jlink_debug_buffer(u8 *buffer, int length);
117 #endif
118
119 static enum tap_state jlink_last_state = TAP_RESET;
120
121 static jlink_jtag_t* jlink_jtag_handle;
122
123 /***************************************************************************/
124 /* External interface implementation */
125
126 jtag_interface_t jlink_interface =
127 {
128         .name = "jlink",
129         .execute_queue = jlink_execute_queue,
130         .speed = jlink_speed,
131         .speed_div = jlink_speed_div,
132         .khz = jlink_khz,
133         .register_commands = jlink_register_commands,
134         .init = jlink_init,
135         .quit = jlink_quit
136 };
137
138 static void jlink_execute_end_state(jtag_command_t *cmd)
139 {
140         DEBUG_JTAG_IO("end_state: %i", cmd->cmd.end_state->end_state);
141
142         if (cmd->cmd.end_state->end_state != TAP_INVALID)
143                 jlink_end_state(cmd->cmd.end_state->end_state);
144 }
145
146 static void jlink_execute_runtest(jtag_command_t *cmd)
147 {
148         DEBUG_JTAG_IO("runtest %i cycles, end in %i",
149                         cmd->cmd.runtest->num_cycles,
150                         cmd->cmd.runtest->end_state);
151
152         if (cmd->cmd.runtest->end_state != TAP_INVALID)
153                 jlink_end_state(cmd->cmd.runtest->end_state);
154
155         jlink_runtest(cmd->cmd.runtest->num_cycles);
156 }
157
158 static void jlink_execute_statemove(jtag_command_t *cmd)
159 {
160         DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
161
162         if (cmd->cmd.statemove->end_state != TAP_INVALID)
163         {
164                 jlink_end_state(cmd->cmd.statemove->end_state);
165         }
166         jlink_state_move();
167 }
168
169 static void jlink_execute_pathmove(jtag_command_t *cmd)
170 {
171         DEBUG_JTAG_IO("pathmove: %i states, end in %i",
172                 cmd->cmd.pathmove->num_states,
173                 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
174
175         jlink_path_move(cmd->cmd.pathmove->num_states,
176                         cmd->cmd.pathmove->path);
177 }
178
179 static void jlink_execute_scan(jtag_command_t *cmd)
180 {
181         int scan_size;
182         enum scan_type type;
183         u8 *buffer;
184
185         DEBUG_JTAG_IO("scan end in %i", cmd->cmd.scan->end_state);
186
187         if (cmd->cmd.scan->end_state != TAP_INVALID)
188                 jlink_end_state(cmd->cmd.scan->end_state);
189
190         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
191         DEBUG_JTAG_IO("scan input, length = %d", scan_size);
192
193 #ifdef _DEBUG_USB_COMMS_
194         jlink_debug_buffer(buffer, (scan_size + 7) / 8);
195 #endif
196         type = jtag_scan_type(cmd->cmd.scan);
197         jlink_scan(cmd->cmd.scan->ir_scan,
198                         type, buffer, scan_size, cmd->cmd.scan);
199 }
200
201 static void jlink_execute_reset(jtag_command_t *cmd)
202 {
203         DEBUG_JTAG_IO("reset trst: %i srst %i",
204                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
205
206         jlink_tap_execute();
207
208         if (cmd->cmd.reset->trst == 1)
209                 tap_set_state(TAP_RESET);
210
211         jlink_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
212 }
213
214 static void jlink_execute_sleep(jtag_command_t *cmd)
215 {
216         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
217         jlink_tap_execute();
218         jtag_sleep(cmd->cmd.sleep->us);
219 }
220
221 static void jlink_execute_command(jtag_command_t *cmd)
222 {
223         switch (cmd->type)
224         {
225         case JTAG_END_STATE: jlink_execute_end_state(cmd); break;
226         case JTAG_RUNTEST:   jlink_execute_runtest(cmd); break;
227         case JTAG_STATEMOVE: jlink_execute_statemove(cmd); break;
228         case JTAG_PATHMOVE:  jlink_execute_pathmove(cmd); break;
229         case JTAG_SCAN:      jlink_execute_scan(cmd); break;
230         case JTAG_RESET:     jlink_execute_reset(cmd); break;
231         case JTAG_SLEEP:     jlink_execute_sleep(cmd); break;
232         default:
233                 LOG_ERROR("BUG: unknown JTAG command type encountered");
234                 exit(-1);
235         }
236 }
237
238 static int jlink_execute_queue(void)
239 {
240         jtag_command_t *cmd = jtag_command_queue;
241
242         while (cmd != NULL)
243         {
244                 jlink_execute_command(cmd);
245                 cmd = cmd->next;
246         }
247
248         return jlink_tap_execute();
249 }
250
251 /* Sets speed in kHz. */
252 static int jlink_speed(int speed)
253 {
254         int result;
255
256         if (speed > JLINK_MAX_SPEED)
257         {
258                 LOG_INFO("Ignoring speed request: %dkHz exceeds %dkHz maximum",
259                                 speed, JLINK_MAX_SPEED);
260                 return ERROR_OK;
261         }
262
263         /* check for RTCK setting */
264         if (speed == 0)
265                 speed = -1;
266
267         usb_out_buffer[0] = EMU_CMD_SET_SPEED;
268         usb_out_buffer[1] = (speed >> 0) & 0xff;
269         usb_out_buffer[2] = (speed >> 8) & 0xff;
270
271         result = jlink_usb_write(jlink_jtag_handle, 3);
272         if (result != 3)
273         {
274                 LOG_ERROR("J-Link setting speed failed (%d)", result);
275                 return ERROR_JTAG_DEVICE_ERROR;
276         }
277
278         return ERROR_OK;
279 }
280
281 static int jlink_speed_div(int speed, int* khz)
282 {
283         *khz = speed;
284
285         return ERROR_OK;
286 }
287
288 static int jlink_khz(int khz, int *jtag_speed)
289 {
290         *jtag_speed = khz;
291
292         return ERROR_OK;
293 }
294
295 static int jlink_register_commands(struct command_context_s *cmd_ctx)
296 {
297         register_command(cmd_ctx, NULL, "jlink_info", jlink_handle_jlink_info_command, COMMAND_EXEC,
298                 "query jlink info");
299         return ERROR_OK;
300 }
301
302 static int jlink_init(void)
303 {
304         int check_cnt;
305
306         jlink_jtag_handle = jlink_usb_open();
307
308         if (jlink_jtag_handle == 0)
309         {
310                 LOG_ERROR("Cannot find jlink Interface! Please check connection and permissions.");
311                 return ERROR_JTAG_INIT_FAILED;
312         }
313
314         check_cnt = 0;
315         while (check_cnt < 3)
316         {
317                 if (jlink_get_version_info() == ERROR_OK)
318                 {
319                         /* attempt to get status */
320                         jlink_get_status();
321                         break;
322                 }
323
324                 check_cnt++;
325         }
326
327         if (check_cnt == 3)
328         {
329                 LOG_INFO("J-Link initial read failed, don't worry");
330         }
331
332         LOG_INFO("J-Link JTAG Interface ready");
333
334         jlink_reset(0, 0);
335         jlink_tap_init();
336         jlink_speed(jtag_speed);
337
338         return ERROR_OK;
339 }
340
341 static int jlink_quit(void)
342 {
343         jlink_usb_close(jlink_jtag_handle);
344         return ERROR_OK;
345 }
346
347 /***************************************************************************/
348 /* Queue command implementations */
349
350 static void jlink_end_state(tap_state_t state)
351 {
352         if (tap_is_state_stable(state))
353         {
354                 tap_set_end_state(state);
355         }
356         else
357         {
358                 LOG_ERROR("BUG: %i is not a valid end state", state);
359                 exit(-1);
360         }
361 }
362
363 /* Goes to the end state. */
364 static void jlink_state_move(void)
365 {
366         int i;
367         int tms = 0;
368         u8 tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
369
370         for (i = 0; i < 7; i++)
371         {
372                 tms = (tms_scan >> i) & 1;
373                 jlink_tap_append_step(tms, 0);
374         }
375
376         tap_set_state(tap_get_end_state());
377 }
378
379 static void jlink_path_move(int num_states, tap_state_t *path)
380 {
381         int i;
382
383         for (i = 0; i < num_states; i++)
384         {
385                 if (path[i] == tap_state_transition(tap_get_state(), false))
386                 {
387                         jlink_tap_append_step(0, 0);
388                 }
389                 else if (path[i] == tap_state_transition(tap_get_state(), true))
390                 {
391                         jlink_tap_append_step(1, 0);
392                 }
393                 else
394                 {
395                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition", tap_state_name(tap_get_state()), tap_state_name(path[i]));
396                         exit(-1);
397                 }
398
399                 tap_set_state(path[i]);
400         }
401
402         tap_set_end_state(tap_get_state());
403 }
404
405 static void jlink_runtest(int num_cycles)
406 {
407         int i;
408
409         tap_state_t saved_end_state = tap_get_end_state();
410
411         /* only do a state_move when we're not already in IDLE */
412         if (tap_get_state() != TAP_IDLE)
413         {
414                 jlink_end_state(TAP_IDLE);
415                 jlink_state_move();
416         }
417
418         /* execute num_cycles */
419         for (i = 0; i < num_cycles; i++)
420         {
421                 jlink_tap_append_step(0, 0);
422         }
423
424         /* finish in end_state */
425         jlink_end_state(saved_end_state);
426         if (tap_get_state() != tap_get_end_state())
427         {
428                 jlink_state_move();
429         }
430 }
431
432 static void jlink_scan(int ir_scan, enum scan_type type, u8 *buffer, int scan_size, scan_command_t *command)
433 {
434         tap_state_t saved_end_state;
435
436         jlink_tap_ensure_space(1, scan_size + 8);
437
438         saved_end_state = tap_get_end_state();
439
440         /* Move to appropriate scan state */
441         jlink_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
442
443         /* Only move if we're not already there */
444         if (tap_get_state() != tap_get_end_state())
445                 jlink_state_move();
446
447         jlink_end_state(saved_end_state);
448
449         /* Scan */
450         jlink_tap_append_scan(scan_size, buffer, command);
451
452         /* We are in Exit1, go to Pause */
453         jlink_tap_append_step(0, 0);
454
455         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
456
457         if (tap_get_state() != tap_get_end_state())
458         {
459                 jlink_state_move();
460         }
461 }
462
463 static void jlink_reset(int trst, int srst)
464 {
465         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
466
467         /* Signals are active low */
468         if (srst == 0)
469         {
470                 jlink_simple_command(EMU_CMD_HW_RESET1);
471                 jlink_end_state(TAP_RESET);
472                 jlink_state_move();
473         }
474         else if (srst == 1)
475         {
476                 jlink_simple_command(EMU_CMD_HW_RESET0);
477         }
478
479         if (trst == 0)
480         {
481                 jlink_simple_command(EMU_CMD_HW_TRST1);
482                 jlink_end_state(TAP_RESET);
483                 jlink_state_move();
484         }
485         else if (trst == 1)
486         {
487                 jlink_simple_command(EMU_CMD_HW_TRST0);
488         }
489 }
490
491 static void jlink_simple_command(u8 command)
492 {
493         int result;
494
495         DEBUG_JTAG_IO("0x%02x", command);
496
497         usb_out_buffer[0] = command;
498         result = jlink_usb_write(jlink_jtag_handle, 1);
499
500         if (result != 1)
501         {
502                 LOG_ERROR("J-Link command 0x%02x failed (%d)", command, result);
503         }
504 }
505
506 static int jlink_get_status(void)
507 {
508         int result;
509
510         jlink_simple_command(EMU_CMD_GET_STATE);
511
512         result = jlink_usb_read(jlink_jtag_handle, 8);
513         if (result != 8)
514         {
515                 LOG_ERROR("J-Link command EMU_CMD_GET_STATE failed (%d)\n", result);
516                 return ERROR_JTAG_DEVICE_ERROR;
517         }
518
519         int vref = usb_in_buffer[0] + (usb_in_buffer[1] << 8);
520         LOG_INFO("Vref = %d.%d TCK = %d TDI = %d TDO = %d TMS = %d SRST = %d TRST = %d\n", \
521                 vref / 1000, vref % 1000, \
522                 usb_in_buffer[2], usb_in_buffer[3], usb_in_buffer[4], \
523                 usb_in_buffer[5], usb_in_buffer[6], usb_in_buffer[7]);
524
525         if (vref < 1500)
526                 LOG_ERROR("Vref too low. Check Target Power\n");
527
528         return ERROR_OK;
529 }
530
531 static int jlink_get_version_info(void)
532 {
533         int result;
534         int len;
535         u32 jlink_caps, jlink_max_size;
536
537         /* query hardware version */
538         jlink_simple_command(EMU_CMD_VERSION);
539
540         result = jlink_usb_read(jlink_jtag_handle, 2);
541         if (2 != result)
542         {
543                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)\n", result);
544                 return ERROR_JTAG_DEVICE_ERROR;
545         }
546
547         len = buf_get_u32(usb_in_buffer, 0, 16);
548         result = jlink_usb_read(jlink_jtag_handle, len);
549         if (result != len)
550         {
551                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)\n", result);
552                 return ERROR_JTAG_DEVICE_ERROR;
553         }
554
555         usb_in_buffer[result] = 0;
556         LOG_INFO("%s", (char *)usb_in_buffer);
557
558         /* query hardware capabilities */
559         jlink_simple_command(EMU_CMD_GET_CAPS);
560
561         result = jlink_usb_read(jlink_jtag_handle, 4);
562         if (4 != result)
563         {
564                 LOG_ERROR("J-Link command EMU_CMD_GET_CAPS failed (%d)\n", result);
565                 return ERROR_JTAG_DEVICE_ERROR;
566         }
567
568         jlink_caps = buf_get_u32(usb_in_buffer, 0, 32);
569         LOG_INFO("JLink caps 0x%x", jlink_caps);
570
571
572         /* query hardware maximum memory block */
573         jlink_simple_command(EMU_CMD_GET_MAX_MEM_BLOCK);
574
575         result = jlink_usb_read(jlink_jtag_handle, 4);
576         if (4 != result)
577         {
578                 LOG_ERROR("J-Link command EMU_CMD_GET_MAX_MEM_BLOCK failed (%d)\n", result);
579                 return ERROR_JTAG_DEVICE_ERROR;
580         }
581
582         jlink_max_size = buf_get_u32(usb_in_buffer, 0, 32);
583         LOG_INFO("JLink max mem block %i", jlink_max_size);
584
585
586         return ERROR_OK;
587 }
588
589 static int jlink_handle_jlink_info_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
590 {
591         if (jlink_get_version_info() == ERROR_OK)
592         {
593                 /* attempt to get status */
594                 jlink_get_status();
595         }
596
597         return ERROR_OK;
598 }
599
600 /***************************************************************************/
601 /* J-Link tap functions */
602
603 /* 2048 is the max value we can use here */
604 #define JLINK_TAP_BUFFER_SIZE 2048
605
606 static unsigned tap_length;
607 static u8 tms_buffer[JLINK_TAP_BUFFER_SIZE];
608 static u8 tdi_buffer[JLINK_TAP_BUFFER_SIZE];
609 static u8 tdo_buffer[JLINK_TAP_BUFFER_SIZE];
610
611 typedef struct
612 {
613         int first;      /* First bit position in tdo_buffer to read */
614         int length; /* Number of bits to read */
615         scan_command_t *command; /* Corresponding scan command */
616         u8 *buffer;
617 } pending_scan_result_t;
618
619 #define MAX_PENDING_SCAN_RESULTS 256
620
621 static int pending_scan_results_length;
622 static pending_scan_result_t pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
623
624 static void jlink_tap_init(void)
625 {
626         tap_length = 0;
627         pending_scan_results_length = 0;
628 }
629
630 static void jlink_tap_ensure_space(int scans, int bits)
631 {
632         int available_scans = MAX_PENDING_SCAN_RESULTS - pending_scan_results_length;
633         int available_bits = JLINK_TAP_BUFFER_SIZE * 8 - tap_length;
634
635         if (scans > available_scans || bits > available_bits)
636         {
637                 jlink_tap_execute();
638         }
639 }
640
641 static void jlink_tap_append_step(int tms, int tdi)
642 {
643         int index = tap_length / 8;
644
645         if (index >= JLINK_TAP_BUFFER_SIZE)
646         {
647                 LOG_ERROR("jlink_tap_append_step: overflow");
648                 exit(-1);
649         }
650
651         int bit_index = tap_length % 8;
652         u8 bit = 1 << bit_index;
653
654         // we do not pad TMS, so be sure to initialize all bits
655         if (0 == bit_index)
656                 tms_buffer[index] = tdi_buffer[index] = 0;
657
658         if (tms)
659                 tms_buffer[index] |= bit;
660         else
661                 tms_buffer[index] &= ~bit;
662
663         if (tdi)
664                 tdi_buffer[index] |= bit;
665         else
666                 tdi_buffer[index] &= ~bit;
667
668         tap_length++;
669 }
670
671 static void jlink_tap_append_scan(int length, u8 *buffer, scan_command_t *command)
672 {
673         pending_scan_result_t *pending_scan_result =
674                 &pending_scan_results_buffer[pending_scan_results_length];
675         int i;
676
677         pending_scan_result->first = tap_length;
678         pending_scan_result->length = length;
679         pending_scan_result->command = command;
680         pending_scan_result->buffer = buffer;
681
682         for (i = 0; i < length; i++)
683         {
684                 int tms = i < length - 1 ? 0 : 1;
685                 int tdi = buffer[i / 8] & (1 << (i % 8));
686                 jlink_tap_append_step(tms, tdi);
687         }
688         pending_scan_results_length++;
689 }
690
691 /* Pad and send a tap sequence to the device, and receive the answer.
692  * For the purpose of padding we assume that we are in idle or pause state. */
693 static int jlink_tap_execute(void)
694 {
695         int byte_length;
696         int i;
697         int result;
698
699         if (!tap_length)
700                 return ERROR_OK;
701
702         // number of full bytes (plus one if some would be left over)
703         byte_length = TAP_SCAN_BYTES(tap_length);
704
705         usb_out_buffer[0] = EMU_CMD_HW_JTAG3;
706         usb_out_buffer[1] = 0;
707         usb_out_buffer[2] = (tap_length >> 0) & 0xff;
708         usb_out_buffer[3] = (tap_length >> 8) & 0xff;
709         memcpy(usb_out_buffer + 4, tms_buffer, byte_length);
710         memcpy(usb_out_buffer + 4 + byte_length, tdi_buffer, byte_length);
711
712         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
713                         tap_length, jlink_last_state);
714
715         result = jlink_usb_message(jlink_jtag_handle, 4 + 2 * byte_length, byte_length);
716         if (result != byte_length)
717         {
718                 LOG_ERROR("jlink_tap_execute, wrong result %d (expected %d)", result, byte_length);
719                 jlink_tap_init();
720                 return ERROR_JTAG_QUEUE_FAILED;
721         }
722
723         memcpy(tdo_buffer, usb_in_buffer, byte_length);
724
725         for (i = 0; i < pending_scan_results_length; i++)
726         {
727                 pending_scan_result_t *pending_scan_result = &pending_scan_results_buffer[i];
728                 u8 *buffer = pending_scan_result->buffer;
729                 int length = pending_scan_result->length;
730                 int first = pending_scan_result->first;
731                 scan_command_t *command = pending_scan_result->command;
732
733                 /* Copy to buffer */
734                 buf_set_buf(tdo_buffer, first, buffer, 0, length);
735
736                 DEBUG_JTAG_IO("pending scan result, length = %d", length);
737
738 #ifdef _DEBUG_USB_COMMS_
739                 jlink_debug_buffer(buffer, byte_length);
740 #endif
741
742                 if (jtag_read_buffer(buffer, command) != ERROR_OK)
743                 {
744                         jlink_tap_init();
745                         return ERROR_JTAG_QUEUE_FAILED;
746                 }
747
748                 if (pending_scan_result->buffer != NULL)
749                 {
750                         free(pending_scan_result->buffer);
751                 }
752         }
753
754         jlink_tap_init();
755         return ERROR_OK;
756 }
757
758 /*****************************************************************************/
759 /* JLink USB low-level functions */
760
761 static jlink_jtag_t* jlink_usb_open()
762 {
763         struct usb_bus *busses;
764         struct usb_bus *bus;
765         struct usb_device *dev;
766
767         jlink_jtag_t *result;
768
769         result = (jlink_jtag_t*) malloc(sizeof(jlink_jtag_t));
770
771         usb_init();
772         usb_find_busses();
773         usb_find_devices();
774
775         busses = usb_get_busses();
776
777         /* find jlink_jtag device in usb bus */
778
779         for (bus = busses; bus; bus = bus->next)
780         {
781                 for (dev = bus->devices; dev; dev = dev->next)
782                 {
783                         if ((dev->descriptor.idVendor == VID) && (dev->descriptor.idProduct == PID))
784                         {
785                                 result->usb_handle = usb_open(dev);
786
787                                 /* usb_set_configuration required under win32 */
788                                 usb_set_configuration(result->usb_handle, dev->config[0].bConfigurationValue);
789                                 usb_claim_interface(result->usb_handle, 0);
790
791 #if 0
792                                 /*
793                                  * This makes problems under Mac OS X. And is not needed
794                                  * under Windows. Hopefully this will not break a linux build
795                                  */
796                                 usb_set_altinterface(result->usb_handle, 0);
797 #endif
798                                 return result;
799                         }
800                 }
801         }
802
803         free(result);
804         return NULL;
805 }
806
807 static void jlink_usb_close(jlink_jtag_t *jlink_jtag)
808 {
809         usb_close(jlink_jtag->usb_handle);
810         free(jlink_jtag);
811 }
812
813 /* Send a message and receive the reply. */
814 static int jlink_usb_message(jlink_jtag_t *jlink_jtag, int out_length, int in_length)
815 {
816         int result;
817         int result2;
818
819         result = jlink_usb_write(jlink_jtag, out_length);
820         if (result != out_length)
821         {
822                 LOG_ERROR("usb_bulk_write failed (requested=%d, result=%d)",
823                                 out_length, result);
824                 return ERROR_JTAG_DEVICE_ERROR;
825         }
826
827         result = jlink_usb_read(jlink_jtag, in_length);
828         if ((result != in_length) && (result != (in_length + 1)))
829         {
830                 LOG_ERROR("usb_bulk_read failed (requested=%d, result=%d)",
831                                 in_length, result);
832                 return ERROR_JTAG_DEVICE_ERROR;
833         }
834
835         if (result == in_length)
836         {
837                 /* Must read the result from the EMU too */
838                 result2 = jlink_usb_read_emu_result(jlink_jtag);
839                 if (1 != result2)
840                 {
841                         LOG_ERROR("jlink_usb_read_emu_result failed "
842                                 "(requested=1, result=%d)", result2);
843                         return ERROR_JTAG_DEVICE_ERROR;
844                 }
845
846                 /* Check the result itself */
847                 result2 = usb_emu_result_buffer[0];
848         }
849         else
850         {
851                 /* Save the result, then remove it from return value */
852                 result2 = usb_in_buffer[result--];
853         }
854
855         if (result2)
856         {
857                 LOG_ERROR("jlink_usb_message failed with result=%d)", result2);
858                 return ERROR_JTAG_DEVICE_ERROR;
859         }
860
861         return result;
862 }
863
864 /* calls the given usb_bulk_* function, allowing for the data to trickle in with some timeouts  */
865 static int usb_bulk_with_retries(
866                 int (*f)(usb_dev_handle *, int, char *, int, int),
867                 usb_dev_handle *dev, int ep,
868                 char *bytes, int size, int timeout)
869 {
870         int rc = 0, tries = 3, this_size;
871
872         while (tries && size) {
873
874                 this_size = f(dev, ep, bytes, size, timeout);
875                 if (this_size > 0) {
876                         
877                         size -= this_size;
878                         rc += this_size;
879                         bytes += this_size;
880
881                 } else
882                         tries --;
883         }
884         return rc;
885 }
886
887 static int wrap_usb_bulk_write(usb_dev_handle *dev, int ep,
888                                char *buff, int size, int timeout)
889 {
890         /* usb_bulk_write() takes const char *buff */
891         return usb_bulk_write(dev, ep, buff, size, timeout);
892 }
893
894 static inline int usb_bulk_write_ex(usb_dev_handle *dev, int ep,
895                 char *bytes, int size, int timeout)
896 {
897         return usb_bulk_with_retries(&wrap_usb_bulk_write,
898                         dev, ep, bytes, size, timeout);
899 }
900
901 static inline int usb_bulk_read_ex(usb_dev_handle *dev, int ep,
902                 char *bytes, int size, int timeout)
903 {
904         return usb_bulk_with_retries(&usb_bulk_read,
905                         dev, ep, bytes, size, timeout);
906 }
907
908 /* Write data from out_buffer to USB. */
909 static int jlink_usb_write(jlink_jtag_t *jlink_jtag, int out_length)
910 {
911         int result;
912
913         if (out_length > JLINK_OUT_BUFFER_SIZE)
914         {
915                 LOG_ERROR("jlink_jtag_write illegal out_length=%d (max=%d)", out_length, JLINK_OUT_BUFFER_SIZE);
916                 return -1;
917         }
918
919         result = usb_bulk_write_ex(jlink_jtag->usb_handle, JLINK_WRITE_ENDPOINT,
920                 (char *)usb_out_buffer, out_length, JLINK_USB_TIMEOUT);
921
922         DEBUG_JTAG_IO("jlink_usb_write, out_length = %d, result = %d", out_length, result);
923
924 #ifdef _DEBUG_USB_COMMS_
925         jlink_debug_buffer(usb_out_buffer, out_length);
926 #endif
927         return result;
928 }
929
930 /* Read data from USB into in_buffer. */
931 static int jlink_usb_read(jlink_jtag_t *jlink_jtag, int expected_size)
932 {
933         int result = usb_bulk_read_ex(jlink_jtag->usb_handle, JLINK_READ_ENDPOINT,
934                 (char *)usb_in_buffer, expected_size, JLINK_USB_TIMEOUT);
935
936         DEBUG_JTAG_IO("jlink_usb_read, result = %d", result);
937
938 #ifdef _DEBUG_USB_COMMS_
939         jlink_debug_buffer(usb_in_buffer, result);
940 #endif
941         return result;
942 }
943
944 /* Read the result from the previous EMU cmd into result_buffer. */
945 static int jlink_usb_read_emu_result(jlink_jtag_t *jlink_jtag)
946 {
947         int result = usb_bulk_read_ex(jlink_jtag->usb_handle, JLINK_READ_ENDPOINT,
948                 (char *)usb_emu_result_buffer, 1 /* JLINK_EMU_RESULT_BUFFER_SIZE */,
949                 JLINK_USB_TIMEOUT);
950
951         DEBUG_JTAG_IO("jlink_usb_read_result, result = %d", result);
952
953 #ifdef _DEBUG_USB_COMMS_
954         jlink_debug_buffer(usb_emu_result_buffer, result);
955 #endif
956         return result;
957 }
958
959 #ifdef _DEBUG_USB_COMMS_
960 #define BYTES_PER_LINE  16
961
962 static void jlink_debug_buffer(u8 *buffer, int length)
963 {
964         char line[81];
965         char s[4];
966         int i;
967         int j;
968
969         for (i = 0; i < length; i += BYTES_PER_LINE)
970         {
971                 snprintf(line, 5, "%04x", i);
972                 for (j = i; j < i + BYTES_PER_LINE && j < length; j++)
973                 {
974                         snprintf(s, 4, " %02x", buffer[j]);
975                         strcat(line, s);
976                 }
977                 LOG_DEBUG("%s", line);
978         }
979 }
980 #endif