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