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