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