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