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