doxygen: use correct comment syntax
[openocd/andreasf.git] / src / jtag / core.c
blob6de168e61630ec2b94e100a550d16e2c07ddd4df
1 /***************************************************************************
2 * Copyright (C) 2009 Zachary T Welch *
3 * zw@superlucidity.net *
4 * *
5 * Copyright (C) 2007,2008,2009 Ø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) 2005 by Dominic Rath *
13 * Dominic.Rath@gmx.de *
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, write to the *
27 * Free Software Foundation, Inc., *
28 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
29 ***************************************************************************/
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
35 #include "jtag.h"
36 #include "interface.h"
37 #include <transport/transport.h>
39 #ifdef HAVE_STRINGS_H
40 #include <strings.h>
41 #endif
43 /* SVF and XSVF are higher level JTAG command sets (for boundary scan) */
44 #include "svf/svf.h"
45 #include "xsvf/xsvf.h"
47 /** The number of JTAG queue flushes (for profiling and debugging purposes). */
48 static int jtag_flush_queue_count;
50 /* Sleep this # of ms after flushing the queue */
51 static int jtag_flush_queue_sleep;
53 static void jtag_add_scan_check(struct jtag_tap *active,
54 void (*jtag_add_scan)(struct jtag_tap *active,
55 int in_num_fields,
56 const struct scan_field *in_fields,
57 tap_state_t state),
58 int in_num_fields, struct scan_field *in_fields, tap_state_t state);
60 /**
61 * The jtag_error variable is set when an error occurs while executing
62 * the queue. Application code may set this using jtag_set_error(),
63 * when an error occurs during processing that should be reported during
64 * jtag_execute_queue().
66 * The value is set and cleared, but never read by normal application code.
68 * This value is returned (and cleared) by jtag_execute_queue().
70 static int jtag_error = ERROR_OK;
72 static const char *jtag_event_strings[] = {
73 [JTAG_TRST_ASSERTED] = "TAP reset",
74 [JTAG_TAP_EVENT_SETUP] = "TAP setup",
75 [JTAG_TAP_EVENT_ENABLE] = "TAP enabled",
76 [JTAG_TAP_EVENT_DISABLE] = "TAP disabled",
80 * JTAG adapters must initialize with TRST and SRST de-asserted
81 * (they're negative logic, so that means *high*). But some
82 * hardware doesn't necessarily work that way ... so set things
83 * up so that jtag_init() always forces that state.
85 static int jtag_trst = -1;
86 static int jtag_srst = -1;
88 /**
89 * List all TAPs that have been created.
91 static struct jtag_tap *__jtag_all_taps;
92 /**
93 * The number of TAPs in the __jtag_all_taps list, used to track the
94 * assigned chain position to new TAPs
96 static unsigned jtag_num_taps;
98 static enum reset_types jtag_reset_config = RESET_NONE;
99 tap_state_t cmd_queue_cur_state = TAP_RESET;
101 static bool jtag_verify_capture_ir = true;
102 static int jtag_verify = 1;
104 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines
105 *deasserted (in ms) */
106 static int adapter_nsrst_delay; /* default to no nSRST delay */
107 static int jtag_ntrst_delay;/* default to no nTRST delay */
108 static int adapter_nsrst_assert_width; /* width of assertion */
109 static int jtag_ntrst_assert_width; /* width of assertion */
112 * Contains a single callback along with a pointer that will be passed
113 * when an event occurs.
115 struct jtag_event_callback {
116 /** a event callback */
117 jtag_event_handler_t callback;
118 /** the private data to pass to the callback */
119 void *priv;
120 /** the next callback */
121 struct jtag_event_callback *next;
124 /* callbacks to inform high-level handlers about JTAG state changes */
125 static struct jtag_event_callback *jtag_event_callbacks;
127 /* speed in kHz*/
128 static int speed_khz;
129 /* speed to fallback to when RCLK is requested but not supported */
130 static int rclk_fallback_speed_khz;
131 static enum {CLOCK_MODE_UNSELECTED, CLOCK_MODE_KHZ, CLOCK_MODE_RCLK} clock_mode;
132 static int jtag_speed;
134 static struct jtag_interface *jtag;
136 const struct swd_driver *swd;
138 /* configuration */
139 struct jtag_interface *jtag_interface;
141 void jtag_set_flush_queue_sleep(int ms)
143 jtag_flush_queue_sleep = ms;
146 void jtag_set_error(int error)
148 if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
149 return;
150 jtag_error = error;
153 int jtag_error_clear(void)
155 int temp = jtag_error;
156 jtag_error = ERROR_OK;
157 return temp;
160 /************/
162 static bool jtag_poll = 1;
164 bool is_jtag_poll_safe(void)
166 /* Polling can be disabled explicitly with set_enabled(false).
167 * It is also implicitly disabled while TRST is active and
168 * while SRST is gating the JTAG clock.
170 if (!jtag_poll || jtag_trst != 0)
171 return false;
172 return jtag_srst == 0 || (jtag_reset_config & RESET_SRST_NO_GATING);
175 bool jtag_poll_get_enabled(void)
177 return jtag_poll;
180 void jtag_poll_set_enabled(bool value)
182 jtag_poll = value;
185 /************/
187 struct jtag_tap *jtag_all_taps(void)
189 return __jtag_all_taps;
192 unsigned jtag_tap_count(void)
194 return jtag_num_taps;
197 unsigned jtag_tap_count_enabled(void)
199 struct jtag_tap *t = jtag_all_taps();
200 unsigned n = 0;
201 while (t) {
202 if (t->enabled)
203 n++;
204 t = t->next_tap;
206 return n;
209 /** Append a new TAP to the chain of all taps. */
210 void jtag_tap_add(struct jtag_tap *t)
212 t->abs_chain_position = jtag_num_taps++;
214 struct jtag_tap **tap = &__jtag_all_taps;
215 while (*tap != NULL)
216 tap = &(*tap)->next_tap;
217 *tap = t;
220 /* returns a pointer to the n-th device in the scan chain */
221 struct jtag_tap *jtag_tap_by_position(unsigned n)
223 struct jtag_tap *t = jtag_all_taps();
225 while (t && n-- > 0)
226 t = t->next_tap;
228 return t;
231 struct jtag_tap *jtag_tap_by_string(const char *s)
233 /* try by name first */
234 struct jtag_tap *t = jtag_all_taps();
236 while (t) {
237 if (0 == strcmp(t->dotted_name, s))
238 return t;
239 t = t->next_tap;
242 /* no tap found by name, so try to parse the name as a number */
243 unsigned n;
244 if (parse_uint(s, &n) != ERROR_OK)
245 return NULL;
247 /* FIXME remove this numeric fallback code late June 2010, along
248 * with all info in the User's Guide that TAPs have numeric IDs.
249 * Also update "scan_chain" output to not display the numbers.
251 t = jtag_tap_by_position(n);
252 if (t)
253 LOG_WARNING("Specify TAP '%s' by name, not number %u",
254 t->dotted_name, n);
256 return t;
259 struct jtag_tap *jtag_tap_next_enabled(struct jtag_tap *p)
261 p = p ? p->next_tap : jtag_all_taps();
262 while (p) {
263 if (p->enabled)
264 return p;
265 p = p->next_tap;
267 return NULL;
270 const char *jtag_tap_name(const struct jtag_tap *tap)
272 return (tap == NULL) ? "(unknown)" : tap->dotted_name;
276 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
278 struct jtag_event_callback **callbacks_p = &jtag_event_callbacks;
280 if (callback == NULL)
281 return ERROR_COMMAND_SYNTAX_ERROR;
283 if (*callbacks_p) {
284 while ((*callbacks_p)->next)
285 callbacks_p = &((*callbacks_p)->next);
286 callbacks_p = &((*callbacks_p)->next);
289 (*callbacks_p) = malloc(sizeof(struct jtag_event_callback));
290 (*callbacks_p)->callback = callback;
291 (*callbacks_p)->priv = priv;
292 (*callbacks_p)->next = NULL;
294 return ERROR_OK;
297 int jtag_unregister_event_callback(jtag_event_handler_t callback, void *priv)
299 struct jtag_event_callback **p = &jtag_event_callbacks, *temp;
301 if (callback == NULL)
302 return ERROR_COMMAND_SYNTAX_ERROR;
304 while (*p) {
305 if (((*p)->priv != priv) || ((*p)->callback != callback)) {
306 p = &(*p)->next;
307 continue;
310 temp = *p;
311 *p = (*p)->next;
312 free(temp);
315 return ERROR_OK;
318 int jtag_call_event_callbacks(enum jtag_event event)
320 struct jtag_event_callback *callback = jtag_event_callbacks;
322 LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
324 while (callback) {
325 struct jtag_event_callback *next;
327 /* callback may remove itself */
328 next = callback->next;
329 callback->callback(event, callback->priv);
330 callback = next;
333 return ERROR_OK;
336 static void jtag_checks(void)
338 assert(jtag_trst == 0);
341 static void jtag_prelude(tap_state_t state)
343 jtag_checks();
345 assert(state != TAP_INVALID);
347 cmd_queue_cur_state = state;
350 void jtag_add_ir_scan_noverify(struct jtag_tap *active, const struct scan_field *in_fields,
351 tap_state_t state)
353 jtag_prelude(state);
355 int retval = interface_jtag_add_ir_scan(active, in_fields, state);
356 jtag_set_error(retval);
359 static void jtag_add_ir_scan_noverify_callback(struct jtag_tap *active,
360 int dummy,
361 const struct scan_field *in_fields,
362 tap_state_t state)
364 jtag_add_ir_scan_noverify(active, in_fields, state);
367 /* If fields->in_value is filled out, then the captured IR value will be checked */
368 void jtag_add_ir_scan(struct jtag_tap *active, struct scan_field *in_fields, tap_state_t state)
370 assert(state != TAP_RESET);
372 if (jtag_verify && jtag_verify_capture_ir) {
373 /* 8 x 32 bit id's is enough for all invocations */
375 /* if we are to run a verification of the ir scan, we need to get the input back.
376 * We may have to allocate space if the caller didn't ask for the input back.
378 in_fields->check_value = active->expected;
379 in_fields->check_mask = active->expected_mask;
380 jtag_add_scan_check(active, jtag_add_ir_scan_noverify_callback, 1, in_fields,
381 state);
382 } else
383 jtag_add_ir_scan_noverify(active, in_fields, state);
386 void jtag_add_plain_ir_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
387 tap_state_t state)
389 assert(out_bits != NULL);
390 assert(state != TAP_RESET);
392 jtag_prelude(state);
394 int retval = interface_jtag_add_plain_ir_scan(
395 num_bits, out_bits, in_bits, state);
396 jtag_set_error(retval);
399 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
400 uint8_t *in_check_mask, int num_bits);
402 static int jtag_check_value_mask_callback(jtag_callback_data_t data0,
403 jtag_callback_data_t data1,
404 jtag_callback_data_t data2,
405 jtag_callback_data_t data3)
407 return jtag_check_value_inner((uint8_t *)data0,
408 (uint8_t *)data1,
409 (uint8_t *)data2,
410 (int)data3);
413 static void jtag_add_scan_check(struct jtag_tap *active, void (*jtag_add_scan)(
414 struct jtag_tap *active,
415 int in_num_fields,
416 const struct scan_field *in_fields,
417 tap_state_t state),
418 int in_num_fields, struct scan_field *in_fields, tap_state_t state)
420 jtag_add_scan(active, in_num_fields, in_fields, state);
422 for (int i = 0; i < in_num_fields; i++) {
423 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL)) {
424 /* this is synchronous for a minidriver */
425 jtag_add_callback4(jtag_check_value_mask_callback,
426 (jtag_callback_data_t)in_fields[i].in_value,
427 (jtag_callback_data_t)in_fields[i].check_value,
428 (jtag_callback_data_t)in_fields[i].check_mask,
429 (jtag_callback_data_t)in_fields[i].num_bits);
434 void jtag_add_dr_scan_check(struct jtag_tap *active,
435 int in_num_fields,
436 struct scan_field *in_fields,
437 tap_state_t state)
439 if (jtag_verify)
440 jtag_add_scan_check(active, jtag_add_dr_scan, in_num_fields, in_fields, state);
441 else
442 jtag_add_dr_scan(active, in_num_fields, in_fields, state);
446 void jtag_add_dr_scan(struct jtag_tap *active,
447 int in_num_fields,
448 const struct scan_field *in_fields,
449 tap_state_t state)
451 assert(state != TAP_RESET);
453 jtag_prelude(state);
455 int retval;
456 retval = interface_jtag_add_dr_scan(active, in_num_fields, in_fields, state);
457 jtag_set_error(retval);
460 void jtag_add_plain_dr_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
461 tap_state_t state)
463 assert(out_bits != NULL);
464 assert(state != TAP_RESET);
466 jtag_prelude(state);
468 int retval;
469 retval = interface_jtag_add_plain_dr_scan(num_bits, out_bits, in_bits, state);
470 jtag_set_error(retval);
473 void jtag_add_tlr(void)
475 jtag_prelude(TAP_RESET);
476 jtag_set_error(interface_jtag_add_tlr());
478 /* NOTE: order here matches TRST path in jtag_add_reset() */
479 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
480 jtag_notify_event(JTAG_TRST_ASSERTED);
484 * If supported by the underlying adapter, this clocks a raw bit sequence
485 * onto TMS for switching betwen JTAG and SWD modes.
487 * DO NOT use this to bypass the integrity checks and logging provided
488 * by the jtag_add_pathmove() and jtag_add_statemove() calls.
490 * @param nbits How many bits to clock out.
491 * @param seq The bit sequence. The LSB is bit 0 of seq[0].
492 * @param state The JTAG tap state to record on completion. Use
493 * TAP_INVALID to represent being in in SWD mode.
495 * @todo Update naming conventions to stop assuming everything is JTAG.
497 int jtag_add_tms_seq(unsigned nbits, const uint8_t *seq, enum tap_state state)
499 int retval;
501 if (!(jtag->supported & DEBUG_CAP_TMS_SEQ))
502 return ERROR_JTAG_NOT_IMPLEMENTED;
504 jtag_checks();
505 cmd_queue_cur_state = state;
507 retval = interface_add_tms_seq(nbits, seq, state);
508 jtag_set_error(retval);
509 return retval;
512 void jtag_add_pathmove(int num_states, const tap_state_t *path)
514 tap_state_t cur_state = cmd_queue_cur_state;
516 /* the last state has to be a stable state */
517 if (!tap_is_state_stable(path[num_states - 1])) {
518 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
519 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
520 return;
523 for (int i = 0; i < num_states; i++) {
524 if (path[i] == TAP_RESET) {
525 LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
526 jtag_set_error(ERROR_JTAG_STATE_INVALID);
527 return;
530 if (tap_state_transition(cur_state, true) != path[i] &&
531 tap_state_transition(cur_state, false) != path[i]) {
532 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
533 tap_state_name(cur_state), tap_state_name(path[i]));
534 jtag_set_error(ERROR_JTAG_TRANSITION_INVALID);
535 return;
537 cur_state = path[i];
540 jtag_checks();
542 jtag_set_error(interface_jtag_add_pathmove(num_states, path));
543 cmd_queue_cur_state = path[num_states - 1];
546 int jtag_add_statemove(tap_state_t goal_state)
548 tap_state_t cur_state = cmd_queue_cur_state;
550 if (goal_state != cur_state) {
551 LOG_DEBUG("cur_state=%s goal_state=%s",
552 tap_state_name(cur_state),
553 tap_state_name(goal_state));
556 /* If goal is RESET, be paranoid and force that that transition
557 * (e.g. five TCK cycles, TMS high). Else trust "cur_state".
559 if (goal_state == TAP_RESET)
560 jtag_add_tlr();
561 else if (goal_state == cur_state)
562 /* nothing to do */;
564 else if (tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state)) {
565 unsigned tms_bits = tap_get_tms_path(cur_state, goal_state);
566 unsigned tms_count = tap_get_tms_path_len(cur_state, goal_state);
567 tap_state_t moves[8];
568 assert(tms_count < ARRAY_SIZE(moves));
570 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1) {
571 bool bit = tms_bits & 1;
573 cur_state = tap_state_transition(cur_state, bit);
574 moves[i] = cur_state;
577 jtag_add_pathmove(tms_count, moves);
578 } else if (tap_state_transition(cur_state, true) == goal_state
579 || tap_state_transition(cur_state, false) == goal_state)
580 jtag_add_pathmove(1, &goal_state);
581 else
582 return ERROR_FAIL;
584 return ERROR_OK;
587 void jtag_add_runtest(int num_cycles, tap_state_t state)
589 jtag_prelude(state);
590 jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
594 void jtag_add_clocks(int num_cycles)
596 if (!tap_is_state_stable(cmd_queue_cur_state)) {
597 LOG_ERROR("jtag_add_clocks() called with TAP in unstable state \"%s\"",
598 tap_state_name(cmd_queue_cur_state));
599 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
600 return;
603 if (num_cycles > 0) {
604 jtag_checks();
605 jtag_set_error(interface_jtag_add_clocks(num_cycles));
609 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
611 int trst_with_tlr = 0;
612 int new_srst = 0;
613 int new_trst = 0;
615 /* Without SRST, we must use target-specific JTAG operations
616 * on each target; callers should not be requesting SRST when
617 * that signal doesn't exist.
619 * RESET_SRST_PULLS_TRST is a board or chip level quirk, which
620 * can kick in even if the JTAG adapter can't drive TRST.
622 if (req_srst) {
623 if (!(jtag_reset_config & RESET_HAS_SRST)) {
624 LOG_ERROR("BUG: can't assert SRST");
625 jtag_set_error(ERROR_FAIL);
626 return;
628 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) != 0
629 && !req_tlr_or_trst) {
630 LOG_ERROR("BUG: can't assert only SRST");
631 jtag_set_error(ERROR_FAIL);
632 return;
634 new_srst = 1;
637 /* JTAG reset (entry to TAP_RESET state) can always be achieved
638 * using TCK and TMS; that may go through a TAP_{IR,DR}UPDATE
639 * state first. TRST accelerates it, and bypasses those states.
641 * RESET_TRST_PULLS_SRST is a board or chip level quirk, which
642 * can kick in even if the JTAG adapter can't drive SRST.
644 if (req_tlr_or_trst) {
645 if (!(jtag_reset_config & RESET_HAS_TRST))
646 trst_with_tlr = 1;
647 else if ((jtag_reset_config & RESET_TRST_PULLS_SRST) != 0
648 && !req_srst)
649 trst_with_tlr = 1;
650 else
651 new_trst = 1;
654 /* Maybe change TRST and/or SRST signal state */
655 if (jtag_srst != new_srst || jtag_trst != new_trst) {
656 int retval;
658 retval = interface_jtag_add_reset(new_trst, new_srst);
659 if (retval != ERROR_OK)
660 jtag_set_error(retval);
661 else
662 retval = jtag_execute_queue();
664 if (retval != ERROR_OK) {
665 LOG_ERROR("TRST/SRST error");
666 return;
670 /* SRST resets everything hooked up to that signal */
671 if (jtag_srst != new_srst) {
672 jtag_srst = new_srst;
673 if (jtag_srst) {
674 LOG_DEBUG("SRST line asserted");
675 if (adapter_nsrst_assert_width)
676 jtag_add_sleep(adapter_nsrst_assert_width * 1000);
677 } else {
678 LOG_DEBUG("SRST line released");
679 if (adapter_nsrst_delay)
680 jtag_add_sleep(adapter_nsrst_delay * 1000);
684 /* Maybe enter the JTAG TAP_RESET state ...
685 * - using only TMS, TCK, and the JTAG state machine
686 * - or else more directly, using TRST
688 * TAP_RESET should be invisible to non-debug parts of the system.
690 if (trst_with_tlr) {
691 LOG_DEBUG("JTAG reset with TLR instead of TRST");
692 jtag_add_tlr();
694 } else if (jtag_trst != new_trst) {
695 jtag_trst = new_trst;
696 if (jtag_trst) {
697 LOG_DEBUG("TRST line asserted");
698 tap_set_state(TAP_RESET);
699 if (jtag_ntrst_assert_width)
700 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
701 } else {
702 LOG_DEBUG("TRST line released");
703 if (jtag_ntrst_delay)
704 jtag_add_sleep(jtag_ntrst_delay * 1000);
706 /* We just asserted nTRST, so we're now in TAP_RESET.
707 * Inform possible listeners about this, now that
708 * JTAG instructions and data can be shifted. This
709 * sequence must match jtag_add_tlr().
711 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
712 jtag_notify_event(JTAG_TRST_ASSERTED);
717 void jtag_add_sleep(uint32_t us)
719 /** @todo Here, keep_alive() appears to be a layering violation!!! */
720 keep_alive();
721 jtag_set_error(interface_jtag_add_sleep(us));
724 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
725 uint8_t *in_check_mask, int num_bits)
727 int retval = ERROR_OK;
728 int compare_failed;
730 if (in_check_mask)
731 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
732 else
733 compare_failed = buf_cmp(captured, in_check_value, num_bits);
735 if (compare_failed) {
736 char *captured_str, *in_check_value_str;
737 int bits = (num_bits > DEBUG_JTAG_IOZ) ? DEBUG_JTAG_IOZ : num_bits;
739 /* NOTE: we've lost diagnostic context here -- 'which tap' */
741 captured_str = buf_to_str(captured, bits, 16);
742 in_check_value_str = buf_to_str(in_check_value, bits, 16);
744 LOG_WARNING("Bad value '%s' captured during DR or IR scan:",
745 captured_str);
746 LOG_WARNING(" check_value: 0x%s", in_check_value_str);
748 free(captured_str);
749 free(in_check_value_str);
751 if (in_check_mask) {
752 char *in_check_mask_str;
754 in_check_mask_str = buf_to_str(in_check_mask, bits, 16);
755 LOG_WARNING(" check_mask: 0x%s", in_check_mask_str);
756 free(in_check_mask_str);
759 retval = ERROR_JTAG_QUEUE_FAILED;
761 return retval;
764 void jtag_check_value_mask(struct scan_field *field, uint8_t *value, uint8_t *mask)
766 assert(field->in_value != NULL);
768 if (value == NULL) {
769 /* no checking to do */
770 return;
773 jtag_execute_queue_noclear();
775 int retval = jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
776 jtag_set_error(retval);
779 int default_interface_jtag_execute_queue(void)
781 if (NULL == jtag) {
782 LOG_ERROR("No JTAG interface configured yet. "
783 "Issue 'init' command in startup scripts "
784 "before communicating with targets.");
785 return ERROR_FAIL;
788 return jtag->execute_queue();
791 void jtag_execute_queue_noclear(void)
793 jtag_flush_queue_count++;
794 jtag_set_error(interface_jtag_execute_queue());
796 if (jtag_flush_queue_sleep > 0) {
797 /* For debug purposes it can be useful to test performance
798 * or behavior when delaying after flushing the queue,
799 * e.g. to simulate long roundtrip times.
801 usleep(jtag_flush_queue_sleep * 1000);
805 int jtag_get_flush_queue_count(void)
807 return jtag_flush_queue_count;
810 int jtag_execute_queue(void)
812 jtag_execute_queue_noclear();
813 return jtag_error_clear();
816 static int jtag_reset_callback(enum jtag_event event, void *priv)
818 struct jtag_tap *tap = priv;
820 if (event == JTAG_TRST_ASSERTED) {
821 tap->enabled = !tap->disabled_after_reset;
823 /* current instruction is either BYPASS or IDCODE */
824 buf_set_ones(tap->cur_instr, tap->ir_length);
825 tap->bypass = 1;
828 return ERROR_OK;
831 /* sleep at least us microseconds. When we sleep more than 1000ms we
832 * do an alive sleep, i.e. keep GDB alive. Note that we could starve
833 * GDB if we slept for <1000ms many times.
835 void jtag_sleep(uint32_t us)
837 if (us < 1000)
838 usleep(us);
839 else
840 alive_sleep((us+999)/1000);
843 /* Maximum number of enabled JTAG devices we expect in the scan chain,
844 * plus one (to detect garbage at the end). Devices that don't support
845 * IDCODE take up fewer bits, possibly allowing a few more devices.
847 #define JTAG_MAX_CHAIN_SIZE 20
849 #define EXTRACT_MFG(X) (((X) & 0xffe) >> 1)
850 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
851 #define EXTRACT_VER(X) (((X) & 0xf0000000) >> 28)
853 /* A reserved manufacturer ID is used in END_OF_CHAIN_FLAG, so we
854 * know that no valid TAP will have it as an IDCODE value.
856 #define END_OF_CHAIN_FLAG 0x000000ff
858 /* a larger IR length than we ever expect to autoprobe */
859 #define JTAG_IRLEN_MAX 60
861 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
863 struct scan_field field = {
864 .num_bits = num_idcode * 32,
865 .out_value = idcode_buffer,
866 .in_value = idcode_buffer,
869 /* initialize to the end of chain ID value */
870 for (unsigned i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
871 buf_set_u32(idcode_buffer, i * 32, 32, END_OF_CHAIN_FLAG);
873 jtag_add_plain_dr_scan(field.num_bits, field.out_value, field.in_value, TAP_DRPAUSE);
874 jtag_add_tlr();
875 return jtag_execute_queue();
878 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
880 uint8_t zero_check = 0x0;
881 uint8_t one_check = 0xff;
883 for (unsigned i = 0; i < count * 4; i++) {
884 zero_check |= idcodes[i];
885 one_check &= idcodes[i];
888 /* if there wasn't a single non-zero bit or if all bits were one,
889 * the scan is not valid. We wrote a mix of both values; either
891 * - There's a hardware issue (almost certainly):
892 * + all-zeroes can mean a target stuck in JTAG reset
893 * + all-ones tends to mean no target
894 * - The scan chain is WAY longer than we can handle, *AND* either
895 * + there are several hundreds of TAPs in bypass, or
896 * + at least a few dozen TAPs all have an all-ones IDCODE
898 if (zero_check == 0x00 || one_check == 0xff) {
899 LOG_ERROR("JTAG scan chain interrogation failed: all %s",
900 (zero_check == 0x00) ? "zeroes" : "ones");
901 LOG_ERROR("Check JTAG interface, timings, target power, etc.");
902 return false;
904 return true;
907 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
908 const char *name, uint32_t idcode)
910 log_printf_lf(level, __FILE__, __LINE__, __func__,
911 "JTAG tap: %s %16.16s: 0x%08x "
912 "(mfg: 0x%3.3x, part: 0x%4.4x, ver: 0x%1.1x)",
913 name, msg,
914 (unsigned int)idcode,
915 (unsigned int)EXTRACT_MFG(idcode),
916 (unsigned int)EXTRACT_PART(idcode),
917 (unsigned int)EXTRACT_VER(idcode));
920 static bool jtag_idcode_is_final(uint32_t idcode)
923 * Some devices, such as AVR8, will output all 1's instead
924 * of TDI input value at end of chain. Allow those values
925 * instead of failing.
927 return idcode == END_OF_CHAIN_FLAG || idcode == 0xFFFFFFFF;
931 * This helper checks that remaining bits in the examined chain data are
932 * all as expected, but a single JTAG device requires only 64 bits to be
933 * read back correctly. This can help identify and diagnose problems
934 * with the JTAG chain earlier, gives more helpful/explicit error messages.
935 * Returns TRUE iff garbage was found.
937 static bool jtag_examine_chain_end(uint8_t *idcodes, unsigned count, unsigned max)
939 bool triggered = false;
940 for (; count < max - 31; count += 32) {
941 uint32_t idcode = buf_get_u32(idcodes, count, 32);
943 /* do not trigger the warning if the data looks good */
944 if (jtag_idcode_is_final(idcode))
945 continue;
946 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
947 count, (unsigned int)idcode);
948 triggered = true;
950 return triggered;
953 static bool jtag_examine_chain_match_tap(const struct jtag_tap *tap)
955 uint32_t idcode = tap->idcode;
957 /* ignore expected BYPASS codes; warn otherwise */
958 if (0 == tap->expected_ids_cnt && !idcode)
959 return true;
961 /* optionally ignore the JTAG version field */
962 uint32_t mask = tap->ignore_version ? ~(0xff << 24) : ~0;
964 idcode &= mask;
966 /* Loop over the expected identification codes and test for a match */
967 unsigned ii, limit = tap->expected_ids_cnt;
969 for (ii = 0; ii < limit; ii++) {
970 uint32_t expected = tap->expected_ids[ii] & mask;
972 if (idcode == expected)
973 return true;
975 /* treat "-expected-id 0" as a "don't-warn" wildcard */
976 if (0 == tap->expected_ids[ii])
977 return true;
980 /* If none of the expected ids matched, warn */
981 jtag_examine_chain_display(LOG_LVL_WARNING, "UNEXPECTED",
982 tap->dotted_name, tap->idcode);
983 for (ii = 0; ii < limit; ii++) {
984 char msg[32];
986 snprintf(msg, sizeof(msg), "expected %u of %u", ii + 1, limit);
987 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
988 tap->dotted_name, tap->expected_ids[ii]);
990 return false;
993 /* Try to examine chain layout according to IEEE 1149.1 §12
994 * This is called a "blind interrogation" of the scan chain.
996 static int jtag_examine_chain(void)
998 uint8_t idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
999 unsigned bit_count;
1000 int retval;
1001 int tapcount = 0;
1002 bool autoprobe = false;
1004 /* DR scan to collect BYPASS or IDCODE register contents.
1005 * Then make sure the scan data has both ones and zeroes.
1007 LOG_DEBUG("DR scan interrogation for IDCODE/BYPASS");
1008 retval = jtag_examine_chain_execute(idcode_buffer, JTAG_MAX_CHAIN_SIZE);
1009 if (retval != ERROR_OK)
1010 return retval;
1011 if (!jtag_examine_chain_check(idcode_buffer, JTAG_MAX_CHAIN_SIZE))
1012 return ERROR_JTAG_INIT_FAILED;
1014 /* point at the 1st tap */
1015 struct jtag_tap *tap = jtag_tap_next_enabled(NULL);
1017 if (!tap)
1018 autoprobe = true;
1020 for (bit_count = 0;
1021 tap && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;
1022 tap = jtag_tap_next_enabled(tap)) {
1023 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1025 if ((idcode & 1) == 0) {
1026 /* Zero for LSB indicates a device in bypass */
1027 LOG_INFO("TAP %s does not have IDCODE",
1028 tap->dotted_name);
1029 idcode = 0;
1030 tap->hasidcode = false;
1032 bit_count += 1;
1033 } else {
1034 /* Friendly devices support IDCODE */
1035 tap->hasidcode = true;
1036 jtag_examine_chain_display(LOG_LVL_INFO,
1037 "tap/device found",
1038 tap->dotted_name, idcode);
1040 bit_count += 32;
1042 tap->idcode = idcode;
1044 /* ensure the TAP ID matches what was expected */
1045 if (!jtag_examine_chain_match_tap(tap))
1046 retval = ERROR_JTAG_INIT_SOFT_FAIL;
1049 /* Fail if too many TAPs were enabled for us to verify them all. */
1050 if (tap) {
1051 LOG_ERROR("Too many TAPs enabled; '%s' ignored.",
1052 tap->dotted_name);
1053 return ERROR_JTAG_INIT_FAILED;
1056 /* if autoprobing, the tap list is still empty ... populate it! */
1057 while (autoprobe && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31) {
1058 uint32_t idcode;
1059 char buf[12];
1061 /* Is there another TAP? */
1062 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1063 if (jtag_idcode_is_final(idcode))
1064 break;
1066 /* Default everything in this TAP except IR length.
1068 * REVISIT create a jtag_alloc(chip, tap) routine, and
1069 * share it with jim_newtap_cmd().
1071 tap = calloc(1, sizeof *tap);
1072 if (!tap)
1073 return ERROR_FAIL;
1075 sprintf(buf, "auto%d", tapcount++);
1076 tap->chip = strdup(buf);
1077 tap->tapname = strdup("tap");
1079 sprintf(buf, "%s.%s", tap->chip, tap->tapname);
1080 tap->dotted_name = strdup(buf);
1082 /* tap->ir_length == 0 ... signifying irlen autoprobe */
1083 tap->ir_capture_mask = 0x03;
1084 tap->ir_capture_value = 0x01;
1086 tap->enabled = true;
1088 if ((idcode & 1) == 0) {
1089 bit_count += 1;
1090 tap->hasidcode = false;
1091 } else {
1092 bit_count += 32;
1093 tap->hasidcode = true;
1094 tap->idcode = idcode;
1096 tap->expected_ids_cnt = 1;
1097 tap->expected_ids = malloc(sizeof(uint32_t));
1098 tap->expected_ids[0] = idcode;
1101 LOG_WARNING("AUTO %s - use \"jtag newtap "
1102 "%s %s -expected-id 0x%8.8" PRIx32 " ...\"",
1103 tap->dotted_name, tap->chip, tap->tapname,
1104 tap->idcode);
1106 jtag_tap_init(tap);
1109 /* After those IDCODE or BYPASS register values should be
1110 * only the data we fed into the scan chain.
1112 if (jtag_examine_chain_end(idcode_buffer, bit_count,
1113 8 * sizeof(idcode_buffer))) {
1114 LOG_ERROR("double-check your JTAG setup (interface, "
1115 "speed, missing TAPs, ...)");
1116 return ERROR_JTAG_INIT_FAILED;
1119 /* Return success or, for backwards compatibility if only
1120 * some IDCODE values mismatched, a soft/continuable fault.
1122 return retval;
1126 * Validate the date loaded by entry to the Capture-IR state, to help
1127 * find errors related to scan chain configuration (wrong IR lengths)
1128 * or communication.
1130 * Entry state can be anything. On non-error exit, all TAPs are in
1131 * bypass mode. On error exits, the scan chain is reset.
1133 static int jtag_validate_ircapture(void)
1135 struct jtag_tap *tap;
1136 int total_ir_length = 0;
1137 uint8_t *ir_test = NULL;
1138 struct scan_field field;
1139 int val;
1140 int chain_pos = 0;
1141 int retval;
1143 /* when autoprobing, accomodate huge IR lengths */
1144 for (tap = NULL, total_ir_length = 0;
1145 (tap = jtag_tap_next_enabled(tap)) != NULL;
1146 total_ir_length += tap->ir_length) {
1147 if (tap->ir_length == 0)
1148 total_ir_length += JTAG_IRLEN_MAX;
1151 /* increase length to add 2 bit sentinel after scan */
1152 total_ir_length += 2;
1154 ir_test = malloc(DIV_ROUND_UP(total_ir_length, 8));
1155 if (ir_test == NULL)
1156 return ERROR_FAIL;
1158 /* after this scan, all TAPs will capture BYPASS instructions */
1159 buf_set_ones(ir_test, total_ir_length);
1161 field.num_bits = total_ir_length;
1162 field.out_value = ir_test;
1163 field.in_value = ir_test;
1165 jtag_add_plain_ir_scan(field.num_bits, field.out_value, field.in_value, TAP_IDLE);
1167 LOG_DEBUG("IR capture validation scan");
1168 retval = jtag_execute_queue();
1169 if (retval != ERROR_OK)
1170 goto done;
1172 tap = NULL;
1173 chain_pos = 0;
1175 for (;; ) {
1176 tap = jtag_tap_next_enabled(tap);
1177 if (tap == NULL)
1178 break;
1180 /* If we're autoprobing, guess IR lengths. They must be at
1181 * least two bits. Guessing will fail if (a) any TAP does
1182 * not conform to the JTAG spec; or (b) when the upper bits
1183 * captured from some conforming TAP are nonzero. Or if
1184 * (c) an IR length is longer than 32 bits -- which is only
1185 * an implementation limit, which could someday be raised.
1187 * REVISIT optimization: if there's a *single* TAP we can
1188 * lift restrictions (a) and (b) by scanning a recognizable
1189 * pattern before the all-ones BYPASS. Check for where the
1190 * pattern starts in the result, instead of an 0...01 value.
1192 * REVISIT alternative approach: escape to some tcl code
1193 * which could provide more knowledge, based on IDCODE; and
1194 * only guess when that has no success.
1196 if (tap->ir_length == 0) {
1197 tap->ir_length = 2;
1198 while ((val = buf_get_u32(ir_test, chain_pos, tap->ir_length + 1)) == 1
1199 && tap->ir_length <= 32) {
1200 tap->ir_length++;
1202 LOG_WARNING("AUTO %s - use \"... -irlen %d\"",
1203 jtag_tap_name(tap), tap->ir_length);
1206 /* Validate the two LSBs, which must be 01 per JTAG spec.
1208 * Or ... more bits could be provided by TAP declaration.
1209 * Plus, some taps (notably in i.MX series chips) violate
1210 * this part of the JTAG spec, so their capture mask/value
1211 * attributes might disable this test.
1213 val = buf_get_u32(ir_test, chain_pos, tap->ir_length);
1214 if ((val & tap->ir_capture_mask) != tap->ir_capture_value) {
1215 LOG_ERROR("%s: IR capture error; saw 0x%0*x not 0x%0*x",
1216 jtag_tap_name(tap),
1217 (tap->ir_length + 7) / tap->ir_length,
1218 val,
1219 (tap->ir_length + 7) / tap->ir_length,
1220 (unsigned) tap->ir_capture_value);
1222 retval = ERROR_JTAG_INIT_FAILED;
1223 goto done;
1225 LOG_DEBUG("%s: IR capture 0x%0*x", jtag_tap_name(tap),
1226 (tap->ir_length + 7) / tap->ir_length, val);
1227 chain_pos += tap->ir_length;
1230 /* verify the '11' sentinel we wrote is returned at the end */
1231 val = buf_get_u32(ir_test, chain_pos, 2);
1232 if (val != 0x3) {
1233 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1235 LOG_ERROR("IR capture error at bit %d, saw 0x%s not 0x...3",
1236 chain_pos, cbuf);
1237 free(cbuf);
1238 retval = ERROR_JTAG_INIT_FAILED;
1241 done:
1242 free(ir_test);
1243 if (retval != ERROR_OK) {
1244 jtag_add_tlr();
1245 jtag_execute_queue();
1247 return retval;
1250 void jtag_tap_init(struct jtag_tap *tap)
1252 unsigned ir_len_bits;
1253 unsigned ir_len_bytes;
1255 /* if we're autoprobing, cope with potentially huge ir_length */
1256 ir_len_bits = tap->ir_length ? : JTAG_IRLEN_MAX;
1257 ir_len_bytes = DIV_ROUND_UP(ir_len_bits, 8);
1259 tap->expected = calloc(1, ir_len_bytes);
1260 tap->expected_mask = calloc(1, ir_len_bytes);
1261 tap->cur_instr = malloc(ir_len_bytes);
1263 /** @todo cope better with ir_length bigger than 32 bits */
1264 if (ir_len_bits > 32)
1265 ir_len_bits = 32;
1267 buf_set_u32(tap->expected, 0, ir_len_bits, tap->ir_capture_value);
1268 buf_set_u32(tap->expected_mask, 0, ir_len_bits, tap->ir_capture_mask);
1270 /* TAP will be in bypass mode after jtag_validate_ircapture() */
1271 tap->bypass = 1;
1272 buf_set_ones(tap->cur_instr, tap->ir_length);
1274 /* register the reset callback for the TAP */
1275 jtag_register_event_callback(&jtag_reset_callback, tap);
1277 LOG_DEBUG("Created Tap: %s @ abs position %d, "
1278 "irlen %d, capture: 0x%x mask: 0x%x", tap->dotted_name,
1279 tap->abs_chain_position, tap->ir_length,
1280 (unsigned) tap->ir_capture_value,
1281 (unsigned) tap->ir_capture_mask);
1282 jtag_tap_add(tap);
1285 void jtag_tap_free(struct jtag_tap *tap)
1287 jtag_unregister_event_callback(&jtag_reset_callback, tap);
1289 /** @todo is anything missing? no memory leaks please */
1290 free((void *)tap->expected);
1291 free((void *)tap->expected_ids);
1292 free((void *)tap->chip);
1293 free((void *)tap->tapname);
1294 free((void *)tap->dotted_name);
1295 free(tap);
1299 * Do low-level setup like initializing registers, output signals,
1300 * and clocking.
1302 int adapter_init(struct command_context *cmd_ctx)
1304 if (jtag)
1305 return ERROR_OK;
1307 if (!jtag_interface) {
1308 /* nothing was previously specified by "interface" command */
1309 LOG_ERROR("Debug Adapter has to be specified, "
1310 "see \"interface\" command");
1311 return ERROR_JTAG_INVALID_INTERFACE;
1314 int retval;
1315 retval = jtag_interface->init();
1316 if (retval != ERROR_OK)
1317 return retval;
1318 jtag = jtag_interface;
1320 /* LEGACY SUPPORT ... adapter drivers must declare what
1321 * transports they allow. Until they all do so, assume
1322 * the legacy drivers are JTAG-only
1324 if (!transports_are_declared()) {
1325 LOG_ERROR("Adapter driver '%s' did not declare "
1326 "which transports it allows; assuming "
1327 "JTAG-only", jtag->name);
1328 retval = allow_transports(cmd_ctx, jtag_only);
1329 if (retval != ERROR_OK)
1330 return retval;
1333 if (CLOCK_MODE_UNSELECTED == clock_mode) {
1334 LOG_ERROR("An adapter speed is not selected in the init script."
1335 " Insert a call to adapter_khz or jtag_rclk to proceed.");
1336 return ERROR_JTAG_INIT_FAILED;
1339 int requested_khz = jtag_get_speed_khz();
1340 int actual_khz = requested_khz;
1341 int jtag_speed_var = 0;
1342 retval = jtag_get_speed(&jtag_speed_var);
1343 if (retval != ERROR_OK)
1344 return retval;
1345 retval = jtag->speed(jtag_speed_var);
1346 if (retval != ERROR_OK)
1347 return retval;
1348 retval = jtag_get_speed_readable(&actual_khz);
1349 if (ERROR_OK != retval)
1350 LOG_INFO("adapter-specific clock speed value %d", jtag_speed_var);
1351 else if (actual_khz) {
1352 /* Adaptive clocking -- JTAG-specific */
1353 if ((CLOCK_MODE_RCLK == clock_mode)
1354 || ((CLOCK_MODE_KHZ == clock_mode) && !requested_khz)) {
1355 LOG_INFO("RCLK (adaptive clock speed) not supported - fallback to %d kHz"
1356 , actual_khz);
1357 } else
1358 LOG_INFO("clock speed %d kHz", actual_khz);
1359 } else
1360 LOG_INFO("RCLK (adaptive clock speed)");
1362 return ERROR_OK;
1365 int jtag_init_inner(struct command_context *cmd_ctx)
1367 struct jtag_tap *tap;
1368 int retval;
1369 bool issue_setup = true;
1371 LOG_DEBUG("Init JTAG chain");
1373 tap = jtag_tap_next_enabled(NULL);
1374 if (tap == NULL) {
1375 /* Once JTAG itself is properly set up, and the scan chain
1376 * isn't absurdly large, IDCODE autoprobe should work fine.
1378 * But ... IRLEN autoprobe can fail even on systems which
1379 * are fully conformant to JTAG. Also, JTAG setup can be
1380 * quite finicky on some systems.
1382 * REVISIT: if TAP autoprobe works OK, then in many cases
1383 * we could escape to tcl code and set up targets based on
1384 * the TAP's IDCODE values.
1386 LOG_WARNING("There are no enabled taps. "
1387 "AUTO PROBING MIGHT NOT WORK!!");
1389 /* REVISIT default clock will often be too fast ... */
1392 jtag_add_tlr();
1393 retval = jtag_execute_queue();
1394 if (retval != ERROR_OK)
1395 return retval;
1397 /* Examine DR values first. This discovers problems which will
1398 * prevent communication ... hardware issues like TDO stuck, or
1399 * configuring the wrong number of (enabled) TAPs.
1401 retval = jtag_examine_chain();
1402 switch (retval) {
1403 case ERROR_OK:
1404 /* complete success */
1405 break;
1406 default:
1407 /* For backward compatibility reasons, try coping with
1408 * configuration errors involving only ID mismatches.
1409 * We might be able to talk to the devices.
1411 * Also the device might be powered down during startup.
1413 * After OpenOCD starts, we can try to power on the device
1414 * and run a reset.
1416 LOG_ERROR("Trying to use configured scan chain anyway...");
1417 issue_setup = false;
1418 break;
1421 /* Now look at IR values. Problems here will prevent real
1422 * communication. They mostly mean that the IR length is
1423 * wrong ... or that the IR capture value is wrong. (The
1424 * latter is uncommon, but easily worked around: provide
1425 * ircapture/irmask values during TAP setup.)
1427 retval = jtag_validate_ircapture();
1428 if (retval != ERROR_OK) {
1429 /* The target might be powered down. The user
1430 * can power it up and reset it after firing
1431 * up OpenOCD.
1433 issue_setup = false;
1436 if (issue_setup)
1437 jtag_notify_event(JTAG_TAP_EVENT_SETUP);
1438 else
1439 LOG_WARNING("Bypassing JTAG setup events due to errors");
1442 return ERROR_OK;
1445 int adapter_quit(void)
1447 if (!jtag || !jtag->quit)
1448 return ERROR_OK;
1450 /* close the JTAG interface */
1451 int result = jtag->quit();
1452 if (ERROR_OK != result)
1453 LOG_ERROR("failed: %d", result);
1455 return ERROR_OK;
1459 int jtag_init_reset(struct command_context *cmd_ctx)
1461 int retval = adapter_init(cmd_ctx);
1462 if (retval != ERROR_OK)
1463 return retval;
1465 LOG_DEBUG("Initializing with hard TRST+SRST reset");
1468 * This procedure is used by default when OpenOCD triggers a reset.
1469 * It's now done through an overridable Tcl "init_reset" wrapper.
1471 * This started out as a more powerful "get JTAG working" reset than
1472 * jtag_init_inner(), applying TRST because some chips won't activate
1473 * JTAG without a TRST cycle (presumed to be async, though some of
1474 * those chips synchronize JTAG activation using TCK).
1476 * But some chips only activate JTAG as part of an SRST cycle; SRST
1477 * got mixed in. So it became a hard reset routine, which got used
1478 * in more places, and which coped with JTAG reset being forced as
1479 * part of SRST (srst_pulls_trst).
1481 * And even more corner cases started to surface: TRST and/or SRST
1482 * assertion timings matter; some chips need other JTAG operations;
1483 * TRST/SRST sequences can need to be different from these, etc.
1485 * Systems should override that wrapper to support system-specific
1486 * requirements that this not-fully-generic code doesn't handle.
1488 * REVISIT once Tcl code can read the reset_config modes, this won't
1489 * need to be a C routine at all...
1491 jtag_add_reset(1, 0); /* TAP_RESET, using TMS+TCK or TRST */
1492 if (jtag_reset_config & RESET_HAS_SRST) {
1493 jtag_add_reset(1, 1);
1494 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) == 0)
1495 jtag_add_reset(0, 1);
1497 jtag_add_reset(0, 0);
1498 retval = jtag_execute_queue();
1499 if (retval != ERROR_OK)
1500 return retval;
1502 /* Check that we can communication on the JTAG chain + eventually we want to
1503 * be able to perform enumeration only after OpenOCD has started
1504 * telnet and GDB server
1506 * That would allow users to more easily perform any magic they need to before
1507 * reset happens.
1509 return jtag_init_inner(cmd_ctx);
1512 int jtag_init(struct command_context *cmd_ctx)
1514 int retval = adapter_init(cmd_ctx);
1515 if (retval != ERROR_OK)
1516 return retval;
1518 /* guard against oddball hardware: force resets to be inactive */
1519 jtag_add_reset(0, 0);
1520 retval = jtag_execute_queue();
1521 if (retval != ERROR_OK)
1522 return retval;
1524 if (Jim_Eval_Named(cmd_ctx->interp, "jtag_init", __FILE__, __LINE__) != JIM_OK)
1525 return ERROR_FAIL;
1527 return ERROR_OK;
1530 unsigned jtag_get_speed_khz(void)
1532 return speed_khz;
1535 static int adapter_khz_to_speed(unsigned khz, int *speed)
1537 LOG_DEBUG("convert khz to interface specific speed value");
1538 speed_khz = khz;
1539 if (jtag != NULL) {
1540 LOG_DEBUG("have interface set up");
1541 int speed_div1;
1542 int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1543 if (ERROR_OK != retval)
1544 return retval;
1545 *speed = speed_div1;
1547 return ERROR_OK;
1550 static int jtag_rclk_to_speed(unsigned fallback_speed_khz, int *speed)
1552 int retval = adapter_khz_to_speed(0, speed);
1553 if ((ERROR_OK != retval) && fallback_speed_khz) {
1554 LOG_DEBUG("trying fallback speed...");
1555 retval = adapter_khz_to_speed(fallback_speed_khz, speed);
1557 return retval;
1560 static int jtag_set_speed(int speed)
1562 jtag_speed = speed;
1563 /* this command can be called during CONFIG,
1564 * in which case jtag isn't initialized */
1565 return jtag ? jtag->speed(speed) : ERROR_OK;
1568 int jtag_config_khz(unsigned khz)
1570 LOG_DEBUG("handle jtag khz");
1571 clock_mode = CLOCK_MODE_KHZ;
1572 int speed = 0;
1573 int retval = adapter_khz_to_speed(khz, &speed);
1574 return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1577 int jtag_config_rclk(unsigned fallback_speed_khz)
1579 LOG_DEBUG("handle jtag rclk");
1580 clock_mode = CLOCK_MODE_RCLK;
1581 rclk_fallback_speed_khz = fallback_speed_khz;
1582 int speed = 0;
1583 int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1584 return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1587 int jtag_get_speed(int *speed)
1589 switch (clock_mode) {
1590 case CLOCK_MODE_KHZ:
1591 adapter_khz_to_speed(jtag_get_speed_khz(), speed);
1592 break;
1593 case CLOCK_MODE_RCLK:
1594 jtag_rclk_to_speed(rclk_fallback_speed_khz, speed);
1595 break;
1596 default:
1597 LOG_ERROR("BUG: unknown jtag clock mode");
1598 return ERROR_FAIL;
1600 return ERROR_OK;
1603 int jtag_get_speed_readable(int *khz)
1605 int jtag_speed_var = 0;
1606 int retval = jtag_get_speed(&jtag_speed_var);
1607 if (retval != ERROR_OK)
1608 return retval;
1609 return jtag ? jtag->speed_div(jtag_speed_var, khz) : ERROR_OK;
1612 void jtag_set_verify(bool enable)
1614 jtag_verify = enable;
1617 bool jtag_will_verify()
1619 return jtag_verify;
1622 void jtag_set_verify_capture_ir(bool enable)
1624 jtag_verify_capture_ir = enable;
1627 bool jtag_will_verify_capture_ir()
1629 return jtag_verify_capture_ir;
1632 int jtag_power_dropout(int *dropout)
1634 if (jtag == NULL) {
1635 /* TODO: as the jtag interface is not valid all
1636 * we can do at the moment is exit OpenOCD */
1637 LOG_ERROR("No Valid JTAG Interface Configured.");
1638 exit(-1);
1640 return jtag->power_dropout(dropout);
1643 int jtag_srst_asserted(int *srst_asserted)
1645 return jtag->srst_asserted(srst_asserted);
1648 enum reset_types jtag_get_reset_config(void)
1650 return jtag_reset_config;
1652 void jtag_set_reset_config(enum reset_types type)
1654 jtag_reset_config = type;
1657 int jtag_get_trst(void)
1659 return jtag_trst;
1661 int jtag_get_srst(void)
1663 return jtag_srst;
1666 void jtag_set_nsrst_delay(unsigned delay)
1668 adapter_nsrst_delay = delay;
1670 unsigned jtag_get_nsrst_delay(void)
1672 return adapter_nsrst_delay;
1674 void jtag_set_ntrst_delay(unsigned delay)
1676 jtag_ntrst_delay = delay;
1678 unsigned jtag_get_ntrst_delay(void)
1680 return jtag_ntrst_delay;
1684 void jtag_set_nsrst_assert_width(unsigned delay)
1686 adapter_nsrst_assert_width = delay;
1688 unsigned jtag_get_nsrst_assert_width(void)
1690 return adapter_nsrst_assert_width;
1692 void jtag_set_ntrst_assert_width(unsigned delay)
1694 jtag_ntrst_assert_width = delay;
1696 unsigned jtag_get_ntrst_assert_width(void)
1698 return jtag_ntrst_assert_width;
1701 static int jtag_select(struct command_context *ctx)
1703 int retval;
1705 /* NOTE: interface init must already have been done.
1706 * That works with only C code ... no Tcl glue required.
1709 retval = jtag_register_commands(ctx);
1711 if (retval != ERROR_OK)
1712 return retval;
1714 retval = svf_register_commands(ctx);
1716 if (retval != ERROR_OK)
1717 return retval;
1719 return xsvf_register_commands(ctx);
1722 static struct transport jtag_transport = {
1723 .name = "jtag",
1724 .select = jtag_select,
1725 .init = jtag_init,
1728 static void jtag_constructor(void) __attribute__((constructor));
1729 static void jtag_constructor(void)
1731 transport_register(&jtag_transport);
1734 /** Returns true if the current debug session
1735 * is using JTAG as its transport.
1737 bool transport_is_jtag(void)
1739 return get_current_transport() == &jtag_transport;