1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2010 Øyvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2009 SoftPLC Corporation                                *
9  *       http://softplc.com                                                *
10  *   dick@softplc.com                                                      *
11  *                                                                         *
12  *   Copyright (C) 2009 Zachary T Welch                                    *
13  *   zw@superlucidity.net                                                  *
14  *                                                                         *
15  *   This program is free software; you can redistribute it and/or modify  *
16  *   it under the terms of the GNU General Public License as published by  *
17  *   the Free Software Foundation; either version 2 of the License, or     *
18  *   (at your option) any later version.                                   *
19  *                                                                         *
20  *   This program is distributed in the hope that it will be useful,       *
21  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
22  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
23  *   GNU General Public License for more details.                          *
24  *                                                                         *
25  *   You should have received a copy of the GNU General Public License     *
26  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
27  ***************************************************************************/
28 
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32 
33 #include "jtag.h"
34 #include "swd.h"
35 #include "minidriver.h"
36 #include "interface.h"
37 #include "interfaces.h"
38 #include "tcl.h"
39 
40 #ifdef HAVE_STRINGS_H
41 #include <strings.h>
42 #endif
43 
44 #include <helper/time_support.h>
45 #include "transport/transport.h"
46 
47 /**
48  * @file
49  * Holds support for accessing JTAG-specific mechanisms from TCl scripts.
50  */
51 
52 static const Jim_Nvp nvp_jtag_tap_event[] = {
53 	{ .value = JTAG_TRST_ASSERTED,          .name = "post-reset" },
54 	{ .value = JTAG_TAP_EVENT_SETUP,        .name = "setup" },
55 	{ .value = JTAG_TAP_EVENT_ENABLE,       .name = "tap-enable" },
56 	{ .value = JTAG_TAP_EVENT_DISABLE,      .name = "tap-disable" },
57 
58 	{ .name = NULL, .value = -1 }
59 };
60 
jtag_tap_by_jim_obj(Jim_Interp * interp,Jim_Obj * o)61 struct jtag_tap *jtag_tap_by_jim_obj(Jim_Interp *interp, Jim_Obj *o)
62 {
63 	const char *cp = Jim_GetString(o, NULL);
64 	struct jtag_tap *t = cp ? jtag_tap_by_string(cp) : NULL;
65 	if (NULL == cp)
66 		cp = "(unknown)";
67 	if (NULL == t)
68 		Jim_SetResultFormatted(interp, "Tap '%s' could not be found", cp);
69 	return t;
70 }
71 
scan_is_safe(tap_state_t state)72 static bool scan_is_safe(tap_state_t state)
73 {
74 	switch (state) {
75 	    case TAP_RESET:
76 	    case TAP_IDLE:
77 	    case TAP_DRPAUSE:
78 	    case TAP_IRPAUSE:
79 		    return true;
80 	    default:
81 		    return false;
82 	}
83 }
84 
Jim_Command_drscan(Jim_Interp * interp,int argc,Jim_Obj * const * args)85 static int Jim_Command_drscan(Jim_Interp *interp, int argc, Jim_Obj *const *args)
86 {
87 	int retval;
88 	struct scan_field *fields;
89 	int num_fields;
90 	int field_count = 0;
91 	int i, e;
92 	struct jtag_tap *tap;
93 	tap_state_t endstate;
94 
95 	/* args[1] = device
96 	 * args[2] = num_bits
97 	 * args[3] = hex string
98 	 * ... repeat num bits and hex string ...
99 	 *
100 	 * .. optionally:
101 	*     args[N-2] = "-endstate"
102 	 *     args[N-1] = statename
103 	 */
104 	if ((argc < 4) || ((argc % 2) != 0)) {
105 		Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
106 		return JIM_ERR;
107 	}
108 
109 	endstate = TAP_IDLE;
110 
111 	script_debug(interp, argc, args);
112 
113 	/* validate arguments as numbers */
114 	e = JIM_OK;
115 	for (i = 2; i < argc; i += 2) {
116 		long bits;
117 		const char *cp;
118 
119 		e = Jim_GetLong(interp, args[i], &bits);
120 		/* If valid - try next arg */
121 		if (e == JIM_OK)
122 			continue;
123 
124 		/* Not valid.. are we at the end? */
125 		if (((i + 2) != argc)) {
126 			/* nope, then error */
127 			return e;
128 		}
129 
130 		/* it could be: "-endstate FOO"
131 		 * e.g. DRPAUSE so we can issue more instructions
132 		 * before entering RUN/IDLE and executing them.
133 		 */
134 
135 		/* get arg as a string. */
136 		cp = Jim_GetString(args[i], NULL);
137 		/* is it the magic? */
138 		if (0 == strcmp("-endstate", cp)) {
139 			/* is the statename valid? */
140 			cp = Jim_GetString(args[i + 1], NULL);
141 
142 			/* see if it is a valid state name */
143 			endstate = tap_state_by_name(cp);
144 			if (endstate < 0) {
145 				/* update the error message */
146 				Jim_SetResultFormatted(interp, "endstate: %s invalid", cp);
147 			} else {
148 				if (!scan_is_safe(endstate))
149 					LOG_WARNING("drscan with unsafe "
150 						"endstate \"%s\"", cp);
151 
152 				/* valid - so clear the error */
153 				e = JIM_OK;
154 				/* and remove the last 2 args */
155 				argc -= 2;
156 			}
157 		}
158 
159 		/* Still an error? */
160 		if (e != JIM_OK)
161 			return e;	/* too bad */
162 	}	/* validate args */
163 
164 	assert(e == JIM_OK);
165 
166 	tap = jtag_tap_by_jim_obj(interp, args[1]);
167 	if (tap == NULL)
168 		return JIM_ERR;
169 
170 	num_fields = (argc-2)/2;
171 	if (num_fields <= 0) {
172 		Jim_SetResultString(interp, "drscan: no scan fields supplied", -1);
173 		return JIM_ERR;
174 	}
175 	fields = malloc(sizeof(struct scan_field) * num_fields);
176 	for (i = 2; i < argc; i += 2) {
177 		long bits;
178 		int len;
179 		const char *str;
180 
181 		Jim_GetLong(interp, args[i], &bits);
182 		str = Jim_GetString(args[i + 1], &len);
183 
184 		fields[field_count].num_bits = bits;
185 		void *t = malloc(DIV_ROUND_UP(bits, 8));
186 		fields[field_count].out_value = t;
187 		str_to_buf(str, len, t, bits, 0);
188 		fields[field_count].in_value = t;
189 		field_count++;
190 	}
191 
192 	jtag_add_dr_scan(tap, num_fields, fields, endstate);
193 
194 	retval = jtag_execute_queue();
195 	if (retval != ERROR_OK) {
196 		Jim_SetResultString(interp, "drscan: jtag execute failed", -1);
197 
198 		for (i = 0; i < field_count; i++)
199 			free(fields[i].in_value);
200 		free(fields);
201 
202 		return JIM_ERR;
203 	}
204 
205 	field_count = 0;
206 	Jim_Obj *list = Jim_NewListObj(interp, NULL, 0);
207 	for (i = 2; i < argc; i += 2) {
208 		long bits;
209 		char *str;
210 
211 		Jim_GetLong(interp, args[i], &bits);
212 		str = buf_to_hex_str(fields[field_count].in_value, bits);
213 		free(fields[field_count].in_value);
214 
215 		Jim_ListAppendElement(interp, list, Jim_NewStringObj(interp, str, strlen(str)));
216 		free(str);
217 		field_count++;
218 	}
219 
220 	Jim_SetResult(interp, list);
221 
222 	free(fields);
223 
224 	return JIM_OK;
225 }
226 
227 
Jim_Command_pathmove(Jim_Interp * interp,int argc,Jim_Obj * const * args)228 static int Jim_Command_pathmove(Jim_Interp *interp, int argc, Jim_Obj *const *args)
229 {
230 	tap_state_t states[8];
231 
232 	if ((argc < 2) || ((size_t)argc > (ARRAY_SIZE(states) + 1))) {
233 		Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
234 		return JIM_ERR;
235 	}
236 
237 	script_debug(interp, argc, args);
238 
239 	int i;
240 	for (i = 0; i < argc-1; i++) {
241 		const char *cp;
242 		cp = Jim_GetString(args[i + 1], NULL);
243 		states[i] = tap_state_by_name(cp);
244 		if (states[i] < 0) {
245 			/* update the error message */
246 			Jim_SetResultFormatted(interp, "endstate: %s invalid", cp);
247 			return JIM_ERR;
248 		}
249 	}
250 
251 	if ((jtag_add_statemove(states[0]) != ERROR_OK) || (jtag_execute_queue() != ERROR_OK)) {
252 		Jim_SetResultString(interp, "pathmove: jtag execute failed", -1);
253 		return JIM_ERR;
254 	}
255 
256 	jtag_add_pathmove(argc - 2, states + 1);
257 
258 	if (jtag_execute_queue() != ERROR_OK) {
259 		Jim_SetResultString(interp, "pathmove: failed", -1);
260 		return JIM_ERR;
261 	}
262 
263 	return JIM_OK;
264 }
265 
266 
Jim_Command_flush_count(Jim_Interp * interp,int argc,Jim_Obj * const * args)267 static int Jim_Command_flush_count(Jim_Interp *interp, int argc, Jim_Obj *const *args)
268 {
269 	script_debug(interp, argc, args);
270 
271 	Jim_SetResult(interp, Jim_NewIntObj(interp, jtag_get_flush_queue_count()));
272 
273 	return JIM_OK;
274 }
275 
276 /* REVISIT Just what about these should "move" ... ?
277  * These registrations, into the main JTAG table?
278  *
279  * There's a minor compatibility issue, these all show up twice;
280  * that's not desirable:
281  *  - jtag drscan ... NOT DOCUMENTED!
282  *  - drscan ...
283  *
284  * The "irscan" command (for example) doesn't show twice.
285  */
286 static const struct command_registration jtag_command_handlers_to_move[] = {
287 	{
288 		.name = "drscan",
289 		.mode = COMMAND_EXEC,
290 		.jim_handler = Jim_Command_drscan,
291 		.help = "Execute Data Register (DR) scan for one TAP.  "
292 			"Other TAPs must be in BYPASS mode.",
293 		.usage = "tap_name [num_bits value]* ['-endstate' state_name]",
294 	},
295 	{
296 		.name = "flush_count",
297 		.mode = COMMAND_EXEC,
298 		.jim_handler = Jim_Command_flush_count,
299 		.help = "Returns the number of times the JTAG queue "
300 			"has been flushed.",
301 	},
302 	{
303 		.name = "pathmove",
304 		.mode = COMMAND_EXEC,
305 		.jim_handler = Jim_Command_pathmove,
306 		.usage = "start_state state1 [state2 [state3 ...]]",
307 		.help = "Move JTAG state machine from current state "
308 			"(start_state) to state1, then state2, state3, etc.",
309 	},
310 	COMMAND_REGISTRATION_DONE
311 };
312 
313 
314 enum jtag_tap_cfg_param {
315 	JCFG_EVENT,
316 	JCFG_IDCODE,
317 };
318 
319 static Jim_Nvp nvp_config_opts[] = {
320 	{ .name = "-event",      .value = JCFG_EVENT },
321 	{ .name = "-idcode",     .value = JCFG_IDCODE },
322 
323 	{ .name = NULL,          .value = -1 }
324 };
325 
jtag_tap_configure_event(Jim_GetOptInfo * goi,struct jtag_tap * tap)326 static int jtag_tap_configure_event(Jim_GetOptInfo *goi, struct jtag_tap *tap)
327 {
328 	if (goi->argc == 0) {
329 		Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name> ...");
330 		return JIM_ERR;
331 	}
332 
333 	Jim_Nvp *n;
334 	int e = Jim_GetOpt_Nvp(goi, nvp_jtag_tap_event, &n);
335 	if (e != JIM_OK) {
336 		Jim_GetOpt_NvpUnknown(goi, nvp_jtag_tap_event, 1);
337 		return e;
338 	}
339 
340 	if (goi->isconfigure) {
341 		if (goi->argc != 1) {
342 			Jim_WrongNumArgs(goi->interp,
343 				goi->argc,
344 				goi->argv,
345 				"-event <event-name> <event-body>");
346 			return JIM_ERR;
347 		}
348 	} else {
349 		if (goi->argc != 0) {
350 			Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name>");
351 			return JIM_ERR;
352 		}
353 	}
354 
355 	struct jtag_tap_event_action *jteap  = tap->event_action;
356 	/* replace existing event body */
357 	bool found = false;
358 	while (jteap) {
359 		if (jteap->event == (enum jtag_event)n->value) {
360 			found = true;
361 			break;
362 		}
363 		jteap = jteap->next;
364 	}
365 
366 	Jim_SetEmptyResult(goi->interp);
367 
368 	if (goi->isconfigure) {
369 		if (!found)
370 			jteap = calloc(1, sizeof(*jteap));
371 		else if (NULL != jteap->body)
372 			Jim_DecrRefCount(goi->interp, jteap->body);
373 
374 		jteap->interp = goi->interp;
375 		jteap->event = n->value;
376 
377 		Jim_Obj *o;
378 		Jim_GetOpt_Obj(goi, &o);
379 		jteap->body = Jim_DuplicateObj(goi->interp, o);
380 		Jim_IncrRefCount(jteap->body);
381 
382 		if (!found) {
383 			/* add to head of event list */
384 			jteap->next = tap->event_action;
385 			tap->event_action = jteap;
386 		}
387 	} else if (found) {
388 		jteap->interp = goi->interp;
389 		Jim_SetResult(goi->interp,
390 			Jim_DuplicateObj(goi->interp, jteap->body));
391 	}
392 	return JIM_OK;
393 }
394 
jtag_tap_configure_cmd(Jim_GetOptInfo * goi,struct jtag_tap * tap)395 static int jtag_tap_configure_cmd(Jim_GetOptInfo *goi, struct jtag_tap *tap)
396 {
397 	/* parse config or cget options */
398 	while (goi->argc > 0) {
399 		Jim_SetEmptyResult(goi->interp);
400 
401 		Jim_Nvp *n;
402 		int e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
403 		if (e != JIM_OK) {
404 			Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
405 			return e;
406 		}
407 
408 		switch (n->value) {
409 			case JCFG_EVENT:
410 				e = jtag_tap_configure_event(goi, tap);
411 				if (e != JIM_OK)
412 					return e;
413 				break;
414 			case JCFG_IDCODE:
415 				if (goi->isconfigure) {
416 					Jim_SetResultFormatted(goi->interp,
417 							"not settable: %s", n->name);
418 					return JIM_ERR;
419 				} else {
420 					if (goi->argc != 0) {
421 						Jim_WrongNumArgs(goi->interp,
422 								goi->argc, goi->argv,
423 								"NO PARAMS");
424 						return JIM_ERR;
425 					}
426 				}
427 				Jim_SetResult(goi->interp, Jim_NewIntObj(goi->interp, tap->idcode));
428 				break;
429 			default:
430 				Jim_SetResultFormatted(goi->interp, "unknown value: %s", n->name);
431 				return JIM_ERR;
432 		}
433 	}
434 
435 	return JIM_OK;
436 }
437 
is_bad_irval(int ir_length,jim_wide w)438 static int is_bad_irval(int ir_length, jim_wide w)
439 {
440 	jim_wide v = 1;
441 
442 	v <<= ir_length;
443 	v -= 1;
444 	v = ~v;
445 	return (w & v) != 0;
446 }
447 
jim_newtap_expected_id(Jim_Nvp * n,Jim_GetOptInfo * goi,struct jtag_tap * pTap)448 static int jim_newtap_expected_id(Jim_Nvp *n, Jim_GetOptInfo *goi,
449 	struct jtag_tap *pTap)
450 {
451 	jim_wide w;
452 	int e = Jim_GetOpt_Wide(goi, &w);
453 	if (e != JIM_OK) {
454 		Jim_SetResultFormatted(goi->interp, "option: %s bad parameter", n->name);
455 		return e;
456 	}
457 
458 	uint32_t *p = realloc(pTap->expected_ids,
459 			      (pTap->expected_ids_cnt + 1) * sizeof(uint32_t));
460 	if (!p) {
461 		Jim_SetResultFormatted(goi->interp, "no memory");
462 		return JIM_ERR;
463 	}
464 
465 	pTap->expected_ids = p;
466 	pTap->expected_ids[pTap->expected_ids_cnt++] = w;
467 
468 	return JIM_OK;
469 }
470 
471 #define NTAP_OPT_IRLEN     0
472 #define NTAP_OPT_IRMASK    1
473 #define NTAP_OPT_IRCAPTURE 2
474 #define NTAP_OPT_ENABLED   3
475 #define NTAP_OPT_DISABLED  4
476 #define NTAP_OPT_EXPECTED_ID 5
477 #define NTAP_OPT_VERSION   6
478 
jim_newtap_ir_param(Jim_Nvp * n,Jim_GetOptInfo * goi,struct jtag_tap * pTap)479 static int jim_newtap_ir_param(Jim_Nvp *n, Jim_GetOptInfo *goi,
480 	struct jtag_tap *pTap)
481 {
482 	jim_wide w;
483 	int e = Jim_GetOpt_Wide(goi, &w);
484 	if (e != JIM_OK) {
485 		Jim_SetResultFormatted(goi->interp,
486 			"option: %s bad parameter", n->name);
487 		return e;
488 	}
489 	switch (n->value) {
490 	    case NTAP_OPT_IRLEN:
491 		    if (w > (jim_wide) (8 * sizeof(pTap->ir_capture_value))) {
492 			    LOG_WARNING("%s: huge IR length %d",
493 				    pTap->dotted_name, (int) w);
494 		    }
495 		    pTap->ir_length = w;
496 		    break;
497 	    case NTAP_OPT_IRMASK:
498 		    if (is_bad_irval(pTap->ir_length, w)) {
499 			    LOG_ERROR("%s: IR mask %x too big",
500 				    pTap->dotted_name,
501 				    (int) w);
502 			    return JIM_ERR;
503 		    }
504 		    if ((w & 3) != 3)
505 			    LOG_WARNING("%s: nonstandard IR mask", pTap->dotted_name);
506 		    pTap->ir_capture_mask = w;
507 		    break;
508 	    case NTAP_OPT_IRCAPTURE:
509 		    if (is_bad_irval(pTap->ir_length, w)) {
510 			    LOG_ERROR("%s: IR capture %x too big",
511 				    pTap->dotted_name, (int) w);
512 			    return JIM_ERR;
513 		    }
514 		    if ((w & 3) != 1)
515 			    LOG_WARNING("%s: nonstandard IR value",
516 				    pTap->dotted_name);
517 		    pTap->ir_capture_value = w;
518 		    break;
519 	    default:
520 		    return JIM_ERR;
521 	}
522 	return JIM_OK;
523 }
524 
jim_newtap_cmd(Jim_GetOptInfo * goi)525 static int jim_newtap_cmd(Jim_GetOptInfo *goi)
526 {
527 	struct jtag_tap *pTap;
528 	int x;
529 	int e;
530 	Jim_Nvp *n;
531 	char *cp;
532 	const Jim_Nvp opts[] = {
533 		{ .name = "-irlen",       .value = NTAP_OPT_IRLEN },
534 		{ .name = "-irmask",       .value = NTAP_OPT_IRMASK },
535 		{ .name = "-ircapture",       .value = NTAP_OPT_IRCAPTURE },
536 		{ .name = "-enable",       .value = NTAP_OPT_ENABLED },
537 		{ .name = "-disable",       .value = NTAP_OPT_DISABLED },
538 		{ .name = "-expected-id",       .value = NTAP_OPT_EXPECTED_ID },
539 		{ .name = "-ignore-version",       .value = NTAP_OPT_VERSION },
540 		{ .name = NULL,       .value = -1 },
541 	};
542 
543 	pTap = calloc(1, sizeof(struct jtag_tap));
544 	if (!pTap) {
545 		Jim_SetResultFormatted(goi->interp, "no memory");
546 		return JIM_ERR;
547 	}
548 
549 	/*
550 	 * we expect CHIP + TAP + OPTIONS
551 	 * */
552 	if (goi->argc < 3) {
553 		Jim_SetResultFormatted(goi->interp, "Missing CHIP TAP OPTIONS ....");
554 		free(pTap);
555 		return JIM_ERR;
556 	}
557 
558 	const char *tmp;
559 	Jim_GetOpt_String(goi, &tmp, NULL);
560 	pTap->chip = strdup(tmp);
561 
562 	Jim_GetOpt_String(goi, &tmp, NULL);
563 	pTap->tapname = strdup(tmp);
564 
565 	/* name + dot + name + null */
566 	x = strlen(pTap->chip) + 1 + strlen(pTap->tapname) + 1;
567 	cp = malloc(x);
568 	sprintf(cp, "%s.%s", pTap->chip, pTap->tapname);
569 	pTap->dotted_name = cp;
570 
571 	LOG_DEBUG("Creating New Tap, Chip: %s, Tap: %s, Dotted: %s, %d params",
572 		pTap->chip, pTap->tapname, pTap->dotted_name, goi->argc);
573 
574 	if (!transport_is_jtag()) {
575 		/* SWD doesn't require any JTAG tap parameters */
576 		pTap->enabled = true;
577 		jtag_tap_init(pTap);
578 		return JIM_OK;
579 	}
580 
581 	/* IEEE specifies that the two LSBs of an IR scan are 01, so make
582 	 * that the default.  The "-ircapture" and "-irmask" options are only
583 	 * needed to cope with nonstandard TAPs, or to specify more bits.
584 	 */
585 	pTap->ir_capture_mask = 0x03;
586 	pTap->ir_capture_value = 0x01;
587 
588 	while (goi->argc) {
589 		e = Jim_GetOpt_Nvp(goi, opts, &n);
590 		if (e != JIM_OK) {
591 			Jim_GetOpt_NvpUnknown(goi, opts, 0);
592 			free(cp);
593 			free(pTap);
594 			return e;
595 		}
596 		LOG_DEBUG("Processing option: %s", n->name);
597 		switch (n->value) {
598 		    case NTAP_OPT_ENABLED:
599 			    pTap->disabled_after_reset = false;
600 			    break;
601 		    case NTAP_OPT_DISABLED:
602 			    pTap->disabled_after_reset = true;
603 			    break;
604 		    case NTAP_OPT_EXPECTED_ID:
605 			    e = jim_newtap_expected_id(n, goi, pTap);
606 			    if (JIM_OK != e) {
607 				    free(cp);
608 				    free(pTap);
609 				    return e;
610 			    }
611 			    break;
612 		    case NTAP_OPT_IRLEN:
613 		    case NTAP_OPT_IRMASK:
614 		    case NTAP_OPT_IRCAPTURE:
615 			    e = jim_newtap_ir_param(n, goi, pTap);
616 			    if (JIM_OK != e) {
617 				    free(cp);
618 				    free(pTap);
619 				    return e;
620 			    }
621 			    break;
622 		    case NTAP_OPT_VERSION:
623 			    pTap->ignore_version = true;
624 			    break;
625 		}	/* switch (n->value) */
626 	}	/* while (goi->argc) */
627 
628 	/* default is enabled-after-reset */
629 	pTap->enabled = !pTap->disabled_after_reset;
630 
631 	/* Did all the required option bits get cleared? */
632 	if (pTap->ir_length != 0) {
633 		jtag_tap_init(pTap);
634 		return JIM_OK;
635 	}
636 
637 	Jim_SetResultFormatted(goi->interp,
638 		"newtap: %s missing IR length",
639 		pTap->dotted_name);
640 	jtag_tap_free(pTap);
641 	return JIM_ERR;
642 }
643 
jtag_tap_handle_event(struct jtag_tap * tap,enum jtag_event e)644 static void jtag_tap_handle_event(struct jtag_tap *tap, enum jtag_event e)
645 {
646 	struct jtag_tap_event_action *jteap;
647 	int retval;
648 
649 	for (jteap = tap->event_action; jteap != NULL; jteap = jteap->next) {
650 		if (jteap->event != e)
651 			continue;
652 
653 		Jim_Nvp *nvp = Jim_Nvp_value2name_simple(nvp_jtag_tap_event, e);
654 		LOG_DEBUG("JTAG tap: %s event: %d (%s)\n\taction: %s",
655 			tap->dotted_name, e, nvp->name,
656 			Jim_GetString(jteap->body, NULL));
657 
658 		retval = Jim_EvalObj(jteap->interp, jteap->body);
659 		if (retval == JIM_RETURN)
660 			retval = jteap->interp->returnCode;
661 
662 		if (retval != JIM_OK) {
663 			Jim_MakeErrorMessage(jteap->interp);
664 			LOG_USER("%s", Jim_GetString(Jim_GetResult(jteap->interp), NULL));
665 			continue;
666 		}
667 
668 		switch (e) {
669 		    case JTAG_TAP_EVENT_ENABLE:
670 		    case JTAG_TAP_EVENT_DISABLE:
671 				/* NOTE:  we currently assume the handlers
672 				 * can't fail.  Right here is where we should
673 				 * really be verifying the scan chains ...
674 				 */
675 			    tap->enabled = (e == JTAG_TAP_EVENT_ENABLE);
676 			    LOG_INFO("JTAG tap: %s %s", tap->dotted_name,
677 				tap->enabled ? "enabled" : "disabled");
678 			    break;
679 		    default:
680 			    break;
681 		}
682 	}
683 }
684 
jim_jtag_arp_init(Jim_Interp * interp,int argc,Jim_Obj * const * argv)685 static int jim_jtag_arp_init(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
686 {
687 	Jim_GetOptInfo goi;
688 	Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
689 	if (goi.argc != 0) {
690 		Jim_WrongNumArgs(goi.interp, 1, goi.argv-1, "(no params)");
691 		return JIM_ERR;
692 	}
693 	struct command_context *context = current_command_context(interp);
694 	int e = jtag_init_inner(context);
695 	if (e != ERROR_OK) {
696 		Jim_Obj *eObj = Jim_NewIntObj(goi.interp, e);
697 		Jim_IncrRefCount(eObj);
698 		Jim_SetResultFormatted(goi.interp, "error: %#s", eObj);
699 		Jim_DecrRefCount(goi.interp, eObj);
700 		return JIM_ERR;
701 	}
702 	return JIM_OK;
703 }
704 
jim_jtag_arp_init_reset(Jim_Interp * interp,int argc,Jim_Obj * const * argv)705 static int jim_jtag_arp_init_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
706 {
707 	int e = ERROR_OK;
708 	Jim_GetOptInfo goi;
709 	Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
710 	if (goi.argc != 0) {
711 		Jim_WrongNumArgs(goi.interp, 1, goi.argv-1, "(no params)");
712 		return JIM_ERR;
713 	}
714 	struct command_context *context = current_command_context(interp);
715 	if (transport_is_jtag())
716 		e = jtag_init_reset(context);
717 	else if (transport_is_swd())
718 		e = swd_init_reset(context);
719 
720 	if (e != ERROR_OK) {
721 		Jim_Obj *eObj = Jim_NewIntObj(goi.interp, e);
722 		Jim_IncrRefCount(eObj);
723 		Jim_SetResultFormatted(goi.interp, "error: %#s", eObj);
724 		Jim_DecrRefCount(goi.interp, eObj);
725 		return JIM_ERR;
726 	}
727 	return JIM_OK;
728 }
729 
jim_jtag_newtap(Jim_Interp * interp,int argc,Jim_Obj * const * argv)730 int jim_jtag_newtap(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
731 {
732 	Jim_GetOptInfo goi;
733 	Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
734 	return jim_newtap_cmd(&goi);
735 }
736 
jtag_tap_enable(struct jtag_tap * t)737 static bool jtag_tap_enable(struct jtag_tap *t)
738 {
739 	if (t->enabled)
740 		return false;
741 	jtag_tap_handle_event(t, JTAG_TAP_EVENT_ENABLE);
742 	if (!t->enabled)
743 		return false;
744 
745 	/* FIXME add JTAG sanity checks, w/o TLR
746 	 *  - scan chain length grew by one (this)
747 	 *  - IDs and IR lengths are as expected
748 	 */
749 	jtag_call_event_callbacks(JTAG_TAP_EVENT_ENABLE);
750 	return true;
751 }
jtag_tap_disable(struct jtag_tap * t)752 static bool jtag_tap_disable(struct jtag_tap *t)
753 {
754 	if (!t->enabled)
755 		return false;
756 	jtag_tap_handle_event(t, JTAG_TAP_EVENT_DISABLE);
757 	if (t->enabled)
758 		return false;
759 
760 	/* FIXME add JTAG sanity checks, w/o TLR
761 	 *  - scan chain length shrank by one (this)
762 	 *  - IDs and IR lengths are as expected
763 	 */
764 	jtag_call_event_callbacks(JTAG_TAP_EVENT_DISABLE);
765 	return true;
766 }
767 
jim_jtag_tap_enabler(Jim_Interp * interp,int argc,Jim_Obj * const * argv)768 int jim_jtag_tap_enabler(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
769 {
770 	const char *cmd_name = Jim_GetString(argv[0], NULL);
771 	Jim_GetOptInfo goi;
772 	Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
773 	if (goi.argc != 1) {
774 		Jim_SetResultFormatted(goi.interp, "usage: %s <name>", cmd_name);
775 		return JIM_ERR;
776 	}
777 
778 	struct jtag_tap *t;
779 
780 	t = jtag_tap_by_jim_obj(goi.interp, goi.argv[0]);
781 	if (t == NULL)
782 		return JIM_ERR;
783 
784 	if (strcasecmp(cmd_name, "tapisenabled") == 0) {
785 		/* do nothing, just return the value */
786 	} else if (strcasecmp(cmd_name, "tapenable") == 0) {
787 		if (!jtag_tap_enable(t)) {
788 			LOG_WARNING("failed to enable tap %s", t->dotted_name);
789 			return JIM_ERR;
790 		}
791 	} else if (strcasecmp(cmd_name, "tapdisable") == 0) {
792 		if (!jtag_tap_disable(t)) {
793 			LOG_WARNING("failed to disable tap %s", t->dotted_name);
794 			return JIM_ERR;
795 		}
796 	} else {
797 		LOG_ERROR("command '%s' unknown", cmd_name);
798 		return JIM_ERR;
799 	}
800 	bool e = t->enabled;
801 	Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, e));
802 	return JIM_OK;
803 }
804 
jim_jtag_configure(Jim_Interp * interp,int argc,Jim_Obj * const * argv)805 int jim_jtag_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
806 {
807 	const char *cmd_name = Jim_GetString(argv[0], NULL);
808 	Jim_GetOptInfo goi;
809 	Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
810 	goi.isconfigure = !strcmp(cmd_name, "configure");
811 	if (goi.argc < 2 + goi.isconfigure) {
812 		Jim_WrongNumArgs(goi.interp, 0, NULL,
813 			"<tap_name> <attribute> ...");
814 		return JIM_ERR;
815 	}
816 
817 	struct jtag_tap *t;
818 
819 	Jim_Obj *o;
820 	Jim_GetOpt_Obj(&goi, &o);
821 	t = jtag_tap_by_jim_obj(goi.interp, o);
822 	if (t == NULL)
823 		return JIM_ERR;
824 
825 	return jtag_tap_configure_cmd(&goi, t);
826 }
827 
jim_jtag_names(Jim_Interp * interp,int argc,Jim_Obj * const * argv)828 static int jim_jtag_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
829 {
830 	Jim_GetOptInfo goi;
831 	Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
832 	if (goi.argc != 0) {
833 		Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
834 		return JIM_ERR;
835 	}
836 	Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
837 	struct jtag_tap *tap;
838 
839 	for (tap = jtag_all_taps(); tap; tap = tap->next_tap) {
840 		Jim_ListAppendElement(goi.interp,
841 			Jim_GetResult(goi.interp),
842 			Jim_NewStringObj(goi.interp,
843 				tap->dotted_name, -1));
844 	}
845 	return JIM_OK;
846 }
847 
COMMAND_HANDLER(handle_jtag_init_command)848 COMMAND_HANDLER(handle_jtag_init_command)
849 {
850 	if (CMD_ARGC != 0)
851 		return ERROR_COMMAND_SYNTAX_ERROR;
852 
853 	static bool jtag_initialized;
854 	if (jtag_initialized) {
855 		LOG_INFO("'jtag init' has already been called");
856 		return ERROR_OK;
857 	}
858 	jtag_initialized = true;
859 
860 	LOG_DEBUG("Initializing jtag devices...");
861 	return jtag_init(CMD_CTX);
862 }
863 
864 static const struct command_registration jtag_subcommand_handlers[] = {
865 	{
866 		.name = "init",
867 		.mode = COMMAND_ANY,
868 		.handler = handle_jtag_init_command,
869 		.help = "initialize jtag scan chain",
870 		.usage = ""
871 	},
872 	{
873 		.name = "arp_init",
874 		.mode = COMMAND_ANY,
875 		.jim_handler = jim_jtag_arp_init,
876 		.help = "Validates JTAG scan chain against the list of "
877 			"declared TAPs using just the four standard JTAG "
878 			"signals.",
879 	},
880 	{
881 		.name = "arp_init-reset",
882 		.mode = COMMAND_ANY,
883 		.jim_handler = jim_jtag_arp_init_reset,
884 		.help = "Uses TRST and SRST to try resetting everything on "
885 			"the JTAG scan chain, then performs 'jtag arp_init'."
886 	},
887 	{
888 		.name = "newtap",
889 		.mode = COMMAND_CONFIG,
890 		.jim_handler = jim_jtag_newtap,
891 		.help = "Create a new TAP instance named basename.tap_type, "
892 			"and appends it to the scan chain.",
893 		.usage = "basename tap_type '-irlen' count "
894 			"['-enable'|'-disable'] "
895 			"['-expected_id' number] "
896 			"['-ignore-version'] "
897 			"['-ircapture' number] "
898 			"['-mask' number] ",
899 	},
900 	{
901 		.name = "tapisenabled",
902 		.mode = COMMAND_EXEC,
903 		.jim_handler = jim_jtag_tap_enabler,
904 		.help = "Returns a Tcl boolean (0/1) indicating whether "
905 			"the TAP is enabled (1) or not (0).",
906 		.usage = "tap_name",
907 	},
908 	{
909 		.name = "tapenable",
910 		.mode = COMMAND_EXEC,
911 		.jim_handler = jim_jtag_tap_enabler,
912 		.help = "Try to enable the specified TAP using the "
913 			"'tap-enable' TAP event.",
914 		.usage = "tap_name",
915 	},
916 	{
917 		.name = "tapdisable",
918 		.mode = COMMAND_EXEC,
919 		.jim_handler = jim_jtag_tap_enabler,
920 		.help = "Try to disable the specified TAP using the "
921 			"'tap-disable' TAP event.",
922 		.usage = "tap_name",
923 	},
924 	{
925 		.name = "configure",
926 		.mode = COMMAND_ANY,
927 		.jim_handler = jim_jtag_configure,
928 		.help = "Provide a Tcl handler for the specified "
929 			"TAP event.",
930 		.usage = "tap_name '-event' event_name handler",
931 	},
932 	{
933 		.name = "cget",
934 		.mode = COMMAND_EXEC,
935 		.jim_handler = jim_jtag_configure,
936 		.help = "Return any Tcl handler for the specified "
937 			"TAP event.",
938 		.usage = "tap_name '-event' event_name",
939 	},
940 	{
941 		.name = "names",
942 		.mode = COMMAND_ANY,
943 		.jim_handler = jim_jtag_names,
944 		.help = "Returns list of all JTAG tap names.",
945 	},
946 	{
947 		.chain = jtag_command_handlers_to_move,
948 	},
949 	COMMAND_REGISTRATION_DONE
950 };
951 
jtag_notify_event(enum jtag_event event)952 void jtag_notify_event(enum jtag_event event)
953 {
954 	struct jtag_tap *tap;
955 
956 	for (tap = jtag_all_taps(); tap; tap = tap->next_tap)
957 		jtag_tap_handle_event(tap, event);
958 }
959 
960 
COMMAND_HANDLER(handle_scan_chain_command)961 COMMAND_HANDLER(handle_scan_chain_command)
962 {
963 	struct jtag_tap *tap;
964 	char expected_id[12];
965 
966 	tap = jtag_all_taps();
967 	command_print(CMD,
968 		"   TapName             Enabled  IdCode     Expected   IrLen IrCap IrMask");
969 	command_print(CMD,
970 		"-- ------------------- -------- ---------- ---------- ----- ----- ------");
971 
972 	while (tap) {
973 		uint32_t expected, expected_mask, ii;
974 
975 		snprintf(expected_id, sizeof(expected_id), "0x%08x",
976 			(unsigned)((tap->expected_ids_cnt > 0)
977 				   ? tap->expected_ids[0]
978 				   : 0));
979 		if (tap->ignore_version)
980 			expected_id[2] = '*';
981 
982 		expected = buf_get_u32(tap->expected, 0, tap->ir_length);
983 		expected_mask = buf_get_u32(tap->expected_mask, 0, tap->ir_length);
984 
985 		command_print(CMD,
986 			"%2d %-18s     %c     0x%08x %s %5d 0x%02x  0x%02x",
987 			tap->abs_chain_position,
988 			tap->dotted_name,
989 			tap->enabled ? 'Y' : 'n',
990 			(unsigned int)(tap->idcode),
991 			expected_id,
992 			(unsigned int)(tap->ir_length),
993 			(unsigned int)(expected),
994 			(unsigned int)(expected_mask));
995 
996 		for (ii = 1; ii < tap->expected_ids_cnt; ii++) {
997 			snprintf(expected_id, sizeof(expected_id), "0x%08x",
998 				(unsigned) tap->expected_ids[ii]);
999 			if (tap->ignore_version)
1000 				expected_id[2] = '*';
1001 
1002 			command_print(CMD,
1003 				"                                           %s",
1004 				expected_id);
1005 		}
1006 
1007 		tap = tap->next_tap;
1008 	}
1009 
1010 	return ERROR_OK;
1011 }
1012 
COMMAND_HANDLER(handle_jtag_ntrst_delay_command)1013 COMMAND_HANDLER(handle_jtag_ntrst_delay_command)
1014 {
1015 	if (CMD_ARGC > 1)
1016 		return ERROR_COMMAND_SYNTAX_ERROR;
1017 	if (CMD_ARGC == 1) {
1018 		unsigned delay;
1019 		COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1020 
1021 		jtag_set_ntrst_delay(delay);
1022 	}
1023 	command_print(CMD, "jtag_ntrst_delay: %u", jtag_get_ntrst_delay());
1024 	return ERROR_OK;
1025 }
1026 
COMMAND_HANDLER(handle_jtag_ntrst_assert_width_command)1027 COMMAND_HANDLER(handle_jtag_ntrst_assert_width_command)
1028 {
1029 	if (CMD_ARGC > 1)
1030 		return ERROR_COMMAND_SYNTAX_ERROR;
1031 	if (CMD_ARGC == 1) {
1032 		unsigned delay;
1033 		COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1034 
1035 		jtag_set_ntrst_assert_width(delay);
1036 	}
1037 	command_print(CMD, "jtag_ntrst_assert_width: %u", jtag_get_ntrst_assert_width());
1038 	return ERROR_OK;
1039 }
1040 
COMMAND_HANDLER(handle_jtag_rclk_command)1041 COMMAND_HANDLER(handle_jtag_rclk_command)
1042 {
1043 	if (CMD_ARGC > 1)
1044 		return ERROR_COMMAND_SYNTAX_ERROR;
1045 
1046 	int retval = ERROR_OK;
1047 	if (CMD_ARGC == 1) {
1048 		unsigned khz = 0;
1049 		COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], khz);
1050 
1051 		retval = jtag_config_rclk(khz);
1052 		if (ERROR_OK != retval)
1053 			return retval;
1054 	}
1055 
1056 	int cur_khz = jtag_get_speed_khz();
1057 	retval = jtag_get_speed_readable(&cur_khz);
1058 	if (ERROR_OK != retval)
1059 		return retval;
1060 
1061 	if (cur_khz)
1062 		command_print(CMD, "RCLK not supported - fallback to %d kHz", cur_khz);
1063 	else
1064 		command_print(CMD, "RCLK - adaptive");
1065 
1066 	return retval;
1067 }
1068 
COMMAND_HANDLER(handle_runtest_command)1069 COMMAND_HANDLER(handle_runtest_command)
1070 {
1071 	if (CMD_ARGC != 1)
1072 		return ERROR_COMMAND_SYNTAX_ERROR;
1073 
1074 	unsigned num_clocks;
1075 	COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num_clocks);
1076 
1077 	jtag_add_runtest(num_clocks, TAP_IDLE);
1078 	return jtag_execute_queue();
1079 }
1080 
1081 /*
1082  * For "irscan" or "drscan" commands, the "end" (really, "next") state
1083  * should be stable ... and *NOT* a shift state, otherwise free-running
1084  * jtag clocks could change the values latched by the update state.
1085  * Not surprisingly, this is the same constraint as SVF; the "irscan"
1086  * and "drscan" commands are a write-only subset of what SVF provides.
1087  */
1088 
COMMAND_HANDLER(handle_irscan_command)1089 COMMAND_HANDLER(handle_irscan_command)
1090 {
1091 	int i;
1092 	struct scan_field *fields;
1093 	struct jtag_tap *tap = NULL;
1094 	tap_state_t endstate;
1095 
1096 	if ((CMD_ARGC < 2) || (CMD_ARGC % 2))
1097 		return ERROR_COMMAND_SYNTAX_ERROR;
1098 
1099 	/* optional "-endstate" "statename" at the end of the arguments,
1100 	 * so that e.g. IRPAUSE can let us load the data register before
1101 	 * entering RUN/IDLE to execute the instruction we load here.
1102 	 */
1103 	endstate = TAP_IDLE;
1104 
1105 	if (CMD_ARGC >= 4) {
1106 		/* have at least one pair of numbers.
1107 		 * is last pair the magic text? */
1108 		if (strcmp("-endstate", CMD_ARGV[CMD_ARGC - 2]) == 0) {
1109 			endstate = tap_state_by_name(CMD_ARGV[CMD_ARGC - 1]);
1110 			if (endstate == TAP_INVALID)
1111 				return ERROR_COMMAND_SYNTAX_ERROR;
1112 			if (!scan_is_safe(endstate))
1113 				LOG_WARNING("unstable irscan endstate \"%s\"",
1114 					CMD_ARGV[CMD_ARGC - 1]);
1115 			CMD_ARGC -= 2;
1116 		}
1117 	}
1118 
1119 	int num_fields = CMD_ARGC / 2;
1120 	if (num_fields > 1) {
1121 		/* we really should be looking at plain_ir_scan if we want
1122 		 * anything more fancy.
1123 		 */
1124 		LOG_ERROR("Specify a single value for tap");
1125 		return ERROR_COMMAND_SYNTAX_ERROR;
1126 	}
1127 
1128 	fields = calloc(num_fields, sizeof(*fields));
1129 
1130 	int retval;
1131 	for (i = 0; i < num_fields; i++) {
1132 		tap = jtag_tap_by_string(CMD_ARGV[i*2]);
1133 		if (tap == NULL) {
1134 			free(fields);
1135 			command_print(CMD, "Tap: %s unknown", CMD_ARGV[i*2]);
1136 
1137 			return ERROR_FAIL;
1138 		}
1139 		uint64_t value;
1140 		retval = parse_u64(CMD_ARGV[i * 2 + 1], &value);
1141 		if (ERROR_OK != retval)
1142 			goto error_return;
1143 
1144 		int field_size = tap->ir_length;
1145 		fields[i].num_bits = field_size;
1146 		uint8_t *v = calloc(1, DIV_ROUND_UP(field_size, 8));
1147 		if (!v) {
1148 			LOG_ERROR("Out of memory");
1149 			goto error_return;
1150 		}
1151 
1152 		buf_set_u64(v, 0, field_size, value);
1153 		fields[i].out_value = v;
1154 		fields[i].in_value = NULL;
1155 	}
1156 
1157 	/* did we have an endstate? */
1158 	jtag_add_ir_scan(tap, fields, endstate);
1159 
1160 	retval = jtag_execute_queue();
1161 
1162 error_return:
1163 	for (i = 0; i < num_fields; i++)
1164 		free((void *)fields[i].out_value);
1165 
1166 	free(fields);
1167 
1168 	return retval;
1169 }
1170 
COMMAND_HANDLER(handle_verify_ircapture_command)1171 COMMAND_HANDLER(handle_verify_ircapture_command)
1172 {
1173 	if (CMD_ARGC > 1)
1174 		return ERROR_COMMAND_SYNTAX_ERROR;
1175 
1176 	if (CMD_ARGC == 1) {
1177 		bool enable;
1178 		COMMAND_PARSE_ENABLE(CMD_ARGV[0], enable);
1179 		jtag_set_verify_capture_ir(enable);
1180 	}
1181 
1182 	const char *status = jtag_will_verify_capture_ir() ? "enabled" : "disabled";
1183 	command_print(CMD, "verify Capture-IR is %s", status);
1184 
1185 	return ERROR_OK;
1186 }
1187 
COMMAND_HANDLER(handle_verify_jtag_command)1188 COMMAND_HANDLER(handle_verify_jtag_command)
1189 {
1190 	if (CMD_ARGC > 1)
1191 		return ERROR_COMMAND_SYNTAX_ERROR;
1192 
1193 	if (CMD_ARGC == 1) {
1194 		bool enable;
1195 		COMMAND_PARSE_ENABLE(CMD_ARGV[0], enable);
1196 		jtag_set_verify(enable);
1197 	}
1198 
1199 	const char *status = jtag_will_verify() ? "enabled" : "disabled";
1200 	command_print(CMD, "verify jtag capture is %s", status);
1201 
1202 	return ERROR_OK;
1203 }
1204 
COMMAND_HANDLER(handle_tms_sequence_command)1205 COMMAND_HANDLER(handle_tms_sequence_command)
1206 {
1207 	if (CMD_ARGC > 1)
1208 		return ERROR_COMMAND_SYNTAX_ERROR;
1209 
1210 	if (CMD_ARGC == 1) {
1211 		bool use_new_table;
1212 		if (strcmp(CMD_ARGV[0], "short") == 0)
1213 			use_new_table = true;
1214 		else if (strcmp(CMD_ARGV[0], "long") == 0)
1215 			use_new_table = false;
1216 		else
1217 			return ERROR_COMMAND_SYNTAX_ERROR;
1218 
1219 		tap_use_new_tms_table(use_new_table);
1220 	}
1221 
1222 	command_print(CMD, "tms sequence is  %s",
1223 		tap_uses_new_tms_table() ? "short" : "long");
1224 
1225 	return ERROR_OK;
1226 }
1227 
COMMAND_HANDLER(handle_jtag_flush_queue_sleep)1228 COMMAND_HANDLER(handle_jtag_flush_queue_sleep)
1229 {
1230 	if (CMD_ARGC != 1)
1231 		return ERROR_COMMAND_SYNTAX_ERROR;
1232 
1233 	int sleep_ms;
1234 	COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], sleep_ms);
1235 
1236 	jtag_set_flush_queue_sleep(sleep_ms);
1237 
1238 	return ERROR_OK;
1239 }
1240 
COMMAND_HANDLER(handle_wait_srst_deassert)1241 COMMAND_HANDLER(handle_wait_srst_deassert)
1242 {
1243 	if (CMD_ARGC != 1)
1244 		return ERROR_COMMAND_SYNTAX_ERROR;
1245 
1246 	int timeout_ms;
1247 	COMMAND_PARSE_NUMBER(int, CMD_ARGV[0], timeout_ms);
1248 	if ((timeout_ms <= 0) || (timeout_ms > 100000)) {
1249 		LOG_ERROR("Timeout must be an integer between 0 and 100000");
1250 		return ERROR_FAIL;
1251 	}
1252 
1253 	LOG_USER("Waiting for srst assert + deassert for at most %dms", timeout_ms);
1254 	int asserted_yet;
1255 	int64_t then = timeval_ms();
1256 	while (jtag_srst_asserted(&asserted_yet) == ERROR_OK) {
1257 		if ((timeval_ms() - then) > timeout_ms) {
1258 			LOG_ERROR("Timed out");
1259 			return ERROR_FAIL;
1260 		}
1261 		if (asserted_yet)
1262 			break;
1263 	}
1264 	while (jtag_srst_asserted(&asserted_yet) == ERROR_OK) {
1265 		if ((timeval_ms() - then) > timeout_ms) {
1266 			LOG_ERROR("Timed out");
1267 			return ERROR_FAIL;
1268 		}
1269 		if (!asserted_yet)
1270 			break;
1271 	}
1272 
1273 	return ERROR_OK;
1274 }
1275 
1276 static const struct command_registration jtag_command_handlers[] = {
1277 
1278 	{
1279 		.name = "jtag_flush_queue_sleep",
1280 		.handler = handle_jtag_flush_queue_sleep,
1281 		.mode = COMMAND_ANY,
1282 		.help = "For debug purposes(simulate long delays of interface) "
1283 			"to test performance or change in behavior. Default 0ms.",
1284 		.usage = "[sleep in ms]",
1285 	},
1286 	{
1287 		.name = "jtag_rclk",
1288 		.handler = handle_jtag_rclk_command,
1289 		.mode = COMMAND_ANY,
1290 		.help = "With an argument, change to to use adaptive clocking "
1291 			"if possible; else to use the fallback speed.  "
1292 			"With or without argument, display current setting.",
1293 		.usage = "[fallback_speed_khz]",
1294 	},
1295 	{
1296 		.name = "jtag_ntrst_delay",
1297 		.handler = handle_jtag_ntrst_delay_command,
1298 		.mode = COMMAND_ANY,
1299 		.help = "delay after deasserting trst in ms",
1300 		.usage = "[milliseconds]",
1301 	},
1302 	{
1303 		.name = "jtag_ntrst_assert_width",
1304 		.handler = handle_jtag_ntrst_assert_width_command,
1305 		.mode = COMMAND_ANY,
1306 		.help = "delay after asserting trst in ms",
1307 		.usage = "[milliseconds]",
1308 	},
1309 	{
1310 		.name = "scan_chain",
1311 		.handler = handle_scan_chain_command,
1312 		.mode = COMMAND_ANY,
1313 		.help = "print current scan chain configuration",
1314 		.usage = ""
1315 	},
1316 	{
1317 		.name = "runtest",
1318 		.handler = handle_runtest_command,
1319 		.mode = COMMAND_EXEC,
1320 		.help = "Move to Run-Test/Idle, and issue TCK for num_cycles.",
1321 		.usage = "num_cycles"
1322 	},
1323 	{
1324 		.name = "irscan",
1325 		.handler = handle_irscan_command,
1326 		.mode = COMMAND_EXEC,
1327 		.help = "Execute Instruction Register (IR) scan.  The "
1328 			"specified opcodes are put into each TAP's IR, "
1329 			"and other TAPs are put in BYPASS.",
1330 		.usage = "[tap_name instruction]* ['-endstate' state_name]",
1331 	},
1332 	{
1333 		.name = "verify_ircapture",
1334 		.handler = handle_verify_ircapture_command,
1335 		.mode = COMMAND_ANY,
1336 		.help = "Display or assign flag controlling whether to "
1337 			"verify values captured during Capture-IR.",
1338 		.usage = "['enable'|'disable']",
1339 	},
1340 	{
1341 		.name = "verify_jtag",
1342 		.handler = handle_verify_jtag_command,
1343 		.mode = COMMAND_ANY,
1344 		.help = "Display or assign flag controlling whether to "
1345 			"verify values captured during IR and DR scans.",
1346 		.usage = "['enable'|'disable']",
1347 	},
1348 	{
1349 		.name = "tms_sequence",
1350 		.handler = handle_tms_sequence_command,
1351 		.mode = COMMAND_ANY,
1352 		.help = "Display or change what style TMS sequences to use "
1353 			"for JTAG state transitions:  short (default) or "
1354 			"long.  Only for working around JTAG bugs.",
1355 		/* Specifically for working around DRIVER bugs... */
1356 		.usage = "['short'|'long']",
1357 	},
1358 	{
1359 		.name = "wait_srst_deassert",
1360 		.handler = handle_wait_srst_deassert,
1361 		.mode = COMMAND_ANY,
1362 		.help = "Wait for an SRST deassert. "
1363 			"Useful for cases where you need something to happen within ms "
1364 			"of an srst deassert. Timeout in ms ",
1365 		.usage = "ms",
1366 	},
1367 	{
1368 		.name = "jtag",
1369 		.mode = COMMAND_ANY,
1370 		.help = "perform jtag tap actions",
1371 		.usage = "",
1372 
1373 		.chain = jtag_subcommand_handlers,
1374 	},
1375 	{
1376 		.chain = jtag_command_handlers_to_move,
1377 	},
1378 	COMMAND_REGISTRATION_DONE
1379 };
1380 
jtag_register_commands(struct command_context * cmd_ctx)1381 int jtag_register_commands(struct command_context *cmd_ctx)
1382 {
1383 	return register_commands(cmd_ctx, NULL, jtag_command_handlers);
1384 }
1385