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