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