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