1 /***************************************************************************
2 * Copyright (C) 2009 Zachary T Welch *
3 * zw@superlucidity.net *
5 * Copyright (C) 2007,2008,2009 Øyvind Harboe *
6 * oyvind.harboe@zylin.com *
8 * Copyright (C) 2009 SoftPLC Corporation *
12 * Copyright (C) 2005 by Dominic Rath *
13 * Dominic.Rath@gmx.de *
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. *
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. *
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 ***************************************************************************/
35 #include "minidriver.h"
36 #include "interface.h"
43 /// The number of JTAG queue flushes (for profiling and debugging purposes).
44 static int jtag_flush_queue_count;
46 static void jtag_add_scan_check(void (*jtag_add_scan)(int in_num_fields, const struct scan_field *in_fields, tap_state_t state),
47 int in_num_fields, struct scan_field *in_fields, tap_state_t state);
50 * The jtag_error variable is set when an error occurs while executing
51 * the queue. Application code may set this using jtag_set_error(),
52 * when an error occurs during processing that should be reported during
53 * jtag_execute_queue().
55 * Tts value may be checked with jtag_get_error() and cleared with
56 * jtag_error_clear(). This value is returned (and cleared) by
57 * jtag_execute_queue().
59 static int jtag_error = ERROR_OK;
61 static const char *jtag_event_strings[] =
63 [JTAG_TRST_ASSERTED] = "TAP reset",
64 [JTAG_TAP_EVENT_SETUP] = "TAP setup",
65 [JTAG_TAP_EVENT_ENABLE] = "TAP enabled",
66 [JTAG_TAP_EVENT_DISABLE] = "TAP disabled",
70 * JTAG adapters must initialize with TRST and SRST de-asserted
71 * (they're negative logic, so that means *high*). But some
72 * hardware doesn't necessarily work that way ... so set things
73 * up so that jtag_init() always forces that state.
75 static int jtag_trst = -1;
76 static int jtag_srst = -1;
79 * List all TAPs that have been created.
81 static struct jtag_tap *__jtag_all_taps = NULL;
83 * The number of TAPs in the __jtag_all_taps list, used to track the
84 * assigned chain position to new TAPs
86 static unsigned jtag_num_taps = 0;
88 static enum reset_types jtag_reset_config = RESET_NONE;
89 static tap_state_t cmd_queue_end_state = TAP_RESET;
90 tap_state_t cmd_queue_cur_state = TAP_RESET;
92 static bool jtag_verify_capture_ir = true;
93 static int jtag_verify = 1;
95 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines deasserted (in ms) */
96 static int jtag_nsrst_delay = 0; /* default to no nSRST delay */
97 static int jtag_ntrst_delay = 0; /* default to no nTRST delay */
98 static int jtag_nsrst_assert_width = 0; /* width of assertion */
99 static int jtag_ntrst_assert_width = 0; /* width of assertion */
102 * Contains a single callback along with a pointer that will be passed
103 * when an event occurs.
105 struct jtag_event_callback {
107 jtag_event_handler_t callback;
108 /// the private data to pass to the callback
110 /// the next callback
111 struct jtag_event_callback* next;
114 /* callbacks to inform high-level handlers about JTAG state changes */
115 static struct jtag_event_callback *jtag_event_callbacks;
118 static int speed_khz = 0;
119 /* speed to fallback to when RCLK is requested but not supported */
120 static int rclk_fallback_speed_khz = 0;
121 static enum {CLOCK_MODE_SPEED, CLOCK_MODE_KHZ, CLOCK_MODE_RCLK} clock_mode;
122 static int jtag_speed = 0;
124 static struct jtag_interface *jtag = NULL;
127 struct jtag_interface *jtag_interface = NULL;
129 void jtag_set_error(int error)
131 if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
135 int jtag_get_error(void)
139 int jtag_error_clear(void)
141 int temp = jtag_error;
142 jtag_error = ERROR_OK;
148 static bool jtag_poll = 1;
150 bool is_jtag_poll_safe(void)
152 /* Polling can be disabled explicitly with set_enabled(false).
153 * It is also implicitly disabled while TRST is active and
154 * while SRST is gating the JTAG clock.
156 if (!jtag_poll || jtag_trst != 0)
158 return jtag_srst == 0 || (jtag_reset_config & RESET_SRST_NO_GATING);
161 bool jtag_poll_get_enabled(void)
166 void jtag_poll_set_enabled(bool value)
173 struct jtag_tap *jtag_all_taps(void)
175 return __jtag_all_taps;
178 unsigned jtag_tap_count(void)
180 return jtag_num_taps;
183 unsigned jtag_tap_count_enabled(void)
185 struct jtag_tap *t = jtag_all_taps();
196 /// Append a new TAP to the chain of all taps.
197 void jtag_tap_add(struct jtag_tap *t)
199 t->abs_chain_position = jtag_num_taps++;
201 struct jtag_tap **tap = &__jtag_all_taps;
203 tap = &(*tap)->next_tap;
207 /* returns a pointer to the n-th device in the scan chain */
208 static inline struct jtag_tap *jtag_tap_by_position(unsigned n)
210 struct jtag_tap *t = jtag_all_taps();
218 struct jtag_tap *jtag_tap_by_string(const char *s)
220 /* try by name first */
221 struct jtag_tap *t = jtag_all_taps();
225 if (0 == strcmp(t->dotted_name, s))
230 /* no tap found by name, so try to parse the name as a number */
232 if (parse_uint(s, &n) != ERROR_OK)
235 /* FIXME remove this numeric fallback code late June 2010, along
236 * with all info in the User's Guide that TAPs have numeric IDs.
237 * Also update "scan_chain" output to not display the numbers.
239 t = jtag_tap_by_position(n);
241 LOG_WARNING("Specify TAP '%s' by name, not number %u",
247 struct jtag_tap *jtag_tap_by_jim_obj(Jim_Interp *interp, Jim_Obj *o)
249 const char *cp = Jim_GetString(o, NULL);
250 struct jtag_tap *t = cp ? jtag_tap_by_string(cp) : NULL;
254 Jim_SetResult_sprintf(interp, "Tap '%s' could not be found", cp);
258 struct jtag_tap* jtag_tap_next_enabled(struct jtag_tap* p)
260 p = p ? p->next_tap : jtag_all_taps();
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)
282 return ERROR_INVALID_ARGUMENTS;
287 while ((*callbacks_p)->next)
288 callbacks_p = &((*callbacks_p)->next);
289 callbacks_p = &((*callbacks_p)->next);
292 (*callbacks_p) = malloc(sizeof(struct jtag_event_callback));
293 (*callbacks_p)->callback = callback;
294 (*callbacks_p)->priv = priv;
295 (*callbacks_p)->next = NULL;
300 int jtag_unregister_event_callback(jtag_event_handler_t callback, void *priv)
302 struct jtag_event_callback **callbacks_p;
303 struct jtag_event_callback **next;
305 if (callback == NULL)
307 return ERROR_INVALID_ARGUMENTS;
310 for (callbacks_p = &jtag_event_callbacks;
311 *callbacks_p != NULL;
314 next = &((*callbacks_p)->next);
316 if ((*callbacks_p)->priv != priv)
319 if ((*callbacks_p)->callback == callback)
322 *callbacks_p = *next;
329 int jtag_call_event_callbacks(enum jtag_event event)
331 struct jtag_event_callback *callback = jtag_event_callbacks;
333 LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
337 struct jtag_event_callback *next;
339 /* callback may remove itself */
340 next = callback->next;
341 callback->callback(event, callback->priv);
348 static void jtag_checks(void)
350 assert(jtag_trst == 0);
353 static void jtag_prelude(tap_state_t state)
357 assert(state != TAP_INVALID);
359 cmd_queue_cur_state = state;
362 void jtag_alloc_in_value32(struct scan_field *field)
364 interface_jtag_alloc_in_value32(field);
367 void jtag_add_ir_scan_noverify(int in_count, const struct scan_field *in_fields,
372 int retval = interface_jtag_add_ir_scan(in_count, in_fields, state);
373 jtag_set_error(retval);
377 void jtag_add_ir_scan(int in_num_fields, struct scan_field *in_fields, tap_state_t state)
379 assert(state != TAP_RESET);
381 if (jtag_verify && jtag_verify_capture_ir)
383 /* 8 x 32 bit id's is enough for all invocations */
385 for (int j = 0; j < in_num_fields; j++)
387 /* if we are to run a verification of the ir scan, we need to get the input back.
388 * We may have to allocate space if the caller didn't ask for the input back.
390 in_fields[j].check_value = in_fields[j].tap->expected;
391 in_fields[j].check_mask = in_fields[j].tap->expected_mask;
393 jtag_add_scan_check(jtag_add_ir_scan_noverify, in_num_fields, in_fields, state);
396 jtag_add_ir_scan_noverify(in_num_fields, in_fields, state);
400 void jtag_add_plain_ir_scan(int in_num_fields, const struct scan_field *in_fields,
403 assert(state != TAP_RESET);
407 int retval = interface_jtag_add_plain_ir_scan(
408 in_num_fields, in_fields, state);
409 jtag_set_error(retval);
412 void jtag_add_callback(jtag_callback1_t f, jtag_callback_data_t data0)
414 interface_jtag_add_callback(f, data0);
417 void jtag_add_callback4(jtag_callback_t f, jtag_callback_data_t data0,
418 jtag_callback_data_t data1, jtag_callback_data_t data2,
419 jtag_callback_data_t data3)
421 interface_jtag_add_callback4(f, data0, data1, data2, data3);
424 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
425 uint8_t *in_check_mask, int num_bits);
427 static int jtag_check_value_mask_callback(jtag_callback_data_t data0, jtag_callback_data_t data1, jtag_callback_data_t data2, jtag_callback_data_t data3)
429 return jtag_check_value_inner((uint8_t *)data0, (uint8_t *)data1, (uint8_t *)data2, (int)data3);
432 static void jtag_add_scan_check(void (*jtag_add_scan)(int in_num_fields, const struct scan_field *in_fields, tap_state_t state),
433 int in_num_fields, struct scan_field *in_fields, tap_state_t state)
435 for (int i = 0; i < in_num_fields; i++)
437 struct scan_field *field = &in_fields[i];
438 field->allocated = 0;
440 if (field->check_value || field->in_value)
442 interface_jtag_add_scan_check_alloc(field);
446 jtag_add_scan(in_num_fields, in_fields, state);
448 for (int i = 0; i < in_num_fields; i++)
450 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL))
452 /* this is synchronous for a minidriver */
453 jtag_add_callback4(jtag_check_value_mask_callback, (jtag_callback_data_t)in_fields[i].in_value,
454 (jtag_callback_data_t)in_fields[i].check_value,
455 (jtag_callback_data_t)in_fields[i].check_mask,
456 (jtag_callback_data_t)in_fields[i].num_bits);
458 if (in_fields[i].allocated)
460 free(in_fields[i].in_value);
462 if (in_fields[i].modified)
464 in_fields[i].in_value = NULL;
469 void jtag_add_dr_scan_check(int in_num_fields, struct scan_field *in_fields, tap_state_t state)
473 jtag_add_scan_check(jtag_add_dr_scan, in_num_fields, in_fields, state);
476 jtag_add_dr_scan(in_num_fields, in_fields, state);
481 void jtag_add_dr_scan(int in_num_fields, const struct scan_field *in_fields,
484 assert(state != TAP_RESET);
489 retval = interface_jtag_add_dr_scan(in_num_fields, in_fields, state);
490 jtag_set_error(retval);
493 void jtag_add_plain_dr_scan(int in_num_fields, const struct scan_field *in_fields,
496 assert(state != TAP_RESET);
501 retval = interface_jtag_add_plain_dr_scan(in_num_fields, in_fields, state);
502 jtag_set_error(retval);
505 void jtag_add_dr_out(struct jtag_tap* tap,
506 int num_fields, const int* num_bits, const uint32_t* value,
507 tap_state_t end_state)
509 assert(end_state != TAP_RESET);
510 assert(end_state != TAP_INVALID);
512 cmd_queue_cur_state = end_state;
514 interface_jtag_add_dr_out(tap,
515 num_fields, num_bits, value,
519 void jtag_add_tlr(void)
521 jtag_prelude(TAP_RESET);
522 jtag_set_error(interface_jtag_add_tlr());
524 /* NOTE: order here matches TRST path in jtag_add_reset() */
525 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
526 jtag_notify_event(JTAG_TRST_ASSERTED);
529 void jtag_add_pathmove(int num_states, const tap_state_t *path)
531 tap_state_t cur_state = cmd_queue_cur_state;
533 /* the last state has to be a stable state */
534 if (!tap_is_state_stable(path[num_states - 1]))
536 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
537 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
541 for (int i = 0; i < num_states; i++)
543 if (path[i] == TAP_RESET)
545 LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
546 jtag_set_error(ERROR_JTAG_STATE_INVALID);
550 if (tap_state_transition(cur_state, true) != path[i]
551 && tap_state_transition(cur_state, false) != path[i])
553 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
554 tap_state_name(cur_state), tap_state_name(path[i]));
555 jtag_set_error(ERROR_JTAG_TRANSITION_INVALID);
563 jtag_set_error(interface_jtag_add_pathmove(num_states, path));
564 cmd_queue_cur_state = path[num_states - 1];
567 int jtag_add_statemove(tap_state_t goal_state)
569 tap_state_t cur_state = cmd_queue_cur_state;
571 LOG_DEBUG("cur_state=%s goal_state=%s",
572 tap_state_name(cur_state),
573 tap_state_name(goal_state));
576 /* If goal is RESET, be paranoid and force that that transition
577 * (e.g. five TCK cycles, TMS high). Else trust "cur_state".
579 if (goal_state == TAP_RESET)
581 else if (goal_state == cur_state)
582 /* nothing to do */ ;
584 else if (tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state))
586 unsigned tms_bits = tap_get_tms_path(cur_state, goal_state);
587 unsigned tms_count = tap_get_tms_path_len(cur_state, goal_state);
588 tap_state_t moves[8];
589 assert(tms_count < DIM(moves));
591 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1)
593 bool bit = tms_bits & 1;
595 cur_state = tap_state_transition(cur_state, bit);
596 moves[i] = cur_state;
599 jtag_add_pathmove(tms_count, moves);
601 else if (tap_state_transition(cur_state, true) == goal_state
602 || tap_state_transition(cur_state, false) == goal_state)
604 jtag_add_pathmove(1, &goal_state);
613 void jtag_add_runtest(int num_cycles, tap_state_t state)
616 jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
620 void jtag_add_clocks(int num_cycles)
622 if (!tap_is_state_stable(cmd_queue_cur_state))
624 LOG_ERROR("jtag_add_clocks() called with TAP in unstable state \"%s\"",
625 tap_state_name(cmd_queue_cur_state));
626 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
633 jtag_set_error(interface_jtag_add_clocks(num_cycles));
637 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
639 int trst_with_tlr = 0;
643 /* Without SRST, we must use target-specific JTAG operations
644 * on each target; callers should not be requesting SRST when
645 * that signal doesn't exist.
647 * RESET_SRST_PULLS_TRST is a board or chip level quirk, which
648 * can kick in even if the JTAG adapter can't drive TRST.
651 if (!(jtag_reset_config & RESET_HAS_SRST)) {
652 LOG_ERROR("BUG: can't assert SRST");
653 jtag_set_error(ERROR_FAIL);
656 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) != 0
657 && !req_tlr_or_trst) {
658 LOG_ERROR("BUG: can't assert only SRST");
659 jtag_set_error(ERROR_FAIL);
665 /* JTAG reset (entry to TAP_RESET state) can always be achieved
666 * using TCK and TMS; that may go through a TAP_{IR,DR}UPDATE
667 * state first. TRST accelerates it, and bypasses those states.
669 * RESET_TRST_PULLS_SRST is a board or chip level quirk, which
670 * can kick in even if the JTAG adapter can't drive SRST.
672 if (req_tlr_or_trst) {
673 if (!(jtag_reset_config & RESET_HAS_TRST))
675 else if ((jtag_reset_config & RESET_TRST_PULLS_SRST) != 0
682 /* Maybe change TRST and/or SRST signal state */
683 if (jtag_srst != new_srst || jtag_trst != new_trst) {
686 retval = interface_jtag_add_reset(new_trst, new_srst);
687 if (retval != ERROR_OK)
688 jtag_set_error(retval);
690 retval = jtag_execute_queue();
692 if (retval != ERROR_OK) {
693 LOG_ERROR("TRST/SRST error %d", retval);
698 /* SRST resets everything hooked up to that signal */
699 if (jtag_srst != new_srst) {
700 jtag_srst = new_srst;
703 LOG_DEBUG("SRST line asserted");
704 if (jtag_nsrst_assert_width)
705 jtag_add_sleep(jtag_nsrst_assert_width * 1000);
708 LOG_DEBUG("SRST line released");
709 if (jtag_nsrst_delay)
710 jtag_add_sleep(jtag_nsrst_delay * 1000);
714 /* Maybe enter the JTAG TAP_RESET state ...
715 * - using only TMS, TCK, and the JTAG state machine
716 * - or else more directly, using TRST
718 * TAP_RESET should be invisible to non-debug parts of the system.
721 LOG_DEBUG("JTAG reset with TLR instead of TRST");
722 jtag_set_end_state(TAP_RESET);
725 } else if (jtag_trst != new_trst) {
726 jtag_trst = new_trst;
728 LOG_DEBUG("TRST line asserted");
729 tap_set_state(TAP_RESET);
730 if (jtag_ntrst_assert_width)
731 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
733 LOG_DEBUG("TRST line released");
734 if (jtag_ntrst_delay)
735 jtag_add_sleep(jtag_ntrst_delay * 1000);
737 /* We just asserted nTRST, so we're now in TAP_RESET.
738 * Inform possible listeners about this, now that
739 * JTAG instructions and data can be shifted. This
740 * sequence must match jtag_add_tlr().
742 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
743 jtag_notify_event(JTAG_TRST_ASSERTED);
748 tap_state_t jtag_set_end_state(tap_state_t state)
750 if ((state == TAP_DRSHIFT)||(state == TAP_IRSHIFT))
752 LOG_ERROR("BUG: TAP_DRSHIFT/IRSHIFT can't be end state. Calling code should use a larger scan field");
755 if (state != TAP_INVALID)
756 cmd_queue_end_state = state;
757 return cmd_queue_end_state;
760 tap_state_t jtag_get_end_state(void)
762 return cmd_queue_end_state;
765 void jtag_add_sleep(uint32_t us)
767 /// @todo Here, keep_alive() appears to be a layering violation!!!
769 jtag_set_error(interface_jtag_add_sleep(us));
772 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
773 uint8_t *in_check_mask, int num_bits)
775 int retval = ERROR_OK;
777 int compare_failed = 0;
780 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
782 compare_failed = buf_cmp(captured, in_check_value, num_bits);
784 if (compare_failed) {
785 char *captured_str, *in_check_value_str;
786 int bits = (num_bits > DEBUG_JTAG_IOZ)
790 /* NOTE: we've lost diagnostic context here -- 'which tap' */
792 captured_str = buf_to_str(captured, bits, 16);
793 in_check_value_str = buf_to_str(in_check_value, bits, 16);
795 LOG_WARNING("Bad value '%s' captured during DR or IR scan:",
797 LOG_WARNING(" check_value: 0x%s", in_check_value_str);
800 free(in_check_value_str);
803 char *in_check_mask_str;
805 in_check_mask_str = buf_to_str(in_check_mask, bits, 16);
806 LOG_WARNING(" check_mask: 0x%s", in_check_mask_str);
807 free(in_check_mask_str);
810 retval = ERROR_JTAG_QUEUE_FAILED;
815 void jtag_check_value_mask(struct scan_field *field, uint8_t *value, uint8_t *mask)
817 assert(field->in_value != NULL);
821 /* no checking to do */
825 jtag_execute_queue_noclear();
827 int retval = jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
828 jtag_set_error(retval);
833 int default_interface_jtag_execute_queue(void)
837 LOG_ERROR("No JTAG interface configured yet. "
838 "Issue 'init' command in startup scripts "
839 "before communicating with targets.");
843 return jtag->execute_queue();
846 void jtag_execute_queue_noclear(void)
848 jtag_flush_queue_count++;
849 jtag_set_error(interface_jtag_execute_queue());
852 int jtag_get_flush_queue_count(void)
854 return jtag_flush_queue_count;
857 int jtag_execute_queue(void)
859 jtag_execute_queue_noclear();
860 return jtag_error_clear();
863 static int jtag_reset_callback(enum jtag_event event, void *priv)
865 struct jtag_tap *tap = priv;
867 if (event == JTAG_TRST_ASSERTED)
869 tap->enabled = !tap->disabled_after_reset;
871 /* current instruction is either BYPASS or IDCODE */
872 buf_set_ones(tap->cur_instr, tap->ir_length);
879 void jtag_sleep(uint32_t us)
881 alive_sleep(us/1000);
884 /* Maximum number of enabled JTAG devices we expect in the scan chain,
885 * plus one (to detect garbage at the end). Devices that don't support
886 * IDCODE take up fewer bits, possibly allowing a few more devices.
888 #define JTAG_MAX_CHAIN_SIZE 20
890 #define EXTRACT_MFG(X) (((X) & 0xffe) >> 1)
891 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
892 #define EXTRACT_VER(X) (((X) & 0xf0000000) >> 28)
894 /* A reserved manufacturer ID is used in END_OF_CHAIN_FLAG, so we
895 * know that no valid TAP will have it as an IDCODE value.
897 #define END_OF_CHAIN_FLAG 0x000000ff
899 /* a larger IR length than we ever expect to autoprobe */
900 #define JTAG_IRLEN_MAX 60
902 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
904 struct scan_field field = {
906 .num_bits = num_idcode * 32,
907 .out_value = idcode_buffer,
908 .in_value = idcode_buffer,
911 // initialize to the end of chain ID value
912 for (unsigned i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
913 buf_set_u32(idcode_buffer, i * 32, 32, END_OF_CHAIN_FLAG);
915 jtag_add_plain_dr_scan(1, &field, TAP_DRPAUSE);
917 return jtag_execute_queue();
920 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
922 uint8_t zero_check = 0x0;
923 uint8_t one_check = 0xff;
925 for (unsigned i = 0; i < count * 4; i++)
927 zero_check |= idcodes[i];
928 one_check &= idcodes[i];
931 /* if there wasn't a single non-zero bit or if all bits were one,
932 * the scan is not valid. We wrote a mix of both values; either
934 * - There's a hardware issue (almost certainly):
935 * + all-zeroes can mean a target stuck in JTAG reset
936 * + all-ones tends to mean no target
937 * - The scan chain is WAY longer than we can handle, *AND* either
938 * + there are several hundreds of TAPs in bypass, or
939 * + at least a few dozen TAPs all have an all-ones IDCODE
941 if (zero_check == 0x00 || one_check == 0xff)
943 LOG_ERROR("JTAG scan chain interrogation failed: all %s",
944 (zero_check == 0x00) ? "zeroes" : "ones");
945 LOG_ERROR("Check JTAG interface, timings, target power, etc.");
951 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
952 const char *name, uint32_t idcode)
954 log_printf_lf(level, __FILE__, __LINE__, __FUNCTION__,
955 "JTAG tap: %s %16.16s: 0x%08x "
956 "(mfg: 0x%3.3x, part: 0x%4.4x, ver: 0x%1.1x)",
958 (unsigned int)idcode,
959 (unsigned int)EXTRACT_MFG(idcode),
960 (unsigned int)EXTRACT_PART(idcode),
961 (unsigned int)EXTRACT_VER(idcode));
964 static bool jtag_idcode_is_final(uint32_t idcode)
967 * Some devices, such as AVR8, will output all 1's instead
968 * of TDI input value at end of chain. Allow those values
969 * instead of failing.
971 return idcode == END_OF_CHAIN_FLAG || idcode == 0xFFFFFFFF;
975 * This helper checks that remaining bits in the examined chain data are
976 * all as expected, but a single JTAG device requires only 64 bits to be
977 * read back correctly. This can help identify and diagnose problems
978 * with the JTAG chain earlier, gives more helpful/explicit error messages.
979 * Returns TRUE iff garbage was found.
981 static bool jtag_examine_chain_end(uint8_t *idcodes, unsigned count, unsigned max)
983 bool triggered = false;
984 for (; count < max - 31; count += 32)
986 uint32_t idcode = buf_get_u32(idcodes, count, 32);
988 /* do not trigger the warning if the data looks good */
989 if (jtag_idcode_is_final(idcode))
991 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
992 count, (unsigned int)idcode);
998 static bool jtag_examine_chain_match_tap(const struct jtag_tap *tap)
1000 /* ignore expected BYPASS codes; warn otherwise */
1001 if (0 == tap->expected_ids_cnt && !tap->idcode)
1004 /* Loop over the expected identification codes and test for a match */
1005 unsigned ii, limit = tap->expected_ids_cnt;
1007 for (ii = 0; ii < limit; ii++)
1009 if (tap->idcode == tap->expected_ids[ii])
1012 /* treat "-expected-id 0" as a "don't-warn" wildcard */
1013 if (0 == tap->expected_ids[ii])
1017 /* If none of the expected ids matched, warn */
1018 jtag_examine_chain_display(LOG_LVL_WARNING, "UNEXPECTED",
1019 tap->dotted_name, tap->idcode);
1020 for (ii = 0; ii < limit; ii++)
1024 snprintf(msg, sizeof(msg), "expected %u of %u", ii + 1, limit);
1025 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
1026 tap->dotted_name, tap->expected_ids[ii]);
1031 /* Try to examine chain layout according to IEEE 1149.1 §12
1032 * This is called a "blind interrogation" of the scan chain.
1034 static int jtag_examine_chain(void)
1036 uint8_t idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
1040 bool autoprobe = false;
1042 /* DR scan to collect BYPASS or IDCODE register contents.
1043 * Then make sure the scan data has both ones and zeroes.
1045 LOG_DEBUG("DR scan interrogation for IDCODE/BYPASS");
1046 retval = jtag_examine_chain_execute(idcode_buffer, JTAG_MAX_CHAIN_SIZE);
1047 if (retval != ERROR_OK)
1049 if (!jtag_examine_chain_check(idcode_buffer, JTAG_MAX_CHAIN_SIZE))
1050 return ERROR_JTAG_INIT_FAILED;
1052 /* point at the 1st tap */
1053 struct jtag_tap *tap = jtag_tap_next_enabled(NULL);
1059 tap && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;
1060 tap = jtag_tap_next_enabled(tap))
1062 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1064 if ((idcode & 1) == 0)
1066 /* Zero for LSB indicates a device in bypass */
1067 LOG_WARNING("TAP %s does not have IDCODE",
1070 tap->hasidcode = false;
1076 /* Friendly devices support IDCODE */
1077 tap->hasidcode = true;
1078 jtag_examine_chain_display(LOG_LVL_INFO,
1080 tap->dotted_name, idcode);
1084 tap->idcode = idcode;
1086 /* ensure the TAP ID matches what was expected */
1087 if (!jtag_examine_chain_match_tap(tap))
1088 retval = ERROR_JTAG_INIT_SOFT_FAIL;
1091 /* Fail if too many TAPs were enabled for us to verify them all. */
1093 LOG_ERROR("Too many TAPs enabled; '%s' ignored.",
1095 return ERROR_JTAG_INIT_FAILED;
1098 /* if autoprobing, the tap list is still empty ... populate it! */
1099 while (autoprobe && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31) {
1103 /* Is there another TAP? */
1104 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1105 if (jtag_idcode_is_final(idcode))
1108 /* Default everything in this TAP except IR length.
1110 * REVISIT create a jtag_alloc(chip, tap) routine, and
1111 * share it with jim_newtap_cmd().
1113 tap = calloc(1, sizeof *tap);
1117 sprintf(buf, "auto%d", tapcount++);
1118 tap->chip = strdup(buf);
1119 tap->tapname = strdup("tap");
1121 sprintf(buf, "%s.%s", tap->chip, tap->tapname);
1122 tap->dotted_name = strdup(buf);
1124 /* tap->ir_length == 0 ... signifying irlen autoprobe */
1125 tap->ir_capture_mask = 0x03;
1126 tap->ir_capture_value = 0x01;
1128 tap->enabled = true;
1130 if ((idcode & 1) == 0) {
1132 tap->hasidcode = false;
1135 tap->hasidcode = true;
1136 tap->idcode = idcode;
1138 tap->expected_ids_cnt = 1;
1139 tap->expected_ids = malloc(sizeof(uint32_t));
1140 tap->expected_ids[0] = idcode;
1143 LOG_WARNING("AUTO %s - use \"jtag newtap "
1144 "%s %s -expected-id 0x%8.8" PRIx32 " ...\"",
1145 tap->dotted_name, tap->chip, tap->tapname,
1151 /* After those IDCODE or BYPASS register values should be
1152 * only the data we fed into the scan chain.
1154 if (jtag_examine_chain_end(idcode_buffer, bit_count,
1155 8 * sizeof(idcode_buffer))) {
1156 LOG_ERROR("double-check your JTAG setup (interface, "
1157 "speed, missing TAPs, ...)");
1158 return ERROR_JTAG_INIT_FAILED;
1161 /* Return success or, for backwards compatibility if only
1162 * some IDCODE values mismatched, a soft/continuable fault.
1168 * Validate the date loaded by entry to the Capture-IR state, to help
1169 * find errors related to scan chain configuration (wrong IR lengths)
1172 * Entry state can be anything. On non-error exit, all TAPs are in
1173 * bypass mode. On error exits, the scan chain is reset.
1175 static int jtag_validate_ircapture(void)
1177 struct jtag_tap *tap;
1178 int total_ir_length = 0;
1179 uint8_t *ir_test = NULL;
1180 struct scan_field field;
1185 /* when autoprobing, accomodate huge IR lengths */
1186 for (tap = NULL, total_ir_length = 0;
1187 (tap = jtag_tap_next_enabled(tap)) != NULL;
1188 total_ir_length += tap->ir_length) {
1189 if (tap->ir_length == 0)
1190 total_ir_length += JTAG_IRLEN_MAX;
1193 /* increase length to add 2 bit sentinel after scan */
1194 total_ir_length += 2;
1196 ir_test = malloc(CEIL(total_ir_length, 8));
1197 if (ir_test == NULL)
1200 /* after this scan, all TAPs will capture BYPASS instructions */
1201 buf_set_ones(ir_test, total_ir_length);
1204 field.num_bits = total_ir_length;
1205 field.out_value = ir_test;
1206 field.in_value = ir_test;
1208 jtag_add_plain_ir_scan(1, &field, TAP_IDLE);
1210 LOG_DEBUG("IR capture validation scan");
1211 retval = jtag_execute_queue();
1212 if (retval != ERROR_OK)
1219 tap = jtag_tap_next_enabled(tap);
1224 /* If we're autoprobing, guess IR lengths. They must be at
1225 * least two bits. Guessing will fail if (a) any TAP does
1226 * not conform to the JTAG spec; or (b) when the upper bits
1227 * captured from some conforming TAP are nonzero.
1229 * REVISIT alternative approach: escape to some tcl code
1230 * which could provide more knowledge, based on IDCODE; and
1231 * only guess when that has no success.
1233 if (tap->ir_length == 0) {
1235 while ((val = buf_get_u32(ir_test, chain_pos,
1236 tap->ir_length + 1)) == 1) {
1239 LOG_WARNING("AUTO %s - use \"... -irlen %d\"",
1240 jtag_tap_name(tap), tap->ir_length);
1243 /* Validate the two LSBs, which must be 01 per JTAG spec.
1245 * Or ... more bits could be provided by TAP declaration.
1246 * Plus, some taps (notably in i.MX series chips) violate
1247 * this part of the JTAG spec, so their capture mask/value
1248 * attributes might disable this test.
1250 val = buf_get_u32(ir_test, chain_pos, tap->ir_length);
1251 if ((val & tap->ir_capture_mask) != tap->ir_capture_value) {
1252 LOG_ERROR("%s: IR capture error; saw 0x%0*x not 0x%0*x",
1254 (tap->ir_length + 7) / tap->ir_length,
1256 (tap->ir_length + 7) / tap->ir_length,
1257 (unsigned) tap->ir_capture_value);
1259 retval = ERROR_JTAG_INIT_FAILED;
1262 LOG_DEBUG("%s: IR capture 0x%0*x", jtag_tap_name(tap),
1263 (tap->ir_length + 7) / tap->ir_length, val);
1264 chain_pos += tap->ir_length;
1267 /* verify the '11' sentinel we wrote is returned at the end */
1268 val = buf_get_u32(ir_test, chain_pos, 2);
1271 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1273 LOG_ERROR("IR capture error at bit %d, saw 0x%s not 0x...3",
1276 retval = ERROR_JTAG_INIT_FAILED;
1281 if (retval != ERROR_OK) {
1283 jtag_execute_queue();
1289 void jtag_tap_init(struct jtag_tap *tap)
1291 unsigned ir_len_bits;
1292 unsigned ir_len_bytes;
1294 /* if we're autoprobing, cope with potentially huge ir_length */
1295 ir_len_bits = tap->ir_length ? : JTAG_IRLEN_MAX;
1296 ir_len_bytes = CEIL(ir_len_bits, 8);
1298 tap->expected = calloc(1, ir_len_bytes);
1299 tap->expected_mask = calloc(1, ir_len_bytes);
1300 tap->cur_instr = malloc(ir_len_bytes);
1302 /// @todo cope better with ir_length bigger than 32 bits
1303 if (ir_len_bits > 32)
1306 buf_set_u32(tap->expected, 0, ir_len_bits, tap->ir_capture_value);
1307 buf_set_u32(tap->expected_mask, 0, ir_len_bits, tap->ir_capture_mask);
1309 // TAP will be in bypass mode after jtag_validate_ircapture()
1311 buf_set_ones(tap->cur_instr, tap->ir_length);
1313 // register the reset callback for the TAP
1314 jtag_register_event_callback(&jtag_reset_callback, tap);
1316 LOG_DEBUG("Created Tap: %s @ abs position %d, "
1317 "irlen %d, capture: 0x%x mask: 0x%x", tap->dotted_name,
1318 tap->abs_chain_position, tap->ir_length,
1319 (unsigned) tap->ir_capture_value,
1320 (unsigned) tap->ir_capture_mask);
1324 void jtag_tap_free(struct jtag_tap *tap)
1326 jtag_unregister_event_callback(&jtag_reset_callback, tap);
1328 /// @todo is anything missing? no memory leaks please
1329 free((void *)tap->expected);
1330 free((void *)tap->expected_ids);
1331 free((void *)tap->chip);
1332 free((void *)tap->tapname);
1333 free((void *)tap->dotted_name);
1337 int jtag_interface_init(struct command_context_s *cmd_ctx)
1342 if (!jtag_interface)
1344 /* nothing was previously specified by "interface" command */
1345 LOG_ERROR("JTAG interface has to be specified, see \"interface\" command");
1346 return ERROR_JTAG_INVALID_INTERFACE;
1349 jtag = jtag_interface;
1350 if (jtag_interface->init() != ERROR_OK)
1353 return ERROR_JTAG_INIT_FAILED;
1356 int requested_khz = jtag_get_speed_khz();
1357 int actual_khz = requested_khz;
1358 int retval = jtag_get_speed_readable(&actual_khz);
1359 if (ERROR_OK != retval)
1360 LOG_INFO("interface specific clock speed value %d", jtag_get_speed());
1361 else if (actual_khz)
1363 if ((CLOCK_MODE_RCLK == clock_mode)
1364 || ((CLOCK_MODE_KHZ == clock_mode) && !requested_khz))
1366 LOG_INFO("RCLK (adaptive clock speed) not supported - fallback to %d kHz"
1370 LOG_INFO("clock speed %d kHz", actual_khz);
1373 LOG_INFO("RCLK (adaptive clock speed)");
1378 int jtag_init_inner(struct command_context_s *cmd_ctx)
1380 struct jtag_tap *tap;
1382 bool issue_setup = true;
1384 LOG_DEBUG("Init JTAG chain");
1386 tap = jtag_tap_next_enabled(NULL);
1388 /* Once JTAG itself is properly set up, and the scan chain
1389 * isn't absurdly large, IDCODE autoprobe should work fine.
1391 * But ... IRLEN autoprobe can fail even on systems which
1392 * are fully conformant to JTAG. Also, JTAG setup can be
1393 * quite finicky on some systems.
1395 * REVISIT: if TAP autoprobe works OK, then in many cases
1396 * we could escape to tcl code and set up targets based on
1397 * the TAP's IDCODE values.
1399 LOG_WARNING("There are no enabled taps. "
1400 "AUTO PROBING MIGHT NOT WORK!!");
1402 /* REVISIT default clock will often be too fast ... */
1406 if ((retval = jtag_execute_queue()) != ERROR_OK)
1409 /* Examine DR values first. This discovers problems which will
1410 * prevent communication ... hardware issues like TDO stuck, or
1411 * configuring the wrong number of (enabled) TAPs.
1413 retval = jtag_examine_chain();
1416 /* complete success */
1418 case ERROR_JTAG_INIT_SOFT_FAIL:
1419 /* For backward compatibility reasons, try coping with
1420 * configuration errors involving only ID mismatches.
1421 * We might be able to talk to the devices.
1423 LOG_ERROR("Trying to use configured scan chain anyway...");
1424 issue_setup = false;
1427 /* some hard error; already issued diagnostics */
1431 /* Now look at IR values. Problems here will prevent real
1432 * communication. They mostly mean that the IR length is
1433 * wrong ... or that the IR capture value is wrong. (The
1434 * latter is uncommon, but easily worked around: provide
1435 * ircapture/irmask values during TAP setup.)
1437 retval = jtag_validate_ircapture();
1438 if (retval != ERROR_OK)
1442 jtag_notify_event(JTAG_TAP_EVENT_SETUP);
1444 LOG_WARNING("Bypassing JTAG setup events due to errors");
1450 int jtag_interface_quit(void)
1452 if (!jtag || !jtag->quit)
1455 // close the JTAG interface
1456 int result = jtag->quit();
1457 if (ERROR_OK != result)
1458 LOG_ERROR("failed: %d", result);
1464 int jtag_init_reset(struct command_context_s *cmd_ctx)
1468 if ((retval = jtag_interface_init(cmd_ctx)) != ERROR_OK)
1471 LOG_DEBUG("Initializing with hard TRST+SRST reset");
1474 * This procedure is used by default when OpenOCD triggers a reset.
1475 * It's now done through an overridable Tcl "init_reset" wrapper.
1477 * This started out as a more powerful "get JTAG working" reset than
1478 * jtag_init_inner(), applying TRST because some chips won't activate
1479 * JTAG without a TRST cycle (presumed to be async, though some of
1480 * those chips synchronize JTAG activation using TCK).
1482 * But some chips only activate JTAG as part of an SRST cycle; SRST
1483 * got mixed in. So it became a hard reset routine, which got used
1484 * in more places, and which coped with JTAG reset being forced as
1485 * part of SRST (srst_pulls_trst).
1487 * And even more corner cases started to surface: TRST and/or SRST
1488 * assertion timings matter; some chips need other JTAG operations;
1489 * TRST/SRST sequences can need to be different from these, etc.
1491 * Systems should override that wrapper to support system-specific
1492 * requirements that this not-fully-generic code doesn't handle.
1494 * REVISIT once Tcl code can read the reset_config modes, this won't
1495 * need to be a C routine at all...
1497 jtag_add_reset(1, 0); /* TAP_RESET, using TMS+TCK or TRST */
1498 if (jtag_reset_config & RESET_HAS_SRST)
1500 jtag_add_reset(1, 1);
1501 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) == 0)
1502 jtag_add_reset(0, 1);
1504 jtag_add_reset(0, 0);
1505 if ((retval = jtag_execute_queue()) != ERROR_OK)
1508 /* Check that we can communication on the JTAG chain + eventually we want to
1509 * be able to perform enumeration only after OpenOCD has started
1510 * telnet and GDB server
1512 * That would allow users to more easily perform any magic they need to before
1515 return jtag_init_inner(cmd_ctx);
1518 int jtag_init(struct command_context_s *cmd_ctx)
1522 if ((retval = jtag_interface_init(cmd_ctx)) != ERROR_OK)
1525 /* guard against oddball hardware: force resets to be inactive */
1526 jtag_add_reset(0, 0);
1527 if ((retval = jtag_execute_queue()) != ERROR_OK)
1530 if (Jim_Eval_Named(interp, "jtag_init", __FILE__, __LINE__) != JIM_OK)
1536 unsigned jtag_get_speed_khz(void)
1541 static int jtag_khz_to_speed(unsigned khz, int* speed)
1543 LOG_DEBUG("convert khz to interface specific speed value");
1547 LOG_DEBUG("have interface set up");
1549 int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1550 if (ERROR_OK != retval)
1554 *speed = speed_div1;
1559 static int jtag_rclk_to_speed(unsigned fallback_speed_khz, int* speed)
1561 int retval = jtag_khz_to_speed(0, speed);
1562 if ((ERROR_OK != retval) && fallback_speed_khz)
1564 LOG_DEBUG("trying fallback speed...");
1565 retval = jtag_khz_to_speed(fallback_speed_khz, speed);
1570 static int jtag_set_speed(int speed)
1573 /* this command can be called during CONFIG,
1574 * in which case jtag isn't initialized */
1575 return jtag ? jtag->speed(speed) : ERROR_OK;
1578 int jtag_config_khz(unsigned khz)
1580 LOG_DEBUG("handle jtag khz");
1581 clock_mode = CLOCK_MODE_KHZ;
1583 int retval = jtag_khz_to_speed(khz, &speed);
1584 return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1587 int jtag_config_rclk(unsigned fallback_speed_khz)
1589 LOG_DEBUG("handle jtag rclk");
1590 clock_mode = CLOCK_MODE_RCLK;
1591 rclk_fallback_speed_khz = fallback_speed_khz;
1593 int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1594 return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1597 int jtag_get_speed(void)
1602 case CLOCK_MODE_SPEED:
1605 case CLOCK_MODE_KHZ:
1606 jtag_khz_to_speed(jtag_get_speed_khz(), &speed);
1608 case CLOCK_MODE_RCLK:
1609 jtag_rclk_to_speed(rclk_fallback_speed_khz, &speed);
1612 LOG_ERROR("BUG: unknown jtag clock mode");
1619 int jtag_get_speed_readable(int *khz)
1621 return jtag ? jtag->speed_div(jtag_get_speed(), khz) : ERROR_OK;
1624 void jtag_set_verify(bool enable)
1626 jtag_verify = enable;
1629 bool jtag_will_verify()
1634 void jtag_set_verify_capture_ir(bool enable)
1636 jtag_verify_capture_ir = enable;
1639 bool jtag_will_verify_capture_ir()
1641 return jtag_verify_capture_ir;
1644 int jtag_power_dropout(int *dropout)
1646 return jtag->power_dropout(dropout);
1649 int jtag_srst_asserted(int *srst_asserted)
1651 return jtag->srst_asserted(srst_asserted);
1654 enum reset_types jtag_get_reset_config(void)
1656 return jtag_reset_config;
1658 void jtag_set_reset_config(enum reset_types type)
1660 jtag_reset_config = type;
1663 int jtag_get_trst(void)
1667 int jtag_get_srst(void)
1672 void jtag_set_nsrst_delay(unsigned delay)
1674 jtag_nsrst_delay = delay;
1676 unsigned jtag_get_nsrst_delay(void)
1678 return jtag_nsrst_delay;
1680 void jtag_set_ntrst_delay(unsigned delay)
1682 jtag_ntrst_delay = delay;
1684 unsigned jtag_get_ntrst_delay(void)
1686 return jtag_ntrst_delay;
1690 void jtag_set_nsrst_assert_width(unsigned delay)
1692 jtag_nsrst_assert_width = delay;
1694 unsigned jtag_get_nsrst_assert_width(void)
1696 return jtag_nsrst_assert_width;
1698 void jtag_set_ntrst_assert_width(unsigned delay)
1700 jtag_ntrst_assert_width = delay;
1702 unsigned jtag_get_ntrst_assert_width(void)
1704 return jtag_ntrst_assert_width;