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