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