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