]> git.sur5r.net Git - openocd/blob - src/jtag/core.c
jtag: getting the JTAG speed can fail
[openocd] / src / jtag / core.c
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
33
34 #include "jtag.h"
35 #include "interface.h"
36 #include "transport.h"
37
38 #ifdef HAVE_STRINGS_H
39 #include <strings.h>
40 #endif
41
42 /* SVF and XSVF are higher level JTAG command sets (for boundary scan) */
43 #include "svf/svf.h"
44 #include "xsvf/xsvf.h"
45
46 /// The number of JTAG queue flushes (for profiling and debugging purposes).
47 static int jtag_flush_queue_count;
48
49 // Sleep this # of ms after flushing the queue
50 static int jtag_flush_queue_sleep = 0;
51
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);
55
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().
61  *
62  * The value is set and cleared, but never read by normal application code.
63  *
64  * This value is returned (and cleared) by jtag_execute_queue().
65  */
66 static int jtag_error = ERROR_OK;
67
68 static const char *jtag_event_strings[] =
69 {
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",
74 };
75
76 /*
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.
81  */
82 static int jtag_trst = -1;
83 static int jtag_srst = -1;
84
85 /**
86  * List all TAPs that have been created.
87  */
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
92  */
93 static unsigned jtag_num_taps = 0;
94
95 static enum reset_types jtag_reset_config = RESET_NONE;
96 tap_state_t cmd_queue_cur_state = TAP_RESET;
97
98 static bool jtag_verify_capture_ir = true;
99 static int jtag_verify = 1;
100
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 */
106
107 /**
108  * Contains a single callback along with a pointer that will be passed
109  * when an event occurs.
110  */
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;
118 };
119
120 /* callbacks to inform high-level handlers about JTAG state changes */
121 static struct jtag_event_callback *jtag_event_callbacks;
122
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;
129
130 static struct jtag_interface *jtag = NULL;
131
132 /* configuration */
133 struct jtag_interface *jtag_interface = NULL;
134
135 void jtag_set_flush_queue_sleep(int ms)
136 {
137         jtag_flush_queue_sleep = ms;
138 }
139
140 void jtag_set_error(int error)
141 {
142         if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
143                 return;
144         jtag_error = error;
145 }
146
147 int jtag_error_clear(void)
148 {
149         int temp = jtag_error;
150         jtag_error = ERROR_OK;
151         return temp;
152 }
153
154 /************/
155
156 static bool jtag_poll = 1;
157
158 bool is_jtag_poll_safe(void)
159 {
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.
163          */
164         if (!jtag_poll || jtag_trst != 0)
165                 return false;
166         return jtag_srst == 0 || (jtag_reset_config & RESET_SRST_NO_GATING);
167 }
168
169 bool jtag_poll_get_enabled(void)
170 {
171         return jtag_poll;
172 }
173
174 void jtag_poll_set_enabled(bool value)
175 {
176         jtag_poll = value;
177 }
178
179 /************/
180
181 struct jtag_tap *jtag_all_taps(void)
182 {
183         return __jtag_all_taps;
184 };
185
186 unsigned jtag_tap_count(void)
187 {
188         return jtag_num_taps;
189 }
190
191 unsigned jtag_tap_count_enabled(void)
192 {
193         struct jtag_tap *t = jtag_all_taps();
194         unsigned n = 0;
195         while (t)
196         {
197                 if (t->enabled)
198                         n++;
199                 t = t->next_tap;
200         }
201         return n;
202 }
203
204 /// Append a new TAP to the chain of all taps.
205 void jtag_tap_add(struct jtag_tap *t)
206 {
207         t->abs_chain_position = jtag_num_taps++;
208
209         struct jtag_tap **tap = &__jtag_all_taps;
210         while (*tap != NULL)
211                 tap = &(*tap)->next_tap;
212         *tap = t;
213 }
214
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)
217 {
218         struct jtag_tap *t = jtag_all_taps();
219
220         while (t && n-- > 0)
221                 t = t->next_tap;
222
223         return t;
224 }
225
226 struct jtag_tap *jtag_tap_by_string(const char *s)
227 {
228         /* try by name first */
229         struct jtag_tap *t = jtag_all_taps();
230
231         while (t)
232         {
233                 if (0 == strcmp(t->dotted_name, s))
234                         return t;
235                 t = t->next_tap;
236         }
237
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;
242
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.
246          */
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);
251
252         return t;
253 }
254
255 struct jtag_tap* jtag_tap_next_enabled(struct jtag_tap* p)
256 {
257         p = p ? p->next_tap : jtag_all_taps();
258         while (p)
259         {
260                 if (p->enabled)
261                         return p;
262                 p = p->next_tap;
263         }
264         return NULL;
265 }
266
267 const char *jtag_tap_name(const struct jtag_tap *tap)
268 {
269         return (tap == NULL) ? "(unknown)" : tap->dotted_name;
270 }
271
272
273 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
274 {
275         struct jtag_event_callback **callbacks_p = &jtag_event_callbacks;
276
277         if (callback == NULL)
278         {
279                 return ERROR_INVALID_ARGUMENTS;
280         }
281
282         if (*callbacks_p)
283         {
284                 while ((*callbacks_p)->next)
285                         callbacks_p = &((*callbacks_p)->next);
286                 callbacks_p = &((*callbacks_p)->next);
287         }
288
289         (*callbacks_p) = malloc(sizeof(struct jtag_event_callback));
290         (*callbacks_p)->callback = callback;
291         (*callbacks_p)->priv = priv;
292         (*callbacks_p)->next = NULL;
293
294         return ERROR_OK;
295 }
296
297 int jtag_unregister_event_callback(jtag_event_handler_t callback, void *priv)
298 {
299         struct jtag_event_callback **callbacks_p;
300         struct jtag_event_callback **next;
301
302         if (callback == NULL)
303         {
304                 return ERROR_INVALID_ARGUMENTS;
305         }
306
307         for (callbacks_p = &jtag_event_callbacks;
308                         *callbacks_p != NULL;
309                         callbacks_p = next)
310         {
311                 next = &((*callbacks_p)->next);
312
313                 if ((*callbacks_p)->priv != priv)
314                         continue;
315
316                 if ((*callbacks_p)->callback == callback)
317                 {
318                         free(*callbacks_p);
319                         *callbacks_p = *next;
320                 }
321         }
322
323         return ERROR_OK;
324 }
325
326 int jtag_call_event_callbacks(enum jtag_event event)
327 {
328         struct jtag_event_callback *callback = jtag_event_callbacks;
329
330         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
331
332         while (callback)
333         {
334                 struct jtag_event_callback *next;
335
336                 /* callback may remove itself */
337                 next = callback->next;
338                 callback->callback(event, callback->priv);
339                 callback = next;
340         }
341
342         return ERROR_OK;
343 }
344
345 static void jtag_checks(void)
346 {
347         assert(jtag_trst == 0);
348 }
349
350 static void jtag_prelude(tap_state_t state)
351 {
352         jtag_checks();
353
354         assert(state != TAP_INVALID);
355
356         cmd_queue_cur_state = state;
357 }
358
359 void jtag_alloc_in_value32(struct scan_field *field)
360 {
361         interface_jtag_alloc_in_value32(field);
362 }
363
364 void jtag_add_ir_scan_noverify(struct jtag_tap *active, const struct scan_field *in_fields,
365                 tap_state_t state)
366 {
367         jtag_prelude(state);
368
369         int retval = interface_jtag_add_ir_scan(active, in_fields, state);
370         jtag_set_error(retval);
371 }
372
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)
375 {
376         jtag_add_ir_scan_noverify(active, in_fields, state);
377 }
378
379 void jtag_add_ir_scan(struct jtag_tap *active, struct scan_field *in_fields, tap_state_t state)
380 {
381         assert(state != TAP_RESET);
382
383         if (jtag_verify && jtag_verify_capture_ir)
384         {
385                 /* 8 x 32 bit id's is enough for all invocations */
386
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.
389                  */
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
394         {
395                 jtag_add_ir_scan_noverify(active, in_fields, state);
396         }
397 }
398
399 void jtag_add_plain_ir_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
400                 tap_state_t state)
401 {
402         assert(out_bits != NULL);
403         assert(state != TAP_RESET);
404
405         jtag_prelude(state);
406
407         int retval = interface_jtag_add_plain_ir_scan(
408                         num_bits, out_bits, in_bits, state);
409         jtag_set_error(retval);
410 }
411
412 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
413                 uint8_t *in_check_mask, int num_bits);
414
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)
416 {
417         return jtag_check_value_inner((uint8_t *)data0, (uint8_t *)data1, (uint8_t *)data2, (int)data3);
418 }
419
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)
422 {
423         for (int i = 0; i < in_num_fields; i++)
424         {
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;
432         }
433
434         jtag_add_scan(active, in_num_fields, in_fields, state);
435
436         for (int i = 0; i < in_num_fields; i++)
437         {
438                 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL))
439                 {
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);
445                 }
446                 if (in_fields[i].allocated)
447                 {
448                         free(in_fields[i].in_value);
449                 }
450                 if (in_fields[i].modified)
451                 {
452                         in_fields[i].in_value = NULL;
453                 }
454         }
455 }
456
457 void jtag_add_dr_scan_check(struct jtag_tap *active, int in_num_fields, struct scan_field *in_fields, tap_state_t state)
458 {
459         if (jtag_verify)
460         {
461                 jtag_add_scan_check(active, jtag_add_dr_scan, in_num_fields, in_fields, state);
462         } else
463         {
464                 jtag_add_dr_scan(active, in_num_fields, in_fields, state);
465         }
466 }
467
468
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)
471 {
472         assert(state != TAP_RESET);
473
474         jtag_prelude(state);
475
476         int retval;
477         retval = interface_jtag_add_dr_scan(active, in_num_fields, in_fields, state);
478         jtag_set_error(retval);
479 }
480
481 void jtag_add_plain_dr_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
482                 tap_state_t state)
483 {
484         assert(out_bits != NULL);
485         assert(state != TAP_RESET);
486
487         jtag_prelude(state);
488
489         int retval;
490         retval = interface_jtag_add_plain_dr_scan(num_bits, out_bits, in_bits, state);
491         jtag_set_error(retval);
492 }
493
494 void jtag_add_tlr(void)
495 {
496         jtag_prelude(TAP_RESET);
497         jtag_set_error(interface_jtag_add_tlr());
498
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);
502 }
503
504 /**
505  * If supported by the underlying adapter, this clocks a raw bit sequence
506  * onto TMS for switching betwen JTAG and SWD modes.
507  *
508  * DO NOT use this to bypass the integrity checks and logging provided
509  * by the jtag_add_pathmove() and jtag_add_statemove() calls.
510  *
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.
515  *
516  * @todo Update naming conventions to stop assuming everything is JTAG.
517  */
518 int jtag_add_tms_seq(unsigned nbits, const uint8_t *seq, enum tap_state state)
519 {
520         int retval;
521
522         if (!(jtag->supported & DEBUG_CAP_TMS_SEQ))
523                 return ERROR_JTAG_NOT_IMPLEMENTED;
524
525         jtag_checks();
526         cmd_queue_cur_state = state;
527
528         retval = interface_add_tms_seq(nbits, seq, state);
529         jtag_set_error(retval);
530         return retval;
531 }
532
533 void jtag_add_pathmove(int num_states, const tap_state_t *path)
534 {
535         tap_state_t cur_state = cmd_queue_cur_state;
536
537         /* the last state has to be a stable state */
538         if (!tap_is_state_stable(path[num_states - 1]))
539         {
540                 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
541                 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
542                 return;
543         }
544
545         for (int i = 0; i < num_states; i++)
546         {
547                 if (path[i] == TAP_RESET)
548                 {
549                         LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
550                         jtag_set_error(ERROR_JTAG_STATE_INVALID);
551                         return;
552                 }
553
554                 if (tap_state_transition(cur_state, true)  != path[i]
555                   && tap_state_transition(cur_state, false) != path[i])
556                 {
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;
561                 }
562                 cur_state = path[i];
563         }
564
565         jtag_checks();
566
567         jtag_set_error(interface_jtag_add_pathmove(num_states, path));
568         cmd_queue_cur_state = path[num_states - 1];
569 }
570
571 int jtag_add_statemove(tap_state_t goal_state)
572 {
573         tap_state_t cur_state = cmd_queue_cur_state;
574
575         if (goal_state != cur_state)
576         {
577                 LOG_DEBUG("cur_state=%s goal_state=%s",
578                         tap_state_name(cur_state),
579                         tap_state_name(goal_state));
580         }
581
582         /* If goal is RESET, be paranoid and force that that transition
583          * (e.g. five TCK cycles, TMS high).  Else trust "cur_state".
584          */
585         if (goal_state == TAP_RESET)
586                 jtag_add_tlr();
587         else if (goal_state == cur_state)
588                 /* nothing to do */ ;
589
590         else if (tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state))
591         {
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));
596
597                 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1)
598                 {
599                         bool bit = tms_bits & 1;
600
601                         cur_state = tap_state_transition(cur_state, bit);
602                         moves[i] = cur_state;
603                 }
604
605                 jtag_add_pathmove(tms_count, moves);
606         }
607         else if (tap_state_transition(cur_state, true)  == goal_state
608                 ||   tap_state_transition(cur_state, false) == goal_state)
609         {
610                 jtag_add_pathmove(1, &goal_state);
611         }
612
613         else
614                 return ERROR_FAIL;
615
616         return ERROR_OK;
617 }
618
619 void jtag_add_runtest(int num_cycles, tap_state_t state)
620 {
621         jtag_prelude(state);
622         jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
623 }
624
625
626 void jtag_add_clocks(int num_cycles)
627 {
628         if (!tap_is_state_stable(cmd_queue_cur_state))
629         {
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;
634         }
635
636         if (num_cycles > 0)
637         {
638                 jtag_checks();
639                 jtag_set_error(interface_jtag_add_clocks(num_cycles));
640         }
641 }
642
643 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
644 {
645         int trst_with_tlr = 0;
646         int new_srst = 0;
647         int new_trst = 0;
648
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.
652          *
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.
655          */
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;
661                 }
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;
667                 }
668                 new_srst = 1;
669         }
670
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.
674          *
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.
677          */
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;
686         }
687
688         /* Maybe change TRST and/or SRST signal state */
689         if (jtag_srst != new_srst || jtag_trst != new_trst) {
690                 int retval;
691
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();
697
698                 if (retval != ERROR_OK) {
699                         LOG_ERROR("TRST/SRST error %d", retval);
700                         return;
701                 }
702         }
703
704         /* SRST resets everything hooked up to that signal */
705         if (jtag_srst != new_srst) {
706                 jtag_srst = new_srst;
707                 if (jtag_srst)
708                 {
709                         LOG_DEBUG("SRST line asserted");
710                         if (adapter_nsrst_assert_width)
711                                 jtag_add_sleep(adapter_nsrst_assert_width * 1000);
712                 }
713                 else {
714                         LOG_DEBUG("SRST line released");
715                         if (adapter_nsrst_delay)
716                                 jtag_add_sleep(adapter_nsrst_delay * 1000);
717                 }
718         }
719
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
723          *
724          * TAP_RESET should be invisible to non-debug parts of the system.
725          */
726         if (trst_with_tlr) {
727                 LOG_DEBUG("JTAG reset with TLR instead of TRST");
728                 jtag_add_tlr();
729
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);
741
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().
746                          */
747                         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
748                         jtag_notify_event(JTAG_TRST_ASSERTED);
749                 }
750         }
751 }
752
753 void jtag_add_sleep(uint32_t us)
754 {
755         /// @todo Here, keep_alive() appears to be a layering violation!!!
756         keep_alive();
757         jtag_set_error(interface_jtag_add_sleep(us));
758 }
759
760 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
761                 uint8_t *in_check_mask, int num_bits)
762 {
763         int retval = ERROR_OK;
764         int compare_failed;
765
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);
770
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;
776
777                 /* NOTE:  we've lost diagnostic context here -- 'which tap' */
778
779                 captured_str = buf_to_str(captured, bits, 16);
780                 in_check_value_str = buf_to_str(in_check_value, bits, 16);
781
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);
785
786                 free(captured_str);
787                 free(in_check_value_str);
788
789                 if (in_check_mask) {
790                         char *in_check_mask_str;
791
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);
795                 }
796
797                 retval = ERROR_JTAG_QUEUE_FAILED;
798         }
799         return retval;
800 }
801
802 void jtag_check_value_mask(struct scan_field *field, uint8_t *value, uint8_t *mask)
803 {
804         assert(field->in_value != NULL);
805
806         if (value == NULL)
807         {
808                 /* no checking to do */
809                 return;
810         }
811
812         jtag_execute_queue_noclear();
813
814         int retval = jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
815         jtag_set_error(retval);
816 }
817
818
819
820 int default_interface_jtag_execute_queue(void)
821 {
822         if (NULL == jtag)
823         {
824                 LOG_ERROR("No JTAG interface configured yet.  "
825                         "Issue 'init' command in startup scripts "
826                         "before communicating with targets.");
827                 return ERROR_FAIL;
828         }
829
830         return jtag->execute_queue();
831 }
832
833 void jtag_execute_queue_noclear(void)
834 {
835         jtag_flush_queue_count++;
836         jtag_set_error(interface_jtag_execute_queue());
837
838         if (jtag_flush_queue_sleep > 0)
839         {
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.
843                  */
844                 usleep(jtag_flush_queue_sleep * 1000);
845         }
846 }
847
848 int jtag_get_flush_queue_count(void)
849 {
850         return jtag_flush_queue_count;
851 }
852
853 int jtag_execute_queue(void)
854 {
855         jtag_execute_queue_noclear();
856         return jtag_error_clear();
857 }
858
859 static int jtag_reset_callback(enum jtag_event event, void *priv)
860 {
861         struct jtag_tap *tap = priv;
862
863         if (event == JTAG_TRST_ASSERTED)
864         {
865                 tap->enabled = !tap->disabled_after_reset;
866
867                 /* current instruction is either BYPASS or IDCODE */
868                 buf_set_ones(tap->cur_instr, tap->ir_length);
869                 tap->bypass = 1;
870         }
871
872         return ERROR_OK;
873 }
874
875 void jtag_sleep(uint32_t us)
876 {
877         alive_sleep(us/1000);
878 }
879
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.
883  */
884 #define JTAG_MAX_CHAIN_SIZE 20
885
886 #define EXTRACT_MFG(X)  (((X) & 0xffe) >> 1)
887 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
888 #define EXTRACT_VER(X)  (((X) & 0xf0000000) >> 28)
889
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.
892  */
893 #define END_OF_CHAIN_FLAG       0x000000ff
894
895 /* a larger IR length than we ever expect to autoprobe */
896 #define JTAG_IRLEN_MAX          60
897
898 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
899 {
900         struct scan_field field = {
901                         .num_bits = num_idcode * 32,
902                         .out_value = idcode_buffer,
903                         .in_value = idcode_buffer,
904                 };
905
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);
909
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();
913 }
914
915 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
916 {
917         uint8_t zero_check = 0x0;
918         uint8_t one_check = 0xff;
919
920         for (unsigned i = 0; i < count * 4; i++)
921         {
922                 zero_check |= idcodes[i];
923                 one_check &= idcodes[i];
924         }
925
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
928          *
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
935          */
936         if (zero_check == 0x00 || one_check == 0xff)
937         {
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;
942         }
943         return true;
944 }
945
946 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
947                 const char *name, uint32_t idcode)
948 {
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));
957 }
958
959 static bool jtag_idcode_is_final(uint32_t idcode)
960 {
961         /*
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.
965          */
966         return idcode == END_OF_CHAIN_FLAG || idcode == 0xFFFFFFFF;
967 }
968
969 /**
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.
975  */
976 static bool jtag_examine_chain_end(uint8_t *idcodes, unsigned count, unsigned max)
977 {
978         bool triggered = false;
979         for (; count < max - 31; count += 32)
980         {
981                 uint32_t idcode = buf_get_u32(idcodes, count, 32);
982
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;
989         }
990         return triggered;
991 }
992
993 static bool jtag_examine_chain_match_tap(const struct jtag_tap *tap)
994 {
995         uint32_t idcode = tap->idcode;
996
997         /* ignore expected BYPASS codes; warn otherwise */
998         if (0 == tap->expected_ids_cnt && !idcode)
999                 return true;
1000
1001         /* optionally ignore the JTAG version field */
1002         uint32_t mask = tap->ignore_version ? ~(0xff << 24) : ~0;
1003
1004         idcode &= mask;
1005
1006         /* Loop over the expected identification codes and test for a match */
1007         unsigned ii, limit = tap->expected_ids_cnt;
1008
1009         for (ii = 0; ii < limit; ii++)
1010         {
1011                 uint32_t expected = tap->expected_ids[ii] & mask;
1012
1013                 if (idcode == expected)
1014                         return true;
1015
1016                 /* treat "-expected-id 0" as a "don't-warn" wildcard */
1017                 if (0 == tap->expected_ids[ii])
1018                         return true;
1019         }
1020
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++)
1025         {
1026                 char msg[32];
1027
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]);
1031         }
1032         return false;
1033 }
1034
1035 /* Try to examine chain layout according to IEEE 1149.1 Â§12
1036  * This is called a "blind interrogation" of the scan chain.
1037  */
1038 static int jtag_examine_chain(void)
1039 {
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;
1045
1046         /* DR scan to collect BYPASS or IDCODE register contents.
1047          * Then make sure the scan data has both ones and zeroes.
1048          */
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;
1055
1056         /* point at the 1st tap */
1057         struct jtag_tap *tap = jtag_tap_next_enabled(NULL);
1058
1059         if (!tap)
1060                 autoprobe = true;
1061
1062         for (bit_count = 0;
1063                         tap && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;
1064                         tap = jtag_tap_next_enabled(tap))
1065         {
1066                 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1067
1068                 if ((idcode & 1) == 0)
1069                 {
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;
1075
1076                         bit_count += 1;
1077                 }
1078                 else
1079                 {
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);
1085
1086                         bit_count += 32;
1087                 }
1088                 tap->idcode = idcode;
1089
1090                 /* ensure the TAP ID matches what was expected */
1091                 if (!jtag_examine_chain_match_tap(tap))
1092                         retval = ERROR_JTAG_INIT_SOFT_FAIL;
1093         }
1094
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;
1100         }
1101
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];
1106
1107                 /* Is there another TAP? */
1108                 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1109                 if (jtag_idcode_is_final(idcode))
1110                         break;
1111
1112                 /* Default everything in this TAP except IR length.
1113                  *
1114                  * REVISIT create a jtag_alloc(chip, tap) routine, and
1115                  * share it with jim_newtap_cmd().
1116                  */
1117                 tap = calloc(1, sizeof *tap);
1118                 if (!tap)
1119                         return ERROR_FAIL;
1120
1121                 sprintf(buf, "auto%d", tapcount++);
1122                 tap->chip = strdup(buf);
1123                 tap->tapname = strdup("tap");
1124
1125                 sprintf(buf, "%s.%s", tap->chip, tap->tapname);
1126                 tap->dotted_name = strdup(buf);
1127
1128                 /* tap->ir_length == 0 ... signifying irlen autoprobe */
1129                 tap->ir_capture_mask = 0x03;
1130                 tap->ir_capture_value = 0x01;
1131
1132                 tap->enabled = true;
1133
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;
1141
1142                         tap->expected_ids_cnt = 1;
1143                         tap->expected_ids = malloc(sizeof(uint32_t));
1144                         tap->expected_ids[0] = idcode;
1145                 }
1146
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);
1151
1152                 jtag_tap_init(tap);
1153         }
1154
1155         /* After those IDCODE or BYPASS register values should be
1156          * only the data we fed into the scan chain.
1157          */
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;
1163         }
1164
1165         /* Return success or, for backwards compatibility if only
1166          * some IDCODE values mismatched, a soft/continuable fault.
1167          */
1168         return retval;
1169 }
1170
1171 /*
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.
1175  *
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.
1178  */
1179 static int jtag_validate_ircapture(void)
1180 {
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;
1188
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;
1195         }
1196
1197         /* increase length to add 2 bit sentinel after scan */
1198         total_ir_length += 2;
1199
1200         ir_test = malloc(DIV_ROUND_UP(total_ir_length, 8));
1201         if (ir_test == NULL)
1202                 return ERROR_FAIL;
1203
1204         /* after this scan, all TAPs will capture BYPASS instructions */
1205         buf_set_ones(ir_test, total_ir_length);
1206
1207         field.num_bits = total_ir_length;
1208         field.out_value = ir_test;
1209         field.in_value = ir_test;
1210
1211         jtag_add_plain_ir_scan(field.num_bits, field.out_value, field.in_value, TAP_IDLE);
1212
1213         LOG_DEBUG("IR capture validation scan");
1214         retval = jtag_execute_queue();
1215         if (retval != ERROR_OK)
1216                 goto done;
1217
1218         tap = NULL;
1219         chain_pos = 0;
1220
1221         for (;;) {
1222                 tap = jtag_tap_next_enabled(tap);
1223                 if (tap == NULL) {
1224                         break;
1225                 }
1226
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.
1233                  *
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.
1238                  *
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.
1242                  */
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++;
1249                         }
1250                         LOG_WARNING("AUTO %s - use \"... -irlen %d\"",
1251                                         jtag_tap_name(tap), tap->ir_length);
1252                 }
1253
1254                 /* Validate the two LSBs, which must be 01 per JTAG spec.
1255                  *
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.
1260                  */
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);
1269
1270                         retval = ERROR_JTAG_INIT_FAILED;
1271                         goto done;
1272                 }
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;
1276         }
1277
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)
1281         {
1282                 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1283
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;
1288         }
1289
1290 done:
1291         free(ir_test);
1292         if (retval != ERROR_OK) {
1293                 jtag_add_tlr();
1294                 jtag_execute_queue();
1295         }
1296         return retval;
1297 }
1298
1299
1300 void jtag_tap_init(struct jtag_tap *tap)
1301 {
1302         unsigned ir_len_bits;
1303         unsigned ir_len_bytes;
1304
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);
1308
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);
1312
1313         /// @todo cope better with ir_length bigger than 32 bits
1314         if (ir_len_bits > 32)
1315                 ir_len_bits = 32;
1316
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);
1319
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);
1323
1324         // register the reset callback for the TAP
1325         jtag_register_event_callback(&jtag_reset_callback, tap);
1326
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);
1333 }
1334
1335 void jtag_tap_free(struct jtag_tap *tap)
1336 {
1337         jtag_unregister_event_callback(&jtag_reset_callback, tap);
1338
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);
1346 }
1347
1348 /**
1349  * Do low-level setup like initializing registers, output signals,
1350  * and clocking.
1351  */
1352 int adapter_init(struct command_context *cmd_ctx)
1353 {
1354         if (jtag)
1355                 return ERROR_OK;
1356
1357         if (!jtag_interface)
1358         {
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;
1363         }
1364
1365         jtag = jtag_interface;
1366         if (jtag_interface->init() != ERROR_OK)
1367         {
1368                 jtag = NULL;
1369                 return ERROR_JTAG_INIT_FAILED;
1370         }
1371
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
1375          */
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;
1383         }
1384
1385         int requested_khz = jtag_get_speed_khz();
1386         int actual_khz = requested_khz;
1387         int jtag_speed_var;
1388         int retval = jtag_get_speed(&jtag_speed_var);
1389         if (retval != ERROR_OK)
1390                 return retval;
1391         retval = jtag_get_speed_readable(&actual_khz);
1392         if (ERROR_OK != retval)
1393                 LOG_INFO("adapter-specific clock speed value %d", jtag_speed_var);
1394         else if (actual_khz)
1395         {
1396                 /* Adaptive clocking -- JTAG-specific */
1397                 if ((CLOCK_MODE_RCLK == clock_mode)
1398                         || ((CLOCK_MODE_KHZ == clock_mode) && !requested_khz))
1399                 {
1400                         LOG_INFO("RCLK (adaptive clock speed) not supported - fallback to %d kHz"
1401                                 , actual_khz);
1402                 }
1403                 else
1404                         LOG_INFO("clock speed %d kHz", actual_khz);
1405         }
1406         else
1407                 LOG_INFO("RCLK (adaptive clock speed)");
1408
1409         return ERROR_OK;
1410 }
1411
1412 int jtag_init_inner(struct command_context *cmd_ctx)
1413 {
1414         struct jtag_tap *tap;
1415         int retval;
1416         bool issue_setup = true;
1417
1418         LOG_DEBUG("Init JTAG chain");
1419
1420         tap = jtag_tap_next_enabled(NULL);
1421         if (tap == NULL) {
1422                 /* Once JTAG itself is properly set up, and the scan chain
1423                  * isn't absurdly large, IDCODE autoprobe should work fine.
1424                  *
1425                  * But ... IRLEN autoprobe can fail even on systems which
1426                  * are fully conformant to JTAG.  Also, JTAG setup can be
1427                  * quite finicky on some systems.
1428                  *
1429                  * REVISIT: if TAP autoprobe works OK, then in many cases
1430                  * we could escape to tcl code and set up targets based on
1431                  * the TAP's IDCODE values.
1432                  */
1433                 LOG_WARNING("There are no enabled taps.  "
1434                                 "AUTO PROBING MIGHT NOT WORK!!");
1435
1436                 /* REVISIT default clock will often be too fast ... */
1437         }
1438
1439         jtag_add_tlr();
1440         if ((retval = jtag_execute_queue()) != ERROR_OK)
1441                 return retval;
1442
1443         /* Examine DR values first.  This discovers problems which will
1444          * prevent communication ... hardware issues like TDO stuck, or
1445          * configuring the wrong number of (enabled) TAPs.
1446          */
1447         retval = jtag_examine_chain();
1448         switch (retval) {
1449         case ERROR_OK:
1450                 /* complete success */
1451                 break;
1452         default:
1453                 /* For backward compatibility reasons, try coping with
1454                  * configuration errors involving only ID mismatches.
1455                  * We might be able to talk to the devices.
1456                  *
1457                  * Also the device might be powered down during startup.
1458                  *
1459                  * After OpenOCD starts, we can try to power on the device
1460                  * and run a reset.
1461                  */
1462                 LOG_ERROR("Trying to use configured scan chain anyway...");
1463                 issue_setup = false;
1464                 break;
1465         }
1466
1467         /* Now look at IR values.  Problems here will prevent real
1468          * communication.  They mostly mean that the IR length is
1469          * wrong ... or that the IR capture value is wrong.  (The
1470          * latter is uncommon, but easily worked around:  provide
1471          * ircapture/irmask values during TAP setup.)
1472          */
1473         retval = jtag_validate_ircapture();
1474         if (retval != ERROR_OK)
1475         {
1476                 /* The target might be powered down. The user
1477                  * can power it up and reset it after firing
1478                  * up OpenOCD.
1479                  */
1480                 issue_setup = false;
1481         }
1482
1483         if (issue_setup)
1484                 jtag_notify_event(JTAG_TAP_EVENT_SETUP);
1485         else
1486                 LOG_WARNING("Bypassing JTAG setup events due to errors");
1487
1488
1489         return ERROR_OK;
1490 }
1491
1492 int adapter_quit(void)
1493 {
1494         if (!jtag || !jtag->quit)
1495                 return ERROR_OK;
1496
1497         // close the JTAG interface
1498         int result = jtag->quit();
1499         if (ERROR_OK != result)
1500                 LOG_ERROR("failed: %d", result);
1501
1502         return ERROR_OK;
1503 }
1504
1505
1506 int jtag_init_reset(struct command_context *cmd_ctx)
1507 {
1508         int retval;
1509
1510         if ((retval = adapter_init(cmd_ctx)) != ERROR_OK)
1511                 return retval;
1512
1513         LOG_DEBUG("Initializing with hard TRST+SRST reset");
1514
1515         /*
1516          * This procedure is used by default when OpenOCD triggers a reset.
1517          * It's now done through an overridable Tcl "init_reset" wrapper.
1518          *
1519          * This started out as a more powerful "get JTAG working" reset than
1520          * jtag_init_inner(), applying TRST because some chips won't activate
1521          * JTAG without a TRST cycle (presumed to be async, though some of
1522          * those chips synchronize JTAG activation using TCK).
1523          *
1524          * But some chips only activate JTAG as part of an SRST cycle; SRST
1525          * got mixed in.  So it became a hard reset routine, which got used
1526          * in more places, and which coped with JTAG reset being forced as
1527          * part of SRST (srst_pulls_trst).
1528          *
1529          * And even more corner cases started to surface:  TRST and/or SRST
1530          * assertion timings matter; some chips need other JTAG operations;
1531          * TRST/SRST sequences can need to be different from these, etc.
1532          *
1533          * Systems should override that wrapper to support system-specific
1534          * requirements that this not-fully-generic code doesn't handle.
1535          *
1536          * REVISIT once Tcl code can read the reset_config modes, this won't
1537          * need to be a C routine at all...
1538          */
1539         jtag_add_reset(1, 0); /* TAP_RESET, using TMS+TCK or TRST */
1540         if (jtag_reset_config & RESET_HAS_SRST)
1541         {
1542                 jtag_add_reset(1, 1);
1543                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) == 0)
1544                         jtag_add_reset(0, 1);
1545         }
1546         jtag_add_reset(0, 0);
1547         if ((retval = jtag_execute_queue()) != ERROR_OK)
1548                 return retval;
1549
1550         /* Check that we can communication on the JTAG chain + eventually we want to
1551          * be able to perform enumeration only after OpenOCD has started
1552          * telnet and GDB server
1553          *
1554          * That would allow users to more easily perform any magic they need to before
1555          * reset happens.
1556          */
1557         return jtag_init_inner(cmd_ctx);
1558 }
1559
1560 int jtag_init(struct command_context *cmd_ctx)
1561 {
1562         int retval;
1563
1564         if ((retval = adapter_init(cmd_ctx)) != ERROR_OK)
1565                 return retval;
1566
1567         /* guard against oddball hardware: force resets to be inactive */
1568         jtag_add_reset(0, 0);
1569         if ((retval = jtag_execute_queue()) != ERROR_OK)
1570                 return retval;
1571
1572         if (Jim_Eval_Named(cmd_ctx->interp, "jtag_init", __FILE__, __LINE__) != JIM_OK)
1573                 return ERROR_FAIL;
1574
1575         return ERROR_OK;
1576 }
1577
1578 unsigned jtag_get_speed_khz(void)
1579 {
1580         return speed_khz;
1581 }
1582
1583 static int adapter_khz_to_speed(unsigned khz, int* speed)
1584 {
1585         LOG_DEBUG("convert khz to interface specific speed value");
1586         speed_khz = khz;
1587         if (jtag != NULL)
1588         {
1589                 LOG_DEBUG("have interface set up");
1590                 int speed_div1;
1591                 int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1592                 if (ERROR_OK != retval)
1593                 {
1594                         return retval;
1595                 }
1596                 *speed = speed_div1;
1597         }
1598         return ERROR_OK;
1599 }
1600
1601 static int jtag_rclk_to_speed(unsigned fallback_speed_khz, int* speed)
1602 {
1603         int retval = adapter_khz_to_speed(0, speed);
1604         if ((ERROR_OK != retval) && fallback_speed_khz)
1605         {
1606                 LOG_DEBUG("trying fallback speed...");
1607                 retval = adapter_khz_to_speed(fallback_speed_khz, speed);
1608         }
1609         return retval;
1610 }
1611
1612 static int jtag_set_speed(int speed)
1613 {
1614         jtag_speed = speed;
1615         /* this command can be called during CONFIG,
1616          * in which case jtag isn't initialized */
1617         return jtag ? jtag->speed(speed) : ERROR_OK;
1618 }
1619
1620 int jtag_config_khz(unsigned khz)
1621 {
1622         LOG_DEBUG("handle jtag khz");
1623         clock_mode = CLOCK_MODE_KHZ;
1624         int speed = 0;
1625         int retval = adapter_khz_to_speed(khz, &speed);
1626         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1627 }
1628
1629 int jtag_config_rclk(unsigned fallback_speed_khz)
1630 {
1631         LOG_DEBUG("handle jtag rclk");
1632         clock_mode = CLOCK_MODE_RCLK;
1633         rclk_fallback_speed_khz = fallback_speed_khz;
1634         int speed = 0;
1635         int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1636         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1637 }
1638
1639 int jtag_get_speed(int *speed)
1640 {
1641         switch(clock_mode)
1642         {
1643                 case CLOCK_MODE_SPEED:
1644                         *speed = jtag_speed;
1645                         break;
1646                 case CLOCK_MODE_KHZ:
1647                         adapter_khz_to_speed(jtag_get_speed_khz(), speed);
1648                         break;
1649                 case CLOCK_MODE_RCLK:
1650                         jtag_rclk_to_speed(rclk_fallback_speed_khz, speed);
1651                         break;
1652                 default:
1653                         LOG_ERROR("BUG: unknown jtag clock mode");
1654                         return ERROR_FAIL;
1655         }
1656         return ERROR_OK;
1657 }
1658
1659 int jtag_get_speed_readable(int *khz)
1660 {
1661         int jtag_speed_var;
1662         int retval = jtag_get_speed(&jtag_speed_var);
1663         if (retval != ERROR_OK)
1664                 return retval;
1665         return jtag ? jtag->speed_div(jtag_speed_var, khz) : ERROR_OK;
1666 }
1667
1668 void jtag_set_verify(bool enable)
1669 {
1670         jtag_verify = enable;
1671 }
1672
1673 bool jtag_will_verify()
1674 {
1675         return jtag_verify;
1676 }
1677
1678 void jtag_set_verify_capture_ir(bool enable)
1679 {
1680         jtag_verify_capture_ir = enable;
1681 }
1682
1683 bool jtag_will_verify_capture_ir()
1684 {
1685         return jtag_verify_capture_ir;
1686 }
1687
1688 int jtag_power_dropout(int *dropout)
1689 {
1690         if (jtag == NULL)
1691         {
1692                 /* TODO: as the jtag interface is not valid all
1693                  * we can do at the moment is exit OpenOCD */
1694                 LOG_ERROR("No Valid JTAG Interface Configured.");
1695                 exit(-1);
1696         }
1697         return jtag->power_dropout(dropout);
1698 }
1699
1700 int jtag_srst_asserted(int *srst_asserted)
1701 {
1702         return jtag->srst_asserted(srst_asserted);
1703 }
1704
1705 enum reset_types jtag_get_reset_config(void)
1706 {
1707         return jtag_reset_config;
1708 }
1709 void jtag_set_reset_config(enum reset_types type)
1710 {
1711         jtag_reset_config = type;
1712 }
1713
1714 int jtag_get_trst(void)
1715 {
1716         return jtag_trst;
1717 }
1718 int jtag_get_srst(void)
1719 {
1720         return jtag_srst;
1721 }
1722
1723 void jtag_set_nsrst_delay(unsigned delay)
1724 {
1725         adapter_nsrst_delay = delay;
1726 }
1727 unsigned jtag_get_nsrst_delay(void)
1728 {
1729         return adapter_nsrst_delay;
1730 }
1731 void jtag_set_ntrst_delay(unsigned delay)
1732 {
1733         jtag_ntrst_delay = delay;
1734 }
1735 unsigned jtag_get_ntrst_delay(void)
1736 {
1737         return jtag_ntrst_delay;
1738 }
1739
1740
1741 void jtag_set_nsrst_assert_width(unsigned delay)
1742 {
1743         adapter_nsrst_assert_width = delay;
1744 }
1745 unsigned jtag_get_nsrst_assert_width(void)
1746 {
1747         return adapter_nsrst_assert_width;
1748 }
1749 void jtag_set_ntrst_assert_width(unsigned delay)
1750 {
1751         jtag_ntrst_assert_width = delay;
1752 }
1753 unsigned jtag_get_ntrst_assert_width(void)
1754 {
1755         return jtag_ntrst_assert_width;
1756 }
1757
1758 static int jtag_select(struct command_context *ctx)
1759 {
1760         int retval;
1761
1762         /* NOTE:  interface init must already have been done.
1763          * That works with only C code ... no Tcl glue required.
1764          */
1765
1766         retval = jtag_register_commands(ctx);
1767
1768         if (retval != ERROR_OK)
1769                 return retval;
1770
1771         retval = svf_register_commands(ctx);
1772
1773         if (retval != ERROR_OK)
1774                 return retval;
1775
1776         return xsvf_register_commands(ctx);
1777 }
1778
1779 static struct transport jtag_transport = {
1780         .name = "jtag",
1781         .select = jtag_select,
1782         .init = jtag_init,
1783 };
1784
1785 static void jtag_constructor(void) __attribute__((constructor));
1786 static void jtag_constructor(void)
1787 {
1788         transport_register(&jtag_transport);
1789 }
1790
1791 /** Returns true if the current debug session
1792  * is using JTAG as its transport.
1793  */
1794 bool transport_is_jtag(void)
1795 {
1796         return get_current_transport() == &jtag_transport;
1797 }