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