jtag: remove minidriver code and minidriver-dummy
[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
39 #ifdef HAVE_STRINGS_H
40 #include <strings.h>
41 #endif
42
43 /* SVF and XSVF are higher level JTAG command sets (for boundary scan) */
44 #include "svf/svf.h"
45 #include "xsvf/xsvf.h"
46
47 /** The number of JTAG queue flushes (for profiling and debugging purposes). */
48 static int jtag_flush_queue_count;
49
50 /* Sleep this # of ms after flushing the queue */
51 static int jtag_flush_queue_sleep;
52
53 static void jtag_add_scan_check(struct jtag_tap *active,
54                 void (*jtag_add_scan)(struct jtag_tap *active,
55                 int in_num_fields,
56                 const struct scan_field *in_fields,
57                 tap_state_t state),
58                 int in_num_fields, struct scan_field *in_fields, tap_state_t state);
59
60 /**
61  * The jtag_error variable is set when an error occurs while executing
62  * the queue.  Application code may set this using jtag_set_error(),
63  * when an error occurs during processing that should be reported during
64  * jtag_execute_queue().
65  *
66  * The value is set and cleared, but never read by normal application code.
67  *
68  * This value is returned (and cleared) by jtag_execute_queue().
69  */
70 static int jtag_error = ERROR_OK;
71
72 static const char *jtag_event_strings[] = {
73         [JTAG_TRST_ASSERTED] = "TAP reset",
74         [JTAG_TAP_EVENT_SETUP] = "TAP setup",
75         [JTAG_TAP_EVENT_ENABLE] = "TAP enabled",
76         [JTAG_TAP_EVENT_DISABLE] = "TAP disabled",
77 };
78
79 /*
80  * JTAG adapters must initialize with TRST and SRST de-asserted
81  * (they're negative logic, so that means *high*).  But some
82  * hardware doesn't necessarily work that way ... so set things
83  * up so that jtag_init() always forces that state.
84  */
85 static int jtag_trst = -1;
86 static int jtag_srst = -1;
87
88 /**
89  * List all TAPs that have been created.
90  */
91 static struct jtag_tap *__jtag_all_taps;
92
93 static enum reset_types jtag_reset_config = RESET_NONE;
94 tap_state_t cmd_queue_cur_state = TAP_RESET;
95
96 static bool jtag_verify_capture_ir = true;
97 static int jtag_verify = 1;
98
99 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines
100  *deasserted (in ms) */
101 static int adapter_nsrst_delay; /* default to no nSRST delay */
102 static int jtag_ntrst_delay;/* default to no nTRST delay */
103 static int adapter_nsrst_assert_width;  /* width of assertion */
104 static int jtag_ntrst_assert_width;     /* width of assertion */
105
106 /**
107  * Contains a single callback along with a pointer that will be passed
108  * when an event occurs.
109  */
110 struct jtag_event_callback {
111         /** a event callback */
112         jtag_event_handler_t callback;
113         /** the private data to pass to the callback */
114         void *priv;
115         /** the next callback */
116         struct jtag_event_callback *next;
117 };
118
119 /* callbacks to inform high-level handlers about JTAG state changes */
120 static struct jtag_event_callback *jtag_event_callbacks;
121
122 /* speed in kHz*/
123 static int speed_khz;
124 /* speed to fallback to when RCLK is requested but not supported */
125 static int rclk_fallback_speed_khz;
126 static enum {CLOCK_MODE_UNSELECTED, CLOCK_MODE_KHZ, CLOCK_MODE_RCLK} clock_mode;
127 static int jtag_speed;
128
129 /* FIXME: change name to this variable, it is not anymore JTAG only */
130 static struct adapter_driver *jtag;
131
132 extern struct adapter_driver *adapter_driver;
133
134 void jtag_set_flush_queue_sleep(int ms)
135 {
136         jtag_flush_queue_sleep = ms;
137 }
138
139 void jtag_set_error(int error)
140 {
141         if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
142                 return;
143         jtag_error = error;
144 }
145
146 int jtag_error_clear(void)
147 {
148         int temp = jtag_error;
149         jtag_error = ERROR_OK;
150         return temp;
151 }
152
153 /************/
154
155 static bool jtag_poll = 1;
156
157 bool is_jtag_poll_safe(void)
158 {
159         /* Polling can be disabled explicitly with set_enabled(false).
160          * It is also implicitly disabled while TRST is active and
161          * while SRST is gating the JTAG clock.
162          */
163         if (!transport_is_jtag())
164                 return jtag_poll;
165
166         if (!jtag_poll || jtag_trst != 0)
167                 return false;
168         return jtag_srst == 0 || (jtag_reset_config & RESET_SRST_NO_GATING);
169 }
170
171 bool jtag_poll_get_enabled(void)
172 {
173         return jtag_poll;
174 }
175
176 void jtag_poll_set_enabled(bool value)
177 {
178         jtag_poll = value;
179 }
180
181 /************/
182
183 struct jtag_tap *jtag_all_taps(void)
184 {
185         return __jtag_all_taps;
186 };
187
188 unsigned jtag_tap_count(void)
189 {
190         struct jtag_tap *t = jtag_all_taps();
191         unsigned n = 0;
192         while (t) {
193                 n++;
194                 t = t->next_tap;
195         }
196         return n;
197 }
198
199 unsigned jtag_tap_count_enabled(void)
200 {
201         struct jtag_tap *t = jtag_all_taps();
202         unsigned n = 0;
203         while (t) {
204                 if (t->enabled)
205                         n++;
206                 t = t->next_tap;
207         }
208         return n;
209 }
210
211 /** Append a new TAP to the chain of all taps. */
212 static void jtag_tap_add(struct jtag_tap *t)
213 {
214         unsigned jtag_num_taps = 0;
215
216         struct jtag_tap **tap = &__jtag_all_taps;
217         while (*tap != NULL) {
218                 jtag_num_taps++;
219                 tap = &(*tap)->next_tap;
220         }
221         *tap = t;
222         t->abs_chain_position = jtag_num_taps;
223 }
224
225 /* returns a pointer to the n-th device in the scan chain */
226 struct jtag_tap *jtag_tap_by_position(unsigned n)
227 {
228         struct jtag_tap *t = jtag_all_taps();
229
230         while (t && n-- > 0)
231                 t = t->next_tap;
232
233         return t;
234 }
235
236 struct jtag_tap *jtag_tap_by_string(const char *s)
237 {
238         /* try by name first */
239         struct jtag_tap *t = jtag_all_taps();
240
241         while (t) {
242                 if (0 == strcmp(t->dotted_name, s))
243                         return t;
244                 t = t->next_tap;
245         }
246
247         /* no tap found by name, so try to parse the name as a number */
248         unsigned n;
249         if (parse_uint(s, &n) != ERROR_OK)
250                 return NULL;
251
252         /* FIXME remove this numeric fallback code late June 2010, along
253          * with all info in the User's Guide that TAPs have numeric IDs.
254          * Also update "scan_chain" output to not display the numbers.
255          */
256         t = jtag_tap_by_position(n);
257         if (t)
258                 LOG_WARNING("Specify TAP '%s' by name, not number %u",
259                         t->dotted_name, n);
260
261         return t;
262 }
263
264 struct jtag_tap *jtag_tap_next_enabled(struct jtag_tap *p)
265 {
266         p = p ? p->next_tap : jtag_all_taps();
267         while (p) {
268                 if (p->enabled)
269                         return p;
270                 p = p->next_tap;
271         }
272         return NULL;
273 }
274
275 const char *jtag_tap_name(const struct jtag_tap *tap)
276 {
277         return (tap == NULL) ? "(unknown)" : tap->dotted_name;
278 }
279
280
281 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
282 {
283         struct jtag_event_callback **callbacks_p = &jtag_event_callbacks;
284
285         if (callback == NULL)
286                 return ERROR_COMMAND_SYNTAX_ERROR;
287
288         if (*callbacks_p) {
289                 while ((*callbacks_p)->next)
290                         callbacks_p = &((*callbacks_p)->next);
291                 callbacks_p = &((*callbacks_p)->next);
292         }
293
294         (*callbacks_p) = malloc(sizeof(struct jtag_event_callback));
295         (*callbacks_p)->callback = callback;
296         (*callbacks_p)->priv = priv;
297         (*callbacks_p)->next = NULL;
298
299         return ERROR_OK;
300 }
301
302 int jtag_unregister_event_callback(jtag_event_handler_t callback, void *priv)
303 {
304         struct jtag_event_callback **p = &jtag_event_callbacks, *temp;
305
306         if (callback == NULL)
307                 return ERROR_COMMAND_SYNTAX_ERROR;
308
309         while (*p) {
310                 if (((*p)->priv != priv) || ((*p)->callback != callback)) {
311                         p = &(*p)->next;
312                         continue;
313                 }
314
315                 temp = *p;
316                 *p = (*p)->next;
317                 free(temp);
318         }
319
320         return ERROR_OK;
321 }
322
323 int jtag_call_event_callbacks(enum jtag_event event)
324 {
325         struct jtag_event_callback *callback = jtag_event_callbacks;
326
327         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
328
329         while (callback) {
330                 struct jtag_event_callback *next;
331
332                 /* callback may remove itself */
333                 next = callback->next;
334                 callback->callback(event, callback->priv);
335                 callback = next;
336         }
337
338         return ERROR_OK;
339 }
340
341 static void jtag_checks(void)
342 {
343         assert(jtag_trst == 0);
344 }
345
346 static void jtag_prelude(tap_state_t state)
347 {
348         jtag_checks();
349
350         assert(state != TAP_INVALID);
351
352         cmd_queue_cur_state = state;
353 }
354
355 void jtag_add_ir_scan_noverify(struct jtag_tap *active, const struct scan_field *in_fields,
356         tap_state_t state)
357 {
358         jtag_prelude(state);
359
360         int retval = interface_jtag_add_ir_scan(active, in_fields, state);
361         jtag_set_error(retval);
362 }
363
364 static void jtag_add_ir_scan_noverify_callback(struct jtag_tap *active,
365         int dummy,
366         const struct scan_field *in_fields,
367         tap_state_t state)
368 {
369         jtag_add_ir_scan_noverify(active, in_fields, state);
370 }
371
372 /* If fields->in_value is filled out, then the captured IR value will be checked */
373 void jtag_add_ir_scan(struct jtag_tap *active, struct scan_field *in_fields, tap_state_t state)
374 {
375         assert(state != TAP_RESET);
376
377         if (jtag_verify && jtag_verify_capture_ir) {
378                 /* 8 x 32 bit id's is enough for all invocations */
379
380                 /* if we are to run a verification of the ir scan, we need to get the input back.
381                  * We may have to allocate space if the caller didn't ask for the input back.
382                  */
383                 in_fields->check_value = active->expected;
384                 in_fields->check_mask = active->expected_mask;
385                 jtag_add_scan_check(active, jtag_add_ir_scan_noverify_callback, 1, in_fields,
386                         state);
387         } else
388                 jtag_add_ir_scan_noverify(active, in_fields, state);
389 }
390
391 void jtag_add_plain_ir_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
392         tap_state_t state)
393 {
394         assert(out_bits != NULL);
395         assert(state != TAP_RESET);
396
397         jtag_prelude(state);
398
399         int retval = interface_jtag_add_plain_ir_scan(
400                         num_bits, out_bits, in_bits, state);
401         jtag_set_error(retval);
402 }
403
404 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
405                                   uint8_t *in_check_mask, int num_bits);
406
407 static int jtag_check_value_mask_callback(jtag_callback_data_t data0,
408         jtag_callback_data_t data1,
409         jtag_callback_data_t data2,
410         jtag_callback_data_t data3)
411 {
412         return jtag_check_value_inner((uint8_t *)data0,
413                 (uint8_t *)data1,
414                 (uint8_t *)data2,
415                 (int)data3);
416 }
417
418 static void jtag_add_scan_check(struct jtag_tap *active, void (*jtag_add_scan)(
419                 struct jtag_tap *active,
420                 int in_num_fields,
421                 const struct scan_field *in_fields,
422                 tap_state_t state),
423         int in_num_fields, struct scan_field *in_fields, tap_state_t state)
424 {
425         jtag_add_scan(active, in_num_fields, in_fields, state);
426
427         for (int i = 0; i < in_num_fields; i++) {
428                 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL)) {
429                         jtag_add_callback4(jtag_check_value_mask_callback,
430                                 (jtag_callback_data_t)in_fields[i].in_value,
431                                 (jtag_callback_data_t)in_fields[i].check_value,
432                                 (jtag_callback_data_t)in_fields[i].check_mask,
433                                 (jtag_callback_data_t)in_fields[i].num_bits);
434                 }
435         }
436 }
437
438 void jtag_add_dr_scan_check(struct jtag_tap *active,
439         int in_num_fields,
440         struct scan_field *in_fields,
441         tap_state_t state)
442 {
443         if (jtag_verify)
444                 jtag_add_scan_check(active, jtag_add_dr_scan, in_num_fields, in_fields, state);
445         else
446                 jtag_add_dr_scan(active, in_num_fields, in_fields, state);
447 }
448
449
450 void jtag_add_dr_scan(struct jtag_tap *active,
451         int in_num_fields,
452         const struct scan_field *in_fields,
453         tap_state_t state)
454 {
455         assert(state != TAP_RESET);
456
457         jtag_prelude(state);
458
459         int retval;
460         retval = interface_jtag_add_dr_scan(active, in_num_fields, in_fields, state);
461         jtag_set_error(retval);
462 }
463
464 void jtag_add_plain_dr_scan(int num_bits, const uint8_t *out_bits, uint8_t *in_bits,
465         tap_state_t state)
466 {
467         assert(out_bits != NULL);
468         assert(state != TAP_RESET);
469
470         jtag_prelude(state);
471
472         int retval;
473         retval = interface_jtag_add_plain_dr_scan(num_bits, out_bits, in_bits, state);
474         jtag_set_error(retval);
475 }
476
477 void jtag_add_tlr(void)
478 {
479         jtag_prelude(TAP_RESET);
480         jtag_set_error(interface_jtag_add_tlr());
481
482         /* NOTE: order here matches TRST path in jtag_add_reset() */
483         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
484         jtag_notify_event(JTAG_TRST_ASSERTED);
485 }
486
487 /**
488  * If supported by the underlying adapter, this clocks a raw bit sequence
489  * onto TMS for switching betwen JTAG and SWD modes.
490  *
491  * DO NOT use this to bypass the integrity checks and logging provided
492  * by the jtag_add_pathmove() and jtag_add_statemove() calls.
493  *
494  * @param nbits How many bits to clock out.
495  * @param seq The bit sequence.  The LSB is bit 0 of seq[0].
496  * @param state The JTAG tap state to record on completion.  Use
497  *      TAP_INVALID to represent being in in SWD mode.
498  *
499  * @todo Update naming conventions to stop assuming everything is JTAG.
500  */
501 int jtag_add_tms_seq(unsigned nbits, const uint8_t *seq, enum tap_state state)
502 {
503         int retval;
504
505         if (!(jtag->jtag_ops->supported & DEBUG_CAP_TMS_SEQ))
506                 return ERROR_JTAG_NOT_IMPLEMENTED;
507
508         jtag_checks();
509         cmd_queue_cur_state = state;
510
511         retval = interface_add_tms_seq(nbits, seq, state);
512         jtag_set_error(retval);
513         return retval;
514 }
515
516 void jtag_add_pathmove(int num_states, const tap_state_t *path)
517 {
518         tap_state_t cur_state = cmd_queue_cur_state;
519
520         /* the last state has to be a stable state */
521         if (!tap_is_state_stable(path[num_states - 1])) {
522                 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
523                 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
524                 return;
525         }
526
527         for (int i = 0; i < num_states; i++) {
528                 if (path[i] == TAP_RESET) {
529                         LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
530                         jtag_set_error(ERROR_JTAG_STATE_INVALID);
531                         return;
532                 }
533
534                 if (tap_state_transition(cur_state, true) != path[i] &&
535                                 tap_state_transition(cur_state, false) != path[i]) {
536                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
537                                 tap_state_name(cur_state), tap_state_name(path[i]));
538                         jtag_set_error(ERROR_JTAG_TRANSITION_INVALID);
539                         return;
540                 }
541                 cur_state = path[i];
542         }
543
544         jtag_checks();
545
546         jtag_set_error(interface_jtag_add_pathmove(num_states, path));
547         cmd_queue_cur_state = path[num_states - 1];
548 }
549
550 int jtag_add_statemove(tap_state_t goal_state)
551 {
552         tap_state_t cur_state = cmd_queue_cur_state;
553
554         if (goal_state != cur_state) {
555                 LOG_DEBUG("cur_state=%s goal_state=%s",
556                         tap_state_name(cur_state),
557                         tap_state_name(goal_state));
558         }
559
560         /* If goal is RESET, be paranoid and force that that transition
561          * (e.g. five TCK cycles, TMS high).  Else trust "cur_state".
562          */
563         if (goal_state == TAP_RESET)
564                 jtag_add_tlr();
565         else if (goal_state == cur_state)
566                 /* nothing to do */;
567
568         else if (tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state)) {
569                 unsigned tms_bits  = tap_get_tms_path(cur_state, goal_state);
570                 unsigned tms_count = tap_get_tms_path_len(cur_state, goal_state);
571                 tap_state_t moves[8];
572                 assert(tms_count < ARRAY_SIZE(moves));
573
574                 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1) {
575                         bool bit = tms_bits & 1;
576
577                         cur_state = tap_state_transition(cur_state, bit);
578                         moves[i] = cur_state;
579                 }
580
581                 jtag_add_pathmove(tms_count, moves);
582         } else if (tap_state_transition(cur_state, true)  == goal_state
583                         || tap_state_transition(cur_state, false) == goal_state)
584                 jtag_add_pathmove(1, &goal_state);
585         else
586                 return ERROR_FAIL;
587
588         return ERROR_OK;
589 }
590
591 void jtag_add_runtest(int num_cycles, tap_state_t state)
592 {
593         jtag_prelude(state);
594         jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
595 }
596
597
598 void jtag_add_clocks(int num_cycles)
599 {
600         if (!tap_is_state_stable(cmd_queue_cur_state)) {
601                 LOG_ERROR("jtag_add_clocks() called with TAP in unstable state \"%s\"",
602                         tap_state_name(cmd_queue_cur_state));
603                 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
604                 return;
605         }
606
607         if (num_cycles > 0) {
608                 jtag_checks();
609                 jtag_set_error(interface_jtag_add_clocks(num_cycles));
610         }
611 }
612
613 static int adapter_system_reset(int req_srst)
614 {
615         int retval;
616
617         if (req_srst) {
618                 if (!(jtag_reset_config & RESET_HAS_SRST)) {
619                         LOG_ERROR("BUG: can't assert SRST");
620                         return ERROR_FAIL;
621                 }
622                 req_srst = 1;
623         }
624
625         /* Maybe change SRST signal state */
626         if (jtag_srst != req_srst) {
627                 retval = jtag->reset(0, req_srst);
628                 if (retval != ERROR_OK) {
629                         LOG_ERROR("SRST error");
630                         return ERROR_FAIL;
631                 }
632                 jtag_srst = req_srst;
633
634                 if (req_srst) {
635                         LOG_DEBUG("SRST line asserted");
636                         if (adapter_nsrst_assert_width)
637                                 jtag_sleep(adapter_nsrst_assert_width * 1000);
638                 } else {
639                         LOG_DEBUG("SRST line released");
640                         if (adapter_nsrst_delay)
641                                 jtag_sleep(adapter_nsrst_delay * 1000);
642                 }
643         }
644
645         return ERROR_OK;
646 }
647
648 static void legacy_jtag_add_reset(int req_tlr_or_trst, int req_srst)
649 {
650         int trst_with_tlr = 0;
651         int new_srst = 0;
652         int new_trst = 0;
653
654         /* Without SRST, we must use target-specific JTAG operations
655          * on each target; callers should not be requesting SRST when
656          * that signal doesn't exist.
657          *
658          * RESET_SRST_PULLS_TRST is a board or chip level quirk, which
659          * can kick in even if the JTAG adapter can't drive TRST.
660          */
661         if (req_srst) {
662                 if (!(jtag_reset_config & RESET_HAS_SRST)) {
663                         LOG_ERROR("BUG: can't assert SRST");
664                         jtag_set_error(ERROR_FAIL);
665                         return;
666                 }
667                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) != 0
668                                 && !req_tlr_or_trst) {
669                         LOG_ERROR("BUG: can't assert only SRST");
670                         jtag_set_error(ERROR_FAIL);
671                         return;
672                 }
673                 new_srst = 1;
674         }
675
676         /* JTAG reset (entry to TAP_RESET state) can always be achieved
677          * using TCK and TMS; that may go through a TAP_{IR,DR}UPDATE
678          * state first.  TRST accelerates it, and bypasses those states.
679          *
680          * RESET_TRST_PULLS_SRST is a board or chip level quirk, which
681          * can kick in even if the JTAG adapter can't drive SRST.
682          */
683         if (req_tlr_or_trst) {
684                 if (!(jtag_reset_config & RESET_HAS_TRST))
685                         trst_with_tlr = 1;
686                 else if ((jtag_reset_config & RESET_TRST_PULLS_SRST) != 0
687                          && !req_srst)
688                         trst_with_tlr = 1;
689                 else
690                         new_trst = 1;
691         }
692
693         /* Maybe change TRST and/or SRST signal state */
694         if (jtag_srst != new_srst || jtag_trst != new_trst) {
695                 int retval;
696
697                 retval = interface_jtag_add_reset(new_trst, new_srst);
698                 if (retval != ERROR_OK)
699                         jtag_set_error(retval);
700                 else
701                         retval = jtag_execute_queue();
702
703                 if (retval != ERROR_OK) {
704                         LOG_ERROR("TRST/SRST error");
705                         return;
706                 }
707         }
708
709         /* SRST resets everything hooked up to that signal */
710         if (jtag_srst != new_srst) {
711                 jtag_srst = new_srst;
712                 if (jtag_srst) {
713                         LOG_DEBUG("SRST line asserted");
714                         if (adapter_nsrst_assert_width)
715                                 jtag_add_sleep(adapter_nsrst_assert_width * 1000);
716                 } else {
717                         LOG_DEBUG("SRST line released");
718                         if (adapter_nsrst_delay)
719                                 jtag_add_sleep(adapter_nsrst_delay * 1000);
720                 }
721         }
722
723         /* Maybe enter the JTAG TAP_RESET state ...
724          *  - using only TMS, TCK, and the JTAG state machine
725          *  - or else more directly, using TRST
726          *
727          * TAP_RESET should be invisible to non-debug parts of the system.
728          */
729         if (trst_with_tlr) {
730                 LOG_DEBUG("JTAG reset with TLR instead of TRST");
731                 jtag_add_tlr();
732
733         } else if (jtag_trst != new_trst) {
734                 jtag_trst = new_trst;
735                 if (jtag_trst) {
736                         LOG_DEBUG("TRST line asserted");
737                         tap_set_state(TAP_RESET);
738                         if (jtag_ntrst_assert_width)
739                                 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
740                 } else {
741                         LOG_DEBUG("TRST line released");
742                         if (jtag_ntrst_delay)
743                                 jtag_add_sleep(jtag_ntrst_delay * 1000);
744
745                         /* We just asserted nTRST, so we're now in TAP_RESET.
746                          * Inform possible listeners about this, now that
747                          * JTAG instructions and data can be shifted.  This
748                          * sequence must match jtag_add_tlr().
749                          */
750                         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
751                         jtag_notify_event(JTAG_TRST_ASSERTED);
752                 }
753         }
754 }
755
756 /* FIXME: name is misleading; we do not plan to "add" reset into jtag queue */
757 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
758 {
759         int retval;
760         int trst_with_tlr = 0;
761         int new_srst = 0;
762         int new_trst = 0;
763
764         if (!jtag->reset) {
765                 legacy_jtag_add_reset(req_tlr_or_trst, req_srst);
766                 return;
767         }
768
769         /* Without SRST, we must use target-specific JTAG operations
770          * on each target; callers should not be requesting SRST when
771          * that signal doesn't exist.
772          *
773          * RESET_SRST_PULLS_TRST is a board or chip level quirk, which
774          * can kick in even if the JTAG adapter can't drive TRST.
775          */
776         if (req_srst) {
777                 if (!(jtag_reset_config & RESET_HAS_SRST)) {
778                         LOG_ERROR("BUG: can't assert SRST");
779                         jtag_set_error(ERROR_FAIL);
780                         return;
781                 }
782                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST) != 0
783                                 && !req_tlr_or_trst) {
784                         LOG_ERROR("BUG: can't assert only SRST");
785                         jtag_set_error(ERROR_FAIL);
786                         return;
787                 }
788                 new_srst = 1;
789         }
790
791         /* JTAG reset (entry to TAP_RESET state) can always be achieved
792          * using TCK and TMS; that may go through a TAP_{IR,DR}UPDATE
793          * state first.  TRST accelerates it, and bypasses those states.
794          *
795          * RESET_TRST_PULLS_SRST is a board or chip level quirk, which
796          * can kick in even if the JTAG adapter can't drive SRST.
797          */
798         if (req_tlr_or_trst) {
799                 if (!(jtag_reset_config & RESET_HAS_TRST))
800                         trst_with_tlr = 1;
801                 else if ((jtag_reset_config & RESET_TRST_PULLS_SRST) != 0
802                          && !req_srst)
803                         trst_with_tlr = 1;
804                 else
805                         new_trst = 1;
806         }
807
808         /* Maybe change TRST and/or SRST signal state */
809         if (jtag_srst != new_srst || jtag_trst != new_trst) {
810                 /* guarantee jtag queue empty before changing reset status */
811                 jtag_execute_queue();
812
813                 retval = jtag->reset(new_trst, new_srst);
814                 if (retval != ERROR_OK) {
815                         jtag_set_error(retval);
816                         LOG_ERROR("TRST/SRST error");
817                         return;
818                 }
819         }
820
821         /* SRST resets everything hooked up to that signal */
822         if (jtag_srst != new_srst) {
823                 jtag_srst = new_srst;
824                 if (jtag_srst) {
825                         LOG_DEBUG("SRST line asserted");
826                         if (adapter_nsrst_assert_width)
827                                 jtag_add_sleep(adapter_nsrst_assert_width * 1000);
828                 } else {
829                         LOG_DEBUG("SRST line released");
830                         if (adapter_nsrst_delay)
831                                 jtag_add_sleep(adapter_nsrst_delay * 1000);
832                 }
833         }
834
835         /* Maybe enter the JTAG TAP_RESET state ...
836          *  - using only TMS, TCK, and the JTAG state machine
837          *  - or else more directly, using TRST
838          *
839          * TAP_RESET should be invisible to non-debug parts of the system.
840          */
841         if (trst_with_tlr) {
842                 LOG_DEBUG("JTAG reset with TLR instead of TRST");
843                 jtag_add_tlr();
844                 jtag_execute_queue();
845
846         } else if (jtag_trst != new_trst) {
847                 jtag_trst = new_trst;
848                 if (jtag_trst) {
849                         LOG_DEBUG("TRST line asserted");
850                         tap_set_state(TAP_RESET);
851                         if (jtag_ntrst_assert_width)
852                                 jtag_add_sleep(jtag_ntrst_assert_width * 1000);
853                 } else {
854                         LOG_DEBUG("TRST line released");
855                         if (jtag_ntrst_delay)
856                                 jtag_add_sleep(jtag_ntrst_delay * 1000);
857
858                         /* We just asserted nTRST, so we're now in TAP_RESET.
859                          * Inform possible listeners about this, now that
860                          * JTAG instructions and data can be shifted.  This
861                          * sequence must match jtag_add_tlr().
862                          */
863                         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
864                         jtag_notify_event(JTAG_TRST_ASSERTED);
865                 }
866         }
867 }
868
869 void jtag_add_sleep(uint32_t us)
870 {
871         /** @todo Here, keep_alive() appears to be a layering violation!!! */
872         keep_alive();
873         jtag_set_error(interface_jtag_add_sleep(us));
874 }
875
876 static int jtag_check_value_inner(uint8_t *captured, uint8_t *in_check_value,
877         uint8_t *in_check_mask, int num_bits)
878 {
879         int retval = ERROR_OK;
880         int compare_failed;
881
882         if (in_check_mask)
883                 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
884         else
885                 compare_failed = buf_cmp(captured, in_check_value, num_bits);
886
887         if (compare_failed) {
888                 char *captured_str, *in_check_value_str;
889                 int bits = (num_bits > DEBUG_JTAG_IOZ) ? DEBUG_JTAG_IOZ : num_bits;
890
891                 /* NOTE:  we've lost diagnostic context here -- 'which tap' */
892
893                 captured_str = buf_to_hex_str(captured, bits);
894                 in_check_value_str = buf_to_hex_str(in_check_value, bits);
895
896                 LOG_WARNING("Bad value '%s' captured during DR or IR scan:",
897                         captured_str);
898                 LOG_WARNING(" check_value: 0x%s", in_check_value_str);
899
900                 free(captured_str);
901                 free(in_check_value_str);
902
903                 if (in_check_mask) {
904                         char *in_check_mask_str;
905
906                         in_check_mask_str = buf_to_hex_str(in_check_mask, bits);
907                         LOG_WARNING(" check_mask: 0x%s", in_check_mask_str);
908                         free(in_check_mask_str);
909                 }
910
911                 retval = ERROR_JTAG_QUEUE_FAILED;
912         }
913         return retval;
914 }
915
916 void jtag_check_value_mask(struct scan_field *field, uint8_t *value, uint8_t *mask)
917 {
918         assert(field->in_value != NULL);
919
920         if (value == NULL) {
921                 /* no checking to do */
922                 return;
923         }
924
925         jtag_execute_queue_noclear();
926
927         int retval = jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
928         jtag_set_error(retval);
929 }
930
931 int default_interface_jtag_execute_queue(void)
932 {
933         if (NULL == jtag) {
934                 LOG_ERROR("No JTAG interface configured yet.  "
935                         "Issue 'init' command in startup scripts "
936                         "before communicating with targets.");
937                 return ERROR_FAIL;
938         }
939
940         if (!transport_is_jtag()) {
941                 /*
942                  * FIXME: This should not happen!
943                  * There could be old code that queues jtag commands with non jtag interfaces so, for
944                  * the moment simply highlight it by log an error and return on empty execute_queue.
945                  * We should fix it quitting with assert(0) because it is an internal error.
946                  * The fix can be applied immediately after next release (v0.11.0 ?)
947                  */
948                 LOG_ERROR("JTAG API jtag_execute_queue() called on non JTAG interface");
949                 if (!jtag->jtag_ops || !jtag->jtag_ops->execute_queue)
950                         return ERROR_OK;
951         }
952
953         int result = jtag->jtag_ops->execute_queue();
954
955         struct jtag_command *cmd = jtag_command_queue;
956         while (debug_level >= LOG_LVL_DEBUG_IO && cmd) {
957                 switch (cmd->type) {
958                         case JTAG_SCAN:
959                                 LOG_DEBUG_IO("JTAG %s SCAN to %s",
960                                                 cmd->cmd.scan->ir_scan ? "IR" : "DR",
961                                                 tap_state_name(cmd->cmd.scan->end_state));
962                                 for (int i = 0; i < cmd->cmd.scan->num_fields; i++) {
963                                         struct scan_field *field = cmd->cmd.scan->fields + i;
964                                         if (field->out_value) {
965                                                 char *str = buf_to_hex_str(field->out_value, field->num_bits);
966                                                 LOG_DEBUG_IO("  %db out: %s", field->num_bits, str);
967                                                 free(str);
968                                         }
969                                         if (field->in_value) {
970                                                 char *str = buf_to_hex_str(field->in_value, field->num_bits);
971                                                 LOG_DEBUG_IO("  %db  in: %s", field->num_bits, str);
972                                                 free(str);
973                                         }
974                                 }
975                                 break;
976                         case JTAG_TLR_RESET:
977                                 LOG_DEBUG_IO("JTAG TLR RESET to %s",
978                                                 tap_state_name(cmd->cmd.statemove->end_state));
979                                 break;
980                         case JTAG_RUNTEST:
981                                 LOG_DEBUG_IO("JTAG RUNTEST %d cycles to %s",
982                                                 cmd->cmd.runtest->num_cycles,
983                                                 tap_state_name(cmd->cmd.runtest->end_state));
984                                 break;
985                         case JTAG_RESET:
986                                 {
987                                         const char *reset_str[3] = {
988                                                 "leave", "deassert", "assert"
989                                         };
990                                         LOG_DEBUG_IO("JTAG RESET %s TRST, %s SRST",
991                                                         reset_str[cmd->cmd.reset->trst + 1],
992                                                         reset_str[cmd->cmd.reset->srst + 1]);
993                                 }
994                                 break;
995                         case JTAG_PATHMOVE:
996                                 LOG_DEBUG_IO("JTAG PATHMOVE (TODO)");
997                                 break;
998                         case JTAG_SLEEP:
999                                 LOG_DEBUG_IO("JTAG SLEEP (TODO)");
1000                                 break;
1001                         case JTAG_STABLECLOCKS:
1002                                 LOG_DEBUG_IO("JTAG STABLECLOCKS (TODO)");
1003                                 break;
1004                         case JTAG_TMS:
1005                                 LOG_DEBUG_IO("JTAG TMS (TODO)");
1006                                 break;
1007                         default:
1008                                 LOG_ERROR("Unknown JTAG command: %d", cmd->type);
1009                                 break;
1010                 }
1011                 cmd = cmd->next;
1012         }
1013
1014         return result;
1015 }
1016
1017 void jtag_execute_queue_noclear(void)
1018 {
1019         jtag_flush_queue_count++;
1020         jtag_set_error(interface_jtag_execute_queue());
1021
1022         if (jtag_flush_queue_sleep > 0) {
1023                 /* For debug purposes it can be useful to test performance
1024                  * or behavior when delaying after flushing the queue,
1025                  * e.g. to simulate long roundtrip times.
1026                  */
1027                 usleep(jtag_flush_queue_sleep * 1000);
1028         }
1029 }
1030
1031 int jtag_get_flush_queue_count(void)
1032 {
1033         return jtag_flush_queue_count;
1034 }
1035
1036 int jtag_execute_queue(void)
1037 {
1038         jtag_execute_queue_noclear();
1039         return jtag_error_clear();
1040 }
1041
1042 static int jtag_reset_callback(enum jtag_event event, void *priv)
1043 {
1044         struct jtag_tap *tap = priv;
1045
1046         if (event == JTAG_TRST_ASSERTED) {
1047                 tap->enabled = !tap->disabled_after_reset;
1048
1049                 /* current instruction is either BYPASS or IDCODE */
1050                 buf_set_ones(tap->cur_instr, tap->ir_length);
1051                 tap->bypass = 1;
1052         }
1053
1054         return ERROR_OK;
1055 }
1056
1057 /* sleep at least us microseconds. When we sleep more than 1000ms we
1058  * do an alive sleep, i.e. keep GDB alive. Note that we could starve
1059  * GDB if we slept for <1000ms many times.
1060  */
1061 void jtag_sleep(uint32_t us)
1062 {
1063         if (us < 1000)
1064                 usleep(us);
1065         else
1066                 alive_sleep((us+999)/1000);
1067 }
1068
1069 #define JTAG_MAX_AUTO_TAPS 20
1070
1071 #define EXTRACT_JEP106_BANK(X) (((X) & 0xf00) >> 8)
1072 #define EXTRACT_JEP106_ID(X)   (((X) & 0xfe) >> 1)
1073 #define EXTRACT_MFG(X)  (((X) & 0xffe) >> 1)
1074 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
1075 #define EXTRACT_VER(X)  (((X) & 0xf0000000) >> 28)
1076
1077 /* A reserved manufacturer ID is used in END_OF_CHAIN_FLAG, so we
1078  * know that no valid TAP will have it as an IDCODE value.
1079  */
1080 #define END_OF_CHAIN_FLAG       0xffffffff
1081
1082 /* a larger IR length than we ever expect to autoprobe */
1083 #define JTAG_IRLEN_MAX          60
1084
1085 static int jtag_examine_chain_execute(uint8_t *idcode_buffer, unsigned num_idcode)
1086 {
1087         struct scan_field field = {
1088                 .num_bits = num_idcode * 32,
1089                 .out_value = idcode_buffer,
1090                 .in_value = idcode_buffer,
1091         };
1092
1093         /* initialize to the end of chain ID value */
1094         for (unsigned i = 0; i < num_idcode; i++)
1095                 buf_set_u32(idcode_buffer, i * 32, 32, END_OF_CHAIN_FLAG);
1096
1097         jtag_add_plain_dr_scan(field.num_bits, field.out_value, field.in_value, TAP_DRPAUSE);
1098         jtag_add_tlr();
1099         return jtag_execute_queue();
1100 }
1101
1102 static bool jtag_examine_chain_check(uint8_t *idcodes, unsigned count)
1103 {
1104         uint8_t zero_check = 0x0;
1105         uint8_t one_check = 0xff;
1106
1107         for (unsigned i = 0; i < count * 4; i++) {
1108                 zero_check |= idcodes[i];
1109                 one_check &= idcodes[i];
1110         }
1111
1112         /* if there wasn't a single non-zero bit or if all bits were one,
1113          * the scan is not valid.  We wrote a mix of both values; either
1114          *
1115          *  - There's a hardware issue (almost certainly):
1116          *     + all-zeroes can mean a target stuck in JTAG reset
1117          *     + all-ones tends to mean no target
1118          *  - The scan chain is WAY longer than we can handle, *AND* either
1119          *     + there are several hundreds of TAPs in bypass, or
1120          *     + at least a few dozen TAPs all have an all-ones IDCODE
1121          */
1122         if (zero_check == 0x00 || one_check == 0xff) {
1123                 LOG_ERROR("JTAG scan chain interrogation failed: all %s",
1124                         (zero_check == 0x00) ? "zeroes" : "ones");
1125                 LOG_ERROR("Check JTAG interface, timings, target power, etc.");
1126                 return false;
1127         }
1128         return true;
1129 }
1130
1131 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
1132         const char *name, uint32_t idcode)
1133 {
1134         log_printf_lf(level, __FILE__, __LINE__, __func__,
1135                 "JTAG tap: %s %16.16s: 0x%08x "
1136                 "(mfg: 0x%3.3x (%s), part: 0x%4.4x, ver: 0x%1.1x)",
1137                 name, msg,
1138                 (unsigned int)idcode,
1139                 (unsigned int)EXTRACT_MFG(idcode),
1140                 jep106_manufacturer(EXTRACT_JEP106_BANK(idcode), EXTRACT_JEP106_ID(idcode)),
1141                 (unsigned int)EXTRACT_PART(idcode),
1142                 (unsigned int)EXTRACT_VER(idcode));
1143 }
1144
1145 static bool jtag_idcode_is_final(uint32_t idcode)
1146 {
1147         /*
1148          * Some devices, such as AVR8, will output all 1's instead
1149          * of TDI input value at end of chain. Allow those values
1150          * instead of failing.
1151          */
1152         return idcode == END_OF_CHAIN_FLAG;
1153 }
1154
1155 /**
1156  * This helper checks that remaining bits in the examined chain data are
1157  * all as expected, but a single JTAG device requires only 64 bits to be
1158  * read back correctly.  This can help identify and diagnose problems
1159  * with the JTAG chain earlier, gives more helpful/explicit error messages.
1160  * Returns TRUE iff garbage was found.
1161  */
1162 static bool jtag_examine_chain_end(uint8_t *idcodes, unsigned count, unsigned max)
1163 {
1164         bool triggered = false;
1165         for (; count < max - 31; count += 32) {
1166                 uint32_t idcode = buf_get_u32(idcodes, count, 32);
1167
1168                 /* do not trigger the warning if the data looks good */
1169                 if (jtag_idcode_is_final(idcode))
1170                         continue;
1171                 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
1172                         count, (unsigned int)idcode);
1173                 triggered = true;
1174         }
1175         return triggered;
1176 }
1177
1178 static bool jtag_examine_chain_match_tap(const struct jtag_tap *tap)
1179 {
1180
1181         if (tap->expected_ids_cnt == 0 || !tap->hasidcode)
1182                 return true;
1183
1184         /* optionally ignore the JTAG version field - bits 28-31 of IDCODE */
1185         uint32_t mask = tap->ignore_version ? ~(0xfU << 28) : ~0U;
1186         uint32_t idcode = tap->idcode & mask;
1187
1188         /* Loop over the expected identification codes and test for a match */
1189         for (unsigned ii = 0; ii < tap->expected_ids_cnt; ii++) {
1190                 uint32_t expected = tap->expected_ids[ii] & mask;
1191
1192                 if (idcode == expected)
1193                         return true;
1194
1195                 /* treat "-expected-id 0" as a "don't-warn" wildcard */
1196                 if (0 == tap->expected_ids[ii])
1197                         return true;
1198         }
1199
1200         /* If none of the expected ids matched, warn */
1201         jtag_examine_chain_display(LOG_LVL_WARNING, "UNEXPECTED",
1202                 tap->dotted_name, tap->idcode);
1203         for (unsigned ii = 0; ii < tap->expected_ids_cnt; ii++) {
1204                 char msg[32];
1205
1206                 snprintf(msg, sizeof(msg), "expected %u of %u", ii + 1, tap->expected_ids_cnt);
1207                 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
1208                         tap->dotted_name, tap->expected_ids[ii]);
1209         }
1210         return false;
1211 }
1212
1213 /* Try to examine chain layout according to IEEE 1149.1 Â§12
1214  * This is called a "blind interrogation" of the scan chain.
1215  */
1216 static int jtag_examine_chain(void)
1217 {
1218         int retval;
1219         unsigned max_taps = jtag_tap_count();
1220
1221         /* Autoprobe up to this many. */
1222         if (max_taps < JTAG_MAX_AUTO_TAPS)
1223                 max_taps = JTAG_MAX_AUTO_TAPS;
1224
1225         /* Add room for end-of-chain marker. */
1226         max_taps++;
1227
1228         uint8_t *idcode_buffer = calloc(4, max_taps);
1229         if (idcode_buffer == NULL)
1230                 return ERROR_JTAG_INIT_FAILED;
1231
1232         /* DR scan to collect BYPASS or IDCODE register contents.
1233          * Then make sure the scan data has both ones and zeroes.
1234          */
1235         LOG_DEBUG("DR scan interrogation for IDCODE/BYPASS");
1236         retval = jtag_examine_chain_execute(idcode_buffer, max_taps);
1237         if (retval != ERROR_OK)
1238                 goto out;
1239         if (!jtag_examine_chain_check(idcode_buffer, max_taps)) {
1240                 retval = ERROR_JTAG_INIT_FAILED;
1241                 goto out;
1242         }
1243
1244         /* Point at the 1st predefined tap, if any */
1245         struct jtag_tap *tap = jtag_tap_next_enabled(NULL);
1246
1247         unsigned bit_count = 0;
1248         unsigned autocount = 0;
1249         for (unsigned i = 0; i < max_taps; i++) {
1250                 assert(bit_count < max_taps * 32);
1251                 uint32_t idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1252
1253                 /* No predefined TAP? Auto-probe. */
1254                 if (tap == NULL) {
1255                         /* Is there another TAP? */
1256                         if (jtag_idcode_is_final(idcode))
1257                                 break;
1258
1259                         /* Default everything in this TAP except IR length.
1260                          *
1261                          * REVISIT create a jtag_alloc(chip, tap) routine, and
1262                          * share it with jim_newtap_cmd().
1263                          */
1264                         tap = calloc(1, sizeof(*tap));
1265                         if (!tap) {
1266                                 retval = ERROR_FAIL;
1267                                 goto out;
1268                         }
1269
1270                         tap->chip = alloc_printf("auto%u", autocount++);
1271                         tap->tapname = strdup("tap");
1272                         tap->dotted_name = alloc_printf("%s.%s", tap->chip, tap->tapname);
1273
1274                         tap->ir_length = 0; /* ... signifying irlen autoprobe */
1275                         tap->ir_capture_mask = 0x03;
1276                         tap->ir_capture_value = 0x01;
1277
1278                         tap->enabled = true;
1279
1280                         jtag_tap_init(tap);
1281                 }
1282
1283                 if ((idcode & 1) == 0) {
1284                         /* Zero for LSB indicates a device in bypass */
1285                         LOG_INFO("TAP %s does not have valid IDCODE (idcode=0x%" PRIx32 ")",
1286                                         tap->dotted_name, idcode);
1287                         tap->hasidcode = false;
1288                         tap->idcode = 0;
1289
1290                         bit_count += 1;
1291                 } else {
1292                         /* Friendly devices support IDCODE */
1293                         tap->hasidcode = true;
1294                         tap->idcode = idcode;
1295                         jtag_examine_chain_display(LOG_LVL_INFO, "tap/device found", tap->dotted_name, idcode);
1296
1297                         bit_count += 32;
1298                 }
1299
1300                 /* ensure the TAP ID matches what was expected */
1301                 if (!jtag_examine_chain_match_tap(tap))
1302                         retval = ERROR_JTAG_INIT_SOFT_FAIL;
1303
1304                 tap = jtag_tap_next_enabled(tap);
1305         }
1306
1307         /* After those IDCODE or BYPASS register values should be
1308          * only the data we fed into the scan chain.
1309          */
1310         if (jtag_examine_chain_end(idcode_buffer, bit_count, max_taps * 32)) {
1311                 LOG_ERROR("double-check your JTAG setup (interface, speed, ...)");
1312                 retval = ERROR_JTAG_INIT_FAILED;
1313                 goto out;
1314         }
1315
1316         /* Return success or, for backwards compatibility if only
1317          * some IDCODE values mismatched, a soft/continuable fault.
1318          */
1319 out:
1320         free(idcode_buffer);
1321         return retval;
1322 }
1323
1324 /*
1325  * Validate the date loaded by entry to the Capture-IR state, to help
1326  * find errors related to scan chain configuration (wrong IR lengths)
1327  * or communication.
1328  *
1329  * Entry state can be anything.  On non-error exit, all TAPs are in
1330  * bypass mode.  On error exits, the scan chain is reset.
1331  */
1332 static int jtag_validate_ircapture(void)
1333 {
1334         struct jtag_tap *tap;
1335         int total_ir_length = 0;
1336         uint8_t *ir_test = NULL;
1337         struct scan_field field;
1338         uint64_t val;
1339         int chain_pos = 0;
1340         int retval;
1341
1342         /* when autoprobing, accomodate huge IR lengths */
1343         for (tap = NULL, total_ir_length = 0;
1344                         (tap = jtag_tap_next_enabled(tap)) != NULL;
1345                         total_ir_length += tap->ir_length) {
1346                 if (tap->ir_length == 0)
1347                         total_ir_length += JTAG_IRLEN_MAX;
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 == NULL)
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 == NULL)
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 ((val = 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                 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         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 ? : 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 == NULL) {
1528                 LOG_INFO("This adapter doesn't support configurable speed");
1529                 return ERROR_OK;
1530         }
1531
1532         if (CLOCK_MODE_UNSELECTED == clock_mode) {
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 (ERROR_OK != retval)
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_RCLK == clock_mode)
1553                                 || ((CLOCK_MODE_KHZ == clock_mode) && !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 == NULL) {
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 (ERROR_OK != result)
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 (ERROR_OK != retval)
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 ((ERROR_OK != retval) && 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         jtag_speed = speed;
1807         /* this command can be called during CONFIG,
1808          * in which case jtag isn't initialized */
1809         return jtag ? jtag->speed(speed) : ERROR_OK;
1810 }
1811
1812 int jtag_config_khz(unsigned khz)
1813 {
1814         LOG_DEBUG("handle jtag khz");
1815         clock_mode = CLOCK_MODE_KHZ;
1816         int speed = 0;
1817         int retval = adapter_khz_to_speed(khz, &speed);
1818         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1819 }
1820
1821 int jtag_config_rclk(unsigned fallback_speed_khz)
1822 {
1823         LOG_DEBUG("handle jtag rclk");
1824         clock_mode = CLOCK_MODE_RCLK;
1825         rclk_fallback_speed_khz = fallback_speed_khz;
1826         int speed = 0;
1827         int retval = jtag_rclk_to_speed(fallback_speed_khz, &speed);
1828         return (ERROR_OK != retval) ? retval : jtag_set_speed(speed);
1829 }
1830
1831 int jtag_get_speed(int *speed)
1832 {
1833         switch (clock_mode) {
1834                 case CLOCK_MODE_KHZ:
1835                         adapter_khz_to_speed(jtag_get_speed_khz(), speed);
1836                         break;
1837                 case CLOCK_MODE_RCLK:
1838                         jtag_rclk_to_speed(rclk_fallback_speed_khz, speed);
1839                         break;
1840                 default:
1841                         LOG_ERROR("BUG: unknown jtag clock mode");
1842                         return ERROR_FAIL;
1843         }
1844         return ERROR_OK;
1845 }
1846
1847 int jtag_get_speed_readable(int *khz)
1848 {
1849         int jtag_speed_var = 0;
1850         int retval = jtag_get_speed(&jtag_speed_var);
1851         if (retval != ERROR_OK)
1852                 return retval;
1853         if (!jtag)
1854                 return ERROR_OK;
1855         if (!jtag->speed_div) {
1856                 LOG_ERROR("Translation from jtag_speed to khz not implemented");
1857                 return ERROR_FAIL;
1858         }
1859         return jtag->speed_div(jtag_speed_var, khz);
1860 }
1861
1862 void jtag_set_verify(bool enable)
1863 {
1864         jtag_verify = enable;
1865 }
1866
1867 bool jtag_will_verify(void)
1868 {
1869         return jtag_verify;
1870 }
1871
1872 void jtag_set_verify_capture_ir(bool enable)
1873 {
1874         jtag_verify_capture_ir = enable;
1875 }
1876
1877 bool jtag_will_verify_capture_ir(void)
1878 {
1879         return jtag_verify_capture_ir;
1880 }
1881
1882 int jtag_power_dropout(int *dropout)
1883 {
1884         if (jtag == NULL) {
1885                 /* TODO: as the jtag interface is not valid all
1886                  * we can do at the moment is exit OpenOCD */
1887                 LOG_ERROR("No Valid JTAG Interface Configured.");
1888                 exit(-1);
1889         }
1890         if (jtag->power_dropout)
1891                 return jtag->power_dropout(dropout);
1892
1893         *dropout = 0; /* by default we can't detect power dropout */
1894         return ERROR_OK;
1895 }
1896
1897 int jtag_srst_asserted(int *srst_asserted)
1898 {
1899         if (jtag->srst_asserted)
1900                 return jtag->srst_asserted(srst_asserted);
1901
1902         *srst_asserted = 0; /* by default we can't detect srst asserted */
1903         return ERROR_OK;
1904 }
1905
1906 enum reset_types jtag_get_reset_config(void)
1907 {
1908         return jtag_reset_config;
1909 }
1910 void jtag_set_reset_config(enum reset_types type)
1911 {
1912         jtag_reset_config = type;
1913 }
1914
1915 int jtag_get_trst(void)
1916 {
1917         return jtag_trst == 1;
1918 }
1919 int jtag_get_srst(void)
1920 {
1921         return jtag_srst == 1;
1922 }
1923
1924 void jtag_set_nsrst_delay(unsigned delay)
1925 {
1926         adapter_nsrst_delay = delay;
1927 }
1928 unsigned jtag_get_nsrst_delay(void)
1929 {
1930         return adapter_nsrst_delay;
1931 }
1932 void jtag_set_ntrst_delay(unsigned delay)
1933 {
1934         jtag_ntrst_delay = delay;
1935 }
1936 unsigned jtag_get_ntrst_delay(void)
1937 {
1938         return jtag_ntrst_delay;
1939 }
1940
1941
1942 void jtag_set_nsrst_assert_width(unsigned delay)
1943 {
1944         adapter_nsrst_assert_width = delay;
1945 }
1946 unsigned jtag_get_nsrst_assert_width(void)
1947 {
1948         return adapter_nsrst_assert_width;
1949 }
1950 void jtag_set_ntrst_assert_width(unsigned delay)
1951 {
1952         jtag_ntrst_assert_width = delay;
1953 }
1954 unsigned jtag_get_ntrst_assert_width(void)
1955 {
1956         return jtag_ntrst_assert_width;
1957 }
1958
1959 static int jtag_select(struct command_context *ctx)
1960 {
1961         int retval;
1962
1963         /* NOTE:  interface init must already have been done.
1964          * That works with only C code ... no Tcl glue required.
1965          */
1966
1967         retval = jtag_register_commands(ctx);
1968
1969         if (retval != ERROR_OK)
1970                 return retval;
1971
1972         retval = svf_register_commands(ctx);
1973
1974         if (retval != ERROR_OK)
1975                 return retval;
1976
1977         return xsvf_register_commands(ctx);
1978 }
1979
1980 static struct transport jtag_transport = {
1981         .name = "jtag",
1982         .select = jtag_select,
1983         .init = jtag_init,
1984 };
1985
1986 static void jtag_constructor(void) __attribute__((constructor));
1987 static void jtag_constructor(void)
1988 {
1989         transport_register(&jtag_transport);
1990 }
1991
1992 /** Returns true if the current debug session
1993  * is using JTAG as its transport.
1994  */
1995 bool transport_is_jtag(void)
1996 {
1997         return get_current_transport() == &jtag_transport;
1998 }
1999
2000 int adapter_resets(int trst, int srst)
2001 {
2002         if (get_current_transport() == NULL) {
2003                 LOG_ERROR("transport is not selected");
2004                 return ERROR_FAIL;
2005         }
2006
2007         if (transport_is_jtag()) {
2008                 if (srst == SRST_ASSERT && !(jtag_reset_config & RESET_HAS_SRST)) {
2009                         LOG_ERROR("adapter has no srst signal");
2010                         return ERROR_FAIL;
2011                 }
2012
2013                 /* adapters without trst signal will eventually use tlr sequence */
2014                 jtag_add_reset(trst, srst);
2015                 /*
2016                  * The jtag queue is still used for reset by some adapter. Flush it!
2017                  * FIXME: To be removed when all adapter drivers will be updated!
2018                  */
2019                 jtag_execute_queue();
2020                 return ERROR_OK;
2021         } else if (transport_is_swd() || transport_is_hla() ||
2022                            transport_is_dapdirect_swd() || transport_is_dapdirect_jtag() ||
2023                            transport_is_swim()) {
2024                 if (trst == TRST_ASSERT) {
2025                         LOG_ERROR("transport %s has no trst signal",
2026                                 get_current_transport()->name);
2027                         return ERROR_FAIL;
2028                 }
2029
2030                 if (srst == SRST_ASSERT && !(jtag_reset_config & RESET_HAS_SRST)) {
2031                         LOG_ERROR("adapter has no srst signal");
2032                         return ERROR_FAIL;
2033                 }
2034                 adapter_system_reset(srst);
2035                 return ERROR_OK;
2036         }
2037
2038         if (trst == TRST_DEASSERT && srst == SRST_DEASSERT)
2039                 return ERROR_OK;
2040
2041         LOG_ERROR("reset is not supported on transport %s",
2042                 get_current_transport()->name);
2043
2044         return ERROR_FAIL;
2045 }
2046
2047 int adapter_assert_reset(void)
2048 {
2049         if (transport_is_jtag()) {
2050                 if (jtag_reset_config & RESET_SRST_PULLS_TRST)
2051                         jtag_add_reset(1, 1);
2052                 else
2053                         jtag_add_reset(0, 1);
2054                 return ERROR_OK;
2055         } else if (transport_is_swd() || transport_is_hla() ||
2056                            transport_is_dapdirect_jtag() || transport_is_dapdirect_swd() ||
2057                            transport_is_swim())
2058                 return adapter_system_reset(1);
2059         else if (get_current_transport() != NULL)
2060                 LOG_ERROR("reset is not supported on %s",
2061                         get_current_transport()->name);
2062         else
2063                 LOG_ERROR("transport is not selected");
2064         return ERROR_FAIL;
2065 }
2066
2067 int adapter_deassert_reset(void)
2068 {
2069         if (transport_is_jtag()) {
2070                 jtag_add_reset(0, 0);
2071                 return ERROR_OK;
2072         } else if (transport_is_swd() || transport_is_hla() ||
2073                            transport_is_dapdirect_jtag() || transport_is_dapdirect_swd() ||
2074                            transport_is_swim())
2075                 return adapter_system_reset(0);
2076         else if (get_current_transport() != NULL)
2077                 LOG_ERROR("reset is not supported on %s",
2078                         get_current_transport()->name);
2079         else
2080                 LOG_ERROR("transport is not selected");
2081         return ERROR_FAIL;
2082 }
2083
2084 int adapter_config_trace(bool enabled, enum tpiu_pin_protocol pin_protocol,
2085                 uint32_t port_size, unsigned int *trace_freq,
2086                 unsigned int traceclkin_freq, uint16_t *prescaler)
2087 {
2088         if (jtag->config_trace) {
2089                 return jtag->config_trace(enabled, pin_protocol, port_size, trace_freq,
2090                         traceclkin_freq, prescaler);
2091         } else if (enabled) {
2092                 LOG_ERROR("The selected interface does not support tracing");
2093                 return ERROR_FAIL;
2094         }
2095
2096         return ERROR_OK;
2097 }
2098
2099 int adapter_poll_trace(uint8_t *buf, size_t *size)
2100 {
2101         if (jtag->poll_trace)
2102                 return jtag->poll_trace(buf, size);
2103
2104         return ERROR_FAIL;
2105 }