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