jtag/core: remove unused variable
[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
132 /* FIXME: change name to this variable, it is not anymore JTAG only */
133 static struct adapter_driver *jtag;
134
135 extern struct adapter_driver *adapter_driver;
136
137 void jtag_set_flush_queue_sleep(int ms)
138 {
139         jtag_flush_queue_sleep = ms;
140 }
141
142 void jtag_set_error(int error)
143 {
144         if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
145                 return;
146         jtag_error = error;
147 }
148
149 int jtag_error_clear(void)
150 {
151         int temp = jtag_error;
152         jtag_error = ERROR_OK;
153         return temp;
154 }
155
156 /************/
157
158 static bool jtag_poll = 1;
159
160 bool is_jtag_poll_safe(void)
161 {
162         /* Polling can be disabled explicitly with set_enabled(false).
163          * It is also implicitly disabled while TRST is active and
164          * while SRST is gating the JTAG clock.
165          */
166         if (!transport_is_jtag())
167                 return jtag_poll;
168
169         if (!jtag_poll || jtag_trst != 0)
170                 return false;
171         return jtag_srst == 0 || (jtag_reset_config & RESET_SRST_NO_GATING);
172 }
173
174 bool jtag_poll_get_enabled(void)
175 {
176         return jtag_poll;
177 }
178
179 void jtag_poll_set_enabled(bool value)
180 {
181         jtag_poll = value;
182 }
183
184 /************/
185
186 struct jtag_tap *jtag_all_taps(void)
187 {
188         return __jtag_all_taps;
189 };
190
191 unsigned jtag_tap_count(void)
192 {
193         struct jtag_tap *t = jtag_all_taps();
194         unsigned n = 0;
195         while (t) {
196                 n++;
197                 t = t->next_tap;
198         }
199         return n;
200 }
201
202 unsigned jtag_tap_count_enabled(void)
203 {
204         struct jtag_tap *t = jtag_all_taps();
205         unsigned n = 0;
206         while (t) {
207                 if (t->enabled)
208                         n++;
209                 t = t->next_tap;
210         }
211         return n;
212 }
213
214 /** Append a new TAP to the chain of all taps. */
215 static void jtag_tap_add(struct jtag_tap *t)
216 {
217         unsigned jtag_num_taps = 0;
218
219         struct jtag_tap **tap = &__jtag_all_taps;
220         while (*tap) {
221                 jtag_num_taps++;
222                 tap = &(*tap)->next_tap;
223         }
224         *tap = t;
225         t->abs_chain_position = jtag_num_taps;
226 }
227
228 /* returns a pointer to the n-th device in the scan chain */
229 struct jtag_tap *jtag_tap_by_position(unsigned n)
230 {
231         struct jtag_tap *t = jtag_all_taps();
232
233         while (t && n-- > 0)
234                 t = t->next_tap;
235
236         return t;
237 }
238
239 struct jtag_tap *jtag_tap_by_string(const char *s)
240 {
241         /* try by name first */
242         struct jtag_tap *t = jtag_all_taps();
243
244         while (t) {
245                 if (strcmp(t->dotted_name, s) == 0)
246                         return t;
247                 t = t->next_tap;
248         }
249
250         /* no tap found by name, so try to parse the name as a number */
251         unsigned n;
252         if (parse_uint(s, &n) != ERROR_OK)
253                 return NULL;
254
255         /* FIXME remove this numeric fallback code late June 2010, along
256          * with all info in the User's Guide that TAPs have numeric IDs.
257          * Also update "scan_chain" output to not display the numbers.
258          */
259         t = jtag_tap_by_position(n);
260         if (t)
261                 LOG_WARNING("Specify TAP '%s' by name, not number %u",
262                         t->dotted_name, n);
263
264         return t;
265 }
266
267 struct jtag_tap *jtag_tap_next_enabled(struct jtag_tap *p)
268 {
269         p = p ? p->next_tap : jtag_all_taps();
270         while (p) {
271                 if (p->enabled)
272                         return p;
273                 p = p->next_tap;
274         }
275         return NULL;
276 }
277
278 const char *jtag_tap_name(const struct jtag_tap *tap)
279 {
280         return (!tap) ? "(unknown)" : tap->dotted_name;
281 }
282
283
284 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
285 {
286         struct jtag_event_callback **callbacks_p = &jtag_event_callbacks;
287
288         if (!callback)
289                 return ERROR_COMMAND_SYNTAX_ERROR;
290
291         if (*callbacks_p) {
292                 while ((*callbacks_p)->next)
293                         callbacks_p = &((*callbacks_p)->next);
294                 callbacks_p = &((*callbacks_p)->next);
295         }
296
297         (*callbacks_p) = malloc(sizeof(struct jtag_event_callback));
298         (*callbacks_p)->callback = callback;
299         (*callbacks_p)->priv = priv;
300         (*callbacks_p)->next = NULL;
301
302         return ERROR_OK;
303 }
304
305 int jtag_unregister_event_callback(jtag_event_handler_t callback, void *priv)
306 {
307         struct jtag_event_callback **p = &jtag_event_callbacks, *temp;
308
309         if (!callback)
310                 return ERROR_COMMAND_SYNTAX_ERROR;
311
312         while (*p) {
313                 if (((*p)->priv != priv) || ((*p)->callback != callback)) {
314                         p = &(*p)->next;
315                         continue;
316                 }
317
318                 temp = *p;
319                 *p = (*p)->next;
320                 free(temp);
321         }
322
323         return ERROR_OK;
324 }
325
326 int jtag_call_event_callbacks(enum jtag_event event)
327 {
328         struct jtag_event_callback *callback = jtag_event_callbacks;
329
330         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
331
332         while (callback) {
333                 struct jtag_event_callback *next;
334
335                 /* callback may remove itself */
336                 next = callback->next;
337                 callback->callback(event, callback->priv);
338                 callback = next;
339         }
340
341         return ERROR_OK;
342 }
343
344 static void jtag_checks(void)
345 {
346         assert(jtag_trst == 0);
347 }
348
349 static void jtag_prelude(tap_state_t state)
350 {
351         jtag_checks();
352
353         assert(state != TAP_INVALID);
354
355         cmd_queue_cur_state = state;
356 }
357
358 void jtag_add_ir_scan_noverify(struct jtag_tap *active, const struct scan_field *in_fields,
359         tap_state_t state)
360 {
361         jtag_prelude(state);
362
363         int retval = interface_jtag_add_ir_scan(active, in_fields, state);
364         jtag_set_error(retval);
365 }
366
367 static void jtag_add_ir_scan_noverify_callback(struct jtag_tap *active,
368         int dummy,
369         const struct scan_field *in_fields,
370         tap_state_t state)
371 {
372         jtag_add_ir_scan_noverify(active, in_fields, state);
373 }
374
375 /* If fields->in_value is filled out, then the captured IR value will be checked */
376 void jtag_add_ir_scan(struct jtag_tap *active, struct scan_field *in_fields, tap_state_t state)
377 {
378         assert(state != TAP_RESET);
379
380         if (jtag_verify && jtag_verify_capture_ir) {
381                 /* 8 x 32 bit id's is enough for all invocations */
382
383                 /* if we are to run a verification of the ir scan, we need to get the input back.
384                  * We may have to allocate space if the caller didn't ask for the input back.
385                  */
386                 in_fields->check_value = active->expected;
387                 in_fields->check_mask = active->expected_mask;
388                 jtag_add_scan_check(active, jtag_add_ir_scan_noverify_callback, 1, in_fields,
389                         state);
390         } else
391                 jtag_add_ir_scan_noverify(active, in_fields, state);
392 }
393
394 void jtag_add_plain_ir_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
395         tap_state_t state)
396 {
397         assert(out_bits);
398         assert(state != TAP_RESET);
399
400         jtag_prelude(state);
401
402         int retval = interface_jtag_add_plain_ir_scan(
403                         num_bits, out_bits, in_bits, state);
404         jtag_set_error(retval);
405 }
406
407 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
408                                   uint8_t *in_check_mask, int num_bits);
409
410 static int jtag_check_value_mask_callback(jtag_callback_data_t data0,
411         jtag_callback_data_t data1,
412         jtag_callback_data_t data2,
413         jtag_callback_data_t data3)
414 {
415         return jtag_check_value_inner((uint8_t *)data0,
416                 (uint8_t *)data1,
417                 (uint8_t *)data2,
418                 (int)data3);
419 }
420
421 static void jtag_add_scan_check(struct jtag_tap *active, void (*jtag_add_scan)(
422                 struct jtag_tap *active,
423                 int in_num_fields,
424                 const struct scan_field *in_fields,
425                 tap_state_t state),
426         int in_num_fields, struct scan_field *in_fields, tap_state_t state)
427 {
428         jtag_add_scan(active, in_num_fields, in_fields, state);
429
430         for (int i = 0; i < in_num_fields; i++) {
431                 if ((in_fields[i].check_value) && (in_fields[i].in_value)) {
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);
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 between 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->jtag_ops->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                 jtag_execute_queue();
848
849         } else if (jtag_trst != new_trst) {
850                 jtag_trst = new_trst;
851                 if (jtag_trst) {
852                         LOG_DEBUG("TRST line asserted");
853                         tap_set_state(TAP_RESET);
854                         if (jtag_ntrst_assert_width)
855                                 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
856                 } else {
857                         LOG_DEBUG("TRST line released");
858                         if (jtag_ntrst_delay)
859                                 jtag_add_sleep(jtag_ntrst_delay * 1000);
860
861                         /* We just asserted nTRST, so we're now in TAP_RESET.
862                          * Inform possible listeners about this, now that
863                          * JTAG instructions and data can be shifted.  This
864                          * sequence must match jtag_add_tlr().
865                          */
866                         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
867                         jtag_notify_event(JTAG_TRST_ASSERTED);
868                 }
869         }
870 }
871
872 void jtag_add_sleep(uint32_t us)
873 {
874         /** @todo Here, keep_alive() appears to be a layering violation!!! */
875         keep_alive();
876         jtag_set_error(interface_jtag_add_sleep(us));
877 }
878
879 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
880         uint8_t *in_check_mask, int num_bits)
881 {
882         int retval = ERROR_OK;
883         int compare_failed;
884
885         if (in_check_mask)
886                 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
887         else
888                 compare_failed = buf_cmp(captured, in_check_value, num_bits);
889
890         if (compare_failed) {
891                 char *captured_str, *in_check_value_str;
892                 int bits = (num_bits > DEBUG_JTAG_IOZ) ? DEBUG_JTAG_IOZ : num_bits;
893
894                 /* NOTE:  we've lost diagnostic context here -- 'which tap' */
895
896                 captured_str = buf_to_hex_str(captured, bits);
897                 in_check_value_str = buf_to_hex_str(in_check_value, bits);
898
899                 LOG_WARNING("Bad value '%s' captured during DR or IR scan:",
900                         captured_str);
901                 LOG_WARNING(" check_value: 0x%s", in_check_value_str);
902
903                 free(captured_str);
904                 free(in_check_value_str);
905
906                 if (in_check_mask) {
907                         char *in_check_mask_str;
908
909                         in_check_mask_str = buf_to_hex_str(in_check_mask, bits);
910                         LOG_WARNING(" check_mask: 0x%s", in_check_mask_str);
911                         free(in_check_mask_str);
912                 }
913
914                 retval = ERROR_JTAG_QUEUE_FAILED;
915         }
916         return retval;
917 }
918
919 void jtag_check_value_mask(struct scan_field *field, uint8_t *value, uint8_t *mask)
920 {
921         assert(field->in_value);
922
923         if (!value) {
924                 /* no checking to do */
925                 return;
926         }
927
928         jtag_execute_queue_noclear();
929
930         int retval = jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
931         jtag_set_error(retval);
932 }
933
934 int default_interface_jtag_execute_queue(void)
935 {
936         if (!jtag) {
937                 LOG_ERROR("No JTAG interface configured yet.  "
938                         "Issue 'init' command in startup scripts "
939                         "before communicating with targets.");
940                 return ERROR_FAIL;
941         }
942
943         if (!transport_is_jtag()) {
944                 /*
945                  * FIXME: This should not happen!
946                  * There could be old code that queues jtag commands with non jtag interfaces so, for
947                  * the moment simply highlight it by log an error and return on empty execute_queue.
948                  * We should fix it quitting with assert(0) because it is an internal error.
949                  * The fix can be applied immediately after next release (v0.11.0 ?)
950                  */
951                 LOG_ERROR("JTAG API jtag_execute_queue() called on non JTAG interface");
952                 if (!jtag->jtag_ops || !jtag->jtag_ops->execute_queue)
953                         return ERROR_OK;
954         }
955
956         int result = jtag->jtag_ops->execute_queue();
957
958         struct jtag_command *cmd = jtag_command_queue;
959         while (debug_level >= LOG_LVL_DEBUG_IO && cmd) {
960                 switch (cmd->type) {
961                         case JTAG_SCAN:
962                                 LOG_DEBUG_IO("JTAG %s SCAN to %s",
963                                                 cmd->cmd.scan->ir_scan ? "IR" : "DR",
964                                                 tap_state_name(cmd->cmd.scan->end_state));
965                                 for (int i = 0; i < cmd->cmd.scan->num_fields; i++) {
966                                         struct scan_field *field = cmd->cmd.scan->fields + i;
967                                         if (field->out_value) {
968                                                 char *str = buf_to_hex_str(field->out_value, field->num_bits);
969                                                 LOG_DEBUG_IO("  %db out: %s", field->num_bits, str);
970                                                 free(str);
971                                         }
972                                         if (field->in_value) {
973                                                 char *str = buf_to_hex_str(field->in_value, field->num_bits);
974                                                 LOG_DEBUG_IO("  %db  in: %s", field->num_bits, str);
975                                                 free(str);
976                                         }
977                                 }
978                                 break;
979                         case JTAG_TLR_RESET:
980                                 LOG_DEBUG_IO("JTAG TLR RESET to %s",
981                                                 tap_state_name(cmd->cmd.statemove->end_state));
982                                 break;
983                         case JTAG_RUNTEST:
984                                 LOG_DEBUG_IO("JTAG RUNTEST %d cycles to %s",
985                                                 cmd->cmd.runtest->num_cycles,
986                                                 tap_state_name(cmd->cmd.runtest->end_state));
987                                 break;
988                         case JTAG_RESET:
989                                 {
990                                         const char *reset_str[3] = {
991                                                 "leave", "deassert", "assert"
992                                         };
993                                         LOG_DEBUG_IO("JTAG RESET %s TRST, %s SRST",
994                                                         reset_str[cmd->cmd.reset->trst + 1],
995                                                         reset_str[cmd->cmd.reset->srst + 1]);
996                                 }
997                                 break;
998                         case JTAG_PATHMOVE:
999                                 LOG_DEBUG_IO("JTAG PATHMOVE (TODO)");
1000                                 break;
1001                         case JTAG_SLEEP:
1002                                 LOG_DEBUG_IO("JTAG SLEEP (TODO)");
1003                                 break;
1004                         case JTAG_STABLECLOCKS:
1005                                 LOG_DEBUG_IO("JTAG STABLECLOCKS (TODO)");
1006                                 break;
1007                         case JTAG_TMS:
1008                                 LOG_DEBUG_IO("JTAG TMS (TODO)");
1009                                 break;
1010                         default:
1011                                 LOG_ERROR("Unknown JTAG command: %d", cmd->type);
1012                                 break;
1013                 }
1014                 cmd = cmd->next;
1015         }
1016
1017         return result;
1018 }
1019
1020 void jtag_execute_queue_noclear(void)
1021 {
1022         jtag_flush_queue_count++;
1023         jtag_set_error(interface_jtag_execute_queue());
1024
1025         if (jtag_flush_queue_sleep > 0) {
1026                 /* For debug purposes it can be useful to test performance
1027                  * or behavior when delaying after flushing the queue,
1028                  * e.g. to simulate long roundtrip times.
1029                  */
1030                 usleep(jtag_flush_queue_sleep * 1000);
1031         }
1032 }
1033
1034 int jtag_get_flush_queue_count(void)
1035 {
1036         return jtag_flush_queue_count;
1037 }
1038
1039 int jtag_execute_queue(void)
1040 {
1041         jtag_execute_queue_noclear();
1042         return jtag_error_clear();
1043 }
1044
1045 static int jtag_reset_callback(enum jtag_event event, void *priv)
1046 {
1047         struct jtag_tap *tap = priv;
1048
1049         if (event == JTAG_TRST_ASSERTED) {
1050                 tap->enabled = !tap->disabled_after_reset;
1051
1052                 /* current instruction is either BYPASS or IDCODE */
1053                 buf_set_ones(tap->cur_instr, tap->ir_length);
1054                 tap->bypass = 1;
1055         }
1056
1057         return ERROR_OK;
1058 }
1059
1060 /* sleep at least us microseconds. When we sleep more than 1000ms we
1061  * do an alive sleep, i.e. keep GDB alive. Note that we could starve
1062  * GDB if we slept for <1000ms many times.
1063  */
1064 void jtag_sleep(uint32_t us)
1065 {
1066         if (us < 1000)
1067                 usleep(us);
1068         else
1069                 alive_sleep((us+999)/1000);
1070 }
1071
1072 #define JTAG_MAX_AUTO_TAPS 20
1073
1074 #define EXTRACT_MFG(X)  (((X) & 0xffe) >> 1)
1075 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
1076 #define EXTRACT_VER(X)  (((X) & 0xf0000000) >> 28)
1077
1078 /* A reserved manufacturer ID is used in END_OF_CHAIN_FLAG, so we
1079  * know that no valid TAP will have it as an IDCODE value.
1080  */
1081 #define END_OF_CHAIN_FLAG       0xffffffff
1082
1083 /* a larger IR length than we ever expect to autoprobe */
1084 #define JTAG_IRLEN_MAX          60
1085
1086 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
1087 {
1088         struct scan_field field = {
1089                 .num_bits = num_idcode * 32,
1090                 .out_value = idcode_buffer,
1091                 .in_value = idcode_buffer,
1092         };
1093
1094         /* initialize to the end of chain ID value */
1095         for (unsigned i = 0; i < num_idcode; i++)
1096                 buf_set_u32(idcode_buffer, i * 32, 32, END_OF_CHAIN_FLAG);
1097
1098         jtag_add_plain_dr_scan(field.num_bits, field.out_value, field.in_value, TAP_DRPAUSE);
1099         jtag_add_tlr();
1100         return jtag_execute_queue();
1101 }
1102
1103 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
1104 {
1105         uint8_t zero_check = 0x0;
1106         uint8_t one_check = 0xff;
1107
1108         for (unsigned i = 0; i < count * 4; i++) {
1109                 zero_check |= idcodes[i];
1110                 one_check &= idcodes[i];
1111         }
1112
1113         /* if there wasn't a single non-zero bit or if all bits were one,
1114          * the scan is not valid.  We wrote a mix of both values; either
1115          *
1116          *  - There's a hardware issue (almost certainly):
1117          *     + all-zeroes can mean a target stuck in JTAG reset
1118          *     + all-ones tends to mean no target
1119          *  - The scan chain is WAY longer than we can handle, *AND* either
1120          *     + there are several hundreds of TAPs in bypass, or
1121          *     + at least a few dozen TAPs all have an all-ones IDCODE
1122          */
1123         if (zero_check == 0x00 || one_check == 0xff) {
1124                 LOG_ERROR("JTAG scan chain interrogation failed: all %s",
1125                         (zero_check == 0x00) ? "zeroes" : "ones");
1126                 LOG_ERROR("Check JTAG interface, timings, target power, etc.");
1127                 return false;
1128         }
1129         return true;
1130 }
1131
1132 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
1133         const char *name, uint32_t idcode)
1134 {
1135         log_printf_lf(level, __FILE__, __LINE__, __func__,
1136                 "JTAG tap: %s %16.16s: 0x%08x "
1137                 "(mfg: 0x%3.3x (%s), part: 0x%4.4x, ver: 0x%1.1x)",
1138                 name, msg,
1139                 (unsigned int)idcode,
1140                 (unsigned int)EXTRACT_MFG(idcode),
1141                 jep106_manufacturer(EXTRACT_MFG(idcode)),
1142                 (unsigned int)EXTRACT_PART(idcode),
1143                 (unsigned int)EXTRACT_VER(idcode));
1144 }
1145
1146 static bool jtag_idcode_is_final(uint32_t idcode)
1147 {
1148         /*
1149          * Some devices, such as AVR8, will output all 1's instead
1150          * of TDI input value at end of chain. Allow those values
1151          * instead of failing.
1152          */
1153         return idcode == END_OF_CHAIN_FLAG;
1154 }
1155
1156 /**
1157  * This helper checks that remaining bits in the examined chain data are
1158  * all as expected, but a single JTAG device requires only 64 bits to be
1159  * read back correctly.  This can help identify and diagnose problems
1160  * with the JTAG chain earlier, gives more helpful/explicit error messages.
1161  * Returns TRUE iff garbage was found.
1162  */
1163 static bool jtag_examine_chain_end(uint8_t *idcodes, unsigned count, unsigned max)
1164 {
1165         bool triggered = false;
1166         for (; count < max - 31; count += 32) {
1167                 uint32_t idcode = buf_get_u32(idcodes, count, 32);
1168
1169                 /* do not trigger the warning if the data looks good */
1170                 if (jtag_idcode_is_final(idcode))
1171                         continue;
1172                 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
1173                         count, (unsigned int)idcode);
1174                 triggered = true;
1175         }
1176         return triggered;
1177 }
1178
1179 static bool jtag_examine_chain_match_tap(const struct jtag_tap *tap)
1180 {
1181
1182         if (tap->expected_ids_cnt == 0 || !tap->hasidcode)
1183                 return true;
1184
1185         /* optionally ignore the JTAG version field - bits 28-31 of IDCODE */
1186         uint32_t mask = tap->ignore_version ? ~(0xfU << 28) : ~0U;
1187         uint32_t idcode = tap->idcode & mask;
1188
1189         /* Loop over the expected identification codes and test for a match */
1190         for (unsigned ii = 0; ii < tap->expected_ids_cnt; ii++) {
1191                 uint32_t expected = tap->expected_ids[ii] & mask;
1192
1193                 if (idcode == expected)
1194                         return true;
1195
1196                 /* treat "-expected-id 0" as a "don't-warn" wildcard */
1197                 if (tap->expected_ids[ii] == 0)
1198                         return true;
1199         }
1200
1201         /* If none of the expected ids matched, warn */
1202         jtag_examine_chain_display(LOG_LVL_WARNING, "UNEXPECTED",
1203                 tap->dotted_name, tap->idcode);
1204         for (unsigned ii = 0; ii < tap->expected_ids_cnt; ii++) {
1205                 char msg[32];
1206
1207                 snprintf(msg, sizeof(msg), "expected %u of %u", ii + 1, tap->expected_ids_cnt);
1208                 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
1209                         tap->dotted_name, tap->expected_ids[ii]);
1210         }
1211         return false;
1212 }
1213
1214 /* Try to examine chain layout according to IEEE 1149.1 Â§12
1215  * This is called a "blind interrogation" of the scan chain.
1216  */
1217 static int jtag_examine_chain(void)
1218 {
1219         int retval;
1220         unsigned max_taps = jtag_tap_count();
1221
1222         /* Autoprobe up to this many. */
1223         if (max_taps < JTAG_MAX_AUTO_TAPS)
1224                 max_taps = JTAG_MAX_AUTO_TAPS;
1225
1226         /* Add room for end-of-chain marker. */
1227         max_taps++;
1228
1229         uint8_t *idcode_buffer = calloc(4, max_taps);
1230         if (!idcode_buffer)
1231                 return ERROR_JTAG_INIT_FAILED;
1232
1233         /* DR scan to collect BYPASS or IDCODE register contents.
1234          * Then make sure the scan data has both ones and zeroes.
1235          */
1236         LOG_DEBUG("DR scan interrogation for IDCODE/BYPASS");
1237         retval = jtag_examine_chain_execute(idcode_buffer, max_taps);
1238         if (retval != ERROR_OK)
1239                 goto out;
1240         if (!jtag_examine_chain_check(idcode_buffer, max_taps)) {
1241                 retval = ERROR_JTAG_INIT_FAILED;
1242                 goto out;
1243         }
1244
1245         /* Point at the 1st predefined tap, if any */
1246         struct jtag_tap *tap = jtag_tap_next_enabled(NULL);
1247
1248         unsigned bit_count = 0;
1249         unsigned autocount = 0;
1250         for (unsigned i = 0; i < max_taps; i++) {
1251                 assert(bit_count < max_taps * 32);
1252                 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1253
1254                 /* No predefined TAP? Auto-probe. */
1255                 if (!tap) {
1256                         /* Is there another TAP? */
1257                         if (jtag_idcode_is_final(idcode))
1258                                 break;
1259
1260                         /* Default everything in this TAP except IR length.
1261                          *
1262                          * REVISIT create a jtag_alloc(chip, tap) routine, and
1263                          * share it with jim_newtap_cmd().
1264                          */
1265                         tap = calloc(1, sizeof(*tap));
1266                         if (!tap) {
1267                                 retval = ERROR_FAIL;
1268                                 goto out;
1269                         }
1270
1271                         tap->chip = alloc_printf("auto%u", autocount++);
1272                         tap->tapname = strdup("tap");
1273                         tap->dotted_name = alloc_printf("%s.%s", tap->chip, tap->tapname);
1274
1275                         tap->ir_length = 0; /* ... signifying irlen autoprobe */
1276                         tap->ir_capture_mask = 0x03;
1277                         tap->ir_capture_value = 0x01;
1278
1279                         tap->enabled = true;
1280
1281                         jtag_tap_init(tap);
1282                 }
1283
1284                 if ((idcode & 1) == 0) {
1285                         /* Zero for LSB indicates a device in bypass */
1286                         LOG_INFO("TAP %s does not have valid IDCODE (idcode=0x%" PRIx32 ")",
1287                                         tap->dotted_name, idcode);
1288                         tap->hasidcode = false;
1289                         tap->idcode = 0;
1290
1291                         bit_count += 1;
1292                 } else {
1293                         /* Friendly devices support IDCODE */
1294                         tap->hasidcode = true;
1295                         tap->idcode = idcode;
1296                         jtag_examine_chain_display(LOG_LVL_INFO, "tap/device found", tap->dotted_name, idcode);
1297
1298                         bit_count += 32;
1299                 }
1300
1301                 /* ensure the TAP ID matches what was expected */
1302                 if (!jtag_examine_chain_match_tap(tap))
1303                         retval = ERROR_JTAG_INIT_SOFT_FAIL;
1304
1305                 tap = jtag_tap_next_enabled(tap);
1306         }
1307
1308         /* After those IDCODE or BYPASS register values should be
1309          * only the data we fed into the scan chain.
1310          */
1311         if (jtag_examine_chain_end(idcode_buffer, bit_count, max_taps * 32)) {
1312                 LOG_ERROR("double-check your JTAG setup (interface, speed, ...)");
1313                 retval = ERROR_JTAG_INIT_FAILED;
1314                 goto out;
1315         }
1316
1317         /* Return success or, for backwards compatibility if only
1318          * some IDCODE values mismatched, a soft/continuable fault.
1319          */
1320 out:
1321         free(idcode_buffer);
1322         return retval;
1323 }
1324
1325 /*
1326  * Validate the date loaded by entry to the Capture-IR state, to help
1327  * find errors related to scan chain configuration (wrong IR lengths)
1328  * or communication.
1329  *
1330  * Entry state can be anything.  On non-error exit, all TAPs are in
1331  * bypass mode.  On error exits, the scan chain is reset.
1332  */
1333 static int jtag_validate_ircapture(void)
1334 {
1335         struct jtag_tap *tap;
1336         uint8_t *ir_test = NULL;
1337         struct scan_field field;
1338         int chain_pos = 0;
1339         int retval;
1340
1341         /* when autoprobing, accommodate huge IR lengths */
1342         int total_ir_length = 0;
1343         for (tap = jtag_tap_next_enabled(NULL); tap; tap = jtag_tap_next_enabled(tap)) {
1344                 if (tap->ir_length == 0)
1345                         total_ir_length += JTAG_IRLEN_MAX;
1346                 else
1347                         total_ir_length += tap->ir_length;
1348         }
1349
1350         /* increase length to add 2 bit sentinel after scan */
1351         total_ir_length += 2;
1352
1353         ir_test = malloc(DIV_ROUND_UP(total_ir_length, 8));
1354         if (!ir_test)
1355                 return ERROR_FAIL;
1356
1357         /* after this scan, all TAPs will capture BYPASS instructions */
1358         buf_set_ones(ir_test, total_ir_length);
1359
1360         field.num_bits = total_ir_length;
1361         field.out_value = ir_test;
1362         field.in_value = ir_test;
1363
1364         jtag_add_plain_ir_scan(field.num_bits, field.out_value, field.in_value, TAP_IDLE);
1365
1366         LOG_DEBUG("IR capture validation scan");
1367         retval = jtag_execute_queue();
1368         if (retval != ERROR_OK)
1369                 goto done;
1370
1371         tap = NULL;
1372         chain_pos = 0;
1373
1374         for (;; ) {
1375                 tap = jtag_tap_next_enabled(tap);
1376                 if (!tap)
1377                         break;
1378
1379                 /* If we're autoprobing, guess IR lengths.  They must be at
1380                  * least two bits.  Guessing will fail if (a) any TAP does
1381                  * not conform to the JTAG spec; or (b) when the upper bits
1382                  * captured from some conforming TAP are nonzero.  Or if
1383                  * (c) an IR length is longer than JTAG_IRLEN_MAX bits,
1384                  * an implementation limit, which could someday be raised.
1385                  *
1386                  * REVISIT optimization:  if there's a *single* TAP we can
1387                  * lift restrictions (a) and (b) by scanning a recognizable
1388                  * pattern before the all-ones BYPASS.  Check for where the
1389                  * pattern starts in the result, instead of an 0...01 value.
1390                  *
1391                  * REVISIT alternative approach: escape to some tcl code
1392                  * which could provide more knowledge, based on IDCODE; and
1393                  * only guess when that has no success.
1394                  */
1395                 if (tap->ir_length == 0) {
1396                         tap->ir_length = 2;
1397                         while (buf_get_u64(ir_test, chain_pos, tap->ir_length + 1) == 1
1398                                         && tap->ir_length < JTAG_IRLEN_MAX) {
1399                                 tap->ir_length++;
1400                         }
1401                         LOG_WARNING("AUTO %s - use \"jtag newtap %s %s -irlen %d "
1402                                         "-expected-id 0x%08" PRIx32 "\"",
1403                                         tap->dotted_name, tap->chip, tap->tapname, tap->ir_length, tap->idcode);
1404                 }
1405
1406                 /* Validate the two LSBs, which must be 01 per JTAG spec.
1407                  *
1408                  * Or ... more bits could be provided by TAP declaration.
1409                  * Plus, some taps (notably in i.MX series chips) violate
1410                  * this part of the JTAG spec, so their capture mask/value
1411                  * attributes might disable this test.
1412                  */
1413                 uint64_t val = buf_get_u64(ir_test, chain_pos, tap->ir_length);
1414                 if ((val & tap->ir_capture_mask) != tap->ir_capture_value) {
1415                         LOG_ERROR("%s: IR capture error; saw 0x%0*" PRIx64 " not 0x%0*" PRIx32,
1416                                 jtag_tap_name(tap),
1417                                 (tap->ir_length + 7) / tap->ir_length, val,
1418                                 (tap->ir_length + 7) / tap->ir_length, tap->ir_capture_value);
1419
1420                         retval = ERROR_JTAG_INIT_FAILED;
1421                         goto done;
1422                 }
1423                 LOG_DEBUG("%s: IR capture 0x%0*" PRIx64, jtag_tap_name(tap),
1424                         (tap->ir_length + 7) / tap->ir_length, val);
1425                 chain_pos += tap->ir_length;
1426         }
1427
1428         /* verify the '11' sentinel we wrote is returned at the end */
1429         uint64_t val = buf_get_u64(ir_test, chain_pos, 2);
1430         if (val != 0x3) {
1431                 char *cbuf = buf_to_hex_str(ir_test, total_ir_length);
1432
1433                 LOG_ERROR("IR capture error at bit %d, saw 0x%s not 0x...3",
1434                         chain_pos, cbuf);
1435                 free(cbuf);
1436                 retval = ERROR_JTAG_INIT_FAILED;
1437         }
1438
1439 done:
1440         free(ir_test);
1441         if (retval != ERROR_OK) {
1442                 jtag_add_tlr();
1443                 jtag_execute_queue();
1444         }
1445         return retval;
1446 }
1447
1448 void jtag_tap_init(struct jtag_tap *tap)
1449 {
1450         unsigned ir_len_bits;
1451         unsigned ir_len_bytes;
1452
1453         /* if we're autoprobing, cope with potentially huge ir_length */
1454         ir_len_bits = tap->ir_length ? tap->ir_length : JTAG_IRLEN_MAX;
1455         ir_len_bytes = DIV_ROUND_UP(ir_len_bits, 8);
1456
1457         tap->expected = calloc(1, ir_len_bytes);
1458         tap->expected_mask = calloc(1, ir_len_bytes);
1459         tap->cur_instr = malloc(ir_len_bytes);
1460
1461         /** @todo cope better with ir_length bigger than 32 bits */
1462         if (ir_len_bits > 32)
1463                 ir_len_bits = 32;
1464
1465         buf_set_u32(tap->expected, 0, ir_len_bits, tap->ir_capture_value);
1466         buf_set_u32(tap->expected_mask, 0, ir_len_bits, tap->ir_capture_mask);
1467
1468         /* TAP will be in bypass mode after jtag_validate_ircapture() */
1469         tap->bypass = 1;
1470         buf_set_ones(tap->cur_instr, tap->ir_length);
1471
1472         /* register the reset callback for the TAP */
1473         jtag_register_event_callback(&jtag_reset_callback, tap);
1474         jtag_tap_add(tap);
1475
1476         LOG_DEBUG("Created Tap: %s @ abs position %d, "
1477                         "irlen %d, capture: 0x%x mask: 0x%x", tap->dotted_name,
1478                         tap->abs_chain_position, tap->ir_length,
1479                         (unsigned) tap->ir_capture_value,
1480                         (unsigned) tap->ir_capture_mask);
1481 }
1482
1483 void jtag_tap_free(struct jtag_tap *tap)
1484 {
1485         jtag_unregister_event_callback(&jtag_reset_callback, tap);
1486
1487         struct jtag_tap_event_action *jteap = tap->event_action;
1488         while (jteap) {
1489                 struct jtag_tap_event_action *next = jteap->next;
1490                 Jim_DecrRefCount(jteap->interp, jteap->body);
1491                 free(jteap);
1492                 jteap = next;
1493         }
1494
1495         free(tap->expected);
1496         free(tap->expected_mask);
1497         free(tap->expected_ids);
1498         free(tap->cur_instr);
1499         free(tap->chip);
1500         free(tap->tapname);
1501         free(tap->dotted_name);
1502         free(tap);
1503 }
1504
1505 /**
1506  * Do low-level setup like initializing registers, output signals,
1507  * and clocking.
1508  */
1509 int adapter_init(struct command_context *cmd_ctx)
1510 {
1511         if (jtag)
1512                 return ERROR_OK;
1513
1514         if (!adapter_driver) {
1515                 /* nothing was previously specified by "adapter driver" command */
1516                 LOG_ERROR("Debug Adapter has to be specified, "
1517                         "see \"adapter driver\" command");
1518                 return ERROR_JTAG_INVALID_INTERFACE;
1519         }
1520
1521         int retval;
1522         retval = adapter_driver->init();
1523         if (retval != ERROR_OK)
1524                 return retval;
1525         jtag = adapter_driver;
1526
1527         if (!jtag->speed) {
1528                 LOG_INFO("This adapter doesn't support configurable speed");
1529                 return ERROR_OK;
1530         }
1531
1532         if (clock_mode == CLOCK_MODE_UNSELECTED) {
1533                 LOG_ERROR("An adapter speed is not selected in the init script."
1534                         " Insert a call to \"adapter speed\" or \"jtag_rclk\" to proceed.");
1535                 return ERROR_JTAG_INIT_FAILED;
1536         }
1537
1538         int requested_khz = jtag_get_speed_khz();
1539         int actual_khz = requested_khz;
1540         int jtag_speed_var = 0;
1541         retval = jtag_get_speed(&jtag_speed_var);
1542         if (retval != ERROR_OK)
1543                 return retval;
1544         retval = jtag->speed(jtag_speed_var);
1545         if (retval != ERROR_OK)
1546                 return retval;
1547         retval = jtag_get_speed_readable(&actual_khz);
1548         if (retval != ERROR_OK)
1549                 LOG_INFO("adapter-specific clock speed value %d", jtag_speed_var);
1550         else if (actual_khz) {
1551                 /* Adaptive clocking -- JTAG-specific */
1552                 if ((clock_mode == CLOCK_MODE_RCLK)
1553                                 || ((clock_mode == CLOCK_MODE_KHZ) && !requested_khz)) {
1554                         LOG_INFO("RCLK (adaptive clock speed) not supported - fallback to %d kHz"
1555                         , actual_khz);
1556                 } else
1557                         LOG_INFO("clock speed %d kHz", actual_khz);
1558         } else
1559                 LOG_INFO("RCLK (adaptive clock speed)");
1560
1561         return ERROR_OK;
1562 }
1563
1564 int jtag_init_inner(struct command_context *cmd_ctx)
1565 {
1566         struct jtag_tap *tap;
1567         int retval;
1568         bool issue_setup = true;
1569
1570         LOG_DEBUG("Init JTAG chain");
1571
1572         tap = jtag_tap_next_enabled(NULL);
1573         if (!tap) {
1574                 /* Once JTAG itself is properly set up, and the scan chain
1575                  * isn't absurdly large, IDCODE autoprobe should work fine.
1576                  *
1577                  * But ... IRLEN autoprobe can fail even on systems which
1578                  * are fully conformant to JTAG.  Also, JTAG setup can be
1579                  * quite finicky on some systems.
1580                  *
1581                  * REVISIT: if TAP autoprobe works OK, then in many cases
1582                  * we could escape to tcl code and set up targets based on
1583                  * the TAP's IDCODE values.
1584                  */
1585                 LOG_WARNING("There are no enabled taps.  "
1586                         "AUTO PROBING MIGHT NOT WORK!!");
1587
1588                 /* REVISIT default clock will often be too fast ... */
1589         }
1590
1591         jtag_add_tlr();
1592         retval = jtag_execute_queue();
1593         if (retval != ERROR_OK)
1594                 return retval;
1595
1596         /* Examine DR values first.  This discovers problems which will
1597          * prevent communication ... hardware issues like TDO stuck, or
1598          * configuring the wrong number of (enabled) TAPs.
1599          */
1600         retval = jtag_examine_chain();
1601         switch (retval) {
1602                 case ERROR_OK:
1603                         /* complete success */
1604                         break;
1605                 default:
1606                         /* For backward compatibility reasons, try coping with
1607                          * configuration errors involving only ID mismatches.
1608                          * We might be able to talk to the devices.
1609                          *
1610                          * Also the device might be powered down during startup.
1611                          *
1612                          * After OpenOCD starts, we can try to power on the device
1613                          * and run a reset.
1614                          */
1615                         LOG_ERROR("Trying to use configured scan chain anyway...");
1616                         issue_setup = false;
1617                         break;
1618         }
1619
1620         /* Now look at IR values.  Problems here will prevent real
1621          * communication.  They mostly mean that the IR length is
1622          * wrong ... or that the IR capture value is wrong.  (The
1623          * latter is uncommon, but easily worked around:  provide
1624          * ircapture/irmask values during TAP setup.)
1625          */
1626         retval = jtag_validate_ircapture();
1627         if (retval != ERROR_OK) {
1628                 /* The target might be powered down. The user
1629                  * can power it up and reset it after firing
1630                  * up OpenOCD.
1631                  */
1632                 issue_setup = false;
1633         }
1634
1635         if (issue_setup)
1636                 jtag_notify_event(JTAG_TAP_EVENT_SETUP);
1637         else
1638                 LOG_WARNING("Bypassing JTAG setup events due to errors");
1639
1640
1641         return ERROR_OK;
1642 }
1643
1644 int adapter_quit(void)
1645 {
1646         if (jtag && jtag->quit) {
1647                 /* close the JTAG interface */
1648                 int result = jtag->quit();
1649                 if (result != ERROR_OK)
1650                         LOG_ERROR("failed: %d", result);
1651         }
1652
1653         struct jtag_tap *t = jtag_all_taps();
1654         while (t) {
1655                 struct jtag_tap *n = t->next_tap;
1656                 jtag_tap_free(t);
1657                 t = n;
1658         }
1659
1660         return ERROR_OK;
1661 }
1662
1663 int swd_init_reset(struct command_context *cmd_ctx)
1664 {
1665         int retval, retval1;
1666
1667         retval = adapter_init(cmd_ctx);
1668         if (retval != ERROR_OK)
1669                 return retval;
1670
1671         LOG_DEBUG("Initializing with hard SRST reset");
1672
1673         if (jtag_reset_config & RESET_HAS_SRST)
1674                 retval = adapter_system_reset(1);
1675         retval1 = adapter_system_reset(0);
1676
1677         return (retval == ERROR_OK) ? retval1 : retval;
1678 }
1679
1680 int jtag_init_reset(struct command_context *cmd_ctx)
1681 {
1682         int retval = adapter_init(cmd_ctx);
1683         if (retval != ERROR_OK)
1684                 return retval;
1685
1686         LOG_DEBUG("Initializing with hard TRST+SRST reset");
1687
1688         /*
1689          * This procedure is used by default when OpenOCD triggers a reset.
1690          * It's now done through an overridable Tcl "init_reset" wrapper.
1691          *
1692          * This started out as a more powerful "get JTAG working" reset than
1693          * jtag_init_inner(), applying TRST because some chips won't activate
1694          * JTAG without a TRST cycle (presumed to be async, though some of
1695          * those chips synchronize JTAG activation using TCK).
1696          *
1697          * But some chips only activate JTAG as part of an SRST cycle; SRST
1698          * got mixed in.  So it became a hard reset routine, which got used
1699          * in more places, and which coped with JTAG reset being forced as
1700          * part of SRST (srst_pulls_trst).
1701          *
1702          * And even more corner cases started to surface:  TRST and/or SRST
1703          * assertion timings matter; some chips need other JTAG operations;
1704          * TRST/SRST sequences can need to be different from these, etc.
1705          *
1706          * Systems should override that wrapper to support system-specific
1707          * requirements that this not-fully-generic code doesn't handle.
1708          *
1709          * REVISIT once Tcl code can read the reset_config modes, this won't
1710          * need to be a C routine at all...
1711          */
1712         if (jtag_reset_config & RESET_HAS_SRST) {
1713                 jtag_add_reset(1, 1);
1714                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) == 0)
1715                         jtag_add_reset(0, 1);
1716         } else {
1717                 jtag_add_reset(1, 0);   /* TAP_RESET, using TMS+TCK or TRST */
1718         }
1719
1720         /* some targets enable us to connect with srst asserted */
1721         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1722                 if (jtag_reset_config & RESET_SRST_NO_GATING)
1723                         jtag_add_reset(0, 1);
1724                 else {
1725                         LOG_WARNING("\'srst_nogate\' reset_config option is required");
1726                         jtag_add_reset(0, 0);
1727                 }
1728         } else
1729                 jtag_add_reset(0, 0);
1730         retval = jtag_execute_queue();
1731         if (retval != ERROR_OK)
1732                 return retval;
1733
1734         /* Check that we can communication on the JTAG chain + eventually we want to
1735          * be able to perform enumeration only after OpenOCD has started
1736          * telnet and GDB server
1737          *
1738          * That would allow users to more easily perform any magic they need to before
1739          * reset happens.
1740          */
1741         return jtag_init_inner(cmd_ctx);
1742 }
1743
1744 int jtag_init(struct command_context *cmd_ctx)
1745 {
1746         int retval = adapter_init(cmd_ctx);
1747         if (retval != ERROR_OK)
1748                 return retval;
1749
1750         /* guard against oddball hardware: force resets to be inactive */
1751         jtag_add_reset(0, 0);
1752
1753         /* some targets enable us to connect with srst asserted */
1754         if (jtag_reset_config & RESET_CNCT_UNDER_SRST) {
1755                 if (jtag_reset_config & RESET_SRST_NO_GATING)
1756                         jtag_add_reset(0, 1);
1757                 else
1758                         LOG_WARNING("\'srst_nogate\' reset_config option is required");
1759         }
1760         retval = jtag_execute_queue();
1761         if (retval != ERROR_OK)
1762                 return retval;
1763
1764         if (Jim_Eval_Named(cmd_ctx->interp, "jtag_init", __FILE__, __LINE__) != JIM_OK)
1765                 return ERROR_FAIL;
1766
1767         return ERROR_OK;
1768 }
1769
1770 unsigned jtag_get_speed_khz(void)
1771 {
1772         return speed_khz;
1773 }
1774
1775 static int adapter_khz_to_speed(unsigned khz, int *speed)
1776 {
1777         LOG_DEBUG("convert khz to interface specific speed value");
1778         speed_khz = khz;
1779         if (!jtag)
1780                 return ERROR_OK;
1781         LOG_DEBUG("have interface set up");
1782         if (!jtag->khz) {
1783                 LOG_ERROR("Translation from khz to jtag_speed not implemented");
1784                 return ERROR_FAIL;
1785         }
1786         int speed_div1;
1787         int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1788         if (retval != ERROR_OK)
1789                 return retval;
1790         *speed = speed_div1;
1791         return ERROR_OK;
1792 }
1793
1794 static int jtag_rclk_to_speed(unsigned fallback_speed_khz, int *speed)
1795 {
1796         int retval = adapter_khz_to_speed(0, speed);
1797         if ((retval != ERROR_OK) && fallback_speed_khz) {
1798                 LOG_DEBUG("trying fallback speed...");
1799                 retval = adapter_khz_to_speed(fallback_speed_khz, speed);
1800         }
1801         return retval;
1802 }
1803
1804 static int jtag_set_speed(int speed)
1805 {
1806         /* this command can be called during CONFIG,
1807          * in which case jtag isn't initialized */
1808         return jtag ? jtag->speed(speed) : ERROR_OK;
1809 }
1810
1811 int jtag_config_khz(unsigned khz)
1812 {
1813         LOG_DEBUG("handle jtag khz");
1814         clock_mode = CLOCK_MODE_KHZ;
1815         int speed = 0;
1816         int retval = adapter_khz_to_speed(khz, &speed);
1817         return (retval != ERROR_OK) ? retval : jtag_set_speed(speed);
1818 }
1819
1820 int jtag_config_rclk(unsigned fallback_speed_khz)
1821 {
1822         LOG_DEBUG("handle jtag rclk");
1823         clock_mode = CLOCK_MODE_RCLK;
1824         rclk_fallback_speed_khz = fallback_speed_khz;
1825         int speed = 0;
1826         int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1827         return (retval != ERROR_OK) ? retval : jtag_set_speed(speed);
1828 }
1829
1830 int jtag_get_speed(int *speed)
1831 {
1832         switch (clock_mode) {
1833                 case CLOCK_MODE_KHZ:
1834                         adapter_khz_to_speed(jtag_get_speed_khz(), speed);
1835                         break;
1836                 case CLOCK_MODE_RCLK:
1837                         jtag_rclk_to_speed(rclk_fallback_speed_khz, speed);
1838                         break;
1839                 default:
1840                         LOG_ERROR("BUG: unknown jtag clock mode");
1841                         return ERROR_FAIL;
1842         }
1843         return ERROR_OK;
1844 }
1845
1846 int jtag_get_speed_readable(int *khz)
1847 {
1848         int jtag_speed_var = 0;
1849         int retval = jtag_get_speed(&jtag_speed_var);
1850         if (retval != ERROR_OK)
1851                 return retval;
1852         if (!jtag)
1853                 return ERROR_OK;
1854         if (!jtag->speed_div) {
1855                 LOG_ERROR("Translation from jtag_speed to khz not implemented");
1856                 return ERROR_FAIL;
1857         }
1858         return jtag->speed_div(jtag_speed_var, khz);
1859 }
1860
1861 void jtag_set_verify(bool enable)
1862 {
1863         jtag_verify = enable;
1864 }
1865
1866 bool jtag_will_verify(void)
1867 {
1868         return jtag_verify;
1869 }
1870
1871 void jtag_set_verify_capture_ir(bool enable)
1872 {
1873         jtag_verify_capture_ir = enable;
1874 }
1875
1876 bool jtag_will_verify_capture_ir(void)
1877 {
1878         return jtag_verify_capture_ir;
1879 }
1880
1881 int jtag_power_dropout(int *dropout)
1882 {
1883         if (!jtag) {
1884                 /* TODO: as the jtag interface is not valid all
1885                  * we can do at the moment is exit OpenOCD */
1886                 LOG_ERROR("No Valid JTAG Interface Configured.");
1887                 exit(-1);
1888         }
1889         if (jtag->power_dropout)
1890                 return jtag->power_dropout(dropout);
1891
1892         *dropout = 0; /* by default we can't detect power dropout */
1893         return ERROR_OK;
1894 }
1895
1896 int jtag_srst_asserted(int *srst_asserted)
1897 {
1898         if (jtag->srst_asserted)
1899                 return jtag->srst_asserted(srst_asserted);
1900
1901         *srst_asserted = 0; /* by default we can't detect srst asserted */
1902         return ERROR_OK;
1903 }
1904
1905 enum reset_types jtag_get_reset_config(void)
1906 {
1907         return jtag_reset_config;
1908 }
1909 void jtag_set_reset_config(enum reset_types type)
1910 {
1911         jtag_reset_config = type;
1912 }
1913
1914 int jtag_get_trst(void)
1915 {
1916         return jtag_trst == 1;
1917 }
1918 int jtag_get_srst(void)
1919 {
1920         return jtag_srst == 1;
1921 }
1922
1923 void jtag_set_nsrst_delay(unsigned delay)
1924 {
1925         adapter_nsrst_delay = delay;
1926 }
1927 unsigned jtag_get_nsrst_delay(void)
1928 {
1929         return adapter_nsrst_delay;
1930 }
1931 void jtag_set_ntrst_delay(unsigned delay)
1932 {
1933         jtag_ntrst_delay = delay;
1934 }
1935 unsigned jtag_get_ntrst_delay(void)
1936 {
1937         return jtag_ntrst_delay;
1938 }
1939
1940
1941 void jtag_set_nsrst_assert_width(unsigned delay)
1942 {
1943         adapter_nsrst_assert_width = delay;
1944 }
1945 unsigned jtag_get_nsrst_assert_width(void)
1946 {
1947         return adapter_nsrst_assert_width;
1948 }
1949 void jtag_set_ntrst_assert_width(unsigned delay)
1950 {
1951         jtag_ntrst_assert_width = delay;
1952 }
1953 unsigned jtag_get_ntrst_assert_width(void)
1954 {
1955         return jtag_ntrst_assert_width;
1956 }
1957
1958 static int jtag_select(struct command_context *ctx)
1959 {
1960         int retval;
1961
1962         /* NOTE:  interface init must already have been done.
1963          * That works with only C code ... no Tcl glue required.
1964          */
1965
1966         retval = jtag_register_commands(ctx);
1967
1968         if (retval != ERROR_OK)
1969                 return retval;
1970
1971         retval = svf_register_commands(ctx);
1972
1973         if (retval != ERROR_OK)
1974                 return retval;
1975
1976         retval = xsvf_register_commands(ctx);
1977
1978         if (retval != ERROR_OK)
1979                 return retval;
1980
1981         return ipdbg_register_commands(ctx);
1982 }
1983
1984 static struct transport jtag_transport = {
1985         .name = "jtag",
1986         .select = jtag_select,
1987         .init = jtag_init,
1988 };
1989
1990 static void jtag_constructor(void) __attribute__((constructor));
1991 static void jtag_constructor(void)
1992 {
1993         transport_register(&jtag_transport);
1994 }
1995
1996 /** Returns true if the current debug session
1997  * is using JTAG as its transport.
1998  */
1999 bool transport_is_jtag(void)
2000 {
2001         return get_current_transport() == &jtag_transport;
2002 }
2003
2004 int adapter_resets(int trst, int srst)
2005 {
2006         if (!get_current_transport()) {
2007                 LOG_ERROR("transport is not selected");
2008                 return ERROR_FAIL;
2009         }
2010
2011         if (transport_is_jtag()) {
2012                 if (srst == SRST_ASSERT && !(jtag_reset_config & RESET_HAS_SRST)) {
2013                         LOG_ERROR("adapter has no srst signal");
2014                         return ERROR_FAIL;
2015                 }
2016
2017                 /* adapters without trst signal will eventually use tlr sequence */
2018                 jtag_add_reset(trst, srst);
2019                 /*
2020                  * The jtag queue is still used for reset by some adapter. Flush it!
2021                  * FIXME: To be removed when all adapter drivers will be updated!
2022                  */
2023                 jtag_execute_queue();
2024                 return ERROR_OK;
2025         } else if (transport_is_swd() || transport_is_hla() ||
2026                            transport_is_dapdirect_swd() || transport_is_dapdirect_jtag() ||
2027                            transport_is_swim()) {
2028                 if (trst == TRST_ASSERT) {
2029                         LOG_ERROR("transport %s has no trst signal",
2030                                 get_current_transport()->name);
2031                         return ERROR_FAIL;
2032                 }
2033
2034                 if (srst == SRST_ASSERT && !(jtag_reset_config & RESET_HAS_SRST)) {
2035                         LOG_ERROR("adapter has no srst signal");
2036                         return ERROR_FAIL;
2037                 }
2038                 adapter_system_reset(srst);
2039                 return ERROR_OK;
2040         }
2041
2042         if (trst == TRST_DEASSERT && srst == SRST_DEASSERT)
2043                 return ERROR_OK;
2044
2045         LOG_ERROR("reset is not supported on transport %s",
2046                 get_current_transport()->name);
2047
2048         return ERROR_FAIL;
2049 }
2050
2051 int adapter_assert_reset(void)
2052 {
2053         if (transport_is_jtag()) {
2054                 if (jtag_reset_config & RESET_SRST_PULLS_TRST)
2055                         jtag_add_reset(1, 1);
2056                 else
2057                         jtag_add_reset(0, 1);
2058                 return ERROR_OK;
2059         } else if (transport_is_swd() || transport_is_hla() ||
2060                            transport_is_dapdirect_jtag() || transport_is_dapdirect_swd() ||
2061                            transport_is_swim())
2062                 return adapter_system_reset(1);
2063         else if (get_current_transport())
2064                 LOG_ERROR("reset is not supported on %s",
2065                         get_current_transport()->name);
2066         else
2067                 LOG_ERROR("transport is not selected");
2068         return ERROR_FAIL;
2069 }
2070
2071 int adapter_deassert_reset(void)
2072 {
2073         if (transport_is_jtag()) {
2074                 jtag_add_reset(0, 0);
2075                 return ERROR_OK;
2076         } else if (transport_is_swd() || transport_is_hla() ||
2077                            transport_is_dapdirect_jtag() || transport_is_dapdirect_swd() ||
2078                            transport_is_swim())
2079                 return adapter_system_reset(0);
2080         else if (get_current_transport())
2081                 LOG_ERROR("reset is not supported on %s",
2082                         get_current_transport()->name);
2083         else
2084                 LOG_ERROR("transport is not selected");
2085         return ERROR_FAIL;
2086 }
2087
2088 int adapter_config_trace(bool enabled, enum tpiu_pin_protocol pin_protocol,
2089                 uint32_t port_size, unsigned int *trace_freq,
2090                 unsigned int traceclkin_freq, uint16_t *prescaler)
2091 {
2092         if (jtag->config_trace) {
2093                 return jtag->config_trace(enabled, pin_protocol, port_size, trace_freq,
2094                         traceclkin_freq, prescaler);
2095         } else if (enabled) {
2096                 LOG_ERROR("The selected interface does not support tracing");
2097                 return ERROR_FAIL;
2098         }
2099
2100         return ERROR_OK;
2101 }
2102
2103 int adapter_poll_trace(uint8_t *buf, size_t *size)
2104 {
2105         if (jtag->poll_trace)
2106                 return jtag->poll_trace(buf, size);
2107
2108         return ERROR_FAIL;
2109 }