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