jtag/drivers/ftdi: require defining SWD_EN signal for SWD mode
[fw/openocd] / src / jtag / drivers / ftdi.c
1 /**************************************************************************
2 *   Copyright (C) 2012 by Andreas Fritiofson                              *
3 *   andreas.fritiofson@gmail.com                                          *
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 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
19 ***************************************************************************/
20
21 /**
22  * @file
23  * JTAG adapters based on the FT2232 full and high speed USB parts are
24  * popular low cost JTAG debug solutions.  Many FT2232 based JTAG adapters
25  * are discrete, but development boards may integrate them as alternatives
26  * to more capable (and expensive) third party JTAG pods.
27  *
28  * JTAG uses only one of the two communications channels ("MPSSE engines")
29  * on these devices.  Adapters based on FT4232 parts have four ports/channels
30  * (A/B/C/D), instead of just two (A/B).
31  *
32  * Especially on development boards integrating one of these chips (as
33  * opposed to discrete pods/dongles), the additional channels can be used
34  * for a variety of purposes, but OpenOCD only uses one channel at a time.
35  *
36  *  - As a USB-to-serial adapter for the target's console UART ...
37  *    which may be able to support ROM boot loaders that load initial
38  *    firmware images to flash (or SRAM).
39  *
40  *  - On systems which support ARM's SWD in addition to JTAG, or instead
41  *    of it, that second port can be used for reading SWV/SWO trace data.
42  *
43  *  - Additional JTAG links, e.g. to a CPLD or * FPGA.
44  *
45  * FT2232 based JTAG adapters are "dumb" not "smart", because most JTAG
46  * request/response interactions involve round trips over the USB link.
47  * A "smart" JTAG adapter has intelligence close to the scan chain, so it
48  * can for example poll quickly for a status change (usually taking on the
49  * order of microseconds not milliseconds) before beginning a queued
50  * transaction which require the previous one to have completed.
51  *
52  * There are dozens of adapters of this type, differing in details which
53  * this driver needs to understand.  Those "layout" details are required
54  * as part of FT2232 driver configuration.
55  *
56  * This code uses information contained in the MPSSE specification which was
57  * found here:
58  * http://www.ftdichip.com/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf
59  * Hereafter this is called the "MPSSE Spec".
60  *
61  * The datasheet for the ftdichip.com's FT2232D part is here:
62  * http://www.ftdichip.com/Documents/DataSheets/DS_FT2232D.pdf
63  *
64  * Also note the issue with code 0x4b (clock data to TMS) noted in
65  * http://developer.intra2net.com/mailarchive/html/libftdi/2009/msg00292.html
66  * which can affect longer JTAG state paths.
67  */
68
69 #ifdef HAVE_CONFIG_H
70 #include "config.h"
71 #endif
72
73 /* project specific includes */
74 #include <jtag/interface.h>
75 #include <jtag/swd.h>
76 #include <transport/transport.h>
77 #include <helper/time_support.h>
78
79 #if IS_CYGWIN == 1
80 #include <windows.h>
81 #endif
82
83 #include <assert.h>
84
85 /* FTDI access library includes */
86 #include "mpsse.h"
87
88 #define JTAG_MODE (LSB_FIRST | POS_EDGE_IN | NEG_EDGE_OUT)
89 #define SWD_MODE (LSB_FIRST | POS_EDGE_IN | NEG_EDGE_OUT)
90
91 static char *ftdi_device_desc;
92 static char *ftdi_serial;
93 static uint8_t ftdi_channel;
94
95 static bool swd_mode;
96
97 #define MAX_USB_IDS 8
98 /* vid = pid = 0 marks the end of the list */
99 static uint16_t ftdi_vid[MAX_USB_IDS + 1] = { 0 };
100 static uint16_t ftdi_pid[MAX_USB_IDS + 1] = { 0 };
101
102 static struct mpsse_ctx *mpsse_ctx;
103
104 struct signal {
105         const char *name;
106         uint16_t data_mask;
107         uint16_t oe_mask;
108         bool invert_data;
109         bool invert_oe;
110         struct signal *next;
111 };
112
113 static struct signal *signals;
114
115 /* FIXME: Where to store per-instance data? We need an SWD context. */
116 static struct swd_cmd_queue_entry {
117         uint8_t cmd;
118         uint32_t *dst;
119         uint8_t trn_ack_data_parity_trn[DIV_ROUND_UP(4 + 3 + 32 + 1 + 4, 8)];
120 } *swd_cmd_queue;
121 static size_t swd_cmd_queue_length;
122 static size_t swd_cmd_queue_alloced;
123 static int queued_retval;
124 static int freq;
125
126 static uint16_t output;
127 static uint16_t direction;
128 static uint16_t jtag_output_init;
129 static uint16_t jtag_direction_init;
130
131 static int ftdi_swd_switch_seq(struct adiv5_dap *dap, enum swd_special_seq seq);
132
133 static struct signal *find_signal_by_name(const char *name)
134 {
135         for (struct signal *sig = signals; sig; sig = sig->next) {
136                 if (strcmp(name, sig->name) == 0)
137                         return sig;
138         }
139         return NULL;
140 }
141
142 static struct signal *create_signal(const char *name)
143 {
144         struct signal **psig = &signals;
145         while (*psig)
146                 psig = &(*psig)->next;
147
148         *psig = calloc(1, sizeof(**psig));
149         if (*psig == NULL)
150                 return NULL;
151
152         (*psig)->name = strdup(name);
153         if ((*psig)->name == NULL) {
154                 free(*psig);
155                 *psig = NULL;
156         }
157         return *psig;
158 }
159
160 static int ftdi_set_signal(const struct signal *s, char value)
161 {
162         bool data;
163         bool oe;
164
165         if (s->data_mask == 0 && s->oe_mask == 0) {
166                 LOG_ERROR("interface doesn't provide signal '%s'", s->name);
167                 return ERROR_FAIL;
168         }
169         switch (value) {
170         case '0':
171                 data = s->invert_data;
172                 oe = !s->invert_oe;
173                 break;
174         case '1':
175                 if (s->data_mask == 0) {
176                         LOG_ERROR("interface can't drive '%s' high", s->name);
177                         return ERROR_FAIL;
178                 }
179                 data = !s->invert_data;
180                 oe = !s->invert_oe;
181                 break;
182         case 'z':
183         case 'Z':
184                 if (s->oe_mask == 0) {
185                         LOG_ERROR("interface can't tri-state '%s'", s->name);
186                         return ERROR_FAIL;
187                 }
188                 data = s->invert_data;
189                 oe = s->invert_oe;
190                 break;
191         default:
192                 assert(0 && "invalid signal level specifier");
193                 return ERROR_FAIL;
194         }
195
196         uint16_t old_output = output;
197         uint16_t old_direction = direction;
198
199         output = data ? output | s->data_mask : output & ~s->data_mask;
200         if (s->oe_mask == s->data_mask)
201                 direction = oe ? direction | s->oe_mask : direction & ~s->oe_mask;
202         else
203                 output = oe ? output | s->oe_mask : output & ~s->oe_mask;
204
205         if ((output & 0xff) != (old_output & 0xff) || (direction & 0xff) != (old_direction & 0xff))
206                 mpsse_set_data_bits_low_byte(mpsse_ctx, output & 0xff, direction & 0xff);
207         if ((output >> 8 != old_output >> 8) || (direction >> 8 != old_direction >> 8))
208                 mpsse_set_data_bits_high_byte(mpsse_ctx, output >> 8, direction >> 8);
209
210         return ERROR_OK;
211 }
212
213
214 /**
215  * Function move_to_state
216  * moves the TAP controller from the current state to a
217  * \a goal_state through a path given by tap_get_tms_path().  State transition
218  * logging is performed by delegation to clock_tms().
219  *
220  * @param goal_state is the destination state for the move.
221  */
222 static void move_to_state(tap_state_t goal_state)
223 {
224         tap_state_t start_state = tap_get_state();
225
226         /*      goal_state is 1/2 of a tuple/pair of states which allow convenient
227                 lookup of the required TMS pattern to move to this state from the
228                 start state.
229         */
230
231         /* do the 2 lookups */
232         uint8_t tms_bits  = tap_get_tms_path(start_state, goal_state);
233         int tms_count = tap_get_tms_path_len(start_state, goal_state);
234         assert(tms_count <= 8);
235
236         DEBUG_JTAG_IO("start=%s goal=%s", tap_state_name(start_state), tap_state_name(goal_state));
237
238         /* Track state transitions step by step */
239         for (int i = 0; i < tms_count; i++)
240                 tap_set_state(tap_state_transition(tap_get_state(), (tms_bits >> i) & 1));
241
242         mpsse_clock_tms_cs_out(mpsse_ctx,
243                 &tms_bits,
244                 0,
245                 tms_count,
246                 false,
247                 JTAG_MODE);
248 }
249
250 static int ftdi_speed(int speed)
251 {
252         int retval;
253         retval = mpsse_set_frequency(mpsse_ctx, speed);
254
255         if (retval < 0) {
256                 LOG_ERROR("couldn't set FTDI TCK speed");
257                 return retval;
258         }
259
260         return ERROR_OK;
261 }
262
263 static int ftdi_speed_div(int speed, int *khz)
264 {
265         *khz = speed / 1000;
266         return ERROR_OK;
267 }
268
269 static int ftdi_khz(int khz, int *jtag_speed)
270 {
271         if (khz == 0 && !mpsse_is_high_speed(mpsse_ctx)) {
272                 LOG_DEBUG("RCLK not supported");
273                 return ERROR_FAIL;
274         }
275
276         *jtag_speed = khz * 1000;
277         return ERROR_OK;
278 }
279
280 static void ftdi_end_state(tap_state_t state)
281 {
282         if (tap_is_state_stable(state))
283                 tap_set_end_state(state);
284         else {
285                 LOG_ERROR("BUG: %s is not a stable end state", tap_state_name(state));
286                 exit(-1);
287         }
288 }
289
290 static void ftdi_execute_runtest(struct jtag_command *cmd)
291 {
292         int i;
293         uint8_t zero = 0;
294
295         DEBUG_JTAG_IO("runtest %i cycles, end in %s",
296                 cmd->cmd.runtest->num_cycles,
297                 tap_state_name(cmd->cmd.runtest->end_state));
298
299         if (tap_get_state() != TAP_IDLE)
300                 move_to_state(TAP_IDLE);
301
302         /* TODO: Reuse ftdi_execute_stableclocks */
303         i = cmd->cmd.runtest->num_cycles;
304         while (i > 0) {
305                 /* there are no state transitions in this code, so omit state tracking */
306                 unsigned this_len = i > 7 ? 7 : i;
307                 mpsse_clock_tms_cs_out(mpsse_ctx, &zero, 0, this_len, false, JTAG_MODE);
308                 i -= this_len;
309         }
310
311         ftdi_end_state(cmd->cmd.runtest->end_state);
312
313         if (tap_get_state() != tap_get_end_state())
314                 move_to_state(tap_get_end_state());
315
316         DEBUG_JTAG_IO("runtest: %i, end in %s",
317                 cmd->cmd.runtest->num_cycles,
318                 tap_state_name(tap_get_end_state()));
319 }
320
321 static void ftdi_execute_statemove(struct jtag_command *cmd)
322 {
323         DEBUG_JTAG_IO("statemove end in %s",
324                 tap_state_name(cmd->cmd.statemove->end_state));
325
326         ftdi_end_state(cmd->cmd.statemove->end_state);
327
328         /* shortest-path move to desired end state */
329         if (tap_get_state() != tap_get_end_state() || tap_get_end_state() == TAP_RESET)
330                 move_to_state(tap_get_end_state());
331 }
332
333 /**
334  * Clock a bunch of TMS (or SWDIO) transitions, to change the JTAG
335  * (or SWD) state machine. REVISIT: Not the best method, perhaps.
336  */
337 static void ftdi_execute_tms(struct jtag_command *cmd)
338 {
339         DEBUG_JTAG_IO("TMS: %d bits", cmd->cmd.tms->num_bits);
340
341         /* TODO: Missing tap state tracking, also missing from ft2232.c! */
342         mpsse_clock_tms_cs_out(mpsse_ctx,
343                 cmd->cmd.tms->bits,
344                 0,
345                 cmd->cmd.tms->num_bits,
346                 false,
347                 JTAG_MODE);
348 }
349
350 static void ftdi_execute_pathmove(struct jtag_command *cmd)
351 {
352         tap_state_t *path = cmd->cmd.pathmove->path;
353         int num_states  = cmd->cmd.pathmove->num_states;
354
355         DEBUG_JTAG_IO("pathmove: %i states, current: %s  end: %s", num_states,
356                 tap_state_name(tap_get_state()),
357                 tap_state_name(path[num_states-1]));
358
359         int state_count = 0;
360         unsigned bit_count = 0;
361         uint8_t tms_byte = 0;
362
363         DEBUG_JTAG_IO("-");
364
365         /* this loop verifies that the path is legal and logs each state in the path */
366         while (num_states--) {
367
368                 /* either TMS=0 or TMS=1 must work ... */
369                 if (tap_state_transition(tap_get_state(), false)
370                     == path[state_count])
371                         buf_set_u32(&tms_byte, bit_count++, 1, 0x0);
372                 else if (tap_state_transition(tap_get_state(), true)
373                          == path[state_count]) {
374                         buf_set_u32(&tms_byte, bit_count++, 1, 0x1);
375
376                         /* ... or else the caller goofed BADLY */
377                 } else {
378                         LOG_ERROR("BUG: %s -> %s isn't a valid "
379                                 "TAP state transition",
380                                 tap_state_name(tap_get_state()),
381                                 tap_state_name(path[state_count]));
382                         exit(-1);
383                 }
384
385                 tap_set_state(path[state_count]);
386                 state_count++;
387
388                 if (bit_count == 7 || num_states == 0) {
389                         mpsse_clock_tms_cs_out(mpsse_ctx,
390                                         &tms_byte,
391                                         0,
392                                         bit_count,
393                                         false,
394                                         JTAG_MODE);
395                         bit_count = 0;
396                 }
397         }
398         tap_set_end_state(tap_get_state());
399 }
400
401 static void ftdi_execute_scan(struct jtag_command *cmd)
402 {
403         DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
404                 jtag_scan_type(cmd->cmd.scan));
405
406         /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
407         while (cmd->cmd.scan->num_fields > 0
408                         && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
409                 cmd->cmd.scan->num_fields--;
410                 LOG_DEBUG("discarding trailing empty field");
411         }
412
413         if (cmd->cmd.scan->num_fields == 0) {
414                 LOG_DEBUG("empty scan, doing nothing");
415                 return;
416         }
417
418         if (cmd->cmd.scan->ir_scan) {
419                 if (tap_get_state() != TAP_IRSHIFT)
420                         move_to_state(TAP_IRSHIFT);
421         } else {
422                 if (tap_get_state() != TAP_DRSHIFT)
423                         move_to_state(TAP_DRSHIFT);
424         }
425
426         ftdi_end_state(cmd->cmd.scan->end_state);
427
428         struct scan_field *field = cmd->cmd.scan->fields;
429         unsigned scan_size = 0;
430
431         for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
432                 scan_size += field->num_bits;
433                 DEBUG_JTAG_IO("%s%s field %d/%d %d bits",
434                         field->in_value ? "in" : "",
435                         field->out_value ? "out" : "",
436                         i,
437                         cmd->cmd.scan->num_fields,
438                         field->num_bits);
439
440                 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
441                         /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
442                          * movement. This last field can't have length zero, it was checked above. */
443                         mpsse_clock_data(mpsse_ctx,
444                                 field->out_value,
445                                 0,
446                                 field->in_value,
447                                 0,
448                                 field->num_bits - 1,
449                                 JTAG_MODE);
450                         uint8_t last_bit = 0;
451                         if (field->out_value)
452                                 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
453                         uint8_t tms_bits = 0x01;
454                         mpsse_clock_tms_cs(mpsse_ctx,
455                                         &tms_bits,
456                                         0,
457                                         field->in_value,
458                                         field->num_bits - 1,
459                                         1,
460                                         last_bit,
461                                         JTAG_MODE);
462                         tap_set_state(tap_state_transition(tap_get_state(), 1));
463                         mpsse_clock_tms_cs_out(mpsse_ctx,
464                                         &tms_bits,
465                                         1,
466                                         1,
467                                         last_bit,
468                                         JTAG_MODE);
469                         tap_set_state(tap_state_transition(tap_get_state(), 0));
470                 } else
471                         mpsse_clock_data(mpsse_ctx,
472                                 field->out_value,
473                                 0,
474                                 field->in_value,
475                                 0,
476                                 field->num_bits,
477                                 JTAG_MODE);
478         }
479
480         if (tap_get_state() != tap_get_end_state())
481                 move_to_state(tap_get_end_state());
482
483         DEBUG_JTAG_IO("%s scan, %i bits, end in %s",
484                 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
485                 tap_state_name(tap_get_end_state()));
486 }
487
488 static void ftdi_execute_reset(struct jtag_command *cmd)
489 {
490         DEBUG_JTAG_IO("reset trst: %i srst %i",
491                 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
492
493         if (cmd->cmd.reset->trst == 1
494             || (cmd->cmd.reset->srst
495                 && (jtag_get_reset_config() & RESET_SRST_PULLS_TRST)))
496                 tap_set_state(TAP_RESET);
497
498         struct signal *trst = find_signal_by_name("nTRST");
499         if (cmd->cmd.reset->trst == 1) {
500                 if (trst)
501                         ftdi_set_signal(trst, '0');
502                 else
503                         LOG_ERROR("Can't assert TRST: nTRST signal is not defined");
504         } else if (trst && cmd->cmd.reset->trst == 0) {
505                 if (jtag_get_reset_config() & RESET_TRST_OPEN_DRAIN)
506                         ftdi_set_signal(trst, 'z');
507                 else
508                         ftdi_set_signal(trst, '1');
509         }
510
511         struct signal *srst = find_signal_by_name("nSRST");
512         if (cmd->cmd.reset->srst == 1) {
513                 if (srst)
514                         ftdi_set_signal(srst, '0');
515                 else
516                         LOG_ERROR("Can't assert SRST: nSRST signal is not defined");
517         } else if (srst && cmd->cmd.reset->srst == 0) {
518                 if (jtag_get_reset_config() & RESET_SRST_PUSH_PULL)
519                         ftdi_set_signal(srst, '1');
520                 else
521                         ftdi_set_signal(srst, 'z');
522         }
523
524         DEBUG_JTAG_IO("trst: %i, srst: %i",
525                 cmd->cmd.reset->trst, cmd->cmd.reset->srst);
526 }
527
528 static void ftdi_execute_sleep(struct jtag_command *cmd)
529 {
530         DEBUG_JTAG_IO("sleep %" PRIi32, cmd->cmd.sleep->us);
531
532         mpsse_flush(mpsse_ctx);
533         jtag_sleep(cmd->cmd.sleep->us);
534         DEBUG_JTAG_IO("sleep %" PRIi32 " usec while in %s",
535                 cmd->cmd.sleep->us,
536                 tap_state_name(tap_get_state()));
537 }
538
539 static void ftdi_execute_stableclocks(struct jtag_command *cmd)
540 {
541         /* this is only allowed while in a stable state.  A check for a stable
542          * state was done in jtag_add_clocks()
543          */
544         int num_cycles = cmd->cmd.stableclocks->num_cycles;
545
546         /* 7 bits of either ones or zeros. */
547         uint8_t tms = tap_get_state() == TAP_RESET ? 0x7f : 0x00;
548
549         /* TODO: Use mpsse_clock_data with in=out=0 for this, if TMS can be set to
550          * the correct level and remain there during the scan */
551         while (num_cycles > 0) {
552                 /* there are no state transitions in this code, so omit state tracking */
553                 unsigned this_len = num_cycles > 7 ? 7 : num_cycles;
554                 mpsse_clock_tms_cs_out(mpsse_ctx, &tms, 0, this_len, false, JTAG_MODE);
555                 num_cycles -= this_len;
556         }
557
558         DEBUG_JTAG_IO("clocks %i while in %s",
559                 cmd->cmd.stableclocks->num_cycles,
560                 tap_state_name(tap_get_state()));
561 }
562
563 static void ftdi_execute_command(struct jtag_command *cmd)
564 {
565         switch (cmd->type) {
566                 case JTAG_RESET:
567                         ftdi_execute_reset(cmd);
568                         break;
569                 case JTAG_RUNTEST:
570                         ftdi_execute_runtest(cmd);
571                         break;
572                 case JTAG_TLR_RESET:
573                         ftdi_execute_statemove(cmd);
574                         break;
575                 case JTAG_PATHMOVE:
576                         ftdi_execute_pathmove(cmd);
577                         break;
578                 case JTAG_SCAN:
579                         ftdi_execute_scan(cmd);
580                         break;
581                 case JTAG_SLEEP:
582                         ftdi_execute_sleep(cmd);
583                         break;
584                 case JTAG_STABLECLOCKS:
585                         ftdi_execute_stableclocks(cmd);
586                         break;
587                 case JTAG_TMS:
588                         ftdi_execute_tms(cmd);
589                         break;
590                 default:
591                         LOG_ERROR("BUG: unknown JTAG command type encountered: %d", cmd->type);
592                         break;
593         }
594 }
595
596 static int ftdi_execute_queue(void)
597 {
598         /* blink, if the current layout has that feature */
599         struct signal *led = find_signal_by_name("LED");
600         if (led)
601                 ftdi_set_signal(led, '1');
602
603         for (struct jtag_command *cmd = jtag_command_queue; cmd; cmd = cmd->next) {
604                 /* fill the write buffer with the desired command */
605                 ftdi_execute_command(cmd);
606         }
607
608         if (led)
609                 ftdi_set_signal(led, '0');
610
611         int retval = mpsse_flush(mpsse_ctx);
612         if (retval != ERROR_OK)
613                 LOG_ERROR("error while flushing MPSSE queue: %d", retval);
614
615         return retval;
616 }
617
618 static int ftdi_initialize(void)
619 {
620         if (tap_get_tms_path_len(TAP_IRPAUSE, TAP_IRPAUSE) == 7)
621                 LOG_DEBUG("ftdi interface using 7 step jtag state transitions");
622         else
623                 LOG_DEBUG("ftdi interface using shortest path jtag state transitions");
624
625         for (int i = 0; ftdi_vid[i] || ftdi_pid[i]; i++) {
626                 mpsse_ctx = mpsse_open(&ftdi_vid[i], &ftdi_pid[i], ftdi_device_desc,
627                                 ftdi_serial, ftdi_channel);
628                 if (mpsse_ctx)
629                         break;
630         }
631
632         if (!mpsse_ctx)
633                 return ERROR_JTAG_INIT_FAILED;
634
635         output = jtag_output_init;
636         direction = jtag_direction_init;
637
638         if (swd_mode) {
639                 struct signal *sig = find_signal_by_name("SWD_EN");
640                 if (!sig) {
641                         LOG_ERROR("SWD mode is active but SWD_EN signal is not defined");
642                         return ERROR_JTAG_INIT_FAILED;
643                 }
644                 /* A dummy SWD_EN would have zero mask */
645                 if (sig->data_mask)
646                         ftdi_set_signal(sig, '1');
647         }
648
649         mpsse_set_data_bits_low_byte(mpsse_ctx, output & 0xff, direction & 0xff);
650         mpsse_set_data_bits_high_byte(mpsse_ctx, output >> 8, direction >> 8);
651
652         mpsse_loopback_config(mpsse_ctx, false);
653
654         /* Set a low default */
655         freq = mpsse_set_frequency(mpsse_ctx, 1000);
656
657         if (swd_mode)
658                 ftdi_swd_switch_seq(NULL, JTAG_TO_SWD);
659         else
660                 ftdi_swd_switch_seq(NULL, SWD_TO_JTAG);
661
662         return mpsse_flush(mpsse_ctx);
663 }
664
665 static int ftdi_quit(void)
666 {
667         mpsse_close(mpsse_ctx);
668
669         return ERROR_OK;
670 }
671
672 COMMAND_HANDLER(ftdi_handle_device_desc_command)
673 {
674         if (CMD_ARGC == 1) {
675                 if (ftdi_device_desc)
676                         free(ftdi_device_desc);
677                 ftdi_device_desc = strdup(CMD_ARGV[0]);
678         } else {
679                 LOG_ERROR("expected exactly one argument to ftdi_device_desc <description>");
680         }
681
682         return ERROR_OK;
683 }
684
685 COMMAND_HANDLER(ftdi_handle_serial_command)
686 {
687         if (CMD_ARGC == 1) {
688                 if (ftdi_serial)
689                         free(ftdi_serial);
690                 ftdi_serial = strdup(CMD_ARGV[0]);
691         } else {
692                 return ERROR_COMMAND_SYNTAX_ERROR;
693         }
694
695         return ERROR_OK;
696 }
697
698 COMMAND_HANDLER(ftdi_handle_channel_command)
699 {
700         if (CMD_ARGC == 1)
701                 COMMAND_PARSE_NUMBER(u8, CMD_ARGV[0], ftdi_channel);
702         else
703                 return ERROR_COMMAND_SYNTAX_ERROR;
704
705         return ERROR_OK;
706 }
707
708 COMMAND_HANDLER(ftdi_handle_layout_init_command)
709 {
710         if (CMD_ARGC != 2)
711                 return ERROR_COMMAND_SYNTAX_ERROR;
712
713         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[0], jtag_output_init);
714         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], jtag_direction_init);
715
716         return ERROR_OK;
717 }
718
719 COMMAND_HANDLER(ftdi_handle_layout_signal_command)
720 {
721         if (CMD_ARGC < 1)
722                 return ERROR_COMMAND_SYNTAX_ERROR;
723
724         bool invert_data = false;
725         uint16_t data_mask = 0;
726         bool invert_oe = false;
727         uint16_t oe_mask = 0;
728         for (unsigned i = 1; i < CMD_ARGC; i += 2) {
729                 if (strcmp("-data", CMD_ARGV[i]) == 0) {
730                         invert_data = false;
731                         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], data_mask);
732                 } else if (strcmp("-ndata", CMD_ARGV[i]) == 0) {
733                         invert_data = true;
734                         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], data_mask);
735                 } else if (strcmp("-oe", CMD_ARGV[i]) == 0) {
736                         invert_oe = false;
737                         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], oe_mask);
738                 } else if (strcmp("-noe", CMD_ARGV[i]) == 0) {
739                         invert_oe = true;
740                         COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], oe_mask);
741                 } else if (!strcmp("-alias", CMD_ARGV[i]) ||
742                            !strcmp("-nalias", CMD_ARGV[i])) {
743                         if (!strcmp("-nalias", CMD_ARGV[i]))
744                                 invert_data = true;
745                         struct signal *sig = find_signal_by_name(CMD_ARGV[i + 1]);
746                         if (!sig) {
747                                 LOG_ERROR("signal %s is not defined", CMD_ARGV[i + 1]);
748                                 return ERROR_FAIL;
749                         }
750                         data_mask = sig->data_mask;
751                         oe_mask = sig->oe_mask;
752                         invert_oe = sig->invert_oe;
753                         invert_data ^= sig->invert_data;
754                 } else {
755                         LOG_ERROR("unknown option '%s'", CMD_ARGV[i]);
756                         return ERROR_COMMAND_SYNTAX_ERROR;
757                 }
758         }
759
760         struct signal *sig;
761         sig = find_signal_by_name(CMD_ARGV[0]);
762         if (!sig)
763                 sig = create_signal(CMD_ARGV[0]);
764         if (!sig) {
765                 LOG_ERROR("failed to create signal %s", CMD_ARGV[0]);
766                 return ERROR_FAIL;
767         }
768
769         sig->invert_data = invert_data;
770         sig->data_mask = data_mask;
771         sig->invert_oe = invert_oe;
772         sig->oe_mask = oe_mask;
773
774         return ERROR_OK;
775 }
776
777 COMMAND_HANDLER(ftdi_handle_set_signal_command)
778 {
779         if (CMD_ARGC < 2)
780                 return ERROR_COMMAND_SYNTAX_ERROR;
781
782         struct signal *sig;
783         sig = find_signal_by_name(CMD_ARGV[0]);
784         if (!sig) {
785                 LOG_ERROR("interface configuration doesn't define signal '%s'", CMD_ARGV[0]);
786                 return ERROR_FAIL;
787         }
788
789         switch (*CMD_ARGV[1]) {
790         case '0':
791         case '1':
792         case 'z':
793         case 'Z':
794                 /* single character level specifier only */
795                 if (CMD_ARGV[1][1] == '\0') {
796                         ftdi_set_signal(sig, *CMD_ARGV[1]);
797                         break;
798                 }
799         default:
800                 LOG_ERROR("unknown signal level '%s', use 0, 1 or z", CMD_ARGV[1]);
801                 return ERROR_COMMAND_SYNTAX_ERROR;
802         }
803
804         return mpsse_flush(mpsse_ctx);
805 }
806
807 COMMAND_HANDLER(ftdi_handle_vid_pid_command)
808 {
809         if (CMD_ARGC > MAX_USB_IDS * 2) {
810                 LOG_WARNING("ignoring extra IDs in ftdi_vid_pid "
811                         "(maximum is %d pairs)", MAX_USB_IDS);
812                 CMD_ARGC = MAX_USB_IDS * 2;
813         }
814         if (CMD_ARGC < 2 || (CMD_ARGC & 1)) {
815                 LOG_WARNING("incomplete ftdi_vid_pid configuration directive");
816                 if (CMD_ARGC < 2)
817                         return ERROR_COMMAND_SYNTAX_ERROR;
818                 /* remove the incomplete trailing id */
819                 CMD_ARGC -= 1;
820         }
821
822         unsigned i;
823         for (i = 0; i < CMD_ARGC; i += 2) {
824                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i], ftdi_vid[i >> 1]);
825                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[i + 1], ftdi_pid[i >> 1]);
826         }
827
828         /*
829          * Explicitly terminate, in case there are multiples instances of
830          * ftdi_vid_pid.
831          */
832         ftdi_vid[i >> 1] = ftdi_pid[i >> 1] = 0;
833
834         return ERROR_OK;
835 }
836
837 static const struct command_registration ftdi_command_handlers[] = {
838         {
839                 .name = "ftdi_device_desc",
840                 .handler = &ftdi_handle_device_desc_command,
841                 .mode = COMMAND_CONFIG,
842                 .help = "set the USB device description of the FTDI device",
843                 .usage = "description_string",
844         },
845         {
846                 .name = "ftdi_serial",
847                 .handler = &ftdi_handle_serial_command,
848                 .mode = COMMAND_CONFIG,
849                 .help = "set the serial number of the FTDI device",
850                 .usage = "serial_string",
851         },
852         {
853                 .name = "ftdi_channel",
854                 .handler = &ftdi_handle_channel_command,
855                 .mode = COMMAND_CONFIG,
856                 .help = "set the channel of the FTDI device that is used as JTAG",
857                 .usage = "(0-3)",
858         },
859         {
860                 .name = "ftdi_layout_init",
861                 .handler = &ftdi_handle_layout_init_command,
862                 .mode = COMMAND_CONFIG,
863                 .help = "initialize the FTDI GPIO signals used "
864                         "to control output-enables and reset signals",
865                 .usage = "data direction",
866         },
867         {
868                 .name = "ftdi_layout_signal",
869                 .handler = &ftdi_handle_layout_signal_command,
870                 .mode = COMMAND_ANY,
871                 .help = "define a signal controlled by one or more FTDI GPIO as data "
872                         "and/or output enable",
873                 .usage = "name [-data mask|-ndata mask] [-oe mask|-noe mask] [-alias|-nalias name]",
874         },
875         {
876                 .name = "ftdi_set_signal",
877                 .handler = &ftdi_handle_set_signal_command,
878                 .mode = COMMAND_EXEC,
879                 .help = "control a layout-specific signal",
880                 .usage = "name (1|0|z)",
881         },
882         {
883                 .name = "ftdi_vid_pid",
884                 .handler = &ftdi_handle_vid_pid_command,
885                 .mode = COMMAND_CONFIG,
886                 .help = "the vendor ID and product ID of the FTDI device",
887                 .usage = "(vid pid)* ",
888         },
889         COMMAND_REGISTRATION_DONE
890 };
891
892 static int create_default_signal(const char *name, uint16_t data_mask)
893 {
894         struct signal *sig = create_signal(name);
895         if (!sig) {
896                 LOG_ERROR("failed to create signal %s", name);
897                 return ERROR_FAIL;
898         }
899         sig->invert_data = false;
900         sig->data_mask = data_mask;
901         sig->invert_oe = false;
902         sig->oe_mask = 0;
903
904         return ERROR_OK;
905 }
906
907 static int create_signals(void)
908 {
909         if (create_default_signal("TCK", 0x01) != ERROR_OK)
910                 return ERROR_FAIL;
911         if (create_default_signal("TDI", 0x02) != ERROR_OK)
912                 return ERROR_FAIL;
913         if (create_default_signal("TDO", 0x04) != ERROR_OK)
914                 return ERROR_FAIL;
915         if (create_default_signal("TMS", 0x08) != ERROR_OK)
916                 return ERROR_FAIL;
917         return ERROR_OK;
918 }
919
920 static int ftdi_swd_init(void)
921 {
922         LOG_INFO("FTDI SWD mode enabled");
923         swd_mode = true;
924
925         if (create_signals() != ERROR_OK)
926                 return ERROR_FAIL;
927
928         swd_cmd_queue_alloced = 10;
929         swd_cmd_queue = malloc(swd_cmd_queue_alloced * sizeof(*swd_cmd_queue));
930
931         return swd_cmd_queue != NULL ? ERROR_OK : ERROR_FAIL;
932 }
933
934 static void ftdi_swd_swdio_en(bool enable)
935 {
936         struct signal *oe = find_signal_by_name("SWDIO_OE");
937         if (oe)
938                 ftdi_set_signal(oe, enable ? '1' : '0');
939 }
940
941 /**
942  * Flush the MPSSE queue and process the SWD transaction queue
943  * @param dap
944  * @return
945  */
946 static int ftdi_swd_run_queue(struct adiv5_dap *dap)
947 {
948         LOG_DEBUG("Executing %zu queued transactions", swd_cmd_queue_length);
949         int retval;
950         struct signal *led = find_signal_by_name("LED");
951
952         if (queued_retval != ERROR_OK) {
953                 LOG_DEBUG("Skipping due to previous errors: %d", queued_retval);
954                 goto skip;
955         }
956
957         /* A transaction must be followed by another transaction or at least 8 idle cycles to
958          * ensure that data is clocked through the AP. */
959         mpsse_clock_data_out(mpsse_ctx, NULL, 0, 8, SWD_MODE);
960
961         /* Terminate the "blink", if the current layout has that feature */
962         if (led)
963                 ftdi_set_signal(led, '0');
964
965         queued_retval = mpsse_flush(mpsse_ctx);
966         if (queued_retval != ERROR_OK) {
967                 LOG_ERROR("MPSSE failed");
968                 goto skip;
969         }
970
971         for (size_t i = 0; i < swd_cmd_queue_length; i++) {
972                 int ack = buf_get_u32(&swd_cmd_queue[i].trn_ack_data_parity_trn, 1, 3);
973
974                 LOG_DEBUG("%s %s %s reg %X = %08"PRIx32,
975                                 ack == SWD_ACK_OK ? "OK" : ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK",
976                                 swd_cmd_queue[i].cmd & SWD_CMD_APnDP ? "AP" : "DP",
977                                 swd_cmd_queue[i].cmd & SWD_CMD_RnW ? "read" : "write",
978                                 (swd_cmd_queue[i].cmd & SWD_CMD_A32) >> 1,
979                                 buf_get_u32(swd_cmd_queue[i].trn_ack_data_parity_trn,
980                                                 1 + 3 + (swd_cmd_queue[i].cmd & SWD_CMD_RnW ? 0 : 1), 32));
981
982                 if (ack != SWD_ACK_OK) {
983                         queued_retval = ack;
984                         goto skip;
985
986                 } else if (swd_cmd_queue[i].cmd & SWD_CMD_RnW) {
987                         uint32_t data = buf_get_u32(swd_cmd_queue[i].trn_ack_data_parity_trn, 1 + 3, 32);
988                         int parity = buf_get_u32(swd_cmd_queue[i].trn_ack_data_parity_trn, 1 + 3 + 32, 1);
989
990                         if (parity != parity_u32(data)) {
991                                 LOG_ERROR("SWD Read data parity mismatch");
992                                 queued_retval = ERROR_FAIL;
993                                 goto skip;
994                         }
995
996                         if (swd_cmd_queue[i].dst != NULL)
997                                 *swd_cmd_queue[i].dst = data;
998                 }
999         }
1000
1001 skip:
1002         swd_cmd_queue_length = 0;
1003         retval = queued_retval;
1004         queued_retval = ERROR_OK;
1005
1006         /* Queue a new "blink" */
1007         if (led && retval == ERROR_OK)
1008                 ftdi_set_signal(led, '1');
1009
1010         return retval;
1011 }
1012
1013 static void ftdi_swd_queue_cmd(struct adiv5_dap *dap, uint8_t cmd, uint32_t *dst, uint32_t data)
1014 {
1015         if (swd_cmd_queue_length >= swd_cmd_queue_alloced) {
1016                 /* Not enough room in the queue. Run the queue and increase its size for next time.
1017                  * Note that it's not possible to avoid running the queue here, because mpsse contains
1018                  * pointers into the queue which may be invalid after the realloc. */
1019                 queued_retval = ftdi_swd_run_queue(dap);
1020                 struct swd_cmd_queue_entry *q = realloc(swd_cmd_queue, swd_cmd_queue_alloced * 2 * sizeof(*swd_cmd_queue));
1021                 if (q != NULL) {
1022                         swd_cmd_queue = q;
1023                         swd_cmd_queue_alloced *= 2;
1024                         LOG_DEBUG("Increased SWD command queue to %zu elements", swd_cmd_queue_alloced);
1025                 }
1026         }
1027
1028         if (queued_retval != ERROR_OK)
1029                 return;
1030
1031         size_t i = swd_cmd_queue_length++;
1032         swd_cmd_queue[i].cmd = cmd | SWD_CMD_START | SWD_CMD_PARK;
1033
1034         mpsse_clock_data_out(mpsse_ctx, &swd_cmd_queue[i].cmd, 0, 8, SWD_MODE);
1035
1036         if (swd_cmd_queue[i].cmd & SWD_CMD_RnW) {
1037                 /* Queue a read transaction */
1038                 swd_cmd_queue[i].dst = dst;
1039
1040                 ftdi_swd_swdio_en(false);
1041                 mpsse_clock_data_in(mpsse_ctx, swd_cmd_queue[i].trn_ack_data_parity_trn,
1042                                 0, 1 + 3 + 32 + 1 + 1, SWD_MODE);
1043                 ftdi_swd_swdio_en(true);
1044         } else {
1045                 /* Queue a write transaction */
1046                 ftdi_swd_swdio_en(false);
1047
1048                 mpsse_clock_data_in(mpsse_ctx, swd_cmd_queue[i].trn_ack_data_parity_trn,
1049                                 0, 1 + 3 + 1, SWD_MODE);
1050
1051                 ftdi_swd_swdio_en(true);
1052
1053                 buf_set_u32(swd_cmd_queue[i].trn_ack_data_parity_trn, 1 + 3 + 1, 32, data);
1054                 buf_set_u32(swd_cmd_queue[i].trn_ack_data_parity_trn, 1 + 3 + 1 + 32, 1, parity_u32(data));
1055
1056                 mpsse_clock_data_out(mpsse_ctx, swd_cmd_queue[i].trn_ack_data_parity_trn,
1057                                 1 + 3 + 1, 32 + 1, SWD_MODE);
1058         }
1059
1060         /* Insert idle cycles after AP accesses to avoid WAIT */
1061         if (cmd & SWD_CMD_APnDP)
1062                 mpsse_clock_data_out(mpsse_ctx, NULL, 0, dap->memaccess_tck, SWD_MODE);
1063
1064 }
1065
1066 static void ftdi_swd_read_reg(struct adiv5_dap *dap, uint8_t cmd, uint32_t *value)
1067 {
1068         assert(cmd & SWD_CMD_RnW);
1069         ftdi_swd_queue_cmd(dap, cmd, value, 0);
1070 }
1071
1072 static void ftdi_swd_write_reg(struct adiv5_dap *dap, uint8_t cmd, uint32_t value)
1073 {
1074         assert(!(cmd & SWD_CMD_RnW));
1075         ftdi_swd_queue_cmd(dap, cmd, NULL, value);
1076 }
1077
1078 static int_least32_t ftdi_swd_frequency(struct adiv5_dap *dap, int_least32_t hz)
1079 {
1080         if (hz > 0)
1081                 freq = mpsse_set_frequency(mpsse_ctx, hz);
1082
1083         return freq;
1084 }
1085
1086 static int ftdi_swd_switch_seq(struct adiv5_dap *dap, enum swd_special_seq seq)
1087 {
1088         switch (seq) {
1089         case LINE_RESET:
1090                 LOG_DEBUG("SWD line reset");
1091                 mpsse_clock_data_out(mpsse_ctx, swd_seq_line_reset, 0, swd_seq_line_reset_len, SWD_MODE);
1092                 break;
1093         case JTAG_TO_SWD:
1094                 LOG_DEBUG("JTAG-to-SWD");
1095                 mpsse_clock_data_out(mpsse_ctx, swd_seq_jtag_to_swd, 0, swd_seq_jtag_to_swd_len, SWD_MODE);
1096                 break;
1097         case SWD_TO_JTAG:
1098                 LOG_DEBUG("SWD-to-JTAG");
1099                 mpsse_clock_data_out(mpsse_ctx, swd_seq_swd_to_jtag, 0, swd_seq_swd_to_jtag_len, SWD_MODE);
1100                 break;
1101         default:
1102                 LOG_ERROR("Sequence %d not supported", seq);
1103                 return ERROR_FAIL;
1104         }
1105
1106         return ERROR_OK;
1107 }
1108
1109 static const struct swd_driver ftdi_swd = {
1110         .init = ftdi_swd_init,
1111         .frequency = ftdi_swd_frequency,
1112         .switch_seq = ftdi_swd_switch_seq,
1113         .read_reg = ftdi_swd_read_reg,
1114         .write_reg = ftdi_swd_write_reg,
1115         .run = ftdi_swd_run_queue,
1116 };
1117
1118 static const char * const ftdi_transports[] = { "jtag", "swd", NULL };
1119
1120 struct jtag_interface ftdi_interface = {
1121         .name = "ftdi",
1122         .supported = DEBUG_CAP_TMS_SEQ,
1123         .commands = ftdi_command_handlers,
1124         .transports = ftdi_transports,
1125         .swd = &ftdi_swd,
1126
1127         .init = ftdi_initialize,
1128         .quit = ftdi_quit,
1129         .speed = ftdi_speed,
1130         .speed_div = ftdi_speed_div,
1131         .khz = ftdi_khz,
1132         .execute_queue = ftdi_execute_queue,
1133 };