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