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