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