drivers/ulink: Group adapter commands
[fw/openocd] / src / jtag / drivers / ulink.c
1 /***************************************************************************
2  *   Copyright (C) 2011-2013 by Martin Schmoelzer                          *
3  *   <martin.schmoelzer@student.tuwien.ac.at>                              *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
17  ***************************************************************************/
18
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22
23 #include <math.h>
24 #include "helper/system.h"
25 #include <jtag/interface.h>
26 #include <jtag/commands.h>
27 #include <target/image.h>
28 #include <libusb.h>
29 #include "libusb_helper.h"
30 #include "OpenULINK/include/msgtypes.h"
31
32 /** USB Vendor ID of ULINK device in unconfigured state (no firmware loaded
33  *  yet) or with OpenULINK firmware. */
34 #define ULINK_VID                0xC251
35
36 /** USB Product ID of ULINK device in unconfigured state (no firmware loaded
37  *  yet) or with OpenULINK firmware. */
38 #define ULINK_PID                0x2710
39
40 /** Address of EZ-USB CPU Control & Status register. This register can be
41  *  written by issuing a Control EP0 vendor request. */
42 #define CPUCS_REG                0x7F92
43
44 /** USB Control EP0 bRequest: "Firmware Load". */
45 #define REQUEST_FIRMWARE_LOAD    0xA0
46
47 /** Value to write into CPUCS to put EZ-USB into reset. */
48 #define CPU_RESET                0x01
49
50 /** Value to write into CPUCS to put EZ-USB out of reset. */
51 #define CPU_START                0x00
52
53 /** Base address of firmware in EZ-USB code space. */
54 #define FIRMWARE_ADDR            0x0000
55
56 /** USB interface number */
57 #define USB_INTERFACE            0
58
59 /** libusb timeout in ms */
60 #define USB_TIMEOUT              5000
61
62 /** Delay (in microseconds) to wait while EZ-USB performs ReNumeration. */
63 #define ULINK_RENUMERATION_DELAY 1500000
64
65 /** Default location of OpenULINK firmware image. */
66 #define ULINK_FIRMWARE_FILE      PKGDATADIR "/OpenULINK/ulink_firmware.hex"
67
68 /** Maximum size of a single firmware section. Entire EZ-USB code space = 8kB */
69 #define SECTION_BUFFERSIZE       8192
70
71 /** Tuning of OpenOCD SCAN commands split into multiple OpenULINK commands. */
72 #define SPLIT_SCAN_THRESHOLD     10
73
74 /** ULINK hardware type */
75 enum ulink_type {
76         /** Original ULINK adapter, based on Cypress EZ-USB (AN2131):
77          *  Full JTAG support, no SWD support. */
78         ULINK_1,
79
80         /** Newer ULINK adapter, based on NXP LPC2148. Currently unsupported. */
81         ULINK_2,
82
83         /** Newer ULINK adapter, based on EZ-USB FX2 + FPGA. Currently unsupported. */
84         ULINK_PRO,
85
86         /** Newer ULINK adapter, possibly based on ULINK 2. Currently unsupported. */
87         ULINK_ME
88 };
89
90 enum ulink_payload_direction {
91         PAYLOAD_DIRECTION_OUT,
92         PAYLOAD_DIRECTION_IN
93 };
94
95 enum ulink_delay_type {
96         DELAY_CLOCK_TCK,
97         DELAY_CLOCK_TMS,
98         DELAY_SCAN_IN,
99         DELAY_SCAN_OUT,
100         DELAY_SCAN_IO
101 };
102
103 /**
104  * OpenULINK command (OpenULINK command queue element).
105  *
106  * For the OUT direction payload, things are quite easy: Payload is stored
107  * in a rather small array (up to 63 bytes), the payload is always allocated
108  * by the function generating the command and freed by ulink_clear_queue().
109  *
110  * For the IN direction payload, things get a little bit more complicated:
111  * The maximum IN payload size for a single command is 64 bytes. Assume that
112  * a single OpenOCD command needs to scan 256 bytes. This results in the
113  * generation of four OpenULINK commands. The function generating these
114  * commands shall allocate an uint8_t[256] array. Each command's #payload_in
115  * pointer shall point to the corresponding offset where IN data shall be
116  * placed, while #payload_in_start shall point to the first element of the 256
117  * byte array.
118  * - first command:  #payload_in_start + 0
119  * - second command: #payload_in_start + 64
120  * - third command:  #payload_in_start + 128
121  * - fourth command: #payload_in_start + 192
122  *
123  * The last command sets #needs_postprocessing to true.
124  */
125 struct ulink_cmd {
126         uint8_t id;                     /**< ULINK command ID */
127
128         uint8_t *payload_out;           /**< OUT direction payload data */
129         uint8_t payload_out_size;       /**< OUT direction payload size for this command */
130
131         uint8_t *payload_in_start;      /**< Pointer to first element of IN payload array */
132         uint8_t *payload_in;            /**< Pointer where IN payload shall be stored */
133         uint8_t payload_in_size;        /**< IN direction payload size for this command */
134
135         /** Indicates if this command needs post-processing */
136         bool needs_postprocessing;
137
138         /** Indicates if ulink_clear_queue() should free payload_in_start  */
139         bool free_payload_in_start;
140
141         /** Pointer to corresponding OpenOCD command for post-processing */
142         struct jtag_command *cmd_origin;
143
144         struct ulink_cmd *next;         /**< Pointer to next command (linked list) */
145 };
146
147 /** Describes one driver instance */
148 struct ulink {
149         struct libusb_context *libusb_ctx;
150         struct libusb_device_handle *usb_device_handle;
151         enum ulink_type type;
152
153         unsigned int ep_in;             /**< IN endpoint number */
154         unsigned int ep_out;            /**< OUT endpoint number */
155
156         int delay_scan_in;      /**< Delay value for SCAN_IN commands */
157         int delay_scan_out;     /**< Delay value for SCAN_OUT commands */
158         int delay_scan_io;      /**< Delay value for SCAN_IO commands */
159         int delay_clock_tck;    /**< Delay value for CLOCK_TMS commands */
160         int delay_clock_tms;    /**< Delay value for CLOCK_TCK commands */
161
162         int commands_in_queue;          /**< Number of commands in queue */
163         struct ulink_cmd *queue_start;  /**< Pointer to first command in queue */
164         struct ulink_cmd *queue_end;    /**< Pointer to last command in queue */
165 };
166
167 /**************************** Function Prototypes *****************************/
168
169 /* USB helper functions */
170 static int ulink_usb_open(struct ulink **device);
171 static int ulink_usb_close(struct ulink **device);
172
173 /* ULINK MCU (Cypress EZ-USB) specific functions */
174 static int ulink_cpu_reset(struct ulink *device, unsigned char reset_bit);
175 static int ulink_load_firmware_and_renumerate(struct ulink **device, const char *filename,
176                 uint32_t delay);
177 static int ulink_load_firmware(struct ulink *device, const char *filename);
178 static int ulink_write_firmware_section(struct ulink *device,
179                 struct image *firmware_image, int section_index);
180
181 /* Generic helper functions */
182 static void ulink_print_signal_states(uint8_t input_signals, uint8_t output_signals);
183
184 /* OpenULINK command generation helper functions */
185 static int ulink_allocate_payload(struct ulink_cmd *ulink_cmd, int size,
186                 enum ulink_payload_direction direction);
187
188 /* OpenULINK command queue helper functions */
189 static int ulink_get_queue_size(struct ulink *device,
190                 enum ulink_payload_direction direction);
191 static void ulink_clear_queue(struct ulink *device);
192 static int ulink_append_queue(struct ulink *device, struct ulink_cmd *ulink_cmd);
193 static int ulink_execute_queued_commands(struct ulink *device, int timeout);
194
195 static void ulink_print_queue(struct ulink *device);
196
197 static int ulink_append_scan_cmd(struct ulink *device,
198                 enum scan_type scan_type,
199                 int scan_size_bits,
200                 uint8_t *tdi,
201                 uint8_t *tdo_start,
202                 uint8_t *tdo,
203                 uint8_t tms_count_start,
204                 uint8_t tms_sequence_start,
205                 uint8_t tms_count_end,
206                 uint8_t tms_sequence_end,
207                 struct jtag_command *origin,
208                 bool postprocess);
209 static int ulink_append_clock_tms_cmd(struct ulink *device, uint8_t count,
210                 uint8_t sequence);
211 static int ulink_append_clock_tck_cmd(struct ulink *device, uint16_t count);
212 static int ulink_append_get_signals_cmd(struct ulink *device);
213 static int ulink_append_set_signals_cmd(struct ulink *device, uint8_t low,
214                 uint8_t high);
215 static int ulink_append_sleep_cmd(struct ulink *device, uint32_t us);
216 static int ulink_append_configure_tck_cmd(struct ulink *device,
217                 int delay_scan_in,
218                 int delay_scan_out,
219                 int delay_scan_io,
220                 int delay_tck,
221                 int delay_tms);
222 static int __attribute__((unused)) ulink_append_led_cmd(struct ulink *device, uint8_t led_state);
223 static int ulink_append_test_cmd(struct ulink *device);
224
225 /* OpenULINK TCK frequency helper functions */
226 static int ulink_calculate_delay(enum ulink_delay_type type, long f, int *delay);
227
228 /* Interface between OpenULINK and OpenOCD */
229 static void ulink_set_end_state(tap_state_t endstate);
230 static int ulink_queue_statemove(struct ulink *device);
231
232 static int ulink_queue_scan(struct ulink *device, struct jtag_command *cmd);
233 static int ulink_queue_tlr_reset(struct ulink *device, struct jtag_command *cmd);
234 static int ulink_queue_runtest(struct ulink *device, struct jtag_command *cmd);
235 static int ulink_queue_reset(struct ulink *device, struct jtag_command *cmd);
236 static int ulink_queue_pathmove(struct ulink *device, struct jtag_command *cmd);
237 static int ulink_queue_sleep(struct ulink *device, struct jtag_command *cmd);
238 static int ulink_queue_stableclocks(struct ulink *device, struct jtag_command *cmd);
239
240 static int ulink_post_process_scan(struct ulink_cmd *ulink_cmd);
241 static int ulink_post_process_queue(struct ulink *device);
242
243 /* adapter driver functions */
244 static int ulink_execute_queue(void);
245 static int ulink_khz(int khz, int *jtag_speed);
246 static int ulink_speed(int speed);
247 static int ulink_speed_div(int speed, int *khz);
248 static int ulink_init(void);
249 static int ulink_quit(void);
250
251 /****************************** Global Variables ******************************/
252
253 static struct ulink *ulink_handle;
254
255 /**************************** USB helper functions ****************************/
256
257 /**
258  * Opens the ULINK device
259  *
260  * Currently, only the original ULINK is supported
261  *
262  * @param device pointer to struct ulink identifying ULINK driver instance.
263  * @return on success: ERROR_OK
264  * @return on failure: ERROR_FAIL
265  */
266 static int ulink_usb_open(struct ulink **device)
267 {
268         ssize_t num_devices, i;
269         bool found;
270         struct libusb_device **usb_devices;
271         struct libusb_device_descriptor usb_desc;
272         struct libusb_device_handle *usb_device_handle;
273
274         num_devices = libusb_get_device_list((*device)->libusb_ctx, &usb_devices);
275
276         if (num_devices <= 0)
277                 return ERROR_FAIL;
278
279         found = false;
280         for (i = 0; i < num_devices; i++) {
281                 if (libusb_get_device_descriptor(usb_devices[i], &usb_desc) != 0)
282                         continue;
283                 else if (usb_desc.idVendor == ULINK_VID && usb_desc.idProduct == ULINK_PID) {
284                         found = true;
285                         break;
286                 }
287         }
288
289         if (!found)
290                 return ERROR_FAIL;
291
292         if (libusb_open(usb_devices[i], &usb_device_handle) != 0)
293                 return ERROR_FAIL;
294         libusb_free_device_list(usb_devices, 1);
295
296         (*device)->usb_device_handle = usb_device_handle;
297         (*device)->type = ULINK_1;
298
299         return ERROR_OK;
300 }
301
302 /**
303  * Releases the ULINK interface and closes the USB device handle.
304  *
305  * @param device pointer to struct ulink identifying ULINK driver instance.
306  * @return on success: ERROR_OK
307  * @return on failure: ERROR_FAIL
308  */
309 static int ulink_usb_close(struct ulink **device)
310 {
311         if (libusb_release_interface((*device)->usb_device_handle, 0) != 0)
312                 return ERROR_FAIL;
313
314         libusb_close((*device)->usb_device_handle);
315
316         (*device)->usb_device_handle = NULL;
317
318         return ERROR_OK;
319 }
320
321 /******************* ULINK CPU (EZ-USB) specific functions ********************/
322
323 /**
324  * Writes '0' or '1' to the CPUCS register, putting the EZ-USB CPU into reset
325  * or out of reset.
326  *
327  * @param device pointer to struct ulink identifying ULINK driver instance.
328  * @param reset_bit 0 to put CPU into reset, 1 to put CPU out of reset.
329  * @return on success: ERROR_OK
330  * @return on failure: ERROR_FAIL
331  */
332 static int ulink_cpu_reset(struct ulink *device, unsigned char reset_bit)
333 {
334         int ret;
335
336         ret = libusb_control_transfer(device->usb_device_handle,
337                         (LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE),
338                         REQUEST_FIRMWARE_LOAD, CPUCS_REG, 0, &reset_bit, 1, USB_TIMEOUT);
339
340         /* usb_control_msg() returns the number of bytes transferred during the
341          * DATA stage of the control transfer - must be exactly 1 in this case! */
342         if (ret != 1)
343                 return ERROR_FAIL;
344         return ERROR_OK;
345 }
346
347 /**
348  * Puts the ULINK's EZ-USB microcontroller into reset state, downloads
349  * the firmware image, resumes the microcontroller and re-enumerates
350  * USB devices.
351  *
352  * @param device pointer to struct ulink identifying ULINK driver instance.
353  *  The usb_handle member will be modified during re-enumeration.
354  * @param filename path to the Intel HEX file containing the firmware image.
355  * @param delay the delay to wait for the device to re-enumerate.
356  * @return on success: ERROR_OK
357  * @return on failure: ERROR_FAIL
358  */
359 static int ulink_load_firmware_and_renumerate(struct ulink **device,
360         const char *filename, uint32_t delay)
361 {
362         int ret;
363
364         /* Basic process: After downloading the firmware, the ULINK will disconnect
365          * itself and re-connect after a short amount of time so we have to close
366          * the handle and re-enumerate USB devices */
367
368         ret = ulink_load_firmware(*device, filename);
369         if (ret != ERROR_OK)
370                 return ret;
371
372         ret = ulink_usb_close(device);
373         if (ret != ERROR_OK)
374                 return ret;
375
376         usleep(delay);
377
378         ret = ulink_usb_open(device);
379         if (ret != ERROR_OK)
380                 return ret;
381
382         return ERROR_OK;
383 }
384
385 /**
386  * Downloads a firmware image to the ULINK's EZ-USB microcontroller
387  * over the USB bus.
388  *
389  * @param device pointer to struct ulink identifying ULINK driver instance.
390  * @param filename an absolute or relative path to the Intel HEX file
391  *  containing the firmware image.
392  * @return on success: ERROR_OK
393  * @return on failure: ERROR_FAIL
394  */
395 static int ulink_load_firmware(struct ulink *device, const char *filename)
396 {
397         struct image ulink_firmware_image;
398         int ret;
399
400         ret = ulink_cpu_reset(device, CPU_RESET);
401         if (ret != ERROR_OK) {
402                 LOG_ERROR("Could not halt ULINK CPU");
403                 return ret;
404         }
405
406         ulink_firmware_image.base_address = 0;
407         ulink_firmware_image.base_address_set = false;
408
409         ret = image_open(&ulink_firmware_image, filename, "ihex");
410         if (ret != ERROR_OK) {
411                 LOG_ERROR("Could not load firmware image");
412                 return ret;
413         }
414
415         /* Download all sections in the image to ULINK */
416         for (unsigned int i = 0; i < ulink_firmware_image.num_sections; i++) {
417                 ret = ulink_write_firmware_section(device, &ulink_firmware_image, i);
418                 if (ret != ERROR_OK)
419                         return ret;
420         }
421
422         image_close(&ulink_firmware_image);
423
424         ret = ulink_cpu_reset(device, CPU_START);
425         if (ret != ERROR_OK) {
426                 LOG_ERROR("Could not restart ULINK CPU");
427                 return ret;
428         }
429
430         return ERROR_OK;
431 }
432
433 /**
434  * Send one contiguous firmware section to the ULINK's EZ-USB microcontroller
435  * over the USB bus.
436  *
437  * @param device pointer to struct ulink identifying ULINK driver instance.
438  * @param firmware_image pointer to the firmware image that contains the section
439  *  which should be sent to the ULINK's EZ-USB microcontroller.
440  * @param section_index index of the section within the firmware image.
441  * @return on success: ERROR_OK
442  * @return on failure: ERROR_FAIL
443  */
444 static int ulink_write_firmware_section(struct ulink *device,
445         struct image *firmware_image, int section_index)
446 {
447         uint16_t addr, size, bytes_remaining, chunk_size;
448         uint8_t data[SECTION_BUFFERSIZE];
449         uint8_t *data_ptr = data;
450         size_t size_read;
451         int ret;
452
453         size = (uint16_t)firmware_image->sections[section_index].size;
454         addr = (uint16_t)firmware_image->sections[section_index].base_address;
455
456         LOG_DEBUG("section %02i at addr 0x%04x (size 0x%04x)", section_index, addr,
457                 size);
458
459         /* Copy section contents to local buffer */
460         ret = image_read_section(firmware_image, section_index, 0, size, data,
461                         &size_read);
462
463         if ((ret != ERROR_OK) || (size_read != size)) {
464                 /* Propagating the return code would return '0' (misleadingly indicating
465                  * successful execution of the function) if only the size check fails. */
466                 return ERROR_FAIL;
467         }
468
469         bytes_remaining = size;
470
471         /* Send section data in chunks of up to 64 bytes to ULINK */
472         while (bytes_remaining > 0) {
473                 if (bytes_remaining > 64)
474                         chunk_size = 64;
475                 else
476                         chunk_size = bytes_remaining;
477
478                 ret = libusb_control_transfer(device->usb_device_handle,
479                                 (LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE),
480                                 REQUEST_FIRMWARE_LOAD, addr, FIRMWARE_ADDR, (unsigned char *)data_ptr,
481                                 chunk_size, USB_TIMEOUT);
482
483                 if (ret != (int)chunk_size) {
484                         /* Abort if libusb sent less data than requested */
485                         return ERROR_FAIL;
486                 }
487
488                 bytes_remaining -= chunk_size;
489                 addr += chunk_size;
490                 data_ptr += chunk_size;
491         }
492
493         return ERROR_OK;
494 }
495
496 /************************** Generic helper functions **************************/
497
498 /**
499  * Print state of interesting signals via LOG_INFO().
500  *
501  * @param input_signals input signal states as returned by CMD_GET_SIGNALS
502  * @param output_signals output signal states as returned by CMD_GET_SIGNALS
503  */
504 static void ulink_print_signal_states(uint8_t input_signals, uint8_t output_signals)
505 {
506         LOG_INFO("ULINK signal states: TDI: %i, TDO: %i, TMS: %i, TCK: %i, TRST: %i,"
507                 " SRST: %i",
508                 (output_signals & SIGNAL_TDI   ? 1 : 0),
509                 (input_signals  & SIGNAL_TDO   ? 1 : 0),
510                 (output_signals & SIGNAL_TMS   ? 1 : 0),
511                 (output_signals & SIGNAL_TCK   ? 1 : 0),
512                 (output_signals & SIGNAL_TRST  ? 0 : 1),        /* Inverted by hardware */
513                 (output_signals & SIGNAL_RESET ? 0 : 1));       /* Inverted by hardware */
514 }
515
516 /**************** OpenULINK command generation helper functions ***************/
517
518 /**
519  * Allocate and initialize space in memory for OpenULINK command payload.
520  *
521  * @param ulink_cmd pointer to command whose payload should be allocated.
522  * @param size the amount of memory to allocate (bytes).
523  * @param direction which payload to allocate.
524  * @return on success: ERROR_OK
525  * @return on failure: ERROR_FAIL
526  */
527 static int ulink_allocate_payload(struct ulink_cmd *ulink_cmd, int size,
528         enum ulink_payload_direction direction)
529 {
530         uint8_t *payload;
531
532         payload = calloc(size, sizeof(uint8_t));
533
534         if (!payload) {
535                 LOG_ERROR("Could not allocate OpenULINK command payload: out of memory");
536                 return ERROR_FAIL;
537         }
538
539         switch (direction) {
540             case PAYLOAD_DIRECTION_OUT:
541                     if (ulink_cmd->payload_out) {
542                             LOG_ERROR("BUG: Duplicate payload allocation for OpenULINK command");
543                             free(payload);
544                             return ERROR_FAIL;
545                     } else {
546                             ulink_cmd->payload_out = payload;
547                             ulink_cmd->payload_out_size = size;
548                     }
549                     break;
550             case PAYLOAD_DIRECTION_IN:
551                     if (ulink_cmd->payload_in_start) {
552                             LOG_ERROR("BUG: Duplicate payload allocation for OpenULINK command");
553                             free(payload);
554                             return ERROR_FAIL;
555                     } else {
556                             ulink_cmd->payload_in_start = payload;
557                             ulink_cmd->payload_in = payload;
558                             ulink_cmd->payload_in_size = size;
559
560                                 /* By default, free payload_in_start in ulink_clear_queue(). Commands
561                                  * that do not want this behavior (e. g. split scans) must turn it off
562                                  * separately! */
563                             ulink_cmd->free_payload_in_start = true;
564                     }
565                     break;
566         }
567
568         return ERROR_OK;
569 }
570
571 /****************** OpenULINK command queue helper functions ******************/
572
573 /**
574  * Get the current number of bytes in the queue, including command IDs.
575  *
576  * @param device pointer to struct ulink identifying ULINK driver instance.
577  * @param direction the transfer direction for which to get byte count.
578  * @return the number of bytes currently stored in the queue for the specified
579  *  direction.
580  */
581 static int ulink_get_queue_size(struct ulink *device,
582         enum ulink_payload_direction direction)
583 {
584         struct ulink_cmd *current = device->queue_start;
585         int sum = 0;
586
587         while (current) {
588                 switch (direction) {
589                     case PAYLOAD_DIRECTION_OUT:
590                             sum += current->payload_out_size + 1;       /* + 1 byte for Command ID */
591                             break;
592                     case PAYLOAD_DIRECTION_IN:
593                             sum += current->payload_in_size;
594                             break;
595                 }
596
597                 current = current->next;
598         }
599
600         return sum;
601 }
602
603 /**
604  * Clear the OpenULINK command queue.
605  *
606  * @param device pointer to struct ulink identifying ULINK driver instance.
607  * @return on success: ERROR_OK
608  * @return on failure: ERROR_FAIL
609  */
610 static void ulink_clear_queue(struct ulink *device)
611 {
612         struct ulink_cmd *current = device->queue_start;
613         struct ulink_cmd *next = NULL;
614
615         while (current) {
616                 /* Save pointer to next element */
617                 next = current->next;
618
619                 /* Free payloads: OUT payload can be freed immediately */
620                 free(current->payload_out);
621                 current->payload_out = NULL;
622
623                 /* IN payload MUST be freed ONLY if no other commands use the
624                  * payload_in_start buffer */
625                 if (current->free_payload_in_start == true) {
626                         free(current->payload_in_start);
627                         current->payload_in_start = NULL;
628                         current->payload_in = NULL;
629                 }
630
631                 /* Free queue element */
632                 free(current);
633
634                 /* Proceed with next element */
635                 current = next;
636         }
637
638         device->commands_in_queue = 0;
639         device->queue_start = NULL;
640         device->queue_end = NULL;
641 }
642
643 /**
644  * Add a command to the OpenULINK command queue.
645  *
646  * @param device pointer to struct ulink identifying ULINK driver instance.
647  * @param ulink_cmd pointer to command that shall be appended to the OpenULINK
648  *  command queue.
649  * @return on success: ERROR_OK
650  * @return on failure: ERROR_FAIL
651  */
652 static int ulink_append_queue(struct ulink *device, struct ulink_cmd *ulink_cmd)
653 {
654         int newsize_out, newsize_in;
655         int ret = ERROR_OK;
656
657         newsize_out = ulink_get_queue_size(device, PAYLOAD_DIRECTION_OUT) + 1
658                 + ulink_cmd->payload_out_size;
659
660         newsize_in = ulink_get_queue_size(device, PAYLOAD_DIRECTION_IN)
661                 + ulink_cmd->payload_in_size;
662
663         /* Check if the current command can be appended to the queue */
664         if ((newsize_out > 64) || (newsize_in > 64)) {
665                 /* New command does not fit. Execute all commands in queue before starting
666                  * new queue with the current command as first entry. */
667                 ret = ulink_execute_queued_commands(device, USB_TIMEOUT);
668
669                 if (ret == ERROR_OK)
670                         ret = ulink_post_process_queue(device);
671
672                 if (ret == ERROR_OK)
673                         ulink_clear_queue(device);
674         }
675
676         if (!device->queue_start) {
677                 /* Queue was empty */
678                 device->commands_in_queue = 1;
679
680                 device->queue_start = ulink_cmd;
681                 device->queue_end = ulink_cmd;
682         } else {
683                 /* There are already commands in the queue */
684                 device->commands_in_queue++;
685
686                 device->queue_end->next = ulink_cmd;
687                 device->queue_end = ulink_cmd;
688         }
689
690         if (ret != ERROR_OK)
691                 ulink_clear_queue(device);
692
693         return ret;
694 }
695
696 /**
697  * Sends all queued OpenULINK commands to the ULINK for execution.
698  *
699  * @param device pointer to struct ulink identifying ULINK driver instance.
700  * @param timeout
701  * @return on success: ERROR_OK
702  * @return on failure: ERROR_FAIL
703  */
704 static int ulink_execute_queued_commands(struct ulink *device, int timeout)
705 {
706         struct ulink_cmd *current;
707         int ret, i, index_out, index_in, count_out, count_in, transferred;
708         uint8_t buffer[64];
709
710         if (LOG_LEVEL_IS(LOG_LVL_DEBUG_IO))
711                 ulink_print_queue(device);
712
713         index_out = 0;
714         count_out = 0;
715         count_in = 0;
716
717         for (current = device->queue_start; current; current = current->next) {
718                 /* Add command to packet */
719                 buffer[index_out] = current->id;
720                 index_out++;
721                 count_out++;
722
723                 for (i = 0; i < current->payload_out_size; i++)
724                         buffer[index_out + i] = current->payload_out[i];
725                 index_out += current->payload_out_size;
726                 count_in += current->payload_in_size;
727                 count_out += current->payload_out_size;
728         }
729
730         /* Send packet to ULINK */
731         ret = libusb_bulk_transfer(device->usb_device_handle, device->ep_out,
732                         (unsigned char *)buffer, count_out, &transferred, timeout);
733         if (ret != 0)
734                 return ERROR_FAIL;
735         if (transferred != count_out)
736                 return ERROR_FAIL;
737
738         /* Wait for response if commands contain IN payload data */
739         if (count_in > 0) {
740                 ret = libusb_bulk_transfer(device->usb_device_handle, device->ep_in,
741                                 (unsigned char *)buffer, 64, &transferred, timeout);
742                 if (ret != 0)
743                         return ERROR_FAIL;
744                 if (transferred != count_in)
745                         return ERROR_FAIL;
746
747                 /* Write back IN payload data */
748                 index_in = 0;
749                 for (current = device->queue_start; current; current = current->next) {
750                         for (i = 0; i < current->payload_in_size; i++) {
751                                 current->payload_in[i] = buffer[index_in];
752                                 index_in++;
753                         }
754                 }
755         }
756
757         return ERROR_OK;
758 }
759
760 /**
761  * Convert an OpenULINK command ID (\a id) to a human-readable string.
762  *
763  * @param id the OpenULINK command ID.
764  * @return the corresponding human-readable string.
765  */
766 static const char *ulink_cmd_id_string(uint8_t id)
767 {
768         switch (id) {
769         case CMD_SCAN_IN:
770                 return "CMD_SCAN_IN";
771         case CMD_SLOW_SCAN_IN:
772                 return "CMD_SLOW_SCAN_IN";
773         case CMD_SCAN_OUT:
774                 return "CMD_SCAN_OUT";
775         case CMD_SLOW_SCAN_OUT:
776                 return "CMD_SLOW_SCAN_OUT";
777         case CMD_SCAN_IO:
778                 return "CMD_SCAN_IO";
779         case CMD_SLOW_SCAN_IO:
780                 return "CMD_SLOW_SCAN_IO";
781         case CMD_CLOCK_TMS:
782                 return "CMD_CLOCK_TMS";
783         case CMD_SLOW_CLOCK_TMS:
784                 return "CMD_SLOW_CLOCK_TMS";
785         case CMD_CLOCK_TCK:
786                 return "CMD_CLOCK_TCK";
787         case CMD_SLOW_CLOCK_TCK:
788                 return "CMD_SLOW_CLOCK_TCK";
789         case CMD_SLEEP_US:
790                 return "CMD_SLEEP_US";
791         case CMD_SLEEP_MS:
792                 return "CMD_SLEEP_MS";
793         case CMD_GET_SIGNALS:
794                 return "CMD_GET_SIGNALS";
795         case CMD_SET_SIGNALS:
796                 return "CMD_SET_SIGNALS";
797         case CMD_CONFIGURE_TCK_FREQ:
798                 return "CMD_CONFIGURE_TCK_FREQ";
799         case CMD_SET_LEDS:
800                 return "CMD_SET_LEDS";
801         case CMD_TEST:
802                 return "CMD_TEST";
803         default:
804                 return "CMD_UNKNOWN";
805         }
806 }
807
808 /**
809  * Print one OpenULINK command to stdout.
810  *
811  * @param ulink_cmd pointer to OpenULINK command.
812  */
813 static void ulink_print_command(struct ulink_cmd *ulink_cmd)
814 {
815         int i;
816
817         printf("  %-22s | OUT size = %i, bytes = 0x",
818                 ulink_cmd_id_string(ulink_cmd->id), ulink_cmd->payload_out_size);
819
820         for (i = 0; i < ulink_cmd->payload_out_size; i++)
821                 printf("%02X ", ulink_cmd->payload_out[i]);
822         printf("\n                         | IN size  = %i\n",
823                 ulink_cmd->payload_in_size);
824 }
825
826 /**
827  * Print the OpenULINK command queue to stdout.
828  *
829  * @param device pointer to struct ulink identifying ULINK driver instance.
830  */
831 static void ulink_print_queue(struct ulink *device)
832 {
833         struct ulink_cmd *current;
834
835         printf("OpenULINK command queue:\n");
836
837         for (current = device->queue_start; current; current = current->next)
838                 ulink_print_command(current);
839 }
840
841 /**
842  * Perform JTAG scan
843  *
844  * Creates and appends a JTAG scan command to the OpenULINK command queue.
845  * A JTAG scan consists of three steps:
846  * - Move to the desired SHIFT state, depending on scan type (IR/DR scan).
847  * - Shift TDI data into the JTAG chain, optionally reading the TDO pin.
848  * - Move to the desired end state.
849  *
850  * @param device pointer to struct ulink identifying ULINK driver instance.
851  * @param scan_type the type of the scan (IN, OUT, IO (bidirectional)).
852  * @param scan_size_bits number of bits to shift into the JTAG chain.
853  * @param tdi pointer to array containing TDI data.
854  * @param tdo_start pointer to first element of array where TDO data shall be
855  *  stored. See #ulink_cmd for details.
856  * @param tdo pointer to array where TDO data shall be stored
857  * @param tms_count_start number of TMS state transitions to perform BEFORE
858  *  shifting data into the JTAG chain.
859  * @param tms_sequence_start sequence of TMS state transitions that will be
860  *  performed BEFORE shifting data into the JTAG chain.
861  * @param tms_count_end number of TMS state transitions to perform AFTER
862  *  shifting data into the JTAG chain.
863  * @param tms_sequence_end sequence of TMS state transitions that will be
864  *  performed AFTER shifting data into the JTAG chain.
865  * @param origin pointer to OpenOCD command that generated this scan command.
866  * @param postprocess whether this command needs to be post-processed after
867  *  execution.
868  * @return on success: ERROR_OK
869  * @return on failure: ERROR_FAIL
870  */
871 static int ulink_append_scan_cmd(struct ulink *device, enum scan_type scan_type,
872         int scan_size_bits, uint8_t *tdi, uint8_t *tdo_start, uint8_t *tdo,
873         uint8_t tms_count_start, uint8_t tms_sequence_start, uint8_t tms_count_end,
874         uint8_t tms_sequence_end, struct jtag_command *origin, bool postprocess)
875 {
876         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
877         int ret, i, scan_size_bytes;
878         uint8_t bits_last_byte;
879
880         if (!cmd)
881                 return ERROR_FAIL;
882
883         /* Check size of command. USB buffer can hold 64 bytes, 1 byte is command ID,
884          * 5 bytes are setup data -> 58 remaining payload bytes for TDI data */
885         if (scan_size_bits > (58 * 8)) {
886                 LOG_ERROR("BUG: Tried to create CMD_SCAN_IO OpenULINK command with too"
887                         " large payload");
888                 free(cmd);
889                 return ERROR_FAIL;
890         }
891
892         scan_size_bytes = DIV_ROUND_UP(scan_size_bits, 8);
893
894         bits_last_byte = scan_size_bits % 8;
895         if (bits_last_byte == 0)
896                 bits_last_byte = 8;
897
898         /* Allocate out_payload depending on scan type */
899         switch (scan_type) {
900             case SCAN_IN:
901                     if (device->delay_scan_in < 0)
902                             cmd->id = CMD_SCAN_IN;
903                     else
904                             cmd->id = CMD_SLOW_SCAN_IN;
905                     ret = ulink_allocate_payload(cmd, 5, PAYLOAD_DIRECTION_OUT);
906                     break;
907             case SCAN_OUT:
908                     if (device->delay_scan_out < 0)
909                             cmd->id = CMD_SCAN_OUT;
910                     else
911                             cmd->id = CMD_SLOW_SCAN_OUT;
912                     ret = ulink_allocate_payload(cmd, scan_size_bytes + 5, PAYLOAD_DIRECTION_OUT);
913                     break;
914             case SCAN_IO:
915                     if (device->delay_scan_io < 0)
916                             cmd->id = CMD_SCAN_IO;
917                     else
918                             cmd->id = CMD_SLOW_SCAN_IO;
919                     ret = ulink_allocate_payload(cmd, scan_size_bytes + 5, PAYLOAD_DIRECTION_OUT);
920                     break;
921             default:
922                     LOG_ERROR("BUG: ulink_append_scan_cmd() encountered an unknown scan type");
923                     ret = ERROR_FAIL;
924                     break;
925         }
926
927         if (ret != ERROR_OK) {
928                 free(cmd);
929                 return ret;
930         }
931
932         /* Build payload_out that is common to all scan types */
933         cmd->payload_out[0] = scan_size_bytes & 0xFF;
934         cmd->payload_out[1] = bits_last_byte & 0xFF;
935         cmd->payload_out[2] = ((tms_count_start & 0x0F) << 4) | (tms_count_end & 0x0F);
936         cmd->payload_out[3] = tms_sequence_start;
937         cmd->payload_out[4] = tms_sequence_end;
938
939         /* Setup payload_out for types with OUT transfer */
940         if ((scan_type == SCAN_OUT) || (scan_type == SCAN_IO)) {
941                 for (i = 0; i < scan_size_bytes; i++)
942                         cmd->payload_out[i + 5] = tdi[i];
943         }
944
945         /* Setup payload_in pointers for types with IN transfer */
946         if ((scan_type == SCAN_IN) || (scan_type == SCAN_IO)) {
947                 cmd->payload_in_start = tdo_start;
948                 cmd->payload_in = tdo;
949                 cmd->payload_in_size = scan_size_bytes;
950         }
951
952         cmd->needs_postprocessing = postprocess;
953         cmd->cmd_origin = origin;
954
955         /* For scan commands, we free payload_in_start only when the command is
956          * the last in a series of split commands or a stand-alone command */
957         cmd->free_payload_in_start = postprocess;
958
959         return ulink_append_queue(device, cmd);
960 }
961
962 /**
963  * Perform TAP state transitions
964  *
965  * @param device pointer to struct ulink identifying ULINK driver instance.
966  * @param count defines the number of TCK clock cycles generated (up to 8).
967  * @param sequence defines the TMS pin levels for each state transition. The
968  *  Least-Significant Bit is read first.
969  * @return on success: ERROR_OK
970  * @return on failure: ERROR_FAIL
971  */
972 static int ulink_append_clock_tms_cmd(struct ulink *device, uint8_t count,
973         uint8_t sequence)
974 {
975         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
976         int ret;
977
978         if (!cmd)
979                 return ERROR_FAIL;
980
981         if (device->delay_clock_tms < 0)
982                 cmd->id = CMD_CLOCK_TMS;
983         else
984                 cmd->id = CMD_SLOW_CLOCK_TMS;
985
986         /* CMD_CLOCK_TMS has two OUT payload bytes and zero IN payload bytes */
987         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
988         if (ret != ERROR_OK) {
989                 free(cmd);
990                 return ret;
991         }
992
993         cmd->payload_out[0] = count;
994         cmd->payload_out[1] = sequence;
995
996         return ulink_append_queue(device, cmd);
997 }
998
999 /**
1000  * Generate a defined amount of TCK clock cycles
1001  *
1002  * All other JTAG signals are left unchanged.
1003  *
1004  * @param device pointer to struct ulink identifying ULINK driver instance.
1005  * @param count the number of TCK clock cycles to generate.
1006  * @return on success: ERROR_OK
1007  * @return on failure: ERROR_FAIL
1008  */
1009 static int ulink_append_clock_tck_cmd(struct ulink *device, uint16_t count)
1010 {
1011         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1012         int ret;
1013
1014         if (!cmd)
1015                 return ERROR_FAIL;
1016
1017         if (device->delay_clock_tck < 0)
1018                 cmd->id = CMD_CLOCK_TCK;
1019         else
1020                 cmd->id = CMD_SLOW_CLOCK_TCK;
1021
1022         /* CMD_CLOCK_TCK has two OUT payload bytes and zero IN payload bytes */
1023         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1024         if (ret != ERROR_OK) {
1025                 free(cmd);
1026                 return ret;
1027         }
1028
1029         cmd->payload_out[0] = count & 0xff;
1030         cmd->payload_out[1] = (count >> 8) & 0xff;
1031
1032         return ulink_append_queue(device, cmd);
1033 }
1034
1035 /**
1036  * Read JTAG signals.
1037  *
1038  * @param device pointer to struct ulink identifying ULINK driver instance.
1039  * @return on success: ERROR_OK
1040  * @return on failure: ERROR_FAIL
1041  */
1042 static int ulink_append_get_signals_cmd(struct ulink *device)
1043 {
1044         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1045         int ret;
1046
1047         if (!cmd)
1048                 return ERROR_FAIL;
1049
1050         cmd->id = CMD_GET_SIGNALS;
1051         cmd->needs_postprocessing = true;
1052
1053         /* CMD_GET_SIGNALS has two IN payload bytes */
1054         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_IN);
1055
1056         if (ret != ERROR_OK) {
1057                 free(cmd);
1058                 return ret;
1059         }
1060
1061         return ulink_append_queue(device, cmd);
1062 }
1063
1064 /**
1065  * Arbitrarily set JTAG output signals.
1066  *
1067  * @param device pointer to struct ulink identifying ULINK driver instance.
1068  * @param low defines which signals will be de-asserted. Each bit corresponds
1069  *  to a JTAG signal:
1070  *  - SIGNAL_TDI
1071  *  - SIGNAL_TMS
1072  *  - SIGNAL_TCK
1073  *  - SIGNAL_TRST
1074  *  - SIGNAL_BRKIN
1075  *  - SIGNAL_RESET
1076  *  - SIGNAL_OCDSE
1077  * @param high defines which signals will be asserted.
1078  * @return on success: ERROR_OK
1079  * @return on failure: ERROR_FAIL
1080  */
1081 static int ulink_append_set_signals_cmd(struct ulink *device, uint8_t low,
1082         uint8_t high)
1083 {
1084         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1085         int ret;
1086
1087         if (!cmd)
1088                 return ERROR_FAIL;
1089
1090         cmd->id = CMD_SET_SIGNALS;
1091
1092         /* CMD_SET_SIGNALS has two OUT payload bytes and zero IN payload bytes */
1093         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1094
1095         if (ret != ERROR_OK) {
1096                 free(cmd);
1097                 return ret;
1098         }
1099
1100         cmd->payload_out[0] = low;
1101         cmd->payload_out[1] = high;
1102
1103         return ulink_append_queue(device, cmd);
1104 }
1105
1106 /**
1107  * Sleep for a pre-defined number of microseconds
1108  *
1109  * @param device pointer to struct ulink identifying ULINK driver instance.
1110  * @param us the number microseconds to sleep.
1111  * @return on success: ERROR_OK
1112  * @return on failure: ERROR_FAIL
1113  */
1114 static int ulink_append_sleep_cmd(struct ulink *device, uint32_t us)
1115 {
1116         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1117         int ret;
1118
1119         if (!cmd)
1120                 return ERROR_FAIL;
1121
1122         cmd->id = CMD_SLEEP_US;
1123
1124         /* CMD_SLEEP_US has two OUT payload bytes and zero IN payload bytes */
1125         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1126
1127         if (ret != ERROR_OK) {
1128                 free(cmd);
1129                 return ret;
1130         }
1131
1132         cmd->payload_out[0] = us & 0x00ff;
1133         cmd->payload_out[1] = (us >> 8) & 0x00ff;
1134
1135         return ulink_append_queue(device, cmd);
1136 }
1137
1138 /**
1139  * Set TCK delay counters
1140  *
1141  * @param device pointer to struct ulink identifying ULINK driver instance.
1142  * @param delay_scan_in delay count top value in jtag_slow_scan_in() function.
1143  * @param delay_scan_out delay count top value in jtag_slow_scan_out() function.
1144  * @param delay_scan_io delay count top value in jtag_slow_scan_io() function.
1145  * @param delay_tck delay count top value in jtag_clock_tck() function.
1146  * @param delay_tms delay count top value in jtag_slow_clock_tms() function.
1147  * @return on success: ERROR_OK
1148  * @return on failure: ERROR_FAIL
1149  */
1150 static int ulink_append_configure_tck_cmd(struct ulink *device, int delay_scan_in,
1151         int delay_scan_out, int delay_scan_io, int delay_tck, int delay_tms)
1152 {
1153         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1154         int ret;
1155
1156         if (!cmd)
1157                 return ERROR_FAIL;
1158
1159         cmd->id = CMD_CONFIGURE_TCK_FREQ;
1160
1161         /* CMD_CONFIGURE_TCK_FREQ has five OUT payload bytes and zero
1162          * IN payload bytes */
1163         ret = ulink_allocate_payload(cmd, 5, PAYLOAD_DIRECTION_OUT);
1164         if (ret != ERROR_OK) {
1165                 free(cmd);
1166                 return ret;
1167         }
1168
1169         if (delay_scan_in < 0)
1170                 cmd->payload_out[0] = 0;
1171         else
1172                 cmd->payload_out[0] = (uint8_t)delay_scan_in;
1173
1174         if (delay_scan_out < 0)
1175                 cmd->payload_out[1] = 0;
1176         else
1177                 cmd->payload_out[1] = (uint8_t)delay_scan_out;
1178
1179         if (delay_scan_io < 0)
1180                 cmd->payload_out[2] = 0;
1181         else
1182                 cmd->payload_out[2] = (uint8_t)delay_scan_io;
1183
1184         if (delay_tck < 0)
1185                 cmd->payload_out[3] = 0;
1186         else
1187                 cmd->payload_out[3] = (uint8_t)delay_tck;
1188
1189         if (delay_tms < 0)
1190                 cmd->payload_out[4] = 0;
1191         else
1192                 cmd->payload_out[4] = (uint8_t)delay_tms;
1193
1194         return ulink_append_queue(device, cmd);
1195 }
1196
1197 /**
1198  * Turn on/off ULINK LEDs.
1199  *
1200  * @param device pointer to struct ulink identifying ULINK driver instance.
1201  * @param led_state which LED(s) to turn on or off. The following bits
1202  *  influence the LEDS:
1203  *  - Bit 0: Turn COM LED on
1204  *  - Bit 1: Turn RUN LED on
1205  *  - Bit 2: Turn COM LED off
1206  *  - Bit 3: Turn RUN LED off
1207  *  If both the on-bit and the off-bit for the same LED is set, the LED is
1208  *  turned off.
1209  * @return on success: ERROR_OK
1210  * @return on failure: ERROR_FAIL
1211  */
1212 static int ulink_append_led_cmd(struct ulink *device, uint8_t led_state)
1213 {
1214         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1215         int ret;
1216
1217         if (!cmd)
1218                 return ERROR_FAIL;
1219
1220         cmd->id = CMD_SET_LEDS;
1221
1222         /* CMD_SET_LEDS has one OUT payload byte and zero IN payload bytes */
1223         ret = ulink_allocate_payload(cmd, 1, PAYLOAD_DIRECTION_OUT);
1224         if (ret != ERROR_OK) {
1225                 free(cmd);
1226                 return ret;
1227         }
1228
1229         cmd->payload_out[0] = led_state;
1230
1231         return ulink_append_queue(device, cmd);
1232 }
1233
1234 /**
1235  * Test command. Used to check if the ULINK device is ready to accept new
1236  * commands.
1237  *
1238  * @param device pointer to struct ulink identifying ULINK driver instance.
1239  * @return on success: ERROR_OK
1240  * @return on failure: ERROR_FAIL
1241  */
1242 static int ulink_append_test_cmd(struct ulink *device)
1243 {
1244         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1245         int ret;
1246
1247         if (!cmd)
1248                 return ERROR_FAIL;
1249
1250         cmd->id = CMD_TEST;
1251
1252         /* CMD_TEST has one OUT payload byte and zero IN payload bytes */
1253         ret = ulink_allocate_payload(cmd, 1, PAYLOAD_DIRECTION_OUT);
1254         if (ret != ERROR_OK) {
1255                 free(cmd);
1256                 return ret;
1257         }
1258
1259         cmd->payload_out[0] = 0xAA;
1260
1261         return ulink_append_queue(device, cmd);
1262 }
1263
1264 /****************** OpenULINK TCK frequency helper functions ******************/
1265
1266 /**
1267  * Calculate delay values for a given TCK frequency.
1268  *
1269  * The OpenULINK firmware uses five different speed values for different
1270  * commands. These speed values are calculated in these functions.
1271  *
1272  * The five different commands which support variable TCK frequency are
1273  * implemented twice in the firmware:
1274  *   1. Maximum possible frequency without any artificial delay
1275  *   2. Variable frequency with artificial linear delay loop
1276  *
1277  * To set the ULINK to maximum frequency, it is only necessary to use the
1278  * corresponding command IDs. To set the ULINK to a lower frequency, the
1279  * delay loop top values have to be calculated first. Then, a
1280  * CMD_CONFIGURE_TCK_FREQ command needs to be sent to the ULINK device.
1281  *
1282  * The delay values are described by linear equations:
1283  *    t = k * x + d
1284  *    (t = period, k = constant, x = delay value, d = constant)
1285  *
1286  * Thus, the delay can be calculated as in the following equation:
1287  *    x = (t - d) / k
1288  *
1289  * The constants in these equations have been determined and validated by
1290  * measuring the frequency resulting from different delay values.
1291  *
1292  * @param type for which command to calculate the delay value.
1293  * @param f TCK frequency for which to calculate the delay value in Hz.
1294  * @param delay where to store resulting delay value.
1295  * @return on success: ERROR_OK
1296  * @return on failure: ERROR_FAIL
1297  */
1298 static int ulink_calculate_delay(enum ulink_delay_type type, long f, int *delay)
1299 {
1300         float t, x, x_ceil;
1301
1302         /* Calculate period of requested TCK frequency */
1303         t = 1.0 / (float)(f);
1304
1305         switch (type) {
1306             case DELAY_CLOCK_TCK:
1307                     x = (t - (float)(6E-6)) / (float)(4E-6);
1308                     break;
1309             case DELAY_CLOCK_TMS:
1310                     x = (t - (float)(8.5E-6)) / (float)(4E-6);
1311                     break;
1312             case DELAY_SCAN_IN:
1313                     x = (t - (float)(8.8308E-6)) / (float)(4E-6);
1314                     break;
1315             case DELAY_SCAN_OUT:
1316                     x = (t - (float)(1.0527E-5)) / (float)(4E-6);
1317                     break;
1318             case DELAY_SCAN_IO:
1319                     x = (t - (float)(1.3132E-5)) / (float)(4E-6);
1320                     break;
1321             default:
1322                     return ERROR_FAIL;
1323                     break;
1324         }
1325
1326         /* Check if the delay value is negative. This happens when a frequency is
1327          * requested that is too high for the delay loop implementation. In this
1328          * case, set delay value to zero. */
1329         if (x < 0)
1330                 x = 0;
1331
1332         /* We need to convert the exact delay value to an integer. Therefore, we
1333          * round the exact value UP to ensure that the resulting frequency is NOT
1334          * higher than the requested frequency. */
1335         x_ceil = ceilf(x);
1336
1337         /* Check if the value is within limits */
1338         if (x_ceil > 255)
1339                 return ERROR_FAIL;
1340
1341         *delay = (int)x_ceil;
1342
1343         return ERROR_OK;
1344 }
1345
1346 /**
1347  * Calculate frequency for a given delay value.
1348  *
1349  * Similar to the #ulink_calculate_delay function, this function calculates the
1350  * TCK frequency for a given delay value by using linear equations of the form:
1351  *    t = k * x + d
1352  *    (t = period, k = constant, x = delay value, d = constant)
1353  *
1354  * @param type for which command to calculate the delay value.
1355  * @param delay delay value for which to calculate the resulting TCK frequency.
1356  * @return the resulting TCK frequency
1357  */
1358 static long ulink_calculate_frequency(enum ulink_delay_type type, int delay)
1359 {
1360         float t, f_float;
1361
1362         if (delay > 255)
1363                 return 0;
1364
1365         switch (type) {
1366             case DELAY_CLOCK_TCK:
1367                     if (delay < 0)
1368                             t = (float)(2.666E-6);
1369                     else
1370                             t = (float)(4E-6) * (float)(delay) + (float)(6E-6);
1371                     break;
1372             case DELAY_CLOCK_TMS:
1373                     if (delay < 0)
1374                             t = (float)(5.666E-6);
1375                     else
1376                             t = (float)(4E-6) * (float)(delay) + (float)(8.5E-6);
1377                     break;
1378             case DELAY_SCAN_IN:
1379                     if (delay < 0)
1380                             t = (float)(5.5E-6);
1381                     else
1382                             t = (float)(4E-6) * (float)(delay) + (float)(8.8308E-6);
1383                     break;
1384             case DELAY_SCAN_OUT:
1385                     if (delay < 0)
1386                             t = (float)(7.0E-6);
1387                     else
1388                             t = (float)(4E-6) * (float)(delay) + (float)(1.0527E-5);
1389                     break;
1390             case DELAY_SCAN_IO:
1391                     if (delay < 0)
1392                             t = (float)(9.926E-6);
1393                     else
1394                             t = (float)(4E-6) * (float)(delay) + (float)(1.3132E-5);
1395                     break;
1396             default:
1397                     return 0;
1398         }
1399
1400         f_float = 1.0 / t;
1401         return roundf(f_float);
1402 }
1403
1404 /******************* Interface between OpenULINK and OpenOCD ******************/
1405
1406 /**
1407  * Sets the end state follower (see interface.h) if \a endstate is a stable
1408  * state.
1409  *
1410  * @param endstate the state the end state follower should be set to.
1411  */
1412 static void ulink_set_end_state(tap_state_t endstate)
1413 {
1414         if (tap_is_state_stable(endstate))
1415                 tap_set_end_state(endstate);
1416         else {
1417                 LOG_ERROR("BUG: %s is not a valid end state", tap_state_name(endstate));
1418                 exit(EXIT_FAILURE);
1419         }
1420 }
1421
1422 /**
1423  * Move from the current TAP state to the current TAP end state.
1424  *
1425  * @param device pointer to struct ulink identifying ULINK driver instance.
1426  * @return on success: ERROR_OK
1427  * @return on failure: ERROR_FAIL
1428  */
1429 static int ulink_queue_statemove(struct ulink *device)
1430 {
1431         uint8_t tms_sequence, tms_count;
1432         int ret;
1433
1434         if (tap_get_state() == tap_get_end_state()) {
1435                 /* Do nothing if we are already there */
1436                 return ERROR_OK;
1437         }
1438
1439         tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1440         tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1441
1442         ret = ulink_append_clock_tms_cmd(device, tms_count, tms_sequence);
1443
1444         if (ret == ERROR_OK)
1445                 tap_set_state(tap_get_end_state());
1446
1447         return ret;
1448 }
1449
1450 /**
1451  * Perform a scan operation on a JTAG register.
1452  *
1453  * @param device pointer to struct ulink identifying ULINK driver instance.
1454  * @param cmd pointer to the command that shall be executed.
1455  * @return on success: ERROR_OK
1456  * @return on failure: ERROR_FAIL
1457  */
1458 static int ulink_queue_scan(struct ulink *device, struct jtag_command *cmd)
1459 {
1460         uint32_t scan_size_bits, scan_size_bytes, bits_last_scan;
1461         uint32_t scans_max_payload, bytecount;
1462         uint8_t *tdi_buffer_start = NULL, *tdi_buffer = NULL;
1463         uint8_t *tdo_buffer_start = NULL, *tdo_buffer = NULL;
1464
1465         uint8_t first_tms_count, first_tms_sequence;
1466         uint8_t last_tms_count, last_tms_sequence;
1467
1468         uint8_t tms_count_pause, tms_sequence_pause;
1469         uint8_t tms_count_resume, tms_sequence_resume;
1470
1471         uint8_t tms_count_start, tms_sequence_start;
1472         uint8_t tms_count_end, tms_sequence_end;
1473
1474         enum scan_type type;
1475         int ret;
1476
1477         /* Determine scan size */
1478         scan_size_bits = jtag_scan_size(cmd->cmd.scan);
1479         scan_size_bytes = DIV_ROUND_UP(scan_size_bits, 8);
1480
1481         /* Determine scan type (IN/OUT/IO) */
1482         type = jtag_scan_type(cmd->cmd.scan);
1483
1484         /* Determine number of scan commands with maximum payload */
1485         scans_max_payload = scan_size_bytes / 58;
1486
1487         /* Determine size of last shift command */
1488         bits_last_scan = scan_size_bits - (scans_max_payload * 58 * 8);
1489
1490         /* Allocate TDO buffer if required */
1491         if ((type == SCAN_IN) || (type == SCAN_IO)) {
1492                 tdo_buffer_start = calloc(sizeof(uint8_t), scan_size_bytes);
1493
1494                 if (!tdo_buffer_start)
1495                         return ERROR_FAIL;
1496
1497                 tdo_buffer = tdo_buffer_start;
1498         }
1499
1500         /* Fill TDI buffer if required */
1501         if ((type == SCAN_OUT) || (type == SCAN_IO)) {
1502                 jtag_build_buffer(cmd->cmd.scan, &tdi_buffer_start);
1503                 tdi_buffer = tdi_buffer_start;
1504         }
1505
1506         /* Get TAP state transitions */
1507         if (cmd->cmd.scan->ir_scan) {
1508                 ulink_set_end_state(TAP_IRSHIFT);
1509                 first_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1510                 first_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1511
1512                 tap_set_state(TAP_IRSHIFT);
1513                 tap_set_end_state(cmd->cmd.scan->end_state);
1514                 last_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1515                 last_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1516
1517                 /* TAP state transitions for split scans */
1518                 tms_count_pause = tap_get_tms_path_len(TAP_IRSHIFT, TAP_IRPAUSE);
1519                 tms_sequence_pause = tap_get_tms_path(TAP_IRSHIFT, TAP_IRPAUSE);
1520                 tms_count_resume = tap_get_tms_path_len(TAP_IRPAUSE, TAP_IRSHIFT);
1521                 tms_sequence_resume = tap_get_tms_path(TAP_IRPAUSE, TAP_IRSHIFT);
1522         } else {
1523                 ulink_set_end_state(TAP_DRSHIFT);
1524                 first_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1525                 first_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1526
1527                 tap_set_state(TAP_DRSHIFT);
1528                 tap_set_end_state(cmd->cmd.scan->end_state);
1529                 last_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1530                 last_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1531
1532                 /* TAP state transitions for split scans */
1533                 tms_count_pause = tap_get_tms_path_len(TAP_DRSHIFT, TAP_DRPAUSE);
1534                 tms_sequence_pause = tap_get_tms_path(TAP_DRSHIFT, TAP_DRPAUSE);
1535                 tms_count_resume = tap_get_tms_path_len(TAP_DRPAUSE, TAP_DRSHIFT);
1536                 tms_sequence_resume = tap_get_tms_path(TAP_DRPAUSE, TAP_DRSHIFT);
1537         }
1538
1539         /* Generate scan commands */
1540         bytecount = scan_size_bytes;
1541         while (bytecount > 0) {
1542                 if (bytecount == scan_size_bytes) {
1543                         /* This is the first scan */
1544                         tms_count_start = first_tms_count;
1545                         tms_sequence_start = first_tms_sequence;
1546                 } else {
1547                         /* Resume from previous scan */
1548                         tms_count_start = tms_count_resume;
1549                         tms_sequence_start = tms_sequence_resume;
1550                 }
1551
1552                 if (bytecount > 58) {   /* Full scan, at least one scan will follow */
1553                         tms_count_end = tms_count_pause;
1554                         tms_sequence_end = tms_sequence_pause;
1555
1556                         ret = ulink_append_scan_cmd(device,
1557                                         type,
1558                                         58 * 8,
1559                                         tdi_buffer,
1560                                         tdo_buffer_start,
1561                                         tdo_buffer,
1562                                         tms_count_start,
1563                                         tms_sequence_start,
1564                                         tms_count_end,
1565                                         tms_sequence_end,
1566                                         cmd,
1567                                         false);
1568
1569                         bytecount -= 58;
1570
1571                         /* Update TDI and TDO buffer pointers */
1572                         if (tdi_buffer_start)
1573                                 tdi_buffer += 58;
1574                         if (tdo_buffer_start)
1575                                 tdo_buffer += 58;
1576                 } else if (bytecount == 58) {   /* Full scan, no further scans */
1577                         tms_count_end = last_tms_count;
1578                         tms_sequence_end = last_tms_sequence;
1579
1580                         ret = ulink_append_scan_cmd(device,
1581                                         type,
1582                                         58 * 8,
1583                                         tdi_buffer,
1584                                         tdo_buffer_start,
1585                                         tdo_buffer,
1586                                         tms_count_start,
1587                                         tms_sequence_start,
1588                                         tms_count_end,
1589                                         tms_sequence_end,
1590                                         cmd,
1591                                         true);
1592
1593                         bytecount = 0;
1594                 } else {/* Scan with less than maximum payload, no further scans */
1595                         tms_count_end = last_tms_count;
1596                         tms_sequence_end = last_tms_sequence;
1597
1598                         ret = ulink_append_scan_cmd(device,
1599                                         type,
1600                                         bits_last_scan,
1601                                         tdi_buffer,
1602                                         tdo_buffer_start,
1603                                         tdo_buffer,
1604                                         tms_count_start,
1605                                         tms_sequence_start,
1606                                         tms_count_end,
1607                                         tms_sequence_end,
1608                                         cmd,
1609                                         true);
1610
1611                         bytecount = 0;
1612                 }
1613
1614                 if (ret != ERROR_OK) {
1615                         free(tdi_buffer_start);
1616                         free(tdo_buffer_start);
1617                         return ret;
1618                 }
1619         }
1620
1621         free(tdi_buffer_start);
1622
1623         /* Set current state to the end state requested by the command */
1624         tap_set_state(cmd->cmd.scan->end_state);
1625
1626         return ERROR_OK;
1627 }
1628
1629 /**
1630  * Move the TAP into the Test Logic Reset state.
1631  *
1632  * @param device pointer to struct ulink identifying ULINK driver instance.
1633  * @param cmd pointer to the command that shall be executed.
1634  * @return on success: ERROR_OK
1635  * @return on failure: ERROR_FAIL
1636  */
1637 static int ulink_queue_tlr_reset(struct ulink *device, struct jtag_command *cmd)
1638 {
1639         int ret;
1640
1641         ret = ulink_append_clock_tms_cmd(device, 5, 0xff);
1642
1643         if (ret == ERROR_OK)
1644                 tap_set_state(TAP_RESET);
1645
1646         return ret;
1647 }
1648
1649 /**
1650  * Run Test.
1651  *
1652  * Generate TCK clock cycles while remaining
1653  * in the Run-Test/Idle state.
1654  *
1655  * @param device pointer to struct ulink identifying ULINK driver instance.
1656  * @param cmd pointer to the command that shall be executed.
1657  * @return on success: ERROR_OK
1658  * @return on failure: ERROR_FAIL
1659  */
1660 static int ulink_queue_runtest(struct ulink *device, struct jtag_command *cmd)
1661 {
1662         int ret;
1663
1664         /* Only perform statemove if the TAP currently isn't in the TAP_IDLE state */
1665         if (tap_get_state() != TAP_IDLE) {
1666                 ulink_set_end_state(TAP_IDLE);
1667                 ulink_queue_statemove(device);
1668         }
1669
1670         /* Generate the clock cycles */
1671         ret = ulink_append_clock_tck_cmd(device, cmd->cmd.runtest->num_cycles);
1672         if (ret != ERROR_OK)
1673                 return ret;
1674
1675         /* Move to end state specified in command */
1676         if (cmd->cmd.runtest->end_state != tap_get_state()) {
1677                 tap_set_end_state(cmd->cmd.runtest->end_state);
1678                 ulink_queue_statemove(device);
1679         }
1680
1681         return ERROR_OK;
1682 }
1683
1684 /**
1685  * Execute a JTAG_RESET command
1686  *
1687  * @param device
1688  * @param cmd pointer to the command that shall be executed.
1689  * @return on success: ERROR_OK
1690  * @return on failure: ERROR_FAIL
1691  */
1692 static int ulink_queue_reset(struct ulink *device, struct jtag_command *cmd)
1693 {
1694         uint8_t low = 0, high = 0;
1695
1696         if (cmd->cmd.reset->trst) {
1697                 tap_set_state(TAP_RESET);
1698                 high |= SIGNAL_TRST;
1699         } else
1700                 low |= SIGNAL_TRST;
1701
1702         if (cmd->cmd.reset->srst)
1703                 high |= SIGNAL_RESET;
1704         else
1705                 low |= SIGNAL_RESET;
1706
1707         return ulink_append_set_signals_cmd(device, low, high);
1708 }
1709
1710 /**
1711  * Move to one TAP state or several states in succession.
1712  *
1713  * @param device pointer to struct ulink identifying ULINK driver instance.
1714  * @param cmd pointer to the command that shall be executed.
1715  * @return on success: ERROR_OK
1716  * @return on failure: ERROR_FAIL
1717  */
1718 static int ulink_queue_pathmove(struct ulink *device, struct jtag_command *cmd)
1719 {
1720         int ret, i, num_states, batch_size, state_count;
1721         tap_state_t *path;
1722         uint8_t tms_sequence;
1723
1724         num_states = cmd->cmd.pathmove->num_states;
1725         path = cmd->cmd.pathmove->path;
1726         state_count = 0;
1727
1728         while (num_states > 0) {
1729                 tms_sequence = 0;
1730
1731                 /* Determine batch size */
1732                 if (num_states >= 8)
1733                         batch_size = 8;
1734                 else
1735                         batch_size = num_states;
1736
1737                 for (i = 0; i < batch_size; i++) {
1738                         if (tap_state_transition(tap_get_state(), false) == path[state_count]) {
1739                                 /* Append '0' transition: clear bit 'i' in tms_sequence */
1740                                 buf_set_u32(&tms_sequence, i, 1, 0x0);
1741                         } else if (tap_state_transition(tap_get_state(), true)
1742                                    == path[state_count]) {
1743                                 /* Append '1' transition: set bit 'i' in tms_sequence */
1744                                 buf_set_u32(&tms_sequence, i, 1, 0x1);
1745                         } else {
1746                                 /* Invalid state transition */
1747                                 LOG_ERROR("BUG: %s -> %s isn't a valid TAP state transition",
1748                                         tap_state_name(tap_get_state()),
1749                                         tap_state_name(path[state_count]));
1750                                 return ERROR_FAIL;
1751                         }
1752
1753                         tap_set_state(path[state_count]);
1754                         state_count++;
1755                         num_states--;
1756                 }
1757
1758                 /* Append CLOCK_TMS command to OpenULINK command queue */
1759                 LOG_INFO(
1760                         "pathmove batch: count = %i, sequence = 0x%x", batch_size, tms_sequence);
1761                 ret = ulink_append_clock_tms_cmd(ulink_handle, batch_size, tms_sequence);
1762                 if (ret != ERROR_OK)
1763                         return ret;
1764         }
1765
1766         return ERROR_OK;
1767 }
1768
1769 /**
1770  * Sleep for a specific amount of time.
1771  *
1772  * @param device pointer to struct ulink identifying ULINK driver instance.
1773  * @param cmd pointer to the command that shall be executed.
1774  * @return on success: ERROR_OK
1775  * @return on failure: ERROR_FAIL
1776  */
1777 static int ulink_queue_sleep(struct ulink *device, struct jtag_command *cmd)
1778 {
1779         /* IMPORTANT! Due to the time offset in command execution introduced by
1780          * command queueing, this needs to be implemented in the ULINK device */
1781         return ulink_append_sleep_cmd(device, cmd->cmd.sleep->us);
1782 }
1783
1784 /**
1785  * Generate TCK cycles while remaining in a stable state.
1786  *
1787  * @param device pointer to struct ulink identifying ULINK driver instance.
1788  * @param cmd pointer to the command that shall be executed.
1789  */
1790 static int ulink_queue_stableclocks(struct ulink *device, struct jtag_command *cmd)
1791 {
1792         int ret;
1793         unsigned num_cycles;
1794
1795         if (!tap_is_state_stable(tap_get_state())) {
1796                 LOG_ERROR("JTAG_STABLECLOCKS: state not stable");
1797                 return ERROR_FAIL;
1798         }
1799
1800         num_cycles = cmd->cmd.stableclocks->num_cycles;
1801
1802         /* TMS stays either high (Test Logic Reset state) or low (all other states) */
1803         if (tap_get_state() == TAP_RESET)
1804                 ret = ulink_append_set_signals_cmd(device, 0, SIGNAL_TMS);
1805         else
1806                 ret = ulink_append_set_signals_cmd(device, SIGNAL_TMS, 0);
1807
1808         if (ret != ERROR_OK)
1809                 return ret;
1810
1811         while (num_cycles > 0) {
1812                 if (num_cycles > 0xFFFF) {
1813                         /* OpenULINK CMD_CLOCK_TCK can generate up to 0xFFFF (uint16_t) cycles */
1814                         ret = ulink_append_clock_tck_cmd(device, 0xFFFF);
1815                         num_cycles -= 0xFFFF;
1816                 } else {
1817                         ret = ulink_append_clock_tck_cmd(device, num_cycles);
1818                         num_cycles = 0;
1819                 }
1820
1821                 if (ret != ERROR_OK)
1822                         return ret;
1823         }
1824
1825         return ERROR_OK;
1826 }
1827
1828 /**
1829  * Post-process JTAG_SCAN command
1830  *
1831  * @param ulink_cmd pointer to OpenULINK command that shall be processed.
1832  * @return on success: ERROR_OK
1833  * @return on failure: ERROR_FAIL
1834  */
1835 static int ulink_post_process_scan(struct ulink_cmd *ulink_cmd)
1836 {
1837         struct jtag_command *cmd = ulink_cmd->cmd_origin;
1838         int ret;
1839
1840         switch (jtag_scan_type(cmd->cmd.scan)) {
1841             case SCAN_IN:
1842             case SCAN_IO:
1843                     ret = jtag_read_buffer(ulink_cmd->payload_in_start, cmd->cmd.scan);
1844                     break;
1845             case SCAN_OUT:
1846                         /* Nothing to do for OUT scans */
1847                     ret = ERROR_OK;
1848                     break;
1849             default:
1850                     LOG_ERROR("BUG: ulink_post_process_scan() encountered an unknown"
1851                         " JTAG scan type");
1852                     ret = ERROR_FAIL;
1853                     break;
1854         }
1855
1856         return ret;
1857 }
1858
1859 /**
1860  * Perform post-processing of commands after OpenULINK queue has been executed.
1861  *
1862  * @param device pointer to struct ulink identifying ULINK driver instance.
1863  * @return on success: ERROR_OK
1864  * @return on failure: ERROR_FAIL
1865  */
1866 static int ulink_post_process_queue(struct ulink *device)
1867 {
1868         struct ulink_cmd *current;
1869         struct jtag_command *openocd_cmd;
1870         int ret;
1871
1872         current = device->queue_start;
1873
1874         while (current) {
1875                 openocd_cmd = current->cmd_origin;
1876
1877                 /* Check if a corresponding OpenOCD command is stored for this
1878                  * OpenULINK command */
1879                 if ((current->needs_postprocessing == true) && (openocd_cmd)) {
1880                         switch (openocd_cmd->type) {
1881                             case JTAG_SCAN:
1882                                     ret = ulink_post_process_scan(current);
1883                                     break;
1884                             case JTAG_TLR_RESET:
1885                             case JTAG_RUNTEST:
1886                             case JTAG_RESET:
1887                             case JTAG_PATHMOVE:
1888                             case JTAG_SLEEP:
1889                             case JTAG_STABLECLOCKS:
1890                                         /* Nothing to do for these commands */
1891                                     ret = ERROR_OK;
1892                                     break;
1893                             default:
1894                                     ret = ERROR_FAIL;
1895                                     LOG_ERROR("BUG: ulink_post_process_queue() encountered unknown JTAG "
1896                                         "command type");
1897                                     break;
1898                         }
1899
1900                         if (ret != ERROR_OK)
1901                                 return ret;
1902                 }
1903
1904                 current = current->next;
1905         }
1906
1907         return ERROR_OK;
1908 }
1909
1910 /**************************** JTAG driver functions ***************************/
1911
1912 /**
1913  * Executes the JTAG Command Queue.
1914  *
1915  * This is done in three stages: First, all OpenOCD commands are processed into
1916  * queued OpenULINK commands. Next, the OpenULINK command queue is sent to the
1917  * ULINK device and data received from the ULINK device is cached. Finally,
1918  * the post-processing function writes back data to the corresponding OpenOCD
1919  * commands.
1920  *
1921  * @return on success: ERROR_OK
1922  * @return on failure: ERROR_FAIL
1923  */
1924 static int ulink_execute_queue(void)
1925 {
1926         struct jtag_command *cmd = jtag_command_queue;
1927         int ret;
1928
1929         while (cmd) {
1930                 switch (cmd->type) {
1931                     case JTAG_SCAN:
1932                             ret = ulink_queue_scan(ulink_handle, cmd);
1933                             break;
1934                     case JTAG_TLR_RESET:
1935                             ret = ulink_queue_tlr_reset(ulink_handle, cmd);
1936                             break;
1937                     case JTAG_RUNTEST:
1938                             ret = ulink_queue_runtest(ulink_handle, cmd);
1939                             break;
1940                     case JTAG_RESET:
1941                             ret = ulink_queue_reset(ulink_handle, cmd);
1942                             break;
1943                     case JTAG_PATHMOVE:
1944                             ret = ulink_queue_pathmove(ulink_handle, cmd);
1945                             break;
1946                     case JTAG_SLEEP:
1947                             ret = ulink_queue_sleep(ulink_handle, cmd);
1948                             break;
1949                     case JTAG_STABLECLOCKS:
1950                             ret = ulink_queue_stableclocks(ulink_handle, cmd);
1951                             break;
1952                     default:
1953                             ret = ERROR_FAIL;
1954                             LOG_ERROR("BUG: encountered unknown JTAG command type");
1955                             break;
1956                 }
1957
1958                 if (ret != ERROR_OK)
1959                         return ret;
1960
1961                 cmd = cmd->next;
1962         }
1963
1964         if (ulink_handle->commands_in_queue > 0) {
1965                 ret = ulink_execute_queued_commands(ulink_handle, USB_TIMEOUT);
1966                 if (ret != ERROR_OK)
1967                         return ret;
1968
1969                 ret = ulink_post_process_queue(ulink_handle);
1970                 if (ret != ERROR_OK)
1971                         return ret;
1972
1973                 ulink_clear_queue(ulink_handle);
1974         }
1975
1976         return ERROR_OK;
1977 }
1978
1979 /**
1980  * Set the TCK frequency of the ULINK adapter.
1981  *
1982  * @param khz desired JTAG TCK frequency.
1983  * @param jtag_speed where to store corresponding adapter-specific speed value.
1984  * @return on success: ERROR_OK
1985  * @return on failure: ERROR_FAIL
1986  */
1987 static int ulink_khz(int khz, int *jtag_speed)
1988 {
1989         int ret;
1990
1991         if (khz == 0) {
1992                 LOG_ERROR("RCLK not supported");
1993                 return ERROR_FAIL;
1994         }
1995
1996         /* CLOCK_TCK commands are decoupled from others. Therefore, the frequency
1997          * setting can be done independently from all other commands. */
1998         if (khz >= 375)
1999                 ulink_handle->delay_clock_tck = -1;
2000         else {
2001                 ret = ulink_calculate_delay(DELAY_CLOCK_TCK, khz * 1000,
2002                                 &ulink_handle->delay_clock_tck);
2003                 if (ret != ERROR_OK)
2004                         return ret;
2005         }
2006
2007         /* SCAN_{IN,OUT,IO} commands invoke CLOCK_TMS commands. Therefore, if the
2008          * requested frequency goes below the maximum frequency for SLOW_CLOCK_TMS
2009          * commands, all SCAN commands MUST also use the variable frequency
2010          * implementation! */
2011         if (khz >= 176) {
2012                 ulink_handle->delay_clock_tms = -1;
2013                 ulink_handle->delay_scan_in = -1;
2014                 ulink_handle->delay_scan_out = -1;
2015                 ulink_handle->delay_scan_io = -1;
2016         } else {
2017                 ret = ulink_calculate_delay(DELAY_CLOCK_TMS, khz * 1000,
2018                                 &ulink_handle->delay_clock_tms);
2019                 if (ret != ERROR_OK)
2020                         return ret;
2021
2022                 ret = ulink_calculate_delay(DELAY_SCAN_IN, khz * 1000,
2023                                 &ulink_handle->delay_scan_in);
2024                 if (ret != ERROR_OK)
2025                         return ret;
2026
2027                 ret = ulink_calculate_delay(DELAY_SCAN_OUT, khz * 1000,
2028                                 &ulink_handle->delay_scan_out);
2029                 if (ret != ERROR_OK)
2030                         return ret;
2031
2032                 ret = ulink_calculate_delay(DELAY_SCAN_IO, khz * 1000,
2033                                 &ulink_handle->delay_scan_io);
2034                 if (ret != ERROR_OK)
2035                         return ret;
2036         }
2037
2038         LOG_DEBUG_IO("ULINK TCK setup: delay_tck      = %i (%li Hz),",
2039                 ulink_handle->delay_clock_tck,
2040                 ulink_calculate_frequency(DELAY_CLOCK_TCK, ulink_handle->delay_clock_tck));
2041         LOG_DEBUG_IO("                 delay_tms      = %i (%li Hz),",
2042                 ulink_handle->delay_clock_tms,
2043                 ulink_calculate_frequency(DELAY_CLOCK_TMS, ulink_handle->delay_clock_tms));
2044         LOG_DEBUG_IO("                 delay_scan_in  = %i (%li Hz),",
2045                 ulink_handle->delay_scan_in,
2046                 ulink_calculate_frequency(DELAY_SCAN_IN, ulink_handle->delay_scan_in));
2047         LOG_DEBUG_IO("                 delay_scan_out = %i (%li Hz),",
2048                 ulink_handle->delay_scan_out,
2049                 ulink_calculate_frequency(DELAY_SCAN_OUT, ulink_handle->delay_scan_out));
2050         LOG_DEBUG_IO("                 delay_scan_io  = %i (%li Hz),",
2051                 ulink_handle->delay_scan_io,
2052                 ulink_calculate_frequency(DELAY_SCAN_IO, ulink_handle->delay_scan_io));
2053
2054         /* Configure the ULINK device with the new delay values */
2055         ret = ulink_append_configure_tck_cmd(ulink_handle,
2056                         ulink_handle->delay_scan_in,
2057                         ulink_handle->delay_scan_out,
2058                         ulink_handle->delay_scan_io,
2059                         ulink_handle->delay_clock_tck,
2060                         ulink_handle->delay_clock_tms);
2061
2062         if (ret != ERROR_OK)
2063                 return ret;
2064
2065         *jtag_speed = khz;
2066
2067         return ERROR_OK;
2068 }
2069
2070 /**
2071  * Set the TCK frequency of the ULINK adapter.
2072  *
2073  * Because of the way the TCK frequency is set up in the OpenULINK firmware,
2074  * there are five different speed settings. To simplify things, the
2075  * adapter-specific speed setting value is identical to the TCK frequency in
2076  * khz.
2077  *
2078  * @param speed desired adapter-specific speed value.
2079  * @return on success: ERROR_OK
2080  * @return on failure: ERROR_FAIL
2081  */
2082 static int ulink_speed(int speed)
2083 {
2084         int dummy;
2085
2086         return ulink_khz(speed, &dummy);
2087 }
2088
2089 /**
2090  * Convert adapter-specific speed value to corresponding TCK frequency in kHz.
2091  *
2092  * Because of the way the TCK frequency is set up in the OpenULINK firmware,
2093  * there are five different speed settings. To simplify things, the
2094  * adapter-specific speed setting value is identical to the TCK frequency in
2095  * khz.
2096  *
2097  * @param speed adapter-specific speed value.
2098  * @param khz where to store corresponding TCK frequency in kHz.
2099  * @return on success: ERROR_OK
2100  * @return on failure: ERROR_FAIL
2101  */
2102 static int ulink_speed_div(int speed, int *khz)
2103 {
2104         *khz = speed;
2105
2106         return ERROR_OK;
2107 }
2108
2109 /**
2110  * Initiates the firmware download to the ULINK adapter and prepares
2111  * the USB handle.
2112  *
2113  * @return on success: ERROR_OK
2114  * @return on failure: ERROR_FAIL
2115  */
2116 static int ulink_init(void)
2117 {
2118         int ret, transferred;
2119         char str_manufacturer[20];
2120         bool download_firmware = false;
2121         unsigned char *dummy;
2122         uint8_t input_signals, output_signals;
2123
2124         ulink_handle = calloc(1, sizeof(struct ulink));
2125         if (!ulink_handle)
2126                 return ERROR_FAIL;
2127
2128         libusb_init(&ulink_handle->libusb_ctx);
2129
2130         ret = ulink_usb_open(&ulink_handle);
2131         if (ret != ERROR_OK) {
2132                 LOG_ERROR("Could not open ULINK device");
2133                 free(ulink_handle);
2134                 ulink_handle = NULL;
2135                 return ret;
2136         }
2137
2138         /* Get String Descriptor to determine if firmware needs to be loaded */
2139         ret = libusb_get_string_descriptor_ascii(ulink_handle->usb_device_handle, 1, (unsigned char *)str_manufacturer, 20);
2140         if (ret < 0) {
2141                 /* Could not get descriptor -> Unconfigured or original Keil firmware */
2142                 download_firmware = true;
2143         } else {
2144                 /* We got a String Descriptor, check if it is the correct one */
2145                 if (strncmp(str_manufacturer, "OpenULINK", 9) != 0)
2146                         download_firmware = true;
2147         }
2148
2149         if (download_firmware == true) {
2150                 LOG_INFO("Loading OpenULINK firmware. This is reversible by power-cycling"
2151                         " ULINK device.");
2152                 ret = ulink_load_firmware_and_renumerate(&ulink_handle,
2153                                 ULINK_FIRMWARE_FILE, ULINK_RENUMERATION_DELAY);
2154                 if (ret != ERROR_OK) {
2155                         LOG_ERROR("Could not download firmware and re-numerate ULINK");
2156                         free(ulink_handle);
2157                         ulink_handle = NULL;
2158                         return ret;
2159                 }
2160         } else
2161                 LOG_INFO("ULINK device is already running OpenULINK firmware");
2162
2163         /* Get OpenULINK USB IN/OUT endpoints and claim the interface */
2164         ret = jtag_libusb_choose_interface(ulink_handle->usb_device_handle,
2165                 &ulink_handle->ep_in, &ulink_handle->ep_out, -1, -1, -1, -1);
2166         if (ret != ERROR_OK)
2167                 return ret;
2168
2169         /* Initialize OpenULINK command queue */
2170         ulink_clear_queue(ulink_handle);
2171
2172         /* Issue one test command with short timeout */
2173         ret = ulink_append_test_cmd(ulink_handle);
2174         if (ret != ERROR_OK)
2175                 return ret;
2176
2177         ret = ulink_execute_queued_commands(ulink_handle, 200);
2178         if (ret != ERROR_OK) {
2179                 /* Sending test command failed. The ULINK device may be forever waiting for
2180                  * the host to fetch an USB Bulk IN packet (e. g. OpenOCD crashed or was
2181                  * shut down by the user via Ctrl-C. Try to retrieve this Bulk IN packet. */
2182                 dummy = calloc(64, sizeof(uint8_t));
2183
2184                 ret = libusb_bulk_transfer(ulink_handle->usb_device_handle, ulink_handle->ep_in,
2185                                 dummy, 64, &transferred, 200);
2186
2187                 free(dummy);
2188
2189                 if (ret != 0 || transferred == 0) {
2190                         /* Bulk IN transfer failed -> unrecoverable error condition */
2191                         LOG_ERROR("Cannot communicate with ULINK device. Disconnect ULINK from "
2192                                 "the USB port and re-connect, then re-run OpenOCD");
2193                         free(ulink_handle);
2194                         ulink_handle = NULL;
2195                         return ERROR_FAIL;
2196                 }
2197 #ifdef _DEBUG_USB_COMMS_
2198                 else {
2199                         /* Successfully received Bulk IN packet -> continue */
2200                         LOG_INFO("Recovered from lost Bulk IN packet");
2201                 }
2202 #endif
2203         }
2204         ulink_clear_queue(ulink_handle);
2205
2206         ret = ulink_append_get_signals_cmd(ulink_handle);
2207         if (ret == ERROR_OK)
2208                 ret = ulink_execute_queued_commands(ulink_handle, 200);
2209
2210         if (ret == ERROR_OK) {
2211                 /* Post-process the single CMD_GET_SIGNALS command */
2212                 input_signals = ulink_handle->queue_start->payload_in[0];
2213                 output_signals = ulink_handle->queue_start->payload_in[1];
2214
2215                 ulink_print_signal_states(input_signals, output_signals);
2216         }
2217
2218         ulink_clear_queue(ulink_handle);
2219
2220         return ERROR_OK;
2221 }
2222
2223 /**
2224  * Closes the USB handle for the ULINK device.
2225  *
2226  * @return on success: ERROR_OK
2227  * @return on failure: ERROR_FAIL
2228  */
2229 static int ulink_quit(void)
2230 {
2231         int ret;
2232
2233         ret = ulink_usb_close(&ulink_handle);
2234         free(ulink_handle);
2235
2236         return ret;
2237 }
2238
2239 /**
2240  * Set a custom path to ULINK firmware image and force downloading to ULINK.
2241  */
2242 COMMAND_HANDLER(ulink_download_firmware_handler)
2243 {
2244         int ret;
2245
2246         if (CMD_ARGC != 1)
2247                 return ERROR_COMMAND_SYNTAX_ERROR;
2248
2249
2250         LOG_INFO("Downloading ULINK firmware image %s", CMD_ARGV[0]);
2251
2252         /* Download firmware image in CMD_ARGV[0] */
2253         ret = ulink_load_firmware_and_renumerate(&ulink_handle, CMD_ARGV[0],
2254                         ULINK_RENUMERATION_DELAY);
2255
2256         return ret;
2257 }
2258
2259 /*************************** Command Registration **************************/
2260
2261 static const struct command_registration ulink_subcommand_handlers[] = {
2262         {
2263                 .name = "download_firmware",
2264                 .handler = &ulink_download_firmware_handler,
2265                 .mode = COMMAND_EXEC,
2266                 .help = "download firmware image to ULINK device",
2267                 .usage = "path/to/ulink_firmware.hex",
2268         },
2269         COMMAND_REGISTRATION_DONE,
2270 };
2271
2272 static const struct command_registration ulink_command_handlers[] = {
2273         {
2274                 .name = "ulink",
2275                 .mode = COMMAND_ANY,
2276                 .help = "perform ulink management",
2277                 .chain = ulink_subcommand_handlers,
2278                 .usage = "",
2279         },
2280         COMMAND_REGISTRATION_DONE
2281 };
2282
2283 static struct jtag_interface ulink_interface = {
2284         .execute_queue = ulink_execute_queue,
2285 };
2286
2287 struct adapter_driver ulink_adapter_driver = {
2288         .name = "ulink",
2289         .transports = jtag_only,
2290         .commands = ulink_command_handlers,
2291
2292         .init = ulink_init,
2293         .quit = ulink_quit,
2294         .speed = ulink_speed,
2295         .khz = ulink_khz,
2296         .speed_div = ulink_speed_div,
2297
2298         .jtag_ops = &ulink_interface,
2299 };