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