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