]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/buspirate.c
CMSIS-DAP: auto-detect CMSIS-DAP USB VID:PID
[openocd] / src / jtag / drivers / buspirate.c
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  ***************************************************************************/
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <jtag/interface.h>
27 #include <jtag/commands.h>
28
29 #include <termios.h>
30 #include <fcntl.h>
31 #include <sys/ioctl.h>
32
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);
38
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);
45
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
55
56 /* Not all OSes have this speed defined */
57 #if !defined(B1000000)
58 #define  B1000000 0010010
59 #endif
60
61 enum {
62         MODE_HIZ = 0,
63         MODE_JTAG = 1,          /* push-pull outputs */
64         MODE_JTAG_OD = 2,       /* open-drain outputs */
65 };
66
67 enum {
68         FEATURE_LED = 0x01,
69         FEATURE_VREG = 0x02,
70         FEATURE_TRST = 0x04,
71         FEATURE_SRST = 0x08,
72         FEATURE_PULLUP = 0x10
73 };
74
75 enum {
76         ACTION_DISABLE = 0,
77         ACTION_ENABLE = 1
78 };
79
80 enum {
81         SERIAL_NORMAL = 0,
82         SERIAL_FAST = 1
83 };
84
85 static const cc_t SHORT_TIMEOUT  = 1; /* Must be at least 1. */
86 static const cc_t NORMAL_TIMEOUT = 10;
87
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;
94
95 static enum tap_state last_tap_state = TAP_RESET;
96
97
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);
105
106 static void buspirate_reset(int trst, int srst);
107
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);
116
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);
124
125 static int buspirate_execute_queue(void)
126 {
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;
132
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));
167
168                         buspirate_end_state(cmd->cmd.scan
169                                         ->end_state);
170
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);
176
177                         break;
178                 case JTAG_RESET:
179                         DEBUG_JTAG_IO("reset trst: %i srst %i",
180                                 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
181
182                         /* flush buffers, so we can reset */
183                         buspirate_tap_execute();
184
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);
198                 }
199
200                 cmd = cmd->next;
201         }
202
203         return buspirate_tap_execute();
204 }
205
206
207 /* Returns true if successful, false if error. */
208
209 static bool read_and_discard_all_data(const int fd)
210 {
211         /* LOG_INFO("Discarding any stale data from a previous connection..."); */
212
213         bool was_msg_already_printed = false;
214
215         for ( ; ; ) {
216                 char buffer[1024];  /* Any size will do, it's a trade-off between stack size and performance. */
217
218                 const ssize_t read_count = read(fd, buffer, sizeof(buffer));
219
220                 if (read_count == 0) {
221                         /* This is the "end of file" or "connection closed at the other end" condition. */
222                         return true;
223                 }
224
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;
229                         }
230
231                         continue;
232                 }
233
234                 assert(read_count == -1);  /* According to the specification. */
235
236                 const int errno_code = errno;
237
238                 if (errno_code == EINTR)
239                         continue;
240
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;
246                 }
247
248                 /* Some other error has occurred. */
249                 return false;
250         }
251 }
252
253
254 static int buspirate_init(void)
255 {
256         if (buspirate_port == NULL) {
257                 LOG_ERROR("You need to specify the serial port!");
258                 return ERROR_JTAG_INIT_FAILED;
259         }
260
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;
265         }
266
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.
271
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.
276
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. */
279
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;
283         }
284
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;
288         }
289
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;
293         }
294
295         buspirate_jtag_enable(buspirate_fd);
296
297         if (buspirate_baudrate != SERIAL_NORMAL)
298                 buspirate_jtag_set_speed(buspirate_fd, SERIAL_FAST);
299
300         LOG_INFO("Buspirate Interface ready!");
301
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);
309
310         return ERROR_OK;
311 }
312
313 static int buspirate_quit(void)
314 {
315         LOG_INFO("Shutting down buspirate.");
316         buspirate_jtag_set_mode(buspirate_fd, MODE_HIZ);
317
318         buspirate_jtag_set_speed(buspirate_fd, SERIAL_NORMAL);
319         buspirate_jtag_reset(buspirate_fd);
320
321         buspirate_serial_close(buspirate_fd);
322
323         if (buspirate_port) {
324                 free(buspirate_port);
325                 buspirate_port = NULL;
326         }
327         return ERROR_OK;
328 }
329
330 /* openocd command interface */
331 COMMAND_HANDLER(buspirate_handle_adc_command)
332 {
333         if (buspirate_fd == -1)
334                 return ERROR_OK;
335
336         /* send the command */
337         buspirate_jtag_get_adcs(buspirate_fd);
338
339         return ERROR_OK;
340
341 }
342
343 COMMAND_HANDLER(buspirate_handle_vreg_command)
344 {
345         if (CMD_ARGC < 1)
346                 return ERROR_COMMAND_SYNTAX_ERROR;
347
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>");
354
355         return ERROR_OK;
356
357 }
358
359 COMMAND_HANDLER(buspirate_handle_pullup_command)
360 {
361         if (CMD_ARGC < 1)
362                 return ERROR_COMMAND_SYNTAX_ERROR;
363
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>");
370
371         return ERROR_OK;
372
373 }
374
375 COMMAND_HANDLER(buspirate_handle_led_command)
376 {
377         if (CMD_ARGC < 1)
378                 return ERROR_COMMAND_SYNTAX_ERROR;
379
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>");
390         }
391
392         return ERROR_OK;
393
394 }
395
396 COMMAND_HANDLER(buspirate_handle_mode_command)
397 {
398         if (CMD_ARGC < 1)
399                 return ERROR_COMMAND_SYNTAX_ERROR;
400
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>");
407
408         return ERROR_OK;
409
410 }
411
412 COMMAND_HANDLER(buspirate_handle_speed_command)
413 {
414         if (CMD_ARGC < 1)
415                 return ERROR_COMMAND_SYNTAX_ERROR;
416
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>");
423
424         return ERROR_OK;
425
426 }
427
428 COMMAND_HANDLER(buspirate_handle_port_command)
429 {
430         if (CMD_ARGC < 1)
431                 return ERROR_COMMAND_SYNTAX_ERROR;
432
433         if (buspirate_port == NULL)
434                 buspirate_port = strdup(CMD_ARGV[0]);
435
436         return ERROR_OK;
437
438 }
439
440 static const struct command_registration buspirate_command_handlers[] = {
441         {
442                 .name = "buspirate_adc",
443                 .handler = &buspirate_handle_adc_command,
444                 .mode = COMMAND_EXEC,
445                 .help = "reads voltages on adc pins",
446         },
447         {
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",
453         },
454         {
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",
460         },
461         {
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",
467         },
468         {
469                 .name = "buspirate_speed",
470                 .usage = "<normal|fast>",
471                 .handler = &buspirate_handle_speed_command,
472                 .mode = COMMAND_CONFIG,
473                 .help = "speed of the interface",
474         },
475         {
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",
481         },
482         {
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",
488         },
489         COMMAND_REGISTRATION_DONE
490 };
491
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
498 };
499
500 /*************** jtag execute commands **********************/
501 static void buspirate_end_state(tap_state_t state)
502 {
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);
508         }
509 }
510
511 static void buspirate_state_move(void)
512 {
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());
518
519         for (i = 0; i < tms_count; i++) {
520                 tms = (tms_scan >> i) & 1;
521                 buspirate_tap_append(tms, 0);
522         }
523
524         tap_set_state(tap_get_end_state());
525 }
526
527 static void buspirate_path_move(int num_states, tap_state_t *path)
528 {
529         int i;
530
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);
543                 }
544
545                 tap_set_state(path[i]);
546         }
547
548         tap_set_end_state(tap_get_state());
549 }
550
551 static void buspirate_runtest(int num_cycles)
552 {
553         int i;
554
555         tap_state_t saved_end_state = tap_get_end_state();
556
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();
561         }
562
563         for (i = 0; i < num_cycles; i++)
564                 buspirate_tap_append(0, 0);
565
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()));
569
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();
574 }
575
576 static void buspirate_scan(bool ir_scan, enum scan_type type,
577         uint8_t *buffer, int scan_size, struct scan_command *command)
578 {
579         tap_state_t saved_end_state;
580
581         buspirate_tap_make_space(1, scan_size+8);
582         /* is 8 correct ? (2 moves = 16) */
583
584         saved_end_state = tap_get_end_state();
585
586         buspirate_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
587
588         /* Only move if we're not already there */
589         if (tap_get_state() != tap_get_end_state())
590                 buspirate_state_move();
591
592         buspirate_tap_append_scan(scan_size, buffer, command);
593
594         /* move to PAUSE */
595         buspirate_tap_append(0, 0);
596
597         /* restore the saved state */
598         buspirate_end_state(saved_end_state);
599         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
600
601         if (tap_get_state() != tap_get_end_state())
602                 buspirate_state_move();
603 }
604
605
606 /************************* TAP related stuff **********/
607
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
611
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
622
623 static char tms_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
624 static char tdi_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
625 static int tap_chain_index;
626
627 struct pending_scan_result /* this was stolen from arm-jtag-ew */
628 {
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;
633 };
634
635 static struct pending_scan_result
636 tap_pending_scans[BUSPIRATE_MAX_PENDING_SCANS];
637 static int tap_pending_scans_num;
638
639 static void buspirate_tap_init(void)
640 {
641         tap_chain_index = 0;
642         tap_pending_scans_num = 0;
643 }
644
645 static int buspirate_tap_execute(void)
646 {
647         static const int CMD_TAP_SHIFT_HEADER_LEN = 3;
648
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;
655
656         if (tap_chain_index <= 0)
657                 return ERROR_OK;
658
659         LOG_DEBUG("executing tap num bits = %i scans = %i",
660                         tap_chain_index, tap_pending_scans_num);
661
662         bytes_to_send = DIV_ROUND_UP(tap_chain_index, 8);
663
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 */
667
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++;
674         }
675
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);
682         }
683
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;
688         }
689
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;
694         }
695         in_buf = (uint8_t *)(&tmp[CMD_TAP_SHIFT_HEADER_LEN]);
696
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;
703
704                 /* copy bits from buffer */
705                 buf_set_buf(in_buf, first, buffer, 0, length);
706
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;
711                 }
712
713                 free(buffer);
714         }
715         buspirate_tap_init();
716         return ERROR_OK;
717 }
718
719 static void buspirate_tap_make_space(int scans, int bits)
720 {
721         int have_scans = BUSPIRATE_MAX_PENDING_SCANS - tap_pending_scans_num;
722         int have_bits = BUSPIRATE_BUFFER_SIZE * 8 - tap_chain_index;
723
724         if ((have_scans < scans) || (have_bits < bits))
725                 buspirate_tap_execute();
726 }
727
728 static void buspirate_tap_append(int tms, int tdi)
729 {
730         int chain_index;
731
732         buspirate_tap_make_space(0, 1);
733         chain_index = tap_chain_index / 8;
734
735         if (chain_index < BUSPIRATE_BUFFER_SIZE) {
736                 int bit_index = tap_chain_index % 8;
737                 uint8_t bit = 1 << bit_index;
738
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;
750                 }
751
752                 if (tms)
753                         tms_chain[chain_index] |= bit;
754                 else
755                         tms_chain[chain_index] &= ~bit;
756
757                 if (tdi)
758                         tdi_chain[chain_index] |= bit;
759                 else
760                         tdi_chain[chain_index] &= ~bit;
761
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);
769         }
770 }
771
772 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
773                 struct scan_command *command)
774 {
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;
780
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);
785         }
786         tap_pending_scans_num++;
787 }
788
789 /*************** jtag wrapper functions *********************/
790
791 /* (1) assert or (0) deassert reset lines */
792 static void buspirate_reset(int trst, int srst)
793 {
794         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
795
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);
802
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);
809 }
810
811 /*************** jtag lowlevel functions ********************/
812 static void buspirate_jtag_enable(int fd)
813 {
814         int ret;
815         char tmp[21] = { [0 ... 20] = 0x00 };
816         int done = 0;
817         int cmd_sent = 0;
818
819         LOG_DEBUG("Entering binary mode");
820         buspirate_serial_write(fd, tmp, 20);
821         usleep(10000);
822
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);
830                 }
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);
837                         }
838                         if (tmp[0] != '1') {
839                                 LOG_ERROR("Unsupported binary protocol");
840                                 exit(-1);
841                         }
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);
849                                 }
850                         }
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);
857                 }
858         }
859
860 }
861
862 static void buspirate_jtag_reset(int fd)
863 {
864         char tmp[5];
865
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!");
876 }
877
878 static void buspirate_jtag_set_speed(int fd, char speed)
879 {
880         int ret;
881         char tmp[2];
882         char ack[2];
883
884         ack[0] = 0xAA;
885         ack[1] = 0x55;
886
887         tmp[0] = CMD_UART_SPEED;
888         tmp[1] = speed;
889         buspirate_jtag_command(fd, tmp, 2);
890
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);
895         }
896
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);
902         }
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);
906         }
907         LOG_INFO("Buspirate switched to %s mode",
908                 (speed == SERIAL_NORMAL) ? "normal" : "FAST");
909 }
910
911
912 static void buspirate_jtag_set_mode(int fd, char mode)
913 {
914         char tmp[2];
915         tmp[0] = CMD_PORT_MODE;
916         tmp[1] = mode;
917         buspirate_jtag_command(fd, tmp, 2);
918 }
919
920 static void buspirate_jtag_set_feature(int fd, char feat, char action)
921 {
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);
927 }
928
929 static void buspirate_jtag_get_adcs(int fd)
930 {
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];
939
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);
944 }
945
946 static unsigned char buspirate_jtag_command(int fd,
947                 char *cmd, int cmdlen)
948 {
949         int res;
950         int len = 0;
951
952         res = buspirate_serial_write(fd, cmd, cmdlen);
953
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;
959
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 !");
970                 }
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;
979 }
980
981 /* low level serial port */
982 /* TODO add support for WIN32 and others ! */
983 static int buspirate_serial_open(char *port)
984 {
985         int fd;
986         fd = open(buspirate_port, O_RDWR | O_NOCTTY | O_NDELAY);
987         return fd;
988 }
989
990
991 /* Returns -1 on error. */
992
993 static int buspirate_serial_setspeed(int fd, char speed, cc_t timeout)
994 {
995         struct termios t_opt;
996         speed_t baud = (speed == SERIAL_FAST) ? B1000000 : B115200;
997
998         /* set the serial port parameters */
999         fcntl(fd, F_SETFL, 0);
1000         if (0 != tcgetattr(fd, &t_opt))
1001                 return -1;
1002
1003         if (0 != cfsetispeed(&t_opt, baud))
1004                 return -1;
1005
1006         if (0 != cfsetospeed(&t_opt, baud))
1007                 return -1;
1008
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);
1015
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);
1020
1021         t_opt.c_oflag &= ~OPOST;
1022         t_opt.c_cc[VMIN] = 0;
1023         t_opt.c_cc[VTIME] = timeout;
1024
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;
1033         }
1034
1035         return 0;
1036 }
1037
1038 static int buspirate_serial_write(int fd, char *buf, int size)
1039 {
1040         int ret = 0;
1041
1042         ret = write(fd, buf, size);
1043
1044         LOG_DEBUG("size = %d ret = %d", size, ret);
1045         buspirate_print_buffer(buf, size);
1046
1047         if (ret != size)
1048                 LOG_ERROR("Error sending data");
1049
1050         return ret;
1051 }
1052
1053 static int buspirate_serial_read(int fd, char *buf, int size)
1054 {
1055         int len = 0;
1056         int ret = 0;
1057         int timeout = 0;
1058
1059         while (len < size) {
1060                 ret = read(fd, buf+len, size-len);
1061                 if (ret == -1)
1062                         return -1;
1063
1064                 if (ret == 0) {
1065                         timeout++;
1066
1067                         if (timeout >= 10)
1068                                 break;
1069
1070                         continue;
1071                 }
1072
1073                 len += ret;
1074         }
1075
1076         LOG_DEBUG("should have read = %d actual size = %d", size, len);
1077         buspirate_print_buffer(buf, len);
1078
1079         if (len != size)
1080                 LOG_ERROR("Error reading data");
1081
1082         return len;
1083 }
1084
1085 static void buspirate_serial_close(int fd)
1086 {
1087         close(fd);
1088 }
1089
1090 #define LINE_SIZE      81
1091 #define BYTES_PER_LINE 16
1092 static void buspirate_print_buffer(char *buf, int size)
1093 {
1094         char line[LINE_SIZE];
1095         char tmp[10];
1096         int offset = 0;
1097
1098         line[0] = 0;
1099         while (offset < size) {
1100                 snprintf(tmp, 5, "%02x ", (uint8_t)buf[offset]);
1101                 offset++;
1102
1103                 strcat(line, tmp);
1104
1105                 if (offset % BYTES_PER_LINE == 0) {
1106                         LOG_DEBUG("%s", line);
1107                         line[0] = 0;
1108                 }
1109         }
1110
1111         if (line[0] != 0)
1112                 LOG_DEBUG("%s", line);
1113 }