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