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