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