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