cmsis-dap: add initial cmsis-dap support
[fw/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  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
29  ***************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include "jtag.h"
36 #include "swd.h"
37 #include "interface.h"
38 #include <transport/transport.h>
39
40 #ifdef HAVE_STRINGS_H
41 #include <strings.h>
42 #endif
43
44 /* SVF and XSVF are higher level JTAG command sets (for boundary scan) */
45 #include "svf/svf.h"
46 #include "xsvf/xsvf.h"
47
48 /** The number of JTAG queue flushes (for profiling and debugging purposes). */
49 static int jtag_flush_queue_count;
50
51 /* Sleep this # of ms after flushing the queue */
52 static int jtag_flush_queue_sleep;
53
54 static void jtag_add_scan_check(struct jtag_tap *active,
55                 void (*jtag_add_scan)(struct jtag_tap *active,
56                 int in_num_fields,
57                 const struct scan_field *in_fields,
58                 tap_state_t state),
59                 int in_num_fields, struct scan_field *in_fields, tap_state_t state);
60
61 /**
62  * The jtag_error variable is set when an error occurs while executing
63  * the queue.  Application code may set this using jtag_set_error(),
64  * when an error occurs during processing that should be reported during
65  * jtag_execute_queue().
66  *
67  * The value is set and cleared, but never read by normal application code.
68  *
69  * This value is returned (and cleared) by jtag_execute_queue().
70  */
71 static int jtag_error = ERROR_OK;
72
73 static const char *jtag_event_strings[] = {
74         [JTAG_TRST_ASSERTED] = "TAP reset",
75         [JTAG_TAP_EVENT_SETUP] = "TAP setup",
76         [JTAG_TAP_EVENT_ENABLE] = "TAP enabled",
77         [JTAG_TAP_EVENT_DISABLE] = "TAP disabled",
78 };
79
80 /*
81  * JTAG adapters must initialize with TRST and SRST de-asserted
82  * (they're negative logic, so that means *high*).  But some
83  * hardware doesn't necessarily work that way ... so set things
84  * up so that jtag_init() always forces that state.
85  */
86 static int jtag_trst = -1;
87 static int jtag_srst = -1;
88
89 /**
90  * List all TAPs that have been created.
91  */
92 static struct jtag_tap *__jtag_all_taps;
93 /**
94  * The number of TAPs in the __jtag_all_taps list, used to track the
95  * assigned chain position to new TAPs
96  */
97 static unsigned jtag_num_taps;
98
99 static enum reset_types jtag_reset_config = RESET_NONE;
100 tap_state_t cmd_queue_cur_state = TAP_RESET;
101
102 static bool jtag_verify_capture_ir = true;
103 static int jtag_verify = 1;
104
105 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines
106  *deasserted (in ms) */
107 static int adapter_nsrst_delay; /* default to no nSRST delay */
108 static int jtag_ntrst_delay;/* default to no nTRST delay */
109 static int adapter_nsrst_assert_width;  /* width of assertion */
110 static int jtag_ntrst_assert_width;     /* width of assertion */
111
112 /**
113  * Contains a single callback along with a pointer that will be passed
114  * when an event occurs.
115  */
116 struct jtag_event_callback {
117         /** a event callback */
118         jtag_event_handler_t callback;
119         /** the private data to pass to the callback */
120         void *priv;
121         /** the next callback */
122         struct jtag_event_callback *next;
123 };
124
125 /* callbacks to inform high-level handlers about JTAG state changes */
126 static struct jtag_event_callback *jtag_event_callbacks;
127
128 /* speed in kHz*/
129 static int speed_khz;
130 /* speed to fallback to when RCLK is requested but not supported */
131 static int rclk_fallback_speed_khz;
132 static enum {CLOCK_MODE_UNSELECTED, CLOCK_MODE_KHZ, CLOCK_MODE_RCLK} clock_mode;
133 static int jtag_speed;
134
135 static struct jtag_interface *jtag;
136
137 /* configuration */
138 struct jtag_interface *jtag_interface;
139
140 void jtag_set_flush_queue_sleep(int ms)
141 {
142         jtag_flush_queue_sleep = ms;
143 }
144
145 void jtag_set_error(int error)
146 {
147         if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
148                 return;
149         jtag_error = error;
150 }
151
152 int jtag_error_clear(void)
153 {
154         int temp = jtag_error;
155         jtag_error = ERROR_OK;
156         return temp;
157 }
158
159 /************/
160
161 static bool jtag_poll = 1;
162
163 bool is_jtag_poll_safe(void)
164 {
165         /* Polling can be disabled explicitly with set_enabled(false).
166          * It is also implicitly disabled while TRST is active and
167          * while SRST is gating the JTAG clock.
168          */
169         if (!jtag_poll || jtag_trst != 0)
170                 return false;
171         return jtag_srst == 0 || (jtag_reset_config & RESET_SRST_NO_GATING);
172 }
173
174 bool jtag_poll_get_enabled(void)
175 {
176         return jtag_poll;
177 }
178
179 void jtag_poll_set_enabled(bool value)
180 {
181         jtag_poll = value;
182 }
183
184 /************/
185
186 struct jtag_tap *jtag_all_taps(void)
187 {
188         return __jtag_all_taps;
189 };
190
191 unsigned jtag_tap_count(void)
192 {
193         return jtag_num_taps;
194 }
195
196 unsigned jtag_tap_count_enabled(void)
197 {
198         struct jtag_tap *t = jtag_all_taps();
199         unsigned n = 0;
200         while (t) {
201                 if (t->enabled)
202                         n++;
203                 t = t->next_tap;
204         }
205         return n;
206 }
207
208 /** Append a new TAP to the chain of all taps. */
209 void jtag_tap_add(struct jtag_tap *t)
210 {
211         t->abs_chain_position = jtag_num_taps++;
212
213         struct jtag_tap **tap = &__jtag_all_taps;
214         while (*tap != NULL)
215                 tap = &(*tap)->next_tap;
216         *tap = t;
217 }
218
219 /* returns a pointer to the n-th device in the scan chain */
220 struct jtag_tap *jtag_tap_by_position(unsigned n)
221 {
222         struct jtag_tap *t = jtag_all_taps();
223
224         while (t && n-- > 0)
225                 t = t->next_tap;
226
227         return t;
228 }
229
230 struct jtag_tap *jtag_tap_by_string(const char *s)
231 {
232         /* try by name first */
233         struct jtag_tap *t = jtag_all_taps();
234
235         while (t) {
236                 if (0 == strcmp(t->dotted_name, s))
237                         return t;
238                 t = t->next_tap;
239         }
240
241         /* no tap found by name, so try to parse the name as a number */
242         unsigned n;
243         if (parse_uint(s, &n) != ERROR_OK)
244                 return NULL;
245
246         /* FIXME remove this numeric fallback code late June 2010, along
247          * with all info in the User's Guide that TAPs have numeric IDs.
248          * Also update "scan_chain" output to not display the numbers.
249          */
250         t = jtag_tap_by_position(n);
251         if (t)
252                 LOG_WARNING("Specify TAP '%s' by name, not number %u",
253                         t->dotted_name, n);
254
255         return t;
256 }
257
258 struct jtag_tap *jtag_tap_next_enabled(struct jtag_tap *p)
259 {
260         p = p ? p->next_tap : jtag_all_taps();
261         while (p) {
262                 if (p->enabled)
263                         return p;
264                 p = p->next_tap;
265         }
266         return NULL;
267 }
268
269 const char *jtag_tap_name(const struct jtag_tap *tap)
270 {
271         return (tap == NULL) ? "(unknown)" : tap->dotted_name;
272 }
273
274
275 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
276 {
277         struct jtag_event_callback **callbacks_p = &jtag_event_callbacks;
278
279         if (callback == NULL)
280                 return ERROR_COMMAND_SYNTAX_ERROR;
281
282         if (*callbacks_p) {
283                 while ((*callbacks_p)->next)
284                         callbacks_p = &((*callbacks_p)->next);
285                 callbacks_p = &((*callbacks_p)->next);
286         }
287
288         (*callbacks_p) = malloc(sizeof(struct jtag_event_callback));
289         (*callbacks_p)->callback = callback;
290         (*callbacks_p)->priv = priv;
291         (*callbacks_p)->next = NULL;
292
293         return ERROR_OK;
294 }
295
296 int jtag_unregister_event_callback(jtag_event_handler_t callback, void *priv)
297 {
298         struct jtag_event_callback **p = &jtag_event_callbacks, *temp;
299
300         if (callback == NULL)
301                 return ERROR_COMMAND_SYNTAX_ERROR;
302
303         while (*p) {
304                 if (((*p)->priv != priv) || ((*p)->callback != callback)) {
305                         p = &(*p)->next;
306                         continue;
307                 }
308
309                 temp = *p;
310                 *p = (*p)->next;
311                 free(temp);
312         }
313
314         return ERROR_OK;
315 }
316
317 int jtag_call_event_callbacks(enum jtag_event event)
318 {
319         struct jtag_event_callback *callback = jtag_event_callbacks;
320
321         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
322
323         while (callback) {
324                 struct jtag_event_callback *next;
325
326                 /* callback may remove itself */
327                 next = callback->next;
328                 callback->callback(event, callback->priv);
329                 callback = next;
330         }
331
332         return ERROR_OK;
333 }
334
335 static void jtag_checks(void)
336 {
337         assert(jtag_trst == 0);
338 }
339
340 static void jtag_prelude(tap_state_t state)
341 {
342         jtag_checks();
343
344         assert(state != TAP_INVALID);
345
346         cmd_queue_cur_state = state;
347 }
348
349 void jtag_add_ir_scan_noverify(struct jtag_tap *active, const struct scan_field *in_fields,
350         tap_state_t state)
351 {
352         jtag_prelude(state);
353
354         int retval = interface_jtag_add_ir_scan(active, in_fields, state);
355         jtag_set_error(retval);
356 }
357
358 static void jtag_add_ir_scan_noverify_callback(struct jtag_tap *active,
359         int dummy,
360         const struct scan_field *in_fields,
361         tap_state_t state)
362 {
363         jtag_add_ir_scan_noverify(active, in_fields, state);
364 }
365
366 /* If fields->in_value is filled out, then the captured IR value will be checked */
367 void jtag_add_ir_scan(struct jtag_tap *active, struct scan_field *in_fields, tap_state_t state)
368 {
369         assert(state != TAP_RESET);
370
371         if (jtag_verify && jtag_verify_capture_ir) {
372                 /* 8 x 32 bit id's is enough for all invocations */
373
374                 /* if we are to run a verification of the ir scan, we need to get the input back.
375                  * We may have to allocate space if the caller didn't ask for the input back.
376                  */
377                 in_fields->check_value = active->expected;
378                 in_fields->check_mask = active->expected_mask;
379                 jtag_add_scan_check(active, jtag_add_ir_scan_noverify_callback, 1, in_fields,
380                         state);
381         } else
382                 jtag_add_ir_scan_noverify(active, in_fields, state);
383 }
384
385 void jtag_add_plain_ir_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
386         tap_state_t state)
387 {
388         assert(out_bits != NULL);
389         assert(state != TAP_RESET);
390
391         jtag_prelude(state);
392
393         int retval = interface_jtag_add_plain_ir_scan(
394                         num_bits, out_bits, in_bits, state);
395         jtag_set_error(retval);
396 }
397
398 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
399                                   uint8_t *in_check_mask, int num_bits);
400
401 static int jtag_check_value_mask_callback(jtag_callback_data_t data0,
402         jtag_callback_data_t data1,
403         jtag_callback_data_t data2,
404         jtag_callback_data_t data3)
405 {
406         return jtag_check_value_inner((uint8_t *)data0,
407                 (uint8_t *)data1,
408                 (uint8_t *)data2,
409                 (int)data3);
410 }
411
412 static void jtag_add_scan_check(struct jtag_tap *active, void (*jtag_add_scan)(
413                 struct jtag_tap *active,
414                 int in_num_fields,
415                 const struct scan_field *in_fields,
416                 tap_state_t state),
417         int in_num_fields, struct scan_field *in_fields, tap_state_t state)
418 {
419         jtag_add_scan(active, in_num_fields, in_fields, state);
420
421         for (int i = 0; i < in_num_fields; i++) {
422                 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL)) {
423                         /* this is synchronous for a minidriver */
424                         jtag_add_callback4(jtag_check_value_mask_callback,
425                                 (jtag_callback_data_t)in_fields[i].in_value,
426                                 (jtag_callback_data_t)in_fields[i].check_value,
427                                 (jtag_callback_data_t)in_fields[i].check_mask,
428                                 (jtag_callback_data_t)in_fields[i].num_bits);
429                 }
430         }
431 }
432
433 void jtag_add_dr_scan_check(struct jtag_tap *active,
434         int in_num_fields,
435         struct scan_field *in_fields,
436         tap_state_t state)
437 {
438         if (jtag_verify)
439                 jtag_add_scan_check(active, jtag_add_dr_scan, in_num_fields, in_fields, state);
440         else
441                 jtag_add_dr_scan(active, in_num_fields, in_fields, state);
442 }
443
444
445 void jtag_add_dr_scan(struct jtag_tap *active,
446         int in_num_fields,
447         const struct scan_field *in_fields,
448         tap_state_t state)
449 {
450         assert(state != TAP_RESET);
451
452         jtag_prelude(state);
453
454         int retval;
455         retval = interface_jtag_add_dr_scan(active, in_num_fields, in_fields, state);
456         jtag_set_error(retval);
457 }
458
459 void jtag_add_plain_dr_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
460         tap_state_t state)
461 {
462         assert(out_bits != NULL);
463         assert(state != TAP_RESET);
464
465         jtag_prelude(state);
466
467         int retval;
468         retval = interface_jtag_add_plain_dr_scan(num_bits, out_bits, in_bits, state);
469         jtag_set_error(retval);
470 }
471
472 void jtag_add_tlr(void)
473 {
474         jtag_prelude(TAP_RESET);
475         jtag_set_error(interface_jtag_add_tlr());
476
477         /* NOTE: order here matches TRST path in jtag_add_reset() */
478         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
479         jtag_notify_event(JTAG_TRST_ASSERTED);
480 }
481
482 /**
483  * If supported by the underlying adapter, this clocks a raw bit sequence
484  * onto TMS for switching betwen JTAG and SWD modes.
485  *
486  * DO NOT use this to bypass the integrity checks and logging provided
487  * by the jtag_add_pathmove() and jtag_add_statemove() calls.
488  *
489  * @param nbits How many bits to clock out.
490  * @param seq The bit sequence.  The LSB is bit 0 of seq[0].
491  * @param state The JTAG tap state to record on completion.  Use
492  *      TAP_INVALID to represent being in in SWD mode.
493  *
494  * @todo Update naming conventions to stop assuming everything is JTAG.
495  */
496 int jtag_add_tms_seq(unsigned nbits, const uint8_t *seq, enum tap_state state)
497 {
498         int retval;
499
500         if (!(jtag->supported & DEBUG_CAP_TMS_SEQ))
501                 return ERROR_JTAG_NOT_IMPLEMENTED;
502
503         jtag_checks();
504         cmd_queue_cur_state = state;
505
506         retval = interface_add_tms_seq(nbits, seq, state);
507         jtag_set_error(retval);
508         return retval;
509 }
510
511 void jtag_add_pathmove(int num_states, const tap_state_t *path)
512 {
513         tap_state_t cur_state = cmd_queue_cur_state;
514
515         /* the last state has to be a stable state */
516         if (!tap_is_state_stable(path[num_states - 1])) {
517                 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
518                 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
519                 return;
520         }
521
522         for (int i = 0; i < num_states; i++) {
523                 if (path[i] == TAP_RESET) {
524                         LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
525                         jtag_set_error(ERROR_JTAG_STATE_INVALID);
526                         return;
527                 }
528
529                 if (tap_state_transition(cur_state, true) != path[i] &&
530                                 tap_state_transition(cur_state, false) != path[i]) {
531                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
532                                 tap_state_name(cur_state), tap_state_name(path[i]));
533                         jtag_set_error(ERROR_JTAG_TRANSITION_INVALID);
534                         return;
535                 }
536                 cur_state = path[i];
537         }
538
539         jtag_checks();
540
541         jtag_set_error(interface_jtag_add_pathmove(num_states, path));
542         cmd_queue_cur_state = path[num_states - 1];
543 }
544
545 int jtag_add_statemove(tap_state_t goal_state)
546 {
547         tap_state_t cur_state = cmd_queue_cur_state;
548
549         if (goal_state != cur_state) {
550                 LOG_DEBUG("cur_state=%s goal_state=%s",
551                         tap_state_name(cur_state),
552                         tap_state_name(goal_state));
553         }
554
555         /* If goal is RESET, be paranoid and force that that transition
556          * (e.g. five TCK cycles, TMS high).  Else trust "cur_state".
557          */
558         if (goal_state == TAP_RESET)
559                 jtag_add_tlr();
560         else if (goal_state == cur_state)
561                 /* nothing to do */;
562
563         else if (tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state)) {
564                 unsigned tms_bits  = tap_get_tms_path(cur_state, goal_state);
565                 unsigned tms_count = tap_get_tms_path_len(cur_state, goal_state);
566                 tap_state_t moves[8];
567                 assert(tms_count < ARRAY_SIZE(moves));
568
569                 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1) {
570                         bool bit = tms_bits & 1;
571
572                         cur_state = tap_state_transition(cur_state, bit);
573                         moves[i] = cur_state;
574                 }
575
576                 jtag_add_pathmove(tms_count, moves);
577         } else if (tap_state_transition(cur_state, true)  == goal_state
578                         || tap_state_transition(cur_state, false) == goal_state)
579                 jtag_add_pathmove(1, &goal_state);
580         else
581                 return ERROR_FAIL;
582
583         return ERROR_OK;
584 }
585
586 void jtag_add_runtest(int num_cycles, tap_state_t state)
587 {
588         jtag_prelude(state);
589         jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
590 }
591
592
593 void jtag_add_clocks(int num_cycles)
594 {
595         if (!tap_is_state_stable(cmd_queue_cur_state)) {
596                 LOG_ERROR("jtag_add_clocks() called with TAP in unstable state \"%s\"",
597                         tap_state_name(cmd_queue_cur_state));
598                 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
599                 return;
600         }
601
602         if (num_cycles > 0) {
603                 jtag_checks();
604                 jtag_set_error(interface_jtag_add_clocks(num_cycles));
605         }
606 }
607
608 void swd_add_reset(int req_srst)
609 {
610         if (req_srst) {
611                 if (!(jtag_reset_config & RESET_HAS_SRST)) {
612                         LOG_ERROR("BUG: can't assert SRST");
613                         jtag_set_error(ERROR_FAIL);
614                         return;
615                 }
616                 req_srst = 1;
617         }
618
619         /* Maybe change SRST signal state */
620         if (jtag_srst != req_srst) {
621                 int retval;
622
623                 retval = interface_jtag_add_reset(0, req_srst);
624                 if (retval != ERROR_OK)
625                         jtag_set_error(retval);
626                 else
627                         retval = jtag_execute_queue();
628
629                 if (retval != ERROR_OK) {
630                         LOG_ERROR("TRST/SRST error");
631                         return;
632                 }
633
634                 /* SRST resets everything hooked up to that signal */
635                 jtag_srst = req_srst;
636                 if (jtag_srst) {
637                         LOG_DEBUG("SRST line asserted");
638                         if (adapter_nsrst_assert_width)
639                                 jtag_add_sleep(adapter_nsrst_assert_width * 1000);
640                 } else {
641                         LOG_DEBUG("SRST line released");
642                         if (adapter_nsrst_delay)
643                                 jtag_add_sleep(adapter_nsrst_delay * 1000);
644                 }
645         }
646 }
647
648 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
649 {
650         int trst_with_tlr = 0;
651         int new_srst = 0;
652         int new_trst = 0;
653
654         /* Without SRST, we must use target-specific JTAG operations
655          * on each target; callers should not be requesting SRST when
656          * that signal doesn't exist.
657          *
658          * RESET_SRST_PULLS_TRST is a board or chip level quirk, which
659          * can kick in even if the JTAG adapter can't drive TRST.
660          */
661         if (req_srst) {
662                 if (!(jtag_reset_config & RESET_HAS_SRST)) {
663                         LOG_ERROR("BUG: can't assert SRST");
664                         jtag_set_error(ERROR_FAIL);
665                         return;
666                 }
667                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) != 0
668                                 && !req_tlr_or_trst) {
669                         LOG_ERROR("BUG: can't assert only SRST");
670                         jtag_set_error(ERROR_FAIL);
671                         return;
672                 }
673                 new_srst = 1;
674         }
675
676         /* JTAG reset (entry to TAP_RESET state) can always be achieved
677          * using TCK and TMS; that may go through a TAP_{IR,DR}UPDATE
678          * state first.  TRST accelerates it, and bypasses those states.
679          *
680          * RESET_TRST_PULLS_SRST is a board or chip level quirk, which
681          * can kick in even if the JTAG adapter can't drive SRST.
682          */
683         if (req_tlr_or_trst) {
684                 if (!(jtag_reset_config & RESET_HAS_TRST))
685                         trst_with_tlr = 1;
686                 else if ((jtag_reset_config & RESET_TRST_PULLS_SRST) != 0
687                          && !req_srst)
688                         trst_with_tlr = 1;
689                 else
690                         new_trst = 1;
691         }
692
693         /* Maybe change TRST and/or SRST signal state */
694         if (jtag_srst != new_srst || jtag_trst != new_trst) {
695                 int retval;
696
697                 retval = interface_jtag_add_reset(new_trst, new_srst);
698                 if (retval != ERROR_OK)
699                         jtag_set_error(retval);
700                 else
701                         retval = jtag_execute_queue();
702
703                 if (retval != ERROR_OK) {
704                         LOG_ERROR("TRST/SRST error");
705                         return;
706                 }
707         }
708
709         /* SRST resets everything hooked up to that signal */
710         if (jtag_srst != new_srst) {
711                 jtag_srst = new_srst;
712                 if (jtag_srst) {
713                         LOG_DEBUG("SRST line asserted");
714                         if (adapter_nsrst_assert_width)
715                                 jtag_add_sleep(adapter_nsrst_assert_width * 1000);
716                 } else {
717                         LOG_DEBUG("SRST line released");
718                         if (adapter_nsrst_delay)
719                                 jtag_add_sleep(adapter_nsrst_delay * 1000);
720                 }
721         }
722
723         /* Maybe enter the JTAG TAP_RESET state ...
724          *  - using only TMS, TCK, and the JTAG state machine
725          *  - or else more directly, using TRST
726          *
727          * TAP_RESET should be invisible to non-debug parts of the system.
728          */
729         if (trst_with_tlr) {
730                 LOG_DEBUG("JTAG reset with TLR instead of TRST");
731                 jtag_add_tlr();
732
733         } else if (jtag_trst != new_trst) {
734                 jtag_trst = new_trst;
735                 if (jtag_trst) {
736                         LOG_DEBUG("TRST line asserted");
737                         tap_set_state(TAP_RESET);
738                         if (jtag_ntrst_assert_width)
739                                 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
740                 } else {
741                         LOG_DEBUG("TRST line released");
742                         if (jtag_ntrst_delay)
743                                 jtag_add_sleep(jtag_ntrst_delay * 1000);
744
745                         /* We just asserted nTRST, so we're now in TAP_RESET.
746                          * Inform possible listeners about this, now that
747                          * JTAG instructions and data can be shifted.  This
748                          * sequence must match jtag_add_tlr().
749                          */
750                         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
751                         jtag_notify_event(JTAG_TRST_ASSERTED);
752                 }
753         }
754 }
755
756 void jtag_add_sleep(uint32_t us)
757 {
758         /** @todo Here, keep_alive() appears to be a layering violation!!! */
759         keep_alive();
760         jtag_set_error(interface_jtag_add_sleep(us));
761 }
762
763 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
764         uint8_t *in_check_mask, int num_bits)
765 {
766         int retval = ERROR_OK;
767         int compare_failed;
768
769         if (in_check_mask)
770                 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
771         else
772                 compare_failed = buf_cmp(captured, in_check_value, num_bits);
773
774         if (compare_failed) {
775                 char *captured_str, *in_check_value_str;
776                 int bits = (num_bits > DEBUG_JTAG_IOZ) ? DEBUG_JTAG_IOZ : num_bits;
777
778                 /* NOTE:  we've lost diagnostic context here -- 'which tap' */
779
780                 captured_str = buf_to_str(captured, bits, 16);
781                 in_check_value_str = buf_to_str(in_check_value, bits, 16);
782
783                 LOG_WARNING("Bad value '%s' captured during DR or IR scan:",
784                         captured_str);
785                 LOG_WARNING(" check_value: 0x%s", in_check_value_str);
786
787                 free(captured_str);
788                 free(in_check_value_str);
789
790                 if (in_check_mask) {
791                         char *in_check_mask_str;
792
793                         in_check_mask_str = buf_to_str(in_check_mask, bits, 16);
794                         LOG_WARNING(" check_mask: 0x%s", in_check_mask_str);
795                         free(in_check_mask_str);
796                 }
797
798                 retval = ERROR_JTAG_QUEUE_FAILED;
799         }
800         return retval;
801 }
802
803 void jtag_check_value_mask(struct scan_field *field, uint8_t *value, uint8_t *mask)
804 {
805         assert(field->in_value != NULL);
806
807         if (value == NULL) {
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 int default_interface_jtag_execute_queue(void)
819 {
820         if (NULL == jtag) {
821                 LOG_ERROR("No JTAG interface configured yet.  "
822                         "Issue 'init' command in startup scripts "
823                         "before communicating with targets.");
824                 return ERROR_FAIL;
825         }
826
827         return jtag->execute_queue();
828 }
829
830 void jtag_execute_queue_noclear(void)
831 {
832         jtag_flush_queue_count++;
833         jtag_set_error(interface_jtag_execute_queue());
834
835         if (jtag_flush_queue_sleep > 0) {
836                 /* For debug purposes it can be useful to test performance
837                  * or behavior when delaying after flushing the queue,
838                  * e.g. to simulate long roundtrip times.
839                  */
840                 usleep(jtag_flush_queue_sleep * 1000);
841         }
842 }
843
844 int jtag_get_flush_queue_count(void)
845 {
846         return jtag_flush_queue_count;
847 }
848
849 int jtag_execute_queue(void)
850 {
851         jtag_execute_queue_noclear();
852         return jtag_error_clear();
853 }
854
855 static int jtag_reset_callback(enum jtag_event event, void *priv)
856 {
857         struct jtag_tap *tap = priv;
858
859         if (event == JTAG_TRST_ASSERTED) {
860                 tap->enabled = !tap->disabled_after_reset;
861
862                 /* current instruction is either BYPASS or IDCODE */
863                 buf_set_ones(tap->cur_instr, tap->ir_length);
864                 tap->bypass = 1;
865         }
866
867         return ERROR_OK;
868 }
869
870 /* sleep at least us microseconds. When we sleep more than 1000ms we
871  * do an alive sleep, i.e. keep GDB alive. Note that we could starve
872  * GDB if we slept for <1000ms many times.
873  */
874 void jtag_sleep(uint32_t us)
875 {
876         if (us < 1000)
877                 usleep(us);
878         else
879                 alive_sleep((us+999)/1000);
880 }
881
882 /* Maximum number of enabled JTAG devices we expect in the scan chain,
883  * plus one (to detect garbage at the end).  Devices that don't support
884  * IDCODE take up fewer bits, possibly allowing a few more devices.
885  */
886 #define JTAG_MAX_CHAIN_SIZE 20
887
888 #define EXTRACT_MFG(X)  (((X) & 0xffe) >> 1)
889 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
890 #define EXTRACT_VER(X)  (((X) & 0xf0000000) >> 28)
891
892 /* A reserved manufacturer ID is used in END_OF_CHAIN_FLAG, so we
893  * know that no valid TAP will have it as an IDCODE value.
894  */
895 #define END_OF_CHAIN_FLAG       0xffffffff
896
897 /* a larger IR length than we ever expect to autoprobe */
898 #define JTAG_IRLEN_MAX          60
899
900 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
901 {
902         struct scan_field field = {
903                 .num_bits = num_idcode * 32,
904                 .out_value = idcode_buffer,
905                 .in_value = idcode_buffer,
906         };
907
908         /* initialize to the end of chain ID value */
909         for (unsigned i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
910                 buf_set_u32(idcode_buffer, i * 32, 32, END_OF_CHAIN_FLAG);
911
912         jtag_add_plain_dr_scan(field.num_bits, field.out_value, field.in_value, TAP_DRPAUSE);
913         jtag_add_tlr();
914         return jtag_execute_queue();
915 }
916
917 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
918 {
919         uint8_t zero_check = 0x0;
920         uint8_t one_check = 0xff;
921
922         for (unsigned i = 0; i < count * 4; i++) {
923                 zero_check |= idcodes[i];
924                 one_check &= idcodes[i];
925         }
926
927         /* if there wasn't a single non-zero bit or if all bits were one,
928          * the scan is not valid.  We wrote a mix of both values; either
929          *
930          *  - There's a hardware issue (almost certainly):
931          *     + all-zeroes can mean a target stuck in JTAG reset
932          *     + all-ones tends to mean no target
933          *  - The scan chain is WAY longer than we can handle, *AND* either
934          *     + there are several hundreds of TAPs in bypass, or
935          *     + at least a few dozen TAPs all have an all-ones IDCODE
936          */
937         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;
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__, __func__,
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;
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                 uint32_t idcode = buf_get_u32(idcodes, count, 32);
981
982                 /* do not trigger the warning if the data looks good */
983                 if (jtag_idcode_is_final(idcode))
984                         continue;
985                 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
986                         count, (unsigned int)idcode);
987                 triggered = true;
988         }
989         return triggered;
990 }
991
992 static bool jtag_examine_chain_match_tap(const struct jtag_tap *tap)
993 {
994         uint32_t idcode = tap->idcode;
995
996         /* ignore expected BYPASS codes; warn otherwise */
997         if (0 == tap->expected_ids_cnt && !idcode)
998                 return true;
999
1000         /* optionally ignore the JTAG version field - bits 28-31 of IDCODE */
1001         uint32_t mask = tap->ignore_version ? ~(0xf << 28) : ~0;
1002
1003         idcode &= mask;
1004
1005         /* Loop over the expected identification codes and test for a match */
1006         unsigned ii, limit = tap->expected_ids_cnt;
1007
1008         for (ii = 0; ii < limit; ii++) {
1009                 uint32_t expected = tap->expected_ids[ii] & mask;
1010
1011                 if (idcode == expected)
1012                         return true;
1013
1014                 /* treat "-expected-id 0" as a "don't-warn" wildcard */
1015                 if (0 == tap->expected_ids[ii])
1016                         return true;
1017         }
1018
1019         /* If none of the expected ids matched, warn */
1020         jtag_examine_chain_display(LOG_LVL_WARNING, "UNEXPECTED",
1021                 tap->dotted_name, tap->idcode);
1022         for (ii = 0; ii < limit; ii++) {
1023                 char msg[32];
1024
1025                 snprintf(msg, sizeof(msg), "expected %u of %u", ii + 1, limit);
1026                 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
1027                         tap->dotted_name, tap->expected_ids[ii]);
1028         }
1029         return false;
1030 }
1031
1032 /* Try to examine chain layout according to IEEE 1149.1 Â§12
1033  * This is called a "blind interrogation" of the scan chain.
1034  */
1035 static int jtag_examine_chain(void)
1036 {
1037         uint8_t idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
1038         unsigned bit_count;
1039         int retval;
1040         int tapcount = 0;
1041         bool autoprobe = false;
1042
1043         /* DR scan to collect BYPASS or IDCODE register contents.
1044          * Then make sure the scan data has both ones and zeroes.
1045          */
1046         LOG_DEBUG("DR scan interrogation for IDCODE/BYPASS");
1047         retval = jtag_examine_chain_execute(idcode_buffer, JTAG_MAX_CHAIN_SIZE);
1048         if (retval != ERROR_OK)
1049                 return retval;
1050         if (!jtag_examine_chain_check(idcode_buffer, JTAG_MAX_CHAIN_SIZE))
1051                 return ERROR_JTAG_INIT_FAILED;
1052
1053         /* point at the 1st tap */
1054         struct jtag_tap *tap = jtag_tap_next_enabled(NULL);
1055
1056         if (!tap)
1057                 autoprobe = true;
1058
1059         for (bit_count = 0;
1060              tap && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;
1061              tap = jtag_tap_next_enabled(tap)) {
1062                 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1063
1064                 if ((idcode & 1) == 0) {
1065                         /* Zero for LSB indicates a device in bypass */
1066                         LOG_INFO("TAP %s does not have IDCODE",
1067                                 tap->dotted_name);
1068                         idcode = 0;
1069                         tap->hasidcode = false;
1070
1071                         bit_count += 1;
1072                 } else {
1073                         /* Friendly devices support IDCODE */
1074                         tap->hasidcode = true;
1075                         jtag_examine_chain_display(LOG_LVL_INFO,
1076                                 "tap/device found",
1077                                 tap->dotted_name, idcode);
1078
1079                         bit_count += 32;
1080                 }
1081                 tap->idcode = idcode;
1082
1083                 /* ensure the TAP ID matches what was expected */
1084                 if (!jtag_examine_chain_match_tap(tap))
1085                         retval = ERROR_JTAG_INIT_SOFT_FAIL;
1086         }
1087
1088         /* Fail if too many TAPs were enabled for us to verify them all. */
1089         if (tap) {
1090                 LOG_ERROR("Too many TAPs enabled; '%s' ignored.",
1091                         tap->dotted_name);
1092                 return ERROR_JTAG_INIT_FAILED;
1093         }
1094
1095         /* if autoprobing, the tap list is still empty ... populate it! */
1096         while (autoprobe && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31) {
1097                 uint32_t idcode;
1098                 char buf[12];
1099
1100                 /* Is there another TAP? */
1101                 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1102                 if (jtag_idcode_is_final(idcode))
1103                         break;
1104
1105                 /* Default everything in this TAP except IR length.
1106                  *
1107                  * REVISIT create a jtag_alloc(chip, tap) routine, and
1108                  * share it with jim_newtap_cmd().
1109                  */
1110                 tap = calloc(1, sizeof *tap);
1111                 if (!tap)
1112                         return ERROR_FAIL;
1113
1114                 sprintf(buf, "auto%d", tapcount++);
1115                 tap->chip = strdup(buf);
1116                 tap->tapname = strdup("tap");
1117
1118                 sprintf(buf, "%s.%s", tap->chip, tap->tapname);
1119                 tap->dotted_name = strdup(buf);
1120
1121                 /* tap->ir_length == 0 ... signifying irlen autoprobe */
1122                 tap->ir_capture_mask = 0x03;
1123                 tap->ir_capture_value = 0x01;
1124
1125                 tap->enabled = true;
1126
1127                 if ((idcode & 1) == 0) {
1128                         bit_count += 1;
1129                         tap->hasidcode = false;
1130                 } else {
1131                         bit_count += 32;
1132                         tap->hasidcode = true;
1133                         tap->idcode = idcode;
1134
1135                         tap->expected_ids_cnt = 1;
1136                         tap->expected_ids = malloc(sizeof(uint32_t));
1137                         tap->expected_ids[0] = idcode;
1138                 }
1139
1140                 LOG_WARNING("AUTO %s - use \"jtag newtap "
1141                         "%s %s -expected-id 0x%8.8" PRIx32 " ...\"",
1142                         tap->dotted_name, tap->chip, tap->tapname,
1143                         tap->idcode);
1144
1145                 jtag_tap_init(tap);
1146         }
1147
1148         /* After those IDCODE or BYPASS register values should be
1149          * only the data we fed into the scan chain.
1150          */
1151         if (jtag_examine_chain_end(idcode_buffer, bit_count,
1152                     8 * sizeof(idcode_buffer))) {
1153                 LOG_ERROR("double-check your JTAG setup (interface, "
1154                         "speed, missing TAPs, ...)");
1155                 return ERROR_JTAG_INIT_FAILED;
1156         }
1157
1158         /* Return success or, for backwards compatibility if only
1159          * some IDCODE values mismatched, a soft/continuable fault.
1160          */
1161         return retval;
1162 }
1163
1164 /*
1165  * Validate the date loaded by entry to the Capture-IR state, to help
1166  * find errors related to scan chain configuration (wrong IR lengths)
1167  * or communication.
1168  *
1169  * Entry state can be anything.  On non-error exit, all TAPs are in
1170  * bypass mode.  On error exits, the scan chain is reset.
1171  */
1172 static int jtag_validate_ircapture(void)
1173 {
1174         struct jtag_tap *tap;
1175         int total_ir_length = 0;
1176         uint8_t *ir_test = NULL;
1177         struct scan_field field;
1178         uint64_t val;
1179         int chain_pos = 0;
1180         int retval;
1181
1182         /* when autoprobing, accomodate huge IR lengths */
1183         for (tap = NULL, total_ir_length = 0;
1184                         (tap = jtag_tap_next_enabled(tap)) != NULL;
1185                         total_ir_length += tap->ir_length) {
1186                 if (tap->ir_length == 0)
1187                         total_ir_length += JTAG_IRLEN_MAX;
1188         }
1189
1190         /* increase length to add 2 bit sentinel after scan */
1191         total_ir_length += 2;
1192
1193         ir_test = malloc(DIV_ROUND_UP(total_ir_length, 8));
1194         if (ir_test == NULL)
1195                 return ERROR_FAIL;
1196
1197         /* after this scan, all TAPs will capture BYPASS instructions */
1198         buf_set_ones(ir_test, total_ir_length);
1199
1200         field.num_bits = total_ir_length;
1201         field.out_value = ir_test;
1202         field.in_value = ir_test;
1203
1204         jtag_add_plain_ir_scan(field.num_bits, field.out_value, field.in_value, TAP_IDLE);
1205
1206         LOG_DEBUG("IR capture validation scan");
1207         retval = jtag_execute_queue();
1208         if (retval != ERROR_OK)
1209                 goto done;
1210
1211         tap = NULL;
1212         chain_pos = 0;
1213
1214         for (;; ) {
1215                 tap = jtag_tap_next_enabled(tap);
1216                 if (tap == NULL)
1217                         break;
1218
1219                 /* If we're autoprobing, guess IR lengths.  They must be at
1220                  * least two bits.  Guessing will fail if (a) any TAP does
1221                  * not conform to the JTAG spec; or (b) when the upper bits
1222                  * captured from some conforming TAP are nonzero.  Or if
1223                  * (c) an IR length is longer than 32 bits -- which is only
1224                  * an implementation limit, which could someday be raised.
1225                  *
1226                  * REVISIT optimization:  if there's a *single* TAP we can
1227                  * lift restrictions (a) and (b) by scanning a recognizable
1228                  * pattern before the all-ones BYPASS.  Check for where the
1229                  * pattern starts in the result, instead of an 0...01 value.
1230                  *
1231                  * REVISIT alternative approach: escape to some tcl code
1232                  * which could provide more knowledge, based on IDCODE; and
1233                  * only guess when that has no success.
1234                  */
1235                 if (tap->ir_length == 0) {
1236                         tap->ir_length = 2;
1237                         while ((val = buf_get_u64(ir_test, chain_pos, tap->ir_length + 1)) == 1
1238                                         && tap->ir_length <= 64) {
1239                                 tap->ir_length++;
1240                         }
1241                         LOG_WARNING("AUTO %s - use \"... -irlen %d\"",
1242                                 jtag_tap_name(tap), tap->ir_length);
1243                 }
1244
1245                 /* Validate the two LSBs, which must be 01 per JTAG spec.
1246                  *
1247                  * Or ... more bits could be provided by TAP declaration.
1248                  * Plus, some taps (notably in i.MX series chips) violate
1249                  * this part of the JTAG spec, so their capture mask/value
1250                  * attributes might disable this test.
1251                  */
1252                 val = buf_get_u64(ir_test, chain_pos, tap->ir_length);
1253                 if ((val & tap->ir_capture_mask) != tap->ir_capture_value) {
1254                         LOG_ERROR("%s: IR capture error; saw 0x%0*" PRIx64 " not 0x%0*" PRIx32,
1255                                 jtag_tap_name(tap),
1256                                 (tap->ir_length + 7) / tap->ir_length, val,
1257                                 (tap->ir_length + 7) / tap->ir_length, tap->ir_capture_value);
1258
1259                         retval = ERROR_JTAG_INIT_FAILED;
1260                         goto done;
1261                 }
1262                 LOG_DEBUG("%s: IR capture 0x%0*" PRIx64, jtag_tap_name(tap),
1263                         (tap->ir_length + 7) / tap->ir_length, val);
1264                 chain_pos += tap->ir_length;
1265         }
1266
1267         /* verify the '11' sentinel we wrote is returned at the end */
1268         val = buf_get_u64(ir_test, chain_pos, 2);
1269         if (val != 0x3) {
1270                 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1271
1272                 LOG_ERROR("IR capture error at bit %d, saw 0x%s not 0x...3",
1273                         chain_pos, cbuf);
1274                 free(cbuf);
1275                 retval = ERROR_JTAG_INIT_FAILED;
1276         }
1277
1278 done:
1279         free(ir_test);
1280         if (retval != ERROR_OK) {
1281                 jtag_add_tlr();
1282                 jtag_execute_queue();
1283         }
1284         return retval;
1285 }
1286
1287 void jtag_tap_init(struct jtag_tap *tap)
1288 {
1289         unsigned ir_len_bits;
1290         unsigned ir_len_bytes;
1291
1292         /* if we're autoprobing, cope with potentially huge ir_length */
1293         ir_len_bits = tap->ir_length ? : JTAG_IRLEN_MAX;
1294         ir_len_bytes = DIV_ROUND_UP(ir_len_bits, 8);
1295
1296         tap->expected = calloc(1, ir_len_bytes);
1297         tap->expected_mask = calloc(1, ir_len_bytes);
1298         tap->cur_instr = malloc(ir_len_bytes);
1299
1300         /** @todo cope better with ir_length bigger than 32 bits */
1301         if (ir_len_bits > 32)
1302                 ir_len_bits = 32;
1303
1304         buf_set_u32(tap->expected, 0, ir_len_bits, tap->ir_capture_value);
1305         buf_set_u32(tap->expected_mask, 0, ir_len_bits, tap->ir_capture_mask);
1306
1307         /* TAP will be in bypass mode after jtag_validate_ircapture() */
1308         tap->bypass = 1;
1309         buf_set_ones(tap->cur_instr, tap->ir_length);
1310
1311         /* register the reset callback for the TAP */
1312         jtag_register_event_callback(&jtag_reset_callback, tap);
1313         jtag_tap_add(tap);
1314
1315         LOG_DEBUG("Created Tap: %s @ abs position %d, "
1316                         "irlen %d, capture: 0x%x mask: 0x%x", tap->dotted_name,
1317                         tap->abs_chain_position, tap->ir_length,
1318                         (unsigned) tap->ir_capture_value,
1319                         (unsigned) tap->ir_capture_mask);
1320 }
1321
1322 void jtag_tap_free(struct jtag_tap *tap)
1323 {
1324         jtag_unregister_event_callback(&jtag_reset_callback, tap);
1325
1326         /** @todo is anything missing? no memory leaks please */
1327         free(tap->expected);
1328         free(tap->expected_ids);
1329         free(tap->chip);
1330         free(tap->tapname);
1331         free(tap->dotted_name);
1332         free(tap);
1333 }
1334
1335 /**
1336  * Do low-level setup like initializing registers, output signals,
1337  * and clocking.
1338  */
1339 int adapter_init(struct command_context *cmd_ctx)
1340 {
1341         if (jtag)
1342                 return ERROR_OK;
1343
1344         if (!jtag_interface) {
1345                 /* nothing was previously specified by "interface" command */
1346                 LOG_ERROR("Debug Adapter has to be specified, "
1347                         "see \"interface\" command");
1348                 return ERROR_JTAG_INVALID_INTERFACE;
1349         }
1350
1351         int retval;
1352         retval = jtag_interface->init();
1353         if (retval != ERROR_OK)
1354                 return retval;
1355         jtag = jtag_interface;
1356
1357         /* LEGACY SUPPORT ... adapter drivers  must declare what
1358          * transports they allow.  Until they all do so, assume
1359          * the legacy drivers are JTAG-only
1360          */
1361         if (!transports_are_declared()) {
1362                 LOG_ERROR("Adapter driver '%s' did not declare "
1363                         "which transports it allows; assuming "
1364                         "JTAG-only", jtag->name);
1365                 retval = allow_transports(cmd_ctx, jtag_only);
1366                 if (retval != ERROR_OK)
1367                         return retval;
1368         }
1369
1370         if (jtag->speed == NULL) {
1371                 LOG_INFO("This adapter doesn't support configurable speed");
1372                 return ERROR_OK;
1373         }
1374
1375         if (CLOCK_MODE_UNSELECTED == clock_mode) {
1376                 LOG_ERROR("An adapter speed is not selected in the init script."
1377                         " Insert a call to adapter_khz or jtag_rclk to proceed.");
1378                 return ERROR_JTAG_INIT_FAILED;
1379         }
1380
1381         int requested_khz = jtag_get_speed_khz();
1382         int actual_khz = requested_khz;
1383         int jtag_speed_var = 0;
1384         retval = jtag_get_speed(&jtag_speed_var);
1385         if (retval != ERROR_OK)
1386                 return retval;
1387         retval = jtag->speed(jtag_speed_var);
1388         if (retval != ERROR_OK)
1389                 return retval;
1390         retval = jtag_get_speed_readable(&actual_khz);
1391         if (ERROR_OK != retval)
1392                 LOG_INFO("adapter-specific clock speed value %d", jtag_speed_var);
1393         else if (actual_khz) {
1394                 /* Adaptive clocking -- JTAG-specific */
1395                 if ((CLOCK_MODE_RCLK == clock_mode)
1396                                 || ((CLOCK_MODE_KHZ == clock_mode) && !requested_khz)) {
1397                         LOG_INFO("RCLK (adaptive clock speed) not supported - fallback to %d kHz"
1398                         , actual_khz);
1399                 } else
1400                         LOG_INFO("clock speed %d kHz", actual_khz);
1401         } else
1402                 LOG_INFO("RCLK (adaptive clock speed)");
1403
1404         return ERROR_OK;
1405 }
1406
1407 int jtag_init_inner(struct command_context *cmd_ctx)
1408 {
1409         struct jtag_tap *tap;
1410         int retval;
1411         bool issue_setup = true;
1412
1413         LOG_DEBUG("Init JTAG chain");
1414
1415         tap = jtag_tap_next_enabled(NULL);
1416         if (tap == NULL) {
1417                 /* Once JTAG itself is properly set up, and the scan chain
1418                  * isn't absurdly large, IDCODE autoprobe should work fine.
1419                  *
1420                  * But ... IRLEN autoprobe can fail even on systems which
1421                  * are fully conformant to JTAG.  Also, JTAG setup can be
1422                  * quite finicky on some systems.
1423                  *
1424                  * REVISIT: if TAP autoprobe works OK, then in many cases
1425                  * we could escape to tcl code and set up targets based on
1426                  * the TAP's IDCODE values.
1427                  */
1428                 LOG_WARNING("There are no enabled taps.  "
1429                         "AUTO PROBING MIGHT NOT WORK!!");
1430
1431                 /* REVISIT default clock will often be too fast ... */
1432         }
1433
1434         jtag_add_tlr();
1435         retval = jtag_execute_queue();
1436         if (retval != ERROR_OK)
1437                 return retval;
1438
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.
1442          */
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.
1452                          *
1453                          * Also the device might be powered down during startup.
1454                          *
1455                          * After OpenOCD starts, we can try to power on the device
1456                          * and run a reset.
1457                          */
1458                         LOG_ERROR("Trying to use configured scan chain anyway...");
1459                         issue_setup = false;
1460                         break;
1461         }
1462
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.)
1468          */
1469         retval = jtag_validate_ircapture();
1470         if (retval != ERROR_OK) {
1471                 /* The target might be powered down. The user
1472                  * can power it up and reset it after firing
1473                  * up OpenOCD.
1474                  */
1475                 issue_setup = false;
1476         }
1477
1478         if (issue_setup)
1479                 jtag_notify_event(JTAG_TAP_EVENT_SETUP);
1480         else
1481                 LOG_WARNING("Bypassing JTAG setup events due to errors");
1482
1483
1484         return ERROR_OK;
1485 }
1486
1487 int adapter_quit(void)
1488 {
1489         if (!jtag || !jtag->quit)
1490                 return ERROR_OK;
1491
1492         /* close the JTAG interface */
1493         int result = jtag->quit();
1494         if (ERROR_OK != result)
1495                 LOG_ERROR("failed: %d", result);
1496
1497         return ERROR_OK;
1498 }
1499
1500 int swd_init_reset(struct command_context *cmd_ctx)
1501 {
1502         int retval = adapter_init(cmd_ctx);
1503         if (retval != ERROR_OK)
1504                 return retval;
1505
1506         LOG_DEBUG("Initializing with hard SRST reset");
1507
1508         if (jtag_reset_config & RESET_HAS_SRST)
1509                 swd_add_reset(1);
1510         swd_add_reset(0);
1511         retval = jtag_execute_queue();
1512         return retval;
1513 }
1514
1515 int jtag_init_reset(struct command_context *cmd_ctx)
1516 {
1517         int retval = adapter_init(cmd_ctx);
1518         if (retval != ERROR_OK)
1519                 return retval;
1520
1521         LOG_DEBUG("Initializing with hard TRST+SRST reset");
1522
1523         /*
1524          * This procedure is used by default when OpenOCD triggers a reset.
1525          * It's now done through an overridable Tcl "init_reset" wrapper.
1526          *
1527          * This started out as a more powerful "get JTAG working" reset than
1528          * jtag_init_inner(), applying TRST because some chips won't activate
1529          * JTAG without a TRST cycle (presumed to be async, though some of
1530          * those chips synchronize JTAG activation using TCK).
1531          *
1532          * But some chips only activate JTAG as part of an SRST cycle; SRST
1533          * got mixed in.  So it became a hard reset routine, which got used
1534          * in more places, and which coped with JTAG reset being forced as
1535          * part of SRST (srst_pulls_trst).
1536          *
1537          * And even more corner cases started to surface:  TRST and/or SRST
1538          * assertion timings matter; some chips need other JTAG operations;
1539          * TRST/SRST sequences can need to be different from these, etc.
1540          *
1541          * Systems should override that wrapper to support system-specific
1542          * requirements that this not-fully-generic code doesn't handle.
1543          *
1544          * REVISIT once Tcl code can read the reset_config modes, this won't
1545          * need to be a C routine at all...
1546          */
1547         jtag_add_reset(1, 0);   /* TAP_RESET, using TMS+TCK or TRST */
1548         if (jtag_reset_config & RESET_HAS_SRST) {
1549                 jtag_add_reset(1, 1);
1550                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) == 0)
1551                         jtag_add_reset(0, 1);
1552         }
1553
1554         /* some targets enable us to connect with srst asserted */
1555         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1556                 if (jtag_reset_config & RESET_SRST_NO_GATING)
1557                         jtag_add_reset(0, 1);
1558                 else {
1559                         LOG_WARNING("\'srst_nogate\' reset_config option is required");
1560                         jtag_add_reset(0, 0);
1561                 }
1562         } else
1563                 jtag_add_reset(0, 0);
1564         retval = jtag_execute_queue();
1565         if (retval != ERROR_OK)
1566                 return retval;
1567
1568         /* Check that we can communication on the JTAG chain + eventually we want to
1569          * be able to perform enumeration only after OpenOCD has started
1570          * telnet and GDB server
1571          *
1572          * That would allow users to more easily perform any magic they need to before
1573          * reset happens.
1574          */
1575         return jtag_init_inner(cmd_ctx);
1576 }
1577
1578 int jtag_init(struct command_context *cmd_ctx)
1579 {
1580         int retval = adapter_init(cmd_ctx);
1581         if (retval != ERROR_OK)
1582                 return retval;
1583
1584         /* guard against oddball hardware: force resets to be inactive */
1585         jtag_add_reset(0, 0);
1586
1587         /* some targets enable us to connect with srst asserted */
1588         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1589                 if (jtag_reset_config & RESET_SRST_NO_GATING)
1590                         jtag_add_reset(0, 1);
1591                 else
1592                         LOG_WARNING("\'srst_nogate\' reset_config option is required");
1593         }
1594         retval = jtag_execute_queue();
1595         if (retval != ERROR_OK)
1596                 return retval;
1597
1598         if (Jim_Eval_Named(cmd_ctx->interp, "jtag_init", __FILE__, __LINE__) != JIM_OK)
1599                 return ERROR_FAIL;
1600
1601         return ERROR_OK;
1602 }
1603
1604 unsigned jtag_get_speed_khz(void)
1605 {
1606         return speed_khz;
1607 }
1608
1609 static int adapter_khz_to_speed(unsigned khz, int *speed)
1610 {
1611         LOG_DEBUG("convert khz to interface specific speed value");
1612         speed_khz = khz;
1613         if (jtag != NULL) {
1614                 LOG_DEBUG("have interface set up");
1615                 int speed_div1;
1616                 int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1617                 if (ERROR_OK != retval)
1618                         return retval;
1619                 *speed = speed_div1;
1620         }
1621         return ERROR_OK;
1622 }
1623
1624 static int jtag_rclk_to_speed(unsigned fallback_speed_khz, int *speed)
1625 {
1626         int retval = adapter_khz_to_speed(0, speed);
1627         if ((ERROR_OK != retval) && fallback_speed_khz) {
1628                 LOG_DEBUG("trying fallback speed...");
1629                 retval = adapter_khz_to_speed(fallback_speed_khz, speed);
1630         }
1631         return retval;
1632 }
1633
1634 static int jtag_set_speed(int speed)
1635 {
1636         jtag_speed = speed;
1637         /* this command can be called during CONFIG,
1638          * in which case jtag isn't initialized */
1639         return jtag ? jtag->speed(speed) : ERROR_OK;
1640 }
1641
1642 int jtag_config_khz(unsigned khz)
1643 {
1644         LOG_DEBUG("handle jtag khz");
1645         clock_mode = CLOCK_MODE_KHZ;
1646         int speed = 0;
1647         int retval = adapter_khz_to_speed(khz, &speed);
1648         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1649 }
1650
1651 int jtag_config_rclk(unsigned fallback_speed_khz)
1652 {
1653         LOG_DEBUG("handle jtag rclk");
1654         clock_mode = CLOCK_MODE_RCLK;
1655         rclk_fallback_speed_khz = fallback_speed_khz;
1656         int speed = 0;
1657         int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1658         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1659 }
1660
1661 int jtag_get_speed(int *speed)
1662 {
1663         switch (clock_mode) {
1664                 case CLOCK_MODE_KHZ:
1665                         adapter_khz_to_speed(jtag_get_speed_khz(), speed);
1666                         break;
1667                 case CLOCK_MODE_RCLK:
1668                         jtag_rclk_to_speed(rclk_fallback_speed_khz, speed);
1669                         break;
1670                 default:
1671                         LOG_ERROR("BUG: unknown jtag clock mode");
1672                         return ERROR_FAIL;
1673         }
1674         return ERROR_OK;
1675 }
1676
1677 int jtag_get_speed_readable(int *khz)
1678 {
1679         int jtag_speed_var = 0;
1680         int retval = jtag_get_speed(&jtag_speed_var);
1681         if (retval != ERROR_OK)
1682                 return retval;
1683         return jtag ? jtag->speed_div(jtag_speed_var, khz) : ERROR_OK;
1684 }
1685
1686 void jtag_set_verify(bool enable)
1687 {
1688         jtag_verify = enable;
1689 }
1690
1691 bool jtag_will_verify()
1692 {
1693         return jtag_verify;
1694 }
1695
1696 void jtag_set_verify_capture_ir(bool enable)
1697 {
1698         jtag_verify_capture_ir = enable;
1699 }
1700
1701 bool jtag_will_verify_capture_ir()
1702 {
1703         return jtag_verify_capture_ir;
1704 }
1705
1706 int jtag_power_dropout(int *dropout)
1707 {
1708         if (jtag == NULL) {
1709                 /* TODO: as the jtag interface is not valid all
1710                  * we can do at the moment is exit OpenOCD */
1711                 LOG_ERROR("No Valid JTAG Interface Configured.");
1712                 exit(-1);
1713         }
1714         return jtag->power_dropout(dropout);
1715 }
1716
1717 int jtag_srst_asserted(int *srst_asserted)
1718 {
1719         return jtag->srst_asserted(srst_asserted);
1720 }
1721
1722 enum reset_types jtag_get_reset_config(void)
1723 {
1724         return jtag_reset_config;
1725 }
1726 void jtag_set_reset_config(enum reset_types type)
1727 {
1728         jtag_reset_config = type;
1729 }
1730
1731 int jtag_get_trst(void)
1732 {
1733         return jtag_trst;
1734 }
1735 int jtag_get_srst(void)
1736 {
1737         return jtag_srst;
1738 }
1739
1740 void jtag_set_nsrst_delay(unsigned delay)
1741 {
1742         adapter_nsrst_delay = delay;
1743 }
1744 unsigned jtag_get_nsrst_delay(void)
1745 {
1746         return adapter_nsrst_delay;
1747 }
1748 void jtag_set_ntrst_delay(unsigned delay)
1749 {
1750         jtag_ntrst_delay = delay;
1751 }
1752 unsigned jtag_get_ntrst_delay(void)
1753 {
1754         return jtag_ntrst_delay;
1755 }
1756
1757
1758 void jtag_set_nsrst_assert_width(unsigned delay)
1759 {
1760         adapter_nsrst_assert_width = delay;
1761 }
1762 unsigned jtag_get_nsrst_assert_width(void)
1763 {
1764         return adapter_nsrst_assert_width;
1765 }
1766 void jtag_set_ntrst_assert_width(unsigned delay)
1767 {
1768         jtag_ntrst_assert_width = delay;
1769 }
1770 unsigned jtag_get_ntrst_assert_width(void)
1771 {
1772         return jtag_ntrst_assert_width;
1773 }
1774
1775 static int jtag_select(struct command_context *ctx)
1776 {
1777         int retval;
1778
1779         /* NOTE:  interface init must already have been done.
1780          * That works with only C code ... no Tcl glue required.
1781          */
1782
1783         retval = jtag_register_commands(ctx);
1784
1785         if (retval != ERROR_OK)
1786                 return retval;
1787
1788         retval = svf_register_commands(ctx);
1789
1790         if (retval != ERROR_OK)
1791                 return retval;
1792
1793         return xsvf_register_commands(ctx);
1794 }
1795
1796 static struct transport jtag_transport = {
1797         .name = "jtag",
1798         .select = jtag_select,
1799         .init = jtag_init,
1800 };
1801
1802 static void jtag_constructor(void) __attribute__((constructor));
1803 static void jtag_constructor(void)
1804 {
1805         transport_register(&jtag_transport);
1806 }
1807
1808 /** Returns true if the current debug session
1809  * is using JTAG as its transport.
1810  */
1811 bool transport_is_jtag(void)
1812 {
1813         return get_current_transport() == &jtag_transport;
1814 }
1815
1816 void adapter_assert_reset(void)
1817 {
1818         if (transport_is_jtag()) {
1819                 if (jtag_reset_config & RESET_SRST_PULLS_TRST)
1820                         jtag_add_reset(1, 1);
1821                 else
1822                         jtag_add_reset(0, 1);
1823         } else if (transport_is_swd())
1824                 swd_add_reset(1);
1825         else if (transport_is_cmsis_dap())
1826                 swd_add_reset(1);  /* FIXME */
1827         else if (get_current_transport() != NULL)
1828                 LOG_ERROR("reset is not supported on %s",
1829                         get_current_transport()->name);
1830         else
1831                 LOG_ERROR("transport is not selected");
1832 }
1833
1834 void adapter_deassert_reset(void)
1835 {
1836         if (transport_is_jtag())
1837                 jtag_add_reset(0, 0);
1838         else if (transport_is_swd())
1839                 swd_add_reset(0);
1840         else if (transport_is_cmsis_dap())
1841                 swd_add_reset(0);  /* FIXME */
1842         else if (get_current_transport() != NULL)
1843                 LOG_ERROR("reset is not supported on %s",
1844                         get_current_transport()->name);
1845         else
1846                 LOG_ERROR("transport is not selected");
1847 }