]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/buspirate.c
Remove FSF address from GPL notices
[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, see <http://www.gnu.org/licenses/>. *
18  ***************************************************************************/
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include <jtag/interface.h>
25 #include <jtag/commands.h>
26
27 #include <termios.h>
28 #include <fcntl.h>
29 #include <sys/ioctl.h>
30
31 #undef DEBUG_SERIAL
32 /*#define DEBUG_SERIAL */
33 static int buspirate_execute_queue(void);
34 static int buspirate_init(void);
35 static int buspirate_quit(void);
36
37 static void buspirate_end_state(tap_state_t state);
38 static void buspirate_state_move(void);
39 static void buspirate_path_move(int num_states, tap_state_t *path);
40 static void buspirate_runtest(int num_cycles);
41 static void buspirate_scan(bool ir_scan, enum scan_type type,
42         uint8_t *buffer, int scan_size, struct scan_command *command);
43 static void buspirate_stableclocks(int num_cycles);
44
45 #define CMD_UNKNOWN       0x00
46 #define CMD_PORT_MODE     0x01
47 #define CMD_FEATURE       0x02
48 #define CMD_READ_ADCS     0x03
49 /*#define CMD_TAP_SHIFT     0x04 // old protocol */
50 #define CMD_TAP_SHIFT     0x05
51 #define CMD_ENTER_OOCD    0x06
52 #define CMD_UART_SPEED    0x07
53 #define CMD_JTAG_SPEED    0x08
54
55 /* Not all OSes have this speed defined */
56 #if !defined(B1000000)
57 #define  B1000000 0010010
58 #endif
59
60 enum {
61         MODE_HIZ = 0,
62         MODE_JTAG = 1,          /* push-pull outputs */
63         MODE_JTAG_OD = 2,       /* open-drain outputs */
64 };
65
66 enum {
67         FEATURE_LED = 0x01,
68         FEATURE_VREG = 0x02,
69         FEATURE_TRST = 0x04,
70         FEATURE_SRST = 0x08,
71         FEATURE_PULLUP = 0x10
72 };
73
74 enum {
75         ACTION_DISABLE = 0,
76         ACTION_ENABLE = 1
77 };
78
79 enum {
80         SERIAL_NORMAL = 0,
81         SERIAL_FAST = 1
82 };
83
84 static const cc_t SHORT_TIMEOUT  = 1; /* Must be at least 1. */
85 static const cc_t NORMAL_TIMEOUT = 10;
86
87 static int buspirate_fd = -1;
88 static int buspirate_pinmode = MODE_JTAG_OD;
89 static int buspirate_baudrate = SERIAL_NORMAL;
90 static int buspirate_vreg;
91 static int buspirate_pullup;
92 static char *buspirate_port;
93
94 static enum tap_state last_tap_state = TAP_RESET;
95
96
97 /* TAP interface */
98 static void buspirate_tap_init(void);
99 static int buspirate_tap_execute(void);
100 static void buspirate_tap_append(int tms, int tdi);
101 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
102                 struct scan_command *command);
103 static void buspirate_tap_make_space(int scan, int bits);
104
105 static void buspirate_reset(int trst, int srst);
106
107 /* low level interface */
108 static void buspirate_jtag_reset(int);
109 static void buspirate_jtag_enable(int);
110 static unsigned char buspirate_jtag_command(int, char *, int);
111 static void buspirate_jtag_set_speed(int, char);
112 static void buspirate_jtag_set_mode(int, char);
113 static void buspirate_jtag_set_feature(int, char, char);
114 static void buspirate_jtag_get_adcs(int);
115
116 /* low level HW communication interface */
117 static int buspirate_serial_open(char *port);
118 static int buspirate_serial_setspeed(int fd, char speed, cc_t timeout);
119 static int buspirate_serial_write(int fd, char *buf, int size);
120 static int buspirate_serial_read(int fd, char *buf, int size);
121 static void buspirate_serial_close(int fd);
122 static void buspirate_print_buffer(char *buf, int size);
123
124 static int buspirate_execute_queue(void)
125 {
126         /* currently processed command */
127         struct jtag_command *cmd = jtag_command_queue;
128         int scan_size;
129         enum scan_type type;
130         uint8_t *buffer;
131
132         while (cmd) {
133                 switch (cmd->type) {
134                 case JTAG_RUNTEST:
135                         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
136                                 cmd->cmd.runtest->num_cycles,
137                                 tap_state_name(cmd->cmd.runtest
138                                         ->end_state));
139                         buspirate_end_state(cmd->cmd.runtest
140                                         ->end_state);
141                         buspirate_runtest(cmd->cmd.runtest
142                                         ->num_cycles);
143                         break;
144                 case JTAG_TLR_RESET:
145                         DEBUG_JTAG_IO("statemove end in %s",
146                                 tap_state_name(cmd->cmd.statemove
147                                                 ->end_state));
148                         buspirate_end_state(cmd->cmd.statemove
149                                         ->end_state);
150                         buspirate_state_move();
151                         break;
152                 case JTAG_PATHMOVE:
153                         DEBUG_JTAG_IO("pathmove: %i states, end in %s",
154                                 cmd->cmd.pathmove->num_states,
155                                 tap_state_name(cmd->cmd.pathmove
156                                         ->path[cmd->cmd.pathmove
157                                                 ->num_states - 1]));
158                         buspirate_path_move(cmd->cmd.pathmove
159                                         ->num_states,
160                                         cmd->cmd.pathmove->path);
161                         break;
162                 case JTAG_SCAN:
163                         DEBUG_JTAG_IO("scan end in %s",
164                                 tap_state_name(cmd->cmd.scan
165                                         ->end_state));
166
167                         buspirate_end_state(cmd->cmd.scan
168                                         ->end_state);
169
170                         scan_size = jtag_build_buffer(cmd->cmd.scan,
171                                         &buffer);
172                         type = jtag_scan_type(cmd->cmd.scan);
173                         buspirate_scan(cmd->cmd.scan->ir_scan, type,
174                                 buffer, scan_size, cmd->cmd.scan);
175
176                         break;
177                 case JTAG_RESET:
178                         DEBUG_JTAG_IO("reset trst: %i srst %i",
179                                 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
180
181                         /* flush buffers, so we can reset */
182                         buspirate_tap_execute();
183
184                         if (cmd->cmd.reset->trst == 1)
185                                 tap_set_state(TAP_RESET);
186                         buspirate_reset(cmd->cmd.reset->trst,
187                                         cmd->cmd.reset->srst);
188                         break;
189                 case JTAG_SLEEP:
190                         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
191                         buspirate_tap_execute();
192                         jtag_sleep(cmd->cmd.sleep->us);
193                                 break;
194                 case JTAG_STABLECLOCKS:
195                         DEBUG_JTAG_IO("stable clock %i cycles", cmd->cmd.stableclocks->num_cycles);
196                         buspirate_stableclocks(cmd->cmd.stableclocks->num_cycles);
197                                 break;
198                 default:
199                         LOG_ERROR("BUG: unknown JTAG command type encountered");
200                         exit(-1);
201                 }
202
203                 cmd = cmd->next;
204         }
205
206         return buspirate_tap_execute();
207 }
208
209
210 /* Returns true if successful, false if error. */
211
212 static bool read_and_discard_all_data(const int fd)
213 {
214         /* LOG_INFO("Discarding any stale data from a previous connection..."); */
215
216         bool was_msg_already_printed = false;
217
218         for ( ; ; ) {
219                 char buffer[1024];  /* Any size will do, it's a trade-off between stack size and performance. */
220
221                 const ssize_t read_count = read(fd, buffer, sizeof(buffer));
222
223                 if (read_count == 0) {
224                         /* This is the "end of file" or "connection closed at the other end" condition. */
225                         return true;
226                 }
227
228                 if (read_count > 0) {
229                         if (!was_msg_already_printed)   {
230                                 LOG_INFO("Some stale data from a previous connection was discarded.");
231                                 was_msg_already_printed = true;
232                         }
233
234                         continue;
235                 }
236
237                 assert(read_count == -1);  /* According to the specification. */
238
239                 const int errno_code = errno;
240
241                 if (errno_code == EINTR)
242                         continue;
243
244                 if (errno_code == EAGAIN ||
245                         errno_code == EWOULDBLOCK) {
246                         /* We know that the file descriptor has been opened with O_NONBLOCK or O_NDELAY,
247                            and these codes mean that there is no data to read at present. */
248                         return true;
249                 }
250
251                 /* Some other error has occurred. */
252                 return false;
253         }
254 }
255
256
257 static int buspirate_init(void)
258 {
259         if (buspirate_port == NULL) {
260                 LOG_ERROR("You need to specify the serial port!");
261                 return ERROR_JTAG_INIT_FAILED;
262         }
263
264         buspirate_fd = buspirate_serial_open(buspirate_port);
265         if (buspirate_fd == -1) {
266                 LOG_ERROR("Could not open serial port");
267                 return ERROR_JTAG_INIT_FAILED;
268         }
269
270         /* The Operating System or the device itself may deliver stale data from the last connection,
271            so discard all available bytes right after the new connection has been established.
272            After all, we are implementing here a master/slave protocol, so the slave should have nothing
273            to say until the master sends the first command.
274
275            In the past, there was a tcflush() call in buspirate_serial_setspeed(), but that
276            was not enough. I guess you must actively read from the serial port to trigger any
277            data collection from the device and/or lower USB layers. If you disable the serial port
278            read timeout (if you set SHORT_TIMEOUT to 0), then the discarding does not work any more.
279
280            Note that we are lowering the serial port timeout for this first read operation,
281            otherwise the normal initialisation would be delayed for too long. */
282
283         if (-1 == buspirate_serial_setspeed(buspirate_fd, SERIAL_NORMAL, SHORT_TIMEOUT)) {
284                 LOG_ERROR("Error configuring the serial port.");
285                 return ERROR_JTAG_INIT_FAILED;
286         }
287
288         if (!read_and_discard_all_data(buspirate_fd)) {
289                 LOG_ERROR("Error while attempting to discard any stale data right after establishing the connection.");
290                 return ERROR_JTAG_INIT_FAILED;
291         }
292
293         if (-1 == buspirate_serial_setspeed(buspirate_fd, SERIAL_NORMAL, NORMAL_TIMEOUT)) {
294                 LOG_ERROR("Error configuring the serial port.");
295                 return ERROR_JTAG_INIT_FAILED;
296         }
297
298         buspirate_jtag_enable(buspirate_fd);
299
300         if (buspirate_baudrate != SERIAL_NORMAL)
301                 buspirate_jtag_set_speed(buspirate_fd, SERIAL_FAST);
302
303         LOG_INFO("Buspirate Interface ready!");
304
305         buspirate_tap_init();
306         buspirate_jtag_set_mode(buspirate_fd, buspirate_pinmode);
307         buspirate_jtag_set_feature(buspirate_fd, FEATURE_VREG,
308                 (buspirate_vreg == 1) ? ACTION_ENABLE : ACTION_DISABLE);
309         buspirate_jtag_set_feature(buspirate_fd, FEATURE_PULLUP,
310                 (buspirate_pullup == 1) ? ACTION_ENABLE : ACTION_DISABLE);
311         buspirate_reset(0, 0);
312
313         return ERROR_OK;
314 }
315
316 static int buspirate_quit(void)
317 {
318         LOG_INFO("Shutting down buspirate.");
319         buspirate_jtag_set_mode(buspirate_fd, MODE_HIZ);
320
321         buspirate_jtag_set_speed(buspirate_fd, SERIAL_NORMAL);
322         buspirate_jtag_reset(buspirate_fd);
323
324         buspirate_serial_close(buspirate_fd);
325
326         if (buspirate_port) {
327                 free(buspirate_port);
328                 buspirate_port = NULL;
329         }
330         return ERROR_OK;
331 }
332
333 /* openocd command interface */
334 COMMAND_HANDLER(buspirate_handle_adc_command)
335 {
336         if (buspirate_fd == -1)
337                 return ERROR_OK;
338
339         /* send the command */
340         buspirate_jtag_get_adcs(buspirate_fd);
341
342         return ERROR_OK;
343
344 }
345
346 COMMAND_HANDLER(buspirate_handle_vreg_command)
347 {
348         if (CMD_ARGC < 1)
349                 return ERROR_COMMAND_SYNTAX_ERROR;
350
351         if (atoi(CMD_ARGV[0]) == 1)
352                 buspirate_vreg = 1;
353         else if (atoi(CMD_ARGV[0]) == 0)
354                 buspirate_vreg = 0;
355         else
356                 LOG_ERROR("usage: buspirate_vreg <1|0>");
357
358         return ERROR_OK;
359
360 }
361
362 COMMAND_HANDLER(buspirate_handle_pullup_command)
363 {
364         if (CMD_ARGC < 1)
365                 return ERROR_COMMAND_SYNTAX_ERROR;
366
367         if (atoi(CMD_ARGV[0]) == 1)
368                 buspirate_pullup = 1;
369         else if (atoi(CMD_ARGV[0]) == 0)
370                 buspirate_pullup = 0;
371         else
372                 LOG_ERROR("usage: buspirate_pullup <1|0>");
373
374         return ERROR_OK;
375
376 }
377
378 COMMAND_HANDLER(buspirate_handle_led_command)
379 {
380         if (CMD_ARGC < 1)
381                 return ERROR_COMMAND_SYNTAX_ERROR;
382
383         if (atoi(CMD_ARGV[0]) == 1) {
384                 /* enable led */
385                 buspirate_jtag_set_feature(buspirate_fd, FEATURE_LED,
386                                 ACTION_ENABLE);
387         } else if (atoi(CMD_ARGV[0]) == 0) {
388                 /* disable led */
389                 buspirate_jtag_set_feature(buspirate_fd, FEATURE_LED,
390                                 ACTION_DISABLE);
391         } else {
392                 LOG_ERROR("usage: buspirate_led <1|0>");
393         }
394
395         return ERROR_OK;
396
397 }
398
399 COMMAND_HANDLER(buspirate_handle_mode_command)
400 {
401         if (CMD_ARGC < 1)
402                 return ERROR_COMMAND_SYNTAX_ERROR;
403
404         if (CMD_ARGV[0][0] == 'n')
405                 buspirate_pinmode = MODE_JTAG;
406         else if (CMD_ARGV[0][0] == 'o')
407                 buspirate_pinmode = MODE_JTAG_OD;
408         else
409                 LOG_ERROR("usage: buspirate_mode <normal|open-drain>");
410
411         return ERROR_OK;
412
413 }
414
415 COMMAND_HANDLER(buspirate_handle_speed_command)
416 {
417         if (CMD_ARGC < 1)
418                 return ERROR_COMMAND_SYNTAX_ERROR;
419
420         if (CMD_ARGV[0][0] == 'n')
421                 buspirate_baudrate = SERIAL_NORMAL;
422         else if (CMD_ARGV[0][0] == 'f')
423                 buspirate_baudrate = SERIAL_FAST;
424         else
425                 LOG_ERROR("usage: buspirate_speed <normal|fast>");
426
427         return ERROR_OK;
428
429 }
430
431 COMMAND_HANDLER(buspirate_handle_port_command)
432 {
433         if (CMD_ARGC < 1)
434                 return ERROR_COMMAND_SYNTAX_ERROR;
435
436         if (buspirate_port == NULL)
437                 buspirate_port = strdup(CMD_ARGV[0]);
438
439         return ERROR_OK;
440
441 }
442
443 static const struct command_registration buspirate_command_handlers[] = {
444         {
445                 .name = "buspirate_adc",
446                 .handler = &buspirate_handle_adc_command,
447                 .mode = COMMAND_EXEC,
448                 .help = "reads voltages on adc pins",
449         },
450         {
451                 .name = "buspirate_vreg",
452                 .usage = "<1|0>",
453                 .handler = &buspirate_handle_vreg_command,
454                 .mode = COMMAND_CONFIG,
455                 .help = "changes the state of voltage regulators",
456         },
457         {
458                 .name = "buspirate_pullup",
459                 .usage = "<1|0>",
460                 .handler = &buspirate_handle_pullup_command,
461                 .mode = COMMAND_CONFIG,
462                 .help = "changes the state of pullup",
463         },
464         {
465                 .name = "buspirate_led",
466                 .usage = "<1|0>",
467                 .handler = &buspirate_handle_led_command,
468                 .mode = COMMAND_EXEC,
469                 .help = "changes the state of led",
470         },
471         {
472                 .name = "buspirate_speed",
473                 .usage = "<normal|fast>",
474                 .handler = &buspirate_handle_speed_command,
475                 .mode = COMMAND_CONFIG,
476                 .help = "speed of the interface",
477         },
478         {
479                 .name = "buspirate_mode",
480                 .usage = "<normal|open-drain>",
481                 .handler = &buspirate_handle_mode_command,
482                 .mode = COMMAND_CONFIG,
483                 .help = "pin mode of the interface",
484         },
485         {
486                 .name = "buspirate_port",
487                 .usage = "/dev/ttyUSB0",
488                 .handler = &buspirate_handle_port_command,
489                 .mode = COMMAND_CONFIG,
490                 .help = "name of the serial port to open",
491         },
492         COMMAND_REGISTRATION_DONE
493 };
494
495 struct jtag_interface buspirate_interface = {
496         .name = "buspirate",
497         .execute_queue = buspirate_execute_queue,
498         .commands = buspirate_command_handlers,
499         .init = buspirate_init,
500         .quit = buspirate_quit
501 };
502
503 /*************** jtag execute commands **********************/
504 static void buspirate_end_state(tap_state_t state)
505 {
506         if (tap_is_state_stable(state))
507                 tap_set_end_state(state);
508         else {
509                 LOG_ERROR("BUG: %i is not a valid end state", state);
510                 exit(-1);
511         }
512 }
513
514 static void buspirate_state_move(void)
515 {
516         int i = 0, tms = 0;
517         uint8_t tms_scan = tap_get_tms_path(tap_get_state(),
518                         tap_get_end_state());
519         int tms_count = tap_get_tms_path_len(tap_get_state(),
520                         tap_get_end_state());
521
522         for (i = 0; i < tms_count; i++) {
523                 tms = (tms_scan >> i) & 1;
524                 buspirate_tap_append(tms, 0);
525         }
526
527         tap_set_state(tap_get_end_state());
528 }
529
530 static void buspirate_path_move(int num_states, tap_state_t *path)
531 {
532         int i;
533
534         for (i = 0; i < num_states; i++) {
535                 if (tap_state_transition(tap_get_state(), false) == path[i]) {
536                         buspirate_tap_append(0, 0);
537                 } else if (tap_state_transition(tap_get_state(), true)
538                                 == path[i]) {
539                         buspirate_tap_append(1, 0);
540                 } else {
541                         LOG_ERROR("BUG: %s -> %s isn't a valid "
542                                 "TAP transition",
543                                 tap_state_name(tap_get_state()),
544                                 tap_state_name(path[i]));
545                         exit(-1);
546                 }
547
548                 tap_set_state(path[i]);
549         }
550
551         tap_set_end_state(tap_get_state());
552 }
553
554 static void buspirate_runtest(int num_cycles)
555 {
556         int i;
557
558         tap_state_t saved_end_state = tap_get_end_state();
559
560         /* only do a state_move when we're not already in IDLE */
561         if (tap_get_state() != TAP_IDLE) {
562                 buspirate_end_state(TAP_IDLE);
563                 buspirate_state_move();
564         }
565
566         for (i = 0; i < num_cycles; i++)
567                 buspirate_tap_append(0, 0);
568
569         DEBUG_JTAG_IO("runtest: cur_state %s end_state %s",
570                         tap_state_name(tap_get_state()),
571                         tap_state_name(tap_get_end_state()));
572
573         /* finish in end_state */
574         buspirate_end_state(saved_end_state);
575         if (tap_get_state() != tap_get_end_state())
576                 buspirate_state_move();
577 }
578
579 static void buspirate_scan(bool ir_scan, enum scan_type type,
580         uint8_t *buffer, int scan_size, struct scan_command *command)
581 {
582         tap_state_t saved_end_state;
583
584         buspirate_tap_make_space(1, scan_size+8);
585         /* is 8 correct ? (2 moves = 16) */
586
587         saved_end_state = tap_get_end_state();
588
589         buspirate_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
590
591         /* Only move if we're not already there */
592         if (tap_get_state() != tap_get_end_state())
593                 buspirate_state_move();
594
595         buspirate_tap_append_scan(scan_size, buffer, command);
596
597         /* move to PAUSE */
598         buspirate_tap_append(0, 0);
599
600         /* restore the saved state */
601         buspirate_end_state(saved_end_state);
602         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
603
604         if (tap_get_state() != tap_get_end_state())
605                 buspirate_state_move();
606 }
607
608 static void buspirate_stableclocks(int num_cycles)
609 {
610         int i;
611         int tms = (tap_get_state() == TAP_RESET ? 1 : 0);
612
613         buspirate_tap_make_space(0, num_cycles);
614
615         for (i = 0; i < num_cycles; i++)
616                 buspirate_tap_append(tms, 0);
617 }
618
619 /************************* TAP related stuff **********/
620
621 /* This buffer size matches the maximum CMD_TAP_SHIFT bit length in the Bus Pirate firmware,
622    look for constant 0x2000 in OpenOCD.c . */
623 #define BUSPIRATE_BUFFER_SIZE 1024
624
625 /* The old value of 32 scans was not enough to achieve near 100% utilisation ratio
626    for the current BUSPIRATE_BUFFER_SIZE value of 1024.
627    With 128 scans I am getting full USB 2.0 high speed packets (512 bytes long) when
628    using the JtagDue firmware on the Arduino Due instead of the Bus Pirate, which
629    amounts approximately to a 10% overall speed gain. Bigger packets should also
630    benefit the Bus Pirate, but the speed difference is much smaller.
631    Unfortunately, each 512-byte packet is followed by a 329-byte one, which is not ideal.
632    However, increasing BUSPIRATE_BUFFER_SIZE for the benefit of the JtagDue would
633    make it incompatible with the Bus Pirate firmware. */
634 #define BUSPIRATE_MAX_PENDING_SCANS 128
635
636 static char tms_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
637 static char tdi_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
638 static int tap_chain_index;
639
640 struct pending_scan_result /* this was stolen from arm-jtag-ew */
641 {
642         int first; /* First bit position in tdo_buffer to read */
643         int length; /* Number of bits to read */
644         struct scan_command *command; /* Corresponding scan command */
645         uint8_t *buffer;
646 };
647
648 static struct pending_scan_result
649 tap_pending_scans[BUSPIRATE_MAX_PENDING_SCANS];
650 static int tap_pending_scans_num;
651
652 static void buspirate_tap_init(void)
653 {
654         tap_chain_index = 0;
655         tap_pending_scans_num = 0;
656 }
657
658 static int buspirate_tap_execute(void)
659 {
660         static const int CMD_TAP_SHIFT_HEADER_LEN = 3;
661
662         char tmp[4096];
663         uint8_t *in_buf;
664         int i;
665         int fill_index = 0;
666         int ret;
667         int bytes_to_send;
668
669         if (tap_chain_index <= 0)
670                 return ERROR_OK;
671
672         LOG_DEBUG("executing tap num bits = %i scans = %i",
673                         tap_chain_index, tap_pending_scans_num);
674
675         bytes_to_send = DIV_ROUND_UP(tap_chain_index, 8);
676
677         tmp[0] = CMD_TAP_SHIFT; /* this command expects number of bits */
678         tmp[1] = (char)(tap_chain_index >> 8);  /* high */
679         tmp[2] = (char)(tap_chain_index);  /* low */
680
681         fill_index = CMD_TAP_SHIFT_HEADER_LEN;
682         for (i = 0; i < bytes_to_send; i++) {
683                 tmp[fill_index] = tdi_chain[i];
684                 fill_index++;
685                 tmp[fill_index] = tms_chain[i];
686                 fill_index++;
687         }
688
689         /* jlink.c calls the routine below, which may be useful for debugging purposes.
690            For example, enabling this allows you to compare the log outputs from jlink.c
691            and from this module for JTAG development or troubleshooting purposes. */
692         if (false) {
693                 last_tap_state = jtag_debug_state_machine(tms_chain, tdi_chain,
694                                                                                                   tap_chain_index, last_tap_state);
695         }
696
697         ret = buspirate_serial_write(buspirate_fd, tmp, CMD_TAP_SHIFT_HEADER_LEN + bytes_to_send*2);
698         if (ret != bytes_to_send*2+CMD_TAP_SHIFT_HEADER_LEN) {
699                 LOG_ERROR("error writing :(");
700                 return ERROR_JTAG_DEVICE_ERROR;
701         }
702
703         ret = buspirate_serial_read(buspirate_fd, tmp, bytes_to_send + CMD_TAP_SHIFT_HEADER_LEN);
704         if (ret != bytes_to_send + CMD_TAP_SHIFT_HEADER_LEN) {
705                 LOG_ERROR("error reading");
706                 return ERROR_FAIL;
707         }
708         in_buf = (uint8_t *)(&tmp[CMD_TAP_SHIFT_HEADER_LEN]);
709
710         /* parse the scans */
711         for (i = 0; i < tap_pending_scans_num; i++) {
712                 uint8_t *buffer = tap_pending_scans[i].buffer;
713                 int length = tap_pending_scans[i].length;
714                 int first = tap_pending_scans[i].first;
715                 struct scan_command *command = tap_pending_scans[i].command;
716
717                 /* copy bits from buffer */
718                 buf_set_buf(in_buf, first, buffer, 0, length);
719
720                 /* return buffer to higher level */
721                 if (jtag_read_buffer(buffer, command) != ERROR_OK) {
722                         buspirate_tap_init();
723                         return ERROR_JTAG_QUEUE_FAILED;
724                 }
725
726                 free(buffer);
727         }
728         buspirate_tap_init();
729         return ERROR_OK;
730 }
731
732 static void buspirate_tap_make_space(int scans, int bits)
733 {
734         int have_scans = BUSPIRATE_MAX_PENDING_SCANS - tap_pending_scans_num;
735         int have_bits = BUSPIRATE_BUFFER_SIZE * 8 - tap_chain_index;
736
737         if ((have_scans < scans) || (have_bits < bits))
738                 buspirate_tap_execute();
739 }
740
741 static void buspirate_tap_append(int tms, int tdi)
742 {
743         int chain_index;
744
745         buspirate_tap_make_space(0, 1);
746         chain_index = tap_chain_index / 8;
747
748         if (chain_index < BUSPIRATE_BUFFER_SIZE) {
749                 int bit_index = tap_chain_index % 8;
750                 uint8_t bit = 1 << bit_index;
751
752                 if (0 == bit_index) {
753                         /* Let's say that the TAP shift operation wants to shift 9 bits,
754                            so we will be sending to the Bus Pirate a bit count of 9 but still
755                            full 16 bits (2 bytes) of shift data.
756                            If we don't clear all bits at this point, the last 7 bits will contain
757                            random data from the last buffer contents, which is not pleasant to the eye.
758                            Besides, the Bus Pirate (or some clone) may want to assert in debug builds
759                            that, after consuming all significant data bits, the rest of them are zero.
760                            Therefore, for aesthetic and for assert purposes, we clear all bits below. */
761                         tms_chain[chain_index] = 0;
762                         tdi_chain[chain_index] = 0;
763                 }
764
765                 if (tms)
766                         tms_chain[chain_index] |= bit;
767                 else
768                         tms_chain[chain_index] &= ~bit;
769
770                 if (tdi)
771                         tdi_chain[chain_index] |= bit;
772                 else
773                         tdi_chain[chain_index] &= ~bit;
774
775                 tap_chain_index++;
776         } else {
777                 LOG_ERROR("tap_chain overflow, bad things will happen");
778                 /* Exit abruptly, like jlink.c does. After a buffer overflow we don't want
779                    to carry on, as data will be corrupt. Another option would be to return
780                    some error code at this point. */
781                 exit(-1);
782         }
783 }
784
785 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
786                 struct scan_command *command)
787 {
788         int i;
789         tap_pending_scans[tap_pending_scans_num].length = length;
790         tap_pending_scans[tap_pending_scans_num].buffer = buffer;
791         tap_pending_scans[tap_pending_scans_num].command = command;
792         tap_pending_scans[tap_pending_scans_num].first = tap_chain_index;
793
794         for (i = 0; i < length; i++) {
795                 int tms = (i < length-1 ? 0 : 1);
796                 int tdi = (buffer[i/8] >> (i%8)) & 1;
797                 buspirate_tap_append(tms, tdi);
798         }
799         tap_pending_scans_num++;
800 }
801
802 /*************** jtag wrapper functions *********************/
803
804 /* (1) assert or (0) deassert reset lines */
805 static void buspirate_reset(int trst, int srst)
806 {
807         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
808
809         if (trst)
810                 buspirate_jtag_set_feature(buspirate_fd,
811                                 FEATURE_TRST, ACTION_DISABLE);
812         else
813                 buspirate_jtag_set_feature(buspirate_fd,
814                                 FEATURE_TRST, ACTION_ENABLE);
815
816         if (srst)
817                 buspirate_jtag_set_feature(buspirate_fd,
818                                 FEATURE_SRST, ACTION_DISABLE);
819         else
820                 buspirate_jtag_set_feature(buspirate_fd,
821                                 FEATURE_SRST, ACTION_ENABLE);
822 }
823
824 /*************** jtag lowlevel functions ********************/
825 static void buspirate_jtag_enable(int fd)
826 {
827         int ret;
828         char tmp[21] = { [0 ... 20] = 0x00 };
829         int done = 0;
830         int cmd_sent = 0;
831
832         LOG_DEBUG("Entering binary mode");
833         buspirate_serial_write(fd, tmp, 20);
834         usleep(10000);
835
836         /* reads 1 to n "BBIO1"s and one "OCD1" */
837         while (!done) {
838                 ret = buspirate_serial_read(fd, tmp, 4);
839                 if (ret != 4) {
840                         LOG_ERROR("Buspirate error. Is binary"
841                                 "/OpenOCD support enabled?");
842                         exit(-1);
843                 }
844                 if (strncmp(tmp, "BBIO", 4) == 0) {
845                         ret = buspirate_serial_read(fd, tmp, 1);
846                         if (ret != 1) {
847                                 LOG_ERROR("Buspirate did not answer correctly! "
848                                         "Do you have correct firmware?");
849                                 exit(-1);
850                         }
851                         if (tmp[0] != '1') {
852                                 LOG_ERROR("Unsupported binary protocol");
853                                 exit(-1);
854                         }
855                         if (cmd_sent == 0) {
856                                 cmd_sent = 1;
857                                 tmp[0] = CMD_ENTER_OOCD;
858                                 ret = buspirate_serial_write(fd, tmp, 1);
859                                 if (ret != 1) {
860                                         LOG_ERROR("error reading");
861                                         exit(-1);
862                                 }
863                         }
864                 } else if (strncmp(tmp, "OCD1", 4) == 0)
865                         done = 1;
866                 else {
867                         LOG_ERROR("Buspirate did not answer correctly! "
868                                 "Do you have correct firmware?");
869                         exit(-1);
870                 }
871         }
872
873 }
874
875 static void buspirate_jtag_reset(int fd)
876 {
877         char tmp[5];
878
879         tmp[0] = 0x00; /* exit OCD1 mode */
880         buspirate_serial_write(fd, tmp, 1);
881         usleep(10000);
882         /* We ignore the return value here purposly, nothing we can do */
883         buspirate_serial_read(fd, tmp, 5);
884         if (strncmp(tmp, "BBIO1", 5) == 0) {
885                 tmp[0] = 0x0F; /*  reset BP */
886                 buspirate_serial_write(fd, tmp, 1);
887         } else
888                 LOG_ERROR("Unable to restart buspirate!");
889 }
890
891 static void buspirate_jtag_set_speed(int fd, char speed)
892 {
893         int ret;
894         char tmp[2];
895         char ack[2];
896
897         ack[0] = 0xAA;
898         ack[1] = 0x55;
899
900         tmp[0] = CMD_UART_SPEED;
901         tmp[1] = speed;
902         buspirate_jtag_command(fd, tmp, 2);
903
904         /* here the adapter changes speed, we need follow */
905         if (-1 == buspirate_serial_setspeed(fd, speed, NORMAL_TIMEOUT)) {
906                 LOG_ERROR("Error configuring the serial port.");
907                 exit(-1);
908         }
909
910         buspirate_serial_write(fd, ack, 2);
911         ret = buspirate_serial_read(fd, tmp, 2);
912         if (ret != 2) {
913                 LOG_ERROR("Buspirate did not ack speed change");
914                 exit(-1);
915         }
916         if ((tmp[0] != CMD_UART_SPEED) || (tmp[1] != speed)) {
917                 LOG_ERROR("Buspirate did not reply as expected to the speed change command");
918                 exit(-1);
919         }
920         LOG_INFO("Buspirate switched to %s mode",
921                 (speed == SERIAL_NORMAL) ? "normal" : "FAST");
922 }
923
924
925 static void buspirate_jtag_set_mode(int fd, char mode)
926 {
927         char tmp[2];
928         tmp[0] = CMD_PORT_MODE;
929         tmp[1] = mode;
930         buspirate_jtag_command(fd, tmp, 2);
931 }
932
933 static void buspirate_jtag_set_feature(int fd, char feat, char action)
934 {
935         char tmp[3];
936         tmp[0] = CMD_FEATURE;
937         tmp[1] = feat;   /* what */
938         tmp[2] = action; /* action */
939         buspirate_jtag_command(fd, tmp, 3);
940 }
941
942 static void buspirate_jtag_get_adcs(int fd)
943 {
944         uint8_t tmp[10];
945         uint16_t a, b, c, d;
946         tmp[0] = CMD_READ_ADCS;
947         buspirate_jtag_command(fd, (char *)tmp, 1);
948         a = tmp[2] << 8 | tmp[3];
949         b = tmp[4] << 8 | tmp[5];
950         c = tmp[6] << 8 | tmp[7];
951         d = tmp[8] << 8 | tmp[9];
952
953         LOG_INFO("ADC: ADC_Pin = %.02f VPullup = %.02f V33 = %.02f "
954                 "V50 = %.02f",
955                 ((float)a)/155.1515, ((float)b)/155.1515,
956                 ((float)c)/155.1515, ((float)d)/155.1515);
957 }
958
959 static unsigned char buspirate_jtag_command(int fd,
960                 char *cmd, int cmdlen)
961 {
962         int res;
963         int len = 0;
964
965         res = buspirate_serial_write(fd, cmd, cmdlen);
966
967         if ((cmd[0] == CMD_UART_SPEED)
968                                 || (cmd[0] == CMD_PORT_MODE)
969                                 || (cmd[0] == CMD_FEATURE)
970                                 || (cmd[0] == CMD_JTAG_SPEED))
971                 return 1;
972
973         if (res == cmdlen) {
974                 switch (cmd[0]) {
975                 case CMD_READ_ADCS:
976                         len = 10; /* 2*sizeof(char)+4*sizeof(uint16_t) */
977                         break;
978                 case CMD_TAP_SHIFT:
979                         len = cmdlen;
980                         break;
981                 default:
982                         LOG_INFO("Wrong !");
983                 }
984                 res =  buspirate_serial_read(fd, cmd, len);
985                 if (res > 0)
986                         return (unsigned char)cmd[1];
987                 else
988                         return -1;
989         } else
990                 return -1;
991         return 0;
992 }
993
994 /* low level serial port */
995 /* TODO add support for WIN32 and others ! */
996 static int buspirate_serial_open(char *port)
997 {
998         int fd;
999         fd = open(buspirate_port, O_RDWR | O_NOCTTY | O_NDELAY);
1000         return fd;
1001 }
1002
1003
1004 /* Returns -1 on error. */
1005
1006 static int buspirate_serial_setspeed(int fd, char speed, cc_t timeout)
1007 {
1008         struct termios t_opt;
1009         speed_t baud = (speed == SERIAL_FAST) ? B1000000 : B115200;
1010
1011         /* set the serial port parameters */
1012         fcntl(fd, F_SETFL, 0);
1013         if (0 != tcgetattr(fd, &t_opt))
1014                 return -1;
1015
1016         if (0 != cfsetispeed(&t_opt, baud))
1017                 return -1;
1018
1019         if (0 != cfsetospeed(&t_opt, baud))
1020                 return -1;
1021
1022         t_opt.c_cflag |= (CLOCAL | CREAD);
1023         t_opt.c_cflag &= ~PARENB;
1024         t_opt.c_cflag &= ~CSTOPB;
1025         t_opt.c_cflag &= ~CSIZE;
1026         t_opt.c_cflag |= CS8;
1027         t_opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
1028
1029         /* The serial port may have been configured for human interaction with
1030            the Bus Pirate console, but OpenOCD is going to use a binary protocol,
1031            so make sure to turn off any CR/LF translation and the like. */
1032         t_opt.c_iflag &= ~(IXON | IXOFF | IXANY | INLCR | ICRNL);
1033
1034         t_opt.c_oflag &= ~OPOST;
1035         t_opt.c_cc[VMIN] = 0;
1036         t_opt.c_cc[VTIME] = timeout;
1037
1038         /* Note that, in the past, TCSANOW was used below instead of TCSADRAIN,
1039            and CMD_UART_SPEED did not work properly then, at least with
1040            the Bus Pirate v3.5 (USB). */
1041         if (0 != tcsetattr(fd, TCSADRAIN, &t_opt)) {
1042                 /* According to the Linux documentation, this is actually not enough
1043                    to detect errors, you need to call tcgetattr() and check that
1044                    all changes have been performed successfully. */
1045                 return -1;
1046         }
1047
1048         return 0;
1049 }
1050
1051 static int buspirate_serial_write(int fd, char *buf, int size)
1052 {
1053         int ret = 0;
1054
1055         ret = write(fd, buf, size);
1056
1057         LOG_DEBUG("size = %d ret = %d", size, ret);
1058         buspirate_print_buffer(buf, size);
1059
1060         if (ret != size)
1061                 LOG_ERROR("Error sending data");
1062
1063         return ret;
1064 }
1065
1066 static int buspirate_serial_read(int fd, char *buf, int size)
1067 {
1068         int len = 0;
1069         int ret = 0;
1070         int timeout = 0;
1071
1072         while (len < size) {
1073                 ret = read(fd, buf+len, size-len);
1074                 if (ret == -1)
1075                         return -1;
1076
1077                 if (ret == 0) {
1078                         timeout++;
1079
1080                         if (timeout >= 10)
1081                                 break;
1082
1083                         continue;
1084                 }
1085
1086                 len += ret;
1087         }
1088
1089         LOG_DEBUG("should have read = %d actual size = %d", size, len);
1090         buspirate_print_buffer(buf, len);
1091
1092         if (len != size)
1093                 LOG_ERROR("Error reading data");
1094
1095         return len;
1096 }
1097
1098 static void buspirate_serial_close(int fd)
1099 {
1100         close(fd);
1101 }
1102
1103 #define LINE_SIZE      81
1104 #define BYTES_PER_LINE 16
1105 static void buspirate_print_buffer(char *buf, int size)
1106 {
1107         char line[LINE_SIZE];
1108         char tmp[10];
1109         int offset = 0;
1110
1111         line[0] = 0;
1112         while (offset < size) {
1113                 snprintf(tmp, 5, "%02x ", (uint8_t)buf[offset]);
1114                 offset++;
1115
1116                 strcat(line, tmp);
1117
1118                 if (offset % BYTES_PER_LINE == 0) {
1119                         LOG_DEBUG("%s", line);
1120                         line[0] = 0;
1121                 }
1122         }
1123
1124         if (line[0] != 0)
1125                 LOG_DEBUG("%s", line);
1126 }