jlink.c 53.8 KB
Newer Older
1 2 3 4
/***************************************************************************
 *   Copyright (C) 2007 by Juergen Stuber <juergen@jstuber.net>            *
 *   based on Dominic Rath's and Benedikt Sauter's usbprog.c               *
 *                                                                         *
5 6 7
 *   Copyright (C) 2008 by Spencer Oliver                                  *
 *   spen@spen-soft.co.uk                                                  *
 *                                                                         *
8 9 10
 *   Copyright (C) 2011 by Jean-Christophe PLAGNIOL-VIILARD                *
 *   plagnioj@jcrosoft.com                                                 *
 *                                                                         *
11 12 13
 *   Copyright (C) 2015 by Marc Schink                                     *
 *   openocd-dev@marcschink.de                                             *
 *                                                                         *
14 15 16
 *   Copyright (C) 2015 by Paul Fertser                                    *
 *   fercerpav@gmail.com                                                   *
 *                                                                         *
17 18 19 20 21 22 23 24 25 26 27
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   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 32 33 34
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

35 36 37
#include <stdint.h>
#include <math.h>

38
#include <jtag/interface.h>
39
#include <jtag/swd.h>
40
#include <jtag/commands.h>
41

42
#include <libjaylink/libjaylink.h>
43

44 45 46 47 48 49
static struct jaylink_context *jayctx;
static struct jaylink_device_handle *devh;
static struct jaylink_connection conn;
static struct jaylink_connection connlist[JAYLINK_MAX_CONNECTIONS];
static enum jaylink_jtag_version jtag_command_version;
static uint8_t caps[JAYLINK_DEV_EXT_CAPS_SIZE];
50

51 52
static uint32_t serial_number;
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
static bool trace_enabled;

#define JLINK_MAX_SPEED			12000
#define JLINK_TAP_BUFFER_SIZE	2048

static unsigned int swd_buffer_size = JLINK_TAP_BUFFER_SIZE;

/* 256 byte non-volatile memory */
struct device_config {
	uint8_t	usb_address;
	/* 0ffset 0x01 to 0x03 */
	uint8_t	reserved_1[3];
	uint32_t target_power;
	/* 0ffset 0x08 to 0x1f */
	uint8_t reserved_2[24];
	/* IP only for J-Link Pro */
	uint8_t ip_address[4];
	uint8_t subnet_mask[4];
	/* 0ffset 0x28 to 0x2f */
	uint8_t reserved_3[8];
	uint8_t mac_address[6];
	/* 0ffset 0x36 to 0xff */
	uint8_t reserved_4[202];
} __attribute__ ((packed));
80

81 82
static struct device_config config;
static struct device_config tmp_config;
83

84
/* Queue command functions */
85 86 87
static void jlink_end_state(tap_state_t state);
static void jlink_state_move(void);
static void jlink_path_move(int num_states, tap_state_t *path);
88
static void jlink_stableclocks(int num_cycles);
89 90
static void jlink_runtest(int num_cycles);
static void jlink_reset(int trst, int srst);
91 92 93
static int jlink_swd_run_queue(void);
static void jlink_swd_queue_cmd(uint8_t cmd, uint32_t *dst, uint32_t data, uint32_t ap_delay_clk);
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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
static int jlink_flush(void);
/**
 * Queue data to go out and in, flushing the queue as many times as
 * necessary.
 *
 * @param out A pointer to TDI data, if NULL, old stale data will be used.
 * @param out_offset A bit offset for TDI data.
 * @param tms_out A pointer to TMS data, if NULL, zeroes will be emitted.
 * @param tms_offset A bit offset for TMS data.
 * @param in A pointer to store TDO data to, if NULL the data will be discarded.
 * @param in_offset A bit offset for TDO data.
 * @param length Amount of bits to transfer out and in.
 *
 * @retval This function doesn't return any value.
 */
static void jlink_clock_data(const uint8_t *out, unsigned out_offset,
			     const uint8_t *tms_out, unsigned tms_offset,
			     uint8_t *in, unsigned in_offset,
			     unsigned length);
116

oharboe's avatar
oharboe committed
117
static enum tap_state jlink_last_state = TAP_RESET;
118
static int queued_retval;
119

120 121 122
/***************************************************************************/
/* External interface implementation */

123 124 125 126 127 128
static void jlink_execute_stableclocks(struct jtag_command *cmd)
{
	DEBUG_JTAG_IO("stableclocks %i cycles", cmd->cmd.runtest->num_cycles);
	jlink_stableclocks(cmd->cmd.runtest->num_cycles);
}

129
static void jlink_execute_runtest(struct jtag_command *cmd)
130
{
131 132
	DEBUG_JTAG_IO("runtest %i cycles, end in %i", cmd->cmd.runtest->num_cycles,
		cmd->cmd.runtest->end_state);
133

134
	jlink_end_state(cmd->cmd.runtest->end_state);
135 136 137
	jlink_runtest(cmd->cmd.runtest->num_cycles);
}

138
static void jlink_execute_statemove(struct jtag_command *cmd)
139 140 141
{
	DEBUG_JTAG_IO("statemove end in %i", cmd->cmd.statemove->end_state);

142
	jlink_end_state(cmd->cmd.statemove->end_state);
143 144 145
	jlink_state_move();
}

146
static void jlink_execute_pathmove(struct jtag_command *cmd)
147 148 149 150 151
{
	DEBUG_JTAG_IO("pathmove: %i states, end in %i",
		cmd->cmd.pathmove->num_states,
		cmd->cmd.pathmove->path[cmd->cmd.pathmove->num_states - 1]);

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 158 159 160 161 162 163 164 165 166 167 168 169 170
	DEBUG_JTAG_IO("%s type:%d", cmd->cmd.scan->ir_scan ? "IRSCAN" : "DRSCAN",
		jtag_scan_type(cmd->cmd.scan));

	/* Make sure there are no trailing fields with num_bits == 0, or the logic below will fail. */
	while (cmd->cmd.scan->num_fields > 0
			&& cmd->cmd.scan->fields[cmd->cmd.scan->num_fields - 1].num_bits == 0) {
		cmd->cmd.scan->num_fields--;
		LOG_DEBUG("discarding trailing empty field");
	}

	if (cmd->cmd.scan->num_fields == 0) {
		LOG_DEBUG("empty scan, doing nothing");
		return;
	}
171

172 173 174 175 176 177 178 179 180 181 182
	if (cmd->cmd.scan->ir_scan) {
		if (tap_get_state() != TAP_IRSHIFT) {
			jlink_end_state(TAP_IRSHIFT);
			jlink_state_move();
		}
	} else {
		if (tap_get_state() != TAP_DRSHIFT) {
			jlink_end_state(TAP_DRSHIFT);
			jlink_state_move();
		}
	}
183

184
	jlink_end_state(cmd->cmd.scan->end_state);
185

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	struct scan_field *field = cmd->cmd.scan->fields;
	unsigned scan_size = 0;

	for (int i = 0; i < cmd->cmd.scan->num_fields; i++, field++) {
		scan_size += field->num_bits;
		DEBUG_JTAG_IO("%s%s field %d/%d %d bits",
			field->in_value ? "in" : "",
			field->out_value ? "out" : "",
			i,
			cmd->cmd.scan->num_fields,
			field->num_bits);

		if (i == cmd->cmd.scan->num_fields - 1 && tap_get_state() != tap_get_end_state()) {
			/* Last field, and we're leaving IRSHIFT/DRSHIFT. Clock last bit during tap
			 * movement. This last field can't have length zero, it was checked above. */
			jlink_clock_data(field->out_value,
					 0,
					 NULL,
					 0,
					 field->in_value,
					 0,
					 field->num_bits - 1);
			uint8_t last_bit = 0;
			if (field->out_value)
				bit_copy(&last_bit, 0, field->out_value, field->num_bits - 1, 1);
			uint8_t tms_bits = 0x01;
			jlink_clock_data(&last_bit,
					 0,
					 &tms_bits,
					 0,
					 field->in_value,
					 field->num_bits - 1,
					 1);
			tap_set_state(tap_state_transition(tap_get_state(), 1));
220
			jlink_clock_data(NULL,
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
					 0,
					 &tms_bits,
					 1,
					 NULL,
					 0,
					 1);
			tap_set_state(tap_state_transition(tap_get_state(), 0));
		} else
			jlink_clock_data(field->out_value,
					 0,
					 NULL,
					 0,
					 field->in_value,
					 0,
					 field->num_bits);
	}

	if (tap_get_state() != tap_get_end_state()) {
		jlink_end_state(tap_get_end_state());
		jlink_state_move();
	}
242

243 244 245
	DEBUG_JTAG_IO("%s scan, %i bits, end in %s",
		(cmd->cmd.scan->ir_scan) ? "IR" : "DR", scan_size,
		tap_state_name(tap_get_end_state()));
246 247
}

248
static void jlink_execute_reset(struct jtag_command *cmd)
249
{
250 251
	DEBUG_JTAG_IO("reset trst: %i srst %i", cmd->cmd.reset->trst,
		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 263 264
	jtag_sleep(cmd->cmd.sleep->us);
}

265
static int jlink_execute_command(struct jtag_command *cmd)
266
{
267
	switch (cmd->type) {
268 269 270
		case JTAG_STABLECLOCKS:
			jlink_execute_stableclocks(cmd);
			break;
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
		case JTAG_RUNTEST:
			jlink_execute_runtest(cmd);
			break;
		case JTAG_TLR_RESET:
			jlink_execute_statemove(cmd);
			break;
		case JTAG_PATHMOVE:
			jlink_execute_pathmove(cmd);
			break;
		case JTAG_SCAN:
			jlink_execute_scan(cmd);
			break;
		case JTAG_RESET:
			jlink_execute_reset(cmd);
			break;
		case JTAG_SLEEP:
			jlink_execute_sleep(cmd);
			break;
		default:
290 291
			LOG_ERROR("BUG: Unknown JTAG command type encountered.");
			return ERROR_JTAG_QUEUE_FAILED;
292
	}
293 294

	return ERROR_OK;
295 296 297 298
}

static int jlink_execute_queue(void)
{
299
	int ret;
300
	struct jtag_command *cmd = jtag_command_queue;
301

302
	while (cmd != NULL) {
303 304 305 306 307
		ret = jlink_execute_command(cmd);

		if (ret != ERROR_OK)
			return ret;

308 309
		cmd = cmd->next;
	}
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 324

		if (ret != JAYLINK_OK) {
			LOG_ERROR("jaylink_get_speeds() failed: %s.",
325
				jaylink_strerror(ret));
326 327 328
			return ERROR_JTAG_DEVICE_ERROR;
		}

329 330
		tmp.freq /= 1000;
		max_speed = tmp.freq / tmp.div;
331 332
	} else {
		max_speed = JLINK_MAX_SPEED;
333
	}
334

335 336 337 338 339 340 341
	if (!speed) {
		if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_ADAPTIVE_CLOCKING)) {
			LOG_ERROR("Adaptive clocking is not supported by the device.");
			return ERROR_JTAG_NOT_IMPLEMENTED;
		}

		speed = JAYLINK_SPEED_ADAPTIVE_CLOCKING;
342 343 344 345
	} else if (speed > max_speed) {
		LOG_INFO("Reduced speed from %d kHz to %d kHz (maximum).", speed,
			max_speed);
		speed = max_speed;
346
	}
347

348
	ret = jaylink_set_speed(devh, speed);
349

350 351
	if (ret != JAYLINK_OK) {
		LOG_ERROR("jaylink_set_speed() failed: %s.",
352
			jaylink_strerror(ret));
353
		return ERROR_JTAG_DEVICE_ERROR;
354
	}
355

356 357 358
	return ERROR_OK;
}

359
static int jlink_speed_div(int speed, int *khz)
360 361 362 363 364 365
{
	*khz = speed;

	return ERROR_OK;
}

366
static int jlink_khz(int khz, int *jtag_speed)
367 368
{
	*jtag_speed = khz;
369

370 371 372
	return ERROR_OK;
}

373 374 375 376 377 378 379 380
static bool read_device_config(struct device_config *cfg)
{
	int ret;

	ret = jaylink_read_raw_config(devh, (uint8_t *)cfg);

	if (ret != JAYLINK_OK) {
		LOG_ERROR("jaylink_read_raw_config() failed: %s.",
381
			jaylink_strerror(ret));
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
		return false;
	}

	if (cfg->usb_address == 0xff)
		cfg->usb_address = 0x00;

	if (cfg->target_power == 0xffffffff)
		cfg->target_power = 0;

	return true;
}

static int select_interface(void)
{
	int ret;
	uint32_t interfaces;

	if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_SELECT_TIF)) {
		if (iface != JAYLINK_TIF_JTAG) {
			LOG_ERROR("Device supports JTAG transport only.");
			return ERROR_JTAG_INIT_FAILED;
		}

		return ERROR_OK;
	}

	ret = jaylink_get_available_interfaces(devh, &interfaces);

	if (ret != JAYLINK_OK) {
		LOG_ERROR("jaylink_get_available_interfaces() failed: %s.",
412
			jaylink_strerror(ret));
413 414 415 416 417 418 419 420
		return ERROR_JTAG_INIT_FAILED;
	}

	if (!(interfaces & (1 << iface))) {
		LOG_ERROR("Selected transport is not supported by the device.");
		return ERROR_JTAG_INIT_FAILED;
	}

421
	ret = jaylink_select_interface(devh, iface, NULL);
422 423 424

	if (ret < 0) {
		LOG_ERROR("jaylink_select_interface() failed: %s.",
425
			jaylink_strerror(ret));
426 427 428 429 430 431
		return ERROR_JTAG_INIT_FAILED;
	}

	return ERROR_OK;
}

432 433
static int jlink_register(void)
{
434
	int ret;
435
	size_t i;
436
	bool handle_found;
437
	size_t count;
438 439 440 441

	if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_REGISTER))
		return ERROR_OK;

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 450
	handle_found = false;

451
	for (i = 0; i < count; i++) {
452 453 454 455 456 457 458 459 460 461
		if (connlist[i].handle == conn.handle) {
			handle_found = true;
			break;
		}
	}

	if (!handle_found) {
		LOG_ERROR("Registration failed: maximum number of connections on the "
			"device reached.");
		return ERROR_FAIL;
462 463 464 465 466
	}

	return ERROR_OK;
}

467
/*
468 469 470
 * Adjust the SWD transaction buffer size depending on the free device internal
 * memory. This ensures that the SWD transactions sent to the device do not
 * exceed the internal memory of the device.
471
 */
472
static bool adjust_swd_buffer_size(void)
473
{
474 475
	int ret;
	uint32_t tmp;
476

477 478
	if (!jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_FREE_MEMORY))
		return true;
479

480
	ret = jaylink_get_free_memory(devh, &tmp);
481

482 483
	if (ret != JAYLINK_OK) {
		LOG_ERROR("jaylink_get_free_memory() failed: %s.",
484
			jaylink_strerror(ret));
485 486
		return false;
	}
487

488 489 490
	if (tmp < 143) {
		LOG_ERROR("Not enough free device internal memory: %u bytes.", tmp);
		return false;
491 492
	}

493
	tmp = MIN(JLINK_TAP_BUFFER_SIZE, (tmp - 16) / 2);
494

495 496 497 498
	if (tmp != swd_buffer_size) {
		swd_buffer_size = tmp;
		LOG_DEBUG("Adjusted SWD transaction buffer size to %u bytes.",
			swd_buffer_size);
499 500
	}

501
	return true;
502 503
}

504 505 506
static int jaylink_log_handler(const struct jaylink_context *ctx,
		enum jaylink_log_level level, const char *format, va_list args,
		void *user_data)
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
{
	enum log_levels tmp;

	switch (level) {
	case JAYLINK_LOG_LEVEL_ERROR:
		tmp = LOG_LVL_ERROR;
		break;
	case JAYLINK_LOG_LEVEL_WARNING:
		tmp = LOG_LVL_WARNING;
		break;
	/*
	 * Forward info messages to the debug output because they are more verbose
	 * than info messages of OpenOCD.
	 */
	case JAYLINK_LOG_LEVEL_INFO:
	case JAYLINK_LOG_LEVEL_DEBUG:
		tmp = LOG_LVL_DEBUG;
		break;
525 526 527
	case JAYLINK_LOG_LEVEL_DEBUG_IO:
		tmp = LOG_LVL_DEBUG_IO;
		break;
528 529 530 531 532 533 534 535 536
	default:
		tmp = LOG_LVL_WARNING;
	}

	log_vprintf_lf(tmp, __FILE__, __LINE__, __func__, format, args);

	return 0;
}

537
static int jlink_init(void)
538
{
539 540 541 542 543 544 545 546
	int ret;
	struct jaylink_device **devs;
	unsigned int i;
	bool found_device;
	uint32_t tmp;
	char *firmware_version;
	struct jaylink_hardware_version hwver;
	struct jaylink_hardware_status hwstatus;
547 548
	enum jaylink_usb_address address;
	size_t length;
549
	size_t num_devices;
Marc Schink's avatar
Marc Schink committed
550
	uint32_t host_interfaces;
551

Marc Schink's avatar
Marc Schink committed
552 553 554
	LOG_DEBUG("Using libjaylink %s (compiled with %s).",
		jaylink_version_package_get_string(), JAYLINK_VERSION_PACKAGE_STRING);

Marc Schink's avatar
Marc Schink committed
555 556 557 558 559
	if (!jaylink_library_has_cap(JAYLINK_CAP_HIF_USB) && use_usb_address) {
		LOG_ERROR("J-Link driver does not support USB devices.");
		return ERROR_JTAG_INIT_FAILED;
	}

560 561 562
	ret = jaylink_init(&jayctx);

	if (ret != JAYLINK_OK) {
563
		LOG_ERROR("jaylink_init() failed: %s.", jaylink_strerror(ret));
564 565
		return ERROR_JTAG_INIT_FAILED;
	}
zwelch's avatar
zwelch committed
566

567 568 569 570
	ret = jaylink_log_set_callback(jayctx, &jaylink_log_handler, NULL);

	if (ret != JAYLINK_OK) {
		LOG_ERROR("jaylink_log_set_callback() failed: %s.",
571
			jaylink_strerror(ret));
572 573 574 575
		jaylink_exit(jayctx);
		return ERROR_JTAG_INIT_FAILED;
	}

Marc Schink's avatar
Marc Schink committed
576 577 578 579 580 581
	host_interfaces = JAYLINK_HIF_USB;

	if (use_serial_number)
		host_interfaces |= JAYLINK_HIF_TCP;

	ret = jaylink_discovery_scan(jayctx, host_interfaces);
582

583 584
	if (ret != JAYLINK_OK) {
		LOG_ERROR("jaylink_discovery_scan() failed: %s.",
585
			jaylink_strerror(ret));
586 587 588 589
		jaylink_exit(jayctx);
		return ERROR_JTAG_INIT_FAILED;
	}

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 596
		return ERROR_JTAG_INIT_FAILED;
	}
597

598 599 600 601 602 603
	if (!use_serial_number && !use_usb_address && num_devices > 1) {
		LOG_ERROR("Multiple devices found, specify the desired device.");
		jaylink_free_devices(devs, true);
		jaylink_exit(jayctx);
		return ERROR_JTAG_INIT_FAILED;
	}
604

605
	found_device = false;
606 607

	for (i = 0; devs[i]; i++) {
608 609 610 611 612 613 614
		if (use_serial_number) {
			ret = jaylink_device_get_serial_number(devs[i], &tmp);

			if (ret == JAYLINK_ERR_NOT_AVAILABLE) {
				continue;
			} else if (ret != JAYLINK_OK) {
				LOG_WARNING("jaylink_device_get_serial_number() failed: %s.",
615
					jaylink_strerror(ret));
616 617 618 619 620 621 622 623 624
				continue;
			}

			if (serial_number != tmp)
				continue;
		}

		if (use_usb_address) {
			ret = jaylink_device_get_usb_address(devs[i], &address);
625

Marc Schink's avatar
Marc Schink committed
626 627 628
			if (ret == JAYLINK_ERR_NOT_SUPPORTED) {
				continue;
			} else if (ret != JAYLINK_OK) {
629
				LOG_WARNING("jaylink_device_get_usb_address() failed: %s.",
630
					jaylink_strerror(ret));
631 632
				continue;
			}
633

634 635 636
			if (usb_address != address)
				continue;
		}
637

638 639
		ret = jaylink_open(devs[i], &devh);

640 641 642
		if (ret == JAYLINK_OK) {
			found_device = true;
			break;
643 644
		}

645
		LOG_ERROR("Failed to open device: %s.", jaylink_strerror(ret));
646
	}
647

648
	jaylink_free_devices(devs, true);
649 650 651 652 653 654

	if (!found_device) {
		LOG_ERROR("No J-Link device found.");
		jaylink_exit(jayctx);
		return ERROR_JTAG_INIT_FAILED;
	}
655

656
	/*
657 658
	 * Be careful with changing the following initialization sequence because
	 * 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 667 668
		jaylink_close(devh);
		jaylink_exit(jayctx);
		return ERROR_JTAG_INIT_FAILED;
669 670 671 672 673
	} else if (length > 0) {
		LOG_INFO("%s", firmware_version);
		free(firmware_version);
	} else {
		LOG_WARNING("Device responds empty firmware version string.");
674 675 676 677 678 679
	}

	memset(caps, 0, JAYLINK_DEV_EXT_CAPS_SIZE);
	ret = jaylink_get_caps(devh, caps);

	if (ret != JAYLINK_OK) {
680
		LOG_ERROR("jaylink_get_caps() failed: %s.", jaylink_strerror(ret));
681 682 683 684 685 686 687 688 689 690
		jaylink_close(devh);
		jaylink_exit(jayctx);
		return ERROR_JTAG_INIT_FAILED;
	}

	if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_EXT_CAPS)) {
		ret = jaylink_get_extended_caps(devh, caps);

		if (ret != JAYLINK_OK) {
			LOG_ERROR("jaylink_get_extended_caps() failed:  %s.",
691
				jaylink_strerror(ret));
692 693 694 695 696 697
			jaylink_close(devh);
			jaylink_exit(jayctx);
			return ERROR_JTAG_INIT_FAILED;
		}
	}

698
	jtag_command_version = JAYLINK_JTAG_VERSION_2;
699 700 701 702 703 704

	if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_GET_HW_VERSION)) {
		ret = jaylink_get_hardware_version(devh, &hwver);

		if (ret != JAYLINK_OK) {
			LOG_ERROR("Failed to retrieve hardware version: %s.",
705
				jaylink_strerror(ret));
706 707 708 709 710 711 712 713
			jaylink_close(devh);
			jaylink_exit(jayctx);
			return ERROR_JTAG_INIT_FAILED;
		}

		LOG_INFO("Hardware version: %u.%02u", hwver.major, hwver.minor);

		if (hwver.major >= 5)
714
			jtag_command_version = JAYLINK_JTAG_VERSION_3;
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
	}

	if (iface == JAYLINK_TIF_SWD) {
		/*
		 * Adjust the SWD transaction buffer size in case there is already
		 * allocated memory on the device. This happens for example if the
		 * memory for SWO capturing is still allocated because the software
		 * which used the device before has not been shut down properly.
		 */
		if (!adjust_swd_buffer_size()) {
			jaylink_close(devh);
			jaylink_exit(jayctx);
			return ERROR_JTAG_INIT_FAILED;
		}
	}

	if (jaylink_has_cap(caps, JAYLINK_DEV_CAP_READ_CONFIG)) {
		if (!read_device_config(&config)) {
			LOG_ERROR("Failed to read device configuration data.");
			jaylink_close(devh);
			jaylink_exit(jayctx);
			return ERROR_JTAG_INIT_FAILED;
		}

		memcpy(&tmp_config, &config, sizeof(struct device_config));
	}

	ret = jaylink_get_hardware_status(devh, &hwstatus);

	if (ret != JAYLINK_OK) {
		LOG_ERROR("jaylink_get_hardware_status() failed: %s.",
746
			jaylink_strerror(ret));
747 748
		jaylink_close(devh);
		jaylink_exit(jayctx);
749 750
		return ERROR_JTAG_INIT_FAILED;
	}
751

752 753 754 755 756
	LOG_INFO("VTarget = %u.%03u V", hwstatus.target_voltage / 1000,
		hwstatus.target_voltage % 1000);

	conn.handle = 0;
	conn.pid = 0;
757
	strcpy(conn.hid, "0.0.0.0");
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
	conn.iid = 0;
	conn.cid = 0;

	ret = jlink_register();

	if (ret != ERROR_OK) {
		jaylink_close(devh);
		jaylink_exit(jayctx);
		return ERROR_JTAG_INIT_FAILED;
	}

	ret = select_interface();

	if (ret != ERROR_OK) {
		jaylink_close(devh);
		jaylink_exit(jayctx);
		return ret;
	}
776

777
	jlink_reset(0, 0);
778
	jtag_sleep(3000);
779
	jlink_tap_init();
780

781 782
	jlink_speed(jtag_get_speed_khz());

783 784 785 786 787 788
	if (iface == JAYLINK_TIF_JTAG) {
		/*
		 * J-Link devices with firmware version v5 and v6 seems to have an issue
		 * if the first tap move is not divisible by 8, so we send a TLR on
		 * first power up.
		 */
789 790
		uint8_t tms = 0xff;
		jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 8);
791

792
		jlink_flush();
793 794
	}

795 796 797
	return ERROR_OK;
}

798
static int jlink_quit(void)
799
{
800
	int ret;
801
	size_t count;
802 803 804 805 806

	if (trace_enabled) {
		ret = jaylink_swo_stop(devh);

		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 819 820
	}

	jaylink_close(devh);
	jaylink_exit(jayctx);

821 822 823 824 825 826
	return ERROR_OK;
}

/***************************************************************************/
/* Queue command implementations */

827
static void jlink_end_state(tap_state_t state)
828
{
829 830
	if (tap_is_state_stable(state))
		tap_set_end_state(state);
831
	else {
832 833 834 835 836 837
		LOG_ERROR("BUG: %i is not a valid end state", state);
		exit(-1);
	}
}

/* Goes to the end state. */
838
static void jlink_state_move(void)
839
{
840 841 842 843 844
	uint8_t tms_scan;
	uint8_t tms_scan_bits;

	tms_scan = tap_get_tms_path(tap_get_state(), tap_get_end_state());
	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 863
			LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition.",
				tap_state_name(tap_get_state()), tap_state_name(path[i]));
864 865
			exit(-1);
		}
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 878 879 880 881
	uint8_t tms = tap_get_state() == TAP_RESET;
	/* Execute num_cycles. */
	for (i = 0; i < num_cycles; i++)
		jlink_clock_data(NULL, 0, &tms, 0, NULL, 0, 1);
}
882

883 884 885
static void jlink_runtest(int num_cycles)
{
	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 901 902
		jlink_state_move();
}

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 924
	int tmp;

925 926 927 928
	if (CMD_ARGC != 1) {
		command_print(CMD_CTX, "Need exactly one argument for jlink usb.");
		return ERROR_COMMAND_SYNTAX_ERROR;
	}
929

930
	if (sscanf(CMD_ARGV[0], "%i", &tmp) != 1) {
931 932 933
		command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
		return ERROR_FAIL;
	}
934

935
	if (tmp < JAYLINK_USB_ADDRESS_0 || tmp > JAYLINK_USB_ADDRESS_3) {
936 937 938 939
		command_print(CMD_CTX, "Invalid USB address: %s.", CMD_ARGV[0]);
		return ERROR_FAIL;
	}

940 941
	usb_address = tmp;

942 943
	use_serial_number = false;
	use_usb_address = true;</