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