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