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