e5f8fb630fc46bd6a2cf258ab7a9170d2b5f8d6c
[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  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <jtag/interface.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_speed(int speed);
36 static int buspirate_khz(int khz, int *jtag_speed);
37 static int buspirate_init(void);
38 static int buspirate_quit(void);
39
40 static void buspirate_end_state(tap_state_t state);
41 static void buspirate_state_move(void);
42 static void buspirate_path_move(int num_states, tap_state_t *path);
43 static void buspirate_runtest(int num_cycles);
44 static void buspirate_scan(bool ir_scan, enum scan_type type,
45         uint8_t *buffer, int scan_size, struct scan_command *command);
46
47
48 #define CMD_UNKOWN        0x00
49 #define CMD_PORT_MODE     0x01
50 #define CMD_FEATURE       0x02
51 #define CMD_READ_ADCS     0x03
52 /*#define CMD_TAP_SHIFT     0x04 // old protocol */
53 #define CMD_TAP_SHIFT     0x05
54 #define CMD_ENTER_OOCD    0x06
55 #define CMD_UART_SPEED    0x07
56 #define CMD_JTAG_SPEED    0x08
57
58 enum {
59         MODE_HIZ = 0,
60         MODE_JTAG = 1,          /* push-pull outputs */
61         MODE_JTAG_OD = 2,       /* open-drain outputs */
62 };
63
64 enum {
65         FEATURE_LED = 0x01,
66         FEATURE_VREG = 0x02,
67         FEATURE_TRST = 0x04,
68         FEATURE_SRST = 0x08,
69         FEATURE_PULLUP = 0x10
70 };
71
72 enum {
73         ACTION_DISABLE = 0,
74         ACTION_ENABLE = 1
75 };
76
77 enum {
78         SERIAL_NORMAL = 0,
79         SERIAL_FAST = 1
80 };
81
82
83 static int buspirate_fd = -1;
84 static int buspirate_pinmode = MODE_JTAG_OD;
85 static int buspirate_baudrate = SERIAL_NORMAL;
86 static int buspirate_vreg;
87 static int buspirate_pullup;
88 static char *buspirate_port;
89
90
91 /* TAP interface */
92 static void buspirate_tap_init(void);
93 static int buspirate_tap_execute(void);
94 static void buspirate_tap_append(int tms, int tdi);
95 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
96                 struct scan_command *command);
97 static void buspirate_tap_make_space(int scan, int bits);
98
99 static void buspirate_reset(int trst, int srst);
100
101 /* low level interface */
102 static void buspirate_jtag_reset(int);
103 static void buspirate_jtag_enable(int);
104 static unsigned char buspirate_jtag_command(int, char *, int);
105 static void buspirate_jtag_set_speed(int, char);
106 static void buspirate_jtag_set_mode(int, char);
107 static void buspirate_jtag_set_feature(int, char, char);
108 static void buspirate_jtag_get_adcs(int);
109
110 /* low level HW communication interface */
111 static int buspirate_serial_setspeed(int fd, speed_t speed);
112 static int buspirate_serial_write(int fd, char *buf, int size);
113 static int buspirate_serial_read(int fd, char *buf, int size);
114 static void buspirate_print_buffer(char *buf, int size);
115
116 static int buspirate_speed(int speed)
117 {
118         /* TODO */
119         LOG_INFO("Want to set speed to %dkHz, but not implemented yet", speed);
120         return ERROR_OK;
121 }
122
123 static int buspirate_khz(int khz, int *jtag_speed)
124 {
125         *jtag_speed = khz;
126         return ERROR_OK;
127 }
128
129 static int buspirate_execute_queue(void)
130 {
131         /* currently processed command */
132         struct jtag_command *cmd = jtag_command_queue;
133         int scan_size;
134         enum scan_type type;
135         uint8_t *buffer;
136
137         while (cmd) {
138                 switch (cmd->type) {
139                 case JTAG_RUNTEST:
140                         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
141                                 cmd->cmd.runtest->num_cycles,
142                                 tap_state_name(cmd->cmd.runtest
143                                         ->end_state));
144                         buspirate_end_state(cmd->cmd.runtest
145                                         ->end_state);
146                         buspirate_runtest(cmd->cmd.runtest
147                                         ->num_cycles);
148                         break;
149                 case JTAG_TLR_RESET:
150                         DEBUG_JTAG_IO("statemove end in %s",
151                                 tap_state_name(cmd->cmd.statemove
152                                                 ->end_state));
153                         buspirate_end_state(cmd->cmd.statemove
154                                         ->end_state);
155                         buspirate_state_move();
156                         break;
157                 case JTAG_PATHMOVE:
158                         DEBUG_JTAG_IO("pathmove: %i states, end in %s",
159                                 cmd->cmd.pathmove->num_states,
160                                 tap_state_name(cmd->cmd.pathmove
161                                         ->path[cmd->cmd.pathmove
162                                                 ->num_states - 1]));
163                         buspirate_path_move(cmd->cmd.pathmove
164                                         ->num_states,
165                                         cmd->cmd.pathmove->path);
166                         break;
167                 case JTAG_SCAN:
168                         DEBUG_JTAG_IO("scan end in %s",
169                                 tap_state_name(cmd->cmd.scan
170                                         ->end_state));
171
172                         buspirate_end_state(cmd->cmd.scan
173                                         ->end_state);
174
175                         scan_size = jtag_build_buffer(cmd->cmd.scan,
176                                         &buffer);
177                         type = jtag_scan_type(cmd->cmd.scan);
178                         buspirate_scan(cmd->cmd.scan->ir_scan, type,
179                                 buffer, scan_size, cmd->cmd.scan);
180
181                         break;
182                 case JTAG_RESET:
183                         DEBUG_JTAG_IO("reset trst: %i srst %i",
184                                 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
185
186                         /* flush buffers, so we can reset */
187                         buspirate_tap_execute();
188
189                         if (cmd->cmd.reset->trst == 1)
190                                 tap_set_state(TAP_RESET);
191                         buspirate_reset(cmd->cmd.reset->trst,
192                                         cmd->cmd.reset->srst);
193                         break;
194                 case JTAG_SLEEP:
195                         DEBUG_JTAG_IO("sleep %i", cmd->cmd.sleep->us);
196                         buspirate_tap_execute();
197                         jtag_sleep(cmd->cmd.sleep->us);
198                                 break;
199                 default:
200                         LOG_ERROR("BUG: unknown JTAG command type encountered");
201                         exit(-1);
202                 }
203
204                 cmd = cmd->next;
205         }
206
207         return buspirate_tap_execute();
208 }
209
210 static int buspirate_init(void)
211 {
212         if (buspirate_port == NULL) {
213                 LOG_ERROR("You need to specify port !");
214                 return ERROR_JTAG_INIT_FAILED;
215         }
216
217         buspirate_fd = open(buspirate_port, O_RDWR | O_NOCTTY);
218         if (buspirate_fd == -1) {
219                 LOG_ERROR("Could not open serial port.");
220                 return ERROR_JTAG_INIT_FAILED;
221         }
222
223         buspirate_serial_setspeed(buspirate_fd, B115200);
224
225         buspirate_jtag_enable(buspirate_fd);
226
227         if (buspirate_baudrate != SERIAL_NORMAL)
228                 buspirate_jtag_set_speed(buspirate_fd, SERIAL_FAST);
229
230         LOG_INFO("Buspirate Interface ready!");
231
232         buspirate_tap_init();
233         buspirate_jtag_set_mode(buspirate_fd, buspirate_pinmode);
234         buspirate_jtag_set_feature(buspirate_fd, FEATURE_VREG,
235                 (buspirate_vreg == 1) ? ACTION_ENABLE : ACTION_DISABLE);
236         buspirate_jtag_set_feature(buspirate_fd, FEATURE_PULLUP,
237                 (buspirate_pullup == 1) ? ACTION_ENABLE : ACTION_DISABLE);
238         buspirate_reset(0, 0);
239
240         return ERROR_OK;
241 }
242
243 static int buspirate_quit(void)
244 {
245         LOG_INFO("Shuting down buspirate ");
246         buspirate_jtag_set_mode(buspirate_fd, MODE_HIZ);
247
248         buspirate_jtag_set_speed(buspirate_fd, SERIAL_NORMAL);
249         buspirate_jtag_reset(buspirate_fd);
250         if (buspirate_port) {
251                 free(buspirate_port);
252                 buspirate_port = NULL;
253         }
254         return ERROR_OK;
255 }
256
257 /* openocd command interface */
258 COMMAND_HANDLER(buspirate_handle_adc_command)
259 {
260         if (CMD_ARGC != 0) {
261                 LOG_ERROR("usage: buspirate_adc");
262                 return ERROR_OK;
263         }
264
265         if (buspirate_fd == -1)
266                 return ERROR_OK;
267
268         /* send the command */
269         buspirate_jtag_get_adcs(buspirate_fd);
270
271         return ERROR_OK;
272
273 }
274
275 COMMAND_HANDLER(buspirate_handle_vreg_command)
276 {
277         if (CMD_ARGC != 1) {
278                 LOG_ERROR("usage: buspirate_vreg <1|0>");
279                 return ERROR_OK;
280         }
281
282         if (atoi(CMD_ARGV[0]) == 1)
283                 buspirate_vreg = 1;
284         else
285                 buspirate_vreg = 0;
286
287         return ERROR_OK;
288
289 }
290
291 COMMAND_HANDLER(buspirate_handle_pullup_command)
292 {
293         if (CMD_ARGC != 1) {
294                 LOG_ERROR("usage: buspirate_pullup <1|0>");
295                 return ERROR_OK;
296         }
297
298         if (atoi(CMD_ARGV[0]) == 1)
299                 buspirate_pullup = 1;
300         else
301                 buspirate_pullup = 0;
302
303         return ERROR_OK;
304
305 }
306
307 COMMAND_HANDLER(buspirate_handle_led_command)
308 {
309         if (CMD_ARGC != 1) {
310                 LOG_ERROR("usage: buspirate_led <1|0>");
311                 return ERROR_OK;
312         }
313
314         if (atoi(CMD_ARGV[0]) == 1) {
315                 /* enable led */
316                 buspirate_jtag_set_feature(buspirate_fd, FEATURE_LED,
317                                 ACTION_ENABLE);
318         } else {
319                 /* disable led */
320                 buspirate_jtag_set_feature(buspirate_fd, FEATURE_LED,
321                                 ACTION_DISABLE);
322         }
323
324         return ERROR_OK;
325
326 }
327
328 COMMAND_HANDLER(buspirate_handle_mode_command)
329 {
330         if (CMD_ARGC != 1) {
331                 LOG_ERROR("usage: buspirate_mode <normal|open-drain>");
332                 return ERROR_OK;
333         }
334
335         if (CMD_ARGV[0][0] == 'n')
336                 buspirate_pinmode = MODE_JTAG;
337         else if (CMD_ARGV[0][0] == 'o')
338                 buspirate_pinmode = MODE_JTAG_OD;
339         else
340                 LOG_ERROR("usage: buspirate_mode <normal|open-drain>");
341
342         return ERROR_OK;
343
344 }
345
346 COMMAND_HANDLER(buspirate_handle_speed_command)
347 {
348         if (CMD_ARGC != 1) {
349                 LOG_ERROR("usage: buspirate_speed <normal|fast>");
350                 return ERROR_OK;
351         }
352
353         if (CMD_ARGV[0][0] == 'n')
354                 buspirate_baudrate = SERIAL_NORMAL;
355         else if (CMD_ARGV[0][0] == 'f')
356                 buspirate_baudrate = SERIAL_FAST;
357         else
358                 LOG_ERROR("usage: buspirate_speed <normal|fast>");
359
360         return ERROR_OK;
361
362 }
363
364 COMMAND_HANDLER(buspirate_handle_port_command)
365 {
366         if (CMD_ARGC != 1) {
367                 LOG_ERROR("usage: buspirate_port /dev/ttyUSB0");
368                 return ERROR_OK;
369         }
370
371         if (buspirate_port == 0)
372                 buspirate_port = strdup(CMD_ARGV[0]);
373
374         return ERROR_OK;
375
376 }
377
378 static const struct command_registration buspirate_command_handlers[] = {
379         {
380                 .name = "buspirate_adc",
381                 .handler = &buspirate_handle_adc_command,
382                 .mode = COMMAND_EXEC,
383                 .help = "reads voltages on adc pins",
384         },
385         {
386                 .name = "buspirate_vreg",
387                 .handler = &buspirate_handle_vreg_command,
388                 .mode = COMMAND_CONFIG,
389                 .help = "changes the state of voltage regulators",
390         },
391         {
392                 .name = "buspirate_pullup",
393                 .handler = &buspirate_handle_pullup_command,
394                 .mode = COMMAND_CONFIG,
395                 .help = "changes the state of pullup",
396         },
397         {
398                 .name = "buspirate_led",
399                 .handler = &buspirate_handle_led_command,
400                 .mode = COMMAND_EXEC,
401                 .help = "changes the state of led",
402         },
403         {
404                 .name = "buspirate_speed",
405                 .handler = &buspirate_handle_speed_command,
406                 .mode = COMMAND_CONFIG,
407                 .help = "speed of the interface",
408         },
409         {
410                 .name = "buspirate_mode",
411                 .handler = &buspirate_handle_mode_command,
412                 .mode = COMMAND_CONFIG,
413                 .help = "pin mode of the interface",
414         },
415         {
416                 .name = "buspirate_port",
417                 .handler = &buspirate_handle_port_command,
418                 .mode = COMMAND_CONFIG,
419                 .help = "name of the serial port to open",
420         },
421         COMMAND_REGISTRATION_DONE
422 };
423
424 struct jtag_interface buspirate_interface = {
425         .name = "buspirate",
426         .execute_queue = buspirate_execute_queue,
427         .speed = buspirate_speed,
428         .khz = buspirate_khz,
429         .commands = buspirate_command_handlers,
430         .init = buspirate_init,
431         .quit = buspirate_quit
432 };
433
434 /*************** jtag execute commands **********************/
435 static void buspirate_end_state(tap_state_t state)
436 {
437         if (tap_is_state_stable(state))
438                 tap_set_end_state(state);
439         else {
440                 LOG_ERROR("BUG: %i is not a valid end state", state);
441                 exit(-1);
442         }
443 }
444
445 static void buspirate_state_move(void)
446 {
447         int i = 0, tms = 0;
448         uint8_t tms_scan = tap_get_tms_path(tap_get_state(),
449                         tap_get_end_state());
450         int tms_count = tap_get_tms_path_len(tap_get_state(),
451                         tap_get_end_state());
452
453         for (i = 0; i < tms_count; i++) {
454                 tms = (tms_scan >> i) & 1;
455                 buspirate_tap_append(tms, 0);
456         }
457
458         tap_set_state(tap_get_end_state());
459 }
460
461 static void buspirate_path_move(int num_states, tap_state_t *path)
462 {
463         int i;
464
465         for (i = 0; i < num_states; i++) {
466                 if (tap_state_transition(tap_get_state(), false) == path[i]) {
467                         buspirate_tap_append(0, 0);
468                 } else if (tap_state_transition(tap_get_state(), true)
469                                 == path[i]) {
470                         buspirate_tap_append(1, 0);
471                 } else {
472                         LOG_ERROR("BUG: %s -> %s isn't a valid "
473                                 "TAP transition",
474                                 tap_state_name(tap_get_state()),
475                                 tap_state_name(path[i]));
476                         exit(-1);
477                 }
478
479                 tap_set_state(path[i]);
480         }
481
482         tap_set_end_state(tap_get_state());
483 }
484
485 static void buspirate_runtest(int num_cycles)
486 {
487         int i;
488
489         tap_state_t saved_end_state = tap_get_end_state();
490
491         /* only do a state_move when we're not already in IDLE */
492         if (tap_get_state() != TAP_IDLE) {
493                 buspirate_end_state(TAP_IDLE);
494                 buspirate_state_move();
495         }
496
497         for (i = 0; i < num_cycles; i++)
498                 buspirate_tap_append(0, 0);
499
500         DEBUG_JTAG_IO("runtest: cur_state %s end_state %s",
501                         tap_state_name(tap_get_state()),
502                         tap_state_name(tap_get_end_state()));
503
504         /* finish in end_state */
505         buspirate_end_state(saved_end_state);
506         if (tap_get_state() != tap_get_end_state())
507                 buspirate_state_move();
508 }
509
510 static void buspirate_scan(bool ir_scan, enum scan_type type,
511         uint8_t *buffer, int scan_size, struct scan_command *command)
512 {
513         tap_state_t saved_end_state;
514
515         buspirate_tap_make_space(1, scan_size+8);
516         /* is 8 correct ? (2 moves = 16) */
517
518         saved_end_state = tap_get_end_state();
519
520         buspirate_end_state(ir_scan ? TAP_IRSHIFT : TAP_DRSHIFT);
521         buspirate_state_move();
522
523         buspirate_tap_append_scan(scan_size, buffer, command);
524
525         /* move to PAUSE */
526         buspirate_tap_append(0, 0);
527
528         /* restore the saved state */
529         buspirate_end_state(saved_end_state);
530         tap_set_state(ir_scan ? TAP_IRPAUSE : TAP_DRPAUSE);
531
532         if (tap_get_state() != tap_get_end_state())
533                 buspirate_state_move();
534 }
535
536
537 /************************* TAP related stuff **********/
538
539 #define BUSPIRATE_BUFFER_SIZE 1024
540 #define BUSPIRATE_MAX_PENDING_SCANS 32
541
542 static char tms_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
543 static char tdi_chain[BUSPIRATE_BUFFER_SIZE]; /* send */
544 static int tap_chain_index;
545
546 struct pending_scan_result /* this was stolen from arm-jtag-ew */
547 {
548         int first; /* First bit position in tdo_buffer to read */
549         int length; /* Number of bits to read */
550         struct scan_command *command; /* Corresponding scan command */
551         uint8_t *buffer;
552 };
553
554 static struct pending_scan_result
555 tap_pending_scans[BUSPIRATE_MAX_PENDING_SCANS];
556 static int tap_pending_scans_num;
557
558 static void buspirate_tap_init(void)
559 {
560         tap_chain_index = 0;
561         tap_pending_scans_num = 0;
562 }
563
564 static int buspirate_tap_execute(void)
565 {
566         char tmp[4096];
567         uint8_t *in_buf;
568         int i;
569         int fill_index = 0;
570         int ret;
571         int bytes_to_send;
572
573         if (tap_chain_index <= 0)
574                 return ERROR_OK;
575
576         LOG_DEBUG("executing tap num bits = %i scans = %i",
577                         tap_chain_index, tap_pending_scans_num);
578
579         bytes_to_send = (tap_chain_index+7) / 8;
580
581         tmp[0] = CMD_TAP_SHIFT; /* this command expects number of bits */
582         tmp[1] = (char)(tap_chain_index >> 8);  /* high */
583         tmp[2] = (char)(tap_chain_index);  /* low */
584
585         fill_index = 3;
586         for (i = 0; i < bytes_to_send; i++) {
587                 tmp[fill_index] = tdi_chain[i];
588                 fill_index++;
589                 tmp[fill_index] = tms_chain[i];
590                 fill_index++;
591         }
592
593         ret = buspirate_serial_write(buspirate_fd, tmp, 3 + bytes_to_send*2);
594         if (ret != bytes_to_send*2+3) {
595                 LOG_ERROR("error writing :(");
596                 return ERROR_JTAG_DEVICE_ERROR;
597         }
598
599         ret = buspirate_serial_read(buspirate_fd, tmp, bytes_to_send + 3);
600         in_buf = (uint8_t *)(&tmp[3]);
601
602         /* parse the scans */
603         for (i = 0; i < tap_pending_scans_num; i++) {
604                 uint8_t *buffer = tap_pending_scans[i].buffer;
605                 int length = tap_pending_scans[i].length;
606                 int first = tap_pending_scans[i].first;
607                 struct scan_command *command = tap_pending_scans[i].command;
608
609                 /* copy bits from buffer */
610                 buf_set_buf(in_buf, first, buffer, 0, length);
611
612                 /* return buffer to higher level */
613                 if (jtag_read_buffer(buffer, command) != ERROR_OK) {
614                         buspirate_tap_init();
615                         return ERROR_JTAG_QUEUE_FAILED;
616                 }
617
618                 free(buffer);
619         }
620         tap_pending_scans_num = 0;
621         tap_chain_index = 0;
622         return ERROR_OK;
623 }
624
625 static void buspirate_tap_make_space(int scans, int bits)
626 {
627         int have_scans = BUSPIRATE_MAX_PENDING_SCANS - tap_pending_scans_num;
628         int have_bits = BUSPIRATE_BUFFER_SIZE * 8 - tap_chain_index;
629
630         if ((have_scans < scans) || (have_bits < bits))
631                 buspirate_tap_execute();
632 }
633
634 static void buspirate_tap_append(int tms, int tdi)
635 {
636         int chain_index;
637
638         buspirate_tap_make_space(0, 1);
639         chain_index = tap_chain_index / 8;
640
641         if (chain_index < BUSPIRATE_BUFFER_SIZE) {
642                 int bit_index = tap_chain_index % 8;
643                 uint8_t bit = 1 << bit_index;
644
645                 if (tms)
646                         tms_chain[chain_index] |= bit;
647                 else
648                         tms_chain[chain_index] &= ~bit;
649
650                 if (tdi)
651                         tdi_chain[chain_index] |= bit;
652                 else
653                         tdi_chain[chain_index] &= ~bit;
654
655                 tap_chain_index++;
656         } else
657                 LOG_ERROR("tap_chain overflow, Bad things will happen");
658
659 }
660
661 static void buspirate_tap_append_scan(int length, uint8_t *buffer,
662                 struct scan_command *command)
663 {
664         int i;
665         tap_pending_scans[tap_pending_scans_num].length = length;
666         tap_pending_scans[tap_pending_scans_num].buffer = buffer;
667         tap_pending_scans[tap_pending_scans_num].command = command;
668         tap_pending_scans[tap_pending_scans_num].first = tap_chain_index;
669
670         for (i = 0; i < length; i++) {
671                 int tms = (i < length-1 ? 0 : 1);
672                 int tdi = (buffer[i/8] >> (i%8)) & 1;
673                 buspirate_tap_append(tms, tdi);
674         }
675         tap_pending_scans_num++;
676 }
677
678 /*************** jtag wrapper functions *********************/
679
680 /* (1) assert or (0) deassert reset lines */
681 static void buspirate_reset(int trst, int srst)
682 {
683         LOG_DEBUG("trst: %i, srst: %i", trst, srst);
684
685         if (trst)
686                 buspirate_jtag_set_feature(buspirate_fd,
687                                 FEATURE_TRST, ACTION_DISABLE);
688         else
689                 buspirate_jtag_set_feature(buspirate_fd,
690                                 FEATURE_TRST, ACTION_ENABLE);
691
692         if (srst)
693                 buspirate_jtag_set_feature(buspirate_fd,
694                                 FEATURE_SRST, ACTION_DISABLE);
695         else
696                 buspirate_jtag_set_feature(buspirate_fd,
697                                 FEATURE_SRST, ACTION_ENABLE);
698 }
699
700 /*************** jtag lowlevel functions ********************/
701 static void buspirate_jtag_enable(int fd)
702 {
703         int ret;
704         char tmp[21] = { [0 ... 20] = 0x00 };
705         int done = 0;
706         int cmd_sent = 0;
707
708         LOG_DEBUG("Entering binary mode");
709         buspirate_serial_write(fd, tmp, 20);
710         usleep(10000);
711
712         /* reads 1 to n "BBIO1"s and one "OCD1" */
713         while (!done) {
714                 ret = buspirate_serial_read(fd, tmp, 4);
715                 if (ret != 4) {
716                         LOG_ERROR("Buspirate did not respond :"
717                                 "( restart everything");
718                         exit(-1);
719                 }
720                 LOG_DEBUG("TUI");
721                 if (strncmp(tmp, "BBIO", 4) == 0) {
722                         ret = buspirate_serial_read(fd, tmp, 1);
723                         if (ret != 1) {
724                                 LOG_ERROR("Buspirate did not respond well :"
725                                         "( restart everything");
726                                 exit(-1);
727                         }
728                         if (tmp[0] != '1') {
729                                 LOG_ERROR("Unsupported binary protocol ");
730                                 exit(-1);
731                         }
732                         if (cmd_sent == 0) {
733                                 cmd_sent = 1;
734                                 tmp[0] = CMD_ENTER_OOCD;
735                                 ret = buspirate_serial_write(fd, tmp, 1);
736                         }
737                 } else if (strncmp(tmp, "OCD1", 4) == 0)
738                         done = 1;
739                 else {
740                         LOG_ERROR("Buspirate did not respond :"
741                                 "( restart everything");
742                         exit(-1);
743                 }
744         }
745
746 }
747
748 static void buspirate_jtag_reset(int fd)
749 {
750         int ret;
751         char tmp[5];
752
753         tmp[0] = 0x00; /* exit OCD1 mode */
754         buspirate_serial_write(fd, tmp, 1);
755         usleep(10000);
756         ret = buspirate_serial_read(fd, tmp, 5);
757         if (strncmp(tmp, "BBIO1", 5) == 0) {
758                 tmp[0] = 0x0F; /*  reset BP */
759                 buspirate_serial_write(fd, tmp, 1);
760         } else
761                 LOG_ERROR("Bad reply :( Please restart manually");
762 }
763
764 static void buspirate_jtag_set_speed(int fd, char speed)
765 {
766         int ret;
767         char tmp[2];
768         char ack[2];
769         speed_t baudrate = B115200;
770
771         ack[0] = 0xAA;
772         ack[1] = 0x55;
773
774         tmp[0] = CMD_UART_SPEED;
775         tmp[1] = speed;
776         buspirate_jtag_command(fd, tmp, 2);
777
778         /* here the adapter changes speed, we need follow */
779         if (speed == SERIAL_FAST)
780                 baudrate = B1000000;
781
782         buspirate_serial_setspeed(fd, baudrate);
783
784         buspirate_serial_write(fd, ack, 2);
785         ret = buspirate_serial_read(fd, tmp, 2);
786         if (ret != 2) {
787                 LOG_ERROR("Buspirate did not respond :"
788                         "( restart everything");
789                 exit(-1);
790         }
791         if ((tmp[0] != CMD_UART_SPEED) || (tmp[1] != speed)) {
792                 LOG_ERROR("Buspirate didn't reply as expected :"
793                         "( restart everything");
794                 exit(-1);
795         }
796         LOG_INFO("Buspirate switched to %s mode",
797                 (speed == SERIAL_NORMAL) ? "normal" : "FAST");
798 }
799
800
801 static void buspirate_jtag_set_mode(int fd, char mode)
802 {
803         char tmp[2];
804         tmp[0] = CMD_PORT_MODE;
805         tmp[1] = mode;
806         buspirate_jtag_command(fd, tmp, 2);
807 }
808
809 static void buspirate_jtag_set_feature(int fd, char feat, char action)
810 {
811         char tmp[3];
812         tmp[0] = CMD_FEATURE;
813         tmp[1] = feat;   /* what */
814         tmp[2] = action; /* action */
815         buspirate_jtag_command(fd, tmp, 3);
816 }
817
818 static void buspirate_jtag_get_adcs(int fd)
819 {
820         uint8_t tmp[10];
821         uint16_t a, b, c, d;
822         tmp[0] = CMD_READ_ADCS;
823         buspirate_jtag_command(fd, (char *)tmp, 1);
824         a = tmp[2] << 8 | tmp[3];
825         b = tmp[4] << 8 | tmp[5];
826         c = tmp[6] << 8 | tmp[7];
827         d = tmp[8] << 8 | tmp[9];
828
829         LOG_INFO("ADC: ADC_Pin = %.02f VPullup = %.02f V33 = %.02f "
830                 "V50 = %.02f",
831                 ((float)a)/155.1515, ((float)b)/155.1515,
832                 ((float)c)/155.1515, ((float)d)/155.1515);
833 }
834
835 static unsigned char buspirate_jtag_command(int fd,
836                 char *cmd, int cmdlen)
837 {
838         int res;
839         int len = 0;
840
841         res = buspirate_serial_write(fd, cmd, cmdlen);
842
843         if ((cmd[0] == CMD_UART_SPEED)
844                                 || (cmd[0] == CMD_PORT_MODE)
845                                 || (cmd[0] == CMD_FEATURE)
846                                 || (cmd[0] == CMD_JTAG_SPEED))
847                 return 1;
848
849         if (res == cmdlen) {
850                 switch (cmd[0]) {
851                 case CMD_READ_ADCS:
852                         len = 10; /* 2*sizeof(char)+4*sizeof(uint16_t) */
853                         break;
854                 case CMD_TAP_SHIFT:
855                         len = cmdlen;
856                         break;
857                 default:
858                         LOG_INFO("Wrong !");
859                 }
860                 res =  buspirate_serial_read(fd, cmd, len);
861                 if (res > 0)
862                         return (unsigned char)cmd[1];
863                 else
864                         return -1;
865         } else
866                 return -1;
867         return 0;
868 }
869
870 /* low level serial port */
871 /* TODO add support for WIN32 and others ! */
872 static int buspirate_serial_setspeed(int fd, speed_t speed)
873 {
874         struct termios t_opt;
875
876         /* set the serial port parameters */
877         fcntl(fd, F_SETFL, 0);
878         tcgetattr(fd, &t_opt);
879         cfsetispeed(&t_opt, speed);
880         cfsetospeed(&t_opt, speed);
881         t_opt.c_cflag |= (CLOCAL | CREAD);
882         t_opt.c_cflag &= ~PARENB;
883         t_opt.c_cflag &= ~CSTOPB;
884         t_opt.c_cflag &= ~CSIZE;
885         t_opt.c_cflag |= CS8;
886         t_opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
887         t_opt.c_iflag &= ~(IXON | IXOFF | IXANY);
888         t_opt.c_oflag &= ~OPOST;
889         t_opt.c_cc[VMIN] = 0;
890         t_opt.c_cc[VTIME] = 10;
891         tcflush(fd, TCIFLUSH);
892         tcsetattr(fd, TCSANOW, &t_opt);
893
894         return 0;
895 }
896
897 static int buspirate_serial_write(int fd, char *buf, int size)
898 {
899         int ret = 0;
900
901         ret = write(fd, buf, size);
902
903         LOG_DEBUG("size = %d ret = %d", size, ret);
904         buspirate_print_buffer(buf, size);
905
906         if (ret != size)
907                 LOG_ERROR("Error sending data");
908
909         return ret;
910 }
911
912 static int buspirate_serial_read(int fd, char *buf, int size)
913 {
914         int len = 0;
915         int ret = 0;
916         int timeout = 0;
917
918         while (len < size) {
919                 ret = read(fd, buf+len, size-len);
920                 if (ret == -1)
921                         return -1;
922
923                 if (ret == 0) {
924                         timeout++;
925
926                         if (timeout >= 10)
927                                 break;
928
929                         continue;
930                 }
931
932                 len += ret;
933         }
934
935         LOG_DEBUG("should have read = %d actual size = %d", size, len);
936         buspirate_print_buffer(buf, len);
937
938         if (len != size)
939                 LOG_ERROR("Error sending data");
940
941         return len;
942 }
943
944 #define LINE_SIZE      81
945 #define BYTES_PER_LINE 16
946 static void buspirate_print_buffer(char *buf, int size)
947 {
948         char line[LINE_SIZE];
949         char tmp[10];
950         int offset = 0;
951
952         line[0] = 0;
953         while (offset < size) {
954                 snprintf(tmp, 5, "%02x ", (uint8_t)buf[offset]);
955                 offset++;
956
957                 strcat(line, tmp);
958
959                 if (offset % BYTES_PER_LINE == 0) {
960                         LOG_DEBUG("%s", line);
961                         line[0] = 0;
962                 }
963         }
964
965         if (line[0] != 0) {
966                 LOG_DEBUG("%s", line);
967         }
968 }
969