1 /***************************************************************************
2 * Copyright (C) 2011-2013 by Martin Schmoelzer *
3 * <martin.schmoelzer@student.tuwien.ac.at> *
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. *
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. *
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 ***************************************************************************/
24 #include "helper/system.h"
25 #include <jtag/interface.h>
26 #include <jtag/commands.h>
27 #include <target/image.h>
29 #include "libusb_helper.h"
30 #include "OpenULINK/include/msgtypes.h"
32 /** USB Vendor ID of ULINK device in unconfigured state (no firmware loaded
33 * yet) or with OpenULINK firmware. */
34 #define ULINK_VID 0xC251
36 /** USB Product ID of ULINK device in unconfigured state (no firmware loaded
37 * yet) or with OpenULINK firmware. */
38 #define ULINK_PID 0x2710
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
44 /** USB Control EP0 bRequest: "Firmware Load". */
45 #define REQUEST_FIRMWARE_LOAD 0xA0
47 /** Value to write into CPUCS to put EZ-USB into reset. */
48 #define CPU_RESET 0x01
50 /** Value to write into CPUCS to put EZ-USB out of reset. */
51 #define CPU_START 0x00
53 /** Base address of firmware in EZ-USB code space. */
54 #define FIRMWARE_ADDR 0x0000
56 /** USB interface number */
57 #define USB_INTERFACE 0
59 /** Delay (in microseconds) to wait while EZ-USB performs ReNumeration. */
60 #define ULINK_RENUMERATION_DELAY 1500000
62 /** Default location of OpenULINK firmware image. */
63 #define ULINK_FIRMWARE_FILE PKGDATADIR "/OpenULINK/ulink_firmware.hex"
65 /** Maximum size of a single firmware section. Entire EZ-USB code space = 8kB */
66 #define SECTION_BUFFERSIZE 8192
68 /** Tuning of OpenOCD SCAN commands split into multiple OpenULINK commands. */
69 #define SPLIT_SCAN_THRESHOLD 10
71 /** ULINK hardware type */
73 /** Original ULINK adapter, based on Cypress EZ-USB (AN2131):
74 * Full JTAG support, no SWD support. */
77 /** Newer ULINK adapter, based on NXP LPC2148. Currently unsupported. */
80 /** Newer ULINK adapter, based on EZ-USB FX2 + FPGA. Currently unsupported. */
83 /** Newer ULINK adapter, possibly based on ULINK 2. Currently unsupported. */
87 enum ulink_payload_direction {
88 PAYLOAD_DIRECTION_OUT,
92 enum ulink_delay_type {
101 * OpenULINK command (OpenULINK command queue element).
103 * For the OUT direction payload, things are quite easy: Payload is stored
104 * in a rather small array (up to 63 bytes), the payload is always allocated
105 * by the function generating the command and freed by ulink_clear_queue().
107 * For the IN direction payload, things get a little bit more complicated:
108 * The maximum IN payload size for a single command is 64 bytes. Assume that
109 * a single OpenOCD command needs to scan 256 bytes. This results in the
110 * generation of four OpenULINK commands. The function generating these
111 * commands shall allocate an uint8_t[256] array. Each command's #payload_in
112 * pointer shall point to the corresponding offset where IN data shall be
113 * placed, while #payload_in_start shall point to the first element of the 256
115 * - first command: #payload_in_start + 0
116 * - second command: #payload_in_start + 64
117 * - third command: #payload_in_start + 128
118 * - fourth command: #payload_in_start + 192
120 * The last command sets #needs_postprocessing to true.
123 uint8_t id; /**< ULINK command ID */
125 uint8_t *payload_out; /**< OUT direction payload data */
126 uint8_t payload_out_size; /**< OUT direction payload size for this command */
128 uint8_t *payload_in_start; /**< Pointer to first element of IN payload array */
129 uint8_t *payload_in; /**< Pointer where IN payload shall be stored */
130 uint8_t payload_in_size; /**< IN direction payload size for this command */
132 /** Indicates if this command needs post-processing */
133 bool needs_postprocessing;
135 /** Indicates if ulink_clear_queue() should free payload_in_start */
136 bool free_payload_in_start;
138 /** Pointer to corresponding OpenOCD command for post-processing */
139 struct jtag_command *cmd_origin;
141 struct ulink_cmd *next; /**< Pointer to next command (linked list) */
144 /** Describes one driver instance */
146 struct libusb_context *libusb_ctx;
147 struct libusb_device_handle *usb_device_handle;
148 enum ulink_type type;
150 unsigned int ep_in; /**< IN endpoint number */
151 unsigned int ep_out; /**< OUT endpoint number */
153 int delay_scan_in; /**< Delay value for SCAN_IN commands */
154 int delay_scan_out; /**< Delay value for SCAN_OUT commands */
155 int delay_scan_io; /**< Delay value for SCAN_IO commands */
156 int delay_clock_tck; /**< Delay value for CLOCK_TMS commands */
157 int delay_clock_tms; /**< Delay value for CLOCK_TCK commands */
159 int commands_in_queue; /**< Number of commands in queue */
160 struct ulink_cmd *queue_start; /**< Pointer to first command in queue */
161 struct ulink_cmd *queue_end; /**< Pointer to last command in queue */
164 /**************************** Function Prototypes *****************************/
166 /* USB helper functions */
167 static int ulink_usb_open(struct ulink **device);
168 static int ulink_usb_close(struct ulink **device);
170 /* ULINK MCU (Cypress EZ-USB) specific functions */
171 static int ulink_cpu_reset(struct ulink *device, unsigned char reset_bit);
172 static int ulink_load_firmware_and_renumerate(struct ulink **device, const char *filename,
174 static int ulink_load_firmware(struct ulink *device, const char *filename);
175 static int ulink_write_firmware_section(struct ulink *device,
176 struct image *firmware_image, int section_index);
178 /* Generic helper functions */
179 static void ulink_print_signal_states(uint8_t input_signals, uint8_t output_signals);
181 /* OpenULINK command generation helper functions */
182 static int ulink_allocate_payload(struct ulink_cmd *ulink_cmd, int size,
183 enum ulink_payload_direction direction);
185 /* OpenULINK command queue helper functions */
186 static int ulink_get_queue_size(struct ulink *device,
187 enum ulink_payload_direction direction);
188 static void ulink_clear_queue(struct ulink *device);
189 static int ulink_append_queue(struct ulink *device, struct ulink_cmd *ulink_cmd);
190 static int ulink_execute_queued_commands(struct ulink *device, int timeout);
192 static void ulink_print_queue(struct ulink *device);
194 static int ulink_append_scan_cmd(struct ulink *device,
195 enum scan_type scan_type,
200 uint8_t tms_count_start,
201 uint8_t tms_sequence_start,
202 uint8_t tms_count_end,
203 uint8_t tms_sequence_end,
204 struct jtag_command *origin,
206 static int ulink_append_clock_tms_cmd(struct ulink *device, uint8_t count,
208 static int ulink_append_clock_tck_cmd(struct ulink *device, uint16_t count);
209 static int ulink_append_get_signals_cmd(struct ulink *device);
210 static int ulink_append_set_signals_cmd(struct ulink *device, uint8_t low,
212 static int ulink_append_sleep_cmd(struct ulink *device, uint32_t us);
213 static int ulink_append_configure_tck_cmd(struct ulink *device,
219 static int __attribute__((unused)) ulink_append_led_cmd(struct ulink *device, uint8_t led_state);
220 static int ulink_append_test_cmd(struct ulink *device);
222 /* OpenULINK TCK frequency helper functions */
223 static int ulink_calculate_delay(enum ulink_delay_type type, long f, int *delay);
225 /* Interface between OpenULINK and OpenOCD */
226 static void ulink_set_end_state(tap_state_t endstate);
227 static int ulink_queue_statemove(struct ulink *device);
229 static int ulink_queue_scan(struct ulink *device, struct jtag_command *cmd);
230 static int ulink_queue_tlr_reset(struct ulink *device, struct jtag_command *cmd);
231 static int ulink_queue_runtest(struct ulink *device, struct jtag_command *cmd);
232 static int ulink_queue_reset(struct ulink *device, struct jtag_command *cmd);
233 static int ulink_queue_pathmove(struct ulink *device, struct jtag_command *cmd);
234 static int ulink_queue_sleep(struct ulink *device, struct jtag_command *cmd);
235 static int ulink_queue_stableclocks(struct ulink *device, struct jtag_command *cmd);
237 static int ulink_post_process_scan(struct ulink_cmd *ulink_cmd);
238 static int ulink_post_process_queue(struct ulink *device);
240 /* adapter driver functions */
241 static int ulink_execute_queue(void);
242 static int ulink_khz(int khz, int *jtag_speed);
243 static int ulink_speed(int speed);
244 static int ulink_speed_div(int speed, int *khz);
245 static int ulink_init(void);
246 static int ulink_quit(void);
248 /****************************** Global Variables ******************************/
250 static struct ulink *ulink_handle;
252 /**************************** USB helper functions ****************************/
255 * Opens the ULINK device
257 * Currently, only the original ULINK is supported
259 * @param device pointer to struct ulink identifying ULINK driver instance.
260 * @return on success: ERROR_OK
261 * @return on failure: ERROR_FAIL
263 static int ulink_usb_open(struct ulink **device)
265 ssize_t num_devices, i;
267 struct libusb_device **usb_devices;
268 struct libusb_device_descriptor usb_desc;
269 struct libusb_device_handle *usb_device_handle;
271 num_devices = libusb_get_device_list((*device)->libusb_ctx, &usb_devices);
273 if (num_devices <= 0)
277 for (i = 0; i < num_devices; i++) {
278 if (libusb_get_device_descriptor(usb_devices[i], &usb_desc) != 0)
280 else if (usb_desc.idVendor == ULINK_VID && usb_desc.idProduct == ULINK_PID) {
289 if (libusb_open(usb_devices[i], &usb_device_handle) != 0)
291 libusb_free_device_list(usb_devices, 1);
293 (*device)->usb_device_handle = usb_device_handle;
294 (*device)->type = ULINK_1;
300 * Releases the ULINK interface and closes the USB device handle.
302 * @param device pointer to struct ulink identifying ULINK driver instance.
303 * @return on success: ERROR_OK
304 * @return on failure: ERROR_FAIL
306 static int ulink_usb_close(struct ulink **device)
308 if (libusb_release_interface((*device)->usb_device_handle, 0) != 0)
311 libusb_close((*device)->usb_device_handle);
313 (*device)->usb_device_handle = NULL;
318 /******************* ULINK CPU (EZ-USB) specific functions ********************/
321 * Writes '0' or '1' to the CPUCS register, putting the EZ-USB CPU into reset
324 * @param device pointer to struct ulink identifying ULINK driver instance.
325 * @param reset_bit 0 to put CPU into reset, 1 to put CPU out of reset.
326 * @return on success: ERROR_OK
327 * @return on failure: ERROR_FAIL
329 static int ulink_cpu_reset(struct ulink *device, unsigned char reset_bit)
333 ret = libusb_control_transfer(device->usb_device_handle,
334 (LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE),
335 REQUEST_FIRMWARE_LOAD, CPUCS_REG, 0, &reset_bit, 1, LIBUSB_TIMEOUT_MS);
337 /* usb_control_msg() returns the number of bytes transferred during the
338 * DATA stage of the control transfer - must be exactly 1 in this case! */
345 * Puts the ULINK's EZ-USB microcontroller into reset state, downloads
346 * the firmware image, resumes the microcontroller and re-enumerates
349 * @param device pointer to struct ulink identifying ULINK driver instance.
350 * The usb_handle member will be modified during re-enumeration.
351 * @param filename path to the Intel HEX file containing the firmware image.
352 * @param delay the delay to wait for the device to re-enumerate.
353 * @return on success: ERROR_OK
354 * @return on failure: ERROR_FAIL
356 static int ulink_load_firmware_and_renumerate(struct ulink **device,
357 const char *filename, uint32_t delay)
361 /* Basic process: After downloading the firmware, the ULINK will disconnect
362 * itself and re-connect after a short amount of time so we have to close
363 * the handle and re-enumerate USB devices */
365 ret = ulink_load_firmware(*device, filename);
369 ret = ulink_usb_close(device);
375 ret = ulink_usb_open(device);
383 * Downloads a firmware image to the ULINK's EZ-USB microcontroller
386 * @param device pointer to struct ulink identifying ULINK driver instance.
387 * @param filename an absolute or relative path to the Intel HEX file
388 * containing the firmware image.
389 * @return on success: ERROR_OK
390 * @return on failure: ERROR_FAIL
392 static int ulink_load_firmware(struct ulink *device, const char *filename)
394 struct image ulink_firmware_image;
397 ret = ulink_cpu_reset(device, CPU_RESET);
398 if (ret != ERROR_OK) {
399 LOG_ERROR("Could not halt ULINK CPU");
403 ulink_firmware_image.base_address = 0;
404 ulink_firmware_image.base_address_set = false;
406 ret = image_open(&ulink_firmware_image, filename, "ihex");
407 if (ret != ERROR_OK) {
408 LOG_ERROR("Could not load firmware image");
412 /* Download all sections in the image to ULINK */
413 for (unsigned int i = 0; i < ulink_firmware_image.num_sections; i++) {
414 ret = ulink_write_firmware_section(device, &ulink_firmware_image, i);
419 image_close(&ulink_firmware_image);
421 ret = ulink_cpu_reset(device, CPU_START);
422 if (ret != ERROR_OK) {
423 LOG_ERROR("Could not restart ULINK CPU");
431 * Send one contiguous firmware section to the ULINK's EZ-USB microcontroller
434 * @param device pointer to struct ulink identifying ULINK driver instance.
435 * @param firmware_image pointer to the firmware image that contains the section
436 * which should be sent to the ULINK's EZ-USB microcontroller.
437 * @param section_index index of the section within the firmware image.
438 * @return on success: ERROR_OK
439 * @return on failure: ERROR_FAIL
441 static int ulink_write_firmware_section(struct ulink *device,
442 struct image *firmware_image, int section_index)
444 uint16_t addr, size, bytes_remaining, chunk_size;
445 uint8_t data[SECTION_BUFFERSIZE];
446 uint8_t *data_ptr = data;
450 size = (uint16_t)firmware_image->sections[section_index].size;
451 addr = (uint16_t)firmware_image->sections[section_index].base_address;
453 LOG_DEBUG("section %02i at addr 0x%04x (size 0x%04x)", section_index, addr,
456 /* Copy section contents to local buffer */
457 ret = image_read_section(firmware_image, section_index, 0, size, data,
460 if ((ret != ERROR_OK) || (size_read != size)) {
461 /* Propagating the return code would return '0' (misleadingly indicating
462 * successful execution of the function) if only the size check fails. */
466 bytes_remaining = size;
468 /* Send section data in chunks of up to 64 bytes to ULINK */
469 while (bytes_remaining > 0) {
470 if (bytes_remaining > 64)
473 chunk_size = bytes_remaining;
475 ret = libusb_control_transfer(device->usb_device_handle,
476 (LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE),
477 REQUEST_FIRMWARE_LOAD, addr, FIRMWARE_ADDR, (unsigned char *)data_ptr,
478 chunk_size, LIBUSB_TIMEOUT_MS);
480 if (ret != (int)chunk_size) {
481 /* Abort if libusb sent less data than requested */
485 bytes_remaining -= chunk_size;
487 data_ptr += chunk_size;
493 /************************** Generic helper functions **************************/
496 * Print state of interesting signals via LOG_INFO().
498 * @param input_signals input signal states as returned by CMD_GET_SIGNALS
499 * @param output_signals output signal states as returned by CMD_GET_SIGNALS
501 static void ulink_print_signal_states(uint8_t input_signals, uint8_t output_signals)
503 LOG_INFO("ULINK signal states: TDI: %i, TDO: %i, TMS: %i, TCK: %i, TRST: %i,"
505 (output_signals & SIGNAL_TDI ? 1 : 0),
506 (input_signals & SIGNAL_TDO ? 1 : 0),
507 (output_signals & SIGNAL_TMS ? 1 : 0),
508 (output_signals & SIGNAL_TCK ? 1 : 0),
509 (output_signals & SIGNAL_TRST ? 0 : 1), /* Inverted by hardware */
510 (output_signals & SIGNAL_RESET ? 0 : 1)); /* Inverted by hardware */
513 /**************** OpenULINK command generation helper functions ***************/
516 * Allocate and initialize space in memory for OpenULINK command payload.
518 * @param ulink_cmd pointer to command whose payload should be allocated.
519 * @param size the amount of memory to allocate (bytes).
520 * @param direction which payload to allocate.
521 * @return on success: ERROR_OK
522 * @return on failure: ERROR_FAIL
524 static int ulink_allocate_payload(struct ulink_cmd *ulink_cmd, int size,
525 enum ulink_payload_direction direction)
529 payload = calloc(size, sizeof(uint8_t));
532 LOG_ERROR("Could not allocate OpenULINK command payload: out of memory");
537 case PAYLOAD_DIRECTION_OUT:
538 if (ulink_cmd->payload_out) {
539 LOG_ERROR("BUG: Duplicate payload allocation for OpenULINK command");
543 ulink_cmd->payload_out = payload;
544 ulink_cmd->payload_out_size = size;
547 case PAYLOAD_DIRECTION_IN:
548 if (ulink_cmd->payload_in_start) {
549 LOG_ERROR("BUG: Duplicate payload allocation for OpenULINK command");
553 ulink_cmd->payload_in_start = payload;
554 ulink_cmd->payload_in = payload;
555 ulink_cmd->payload_in_size = size;
557 /* By default, free payload_in_start in ulink_clear_queue(). Commands
558 * that do not want this behavior (e. g. split scans) must turn it off
560 ulink_cmd->free_payload_in_start = true;
568 /****************** OpenULINK command queue helper functions ******************/
571 * Get the current number of bytes in the queue, including command IDs.
573 * @param device pointer to struct ulink identifying ULINK driver instance.
574 * @param direction the transfer direction for which to get byte count.
575 * @return the number of bytes currently stored in the queue for the specified
578 static int ulink_get_queue_size(struct ulink *device,
579 enum ulink_payload_direction direction)
581 struct ulink_cmd *current = device->queue_start;
586 case PAYLOAD_DIRECTION_OUT:
587 sum += current->payload_out_size + 1; /* + 1 byte for Command ID */
589 case PAYLOAD_DIRECTION_IN:
590 sum += current->payload_in_size;
594 current = current->next;
601 * Clear the OpenULINK command queue.
603 * @param device pointer to struct ulink identifying ULINK driver instance.
605 static void ulink_clear_queue(struct ulink *device)
607 struct ulink_cmd *current = device->queue_start;
608 struct ulink_cmd *next = NULL;
611 /* Save pointer to next element */
612 next = current->next;
614 /* Free payloads: OUT payload can be freed immediately */
615 free(current->payload_out);
616 current->payload_out = NULL;
618 /* IN payload MUST be freed ONLY if no other commands use the
619 * payload_in_start buffer */
620 if (current->free_payload_in_start == true) {
621 free(current->payload_in_start);
622 current->payload_in_start = NULL;
623 current->payload_in = NULL;
626 /* Free queue element */
629 /* Proceed with next element */
633 device->commands_in_queue = 0;
634 device->queue_start = NULL;
635 device->queue_end = NULL;
639 * Add a command to the OpenULINK command queue.
641 * @param device pointer to struct ulink identifying ULINK driver instance.
642 * @param ulink_cmd pointer to command that shall be appended to the OpenULINK
644 * @return on success: ERROR_OK
645 * @return on failure: ERROR_FAIL
647 static int ulink_append_queue(struct ulink *device, struct ulink_cmd *ulink_cmd)
649 int newsize_out, newsize_in;
652 newsize_out = ulink_get_queue_size(device, PAYLOAD_DIRECTION_OUT) + 1
653 + ulink_cmd->payload_out_size;
655 newsize_in = ulink_get_queue_size(device, PAYLOAD_DIRECTION_IN)
656 + ulink_cmd->payload_in_size;
658 /* Check if the current command can be appended to the queue */
659 if ((newsize_out > 64) || (newsize_in > 64)) {
660 /* New command does not fit. Execute all commands in queue before starting
661 * new queue with the current command as first entry. */
662 ret = ulink_execute_queued_commands(device, LIBUSB_TIMEOUT_MS);
665 ret = ulink_post_process_queue(device);
668 ulink_clear_queue(device);
671 if (!device->queue_start) {
672 /* Queue was empty */
673 device->commands_in_queue = 1;
675 device->queue_start = ulink_cmd;
676 device->queue_end = ulink_cmd;
678 /* There are already commands in the queue */
679 device->commands_in_queue++;
681 device->queue_end->next = ulink_cmd;
682 device->queue_end = ulink_cmd;
686 ulink_clear_queue(device);
692 * Sends all queued OpenULINK commands to the ULINK for execution.
694 * @param device pointer to struct ulink identifying ULINK driver instance.
696 * @return on success: ERROR_OK
697 * @return on failure: ERROR_FAIL
699 static int ulink_execute_queued_commands(struct ulink *device, int timeout)
701 struct ulink_cmd *current;
702 int ret, i, index_out, index_in, count_out, count_in, transferred;
705 if (LOG_LEVEL_IS(LOG_LVL_DEBUG_IO))
706 ulink_print_queue(device);
712 for (current = device->queue_start; current; current = current->next) {
713 /* Add command to packet */
714 buffer[index_out] = current->id;
718 for (i = 0; i < current->payload_out_size; i++)
719 buffer[index_out + i] = current->payload_out[i];
720 index_out += current->payload_out_size;
721 count_in += current->payload_in_size;
722 count_out += current->payload_out_size;
725 /* Send packet to ULINK */
726 ret = libusb_bulk_transfer(device->usb_device_handle, device->ep_out,
727 (unsigned char *)buffer, count_out, &transferred, timeout);
730 if (transferred != count_out)
733 /* Wait for response if commands contain IN payload data */
735 ret = libusb_bulk_transfer(device->usb_device_handle, device->ep_in,
736 (unsigned char *)buffer, 64, &transferred, timeout);
739 if (transferred != count_in)
742 /* Write back IN payload data */
744 for (current = device->queue_start; current; current = current->next) {
745 for (i = 0; i < current->payload_in_size; i++) {
746 current->payload_in[i] = buffer[index_in];
756 * Convert an OpenULINK command ID (\a id) to a human-readable string.
758 * @param id the OpenULINK command ID.
759 * @return the corresponding human-readable string.
761 static const char *ulink_cmd_id_string(uint8_t id)
765 return "CMD_SCAN_IN";
766 case CMD_SLOW_SCAN_IN:
767 return "CMD_SLOW_SCAN_IN";
769 return "CMD_SCAN_OUT";
770 case CMD_SLOW_SCAN_OUT:
771 return "CMD_SLOW_SCAN_OUT";
773 return "CMD_SCAN_IO";
774 case CMD_SLOW_SCAN_IO:
775 return "CMD_SLOW_SCAN_IO";
777 return "CMD_CLOCK_TMS";
778 case CMD_SLOW_CLOCK_TMS:
779 return "CMD_SLOW_CLOCK_TMS";
781 return "CMD_CLOCK_TCK";
782 case CMD_SLOW_CLOCK_TCK:
783 return "CMD_SLOW_CLOCK_TCK";
785 return "CMD_SLEEP_US";
787 return "CMD_SLEEP_MS";
788 case CMD_GET_SIGNALS:
789 return "CMD_GET_SIGNALS";
790 case CMD_SET_SIGNALS:
791 return "CMD_SET_SIGNALS";
792 case CMD_CONFIGURE_TCK_FREQ:
793 return "CMD_CONFIGURE_TCK_FREQ";
795 return "CMD_SET_LEDS";
799 return "CMD_UNKNOWN";
804 * Print one OpenULINK command to stdout.
806 * @param ulink_cmd pointer to OpenULINK command.
808 static void ulink_print_command(struct ulink_cmd *ulink_cmd)
812 printf(" %-22s | OUT size = %i, bytes = 0x",
813 ulink_cmd_id_string(ulink_cmd->id), ulink_cmd->payload_out_size);
815 for (i = 0; i < ulink_cmd->payload_out_size; i++)
816 printf("%02X ", ulink_cmd->payload_out[i]);
817 printf("\n | IN size = %i\n",
818 ulink_cmd->payload_in_size);
822 * Print the OpenULINK command queue to stdout.
824 * @param device pointer to struct ulink identifying ULINK driver instance.
826 static void ulink_print_queue(struct ulink *device)
828 struct ulink_cmd *current;
830 printf("OpenULINK command queue:\n");
832 for (current = device->queue_start; current; current = current->next)
833 ulink_print_command(current);
839 * Creates and appends a JTAG scan command to the OpenULINK command queue.
840 * A JTAG scan consists of three steps:
841 * - Move to the desired SHIFT state, depending on scan type (IR/DR scan).
842 * - Shift TDI data into the JTAG chain, optionally reading the TDO pin.
843 * - Move to the desired end state.
845 * @param device pointer to struct ulink identifying ULINK driver instance.
846 * @param scan_type the type of the scan (IN, OUT, IO (bidirectional)).
847 * @param scan_size_bits number of bits to shift into the JTAG chain.
848 * @param tdi pointer to array containing TDI data.
849 * @param tdo_start pointer to first element of array where TDO data shall be
850 * stored. See #ulink_cmd for details.
851 * @param tdo pointer to array where TDO data shall be stored
852 * @param tms_count_start number of TMS state transitions to perform BEFORE
853 * shifting data into the JTAG chain.
854 * @param tms_sequence_start sequence of TMS state transitions that will be
855 * performed BEFORE shifting data into the JTAG chain.
856 * @param tms_count_end number of TMS state transitions to perform AFTER
857 * shifting data into the JTAG chain.
858 * @param tms_sequence_end sequence of TMS state transitions that will be
859 * performed AFTER shifting data into the JTAG chain.
860 * @param origin pointer to OpenOCD command that generated this scan command.
861 * @param postprocess whether this command needs to be post-processed after
863 * @return on success: ERROR_OK
864 * @return on failure: ERROR_FAIL
866 static int ulink_append_scan_cmd(struct ulink *device, enum scan_type scan_type,
867 int scan_size_bits, uint8_t *tdi, uint8_t *tdo_start, uint8_t *tdo,
868 uint8_t tms_count_start, uint8_t tms_sequence_start, uint8_t tms_count_end,
869 uint8_t tms_sequence_end, struct jtag_command *origin, bool postprocess)
871 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
872 int ret, i, scan_size_bytes;
873 uint8_t bits_last_byte;
878 /* Check size of command. USB buffer can hold 64 bytes, 1 byte is command ID,
879 * 5 bytes are setup data -> 58 remaining payload bytes for TDI data */
880 if (scan_size_bits > (58 * 8)) {
881 LOG_ERROR("BUG: Tried to create CMD_SCAN_IO OpenULINK command with too"
887 scan_size_bytes = DIV_ROUND_UP(scan_size_bits, 8);
889 bits_last_byte = scan_size_bits % 8;
890 if (bits_last_byte == 0)
893 /* Allocate out_payload depending on scan type */
896 if (device->delay_scan_in < 0)
897 cmd->id = CMD_SCAN_IN;
899 cmd->id = CMD_SLOW_SCAN_IN;
900 ret = ulink_allocate_payload(cmd, 5, PAYLOAD_DIRECTION_OUT);
903 if (device->delay_scan_out < 0)
904 cmd->id = CMD_SCAN_OUT;
906 cmd->id = CMD_SLOW_SCAN_OUT;
907 ret = ulink_allocate_payload(cmd, scan_size_bytes + 5, PAYLOAD_DIRECTION_OUT);
910 if (device->delay_scan_io < 0)
911 cmd->id = CMD_SCAN_IO;
913 cmd->id = CMD_SLOW_SCAN_IO;
914 ret = ulink_allocate_payload(cmd, scan_size_bytes + 5, PAYLOAD_DIRECTION_OUT);
917 LOG_ERROR("BUG: ulink_append_scan_cmd() encountered an unknown scan type");
922 if (ret != ERROR_OK) {
927 /* Build payload_out that is common to all scan types */
928 cmd->payload_out[0] = scan_size_bytes & 0xFF;
929 cmd->payload_out[1] = bits_last_byte & 0xFF;
930 cmd->payload_out[2] = ((tms_count_start & 0x0F) << 4) | (tms_count_end & 0x0F);
931 cmd->payload_out[3] = tms_sequence_start;
932 cmd->payload_out[4] = tms_sequence_end;
934 /* Setup payload_out for types with OUT transfer */
935 if ((scan_type == SCAN_OUT) || (scan_type == SCAN_IO)) {
936 for (i = 0; i < scan_size_bytes; i++)
937 cmd->payload_out[i + 5] = tdi[i];
940 /* Setup payload_in pointers for types with IN transfer */
941 if ((scan_type == SCAN_IN) || (scan_type == SCAN_IO)) {
942 cmd->payload_in_start = tdo_start;
943 cmd->payload_in = tdo;
944 cmd->payload_in_size = scan_size_bytes;
947 cmd->needs_postprocessing = postprocess;
948 cmd->cmd_origin = origin;
950 /* For scan commands, we free payload_in_start only when the command is
951 * the last in a series of split commands or a stand-alone command */
952 cmd->free_payload_in_start = postprocess;
954 return ulink_append_queue(device, cmd);
958 * Perform TAP state transitions
960 * @param device pointer to struct ulink identifying ULINK driver instance.
961 * @param count defines the number of TCK clock cycles generated (up to 8).
962 * @param sequence defines the TMS pin levels for each state transition. The
963 * Least-Significant Bit is read first.
964 * @return on success: ERROR_OK
965 * @return on failure: ERROR_FAIL
967 static int ulink_append_clock_tms_cmd(struct ulink *device, uint8_t count,
970 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
976 if (device->delay_clock_tms < 0)
977 cmd->id = CMD_CLOCK_TMS;
979 cmd->id = CMD_SLOW_CLOCK_TMS;
981 /* CMD_CLOCK_TMS has two OUT payload bytes and zero IN payload bytes */
982 ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
983 if (ret != ERROR_OK) {
988 cmd->payload_out[0] = count;
989 cmd->payload_out[1] = sequence;
991 return ulink_append_queue(device, cmd);
995 * Generate a defined amount of TCK clock cycles
997 * All other JTAG signals are left unchanged.
999 * @param device pointer to struct ulink identifying ULINK driver instance.
1000 * @param count the number of TCK clock cycles to generate.
1001 * @return on success: ERROR_OK
1002 * @return on failure: ERROR_FAIL
1004 static int ulink_append_clock_tck_cmd(struct ulink *device, uint16_t count)
1006 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1012 if (device->delay_clock_tck < 0)
1013 cmd->id = CMD_CLOCK_TCK;
1015 cmd->id = CMD_SLOW_CLOCK_TCK;
1017 /* CMD_CLOCK_TCK has two OUT payload bytes and zero IN payload bytes */
1018 ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1019 if (ret != ERROR_OK) {
1024 cmd->payload_out[0] = count & 0xff;
1025 cmd->payload_out[1] = (count >> 8) & 0xff;
1027 return ulink_append_queue(device, cmd);
1031 * Read JTAG signals.
1033 * @param device pointer to struct ulink identifying ULINK driver instance.
1034 * @return on success: ERROR_OK
1035 * @return on failure: ERROR_FAIL
1037 static int ulink_append_get_signals_cmd(struct ulink *device)
1039 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1045 cmd->id = CMD_GET_SIGNALS;
1046 cmd->needs_postprocessing = true;
1048 /* CMD_GET_SIGNALS has two IN payload bytes */
1049 ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_IN);
1051 if (ret != ERROR_OK) {
1056 return ulink_append_queue(device, cmd);
1060 * Arbitrarily set JTAG output signals.
1062 * @param device pointer to struct ulink identifying ULINK driver instance.
1063 * @param low defines which signals will be de-asserted. Each bit corresponds
1072 * @param high defines which signals will be asserted.
1073 * @return on success: ERROR_OK
1074 * @return on failure: ERROR_FAIL
1076 static int ulink_append_set_signals_cmd(struct ulink *device, uint8_t low,
1079 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1085 cmd->id = CMD_SET_SIGNALS;
1087 /* CMD_SET_SIGNALS has two OUT payload bytes and zero IN payload bytes */
1088 ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1090 if (ret != ERROR_OK) {
1095 cmd->payload_out[0] = low;
1096 cmd->payload_out[1] = high;
1098 return ulink_append_queue(device, cmd);
1102 * Sleep for a pre-defined number of microseconds
1104 * @param device pointer to struct ulink identifying ULINK driver instance.
1105 * @param us the number microseconds to sleep.
1106 * @return on success: ERROR_OK
1107 * @return on failure: ERROR_FAIL
1109 static int ulink_append_sleep_cmd(struct ulink *device, uint32_t us)
1111 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1117 cmd->id = CMD_SLEEP_US;
1119 /* CMD_SLEEP_US has two OUT payload bytes and zero IN payload bytes */
1120 ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1122 if (ret != ERROR_OK) {
1127 cmd->payload_out[0] = us & 0x00ff;
1128 cmd->payload_out[1] = (us >> 8) & 0x00ff;
1130 return ulink_append_queue(device, cmd);
1134 * Set TCK delay counters
1136 * @param device pointer to struct ulink identifying ULINK driver instance.
1137 * @param delay_scan_in delay count top value in jtag_slow_scan_in() function.
1138 * @param delay_scan_out delay count top value in jtag_slow_scan_out() function.
1139 * @param delay_scan_io delay count top value in jtag_slow_scan_io() function.
1140 * @param delay_tck delay count top value in jtag_clock_tck() function.
1141 * @param delay_tms delay count top value in jtag_slow_clock_tms() function.
1142 * @return on success: ERROR_OK
1143 * @return on failure: ERROR_FAIL
1145 static int ulink_append_configure_tck_cmd(struct ulink *device, int delay_scan_in,
1146 int delay_scan_out, int delay_scan_io, int delay_tck, int delay_tms)
1148 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1154 cmd->id = CMD_CONFIGURE_TCK_FREQ;
1156 /* CMD_CONFIGURE_TCK_FREQ has five OUT payload bytes and zero
1157 * IN payload bytes */
1158 ret = ulink_allocate_payload(cmd, 5, PAYLOAD_DIRECTION_OUT);
1159 if (ret != ERROR_OK) {
1164 if (delay_scan_in < 0)
1165 cmd->payload_out[0] = 0;
1167 cmd->payload_out[0] = (uint8_t)delay_scan_in;
1169 if (delay_scan_out < 0)
1170 cmd->payload_out[1] = 0;
1172 cmd->payload_out[1] = (uint8_t)delay_scan_out;
1174 if (delay_scan_io < 0)
1175 cmd->payload_out[2] = 0;
1177 cmd->payload_out[2] = (uint8_t)delay_scan_io;
1180 cmd->payload_out[3] = 0;
1182 cmd->payload_out[3] = (uint8_t)delay_tck;
1185 cmd->payload_out[4] = 0;
1187 cmd->payload_out[4] = (uint8_t)delay_tms;
1189 return ulink_append_queue(device, cmd);
1193 * Turn on/off ULINK LEDs.
1195 * @param device pointer to struct ulink identifying ULINK driver instance.
1196 * @param led_state which LED(s) to turn on or off. The following bits
1197 * influence the LEDS:
1198 * - Bit 0: Turn COM LED on
1199 * - Bit 1: Turn RUN LED on
1200 * - Bit 2: Turn COM LED off
1201 * - Bit 3: Turn RUN LED off
1202 * If both the on-bit and the off-bit for the same LED is set, the LED is
1204 * @return on success: ERROR_OK
1205 * @return on failure: ERROR_FAIL
1207 static int ulink_append_led_cmd(struct ulink *device, uint8_t led_state)
1209 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1215 cmd->id = CMD_SET_LEDS;
1217 /* CMD_SET_LEDS has one OUT payload byte and zero IN payload bytes */
1218 ret = ulink_allocate_payload(cmd, 1, PAYLOAD_DIRECTION_OUT);
1219 if (ret != ERROR_OK) {
1224 cmd->payload_out[0] = led_state;
1226 return ulink_append_queue(device, cmd);
1230 * Test command. Used to check if the ULINK device is ready to accept new
1233 * @param device pointer to struct ulink identifying ULINK driver instance.
1234 * @return on success: ERROR_OK
1235 * @return on failure: ERROR_FAIL
1237 static int ulink_append_test_cmd(struct ulink *device)
1239 struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1247 /* CMD_TEST has one OUT payload byte and zero IN payload bytes */
1248 ret = ulink_allocate_payload(cmd, 1, PAYLOAD_DIRECTION_OUT);
1249 if (ret != ERROR_OK) {
1254 cmd->payload_out[0] = 0xAA;
1256 return ulink_append_queue(device, cmd);
1259 /****************** OpenULINK TCK frequency helper functions ******************/
1262 * Calculate delay values for a given TCK frequency.
1264 * The OpenULINK firmware uses five different speed values for different
1265 * commands. These speed values are calculated in these functions.
1267 * The five different commands which support variable TCK frequency are
1268 * implemented twice in the firmware:
1269 * 1. Maximum possible frequency without any artificial delay
1270 * 2. Variable frequency with artificial linear delay loop
1272 * To set the ULINK to maximum frequency, it is only necessary to use the
1273 * corresponding command IDs. To set the ULINK to a lower frequency, the
1274 * delay loop top values have to be calculated first. Then, a
1275 * CMD_CONFIGURE_TCK_FREQ command needs to be sent to the ULINK device.
1277 * The delay values are described by linear equations:
1279 * (t = period, k = constant, x = delay value, d = constant)
1281 * Thus, the delay can be calculated as in the following equation:
1284 * The constants in these equations have been determined and validated by
1285 * measuring the frequency resulting from different delay values.
1287 * @param type for which command to calculate the delay value.
1288 * @param f TCK frequency for which to calculate the delay value in Hz.
1289 * @param delay where to store resulting delay value.
1290 * @return on success: ERROR_OK
1291 * @return on failure: ERROR_FAIL
1293 static int ulink_calculate_delay(enum ulink_delay_type type, long f, int *delay)
1297 /* Calculate period of requested TCK frequency */
1298 t = 1.0 / (float)(f);
1301 case DELAY_CLOCK_TCK:
1302 x = (t - (float)(6E-6)) / (float)(4E-6);
1304 case DELAY_CLOCK_TMS:
1305 x = (t - (float)(8.5E-6)) / (float)(4E-6);
1308 x = (t - (float)(8.8308E-6)) / (float)(4E-6);
1310 case DELAY_SCAN_OUT:
1311 x = (t - (float)(1.0527E-5)) / (float)(4E-6);
1314 x = (t - (float)(1.3132E-5)) / (float)(4E-6);
1321 /* Check if the delay value is negative. This happens when a frequency is
1322 * requested that is too high for the delay loop implementation. In this
1323 * case, set delay value to zero. */
1327 /* We need to convert the exact delay value to an integer. Therefore, we
1328 * round the exact value UP to ensure that the resulting frequency is NOT
1329 * higher than the requested frequency. */
1332 /* Check if the value is within limits */
1336 *delay = (int)x_ceil;
1342 * Calculate frequency for a given delay value.
1344 * Similar to the #ulink_calculate_delay function, this function calculates the
1345 * TCK frequency for a given delay value by using linear equations of the form:
1347 * (t = period, k = constant, x = delay value, d = constant)
1349 * @param type for which command to calculate the delay value.
1350 * @param delay delay value for which to calculate the resulting TCK frequency.
1351 * @return the resulting TCK frequency
1353 static long ulink_calculate_frequency(enum ulink_delay_type type, int delay)
1361 case DELAY_CLOCK_TCK:
1363 t = (float)(2.666E-6);
1365 t = (float)(4E-6) * (float)(delay) + (float)(6E-6);
1367 case DELAY_CLOCK_TMS:
1369 t = (float)(5.666E-6);
1371 t = (float)(4E-6) * (float)(delay) + (float)(8.5E-6);
1375 t = (float)(5.5E-6);
1377 t = (float)(4E-6) * (float)(delay) + (float)(8.8308E-6);
1379 case DELAY_SCAN_OUT:
1381 t = (float)(7.0E-6);
1383 t = (float)(4E-6) * (float)(delay) + (float)(1.0527E-5);
1387 t = (float)(9.926E-6);
1389 t = (float)(4E-6) * (float)(delay) + (float)(1.3132E-5);
1396 return roundf(f_float);
1399 /******************* Interface between OpenULINK and OpenOCD ******************/
1402 * Sets the end state follower (see interface.h) if \a endstate is a stable
1405 * @param endstate the state the end state follower should be set to.
1407 static void ulink_set_end_state(tap_state_t endstate)
1409 if (tap_is_state_stable(endstate))
1410 tap_set_end_state(endstate);
1412 LOG_ERROR("BUG: %s is not a valid end state", tap_state_name(endstate));
1418 * Move from the current TAP state to the current TAP end state.
1420 * @param device pointer to struct ulink identifying ULINK driver instance.
1421 * @return on success: ERROR_OK
1422 * @return on failure: ERROR_FAIL
1424 static int ulink_queue_statemove(struct ulink *device)
1426 uint8_t tms_sequence, tms_count;
1429 if (tap_get_state() == tap_get_end_state()) {
1430 /* Do nothing if we are already there */
1434 tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1435 tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1437 ret = ulink_append_clock_tms_cmd(device, tms_count, tms_sequence);
1439 if (ret == ERROR_OK)
1440 tap_set_state(tap_get_end_state());
1446 * Perform a scan operation on a JTAG register.
1448 * @param device pointer to struct ulink identifying ULINK driver instance.
1449 * @param cmd pointer to the command that shall be executed.
1450 * @return on success: ERROR_OK
1451 * @return on failure: ERROR_FAIL
1453 static int ulink_queue_scan(struct ulink *device, struct jtag_command *cmd)
1455 uint32_t scan_size_bits, scan_size_bytes, bits_last_scan;
1456 uint32_t scans_max_payload, bytecount;
1457 uint8_t *tdi_buffer_start = NULL, *tdi_buffer = NULL;
1458 uint8_t *tdo_buffer_start = NULL, *tdo_buffer = NULL;
1460 uint8_t first_tms_count, first_tms_sequence;
1461 uint8_t last_tms_count, last_tms_sequence;
1463 uint8_t tms_count_pause, tms_sequence_pause;
1464 uint8_t tms_count_resume, tms_sequence_resume;
1466 uint8_t tms_count_start, tms_sequence_start;
1467 uint8_t tms_count_end, tms_sequence_end;
1469 enum scan_type type;
1472 /* Determine scan size */
1473 scan_size_bits = jtag_scan_size(cmd->cmd.scan);
1474 scan_size_bytes = DIV_ROUND_UP(scan_size_bits, 8);
1476 /* Determine scan type (IN/OUT/IO) */
1477 type = jtag_scan_type(cmd->cmd.scan);
1479 /* Determine number of scan commands with maximum payload */
1480 scans_max_payload = scan_size_bytes / 58;
1482 /* Determine size of last shift command */
1483 bits_last_scan = scan_size_bits - (scans_max_payload * 58 * 8);
1485 /* Allocate TDO buffer if required */
1486 if ((type == SCAN_IN) || (type == SCAN_IO)) {
1487 tdo_buffer_start = calloc(sizeof(uint8_t), scan_size_bytes);
1489 if (!tdo_buffer_start)
1492 tdo_buffer = tdo_buffer_start;
1495 /* Fill TDI buffer if required */
1496 if ((type == SCAN_OUT) || (type == SCAN_IO)) {
1497 jtag_build_buffer(cmd->cmd.scan, &tdi_buffer_start);
1498 tdi_buffer = tdi_buffer_start;
1501 /* Get TAP state transitions */
1502 if (cmd->cmd.scan->ir_scan) {
1503 ulink_set_end_state(TAP_IRSHIFT);
1504 first_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1505 first_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1507 tap_set_state(TAP_IRSHIFT);
1508 tap_set_end_state(cmd->cmd.scan->end_state);
1509 last_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1510 last_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1512 /* TAP state transitions for split scans */
1513 tms_count_pause = tap_get_tms_path_len(TAP_IRSHIFT, TAP_IRPAUSE);
1514 tms_sequence_pause = tap_get_tms_path(TAP_IRSHIFT, TAP_IRPAUSE);
1515 tms_count_resume = tap_get_tms_path_len(TAP_IRPAUSE, TAP_IRSHIFT);
1516 tms_sequence_resume = tap_get_tms_path(TAP_IRPAUSE, TAP_IRSHIFT);
1518 ulink_set_end_state(TAP_DRSHIFT);
1519 first_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1520 first_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1522 tap_set_state(TAP_DRSHIFT);
1523 tap_set_end_state(cmd->cmd.scan->end_state);
1524 last_tms_count = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
1525 last_tms_sequence = tap_get_tms_path(tap_get_state(), tap_get_end_state());
1527 /* TAP state transitions for split scans */
1528 tms_count_pause = tap_get_tms_path_len(TAP_DRSHIFT, TAP_DRPAUSE);
1529 tms_sequence_pause = tap_get_tms_path(TAP_DRSHIFT, TAP_DRPAUSE);
1530 tms_count_resume = tap_get_tms_path_len(TAP_DRPAUSE, TAP_DRSHIFT);
1531 tms_sequence_resume = tap_get_tms_path(TAP_DRPAUSE, TAP_DRSHIFT);
1534 /* Generate scan commands */
1535 bytecount = scan_size_bytes;
1536 while (bytecount > 0) {
1537 if (bytecount == scan_size_bytes) {
1538 /* This is the first scan */
1539 tms_count_start = first_tms_count;
1540 tms_sequence_start = first_tms_sequence;
1542 /* Resume from previous scan */
1543 tms_count_start = tms_count_resume;
1544 tms_sequence_start = tms_sequence_resume;
1547 if (bytecount > 58) { /* Full scan, at least one scan will follow */
1548 tms_count_end = tms_count_pause;
1549 tms_sequence_end = tms_sequence_pause;
1551 ret = ulink_append_scan_cmd(device,
1566 /* Update TDI and TDO buffer pointers */
1567 if (tdi_buffer_start)
1569 if (tdo_buffer_start)
1571 } else if (bytecount == 58) { /* Full scan, no further scans */
1572 tms_count_end = last_tms_count;
1573 tms_sequence_end = last_tms_sequence;
1575 ret = ulink_append_scan_cmd(device,
1589 } else {/* Scan with less than maximum payload, no further scans */
1590 tms_count_end = last_tms_count;
1591 tms_sequence_end = last_tms_sequence;
1593 ret = ulink_append_scan_cmd(device,
1609 if (ret != ERROR_OK) {
1610 free(tdi_buffer_start);
1611 free(tdo_buffer_start);
1616 free(tdi_buffer_start);
1618 /* Set current state to the end state requested by the command */
1619 tap_set_state(cmd->cmd.scan->end_state);
1625 * Move the TAP into the Test Logic Reset state.
1627 * @param device pointer to struct ulink identifying ULINK driver instance.
1628 * @param cmd pointer to the command that shall be executed.
1629 * @return on success: ERROR_OK
1630 * @return on failure: ERROR_FAIL
1632 static int ulink_queue_tlr_reset(struct ulink *device, struct jtag_command *cmd)
1636 ret = ulink_append_clock_tms_cmd(device, 5, 0xff);
1638 if (ret == ERROR_OK)
1639 tap_set_state(TAP_RESET);
1647 * Generate TCK clock cycles while remaining
1648 * in the Run-Test/Idle state.
1650 * @param device pointer to struct ulink identifying ULINK driver instance.
1651 * @param cmd pointer to the command that shall be executed.
1652 * @return on success: ERROR_OK
1653 * @return on failure: ERROR_FAIL
1655 static int ulink_queue_runtest(struct ulink *device, struct jtag_command *cmd)
1659 /* Only perform statemove if the TAP currently isn't in the TAP_IDLE state */
1660 if (tap_get_state() != TAP_IDLE) {
1661 ulink_set_end_state(TAP_IDLE);
1662 ulink_queue_statemove(device);
1665 /* Generate the clock cycles */
1666 ret = ulink_append_clock_tck_cmd(device, cmd->cmd.runtest->num_cycles);
1667 if (ret != ERROR_OK)
1670 /* Move to end state specified in command */
1671 if (cmd->cmd.runtest->end_state != tap_get_state()) {
1672 tap_set_end_state(cmd->cmd.runtest->end_state);
1673 ulink_queue_statemove(device);
1680 * Execute a JTAG_RESET command
1683 * @param cmd pointer to the command that shall be executed.
1684 * @return on success: ERROR_OK
1685 * @return on failure: ERROR_FAIL
1687 static int ulink_queue_reset(struct ulink *device, struct jtag_command *cmd)
1689 uint8_t low = 0, high = 0;
1691 if (cmd->cmd.reset->trst) {
1692 tap_set_state(TAP_RESET);
1693 high |= SIGNAL_TRST;
1697 if (cmd->cmd.reset->srst)
1698 high |= SIGNAL_RESET;
1700 low |= SIGNAL_RESET;
1702 return ulink_append_set_signals_cmd(device, low, high);
1706 * Move to one TAP state or several states in succession.
1708 * @param device pointer to struct ulink identifying ULINK driver instance.
1709 * @param cmd pointer to the command that shall be executed.
1710 * @return on success: ERROR_OK
1711 * @return on failure: ERROR_FAIL
1713 static int ulink_queue_pathmove(struct ulink *device, struct jtag_command *cmd)
1715 int ret, i, num_states, batch_size, state_count;
1717 uint8_t tms_sequence;
1719 num_states = cmd->cmd.pathmove->num_states;
1720 path = cmd->cmd.pathmove->path;
1723 while (num_states > 0) {
1726 /* Determine batch size */
1727 if (num_states >= 8)
1730 batch_size = num_states;
1732 for (i = 0; i < batch_size; i++) {
1733 if (tap_state_transition(tap_get_state(), false) == path[state_count]) {
1734 /* Append '0' transition: clear bit 'i' in tms_sequence */
1735 buf_set_u32(&tms_sequence, i, 1, 0x0);
1736 } else if (tap_state_transition(tap_get_state(), true)
1737 == path[state_count]) {
1738 /* Append '1' transition: set bit 'i' in tms_sequence */
1739 buf_set_u32(&tms_sequence, i, 1, 0x1);
1741 /* Invalid state transition */
1742 LOG_ERROR("BUG: %s -> %s isn't a valid TAP state transition",
1743 tap_state_name(tap_get_state()),
1744 tap_state_name(path[state_count]));
1748 tap_set_state(path[state_count]);
1753 /* Append CLOCK_TMS command to OpenULINK command queue */
1755 "pathmove batch: count = %i, sequence = 0x%x", batch_size, tms_sequence);
1756 ret = ulink_append_clock_tms_cmd(ulink_handle, batch_size, tms_sequence);
1757 if (ret != ERROR_OK)
1765 * Sleep for a specific amount of time.
1767 * @param device pointer to struct ulink identifying ULINK driver instance.
1768 * @param cmd pointer to the command that shall be executed.
1769 * @return on success: ERROR_OK
1770 * @return on failure: ERROR_FAIL
1772 static int ulink_queue_sleep(struct ulink *device, struct jtag_command *cmd)
1774 /* IMPORTANT! Due to the time offset in command execution introduced by
1775 * command queueing, this needs to be implemented in the ULINK device */
1776 return ulink_append_sleep_cmd(device, cmd->cmd.sleep->us);
1780 * Generate TCK cycles while remaining in a stable state.
1782 * @param device pointer to struct ulink identifying ULINK driver instance.
1783 * @param cmd pointer to the command that shall be executed.
1785 static int ulink_queue_stableclocks(struct ulink *device, struct jtag_command *cmd)
1788 unsigned num_cycles;
1790 if (!tap_is_state_stable(tap_get_state())) {
1791 LOG_ERROR("JTAG_STABLECLOCKS: state not stable");
1795 num_cycles = cmd->cmd.stableclocks->num_cycles;
1797 /* TMS stays either high (Test Logic Reset state) or low (all other states) */
1798 if (tap_get_state() == TAP_RESET)
1799 ret = ulink_append_set_signals_cmd(device, 0, SIGNAL_TMS);
1801 ret = ulink_append_set_signals_cmd(device, SIGNAL_TMS, 0);
1803 if (ret != ERROR_OK)
1806 while (num_cycles > 0) {
1807 if (num_cycles > 0xFFFF) {
1808 /* OpenULINK CMD_CLOCK_TCK can generate up to 0xFFFF (uint16_t) cycles */
1809 ret = ulink_append_clock_tck_cmd(device, 0xFFFF);
1810 num_cycles -= 0xFFFF;
1812 ret = ulink_append_clock_tck_cmd(device, num_cycles);
1816 if (ret != ERROR_OK)
1824 * Post-process JTAG_SCAN command
1826 * @param ulink_cmd pointer to OpenULINK command that shall be processed.
1827 * @return on success: ERROR_OK
1828 * @return on failure: ERROR_FAIL
1830 static int ulink_post_process_scan(struct ulink_cmd *ulink_cmd)
1832 struct jtag_command *cmd = ulink_cmd->cmd_origin;
1835 switch (jtag_scan_type(cmd->cmd.scan)) {
1838 ret = jtag_read_buffer(ulink_cmd->payload_in_start, cmd->cmd.scan);
1841 /* Nothing to do for OUT scans */
1845 LOG_ERROR("BUG: ulink_post_process_scan() encountered an unknown"
1855 * Perform post-processing of commands after OpenULINK queue has been executed.
1857 * @param device pointer to struct ulink identifying ULINK driver instance.
1858 * @return on success: ERROR_OK
1859 * @return on failure: ERROR_FAIL
1861 static int ulink_post_process_queue(struct ulink *device)
1863 struct ulink_cmd *current;
1864 struct jtag_command *openocd_cmd;
1867 current = device->queue_start;
1870 openocd_cmd = current->cmd_origin;
1872 /* Check if a corresponding OpenOCD command is stored for this
1873 * OpenULINK command */
1874 if ((current->needs_postprocessing == true) && (openocd_cmd)) {
1875 switch (openocd_cmd->type) {
1877 ret = ulink_post_process_scan(current);
1879 case JTAG_TLR_RESET:
1884 case JTAG_STABLECLOCKS:
1885 /* Nothing to do for these commands */
1890 LOG_ERROR("BUG: ulink_post_process_queue() encountered unknown JTAG "
1895 if (ret != ERROR_OK)
1899 current = current->next;
1905 /**************************** JTAG driver functions ***************************/
1908 * Executes the JTAG Command Queue.
1910 * This is done in three stages: First, all OpenOCD commands are processed into
1911 * queued OpenULINK commands. Next, the OpenULINK command queue is sent to the
1912 * ULINK device and data received from the ULINK device is cached. Finally,
1913 * the post-processing function writes back data to the corresponding OpenOCD
1916 * @return on success: ERROR_OK
1917 * @return on failure: ERROR_FAIL
1919 static int ulink_execute_queue(void)
1921 struct jtag_command *cmd = jtag_command_queue;
1925 switch (cmd->type) {
1927 ret = ulink_queue_scan(ulink_handle, cmd);
1929 case JTAG_TLR_RESET:
1930 ret = ulink_queue_tlr_reset(ulink_handle, cmd);
1933 ret = ulink_queue_runtest(ulink_handle, cmd);
1936 ret = ulink_queue_reset(ulink_handle, cmd);
1939 ret = ulink_queue_pathmove(ulink_handle, cmd);
1942 ret = ulink_queue_sleep(ulink_handle, cmd);
1944 case JTAG_STABLECLOCKS:
1945 ret = ulink_queue_stableclocks(ulink_handle, cmd);
1949 LOG_ERROR("BUG: encountered unknown JTAG command type");
1953 if (ret != ERROR_OK)
1959 if (ulink_handle->commands_in_queue > 0) {
1960 ret = ulink_execute_queued_commands(ulink_handle, LIBUSB_TIMEOUT_MS);
1961 if (ret != ERROR_OK)
1964 ret = ulink_post_process_queue(ulink_handle);
1965 if (ret != ERROR_OK)
1968 ulink_clear_queue(ulink_handle);
1975 * Set the TCK frequency of the ULINK adapter.
1977 * @param khz desired JTAG TCK frequency.
1978 * @param jtag_speed where to store corresponding adapter-specific speed value.
1979 * @return on success: ERROR_OK
1980 * @return on failure: ERROR_FAIL
1982 static int ulink_khz(int khz, int *jtag_speed)
1987 LOG_ERROR("RCLK not supported");
1991 /* CLOCK_TCK commands are decoupled from others. Therefore, the frequency
1992 * setting can be done independently from all other commands. */
1994 ulink_handle->delay_clock_tck = -1;
1996 ret = ulink_calculate_delay(DELAY_CLOCK_TCK, khz * 1000,
1997 &ulink_handle->delay_clock_tck);
1998 if (ret != ERROR_OK)
2002 /* SCAN_{IN,OUT,IO} commands invoke CLOCK_TMS commands. Therefore, if the
2003 * requested frequency goes below the maximum frequency for SLOW_CLOCK_TMS
2004 * commands, all SCAN commands MUST also use the variable frequency
2005 * implementation! */
2007 ulink_handle->delay_clock_tms = -1;
2008 ulink_handle->delay_scan_in = -1;
2009 ulink_handle->delay_scan_out = -1;
2010 ulink_handle->delay_scan_io = -1;
2012 ret = ulink_calculate_delay(DELAY_CLOCK_TMS, khz * 1000,
2013 &ulink_handle->delay_clock_tms);
2014 if (ret != ERROR_OK)
2017 ret = ulink_calculate_delay(DELAY_SCAN_IN, khz * 1000,
2018 &ulink_handle->delay_scan_in);
2019 if (ret != ERROR_OK)
2022 ret = ulink_calculate_delay(DELAY_SCAN_OUT, khz * 1000,
2023 &ulink_handle->delay_scan_out);
2024 if (ret != ERROR_OK)
2027 ret = ulink_calculate_delay(DELAY_SCAN_IO, khz * 1000,
2028 &ulink_handle->delay_scan_io);
2029 if (ret != ERROR_OK)
2033 LOG_DEBUG_IO("ULINK TCK setup: delay_tck = %i (%li Hz),",
2034 ulink_handle->delay_clock_tck,
2035 ulink_calculate_frequency(DELAY_CLOCK_TCK, ulink_handle->delay_clock_tck));
2036 LOG_DEBUG_IO(" delay_tms = %i (%li Hz),",
2037 ulink_handle->delay_clock_tms,
2038 ulink_calculate_frequency(DELAY_CLOCK_TMS, ulink_handle->delay_clock_tms));
2039 LOG_DEBUG_IO(" delay_scan_in = %i (%li Hz),",
2040 ulink_handle->delay_scan_in,
2041 ulink_calculate_frequency(DELAY_SCAN_IN, ulink_handle->delay_scan_in));
2042 LOG_DEBUG_IO(" delay_scan_out = %i (%li Hz),",
2043 ulink_handle->delay_scan_out,
2044 ulink_calculate_frequency(DELAY_SCAN_OUT, ulink_handle->delay_scan_out));
2045 LOG_DEBUG_IO(" delay_scan_io = %i (%li Hz),",
2046 ulink_handle->delay_scan_io,
2047 ulink_calculate_frequency(DELAY_SCAN_IO, ulink_handle->delay_scan_io));
2049 /* Configure the ULINK device with the new delay values */
2050 ret = ulink_append_configure_tck_cmd(ulink_handle,
2051 ulink_handle->delay_scan_in,
2052 ulink_handle->delay_scan_out,
2053 ulink_handle->delay_scan_io,
2054 ulink_handle->delay_clock_tck,
2055 ulink_handle->delay_clock_tms);
2057 if (ret != ERROR_OK)
2066 * Set the TCK frequency of the ULINK adapter.
2068 * Because of the way the TCK frequency is set up in the OpenULINK firmware,
2069 * there are five different speed settings. To simplify things, the
2070 * adapter-specific speed setting value is identical to the TCK frequency in
2073 * @param speed desired adapter-specific speed value.
2074 * @return on success: ERROR_OK
2075 * @return on failure: ERROR_FAIL
2077 static int ulink_speed(int speed)
2081 return ulink_khz(speed, &dummy);
2085 * Convert adapter-specific speed value to corresponding TCK frequency in kHz.
2087 * Because of the way the TCK frequency is set up in the OpenULINK firmware,
2088 * there are five different speed settings. To simplify things, the
2089 * adapter-specific speed setting value is identical to the TCK frequency in
2092 * @param speed adapter-specific speed value.
2093 * @param khz where to store corresponding TCK frequency in kHz.
2094 * @return on success: ERROR_OK
2095 * @return on failure: ERROR_FAIL
2097 static int ulink_speed_div(int speed, int *khz)
2105 * Initiates the firmware download to the ULINK adapter and prepares
2108 * @return on success: ERROR_OK
2109 * @return on failure: ERROR_FAIL
2111 static int ulink_init(void)
2113 int ret, transferred;
2114 char str_manufacturer[20];
2115 bool download_firmware = false;
2116 unsigned char *dummy;
2117 uint8_t input_signals, output_signals;
2119 ulink_handle = calloc(1, sizeof(struct ulink));
2123 libusb_init(&ulink_handle->libusb_ctx);
2125 ret = ulink_usb_open(&ulink_handle);
2126 if (ret != ERROR_OK) {
2127 LOG_ERROR("Could not open ULINK device");
2129 ulink_handle = NULL;
2133 /* Get String Descriptor to determine if firmware needs to be loaded */
2134 ret = libusb_get_string_descriptor_ascii(ulink_handle->usb_device_handle, 1, (unsigned char *)str_manufacturer, 20);
2136 /* Could not get descriptor -> Unconfigured or original Keil firmware */
2137 download_firmware = true;
2139 /* We got a String Descriptor, check if it is the correct one */
2140 if (strncmp(str_manufacturer, "OpenULINK", 9) != 0)
2141 download_firmware = true;
2144 if (download_firmware == true) {
2145 LOG_INFO("Loading OpenULINK firmware. This is reversible by power-cycling"
2147 ret = ulink_load_firmware_and_renumerate(&ulink_handle,
2148 ULINK_FIRMWARE_FILE, ULINK_RENUMERATION_DELAY);
2149 if (ret != ERROR_OK) {
2150 LOG_ERROR("Could not download firmware and re-numerate ULINK");
2152 ulink_handle = NULL;
2156 LOG_INFO("ULINK device is already running OpenULINK firmware");
2158 /* Get OpenULINK USB IN/OUT endpoints and claim the interface */
2159 ret = jtag_libusb_choose_interface(ulink_handle->usb_device_handle,
2160 &ulink_handle->ep_in, &ulink_handle->ep_out, -1, -1, -1, -1);
2161 if (ret != ERROR_OK)
2164 /* Initialize OpenULINK command queue */
2165 ulink_clear_queue(ulink_handle);
2167 /* Issue one test command with short timeout */
2168 ret = ulink_append_test_cmd(ulink_handle);
2169 if (ret != ERROR_OK)
2172 ret = ulink_execute_queued_commands(ulink_handle, 200);
2173 if (ret != ERROR_OK) {
2174 /* Sending test command failed. The ULINK device may be forever waiting for
2175 * the host to fetch an USB Bulk IN packet (e. g. OpenOCD crashed or was
2176 * shut down by the user via Ctrl-C. Try to retrieve this Bulk IN packet. */
2177 dummy = calloc(64, sizeof(uint8_t));
2179 ret = libusb_bulk_transfer(ulink_handle->usb_device_handle, ulink_handle->ep_in,
2180 dummy, 64, &transferred, 200);
2184 if (ret != 0 || transferred == 0) {
2185 /* Bulk IN transfer failed -> unrecoverable error condition */
2186 LOG_ERROR("Cannot communicate with ULINK device. Disconnect ULINK from "
2187 "the USB port and re-connect, then re-run OpenOCD");
2189 ulink_handle = NULL;
2192 #ifdef _DEBUG_USB_COMMS_
2194 /* Successfully received Bulk IN packet -> continue */
2195 LOG_INFO("Recovered from lost Bulk IN packet");
2199 ulink_clear_queue(ulink_handle);
2201 ret = ulink_append_get_signals_cmd(ulink_handle);
2202 if (ret == ERROR_OK)
2203 ret = ulink_execute_queued_commands(ulink_handle, 200);
2205 if (ret == ERROR_OK) {
2206 /* Post-process the single CMD_GET_SIGNALS command */
2207 input_signals = ulink_handle->queue_start->payload_in[0];
2208 output_signals = ulink_handle->queue_start->payload_in[1];
2210 ulink_print_signal_states(input_signals, output_signals);
2213 ulink_clear_queue(ulink_handle);
2219 * Closes the USB handle for the ULINK device.
2221 * @return on success: ERROR_OK
2222 * @return on failure: ERROR_FAIL
2224 static int ulink_quit(void)
2228 ret = ulink_usb_close(&ulink_handle);
2235 * Set a custom path to ULINK firmware image and force downloading to ULINK.
2237 COMMAND_HANDLER(ulink_download_firmware_handler)
2242 return ERROR_COMMAND_SYNTAX_ERROR;
2245 LOG_INFO("Downloading ULINK firmware image %s", CMD_ARGV[0]);
2247 /* Download firmware image in CMD_ARGV[0] */
2248 ret = ulink_load_firmware_and_renumerate(&ulink_handle, CMD_ARGV[0],
2249 ULINK_RENUMERATION_DELAY);
2254 /*************************** Command Registration **************************/
2256 static const struct command_registration ulink_subcommand_handlers[] = {
2258 .name = "download_firmware",
2259 .handler = &ulink_download_firmware_handler,
2260 .mode = COMMAND_EXEC,
2261 .help = "download firmware image to ULINK device",
2262 .usage = "path/to/ulink_firmware.hex",
2264 COMMAND_REGISTRATION_DONE,
2267 static const struct command_registration ulink_command_handlers[] = {
2270 .mode = COMMAND_ANY,
2271 .help = "perform ulink management",
2272 .chain = ulink_subcommand_handlers,
2275 COMMAND_REGISTRATION_DONE
2278 static struct jtag_interface ulink_interface = {
2279 .execute_queue = ulink_execute_queue,
2282 struct adapter_driver ulink_adapter_driver = {
2284 .transports = jtag_only,
2285 .commands = ulink_command_handlers,
2289 .speed = ulink_speed,
2291 .speed_div = ulink_speed_div,
2293 .jtag_ops = &ulink_interface,