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