]> git.sur5r.net Git - openocd/blob - src/jtag/jlink.c
36395fd82ce174c7191f59fc4f7a90e506e72566
[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 "replacements.h"
29
30 #include "jtag.h"
31
32 #include <usb.h>
33 #include <string.h>
34
35 #include "log.h"
36
37 #define VID 0x1366
38 #define PID 0x0101
39
40 #define JLINK_WRITE_ENDPOINT    0x02
41 #define JLINK_READ_ENDPOINT             0x81
42
43 #define JLINK_USB_TIMEOUT               1000
44
45 // See Section 1.3.2 of the Segger JLink USB protocol manual
46 #define JLINK_IN_BUFFER_SIZE                    2048
47 #define JLINK_OUT_BUFFER_SIZE                   2048
48 #define JLINK_EMU_RESULT_BUFFER_SIZE    64
49
50 /* Global USB buffers */
51 static u8 usb_in_buffer[JLINK_IN_BUFFER_SIZE];
52 static u8 usb_out_buffer[JLINK_OUT_BUFFER_SIZE];
53 static u8 usb_emu_result_buffer[JLINK_EMU_RESULT_BUFFER_SIZE];
54
55 /* Constants for JLink command */
56 #define EMU_CMD_VERSION     0x01
57 #define EMU_CMD_SET_SPEED   0x05
58 #define EMU_CMD_GET_STATE   0x07
59 #define EMU_CMD_HW_JTAG3    0xcf
60 #define EMU_CMD_HW_RESET0   0xdc
61 #define EMU_CMD_HW_RESET1   0xdd
62 #define EMU_CMD_HW_TRST0    0xde
63 #define EMU_CMD_HW_TRST1    0xdf
64
65 /* max speed 12MHz v5.0 jlink */
66 #define JLINK_MAX_SPEED 12000
67
68 /* External interface functions */
69 static int jlink_execute_queue(void);
70 static int jlink_speed(int speed);
71 static int jlink_speed_div(int speed, int* khz);
72 static int jlink_khz(int khz, int *jtag_speed);
73 static int jlink_register_commands(struct command_context_s *cmd_ctx);
74 static int jlink_init(void);
75 static int jlink_quit(void);
76
77 /* CLI command handler functions */
78 static int jlink_handle_jlink_info_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
79
80 /* Queue command functions */
81 static void jlink_end_state(tap_state_t state);
82 static void jlink_state_move(void);
83 static void jlink_path_move(int num_states, tap_state_t *path);
84 static void jlink_runtest(int num_cycles);
85 static void jlink_scan(int ir_scan, enum scan_type type, u8 *buffer, int scan_size, scan_command_t *command);
86 static void jlink_reset(int trst, int srst);
87 static void jlink_simple_command(u8 command);
88 static int jlink_get_status(void);
89
90 /* J-Link tap buffer functions */
91 static void jlink_tap_init(void);
92 static int jlink_tap_execute(void);
93 static void jlink_tap_ensure_space(int scans, int bits);
94 static void jlink_tap_append_step(int tms, int tdi);
95 static void jlink_tap_append_scan(int length, u8 *buffer, scan_command_t *command);
96
97 /* Jlink lowlevel functions */
98 typedef struct jlink_jtag
99 {
100         struct usb_dev_handle* usb_handle;
101 } jlink_jtag_t;
102
103 static jlink_jtag_t *jlink_usb_open(void);
104 static void jlink_usb_close(jlink_jtag_t *jlink_jtag);
105 static int jlink_usb_message(jlink_jtag_t *jlink_jtag, int out_length, int in_length);
106 static int jlink_usb_write(jlink_jtag_t *jlink_jtag, int out_length);
107 static int jlink_usb_read(jlink_jtag_t *jlink_jtag, int expected_size);
108 static int jlink_usb_read_emu_result(jlink_jtag_t *jlink_jtag);
109
110 /* helper functions */
111 static int jlink_get_version_info(void);
112
113 #ifdef _DEBUG_USB_COMMS_
114 static void jlink_debug_buffer(u8 *buffer, int length);
115 #endif
116
117 static enum tap_state jlink_last_state = TAP_RESET;
118
119 static jlink_jtag_t* jlink_jtag_handle;
120
121 /***************************************************************************/
122 /* External interface implementation */
123
124 jtag_interface_t jlink_interface =
125 {
126         .name = "jlink",
127         .execute_queue = jlink_execute_queue,
128         .speed = jlink_speed,
129         .speed_div = jlink_speed_div,
130         .khz = jlink_khz,
131         .register_commands = jlink_register_commands,
132         .init = jlink_init,
133         .quit = jlink_quit
134 };
135
136 static void jlink_execute_end_state(jtag_command_t *cmd)
137 {
138         DEBUG_JTAG_IO("end_state: %i", cmd->cmd.end_state->end_state);
139
140         if (cmd->cmd.end_state->end_state != TAP_INVALID)
141                 jlink_end_state(cmd->cmd.end_state->end_state);
142 }
143
144 static void jlink_execute_runtest(jtag_command_t *cmd)
145 {
146         DEBUG_JTAG_IO("runtest %i cycles, end in %i",
147                         cmd->cmd.runtest->num_cycles,
148                         cmd->cmd.runtest->end_state);
149
150         if (cmd->cmd.runtest->end_state != TAP_INVALID)
151                 jlink_end_state(cmd->cmd.runtest->end_state);
152
153         jlink_runtest(cmd->cmd.runtest->num_cycles);
154 }
155
156 static void jlink_execute_statemove(jtag_command_t *cmd)
157 {
158         DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
159
160         if (cmd->cmd.statemove->end_state != TAP_INVALID)
161         {
162                 jlink_end_state(cmd->cmd.statemove->end_state);
163         }
164         jlink_state_move();
165 }
166
167 static void jlink_execute_pathmove(jtag_command_t *cmd)
168 {
169         DEBUG_JTAG_IO("pathmove: %i states, end in %i",
170                 cmd->cmd.pathmove->num_states,
171                 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
172
173         jlink_path_move(cmd->cmd.pathmove->num_states,
174                         cmd->cmd.pathmove->path);
175 }
176
177 static void jlink_execute_scan(jtag_command_t *cmd)
178 {
179         int scan_size;
180         enum scan_type type;
181         u8 *buffer;
182
183         DEBUG_JTAG_IO("scan end in %i", cmd->cmd.scan->end_state);
184
185         if (cmd->cmd.scan->end_state != TAP_INVALID)
186                 jlink_end_state(cmd->cmd.scan->end_state);
187
188         scan_size = jtag_build_buffer(cmd->cmd.scan, &buffer);
189         DEBUG_JTAG_IO("scan input, length = %d", scan_size);
190
191 #ifdef _DEBUG_USB_COMMS_
192         jlink_debug_buffer(buffer, (scan_size + 7) / 8);
193 #endif
194         type = jtag_scan_type(cmd->cmd.scan);
195         jlink_scan(cmd->cmd.scan->ir_scan,
196                         type, buffer, scan_size, cmd->cmd.scan);
197 }
198
199 static void jlink_execute_reset(jtag_command_t *cmd)
200 {
201         DEBUG_JTAG_IO("reset trst: %i srst %i",
202                         cmd->cmd.reset->trst, cmd->cmd.reset->srst);
203
204         jlink_tap_execute();
205
206         if (cmd->cmd.reset->trst == 1)
207                 tap_set_state(TAP_RESET);
208
209         jlink_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
210 }
211
212 static void jlink_execute_sleep(jtag_command_t *cmd)
213 {
214         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
215         jlink_tap_execute();
216         jtag_sleep(cmd->cmd.sleep->us);
217 }
218
219 static void jlink_execute_command(jtag_command_t *cmd)
220 {
221         switch (cmd->type)
222         {
223         case JTAG_END_STATE: jlink_execute_end_state(cmd); break;
224         case JTAG_RUNTEST:   jlink_execute_runtest(cmd); break;
225         case JTAG_STATEMOVE: jlink_execute_statemove(cmd); break;
226         case JTAG_PATHMOVE:  jlink_execute_pathmove(cmd); break;
227         case JTAG_SCAN:      jlink_execute_scan(cmd); break;
228         case JTAG_RESET:     jlink_execute_reset(cmd); break;
229         case JTAG_SLEEP:     jlink_execute_sleep(cmd); break;
230         default:
231                 LOG_ERROR("BUG: unknown JTAG command type encountered");
232                 exit(-1);
233         }
234 }
235
236 static int jlink_execute_queue(void)
237 {
238         jtag_command_t *cmd = jtag_command_queue;
239
240         while (cmd != NULL)
241         {
242                 jlink_execute_command(cmd);
243                 cmd = cmd->next;
244         }
245
246         return jlink_tap_execute();
247 }
248
249 /* Sets speed in kHz. */
250 static int jlink_speed(int speed)
251 {
252         int result;
253
254         if (speed > JLINK_MAX_SPEED)
255         {
256                 LOG_INFO("Ignoring speed request: %dkHz exceeds %dkHz maximum",
257                                 speed, JLINK_MAX_SPEED);
258                 return ERROR_OK;
259         }
260
261         /* check for RTCK setting */
262         if (speed == 0)
263                 speed = -1;
264
265         usb_out_buffer[0] = EMU_CMD_SET_SPEED;
266         usb_out_buffer[1] = (speed >> 0) & 0xff;
267         usb_out_buffer[2] = (speed >> 8) & 0xff;
268
269         result = jlink_usb_write(jlink_jtag_handle, 3);
270         if (result != 3)
271         {
272                 LOG_ERROR("J-Link setting speed failed (%d)", result);
273                 return ERROR_JTAG_DEVICE_ERROR;
274         }
275
276         return ERROR_OK;
277 }
278
279 static int jlink_speed_div(int speed, int* khz)
280 {
281         *khz = speed;
282
283         return ERROR_OK;
284 }
285
286 static int jlink_khz(int khz, int *jtag_speed)
287 {
288         *jtag_speed = khz;
289
290         return ERROR_OK;
291 }
292
293 static int jlink_register_commands(struct command_context_s *cmd_ctx)
294 {
295         register_command(cmd_ctx, NULL, "jlink_info", jlink_handle_jlink_info_command, COMMAND_EXEC,
296                 "query jlink info");
297         return ERROR_OK;
298 }
299
300 static int jlink_init(void)
301 {
302         int check_cnt;
303
304         jlink_jtag_handle = jlink_usb_open();
305
306         if (jlink_jtag_handle == 0)
307         {
308                 LOG_ERROR("Cannot find jlink Interface! Please check connection and permissions.");
309                 return ERROR_JTAG_INIT_FAILED;
310         }
311
312         check_cnt = 0;
313         while (check_cnt < 3)
314         {
315                 if (jlink_get_version_info() == ERROR_OK)
316                 {
317                         /* attempt to get status */
318                         jlink_get_status();
319                         break;
320                 }
321
322                 check_cnt++;
323         }
324
325         if (check_cnt == 3)
326         {
327                 LOG_INFO("J-Link initial read failed, don't worry");
328         }
329
330         LOG_INFO("J-Link JTAG Interface ready");
331
332         jlink_reset(0, 0);
333         jlink_tap_init();
334         jlink_speed(jtag_speed);
335
336         return ERROR_OK;
337 }
338
339 static int jlink_quit(void)
340 {
341         jlink_usb_close(jlink_jtag_handle);
342         return ERROR_OK;
343 }
344
345 /***************************************************************************/
346 /* Queue command implementations */
347
348 static void jlink_end_state(tap_state_t state)
349 {
350         if (tap_is_state_stable(state))
351         {
352                 tap_set_end_state(state);
353         }
354         else
355         {
356                 LOG_ERROR("BUG: %i is not a valid end state", state);
357                 exit(-1);
358         }
359 }
360
361 /* Goes to the end state. */
362 static void jlink_state_move(void)
363 {
364         int i;
365         int tms = 0;
366         u8 tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
367
368         for (i = 0; i < 7; i++)
369         {
370                 tms = (tms_scan >> i) & 1;
371                 jlink_tap_append_step(tms, 0);
372         }
373
374         tap_set_state(tap_get_end_state());
375 }
376
377 static void jlink_path_move(int num_states, tap_state_t *path)
378 {
379         int i;
380
381         for (i = 0; i < num_states; i++)
382         {
383                 if (path[i] == tap_state_transition(tap_get_state(), false))
384                 {
385                         jlink_tap_append_step(0, 0);
386                 }
387                 else if (path[i] == tap_state_transition(tap_get_state(), true))
388                 {
389                         jlink_tap_append_step(1, 0);
390                 }
391                 else
392                 {
393                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition", tap_state_name(tap_get_state()), tap_state_name(path[i]));
394                         exit(-1);
395                 }
396
397                 tap_set_state(path[i]);
398         }
399
400         tap_set_end_state(tap_get_state());
401 }
402
403 static void jlink_runtest(int num_cycles)
404 {
405         int i;
406
407         tap_state_t saved_end_state = tap_get_end_state();
408
409         /* only do a state_move when we're not already in IDLE */
410         if (tap_get_state() != TAP_IDLE)
411         {
412                 jlink_end_state(TAP_IDLE);
413                 jlink_state_move();
414         }
415
416         /* execute num_cycles */
417         for (i = 0; i < num_cycles; i++)
418         {
419                 jlink_tap_append_step(0, 0);
420         }
421
422         /* finish in end_state */
423         jlink_end_state(saved_end_state);
424         if (tap_get_state() != tap_get_end_state())
425         {
426                 jlink_state_move();
427         }
428 }
429
430 static void jlink_scan(int ir_scan, enum scan_type type, u8 *buffer, int scan_size, scan_command_t *command)
431 {
432         tap_state_t saved_end_state;
433
434         jlink_tap_ensure_space(1, scan_size + 8);
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                 jlink_end_state(TAP_RESET);
470                 jlink_state_move();
471         }
472         else if (srst == 1)
473         {
474                 jlink_simple_command(EMU_CMD_HW_RESET0);
475         }
476
477         if (trst == 0)
478         {
479                 jlink_simple_command(EMU_CMD_HW_TRST1);
480                 jlink_end_state(TAP_RESET);
481                 jlink_state_move();
482         }
483         else if (trst == 1)
484         {
485                 jlink_simple_command(EMU_CMD_HW_TRST0);
486         }
487 }
488
489 static void jlink_simple_command(u8 command)
490 {
491         int result;
492
493         DEBUG_JTAG_IO("0x%02x", command);
494
495         usb_out_buffer[0] = command;
496         result = jlink_usb_write(jlink_jtag_handle, 1);
497
498         if (result != 1)
499         {
500                 LOG_ERROR("J-Link command 0x%02x failed (%d)", command, result);
501         }
502 }
503
504 static int jlink_get_status(void)
505 {
506         int result;
507
508         jlink_simple_command(EMU_CMD_GET_STATE);
509
510         result = jlink_usb_read(jlink_jtag_handle, 8);
511         if (result != 8)
512         {
513                 LOG_ERROR("J-Link command EMU_CMD_GET_STATE failed (%d)\n", result);
514                 return ERROR_JTAG_DEVICE_ERROR;
515         }
516
517         int vref = usb_in_buffer[0] + (usb_in_buffer[1] << 8);
518         LOG_INFO("Vref = %d.%d TCK = %d TDI = %d TDO = %d TMS = %d SRST = %d TRST = %d\n", \
519                 vref / 1000, vref % 1000, \
520                 usb_in_buffer[2], usb_in_buffer[3], usb_in_buffer[4], \
521                 usb_in_buffer[5], usb_in_buffer[6], usb_in_buffer[7]);
522
523         if (vref < 1500)
524                 LOG_ERROR("Vref too low. Check Target Power\n");
525
526         return ERROR_OK;
527 }
528
529 static int jlink_get_version_info(void)
530 {
531         int result;
532         int len;
533
534         /* query hardware version */
535         jlink_simple_command(EMU_CMD_VERSION);
536
537         result = jlink_usb_read(jlink_jtag_handle, 2);
538         if (2 != result)
539         {
540                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)\n",
541                                 result);
542                 return ERROR_JTAG_DEVICE_ERROR;
543         }
544
545         len = buf_get_u32(usb_in_buffer, 0, 16);
546         result = jlink_usb_read(jlink_jtag_handle, len);
547         if (result != len)
548         {
549                 LOG_ERROR("J-Link command EMU_CMD_VERSION failed (%d)\n",
550                                 result);
551                 return ERROR_JTAG_DEVICE_ERROR;
552         }
553
554         usb_in_buffer[result] = 0;
555         LOG_INFO("%s", (char *)usb_in_buffer);
556
557         return ERROR_OK;
558 }
559
560 static int jlink_handle_jlink_info_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
561 {
562         if (jlink_get_version_info() == ERROR_OK)
563         {
564                 /* attempt to get status */
565                 jlink_get_status();
566         }
567
568         return ERROR_OK;
569 }
570
571 /***************************************************************************/
572 /* J-Link tap functions */
573
574 /* 2048 is the max value we can use here */
575 #define JLINK_TAP_BUFFER_SIZE 2048
576
577 static unsigned tap_length;
578 static u8 tms_buffer[JLINK_TAP_BUFFER_SIZE];
579 static u8 tdi_buffer[JLINK_TAP_BUFFER_SIZE];
580 static u8 tdo_buffer[JLINK_TAP_BUFFER_SIZE];
581
582 typedef struct
583 {
584         int first;      /* First bit position in tdo_buffer to read */
585         int length; /* Number of bits to read */
586         scan_command_t *command; /* Corresponding scan command */
587         u8 *buffer;
588 } pending_scan_result_t;
589
590 #define MAX_PENDING_SCAN_RESULTS 256
591
592 static int pending_scan_results_length;
593 static pending_scan_result_t pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
594
595 static int last_tms;
596
597 static void jlink_tap_init(void)
598 {
599         tap_length = 0;
600         pending_scan_results_length = 0;
601 }
602
603 static void jlink_tap_ensure_space(int scans, int bits)
604 {
605         int available_scans = MAX_PENDING_SCAN_RESULTS - pending_scan_results_length;
606         int available_bits = JLINK_TAP_BUFFER_SIZE * 8 - tap_length;
607
608         if (scans > available_scans || bits > available_bits)
609         {
610                 jlink_tap_execute();
611         }
612 }
613
614 static void jlink_tap_append_step(int tms, int tdi)
615 {
616         last_tms = tms;
617         int index = tap_length / 8;
618
619         if (index >= JLINK_TAP_BUFFER_SIZE)
620         {
621                 LOG_ERROR("jlink_tap_append_step: overflow");
622                 exit(-1);
623         }
624
625         int bit_index = tap_length % 8;
626         u8 bit = 1 << bit_index;
627
628         // we do not pad TMS, so be sure to initialize all bits
629         if (0 == bit_index)
630                 tms_buffer[index] = tdi_buffer[index] = 0;
631
632         if (tms)
633                 tms_buffer[index] |= bit;
634         else
635                 tms_buffer[index] &= ~bit;
636
637         if (tdi)
638                 tdi_buffer[index] |= bit;
639         else
640                 tdi_buffer[index] &= ~bit;
641
642         tap_length++;
643 }
644
645 static void jlink_tap_append_scan(int length, u8 *buffer, scan_command_t *command)
646 {
647         pending_scan_result_t *pending_scan_result =
648                 &pending_scan_results_buffer[pending_scan_results_length];
649         int i;
650
651         pending_scan_result->first = tap_length;
652         pending_scan_result->length = length;
653         pending_scan_result->command = command;
654         pending_scan_result->buffer = buffer;
655
656         for (i = 0; i < length; i++)
657         {
658                 int tms = i < length - 1 ? 0 : 1;
659                 int tdi = buffer[i / 8] & (1 << (i % 8));
660                 jlink_tap_append_step(tms, tdi);
661         }
662         pending_scan_results_length++;
663 }
664
665 /* Pad and send a tap sequence to the device, and receive the answer.
666  * For the purpose of padding we assume that we are in idle or pause state. */
667 static int jlink_tap_execute(void)
668 {
669         int byte_length;
670         int i;
671         int result;
672
673         if (!tap_length)
674                 return ERROR_OK;
675
676         // number of full bytes (plus one if some would be left over)
677         byte_length = TAP_SCAN_BYTES(tap_length);
678
679         usb_out_buffer[0] = EMU_CMD_HW_JTAG3;
680         usb_out_buffer[1] = 0;
681         usb_out_buffer[2] = (tap_length >> 0) & 0xff;
682         usb_out_buffer[3] = (tap_length >> 8) & 0xff;
683         memcpy(usb_out_buffer + 4, tms_buffer, byte_length);
684         memcpy(usb_out_buffer + 4 + byte_length, tdi_buffer, byte_length);
685
686         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
687                         tap_length, jlink_last_state);
688
689         result = jlink_usb_message(jlink_jtag_handle, 4 + 2 * byte_length, byte_length);
690         if (result != byte_length)
691         {
692                 LOG_ERROR("jlink_tap_execute, wrong result %d (expected %d)",
693                                 result, byte_length);
694                 return ERROR_JTAG_QUEUE_FAILED;
695         }
696
697         memcpy(tdo_buffer, usb_in_buffer, byte_length);
698
699         for (i = 0; i < pending_scan_results_length; i++)
700         {
701                 pending_scan_result_t *pending_scan_result = &pending_scan_results_buffer[i];
702                 u8 *buffer = pending_scan_result->buffer;
703                 int length = pending_scan_result->length;
704                 int first = pending_scan_result->first;
705                 scan_command_t *command = pending_scan_result->command;
706
707                 /* Copy to buffer */
708                 buf_set_buf(tdo_buffer, first, buffer, 0, length);
709
710                 DEBUG_JTAG_IO("pending scan result, length = %d", length);
711
712 #ifdef _DEBUG_USB_COMMS_
713                 jlink_debug_buffer(buffer, byte_length);
714 #endif
715
716                 if (jtag_read_buffer(buffer, command) != ERROR_OK)
717                 {
718                         jlink_tap_init();
719                         return ERROR_JTAG_QUEUE_FAILED;
720                 }
721
722                 if (pending_scan_result->buffer != NULL)
723                 {
724                         free(pending_scan_result->buffer);
725                 }
726         }
727
728         jlink_tap_init();
729
730         return ERROR_OK;
731 }
732
733 /*****************************************************************************/
734 /* JLink USB low-level functions */
735
736 static jlink_jtag_t* jlink_usb_open()
737 {
738         struct usb_bus *busses;
739         struct usb_bus *bus;
740         struct usb_device *dev;
741
742         jlink_jtag_t *result;
743
744         result = (jlink_jtag_t*) malloc(sizeof(jlink_jtag_t));
745
746         usb_init();
747         usb_find_busses();
748         usb_find_devices();
749
750         busses = usb_get_busses();
751
752         /* find jlink_jtag device in usb bus */
753
754         for (bus = busses; bus; bus = bus->next)
755         {
756                 for (dev = bus->devices; dev; dev = dev->next)
757                 {
758                         if ((dev->descriptor.idVendor == VID) && (dev->descriptor.idProduct == PID))
759                         {
760                                 result->usb_handle = usb_open(dev);
761
762                                 /* usb_set_configuration required under win32 */
763                                 usb_set_configuration(result->usb_handle, dev->config[0].bConfigurationValue);
764                                 usb_claim_interface(result->usb_handle, 0);
765
766 #if 0
767                                 /*
768                                  * This makes problems under Mac OS X. And is not needed
769                                  * under Windows. Hopefully this will not break a linux build
770                                  */
771                                 usb_set_altinterface(result->usb_handle, 0);
772 #endif
773                                 return result;
774                         }
775                 }
776         }
777
778         free(result);
779         return NULL;
780 }
781
782 static void jlink_usb_close(jlink_jtag_t *jlink_jtag)
783 {
784         usb_close(jlink_jtag->usb_handle);
785         free(jlink_jtag);
786 }
787
788 /* Send a message and receive the reply. */
789 static int jlink_usb_message(jlink_jtag_t *jlink_jtag, int out_length, int in_length)
790 {
791         int result;
792         int result2;
793
794         result = jlink_usb_write(jlink_jtag, out_length);
795         if (result != out_length)
796         {
797                 LOG_ERROR("usb_bulk_write failed (requested=%d, result=%d)",
798                                 out_length, result);
799                 return ERROR_JTAG_DEVICE_ERROR;
800         }
801
802         result = jlink_usb_read(jlink_jtag, in_length);
803         if ((result != in_length) && (result != in_length + 1))
804         {
805                 LOG_ERROR("usb_bulk_read failed (requested=%d, result=%d)",
806                                 in_length, result);
807                 return ERROR_JTAG_DEVICE_ERROR;
808         }
809
810         if (result == in_length)
811         {
812                 /* Must read the result from the EMU too */
813                 result2 = jlink_usb_read_emu_result(jlink_jtag);
814                 if (1 != result2)
815                 {
816                         LOG_ERROR("jlink_usb_read_emu_result failed "
817                                 "(requested=1, result=%d)", result2);
818                         return ERROR_JTAG_DEVICE_ERROR;
819                 }
820
821                 /* Check the result itself */
822                 result2 = usb_emu_result_buffer[0];
823         }
824         else
825         {
826                 /* Save the result, then remove it from return value */
827                 result2 = usb_in_buffer[result--];
828         }
829
830         if (result2)
831         {
832                 LOG_ERROR("jlink_usb_message failed with result=%d)", result2);
833                 return ERROR_JTAG_DEVICE_ERROR;
834         }
835
836         return result;
837 }
838
839 /* calls the given usb_bulk_* function, allowing for the data to trickle in with some timeouts  */
840 static int usb_bulk_with_retries(
841                 int (*f)(usb_dev_handle *, int, char *, int, int),
842                 usb_dev_handle *dev, int ep,
843                 char *bytes, int size, int timeout)
844 {
845         int rc = 0, tries = 3, this_size;
846
847         while (tries && size) {
848
849                 this_size = f(dev, ep, bytes, size, timeout);
850                 if (this_size > 0) {
851                         
852                         size -= this_size;
853                         rc += this_size;
854                         bytes += this_size;
855
856                 } else
857                         tries --;
858         }
859         return rc;
860 }
861 static inline int usb_bulk_write_ex(usb_dev_handle *dev, int ep,
862                 char *bytes, int size, int timeout)
863 {
864         return usb_bulk_with_retries(&usb_bulk_write,
865                         dev, ep, bytes, size, timeout);
866 }
867 static inline int usb_bulk_read_ex(usb_dev_handle *dev, int ep,
868                 char *bytes, int size, int timeout)
869 {
870         return usb_bulk_with_retries(&usb_bulk_read,
871                         dev, ep, bytes, size, timeout);
872 }
873
874 /* Write data from out_buffer to USB. */
875 static int jlink_usb_write(jlink_jtag_t *jlink_jtag, int out_length)
876 {
877         int result;
878
879         if (out_length > JLINK_OUT_BUFFER_SIZE)
880         {
881                 LOG_ERROR("jlink_jtag_write illegal out_length=%d (max=%d)", out_length, JLINK_OUT_BUFFER_SIZE);
882                 return -1;
883         }
884
885         result = usb_bulk_write_ex(jlink_jtag->usb_handle, JLINK_WRITE_ENDPOINT,
886                 (char *)usb_out_buffer, out_length, JLINK_USB_TIMEOUT);
887
888         DEBUG_JTAG_IO("jlink_usb_write, out_length = %d, result = %d", out_length, result);
889
890 #ifdef _DEBUG_USB_COMMS_
891         jlink_debug_buffer(usb_out_buffer, out_length);
892 #endif
893         return result;
894 }
895
896 /* Read data from USB into in_buffer. */
897 static int jlink_usb_read(jlink_jtag_t *jlink_jtag, int expected_size)
898 {
899         int result = usb_bulk_read_ex(jlink_jtag->usb_handle, JLINK_READ_ENDPOINT,
900                 (char *)usb_in_buffer, expected_size, JLINK_USB_TIMEOUT);
901
902         DEBUG_JTAG_IO("jlink_usb_read, result = %d", result);
903
904 #ifdef _DEBUG_USB_COMMS_
905         jlink_debug_buffer(usb_in_buffer, result);
906 #endif
907         return result;
908 }
909
910 /* Read the result from the previous EMU cmd into result_buffer. */
911 static int jlink_usb_read_emu_result(jlink_jtag_t *jlink_jtag)
912 {
913         int result = usb_bulk_read_ex(jlink_jtag->usb_handle, JLINK_READ_ENDPOINT,
914                 (char *)usb_emu_result_buffer, 1 /* JLINK_EMU_RESULT_BUFFER_SIZE */,
915                 JLINK_USB_TIMEOUT);
916
917         DEBUG_JTAG_IO("jlink_usb_read_result, result = %d", result);
918
919 #ifdef _DEBUG_USB_COMMS_
920         jlink_debug_buffer(usb_emu_result_buffer, result);
921 #endif
922         return result;
923 }
924
925 #ifdef _DEBUG_USB_COMMS_
926 #define BYTES_PER_LINE  16
927
928 static void jlink_debug_buffer(u8 *buffer, int length)
929 {
930         char line[81];
931         char s[4];
932         int i;
933         int j;
934
935         for (i = 0; i < length; i += BYTES_PER_LINE)
936         {
937                 snprintf(line, 5, "%04x", i);
938                 for (j = i; j < i + BYTES_PER_LINE && j < length; j++)
939                 {
940                         snprintf(s, 4, " %02x", buffer[j]);
941                         strcat(line, s);
942                 }
943                 LOG_DEBUG("%s", line);
944         }
945 }
946 #endif