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