drivers: USB Blaster II: claim interface before using it
[fw/openocd] / src / jtag / drivers / jlink.c
1 /***************************************************************************
2  *   Copyright (C) 2007 by Juergen Stuber <juergen@jstuber.net>            *
3  *   based on Dominic Rath's and Benedikt Sauter's usbprog.c               *
4  *                                                                         *
5  *   Copyright (C) 2008 by Spencer Oliver                                  *
6  *   spen@spen-soft.co.uk                                                  *
7  *                                                                         *
8  *   Copyright (C) 2011 by Jean-Christophe PLAGNIOL-VIILARD                *
9  *   plagnioj@jcrosoft.com                                                 *
10  *                                                                         *
11  *   Copyright (C) 2015 by Marc Schink                                     *
12  *   openocd-dev@marcschink.de                                             *
13  *                                                                         *
14  *   Copyright (C) 2015 by Paul Fertser                                    *
15  *   fercerpav@gmail.com                                                   *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
29  ***************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include <stdint.h>
36 #include <math.h>
37
38 #include <jtag/interface.h>
39 #include <jtag/swd.h>
40 #include <jtag/commands.h>
41 #include <jtag/drivers/jtag_usb_common.h>
42 #include <target/cortex_m.h>
43
44 #include <libjaylink/libjaylink.h>
45
46 static struct jaylink_context *jayctx;
47 static struct jaylink_device_handle *devh;
48 static struct jaylink_connection conn;
49 static struct jaylink_connection connlist[JAYLINK_MAX_CONNECTIONS];
50 static enum jaylink_jtag_version jtag_command_version;
51 static uint8_t caps[JAYLINK_DEV_EXT_CAPS_SIZE];
52
53 static uint32_t serial_number;
54 static bool use_serial_number;
55 static bool use_usb_location;
56 static enum jaylink_usb_address usb_address;
57 static bool use_usb_address;
58 static enum jaylink_target_interface iface = JAYLINK_TIF_JTAG;
59 static bool trace_enabled;
60
61 #define JLINK_MAX_SPEED                 12000
62 #define JLINK_TAP_BUFFER_SIZE   2048
63
64 static unsigned int swd_buffer_size = JLINK_TAP_BUFFER_SIZE;
65
66 /* Maximum SWO frequency deviation. */
67 #define SWO_MAX_FREQ_DEV        0.03
68
69 /* 256 byte non-volatile memory */
70 struct device_config {
71         uint8_t usb_address;
72         /* 0ffset 0x01 to 0x03 */
73         uint8_t reserved_1[3];
74         uint32_t target_power;
75         /* 0ffset 0x08 to 0x1f */
76         uint8_t reserved_2[24];
77         /* IP only for J-Link Pro */
78         uint8_t ip_address[4];
79         uint8_t subnet_mask[4];
80         /* 0ffset 0x28 to 0x2f */
81         uint8_t reserved_3[8];
82         uint8_t mac_address[6];
83         /* 0ffset 0x36 to 0xff */
84         uint8_t reserved_4[202];
85 } __attribute__ ((packed));
86
87 static struct device_config config;
88 static struct device_config tmp_config;
89
90 /* Queue command functions */
91 static void jlink_end_state(tap_state_t state);
92 static void jlink_state_move(void);
93 static void jlink_path_move(int num_states, tap_state_t *path);
94 static void jlink_stableclocks(int num_cycles);
95 static void jlink_runtest(int num_cycles);
96 static void jlink_reset(int trst, int srst);
97 static int jlink_reset_safe(int trst, int srst);
98 static int jlink_swd_run_queue(void);
99 static void jlink_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk);
100 static int jlink_swd_switch_seq(enum swd_special_seq seq);
101
102 /* J-Link tap buffer functions */
103 static void jlink_tap_init(void);
104 static int jlink_flush(void);
105 /**
106  * Queue data to go out and in, flushing the queue as many times as
107  * necessary.
108  *
109  * @param out A pointer to TDI data, if NULL, old stale data will be used.
110  * @param out_offset A bit offset for TDI data.
111  * @param tms_out A pointer to TMS data, if NULL, zeroes will be emitted.
112  * @param tms_offset A bit offset for TMS data.
113  * @param in A pointer to store TDO data to, if NULL the data will be discarded.
114  * @param in_offset A bit offset for TDO data.
115  * @param length Amount of bits to transfer out and in.
116  *
117  * @retval This function doesn't return any value.
118  */
119 static void jlink_clock_data(const uint8_t *out, unsigned out_offset,
120                              const uint8_t *tms_out, unsigned tms_offset,
121                              uint8_t *in, unsigned in_offset,
122                              unsigned length);
123
124 static enum tap_state jlink_last_state = TAP_RESET;
125 static int queued_retval;
126
127 /***************************************************************************/
128 /* External interface implementation */
129
130 static void jlink_execute_stableclocks(struct jtag_command *cmd)
131 {
132         LOG_DEBUG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
133         jlink_stableclocks(cmd->cmd.runtest->num_cycles);
134 }
135
136 static void jlink_execute_runtest(struct jtag_command *cmd)
137 {
138         LOG_DEBUG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
139                 cmd->cmd.runtest->end_state);
140
141         jlink_end_state(cmd->cmd.runtest->end_state);
142         jlink_runtest(cmd->cmd.runtest->num_cycles);
143 }
144
145 static void jlink_execute_statemove(struct jtag_command *cmd)
146 {
147         LOG_DEBUG_IO("statemove end in %i", cmd->cmd.statemove->end_state);
148
149         jlink_end_state(cmd->cmd.statemove->end_state);
150         jlink_state_move();
151 }
152
153 static void jlink_execute_pathmove(struct jtag_command *cmd)
154 {
155         LOG_DEBUG_IO("pathmove: %i states, end in %i",
156                 cmd->cmd.pathmove->num_states,
157                 cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);
158
159         jlink_path_move(cmd->cmd.pathmove->num_states, cmd->cmd.pathmove->path);
160 }
161
162 static void jlink_execute_scan(struct jtag_command *cmd)
163 {
164         LOG_DEBUG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
165                 jtag_scan_type(cmd->cmd.scan));
166
167         /* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
168         while (cmd->cmd.scan->num_fields > 0
169                         && cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
170                 cmd->cmd.scan->num_fields--;
171                 LOG_DEBUG("discarding trailing empty field");
172         }
173
174         if (cmd->cmd.scan->num_fields == 0) {
175                 LOG_DEBUG("empty scan, doing nothing");
176                 return;
177         }
178
179         if (cmd->cmd.scan->ir_scan) {
180                 if (tap_get_state() != TAP_IRSHIFT) {
181                         jlink_end_state(TAP_IRSHIFT);
182                         jlink_state_move();
183                 }
184         } else {
185                 if (tap_get_state() != TAP_DRSHIFT) {
186                         jlink_end_state(TAP_DRSHIFT);
187                         jlink_state_move();
188                 }
189         }
190
191         jlink_end_state(cmd->cmd.scan->end_state);
192
193         struct scan_field *field = cmd->cmd.scan->fields;
194         unsigned scan_size = 0;
195
196         for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
197                 scan_size += field->num_bits;
198                 LOG_DEBUG_IO("%s%s field %d/%d %d bits",
199                         field->in_value ? "in" : "",
200                         field->out_value ? "out" : "",
201                         i,
202                         cmd->cmd.scan->num_fields,
203                         field->num_bits);
204
205                 if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
206                         /* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
207                          * movement. This last field can't have length zero, it was checked above. */
208                         jlink_clock_data(field->out_value,
209                                          0,
210                                          NULL,
211                                          0,
212                                          field->in_value,
213                                          0,
214                                          field->num_bits - 1);
215                         uint8_t last_bit = 0;
216                         if (field->out_value)
217                                 bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
218                         uint8_t tms_bits = 0x01;
219                         jlink_clock_data(&last_bit,
220                                          0,
221                                          &tms_bits,
222                                          0,
223                                          field->in_value,
224                                          field->num_bits - 1,
225                                          1);
226                         tap_set_state(tap_state_transition(tap_get_state(), 1));
227                         jlink_clock_data(NULL,
228                                          0,
229                                          &tms_bits,
230                                          1,
231                                          NULL,
232                                          0,
233                                          1);
234                         tap_set_state(tap_state_transition(tap_get_state(), 0));
235                 } else
236                         jlink_clock_data(field->out_value,
237                                          0,
238                                          NULL,
239                                          0,
240                                          field->in_value,
241                                          0,
242                                          field->num_bits);
243         }
244
245         if (tap_get_state() != tap_get_end_state()) {
246                 jlink_end_state(tap_get_end_state());
247                 jlink_state_move();
248         }
249
250         LOG_DEBUG_IO("%s scan, %i bits, end in %s",
251                 (cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
252                 tap_state_name(tap_get_end_state()));
253 }
254
255 static void jlink_execute_sleep(struct jtag_command *cmd)
256 {
257         LOG_DEBUG_IO("sleep %" PRIu32 "", cmd->cmd.sleep->us);
258         jlink_flush();
259         jtag_sleep(cmd->cmd.sleep->us);
260 }
261
262 static int jlink_execute_command(struct jtag_command *cmd)
263 {
264         switch (cmd->type) {
265                 case JTAG_STABLECLOCKS:
266                         jlink_execute_stableclocks(cmd);
267                         break;
268                 case JTAG_RUNTEST:
269                         jlink_execute_runtest(cmd);
270                         break;
271                 case JTAG_TLR_RESET:
272                         jlink_execute_statemove(cmd);
273                         break;
274                 case JTAG_PATHMOVE:
275                         jlink_execute_pathmove(cmd);
276                         break;
277                 case JTAG_SCAN:
278                         jlink_execute_scan(cmd);
279                         break;
280                 case JTAG_SLEEP:
281                         jlink_execute_sleep(cmd);
282                         break;
283                 default:
284                         LOG_ERROR("BUG: Unknown JTAG command type encountered.");
285                         return ERROR_JTAG_QUEUE_FAILED;
286         }
287
288         return ERROR_OK;
289 }
290
291 static int jlink_execute_queue(void)
292 {
293         int ret;
294         struct jtag_command *cmd = jtag_command_queue;
295
296         while (cmd != NULL) {
297                 ret = jlink_execute_command(cmd);
298
299                 if (ret != ERROR_OK)
300                         return ret;
301
302                 cmd = cmd->next;
303         }
304
305         return jlink_flush();
306 }
307
308 static int jlink_speed(int speed)
309 {
310         int ret;
311         struct jaylink_speed tmp;
312         int max_speed;
313
314         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_SPEEDS)) {
315                 ret = jaylink_get_speeds(devh, &tmp);
316
317                 if (ret != JAYLINK_OK) {
318                         LOG_ERROR("jaylink_get_speeds() failed: %s.",
319                                 jaylink_strerror(ret));
320                         return ERROR_JTAG_DEVICE_ERROR;
321                 }
322
323                 tmp.freq /= 1000;
324                 max_speed = tmp.freq / tmp.div;
325         } else {
326                 max_speed = JLINK_MAX_SPEED;
327         }
328
329         if (!speed) {
330                 if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ADAPTIVE_CLOCKING)) {
331                         LOG_ERROR("Adaptive clocking is not supported by the device.");
332                         return ERROR_JTAG_NOT_IMPLEMENTED;
333                 }
334
335                 speed = JAYLINK_SPEED_ADAPTIVE_CLOCKING;
336         } else if (speed > max_speed) {
337                 LOG_INFO("Reduced speed from %d kHz to %d kHz (maximum).", speed,
338                         max_speed);
339                 speed = max_speed;
340         }
341
342         ret = jaylink_set_speed(devh, speed);
343
344         if (ret != JAYLINK_OK) {
345                 LOG_ERROR("jaylink_set_speed() failed: %s.",
346                         jaylink_strerror(ret));
347                 return ERROR_JTAG_DEVICE_ERROR;
348         }
349
350         return ERROR_OK;
351 }
352
353 static int jlink_speed_div(int speed, int *khz)
354 {
355         *khz = speed;
356
357         return ERROR_OK;
358 }
359
360 static int jlink_khz(int khz, int *jtag_speed)
361 {
362         *jtag_speed = khz;
363
364         return ERROR_OK;
365 }
366
367 static bool read_device_config(struct device_config *cfg)
368 {
369         int ret;
370
371         ret = jaylink_read_raw_config(devh, (uint8_t *)cfg);
372
373         if (ret != JAYLINK_OK) {
374                 LOG_ERROR("jaylink_read_raw_config() failed: %s.",
375                         jaylink_strerror(ret));
376                 return false;
377         }
378
379         if (cfg->usb_address == 0xff)
380                 cfg->usb_address = 0x00;
381
382         if (cfg->target_power == 0xffffffff)
383                 cfg->target_power = 0;
384
385         return true;
386 }
387
388 static int select_interface(void)
389 {
390         int ret;
391         uint32_t interfaces;
392
393         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SELECT_TIF)) {
394                 if (iface != JAYLINK_TIF_JTAG) {
395                         LOG_ERROR("Device supports JTAG transport only.");
396                         return ERROR_JTAG_INIT_FAILED;
397                 }
398
399                 return ERROR_OK;
400         }
401
402         ret = jaylink_get_available_interfaces(devh, &interfaces);
403
404         if (ret != JAYLINK_OK) {
405                 LOG_ERROR("jaylink_get_available_interfaces() failed: %s.",
406                         jaylink_strerror(ret));
407                 return ERROR_JTAG_INIT_FAILED;
408         }
409
410         if (!(interfaces & (1 << iface))) {
411                 LOG_ERROR("Selected transport is not supported by the device.");
412                 return ERROR_JTAG_INIT_FAILED;
413         }
414
415         ret = jaylink_select_interface(devh, iface, NULL);
416
417         if (ret < 0) {
418                 LOG_ERROR("jaylink_select_interface() failed: %s.",
419                         jaylink_strerror(ret));
420                 return ERROR_JTAG_INIT_FAILED;
421         }
422
423         return ERROR_OK;
424 }
425
426 static int jlink_register(void)
427 {
428         int ret;
429         size_t i;
430         bool handle_found;
431         size_t count;
432
433         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_REGISTER))
434                 return ERROR_OK;
435
436         ret = jaylink_register(devh, &conn, connlist, &count);
437
438         if (ret != JAYLINK_OK) {
439                 LOG_ERROR("jaylink_register() failed: %s.", jaylink_strerror(ret));
440                 return ERROR_FAIL;
441         }
442
443         handle_found = false;
444
445         for (i = 0; i < count; i++) {
446                 if (connlist[i].handle == conn.handle) {
447                         handle_found = true;
448                         break;
449                 }
450         }
451
452         if (!handle_found) {
453                 LOG_ERROR("Registration failed: maximum number of connections on the "
454                         "device reached.");
455                 return ERROR_FAIL;
456         }
457
458         return ERROR_OK;
459 }
460
461 /*
462  * Adjust the SWD transaction buffer size depending on the free device internal
463  * memory. This ensures that the SWD transactions sent to the device do not
464  * exceed the internal memory of the device.
465  */
466 static bool adjust_swd_buffer_size(void)
467 {
468         int ret;
469         uint32_t tmp;
470
471         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY))
472                 return true;
473
474         ret = jaylink_get_free_memory(devh, &tmp);
475
476         if (ret != JAYLINK_OK) {
477                 LOG_ERROR("jaylink_get_free_memory() failed: %s.",
478                         jaylink_strerror(ret));
479                 return false;
480         }
481
482         if (tmp < 143) {
483                 LOG_ERROR("Not enough free device internal memory: %" PRIu32 " bytes.", tmp);
484                 return false;
485         }
486
487         tmp = MIN(JLINK_TAP_BUFFER_SIZE, (tmp - 16) / 2);
488
489         if (tmp != swd_buffer_size) {
490                 swd_buffer_size = tmp;
491                 LOG_DEBUG("Adjusted SWD transaction buffer size to %u bytes.",
492                         swd_buffer_size);
493         }
494
495         return true;
496 }
497
498 static int jaylink_log_handler(const struct jaylink_context *ctx,
499                 enum jaylink_log_level level, const char *format, va_list args,
500                 void *user_data)
501 {
502         enum log_levels tmp;
503
504         switch (level) {
505         case JAYLINK_LOG_LEVEL_ERROR:
506                 tmp = LOG_LVL_ERROR;
507                 break;
508         case JAYLINK_LOG_LEVEL_WARNING:
509                 tmp = LOG_LVL_WARNING;
510                 break;
511         /*
512          * Forward info messages to the debug output because they are more verbose
513          * than info messages of OpenOCD.
514          */
515         case JAYLINK_LOG_LEVEL_INFO:
516         case JAYLINK_LOG_LEVEL_DEBUG:
517                 tmp = LOG_LVL_DEBUG;
518                 break;
519         case JAYLINK_LOG_LEVEL_DEBUG_IO:
520                 tmp = LOG_LVL_DEBUG_IO;
521                 break;
522         default:
523                 tmp = LOG_LVL_WARNING;
524         }
525
526         log_vprintf_lf(tmp, __FILE__, __LINE__, __func__, format, args);
527
528         return 0;
529 }
530
531 static bool jlink_usb_location_equal(struct jaylink_device *dev)
532 {
533         int retval;
534         uint8_t bus;
535         uint8_t *ports;
536         size_t num_ports;
537         bool equal = false;
538
539         retval = jaylink_device_get_usb_bus_ports(dev, &bus, &ports, &num_ports);
540
541         if (retval == JAYLINK_ERR_NOT_SUPPORTED) {
542                 return false;
543         } else if (retval != JAYLINK_OK) {
544                 LOG_WARNING("jaylink_device_get_usb_bus_ports() failed: %s.",
545                         jaylink_strerror(retval));
546                 return false;
547         }
548
549         equal = jtag_usb_location_equal(bus, ports,     num_ports);
550         free(ports);
551
552         return equal;
553 }
554
555
556 static int jlink_open_device(uint32_t ifaces, bool *found_device)
557 {
558         int ret = jaylink_discovery_scan(jayctx, ifaces);
559         if (ret != JAYLINK_OK) {
560                 LOG_ERROR("jaylink_discovery_scan() failed: %s.", jaylink_strerror(ret));
561                 jaylink_exit(jayctx);
562                 return ERROR_JTAG_INIT_FAILED;
563         }
564
565         size_t num_devices;
566         struct jaylink_device **devs;
567         ret = jaylink_get_devices(jayctx, &devs, &num_devices);
568
569         if (ret != JAYLINK_OK) {
570                 LOG_ERROR("jaylink_get_devices() failed: %s.", jaylink_strerror(ret));
571                 jaylink_exit(jayctx);
572                 return ERROR_JTAG_INIT_FAILED;
573         }
574
575         use_usb_location = (jtag_usb_get_location() != NULL);
576
577         if (!use_serial_number && !use_usb_address && !use_usb_location && num_devices > 1) {
578                 LOG_ERROR("Multiple devices found, specify the desired device.");
579                 jaylink_free_devices(devs, true);
580                 jaylink_exit(jayctx);
581                 return ERROR_JTAG_INIT_FAILED;
582         }
583
584         *found_device = false;
585
586         for (size_t i = 0; devs[i]; i++) {
587                 struct jaylink_device *dev = devs[i];
588
589                 if (use_serial_number) {
590                         uint32_t tmp;
591                         ret = jaylink_device_get_serial_number(dev, &tmp);
592
593                         if (ret == JAYLINK_ERR_NOT_AVAILABLE) {
594                                 continue;
595                         } else if (ret != JAYLINK_OK) {
596                                 LOG_WARNING("jaylink_device_get_serial_number() failed: %s.",
597                                         jaylink_strerror(ret));
598                                 continue;
599                         }
600
601                         if (serial_number != tmp)
602                                 continue;
603                 }
604
605                 if (use_usb_address) {
606                         enum jaylink_usb_address address;
607                         ret = jaylink_device_get_usb_address(dev, &address);
608
609                         if (ret == JAYLINK_ERR_NOT_SUPPORTED) {
610                                 continue;
611                         } else if (ret != JAYLINK_OK) {
612                                 LOG_WARNING("jaylink_device_get_usb_address() failed: %s.",
613                                         jaylink_strerror(ret));
614                                 continue;
615                         }
616
617                         if (usb_address != address)
618                                 continue;
619                 }
620
621                 if (use_usb_location && !jlink_usb_location_equal(dev))
622                         continue;
623
624                 ret = jaylink_open(dev, &devh);
625
626                 if (ret == JAYLINK_OK) {
627                         *found_device = true;
628                         break;
629                 }
630
631                 LOG_ERROR("Failed to open device: %s.", jaylink_strerror(ret));
632         }
633
634         jaylink_free_devices(devs, true);
635         return ERROR_OK;
636 }
637
638
639 static int jlink_init(void)
640 {
641         int ret;
642         char *firmware_version;
643         struct jaylink_hardware_version hwver;
644         struct jaylink_hardware_status hwstatus;
645         size_t length;
646
647         LOG_DEBUG("Using libjaylink %s (compiled with %s).",
648                 jaylink_version_package_get_string(), JAYLINK_VERSION_PACKAGE_STRING);
649
650         if (!jaylink_library_has_cap(JAYLINK_CAP_HIF_USB) && use_usb_address) {
651                 LOG_ERROR("J-Link driver does not support USB devices.");
652                 return ERROR_JTAG_INIT_FAILED;
653         }
654
655         ret = jaylink_init(&jayctx);
656
657         if (ret != JAYLINK_OK) {
658                 LOG_ERROR("jaylink_init() failed: %s.", jaylink_strerror(ret));
659                 return ERROR_JTAG_INIT_FAILED;
660         }
661
662         ret = jaylink_log_set_callback(jayctx, &jaylink_log_handler, NULL);
663
664         if (ret != JAYLINK_OK) {
665                 LOG_ERROR("jaylink_log_set_callback() failed: %s.",
666                         jaylink_strerror(ret));
667                 jaylink_exit(jayctx);
668                 return ERROR_JTAG_INIT_FAILED;
669         }
670
671         bool found_device;
672         ret = jlink_open_device(JAYLINK_HIF_USB, &found_device);
673         if (ret != ERROR_OK)
674                 return ret;
675
676         if (!found_device && use_serial_number) {
677                 ret = jlink_open_device(JAYLINK_HIF_TCP, &found_device);
678                 if (ret != ERROR_OK)
679                         return ret;
680         }
681
682         if (!found_device) {
683                 LOG_ERROR("No J-Link device found.");
684                 jaylink_exit(jayctx);
685                 return ERROR_JTAG_INIT_FAILED;
686         }
687
688         /*
689          * Be careful with changing the following initialization sequence because
690          * some devices are known to be sensitive regarding the order.
691          */
692
693         ret = jaylink_get_firmware_version(devh, &firmware_version, &length);
694
695         if (ret != JAYLINK_OK) {
696                 LOG_ERROR("jaylink_get_firmware_version() failed: %s.",
697                         jaylink_strerror(ret));
698                 jaylink_close(devh);
699                 jaylink_exit(jayctx);
700                 return ERROR_JTAG_INIT_FAILED;
701         } else if (length > 0) {
702                 LOG_INFO("%s", firmware_version);
703                 free(firmware_version);
704         } else {
705                 LOG_WARNING("Device responds empty firmware version string.");
706         }
707
708         memset(caps, 0, JAYLINK_DEV_EXT_CAPS_SIZE);
709         ret = jaylink_get_caps(devh, caps);
710
711         if (ret != JAYLINK_OK) {
712                 LOG_ERROR("jaylink_get_caps() failed: %s.", jaylink_strerror(ret));
713                 jaylink_close(devh);
714                 jaylink_exit(jayctx);
715                 return ERROR_JTAG_INIT_FAILED;
716         }
717
718         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_EXT_CAPS)) {
719                 ret = jaylink_get_extended_caps(devh, caps);
720
721                 if (ret != JAYLINK_OK) {
722                         LOG_ERROR("jaylink_get_extended_caps() failed:  %s.",
723                                 jaylink_strerror(ret));
724                         jaylink_close(devh);
725                         jaylink_exit(jayctx);
726                         return ERROR_JTAG_INIT_FAILED;
727                 }
728         }
729
730         jtag_command_version = JAYLINK_JTAG_VERSION_2;
731
732         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_HW_VERSION)) {
733                 ret = jaylink_get_hardware_version(devh, &hwver);
734
735                 if (ret != JAYLINK_OK) {
736                         LOG_ERROR("Failed to retrieve hardware version: %s.",
737                                 jaylink_strerror(ret));
738                         jaylink_close(devh);
739                         jaylink_exit(jayctx);
740                         return ERROR_JTAG_INIT_FAILED;
741                 }
742
743                 LOG_INFO("Hardware version: %u.%02u", hwver.major, hwver.minor);
744
745                 if (hwver.major >= 5)
746                         jtag_command_version = JAYLINK_JTAG_VERSION_3;
747         }
748
749         if (iface == JAYLINK_TIF_SWD) {
750                 /*
751                  * Adjust the SWD transaction buffer size in case there is already
752                  * allocated memory on the device. This happens for example if the
753                  * memory for SWO capturing is still allocated because the software
754                  * which used the device before has not been shut down properly.
755                  */
756                 if (!adjust_swd_buffer_size()) {
757                         jaylink_close(devh);
758                         jaylink_exit(jayctx);
759                         return ERROR_JTAG_INIT_FAILED;
760                 }
761         }
762
763         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
764                 if (!read_device_config(&config)) {
765                         LOG_ERROR("Failed to read device configuration data.");
766                         jaylink_close(devh);
767                         jaylink_exit(jayctx);
768                         return ERROR_JTAG_INIT_FAILED;
769                 }
770
771                 memcpy(&tmp_config, &config, sizeof(struct device_config));
772         }
773
774         ret = jaylink_get_hardware_status(devh, &hwstatus);
775
776         if (ret != JAYLINK_OK) {
777                 LOG_ERROR("jaylink_get_hardware_status() failed: %s.",
778                         jaylink_strerror(ret));
779                 jaylink_close(devh);
780                 jaylink_exit(jayctx);
781                 return ERROR_JTAG_INIT_FAILED;
782         }
783
784         LOG_INFO("VTarget = %u.%03u V", hwstatus.target_voltage / 1000,
785                 hwstatus.target_voltage % 1000);
786
787         conn.handle = 0;
788         conn.pid = 0;
789         strcpy(conn.hid, "0.0.0.0");
790         conn.iid = 0;
791         conn.cid = 0;
792
793         ret = jlink_register();
794
795         if (ret != ERROR_OK) {
796                 jaylink_close(devh);
797                 jaylink_exit(jayctx);
798                 return ERROR_JTAG_INIT_FAILED;
799         }
800
801         ret = select_interface();
802
803         if (ret != ERROR_OK) {
804                 jaylink_close(devh);
805                 jaylink_exit(jayctx);
806                 return ret;
807         }
808
809         jlink_reset(0, 0);
810         jtag_sleep(3000);
811         jlink_tap_init();
812
813         jlink_speed(jtag_get_speed_khz());
814
815         if (iface == JAYLINK_TIF_JTAG) {
816                 /*
817                  * J-Link devices with firmware version v5 and v6 seems to have an issue
818                  * if the first tap move is not divisible by 8, so we send a TLR on
819                  * first power up.
820                  */
821                 uint8_t tms = 0xff;
822                 jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 8);
823
824                 jlink_flush();
825         }
826
827         return ERROR_OK;
828 }
829
830 static int jlink_quit(void)
831 {
832         int ret;
833         size_t count;
834
835         if (trace_enabled) {
836                 ret = jaylink_swo_stop(devh);
837
838                 if (ret != JAYLINK_OK)
839                         LOG_ERROR("jaylink_swo_stop() failed: %s.", jaylink_strerror(ret));
840         }
841
842         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_REGISTER)) {
843                 ret = jaylink_unregister(devh, &conn, connlist, &count);
844
845                 if (ret != JAYLINK_OK)
846                         LOG_ERROR("jaylink_unregister() failed: %s.",
847                                 jaylink_strerror(ret));
848         }
849
850         jaylink_close(devh);
851         jaylink_exit(jayctx);
852
853         return ERROR_OK;
854 }
855
856 /***************************************************************************/
857 /* Queue command implementations */
858
859 static void jlink_end_state(tap_state_t state)
860 {
861         if (tap_is_state_stable(state))
862                 tap_set_end_state(state);
863         else {
864                 LOG_ERROR("BUG: %i is not a valid end state", state);
865                 exit(-1);
866         }
867 }
868
869 /* Goes to the end state. */
870 static void jlink_state_move(void)
871 {
872         uint8_t tms_scan;
873         uint8_t tms_scan_bits;
874
875         tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
876         tms_scan_bits = tap_get_tms_path_len(tap_get_state(), tap_get_end_state());
877
878         jlink_clock_data(NULL, 0, &tms_scan, 0, NULL, 0, tms_scan_bits);
879
880         tap_set_state(tap_get_end_state());
881 }
882
883 static void jlink_path_move(int num_states, tap_state_t *path)
884 {
885         int i;
886         uint8_t tms = 0xff;
887
888         for (i = 0; i < num_states; i++) {
889                 if (path[i] == tap_state_transition(tap_get_state(), false))
890                         jlink_clock_data(NULL, 0, NULL, 0, NULL, 0, 1);
891                 else if (path[i] == tap_state_transition(tap_get_state(), true))
892                         jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 1);
893                 else {
894                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
895                                 tap_state_name(tap_get_state()), tap_state_name(path[i]));
896                         exit(-1);
897                 }
898
899                 tap_set_state(path[i]);
900         }
901
902         tap_set_end_state(tap_get_state());
903 }
904
905 static void jlink_stableclocks(int num_cycles)
906 {
907         int i;
908
909         uint8_t tms = tap_get_state() == TAP_RESET;
910         /* Execute num_cycles. */
911         for (i = 0; i < num_cycles; i++)
912                 jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 1);
913 }
914
915 static void jlink_runtest(int num_cycles)
916 {
917         tap_state_t saved_end_state = tap_get_end_state();
918
919         /* Only do a state_move when we're not already in IDLE. */
920         if (tap_get_state() != TAP_IDLE) {
921                 jlink_end_state(TAP_IDLE);
922                 jlink_state_move();
923                 /* num_cycles--; */
924         }
925
926         jlink_stableclocks(num_cycles);
927
928         /* Finish in end_state. */
929         jlink_end_state(saved_end_state);
930
931         if (tap_get_state() != tap_get_end_state())
932                 jlink_state_move();
933 }
934
935 static void jlink_reset(int trst, int srst)
936 {
937         LOG_DEBUG("TRST: %i, SRST: %i.", trst, srst);
938
939         /* Signals are active low. */
940         if (srst == 0)
941                 jaylink_set_reset(devh);
942
943         if (srst == 1)
944                 jaylink_clear_reset(devh);
945
946         if (trst == 1)
947                 jaylink_jtag_clear_trst(devh);
948
949         if (trst == 0)
950                 jaylink_jtag_set_trst(devh);
951 }
952
953 static int jlink_reset_safe(int trst, int srst)
954 {
955         jlink_flush();
956         jlink_reset(trst, srst);
957         return jlink_flush();
958 }
959
960 COMMAND_HANDLER(jlink_usb_command)
961 {
962         int tmp;
963
964         if (CMD_ARGC != 1) {
965                 command_print(CMD, "Need exactly one argument for jlink usb.");
966                 return ERROR_COMMAND_SYNTAX_ERROR;
967         }
968
969         if (sscanf(CMD_ARGV[0], "%i", &tmp) != 1) {
970                 command_print(CMD, "Invalid USB address: %s.", CMD_ARGV[0]);
971                 return ERROR_FAIL;
972         }
973
974         if (tmp < JAYLINK_USB_ADDRESS_0 || tmp > JAYLINK_USB_ADDRESS_3) {
975                 command_print(CMD, "Invalid USB address: %s.", CMD_ARGV[0]);
976                 return ERROR_FAIL;
977         }
978
979         usb_address = tmp;
980
981         use_serial_number = false;
982         use_usb_address = true;
983
984         return ERROR_OK;
985 }
986
987 COMMAND_HANDLER(jlink_serial_command)
988 {
989         int ret;
990
991         if (CMD_ARGC != 1) {
992                 command_print(CMD, "Need exactly one argument for jlink serial.");
993                 return ERROR_COMMAND_SYNTAX_ERROR;
994         }
995
996         ret = jaylink_parse_serial_number(CMD_ARGV[0], &serial_number);
997
998         if (ret == JAYLINK_ERR) {
999                 command_print(CMD, "Invalid serial number: %s.", CMD_ARGV[0]);
1000                 return ERROR_FAIL;
1001         } else if (ret != JAYLINK_OK) {
1002                 command_print(CMD, "jaylink_parse_serial_number() failed: %s.",
1003                         jaylink_strerror(ret));
1004                 return ERROR_FAIL;
1005         }
1006
1007         use_serial_number = true;
1008         use_usb_address = false;
1009
1010         return ERROR_OK;
1011 }
1012
1013 COMMAND_HANDLER(jlink_handle_hwstatus_command)
1014 {
1015         int ret;
1016         struct jaylink_hardware_status status;
1017
1018         ret = jaylink_get_hardware_status(devh, &status);
1019
1020         if (ret != JAYLINK_OK) {
1021                 command_print(CMD, "jaylink_get_hardware_status() failed: %s.",
1022                         jaylink_strerror(ret));
1023                 return ERROR_FAIL;
1024         }
1025
1026         command_print(CMD, "VTarget = %u.%03u V",
1027                 status.target_voltage / 1000, status.target_voltage % 1000);
1028
1029         command_print(CMD, "TCK = %u TDI = %u TDO = %u TMS = %u SRST = %u "
1030                 "TRST = %u", status.tck, status.tdi, status.tdo, status.tms,
1031                 status.tres, status.trst);
1032
1033         if (status.target_voltage < 1500)
1034                 command_print(CMD, "Target voltage too low. Check target power.");
1035
1036         return ERROR_OK;
1037 }
1038
1039 COMMAND_HANDLER(jlink_handle_free_memory_command)
1040 {
1041         int ret;
1042         uint32_t tmp;
1043
1044         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY)) {
1045                 command_print(CMD, "Retrieval of free memory is not supported by "
1046                         "the device.");
1047                 return ERROR_OK;
1048         }
1049
1050         ret = jaylink_get_free_memory(devh, &tmp);
1051
1052         if (ret != JAYLINK_OK) {
1053                 command_print(CMD, "jaylink_get_free_memory() failed: %s.",
1054                         jaylink_strerror(ret));
1055                 return ERROR_FAIL;
1056         }
1057
1058         command_print(CMD, "Device has %" PRIu32 " bytes of free memory.", tmp);
1059
1060         return ERROR_OK;
1061 }
1062
1063 COMMAND_HANDLER(jlink_handle_jlink_jtag_command)
1064 {
1065         int tmp;
1066         int version;
1067
1068         if (!CMD_ARGC) {
1069                 switch (jtag_command_version) {
1070                         case JAYLINK_JTAG_VERSION_2:
1071                                 version = 2;
1072                                 break;
1073                         case JAYLINK_JTAG_VERSION_3:
1074                                 version = 3;
1075                                 break;
1076                         default:
1077                                 return ERROR_FAIL;
1078                 }
1079
1080                 command_print(CMD, "JTAG command version: %i", version);
1081         } else if (CMD_ARGC == 1) {
1082                 if (sscanf(CMD_ARGV[0], "%i", &tmp) != 1) {
1083                         command_print(CMD, "Invalid argument: %s.", CMD_ARGV[0]);
1084                         return ERROR_COMMAND_SYNTAX_ERROR;
1085                 }
1086
1087                 switch (tmp) {
1088                         case 2:
1089                                 jtag_command_version = JAYLINK_JTAG_VERSION_2;
1090                                 break;
1091                         case 3:
1092                                 jtag_command_version = JAYLINK_JTAG_VERSION_3;
1093                                 break;
1094                         default:
1095                                 command_print(CMD, "Invalid argument: %s.", CMD_ARGV[0]);
1096                                 return ERROR_COMMAND_SYNTAX_ERROR;
1097                 }
1098         } else {
1099                 command_print(CMD, "Need exactly one argument for jlink jtag.");
1100                 return ERROR_COMMAND_SYNTAX_ERROR;
1101         }
1102
1103         return ERROR_OK;
1104 }
1105
1106 COMMAND_HANDLER(jlink_handle_target_power_command)
1107 {
1108         int ret;
1109         int enable;
1110
1111         if (CMD_ARGC != 1) {
1112                 command_print(CMD, "Need exactly one argument for jlink "
1113                         "targetpower.");
1114                 return ERROR_COMMAND_SYNTAX_ERROR;
1115         }
1116
1117         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER)) {
1118                 command_print(CMD, "Target power supply is not supported by the "
1119                         "device.");
1120                 return ERROR_OK;
1121         }
1122
1123         if (!strcmp(CMD_ARGV[0], "on")) {
1124                 enable = true;
1125         } else if (!strcmp(CMD_ARGV[0], "off")) {
1126                 enable = false;
1127         } else {
1128                 command_print(CMD, "Invalid argument: %s.", CMD_ARGV[0]);
1129                 return ERROR_FAIL;
1130         }
1131
1132         ret = jaylink_set_target_power(devh, enable);
1133
1134         if (ret != JAYLINK_OK) {
1135                 command_print(CMD, "jaylink_set_target_power() failed: %s.",
1136                         jaylink_strerror(ret));
1137                 return ERROR_FAIL;
1138         }
1139
1140         return ERROR_OK;
1141 }
1142
1143 static void show_config_usb_address(struct command_invocation *cmd)
1144 {
1145         if (config.usb_address != tmp_config.usb_address)
1146                 command_print(cmd, "USB address: %u [%u]", config.usb_address,
1147                         tmp_config.usb_address);
1148         else
1149                 command_print(cmd, "USB address: %u", config.usb_address);
1150 }
1151
1152 static void show_config_ip_address(struct command_invocation *cmd)
1153 {
1154         if (!memcmp(config.ip_address, tmp_config.ip_address, 4))
1155                 command_print(cmd, "IP address: %d.%d.%d.%d",
1156                         config.ip_address[3], config.ip_address[2],
1157                         config.ip_address[1], config.ip_address[0]);
1158         else
1159                 command_print(cmd, "IP address: %d.%d.%d.%d [%d.%d.%d.%d]",
1160                         config.ip_address[3], config.ip_address[2],
1161                         config.ip_address[1], config.ip_address[0],
1162                         tmp_config.ip_address[3], tmp_config.ip_address[2],
1163                         tmp_config.ip_address[1], tmp_config.ip_address[0]);
1164
1165         if (!memcmp(config.subnet_mask, tmp_config.subnet_mask, 4))
1166                 command_print(cmd, "Subnet mask: %d.%d.%d.%d",
1167                         config.subnet_mask[3], config.subnet_mask[2],
1168                         config.subnet_mask[1], config.subnet_mask[0]);
1169         else
1170                 command_print(cmd, "Subnet mask: %d.%d.%d.%d [%d.%d.%d.%d]",
1171                         config.subnet_mask[3], config.subnet_mask[2],
1172                         config.subnet_mask[1], config.subnet_mask[0],
1173                         tmp_config.subnet_mask[3], tmp_config.subnet_mask[2],
1174                         tmp_config.subnet_mask[1], tmp_config.subnet_mask[0]);
1175 }
1176
1177 static void show_config_mac_address(struct command_invocation *cmd)
1178 {
1179         if (!memcmp(config.mac_address, tmp_config.mac_address, 6))
1180                 command_print(cmd, "MAC address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x",
1181                         config.mac_address[5], config.mac_address[4],
1182                         config.mac_address[3], config.mac_address[2],
1183                         config.mac_address[1], config.mac_address[0]);
1184         else
1185                 command_print(cmd, "MAC address: %.02x:%.02x:%.02x:%.02x:%.02x:%.02x "
1186                         "[%.02x:%.02x:%.02x:%.02x:%.02x:%.02x]",
1187                         config.mac_address[5], config.mac_address[4],
1188                         config.mac_address[3], config.mac_address[2],
1189                         config.mac_address[1], config.mac_address[0],
1190                         tmp_config.mac_address[5], tmp_config.mac_address[4],
1191                         tmp_config.mac_address[3], tmp_config.mac_address[2],
1192                         tmp_config.mac_address[1], tmp_config.mac_address[0]);
1193 }
1194
1195 static void show_config_target_power(struct command_invocation *cmd)
1196 {
1197         const char *target_power;
1198         const char *current_target_power;
1199
1200         if (!config.target_power)
1201                 target_power = "off";
1202         else
1203                 target_power = "on";
1204
1205         if (!tmp_config.target_power)
1206                 current_target_power = "off";
1207         else
1208                 current_target_power = "on";
1209
1210         if (config.target_power != tmp_config.target_power)
1211                 command_print(cmd, "Target power supply: %s [%s]", target_power,
1212                         current_target_power);
1213         else
1214                 command_print(cmd, "Target power supply: %s", target_power);
1215 }
1216
1217 static void show_config(struct command_invocation *cmd)
1218 {
1219         command_print(cmd, "J-Link device configuration:");
1220
1221         show_config_usb_address(cmd);
1222
1223         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER))
1224                 show_config_target_power(cmd);
1225
1226         if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1227                 show_config_ip_address(cmd);
1228                 show_config_mac_address(cmd);
1229         }
1230 }
1231
1232 static int poll_trace(uint8_t *buf, size_t *size)
1233 {
1234         int ret;
1235         uint32_t length;
1236
1237         length = *size;
1238
1239         ret = jaylink_swo_read(devh, buf, &length);
1240
1241         if (ret != JAYLINK_OK) {
1242                 LOG_ERROR("jaylink_swo_read() failed: %s.", jaylink_strerror(ret));
1243                 return ERROR_FAIL;
1244         }
1245
1246         *size = length;
1247
1248         return ERROR_OK;
1249 }
1250
1251 static uint32_t calculate_trace_buffer_size(void)
1252 {
1253         int ret;
1254         uint32_t tmp;
1255
1256         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY))
1257                 return 0;
1258
1259         ret = jaylink_get_free_memory(devh, &tmp);
1260
1261         if (ret != JAYLINK_OK) {
1262                 LOG_ERROR("jaylink_get_free_memory() failed: %s.",
1263                         jaylink_strerror(ret));
1264                 return ERROR_FAIL;
1265         }
1266
1267         if (tmp > 0x3fff || tmp <= 0x600)
1268                 tmp = tmp >> 1;
1269         else
1270                 tmp = tmp - 0x400;
1271
1272         return tmp & 0xffffff00;
1273 }
1274
1275 static bool calculate_swo_prescaler(unsigned int traceclkin_freq,
1276                 uint32_t trace_freq, uint16_t *prescaler)
1277 {
1278         unsigned int presc = (traceclkin_freq + trace_freq / 2) / trace_freq;
1279         if (presc == 0 || presc > TPIU_ACPR_MAX_SWOSCALER + 1)
1280                 return false;
1281
1282         /* Probe's UART speed must be within 3% of the TPIU's SWO baud rate. */
1283         unsigned int max_deviation = (traceclkin_freq * 3) / 100;
1284         if (presc * trace_freq < traceclkin_freq - max_deviation ||
1285             presc * trace_freq > traceclkin_freq + max_deviation)
1286                 return false;
1287
1288         *prescaler = presc;
1289
1290         return true;
1291 }
1292
1293 static bool detect_swo_freq_and_prescaler(struct jaylink_swo_speed speed,
1294                 unsigned int traceclkin_freq, unsigned int *trace_freq,
1295                 uint16_t *prescaler)
1296 {
1297         uint32_t divider;
1298         unsigned int presc;
1299         double deviation;
1300
1301         for (divider = speed.min_div; divider <= speed.max_div; divider++) {
1302                 *trace_freq = speed.freq / divider;
1303                 presc = ((1.0 - SWO_MAX_FREQ_DEV) * traceclkin_freq) / *trace_freq + 1;
1304
1305                 if (presc > TPIU_ACPR_MAX_SWOSCALER + 1)
1306                         break;
1307
1308                 deviation = fabs(1.0 - ((double)*trace_freq * presc / traceclkin_freq));
1309
1310                 if (deviation <= SWO_MAX_FREQ_DEV) {
1311                         *prescaler = presc;
1312                         return true;
1313                 }
1314         }
1315
1316         return false;
1317 }
1318
1319 static int config_trace(bool enabled, enum tpiu_pin_protocol pin_protocol,
1320                 uint32_t port_size, unsigned int *trace_freq,
1321                 unsigned int traceclkin_freq, uint16_t *prescaler)
1322 {
1323         int ret;
1324         uint32_t buffer_size;
1325         struct jaylink_swo_speed speed;
1326         uint32_t divider;
1327         uint32_t min_freq;
1328         uint32_t max_freq;
1329
1330         trace_enabled = enabled;
1331
1332         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SWO)) {
1333                 if (!enabled)
1334                         return ERROR_OK;
1335
1336                 LOG_ERROR("Trace capturing is not supported by the device.");
1337                 return ERROR_FAIL;
1338         }
1339
1340         ret = jaylink_swo_stop(devh);
1341
1342         if (ret != JAYLINK_OK) {
1343                 LOG_ERROR("jaylink_swo_stop() failed: %s.", jaylink_strerror(ret));
1344                 return ERROR_FAIL;
1345         }
1346
1347         if (!enabled) {
1348                 /*
1349                  * Adjust the SWD transaction buffer size as stopping SWO capturing
1350                  * deallocates device internal memory.
1351                  */
1352                 if (!adjust_swd_buffer_size())
1353                         return ERROR_FAIL;
1354
1355                 return ERROR_OK;
1356         }
1357
1358         if (pin_protocol != TPIU_PIN_PROTOCOL_ASYNC_UART) {
1359                 LOG_ERROR("Selected pin protocol is not supported.");
1360                 return ERROR_FAIL;
1361         }
1362
1363         buffer_size = calculate_trace_buffer_size();
1364
1365         if (!buffer_size) {
1366                 LOG_ERROR("Not enough free device memory to start trace capturing.");
1367                 return ERROR_FAIL;
1368         }
1369
1370         ret = jaylink_swo_get_speeds(devh, JAYLINK_SWO_MODE_UART, &speed);
1371
1372         if (ret != JAYLINK_OK) {
1373                 LOG_ERROR("jaylink_swo_get_speeds() failed: %s.",
1374                         jaylink_strerror(ret));
1375                 return ERROR_FAIL;
1376         }
1377
1378         if (*trace_freq > 0) {
1379                 divider = speed.freq / *trace_freq;
1380                 min_freq = speed.freq / speed.max_div;
1381                 max_freq = speed.freq / speed.min_div;
1382
1383                 if (*trace_freq > max_freq) {
1384                         LOG_INFO("Given SWO frequency too high, using %" PRIu32 " Hz instead.",
1385                                 max_freq);
1386                         *trace_freq = max_freq;
1387                 } else if (*trace_freq < min_freq) {
1388                         LOG_INFO("Given SWO frequency too low, using %" PRIu32 " Hz instead.",
1389                                 min_freq);
1390                         *trace_freq = min_freq;
1391                 } else if (*trace_freq != speed.freq / divider) {
1392                         *trace_freq = speed.freq / divider;
1393
1394                         LOG_INFO("Given SWO frequency is not supported by the device, "
1395                                 "using %u Hz instead.", *trace_freq);
1396                 }
1397
1398                 if (!calculate_swo_prescaler(traceclkin_freq, *trace_freq,
1399                                 prescaler)) {
1400                         LOG_ERROR("SWO frequency is not suitable. Please choose a "
1401                                 "different frequency or use auto-detection.");
1402                         return ERROR_FAIL;
1403                 }
1404         } else {
1405                 LOG_INFO("Trying to auto-detect SWO frequency.");
1406
1407                 if (!detect_swo_freq_and_prescaler(speed, traceclkin_freq, trace_freq,
1408                                 prescaler)) {
1409                         LOG_ERROR("Maximum permitted frequency deviation of %.02f %% "
1410                                 "could not be achieved.", SWO_MAX_FREQ_DEV);
1411                         LOG_ERROR("Auto-detection of SWO frequency failed.");
1412                         return ERROR_FAIL;
1413                 }
1414
1415                 LOG_INFO("Using SWO frequency of %u Hz.", *trace_freq);
1416         }
1417
1418         ret = jaylink_swo_start(devh, JAYLINK_SWO_MODE_UART, *trace_freq,
1419                 buffer_size);
1420
1421         if (ret != JAYLINK_OK) {
1422                 LOG_ERROR("jaylink_start_swo() failed: %s.", jaylink_strerror(ret));
1423                 return ERROR_FAIL;
1424         }
1425
1426         LOG_DEBUG("Using %" PRIu32 " bytes device memory for trace capturing.",
1427                 buffer_size);
1428
1429         /*
1430          * Adjust the SWD transaction buffer size as starting SWO capturing
1431          * allocates device internal memory.
1432          */
1433         if (!adjust_swd_buffer_size())
1434                 return ERROR_FAIL;
1435
1436         return ERROR_OK;
1437 }
1438
1439 COMMAND_HANDLER(jlink_handle_config_usb_address_command)
1440 {
1441         uint8_t tmp;
1442
1443         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1444                 command_print(CMD, "Reading configuration is not supported by the "
1445                         "device.");
1446                 return ERROR_OK;
1447         }
1448
1449         if (!CMD_ARGC) {
1450                 show_config_usb_address(CMD);
1451         } else if (CMD_ARGC == 1) {
1452                 if (sscanf(CMD_ARGV[0], "%" SCNd8, &tmp) != 1) {
1453                         command_print(CMD, "Invalid USB address: %s.", CMD_ARGV[0]);
1454                         return ERROR_FAIL;
1455                 }
1456
1457                 if (tmp > JAYLINK_USB_ADDRESS_3) {
1458                         command_print(CMD, "Invalid USB address: %u.", tmp);
1459                         return ERROR_FAIL;
1460                 }
1461
1462                 tmp_config.usb_address = tmp;
1463         } else {
1464                 command_print(CMD, "Need exactly one argument for jlink config "
1465                         "usb.");
1466                 return ERROR_COMMAND_SYNTAX_ERROR;
1467         }
1468
1469         return ERROR_OK;
1470 }
1471
1472 COMMAND_HANDLER(jlink_handle_config_target_power_command)
1473 {
1474         int enable;
1475
1476         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1477                 command_print(CMD, "Reading configuration is not supported by the "
1478                         "device.");
1479                 return ERROR_OK;
1480         }
1481
1482         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SET_TARGET_POWER)) {
1483                 command_print(CMD, "Target power supply is not supported by the "
1484                         "device.");
1485                 return ERROR_OK;
1486         }
1487
1488         if (!CMD_ARGC) {
1489                 show_config_target_power(CMD);
1490         } else if (CMD_ARGC == 1) {
1491                 if (!strcmp(CMD_ARGV[0], "on")) {
1492                         enable = true;
1493                 } else if (!strcmp(CMD_ARGV[0], "off")) {
1494                         enable = false;
1495                 } else {
1496                         command_print(CMD, "Invalid argument: %s.", CMD_ARGV[0]);
1497                         return ERROR_FAIL;
1498                 }
1499
1500                 tmp_config.target_power = enable;
1501         } else {
1502                 command_print(CMD, "Need exactly one argument for jlink config "
1503                         "targetpower.");
1504                 return ERROR_COMMAND_SYNTAX_ERROR;
1505         }
1506
1507         return ERROR_OK;
1508 }
1509
1510 COMMAND_HANDLER(jlink_handle_config_mac_address_command)
1511 {
1512         uint8_t addr[6];
1513         int i;
1514         char *e;
1515         const char *str;
1516
1517         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1518                 command_print(CMD, "Reading configuration is not supported by the "
1519                         "device.");
1520                 return ERROR_OK;
1521         }
1522
1523         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1524                 command_print(CMD, "Ethernet connectivity is not supported by the "
1525                         "device.");
1526                 return ERROR_OK;
1527         }
1528
1529         if (!CMD_ARGC) {
1530                 show_config_mac_address(CMD);
1531         } else if (CMD_ARGC == 1) {
1532                 str = CMD_ARGV[0];
1533
1534                 if ((strlen(str) != 17) || (str[2] != ':' || str[5] != ':' ||
1535                                 str[8] != ':' || str[11] != ':' || str[14] != ':')) {
1536                         command_print(CMD, "Invalid MAC address format.");
1537                         return ERROR_COMMAND_SYNTAX_ERROR;
1538                 }
1539
1540                 for (i = 5; i >= 0; i--) {
1541                         addr[i] = strtoul(str, &e, 16);
1542                         str = e + 1;
1543                 }
1544
1545                 if (!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5])) {
1546                         command_print(CMD, "Invalid MAC address: zero address.");
1547                         return ERROR_COMMAND_SYNTAX_ERROR;
1548                 }
1549
1550                 if (!(0x01 & addr[0])) {
1551                         command_print(CMD, "Invalid MAC address: multicast address.");
1552                         return ERROR_COMMAND_SYNTAX_ERROR;
1553                 }
1554
1555                 memcpy(tmp_config.mac_address, addr, sizeof(addr));
1556         } else {
1557                 command_print(CMD, "Need exactly one argument for jlink config "
1558                         " mac.");
1559                 return ERROR_COMMAND_SYNTAX_ERROR;
1560         }
1561
1562         return ERROR_OK;
1563 }
1564
1565 static bool string_to_ip(const char *s, uint8_t *ip, int *pos)
1566 {
1567         uint8_t lip[4];
1568         char *e;
1569         const char *s_save = s;
1570         int i;
1571
1572         if (!s)
1573                 return false;
1574
1575         for (i = 0; i < 4; i++) {
1576                 lip[i] = strtoul(s, &e, 10);
1577
1578                 if (*e != '.' && i != 3)
1579                         return false;
1580
1581                 s = e + 1;
1582         }
1583
1584         *pos = e - s_save;
1585         memcpy(ip, lip, sizeof(lip));
1586
1587         return true;
1588 }
1589
1590 static void cpy_ip(uint8_t *dst, uint8_t *src)
1591 {
1592         int i, j;
1593
1594         for (i = 0, j = 3; i < 4; i++, j--)
1595                 dst[i] = src[j];
1596 }
1597
1598 COMMAND_HANDLER(jlink_handle_config_ip_address_command)
1599 {
1600         uint8_t ip_address[4];
1601         uint32_t subnet_mask = 0;
1602         int i, len;
1603         uint8_t subnet_bits = 24;
1604
1605         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1606                 command_print(CMD, "Reading configuration is not supported by the "
1607                         "device.");
1608                 return ERROR_OK;
1609         }
1610
1611         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ETHERNET)) {
1612                 command_print(CMD, "Ethernet connectivity is not supported by the "
1613                         "device.");
1614                 return ERROR_OK;
1615         }
1616
1617         if (!CMD_ARGC) {
1618                 show_config_ip_address(CMD);
1619         } else {
1620                 if (!string_to_ip(CMD_ARGV[0], ip_address, &i))
1621                         return ERROR_COMMAND_SYNTAX_ERROR;
1622
1623                 len = strlen(CMD_ARGV[0]);
1624
1625                 /* Check for format A.B.C.D/E. */
1626                 if (i < len) {
1627                         if (CMD_ARGV[0][i] != '/')
1628                                 return ERROR_COMMAND_SYNTAX_ERROR;
1629
1630                         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[0] + i + 1, subnet_bits);
1631                 } else if (CMD_ARGC > 1) {
1632                         if (!string_to_ip(CMD_ARGV[1], (uint8_t *)&subnet_mask, &i))
1633                                 return ERROR_COMMAND_SYNTAX_ERROR;
1634                 }
1635
1636                 if (!subnet_mask)
1637                         subnet_mask = (uint32_t)(subnet_bits < 32 ?
1638                                 ((1ULL << subnet_bits) - 1) : 0xffffffff);
1639
1640                 cpy_ip(tmp_config.ip_address, ip_address);
1641                 cpy_ip(tmp_config.subnet_mask, (uint8_t *)&subnet_mask);
1642         }
1643
1644         return ERROR_OK;
1645 }
1646
1647 COMMAND_HANDLER(jlink_handle_config_reset_command)
1648 {
1649         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG))
1650                 return ERROR_OK;
1651
1652         memcpy(&tmp_config, &config, sizeof(struct device_config));
1653
1654         return ERROR_OK;
1655 }
1656
1657
1658 COMMAND_HANDLER(jlink_handle_config_write_command)
1659 {
1660         int ret;
1661
1662         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1663                 command_print(CMD, "Reading configuration is not supported by the "
1664                         "device.");
1665                 return ERROR_OK;
1666         }
1667
1668         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_WRITE_CONFIG)) {
1669                 command_print(CMD, "Writing configuration is not supported by the "
1670                         "device.");
1671                 return ERROR_OK;
1672         }
1673
1674         if (!memcmp(&config, &tmp_config, sizeof(struct device_config))) {
1675                 command_print(CMD, "Operation not performed due to no changes in "
1676                         "the configuration.");
1677                 return ERROR_OK;
1678         }
1679
1680         ret = jaylink_write_raw_config(devh, (const uint8_t *)&tmp_config);
1681
1682         if (ret != JAYLINK_OK) {
1683                 LOG_ERROR("jaylink_write_raw_config() failed: %s.",
1684                         jaylink_strerror(ret));
1685                 return ERROR_FAIL;
1686         }
1687
1688         if (!read_device_config(&config)) {
1689                 LOG_ERROR("Failed to read device configuration for verification.");
1690                 return ERROR_FAIL;
1691         }
1692
1693         if (memcmp(&config, &tmp_config, sizeof(struct device_config))) {
1694                 LOG_ERROR("Verification of device configuration failed. Please check "
1695                         "your device.");
1696                 return ERROR_FAIL;
1697         }
1698
1699         memcpy(&tmp_config, &config, sizeof(struct device_config));
1700         command_print(CMD, "The new device configuration applies after power "
1701                 "cycling the J-Link device.");
1702
1703         return ERROR_OK;
1704 }
1705
1706 COMMAND_HANDLER(jlink_handle_config_command)
1707 {
1708         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
1709                 command_print(CMD, "Device doesn't support reading configuration.");
1710                 return ERROR_OK;
1711         }
1712
1713         if (CMD_ARGC == 0)
1714                 show_config(CMD);
1715
1716         return ERROR_OK;
1717 }
1718
1719 COMMAND_HANDLER(jlink_handle_emucom_write_command)
1720 {
1721         int ret;
1722         size_t tmp;
1723         uint32_t channel;
1724         uint32_t length;
1725         uint8_t *buf;
1726         size_t dummy;
1727
1728         if (CMD_ARGC != 2)
1729                 return ERROR_COMMAND_SYNTAX_ERROR;
1730
1731         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_EMUCOM)) {
1732                 LOG_ERROR("Device does not support EMUCOM.");
1733                 return ERROR_FAIL;
1734         }
1735
1736         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], channel);
1737
1738         tmp = strlen(CMD_ARGV[1]);
1739
1740         if (tmp % 2 != 0) {
1741                 LOG_ERROR("Data must be encoded as hexadecimal pairs.");
1742                 return ERROR_COMMAND_ARGUMENT_INVALID;
1743         }
1744
1745         buf = malloc(tmp / 2);
1746
1747         if (!buf) {
1748                 LOG_ERROR("Failed to allocate buffer.");
1749                 return ERROR_FAIL;
1750         }
1751
1752         dummy = unhexify(buf, CMD_ARGV[1], tmp / 2);
1753
1754         if (dummy != (tmp / 2)) {
1755                 LOG_ERROR("Data must be encoded as hexadecimal pairs.");
1756                 free(buf);
1757                 return ERROR_COMMAND_ARGUMENT_INVALID;
1758         }
1759
1760         length = tmp / 2;
1761         ret = jaylink_emucom_write(devh, channel, buf, &length);
1762
1763         free(buf);
1764
1765         if (ret == JAYLINK_ERR_DEV_NOT_SUPPORTED) {
1766                 LOG_ERROR("Channel not supported by the device.");
1767                 return ERROR_FAIL;
1768         } else if (ret != JAYLINK_OK) {
1769                 LOG_ERROR("Failed to write to channel: %s.", jaylink_strerror(ret));
1770                 return ERROR_FAIL;
1771         }
1772
1773         if (length != (tmp / 2))
1774                 LOG_WARNING("Only %" PRIu32 " bytes written to the channel.", length);
1775
1776         return ERROR_OK;
1777 }
1778
1779 COMMAND_HANDLER(jlink_handle_emucom_read_command)
1780 {
1781         int ret;
1782         uint32_t channel;
1783         uint32_t length;
1784         uint8_t *buf;
1785         size_t tmp;
1786
1787         if (CMD_ARGC != 2)
1788                 return ERROR_COMMAND_SYNTAX_ERROR;
1789
1790         if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_EMUCOM)) {
1791                 LOG_ERROR("Device does not support EMUCOM.");
1792                 return ERROR_FAIL;
1793         }
1794
1795         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[0], channel);
1796         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
1797
1798         buf = malloc(length * 3 + 1);
1799
1800         if (!buf) {
1801                 LOG_ERROR("Failed to allocate buffer.");
1802                 return ERROR_FAIL;
1803         }
1804
1805         ret = jaylink_emucom_read(devh, channel, buf, &length);
1806
1807         if (ret == JAYLINK_ERR_DEV_NOT_SUPPORTED) {
1808                 LOG_ERROR("Channel is not supported by the device.");
1809                 free(buf);
1810                 return ERROR_FAIL;
1811         } else if (ret == JAYLINK_ERR_DEV_NOT_AVAILABLE) {
1812                 LOG_ERROR("Channel is not available for the requested amount of data. "
1813                         "%" PRIu32 " bytes are available.", length);
1814                 free(buf);
1815                 return ERROR_FAIL;
1816         } else if (ret != JAYLINK_OK) {
1817                 LOG_ERROR("Failed to read from channel: %s.", jaylink_strerror(ret));
1818                 free(buf);
1819                 return ERROR_FAIL;
1820         }
1821
1822         tmp = hexify((char *)buf + length, buf, length, 2 * length + 1);
1823
1824         if (tmp != 2 * length) {
1825                 LOG_ERROR("Failed to convert data into hexadecimal string.");
1826                 free(buf);
1827                 return ERROR_FAIL;
1828         }
1829
1830         command_print(CMD, "%s", buf + length);
1831         free(buf);
1832
1833         return ERROR_OK;
1834 }
1835
1836 static const struct command_registration jlink_config_subcommand_handlers[] = {
1837         {
1838                 .name = "usb",
1839                 .handler = &jlink_handle_config_usb_address_command,
1840                 .mode = COMMAND_EXEC,
1841                 .help = "set the USB address",
1842                 .usage = "[0-3]",
1843         },
1844         {
1845                 .name = "targetpower",
1846                 .handler = &jlink_handle_config_target_power_command,
1847                 .mode = COMMAND_EXEC,
1848                 .help = "set the target power supply",
1849                 .usage = "[on|off]"
1850         },
1851         {
1852                 .name = "mac",
1853                 .handler = &jlink_handle_config_mac_address_command,
1854                 .mode = COMMAND_EXEC,
1855                 .help = "set the MAC Address",
1856                 .usage = "[ff:ff:ff:ff:ff:ff]",
1857         },
1858         {
1859                 .name = "ip",
1860                 .handler = &jlink_handle_config_ip_address_command,
1861                 .mode = COMMAND_EXEC,
1862                 .help = "set the IP address, where A.B.C.D is the IP address, "
1863                         "E the bit of the subnet mask, F.G.H.I the subnet mask",
1864                 .usage = "[A.B.C.D[/E] [F.G.H.I]]",
1865         },
1866         {
1867                 .name = "reset",
1868                 .handler = &jlink_handle_config_reset_command,
1869                 .mode = COMMAND_EXEC,
1870                 .help = "undo configuration changes",
1871                 .usage = "",
1872         },
1873         {
1874                 .name = "write",
1875                 .handler = &jlink_handle_config_write_command,
1876                 .mode = COMMAND_EXEC,
1877                 .help = "write configuration to the device",
1878                 .usage = "",
1879         },
1880         COMMAND_REGISTRATION_DONE
1881 };
1882
1883 static const struct command_registration jlink_emucom_subcommand_handlers[] = {
1884         {
1885                 .name = "write",
1886                 .handler = &jlink_handle_emucom_write_command,
1887                 .mode = COMMAND_EXEC,
1888                 .help = "write to a channel",
1889                 .usage = "<channel> <data>",
1890         },
1891         {
1892                 .name = "read",
1893                 .handler = &jlink_handle_emucom_read_command,
1894                 .mode = COMMAND_EXEC,
1895                 .help = "read from a channel",
1896                 .usage = "<channel> <length>"
1897         },
1898         COMMAND_REGISTRATION_DONE
1899 };
1900
1901 static const struct command_registration jlink_subcommand_handlers[] = {
1902         {
1903                 .name = "jtag",
1904                 .handler = &jlink_handle_jlink_jtag_command,
1905                 .mode = COMMAND_EXEC,
1906                 .help = "select the JTAG command version",
1907                 .usage = "[2|3]",
1908         },
1909         {
1910                 .name = "targetpower",
1911                 .handler = &jlink_handle_target_power_command,
1912                 .mode = COMMAND_EXEC,
1913                 .help = "set the target power supply",
1914                 .usage = "<on|off>"
1915         },
1916         {
1917                 .name = "freemem",
1918                 .handler = &jlink_handle_free_memory_command,
1919                 .mode = COMMAND_EXEC,
1920                 .help = "show free device memory",
1921                 .usage = "",
1922         },
1923         {
1924                 .name = "hwstatus",
1925                 .handler = &jlink_handle_hwstatus_command,
1926                 .mode = COMMAND_EXEC,
1927                 .help = "show the hardware status",
1928                 .usage = "",
1929         },
1930         {
1931                 .name = "usb",
1932                 .handler = &jlink_usb_command,
1933                 .mode = COMMAND_CONFIG,
1934                 .help = "set the USB address of the device that should be used",
1935                 .usage = "<0-3>"
1936         },
1937         {
1938                 .name = "serial",
1939                 .handler = &jlink_serial_command,
1940                 .mode = COMMAND_CONFIG,
1941                 .help = "set the serial number of the device that should be used",
1942                 .usage = "<serial number>"
1943         },
1944         {
1945                 .name = "config",
1946                 .handler = &jlink_handle_config_command,
1947                 .mode = COMMAND_EXEC,
1948                 .help = "access the device configuration. If no argument is given "
1949                         "this will show the device configuration",
1950                 .chain = jlink_config_subcommand_handlers,
1951                 .usage = "[<cmd>]",
1952         },
1953         {
1954                 .name = "emucom",
1955                 .mode = COMMAND_EXEC,
1956                 .help = "access EMUCOM channel",
1957                 .chain = jlink_emucom_subcommand_handlers,
1958                 .usage = "",
1959         },
1960         COMMAND_REGISTRATION_DONE
1961 };
1962
1963 static const struct command_registration jlink_command_handlers[] = {
1964         {
1965                 .name = "jlink",
1966                 .mode = COMMAND_ANY,
1967                 .help = "perform jlink management",
1968                 .chain = jlink_subcommand_handlers,
1969                 .usage = "",
1970         },
1971         COMMAND_REGISTRATION_DONE
1972 };
1973
1974 static int jlink_swd_init(void)
1975 {
1976         iface = JAYLINK_TIF_SWD;
1977
1978         return ERROR_OK;
1979 }
1980
1981 static void jlink_swd_write_reg(uint8_t cmd, uint32_t value, uint32_t ap_delay_clk)
1982 {
1983         assert(!(cmd & SWD_CMD_RnW));
1984         jlink_swd_queue_cmd(cmd, NULL, value, ap_delay_clk);
1985 }
1986
1987 static void jlink_swd_read_reg(uint8_t cmd, uint32_t *value, uint32_t ap_delay_clk)
1988 {
1989         assert(cmd & SWD_CMD_RnW);
1990         jlink_swd_queue_cmd(cmd, value, 0, ap_delay_clk);
1991 }
1992
1993 /***************************************************************************/
1994 /* J-Link tap functions */
1995
1996 static unsigned tap_length;
1997 /* In SWD mode use tms buffer for direction control */
1998 static uint8_t tms_buffer[JLINK_TAP_BUFFER_SIZE];
1999 static uint8_t tdi_buffer[JLINK_TAP_BUFFER_SIZE];
2000 static uint8_t tdo_buffer[JLINK_TAP_BUFFER_SIZE];
2001
2002 struct pending_scan_result {
2003         /** First bit position in tdo_buffer to read. */
2004         unsigned first;
2005         /** Number of bits to read. */
2006         unsigned length;
2007         /** Location to store the result */
2008         void *buffer;
2009         /** Offset in the destination buffer */
2010         unsigned buffer_offset;
2011 };
2012
2013 #define MAX_PENDING_SCAN_RESULTS 256
2014
2015 static int pending_scan_results_length;
2016 static struct pending_scan_result pending_scan_results_buffer[MAX_PENDING_SCAN_RESULTS];
2017
2018 static void jlink_tap_init(void)
2019 {
2020         tap_length = 0;
2021         pending_scan_results_length = 0;
2022         memset(tms_buffer, 0, sizeof(tms_buffer));
2023         memset(tdi_buffer, 0, sizeof(tdi_buffer));
2024 }
2025
2026 static void jlink_clock_data(const uint8_t *out, unsigned out_offset,
2027                              const uint8_t *tms_out, unsigned tms_offset,
2028                              uint8_t *in, unsigned in_offset,
2029                              unsigned length)
2030 {
2031         do {
2032                 unsigned available_length = JLINK_TAP_BUFFER_SIZE - tap_length / 8;
2033
2034                 if (!available_length ||
2035                     (in && pending_scan_results_length == MAX_PENDING_SCAN_RESULTS)) {
2036                         if (jlink_flush() != ERROR_OK)
2037                                 return;
2038                         available_length = JLINK_TAP_BUFFER_SIZE;
2039                 }
2040
2041                 struct pending_scan_result *pending_scan_result =
2042                         &pending_scan_results_buffer[pending_scan_results_length];
2043
2044                 unsigned scan_length = length > available_length ?
2045                         available_length : length;
2046
2047                 if (out)
2048                         buf_set_buf(out, out_offset, tdi_buffer, tap_length, scan_length);
2049                 if (tms_out)
2050                         buf_set_buf(tms_out, tms_offset, tms_buffer, tap_length, scan_length);
2051
2052                 if (in) {
2053                         pending_scan_result->first = tap_length;
2054                         pending_scan_result->length = scan_length;
2055                         pending_scan_result->buffer = in;
2056                         pending_scan_result->buffer_offset = in_offset;
2057                         pending_scan_results_length++;
2058                 }
2059
2060                 tap_length += scan_length;
2061                 out_offset += scan_length;
2062                 tms_offset += scan_length;
2063                 in_offset += scan_length;
2064                 length -= scan_length;
2065         } while (length > 0);
2066 }
2067
2068 static int jlink_flush(void)
2069 {
2070         int i;
2071         int ret;
2072
2073         if (!tap_length)
2074                 return ERROR_OK;
2075
2076         jlink_last_state = jtag_debug_state_machine(tms_buffer, tdi_buffer,
2077                 tap_length, jlink_last_state);
2078
2079         ret = jaylink_jtag_io(devh, tms_buffer, tdi_buffer, tdo_buffer,
2080                 tap_length, jtag_command_version);
2081
2082         if (ret != JAYLINK_OK) {
2083                 LOG_ERROR("jaylink_jtag_io() failed: %s.", jaylink_strerror(ret));
2084                 jlink_tap_init();
2085                 return ERROR_JTAG_QUEUE_FAILED;
2086         }
2087
2088         for (i = 0; i < pending_scan_results_length; i++) {
2089                 struct pending_scan_result *p = &pending_scan_results_buffer[i];
2090
2091                 buf_set_buf(tdo_buffer, p->first, p->buffer,
2092                             p->buffer_offset, p->length);
2093
2094                 LOG_DEBUG_IO("Pending scan result, length = %d.", p->length);
2095         }
2096
2097         jlink_tap_init();
2098
2099         return ERROR_OK;
2100 }
2101
2102 static void fill_buffer(uint8_t *buf, uint32_t val, uint32_t len)
2103 {
2104         unsigned int tap_pos = tap_length;
2105
2106         while (len > 32) {
2107                 buf_set_u32(buf, tap_pos, 32, val);
2108                 len -= 32;
2109                 tap_pos += 32;
2110         }
2111
2112         if (len)
2113                 buf_set_u32(buf, tap_pos, len, val);
2114 }
2115
2116 static void jlink_queue_data_out(const uint8_t *data, uint32_t len)
2117 {
2118         const uint32_t dir_out = 0xffffffff;
2119
2120         if (data)
2121                 bit_copy(tdi_buffer, tap_length, data, 0, len);
2122         else
2123                 fill_buffer(tdi_buffer, 0, len);
2124
2125         fill_buffer(tms_buffer, dir_out, len);
2126         tap_length += len;
2127 }
2128
2129 static void jlink_queue_data_in(uint32_t len)
2130 {
2131         const uint32_t dir_in = 0;
2132
2133         fill_buffer(tms_buffer, dir_in, len);
2134         tap_length += len;
2135 }
2136
2137 static int jlink_swd_switch_seq(enum swd_special_seq seq)
2138 {
2139         const uint8_t *s;
2140         unsigned int s_len;
2141
2142         switch (seq) {
2143                 case LINE_RESET:
2144                         LOG_DEBUG("SWD line reset");
2145                         s = swd_seq_line_reset;
2146                         s_len = swd_seq_line_reset_len;
2147                         break;
2148                 case JTAG_TO_SWD:
2149                         LOG_DEBUG("JTAG-to-SWD");
2150                         s = swd_seq_jtag_to_swd;
2151                         s_len = swd_seq_jtag_to_swd_len;
2152                         break;
2153                 case SWD_TO_JTAG:
2154                         LOG_DEBUG("SWD-to-JTAG");
2155                         s = swd_seq_swd_to_jtag;
2156                         s_len = swd_seq_swd_to_jtag_len;
2157                         break;
2158                 default:
2159                         LOG_ERROR("Sequence %d not supported.", seq);
2160                         return ERROR_FAIL;
2161         }
2162
2163         jlink_queue_data_out(s, s_len);
2164
2165         return ERROR_OK;
2166 }
2167
2168 static int jlink_swd_run_queue(void)
2169 {
2170         int i;
2171         int ret;
2172
2173         LOG_DEBUG("Executing %d queued transactions.", pending_scan_results_length);
2174
2175         if (queued_retval != ERROR_OK) {
2176                 LOG_DEBUG("Skipping due to previous errors: %d.", queued_retval);
2177                 goto skip;
2178         }
2179
2180         /*
2181          * A transaction must be followed by another transaction or at least 8 idle
2182          * cycles to ensure that data is clocked through the AP.
2183          */
2184         jlink_queue_data_out(NULL, 8);
2185
2186         ret = jaylink_swd_io(devh, tms_buffer, tdi_buffer, tdo_buffer, tap_length);
2187
2188         if (ret != JAYLINK_OK) {
2189                 LOG_ERROR("jaylink_swd_io() failed: %s.", jaylink_strerror(ret));
2190                 goto skip;
2191         }
2192
2193         for (i = 0; i < pending_scan_results_length; i++) {
2194                 int ack = buf_get_u32(tdo_buffer, pending_scan_results_buffer[i].first, 3);
2195
2196                 if (ack != SWD_ACK_OK) {
2197                         LOG_DEBUG("SWD ack not OK: %d %s", ack,
2198                                   ack == SWD_ACK_WAIT ? "WAIT" : ack == SWD_ACK_FAULT ? "FAULT" : "JUNK");
2199                         queued_retval = ack == SWD_ACK_WAIT ? ERROR_WAIT : ERROR_FAIL;
2200                         goto skip;
2201                 } else if (pending_scan_results_buffer[i].length) {
2202                         uint32_t data = buf_get_u32(tdo_buffer, 3 + pending_scan_results_buffer[i].first, 32);
2203                         int parity = buf_get_u32(tdo_buffer, 3 + 32 + pending_scan_results_buffer[i].first, 1);
2204
2205                         if (parity != parity_u32(data)) {
2206                                 LOG_ERROR("SWD: Read data parity mismatch.");
2207                                 queued_retval = ERROR_FAIL;
2208                                 goto skip;
2209                         }
2210
2211                         if (pending_scan_results_buffer[i].buffer)
2212                                 *(uint32_t *)pending_scan_results_buffer[i].buffer = data;
2213                 }
2214         }
2215
2216 skip:
2217         jlink_tap_init();
2218         ret = queued_retval;
2219         queued_retval = ERROR_OK;
2220
2221         return ret;
2222 }
2223
2224 static void jlink_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk)
2225 {
2226         uint8_t data_parity_trn[DIV_ROUND_UP(32 + 1, 8)];
2227         if (tap_length + 46 + 8 + ap_delay_clk >= swd_buffer_size * 8 ||
2228             pending_scan_results_length == MAX_PENDING_SCAN_RESULTS) {
2229                 /* Not enough room in the queue. Run the queue. */
2230                 queued_retval = jlink_swd_run_queue();
2231         }
2232
2233         if (queued_retval != ERROR_OK)
2234                 return;
2235
2236         cmd |= SWD_CMD_START | SWD_CMD_PARK;
2237
2238         jlink_queue_data_out(&cmd, 8);
2239
2240         pending_scan_results_buffer[pending_scan_results_length].first = tap_length;
2241
2242         if (cmd & SWD_CMD_RnW) {
2243                 /* Queue a read transaction. */
2244                 pending_scan_results_buffer[pending_scan_results_length].length = 32;
2245                 pending_scan_results_buffer[pending_scan_results_length].buffer = dst;
2246
2247                 jlink_queue_data_in(1 + 3 + 32 + 1 + 1);
2248         } else {
2249                 /* Queue a write transaction. */
2250                 pending_scan_results_buffer[pending_scan_results_length].length = 0;
2251                 jlink_queue_data_in(1 + 3 + 1);
2252
2253                 buf_set_u32(data_parity_trn, 0, 32, data);
2254                 buf_set_u32(data_parity_trn, 32, 1, parity_u32(data));
2255
2256                 jlink_queue_data_out(data_parity_trn, 32 + 1);
2257         }
2258
2259         pending_scan_results_length++;
2260
2261         /* Insert idle cycles after AP accesses to avoid WAIT. */
2262         if (cmd & SWD_CMD_APnDP)
2263                 jlink_queue_data_out(NULL, ap_delay_clk);
2264 }
2265
2266 static const struct swd_driver jlink_swd = {
2267         .init = &jlink_swd_init,
2268         .switch_seq = &jlink_swd_switch_seq,
2269         .read_reg = &jlink_swd_read_reg,
2270         .write_reg = &jlink_swd_write_reg,
2271         .run = &jlink_swd_run_queue,
2272 };
2273
2274 static const char * const jlink_transports[] = { "jtag", "swd", NULL };
2275
2276 static struct jtag_interface jlink_interface = {
2277         .execute_queue = &jlink_execute_queue,
2278 };
2279
2280 struct adapter_driver jlink_adapter_driver = {
2281         .name = "jlink",
2282         .transports = jlink_transports,
2283         .commands = jlink_command_handlers,
2284
2285         .init = &jlink_init,
2286         .quit = &jlink_quit,
2287         .reset = &jlink_reset_safe,
2288         .speed = &jlink_speed,
2289         .khz = &jlink_khz,
2290         .speed_div = &jlink_speed_div,
2291         .config_trace = &config_trace,
2292         .poll_trace = &poll_trace,
2293
2294         .jtag_ops = &jlink_interface,
2295         .swd_ops = &jlink_swd,
2296 };