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