]> git.sur5r.net Git - openocd/blob - src/jtag/drivers/buspirate.c
76be103e6928edab77ffe0c6b0851bc31046931d
[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/swd.h>
26 #include <jtag/commands.h>
27
28 #include <termios.h>
29 #include <fcntl.h>
30 #include <sys/ioctl.h>
31
32 #undef DEBUG_SERIAL
33 /*#define DEBUG_SERIAL */
34 static int buspirate_execute_queue(void);
35 static int buspirate_init(void);
36 static int buspirate_quit(void);
37
38 static void buspirate_end_state(tap_state_t state);
39 static void buspirate_state_move(void);
40 static void buspirate_path_move(int num_states, tap_state_t *path);
41 static void buspirate_runtest(int num_cycles);
42 static void buspirate_scan(bool ir_scan, enum scan_type type,
43         uint8_t *buffer, int scan_size, struct scan_command *command);
44 static void buspirate_stableclocks(int num_cycles);
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_RWIRE   0x05
53 #define CMD_ENTER_OOCD    0x06
54 #define CMD_UART_SPEED    0x07
55 #define CMD_JTAG_SPEED    0x08
56 #define CMD_RAW_PERIPH    0x40
57 #define CMD_RAW_SPEED     0x60
58 #define CMD_RAW_MODE      0x80
59
60 /* raw-wire mode configuration */
61 #define CMD_RAW_CONFIG_HIZ 0x00
62 #define CMD_RAW_CONFIG_3V3 0x08
63 #define CMD_RAW_CONFIG_2W  0x00
64 #define CMD_RAW_CONFIG_3W  0x04
65 #define CMD_RAW_CONFIG_MSB 0x00
66 #define CMD_RAW_CONFIG_LSB 0x02
67
68 /* Not all OSes have this speed defined */
69 #if !defined(B1000000)
70 #define  B1000000 0010010
71 #endif
72
73 enum {
74         MODE_HIZ = 0,
75         MODE_JTAG = 1,          /* push-pull outputs */
76         MODE_JTAG_OD = 2,       /* open-drain outputs */
77 };
78
79 enum {
80         FEATURE_LED = 0x01,
81         FEATURE_VREG = 0x02,
82         FEATURE_TRST = 0x04,
83         FEATURE_SRST = 0x08,
84         FEATURE_PULLUP = 0x10
85 };
86
87 enum {
88         ACTION_DISABLE = 0,
89         ACTION_ENABLE = 1
90 };
91
92 enum {
93         SERIAL_NORMAL = 0,
94         SERIAL_FAST = 1
95 };
96
97 enum {
98         SPEED_RAW_5_KHZ   = 0x0,
99         SPEED_RAW_50_KHZ  = 0x1,
100         SPEED_RAW_100_KHZ = 0x2,
101         SPEED_RAW_400_KHZ = 0x3
102 };
103
104 /* SWD mode specific */
105 static bool swd_mode;
106 static int  queued_retval;
107 static char swd_features;
108
109 static const cc_t SHORT_TIMEOUT  = 1; /* Must be at least 1. */
110 static const cc_t NORMAL_TIMEOUT = 10;
111
112 static int buspirate_fd = -1;
113 static int buspirate_pinmode = MODE_JTAG_OD;
114 static int buspirate_baudrate = SERIAL_NORMAL;
115 static int buspirate_vreg;
116 static int buspirate_pullup;
117 static char *buspirate_port;
118
119 static enum tap_state last_tap_state = TAP_RESET;
120
121 /* SWD interface */
122 static int buspirate_swd_init(void);
123 static void buspirate_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk);
124 static void buspirate_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk);
125 static int buspirate_swd_switch_seq(enum swd_special_seq seq);
126 static int buspirate_swd_run_queue(void);
127
128 /* TAP interface */
129 static void buspirate_tap_init(void);
130 static int buspirate_tap_execute(void);
131 static void buspirate_tap_append(int tms, int tdi);
132 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
133                 struct scan_command *command);
134 static void buspirate_tap_make_space(int scan, int bits);
135
136 static void buspirate_reset(int trst, int srst);
137 static void buspirate_set_feature(int, char, char);
138 static void buspirate_set_mode(int, char);
139 static void buspirate_set_speed(int, char);
140
141 /* low level interface */
142 static void buspirate_bbio_enable(int);
143 static void buspirate_jtag_reset(int);
144 static unsigned char buspirate_jtag_command(int, char *, int);
145 static void buspirate_jtag_set_speed(int, char);
146 static void buspirate_jtag_set_mode(int, char);
147 static void buspirate_jtag_set_feature(int, char, char);
148 static void buspirate_jtag_get_adcs(int);
149
150 /* low level two-wire interface */
151 static void buspirate_swd_set_speed(int, char);
152 static void buspirate_swd_set_feature(int, char, char);
153 static void buspirate_swd_set_mode(int, char);
154
155 /* low level HW communication interface */
156 static int buspirate_serial_open(char *port);
157 static int buspirate_serial_setspeed(int fd, char speed, cc_t timeout);
158 static int buspirate_serial_write(int fd, char *buf, int size);
159 static int buspirate_serial_read(int fd, char *buf, int size);
160 static void buspirate_serial_close(int fd);
161 static void buspirate_print_buffer(char *buf, int size);
162
163 static int buspirate_execute_queue(void)
164 {
165         /* currently processed command */
166         struct jtag_command *cmd = jtag_command_queue;
167         int scan_size;
168         enum scan_type type;
169         uint8_t *buffer;
170
171         while (cmd) {
172                 switch (cmd->type) {
173                 case JTAG_RUNTEST:
174                         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
175                                 cmd->cmd.runtest->num_cycles,
176                                 tap_state_name(cmd->cmd.runtest
177                                         ->end_state));
178                         buspirate_end_state(cmd->cmd.runtest
179                                         ->end_state);
180                         buspirate_runtest(cmd->cmd.runtest
181                                         ->num_cycles);
182                         break;
183                 case JTAG_TLR_RESET:
184                         DEBUG_JTAG_IO("statemove end in %s",
185                                 tap_state_name(cmd->cmd.statemove
186                                                 ->end_state));
187                         buspirate_end_state(cmd->cmd.statemove
188                                         ->end_state);
189                         buspirate_state_move();
190                         break;
191                 case JTAG_PATHMOVE:
192                         DEBUG_JTAG_IO("pathmove: %i states, end in %s",
193                                 cmd->cmd.pathmove->num_states,
194                                 tap_state_name(cmd->cmd.pathmove
195                                         ->path[cmd->cmd.pathmove
196                                                 ->num_states - 1]));
197                         buspirate_path_move(cmd->cmd.pathmove
198                                         ->num_states,
199                                         cmd->cmd.pathmove->path);
200                         break;
201                 case JTAG_SCAN:
202                         DEBUG_JTAG_IO("scan end in %s",
203                                 tap_state_name(cmd->cmd.scan
204                                         ->end_state));
205
206                         buspirate_end_state(cmd->cmd.scan
207                                         ->end_state);
208
209                         scan_size = jtag_build_buffer(cmd->cmd.scan,
210                                         &buffer);
211                         type = jtag_scan_type(cmd->cmd.scan);
212                         buspirate_scan(cmd->cmd.scan->ir_scan, type,
213                                 buffer, scan_size, cmd->cmd.scan);
214
215                         break;
216                 case JTAG_RESET:
217                         DEBUG_JTAG_IO("reset trst: %i srst %i",
218                                 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
219
220                         /* flush buffers, so we can reset */
221                         buspirate_tap_execute();
222
223                         if (cmd->cmd.reset->trst == 1)
224                                 tap_set_state(TAP_RESET);
225                         buspirate_reset(cmd->cmd.reset->trst,
226                                         cmd->cmd.reset->srst);
227                         break;
228                 case JTAG_SLEEP:
229                         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
230                         buspirate_tap_execute();
231                         jtag_sleep(cmd->cmd.sleep->us);
232                                 break;
233                 case JTAG_STABLECLOCKS:
234                         DEBUG_JTAG_IO("stable clock %i cycles", cmd->cmd.stableclocks->num_cycles);
235                         buspirate_stableclocks(cmd->cmd.stableclocks->num_cycles);
236                                 break;
237                 default:
238                         LOG_ERROR("BUG: unknown JTAG command type encountered");
239                         exit(-1);
240                 }
241
242                 cmd = cmd->next;
243         }
244
245         return buspirate_tap_execute();
246 }
247
248
249 /* Returns true if successful, false if error. */
250
251 static bool read_and_discard_all_data(const int fd)
252 {
253         /* LOG_INFO("Discarding any stale data from a previous connection..."); */
254
255         bool was_msg_already_printed = false;
256
257         for ( ; ; ) {
258                 char buffer[1024];  /* Any size will do, it's a trade-off between stack size and performance. */
259
260                 const ssize_t read_count = read(fd, buffer, sizeof(buffer));
261
262                 if (read_count == 0) {
263                         /* This is the "end of file" or "connection closed at the other end" condition. */
264                         return true;
265                 }
266
267                 if (read_count > 0) {
268                         if (!was_msg_already_printed)   {
269                                 LOG_INFO("Some stale data from a previous connection was discarded.");
270                                 was_msg_already_printed = true;
271                         }
272
273                         continue;
274                 }
275
276                 assert(read_count == -1);  /* According to the specification. */
277
278                 const int errno_code = errno;
279
280                 if (errno_code == EINTR)
281                         continue;
282
283                 if (errno_code == EAGAIN ||
284                         errno_code == EWOULDBLOCK) {
285                         /* We know that the file descriptor has been opened with O_NONBLOCK or O_NDELAY,
286                            and these codes mean that there is no data to read at present. */
287                         return true;
288                 }
289
290                 /* Some other error has occurred. */
291                 return false;
292         }
293 }
294
295
296 static int buspirate_init(void)
297 {
298         if (buspirate_port == NULL) {
299                 LOG_ERROR("You need to specify the serial port!");
300                 return ERROR_JTAG_INIT_FAILED;
301         }
302
303         buspirate_fd = buspirate_serial_open(buspirate_port);
304         if (buspirate_fd == -1) {
305                 LOG_ERROR("Could not open serial port");
306                 return ERROR_JTAG_INIT_FAILED;
307         }
308
309         /* The Operating System or the device itself may deliver stale data from the last connection,
310            so discard all available bytes right after the new connection has been established.
311            After all, we are implementing here a master/slave protocol, so the slave should have nothing
312            to say until the master sends the first command.
313
314            In the past, there was a tcflush() call in buspirate_serial_setspeed(), but that
315            was not enough. I guess you must actively read from the serial port to trigger any
316            data collection from the device and/or lower USB layers. If you disable the serial port
317            read timeout (if you set SHORT_TIMEOUT to 0), then the discarding does not work any more.
318
319            Note that we are lowering the serial port timeout for this first read operation,
320            otherwise the normal initialisation would be delayed for too long. */
321
322         if (-1 == buspirate_serial_setspeed(buspirate_fd, SERIAL_NORMAL, SHORT_TIMEOUT)) {
323                 LOG_ERROR("Error configuring the serial port.");
324                 return ERROR_JTAG_INIT_FAILED;
325         }
326
327         if (!read_and_discard_all_data(buspirate_fd)) {
328                 LOG_ERROR("Error while attempting to discard any stale data right after establishing the connection.");
329                 return ERROR_JTAG_INIT_FAILED;
330         }
331
332         if (-1 == buspirate_serial_setspeed(buspirate_fd, SERIAL_NORMAL, NORMAL_TIMEOUT)) {
333                 LOG_ERROR("Error configuring the serial port.");
334                 return ERROR_JTAG_INIT_FAILED;
335         }
336
337         buspirate_bbio_enable(buspirate_fd);
338
339         if (swd_mode || buspirate_baudrate != SERIAL_NORMAL)
340                 buspirate_set_speed(buspirate_fd, SERIAL_FAST);
341
342         LOG_INFO("Buspirate %s Interface ready!", swd_mode ? "SWD" : "JTAG");
343
344         if (!swd_mode)
345                 buspirate_tap_init();
346
347         buspirate_set_mode(buspirate_fd, buspirate_pinmode);
348         buspirate_set_feature(buspirate_fd, FEATURE_VREG,
349                 (buspirate_vreg == 1) ? ACTION_ENABLE : ACTION_DISABLE);
350         buspirate_set_feature(buspirate_fd, FEATURE_PULLUP,
351                 (buspirate_pullup == 1) ? ACTION_ENABLE : ACTION_DISABLE);
352         buspirate_reset(0, 0);
353
354         return ERROR_OK;
355 }
356
357 static int buspirate_quit(void)
358 {
359         LOG_INFO("Shutting down buspirate.");
360         buspirate_set_mode(buspirate_fd, MODE_HIZ);
361         buspirate_set_speed(buspirate_fd, SERIAL_NORMAL);
362
363         buspirate_jtag_reset(buspirate_fd);
364
365         buspirate_serial_close(buspirate_fd);
366
367         if (buspirate_port) {
368                 free(buspirate_port);
369                 buspirate_port = NULL;
370         }
371         return ERROR_OK;
372 }
373
374 /* openocd command interface */
375 COMMAND_HANDLER(buspirate_handle_adc_command)
376 {
377         if (buspirate_fd == -1)
378                 return ERROR_OK;
379
380         /* unavailable in SWD mode */
381         if (swd_mode)
382                 return ERROR_OK;
383
384         /* send the command */
385         buspirate_jtag_get_adcs(buspirate_fd);
386
387         return ERROR_OK;
388
389 }
390
391 COMMAND_HANDLER(buspirate_handle_vreg_command)
392 {
393         if (CMD_ARGC < 1)
394                 return ERROR_COMMAND_SYNTAX_ERROR;
395
396         if (atoi(CMD_ARGV[0]) == 1)
397                 buspirate_vreg = 1;
398         else if (atoi(CMD_ARGV[0]) == 0)
399                 buspirate_vreg = 0;
400         else
401                 LOG_ERROR("usage: buspirate_vreg <1|0>");
402
403         return ERROR_OK;
404
405 }
406
407 COMMAND_HANDLER(buspirate_handle_pullup_command)
408 {
409         if (CMD_ARGC < 1)
410                 return ERROR_COMMAND_SYNTAX_ERROR;
411
412         if (atoi(CMD_ARGV[0]) == 1)
413                 buspirate_pullup = 1;
414         else if (atoi(CMD_ARGV[0]) == 0)
415                 buspirate_pullup = 0;
416         else
417                 LOG_ERROR("usage: buspirate_pullup <1|0>");
418
419         return ERROR_OK;
420
421 }
422
423 COMMAND_HANDLER(buspirate_handle_led_command)
424 {
425         if (CMD_ARGC < 1)
426                 return ERROR_COMMAND_SYNTAX_ERROR;
427
428         if (atoi(CMD_ARGV[0]) == 1) {
429                 /* enable led */
430                 buspirate_set_feature(buspirate_fd, FEATURE_LED,
431                                 ACTION_ENABLE);
432         } else if (atoi(CMD_ARGV[0]) == 0) {
433                 /* disable led */
434                 buspirate_set_feature(buspirate_fd, FEATURE_LED,
435                                 ACTION_DISABLE);
436         } else {
437                 LOG_ERROR("usage: buspirate_led <1|0>");
438         }
439
440         return ERROR_OK;
441
442 }
443
444 COMMAND_HANDLER(buspirate_handle_mode_command)
445 {
446         if (CMD_ARGC < 1)
447                 return ERROR_COMMAND_SYNTAX_ERROR;
448
449         if (CMD_ARGV[0][0] == 'n')
450                 buspirate_pinmode = MODE_JTAG;
451         else if (CMD_ARGV[0][0] == 'o')
452                 buspirate_pinmode = MODE_JTAG_OD;
453         else
454                 LOG_ERROR("usage: buspirate_mode <normal|open-drain>");
455
456         return ERROR_OK;
457
458 }
459
460 COMMAND_HANDLER(buspirate_handle_speed_command)
461 {
462         if (CMD_ARGC < 1)
463                 return ERROR_COMMAND_SYNTAX_ERROR;
464
465         if (CMD_ARGV[0][0] == 'n')
466                 buspirate_baudrate = SERIAL_NORMAL;
467         else if (CMD_ARGV[0][0] == 'f')
468                 buspirate_baudrate = SERIAL_FAST;
469         else
470                 LOG_ERROR("usage: buspirate_speed <normal|fast>");
471
472         return ERROR_OK;
473
474 }
475
476 COMMAND_HANDLER(buspirate_handle_port_command)
477 {
478         if (CMD_ARGC < 1)
479                 return ERROR_COMMAND_SYNTAX_ERROR;
480
481         if (buspirate_port == NULL)
482                 buspirate_port = strdup(CMD_ARGV[0]);
483
484         return ERROR_OK;
485
486 }
487
488 static const struct command_registration buspirate_command_handlers[] = {
489         {
490                 .name = "buspirate_adc",
491                 .handler = &buspirate_handle_adc_command,
492                 .mode = COMMAND_EXEC,
493                 .help = "reads voltages on adc pins",
494         },
495         {
496                 .name = "buspirate_vreg",
497                 .usage = "<1|0>",
498                 .handler = &buspirate_handle_vreg_command,
499                 .mode = COMMAND_CONFIG,
500                 .help = "changes the state of voltage regulators",
501         },
502         {
503                 .name = "buspirate_pullup",
504                 .usage = "<1|0>",
505                 .handler = &buspirate_handle_pullup_command,
506                 .mode = COMMAND_CONFIG,
507                 .help = "changes the state of pullup",
508         },
509         {
510                 .name = "buspirate_led",
511                 .usage = "<1|0>",
512                 .handler = &buspirate_handle_led_command,
513                 .mode = COMMAND_EXEC,
514                 .help = "changes the state of led",
515         },
516         {
517                 .name = "buspirate_speed",
518                 .usage = "<normal|fast>",
519                 .handler = &buspirate_handle_speed_command,
520                 .mode = COMMAND_CONFIG,
521                 .help = "speed of the interface",
522         },
523         {
524                 .name = "buspirate_mode",
525                 .usage = "<normal|open-drain>",
526                 .handler = &buspirate_handle_mode_command,
527                 .mode = COMMAND_CONFIG,
528                 .help = "pin mode of the interface",
529         },
530         {
531                 .name = "buspirate_port",
532                 .usage = "/dev/ttyUSB0",
533                 .handler = &buspirate_handle_port_command,
534                 .mode = COMMAND_CONFIG,
535                 .help = "name of the serial port to open",
536         },
537         COMMAND_REGISTRATION_DONE
538 };
539
540 static const struct swd_driver buspirate_swd = {
541         .init = buspirate_swd_init,
542         .switch_seq = buspirate_swd_switch_seq,
543         .read_reg = buspirate_swd_read_reg,
544         .write_reg = buspirate_swd_write_reg,
545         .run = buspirate_swd_run_queue,
546 };
547
548 static const char * const buspirate_transports[] = { "jtag", "swd", NULL };
549
550 struct jtag_interface buspirate_interface = {
551         .name = "buspirate",
552         .execute_queue = buspirate_execute_queue,
553         .commands = buspirate_command_handlers,
554         .transports = buspirate_transports,
555         .swd = &buspirate_swd,
556         .init = buspirate_init,
557         .quit = buspirate_quit
558 };
559
560 /*************** jtag execute commands **********************/
561 static void buspirate_end_state(tap_state_t state)
562 {
563         if (tap_is_state_stable(state))
564                 tap_set_end_state(state);
565         else {
566                 LOG_ERROR("BUG: %i is not a valid end state", state);
567                 exit(-1);
568         }
569 }
570
571 static void buspirate_state_move(void)
572 {
573         int i = 0, tms = 0;
574         uint8_t tms_scan = tap_get_tms_path(tap_get_state(),
575                         tap_get_end_state());
576         int tms_count = tap_get_tms_path_len(tap_get_state(),
577                         tap_get_end_state());
578
579         for (i = 0; i < tms_count; i++) {
580                 tms = (tms_scan >> i) & 1;
581                 buspirate_tap_append(tms, 0);
582         }
583
584         tap_set_state(tap_get_end_state());
585 }
586
587 static void buspirate_path_move(int num_states, tap_state_t *path)
588 {
589         int i;
590
591         for (i = 0; i < num_states; i++) {
592                 if (tap_state_transition(tap_get_state(), false) == path[i]) {
593                         buspirate_tap_append(0, 0);
594                 } else if (tap_state_transition(tap_get_state(), true)
595                                 == path[i]) {
596                         buspirate_tap_append(1, 0);
597                 } else {
598                         LOG_ERROR("BUG: %s -> %s isn't a valid "
599                                 "TAP transition",
600                                 tap_state_name(tap_get_state()),
601                                 tap_state_name(path[i]));
602                         exit(-1);
603                 }
604
605                 tap_set_state(path[i]);
606         }
607
608         tap_set_end_state(tap_get_state());
609 }
610
611 static void buspirate_runtest(int num_cycles)
612 {
613         int i;
614
615         tap_state_t saved_end_state = tap_get_end_state();
616
617         /* only do a state_move when we're not already in IDLE */
618         if (tap_get_state() != TAP_IDLE) {
619                 buspirate_end_state(TAP_IDLE);
620                 buspirate_state_move();
621         }
622
623         for (i = 0; i < num_cycles; i++)
624                 buspirate_tap_append(0, 0);
625
626         DEBUG_JTAG_IO("runtest: cur_state %s end_state %s",
627                         tap_state_name(tap_get_state()),
628                         tap_state_name(tap_get_end_state()));
629
630         /* finish in end_state */
631         buspirate_end_state(saved_end_state);
632         if (tap_get_state() != tap_get_end_state())
633                 buspirate_state_move();
634 }
635
636 static void buspirate_scan(bool ir_scan, enum scan_type type,
637         uint8_t *buffer, int scan_size, struct scan_command *command)
638 {
639         tap_state_t saved_end_state;
640
641         buspirate_tap_make_space(1, scan_size+8);
642         /* is 8 correct ? (2 moves = 16) */
643
644         saved_end_state = tap_get_end_state();
645
646         buspirate_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
647
648         /* Only move if we're not already there */
649         if (tap_get_state() != tap_get_end_state())
650                 buspirate_state_move();
651
652         buspirate_tap_append_scan(scan_size, buffer, command);
653
654         /* move to PAUSE */
655         buspirate_tap_append(0, 0);
656
657         /* restore the saved state */
658         buspirate_end_state(saved_end_state);
659         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
660
661         if (tap_get_state() != tap_get_end_state())
662                 buspirate_state_move();
663 }
664
665 static void buspirate_stableclocks(int num_cycles)
666 {
667         int i;
668         int tms = (tap_get_state() == TAP_RESET ? 1 : 0);
669
670         buspirate_tap_make_space(0, num_cycles);
671
672         for (i = 0; i < num_cycles; i++)
673                 buspirate_tap_append(tms, 0);
674 }
675
676 /************************* TAP related stuff **********/
677
678 /* This buffer size matches the maximum CMD_TAP_SHIFT bit length in the Bus Pirate firmware,
679    look for constant 0x2000 in OpenOCD.c . */
680 #define BUSPIRATE_BUFFER_SIZE 1024
681
682 /* The old value of 32 scans was not enough to achieve near 100% utilisation ratio
683    for the current BUSPIRATE_BUFFER_SIZE value of 1024.
684    With 128 scans I am getting full USB 2.0 high speed packets (512 bytes long) when
685    using the JtagDue firmware on the Arduino Due instead of the Bus Pirate, which
686    amounts approximately to a 10% overall speed gain. Bigger packets should also
687    benefit the Bus Pirate, but the speed difference is much smaller.
688    Unfortunately, each 512-byte packet is followed by a 329-byte one, which is not ideal.
689    However, increasing BUSPIRATE_BUFFER_SIZE for the benefit of the JtagDue would
690    make it incompatible with the Bus Pirate firmware. */
691 #define BUSPIRATE_MAX_PENDING_SCANS 128
692
693 static char tms_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
694 static char tdi_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
695 static int tap_chain_index;
696
697 struct pending_scan_result /* this was stolen from arm-jtag-ew */
698 {
699         int first; /* First bit position in tdo_buffer to read */
700         int length; /* Number of bits to read */
701         struct scan_command *command; /* Corresponding scan command */
702         uint8_t *buffer;
703 };
704
705 static struct pending_scan_result
706 tap_pending_scans[BUSPIRATE_MAX_PENDING_SCANS];
707 static int tap_pending_scans_num;
708
709 static void buspirate_tap_init(void)
710 {
711         tap_chain_index = 0;
712         tap_pending_scans_num = 0;
713 }
714
715 static int buspirate_tap_execute(void)
716 {
717         static const int CMD_TAP_SHIFT_HEADER_LEN = 3;
718
719         char tmp[4096];
720         uint8_t *in_buf;
721         int i;
722         int fill_index = 0;
723         int ret;
724         int bytes_to_send;
725
726         if (tap_chain_index <= 0)
727                 return ERROR_OK;
728
729         LOG_DEBUG("executing tap num bits = %i scans = %i",
730                         tap_chain_index, tap_pending_scans_num);
731
732         bytes_to_send = DIV_ROUND_UP(tap_chain_index, 8);
733
734         tmp[0] = CMD_TAP_SHIFT; /* this command expects number of bits */
735         tmp[1] = (char)(tap_chain_index >> 8);  /* high */
736         tmp[2] = (char)(tap_chain_index);  /* low */
737
738         fill_index = CMD_TAP_SHIFT_HEADER_LEN;
739         for (i = 0; i < bytes_to_send; i++) {
740                 tmp[fill_index] = tdi_chain[i];
741                 fill_index++;
742                 tmp[fill_index] = tms_chain[i];
743                 fill_index++;
744         }
745
746         /* jlink.c calls the routine below, which may be useful for debugging purposes.
747            For example, enabling this allows you to compare the log outputs from jlink.c
748            and from this module for JTAG development or troubleshooting purposes. */
749         if (false) {
750                 last_tap_state = jtag_debug_state_machine(tms_chain, tdi_chain,
751                                                                                                   tap_chain_index, last_tap_state);
752         }
753
754         ret = buspirate_serial_write(buspirate_fd, tmp, CMD_TAP_SHIFT_HEADER_LEN + bytes_to_send*2);
755         if (ret != bytes_to_send*2+CMD_TAP_SHIFT_HEADER_LEN) {
756                 LOG_ERROR("error writing :(");
757                 return ERROR_JTAG_DEVICE_ERROR;
758         }
759
760         ret = buspirate_serial_read(buspirate_fd, tmp, bytes_to_send + CMD_TAP_SHIFT_HEADER_LEN);
761         if (ret != bytes_to_send + CMD_TAP_SHIFT_HEADER_LEN) {
762                 LOG_ERROR("error reading");
763                 return ERROR_FAIL;
764         }
765         in_buf = (uint8_t *)(&tmp[CMD_TAP_SHIFT_HEADER_LEN]);
766
767         /* parse the scans */
768         for (i = 0; i < tap_pending_scans_num; i++) {
769                 uint8_t *buffer = tap_pending_scans[i].buffer;
770                 int length = tap_pending_scans[i].length;
771                 int first = tap_pending_scans[i].first;
772                 struct scan_command *command = tap_pending_scans[i].command;
773
774                 /* copy bits from buffer */
775                 buf_set_buf(in_buf, first, buffer, 0, length);
776
777                 /* return buffer to higher level */
778                 if (jtag_read_buffer(buffer, command) != ERROR_OK) {
779                         buspirate_tap_init();
780                         return ERROR_JTAG_QUEUE_FAILED;
781                 }
782
783                 free(buffer);
784         }
785         buspirate_tap_init();
786         return ERROR_OK;
787 }
788
789 static void buspirate_tap_make_space(int scans, int bits)
790 {
791         int have_scans = BUSPIRATE_MAX_PENDING_SCANS - tap_pending_scans_num;
792         int have_bits = BUSPIRATE_BUFFER_SIZE * 8 - tap_chain_index;
793
794         if ((have_scans < scans) || (have_bits < bits))
795                 buspirate_tap_execute();
796 }
797
798 static void buspirate_tap_append(int tms, int tdi)
799 {
800         int chain_index;
801
802         buspirate_tap_make_space(0, 1);
803         chain_index = tap_chain_index / 8;
804
805         if (chain_index < BUSPIRATE_BUFFER_SIZE) {
806                 int bit_index = tap_chain_index % 8;
807                 uint8_t bit = 1 << bit_index;
808
809                 if (0 == bit_index) {
810                         /* Let's say that the TAP shift operation wants to shift 9 bits,
811                            so we will be sending to the Bus Pirate a bit count of 9 but still
812                            full 16 bits (2 bytes) of shift data.
813                            If we don't clear all bits at this point, the last 7 bits will contain
814                            random data from the last buffer contents, which is not pleasant to the eye.
815                            Besides, the Bus Pirate (or some clone) may want to assert in debug builds
816                            that, after consuming all significant data bits, the rest of them are zero.
817                            Therefore, for aesthetic and for assert purposes, we clear all bits below. */
818                         tms_chain[chain_index] = 0;
819                         tdi_chain[chain_index] = 0;
820                 }
821
822                 if (tms)
823                         tms_chain[chain_index] |= bit;
824                 else
825                         tms_chain[chain_index] &= ~bit;
826
827                 if (tdi)
828                         tdi_chain[chain_index] |= bit;
829                 else
830                         tdi_chain[chain_index] &= ~bit;
831
832                 tap_chain_index++;
833         } else {
834                 LOG_ERROR("tap_chain overflow, bad things will happen");
835                 /* Exit abruptly, like jlink.c does. After a buffer overflow we don't want
836                    to carry on, as data will be corrupt. Another option would be to return
837                    some error code at this point. */
838                 exit(-1);
839         }
840 }
841
842 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
843                 struct scan_command *command)
844 {
845         int i;
846         tap_pending_scans[tap_pending_scans_num].length = length;
847         tap_pending_scans[tap_pending_scans_num].buffer = buffer;
848         tap_pending_scans[tap_pending_scans_num].command = command;
849         tap_pending_scans[tap_pending_scans_num].first = tap_chain_index;
850
851         for (i = 0; i < length; i++) {
852                 int tms = (i < length-1 ? 0 : 1);
853                 int tdi = (buffer[i/8] >> (i%8)) & 1;
854                 buspirate_tap_append(tms, tdi);
855         }
856         tap_pending_scans_num++;
857 }
858
859 /*************** wrapper functions *********************/
860
861 /* (1) assert or (0) deassert reset lines */
862 static void buspirate_reset(int trst, int srst)
863 {
864         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
865
866         if (trst)
867                 buspirate_set_feature(buspirate_fd, FEATURE_TRST, ACTION_DISABLE);
868         else
869                 buspirate_set_feature(buspirate_fd, FEATURE_TRST, ACTION_ENABLE);
870
871         if (srst)
872                 buspirate_set_feature(buspirate_fd, FEATURE_SRST, ACTION_DISABLE);
873         else
874                 buspirate_set_feature(buspirate_fd, FEATURE_SRST, ACTION_ENABLE);
875 }
876
877 static void buspirate_set_feature(int fd, char feat, char action)
878 {
879         if (swd_mode)
880                 buspirate_swd_set_feature(fd, feat, action);
881         else
882                 buspirate_jtag_set_feature(fd, feat, action);
883 }
884
885 static void buspirate_set_mode(int fd, char mode)
886 {
887         if (swd_mode)
888                 buspirate_swd_set_mode(fd, mode);
889         else
890                 buspirate_jtag_set_mode(fd, mode);
891 }
892
893 static void buspirate_set_speed(int fd, char speed)
894 {
895         if (swd_mode)
896                 buspirate_swd_set_speed(fd, speed);
897         else
898                 buspirate_jtag_set_speed(fd, speed);
899 }
900
901
902 /*************** swd lowlevel functions ********************/
903
904 static void buspirate_swd_set_speed(int fd, char speed)
905 {
906         int  ret;
907         char tmp[1];
908
909         LOG_DEBUG("Buspirate speed setting in SWD mode defaults to 400 kHz");
910
911         /* speed settings */
912         tmp[0] = CMD_RAW_SPEED | SPEED_RAW_400_KHZ;
913         buspirate_serial_write(fd, tmp, 1);
914         ret = buspirate_serial_read(fd, tmp, 1);
915         if (ret != 1) {
916                 LOG_ERROR("Buspirate did not answer correctly");
917                 exit(-1);
918         }
919         if (tmp[0] != 1) {
920                 LOG_ERROR("Buspirate did not reply as expected to the speed change command");
921                 exit(-1);
922         }
923 }
924
925 static void buspirate_swd_set_mode(int fd, char mode)
926 {
927         int ret;
928         char tmp[1];
929
930         /* raw-wire mode configuration */
931         if (mode == MODE_HIZ)
932                 tmp[0] = CMD_RAW_MODE | CMD_RAW_CONFIG_LSB;
933         else
934                 tmp[0] = CMD_RAW_MODE | CMD_RAW_CONFIG_LSB | CMD_RAW_CONFIG_3V3;
935
936         buspirate_serial_write(fd, tmp, 1);
937         ret = buspirate_serial_read(fd, tmp, 1);
938         if (ret != 1) {
939                 LOG_ERROR("Buspirate did not answer correctly");
940                 exit(-1);
941         }
942         if (tmp[0] != 1) {
943                 LOG_ERROR("Buspirate did not reply as expected to the configure command");
944                 exit(-1);
945         }
946 }
947
948 static void buspirate_swd_set_feature(int fd, char feat, char action)
949 {
950         int  ret;
951         char tmp[1];
952
953         switch (feat) {
954                 case FEATURE_TRST:
955                         LOG_DEBUG("Buspirate TRST feature not available in SWD mode");
956                         return;
957                 case FEATURE_LED:
958                         LOG_ERROR("Buspirate LED feature not available in SWD mode");
959                         return;
960                 case FEATURE_SRST:
961                         swd_features = (action == ACTION_ENABLE) ? swd_features | 0x02 : swd_features & 0x0D;
962                         break;
963                 case FEATURE_PULLUP:
964                         swd_features = (action == ACTION_ENABLE) ? swd_features | 0x04 : swd_features & 0x0B;
965                         break;
966                 case FEATURE_VREG:
967                         swd_features = (action == ACTION_ENABLE) ? swd_features | 0x08 : swd_features & 0x07;
968                         break;
969                 default:
970                         LOG_DEBUG("Buspirate unknown feature %d", feat);
971                         return;
972         }
973
974         tmp[0] = CMD_RAW_PERIPH | swd_features;
975         buspirate_serial_write(fd, tmp, 1);
976         ret = buspirate_serial_read(fd, tmp, 1);
977         if (ret != 1) {
978                 LOG_DEBUG("Buspirate feature %d not supported in SWD mode", feat);
979         } else if (tmp[0] != 1) {
980                 LOG_ERROR("Buspirate did not reply as expected to the configure command");
981                 exit(-1);
982         }
983 }
984
985 /*************** jtag lowlevel functions ********************/
986 static void buspirate_bbio_enable(int fd)
987 {
988         int ret;
989         char command;
990         const char *mode_answers[2] = { "OCD1", "RAW1" };
991         const char *correct_ans     = NULL;
992         char tmp[21] = { [0 ... 20] = 0x00 };
993         int done = 0;
994         int cmd_sent = 0;
995
996         if (swd_mode) {
997                 command     = CMD_ENTER_RWIRE;
998                 correct_ans = mode_answers[1];
999         } else {
1000                 command     = CMD_ENTER_OOCD;
1001                 correct_ans = mode_answers[0];
1002         }
1003
1004         LOG_DEBUG("Entering binary mode, that is %s", correct_ans);
1005         buspirate_serial_write(fd, tmp, 20);
1006         usleep(10000);
1007
1008         /* reads 1 to n "BBIO1"s and one "OCD1" or "RAW1" */
1009         while (!done) {
1010                 ret = buspirate_serial_read(fd, tmp, 4);
1011                 if (ret != 4) {
1012                         LOG_ERROR("Buspirate error. Is binary"
1013                                 "/OpenOCD support enabled?");
1014                         exit(-1);
1015                 }
1016                 if (strncmp(tmp, "BBIO", 4) == 0) {
1017                         ret = buspirate_serial_read(fd, tmp, 1);
1018                         if (ret != 1) {
1019                                 LOG_ERROR("Buspirate did not answer correctly! "
1020                                         "Do you have correct firmware?");
1021                                 exit(-1);
1022                         }
1023                         if (tmp[0] != '1') {
1024                                 LOG_ERROR("Unsupported binary protocol");
1025                                 exit(-1);
1026                         }
1027                         if (cmd_sent == 0) {
1028                                 cmd_sent = 1;
1029                                 tmp[0] = command;
1030                                 ret = buspirate_serial_write(fd, tmp, 1);
1031                                 if (ret != 1) {
1032                                         LOG_ERROR("error reading");
1033                                         exit(-1);
1034                                 }
1035                         }
1036                 } else if (strncmp(tmp, correct_ans, 4) == 0)
1037                         done = 1;
1038                 else {
1039                         LOG_ERROR("Buspirate did not answer correctly! "
1040                                 "Do you have correct firmware?");
1041                         exit(-1);
1042                 }
1043         }
1044
1045 }
1046
1047 static void buspirate_jtag_reset(int fd)
1048 {
1049         char tmp[5];
1050
1051         tmp[0] = 0x00; /* exit OCD1 mode */
1052         buspirate_serial_write(fd, tmp, 1);
1053         usleep(10000);
1054         /* We ignore the return value here purposly, nothing we can do */
1055         buspirate_serial_read(fd, tmp, 5);
1056         if (strncmp(tmp, "BBIO1", 5) == 0) {
1057                 tmp[0] = 0x0F; /*  reset BP */
1058                 buspirate_serial_write(fd, tmp, 1);
1059         } else
1060                 LOG_ERROR("Unable to restart buspirate!");
1061 }
1062
1063 static void buspirate_jtag_set_speed(int fd, char speed)
1064 {
1065         int ret;
1066         char tmp[2];
1067         char ack[2];
1068
1069         ack[0] = 0xAA;
1070         ack[1] = 0x55;
1071
1072         tmp[0] = CMD_UART_SPEED;
1073         tmp[1] = speed;
1074         buspirate_jtag_command(fd, tmp, 2);
1075
1076         /* here the adapter changes speed, we need follow */
1077         if (-1 == buspirate_serial_setspeed(fd, speed, NORMAL_TIMEOUT)) {
1078                 LOG_ERROR("Error configuring the serial port.");
1079                 exit(-1);
1080         }
1081
1082         buspirate_serial_write(fd, ack, 2);
1083         ret = buspirate_serial_read(fd, tmp, 2);
1084         if (ret != 2) {
1085                 LOG_ERROR("Buspirate did not ack speed change");
1086                 exit(-1);
1087         }
1088         if ((tmp[0] != CMD_UART_SPEED) || (tmp[1] != speed)) {
1089                 LOG_ERROR("Buspirate did not reply as expected to the speed change command");
1090                 exit(-1);
1091         }
1092         LOG_INFO("Buspirate switched to %s mode",
1093                 (speed == SERIAL_NORMAL) ? "normal" : "FAST");
1094 }
1095
1096
1097 static void buspirate_jtag_set_mode(int fd, char mode)
1098 {
1099         char tmp[2];
1100         tmp[0] = CMD_PORT_MODE;
1101         tmp[1] = mode;
1102         buspirate_jtag_command(fd, tmp, 2);
1103 }
1104
1105 static void buspirate_jtag_set_feature(int fd, char feat, char action)
1106 {
1107         char tmp[3];
1108         tmp[0] = CMD_FEATURE;
1109         tmp[1] = feat;   /* what */
1110         tmp[2] = action; /* action */
1111         buspirate_jtag_command(fd, tmp, 3);
1112 }
1113
1114 static void buspirate_jtag_get_adcs(int fd)
1115 {
1116         uint8_t tmp[10];
1117         uint16_t a, b, c, d;
1118         tmp[0] = CMD_READ_ADCS;
1119         buspirate_jtag_command(fd, (char *)tmp, 1);
1120         a = tmp[2] << 8 | tmp[3];
1121         b = tmp[4] << 8 | tmp[5];
1122         c = tmp[6] << 8 | tmp[7];
1123         d = tmp[8] << 8 | tmp[9];
1124
1125         LOG_INFO("ADC: ADC_Pin = %.02f VPullup = %.02f V33 = %.02f "
1126                 "V50 = %.02f",
1127                 ((float)a)/155.1515, ((float)b)/155.1515,
1128                 ((float)c)/155.1515, ((float)d)/155.1515);
1129 }
1130
1131 static unsigned char buspirate_jtag_command(int fd,
1132                 char *cmd, int cmdlen)
1133 {
1134         int res;
1135         int len = 0;
1136
1137         res = buspirate_serial_write(fd, cmd, cmdlen);
1138
1139         if ((cmd[0] == CMD_UART_SPEED)
1140                                 || (cmd[0] == CMD_PORT_MODE)
1141                                 || (cmd[0] == CMD_FEATURE)
1142                                 || (cmd[0] == CMD_JTAG_SPEED))
1143                 return 1;
1144
1145         if (res == cmdlen) {
1146                 switch (cmd[0]) {
1147                 case CMD_READ_ADCS:
1148                         len = 10; /* 2*sizeof(char)+4*sizeof(uint16_t) */
1149                         break;
1150                 case CMD_TAP_SHIFT:
1151                         len = cmdlen;
1152                         break;
1153                 default:
1154                         LOG_INFO("Wrong !");
1155                 }
1156                 res =  buspirate_serial_read(fd, cmd, len);
1157                 if (res > 0)
1158                         return (unsigned char)cmd[1];
1159                 else
1160                         return -1;
1161         } else
1162                 return -1;
1163         return 0;
1164 }
1165
1166 /* low level serial port */
1167 /* TODO add support for WIN32 and others ! */
1168 static int buspirate_serial_open(char *port)
1169 {
1170         int fd;
1171         fd = open(buspirate_port, O_RDWR | O_NOCTTY | O_NDELAY);
1172         return fd;
1173 }
1174
1175
1176 /* Returns -1 on error. */
1177
1178 static int buspirate_serial_setspeed(int fd, char speed, cc_t timeout)
1179 {
1180         struct termios t_opt;
1181         speed_t baud = (speed == SERIAL_FAST) ? B1000000 : B115200;
1182
1183         /* set the serial port parameters */
1184         fcntl(fd, F_SETFL, 0);
1185         if (0 != tcgetattr(fd, &t_opt))
1186                 return -1;
1187
1188         if (0 != cfsetispeed(&t_opt, baud))
1189                 return -1;
1190
1191         if (0 != cfsetospeed(&t_opt, baud))
1192                 return -1;
1193
1194         t_opt.c_cflag |= (CLOCAL | CREAD);
1195         t_opt.c_cflag &= ~PARENB;
1196         t_opt.c_cflag &= ~CSTOPB;
1197         t_opt.c_cflag &= ~CSIZE;
1198         t_opt.c_cflag |= CS8;
1199         t_opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
1200
1201         /* The serial port may have been configured for human interaction with
1202            the Bus Pirate console, but OpenOCD is going to use a binary protocol,
1203            so make sure to turn off any CR/LF translation and the like. */
1204         t_opt.c_iflag &= ~(IXON | IXOFF | IXANY | INLCR | ICRNL);
1205
1206         t_opt.c_oflag &= ~OPOST;
1207         t_opt.c_cc[VMIN] = 0;
1208         t_opt.c_cc[VTIME] = timeout;
1209
1210         /* Note that, in the past, TCSANOW was used below instead of TCSADRAIN,
1211            and CMD_UART_SPEED did not work properly then, at least with
1212            the Bus Pirate v3.5 (USB). */
1213         if (0 != tcsetattr(fd, TCSADRAIN, &t_opt)) {
1214                 /* According to the Linux documentation, this is actually not enough
1215                    to detect errors, you need to call tcgetattr() and check that
1216                    all changes have been performed successfully. */
1217                 return -1;
1218         }
1219
1220         return 0;
1221 }
1222
1223 static int buspirate_serial_write(int fd, char *buf, int size)
1224 {
1225         int ret = 0;
1226
1227         ret = write(fd, buf, size);
1228
1229         LOG_DEBUG("size = %d ret = %d", size, ret);
1230         buspirate_print_buffer(buf, size);
1231
1232         if (ret != size)
1233                 LOG_ERROR("Error sending data");
1234
1235         return ret;
1236 }
1237
1238 static int buspirate_serial_read(int fd, char *buf, int size)
1239 {
1240         int len = 0;
1241         int ret = 0;
1242         int timeout = 0;
1243
1244         while (len < size) {
1245                 ret = read(fd, buf+len, size-len);
1246                 if (ret == -1)
1247                         return -1;
1248
1249                 if (ret == 0) {
1250                         timeout++;
1251
1252                         if (timeout >= 10)
1253                                 break;
1254
1255                         continue;
1256                 }
1257
1258                 len += ret;
1259         }
1260
1261         LOG_DEBUG("should have read = %d actual size = %d", size, len);
1262         buspirate_print_buffer(buf, len);
1263
1264         if (len != size)
1265                 LOG_ERROR("Error reading data");
1266
1267         return len;
1268 }
1269
1270 static void buspirate_serial_close(int fd)
1271 {
1272         close(fd);
1273 }
1274
1275 #define LINE_SIZE      81
1276 #define BYTES_PER_LINE 16
1277 static void buspirate_print_buffer(char *buf, int size)
1278 {
1279         char line[LINE_SIZE];
1280         char tmp[10];
1281         int offset = 0;
1282
1283         line[0] = 0;
1284         while (offset < size) {
1285                 snprintf(tmp, 5, "%02x ", (uint8_t)buf[offset]);
1286                 offset++;
1287
1288                 strcat(line, tmp);
1289
1290                 if (offset % BYTES_PER_LINE == 0) {
1291                         LOG_DEBUG("%s", line);
1292                         line[0] = 0;
1293                 }
1294         }
1295
1296         if (line[0] != 0)
1297                 LOG_DEBUG("%s", line);
1298 }
1299
1300 /************************* SWD related stuff **********/
1301
1302 static int buspirate_swd_init(void)
1303 {
1304         LOG_INFO("Buspirate SWD mode enabled");
1305         swd_mode = true;
1306
1307         return ERROR_OK;
1308 }
1309
1310 static int buspirate_swd_switch_seq(enum swd_special_seq seq)
1311 {
1312         const uint8_t *sequence;
1313         int sequence_len;
1314         char tmp[64];
1315
1316         switch (seq) {
1317         case LINE_RESET:
1318                 LOG_DEBUG("SWD line reset");
1319                 sequence = swd_seq_line_reset;
1320                 sequence_len = DIV_ROUND_UP(swd_seq_line_reset_len, 8);
1321                 break;
1322         case JTAG_TO_SWD:
1323                 LOG_DEBUG("JTAG-to-SWD");
1324                 sequence = swd_seq_jtag_to_swd;
1325                 sequence_len = DIV_ROUND_UP(swd_seq_jtag_to_swd_len, 8);
1326                 break;
1327         case SWD_TO_JTAG:
1328                 LOG_DEBUG("SWD-to-JTAG");
1329                 sequence = swd_seq_swd_to_jtag;
1330                 sequence_len = DIV_ROUND_UP(swd_seq_swd_to_jtag_len, 8);
1331                 break;
1332         default:
1333                 LOG_ERROR("Sequence %d not supported", seq);
1334                 return ERROR_FAIL;
1335         }
1336
1337         /* FIXME: all above sequences fit into one pirate command for now
1338          *        but it may cause trouble later
1339          */
1340
1341         tmp[0] = 0x10 + ((sequence_len - 1) & 0x0F);
1342         memcpy(tmp + 1, sequence, sequence_len);
1343
1344         buspirate_serial_write(buspirate_fd, tmp, sequence_len + 1);
1345         buspirate_serial_read(buspirate_fd, tmp, sequence_len + 1);
1346
1347         return ERROR_OK;
1348 }
1349
1350 static uint8_t buspirate_swd_write_header(uint8_t cmd)
1351 {
1352         char tmp[8];
1353         int  to_send;
1354
1355         tmp[0] = 0x10; /* bus pirate: send 1 byte */
1356         tmp[1] = cmd;  /* swd cmd */
1357         tmp[2] = 0x07; /* ack __x */
1358         tmp[3] = 0x07; /* ack _x_ */
1359         tmp[4] = 0x07; /* ack x__ */
1360         tmp[5] = 0x07; /* write mode trn_1 */
1361         tmp[6] = 0x07; /* write mode trn_2 */
1362
1363         to_send = ((cmd & SWD_CMD_RnW) == 0) ? 7 : 5;
1364         buspirate_serial_write(buspirate_fd, tmp, to_send);
1365
1366         /* read ack */
1367         buspirate_serial_read(buspirate_fd, tmp, 2); /* drop pirate command ret vals */
1368         buspirate_serial_read(buspirate_fd, tmp, to_send - 2); /* ack bits */
1369
1370         return tmp[2] << 2 | tmp[1] << 1 | tmp[0];
1371 }
1372
1373 static void buspirate_swd_idle_clocks(uint32_t no_bits)
1374 {
1375         uint32_t no_bytes;
1376         char tmp[20];
1377
1378         no_bytes = (no_bits + 7) / 8;
1379         memset(tmp + 1, 0x00, sizeof(tmp) - 1);
1380
1381         /* unfortunately bus pirate misbehaves when clocks are sent in parts
1382          * so we need to limit at 128 clock cycles
1383          */
1384         if (no_bytes > 16)
1385                 no_bytes = 16;
1386
1387         while (no_bytes) {
1388                 uint8_t to_send = no_bytes > 16 ? 16 : no_bytes;
1389                 tmp[0] = 0x10 + ((to_send - 1) & 0x0F);
1390
1391                 buspirate_serial_write(buspirate_fd, tmp, to_send + 1);
1392                 buspirate_serial_read(buspirate_fd, tmp, to_send + 1);
1393
1394                 no_bytes -= to_send;
1395         }
1396 }
1397
1398 static void buspirate_swd_clear_sticky_errors(void)
1399 {
1400         buspirate_swd_write_reg(swd_cmd(false,  false, DP_ABORT),
1401                 STKCMPCLR | STKERRCLR | WDERRCLR | ORUNERRCLR, 0);
1402 }
1403
1404 static void buspirate_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
1405 {
1406         char tmp[16];
1407
1408         LOG_DEBUG("buspirate_swd_read_reg");
1409         assert(cmd & SWD_CMD_RnW);
1410
1411         if (queued_retval != ERROR_OK) {
1412                 LOG_DEBUG("Skip buspirate_swd_read_reg because queued_retval=%d", queued_retval);
1413                 return;
1414         }
1415
1416         cmd |= SWD_CMD_START | SWD_CMD_PARK;
1417         uint8_t ack = buspirate_swd_write_header(cmd);
1418
1419         /* do a read transaction */
1420         tmp[0] = 0x06; /* 4 data bytes */
1421         tmp[1] = 0x06;
1422         tmp[2] = 0x06;
1423         tmp[3] = 0x06;
1424         tmp[4] = 0x07; /* parity bit */
1425         tmp[5] = 0x21; /* 2 turnaround clocks */
1426
1427         buspirate_serial_write(buspirate_fd, tmp, 6);
1428         buspirate_serial_read(buspirate_fd, tmp, 6);
1429
1430         /* store the data and parity */
1431         uint32_t data = (uint8_t) tmp[0];
1432         data |= (uint8_t) tmp[1] << 8;
1433         data |= (uint8_t) tmp[2] << 16;
1434         data |= (uint8_t) tmp[3] << 24;
1435         int parity = tmp[4] ? 0x01 : 0x00;
1436
1437         LOG_DEBUG("%s %s %s reg %X = %08"PRIx32,
1438                         ack == SWD_ACK_OK ? "OK" : ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
1439                         cmd & SWD_CMD_APnDP ? "AP" : "DP",
1440                         cmd & SWD_CMD_RnW ? "read" : "write",
1441                         (cmd & SWD_CMD_A32) >> 1,
1442                         data);
1443
1444         switch (ack) {
1445          case SWD_ACK_OK:
1446                 if (parity != parity_u32(data)) {
1447                         LOG_DEBUG("Read data parity mismatch %x %x", parity, parity_u32(data));
1448                         queued_retval = ERROR_FAIL;
1449                         return;
1450                 }
1451                 if (value)
1452                         *value = data;
1453                 if (cmd & SWD_CMD_APnDP)
1454                         buspirate_swd_idle_clocks(ap_delay_clk);
1455                 return;
1456          case SWD_ACK_WAIT:
1457                 LOG_DEBUG("SWD_ACK_WAIT");
1458                 buspirate_swd_clear_sticky_errors();
1459                 return;
1460          case SWD_ACK_FAULT:
1461                 LOG_DEBUG("SWD_ACK_FAULT");
1462                 queued_retval = ack;
1463                 return;
1464          default:
1465                 LOG_DEBUG("No valid acknowledge: ack=%d", ack);
1466                 queued_retval = ack;
1467                 return;
1468         }
1469 }
1470
1471 static void buspirate_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
1472 {
1473         char tmp[16];
1474
1475         LOG_DEBUG("buspirate_swd_write_reg");
1476         assert(!(cmd & SWD_CMD_RnW));
1477
1478         if (queued_retval != ERROR_OK) {
1479                 LOG_DEBUG("Skip buspirate_swd_write_reg because queued_retval=%d", queued_retval);
1480                 return;
1481         }
1482
1483         cmd |= SWD_CMD_START | SWD_CMD_PARK;
1484         uint8_t ack = buspirate_swd_write_header(cmd);
1485
1486         /* do a write transaction */
1487         tmp[0] = 0x10 + ((4 + 1 - 1) & 0xF); /* bus pirate: send 4+1 bytes */
1488         buf_set_u32((uint8_t *) tmp + 1, 0, 32, value);
1489         /* write sequence ends with parity bit and 7 idle ticks */
1490         tmp[5] = parity_u32(value) ? 0x01 : 0x00;
1491
1492         buspirate_serial_write(buspirate_fd, tmp, 6);
1493         buspirate_serial_read(buspirate_fd, tmp, 6);
1494
1495         LOG_DEBUG("%s %s %s reg %X = %08"PRIx32,
1496                         ack == SWD_ACK_OK ? "OK" : ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
1497                         cmd & SWD_CMD_APnDP ? "AP" : "DP",
1498                         cmd & SWD_CMD_RnW ? "read" : "write",
1499                         (cmd & SWD_CMD_A32) >> 1,
1500                         value);
1501
1502         switch (ack) {
1503          case SWD_ACK_OK:
1504                 if (cmd & SWD_CMD_APnDP)
1505                         buspirate_swd_idle_clocks(ap_delay_clk);
1506                 return;
1507          case SWD_ACK_WAIT:
1508                 LOG_DEBUG("SWD_ACK_WAIT");
1509                 buspirate_swd_clear_sticky_errors();
1510                 return;
1511          case SWD_ACK_FAULT:
1512                 LOG_DEBUG("SWD_ACK_FAULT");
1513                 queued_retval = ack;
1514                 return;
1515          default:
1516                 LOG_DEBUG("No valid acknowledge: ack=%d", ack);
1517                 queued_retval = ack;
1518                 return;
1519         }
1520 }
1521
1522 static int buspirate_swd_run_queue(void)
1523 {
1524         LOG_DEBUG("buspirate_swd_run_queue");
1525         /* A transaction must be followed by another transaction or at least 8 idle cycles to
1526          * ensure that data is clocked through the AP. */
1527         buspirate_swd_idle_clocks(8);
1528
1529         int retval = queued_retval;
1530         queued_retval = ERROR_OK;
1531         LOG_DEBUG("SWD queue return value: %02x", retval);
1532         return retval;
1533 }
1534
1535