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