Out-of-line jtag_tap_next_enabled and simplify its logic.
[fw/openocd] / src / jtag / core.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007,2008 Ã˜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) 2009 Zachary T Welch                                    *
13  *   zw@superlucidity.net                                                  *
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, write to the                         *
27  *   Free Software Foundation, Inc.,                                       *
28  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
29  ***************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33
34 #include "jtag.h"
35 #include "minidriver.h"
36 #include "interface.h"
37
38 #ifdef HAVE_STRINGS_H
39 #include <strings.h>
40 #endif
41
42
43 /// The number of JTAG queue flushes (for profiling and debugging purposes).
44 static int jtag_flush_queue_count;
45
46 static void jtag_add_scan_check(void (*jtag_add_scan)(int in_num_fields, const scan_field_t *in_fields, tap_state_t state),
47                 int in_num_fields, scan_field_t *in_fields, tap_state_t state);
48
49 /**
50  * The jtag_error variable is set when an error occurs while executing
51  * the queue.  Application code may set this using jtag_set_error(),
52  * when an error occurs during processing that should be reported during
53  * jtag_execute_queue().
54  *
55  * Tts value may be checked with jtag_get_error() and cleared with
56  * jtag_error_clear().  This value is returned (and cleared) by
57  * jtag_execute_queue().
58  */
59 static int jtag_error = ERROR_OK;
60
61 static char* jtag_event_strings[] =
62 {
63         "JTAG controller reset (RESET or TRST)"
64 };
65
66 static int jtag_trst = 0;
67 static int jtag_srst = 0;
68
69 /**
70  * List all TAPs that have been created.
71  */
72 static jtag_tap_t *__jtag_all_taps = NULL;
73 /**
74  * The number of TAPs in the __jtag_all_taps list, used to track the
75  * assigned chain position to new TAPs
76  */
77 static unsigned jtag_num_taps = 0;
78
79 static enum reset_types jtag_reset_config = RESET_NONE;
80 static tap_state_t cmd_queue_end_state = TAP_RESET;
81 tap_state_t cmd_queue_cur_state = TAP_RESET;
82
83 static bool jtag_verify_capture_ir = true;
84 static int jtag_verify = 1;
85
86 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines deasserted (in ms) */
87 static int jtag_nsrst_delay = 0; /* default to no nSRST delay */
88 static int jtag_ntrst_delay = 0; /* default to no nTRST delay */
89
90 typedef struct jtag_event_callback_s
91 {
92         jtag_event_handler_t          callback;
93         void*                         priv;
94         struct jtag_event_callback_s* next;
95 } jtag_event_callback_t;
96
97 /* callbacks to inform high-level handlers about JTAG state changes */
98 static jtag_event_callback_t *jtag_event_callbacks;
99
100 /* speed in kHz*/
101 static int speed_khz = 0;
102 /* flag if the kHz speed was defined */
103 static bool hasKHz = false;
104 static int jtag_speed = 0;
105
106 static struct jtag_interface_s *jtag = NULL;
107
108 /* configuration */
109 jtag_interface_t *jtag_interface = NULL;
110
111 void jtag_set_error(int error)
112 {
113         if ((error == ERROR_OK) || (jtag_error != ERROR_OK))
114                 return;
115         jtag_error = error;
116 }
117 int jtag_get_error(void)
118 {
119         return jtag_error;
120 }
121 int jtag_error_clear(void)
122 {
123         int temp = jtag_error;
124         jtag_error = ERROR_OK;
125         return temp;
126 }
127
128
129 jtag_tap_t *jtag_all_taps(void)
130 {
131         return __jtag_all_taps;
132 };
133
134 unsigned jtag_tap_count(void)
135 {
136         return jtag_num_taps;
137 }
138
139 unsigned jtag_tap_count_enabled(void)
140 {
141         jtag_tap_t *t = jtag_all_taps();
142         unsigned n = 0;
143         while(t)
144         {
145                 if (t->enabled)
146                         n++;
147                 t = t->next_tap;
148         }
149         return n;
150 }
151
152 /// Append a new TAP to the chain of all taps.
153 void jtag_tap_add(struct jtag_tap_s *t)
154 {
155         t->abs_chain_position = jtag_num_taps++;
156
157         jtag_tap_t **tap = &__jtag_all_taps;
158         while(*tap != NULL)
159                 tap = &(*tap)->next_tap;
160         *tap = t;
161 }
162
163 jtag_tap_t *jtag_tap_by_string(const char *s)
164 {
165         /* try by name first */
166         jtag_tap_t *t = jtag_all_taps();
167         while (t)
168         {
169                 if (0 == strcmp(t->dotted_name, s))
170                         return t;
171                 t = t->next_tap;
172         }
173
174         /* no tap found by name, so try to parse the name as a number */
175         char *cp;
176         unsigned n = strtoul(s, &cp, 0);
177         if ((s == cp) || (*cp != 0))
178                 return NULL;
179
180         return jtag_tap_by_position(n);
181 }
182
183 jtag_tap_t *jtag_tap_by_jim_obj(Jim_Interp *interp, Jim_Obj *o)
184 {
185         const char *cp = Jim_GetString(o, NULL);
186         jtag_tap_t *t = cp ? jtag_tap_by_string(cp) : NULL;
187         if (NULL == cp)
188                 cp = "(unknown)";
189         if (NULL == t)
190                 Jim_SetResult_sprintf(interp, "Tap '%s' could not be found", cp);
191         return t;
192 }
193
194 /* returns a pointer to the n-th device in the scan chain */
195 jtag_tap_t *jtag_tap_by_position(unsigned n)
196 {
197         jtag_tap_t *t = jtag_all_taps();
198
199         while (t && n-- > 0)
200                 t = t->next_tap;
201
202         return t;
203 }
204
205 jtag_tap_t* jtag_tap_next_enabled(jtag_tap_t* p)
206 {
207         p = p ? p->next_tap : jtag_all_taps();
208         while (p)
209         {
210                 if (p->enabled)
211                         return p;
212                 p = p->next_tap;
213         }
214         return NULL;
215 }
216
217 const char *jtag_tap_name(const jtag_tap_t *tap)
218 {
219         return (tap == NULL) ? "(unknown)" : tap->dotted_name;
220 }
221
222
223 int jtag_register_event_callback(jtag_event_handler_t callback, void *priv)
224 {
225         jtag_event_callback_t **callbacks_p = &jtag_event_callbacks;
226
227         if (callback == NULL)
228         {
229                 return ERROR_INVALID_ARGUMENTS;
230         }
231
232         if (*callbacks_p)
233         {
234                 while ((*callbacks_p)->next)
235                         callbacks_p = &((*callbacks_p)->next);
236                 callbacks_p = &((*callbacks_p)->next);
237         }
238
239         (*callbacks_p) = malloc(sizeof(jtag_event_callback_t));
240         (*callbacks_p)->callback = callback;
241         (*callbacks_p)->priv = priv;
242         (*callbacks_p)->next = NULL;
243
244         return ERROR_OK;
245 }
246
247 int jtag_unregister_event_callback(jtag_event_handler_t callback)
248 {
249         jtag_event_callback_t **callbacks_p = &jtag_event_callbacks;
250
251         if (callback == NULL)
252         {
253                 return ERROR_INVALID_ARGUMENTS;
254         }
255
256         while (*callbacks_p)
257         {
258                 jtag_event_callback_t **next = &((*callbacks_p)->next);
259                 if ((*callbacks_p)->callback == callback)
260                 {
261                         free(*callbacks_p);
262                         *callbacks_p = *next;
263                 }
264                 callbacks_p = next;
265         }
266
267         return ERROR_OK;
268 }
269
270 int jtag_call_event_callbacks(enum jtag_event event)
271 {
272         jtag_event_callback_t *callback = jtag_event_callbacks;
273
274         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
275
276         while (callback)
277         {
278                 callback->callback(event, callback->priv);
279                 callback = callback->next;
280         }
281
282         return ERROR_OK;
283 }
284
285 static void jtag_checks(void)
286 {
287         assert(jtag_trst == 0);
288 }
289
290 static void jtag_prelude(tap_state_t state)
291 {
292         jtag_checks();
293
294         assert(state!=TAP_INVALID);
295
296         cmd_queue_cur_state = state;
297 }
298
299 void jtag_alloc_in_value32(scan_field_t *field)
300 {
301         interface_jtag_alloc_in_value32(field);
302 }
303
304 void jtag_add_ir_scan_noverify(int in_count, const scan_field_t *in_fields,
305                 tap_state_t state)
306 {
307         jtag_prelude(state);
308
309         int retval = interface_jtag_add_ir_scan(in_count, in_fields, state);
310         jtag_set_error(retval);
311 }
312
313
314 void jtag_add_ir_scan(int in_num_fields, scan_field_t *in_fields, tap_state_t state)
315 {
316         if (jtag_verify&&jtag_verify_capture_ir)
317         {
318                 /* 8 x 32 bit id's is enough for all invocations */
319
320                 for (int j = 0; j < in_num_fields; j++)
321                 {
322                         /* if we are to run a verification of the ir scan, we need to get the input back.
323                          * We may have to allocate space if the caller didn't ask for the input back.
324                          */
325                         in_fields[j].check_value=in_fields[j].tap->expected;
326                         in_fields[j].check_mask=in_fields[j].tap->expected_mask;
327                 }
328                 jtag_add_scan_check(jtag_add_ir_scan_noverify, in_num_fields, in_fields, state);
329         } else
330         {
331                 jtag_add_ir_scan_noverify(in_num_fields, in_fields, state);
332         }
333 }
334
335 void jtag_add_plain_ir_scan(int in_num_fields, const scan_field_t *in_fields,
336                 tap_state_t state)
337 {
338         jtag_prelude(state);
339
340         int retval = interface_jtag_add_plain_ir_scan(
341                         in_num_fields, in_fields, state);
342         jtag_set_error(retval);
343 }
344
345 void jtag_add_callback(jtag_callback1_t f, u8 *in)
346 {
347         interface_jtag_add_callback(f, in);
348 }
349
350 void jtag_add_callback4(jtag_callback_t f, u8 *in,
351                 jtag_callback_data_t data1, jtag_callback_data_t data2,
352                 jtag_callback_data_t data3)
353 {
354         interface_jtag_add_callback4(f, in, data1, data2, data3);
355 }
356
357 int jtag_check_value_inner(u8 *captured, u8 *in_check_value, u8 *in_check_mask, int num_bits);
358
359 static int jtag_check_value_mask_callback(u8 *in, jtag_callback_data_t data1, jtag_callback_data_t data2, jtag_callback_data_t data3)
360 {
361         return jtag_check_value_inner(in, (u8 *)data1, (u8 *)data2, (int)data3);
362 }
363
364 static void jtag_add_scan_check(void (*jtag_add_scan)(int in_num_fields, const scan_field_t *in_fields, tap_state_t state),
365                 int in_num_fields, scan_field_t *in_fields, tap_state_t state)
366 {
367         for (int i = 0; i < in_num_fields; i++)
368         {
369                 struct scan_field_s *field = &in_fields[i];
370                 field->allocated = 0;
371                 field->modified = 0;
372                 if (field->check_value || field->in_value)
373                         continue;
374                 interface_jtag_add_scan_check_alloc(field);
375                 field->modified = 1;
376         }
377
378         jtag_add_scan(in_num_fields, in_fields, state);
379
380         for (int i = 0; i < in_num_fields; i++)
381         {
382                 if ((in_fields[i].check_value != NULL) && (in_fields[i].in_value != NULL))
383                 {
384                         /* this is synchronous for a minidriver */
385                         jtag_add_callback4(jtag_check_value_mask_callback, in_fields[i].in_value,
386                                 (jtag_callback_data_t)in_fields[i].check_value,
387                                 (jtag_callback_data_t)in_fields[i].check_mask,
388                                 (jtag_callback_data_t)in_fields[i].num_bits);
389                 }
390                 if (in_fields[i].allocated)
391                 {
392                         free(in_fields[i].in_value);
393                 }
394                 if (in_fields[i].modified)
395                 {
396                         in_fields[i].in_value = NULL;
397                 }
398         }
399 }
400
401 void jtag_add_dr_scan_check(int in_num_fields, scan_field_t *in_fields, tap_state_t state)
402 {
403         if (jtag_verify)
404         {
405                 jtag_add_scan_check(jtag_add_dr_scan, in_num_fields, in_fields, state);
406         } else
407         {
408                 jtag_add_dr_scan(in_num_fields, in_fields, state);
409         }
410 }
411
412
413 void jtag_add_dr_scan(int in_num_fields, const scan_field_t *in_fields,
414                 tap_state_t state)
415 {
416         jtag_prelude(state);
417
418         int retval;
419         retval = interface_jtag_add_dr_scan(in_num_fields, in_fields, state);
420         jtag_set_error(retval);
421 }
422
423 void jtag_add_plain_dr_scan(int in_num_fields, const scan_field_t *in_fields,
424                 tap_state_t state)
425 {
426         jtag_prelude(state);
427
428         int retval;
429         retval = interface_jtag_add_plain_dr_scan(in_num_fields, in_fields, state);
430         jtag_set_error(retval);
431 }
432
433 void jtag_add_dr_out(jtag_tap_t* tap,
434                 int num_fields, const int* num_bits, const u32* value,
435                 tap_state_t end_state)
436 {
437         assert(end_state != TAP_INVALID);
438
439         cmd_queue_cur_state = end_state;
440
441         interface_jtag_add_dr_out(tap,
442                         num_fields, num_bits, value,
443                         end_state);
444 }
445
446 void jtag_add_tlr(void)
447 {
448         jtag_prelude(TAP_RESET);
449         jtag_set_error(interface_jtag_add_tlr());
450         jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
451 }
452
453 void jtag_add_pathmove(int num_states, const tap_state_t *path)
454 {
455         tap_state_t cur_state = cmd_queue_cur_state;
456
457         /* the last state has to be a stable state */
458         if (!tap_is_state_stable(path[num_states - 1]))
459         {
460                 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
461                 jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
462                 return;
463         }
464
465         for (int i = 0; i < num_states; i++)
466         {
467                 if (path[i] == TAP_RESET)
468                 {
469                         LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
470                         jtag_set_error(ERROR_JTAG_STATE_INVALID);
471                         return;
472                 }
473
474                 if ( tap_state_transition(cur_state, true)  != path[i]
475                   && tap_state_transition(cur_state, false) != path[i])
476                 {
477                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition",
478                                         tap_state_name(cur_state), tap_state_name(path[i]));
479                         jtag_set_error(ERROR_JTAG_TRANSITION_INVALID);
480                         return;
481                 }
482                 cur_state = path[i];
483         }
484
485         jtag_checks();
486
487         jtag_set_error(interface_jtag_add_pathmove(num_states, path));
488         cmd_queue_cur_state = path[num_states - 1];
489 }
490
491 int jtag_add_statemove(tap_state_t goal_state)
492 {
493         tap_state_t cur_state = cmd_queue_cur_state;
494
495         LOG_DEBUG( "cur_state=%s goal_state=%s",
496                 tap_state_name(cur_state),
497                 tap_state_name(goal_state) );
498
499
500         if (goal_state==cur_state )
501                 ;       /* nothing to do */
502         else if( goal_state==TAP_RESET )
503         {
504                 jtag_add_tlr();
505         }
506         else if( tap_is_state_stable(cur_state) && tap_is_state_stable(goal_state) )
507         {
508                 unsigned tms_bits  = tap_get_tms_path(cur_state, goal_state);
509                 unsigned tms_count = tap_get_tms_path_len(cur_state, goal_state);
510                 tap_state_t moves[8];
511                 assert(tms_count < DIM(moves));
512
513                 for (unsigned i = 0; i < tms_count; i++, tms_bits >>= 1)
514                 {
515                         bool bit = tms_bits & 1;
516
517                         cur_state = tap_state_transition(cur_state, bit);
518                         moves[i] = cur_state;
519                 }
520
521                 jtag_add_pathmove(tms_count, moves);
522         }
523         else if( tap_state_transition(cur_state, true)  == goal_state
524                 ||   tap_state_transition(cur_state, false) == goal_state )
525         {
526                 jtag_add_pathmove(1, &goal_state);
527         }
528
529         else
530                 return ERROR_FAIL;
531
532         return ERROR_OK;
533 }
534
535 void jtag_add_runtest(int num_cycles, tap_state_t state)
536 {
537         jtag_prelude(state);
538         jtag_set_error(interface_jtag_add_runtest(num_cycles, state));
539 }
540
541
542 void jtag_add_clocks(int num_cycles)
543 {
544         if (!tap_is_state_stable(cmd_queue_cur_state))
545         {
546                  LOG_ERROR("jtag_add_clocks() called with TAP in unstable state \"%s\"",
547                                  tap_state_name(cmd_queue_cur_state));
548                  jtag_set_error(ERROR_JTAG_NOT_STABLE_STATE);
549                  return;
550         }
551
552         if (num_cycles > 0)
553         {
554                 jtag_checks();
555                 jtag_set_error(interface_jtag_add_clocks(num_cycles));
556         }
557 }
558
559 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
560 {
561         int trst_with_tlr = 0;
562
563         /* FIX!!! there are *many* different cases here. A better
564          * approach is needed for legal combinations of transitions...
565          */
566         if ((jtag_reset_config & RESET_HAS_SRST)&&
567                         (jtag_reset_config & RESET_HAS_TRST)&&
568                         ((jtag_reset_config & RESET_SRST_PULLS_TRST)==0))
569         {
570                 if (((req_tlr_or_trst&&!jtag_trst)||
571                                 (!req_tlr_or_trst&&jtag_trst))&&
572                                 ((req_srst&&!jtag_srst)||
573                                                 (!req_srst&&jtag_srst)))
574                 {
575                         /* FIX!!! srst_pulls_trst allows 1,1 => 0,0 transition.... */
576                         //LOG_ERROR("BUG: transition of req_tlr_or_trst and req_srst in the same jtag_add_reset() call is undefined");
577                 }
578         }
579
580         /* Make sure that jtag_reset_config allows the requested reset */
581         /* if SRST pulls TRST, we can't fulfill srst == 1 with trst == 0 */
582         if (((jtag_reset_config & RESET_SRST_PULLS_TRST) && (req_srst == 1)) && (!req_tlr_or_trst))
583         {
584                 LOG_ERROR("BUG: requested reset would assert trst");
585                 jtag_set_error(ERROR_FAIL);
586                 return;
587         }
588
589         /* if TRST pulls SRST, we reset with TAP T-L-R */
590         if (((jtag_reset_config & RESET_TRST_PULLS_SRST) && (req_tlr_or_trst)) && (req_srst == 0))
591         {
592                 trst_with_tlr = 1;
593         }
594
595         if (req_srst && !(jtag_reset_config & RESET_HAS_SRST))
596         {
597                 LOG_ERROR("BUG: requested SRST assertion, but the current configuration doesn't support this");
598                 jtag_set_error(ERROR_FAIL);
599                 return;
600         }
601
602         if (req_tlr_or_trst)
603         {
604                 if (!trst_with_tlr && (jtag_reset_config & RESET_HAS_TRST))
605                 {
606                         jtag_trst = 1;
607                 } else
608                 {
609                         trst_with_tlr = 1;
610                 }
611         } else
612         {
613                 jtag_trst = 0;
614         }
615
616         jtag_srst = req_srst;
617
618         int retval = interface_jtag_add_reset(jtag_trst, jtag_srst);
619         if (retval != ERROR_OK)
620         {
621                 jtag_set_error(retval);
622                 return;
623         }
624         jtag_execute_queue();
625
626         if (jtag_srst)
627         {
628                 LOG_DEBUG("SRST line asserted");
629         }
630         else
631         {
632                 LOG_DEBUG("SRST line released");
633                 if (jtag_nsrst_delay)
634                         jtag_add_sleep(jtag_nsrst_delay * 1000);
635         }
636
637         if (trst_with_tlr)
638         {
639                 LOG_DEBUG("JTAG reset with RESET instead of TRST");
640                 jtag_set_end_state(TAP_RESET);
641                 jtag_add_tlr();
642                 return;
643         }
644
645         if (jtag_trst)
646         {
647                 /* we just asserted nTRST, so we're now in Test-Logic-Reset,
648                  * and inform possible listeners about this
649                  */
650                 LOG_DEBUG("TRST line asserted");
651                 tap_set_state(TAP_RESET);
652                 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
653         }
654         else
655         {
656                 if (jtag_ntrst_delay)
657                         jtag_add_sleep(jtag_ntrst_delay * 1000);
658         }
659 }
660
661 tap_state_t jtag_set_end_state(tap_state_t state)
662 {
663         if ((state == TAP_DRSHIFT)||(state == TAP_IRSHIFT))
664         {
665                 LOG_ERROR("BUG: TAP_DRSHIFT/IRSHIFT can't be end state. Calling code should use a larger scan field");
666         }
667
668         if (state!=TAP_INVALID)
669                 cmd_queue_end_state = state;
670         return cmd_queue_end_state;
671 }
672
673 tap_state_t jtag_get_end_state(void)
674 {
675         return cmd_queue_end_state;
676 }
677
678 void jtag_add_sleep(u32 us)
679 {
680         /// @todo Here, keep_alive() appears to be a layering violation!!!
681         keep_alive();
682         jtag_set_error(interface_jtag_add_sleep(us));
683 }
684
685 int jtag_check_value_inner(u8 *captured, u8 *in_check_value, u8 *in_check_mask, int num_bits)
686 {
687         int retval = ERROR_OK;
688
689         int compare_failed = 0;
690
691         if (in_check_mask)
692                 compare_failed = buf_cmp_mask(captured, in_check_value, in_check_mask, num_bits);
693         else
694                 compare_failed = buf_cmp(captured, in_check_value, num_bits);
695
696         if (compare_failed){
697                 /* An error handler could have caught the failing check
698                  * only report a problem when there wasn't a handler, or if the handler
699                  * acknowledged the error
700                  */
701                 /*
702                 LOG_WARNING("TAP %s:",
703                                         jtag_tap_name(field->tap));
704                                         */
705                 if (compare_failed)
706                 {
707                         char *captured_char = buf_to_str(captured, (num_bits > DEBUG_JTAG_IOZ) ? DEBUG_JTAG_IOZ : num_bits, 16);
708                         char *in_check_value_char = buf_to_str(in_check_value, (num_bits > DEBUG_JTAG_IOZ) ? DEBUG_JTAG_IOZ : num_bits, 16);
709
710                         if (in_check_mask)
711                         {
712                                 char *in_check_mask_char;
713                                 in_check_mask_char = buf_to_str(in_check_mask, (num_bits > DEBUG_JTAG_IOZ) ? DEBUG_JTAG_IOZ : num_bits, 16);
714                                 LOG_WARNING("value captured during scan didn't pass the requested check:");
715                                 LOG_WARNING("captured: 0x%s check_value: 0x%s check_mask: 0x%s",
716                                                         captured_char, in_check_value_char, in_check_mask_char);
717                                 free(in_check_mask_char);
718                         }
719                         else
720                         {
721                                 LOG_WARNING("value captured during scan didn't pass the requested check: captured: 0x%s check_value: 0x%s", captured_char, in_check_value_char);
722                         }
723
724                         free(captured_char);
725                         free(in_check_value_char);
726
727                         retval = ERROR_JTAG_QUEUE_FAILED;
728                 }
729
730         }
731         return retval;
732 }
733
734 void jtag_check_value_mask(scan_field_t *field, u8 *value, u8 *mask)
735 {
736         assert(field->in_value != NULL);
737
738         if (value==NULL)
739         {
740                 /* no checking to do */
741                 return;
742         }
743
744         jtag_execute_queue_noclear();
745
746         int retval=jtag_check_value_inner(field->in_value, value, mask, field->num_bits);
747         jtag_set_error(retval);
748 }
749
750
751
752 int default_interface_jtag_execute_queue(void)
753 {
754         if (NULL == jtag)
755         {
756                 LOG_ERROR("No JTAG interface configured yet.  "
757                         "Issue 'init' command in startup scripts "
758                         "before communicating with targets.");
759                 return ERROR_FAIL;
760         }
761
762         return jtag->execute_queue();
763 }
764
765 void jtag_execute_queue_noclear(void)
766 {
767         jtag_flush_queue_count++;
768         jtag_set_error(interface_jtag_execute_queue());
769 }
770
771 int jtag_get_flush_queue_count(void)
772 {
773         return jtag_flush_queue_count;
774 }
775
776 int jtag_execute_queue(void)
777 {
778         jtag_execute_queue_noclear();
779         return jtag_error_clear();
780 }
781
782 static int jtag_reset_callback(enum jtag_event event, void *priv)
783 {
784         jtag_tap_t *tap = priv;
785
786         LOG_DEBUG("-");
787
788         if (event == JTAG_TRST_ASSERTED)
789         {
790                 buf_set_ones(tap->cur_instr, tap->ir_length);
791                 tap->bypass = 1;
792         }
793
794         return ERROR_OK;
795 }
796
797 void jtag_sleep(u32 us)
798 {
799         alive_sleep(us/1000);
800 }
801
802 /// maximum number of JTAG devices expected in the chain
803 #define JTAG_MAX_CHAIN_SIZE 20
804
805 #define EXTRACT_MFG(X)  (((X) & 0xffe) >> 1)
806 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
807 #define EXTRACT_VER(X)  (((X) & 0xf0000000) >> 28)
808
809 static int jtag_examine_chain_execute(u8 *idcode_buffer, unsigned num_idcode)
810 {
811         scan_field_t field = {
812                         .tap = NULL,
813                         .num_bits = num_idcode * 32,
814                         .out_value = idcode_buffer,
815                         .in_value = idcode_buffer,
816                 };
817
818         // initialize to the end of chain ID value
819         for (unsigned i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
820                 buf_set_u32(idcode_buffer, i * 32, 32, 0x000000FF);
821
822         jtag_add_plain_dr_scan(1, &field, TAP_RESET);
823         return jtag_execute_queue();
824 }
825
826 static bool jtag_examine_chain_check(u8 *idcodes, unsigned count)
827 {
828         u8 zero_check = 0x0;
829         u8 one_check = 0xff;
830
831         for (unsigned i = 0; i < count * 4; i++)
832         {
833                 zero_check |= idcodes[i];
834                 one_check &= idcodes[i];
835         }
836
837         /* if there wasn't a single non-zero bit or if all bits were one,
838          * the scan is not valid */
839         if (zero_check == 0x00 || one_check == 0xff)
840         {
841                 LOG_ERROR("JTAG communication failure: check connection, "
842                         "JTAG interface, target power etc.");
843                 return false;
844         }
845         return true;
846 }
847
848 static void jtag_examine_chain_display(enum log_levels level, const char *msg,
849                 const char *name, u32 idcode)
850 {
851         log_printf_lf(level, __FILE__, __LINE__, __FUNCTION__,
852                         "JTAG tap: %s %16.16s: 0x%08x "
853                         "(mfg: 0x%3.3x, part: 0x%4.4x, ver: 0x%1.1x)",
854                 name, msg, idcode,
855                 EXTRACT_MFG(idcode), EXTRACT_PART(idcode), EXTRACT_VER(idcode) );
856 }
857
858 static bool jtag_idcode_is_final(u32 idcode)
859 {
860                 return idcode == 0x000000FF || idcode == 0xFFFFFFFF;
861 }
862
863 /**
864  * This helper checks that remaining bits in the examined chain data are
865  * all as expected, but a single JTAG device requires only 64 bits to be
866  * read back correctly.  This can help identify and diagnose problems
867  * with the JTAG chain earlier, gives more helpful/explicit error messages.
868  */
869 static void jtag_examine_chain_end(u8 *idcodes, unsigned count, unsigned max)
870 {
871         bool triggered = false;
872         for ( ; count < max - 31; count += 32)
873         {
874                 u32 idcode = buf_get_u32(idcodes, count, 32);
875                 // do not trigger the warning if the data looks good
876                 if (!triggered && jtag_idcode_is_final(idcode))
877                         continue;
878                 LOG_WARNING("Unexpected idcode after end of chain: %d 0x%08x",
879                                 count, idcode);
880                 triggered = true;
881         }
882 }
883
884 static bool jtag_examine_chain_match_tap(const struct jtag_tap_s *tap)
885 {
886         if (0 == tap->expected_ids_cnt)
887         {
888                 /// @todo Enable LOG_INFO to ask for reports about unknown TAP IDs.
889 #if 0
890                 LOG_INFO("Uknown JTAG TAP ID: 0x%08x", tap->idcode)
891                 LOG_INFO("Please report the chip name and reported ID code to the openocd project");
892 #endif
893                 return true;
894         }
895
896         /* Loop over the expected identification codes and test for a match */
897         u8 ii;
898         for (ii = 0; ii < tap->expected_ids_cnt; ii++)
899         {
900                 if (tap->idcode == tap->expected_ids[ii])
901                         break;
902         }
903
904         /* If none of the expected ids matched, log an error */
905         if (ii != tap->expected_ids_cnt)
906         {
907                 LOG_INFO("JTAG Tap/device matched");
908                 return true;
909         }
910         jtag_examine_chain_display(LOG_LVL_ERROR, "got",
911                         tap->dotted_name, tap->idcode);
912         for (ii = 0; ii < tap->expected_ids_cnt; ii++)
913         {
914                 char msg[32];
915                 snprintf(msg, sizeof(msg), "expected %hhu of %hhu",
916                                 ii + 1, tap->expected_ids_cnt);
917                 jtag_examine_chain_display(LOG_LVL_ERROR, msg,
918                                 tap->dotted_name, tap->expected_ids[ii]);
919         }
920         return false;
921 }
922
923 /* Try to examine chain layout according to IEEE 1149.1 Â§12
924  */
925 int jtag_examine_chain(void)
926 {
927         u8 idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
928         unsigned device_count = 0;
929
930         jtag_examine_chain_execute(idcode_buffer, JTAG_MAX_CHAIN_SIZE);
931
932         if (!jtag_examine_chain_check(idcode_buffer, JTAG_MAX_CHAIN_SIZE))
933                 return ERROR_JTAG_INIT_FAILED;
934
935         /* point at the 1st tap */
936         jtag_tap_t *tap = jtag_tap_next_enabled(NULL);
937         if (tap == NULL)
938         {
939                 LOG_ERROR("JTAG: No taps enabled?");
940                 return ERROR_JTAG_INIT_FAILED;
941         }
942
943         for (unsigned bit_count = 0; bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;)
944         {
945                 u32 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
946                 if ((idcode & 1) == 0)
947                 {
948                         /* LSB must not be 0, this indicates a device in bypass */
949                         LOG_WARNING("Tap/Device does not have IDCODE");
950                         idcode = 0;
951
952                         bit_count += 1;
953                 }
954                 else
955                 {
956                         /*
957                          * End of chain (invalid manufacturer ID) some devices, such
958                          * as AVR will output all 1's instead of TDI input value at
959                          * end of chain.
960                          */
961                         if (jtag_idcode_is_final(idcode))
962                         {
963                                 jtag_examine_chain_end(idcode_buffer,
964                                                 bit_count + 32, JTAG_MAX_CHAIN_SIZE * 32);
965                                 break;
966                         }
967
968                         jtag_examine_chain_display(LOG_LVL_INFO, "tap/device found",
969                                         tap ? tap->dotted_name : "(not-named)",
970                                         idcode);
971
972                         bit_count += 32;
973                 }
974                 device_count++;
975                 if (!tap)
976                         continue;
977
978                 tap->idcode = idcode;
979
980                 // ensure the TAP ID does matches what was expected
981                 if (!jtag_examine_chain_match_tap(tap))
982                         return ERROR_JTAG_INIT_FAILED;
983
984                 tap = jtag_tap_next_enabled(tap);
985         }
986
987         /* see if number of discovered devices matches configuration */
988         if (device_count != jtag_tap_count_enabled())
989         {
990                 LOG_ERROR("number of discovered devices in JTAG chain (%i) "
991                                 "does not match (enabled) configuration (%i), total taps: %d",
992                                 device_count, jtag_tap_count_enabled(), jtag_tap_count());
993                 LOG_ERROR("check the config file and ensure proper JTAG communication"
994                                 " (connections, speed, ...)");
995                 return ERROR_JTAG_INIT_FAILED;
996         }
997
998         return ERROR_OK;
999 }
1000
1001 int jtag_validate_chain(void)
1002 {
1003         jtag_tap_t *tap;
1004         int total_ir_length = 0;
1005         u8 *ir_test = NULL;
1006         scan_field_t field;
1007         int chain_pos = 0;
1008
1009         tap = NULL;
1010         total_ir_length = 0;
1011         for(;;){
1012                 tap = jtag_tap_next_enabled(tap);
1013                 if( tap == NULL ){
1014                         break;
1015                 }
1016                 total_ir_length += tap->ir_length;
1017         }
1018
1019         total_ir_length += 2;
1020         ir_test = malloc(CEIL(total_ir_length, 8));
1021         buf_set_ones(ir_test, total_ir_length);
1022
1023         field.tap = NULL;
1024         field.num_bits = total_ir_length;
1025         field.out_value = ir_test;
1026         field.in_value = ir_test;
1027
1028
1029         jtag_add_plain_ir_scan(1, &field, TAP_RESET);
1030         jtag_execute_queue();
1031
1032         tap = NULL;
1033         chain_pos = 0;
1034         int val;
1035         for(;;){
1036                 tap = jtag_tap_next_enabled(tap);
1037                 if( tap == NULL ){
1038                         break;
1039                 }
1040
1041                 val = buf_get_u32(ir_test, chain_pos, 2);
1042                 if (val != 0x1)
1043                 {
1044                         char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1045                         LOG_ERROR("Could not validate JTAG scan chain, IR mismatch, scan returned 0x%s. tap=%s pos=%d expected 0x1 got %0x", cbuf, jtag_tap_name(tap), chain_pos, val);
1046                         free(cbuf);
1047                         free(ir_test);
1048                         return ERROR_JTAG_INIT_FAILED;
1049                 }
1050                 chain_pos += tap->ir_length;
1051         }
1052
1053         val = buf_get_u32(ir_test, chain_pos, 2);
1054         if (val != 0x3)
1055         {
1056                 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1057                 LOG_ERROR("Could not validate end of JTAG scan chain, IR mismatch, scan returned 0x%s. pos=%d expected 0x3 got %0x", cbuf, chain_pos, val);
1058                 free(cbuf);
1059                 free(ir_test);
1060                 return ERROR_JTAG_INIT_FAILED;
1061         }
1062
1063         free(ir_test);
1064
1065         return ERROR_OK;
1066 }
1067
1068
1069 void jtag_tap_init(jtag_tap_t *tap)
1070 {
1071         assert(0 != tap->ir_length);
1072
1073         tap->expected = malloc(tap->ir_length);
1074         tap->expected_mask = malloc(tap->ir_length);
1075         tap->cur_instr = malloc(tap->ir_length);
1076
1077         buf_set_u32(tap->expected, 0, tap->ir_length, tap->ir_capture_value);
1078         buf_set_u32(tap->expected_mask, 0, tap->ir_length, tap->ir_capture_mask);
1079         buf_set_ones(tap->cur_instr, tap->ir_length);
1080
1081         // place TAP in bypass mode
1082         tap->bypass = 1;
1083         // register the reset callback for the TAP
1084         jtag_register_event_callback(&jtag_reset_callback, tap);
1085
1086         LOG_DEBUG("Created Tap: %s @ abs position %d, "
1087                         "irlen %d, capture: 0x%x mask: 0x%x", tap->dotted_name,
1088                                 tap->abs_chain_position, tap->ir_length,
1089                                 tap->ir_capture_value, tap->ir_capture_mask);
1090         jtag_tap_add(tap);
1091 }
1092
1093 void jtag_tap_free(jtag_tap_t *tap)
1094 {
1095         /// @todo is anything missing? no memory leaks please 
1096         free((void *)tap->expected_ids);
1097         free((void *)tap->chip);
1098         free((void *)tap->tapname);
1099         free((void *)tap->dotted_name);
1100         free(tap);
1101 }
1102
1103 int jtag_interface_init(struct command_context_s *cmd_ctx)
1104 {
1105         if (jtag)
1106                 return ERROR_OK;
1107
1108         if (!jtag_interface)
1109         {
1110                 /* nothing was previously specified by "interface" command */
1111                 LOG_ERROR("JTAG interface has to be specified, see \"interface\" command");
1112                 return ERROR_JTAG_INVALID_INTERFACE;
1113         }
1114         if(hasKHz)
1115         {
1116                 jtag_interface->khz(jtag_get_speed_khz(), &jtag_speed);
1117                 hasKHz = false;
1118         }
1119
1120         if (jtag_interface->init() != ERROR_OK)
1121                 return ERROR_JTAG_INIT_FAILED;
1122
1123         jtag = jtag_interface;
1124         return ERROR_OK;
1125 }
1126
1127 static int jtag_init_inner(struct command_context_s *cmd_ctx)
1128 {
1129         jtag_tap_t *tap;
1130         int retval;
1131
1132         LOG_DEBUG("Init JTAG chain");
1133
1134         tap = jtag_tap_next_enabled(NULL);
1135         if( tap == NULL ){
1136                 LOG_ERROR("There are no enabled taps?");
1137                 return ERROR_JTAG_INIT_FAILED;
1138         }
1139
1140         jtag_add_tlr();
1141         if ((retval=jtag_execute_queue())!=ERROR_OK)
1142                 return retval;
1143
1144         /* examine chain first, as this could discover the real chain layout */
1145         if (jtag_examine_chain() != ERROR_OK)
1146         {
1147                 LOG_ERROR("trying to validate configured JTAG chain anyway...");
1148         }
1149
1150         if (jtag_validate_chain() != ERROR_OK)
1151         {
1152                 LOG_WARNING("Could not validate JTAG chain, continuing anyway...");
1153         }
1154
1155         return ERROR_OK;
1156 }
1157
1158 int jtag_interface_quit(void)
1159 {
1160         if (!jtag || !jtag->quit)
1161                 return ERROR_OK;
1162
1163         // close the JTAG interface
1164         int result = jtag->quit();
1165         if (ERROR_OK != result)
1166                 LOG_ERROR("failed: %d", result);
1167
1168         return ERROR_OK;
1169 }
1170
1171
1172 int jtag_init_reset(struct command_context_s *cmd_ctx)
1173 {
1174         int retval;
1175
1176         if ((retval=jtag_interface_init(cmd_ctx)) != ERROR_OK)
1177                 return retval;
1178
1179         LOG_DEBUG("Trying to bring the JTAG controller to life by asserting TRST / RESET");
1180
1181         /* Reset can happen after a power cycle.
1182          *
1183          * Ideally we would only assert TRST or run RESET before the target reset.
1184          *
1185          * However w/srst_pulls_trst, trst is asserted together with the target
1186          * reset whether we want it or not.
1187          *
1188          * NB! Some targets have JTAG circuitry disabled until a
1189          * trst & srst has been asserted.
1190          *
1191          * NB! here we assume nsrst/ntrst delay are sufficient!
1192          *
1193          * NB! order matters!!!! srst *can* disconnect JTAG circuitry
1194          *
1195          */
1196         jtag_add_reset(1, 0); /* RESET or TRST */
1197         if (jtag_reset_config & RESET_HAS_SRST)
1198         {
1199                 jtag_add_reset(1, 1);
1200                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST)==0)
1201                         jtag_add_reset(0, 1);
1202         }
1203         jtag_add_reset(0, 0);
1204         if ((retval = jtag_execute_queue()) != ERROR_OK)
1205                 return retval;
1206
1207         /* Check that we can communication on the JTAG chain + eventually we want to
1208          * be able to perform enumeration only after OpenOCD has started
1209          * telnet and GDB server
1210          *
1211          * That would allow users to more easily perform any magic they need to before
1212          * reset happens.
1213          */
1214         return jtag_init_inner(cmd_ctx);
1215 }
1216
1217 int jtag_init(struct command_context_s *cmd_ctx)
1218 {
1219         int retval;
1220         if ((retval=jtag_interface_init(cmd_ctx)) != ERROR_OK)
1221                 return retval;
1222         if (jtag_init_inner(cmd_ctx)==ERROR_OK)
1223         {
1224                 return ERROR_OK;
1225         }
1226         return jtag_init_reset(cmd_ctx);
1227 }
1228
1229 void jtag_set_speed_khz(unsigned khz)
1230 {
1231         speed_khz = khz;
1232 }
1233 unsigned jtag_get_speed_khz(void)
1234 {
1235         return speed_khz;
1236 }
1237 int jtag_config_khz(unsigned khz)
1238 {
1239         LOG_DEBUG("handle jtag khz");
1240         jtag_set_speed_khz(khz);
1241
1242         int cur_speed = 0;
1243         if (jtag != NULL)
1244         {
1245                 LOG_DEBUG("have interface set up");
1246                 int speed_div1;
1247                 int retval = jtag->khz(jtag_get_speed_khz(), &speed_div1);
1248                 if (ERROR_OK != retval)
1249                 {
1250                         jtag_set_speed_khz(0);
1251                         return retval;
1252                 }
1253                 cur_speed = speed_div1;
1254         }
1255         return jtag_set_speed(cur_speed);
1256 }
1257
1258 int jtag_get_speed(void)
1259 {
1260         return jtag_speed;
1261 }
1262
1263 int jtag_set_speed(int speed)
1264 {
1265         jtag_speed = speed;
1266         /* this command can be called during CONFIG,
1267          * in which case jtag isn't initialized */
1268         hasKHz = !jtag;
1269         return jtag ? jtag->speed(speed) : ERROR_OK;
1270 }
1271
1272 int jtag_get_speed_readable(int *speed)
1273 {
1274         return jtag ? jtag->speed_div(jtag_get_speed(), speed) : ERROR_OK;
1275 }
1276
1277
1278 void jtag_set_verify(bool enable)
1279 {
1280         jtag_verify = enable;
1281 }
1282
1283 bool jtag_will_verify()
1284 {
1285         return jtag_verify;
1286 }
1287
1288 void jtag_set_verify_capture_ir(bool enable)
1289 {
1290         jtag_verify_capture_ir = enable;
1291 }
1292
1293 bool jtag_will_verify_capture_ir()
1294 {
1295         return jtag_verify_capture_ir;
1296 }
1297
1298 int jtag_power_dropout(int *dropout)
1299 {
1300         return jtag->power_dropout(dropout);
1301 }
1302
1303 int jtag_srst_asserted(int *srst_asserted)
1304 {
1305         return jtag->srst_asserted(srst_asserted);
1306 }
1307
1308 enum reset_types jtag_get_reset_config(void)
1309 {
1310         return jtag_reset_config;
1311 }
1312 void jtag_set_reset_config(enum reset_types type)
1313 {
1314         jtag_reset_config = type;
1315 }
1316
1317 int jtag_get_trst(void)
1318 {
1319         return jtag_trst;
1320 }
1321 int jtag_get_srst(void)
1322 {
1323         return jtag_srst;
1324 }
1325
1326 void jtag_set_nsrst_delay(unsigned delay)
1327 {
1328         jtag_nsrst_delay = delay;
1329 }
1330 unsigned jtag_get_nsrst_delay(void)
1331 {
1332         return jtag_nsrst_delay;
1333 }
1334 void jtag_set_ntrst_delay(unsigned delay)
1335 {
1336         jtag_ntrst_delay = delay;
1337 }
1338 unsigned jtag_get_ntrst_delay(void)
1339 {
1340         return jtag_ntrst_delay;
1341 }