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