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