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