libusb_helper.h: Increase USB timeout
[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 /** Delay (in microseconds) to wait while EZ-USB performs ReNumeration. */
60 #define ULINK_RENUMERATION_DELAY 1500000
61
62 /** Default location of OpenULINK firmware image. */
63 #define ULINK_FIRMWARE_FILE      PKGDATADIR "/OpenULINK/ulink_firmware.hex"
64
65 /** Maximum size of a single firmware section. Entire EZ-USB code space = 8kB */
66 #define SECTION_BUFFERSIZE       8192
67
68 /** Tuning of OpenOCD SCAN commands split into multiple OpenULINK commands. */
69 #define SPLIT_SCAN_THRESHOLD     10
70
71 /** ULINK hardware type */
72 enum ulink_type {
73         /** Original ULINK adapter, based on Cypress EZ-USB (AN2131):
74          *  Full JTAG support, no SWD support. */
75         ULINK_1,
76
77         /** Newer ULINK adapter, based on NXP LPC2148. Currently unsupported. */
78         ULINK_2,
79
80         /** Newer ULINK adapter, based on EZ-USB FX2 + FPGA. Currently unsupported. */
81         ULINK_PRO,
82
83         /** Newer ULINK adapter, possibly based on ULINK 2. Currently unsupported. */
84         ULINK_ME
85 };
86
87 enum ulink_payload_direction {
88         PAYLOAD_DIRECTION_OUT,
89         PAYLOAD_DIRECTION_IN
90 };
91
92 enum ulink_delay_type {
93         DELAY_CLOCK_TCK,
94         DELAY_CLOCK_TMS,
95         DELAY_SCAN_IN,
96         DELAY_SCAN_OUT,
97         DELAY_SCAN_IO
98 };
99
100 /**
101  * OpenULINK command (OpenULINK command queue element).
102  *
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().
106  *
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
114  * byte array.
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
119  *
120  * The last command sets #needs_postprocessing to true.
121  */
122 struct ulink_cmd {
123         uint8_t id;                     /**< ULINK command ID */
124
125         uint8_t *payload_out;           /**< OUT direction payload data */
126         uint8_t payload_out_size;       /**< OUT direction payload size for this command */
127
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 */
131
132         /** Indicates if this command needs post-processing */
133         bool needs_postprocessing;
134
135         /** Indicates if ulink_clear_queue() should free payload_in_start  */
136         bool free_payload_in_start;
137
138         /** Pointer to corresponding OpenOCD command for post-processing */
139         struct jtag_command *cmd_origin;
140
141         struct ulink_cmd *next;         /**< Pointer to next command (linked list) */
142 };
143
144 /** Describes one driver instance */
145 struct ulink {
146         struct libusb_context *libusb_ctx;
147         struct libusb_device_handle *usb_device_handle;
148         enum ulink_type type;
149
150         unsigned int ep_in;             /**< IN endpoint number */
151         unsigned int ep_out;            /**< OUT endpoint number */
152
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 */
158
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 */
162 };
163
164 /**************************** Function Prototypes *****************************/
165
166 /* USB helper functions */
167 static int ulink_usb_open(struct ulink **device);
168 static int ulink_usb_close(struct ulink **device);
169
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,
173                 uint32_t delay);
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);
177
178 /* Generic helper functions */
179 static void ulink_print_signal_states(uint8_t input_signals, uint8_t output_signals);
180
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);
184
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);
191
192 static void ulink_print_queue(struct ulink *device);
193
194 static int ulink_append_scan_cmd(struct ulink *device,
195                 enum scan_type scan_type,
196                 int scan_size_bits,
197                 uint8_t *tdi,
198                 uint8_t *tdo_start,
199                 uint8_t *tdo,
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,
205                 bool postprocess);
206 static int ulink_append_clock_tms_cmd(struct ulink *device, uint8_t count,
207                 uint8_t sequence);
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,
211                 uint8_t high);
212 static int ulink_append_sleep_cmd(struct ulink *device, uint32_t us);
213 static int ulink_append_configure_tck_cmd(struct ulink *device,
214                 int delay_scan_in,
215                 int delay_scan_out,
216                 int delay_scan_io,
217                 int delay_tck,
218                 int delay_tms);
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);
221
222 /* OpenULINK TCK frequency helper functions */
223 static int ulink_calculate_delay(enum ulink_delay_type type, long f, int *delay);
224
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);
228
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);
236
237 static int ulink_post_process_scan(struct ulink_cmd *ulink_cmd);
238 static int ulink_post_process_queue(struct ulink *device);
239
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);
247
248 /****************************** Global Variables ******************************/
249
250 static struct ulink *ulink_handle;
251
252 /**************************** USB helper functions ****************************/
253
254 /**
255  * Opens the ULINK device
256  *
257  * Currently, only the original ULINK is supported
258  *
259  * @param device pointer to struct ulink identifying ULINK driver instance.
260  * @return on success: ERROR_OK
261  * @return on failure: ERROR_FAIL
262  */
263 static int ulink_usb_open(struct ulink **device)
264 {
265         ssize_t num_devices, i;
266         bool found;
267         struct libusb_device **usb_devices;
268         struct libusb_device_descriptor usb_desc;
269         struct libusb_device_handle *usb_device_handle;
270
271         num_devices = libusb_get_device_list((*device)->libusb_ctx, &usb_devices);
272
273         if (num_devices <= 0)
274                 return ERROR_FAIL;
275
276         found = false;
277         for (i = 0; i < num_devices; i++) {
278                 if (libusb_get_device_descriptor(usb_devices[i], &usb_desc) != 0)
279                         continue;
280                 else if (usb_desc.idVendor == ULINK_VID && usb_desc.idProduct == ULINK_PID) {
281                         found = true;
282                         break;
283                 }
284         }
285
286         if (!found)
287                 return ERROR_FAIL;
288
289         if (libusb_open(usb_devices[i], &usb_device_handle) != 0)
290                 return ERROR_FAIL;
291         libusb_free_device_list(usb_devices, 1);
292
293         (*device)->usb_device_handle = usb_device_handle;
294         (*device)->type = ULINK_1;
295
296         return ERROR_OK;
297 }
298
299 /**
300  * Releases the ULINK interface and closes the USB device handle.
301  *
302  * @param device pointer to struct ulink identifying ULINK driver instance.
303  * @return on success: ERROR_OK
304  * @return on failure: ERROR_FAIL
305  */
306 static int ulink_usb_close(struct ulink **device)
307 {
308         if (libusb_release_interface((*device)->usb_device_handle, 0) != 0)
309                 return ERROR_FAIL;
310
311         libusb_close((*device)->usb_device_handle);
312
313         (*device)->usb_device_handle = NULL;
314
315         return ERROR_OK;
316 }
317
318 /******************* ULINK CPU (EZ-USB) specific functions ********************/
319
320 /**
321  * Writes '0' or '1' to the CPUCS register, putting the EZ-USB CPU into reset
322  * or out of reset.
323  *
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
328  */
329 static int ulink_cpu_reset(struct ulink *device, unsigned char reset_bit)
330 {
331         int ret;
332
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);
336
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! */
339         if (ret != 1)
340                 return ERROR_FAIL;
341         return ERROR_OK;
342 }
343
344 /**
345  * Puts the ULINK's EZ-USB microcontroller into reset state, downloads
346  * the firmware image, resumes the microcontroller and re-enumerates
347  * USB devices.
348  *
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
355  */
356 static int ulink_load_firmware_and_renumerate(struct ulink **device,
357         const char *filename, uint32_t delay)
358 {
359         int ret;
360
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 */
364
365         ret = ulink_load_firmware(*device, filename);
366         if (ret != ERROR_OK)
367                 return ret;
368
369         ret = ulink_usb_close(device);
370         if (ret != ERROR_OK)
371                 return ret;
372
373         usleep(delay);
374
375         ret = ulink_usb_open(device);
376         if (ret != ERROR_OK)
377                 return ret;
378
379         return ERROR_OK;
380 }
381
382 /**
383  * Downloads a firmware image to the ULINK's EZ-USB microcontroller
384  * over the USB bus.
385  *
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
391  */
392 static int ulink_load_firmware(struct ulink *device, const char *filename)
393 {
394         struct image ulink_firmware_image;
395         int ret;
396
397         ret = ulink_cpu_reset(device, CPU_RESET);
398         if (ret != ERROR_OK) {
399                 LOG_ERROR("Could not halt ULINK CPU");
400                 return ret;
401         }
402
403         ulink_firmware_image.base_address = 0;
404         ulink_firmware_image.base_address_set = false;
405
406         ret = image_open(&ulink_firmware_image, filename, "ihex");
407         if (ret != ERROR_OK) {
408                 LOG_ERROR("Could not load firmware image");
409                 return ret;
410         }
411
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);
415                 if (ret != ERROR_OK)
416                         return ret;
417         }
418
419         image_close(&ulink_firmware_image);
420
421         ret = ulink_cpu_reset(device, CPU_START);
422         if (ret != ERROR_OK) {
423                 LOG_ERROR("Could not restart ULINK CPU");
424                 return ret;
425         }
426
427         return ERROR_OK;
428 }
429
430 /**
431  * Send one contiguous firmware section to the ULINK's EZ-USB microcontroller
432  * over the USB bus.
433  *
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
440  */
441 static int ulink_write_firmware_section(struct ulink *device,
442         struct image *firmware_image, int section_index)
443 {
444         uint16_t addr, size, bytes_remaining, chunk_size;
445         uint8_t data[SECTION_BUFFERSIZE];
446         uint8_t *data_ptr = data;
447         size_t size_read;
448         int ret;
449
450         size = (uint16_t)firmware_image->sections[section_index].size;
451         addr = (uint16_t)firmware_image->sections[section_index].base_address;
452
453         LOG_DEBUG("section %02i at addr 0x%04x (size 0x%04x)", section_index, addr,
454                 size);
455
456         /* Copy section contents to local buffer */
457         ret = image_read_section(firmware_image, section_index, 0, size, data,
458                         &size_read);
459
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. */
463                 return ERROR_FAIL;
464         }
465
466         bytes_remaining = size;
467
468         /* Send section data in chunks of up to 64 bytes to ULINK */
469         while (bytes_remaining > 0) {
470                 if (bytes_remaining > 64)
471                         chunk_size = 64;
472                 else
473                         chunk_size = bytes_remaining;
474
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);
479
480                 if (ret != (int)chunk_size) {
481                         /* Abort if libusb sent less data than requested */
482                         return ERROR_FAIL;
483                 }
484
485                 bytes_remaining -= chunk_size;
486                 addr += chunk_size;
487                 data_ptr += chunk_size;
488         }
489
490         return ERROR_OK;
491 }
492
493 /************************** Generic helper functions **************************/
494
495 /**
496  * Print state of interesting signals via LOG_INFO().
497  *
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
500  */
501 static void ulink_print_signal_states(uint8_t input_signals, uint8_t output_signals)
502 {
503         LOG_INFO("ULINK signal states: TDI: %i, TDO: %i, TMS: %i, TCK: %i, TRST: %i,"
504                 " SRST: %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 */
511 }
512
513 /**************** OpenULINK command generation helper functions ***************/
514
515 /**
516  * Allocate and initialize space in memory for OpenULINK command payload.
517  *
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
523  */
524 static int ulink_allocate_payload(struct ulink_cmd *ulink_cmd, int size,
525         enum ulink_payload_direction direction)
526 {
527         uint8_t *payload;
528
529         payload = calloc(size, sizeof(uint8_t));
530
531         if (!payload) {
532                 LOG_ERROR("Could not allocate OpenULINK command payload: out of memory");
533                 return ERROR_FAIL;
534         }
535
536         switch (direction) {
537             case PAYLOAD_DIRECTION_OUT:
538                     if (ulink_cmd->payload_out) {
539                             LOG_ERROR("BUG: Duplicate payload allocation for OpenULINK command");
540                             free(payload);
541                             return ERROR_FAIL;
542                     } else {
543                             ulink_cmd->payload_out = payload;
544                             ulink_cmd->payload_out_size = size;
545                     }
546                     break;
547             case PAYLOAD_DIRECTION_IN:
548                     if (ulink_cmd->payload_in_start) {
549                             LOG_ERROR("BUG: Duplicate payload allocation for OpenULINK command");
550                             free(payload);
551                             return ERROR_FAIL;
552                     } else {
553                             ulink_cmd->payload_in_start = payload;
554                             ulink_cmd->payload_in = payload;
555                             ulink_cmd->payload_in_size = size;
556
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
559                                  * separately! */
560                             ulink_cmd->free_payload_in_start = true;
561                     }
562                     break;
563         }
564
565         return ERROR_OK;
566 }
567
568 /****************** OpenULINK command queue helper functions ******************/
569
570 /**
571  * Get the current number of bytes in the queue, including command IDs.
572  *
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
576  *  direction.
577  */
578 static int ulink_get_queue_size(struct ulink *device,
579         enum ulink_payload_direction direction)
580 {
581         struct ulink_cmd *current = device->queue_start;
582         int sum = 0;
583
584         while (current) {
585                 switch (direction) {
586                     case PAYLOAD_DIRECTION_OUT:
587                             sum += current->payload_out_size + 1;       /* + 1 byte for Command ID */
588                             break;
589                     case PAYLOAD_DIRECTION_IN:
590                             sum += current->payload_in_size;
591                             break;
592                 }
593
594                 current = current->next;
595         }
596
597         return sum;
598 }
599
600 /**
601  * Clear the OpenULINK command queue.
602  *
603  * @param device pointer to struct ulink identifying ULINK driver instance.
604  */
605 static void ulink_clear_queue(struct ulink *device)
606 {
607         struct ulink_cmd *current = device->queue_start;
608         struct ulink_cmd *next = NULL;
609
610         while (current) {
611                 /* Save pointer to next element */
612                 next = current->next;
613
614                 /* Free payloads: OUT payload can be freed immediately */
615                 free(current->payload_out);
616                 current->payload_out = NULL;
617
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;
624                 }
625
626                 /* Free queue element */
627                 free(current);
628
629                 /* Proceed with next element */
630                 current = next;
631         }
632
633         device->commands_in_queue = 0;
634         device->queue_start = NULL;
635         device->queue_end = NULL;
636 }
637
638 /**
639  * Add a command to the OpenULINK command queue.
640  *
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
643  *  command queue.
644  * @return on success: ERROR_OK
645  * @return on failure: ERROR_FAIL
646  */
647 static int ulink_append_queue(struct ulink *device, struct ulink_cmd *ulink_cmd)
648 {
649         int newsize_out, newsize_in;
650         int ret = ERROR_OK;
651
652         newsize_out = ulink_get_queue_size(device, PAYLOAD_DIRECTION_OUT) + 1
653                 + ulink_cmd->payload_out_size;
654
655         newsize_in = ulink_get_queue_size(device, PAYLOAD_DIRECTION_IN)
656                 + ulink_cmd->payload_in_size;
657
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);
663
664                 if (ret == ERROR_OK)
665                         ret = ulink_post_process_queue(device);
666
667                 if (ret == ERROR_OK)
668                         ulink_clear_queue(device);
669         }
670
671         if (!device->queue_start) {
672                 /* Queue was empty */
673                 device->commands_in_queue = 1;
674
675                 device->queue_start = ulink_cmd;
676                 device->queue_end = ulink_cmd;
677         } else {
678                 /* There are already commands in the queue */
679                 device->commands_in_queue++;
680
681                 device->queue_end->next = ulink_cmd;
682                 device->queue_end = ulink_cmd;
683         }
684
685         if (ret != ERROR_OK)
686                 ulink_clear_queue(device);
687
688         return ret;
689 }
690
691 /**
692  * Sends all queued OpenULINK commands to the ULINK for execution.
693  *
694  * @param device pointer to struct ulink identifying ULINK driver instance.
695  * @param timeout
696  * @return on success: ERROR_OK
697  * @return on failure: ERROR_FAIL
698  */
699 static int ulink_execute_queued_commands(struct ulink *device, int timeout)
700 {
701         struct ulink_cmd *current;
702         int ret, i, index_out, index_in, count_out, count_in, transferred;
703         uint8_t buffer[64];
704
705         if (LOG_LEVEL_IS(LOG_LVL_DEBUG_IO))
706                 ulink_print_queue(device);
707
708         index_out = 0;
709         count_out = 0;
710         count_in = 0;
711
712         for (current = device->queue_start; current; current = current->next) {
713                 /* Add command to packet */
714                 buffer[index_out] = current->id;
715                 index_out++;
716                 count_out++;
717
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;
723         }
724
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);
728         if (ret != 0)
729                 return ERROR_FAIL;
730         if (transferred != count_out)
731                 return ERROR_FAIL;
732
733         /* Wait for response if commands contain IN payload data */
734         if (count_in > 0) {
735                 ret = libusb_bulk_transfer(device->usb_device_handle, device->ep_in,
736                                 (unsigned char *)buffer, 64, &transferred, timeout);
737                 if (ret != 0)
738                         return ERROR_FAIL;
739                 if (transferred != count_in)
740                         return ERROR_FAIL;
741
742                 /* Write back IN payload data */
743                 index_in = 0;
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];
747                                 index_in++;
748                         }
749                 }
750         }
751
752         return ERROR_OK;
753 }
754
755 /**
756  * Convert an OpenULINK command ID (\a id) to a human-readable string.
757  *
758  * @param id the OpenULINK command ID.
759  * @return the corresponding human-readable string.
760  */
761 static const char *ulink_cmd_id_string(uint8_t id)
762 {
763         switch (id) {
764         case CMD_SCAN_IN:
765                 return "CMD_SCAN_IN";
766         case CMD_SLOW_SCAN_IN:
767                 return "CMD_SLOW_SCAN_IN";
768         case CMD_SCAN_OUT:
769                 return "CMD_SCAN_OUT";
770         case CMD_SLOW_SCAN_OUT:
771                 return "CMD_SLOW_SCAN_OUT";
772         case CMD_SCAN_IO:
773                 return "CMD_SCAN_IO";
774         case CMD_SLOW_SCAN_IO:
775                 return "CMD_SLOW_SCAN_IO";
776         case CMD_CLOCK_TMS:
777                 return "CMD_CLOCK_TMS";
778         case CMD_SLOW_CLOCK_TMS:
779                 return "CMD_SLOW_CLOCK_TMS";
780         case CMD_CLOCK_TCK:
781                 return "CMD_CLOCK_TCK";
782         case CMD_SLOW_CLOCK_TCK:
783                 return "CMD_SLOW_CLOCK_TCK";
784         case CMD_SLEEP_US:
785                 return "CMD_SLEEP_US";
786         case CMD_SLEEP_MS:
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";
794         case CMD_SET_LEDS:
795                 return "CMD_SET_LEDS";
796         case CMD_TEST:
797                 return "CMD_TEST";
798         default:
799                 return "CMD_UNKNOWN";
800         }
801 }
802
803 /**
804  * Print one OpenULINK command to stdout.
805  *
806  * @param ulink_cmd pointer to OpenULINK command.
807  */
808 static void ulink_print_command(struct ulink_cmd *ulink_cmd)
809 {
810         int i;
811
812         printf("  %-22s | OUT size = %i, bytes = 0x",
813                 ulink_cmd_id_string(ulink_cmd->id), ulink_cmd->payload_out_size);
814
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);
819 }
820
821 /**
822  * Print the OpenULINK command queue to stdout.
823  *
824  * @param device pointer to struct ulink identifying ULINK driver instance.
825  */
826 static void ulink_print_queue(struct ulink *device)
827 {
828         struct ulink_cmd *current;
829
830         printf("OpenULINK command queue:\n");
831
832         for (current = device->queue_start; current; current = current->next)
833                 ulink_print_command(current);
834 }
835
836 /**
837  * Perform JTAG scan
838  *
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.
844  *
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
862  *  execution.
863  * @return on success: ERROR_OK
864  * @return on failure: ERROR_FAIL
865  */
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)
870 {
871         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
872         int ret, i, scan_size_bytes;
873         uint8_t bits_last_byte;
874
875         if (!cmd)
876                 return ERROR_FAIL;
877
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"
882                         " large payload");
883                 free(cmd);
884                 return ERROR_FAIL;
885         }
886
887         scan_size_bytes = DIV_ROUND_UP(scan_size_bits, 8);
888
889         bits_last_byte = scan_size_bits % 8;
890         if (bits_last_byte == 0)
891                 bits_last_byte = 8;
892
893         /* Allocate out_payload depending on scan type */
894         switch (scan_type) {
895             case SCAN_IN:
896                     if (device->delay_scan_in < 0)
897                             cmd->id = CMD_SCAN_IN;
898                     else
899                             cmd->id = CMD_SLOW_SCAN_IN;
900                     ret = ulink_allocate_payload(cmd, 5, PAYLOAD_DIRECTION_OUT);
901                     break;
902             case SCAN_OUT:
903                     if (device->delay_scan_out < 0)
904                             cmd->id = CMD_SCAN_OUT;
905                     else
906                             cmd->id = CMD_SLOW_SCAN_OUT;
907                     ret = ulink_allocate_payload(cmd, scan_size_bytes + 5, PAYLOAD_DIRECTION_OUT);
908                     break;
909             case SCAN_IO:
910                     if (device->delay_scan_io < 0)
911                             cmd->id = CMD_SCAN_IO;
912                     else
913                             cmd->id = CMD_SLOW_SCAN_IO;
914                     ret = ulink_allocate_payload(cmd, scan_size_bytes + 5, PAYLOAD_DIRECTION_OUT);
915                     break;
916             default:
917                     LOG_ERROR("BUG: ulink_append_scan_cmd() encountered an unknown scan type");
918                     ret = ERROR_FAIL;
919                     break;
920         }
921
922         if (ret != ERROR_OK) {
923                 free(cmd);
924                 return ret;
925         }
926
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;
933
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];
938         }
939
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;
945         }
946
947         cmd->needs_postprocessing = postprocess;
948         cmd->cmd_origin = origin;
949
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;
953
954         return ulink_append_queue(device, cmd);
955 }
956
957 /**
958  * Perform TAP state transitions
959  *
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
966  */
967 static int ulink_append_clock_tms_cmd(struct ulink *device, uint8_t count,
968         uint8_t sequence)
969 {
970         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
971         int ret;
972
973         if (!cmd)
974                 return ERROR_FAIL;
975
976         if (device->delay_clock_tms < 0)
977                 cmd->id = CMD_CLOCK_TMS;
978         else
979                 cmd->id = CMD_SLOW_CLOCK_TMS;
980
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) {
984                 free(cmd);
985                 return ret;
986         }
987
988         cmd->payload_out[0] = count;
989         cmd->payload_out[1] = sequence;
990
991         return ulink_append_queue(device, cmd);
992 }
993
994 /**
995  * Generate a defined amount of TCK clock cycles
996  *
997  * All other JTAG signals are left unchanged.
998  *
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
1003  */
1004 static int ulink_append_clock_tck_cmd(struct ulink *device, uint16_t count)
1005 {
1006         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1007         int ret;
1008
1009         if (!cmd)
1010                 return ERROR_FAIL;
1011
1012         if (device->delay_clock_tck < 0)
1013                 cmd->id = CMD_CLOCK_TCK;
1014         else
1015                 cmd->id = CMD_SLOW_CLOCK_TCK;
1016
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) {
1020                 free(cmd);
1021                 return ret;
1022         }
1023
1024         cmd->payload_out[0] = count & 0xff;
1025         cmd->payload_out[1] = (count >> 8) & 0xff;
1026
1027         return ulink_append_queue(device, cmd);
1028 }
1029
1030 /**
1031  * Read JTAG signals.
1032  *
1033  * @param device pointer to struct ulink identifying ULINK driver instance.
1034  * @return on success: ERROR_OK
1035  * @return on failure: ERROR_FAIL
1036  */
1037 static int ulink_append_get_signals_cmd(struct ulink *device)
1038 {
1039         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1040         int ret;
1041
1042         if (!cmd)
1043                 return ERROR_FAIL;
1044
1045         cmd->id = CMD_GET_SIGNALS;
1046         cmd->needs_postprocessing = true;
1047
1048         /* CMD_GET_SIGNALS has two IN payload bytes */
1049         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_IN);
1050
1051         if (ret != ERROR_OK) {
1052                 free(cmd);
1053                 return ret;
1054         }
1055
1056         return ulink_append_queue(device, cmd);
1057 }
1058
1059 /**
1060  * Arbitrarily set JTAG output signals.
1061  *
1062  * @param device pointer to struct ulink identifying ULINK driver instance.
1063  * @param low defines which signals will be de-asserted. Each bit corresponds
1064  *  to a JTAG signal:
1065  *  - SIGNAL_TDI
1066  *  - SIGNAL_TMS
1067  *  - SIGNAL_TCK
1068  *  - SIGNAL_TRST
1069  *  - SIGNAL_BRKIN
1070  *  - SIGNAL_RESET
1071  *  - SIGNAL_OCDSE
1072  * @param high defines which signals will be asserted.
1073  * @return on success: ERROR_OK
1074  * @return on failure: ERROR_FAIL
1075  */
1076 static int ulink_append_set_signals_cmd(struct ulink *device, uint8_t low,
1077         uint8_t high)
1078 {
1079         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1080         int ret;
1081
1082         if (!cmd)
1083                 return ERROR_FAIL;
1084
1085         cmd->id = CMD_SET_SIGNALS;
1086
1087         /* CMD_SET_SIGNALS has two OUT payload bytes and zero IN payload bytes */
1088         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1089
1090         if (ret != ERROR_OK) {
1091                 free(cmd);
1092                 return ret;
1093         }
1094
1095         cmd->payload_out[0] = low;
1096         cmd->payload_out[1] = high;
1097
1098         return ulink_append_queue(device, cmd);
1099 }
1100
1101 /**
1102  * Sleep for a pre-defined number of microseconds
1103  *
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
1108  */
1109 static int ulink_append_sleep_cmd(struct ulink *device, uint32_t us)
1110 {
1111         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1112         int ret;
1113
1114         if (!cmd)
1115                 return ERROR_FAIL;
1116
1117         cmd->id = CMD_SLEEP_US;
1118
1119         /* CMD_SLEEP_US has two OUT payload bytes and zero IN payload bytes */
1120         ret = ulink_allocate_payload(cmd, 2, PAYLOAD_DIRECTION_OUT);
1121
1122         if (ret != ERROR_OK) {
1123                 free(cmd);
1124                 return ret;
1125         }
1126
1127         cmd->payload_out[0] = us & 0x00ff;
1128         cmd->payload_out[1] = (us >> 8) & 0x00ff;
1129
1130         return ulink_append_queue(device, cmd);
1131 }
1132
1133 /**
1134  * Set TCK delay counters
1135  *
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
1144  */
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)
1147 {
1148         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1149         int ret;
1150
1151         if (!cmd)
1152                 return ERROR_FAIL;
1153
1154         cmd->id = CMD_CONFIGURE_TCK_FREQ;
1155
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) {
1160                 free(cmd);
1161                 return ret;
1162         }
1163
1164         if (delay_scan_in < 0)
1165                 cmd->payload_out[0] = 0;
1166         else
1167                 cmd->payload_out[0] = (uint8_t)delay_scan_in;
1168
1169         if (delay_scan_out < 0)
1170                 cmd->payload_out[1] = 0;
1171         else
1172                 cmd->payload_out[1] = (uint8_t)delay_scan_out;
1173
1174         if (delay_scan_io < 0)
1175                 cmd->payload_out[2] = 0;
1176         else
1177                 cmd->payload_out[2] = (uint8_t)delay_scan_io;
1178
1179         if (delay_tck < 0)
1180                 cmd->payload_out[3] = 0;
1181         else
1182                 cmd->payload_out[3] = (uint8_t)delay_tck;
1183
1184         if (delay_tms < 0)
1185                 cmd->payload_out[4] = 0;
1186         else
1187                 cmd->payload_out[4] = (uint8_t)delay_tms;
1188
1189         return ulink_append_queue(device, cmd);
1190 }
1191
1192 /**
1193  * Turn on/off ULINK LEDs.
1194  *
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
1203  *  turned off.
1204  * @return on success: ERROR_OK
1205  * @return on failure: ERROR_FAIL
1206  */
1207 static int ulink_append_led_cmd(struct ulink *device, uint8_t led_state)
1208 {
1209         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1210         int ret;
1211
1212         if (!cmd)
1213                 return ERROR_FAIL;
1214
1215         cmd->id = CMD_SET_LEDS;
1216
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) {
1220                 free(cmd);
1221                 return ret;
1222         }
1223
1224         cmd->payload_out[0] = led_state;
1225
1226         return ulink_append_queue(device, cmd);
1227 }
1228
1229 /**
1230  * Test command. Used to check if the ULINK device is ready to accept new
1231  * commands.
1232  *
1233  * @param device pointer to struct ulink identifying ULINK driver instance.
1234  * @return on success: ERROR_OK
1235  * @return on failure: ERROR_FAIL
1236  */
1237 static int ulink_append_test_cmd(struct ulink *device)
1238 {
1239         struct ulink_cmd *cmd = calloc(1, sizeof(struct ulink_cmd));
1240         int ret;
1241
1242         if (!cmd)
1243                 return ERROR_FAIL;
1244
1245         cmd->id = CMD_TEST;
1246
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) {
1250                 free(cmd);
1251                 return ret;
1252         }
1253
1254         cmd->payload_out[0] = 0xAA;
1255
1256         return ulink_append_queue(device, cmd);
1257 }
1258
1259 /****************** OpenULINK TCK frequency helper functions ******************/
1260
1261 /**
1262  * Calculate delay values for a given TCK frequency.
1263  *
1264  * The OpenULINK firmware uses five different speed values for different
1265  * commands. These speed values are calculated in these functions.
1266  *
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
1271  *
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.
1276  *
1277  * The delay values are described by linear equations:
1278  *    t = k * x + d
1279  *    (t = period, k = constant, x = delay value, d = constant)
1280  *
1281  * Thus, the delay can be calculated as in the following equation:
1282  *    x = (t - d) / k
1283  *
1284  * The constants in these equations have been determined and validated by
1285  * measuring the frequency resulting from different delay values.
1286  *
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
1292  */
1293 static int ulink_calculate_delay(enum ulink_delay_type type, long f, int *delay)
1294 {
1295         float t, x, x_ceil;
1296
1297         /* Calculate period of requested TCK frequency */
1298         t = 1.0 / (float)(f);
1299
1300         switch (type) {
1301             case DELAY_CLOCK_TCK:
1302                     x = (t - (float)(6E-6)) / (float)(4E-6);
1303                     break;
1304             case DELAY_CLOCK_TMS:
1305                     x = (t - (float)(8.5E-6)) / (float)(4E-6);
1306                     break;
1307             case DELAY_SCAN_IN:
1308                     x = (t - (float)(8.8308E-6)) / (float)(4E-6);
1309                     break;
1310             case DELAY_SCAN_OUT:
1311                     x = (t - (float)(1.0527E-5)) / (float)(4E-6);
1312                     break;
1313             case DELAY_SCAN_IO:
1314                     x = (t - (float)(1.3132E-5)) / (float)(4E-6);
1315                     break;
1316             default:
1317                     return ERROR_FAIL;
1318                     break;
1319         }
1320
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. */
1324         if (x < 0)
1325                 x = 0;
1326
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. */
1330         x_ceil = ceilf(x);
1331
1332         /* Check if the value is within limits */
1333         if (x_ceil > 255)
1334                 return ERROR_FAIL;
1335
1336         *delay = (int)x_ceil;
1337
1338         return ERROR_OK;
1339 }
1340
1341 /**
1342  * Calculate frequency for a given delay value.
1343  *
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:
1346  *    t = k * x + d
1347  *    (t = period, k = constant, x = delay value, d = constant)
1348  *
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
1352  */
1353 static long ulink_calculate_frequency(enum ulink_delay_type type, int delay)
1354 {
1355         float t, f_float;
1356
1357         if (delay > 255)
1358                 return 0;
1359
1360         switch (type) {
1361             case DELAY_CLOCK_TCK:
1362                     if (delay < 0)
1363                             t = (float)(2.666E-6);
1364                     else
1365                             t = (float)(4E-6) * (float)(delay) + (float)(6E-6);
1366                     break;
1367             case DELAY_CLOCK_TMS:
1368                     if (delay < 0)
1369                             t = (float)(5.666E-6);
1370                     else
1371                             t = (float)(4E-6) * (float)(delay) + (float)(8.5E-6);
1372                     break;
1373             case DELAY_SCAN_IN:
1374                     if (delay < 0)
1375                             t = (float)(5.5E-6);
1376                     else
1377                             t = (float)(4E-6) * (float)(delay) + (float)(8.8308E-6);
1378                     break;
1379             case DELAY_SCAN_OUT:
1380                     if (delay < 0)
1381                             t = (float)(7.0E-6);
1382                     else
1383                             t = (float)(4E-6) * (float)(delay) + (float)(1.0527E-5);
1384                     break;
1385             case DELAY_SCAN_IO:
1386                     if (delay < 0)
1387                             t = (float)(9.926E-6);
1388                     else
1389                             t = (float)(4E-6) * (float)(delay) + (float)(1.3132E-5);
1390                     break;
1391             default:
1392                     return 0;
1393         }
1394
1395         f_float = 1.0 / t;
1396         return roundf(f_float);
1397 }
1398
1399 /******************* Interface between OpenULINK and OpenOCD ******************/
1400
1401 /**
1402  * Sets the end state follower (see interface.h) if \a endstate is a stable
1403  * state.
1404  *
1405  * @param endstate the state the end state follower should be set to.
1406  */
1407 static void ulink_set_end_state(tap_state_t endstate)
1408 {
1409         if (tap_is_state_stable(endstate))
1410                 tap_set_end_state(endstate);
1411         else {
1412                 LOG_ERROR("BUG: %s is not a valid end state", tap_state_name(endstate));
1413                 exit(EXIT_FAILURE);
1414         }
1415 }
1416
1417 /**
1418  * Move from the current TAP state to the current TAP end state.
1419  *
1420  * @param device pointer to struct ulink identifying ULINK driver instance.
1421  * @return on success: ERROR_OK
1422  * @return on failure: ERROR_FAIL
1423  */
1424 static int ulink_queue_statemove(struct ulink *device)
1425 {
1426         uint8_t tms_sequence, tms_count;
1427         int ret;
1428
1429         if (tap_get_state() == tap_get_end_state()) {
1430                 /* Do nothing if we are already there */
1431                 return ERROR_OK;
1432         }
1433
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());
1436
1437         ret = ulink_append_clock_tms_cmd(device, tms_count, tms_sequence);
1438
1439         if (ret == ERROR_OK)
1440                 tap_set_state(tap_get_end_state());
1441
1442         return ret;
1443 }
1444
1445 /**
1446  * Perform a scan operation on a JTAG register.
1447  *
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
1452  */
1453 static int ulink_queue_scan(struct ulink *device, struct jtag_command *cmd)
1454 {
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;
1459
1460         uint8_t first_tms_count, first_tms_sequence;
1461         uint8_t last_tms_count, last_tms_sequence;
1462
1463         uint8_t tms_count_pause, tms_sequence_pause;
1464         uint8_t tms_count_resume, tms_sequence_resume;
1465
1466         uint8_t tms_count_start, tms_sequence_start;
1467         uint8_t tms_count_end, tms_sequence_end;
1468
1469         enum scan_type type;
1470         int ret;
1471
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);
1475
1476         /* Determine scan type (IN/OUT/IO) */
1477         type = jtag_scan_type(cmd->cmd.scan);
1478
1479         /* Determine number of scan commands with maximum payload */
1480         scans_max_payload = scan_size_bytes / 58;
1481
1482         /* Determine size of last shift command */
1483         bits_last_scan = scan_size_bits - (scans_max_payload * 58 * 8);
1484
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);
1488
1489                 if (!tdo_buffer_start)
1490                         return ERROR_FAIL;
1491
1492                 tdo_buffer = tdo_buffer_start;
1493         }
1494
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;
1499         }
1500
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());
1506
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());
1511
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);
1517         } else {
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());
1521
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());
1526
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);
1532         }
1533
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;
1541                 } else {
1542                         /* Resume from previous scan */
1543                         tms_count_start = tms_count_resume;
1544                         tms_sequence_start = tms_sequence_resume;
1545                 }
1546
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;
1550
1551                         ret = ulink_append_scan_cmd(device,
1552                                         type,
1553                                         58 * 8,
1554                                         tdi_buffer,
1555                                         tdo_buffer_start,
1556                                         tdo_buffer,
1557                                         tms_count_start,
1558                                         tms_sequence_start,
1559                                         tms_count_end,
1560                                         tms_sequence_end,
1561                                         cmd,
1562                                         false);
1563
1564                         bytecount -= 58;
1565
1566                         /* Update TDI and TDO buffer pointers */
1567                         if (tdi_buffer_start)
1568                                 tdi_buffer += 58;
1569                         if (tdo_buffer_start)
1570                                 tdo_buffer += 58;
1571                 } else if (bytecount == 58) {   /* Full scan, no further scans */
1572                         tms_count_end = last_tms_count;
1573                         tms_sequence_end = last_tms_sequence;
1574
1575                         ret = ulink_append_scan_cmd(device,
1576                                         type,
1577                                         58 * 8,
1578                                         tdi_buffer,
1579                                         tdo_buffer_start,
1580                                         tdo_buffer,
1581                                         tms_count_start,
1582                                         tms_sequence_start,
1583                                         tms_count_end,
1584                                         tms_sequence_end,
1585                                         cmd,
1586                                         true);
1587
1588                         bytecount = 0;
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;
1592
1593                         ret = ulink_append_scan_cmd(device,
1594                                         type,
1595                                         bits_last_scan,
1596                                         tdi_buffer,
1597                                         tdo_buffer_start,
1598                                         tdo_buffer,
1599                                         tms_count_start,
1600                                         tms_sequence_start,
1601                                         tms_count_end,
1602                                         tms_sequence_end,
1603                                         cmd,
1604                                         true);
1605
1606                         bytecount = 0;
1607                 }
1608
1609                 if (ret != ERROR_OK) {
1610                         free(tdi_buffer_start);
1611                         free(tdo_buffer_start);
1612                         return ret;
1613                 }
1614         }
1615
1616         free(tdi_buffer_start);
1617
1618         /* Set current state to the end state requested by the command */
1619         tap_set_state(cmd->cmd.scan->end_state);
1620
1621         return ERROR_OK;
1622 }
1623
1624 /**
1625  * Move the TAP into the Test Logic Reset state.
1626  *
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
1631  */
1632 static int ulink_queue_tlr_reset(struct ulink *device, struct jtag_command *cmd)
1633 {
1634         int ret;
1635
1636         ret = ulink_append_clock_tms_cmd(device, 5, 0xff);
1637
1638         if (ret == ERROR_OK)
1639                 tap_set_state(TAP_RESET);
1640
1641         return ret;
1642 }
1643
1644 /**
1645  * Run Test.
1646  *
1647  * Generate TCK clock cycles while remaining
1648  * in the Run-Test/Idle state.
1649  *
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
1654  */
1655 static int ulink_queue_runtest(struct ulink *device, struct jtag_command *cmd)
1656 {
1657         int ret;
1658
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);
1663         }
1664
1665         /* Generate the clock cycles */
1666         ret = ulink_append_clock_tck_cmd(device, cmd->cmd.runtest->num_cycles);
1667         if (ret != ERROR_OK)
1668                 return ret;
1669
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);
1674         }
1675
1676         return ERROR_OK;
1677 }
1678
1679 /**
1680  * Execute a JTAG_RESET command
1681  *
1682  * @param device
1683  * @param cmd pointer to the command that shall be executed.
1684  * @return on success: ERROR_OK
1685  * @return on failure: ERROR_FAIL
1686  */
1687 static int ulink_queue_reset(struct ulink *device, struct jtag_command *cmd)
1688 {
1689         uint8_t low = 0, high = 0;
1690
1691         if (cmd->cmd.reset->trst) {
1692                 tap_set_state(TAP_RESET);
1693                 high |= SIGNAL_TRST;
1694         } else
1695                 low |= SIGNAL_TRST;
1696
1697         if (cmd->cmd.reset->srst)
1698                 high |= SIGNAL_RESET;
1699         else
1700                 low |= SIGNAL_RESET;
1701
1702         return ulink_append_set_signals_cmd(device, low, high);
1703 }
1704
1705 /**
1706  * Move to one TAP state or several states in succession.
1707  *
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
1712  */
1713 static int ulink_queue_pathmove(struct ulink *device, struct jtag_command *cmd)
1714 {
1715         int ret, i, num_states, batch_size, state_count;
1716         tap_state_t *path;
1717         uint8_t tms_sequence;
1718
1719         num_states = cmd->cmd.pathmove->num_states;
1720         path = cmd->cmd.pathmove->path;
1721         state_count = 0;
1722
1723         while (num_states > 0) {
1724                 tms_sequence = 0;
1725
1726                 /* Determine batch size */
1727                 if (num_states >= 8)
1728                         batch_size = 8;
1729                 else
1730                         batch_size = num_states;
1731
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);
1740                         } else {
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]));
1745                                 return ERROR_FAIL;
1746                         }
1747
1748                         tap_set_state(path[state_count]);
1749                         state_count++;
1750                         num_states--;
1751                 }
1752
1753                 /* Append CLOCK_TMS command to OpenULINK command queue */
1754                 LOG_INFO(
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)
1758                         return ret;
1759         }
1760
1761         return ERROR_OK;
1762 }
1763
1764 /**
1765  * Sleep for a specific amount of time.
1766  *
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
1771  */
1772 static int ulink_queue_sleep(struct ulink *device, struct jtag_command *cmd)
1773 {
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);
1777 }
1778
1779 /**
1780  * Generate TCK cycles while remaining in a stable state.
1781  *
1782  * @param device pointer to struct ulink identifying ULINK driver instance.
1783  * @param cmd pointer to the command that shall be executed.
1784  */
1785 static int ulink_queue_stableclocks(struct ulink *device, struct jtag_command *cmd)
1786 {
1787         int ret;
1788         unsigned num_cycles;
1789
1790         if (!tap_is_state_stable(tap_get_state())) {
1791                 LOG_ERROR("JTAG_STABLECLOCKS: state not stable");
1792                 return ERROR_FAIL;
1793         }
1794
1795         num_cycles = cmd->cmd.stableclocks->num_cycles;
1796
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);
1800         else
1801                 ret = ulink_append_set_signals_cmd(device, SIGNAL_TMS, 0);
1802
1803         if (ret != ERROR_OK)
1804                 return ret;
1805
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;
1811                 } else {
1812                         ret = ulink_append_clock_tck_cmd(device, num_cycles);
1813                         num_cycles = 0;
1814                 }
1815
1816                 if (ret != ERROR_OK)
1817                         return ret;
1818         }
1819
1820         return ERROR_OK;
1821 }
1822
1823 /**
1824  * Post-process JTAG_SCAN command
1825  *
1826  * @param ulink_cmd pointer to OpenULINK command that shall be processed.
1827  * @return on success: ERROR_OK
1828  * @return on failure: ERROR_FAIL
1829  */
1830 static int ulink_post_process_scan(struct ulink_cmd *ulink_cmd)
1831 {
1832         struct jtag_command *cmd = ulink_cmd->cmd_origin;
1833         int ret;
1834
1835         switch (jtag_scan_type(cmd->cmd.scan)) {
1836             case SCAN_IN:
1837             case SCAN_IO:
1838                     ret = jtag_read_buffer(ulink_cmd->payload_in_start, cmd->cmd.scan);
1839                     break;
1840             case SCAN_OUT:
1841                         /* Nothing to do for OUT scans */
1842                     ret = ERROR_OK;
1843                     break;
1844             default:
1845                     LOG_ERROR("BUG: ulink_post_process_scan() encountered an unknown"
1846                         " JTAG scan type");
1847                     ret = ERROR_FAIL;
1848                     break;
1849         }
1850
1851         return ret;
1852 }
1853
1854 /**
1855  * Perform post-processing of commands after OpenULINK queue has been executed.
1856  *
1857  * @param device pointer to struct ulink identifying ULINK driver instance.
1858  * @return on success: ERROR_OK
1859  * @return on failure: ERROR_FAIL
1860  */
1861 static int ulink_post_process_queue(struct ulink *device)
1862 {
1863         struct ulink_cmd *current;
1864         struct jtag_command *openocd_cmd;
1865         int ret;
1866
1867         current = device->queue_start;
1868
1869         while (current) {
1870                 openocd_cmd = current->cmd_origin;
1871
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) {
1876                             case JTAG_SCAN:
1877                                     ret = ulink_post_process_scan(current);
1878                                     break;
1879                             case JTAG_TLR_RESET:
1880                             case JTAG_RUNTEST:
1881                             case JTAG_RESET:
1882                             case JTAG_PATHMOVE:
1883                             case JTAG_SLEEP:
1884                             case JTAG_STABLECLOCKS:
1885                                         /* Nothing to do for these commands */
1886                                     ret = ERROR_OK;
1887                                     break;
1888                             default:
1889                                     ret = ERROR_FAIL;
1890                                     LOG_ERROR("BUG: ulink_post_process_queue() encountered unknown JTAG "
1891                                         "command type");
1892                                     break;
1893                         }
1894
1895                         if (ret != ERROR_OK)
1896                                 return ret;
1897                 }
1898
1899                 current = current->next;
1900         }
1901
1902         return ERROR_OK;
1903 }
1904
1905 /**************************** JTAG driver functions ***************************/
1906
1907 /**
1908  * Executes the JTAG Command Queue.
1909  *
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
1914  * commands.
1915  *
1916  * @return on success: ERROR_OK
1917  * @return on failure: ERROR_FAIL
1918  */
1919 static int ulink_execute_queue(void)
1920 {
1921         struct jtag_command *cmd = jtag_command_queue;
1922         int ret;
1923
1924         while (cmd) {
1925                 switch (cmd->type) {
1926                     case JTAG_SCAN:
1927                             ret = ulink_queue_scan(ulink_handle, cmd);
1928                             break;
1929                     case JTAG_TLR_RESET:
1930                             ret = ulink_queue_tlr_reset(ulink_handle, cmd);
1931                             break;
1932                     case JTAG_RUNTEST:
1933                             ret = ulink_queue_runtest(ulink_handle, cmd);
1934                             break;
1935                     case JTAG_RESET:
1936                             ret = ulink_queue_reset(ulink_handle, cmd);
1937                             break;
1938                     case JTAG_PATHMOVE:
1939                             ret = ulink_queue_pathmove(ulink_handle, cmd);
1940                             break;
1941                     case JTAG_SLEEP:
1942                             ret = ulink_queue_sleep(ulink_handle, cmd);
1943                             break;
1944                     case JTAG_STABLECLOCKS:
1945                             ret = ulink_queue_stableclocks(ulink_handle, cmd);
1946                             break;
1947                     default:
1948                             ret = ERROR_FAIL;
1949                             LOG_ERROR("BUG: encountered unknown JTAG command type");
1950                             break;
1951                 }
1952
1953                 if (ret != ERROR_OK)
1954                         return ret;
1955
1956                 cmd = cmd->next;
1957         }
1958
1959         if (ulink_handle->commands_in_queue > 0) {
1960                 ret = ulink_execute_queued_commands(ulink_handle, LIBUSB_TIMEOUT_MS);
1961                 if (ret != ERROR_OK)
1962                         return ret;
1963
1964                 ret = ulink_post_process_queue(ulink_handle);
1965                 if (ret != ERROR_OK)
1966                         return ret;
1967
1968                 ulink_clear_queue(ulink_handle);
1969         }
1970
1971         return ERROR_OK;
1972 }
1973
1974 /**
1975  * Set the TCK frequency of the ULINK adapter.
1976  *
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
1981  */
1982 static int ulink_khz(int khz, int *jtag_speed)
1983 {
1984         int ret;
1985
1986         if (khz == 0) {
1987                 LOG_ERROR("RCLK not supported");
1988                 return ERROR_FAIL;
1989         }
1990
1991         /* CLOCK_TCK commands are decoupled from others. Therefore, the frequency
1992          * setting can be done independently from all other commands. */
1993         if (khz >= 375)
1994                 ulink_handle->delay_clock_tck = -1;
1995         else {
1996                 ret = ulink_calculate_delay(DELAY_CLOCK_TCK, khz * 1000,
1997                                 &ulink_handle->delay_clock_tck);
1998                 if (ret != ERROR_OK)
1999                         return ret;
2000         }
2001
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! */
2006         if (khz >= 176) {
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;
2011         } else {
2012                 ret = ulink_calculate_delay(DELAY_CLOCK_TMS, khz * 1000,
2013                                 &ulink_handle->delay_clock_tms);
2014                 if (ret != ERROR_OK)
2015                         return ret;
2016
2017                 ret = ulink_calculate_delay(DELAY_SCAN_IN, khz * 1000,
2018                                 &ulink_handle->delay_scan_in);
2019                 if (ret != ERROR_OK)
2020                         return ret;
2021
2022                 ret = ulink_calculate_delay(DELAY_SCAN_OUT, khz * 1000,
2023                                 &ulink_handle->delay_scan_out);
2024                 if (ret != ERROR_OK)
2025                         return ret;
2026
2027                 ret = ulink_calculate_delay(DELAY_SCAN_IO, khz * 1000,
2028                                 &ulink_handle->delay_scan_io);
2029                 if (ret != ERROR_OK)
2030                         return ret;
2031         }
2032
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));
2048
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);
2056
2057         if (ret != ERROR_OK)
2058                 return ret;
2059
2060         *jtag_speed = khz;
2061
2062         return ERROR_OK;
2063 }
2064
2065 /**
2066  * Set the TCK frequency of the ULINK adapter.
2067  *
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
2071  * khz.
2072  *
2073  * @param speed desired adapter-specific speed value.
2074  * @return on success: ERROR_OK
2075  * @return on failure: ERROR_FAIL
2076  */
2077 static int ulink_speed(int speed)
2078 {
2079         int dummy;
2080
2081         return ulink_khz(speed, &dummy);
2082 }
2083
2084 /**
2085  * Convert adapter-specific speed value to corresponding TCK frequency in kHz.
2086  *
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
2090  * khz.
2091  *
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
2096  */
2097 static int ulink_speed_div(int speed, int *khz)
2098 {
2099         *khz = speed;
2100
2101         return ERROR_OK;
2102 }
2103
2104 /**
2105  * Initiates the firmware download to the ULINK adapter and prepares
2106  * the USB handle.
2107  *
2108  * @return on success: ERROR_OK
2109  * @return on failure: ERROR_FAIL
2110  */
2111 static int ulink_init(void)
2112 {
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;
2118
2119         ulink_handle = calloc(1, sizeof(struct ulink));
2120         if (!ulink_handle)
2121                 return ERROR_FAIL;
2122
2123         libusb_init(&ulink_handle->libusb_ctx);
2124
2125         ret = ulink_usb_open(&ulink_handle);
2126         if (ret != ERROR_OK) {
2127                 LOG_ERROR("Could not open ULINK device");
2128                 free(ulink_handle);
2129                 ulink_handle = NULL;
2130                 return ret;
2131         }
2132
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);
2135         if (ret < 0) {
2136                 /* Could not get descriptor -> Unconfigured or original Keil firmware */
2137                 download_firmware = true;
2138         } else {
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;
2142         }
2143
2144         if (download_firmware == true) {
2145                 LOG_INFO("Loading OpenULINK firmware. This is reversible by power-cycling"
2146                         " ULINK device.");
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");
2151                         free(ulink_handle);
2152                         ulink_handle = NULL;
2153                         return ret;
2154                 }
2155         } else
2156                 LOG_INFO("ULINK device is already running OpenULINK firmware");
2157
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)
2162                 return ret;
2163
2164         /* Initialize OpenULINK command queue */
2165         ulink_clear_queue(ulink_handle);
2166
2167         /* Issue one test command with short timeout */
2168         ret = ulink_append_test_cmd(ulink_handle);
2169         if (ret != ERROR_OK)
2170                 return ret;
2171
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));
2178
2179                 ret = libusb_bulk_transfer(ulink_handle->usb_device_handle, ulink_handle->ep_in,
2180                                 dummy, 64, &transferred, 200);
2181
2182                 free(dummy);
2183
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");
2188                         free(ulink_handle);
2189                         ulink_handle = NULL;
2190                         return ERROR_FAIL;
2191                 }
2192 #ifdef _DEBUG_USB_COMMS_
2193                 else {
2194                         /* Successfully received Bulk IN packet -> continue */
2195                         LOG_INFO("Recovered from lost Bulk IN packet");
2196                 }
2197 #endif
2198         }
2199         ulink_clear_queue(ulink_handle);
2200
2201         ret = ulink_append_get_signals_cmd(ulink_handle);
2202         if (ret == ERROR_OK)
2203                 ret = ulink_execute_queued_commands(ulink_handle, 200);
2204
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];
2209
2210                 ulink_print_signal_states(input_signals, output_signals);
2211         }
2212
2213         ulink_clear_queue(ulink_handle);
2214
2215         return ERROR_OK;
2216 }
2217
2218 /**
2219  * Closes the USB handle for the ULINK device.
2220  *
2221  * @return on success: ERROR_OK
2222  * @return on failure: ERROR_FAIL
2223  */
2224 static int ulink_quit(void)
2225 {
2226         int ret;
2227
2228         ret = ulink_usb_close(&ulink_handle);
2229         free(ulink_handle);
2230
2231         return ret;
2232 }
2233
2234 /**
2235  * Set a custom path to ULINK firmware image and force downloading to ULINK.
2236  */
2237 COMMAND_HANDLER(ulink_download_firmware_handler)
2238 {
2239         int ret;
2240
2241         if (CMD_ARGC != 1)
2242                 return ERROR_COMMAND_SYNTAX_ERROR;
2243
2244
2245         LOG_INFO("Downloading ULINK firmware image %s", CMD_ARGV[0]);
2246
2247         /* Download firmware image in CMD_ARGV[0] */
2248         ret = ulink_load_firmware_and_renumerate(&ulink_handle, CMD_ARGV[0],
2249                         ULINK_RENUMERATION_DELAY);
2250
2251         return ret;
2252 }
2253
2254 /*************************** Command Registration **************************/
2255
2256 static const struct command_registration ulink_subcommand_handlers[] = {
2257         {
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",
2263         },
2264         COMMAND_REGISTRATION_DONE,
2265 };
2266
2267 static const struct command_registration ulink_command_handlers[] = {
2268         {
2269                 .name = "ulink",
2270                 .mode = COMMAND_ANY,
2271                 .help = "perform ulink management",
2272                 .chain = ulink_subcommand_handlers,
2273                 .usage = "",
2274         },
2275         COMMAND_REGISTRATION_DONE
2276 };
2277
2278 static struct jtag_interface ulink_interface = {
2279         .execute_queue = ulink_execute_queue,
2280 };
2281
2282 struct adapter_driver ulink_adapter_driver = {
2283         .name = "ulink",
2284         .transports = jtag_only,
2285         .commands = ulink_command_handlers,
2286
2287         .init = ulink_init,
2288         .quit = ulink_quit,
2289         .speed = ulink_speed,
2290         .khz = ulink_khz,
2291         .speed_div = ulink_speed_div,
2292
2293         .jtag_ops = &ulink_interface,
2294 };