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