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