openocd: fix SPDX tag format for files .c
[fw/openocd] / src / jtag / drivers / usb_blaster / usb_blaster.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 /*
4  *   Driver for USB-JTAG, Altera USB-Blaster and compatibles
5  *
6  *   Inspired from original code from Kolja Waschk's USB-JTAG project
7  *   (http://www.ixo.de/info/usb_jtag/), and from openocd project.
8  *
9  *   Copyright (C) 2013 Franck Jullien franck.jullien@gmail.com
10  *   Copyright (C) 2012 Robert Jarzmik robert.jarzmik@free.fr
11  *   Copyright (C) 2011 Ali Lown ali@lown.me.uk
12  *   Copyright (C) 2009 Catalin Patulea cat@vv.carleton.ca
13  *   Copyright (C) 2006 Kolja Waschk usbjtag@ixo.de
14  *
15  */
16
17 /*
18  * The following information is originally from Kolja Waschk's USB-JTAG,
19  * where it was obtained by reverse engineering an Altera USB-Blaster.
20  * See http://www.ixo.de/info/usb_jtag/ for USB-Blaster block diagram and
21  * usb_jtag-20080705-1200.zip#usb_jtag/host/openocd for protocol.
22  *
23  * The same information is also on the UrJTAG mediawiki, with some additional
24  * notes on bits marked as "unknown" by usb_jtag.
25  * (http://sourceforge.net/apps/mediawiki/urjtag/index.php?
26  *    title=Cable_Altera_USB-Blaster)
27  *
28  * USB-JTAG, Altera USB-Blaster and compatibles are typically implemented as
29  * an FTDIChip FT245 followed by a CPLD which handles a two-mode protocol:
30  *
31  *            _________
32  *           |         |
33  *           | AT93C46 |
34  *           |_________|
35  *            __|__________    _________
36  *           |             |  |         |
37  *      USB__| FTDI 245BM  |__| EPM7064 |__JTAG (B_TDO,B_TDI,B_TMS,B_TCK)
38  *           |_____________|  |_________|
39  *            __|__________    _|___________
40  *           |             |  |             |
41  *           | 6 MHz XTAL  |  | 24 MHz Osc. |
42  *           |_____________|  |_____________|
43  *
44  * USB-JTAG, Altera USB-Blaster II are typically implemented as a Cypress
45  * EZ-USB FX2LP followed by a CPLD.
46  *            _____________    _________
47  *           |             |  |         |
48  *      USB__| EZ-USB FX2  |__| EPM570  |__JTAG (B_TDO,B_TDI,B_TMS,B_TCK)
49  *           |_____________|  |_________|
50  *            __|__________
51  *           |             |
52  *           | 24 MHz XTAL |
53  *           |_____________|
54  */
55
56 #ifdef HAVE_CONFIG_H
57 #include "config.h"
58 #endif
59
60 #if IS_CYGWIN == 1
61 #include "windows.h"
62 #undef LOG_ERROR
63 #endif
64
65 /* project specific includes */
66 #include <jtag/interface.h>
67 #include <jtag/commands.h>
68 #include <helper/time_support.h>
69 #include <helper/replacements.h>
70 #include "ublast_access.h"
71
72 /* system includes */
73 #include <string.h>
74 #include <stdlib.h>
75 #include <unistd.h>
76 #include <sys/time.h>
77 #include <time.h>
78
79 /* Size of USB endpoint max packet size, ie. 64 bytes */
80 #define MAX_PACKET_SIZE 64
81 /*
82  * Size of data buffer that holds bytes in byte-shift mode.
83  * This buffer can hold multiple USB packets aligned to
84  * MAX_PACKET_SIZE bytes boundaries.
85  * BUF_LEN must be grater than or equal MAX_PACKET_SIZE.
86  */
87 #define BUF_LEN 4096
88
89 /* USB-Blaster II specific command */
90 #define CMD_COPY_TDO_BUFFER     0x5F
91
92 enum gpio_steer {
93         FIXED_0 = 0,
94         FIXED_1,
95         SRST,
96         TRST,
97 };
98
99 struct ublast_info {
100         enum gpio_steer pin6;
101         enum gpio_steer pin8;
102         int tms;
103         int tdi;
104         bool trst_asserted;
105         bool srst_asserted;
106         uint8_t buf[BUF_LEN];
107         int bufidx;
108
109         char *lowlevel_name;
110         struct ublast_lowlevel *drv;
111         uint16_t ublast_vid, ublast_pid;
112         uint16_t ublast_vid_uninit, ublast_pid_uninit;
113         int flags;
114         char *firmware_path;
115 };
116
117 /*
118  * Global device control
119  */
120 static struct ublast_info info = {
121         .ublast_vid = 0x09fb, /* Altera */
122         .ublast_pid = 0x6001, /* USB-Blaster */
123         .lowlevel_name = NULL,
124         .srst_asserted = false,
125         .trst_asserted = false,
126         .pin6 = FIXED_1,
127         .pin8 = FIXED_1,
128 };
129
130 /*
131  * Available lowlevel drivers (FTDI, libusb, ...)
132  */
133 struct drvs_map {
134         char *name;
135         struct ublast_lowlevel *(*drv_register)(void);
136 };
137
138 static struct drvs_map lowlevel_drivers_map[] = {
139 #if BUILD_USB_BLASTER
140         { .name = "ftdi", .drv_register = ublast_register_ftdi },
141 #endif
142 #if BUILD_USB_BLASTER_2
143         { .name = "ublast2", .drv_register = ublast2_register_libusb },
144 #endif
145         { NULL, NULL },
146 };
147
148 /*
149  * Access functions to lowlevel driver, agnostic of libftdi/libftdxx
150  */
151 static char *hexdump(uint8_t *buf, unsigned int size)
152 {
153         unsigned int i;
154         char *str = calloc(size * 2 + 1, 1);
155
156         for (i = 0; i < size; i++)
157                 sprintf(str + 2*i, "%02x", buf[i]);
158         return str;
159 }
160
161 static int ublast_buf_read(uint8_t *buf, unsigned size, uint32_t *bytes_read)
162 {
163         int ret = info.drv->read(info.drv, buf, size, bytes_read);
164         char *str = hexdump(buf, *bytes_read);
165
166         LOG_DEBUG_IO("(size=%d, buf=[%s]) -> %" PRIu32, size, str,
167                       *bytes_read);
168         free(str);
169         return ret;
170 }
171
172 static int ublast_buf_write(uint8_t *buf, int size, uint32_t *bytes_written)
173 {
174         int ret = info.drv->write(info.drv, buf, size, bytes_written);
175         char *str = hexdump(buf, *bytes_written);
176
177         LOG_DEBUG_IO("(size=%d, buf=[%s]) -> %" PRIu32, size, str,
178                       *bytes_written);
179         free(str);
180         return ret;
181 }
182
183 static int nb_buf_remaining(void)
184 {
185         return BUF_LEN - info.bufidx;
186 }
187
188 static void ublast_flush_buffer(void)
189 {
190         uint32_t retlen;
191         int nb = info.bufidx, ret = ERROR_OK;
192
193         while (ret == ERROR_OK && nb > 0) {
194                 ret = ublast_buf_write(info.buf, nb, &retlen);
195                 nb -= retlen;
196         }
197         info.bufidx = 0;
198 }
199
200 /*
201  * Actually, the USB-Blaster offers a byte-shift mode to transmit up to 504 data
202  * bits (bidirectional) in a single USB packet. A header byte has to be sent as
203  * the first byte in a packet with the following meaning:
204  *
205  *   Bit 7 (0x80): Must be set to indicate byte-shift mode.
206  *   Bit 6 (0x40): If set, the USB-Blaster will also read data, not just write.
207  *   Bit 5..0:     Define the number N of following bytes
208  *
209  * All N following bytes will then be clocked out serially on TDI. If Bit 6 was
210  * set, it will afterwards return N bytes with TDO data read while clocking out
211  * the TDI data. LSB of the first byte after the header byte will appear first
212  * on TDI.
213  */
214
215 /* Simple bit banging mode:
216  *
217  *   Bit 7 (0x80): Must be zero (see byte-shift mode above)
218  *   Bit 6 (0x40): If set, you will receive a byte indicating the state of TDO
219  *                 in return.
220  *   Bit 5 (0x20): Output Enable/LED.
221  *   Bit 4 (0x10): TDI Output.
222  *   Bit 3 (0x08): nCS Output (not used in JTAG mode).
223  *   Bit 2 (0x04): nCE Output (not used in JTAG mode).
224  *   Bit 1 (0x02): TMS Output.
225  *   Bit 0 (0x01): TCK Output.
226  *
227  * For transmitting a single data bit, you need to write two bytes (one for
228  * setting up TDI/TMS/TCK=0, and one to trigger TCK high with same TDI/TMS
229  * held). Up to 64 bytes can be combined in a single USB packet.
230  * It isn't possible to read a data without transmitting data.
231  */
232
233 #define TCK             (1 << 0)
234 #define TMS             (1 << 1)
235 #define NCE             (1 << 2)
236 #define NCS             (1 << 3)
237 #define TDI             (1 << 4)
238 #define LED             (1 << 5)
239 #define READ            (1 << 6)
240 #define SHMODE          (1 << 7)
241 #define READ_TDO        (1 << 0)
242
243 /**
244  * ublast_queue_byte - queue one 'bitbang mode' byte for USB Blaster
245  * @param abyte the byte to queue
246  *
247  * Queues one byte in 'bitbang mode' to the USB Blaster. The byte is not
248  * actually sent, but stored in a buffer. The write is performed once
249  * the buffer is filled, or if an explicit ublast_flush_buffer() is called.
250  */
251 static void ublast_queue_byte(uint8_t abyte)
252 {
253         if (nb_buf_remaining() < 1)
254                 ublast_flush_buffer();
255         info.buf[info.bufidx++] = abyte;
256         if (nb_buf_remaining() == 0)
257                 ublast_flush_buffer();
258         LOG_DEBUG_IO("(byte=0x%02x)", abyte);
259 }
260
261 /**
262  * ublast_compute_pin - compute if gpio should be asserted
263  * @param steer control (ie. TRST driven, SRST driven, of fixed)
264  *
265  * Returns pin value (1 means driven high, 0 mean driven low)
266  */
267 static bool ublast_compute_pin(enum gpio_steer steer)
268 {
269         switch (steer) {
270         case FIXED_0:
271                 return 0;
272         case FIXED_1:
273                 return 1;
274         case SRST:
275                 return !info.srst_asserted;
276         case TRST:
277                 return !info.trst_asserted;
278         default:
279                 return 1;
280         }
281 }
282
283 /**
284  * ublast_build_out - build bitbang mode output byte
285  * @param type says if reading back TDO is required
286  *
287  * Returns the compute bitbang mode byte
288  */
289 static uint8_t ublast_build_out(enum scan_type type)
290 {
291         uint8_t abyte = 0;
292
293         abyte |= info.tms ? TMS : 0;
294         abyte |= ublast_compute_pin(info.pin6) ? NCE : 0;
295         abyte |= ublast_compute_pin(info.pin8) ? NCS : 0;
296         abyte |= info.tdi ? TDI : 0;
297         abyte |= LED;
298         if (type == SCAN_IN || type == SCAN_IO)
299                 abyte |= READ;
300         return abyte;
301 }
302
303 /**
304  * ublast_reset - reset the JTAG device is possible
305  * @param trst 1 if TRST is to be asserted
306  * @param srst 1 if SRST is to be asserted
307  */
308 static void ublast_reset(int trst, int srst)
309 {
310         uint8_t out_value;
311
312         info.trst_asserted = trst;
313         info.srst_asserted = srst;
314         out_value = ublast_build_out(SCAN_OUT);
315         ublast_queue_byte(out_value);
316         ublast_flush_buffer();
317 }
318
319 /**
320  * ublast_clock_tms - clock a TMS transition
321  * @param tms the TMS to be sent
322  *
323  * Triggers a TMS transition (ie. one JTAG TAP state move).
324  */
325 static void ublast_clock_tms(int tms)
326 {
327         uint8_t out;
328
329         LOG_DEBUG_IO("(tms=%d)", !!tms);
330         info.tms = !!tms;
331         info.tdi = 0;
332         out = ublast_build_out(SCAN_OUT);
333         ublast_queue_byte(out);
334         ublast_queue_byte(out | TCK);
335 }
336
337 /**
338  * ublast_idle_clock - put back TCK to low level
339  *
340  * See ublast_queue_tdi() comment for the usage of this function.
341  */
342 static void ublast_idle_clock(void)
343 {
344         uint8_t out = ublast_build_out(SCAN_OUT);
345
346         LOG_DEBUG_IO(".");
347         ublast_queue_byte(out);
348 }
349
350 /**
351  * ublast_clock_tdi - Output a TDI with bitbang mode
352  * @param tdi the TDI bit to be shifted out
353  * @param type scan type (ie. does a readback of TDO is required)
354  *
355  * Output a TDI bit and assert clock to push it into the JTAG device :
356  *  - writing out TCK=0, TMS=\<old_state>=0, TDI=\<tdi>
357  *  - writing out TCK=1, TMS=\<new_state>, TDI=\<tdi> which triggers the JTAG
358  *    device acquiring the data.
359  *
360  * If a TDO is to be read back, the required read is requested (bitbang mode),
361  * and the USB Blaster will send back a byte with bit0 representing the TDO.
362  */
363 static void ublast_clock_tdi(int tdi, enum scan_type type)
364 {
365         uint8_t out;
366
367         LOG_DEBUG_IO("(tdi=%d)",  !!tdi);
368         info.tdi = !!tdi;
369
370         out = ublast_build_out(SCAN_OUT);
371         ublast_queue_byte(out);
372
373         out = ublast_build_out(type);
374         ublast_queue_byte(out | TCK);
375 }
376
377 /**
378  * ublast_clock_tdi_flip_tms - Output a TDI with bitbang mode, change JTAG state
379  * @param tdi the TDI bit to be shifted out
380  * @param type scan type (ie. does a readback of TDO is required)
381  *
382  * This function is the same as ublast_clock_tdi(), but it changes also the TMS
383  * while output the TDI. This should be the last TDI output of a TDI
384  * sequence, which will change state from :
385  *   - IRSHIFT -> IREXIT1
386  *   - or DRSHIFT -> DREXIT1
387  */
388 static void ublast_clock_tdi_flip_tms(int tdi, enum scan_type type)
389 {
390         uint8_t out;
391
392         LOG_DEBUG_IO("(tdi=%d)", !!tdi);
393         info.tdi = !!tdi;
394         info.tms = !info.tms;
395
396         out = ublast_build_out(SCAN_OUT);
397         ublast_queue_byte(out);
398
399         out = ublast_build_out(type);
400         ublast_queue_byte(out | TCK);
401
402         out = ublast_build_out(SCAN_OUT);
403         ublast_queue_byte(out);
404 }
405
406 /**
407  * ublast_queue_bytes - queue bytes for the USB Blaster
408  * @param bytes byte array
409  * @param nb_bytes number of bytes
410  *
411  * Queues bytes to be sent to the USB Blaster. The bytes are not
412  * actually sent, but stored in a buffer. The write is performed once
413  * the buffer is filled, or if an explicit ublast_flush_buffer() is called.
414  */
415 static void ublast_queue_bytes(uint8_t *bytes, int nb_bytes)
416 {
417         if (info.bufidx + nb_bytes > BUF_LEN) {
418                 LOG_ERROR("buggy code, should never queue more that %d bytes",
419                           info.bufidx + nb_bytes);
420                 exit(-1);
421         }
422         LOG_DEBUG_IO("(nb_bytes=%d, bytes=[0x%02x, ...])", nb_bytes,
423                       bytes ? bytes[0] : 0);
424         if (bytes)
425                 memcpy(&info.buf[info.bufidx], bytes, nb_bytes);
426         else
427                 memset(&info.buf[info.bufidx], 0, nb_bytes);
428         info.bufidx += nb_bytes;
429         if (nb_buf_remaining() == 0)
430                 ublast_flush_buffer();
431 }
432
433 /**
434  * ublast_tms_seq - write a TMS sequence transition to JTAG
435  * @param bits TMS bits to be written (bit0, bit1 .. bitN)
436  * @param nb_bits number of TMS bits (between 1 and 8)
437  * @param skip number of TMS bits to skip at the beginning of the series
438  *
439  * Write a series of TMS transitions, where each transition consists in :
440  *  - writing out TCK=0, TMS=\<new_state>, TDI=\<???>
441  *  - writing out TCK=1, TMS=\<new_state>, TDI=\<???> which triggers the transition
442  * The function ensures that at the end of the sequence, the clock (TCK) is put
443  * low.
444  */
445 static void ublast_tms_seq(const uint8_t *bits, int nb_bits, int skip)
446 {
447         int i;
448
449         LOG_DEBUG_IO("(bits=%02x..., nb_bits=%d)", bits[0], nb_bits);
450         for (i = skip; i < nb_bits; i++)
451                 ublast_clock_tms((bits[i / 8] >> (i % 8)) & 0x01);
452         ublast_idle_clock();
453 }
454
455 /**
456  * ublast_tms - write a tms command
457  * @param cmd tms command
458  */
459 static void ublast_tms(struct tms_command *cmd)
460 {
461         LOG_DEBUG_IO("(num_bits=%d)", cmd->num_bits);
462         ublast_tms_seq(cmd->bits, cmd->num_bits, 0);
463 }
464
465 /**
466  * ublast_path_move - write a TMS sequence transition to JTAG
467  * @param cmd path transition
468  *
469  * Write a series of TMS transitions, where each transition consists in :
470  *  - writing out TCK=0, TMS=\<new_state>, TDI=\<???>
471  *  - writing out TCK=1, TMS=\<new_state>, TDI=\<???> which triggers the transition
472  * The function ensures that at the end of the sequence, the clock (TCK) is put
473  * low.
474  */
475 static void ublast_path_move(struct pathmove_command *cmd)
476 {
477         int i;
478
479         LOG_DEBUG_IO("(num_states=%d, last_state=%d)",
480                   cmd->num_states, cmd->path[cmd->num_states - 1]);
481         for (i = 0; i < cmd->num_states; i++) {
482                 if (tap_state_transition(tap_get_state(), false) == cmd->path[i])
483                         ublast_clock_tms(0);
484                 if (tap_state_transition(tap_get_state(), true) == cmd->path[i])
485                         ublast_clock_tms(1);
486                 tap_set_state(cmd->path[i]);
487         }
488         ublast_idle_clock();
489 }
490
491 /**
492  * ublast_state_move - move JTAG state to the target state
493  * @param state the target state
494  * @param skip number of bits to skip at the beginning of the path
495  *
496  * Input the correct TMS sequence to the JTAG TAP so that we end up in the
497  * target state. This assumes the current state (tap_get_state()) is correct.
498  */
499 static void ublast_state_move(tap_state_t state, int skip)
500 {
501         uint8_t tms_scan;
502         int tms_len;
503
504         LOG_DEBUG_IO("(from %s to %s)", tap_state_name(tap_get_state()),
505                   tap_state_name(state));
506         if (tap_get_state() == state)
507                 return;
508         tms_scan = tap_get_tms_path(tap_get_state(), state);
509         tms_len = tap_get_tms_path_len(tap_get_state(), state);
510         ublast_tms_seq(&tms_scan, tms_len, skip);
511         tap_set_state(state);
512 }
513
514 /**
515  * ublast_read_byteshifted_tdos - read TDO of byteshift writes
516  * @param buf the buffer to store the bits
517  * @param nb_bytes the number of bytes
518  *
519  * Reads back from USB Blaster TDO bits, triggered by a 'byteshift write', ie. eight
520  * bits per received byte from USB interface, and store them in buffer.
521  *
522  * As the USB blaster stores the TDO bits in LSB (ie. first bit in (byte0,
523  * bit0), second bit in (byte0, bit1), ...), which is what we want to return,
524  * simply read bytes from USB interface and store them.
525  *
526  * Returns ERROR_OK if OK, ERROR_xxx if a read error occurred
527  */
528 static int ublast_read_byteshifted_tdos(uint8_t *buf, int nb_bytes)
529 {
530         uint32_t retlen;
531         int ret = ERROR_OK;
532
533         LOG_DEBUG_IO("%s(buf=%p, num_bits=%d)", __func__, buf, nb_bytes * 8);
534         ublast_flush_buffer();
535         while (ret == ERROR_OK && nb_bytes > 0) {
536                 ret = ublast_buf_read(buf, nb_bytes, &retlen);
537                 nb_bytes -= retlen;
538         }
539         return ret;
540 }
541
542 /**
543  * ublast_read_bitbang_tdos - read TDO of bitbang writes
544  * @param buf the buffer to store the bits
545  * @param nb_bits the number of bits
546  *
547  * Reads back from USB Blaster TDO bits, triggered by a 'bitbang write', ie. one
548  * bit per received byte from USB interface, and store them in buffer, where :
549  *  - first bit is stored in byte0, bit0 (LSB)
550  *  - second bit is stored in byte0, bit 1
551  *  ...
552  *  - eight bit is stored in byte0, bit 7
553  *  - ninth bit is stored in byte1, bit 0
554  *  - etc ...
555  *
556  * Returns ERROR_OK if OK, ERROR_xxx if a read error occurred
557  */
558 static int ublast_read_bitbang_tdos(uint8_t *buf, int nb_bits)
559 {
560         int nb1 = nb_bits;
561         int i, ret = ERROR_OK;
562         uint32_t retlen;
563         uint8_t tmp[8];
564
565         LOG_DEBUG_IO("%s(buf=%p, num_bits=%d)", __func__, buf, nb_bits);
566
567         /*
568          * Ensure all previous bitbang writes were issued to the dongle, so that
569          * it returns back the read values.
570          */
571         ublast_flush_buffer();
572
573         ret = ublast_buf_read(tmp, nb1, &retlen);
574         for (i = 0; ret == ERROR_OK && i < nb1; i++)
575                 if (tmp[i] & READ_TDO)
576                         *buf |= (1 << i);
577                 else
578                         *buf &= ~(1 << i);
579         return ret;
580 }
581
582 /**
583  * ublast_queue_tdi - short description
584  * @param bits bits to be queued on TDI (or NULL if 0 are to be queued)
585  * @param nb_bits number of bits
586  * @param scan scan type (ie. if TDO read back is required or not)
587  *
588  * Outputs a series of TDI bits on TDI.
589  * As a side effect, the last TDI bit is sent along a TMS=1, and triggers a JTAG
590  * TAP state shift if input bits were non NULL.
591  *
592  * In order to not saturate the USB Blaster queues, this method reads back TDO
593  * if the scan type requests it, and stores them back in bits.
594  *
595  * As a side note, the state of TCK when entering this function *must* be
596  * low. This is because byteshift mode outputs TDI on rising TCK and reads TDO
597  * on falling TCK if and only if TCK is low before queuing byteshift mode bytes.
598  * If TCK was high, the USB blaster will queue TDI on falling edge, and read TDO
599  * on rising edge !!!
600  */
601 static void ublast_queue_tdi(uint8_t *bits, int nb_bits, enum scan_type scan)
602 {
603         int nb8 = nb_bits / 8;
604         int nb1 = nb_bits % 8;
605         int nbfree_in_packet, i, trans = 0, read_tdos;
606         uint8_t *tdos = calloc(1, nb_bits / 8 + 1);
607         static uint8_t byte0[BUF_LEN];
608
609         /*
610          * As the last TDI bit should always be output in bitbang mode in order
611          * to activate the TMS=1 transition to EXIT_?R state. Therefore a
612          * situation where nb_bits is a multiple of 8 is handled as follows:
613          * - the number of TDI shifted out in "byteshift mode" is 8 less than
614          *   nb_bits
615          * - nb1 = 8
616          * This ensures that nb1 is never 0, and allows the TMS transition.
617          */
618         if (nb8 > 0 && nb1 == 0) {
619                 nb8--;
620                 nb1 = 8;
621         }
622
623         read_tdos = (scan == SCAN_IN || scan == SCAN_IO);
624         for (i = 0; i < nb8; i += trans) {
625                 /*
626                  * Calculate number of bytes to fill USB packet of size MAX_PACKET_SIZE
627                  */
628                 nbfree_in_packet = (MAX_PACKET_SIZE - (info.bufidx%MAX_PACKET_SIZE));
629                 trans = MIN(nbfree_in_packet - 1, nb8 - i);
630
631                 /*
632                  * Queue a byte-shift mode transmission, with as many bytes as
633                  * is possible with regard to :
634                  *  - current filling level of write buffer
635                  *  - remaining bytes to write in byte-shift mode
636                  */
637                 if (read_tdos)
638                         ublast_queue_byte(SHMODE | READ | trans);
639                 else
640                         ublast_queue_byte(SHMODE | trans);
641                 if (bits)
642                         ublast_queue_bytes(&bits[i], trans);
643                 else
644                         ublast_queue_bytes(byte0, trans);
645                 if (read_tdos) {
646                         if (info.flags & COPY_TDO_BUFFER)
647                                 ublast_queue_byte(CMD_COPY_TDO_BUFFER);
648                         ublast_read_byteshifted_tdos(&tdos[i], trans);
649                 }
650         }
651
652         /*
653          * Queue the remaining TDI bits in bitbang mode.
654          */
655         for (i = 0; i < nb1; i++) {
656                 int tdi = bits ? bits[nb8 + i / 8] & (1 << i) : 0;
657                 if (bits && i == nb1 - 1)
658                         ublast_clock_tdi_flip_tms(tdi, scan);
659                 else
660                         ublast_clock_tdi(tdi, scan);
661         }
662         if (nb1 && read_tdos) {
663                 if (info.flags & COPY_TDO_BUFFER)
664                         ublast_queue_byte(CMD_COPY_TDO_BUFFER);
665                 ublast_read_bitbang_tdos(&tdos[nb8], nb1);
666         }
667
668         if (bits)
669                 memcpy(bits, tdos, DIV_ROUND_UP(nb_bits, 8));
670         free(tdos);
671
672         /*
673          * Ensure clock is in lower state
674          */
675         ublast_idle_clock();
676 }
677
678 static void ublast_runtest(int cycles, tap_state_t state)
679 {
680         LOG_DEBUG_IO("%s(cycles=%i, end_state=%d)", __func__, cycles, state);
681
682         ublast_state_move(TAP_IDLE, 0);
683         ublast_queue_tdi(NULL, cycles, SCAN_OUT);
684         ublast_state_move(state, 0);
685 }
686
687 static void ublast_stableclocks(int cycles)
688 {
689         LOG_DEBUG_IO("%s(cycles=%i)", __func__, cycles);
690         ublast_queue_tdi(NULL, cycles, SCAN_OUT);
691 }
692
693 /**
694  * ublast_scan - launches a DR-scan or IR-scan
695  * @param cmd the command to launch
696  *
697  * Launch a JTAG IR-scan or DR-scan
698  *
699  * Returns ERROR_OK if OK, ERROR_xxx if a read/write error occurred.
700  */
701 static int ublast_scan(struct scan_command *cmd)
702 {
703         int scan_bits;
704         uint8_t *buf = NULL;
705         enum scan_type type;
706         int ret = ERROR_OK;
707         static const char * const type2str[] = { "", "SCAN_IN", "SCAN_OUT", "SCAN_IO" };
708         char *log_buf = NULL;
709
710         type = jtag_scan_type(cmd);
711         scan_bits = jtag_build_buffer(cmd, &buf);
712
713         if (cmd->ir_scan)
714                 ublast_state_move(TAP_IRSHIFT, 0);
715         else
716                 ublast_state_move(TAP_DRSHIFT, 0);
717
718         log_buf = hexdump(buf, DIV_ROUND_UP(scan_bits, 8));
719         LOG_DEBUG_IO("%s(scan=%s, type=%s, bits=%d, buf=[%s], end_state=%d)", __func__,
720                   cmd->ir_scan ? "IRSCAN" : "DRSCAN",
721                   type2str[type],
722                   scan_bits, log_buf, cmd->end_state);
723         free(log_buf);
724
725         ublast_queue_tdi(buf, scan_bits, type);
726
727         ret = jtag_read_buffer(buf, cmd);
728         free(buf);
729         /*
730          * ublast_queue_tdi sends the last bit with TMS=1. We are therefore
731          * already in Exit1-DR/IR and have to skip the first step on our way
732          * to end_state.
733          */
734         ublast_state_move(cmd->end_state, 1);
735         return ret;
736 }
737
738 static void ublast_usleep(int us)
739 {
740         LOG_DEBUG_IO("%s(us=%d)",  __func__, us);
741         jtag_sleep(us);
742 }
743
744 static void ublast_initial_wipeout(void)
745 {
746         static uint8_t tms_reset = 0xff;
747         uint8_t out_value;
748         uint32_t retlen;
749         int i;
750
751         out_value = ublast_build_out(SCAN_OUT);
752         for (i = 0; i < BUF_LEN; i++)
753                 info.buf[i] = out_value | ((i % 2) ? TCK : 0);
754
755         /*
756          * Flush USB-Blaster queue fifos
757          *  - empty the write FIFO (128 bytes)
758          *  - empty the read FIFO (384 bytes)
759          */
760         ublast_buf_write(info.buf, BUF_LEN, &retlen);
761         /*
762          * Put JTAG in RESET state (five 1 on TMS)
763          */
764         ublast_tms_seq(&tms_reset, 5, 0);
765         tap_set_state(TAP_RESET);
766 }
767
768 static int ublast_execute_queue(void)
769 {
770         struct jtag_command *cmd;
771         static int first_call = 1;
772         int ret = ERROR_OK;
773
774         if (first_call) {
775                 first_call--;
776                 ublast_initial_wipeout();
777         }
778
779         for (cmd = jtag_command_queue; ret == ERROR_OK && cmd;
780              cmd = cmd->next) {
781                 switch (cmd->type) {
782                 case JTAG_RESET:
783                         ublast_reset(cmd->cmd.reset->trst, cmd->cmd.reset->srst);
784                         break;
785                 case JTAG_RUNTEST:
786                         ublast_runtest(cmd->cmd.runtest->num_cycles,
787                                        cmd->cmd.runtest->end_state);
788                         break;
789                 case JTAG_STABLECLOCKS:
790                         ublast_stableclocks(cmd->cmd.stableclocks->num_cycles);
791                         break;
792                 case JTAG_TLR_RESET:
793                         ublast_state_move(cmd->cmd.statemove->end_state, 0);
794                         break;
795                 case JTAG_PATHMOVE:
796                         ublast_path_move(cmd->cmd.pathmove);
797                         break;
798                 case JTAG_TMS:
799                         ublast_tms(cmd->cmd.tms);
800                         break;
801                 case JTAG_SLEEP:
802                         ublast_usleep(cmd->cmd.sleep->us);
803                         break;
804                 case JTAG_SCAN:
805                         ret = ublast_scan(cmd->cmd.scan);
806                         break;
807                 default:
808                         LOG_ERROR("BUG: unknown JTAG command type 0x%X",
809                                   cmd->type);
810                         ret = ERROR_FAIL;
811                         break;
812                 }
813         }
814
815         ublast_flush_buffer();
816         return ret;
817 }
818
819 /**
820  * ublast_init - Initialize the Altera device
821  *
822  * Initialize the device :
823  *  - open the USB device
824  *  - pretend it's initialized while actual init is delayed until first jtag command
825  *
826  * Returns ERROR_OK if USB device found, error if not.
827  */
828 static int ublast_init(void)
829 {
830         int ret, i;
831
832         for (i = 0; lowlevel_drivers_map[i].name; i++) {
833                 if (info.lowlevel_name) {
834                         if (!strcmp(lowlevel_drivers_map[i].name, info.lowlevel_name)) {
835                                 info.drv = lowlevel_drivers_map[i].drv_register();
836                                 if (!info.drv) {
837                                         LOG_ERROR("Error registering lowlevel driver \"%s\"",
838                                                   info.lowlevel_name);
839                                         return ERROR_JTAG_DEVICE_ERROR;
840                                 }
841                                 break;
842                         }
843                 } else {
844                         info.drv = lowlevel_drivers_map[i].drv_register();
845                         if (info.drv) {
846                                 info.lowlevel_name = strdup(lowlevel_drivers_map[i].name);
847                                 LOG_INFO("No lowlevel driver configured, using %s", info.lowlevel_name);
848                                 break;
849                         }
850                 }
851         }
852
853         if (!info.drv) {
854                 LOG_ERROR("No lowlevel driver available");
855                 return ERROR_JTAG_DEVICE_ERROR;
856         }
857
858         /*
859          * Register the lowlevel driver
860          */
861         info.drv->ublast_vid = info.ublast_vid;
862         info.drv->ublast_pid = info.ublast_pid;
863         info.drv->ublast_vid_uninit = info.ublast_vid_uninit;
864         info.drv->ublast_pid_uninit = info.ublast_pid_uninit;
865         info.drv->firmware_path = info.firmware_path;
866
867         info.flags |= info.drv->flags;
868
869         ret = info.drv->open(info.drv);
870
871         /*
872          * Let lie here : the TAP is in an unknown state, but the first
873          * execute_queue() will trigger a ublast_initial_wipeout(), which will
874          * put the TAP in RESET.
875          */
876         tap_set_state(TAP_RESET);
877         return ret;
878 }
879
880 /**
881  * ublast_quit - Release the Altera device
882  *
883  * Releases the device :
884  *   - put the device pins in 'high impedance' mode
885  *   - close the USB device
886  *
887  * Returns always ERROR_OK
888  */
889 static int ublast_quit(void)
890 {
891         uint8_t byte0 = 0;
892         uint32_t retlen;
893
894         ublast_buf_write(&byte0, 1, &retlen);
895         return info.drv->close(info.drv);
896 }
897
898 COMMAND_HANDLER(ublast_handle_vid_pid_command)
899 {
900         if (CMD_ARGC > 4) {
901                 LOG_WARNING("ignoring extra IDs in ublast_vid_pid "
902                                         "(maximum is 2 pairs)");
903                 CMD_ARGC = 4;
904         }
905
906         if (CMD_ARGC >= 2) {
907                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[0], info.ublast_vid);
908                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[1], info.ublast_pid);
909         } else {
910                 LOG_WARNING("incomplete ublast_vid_pid configuration");
911         }
912
913         if (CMD_ARGC == 4) {
914                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[2], info.ublast_vid_uninit);
915                 COMMAND_PARSE_NUMBER(u16, CMD_ARGV[3], info.ublast_pid_uninit);
916         } else {
917                 LOG_WARNING("incomplete ublast_vid_pid configuration");
918         }
919
920         return ERROR_OK;
921 }
922
923 COMMAND_HANDLER(ublast_handle_pin_command)
924 {
925         uint8_t out_value;
926         const char * const pin_name = CMD_ARGV[0];
927         enum gpio_steer *steer = NULL;
928         static const char * const pin_val_str[] = {
929                 [FIXED_0] = "0",
930                 [FIXED_1] = "1",
931                 [SRST] = "SRST driven",
932                 [TRST] = "TRST driven",
933         };
934
935         if (CMD_ARGC > 2) {
936                 LOG_ERROR("%s takes exactly one or two arguments", CMD_NAME);
937                 return ERROR_COMMAND_SYNTAX_ERROR;
938         }
939
940         if (!strcmp(pin_name, "pin6"))
941                 steer = &info.pin6;
942         if (!strcmp(pin_name, "pin8"))
943                 steer = &info.pin8;
944         if (!steer) {
945                 LOG_ERROR("%s: pin name must be \"pin6\" or \"pin8\"",
946                           CMD_NAME);
947                 return ERROR_COMMAND_SYNTAX_ERROR;
948         }
949
950         if (CMD_ARGC == 1) {
951                 LOG_INFO("%s: %s is set as %s\n", CMD_NAME, pin_name,
952                          pin_val_str[*steer]);
953         }
954
955         if (CMD_ARGC == 2) {
956                 const char * const pin_value = CMD_ARGV[1];
957                 char val = pin_value[0];
958
959                 if (strlen(pin_value) > 1)
960                         val = '?';
961                 switch (tolower((unsigned char)val)) {
962                 case '0':
963                         *steer = FIXED_0;
964                         break;
965                 case '1':
966                         *steer = FIXED_1;
967                         break;
968                 case 't':
969                         *steer = TRST;
970                         break;
971                 case 's':
972                         *steer = SRST;
973                         break;
974                 default:
975                         LOG_ERROR("%s: pin value must be 0, 1, s (SRST) or t (TRST)",
976                                 pin_value);
977                         return ERROR_COMMAND_SYNTAX_ERROR;
978                 }
979
980                 if (info.drv) {
981                         out_value = ublast_build_out(SCAN_OUT);
982                         ublast_queue_byte(out_value);
983                         ublast_flush_buffer();
984                 }
985         }
986         return ERROR_OK;
987 }
988
989 COMMAND_HANDLER(ublast_handle_lowlevel_drv_command)
990 {
991         if (CMD_ARGC != 1)
992                 return ERROR_COMMAND_SYNTAX_ERROR;
993
994         info.lowlevel_name = strdup(CMD_ARGV[0]);
995
996         return ERROR_OK;
997 }
998
999 COMMAND_HANDLER(ublast_firmware_command)
1000 {
1001         if (CMD_ARGC != 1)
1002                 return ERROR_COMMAND_SYNTAX_ERROR;
1003
1004         info.firmware_path = strdup(CMD_ARGV[0]);
1005
1006         return ERROR_OK;
1007 }
1008
1009
1010 static const struct command_registration ublast_subcommand_handlers[] = {
1011         {
1012                 .name = "vid_pid",
1013                 .handler = ublast_handle_vid_pid_command,
1014                 .mode = COMMAND_CONFIG,
1015                 .help = "the vendor ID and product ID of the USB-Blaster and "
1016                         "vendor ID and product ID of the uninitialized device "
1017                         "for USB-Blaster II",
1018                 .usage = "vid pid vid_uninit pid_uninit",
1019         },
1020         {
1021                 .name = "lowlevel_driver",
1022                 .handler = ublast_handle_lowlevel_drv_command,
1023                 .mode = COMMAND_CONFIG,
1024                 .help = "set the lowlevel access for the USB Blaster (ftdi, ublast2)",
1025                 .usage = "(ftdi|ublast2)",
1026         },
1027         {
1028                 .name = "pin",
1029                 .handler = ublast_handle_pin_command,
1030                 .mode = COMMAND_ANY,
1031                 .help = "show or set pin state for the unused GPIO pins",
1032                 .usage = "(pin6|pin8) (0|1|s|t)",
1033         },
1034                 {
1035                 .name = "firmware",
1036                 .handler = &ublast_firmware_command,
1037                 .mode = COMMAND_CONFIG,
1038                 .help = "configure the USB-Blaster II firmware location",
1039                 .usage = "path/to/blaster_xxxx.hex",
1040         },
1041         COMMAND_REGISTRATION_DONE
1042 };
1043
1044 static const struct command_registration ublast_command_handlers[] = {
1045         {
1046                 .name = "usb_blaster",
1047                 .mode = COMMAND_ANY,
1048                 .help = "perform usb_blaster management",
1049                 .chain = ublast_subcommand_handlers,
1050                 .usage = "",
1051         },
1052         COMMAND_REGISTRATION_DONE
1053 };
1054
1055 static struct jtag_interface usb_blaster_interface = {
1056         .supported = DEBUG_CAP_TMS_SEQ,
1057         .execute_queue = ublast_execute_queue,
1058 };
1059
1060 struct adapter_driver usb_blaster_adapter_driver = {
1061         .name = "usb_blaster",
1062         .transports = jtag_only,
1063         .commands = ublast_command_handlers,
1064
1065         .init = ublast_init,
1066         .quit = ublast_quit,
1067
1068         .jtag_ops = &usb_blaster_interface,
1069 };