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