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