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