jtag: add esp_usb_jtag driver
[fw/openocd] / src / jtag / drivers / esp_usb_jtag.c
1 /***************************************************************************
2  *   Espressif USB to Jtag adapter                                         *
3  *   Copyright (C) 2020 Espressif Systems (Shanghai) Co. Ltd.              *
4  *   Author: Jeroen Domburg <jeroen@espressif.com>                         *
5  *                                                                         *
6  *   This program is free software; you can redistribute it and/or modify  *
7  *   it under the terms of the GNU General Public License as published by  *
8  *   the Free Software Foundation; either version 2 of the License, or     *
9  *   (at your option) any later version.                                   *
10  *                                                                         *
11  *   This program is distributed in the hope that it will be useful,       *
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14  *   GNU General Public License for more details.                          *
15  *                                                                         *
16  *   You should have received a copy of the GNU General Public License     *
17  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
18  ***************************************************************************/
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include <jtag/adapter.h>
25 #include <jtag/interface.h>
26 #include <helper/time_support.h>
27 #include <helper/bits.h>
28 #include "bitq.h"
29 #include "libusb_helper.h"
30
31 #define __packed __attribute__((packed))
32
33 /*
34 Holy Crap, it's protocol documentation, and it's even vendor-provided!
35
36 A device that speaks this protocol has two endpoints intended for JTAG debugging: one
37 OUT for the host to send encoded commands to, one IN from which the host can read any read
38 TDO bits. The device will also respond to vendor-defined interface requests on ep0.
39
40 The main communication method is over the IN/OUT endpoints. The commands that are expected
41 on the OUT endpoint are one nibble wide and are processed high-nibble-first, low-nibble-second,
42 and in the order the bytes come in. Commands are defined as follows:
43
44     bit     3   2    1    0
45 CMD_CLK   [ 0   cap  tdi  tms  ]
46 CMD_RST   [ 1   0    0    srst ]
47 CMD_FLUSH [ 1   0    1    0    ]
48 CMD_RSV   [ 1   0    1    1    ]
49 CMD_REP   [ 1   1    R1   R0   ]
50
51 CMD_CLK sets the TDI and TMS lines to the value of `tdi` and `tms` and lowers, then raises, TCK. If
52 `cap` is 1, the value of TDO is captured and can be retrieved over the IN endpoint. The bytes read from
53 the IN endpoint specifically are these bits, with the lowest it in every byte captured first and the
54 bytes returned in the order the data in them was captured. The durations of TCK being high / low can
55 be set using the VEND_JTAG_SETDIV vendor-specific interface request.
56
57 CMD_RST controls the SRST line; as soon as the command is processed, the SRST line will be set
58 to the value of `srst`.
59
60 CMD_FLUSH flushes the IN endpoint; zeroes will be added to the amount of bits in the endpoint until
61 the payload is a multiple of bytes, and the data is offered to the host. If the IN endpoint has
62 no data, this effectively becomes a no-op; the endpoint won't send any 0-byte payloads.
63
64 CMD_RSV is reserved for future use.
65
66 CMD_REP repeats the last command that is not CMD_REP. The amount of times a CMD_REP command will
67 re-execute this command is (r1*2+r0)<<(2*n), where n is the amount of previous repeat commands executed
68 since the command to be repeated.
69
70 An example for CMD_REP: Say the host queues:
71 1. CMD_CLK - This will execute one CMD_CLK.
72 2. CMD_REP with r1=0 and r0=1 - This will execute 1. another (0*2+1)<<(2*0)=1 time.
73 3. CMD_REP with r1=1 and r0=0 - This will execute 1. another (1*2+0)<<(2*1)=4 times.
74 4. CMD_REP with r1=0 and r0=1 - This will execute 1. another (0*2+1)<<(2*2)=8 time.
75 5. CMD_FLUSH - This will flush the IN pipeline.
76 6. CMD_CLK - This will execute one CMD_CLK
77 7. CMD_REP with r1=1 and r0=0 - This will execute 6. another (1*2+0)<<(2*0)=2 times.
78 8. CMD_FLUSH - This will flush the IN pipeline.
79
80 Note that the net effect of the repetitions is that command 1 is executed (1+1+4+8=) 14 times and
81 command 6 is executed (1+2=) 3 times.
82
83 Note that the device only has a fairly limited amount of endpoint RAM. It's probably best to keep
84 an eye on the amount of bytes that are supposed to be in the IN endpoint and grab those before stuffing
85 more commands into the OUT endpoint: the OUT endpoint will not accept any more commands (writes will
86 time out) when the IN endpoint buffers are all filled up.
87
88 The device also supports some vendor-specific interface requests. These requests are sent as control
89 transfers on endpoint 0 to the JTAG endpoint. Note that these commands bypass the data in the OUT
90 endpoint; if timing is important, it's important that this endpoint is empty. This can be done by
91 e.g sending one CMD_CLK capturing TDI, then one CMD_FLUSH, then waiting until the bit appears on the
92 IN endpoint.
93
94 bmRequestType bRequest         wValue   wIndex    wLength Data
95 01000000b     VEND_JTAG_SETDIV [divide] interface 0       None
96 01000000b     VEND_JTAG_SETIO  [iobits] interface 0       None
97 11000000b     VEND_JTAG_GETTDO  0       interface 1       [iostate]
98 10000000b     GET_DESCRIPTOR(6) 0x2000  0         256     [jtag cap desc]
99
100 VEND_JTAG_SETDIV indirectly controls the speed of the TCK clock. The value written here is the length
101 of a TCK cycle, in ticks of the adapters base clock. Both the base clock value as well as the
102 minimum and maximum divider can be read from the jtag capabilities descriptor, as explained
103 below. Note that this should not be set to a value outside of the range described there,
104 otherwise results are undefined.
105
106 VEND_JTAG_SETIO can be controlled to directly set the IO pins. The format of [iobits] normally is
107 {11'b0, srst, trst, tck, tms, tdi}
108 Note that the first 11 0 bits are reserved for future use, current hardware ignores them.
109
110 VEND_JTAG_GETTDO returns one byte, of which bit 0 indicates the current state of the TDO input.
111 Note that other bits are reserved for future use and should be ignored.
112
113 To describe the capabilities of the JTAG adapter, a specific descriptor (0x20) can be retrieved.
114 The format of the descriptor documented below. The descriptor works in the same fashion as USB
115 descriptors: a header indicating the version and total length followed by descriptors with a
116 specific type and size. Forward compatibility is guaranteed as software can skip over an unknown
117 descriptor.
118
119 */
120
121 #define JTAG_PROTO_CAPS_VER 1   /* Version field. At the moment, only version 1 is defined. */
122 struct jtag_proto_caps_hdr {
123         uint8_t proto_ver;      /* Protocol version. Expects JTAG_PROTO_CAPS_VER for now. */
124         uint8_t length; /* of this plus any following descriptors */
125 } __packed;
126
127 /* start of the descriptor headers */
128 #define JTAG_BUILTIN_DESCR_START_OFF            0       /* Devices with builtin usb jtag */
129 /*
130 * ESP USB Bridge https://github.com/espressif/esp-usb-bridge uses string descriptor.
131 * Skip 1 byte length and 1 byte descriptor type
132 */
133 #define JTAG_EUB_DESCR_START_OFF                2       /* ESP USB Bridge */
134
135 /*
136 Note: At the moment, there is only a speed_caps version indicating the base speed of the JTAG
137 hardware is derived from the APB bus speed of the SoC. If later on, there are standalone
138 converters using the protocol, we should define e.g. JTAG_PROTO_CAPS_SPEED_FIXED_TYPE to distinguish
139 between the two.
140
141 Note: If the JTAG device has larger buffers than endpoint-size-plus-a-bit, we should have some kind
142 of caps header to assume this. If no such caps exist, assume a minimum (in) buffer of endpoint size + 4.
143 */
144
145 struct jtag_gen_hdr {
146         uint8_t type;
147         uint8_t length;
148 } __packed;
149
150 struct jtag_proto_caps_speed_apb {
151         uint8_t type;                                   /* Type, always JTAG_PROTO_CAPS_SPEED_APB_TYPE */
152         uint8_t length;                                 /* Length of this */
153         uint8_t apb_speed_10khz[2];             /* ABP bus speed, in 10KHz increments. Base speed is half this. */
154         uint8_t div_min[2];                             /* minimum divisor (to base speed), inclusive */
155         uint8_t div_max[2];                             /* maximum divisor (to base speed), inclusive */
156 } __packed;
157
158 #define JTAG_PROTO_CAPS_DATA_LEN                255
159 #define JTAG_PROTO_CAPS_SPEED_APB_TYPE          1
160
161 #define VEND_DESCR_BUILTIN_JTAG_CAPS            0x2000
162
163 #define VEND_JTAG_SETDIV        0
164 #define VEND_JTAG_SETIO         1
165 #define VEND_JTAG_GETTDO        2
166 #define VEND_JTAG_SET_CHIPID    3
167
168 #define VEND_JTAG_SETIO_TDI     BIT(0)
169 #define VEND_JTAG_SETIO_TMS     BIT(1)
170 #define VEND_JTAG_SETIO_TCK     BIT(2)
171 #define VEND_JTAG_SETIO_TRST    BIT(3)
172 #define VEND_JTAG_SETIO_SRST    BIT(4)
173
174 #define CMD_CLK(cap, tdi, tms) ((cap ? BIT(2) : 0) | (tms ? BIT(1) : 0) | (tdi ? BIT(0) : 0))
175 #define CMD_RST(srst)   (0x8 | (srst ? BIT(0) : 0))
176 #define CMD_FLUSH       0xA
177 #define CMD_RSVD        0xB
178 #define CMD_REP(r)      (0xC + ((r) & 3))
179
180 /* The internal repeats register is 10 bits, which means we can have 5 repeat commands in a
181  *row at max. This translates to ('b1111111111+1=)1024 reps max. */
182 #define CMD_REP_MAX_REPS 1024
183
184 /* Currently we only support one USB device. */
185 #define USB_CONFIGURATION 0
186
187 /* Buffer size; is equal to the endpoint size. In bytes
188  * TODO for future adapters: read from device configuration? */
189 #define OUT_EP_SZ 64
190 /* Out data can be buffered for longer without issues (as long as the in buffer does not overflow),
191  * so we'll use an out buffer that is much larger than the out ep size. */
192 #define OUT_BUF_SZ (OUT_EP_SZ * 32)
193 /* The in buffer cannot be larger than the device can offer, though. */
194 #define IN_BUF_SZ 64
195
196 /* Because a series of out commands can lead to a multitude of IN_BUF_SZ-sized in packets
197  *to be read, we have multiple buffers to store those before the bitq interface reads them out. */
198 #define IN_BUF_CT 8
199
200 #define ESP_USB_INTERFACE       1
201
202 /* Private data */
203 struct esp_usb_jtag {
204         struct libusb_device_handle *usb_device;
205         uint32_t base_speed_khz;
206         uint16_t div_min;
207         uint16_t div_max;
208         uint8_t out_buf[OUT_BUF_SZ];
209         unsigned int out_buf_pos_nibbles;                       /* write position in out_buf */
210
211         uint8_t in_buf[IN_BUF_CT][IN_BUF_SZ];
212         unsigned int in_buf_size_bits[IN_BUF_CT];       /* size in bits of the data stored in an in_buf */
213         unsigned int cur_in_buf_rd, cur_in_buf_wr;      /* read/write index */
214         unsigned int in_buf_pos_bits;   /* which bit in the in buf needs to be returned to bitq next */
215
216         unsigned int read_ep;
217         unsigned int write_ep;
218
219         unsigned int prev_cmd;          /* previous command, stored here for RLEing. */
220         int prev_cmd_repct;                     /* Amount of repetitions of that command we have seen until now */
221
222         /* This is the total number of in bits we need to read, including in unsent commands */
223         unsigned int pending_in_bits;
224
225         unsigned int hw_in_fifo_len;
226
227         struct bitq_interface bitq_interface;
228 };
229
230 /* For now, we only use one static private struct. Technically, we can re-work this, but I don't think
231  * OpenOCD supports multiple JTAG adapters anyway. */
232 static struct esp_usb_jtag esp_usb_jtag_priv;
233 static struct esp_usb_jtag *priv = &esp_usb_jtag_priv;
234
235 static int esp_usb_vid;
236 static int esp_usb_pid;
237 static int esp_usb_jtag_caps;
238 static int esp_usb_target_chip_id;
239
240 static int esp_usb_jtag_init(void);
241 static int esp_usb_jtag_quit(void);
242
243 /* Try to receive from USB endpoint into the current priv->in_buf */
244 static int esp_usb_jtag_recv_buf(void)
245 {
246         if (priv->in_buf_size_bits[priv->cur_in_buf_wr] != 0)
247                 LOG_ERROR("esp_usb_jtag: IN buffer overflow! (%d, size %d)",
248                         priv->cur_in_buf_wr,
249                         priv->in_buf_size_bits[priv->cur_in_buf_wr]);
250
251         unsigned int recvd = 0, ct = (priv->pending_in_bits + 7) / 8;
252         if (ct > IN_BUF_SZ)
253                 ct = IN_BUF_SZ;
254         if (ct == 0) {
255                 /* Note that the adapters IN EP specifically does *not* usually generate 0-byte in
256                  * packets if there has been no data since the last flush.
257                  * As such, we don't need (and shouldn't) try to read it. */
258                 return ERROR_OK;
259         }
260
261         priv->in_buf_size_bits[priv->cur_in_buf_wr] = 0;
262         while (recvd < ct) {
263                 unsigned int tr;
264                 int ret = jtag_libusb_bulk_read(priv->usb_device,
265                         priv->read_ep,
266                         (char *)priv->in_buf[priv->cur_in_buf_wr] + recvd,
267                         ct,
268                         LIBUSB_TIMEOUT_MS,      /*ms*/
269                         (int *)&tr);
270                 if (ret != ERROR_OK || tr == 0) {
271                         /* Sometimes the hardware returns 0 bytes instead of NAKking the transaction. Ignore this. */
272                         return ERROR_FAIL;
273                 }
274
275                 if (tr != ct) {
276                         /* Huh, short read? */
277                         LOG_DEBUG("esp_usb_jtag: usb received only %d out of %d bytes.", tr, ct);
278                 }
279                 /* Adjust the amount of bits we still expect to read from the USB device after this. */
280                 unsigned int bits_in_buf = priv->pending_in_bits;       /* initially assume we read
281                                                                         * everything that was pending */
282                 if (bits_in_buf > tr * 8)
283                         bits_in_buf = tr * 8;   /* ...but correct that if that was not the case. */
284                 priv->pending_in_bits -= bits_in_buf;
285                 priv->in_buf_size_bits[priv->cur_in_buf_wr] += bits_in_buf;
286                 recvd += tr;
287         }
288         /* next in buffer for the next time. */
289         priv->cur_in_buf_wr++;
290         if (priv->cur_in_buf_wr == IN_BUF_CT)
291                 priv->cur_in_buf_wr = 0;
292         LOG_DEBUG_IO("esp_usb_jtag: In ep: received %d bytes; %d bytes (%d bits) left.", recvd,
293                 (priv->pending_in_bits + 7) / 8, priv->pending_in_bits);
294         return ERROR_OK;
295 }
296
297 /* Sends priv->out_buf to the USB device. */
298 static int esp_usb_jtag_send_buf(void)
299 {
300         unsigned int ct = priv->out_buf_pos_nibbles / 2;
301         unsigned int written = 0;
302
303         while (written < ct) {
304                 int tr = 0, ret = jtag_libusb_bulk_write(priv->usb_device,
305                         priv->write_ep,
306                         (char *)priv->out_buf + written,
307                         ct - written,
308                         LIBUSB_TIMEOUT_MS,      /*ms*/
309                         &tr);
310                 LOG_DEBUG_IO("esp_usb_jtag: sent %d bytes.", tr);
311                 if (written + tr != ct) {
312                         LOG_DEBUG("esp_usb_jtag: usb sent only %d out of %d bytes.",
313                                 written + tr,
314                                 ct);
315                 }
316                 if (ret != ERROR_OK)
317                         return ret;
318                 written += tr;
319         }
320         priv->out_buf_pos_nibbles = 0;
321
322         /* If there's more than a bufferful of data queuing up in the jtag adapters IN endpoint, empty
323          * all but one buffer. */
324         while (priv->pending_in_bits > (IN_BUF_SZ + priv->hw_in_fifo_len - 1) * 8)
325                 esp_usb_jtag_recv_buf();
326
327         return ERROR_OK;
328 }
329
330 /* Simply adds a command to the buffer. Is called by the RLE encoding mechanism.
331  *Also sends the intermediate buffer if there's enough to go into one USB packet. */
332 static int esp_usb_jtag_command_add_raw(unsigned int cmd)
333 {
334         int ret = ERROR_OK;
335
336         if ((priv->out_buf_pos_nibbles & 1) == 0)
337                 priv->out_buf[priv->out_buf_pos_nibbles / 2] = (cmd << 4);
338         else
339                 priv->out_buf[priv->out_buf_pos_nibbles / 2] |= cmd;
340         priv->out_buf_pos_nibbles++;
341
342         if (priv->out_buf_pos_nibbles == OUT_BUF_SZ * 2)
343                 ret = esp_usb_jtag_send_buf();
344         if (ret == ERROR_OK && priv->out_buf_pos_nibbles % (OUT_EP_SZ * 2) == 0) {
345                 if (priv->pending_in_bits > (IN_BUF_SZ + priv->hw_in_fifo_len - 1) * 8)
346                         ret = esp_usb_jtag_send_buf();
347         }
348         return ret;
349 }
350
351 /* Writes a command stream equivalent to writing `cmd` `ct` times. */
352 static int esp_usb_jtag_write_rlestream(unsigned int cmd, int ct)
353 {
354         /* Special case: stacking flush commands does not make sense (and may not make the hardware very happy) */
355         if (cmd == CMD_FLUSH)
356                 ct = 1;
357         /* Output previous command and repeat commands */
358         int ret = esp_usb_jtag_command_add_raw(cmd);
359         if (ret != ERROR_OK)
360                 return ret;
361         ct--;   /* as the previous line already executes the command one time */
362         while (ct > 0) {
363                 ret = esp_usb_jtag_command_add_raw(CMD_REP(ct & 3));
364                 if (ret != ERROR_OK)
365                         return ret;
366                 ct >>= 2;
367         }
368         return ERROR_OK;
369 }
370
371 /* Adds a command to the buffer of things to be sent. Transparently handles RLE compression using
372  * the CMD_REP_x commands */
373 static int esp_usb_jtag_command_add(unsigned int cmd)
374 {
375         if (cmd == priv->prev_cmd && priv->prev_cmd_repct < CMD_REP_MAX_REPS) {
376                 priv->prev_cmd_repct++;
377         } else {
378                 /* We can now write out the previous command plus repeat count. */
379                 if (priv->prev_cmd_repct) {
380                         int ret = esp_usb_jtag_write_rlestream(priv->prev_cmd, priv->prev_cmd_repct);
381                         if (ret != ERROR_OK)
382                                 return ret;
383                 }
384                 /* Ready for new command. */
385                 priv->prev_cmd = cmd;
386                 priv->prev_cmd_repct = 1;
387         }
388         return ERROR_OK;
389 }
390
391 /* Called by bitq interface to output a bit on tdi and perhaps read a bit from tdo */
392 static int esp_usb_jtag_out(int tms, int tdi, int tdo_req)
393 {
394         int ret = esp_usb_jtag_command_add(CMD_CLK(tdo_req, tdi, tms));
395         if (ret != ERROR_OK)
396                 return ret;
397         if (tdo_req)
398                 priv->pending_in_bits++;
399         return ERROR_OK;
400 }
401
402 /* Called by bitq interface to flush all output commands and get returned data ready to read */
403 static int esp_usb_jtag_flush(void)
404 {
405         int ret;
406         /*Make sure last command is written */
407         if (priv->prev_cmd_repct) {
408                 ret = esp_usb_jtag_write_rlestream(priv->prev_cmd, priv->prev_cmd_repct);
409                 if (ret != ERROR_OK)
410                         return ret;
411         }
412         priv->prev_cmd_repct = 0;
413         /* Flush in buffer */
414         ret = esp_usb_jtag_command_add_raw(CMD_FLUSH);
415         if (ret != ERROR_OK)
416                 return ret;
417         /* Make sure we have an even amount of commands, as we can't write a nibble by itself. */
418         if (priv->out_buf_pos_nibbles & 1) {
419                 /*If not, pad with an extra FLUSH */
420                 ret = esp_usb_jtag_command_add_raw(CMD_FLUSH);
421                 if (ret != ERROR_OK)
422                         return ret;
423         }
424         LOG_DEBUG_IO("esp_usb_jtag: Flush!");
425         /* Send off the buffer. */
426         ret = esp_usb_jtag_send_buf();
427         if (ret != ERROR_OK)
428                 return ret;
429
430         /* Immediately fetch the response bits. */
431         while (priv->pending_in_bits > 0)
432                 esp_usb_jtag_recv_buf();
433
434         return ERROR_OK;
435 }
436
437 /* Called by bitq interface to sleep for a determined amount of time */
438 static int esp_usb_jtag_sleep(unsigned long us)
439 {
440         esp_usb_jtag_flush();
441         /* TODO: we can sleep more precisely (for small amounts of sleep at least) by sending dummy
442          * commands to the adapter. */
443         jtag_sleep(us);
444         return 0;
445 }
446
447 /* Called by the bitq interface to set the various resets */
448 static int esp_usb_jtag_reset(int trst, int srst)
449 {
450         /* TODO: handle trst using setup commands. Kind-of superfluous, however, as we can also do
451          * a tap reset using tms, and it's also not implemented on other ESP32 chips with external JTAG. */
452         return esp_usb_jtag_command_add(CMD_RST(srst));
453 }
454
455 /* Called by bitq to see if the IN data already is returned to the host. */
456 static int esp_usb_jtag_in_rdy(void)
457 {
458         /* We read all bits in the flush() routine, so if we're here, we have bits or are at EOF. */
459         return 1;
460 }
461
462 /* Read one bit from the IN data */
463 static int esp_usb_jtag_in(void)
464 {
465         if (!esp_usb_jtag_in_rdy()) {
466                 LOG_ERROR("esp_usb_jtag: Eeek! bitq asked us for in data while not ready!");
467                 return -1;
468         }
469         if (priv->cur_in_buf_rd == priv->cur_in_buf_wr &&
470                 priv->in_buf_size_bits[priv->cur_in_buf_rd] == 0)
471                 return -1;
472
473         /* Extract the bit */
474         int r = (priv->in_buf[priv->cur_in_buf_rd][priv->in_buf_pos_bits / 8] &
475                 BIT(priv->in_buf_pos_bits & 7)) ? 1 : 0;
476         /* Move to next bit. */
477         priv->in_buf_pos_bits++;
478         if (priv->in_buf_pos_bits == priv->in_buf_size_bits[priv->cur_in_buf_rd]) {
479                 /* No more bits in this buffer; mark as re-usable and move to next buffer. */
480                 priv->in_buf_pos_bits = 0;
481                 priv->in_buf_size_bits[priv->cur_in_buf_rd] = 0;/*indicate it is free again */
482                 priv->cur_in_buf_rd++;
483                 if (priv->cur_in_buf_rd == IN_BUF_CT)
484                         priv->cur_in_buf_rd = 0;
485         }
486         return r;
487 }
488
489 static int esp_usb_jtag_init(void)
490 {
491         memset(priv, 0, sizeof(struct esp_usb_jtag));
492
493         const uint16_t vids[] = { esp_usb_vid, 0 };             /* must be null terminated */
494         const uint16_t pids[] = { esp_usb_pid, 0 };             /* must be null terminated */
495
496         bitq_interface = &priv->bitq_interface;
497         bitq_interface->out = esp_usb_jtag_out;
498         bitq_interface->flush = esp_usb_jtag_flush;
499         bitq_interface->sleep = esp_usb_jtag_sleep;
500         bitq_interface->reset = esp_usb_jtag_reset;
501         bitq_interface->in_rdy = esp_usb_jtag_in_rdy;
502         bitq_interface->in = esp_usb_jtag_in;
503
504         int r = jtag_libusb_open(vids, pids, &priv->usb_device, NULL);
505         if (r != ERROR_OK) {
506                 LOG_ERROR("esp_usb_jtag: could not find or open device!");
507                 goto out;
508         }
509
510         jtag_libusb_set_configuration(priv->usb_device, USB_CONFIGURATION);
511
512         r = jtag_libusb_choose_interface(priv->usb_device, &priv->read_ep, &priv->write_ep,
513                 LIBUSB_CLASS_VENDOR_SPEC, LIBUSB_CLASS_VENDOR_SPEC, ESP_USB_INTERFACE, LIBUSB_TRANSFER_TYPE_BULK);
514         if (r != ERROR_OK) {
515                 LOG_ERROR("esp_usb_jtag: error finding/claiming JTAG interface on device!");
516                 goto out;
517         }
518
519         /* TODO: This is not proper way to get caps data. Two requests can be done.
520          * 1- With the minimum size required to get to know the total length of that struct,
521          * 2- Then exactly the length of that struct. */
522         uint8_t jtag_caps_desc[JTAG_PROTO_CAPS_DATA_LEN];
523         int jtag_caps_read_len = jtag_libusb_control_transfer(priv->usb_device,
524                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
525                 LIBUSB_REQUEST_GET_DESCRIPTOR, esp_usb_jtag_caps, 0,
526                 (char *)jtag_caps_desc, JTAG_PROTO_CAPS_DATA_LEN, LIBUSB_TIMEOUT_MS);
527         if (jtag_caps_read_len <= 0) {
528                 LOG_ERROR("esp_usb_jtag: could not retrieve jtag_caps descriptor!");
529                 goto out;
530         }
531
532         /* defaults for values we normally get from the jtag caps descriptor */
533         priv->base_speed_khz = UINT32_MAX;
534         priv->div_min = 1;
535         priv->div_max = 1;
536
537         int p = esp_usb_jtag_caps ==
538                 VEND_DESCR_BUILTIN_JTAG_CAPS ? JTAG_BUILTIN_DESCR_START_OFF : JTAG_EUB_DESCR_START_OFF;
539
540         if (p + sizeof(struct jtag_proto_caps_hdr) > (unsigned int)jtag_caps_read_len) {
541                 LOG_ERROR("esp_usb_jtag: not enough data to get header");
542                 goto out;
543         }
544
545         struct jtag_proto_caps_hdr *hdr = (struct jtag_proto_caps_hdr *)&jtag_caps_desc[p];
546         if (hdr->proto_ver != JTAG_PROTO_CAPS_VER) {
547                 LOG_ERROR("esp_usb_jtag: unknown jtag_caps descriptor version 0x%X!",
548                         hdr->proto_ver);
549                 goto out;
550         }
551         if (hdr->length > jtag_caps_read_len) {
552                 LOG_ERROR("esp_usb_jtag: header length (%d) bigger then max read bytes (%d)",
553                         hdr->length, jtag_caps_read_len);
554                 goto out;
555         }
556
557         p += sizeof(struct jtag_proto_caps_hdr);
558
559         while (p + sizeof(struct jtag_gen_hdr) < hdr->length) {
560                 struct jtag_gen_hdr *dhdr = (struct jtag_gen_hdr *)&jtag_caps_desc[p];
561                 if (dhdr->type == JTAG_PROTO_CAPS_SPEED_APB_TYPE) {
562                         if (p + sizeof(struct jtag_proto_caps_speed_apb) < hdr->length) {
563                                 LOG_ERROR("esp_usb_jtag: not enough data to get caps speed");
564                                 goto out;
565                         }
566                         struct jtag_proto_caps_speed_apb *spcap = (struct jtag_proto_caps_speed_apb *)dhdr;
567                         /* base speed always is half APB speed */
568                         priv->base_speed_khz = le_to_h_u16(spcap->apb_speed_10khz) * 10 / 2;
569                         priv->div_min = le_to_h_u16(spcap->div_min);
570                         priv->div_max = le_to_h_u16(spcap->div_max);
571                         /* TODO: mark in priv that this is apb-derived and as such may change if apb
572                          * ever changes? */
573                 } else {
574                         LOG_WARNING("esp_usb_jtag: unknown caps type 0x%X", dhdr->type);
575                 }
576                 p += dhdr->length;
577         }
578         if (priv->base_speed_khz == UINT32_MAX) {
579                 LOG_WARNING("esp_usb_jtag: No speed caps found... using sane-ish defaults.");
580                 priv->base_speed_khz = 1000;
581         }
582         LOG_INFO("esp_usb_jtag: Device found. Base speed %dKHz, div range %d to %d",
583                 priv->base_speed_khz, priv->div_min, priv->div_max);
584
585         /* TODO: grab from (future) descriptor if we ever have a device with larger IN buffers */
586         priv->hw_in_fifo_len = 4;
587
588         /* inform bridge board about the connected target chip for the specific operations
589          * it is also safe to send this info to chips that have builtin usb jtag */
590         jtag_libusb_control_transfer(priv->usb_device,
591                 LIBUSB_REQUEST_TYPE_VENDOR,
592                 VEND_JTAG_SET_CHIPID,
593                 esp_usb_target_chip_id,
594                 0,
595                 NULL,
596                 0,
597                 LIBUSB_TIMEOUT_MS);
598
599         return ERROR_OK;
600
601 out:
602         if (priv->usb_device)
603                 jtag_libusb_close(priv->usb_device);
604         bitq_interface = NULL;
605         priv->usb_device = NULL;
606         return ERROR_FAIL;
607 }
608
609 static int esp_usb_jtag_quit(void)
610 {
611         if (!priv->usb_device)
612                 return ERROR_OK;
613         jtag_libusb_close(priv->usb_device);
614         bitq_cleanup();
615         bitq_interface = NULL;
616         return ERROR_OK;
617 }
618
619 static int esp_usb_jtag_speed_div(int divisor, int *khz)
620 {
621         *khz = priv->base_speed_khz / divisor;
622         return ERROR_OK;
623 }
624
625 static int esp_usb_jtag_khz(int khz, int *divisor)
626 {
627         if (khz == 0) {
628                 LOG_WARNING("esp_usb_jtag: RCLK not supported");
629                 return ERROR_FAIL;
630         }
631
632         *divisor = priv->base_speed_khz / khz;
633         LOG_DEBUG("Divisor for %d KHz with base clock of %d khz is %d",
634                 khz,
635                 priv->base_speed_khz,
636                 *divisor);
637         if (*divisor < priv->div_min)
638                 *divisor = priv->div_min;
639         if (*divisor > priv->div_max)
640                 *divisor = priv->div_max;
641
642         return ERROR_OK;
643 }
644
645 static int esp_usb_jtag_speed(int divisor)
646 {
647         if (divisor == 0) {
648                 LOG_ERROR("esp_usb_jtag: Adaptive clocking is not supported.");
649                 return ERROR_JTAG_NOT_IMPLEMENTED;
650         }
651
652         LOG_DEBUG("esp_usb_jtag: setting divisor %d", divisor);
653         jtag_libusb_control_transfer(priv->usb_device,
654                 LIBUSB_REQUEST_TYPE_VENDOR, VEND_JTAG_SETDIV, divisor, 0, NULL, 0, LIBUSB_TIMEOUT_MS);
655
656         return ERROR_OK;
657 }
658
659 COMMAND_HANDLER(esp_usb_jtag_tdo_cmd)
660 {
661         char tdo;
662         if (!priv->usb_device)
663                 return ERROR_FAIL;
664         int r = jtag_libusb_control_transfer(priv->usb_device,
665                 LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR, VEND_JTAG_GETTDO, 0, 0, &tdo, 1, LIBUSB_TIMEOUT_MS);
666         if (r < 1)
667                 return r;
668
669         command_print(CMD, "%d", tdo);
670
671         return ERROR_OK;
672 }
673
674 COMMAND_HANDLER(esp_usb_jtag_setio_cmd)
675 {
676         uint32_t tdi, tms, tck, trst, srst;
677         uint16_t d = 0;
678
679         if (!priv->usb_device)
680                 return ERROR_FAIL;
681
682         if (CMD_ARGC != 5)
683                 return ERROR_COMMAND_SYNTAX_ERROR;
684
685         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], tdi);
686         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], tms);
687         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], tck);
688         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], trst);
689         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[4], srst);
690         if (tdi)
691                 d |= VEND_JTAG_SETIO_TDI;
692         if (tms)
693                 d |= VEND_JTAG_SETIO_TMS;
694         if (tck)
695                 d |= VEND_JTAG_SETIO_TCK;
696         if (trst)
697                 d |= VEND_JTAG_SETIO_TRST;
698         if (srst)
699                 d |= VEND_JTAG_SETIO_SRST;
700
701         jtag_libusb_control_transfer(priv->usb_device,
702                 0x40, VEND_JTAG_SETIO, d, 0, NULL, 0, LIBUSB_TIMEOUT_MS);
703
704         return ERROR_OK;
705 }
706
707 COMMAND_HANDLER(esp_usb_jtag_vid_pid)
708 {
709         if (CMD_ARGC != 2)
710                 return ERROR_COMMAND_SYNTAX_ERROR;
711
712         COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], esp_usb_vid);
713         COMMAND_PARSE_NUMBER(int, CMD_ARGV[1], esp_usb_pid);
714         LOG_INFO("esp_usb_jtag: VID set to 0x%x and PID to 0x%x", esp_usb_vid, esp_usb_pid);
715
716         return ERROR_OK;
717 }
718
719 COMMAND_HANDLER(esp_usb_jtag_caps_descriptor)
720 {
721         if (CMD_ARGC != 1)
722                 return ERROR_COMMAND_SYNTAX_ERROR;
723
724         COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], esp_usb_jtag_caps);
725         LOG_INFO("esp_usb_jtag: capabilities descriptor set to 0x%x", esp_usb_jtag_caps);
726
727         return ERROR_OK;
728 }
729
730 COMMAND_HANDLER(esp_usb_jtag_chip_id)
731 {
732         if (CMD_ARGC != 1)
733                 return ERROR_COMMAND_SYNTAX_ERROR;
734
735         COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], esp_usb_target_chip_id);
736         LOG_INFO("esp_usb_jtag: target chip id set to %d", esp_usb_target_chip_id);
737
738         return ERROR_OK;
739 }
740
741 static const struct command_registration esp_usb_jtag_subcommands[] = {
742         {
743                 .name = "tdo",
744                 .handler = &esp_usb_jtag_tdo_cmd,
745                 .mode = COMMAND_EXEC,
746                 .help = "Returns the current state of the TDO line",
747                 .usage = "",
748         },
749         {
750                 .name = "setio",
751                 .handler = &esp_usb_jtag_setio_cmd,
752                 .mode = COMMAND_EXEC,
753                 .help = "Manually set the status of the output lines",
754                 .usage = "tdi tms tck trst srst"
755         },
756         {
757                 .name = "vid_pid",
758                 .handler = &esp_usb_jtag_vid_pid,
759                 .mode = COMMAND_CONFIG,
760                 .help = "set vendor ID and product ID for ESP usb jtag driver",
761                 .usage = "vid pid",
762         },
763         {
764                 .name = "caps_descriptor",
765                 .handler = &esp_usb_jtag_caps_descriptor,
766                 .mode = COMMAND_CONFIG,
767                 .help = "set jtag descriptor to read capabilities of ESP usb jtag driver",
768                 .usage = "descriptor",
769         },
770         {
771                 .name = "chip_id",
772                 .handler = &esp_usb_jtag_chip_id,
773                 .mode = COMMAND_CONFIG,
774                 .help = "set chip_id to transfer to the bridge",
775                 .usage = "chip_id",
776         },
777         COMMAND_REGISTRATION_DONE
778 };
779
780 static const struct command_registration esp_usb_jtag_commands[] = {
781         {
782                 .name = "espusbjtag",
783                 .mode = COMMAND_ANY,
784                 .help = "ESP-USB-JTAG commands",
785                 .chain = esp_usb_jtag_subcommands,
786                 .usage = "",
787         },
788         COMMAND_REGISTRATION_DONE
789 };
790
791 static struct jtag_interface esp_usb_jtag_interface = {
792         .supported = DEBUG_CAP_TMS_SEQ,
793         .execute_queue = bitq_execute_queue,
794 };
795
796 struct adapter_driver esp_usb_adapter_driver = {
797         .name = "esp_usb_jtag",
798         .transports = jtag_only,
799         .commands = esp_usb_jtag_commands,
800
801         .init = esp_usb_jtag_init,
802         .quit = esp_usb_jtag_quit,
803         .speed_div = esp_usb_jtag_speed_div,
804         .speed = esp_usb_jtag_speed,
805         .khz = esp_usb_jtag_khz,
806
807         .jtag_ops = &esp_usb_jtag_interface,
808 };