Support hla_serial command for ST-LINK adapters.
[openocd.git] / src / jtag / drivers / buspirate.c
blob12d34b9d784a7c56137c89046420c82dc851d72c
1 /***************************************************************************
2 * Copyright (C) 2010 by Michal Demin *
3 * based on usbprog.c and arm-jtag-ew.c *
4 * Several fixes by R. Diez in 2013. *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
20 ***************************************************************************/
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
26 #include <jtag/interface.h>
27 #include <jtag/commands.h>
29 #include <termios.h>
30 #include <fcntl.h>
31 #include <sys/ioctl.h>
33 #undef DEBUG_SERIAL
34 /*#define DEBUG_SERIAL */
35 static int buspirate_execute_queue(void);
36 static int buspirate_init(void);
37 static int buspirate_quit(void);
39 static void buspirate_end_state(tap_state_t state);
40 static void buspirate_state_move(void);
41 static void buspirate_path_move(int num_states, tap_state_t *path);
42 static void buspirate_runtest(int num_cycles);
43 static void buspirate_scan(bool ir_scan, enum scan_type type,
44 uint8_t *buffer, int scan_size, struct scan_command *command);
46 #define CMD_UNKNOWN 0x00
47 #define CMD_PORT_MODE 0x01
48 #define CMD_FEATURE 0x02
49 #define CMD_READ_ADCS 0x03
50 /*#define CMD_TAP_SHIFT 0x04 // old protocol */
51 #define CMD_TAP_SHIFT 0x05
52 #define CMD_ENTER_OOCD 0x06
53 #define CMD_UART_SPEED 0x07
54 #define CMD_JTAG_SPEED 0x08
56 /* Not all OSes have this speed defined */
57 #if !defined(B1000000)
58 #define B1000000 0010010
59 #endif
61 enum {
62 MODE_HIZ = 0,
63 MODE_JTAG = 1, /* push-pull outputs */
64 MODE_JTAG_OD = 2, /* open-drain outputs */
67 enum {
68 FEATURE_LED = 0x01,
69 FEATURE_VREG = 0x02,
70 FEATURE_TRST = 0x04,
71 FEATURE_SRST = 0x08,
72 FEATURE_PULLUP = 0x10
75 enum {
76 ACTION_DISABLE = 0,
77 ACTION_ENABLE = 1
80 enum {
81 SERIAL_NORMAL = 0,
82 SERIAL_FAST = 1
85 static const cc_t SHORT_TIMEOUT = 1; /* Must be at least 1. */
86 static const cc_t NORMAL_TIMEOUT = 10;
88 static int buspirate_fd = -1;
89 static int buspirate_pinmode = MODE_JTAG_OD;
90 static int buspirate_baudrate = SERIAL_NORMAL;
91 static int buspirate_vreg;
92 static int buspirate_pullup;
93 static char *buspirate_port;
95 static enum tap_state last_tap_state = TAP_RESET;
98 /* TAP interface */
99 static void buspirate_tap_init(void);
100 static int buspirate_tap_execute(void);
101 static void buspirate_tap_append(int tms, int tdi);
102 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
103 struct scan_command *command);
104 static void buspirate_tap_make_space(int scan, int bits);
106 static void buspirate_reset(int trst, int srst);
108 /* low level interface */
109 static void buspirate_jtag_reset(int);
110 static void buspirate_jtag_enable(int);
111 static unsigned char buspirate_jtag_command(int, char *, int);
112 static void buspirate_jtag_set_speed(int, char);
113 static void buspirate_jtag_set_mode(int, char);
114 static void buspirate_jtag_set_feature(int, char, char);
115 static void buspirate_jtag_get_adcs(int);
117 /* low level HW communication interface */
118 static int buspirate_serial_open(char *port);
119 static int buspirate_serial_setspeed(int fd, char speed, cc_t timeout);
120 static int buspirate_serial_write(int fd, char *buf, int size);
121 static int buspirate_serial_read(int fd, char *buf, int size);
122 static void buspirate_serial_close(int fd);
123 static void buspirate_print_buffer(char *buf, int size);
125 static int buspirate_execute_queue(void)
127 /* currently processed command */
128 struct jtag_command *cmd = jtag_command_queue;
129 int scan_size;
130 enum scan_type type;
131 uint8_t *buffer;
133 while (cmd) {
134 switch (cmd->type) {
135 case JTAG_RUNTEST:
136 DEBUG_JTAG_IO("runtest %i cycles, end in %s",
137 cmd->cmd.runtest->num_cycles,
138 tap_state_name(cmd->cmd.runtest
139 ->end_state));
140 buspirate_end_state(cmd->cmd.runtest
141 ->end_state);
142 buspirate_runtest(cmd->cmd.runtest
143 ->num_cycles);
144 break;
145 case JTAG_TLR_RESET:
146 DEBUG_JTAG_IO("statemove end in %s",
147 tap_state_name(cmd->cmd.statemove
148 ->end_state));
149 buspirate_end_state(cmd->cmd.statemove
150 ->end_state);
151 buspirate_state_move();
152 break;
153 case JTAG_PATHMOVE:
154 DEBUG_JTAG_IO("pathmove: %i states, end in %s",
155 cmd->cmd.pathmove->num_states,
156 tap_state_name(cmd->cmd.pathmove
157 ->path[cmd->cmd.pathmove
158 ->num_states - 1]));
159 buspirate_path_move(cmd->cmd.pathmove
160 ->num_states,
161 cmd->cmd.pathmove->path);
162 break;
163 case JTAG_SCAN:
164 DEBUG_JTAG_IO("scan end in %s",
165 tap_state_name(cmd->cmd.scan
166 ->end_state));
168 buspirate_end_state(cmd->cmd.scan
169 ->end_state);
171 scan_size = jtag_build_buffer(cmd->cmd.scan,
172 &buffer);
173 type = jtag_scan_type(cmd->cmd.scan);
174 buspirate_scan(cmd->cmd.scan->ir_scan, type,
175 buffer, scan_size, cmd->cmd.scan);
177 break;
178 case JTAG_RESET:
179 DEBUG_JTAG_IO("reset trst: %i srst %i",
180 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
182 /* flush buffers, so we can reset */
183 buspirate_tap_execute();
185 if (cmd->cmd.reset->trst == 1)
186 tap_set_state(TAP_RESET);
187 buspirate_reset(cmd->cmd.reset->trst,
188 cmd->cmd.reset->srst);
189 break;
190 case JTAG_SLEEP:
191 DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
192 buspirate_tap_execute();
193 jtag_sleep(cmd->cmd.sleep->us);
194 break;
195 default:
196 LOG_ERROR("BUG: unknown JTAG command type encountered");
197 exit(-1);
200 cmd = cmd->next;
203 return buspirate_tap_execute();
207 /* Returns true if successful, false if error. */
209 static bool read_and_discard_all_data(const int fd)
211 /* LOG_INFO("Discarding any stale data from a previous connection..."); */
213 bool was_msg_already_printed = false;
215 for ( ; ; ) {
216 char buffer[1024]; /* Any size will do, it's a trade-off between stack size and performance. */
218 const ssize_t read_count = read(fd, buffer, sizeof(buffer));
220 if (read_count == 0) {
221 /* This is the "end of file" or "connection closed at the other end" condition. */
222 return true;
225 if (read_count > 0) {
226 if (!was_msg_already_printed) {
227 LOG_INFO("Some stale data from a previous connection was discarded.");
228 was_msg_already_printed = true;
231 continue;
234 assert(read_count == -1); /* According to the specification. */
236 const int errno_code = errno;
238 if (errno_code == EINTR)
239 continue;
241 if (errno_code == EAGAIN ||
242 errno_code == EWOULDBLOCK) {
243 /* We know that the file descriptor has been opened with O_NONBLOCK or O_NDELAY,
244 and these codes mean that there is no data to read at present. */
245 return true;
248 /* Some other error has occurred. */
249 return false;
254 static int buspirate_init(void)
256 if (buspirate_port == NULL) {
257 LOG_ERROR("You need to specify the serial port!");
258 return ERROR_JTAG_INIT_FAILED;
261 buspirate_fd = buspirate_serial_open(buspirate_port);
262 if (buspirate_fd == -1) {
263 LOG_ERROR("Could not open serial port");
264 return ERROR_JTAG_INIT_FAILED;
267 /* The Operating System or the device itself may deliver stale data from the last connection,
268 so discard all available bytes right after the new connection has been established.
269 After all, we are implementing here a master/slave protocol, so the slave should have nothing
270 to say until the master sends the first command.
272 In the past, there was a tcflush() call in buspirate_serial_setspeed(), but that
273 was not enough. I guess you must actively read from the serial port to trigger any
274 data collection from the device and/or lower USB layers. If you disable the serial port
275 read timeout (if you set SHORT_TIMEOUT to 0), then the discarding does not work any more.
277 Note that we are lowering the serial port timeout for this first read operation,
278 otherwise the normal initialisation would be delayed for too long. */
280 if (-1 == buspirate_serial_setspeed(buspirate_fd, SERIAL_NORMAL, SHORT_TIMEOUT)) {
281 LOG_ERROR("Error configuring the serial port.");
282 return ERROR_JTAG_INIT_FAILED;
285 if (!read_and_discard_all_data(buspirate_fd)) {
286 LOG_ERROR("Error while attempting to discard any stale data right after establishing the connection.");
287 return ERROR_JTAG_INIT_FAILED;
290 if (-1 == buspirate_serial_setspeed(buspirate_fd, SERIAL_NORMAL, NORMAL_TIMEOUT)) {
291 LOG_ERROR("Error configuring the serial port.");
292 return ERROR_JTAG_INIT_FAILED;
295 buspirate_jtag_enable(buspirate_fd);
297 if (buspirate_baudrate != SERIAL_NORMAL)
298 buspirate_jtag_set_speed(buspirate_fd, SERIAL_FAST);
300 LOG_INFO("Buspirate Interface ready!");
302 buspirate_tap_init();
303 buspirate_jtag_set_mode(buspirate_fd, buspirate_pinmode);
304 buspirate_jtag_set_feature(buspirate_fd, FEATURE_VREG,
305 (buspirate_vreg == 1) ? ACTION_ENABLE : ACTION_DISABLE);
306 buspirate_jtag_set_feature(buspirate_fd, FEATURE_PULLUP,
307 (buspirate_pullup == 1) ? ACTION_ENABLE : ACTION_DISABLE);
308 buspirate_reset(0, 0);
310 return ERROR_OK;
313 static int buspirate_quit(void)
315 LOG_INFO("Shutting down buspirate.");
316 buspirate_jtag_set_mode(buspirate_fd, MODE_HIZ);
318 buspirate_jtag_set_speed(buspirate_fd, SERIAL_NORMAL);
319 buspirate_jtag_reset(buspirate_fd);
321 buspirate_serial_close(buspirate_fd);
323 if (buspirate_port) {
324 free(buspirate_port);
325 buspirate_port = NULL;
327 return ERROR_OK;
330 /* openocd command interface */
331 COMMAND_HANDLER(buspirate_handle_adc_command)
333 if (buspirate_fd == -1)
334 return ERROR_OK;
336 /* send the command */
337 buspirate_jtag_get_adcs(buspirate_fd);
339 return ERROR_OK;
343 COMMAND_HANDLER(buspirate_handle_vreg_command)
345 if (CMD_ARGC < 1)
346 return ERROR_COMMAND_SYNTAX_ERROR;
348 if (atoi(CMD_ARGV[0]) == 1)
349 buspirate_vreg = 1;
350 else if (atoi(CMD_ARGV[0]) == 0)
351 buspirate_vreg = 0;
352 else
353 LOG_ERROR("usage: buspirate_vreg <1|0>");
355 return ERROR_OK;
359 COMMAND_HANDLER(buspirate_handle_pullup_command)
361 if (CMD_ARGC < 1)
362 return ERROR_COMMAND_SYNTAX_ERROR;
364 if (atoi(CMD_ARGV[0]) == 1)
365 buspirate_pullup = 1;
366 else if (atoi(CMD_ARGV[0]) == 0)
367 buspirate_pullup = 0;
368 else
369 LOG_ERROR("usage: buspirate_pullup <1|0>");
371 return ERROR_OK;
375 COMMAND_HANDLER(buspirate_handle_led_command)
377 if (CMD_ARGC < 1)
378 return ERROR_COMMAND_SYNTAX_ERROR;
380 if (atoi(CMD_ARGV[0]) == 1) {
381 /* enable led */
382 buspirate_jtag_set_feature(buspirate_fd, FEATURE_LED,
383 ACTION_ENABLE);
384 } else if (atoi(CMD_ARGV[0]) == 0) {
385 /* disable led */
386 buspirate_jtag_set_feature(buspirate_fd, FEATURE_LED,
387 ACTION_DISABLE);
388 } else {
389 LOG_ERROR("usage: buspirate_led <1|0>");
392 return ERROR_OK;
396 COMMAND_HANDLER(buspirate_handle_mode_command)
398 if (CMD_ARGC < 1)
399 return ERROR_COMMAND_SYNTAX_ERROR;
401 if (CMD_ARGV[0][0] == 'n')
402 buspirate_pinmode = MODE_JTAG;
403 else if (CMD_ARGV[0][0] == 'o')
404 buspirate_pinmode = MODE_JTAG_OD;
405 else
406 LOG_ERROR("usage: buspirate_mode <normal|open-drain>");
408 return ERROR_OK;
412 COMMAND_HANDLER(buspirate_handle_speed_command)
414 if (CMD_ARGC < 1)
415 return ERROR_COMMAND_SYNTAX_ERROR;
417 if (CMD_ARGV[0][0] == 'n')
418 buspirate_baudrate = SERIAL_NORMAL;
419 else if (CMD_ARGV[0][0] == 'f')
420 buspirate_baudrate = SERIAL_FAST;
421 else
422 LOG_ERROR("usage: buspirate_speed <normal|fast>");
424 return ERROR_OK;
428 COMMAND_HANDLER(buspirate_handle_port_command)
430 if (CMD_ARGC < 1)
431 return ERROR_COMMAND_SYNTAX_ERROR;
433 if (buspirate_port == NULL)
434 buspirate_port = strdup(CMD_ARGV[0]);
436 return ERROR_OK;
440 static const struct command_registration buspirate_command_handlers[] = {
442 .name = "buspirate_adc",
443 .handler = &buspirate_handle_adc_command,
444 .mode = COMMAND_EXEC,
445 .help = "reads voltages on adc pins",
448 .name = "buspirate_vreg",
449 .usage = "<1|0>",
450 .handler = &buspirate_handle_vreg_command,
451 .mode = COMMAND_CONFIG,
452 .help = "changes the state of voltage regulators",
455 .name = "buspirate_pullup",
456 .usage = "<1|0>",
457 .handler = &buspirate_handle_pullup_command,
458 .mode = COMMAND_CONFIG,
459 .help = "changes the state of pullup",
462 .name = "buspirate_led",
463 .usage = "<1|0>",
464 .handler = &buspirate_handle_led_command,
465 .mode = COMMAND_EXEC,
466 .help = "changes the state of led",
469 .name = "buspirate_speed",
470 .usage = "<normal|fast>",
471 .handler = &buspirate_handle_speed_command,
472 .mode = COMMAND_CONFIG,
473 .help = "speed of the interface",
476 .name = "buspirate_mode",
477 .usage = "<normal|open-drain>",
478 .handler = &buspirate_handle_mode_command,
479 .mode = COMMAND_CONFIG,
480 .help = "pin mode of the interface",
483 .name = "buspirate_port",
484 .usage = "/dev/ttyUSB0",
485 .handler = &buspirate_handle_port_command,
486 .mode = COMMAND_CONFIG,
487 .help = "name of the serial port to open",
489 COMMAND_REGISTRATION_DONE
492 struct jtag_interface buspirate_interface = {
493 .name = "buspirate",
494 .execute_queue = buspirate_execute_queue,
495 .commands = buspirate_command_handlers,
496 .init = buspirate_init,
497 .quit = buspirate_quit
500 /*************** jtag execute commands **********************/
501 static void buspirate_end_state(tap_state_t state)
503 if (tap_is_state_stable(state))
504 tap_set_end_state(state);
505 else {
506 LOG_ERROR("BUG: %i is not a valid end state", state);
507 exit(-1);
511 static void buspirate_state_move(void)
513 int i = 0, tms = 0;
514 uint8_t tms_scan = tap_get_tms_path(tap_get_state(),
515 tap_get_end_state());
516 int tms_count = tap_get_tms_path_len(tap_get_state(),
517 tap_get_end_state());
519 for (i = 0; i < tms_count; i++) {
520 tms = (tms_scan >> i) & 1;
521 buspirate_tap_append(tms, 0);
524 tap_set_state(tap_get_end_state());
527 static void buspirate_path_move(int num_states, tap_state_t *path)
529 int i;
531 for (i = 0; i < num_states; i++) {
532 if (tap_state_transition(tap_get_state(), false) == path[i]) {
533 buspirate_tap_append(0, 0);
534 } else if (tap_state_transition(tap_get_state(), true)
535 == path[i]) {
536 buspirate_tap_append(1, 0);
537 } else {
538 LOG_ERROR("BUG: %s -> %s isn't a valid "
539 "TAP transition",
540 tap_state_name(tap_get_state()),
541 tap_state_name(path[i]));
542 exit(-1);
545 tap_set_state(path[i]);
548 tap_set_end_state(tap_get_state());
551 static void buspirate_runtest(int num_cycles)
553 int i;
555 tap_state_t saved_end_state = tap_get_end_state();
557 /* only do a state_move when we're not already in IDLE */
558 if (tap_get_state() != TAP_IDLE) {
559 buspirate_end_state(TAP_IDLE);
560 buspirate_state_move();
563 for (i = 0; i < num_cycles; i++)
564 buspirate_tap_append(0, 0);
566 DEBUG_JTAG_IO("runtest: cur_state %s end_state %s",
567 tap_state_name(tap_get_state()),
568 tap_state_name(tap_get_end_state()));
570 /* finish in end_state */
571 buspirate_end_state(saved_end_state);
572 if (tap_get_state() != tap_get_end_state())
573 buspirate_state_move();
576 static void buspirate_scan(bool ir_scan, enum scan_type type,
577 uint8_t *buffer, int scan_size, struct scan_command *command)
579 tap_state_t saved_end_state;
581 buspirate_tap_make_space(1, scan_size+8);
582 /* is 8 correct ? (2 moves = 16) */
584 saved_end_state = tap_get_end_state();
586 buspirate_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
588 /* Only move if we're not already there */
589 if (tap_get_state() != tap_get_end_state())
590 buspirate_state_move();
592 buspirate_tap_append_scan(scan_size, buffer, command);
594 /* move to PAUSE */
595 buspirate_tap_append(0, 0);
597 /* restore the saved state */
598 buspirate_end_state(saved_end_state);
599 tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
601 if (tap_get_state() != tap_get_end_state())
602 buspirate_state_move();
606 /************************* TAP related stuff **********/
608 /* This buffer size matches the maximum CMD_TAP_SHIFT bit length in the Bus Pirate firmware,
609 look for constant 0x2000 in OpenOCD.c . */
610 #define BUSPIRATE_BUFFER_SIZE 1024
612 /* The old value of 32 scans was not enough to achieve near 100% utilisation ratio
613 for the current BUSPIRATE_BUFFER_SIZE value of 1024.
614 With 128 scans I am getting full USB 2.0 high speed packets (512 bytes long) when
615 using the JtagDue firmware on the Arduino Due instead of the Bus Pirate, which
616 amounts approximately to a 10% overall speed gain. Bigger packets should also
617 benefit the Bus Pirate, but the speed difference is much smaller.
618 Unfortunately, each 512-byte packet is followed by a 329-byte one, which is not ideal.
619 However, increasing BUSPIRATE_BUFFER_SIZE for the benefit of the JtagDue would
620 make it incompatible with the Bus Pirate firmware. */
621 #define BUSPIRATE_MAX_PENDING_SCANS 128
623 static char tms_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
624 static char tdi_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
625 static int tap_chain_index;
627 struct pending_scan_result /* this was stolen from arm-jtag-ew */
629 int first; /* First bit position in tdo_buffer to read */
630 int length; /* Number of bits to read */
631 struct scan_command *command; /* Corresponding scan command */
632 uint8_t *buffer;
635 static struct pending_scan_result
636 tap_pending_scans[BUSPIRATE_MAX_PENDING_SCANS];
637 static int tap_pending_scans_num;
639 static void buspirate_tap_init(void)
641 tap_chain_index = 0;
642 tap_pending_scans_num = 0;
645 static int buspirate_tap_execute(void)
647 static const int CMD_TAP_SHIFT_HEADER_LEN = 3;
649 char tmp[4096];
650 uint8_t *in_buf;
651 int i;
652 int fill_index = 0;
653 int ret;
654 int bytes_to_send;
656 if (tap_chain_index <= 0)
657 return ERROR_OK;
659 LOG_DEBUG("executing tap num bits = %i scans = %i",
660 tap_chain_index, tap_pending_scans_num);
662 bytes_to_send = DIV_ROUND_UP(tap_chain_index, 8);
664 tmp[0] = CMD_TAP_SHIFT; /* this command expects number of bits */
665 tmp[1] = (char)(tap_chain_index >> 8); /* high */
666 tmp[2] = (char)(tap_chain_index); /* low */
668 fill_index = CMD_TAP_SHIFT_HEADER_LEN;
669 for (i = 0; i < bytes_to_send; i++) {
670 tmp[fill_index] = tdi_chain[i];
671 fill_index++;
672 tmp[fill_index] = tms_chain[i];
673 fill_index++;
676 /* jlink.c calls the routine below, which may be useful for debugging purposes.
677 For example, enabling this allows you to compare the log outputs from jlink.c
678 and from this module for JTAG development or troubleshooting purposes. */
679 if (false) {
680 last_tap_state = jtag_debug_state_machine(tms_chain, tdi_chain,
681 tap_chain_index, last_tap_state);
684 ret = buspirate_serial_write(buspirate_fd, tmp, CMD_TAP_SHIFT_HEADER_LEN + bytes_to_send*2);
685 if (ret != bytes_to_send*2+CMD_TAP_SHIFT_HEADER_LEN) {
686 LOG_ERROR("error writing :(");
687 return ERROR_JTAG_DEVICE_ERROR;
690 ret = buspirate_serial_read(buspirate_fd, tmp, bytes_to_send + CMD_TAP_SHIFT_HEADER_LEN);
691 if (ret != bytes_to_send + CMD_TAP_SHIFT_HEADER_LEN) {
692 LOG_ERROR("error reading");
693 return ERROR_FAIL;
695 in_buf = (uint8_t *)(&tmp[CMD_TAP_SHIFT_HEADER_LEN]);
697 /* parse the scans */
698 for (i = 0; i < tap_pending_scans_num; i++) {
699 uint8_t *buffer = tap_pending_scans[i].buffer;
700 int length = tap_pending_scans[i].length;
701 int first = tap_pending_scans[i].first;
702 struct scan_command *command = tap_pending_scans[i].command;
704 /* copy bits from buffer */
705 buf_set_buf(in_buf, first, buffer, 0, length);
707 /* return buffer to higher level */
708 if (jtag_read_buffer(buffer, command) != ERROR_OK) {
709 buspirate_tap_init();
710 return ERROR_JTAG_QUEUE_FAILED;
713 free(buffer);
715 buspirate_tap_init();
716 return ERROR_OK;
719 static void buspirate_tap_make_space(int scans, int bits)
721 int have_scans = BUSPIRATE_MAX_PENDING_SCANS - tap_pending_scans_num;
722 int have_bits = BUSPIRATE_BUFFER_SIZE * 8 - tap_chain_index;
724 if ((have_scans < scans) || (have_bits < bits))
725 buspirate_tap_execute();
728 static void buspirate_tap_append(int tms, int tdi)
730 int chain_index;
732 buspirate_tap_make_space(0, 1);
733 chain_index = tap_chain_index / 8;
735 if (chain_index < BUSPIRATE_BUFFER_SIZE) {
736 int bit_index = tap_chain_index % 8;
737 uint8_t bit = 1 << bit_index;
739 if (0 == bit_index) {
740 /* Let's say that the TAP shift operation wants to shift 9 bits,
741 so we will be sending to the Bus Pirate a bit count of 9 but still
742 full 16 bits (2 bytes) of shift data.
743 If we don't clear all bits at this point, the last 7 bits will contain
744 random data from the last buffer contents, which is not pleasant to the eye.
745 Besides, the Bus Pirate (or some clone) may want to assert in debug builds
746 that, after consuming all significant data bits, the rest of them are zero.
747 Therefore, for aesthetic and for assert purposes, we clear all bits below. */
748 tms_chain[chain_index] = 0;
749 tdi_chain[chain_index] = 0;
752 if (tms)
753 tms_chain[chain_index] |= bit;
754 else
755 tms_chain[chain_index] &= ~bit;
757 if (tdi)
758 tdi_chain[chain_index] |= bit;
759 else
760 tdi_chain[chain_index] &= ~bit;
762 tap_chain_index++;
763 } else {
764 LOG_ERROR("tap_chain overflow, bad things will happen");
765 /* Exit abruptly, like jlink.c does. After a buffer overflow we don't want
766 to carry on, as data will be corrupt. Another option would be to return
767 some error code at this point. */
768 exit(-1);
772 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
773 struct scan_command *command)
775 int i;
776 tap_pending_scans[tap_pending_scans_num].length = length;
777 tap_pending_scans[tap_pending_scans_num].buffer = buffer;
778 tap_pending_scans[tap_pending_scans_num].command = command;
779 tap_pending_scans[tap_pending_scans_num].first = tap_chain_index;
781 for (i = 0; i < length; i++) {
782 int tms = (i < length-1 ? 0 : 1);
783 int tdi = (buffer[i/8] >> (i%8)) & 1;
784 buspirate_tap_append(tms, tdi);
786 tap_pending_scans_num++;
789 /*************** jtag wrapper functions *********************/
791 /* (1) assert or (0) deassert reset lines */
792 static void buspirate_reset(int trst, int srst)
794 LOG_DEBUG("trst: %i, srst: %i", trst, srst);
796 if (trst)
797 buspirate_jtag_set_feature(buspirate_fd,
798 FEATURE_TRST, ACTION_DISABLE);
799 else
800 buspirate_jtag_set_feature(buspirate_fd,
801 FEATURE_TRST, ACTION_ENABLE);
803 if (srst)
804 buspirate_jtag_set_feature(buspirate_fd,
805 FEATURE_SRST, ACTION_DISABLE);
806 else
807 buspirate_jtag_set_feature(buspirate_fd,
808 FEATURE_SRST, ACTION_ENABLE);
811 /*************** jtag lowlevel functions ********************/
812 static void buspirate_jtag_enable(int fd)
814 int ret;
815 char tmp[21] = { [0 ... 20] = 0x00 };
816 int done = 0;
817 int cmd_sent = 0;
819 LOG_DEBUG("Entering binary mode");
820 buspirate_serial_write(fd, tmp, 20);
821 usleep(10000);
823 /* reads 1 to n "BBIO1"s and one "OCD1" */
824 while (!done) {
825 ret = buspirate_serial_read(fd, tmp, 4);
826 if (ret != 4) {
827 LOG_ERROR("Buspirate error. Is binary"
828 "/OpenOCD support enabled?");
829 exit(-1);
831 if (strncmp(tmp, "BBIO", 4) == 0) {
832 ret = buspirate_serial_read(fd, tmp, 1);
833 if (ret != 1) {
834 LOG_ERROR("Buspirate did not answer correctly! "
835 "Do you have correct firmware?");
836 exit(-1);
838 if (tmp[0] != '1') {
839 LOG_ERROR("Unsupported binary protocol");
840 exit(-1);
842 if (cmd_sent == 0) {
843 cmd_sent = 1;
844 tmp[0] = CMD_ENTER_OOCD;
845 ret = buspirate_serial_write(fd, tmp, 1);
846 if (ret != 1) {
847 LOG_ERROR("error reading");
848 exit(-1);
851 } else if (strncmp(tmp, "OCD1", 4) == 0)
852 done = 1;
853 else {
854 LOG_ERROR("Buspirate did not answer correctly! "
855 "Do you have correct firmware?");
856 exit(-1);
862 static void buspirate_jtag_reset(int fd)
864 char tmp[5];
866 tmp[0] = 0x00; /* exit OCD1 mode */
867 buspirate_serial_write(fd, tmp, 1);
868 usleep(10000);
869 /* We ignore the return value here purposly, nothing we can do */
870 buspirate_serial_read(fd, tmp, 5);
871 if (strncmp(tmp, "BBIO1", 5) == 0) {
872 tmp[0] = 0x0F; /* reset BP */
873 buspirate_serial_write(fd, tmp, 1);
874 } else
875 LOG_ERROR("Unable to restart buspirate!");
878 static void buspirate_jtag_set_speed(int fd, char speed)
880 int ret;
881 char tmp[2];
882 char ack[2];
884 ack[0] = 0xAA;
885 ack[1] = 0x55;
887 tmp[0] = CMD_UART_SPEED;
888 tmp[1] = speed;
889 buspirate_jtag_command(fd, tmp, 2);
891 /* here the adapter changes speed, we need follow */
892 if (-1 == buspirate_serial_setspeed(fd, speed, NORMAL_TIMEOUT)) {
893 LOG_ERROR("Error configuring the serial port.");
894 exit(-1);
897 buspirate_serial_write(fd, ack, 2);
898 ret = buspirate_serial_read(fd, tmp, 2);
899 if (ret != 2) {
900 LOG_ERROR("Buspirate did not ack speed change");
901 exit(-1);
903 if ((tmp[0] != CMD_UART_SPEED) || (tmp[1] != speed)) {
904 LOG_ERROR("Buspirate did not reply as expected to the speed change command");
905 exit(-1);
907 LOG_INFO("Buspirate switched to %s mode",
908 (speed == SERIAL_NORMAL) ? "normal" : "FAST");
912 static void buspirate_jtag_set_mode(int fd, char mode)
914 char tmp[2];
915 tmp[0] = CMD_PORT_MODE;
916 tmp[1] = mode;
917 buspirate_jtag_command(fd, tmp, 2);
920 static void buspirate_jtag_set_feature(int fd, char feat, char action)
922 char tmp[3];
923 tmp[0] = CMD_FEATURE;
924 tmp[1] = feat; /* what */
925 tmp[2] = action; /* action */
926 buspirate_jtag_command(fd, tmp, 3);
929 static void buspirate_jtag_get_adcs(int fd)
931 uint8_t tmp[10];
932 uint16_t a, b, c, d;
933 tmp[0] = CMD_READ_ADCS;
934 buspirate_jtag_command(fd, (char *)tmp, 1);
935 a = tmp[2] << 8 | tmp[3];
936 b = tmp[4] << 8 | tmp[5];
937 c = tmp[6] << 8 | tmp[7];
938 d = tmp[8] << 8 | tmp[9];
940 LOG_INFO("ADC: ADC_Pin = %.02f VPullup = %.02f V33 = %.02f "
941 "V50 = %.02f",
942 ((float)a)/155.1515, ((float)b)/155.1515,
943 ((float)c)/155.1515, ((float)d)/155.1515);
946 static unsigned char buspirate_jtag_command(int fd,
947 char *cmd, int cmdlen)
949 int res;
950 int len = 0;
952 res = buspirate_serial_write(fd, cmd, cmdlen);
954 if ((cmd[0] == CMD_UART_SPEED)
955 || (cmd[0] == CMD_PORT_MODE)
956 || (cmd[0] == CMD_FEATURE)
957 || (cmd[0] == CMD_JTAG_SPEED))
958 return 1;
960 if (res == cmdlen) {
961 switch (cmd[0]) {
962 case CMD_READ_ADCS:
963 len = 10; /* 2*sizeof(char)+4*sizeof(uint16_t) */
964 break;
965 case CMD_TAP_SHIFT:
966 len = cmdlen;
967 break;
968 default:
969 LOG_INFO("Wrong !");
971 res = buspirate_serial_read(fd, cmd, len);
972 if (res > 0)
973 return (unsigned char)cmd[1];
974 else
975 return -1;
976 } else
977 return -1;
978 return 0;
981 /* low level serial port */
982 /* TODO add support for WIN32 and others ! */
983 static int buspirate_serial_open(char *port)
985 int fd;
986 fd = open(buspirate_port, O_RDWR | O_NOCTTY | O_NDELAY);
987 return fd;
991 /* Returns -1 on error. */
993 static int buspirate_serial_setspeed(int fd, char speed, cc_t timeout)
995 struct termios t_opt;
996 speed_t baud = (speed == SERIAL_FAST) ? B1000000 : B115200;
998 /* set the serial port parameters */
999 fcntl(fd, F_SETFL, 0);
1000 if (0 != tcgetattr(fd, &t_opt))
1001 return -1;
1003 if (0 != cfsetispeed(&t_opt, baud))
1004 return -1;
1006 if (0 != cfsetospeed(&t_opt, baud))
1007 return -1;
1009 t_opt.c_cflag |= (CLOCAL | CREAD);
1010 t_opt.c_cflag &= ~PARENB;
1011 t_opt.c_cflag &= ~CSTOPB;
1012 t_opt.c_cflag &= ~CSIZE;
1013 t_opt.c_cflag |= CS8;
1014 t_opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
1016 /* The serial port may have been configured for human interaction with
1017 the Bus Pirate console, but OpenOCD is going to use a binary protocol,
1018 so make sure to turn off any CR/LF translation and the like. */
1019 t_opt.c_iflag &= ~(IXON | IXOFF | IXANY | INLCR | ICRNL);
1021 t_opt.c_oflag &= ~OPOST;
1022 t_opt.c_cc[VMIN] = 0;
1023 t_opt.c_cc[VTIME] = timeout;
1025 /* Note that, in the past, TCSANOW was used below instead of TCSADRAIN,
1026 and CMD_UART_SPEED did not work properly then, at least with
1027 the Bus Pirate v3.5 (USB). */
1028 if (0 != tcsetattr(fd, TCSADRAIN, &t_opt)) {
1029 /* According to the Linux documentation, this is actually not enough
1030 to detect errors, you need to call tcgetattr() and check that
1031 all changes have been performed successfully. */
1032 return -1;
1035 return 0;
1038 static int buspirate_serial_write(int fd, char *buf, int size)
1040 int ret = 0;
1042 ret = write(fd, buf, size);
1044 LOG_DEBUG("size = %d ret = %d", size, ret);
1045 buspirate_print_buffer(buf, size);
1047 if (ret != size)
1048 LOG_ERROR("Error sending data");
1050 return ret;
1053 static int buspirate_serial_read(int fd, char *buf, int size)
1055 int len = 0;
1056 int ret = 0;
1057 int timeout = 0;
1059 while (len < size) {
1060 ret = read(fd, buf+len, size-len);
1061 if (ret == -1)
1062 return -1;
1064 if (ret == 0) {
1065 timeout++;
1067 if (timeout >= 10)
1068 break;
1070 continue;
1073 len += ret;
1076 LOG_DEBUG("should have read = %d actual size = %d", size, len);
1077 buspirate_print_buffer(buf, len);
1079 if (len != size)
1080 LOG_ERROR("Error reading data");
1082 return len;
1085 static void buspirate_serial_close(int fd)
1087 close(fd);
1090 #define LINE_SIZE 81
1091 #define BYTES_PER_LINE 16
1092 static void buspirate_print_buffer(char *buf, int size)
1094 char line[LINE_SIZE];
1095 char tmp[10];
1096 int offset = 0;
1098 line[0] = 0;
1099 while (offset < size) {
1100 snprintf(tmp, 5, "%02x ", (uint8_t)buf[offset]);
1101 offset++;
1103 strcat(line, tmp);
1105 if (offset % BYTES_PER_LINE == 0) {
1106 LOG_DEBUG("%s", line);
1107 line[0] = 0;
1111 if (line[0] != 0)
1112 LOG_DEBUG("%s", line);