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