Stop ignoring most scan chain validation errors
[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 "minidriver.h"
36 #include "interface.h"
37
38 #ifdef HAVE_STRINGS_H
39 #include <strings.h>
40 #endif
41
42
43 /// The number of JTAG queue flushes (for profiling and debugging purposes).
44 static int jtag_flush_queue_count;
45
46 static void jtag_add_scan_check(void (*jtag_add_scan)(int in_num_fields, const scan_field_t *in_fields, tap_state_t state),
47                 int in_num_fields, scan_field_t *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 jtag_tap_t *__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 jtag_nsrst_delay = 0; /* default to no nSRST delay */
97 static int jtag_ntrst_delay = 0; /* default to no nTRST delay */
98 static int jtag_nsrst_assert_width = 0; /* width of assertion */
99 static int jtag_ntrst_assert_width = 0; /* width of assertion */
100
101 typedef struct jtag_event_callback_s
102 {
103         jtag_event_handler_t          callback;
104         void*                         priv;
105         struct jtag_event_callback_s* next;
106 } jtag_event_callback_t;
107
108 /* callbacks to inform high-level handlers about JTAG state changes */
109 static jtag_event_callback_t *jtag_event_callbacks;
110
111 /* speed in kHz*/
112 static int speed_khz = 0;
113 /* speed to fallback to when RCLK is requested but not supported */
114 static int rclk_fallback_speed_khz = 0;
115 static enum {CLOCK_MODE_SPEED, CLOCK_MODE_KHZ, CLOCK_MODE_RCLK} clock_mode;
116 static int jtag_speed = 0;
117
118 static struct jtag_interface_s *jtag = NULL;
119
120 /* configuration */
121 jtag_interface_t *jtag_interface = NULL;
122
123 void jtag_set_error(int error)
124 {
125         if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
126                 return;
127         jtag_error = error;
128 }
129 int jtag_get_error(void)
130 {
131         return jtag_error;
132 }
133 int jtag_error_clear(void)
134 {
135         int temp = jtag_error;
136         jtag_error = ERROR_OK;
137         return temp;
138 }
139
140
141 jtag_tap_t *jtag_all_taps(void)
142 {
143         return __jtag_all_taps;
144 };
145
146 unsigned jtag_tap_count(void)
147 {
148         return jtag_num_taps;
149 }
150
151 unsigned jtag_tap_count_enabled(void)
152 {
153         jtag_tap_t *t = jtag_all_taps();
154         unsigned n = 0;
155         while (t)
156         {
157                 if (t->enabled)
158                         n++;
159                 t = t->next_tap;
160         }
161         return n;
162 }
163
164 /// Append a new TAP to the chain of all taps.
165 void jtag_tap_add(struct jtag_tap_s *t)
166 {
167         t->abs_chain_position = jtag_num_taps++;
168
169         jtag_tap_t **tap = &__jtag_all_taps;
170         while (*tap != NULL)
171                 tap = &(*tap)->next_tap;
172         *tap = t;
173 }
174
175 /* returns a pointer to the n-th device in the scan chain */
176 static inline jtag_tap_t *jtag_tap_by_position(unsigned n)
177 {
178         jtag_tap_t *t = jtag_all_taps();
179
180         while (t && n-- > 0)
181                 t = t->next_tap;
182
183         return t;
184 }
185
186 jtag_tap_t *jtag_tap_by_string(const char *s)
187 {
188         /* try by name first */
189         jtag_tap_t *t = jtag_all_taps();
190
191         while (t)
192         {
193                 if (0 == strcmp(t->dotted_name, s))
194                         return t;
195                 t = t->next_tap;
196         }
197
198         /* no tap found by name, so try to parse the name as a number */
199         unsigned n;
200         if (parse_uint(s, &n) != ERROR_OK)
201                 return NULL;
202
203         /* FIXME remove this numeric fallback code late June 2010, along
204          * with all info in the User's Guide that TAPs have numeric IDs.
205          * Also update "scan_chain" output to not display the numbers.
206          */
207         t = jtag_tap_by_position(n);
208         if (t)
209                 LOG_WARNING("Specify TAP '%s' by name, not number %u",
210                         t->dotted_name, n);
211
212         return t;
213 }
214
215 jtag_tap_t *jtag_tap_by_jim_obj(Jim_Interp *interp, Jim_Obj *o)
216 {
217         const char *cp = Jim_GetString(o, NULL);
218         jtag_tap_t *t = cp ? jtag_tap_by_string(cp) : NULL;
219         if (NULL == cp)
220                 cp = "(unknown)";
221         if (NULL == t)
222                 Jim_SetResult_sprintf(interp, "Tap '%s' could not be found", cp);
223         return t;
224 }
225
226 jtag_tap_t* jtag_tap_next_enabled(jtag_tap_t* p)
227 {
228         p = p ? p->next_tap : jtag_all_taps();
229         while (p)
230         {
231                 if (p->enabled)
232                         return p;
233                 p = p->next_tap;
234         }
235         return NULL;
236 }
237
238 const char *jtag_tap_name(const jtag_tap_t *tap)
239 {
240         return (tap == NULL) ? "(unknown)" : tap->dotted_name;
241 }
242
243
244 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
245 {
246         jtag_event_callback_t **callbacks_p = &jtag_event_callbacks;
247
248         if (callback == NULL)
249         {
250                 return ERROR_INVALID_ARGUMENTS;
251         }
252
253         if (*callbacks_p)
254         {
255                 while ((*callbacks_p)->next)
256                         callbacks_p = &((*callbacks_p)->next);
257                 callbacks_p = &((*callbacks_p)->next);
258         }
259
260         (*callbacks_p) = malloc(sizeof(jtag_event_callback_t));
261         (*callbacks_p)->callback = callback;
262         (*callbacks_p)->priv = priv;
263         (*callbacks_p)->next = NULL;
264
265         return ERROR_OK;
266 }
267
268 int jtag_unregister_event_callback(jtag_event_handler_t callback, void *priv)
269 {
270         jtag_event_callback_t **callbacks_p;
271         jtag_event_callback_t **next;
272
273         if (callback == NULL)
274         {
275                 return ERROR_INVALID_ARGUMENTS;
276         }
277
278         for (callbacks_p = &jtag_event_callbacks;
279                         *callbacks_p != NULL;
280                         callbacks_p = next)
281         {
282                 next = &((*callbacks_p)->next);
283
284                 if ((*callbacks_p)->priv != priv)
285                         continue;
286
287                 if ((*callbacks_p)->callback == callback)
288                 {
289                         free(*callbacks_p);
290                         *callbacks_p = *next;
291                 }
292         }
293
294         return ERROR_OK;
295 }
296
297 int jtag_call_event_callbacks(enum jtag_event event)
298 {
299         jtag_event_callback_t *callback = jtag_event_callbacks;
300
301         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
302
303         while (callback)
304         {
305                 jtag_event_callback_t *next;
306
307                 /* callback may remove itself */
308                 next = callback->next;
309                 callback->callback(event, callback->priv);
310                 callback = next;
311         }
312
313         return ERROR_OK;
314 }
315
316 static void jtag_checks(void)
317 {
318         assert(jtag_trst == 0);
319 }
320
321 static void jtag_prelude(tap_state_t state)
322 {
323         jtag_checks();
324
325         assert(state != TAP_INVALID);
326
327         cmd_queue_cur_state = state;
328 }
329
330 void jtag_alloc_in_value32(scan_field_t *field)
331 {
332         interface_jtag_alloc_in_value32(field);
333 }
334
335 void jtag_add_ir_scan_noverify(int in_count, const scan_field_t *in_fields,
336                 tap_state_t state)
337 {
338         jtag_prelude(state);
339
340         int retval = interface_jtag_add_ir_scan(in_count, in_fields, state);
341         jtag_set_error(retval);
342 }
343
344
345 void jtag_add_ir_scan(int in_num_fields, scan_field_t *in_fields, tap_state_t state)
346 {
347         assert(state != TAP_RESET);
348
349         if (jtag_verify && jtag_verify_capture_ir)
350         {
351                 /* 8 x 32 bit id's is enough for all invocations */
352
353                 for (int j = 0; j < in_num_fields; j++)
354                 {
355                         /* if we are to run a verification of the ir scan, we need to get the input back.
356                          * We may have to allocate space if the caller didn't ask for the input back.
357                          */
358                         in_fields[j].check_value = in_fields[j].tap->expected;
359                         in_fields[j].check_mask = in_fields[j].tap->expected_mask;
360                 }
361                 jtag_add_scan_check(jtag_add_ir_scan_noverify, in_num_fields, in_fields, state);
362         } else
363         {
364                 jtag_add_ir_scan_noverify(in_num_fields, in_fields, state);
365         }
366 }
367
368 void jtag_add_plain_ir_scan(int in_num_fields, const scan_field_t *in_fields,
369                 tap_state_t state)
370 {
371         assert(state != TAP_RESET);
372
373         jtag_prelude(state);
374
375         int retval = interface_jtag_add_plain_ir_scan(
376                         in_num_fields, in_fields, state);
377         jtag_set_error(retval);
378 }
379
380 void jtag_add_callback(jtag_callback1_t f, jtag_callback_data_t data0)
381 {
382         interface_jtag_add_callback(f, data0);
383 }
384
385 void jtag_add_callback4(jtag_callback_t f, jtag_callback_data_t data0,
386                 jtag_callback_data_t data1, jtag_callback_data_t data2,
387                 jtag_callback_data_t data3)
388 {
389         interface_jtag_add_callback4(f, data0, data1, data2, data3);
390 }
391
392 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
393                 uint8_t *in_check_mask, int num_bits);
394
395 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)
396 {
397         return jtag_check_value_inner((uint8_t *)data0, (uint8_t *)data1, (uint8_t *)data2, (int)data3);
398 }
399
400 static void jtag_add_scan_check(void (*jtag_add_scan)(int in_num_fields, const scan_field_t *in_fields, tap_state_t state),
401                 int in_num_fields, scan_field_t *in_fields, tap_state_t state)
402 {
403         for (int i = 0; i < in_num_fields; i++)
404         {
405                 struct scan_field_s *field = &in_fields[i];
406                 field->allocated = 0;
407                 field->modified = 0;
408                 if (field->check_value || field->in_value)
409                         continue;
410                 interface_jtag_add_scan_check_alloc(field);
411                 field->modified = 1;
412         }
413
414         jtag_add_scan(in_num_fields, in_fields, state);
415
416         for (int i = 0; i < in_num_fields; i++)
417         {
418                 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL))
419                 {
420                         /* this is synchronous for a minidriver */
421                         jtag_add_callback4(jtag_check_value_mask_callback, (jtag_callback_data_t)in_fields[i].in_value,
422                                 (jtag_callback_data_t)in_fields[i].check_value,
423                                 (jtag_callback_data_t)in_fields[i].check_mask,
424                                 (jtag_callback_data_t)in_fields[i].num_bits);
425                 }
426                 if (in_fields[i].allocated)
427                 {
428                         free(in_fields[i].in_value);
429                 }
430                 if (in_fields[i].modified)
431                 {
432                         in_fields[i].in_value = NULL;
433                 }
434         }
435 }
436
437 void jtag_add_dr_scan_check(int in_num_fields, scan_field_t *in_fields, tap_state_t state)
438 {
439         if (jtag_verify)
440         {
441                 jtag_add_scan_check(jtag_add_dr_scan, in_num_fields, in_fields, state);
442         } else
443         {
444                 jtag_add_dr_scan(in_num_fields, in_fields, state);
445         }
446 }
447
448
449 void jtag_add_dr_scan(int in_num_fields, const scan_field_t *in_fields,
450                 tap_state_t state)
451 {
452         assert(state != TAP_RESET);
453
454         jtag_prelude(state);
455
456         int retval;
457         retval = interface_jtag_add_dr_scan(in_num_fields, in_fields, state);
458         jtag_set_error(retval);
459 }
460
461 void jtag_add_plain_dr_scan(int in_num_fields, const scan_field_t *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_plain_dr_scan(in_num_fields, in_fields, state);
470         jtag_set_error(retval);
471 }
472
473 void jtag_add_dr_out(jtag_tap_t* tap,
474                 int num_fields, const int* num_bits, const uint32_t* value,
475                 tap_state_t end_state)
476 {
477         assert(end_state != TAP_RESET);
478         assert(end_state != TAP_INVALID);
479
480         cmd_queue_cur_state = end_state;
481
482         interface_jtag_add_dr_out(tap,
483                         num_fields, num_bits, value,
484                         end_state);
485 }
486
487 void jtag_add_tlr(void)
488 {
489         jtag_prelude(TAP_RESET);
490         jtag_set_error(interface_jtag_add_tlr());
491
492         /* NOTE: order here matches TRST path in jtag_add_reset() */
493         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
494         jtag_notify_event(JTAG_TRST_ASSERTED);
495 }
496
497 void jtag_add_pathmove(int num_states, const tap_state_t *path)
498 {
499         tap_state_t cur_state = cmd_queue_cur_state;
500
501         /* the last state has to be a stable state */
502         if (!tap_is_state_stable(path[num_states - 1]))
503         {
504                 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
505                 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
506                 return;
507         }
508
509         for (int i = 0; i < num_states; i++)
510         {
511                 if (path[i] == TAP_RESET)
512                 {
513                         LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
514                         jtag_set_error(ERROR_JTAG_STATE_INVALID);
515                         return;
516                 }
517
518                 if (tap_state_transition(cur_state, true)  != path[i]
519                   && tap_state_transition(cur_state, false) != path[i])
520                 {
521                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
522                                         tap_state_name(cur_state), tap_state_name(path[i]));
523                         jtag_set_error(ERROR_JTAG_TRANSITION_INVALID);
524                         return;
525                 }
526                 cur_state = path[i];
527         }
528
529         jtag_checks();
530
531         jtag_set_error(interface_jtag_add_pathmove(num_states, path));
532         cmd_queue_cur_state = path[num_states - 1];
533 }
534
535 int jtag_add_statemove(tap_state_t goal_state)
536 {
537         tap_state_t cur_state = cmd_queue_cur_state;
538
539         LOG_DEBUG("cur_state=%s goal_state=%s",
540                 tap_state_name(cur_state),
541                 tap_state_name(goal_state));
542
543
544         if (goal_state == cur_state)
545                 ;       /* nothing to do */
546         else if (goal_state == TAP_RESET)
547         {
548                 jtag_add_tlr();
549         }
550         else if (tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state))
551         {
552                 unsigned tms_bits  = tap_get_tms_path(cur_state, goal_state);
553                 unsigned tms_count = tap_get_tms_path_len(cur_state, goal_state);
554                 tap_state_t moves[8];
555                 assert(tms_count < DIM(moves));
556
557                 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1)
558                 {
559                         bool bit = tms_bits & 1;
560
561                         cur_state = tap_state_transition(cur_state, bit);
562                         moves[i] = cur_state;
563                 }
564
565                 jtag_add_pathmove(tms_count, moves);
566         }
567         else if (tap_state_transition(cur_state, true)  == goal_state
568                 ||   tap_state_transition(cur_state, false) == goal_state)
569         {
570                 jtag_add_pathmove(1, &goal_state);
571         }
572
573         else
574                 return ERROR_FAIL;
575
576         return ERROR_OK;
577 }
578
579 void jtag_add_runtest(int num_cycles, tap_state_t state)
580 {
581         jtag_prelude(state);
582         jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
583 }
584
585
586 void jtag_add_clocks(int num_cycles)
587 {
588         if (!tap_is_state_stable(cmd_queue_cur_state))
589         {
590                  LOG_ERROR("jtag_add_clocks() called with TAP in unstable state \"%s\"",
591                                  tap_state_name(cmd_queue_cur_state));
592                  jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
593                  return;
594         }
595
596         if (num_cycles > 0)
597         {
598                 jtag_checks();
599                 jtag_set_error(interface_jtag_add_clocks(num_cycles));
600         }
601 }
602
603 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
604 {
605         int trst_with_tlr = 0;
606         int new_srst = 0;
607         int new_trst = 0;
608
609         /* Without SRST, we must use target-specific JTAG operations
610          * on each target; callers should not be requesting SRST when
611          * that signal doesn't exist.
612          *
613          * RESET_SRST_PULLS_TRST is a board or chip level quirk, which
614          * can kick in even if the JTAG adapter can't drive TRST.
615          */
616         if (req_srst) {
617                 if (!(jtag_reset_config & RESET_HAS_SRST)) {
618                         LOG_ERROR("BUG: can't assert SRST");
619                         jtag_set_error(ERROR_FAIL);
620                         return;
621                 }
622                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) != 0
623                                 && !req_tlr_or_trst) {
624                         LOG_ERROR("BUG: can't assert only SRST");
625                         jtag_set_error(ERROR_FAIL);
626                         return;
627                 }
628                 new_srst = 1;
629         }
630
631         /* JTAG reset (entry to TAP_RESET state) can always be achieved
632          * using TCK and TMS; that may go through a TAP_{IR,DR}UPDATE
633          * state first.  TRST accelerates it, and bypasses those states.
634          *
635          * RESET_TRST_PULLS_SRST is a board or chip level quirk, which
636          * can kick in even if the JTAG adapter can't drive SRST.
637          */
638         if (req_tlr_or_trst) {
639                 if (!(jtag_reset_config & RESET_HAS_TRST))
640                         trst_with_tlr = 1;
641                 else if ((jtag_reset_config & RESET_TRST_PULLS_SRST) != 0
642                                 && !req_srst)
643                         trst_with_tlr = 1;
644                 else
645                         new_trst = 1;
646         }
647
648         /* Maybe change TRST and/or SRST signal state */
649         if (jtag_srst != new_srst || jtag_trst != new_trst) {
650                 int retval;
651
652                 retval = interface_jtag_add_reset(new_trst, new_srst);
653                 if (retval != ERROR_OK)
654                         jtag_set_error(retval);
655                 else
656                         retval = jtag_execute_queue();
657
658                 if (retval != ERROR_OK) {
659                         LOG_ERROR("TRST/SRST error %d", retval);
660                         return;
661                 }
662         }
663
664         /* SRST resets everything hooked up to that signal */
665         if (jtag_srst != new_srst) {
666                 jtag_srst = new_srst;
667                 if (jtag_srst)
668                 {
669                         LOG_DEBUG("SRST line asserted");
670                         if (jtag_nsrst_assert_width)
671                                 jtag_add_sleep(jtag_nsrst_assert_width * 1000);
672                 }
673                 else {
674                         LOG_DEBUG("SRST line released");
675                         if (jtag_nsrst_delay)
676                                 jtag_add_sleep(jtag_nsrst_delay * 1000);
677                 }
678         }
679
680         /* Maybe enter the JTAG TAP_RESET state ...
681          *  - using only TMS, TCK, and the JTAG state machine
682          *  - or else more directly, using TRST
683          *
684          * TAP_RESET should be invisible to non-debug parts of the system.
685          */
686         if (trst_with_tlr) {
687                 LOG_DEBUG("JTAG reset with TLR instead of TRST");
688                 jtag_set_end_state(TAP_RESET);
689                 jtag_add_tlr();
690
691         } else if (jtag_trst != new_trst) {
692                 jtag_trst = new_trst;
693                 if (jtag_trst) {
694                         LOG_DEBUG("TRST line asserted");
695                         tap_set_state(TAP_RESET);
696                         if (jtag_ntrst_assert_width)
697                                 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
698                 } else {
699                         LOG_DEBUG("TRST line released");
700                         if (jtag_ntrst_delay)
701                                 jtag_add_sleep(jtag_ntrst_delay * 1000);
702
703                         /* We just asserted nTRST, so we're now in TAP_RESET.
704                          * Inform possible listeners about this, now that
705                          * JTAG instructions and data can be shifted.  This
706                          * sequence must match jtag_add_tlr().
707                          */
708                         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
709                         jtag_notify_event(JTAG_TRST_ASSERTED);
710                 }
711         }
712 }
713
714 tap_state_t jtag_set_end_state(tap_state_t state)
715 {
716         if ((state == TAP_DRSHIFT)||(state == TAP_IRSHIFT))
717         {
718                 LOG_ERROR("BUG: TAP_DRSHIFT/IRSHIFT can't be end state. Calling code should use a larger scan field");
719         }
720
721         if (state != TAP_INVALID)
722                 cmd_queue_end_state = state;
723         return cmd_queue_end_state;
724 }
725
726 tap_state_t jtag_get_end_state(void)
727 {
728         return cmd_queue_end_state;
729 }
730
731 void jtag_add_sleep(uint32_t us)
732 {
733         /// @todo Here, keep_alive() appears to be a layering violation!!!
734         keep_alive();
735         jtag_set_error(interface_jtag_add_sleep(us));
736 }
737
738 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
739                 uint8_t *in_check_mask, int num_bits)
740 {
741         int retval = ERROR_OK;
742
743         int compare_failed = 0;
744
745         if (in_check_mask)
746                 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
747         else
748                 compare_failed = buf_cmp(captured, in_check_value, num_bits);
749
750         if (compare_failed) {
751                 char *captured_str, *in_check_value_str;
752                 int bits = (num_bits > DEBUG_JTAG_IOZ)
753                                 ? DEBUG_JTAG_IOZ
754                                 : num_bits;
755
756                 /* NOTE:  we've lost diagnostic context here -- 'which tap' */
757
758                 captured_str = buf_to_str(captured, bits, 16);
759                 in_check_value_str = buf_to_str(in_check_value, bits, 16);
760
761                 LOG_WARNING("Bad value '%s' captured during DR or IR scan:",
762                                 captured_str);
763                 LOG_WARNING(" check_value: 0x%s", in_check_value_str);
764
765                 free(captured_str);
766                 free(in_check_value_str);
767
768                 if (in_check_mask) {
769                         char *in_check_mask_str;
770
771                         in_check_mask_str = buf_to_str(in_check_mask, bits, 16);
772                         LOG_WARNING(" check_mask: 0x%s", in_check_mask_str);
773                         free(in_check_mask_str);
774                 }
775
776                 retval = ERROR_JTAG_QUEUE_FAILED;
777         }
778         return retval;
779 }
780
781 void jtag_check_value_mask(scan_field_t *field, uint8_t *value, uint8_t *mask)
782 {
783         assert(field->in_value != NULL);
784
785         if (value == NULL)
786         {
787                 /* no checking to do */
788                 return;
789         }
790
791         jtag_execute_queue_noclear();
792
793         int retval = jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
794         jtag_set_error(retval);
795 }
796
797
798
799 int default_interface_jtag_execute_queue(void)
800 {
801         if (NULL == jtag)
802         {
803                 LOG_ERROR("No JTAG interface configured yet.  "
804                         "Issue 'init' command in startup scripts "
805                         "before communicating with targets.");
806                 return ERROR_FAIL;
807         }
808
809         return jtag->execute_queue();
810 }
811
812 void jtag_execute_queue_noclear(void)
813 {
814         jtag_flush_queue_count++;
815         jtag_set_error(interface_jtag_execute_queue());
816 }
817
818 int jtag_get_flush_queue_count(void)
819 {
820         return jtag_flush_queue_count;
821 }
822
823 int jtag_execute_queue(void)
824 {
825         jtag_execute_queue_noclear();
826         return jtag_error_clear();
827 }
828
829 static int jtag_reset_callback(enum jtag_event event, void *priv)
830 {
831         jtag_tap_t *tap = priv;
832
833         if (event == JTAG_TRST_ASSERTED)
834         {
835                 tap->enabled = !tap->disabled_after_reset;
836
837                 /* current instruction is either BYPASS or IDCODE */
838                 buf_set_ones(tap->cur_instr, tap->ir_length);
839                 tap->bypass = 1;
840         }
841
842         return ERROR_OK;
843 }
844
845 void jtag_sleep(uint32_t us)
846 {
847         alive_sleep(us/1000);
848 }
849
850 /* Maximum number of enabled JTAG devices we expect in the scan chain,
851  * plus one (to detect garbage at the end).  Devices that don't support
852  * IDCODE take up fewer bits, possibly allowing a few more devices.
853  */
854 #define JTAG_MAX_CHAIN_SIZE 20
855
856 #define EXTRACT_MFG(X)  (((X) & 0xffe) >> 1)
857 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
858 #define EXTRACT_VER(X)  (((X) & 0xf0000000) >> 28)
859
860 /* A reserved manufacturer ID is used in END_OF_CHAIN_FLAG, so we
861  * know that no valid TAP will have it as an IDCODE value.
862  */
863 #define END_OF_CHAIN_FLAG       0x000000ff
864
865 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
866 {
867         scan_field_t field = {
868                         .tap = NULL,
869                         .num_bits = num_idcode * 32,
870                         .out_value = idcode_buffer,
871                         .in_value = idcode_buffer,
872                 };
873
874         // initialize to the end of chain ID value
875         for (unsigned i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
876                 buf_set_u32(idcode_buffer, i * 32, 32, END_OF_CHAIN_FLAG);
877
878         jtag_add_plain_dr_scan(1, &field, TAP_DRPAUSE);
879         jtag_add_tlr();
880         return jtag_execute_queue();
881 }
882
883 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
884 {
885         uint8_t zero_check = 0x0;
886         uint8_t one_check = 0xff;
887
888         for (unsigned i = 0; i < count * 4; i++)
889         {
890                 zero_check |= idcodes[i];
891                 one_check &= idcodes[i];
892         }
893
894         /* if there wasn't a single non-zero bit or if all bits were one,
895          * the scan is not valid.  We wrote a mix of both values; either
896          *
897          *  - There's a hardware issue (almost certainly):
898          *     + all-zeroes can mean a target stuck in JTAG reset
899          *     + all-ones tends to mean no target
900          *  - The scan chain is WAY longer than we can handle, *AND* either
901          *     + there are several hundreds of TAPs in bypass, or
902          *     + at least a few dozen TAPs all have an all-ones IDCODE
903          */
904         if (zero_check == 0x00 || one_check == 0xff)
905         {
906                 LOG_ERROR("JTAG scan chain interrogation failed: all %s",
907                                 (zero_check == 0x00) ? "zeroes" : "ones");
908                 LOG_ERROR("Check JTAG interface, timings, target power, etc.");
909                 return false;
910         }
911         return true;
912 }
913
914 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
915                 const char *name, uint32_t idcode)
916 {
917         log_printf_lf(level, __FILE__, __LINE__, __FUNCTION__,
918                                   "JTAG tap: %s %16.16s: 0x%08x "
919                                   "(mfg: 0x%3.3x, part: 0x%4.4x, ver: 0x%1.1x)",
920                                   name, msg,
921                                   (unsigned int)idcode,
922                                   (unsigned int)EXTRACT_MFG(idcode),
923                                   (unsigned int)EXTRACT_PART(idcode),
924                                   (unsigned int)EXTRACT_VER(idcode));
925 }
926
927 static bool jtag_idcode_is_final(uint32_t idcode)
928 {
929         /*
930          * Some devices, such as AVR8, will output all 1's instead
931          * of TDI input value at end of chain.  Allow those values
932          * instead of failing.
933          */
934         return idcode == END_OF_CHAIN_FLAG || idcode == 0xFFFFFFFF;
935 }
936
937 /**
938  * This helper checks that remaining bits in the examined chain data are
939  * all as expected, but a single JTAG device requires only 64 bits to be
940  * read back correctly.  This can help identify and diagnose problems
941  * with the JTAG chain earlier, gives more helpful/explicit error messages.
942  * Returns TRUE iff garbage was found.
943  */
944 static bool jtag_examine_chain_end(uint8_t *idcodes, unsigned count, unsigned max)
945 {
946         bool triggered = false;
947         for (; count < max - 31; count += 32)
948         {
949                 uint32_t idcode = buf_get_u32(idcodes, count, 32);
950                 // do not trigger the warning if the data looks good
951                 if (!triggered && jtag_idcode_is_final(idcode))
952                         continue;
953                 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
954                                         count, (unsigned int)idcode);
955                 triggered = true;
956         }
957         return triggered;
958 }
959
960 static bool jtag_examine_chain_match_tap(const struct jtag_tap_s *tap)
961 {
962         /* ignore expected BYPASS codes; warn otherwise */
963         if (0 == tap->expected_ids_cnt && !tap->idcode)
964                 return true;
965
966         /* Loop over the expected identification codes and test for a match */
967         uint8_t ii;
968         for (ii = 0; ii < tap->expected_ids_cnt; ii++)
969         {
970                 if (tap->idcode == tap->expected_ids[ii])
971                         return true;
972
973                 /* treat "-expected-id 0" as a "don't-warn" wildcard */
974                 if (0 == tap->expected_ids[ii])
975                         return true;
976         }
977
978         /* If none of the expected ids matched, warn */
979         jtag_examine_chain_display(LOG_LVL_WARNING, "UNEXPECTED",
980                         tap->dotted_name, tap->idcode);
981         for (ii = 0; ii < tap->expected_ids_cnt; ii++)
982         {
983                 char msg[32];
984                 snprintf(msg, sizeof(msg), "expected %hhu of %hhu",
985                                 ii + 1, tap->expected_ids_cnt);
986                 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
987                                 tap->dotted_name, tap->expected_ids[ii]);
988         }
989         return false;
990 }
991
992 /* Try to examine chain layout according to IEEE 1149.1 Â§12
993  * This is called a "blind interrogation" of the scan chain.
994  */
995 static int jtag_examine_chain(void)
996 {
997         uint8_t idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
998         unsigned bit_count;
999         int retval;
1000
1001         /* DR scan to collect BYPASS or IDCODE register contents.
1002          * Then make sure the scan data has both ones and zeroes.
1003          */
1004         retval = jtag_examine_chain_execute(idcode_buffer, JTAG_MAX_CHAIN_SIZE);
1005         if (retval != ERROR_OK)
1006                 return retval;
1007         if (!jtag_examine_chain_check(idcode_buffer, JTAG_MAX_CHAIN_SIZE))
1008                 return ERROR_JTAG_INIT_FAILED;
1009
1010         /* point at the 1st tap */
1011         jtag_tap_t *tap = jtag_tap_next_enabled(NULL);
1012         if (tap == NULL)
1013         {
1014                 LOG_ERROR("JTAG: No taps enabled?");
1015                 return ERROR_JTAG_INIT_FAILED;
1016         }
1017
1018         for (bit_count = 0;
1019                         tap && bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;
1020                         tap = jtag_tap_next_enabled(tap))
1021         {
1022                 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1023
1024                 if ((idcode & 1) == 0)
1025                 {
1026                         /* Zero for LSB indicates a device in bypass */
1027                         LOG_WARNING("TAP %s does not have IDCODE",
1028                                         tap->dotted_name);
1029                         idcode = 0;
1030                         tap->hasidcode = false;
1031
1032                         bit_count += 1;
1033                 }
1034                 else
1035                 {
1036                         /* Friendly devices support IDCODE */
1037                         tap->hasidcode = true;
1038                         jtag_examine_chain_display(LOG_LVL_INFO,
1039                                         "tap/device found",
1040                                         tap->dotted_name, idcode);
1041
1042                         bit_count += 32;
1043                 }
1044                 tap->idcode = idcode;
1045
1046                 /* ensure the TAP ID matches what was expected */
1047                 if (!jtag_examine_chain_match_tap(tap))
1048                         retval = ERROR_JTAG_INIT_SOFT_FAIL;
1049         }
1050
1051         /* Fail if too many TAPs were enabled for us to verify them all. */
1052         if (tap) {
1053                 LOG_ERROR("Too many TAPs enabled; '%s' ignored.",
1054                                 tap->dotted_name);
1055                 return ERROR_JTAG_INIT_FAILED;
1056         }
1057
1058         /* After those IDCODE or BYPASS register values should be
1059          * only the data we fed into the scan chain.
1060          */
1061         if (jtag_examine_chain_end(idcode_buffer, bit_count,
1062                         8 * sizeof(idcode_buffer))) {
1063                 LOG_ERROR("double-check your JTAG setup (interface, "
1064                                 "speed, missing TAPs, ...)");
1065                 return ERROR_JTAG_INIT_FAILED;
1066         }
1067
1068         /* Return success or, for backwards compatibility if only
1069          * some IDCODE values mismatched, a soft/continuable fault.
1070          */
1071         return retval;
1072 }
1073
1074 /*
1075  * Validate the date loaded by entry to the Capture-IR state, to help
1076  * find errors related to scan chain configuration (wrong IR lengths)
1077  * or communication.
1078  *
1079  * Entry state can be anything.  On non-error exit, all TAPs are in
1080  * bypass mode.  On error exits, the scan chain is reset.
1081  */
1082 static int jtag_validate_ircapture(void)
1083 {
1084         jtag_tap_t *tap;
1085         int total_ir_length = 0;
1086         uint8_t *ir_test = NULL;
1087         scan_field_t field;
1088         int val;
1089         int chain_pos = 0;
1090         int retval;
1091
1092         for (tap = NULL, total_ir_length = 0;
1093                         (tap = jtag_tap_next_enabled(tap)) != NULL;
1094                         total_ir_length += tap->ir_length)
1095                 continue;
1096
1097         /* increase length to add 2 bit sentinel after scan */
1098         total_ir_length += 2;
1099
1100         ir_test = malloc(CEIL(total_ir_length, 8));
1101         if (ir_test == NULL)
1102                 return ERROR_FAIL;
1103
1104         /* after this scan, all TAPs will capture BYPASS instructions */
1105         buf_set_ones(ir_test, total_ir_length);
1106
1107         field.tap = NULL;
1108         field.num_bits = total_ir_length;
1109         field.out_value = ir_test;
1110         field.in_value = ir_test;
1111
1112         jtag_add_plain_ir_scan(1, &field, TAP_IDLE);
1113
1114         LOG_DEBUG("IR capture validation scan");
1115         retval = jtag_execute_queue();
1116         if (retval != ERROR_OK)
1117                 goto done;
1118
1119         tap = NULL;
1120         chain_pos = 0;
1121
1122         for (;;) {
1123                 tap = jtag_tap_next_enabled(tap);
1124                 if (tap == NULL) {
1125                         break;
1126                 }
1127
1128                 /* Validate the two LSBs, which must be 01 per JTAG spec.
1129                  *
1130                  * Or ... more bits could be provided by TAP declaration.
1131                  * Plus, some taps (notably in i.MX series chips) violate
1132                  * this part of the JTAG spec, so their capture mask/value
1133                  * attributes might disable this test.
1134                  */
1135                 val = buf_get_u32(ir_test, chain_pos, tap->ir_length);
1136                 if ((val & tap->ir_capture_mask) != tap->ir_capture_value) {
1137                         LOG_ERROR("%s: IR capture error; saw 0x%0*x not 0x%0*x",
1138                                         jtag_tap_name(tap),
1139                                         (tap->ir_length + 7) / tap->ir_length,
1140                                         val,
1141                                         (tap->ir_length + 7) / tap->ir_length,
1142                                         tap->ir_capture_value);
1143
1144                         retval = ERROR_JTAG_INIT_FAILED;
1145                         goto done;
1146                 }
1147                 LOG_DEBUG("%s: IR capture 0x%0*x", jtag_tap_name(tap),
1148                                 (tap->ir_length + 7) / tap->ir_length, val);
1149                 chain_pos += tap->ir_length;
1150         }
1151
1152         /* verify the '11' sentinel we wrote is returned at the end */
1153         val = buf_get_u32(ir_test, chain_pos, 2);
1154         if (val != 0x3)
1155         {
1156                 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1157
1158                 LOG_ERROR("IR capture error at bit %d, saw 0x%s not 0x...3",
1159                                 chain_pos, cbuf);
1160                 free(cbuf);
1161                 retval = ERROR_JTAG_INIT_FAILED;
1162         }
1163
1164 done:
1165         free(ir_test);
1166         if (retval != ERROR_OK) {
1167                 jtag_add_tlr();
1168                 jtag_execute_queue();
1169         }
1170         return retval;
1171 }
1172
1173
1174 void jtag_tap_init(jtag_tap_t *tap)
1175 {
1176         assert(0 != tap->ir_length);
1177
1178         /// @todo fix, this allocates one byte per bit for all three fields!
1179         tap->expected = malloc(tap->ir_length);
1180         tap->expected_mask = malloc(tap->ir_length);
1181         tap->cur_instr = malloc(tap->ir_length);
1182
1183         /// @todo cope sanely with ir_length bigger than 32 bits
1184         buf_set_u32(tap->expected, 0, tap->ir_length, tap->ir_capture_value);
1185         buf_set_u32(tap->expected_mask, 0, tap->ir_length, tap->ir_capture_mask);
1186         buf_set_ones(tap->cur_instr, tap->ir_length);
1187
1188         // place TAP in bypass mode
1189         tap->bypass = 1;
1190         // register the reset callback for the TAP
1191         jtag_register_event_callback(&jtag_reset_callback, tap);
1192
1193         LOG_DEBUG("Created Tap: %s @ abs position %d, "
1194                         "irlen %d, capture: 0x%x mask: 0x%x", tap->dotted_name,
1195                                 tap->abs_chain_position, tap->ir_length,
1196                                 (unsigned) tap->ir_capture_value,
1197                                 (unsigned) tap->ir_capture_mask);
1198         jtag_tap_add(tap);
1199 }
1200
1201 void jtag_tap_free(jtag_tap_t *tap)
1202 {
1203         jtag_unregister_event_callback(&jtag_reset_callback, tap);
1204
1205         /// @todo is anything missing? no memory leaks please
1206         free((void *)tap->expected);
1207         free((void *)tap->expected_ids);
1208         free((void *)tap->chip);
1209         free((void *)tap->tapname);
1210         free((void *)tap->dotted_name);
1211         free(tap);
1212 }
1213
1214 int jtag_interface_init(struct command_context_s *cmd_ctx)
1215 {
1216         if (jtag)
1217                 return ERROR_OK;
1218
1219         if (!jtag_interface)
1220         {
1221                 /* nothing was previously specified by "interface" command */
1222                 LOG_ERROR("JTAG interface has to be specified, see \"interface\" command");
1223                 return ERROR_JTAG_INVALID_INTERFACE;
1224         }
1225
1226         jtag = jtag_interface;
1227         if (jtag_interface->init() != ERROR_OK)
1228         {
1229                 jtag = NULL;
1230                 return ERROR_JTAG_INIT_FAILED;
1231         }
1232
1233         int requested_khz = jtag_get_speed_khz();
1234         int actual_khz = requested_khz;
1235         int retval = jtag_get_speed_readable(&actual_khz);
1236         if (ERROR_OK != retval)
1237                 LOG_INFO("interface specific clock speed value %d", jtag_get_speed());
1238         else if (actual_khz)
1239         {
1240                 if ((CLOCK_MODE_RCLK == clock_mode)
1241                         || ((CLOCK_MODE_KHZ == clock_mode) && !requested_khz))
1242                 {
1243                         LOG_INFO("RCLK (adaptive clock speed) not supported - fallback to %d kHz"
1244                                 , actual_khz);
1245                 }
1246                 else
1247                         LOG_INFO("clock speed %d kHz", actual_khz);
1248         }
1249         else
1250                 LOG_INFO("RCLK (adaptive clock speed)");
1251
1252         return ERROR_OK;
1253 }
1254
1255 int jtag_init_inner(struct command_context_s *cmd_ctx)
1256 {
1257         jtag_tap_t *tap;
1258         int retval;
1259         bool issue_setup = true;
1260
1261         LOG_DEBUG("Init JTAG chain");
1262
1263         tap = jtag_tap_next_enabled(NULL);
1264         if (tap == NULL) {
1265                 LOG_ERROR("There are no enabled taps?");
1266                 return ERROR_JTAG_INIT_FAILED;
1267         }
1268
1269         jtag_add_tlr();
1270         if ((retval = jtag_execute_queue()) != ERROR_OK)
1271                 return retval;
1272
1273         /* Examine DR values first.  This discovers problems which will
1274          * prevent communication ... hardware issues like TDO stuck, or
1275          * configuring the wrong number of (enabled) TAPs.
1276          */
1277         retval = jtag_examine_chain();
1278         switch (retval) {
1279         case ERROR_OK:
1280                 /* complete success */
1281                 break;
1282         case ERROR_JTAG_INIT_SOFT_FAIL:
1283                 /* For backward compatibility reasons, try coping with
1284                  * configuration errors involving only ID mismatches.
1285                  * We might be able to talk to the devices.
1286                  */
1287                 LOG_ERROR("Trying to use configured scan chain anyway...");
1288                 issue_setup = false;
1289                 break;
1290         default:
1291                 /* some hard error; already issued diagnostics */
1292                 return retval;
1293         }
1294
1295         /* Now look at IR values.  Problems here will prevent real
1296          * communication.  They mostly mean that the IR length is
1297          * wrong ... or that the IR capture value is wrong.  (The
1298          * latter is uncommon, but easily worked around:  provide
1299          * ircapture/irmask values during TAP setup.)
1300          */
1301         retval = jtag_validate_ircapture();
1302         if (retval != ERROR_OK)
1303                 return retval;
1304
1305         if (issue_setup)
1306                 jtag_notify_event(JTAG_TAP_EVENT_SETUP);
1307         else
1308                 LOG_WARNING("Bypassing JTAG setup events due to errors");
1309
1310
1311         return ERROR_OK;
1312 }
1313
1314 int jtag_interface_quit(void)
1315 {
1316         if (!jtag || !jtag->quit)
1317                 return ERROR_OK;
1318
1319         // close the JTAG interface
1320         int result = jtag->quit();
1321         if (ERROR_OK != result)
1322                 LOG_ERROR("failed: %d", result);
1323
1324         return ERROR_OK;
1325 }
1326
1327
1328 int jtag_init_reset(struct command_context_s *cmd_ctx)
1329 {
1330         int retval;
1331
1332         if ((retval = jtag_interface_init(cmd_ctx)) != ERROR_OK)
1333                 return retval;
1334
1335         LOG_DEBUG("Trying to bring the JTAG controller to life by asserting TRST / TLR");
1336
1337         /* Reset can happen after a power cycle.
1338          *
1339          * Ideally we would only assert TRST or run TLR before the target reset.
1340          *
1341          * However w/srst_pulls_trst, trst is asserted together with the target
1342          * reset whether we want it or not.
1343          *
1344          * NB! Some targets have JTAG circuitry disabled until a
1345          * trst & srst has been asserted.
1346          *
1347          * NB! here we assume nsrst/ntrst delay are sufficient!
1348          *
1349          * NB! order matters!!!! srst *can* disconnect JTAG circuitry
1350          *
1351          */
1352         jtag_add_reset(1, 0); /* TAP_RESET, using TMS+TCK or TRST */
1353         if (jtag_reset_config & RESET_HAS_SRST)
1354         {
1355                 jtag_add_reset(1, 1);
1356                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) == 0)
1357                         jtag_add_reset(0, 1);
1358         }
1359         jtag_add_reset(0, 0);
1360         if ((retval = jtag_execute_queue()) != ERROR_OK)
1361                 return retval;
1362
1363         /* Check that we can communication on the JTAG chain + eventually we want to
1364          * be able to perform enumeration only after OpenOCD has started
1365          * telnet and GDB server
1366          *
1367          * That would allow users to more easily perform any magic they need to before
1368          * reset happens.
1369          */
1370         return jtag_init_inner(cmd_ctx);
1371 }
1372
1373 int jtag_init(struct command_context_s *cmd_ctx)
1374 {
1375         int retval;
1376
1377         if ((retval = jtag_interface_init(cmd_ctx)) != ERROR_OK)
1378                 return retval;
1379
1380         /* guard against oddball hardware: force resets to be inactive */
1381         jtag_add_reset(0, 0);
1382         if ((retval = jtag_execute_queue()) != ERROR_OK)
1383                 return retval;
1384
1385         if (Jim_Eval_Named(interp, "jtag_init", __FILE__, __LINE__) != JIM_OK)
1386                 return ERROR_FAIL;
1387
1388         return ERROR_OK;
1389 }
1390
1391 unsigned jtag_get_speed_khz(void)
1392 {
1393         return speed_khz;
1394 }
1395
1396 static int jtag_khz_to_speed(unsigned khz, int* speed)
1397 {
1398         LOG_DEBUG("convert khz to interface specific speed value");
1399         speed_khz = khz;
1400         if (jtag != NULL)
1401         {
1402                 LOG_DEBUG("have interface set up");
1403                 int speed_div1;
1404                 int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1405                 if (ERROR_OK != retval)
1406                 {
1407                         return retval;
1408                 }
1409                 *speed = speed_div1;
1410         }
1411         return ERROR_OK;
1412 }
1413
1414 static int jtag_rclk_to_speed(unsigned fallback_speed_khz, int* speed)
1415 {
1416         int retval = jtag_khz_to_speed(0, speed);
1417         if ((ERROR_OK != retval) && fallback_speed_khz)
1418         {
1419                 LOG_DEBUG("trying fallback speed...");
1420                 retval = jtag_khz_to_speed(fallback_speed_khz, speed);
1421         }
1422         return retval;
1423 }
1424
1425 static int jtag_set_speed(int speed)
1426 {
1427         jtag_speed = speed;
1428         /* this command can be called during CONFIG,
1429          * in which case jtag isn't initialized */
1430         return jtag ? jtag->speed(speed) : ERROR_OK;
1431 }
1432
1433 int jtag_config_speed(int speed)
1434 {
1435         LOG_DEBUG("handle jtag speed");
1436         clock_mode = CLOCK_MODE_SPEED;
1437         return jtag_set_speed(speed);
1438 }
1439
1440 int jtag_config_khz(unsigned khz)
1441 {
1442         LOG_DEBUG("handle jtag khz");
1443         clock_mode = CLOCK_MODE_KHZ;
1444         int speed = 0;
1445         int retval = jtag_khz_to_speed(khz, &speed);
1446         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1447 }
1448
1449 int jtag_config_rclk(unsigned fallback_speed_khz)
1450 {
1451         LOG_DEBUG("handle jtag rclk");
1452         clock_mode = CLOCK_MODE_RCLK;
1453         rclk_fallback_speed_khz = fallback_speed_khz;
1454         int speed = 0;
1455         int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1456         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1457 }
1458
1459 int jtag_get_speed(void)
1460 {
1461         int speed;
1462         switch(clock_mode)
1463         {
1464                 case CLOCK_MODE_SPEED:
1465                         speed = jtag_speed;
1466                         break;
1467                 case CLOCK_MODE_KHZ:
1468                         jtag_khz_to_speed(jtag_get_speed_khz(), &speed);
1469                         break;
1470                 case CLOCK_MODE_RCLK:
1471                         jtag_rclk_to_speed(rclk_fallback_speed_khz, &speed);
1472                         break;
1473                 default:
1474                         LOG_ERROR("BUG: unknown jtag clock mode");
1475                         speed = 0;
1476                         break;
1477         }
1478         return speed;
1479 }
1480
1481 int jtag_get_speed_readable(int *khz)
1482 {
1483         return jtag ? jtag->speed_div(jtag_get_speed(), khz) : ERROR_OK;
1484 }
1485
1486 void jtag_set_verify(bool enable)
1487 {
1488         jtag_verify = enable;
1489 }
1490
1491 bool jtag_will_verify()
1492 {
1493         return jtag_verify;
1494 }
1495
1496 void jtag_set_verify_capture_ir(bool enable)
1497 {
1498         jtag_verify_capture_ir = enable;
1499 }
1500
1501 bool jtag_will_verify_capture_ir()
1502 {
1503         return jtag_verify_capture_ir;
1504 }
1505
1506 int jtag_power_dropout(int *dropout)
1507 {
1508         return jtag->power_dropout(dropout);
1509 }
1510
1511 int jtag_srst_asserted(int *srst_asserted)
1512 {
1513         return jtag->srst_asserted(srst_asserted);
1514 }
1515
1516 enum reset_types jtag_get_reset_config(void)
1517 {
1518         return jtag_reset_config;
1519 }
1520 void jtag_set_reset_config(enum reset_types type)
1521 {
1522         jtag_reset_config = type;
1523 }
1524
1525 int jtag_get_trst(void)
1526 {
1527         return jtag_trst;
1528 }
1529 int jtag_get_srst(void)
1530 {
1531         return jtag_srst;
1532 }
1533
1534 void jtag_set_nsrst_delay(unsigned delay)
1535 {
1536         jtag_nsrst_delay = delay;
1537 }
1538 unsigned jtag_get_nsrst_delay(void)
1539 {
1540         return jtag_nsrst_delay;
1541 }
1542 void jtag_set_ntrst_delay(unsigned delay)
1543 {
1544         jtag_ntrst_delay = delay;
1545 }
1546 unsigned jtag_get_ntrst_delay(void)
1547 {
1548         return jtag_ntrst_delay;
1549 }
1550
1551
1552 void jtag_set_nsrst_assert_width(unsigned delay)
1553 {
1554         jtag_nsrst_assert_width = delay;
1555 }
1556 unsigned jtag_get_nsrst_assert_width(void)
1557 {
1558         return jtag_nsrst_assert_width;
1559 }
1560 void jtag_set_ntrst_assert_width(unsigned delay)
1561 {
1562         jtag_ntrst_assert_width = delay;
1563 }
1564 unsigned jtag_get_ntrst_assert_width(void)
1565 {
1566         return jtag_ntrst_assert_width;
1567 }