warning: fix silly -O3 warning
[openocd/cortex.git] / src / jtag / core.c
blobdd3a2a61646c0037567947e121f0d95b6f576452
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 ***************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
34 #include "jtag.h"
35 #include "interface.h"
36 #include "transport.h"
38 #ifdef HAVE_STRINGS_H
39 #include <strings.h>
40 #endif
42 /* SVF and XSVF are higher level JTAG command sets (for boundary scan) */
43 #include "svf/svf.h"
44 #include "xsvf/xsvf.h"
46 /// The number of JTAG queue flushes (for profiling and debugging purposes).
47 static int jtag_flush_queue_count;
49 // Sleep this # of ms after flushing the queue
50 static int jtag_flush_queue_sleep = 0;
52 static void jtag_add_scan_check(struct jtag_tap *active,
53 void (*jtag_add_scan)(struct jtag_tap *active, int in_num_fields, const struct scan_field *in_fields, tap_state_t state),
54 int in_num_fields, struct scan_field *in_fields, tap_state_t state);
56 /**
57 * The jtag_error variable is set when an error occurs while executing
58 * the queue. Application code may set this using jtag_set_error(),
59 * when an error occurs during processing that should be reported during
60 * jtag_execute_queue().
62 * The value is set and cleared, but never read by normal application code.
64 * This value is returned (and cleared) by jtag_execute_queue().
66 static int jtag_error = ERROR_OK;
68 static const char *jtag_event_strings[] =
70 [JTAG_TRST_ASSERTED] = "TAP reset",
71 [JTAG_TAP_EVENT_SETUP] = "TAP setup",
72 [JTAG_TAP_EVENT_ENABLE] = "TAP enabled",
73 [JTAG_TAP_EVENT_DISABLE] = "TAP disabled",
77 * JTAG adapters must initialize with TRST and SRST de-asserted
78 * (they're negative logic, so that means *high*). But some
79 * hardware doesn't necessarily work that way ... so set things
80 * up so that jtag_init() always forces that state.
82 static int jtag_trst = -1;
83 static int jtag_srst = -1;
85 /**
86 * List all TAPs that have been created.
88 static struct jtag_tap *__jtag_all_taps = NULL;
89 /**
90 * The number of TAPs in the __jtag_all_taps list, used to track the
91 * assigned chain position to new TAPs
93 static unsigned jtag_num_taps = 0;
95 static enum reset_types jtag_reset_config = RESET_NONE;
96 tap_state_t cmd_queue_cur_state = TAP_RESET;
98 static bool jtag_verify_capture_ir = true;
99 static int jtag_verify = 1;
101 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines deasserted (in ms) */
102 static int adapter_nsrst_delay = 0; /* default to no nSRST delay */
103 static int jtag_ntrst_delay = 0; /* default to no nTRST delay */
104 static int adapter_nsrst_assert_width = 0; /* width of assertion */
105 static int jtag_ntrst_assert_width = 0; /* width of assertion */
108 * Contains a single callback along with a pointer that will be passed
109 * when an event occurs.
111 struct jtag_event_callback {
112 /// a event callback
113 jtag_event_handler_t callback;
114 /// the private data to pass to the callback
115 void* priv;
116 /// the next callback
117 struct jtag_event_callback* next;
120 /* callbacks to inform high-level handlers about JTAG state changes */
121 static struct jtag_event_callback *jtag_event_callbacks;
123 /* speed in kHz*/
124 static int speed_khz = 0;
125 /* speed to fallback to when RCLK is requested but not supported */
126 static int rclk_fallback_speed_khz = 0;
127 static enum {CLOCK_MODE_SPEED, CLOCK_MODE_KHZ, CLOCK_MODE_RCLK} clock_mode;
128 static int jtag_speed = 0;
130 static struct jtag_interface *jtag = NULL;
132 /* configuration */
133 struct jtag_interface *jtag_interface = NULL;
135 void jtag_set_flush_queue_sleep(int ms)
137 jtag_flush_queue_sleep = ms;
140 void jtag_set_error(int error)
142 if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
143 return;
144 jtag_error = error;
147 int jtag_error_clear(void)
149 int temp = jtag_error;
150 jtag_error = ERROR_OK;
151 return temp;
154 /************/
156 static bool jtag_poll = 1;
158 bool is_jtag_poll_safe(void)
160 /* Polling can be disabled explicitly with set_enabled(false).
161 * It is also implicitly disabled while TRST is active and
162 * while SRST is gating the JTAG clock.
164 if (!jtag_poll || jtag_trst != 0)
165 return false;
166 return jtag_srst == 0 || (jtag_reset_config & RESET_SRST_NO_GATING);
169 bool jtag_poll_get_enabled(void)
171 return jtag_poll;
174 void jtag_poll_set_enabled(bool value)
176 jtag_poll = value;
179 /************/
181 struct jtag_tap *jtag_all_taps(void)
183 return __jtag_all_taps;
186 unsigned jtag_tap_count(void)
188 return jtag_num_taps;
191 unsigned jtag_tap_count_enabled(void)
193 struct jtag_tap *t = jtag_all_taps();
194 unsigned n = 0;
195 while (t)
197 if (t->enabled)
198 n++;
199 t = t->next_tap;
201 return n;
204 /// Append a new TAP to the chain of all taps.
205 void jtag_tap_add(struct jtag_tap *t)
207 t->abs_chain_position = jtag_num_taps++;
209 struct jtag_tap **tap = &__jtag_all_taps;
210 while (*tap != NULL)
211 tap = &(*tap)->next_tap;
212 *tap = t;
215 /* returns a pointer to the n-th device in the scan chain */
216 static inline struct jtag_tap *jtag_tap_by_position(unsigned n)
218 struct jtag_tap *t = jtag_all_taps();
220 while (t && n-- > 0)
221 t = t->next_tap;
223 return t;
226 struct jtag_tap *jtag_tap_by_string(const char *s)
228 /* try by name first */
229 struct jtag_tap *t = jtag_all_taps();
231 while (t)
233 if (0 == strcmp(t->dotted_name, s))
234 return t;
235 t = t->next_tap;
238 /* no tap found by name, so try to parse the name as a number */
239 unsigned n;
240 if (parse_uint(s, &n) != ERROR_OK)
241 return NULL;
243 /* FIXME remove this numeric fallback code late June 2010, along
244 * with all info in the User's Guide that TAPs have numeric IDs.
245 * Also update "scan_chain" output to not display the numbers.
247 t = jtag_tap_by_position(n);
248 if (t)
249 LOG_WARNING("Specify TAP '%s' by name, not number %u",
250 t->dotted_name, n);
252 return t;
255 struct jtag_tap* jtag_tap_next_enabled(struct jtag_tap* p)
257 p = p ? p->next_tap : jtag_all_taps();
258 while (p)
260 if (p->enabled)
261 return p;
262 p = p->next_tap;
264 return NULL;
267 const char *jtag_tap_name(const struct jtag_tap *tap)
269 return (tap == NULL) ? "(unknown)" : tap->dotted_name;
273 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
275 struct jtag_event_callback **callbacks_p = &jtag_event_callbacks;
277 if (callback == NULL)
279 return ERROR_INVALID_ARGUMENTS;
282 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 **callbacks_p;
300 struct jtag_event_callback **next;
302 if (callback == NULL)
304 return ERROR_INVALID_ARGUMENTS;
307 for (callbacks_p = &jtag_event_callbacks;
308 *callbacks_p != NULL;
309 callbacks_p = next)
311 next = &((*callbacks_p)->next);
313 if ((*callbacks_p)->priv != priv)
314 continue;
316 if ((*callbacks_p)->callback == callback)
318 free(*callbacks_p);
319 *callbacks_p = *next;
323 return ERROR_OK;
326 int jtag_call_event_callbacks(enum jtag_event event)
328 struct jtag_event_callback *callback = jtag_event_callbacks;
330 LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
332 while (callback)
334 struct jtag_event_callback *next;
336 /* callback may remove itself */
337 next = callback->next;
338 callback->callback(event, callback->priv);
339 callback = next;
342 return ERROR_OK;
345 static void jtag_checks(void)
347 assert(jtag_trst == 0);
350 static void jtag_prelude(tap_state_t state)
352 jtag_checks();
354 assert(state != TAP_INVALID);
356 cmd_queue_cur_state = state;
359 void jtag_alloc_in_value32(struct scan_field *field)
361 interface_jtag_alloc_in_value32(field);
364 void jtag_add_ir_scan_noverify(struct jtag_tap *active, const struct scan_field *in_fields,
365 tap_state_t state)
367 jtag_prelude(state);
369 int retval = interface_jtag_add_ir_scan(active, in_fields, state);
370 jtag_set_error(retval);
373 static void jtag_add_ir_scan_noverify_callback(struct jtag_tap *active, int dummy, const struct scan_field *in_fields,
374 tap_state_t state)
376 jtag_add_ir_scan_noverify(active, in_fields, state);
379 void jtag_add_ir_scan(struct jtag_tap *active, struct scan_field *in_fields, tap_state_t state)
381 assert(state != TAP_RESET);
383 if (jtag_verify && jtag_verify_capture_ir)
385 /* 8 x 32 bit id's is enough for all invocations */
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->check_value = active->expected;
391 in_fields->check_mask = active->expected_mask;
392 jtag_add_scan_check(active, jtag_add_ir_scan_noverify_callback, 1, in_fields, state);
393 } else
395 jtag_add_ir_scan_noverify(active, in_fields, state);
399 void jtag_add_plain_ir_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
400 tap_state_t state)
402 assert(out_bits != NULL);
403 assert(state != TAP_RESET);
405 jtag_prelude(state);
407 int retval = interface_jtag_add_plain_ir_scan(
408 num_bits, out_bits, in_bits, state);
409 jtag_set_error(retval);
412 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
413 uint8_t *in_check_mask, int num_bits);
415 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)
417 return jtag_check_value_inner((uint8_t *)data0, (uint8_t *)data1, (uint8_t *)data2, (int)data3);
420 static void jtag_add_scan_check(struct jtag_tap *active, void (*jtag_add_scan)(struct jtag_tap *active, int in_num_fields, const struct scan_field *in_fields, tap_state_t state),
421 int in_num_fields, struct scan_field *in_fields, tap_state_t state)
423 for (int i = 0; i < in_num_fields; i++)
425 struct scan_field *field = &in_fields[i];
426 field->allocated = 0;
427 field->modified = 0;
428 if (field->check_value || field->in_value)
429 continue;
430 interface_jtag_add_scan_check_alloc(field);
431 field->modified = 1;
434 jtag_add_scan(active, in_num_fields, in_fields, state);
436 for (int i = 0; i < in_num_fields; i++)
438 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL))
440 /* this is synchronous for a minidriver */
441 jtag_add_callback4(jtag_check_value_mask_callback, (jtag_callback_data_t)in_fields[i].in_value,
442 (jtag_callback_data_t)in_fields[i].check_value,
443 (jtag_callback_data_t)in_fields[i].check_mask,
444 (jtag_callback_data_t)in_fields[i].num_bits);
446 if (in_fields[i].allocated)
448 free(in_fields[i].in_value);
450 if (in_fields[i].modified)
452 in_fields[i].in_value = NULL;
457 void jtag_add_dr_scan_check(struct jtag_tap *active, int in_num_fields, struct scan_field *in_fields, tap_state_t state)
459 if (jtag_verify)
461 jtag_add_scan_check(active, jtag_add_dr_scan, in_num_fields, in_fields, state);
462 } else
464 jtag_add_dr_scan(active, in_num_fields, in_fields, state);
469 void jtag_add_dr_scan(struct jtag_tap *active, int in_num_fields, const struct scan_field *in_fields,
470 tap_state_t state)
472 assert(state != TAP_RESET);
474 jtag_prelude(state);
476 int retval;
477 retval = interface_jtag_add_dr_scan(active, in_num_fields, in_fields, state);
478 jtag_set_error(retval);
481 void jtag_add_plain_dr_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
482 tap_state_t state)
484 assert(out_bits != NULL);
485 assert(state != TAP_RESET);
487 jtag_prelude(state);
489 int retval;
490 retval = interface_jtag_add_plain_dr_scan(num_bits, out_bits, in_bits, state);
491 jtag_set_error(retval);
494 void jtag_add_tlr(void)
496 jtag_prelude(TAP_RESET);
497 jtag_set_error(interface_jtag_add_tlr());
499 /* NOTE: order here matches TRST path in jtag_add_reset() */
500 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
501 jtag_notify_event(JTAG_TRST_ASSERTED);
505 * If supported by the underlying adapter, this clocks a raw bit sequence
506 * onto TMS for switching betwen JTAG and SWD modes.
508 * DO NOT use this to bypass the integrity checks and logging provided
509 * by the jtag_add_pathmove() and jtag_add_statemove() calls.
511 * @param nbits How many bits to clock out.
512 * @param seq The bit sequence. The LSB is bit 0 of seq[0].
513 * @param state The JTAG tap state to record on completion. Use
514 * TAP_INVALID to represent being in in SWD mode.
516 * @todo Update naming conventions to stop assuming everything is JTAG.
518 int jtag_add_tms_seq(unsigned nbits, const uint8_t *seq, enum tap_state state)
520 int retval;
522 if (!(jtag->supported & DEBUG_CAP_TMS_SEQ))
523 return ERROR_JTAG_NOT_IMPLEMENTED;
525 jtag_checks();
526 cmd_queue_cur_state = state;
528 retval = interface_add_tms_seq(nbits, seq, state);
529 jtag_set_error(retval);
530 return retval;
533 void jtag_add_pathmove(int num_states, const tap_state_t *path)
535 tap_state_t cur_state = cmd_queue_cur_state;
537 /* the last state has to be a stable state */
538 if (!tap_is_state_stable(path[num_states - 1]))
540 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
541 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
542 return;
545 for (int i = 0; i < num_states; i++)
547 if (path[i] == TAP_RESET)
549 LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
550 jtag_set_error(ERROR_JTAG_STATE_INVALID);
551 return;
554 if (tap_state_transition(cur_state, true) != path[i]
555 && tap_state_transition(cur_state, false) != path[i])
557 LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
558 tap_state_name(cur_state), tap_state_name(path[i]));
559 jtag_set_error(ERROR_JTAG_TRANSITION_INVALID);
560 return;
562 cur_state = path[i];
565 jtag_checks();
567 jtag_set_error(interface_jtag_add_pathmove(num_states, path));
568 cmd_queue_cur_state = path[num_states - 1];
571 int jtag_add_statemove(tap_state_t goal_state)
573 tap_state_t cur_state = cmd_queue_cur_state;
575 if (goal_state != cur_state)
577 LOG_DEBUG("cur_state=%s goal_state=%s",
578 tap_state_name(cur_state),
579 tap_state_name(goal_state));
582 /* If goal is RESET, be paranoid and force that that transition
583 * (e.g. five TCK cycles, TMS high). Else trust "cur_state".
585 if (goal_state == TAP_RESET)
586 jtag_add_tlr();
587 else if (goal_state == cur_state)
588 /* nothing to do */ ;
590 else if (tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state))
592 unsigned tms_bits = tap_get_tms_path(cur_state, goal_state);
593 unsigned tms_count = tap_get_tms_path_len(cur_state, goal_state);
594 tap_state_t moves[8];
595 assert(tms_count < ARRAY_SIZE(moves));
597 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1)
599 bool bit = tms_bits & 1;
601 cur_state = tap_state_transition(cur_state, bit);
602 moves[i] = cur_state;
605 jtag_add_pathmove(tms_count, moves);
607 else if (tap_state_transition(cur_state, true) == goal_state
608 || tap_state_transition(cur_state, false) == goal_state)
610 jtag_add_pathmove(1, &goal_state);
613 else
614 return ERROR_FAIL;
616 return ERROR_OK;
619 void jtag_add_runtest(int num_cycles, tap_state_t state)
621 jtag_prelude(state);
622 jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
626 void jtag_add_clocks(int num_cycles)
628 if (!tap_is_state_stable(cmd_queue_cur_state))
630 LOG_ERROR("jtag_add_clocks() called with TAP in unstable state \"%s\"",
631 tap_state_name(cmd_queue_cur_state));
632 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
633 return;
636 if (num_cycles > 0)
638 jtag_checks();
639 jtag_set_error(interface_jtag_add_clocks(num_cycles));
643 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
645 int trst_with_tlr = 0;
646 int new_srst = 0;
647 int new_trst = 0;
649 /* Without SRST, we must use target-specific JTAG operations
650 * on each target; callers should not be requesting SRST when
651 * that signal doesn't exist.
653 * RESET_SRST_PULLS_TRST is a board or chip level quirk, which
654 * can kick in even if the JTAG adapter can't drive TRST.
656 if (req_srst) {
657 if (!(jtag_reset_config & RESET_HAS_SRST)) {
658 LOG_ERROR("BUG: can't assert SRST");
659 jtag_set_error(ERROR_FAIL);
660 return;
662 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) != 0
663 && !req_tlr_or_trst) {
664 LOG_ERROR("BUG: can't assert only SRST");
665 jtag_set_error(ERROR_FAIL);
666 return;
668 new_srst = 1;
671 /* JTAG reset (entry to TAP_RESET state) can always be achieved
672 * using TCK and TMS; that may go through a TAP_{IR,DR}UPDATE
673 * state first. TRST accelerates it, and bypasses those states.
675 * RESET_TRST_PULLS_SRST is a board or chip level quirk, which
676 * can kick in even if the JTAG adapter can't drive SRST.
678 if (req_tlr_or_trst) {
679 if (!(jtag_reset_config & RESET_HAS_TRST))
680 trst_with_tlr = 1;
681 else if ((jtag_reset_config & RESET_TRST_PULLS_SRST) != 0
682 && !req_srst)
683 trst_with_tlr = 1;
684 else
685 new_trst = 1;
688 /* Maybe change TRST and/or SRST signal state */
689 if (jtag_srst != new_srst || jtag_trst != new_trst) {
690 int retval;
692 retval = interface_jtag_add_reset(new_trst, new_srst);
693 if (retval != ERROR_OK)
694 jtag_set_error(retval);
695 else
696 retval = jtag_execute_queue();
698 if (retval != ERROR_OK) {
699 LOG_ERROR("TRST/SRST error %d", retval);
700 return;
704 /* SRST resets everything hooked up to that signal */
705 if (jtag_srst != new_srst) {
706 jtag_srst = new_srst;
707 if (jtag_srst)
709 LOG_DEBUG("SRST line asserted");
710 if (adapter_nsrst_assert_width)
711 jtag_add_sleep(adapter_nsrst_assert_width * 1000);
713 else {
714 LOG_DEBUG("SRST line released");
715 if (adapter_nsrst_delay)
716 jtag_add_sleep(adapter_nsrst_delay * 1000);
720 /* Maybe enter the JTAG TAP_RESET state ...
721 * - using only TMS, TCK, and the JTAG state machine
722 * - or else more directly, using TRST
724 * TAP_RESET should be invisible to non-debug parts of the system.
726 if (trst_with_tlr) {
727 LOG_DEBUG("JTAG reset with TLR instead of TRST");
728 jtag_add_tlr();
730 } else if (jtag_trst != new_trst) {
731 jtag_trst = new_trst;
732 if (jtag_trst) {
733 LOG_DEBUG("TRST line asserted");
734 tap_set_state(TAP_RESET);
735 if (jtag_ntrst_assert_width)
736 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
737 } else {
738 LOG_DEBUG("TRST line released");
739 if (jtag_ntrst_delay)
740 jtag_add_sleep(jtag_ntrst_delay * 1000);
742 /* We just asserted nTRST, so we're now in TAP_RESET.
743 * Inform possible listeners about this, now that
744 * JTAG instructions and data can be shifted. This
745 * sequence must match jtag_add_tlr().
747 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
748 jtag_notify_event(JTAG_TRST_ASSERTED);
753 void jtag_add_sleep(uint32_t us)
755 /// @todo Here, keep_alive() appears to be a layering violation!!!
756 keep_alive();
757 jtag_set_error(interface_jtag_add_sleep(us));
760 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
761 uint8_t *in_check_mask, int num_bits)
763 int retval = ERROR_OK;
764 int compare_failed;
766 if (in_check_mask)
767 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
768 else
769 compare_failed = buf_cmp(captured, in_check_value, num_bits);
771 if (compare_failed) {
772 char *captured_str, *in_check_value_str;
773 int bits = (num_bits > DEBUG_JTAG_IOZ)
774 ? DEBUG_JTAG_IOZ
775 : num_bits;
777 /* NOTE: we've lost diagnostic context here -- 'which tap' */
779 captured_str = buf_to_str(captured, bits, 16);
780 in_check_value_str = buf_to_str(in_check_value, bits, 16);
782 LOG_WARNING("Bad value '%s' captured during DR or IR scan:",
783 captured_str);
784 LOG_WARNING(" check_value: 0x%s", in_check_value_str);
786 free(captured_str);
787 free(in_check_value_str);
789 if (in_check_mask) {
790 char *in_check_mask_str;
792 in_check_mask_str = buf_to_str(in_check_mask, bits, 16);
793 LOG_WARNING(" check_mask: 0x%s", in_check_mask_str);
794 free(in_check_mask_str);
797 retval = ERROR_JTAG_QUEUE_FAILED;
799 return retval;
802 void jtag_check_value_mask(struct scan_field *field, uint8_t *value, uint8_t *mask)
804 assert(field->in_value != NULL);
806 if (value == NULL)
808 /* no checking to do */
809 return;
812 jtag_execute_queue_noclear();
814 int retval = jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
815 jtag_set_error(retval);
820 int default_interface_jtag_execute_queue(void)
822 if (NULL == jtag)
824 LOG_ERROR("No JTAG interface configured yet. "
825 "Issue 'init' command in startup scripts "
826 "before communicating with targets.");
827 return ERROR_FAIL;
830 return jtag->execute_queue();
833 void jtag_execute_queue_noclear(void)
835 jtag_flush_queue_count++;
836 jtag_set_error(interface_jtag_execute_queue());
838 if (jtag_flush_queue_sleep > 0)
840 /* For debug purposes it can be useful to test performance
841 * or behavior when delaying after flushing the queue,
842 * e.g. to simulate long roundtrip times.
844 usleep(jtag_flush_queue_sleep * 1000);
848 int jtag_get_flush_queue_count(void)
850 return jtag_flush_queue_count;
853 int jtag_execute_queue(void)
855 jtag_execute_queue_noclear();
856 return jtag_error_clear();
859 static int jtag_reset_callback(enum jtag_event event, void *priv)
861 struct jtag_tap *tap = priv;
863 if (event == JTAG_TRST_ASSERTED)
865 tap->enabled = !tap->disabled_after_reset;
867 /* current instruction is either BYPASS or IDCODE */
868 buf_set_ones(tap->cur_instr, tap->ir_length);
869 tap->bypass = 1;
872 return ERROR_OK;
875 void jtag_sleep(uint32_t us)
877 alive_sleep(us/1000);
880 /* Maximum number of enabled JTAG devices we expect in the scan chain,
881 * plus one (to detect garbage at the end). Devices that don't support
882 * IDCODE take up fewer bits, possibly allowing a few more devices.
884 #define JTAG_MAX_CHAIN_SIZE 20
886 #define EXTRACT_MFG(X) (((X) & 0xffe) >> 1)
887 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
888 #define EXTRACT_VER(X) (((X) & 0xf0000000) >> 28)
890 /* A reserved manufacturer ID is used in END_OF_CHAIN_FLAG, so we
891 * know that no valid TAP will have it as an IDCODE value.
893 #define END_OF_CHAIN_FLAG 0x000000ff
895 /* a larger IR length than we ever expect to autoprobe */
896 #define JTAG_IRLEN_MAX 60
898 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
900 struct scan_field field = {
901 .num_bits = num_idcode * 32,
902 .out_value = idcode_buffer,
903 .in_value = idcode_buffer,
906 // initialize to the end of chain ID value
907 for (unsigned i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
908 buf_set_u32(idcode_buffer, i * 32, 32, END_OF_CHAIN_FLAG);
910 jtag_add_plain_dr_scan(field.num_bits, field.out_value, field.in_value, TAP_DRPAUSE);
911 jtag_add_tlr();
912 return jtag_execute_queue();
915 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
917 uint8_t zero_check = 0x0;
918 uint8_t one_check = 0xff;
920 for (unsigned i = 0; i < count * 4; i++)
922 zero_check |= idcodes[i];
923 one_check &= idcodes[i];
926 /* if there wasn't a single non-zero bit or if all bits were one,
927 * the scan is not valid. We wrote a mix of both values; either
929 * - There's a hardware issue (almost certainly):
930 * + all-zeroes can mean a target stuck in JTAG reset
931 * + all-ones tends to mean no target
932 * - The scan chain is WAY longer than we can handle, *AND* either
933 * + there are several hundreds of TAPs in bypass, or
934 * + at least a few dozen TAPs all have an all-ones IDCODE
936 if (zero_check == 0x00 || one_check == 0xff)
938 LOG_ERROR("JTAG scan chain interrogation failed: all %s",
939 (zero_check == 0x00) ? "zeroes" : "ones");
940 LOG_ERROR("Check JTAG interface, timings, target power, etc.");
941 return false;
943 return true;
946 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
947 const char *name, uint32_t idcode)
949 log_printf_lf(level, __FILE__, __LINE__, __FUNCTION__,
950 "JTAG tap: %s %16.16s: 0x%08x "
951 "(mfg: 0x%3.3x, part: 0x%4.4x, ver: 0x%1.1x)",
952 name, msg,
953 (unsigned int)idcode,
954 (unsigned int)EXTRACT_MFG(idcode),
955 (unsigned int)EXTRACT_PART(idcode),
956 (unsigned int)EXTRACT_VER(idcode));
959 static bool jtag_idcode_is_final(uint32_t idcode)
962 * Some devices, such as AVR8, will output all 1's instead
963 * of TDI input value at end of chain. Allow those values
964 * instead of failing.
966 return idcode == END_OF_CHAIN_FLAG || idcode == 0xFFFFFFFF;
970 * This helper checks that remaining bits in the examined chain data are
971 * all as expected, but a single JTAG device requires only 64 bits to be
972 * read back correctly. This can help identify and diagnose problems
973 * with the JTAG chain earlier, gives more helpful/explicit error messages.
974 * Returns TRUE iff garbage was found.
976 static bool jtag_examine_chain_end(uint8_t *idcodes, unsigned count, unsigned max)
978 bool triggered = false;
979 for (; count < max - 31; count += 32)
981 uint32_t idcode = buf_get_u32(idcodes, count, 32);
983 /* do not trigger the warning if the data looks good */
984 if (jtag_idcode_is_final(idcode))
985 continue;
986 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
987 count, (unsigned int)idcode);
988 triggered = true;
990 return triggered;
993 static bool jtag_examine_chain_match_tap(const struct jtag_tap *tap)
995 uint32_t idcode = tap->idcode;
997 /* ignore expected BYPASS codes; warn otherwise */
998 if (0 == tap->expected_ids_cnt && !idcode)
999 return true;
1001 /* optionally ignore the JTAG version field */
1002 uint32_t mask = tap->ignore_version ? ~(0xff << 24) : ~0;
1004 idcode &= mask;
1006 /* Loop over the expected identification codes and test for a match */
1007 unsigned ii, limit = tap->expected_ids_cnt;
1009 for (ii = 0; ii < limit; ii++)
1011 uint32_t expected = tap->expected_ids[ii] & mask;
1013 if (idcode == expected)
1014 return true;
1016 /* treat "-expected-id 0" as a "don't-warn" wildcard */
1017 if (0 == tap->expected_ids[ii])
1018 return true;
1021 /* If none of the expected ids matched, warn */
1022 jtag_examine_chain_display(LOG_LVL_WARNING, "UNEXPECTED",
1023 tap->dotted_name, tap->idcode);
1024 for (ii = 0; ii < limit; ii++)
1026 char msg[32];
1028 snprintf(msg, sizeof(msg), "expected %u of %u", ii + 1, limit);
1029 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
1030 tap->dotted_name, tap->expected_ids[ii]);
1032 return false;
1035 /* Try to examine chain layout according to IEEE 1149.1 §12
1036 * This is called a "blind interrogation" of the scan chain.
1038 static int jtag_examine_chain(void)
1040 uint8_t idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
1041 unsigned bit_count;
1042 int retval;
1043 int tapcount = 0;
1044 bool autoprobe = false;
1046 /* DR scan to collect BYPASS or IDCODE register contents.
1047 * Then make sure the scan data has both ones and zeroes.
1049 LOG_DEBUG("DR scan interrogation for IDCODE/BYPASS");
1050 retval = jtag_examine_chain_execute(idcode_buffer, JTAG_MAX_CHAIN_SIZE);
1051 if (retval != ERROR_OK)
1052 return retval;
1053 if (!jtag_examine_chain_check(idcode_buffer, JTAG_MAX_CHAIN_SIZE))
1054 return ERROR_JTAG_INIT_FAILED;
1056 /* point at the 1st tap */
1057 struct jtag_tap *tap = jtag_tap_next_enabled(NULL);
1059 if (!tap)
1060 autoprobe = true;
1062 for (bit_count = 0;
1063 tap && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;
1064 tap = jtag_tap_next_enabled(tap))
1066 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1068 if ((idcode & 1) == 0)
1070 /* Zero for LSB indicates a device in bypass */
1071 LOG_INFO("TAP %s does not have IDCODE",
1072 tap->dotted_name);
1073 idcode = 0;
1074 tap->hasidcode = false;
1076 bit_count += 1;
1078 else
1080 /* Friendly devices support IDCODE */
1081 tap->hasidcode = true;
1082 jtag_examine_chain_display(LOG_LVL_INFO,
1083 "tap/device found",
1084 tap->dotted_name, idcode);
1086 bit_count += 32;
1088 tap->idcode = idcode;
1090 /* ensure the TAP ID matches what was expected */
1091 if (!jtag_examine_chain_match_tap(tap))
1092 retval = ERROR_JTAG_INIT_SOFT_FAIL;
1095 /* Fail if too many TAPs were enabled for us to verify them all. */
1096 if (tap) {
1097 LOG_ERROR("Too many TAPs enabled; '%s' ignored.",
1098 tap->dotted_name);
1099 return ERROR_JTAG_INIT_FAILED;
1102 /* if autoprobing, the tap list is still empty ... populate it! */
1103 while (autoprobe && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31) {
1104 uint32_t idcode;
1105 char buf[12];
1107 /* Is there another TAP? */
1108 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1109 if (jtag_idcode_is_final(idcode))
1110 break;
1112 /* Default everything in this TAP except IR length.
1114 * REVISIT create a jtag_alloc(chip, tap) routine, and
1115 * share it with jim_newtap_cmd().
1117 tap = calloc(1, sizeof *tap);
1118 if (!tap)
1119 return ERROR_FAIL;
1121 sprintf(buf, "auto%d", tapcount++);
1122 tap->chip = strdup(buf);
1123 tap->tapname = strdup("tap");
1125 sprintf(buf, "%s.%s", tap->chip, tap->tapname);
1126 tap->dotted_name = strdup(buf);
1128 /* tap->ir_length == 0 ... signifying irlen autoprobe */
1129 tap->ir_capture_mask = 0x03;
1130 tap->ir_capture_value = 0x01;
1132 tap->enabled = true;
1134 if ((idcode & 1) == 0) {
1135 bit_count += 1;
1136 tap->hasidcode = false;
1137 } else {
1138 bit_count += 32;
1139 tap->hasidcode = true;
1140 tap->idcode = idcode;
1142 tap->expected_ids_cnt = 1;
1143 tap->expected_ids = malloc(sizeof(uint32_t));
1144 tap->expected_ids[0] = idcode;
1147 LOG_WARNING("AUTO %s - use \"jtag newtap "
1148 "%s %s -expected-id 0x%8.8" PRIx32 " ...\"",
1149 tap->dotted_name, tap->chip, tap->tapname,
1150 tap->idcode);
1152 jtag_tap_init(tap);
1155 /* After those IDCODE or BYPASS register values should be
1156 * only the data we fed into the scan chain.
1158 if (jtag_examine_chain_end(idcode_buffer, bit_count,
1159 8 * sizeof(idcode_buffer))) {
1160 LOG_ERROR("double-check your JTAG setup (interface, "
1161 "speed, missing TAPs, ...)");
1162 return ERROR_JTAG_INIT_FAILED;
1165 /* Return success or, for backwards compatibility if only
1166 * some IDCODE values mismatched, a soft/continuable fault.
1168 return retval;
1172 * Validate the date loaded by entry to the Capture-IR state, to help
1173 * find errors related to scan chain configuration (wrong IR lengths)
1174 * or communication.
1176 * Entry state can be anything. On non-error exit, all TAPs are in
1177 * bypass mode. On error exits, the scan chain is reset.
1179 static int jtag_validate_ircapture(void)
1181 struct jtag_tap *tap;
1182 int total_ir_length = 0;
1183 uint8_t *ir_test = NULL;
1184 struct scan_field field;
1185 int val;
1186 int chain_pos = 0;
1187 int retval;
1189 /* when autoprobing, accomodate huge IR lengths */
1190 for (tap = NULL, total_ir_length = 0;
1191 (tap = jtag_tap_next_enabled(tap)) != NULL;
1192 total_ir_length += tap->ir_length) {
1193 if (tap->ir_length == 0)
1194 total_ir_length += JTAG_IRLEN_MAX;
1197 /* increase length to add 2 bit sentinel after scan */
1198 total_ir_length += 2;
1200 ir_test = malloc(DIV_ROUND_UP(total_ir_length, 8));
1201 if (ir_test == NULL)
1202 return ERROR_FAIL;
1204 /* after this scan, all TAPs will capture BYPASS instructions */
1205 buf_set_ones(ir_test, total_ir_length);
1207 field.num_bits = total_ir_length;
1208 field.out_value = ir_test;
1209 field.in_value = ir_test;
1211 jtag_add_plain_ir_scan(field.num_bits, field.out_value, field.in_value, TAP_IDLE);
1213 LOG_DEBUG("IR capture validation scan");
1214 retval = jtag_execute_queue();
1215 if (retval != ERROR_OK)
1216 goto done;
1218 tap = NULL;
1219 chain_pos = 0;
1221 for (;;) {
1222 tap = jtag_tap_next_enabled(tap);
1223 if (tap == NULL) {
1224 break;
1227 /* If we're autoprobing, guess IR lengths. They must be at
1228 * least two bits. Guessing will fail if (a) any TAP does
1229 * not conform to the JTAG spec; or (b) when the upper bits
1230 * captured from some conforming TAP are nonzero. Or if
1231 * (c) an IR length is longer than 32 bits -- which is only
1232 * an implementation limit, which could someday be raised.
1234 * REVISIT optimization: if there's a *single* TAP we can
1235 * lift restrictions (a) and (b) by scanning a recognizable
1236 * pattern before the all-ones BYPASS. Check for where the
1237 * pattern starts in the result, instead of an 0...01 value.
1239 * REVISIT alternative approach: escape to some tcl code
1240 * which could provide more knowledge, based on IDCODE; and
1241 * only guess when that has no success.
1243 if (tap->ir_length == 0) {
1244 tap->ir_length = 2;
1245 while ((val = buf_get_u32(ir_test, chain_pos,
1246 tap->ir_length + 1)) == 1
1247 && tap->ir_length <= 32) {
1248 tap->ir_length++;
1250 LOG_WARNING("AUTO %s - use \"... -irlen %d\"",
1251 jtag_tap_name(tap), tap->ir_length);
1254 /* Validate the two LSBs, which must be 01 per JTAG spec.
1256 * Or ... more bits could be provided by TAP declaration.
1257 * Plus, some taps (notably in i.MX series chips) violate
1258 * this part of the JTAG spec, so their capture mask/value
1259 * attributes might disable this test.
1261 val = buf_get_u32(ir_test, chain_pos, tap->ir_length);
1262 if ((val & tap->ir_capture_mask) != tap->ir_capture_value) {
1263 LOG_ERROR("%s: IR capture error; saw 0x%0*x not 0x%0*x",
1264 jtag_tap_name(tap),
1265 (tap->ir_length + 7) / tap->ir_length,
1266 val,
1267 (tap->ir_length + 7) / tap->ir_length,
1268 (unsigned) tap->ir_capture_value);
1270 retval = ERROR_JTAG_INIT_FAILED;
1271 goto done;
1273 LOG_DEBUG("%s: IR capture 0x%0*x", jtag_tap_name(tap),
1274 (tap->ir_length + 7) / tap->ir_length, val);
1275 chain_pos += tap->ir_length;
1278 /* verify the '11' sentinel we wrote is returned at the end */
1279 val = buf_get_u32(ir_test, chain_pos, 2);
1280 if (val != 0x3)
1282 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1284 LOG_ERROR("IR capture error at bit %d, saw 0x%s not 0x...3",
1285 chain_pos, cbuf);
1286 free(cbuf);
1287 retval = ERROR_JTAG_INIT_FAILED;
1290 done:
1291 free(ir_test);
1292 if (retval != ERROR_OK) {
1293 jtag_add_tlr();
1294 jtag_execute_queue();
1296 return retval;
1300 void jtag_tap_init(struct jtag_tap *tap)
1302 unsigned ir_len_bits;
1303 unsigned ir_len_bytes;
1305 /* if we're autoprobing, cope with potentially huge ir_length */
1306 ir_len_bits = tap->ir_length ? : JTAG_IRLEN_MAX;
1307 ir_len_bytes = DIV_ROUND_UP(ir_len_bits, 8);
1309 tap->expected = calloc(1, ir_len_bytes);
1310 tap->expected_mask = calloc(1, ir_len_bytes);
1311 tap->cur_instr = malloc(ir_len_bytes);
1313 /// @todo cope better with ir_length bigger than 32 bits
1314 if (ir_len_bits > 32)
1315 ir_len_bits = 32;
1317 buf_set_u32(tap->expected, 0, ir_len_bits, tap->ir_capture_value);
1318 buf_set_u32(tap->expected_mask, 0, ir_len_bits, tap->ir_capture_mask);
1320 // TAP will be in bypass mode after jtag_validate_ircapture()
1321 tap->bypass = 1;
1322 buf_set_ones(tap->cur_instr, tap->ir_length);
1324 // register the reset callback for the TAP
1325 jtag_register_event_callback(&jtag_reset_callback, tap);
1327 LOG_DEBUG("Created Tap: %s @ abs position %d, "
1328 "irlen %d, capture: 0x%x mask: 0x%x", tap->dotted_name,
1329 tap->abs_chain_position, tap->ir_length,
1330 (unsigned) tap->ir_capture_value,
1331 (unsigned) tap->ir_capture_mask);
1332 jtag_tap_add(tap);
1335 void jtag_tap_free(struct jtag_tap *tap)
1337 jtag_unregister_event_callback(&jtag_reset_callback, tap);
1339 /// @todo is anything missing? no memory leaks please
1340 free((void *)tap->expected);
1341 free((void *)tap->expected_ids);
1342 free((void *)tap->chip);
1343 free((void *)tap->tapname);
1344 free((void *)tap->dotted_name);
1345 free(tap);
1349 * Do low-level setup like initializing registers, output signals,
1350 * and clocking.
1352 int adapter_init(struct command_context *cmd_ctx)
1354 if (jtag)
1355 return ERROR_OK;
1357 if (!jtag_interface)
1359 /* nothing was previously specified by "interface" command */
1360 LOG_ERROR("Debug Adapter has to be specified, "
1361 "see \"interface\" command");
1362 return ERROR_JTAG_INVALID_INTERFACE;
1365 jtag = jtag_interface;
1366 if (jtag_interface->init() != ERROR_OK)
1368 jtag = NULL;
1369 return ERROR_JTAG_INIT_FAILED;
1372 /* LEGACY SUPPORT ... adapter drivers must declare what
1373 * transports they allow. Until they all do so, assume
1374 * the legacy drivers are JTAG-only
1376 if (!transports_are_declared()) {
1377 LOG_ERROR("Adapter driver '%s' did not declare "
1378 "which transports it allows; assuming "
1379 "JTAG-only", jtag->name);
1380 int retval = allow_transports(cmd_ctx, jtag_only);
1381 if (retval != ERROR_OK)
1382 return retval;
1385 int requested_khz = jtag_get_speed_khz();
1386 int actual_khz = requested_khz;
1387 int retval = jtag_get_speed_readable(&actual_khz);
1388 if (ERROR_OK != retval)
1389 LOG_INFO("adapter-specific clock speed value %d", jtag_get_speed());
1390 else if (actual_khz)
1392 /* Adaptive clocking -- JTAG-specific */
1393 if ((CLOCK_MODE_RCLK == clock_mode)
1394 || ((CLOCK_MODE_KHZ == clock_mode) && !requested_khz))
1396 LOG_INFO("RCLK (adaptive clock speed) not supported - fallback to %d kHz"
1397 , actual_khz);
1399 else
1400 LOG_INFO("clock speed %d kHz", actual_khz);
1402 else
1403 LOG_INFO("RCLK (adaptive clock speed)");
1405 return ERROR_OK;
1408 int jtag_init_inner(struct command_context *cmd_ctx)
1410 struct jtag_tap *tap;
1411 int retval;
1412 bool issue_setup = true;
1414 LOG_DEBUG("Init JTAG chain");
1416 tap = jtag_tap_next_enabled(NULL);
1417 if (tap == NULL) {
1418 /* Once JTAG itself is properly set up, and the scan chain
1419 * isn't absurdly large, IDCODE autoprobe should work fine.
1421 * But ... IRLEN autoprobe can fail even on systems which
1422 * are fully conformant to JTAG. Also, JTAG setup can be
1423 * quite finicky on some systems.
1425 * REVISIT: if TAP autoprobe works OK, then in many cases
1426 * we could escape to tcl code and set up targets based on
1427 * the TAP's IDCODE values.
1429 LOG_WARNING("There are no enabled taps. "
1430 "AUTO PROBING MIGHT NOT WORK!!");
1432 /* REVISIT default clock will often be too fast ... */
1435 jtag_add_tlr();
1436 if ((retval = jtag_execute_queue()) != ERROR_OK)
1437 return retval;
1439 /* Examine DR values first. This discovers problems which will
1440 * prevent communication ... hardware issues like TDO stuck, or
1441 * configuring the wrong number of (enabled) TAPs.
1443 retval = jtag_examine_chain();
1444 switch (retval) {
1445 case ERROR_OK:
1446 /* complete success */
1447 break;
1448 default:
1449 /* For backward compatibility reasons, try coping with
1450 * configuration errors involving only ID mismatches.
1451 * We might be able to talk to the devices.
1453 * Also the device might be powered down during startup.
1455 * After OpenOCD starts, we can try to power on the device
1456 * and run a reset.
1458 LOG_ERROR("Trying to use configured scan chain anyway...");
1459 issue_setup = false;
1460 break;
1463 /* Now look at IR values. Problems here will prevent real
1464 * communication. They mostly mean that the IR length is
1465 * wrong ... or that the IR capture value is wrong. (The
1466 * latter is uncommon, but easily worked around: provide
1467 * ircapture/irmask values during TAP setup.)
1469 retval = jtag_validate_ircapture();
1470 if (retval != ERROR_OK)
1472 /* The target might be powered down. The user
1473 * can power it up and reset it after firing
1474 * up OpenOCD.
1476 issue_setup = false;
1479 if (issue_setup)
1480 jtag_notify_event(JTAG_TAP_EVENT_SETUP);
1481 else
1482 LOG_WARNING("Bypassing JTAG setup events due to errors");
1485 return ERROR_OK;
1488 int adapter_quit(void)
1490 if (!jtag || !jtag->quit)
1491 return ERROR_OK;
1493 // close the JTAG interface
1494 int result = jtag->quit();
1495 if (ERROR_OK != result)
1496 LOG_ERROR("failed: %d", result);
1498 return ERROR_OK;
1502 int jtag_init_reset(struct command_context *cmd_ctx)
1504 int retval;
1506 if ((retval = adapter_init(cmd_ctx)) != ERROR_OK)
1507 return retval;
1509 LOG_DEBUG("Initializing with hard TRST+SRST reset");
1512 * This procedure is used by default when OpenOCD triggers a reset.
1513 * It's now done through an overridable Tcl "init_reset" wrapper.
1515 * This started out as a more powerful "get JTAG working" reset than
1516 * jtag_init_inner(), applying TRST because some chips won't activate
1517 * JTAG without a TRST cycle (presumed to be async, though some of
1518 * those chips synchronize JTAG activation using TCK).
1520 * But some chips only activate JTAG as part of an SRST cycle; SRST
1521 * got mixed in. So it became a hard reset routine, which got used
1522 * in more places, and which coped with JTAG reset being forced as
1523 * part of SRST (srst_pulls_trst).
1525 * And even more corner cases started to surface: TRST and/or SRST
1526 * assertion timings matter; some chips need other JTAG operations;
1527 * TRST/SRST sequences can need to be different from these, etc.
1529 * Systems should override that wrapper to support system-specific
1530 * requirements that this not-fully-generic code doesn't handle.
1532 * REVISIT once Tcl code can read the reset_config modes, this won't
1533 * need to be a C routine at all...
1535 jtag_add_reset(1, 0); /* TAP_RESET, using TMS+TCK or TRST */
1536 if (jtag_reset_config & RESET_HAS_SRST)
1538 jtag_add_reset(1, 1);
1539 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) == 0)
1540 jtag_add_reset(0, 1);
1542 jtag_add_reset(0, 0);
1543 if ((retval = jtag_execute_queue()) != ERROR_OK)
1544 return retval;
1546 /* Check that we can communication on the JTAG chain + eventually we want to
1547 * be able to perform enumeration only after OpenOCD has started
1548 * telnet and GDB server
1550 * That would allow users to more easily perform any magic they need to before
1551 * reset happens.
1553 return jtag_init_inner(cmd_ctx);
1556 int jtag_init(struct command_context *cmd_ctx)
1558 int retval;
1560 if ((retval = adapter_init(cmd_ctx)) != ERROR_OK)
1561 return retval;
1563 /* guard against oddball hardware: force resets to be inactive */
1564 jtag_add_reset(0, 0);
1565 if ((retval = jtag_execute_queue()) != ERROR_OK)
1566 return retval;
1568 if (Jim_Eval_Named(cmd_ctx->interp, "jtag_init", __FILE__, __LINE__) != JIM_OK)
1569 return ERROR_FAIL;
1571 return ERROR_OK;
1574 unsigned jtag_get_speed_khz(void)
1576 return speed_khz;
1579 static int adapter_khz_to_speed(unsigned khz, int* speed)
1581 LOG_DEBUG("convert khz to interface specific speed value");
1582 speed_khz = khz;
1583 if (jtag != NULL)
1585 LOG_DEBUG("have interface set up");
1586 int speed_div1;
1587 int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1588 if (ERROR_OK != retval)
1590 return retval;
1592 *speed = speed_div1;
1594 return ERROR_OK;
1597 static int jtag_rclk_to_speed(unsigned fallback_speed_khz, int* speed)
1599 int retval = adapter_khz_to_speed(0, speed);
1600 if ((ERROR_OK != retval) && fallback_speed_khz)
1602 LOG_DEBUG("trying fallback speed...");
1603 retval = adapter_khz_to_speed(fallback_speed_khz, speed);
1605 return retval;
1608 static int jtag_set_speed(int speed)
1610 jtag_speed = speed;
1611 /* this command can be called during CONFIG,
1612 * in which case jtag isn't initialized */
1613 return jtag ? jtag->speed(speed) : ERROR_OK;
1616 int jtag_config_khz(unsigned khz)
1618 LOG_DEBUG("handle jtag khz");
1619 clock_mode = CLOCK_MODE_KHZ;
1620 int speed = 0;
1621 int retval = adapter_khz_to_speed(khz, &speed);
1622 return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1625 int jtag_config_rclk(unsigned fallback_speed_khz)
1627 LOG_DEBUG("handle jtag rclk");
1628 clock_mode = CLOCK_MODE_RCLK;
1629 rclk_fallback_speed_khz = fallback_speed_khz;
1630 int speed = 0;
1631 int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1632 return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1635 int jtag_get_speed(void)
1637 int speed = 0; /* avoid -O3 warning */
1638 switch(clock_mode)
1640 case CLOCK_MODE_SPEED:
1641 speed = jtag_speed;
1642 break;
1643 case CLOCK_MODE_KHZ:
1644 adapter_khz_to_speed(jtag_get_speed_khz(), &speed);
1645 break;
1646 case CLOCK_MODE_RCLK:
1647 jtag_rclk_to_speed(rclk_fallback_speed_khz, &speed);
1648 break;
1649 default:
1650 LOG_ERROR("BUG: unknown jtag clock mode");
1651 speed = 0;
1652 break;
1654 return speed;
1657 int jtag_get_speed_readable(int *khz)
1659 return jtag ? jtag->speed_div(jtag_get_speed(), khz) : ERROR_OK;
1662 void jtag_set_verify(bool enable)
1664 jtag_verify = enable;
1667 bool jtag_will_verify()
1669 return jtag_verify;
1672 void jtag_set_verify_capture_ir(bool enable)
1674 jtag_verify_capture_ir = enable;
1677 bool jtag_will_verify_capture_ir()
1679 return jtag_verify_capture_ir;
1682 int jtag_power_dropout(int *dropout)
1684 if (jtag == NULL)
1686 /* TODO: as the jtag interface is not valid all
1687 * we can do at the moment is exit OpenOCD */
1688 LOG_ERROR("No Valid JTAG Interface Configured.");
1689 exit(-1);
1691 return jtag->power_dropout(dropout);
1694 int jtag_srst_asserted(int *srst_asserted)
1696 return jtag->srst_asserted(srst_asserted);
1699 enum reset_types jtag_get_reset_config(void)
1701 return jtag_reset_config;
1703 void jtag_set_reset_config(enum reset_types type)
1705 jtag_reset_config = type;
1708 int jtag_get_trst(void)
1710 return jtag_trst;
1712 int jtag_get_srst(void)
1714 return jtag_srst;
1717 void jtag_set_nsrst_delay(unsigned delay)
1719 adapter_nsrst_delay = delay;
1721 unsigned jtag_get_nsrst_delay(void)
1723 return adapter_nsrst_delay;
1725 void jtag_set_ntrst_delay(unsigned delay)
1727 jtag_ntrst_delay = delay;
1729 unsigned jtag_get_ntrst_delay(void)
1731 return jtag_ntrst_delay;
1735 void jtag_set_nsrst_assert_width(unsigned delay)
1737 adapter_nsrst_assert_width = delay;
1739 unsigned jtag_get_nsrst_assert_width(void)
1741 return adapter_nsrst_assert_width;
1743 void jtag_set_ntrst_assert_width(unsigned delay)
1745 jtag_ntrst_assert_width = delay;
1747 unsigned jtag_get_ntrst_assert_width(void)
1749 return jtag_ntrst_assert_width;
1752 static int jtag_select(struct command_context *ctx)
1754 int retval;
1756 /* NOTE: interface init must already have been done.
1757 * That works with only C code ... no Tcl glue required.
1760 retval = jtag_register_commands(ctx);
1762 if (retval != ERROR_OK)
1763 return retval;
1765 retval = svf_register_commands(ctx);
1767 if (retval != ERROR_OK)
1768 return retval;
1770 return xsvf_register_commands(ctx);
1773 static struct transport jtag_transport = {
1774 .name = "jtag",
1775 .select = jtag_select,
1776 .init = jtag_init,
1779 static void jtag_constructor(void) __attribute__((constructor));
1780 static void jtag_constructor(void)
1782 transport_register(&jtag_transport);
1785 /** Returns true if the current debug session
1786 * is using JTAG as its transport.
1788 bool transport_is_jtag(void)
1790 return get_current_transport() == &jtag_transport;