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