buildfix
[fw/openocd] / src / jtag / tcl.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007-2010 Ã˜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 #include "interfaces.h"
38
39 #ifdef HAVE_STRINGS_H
40 #include <strings.h>
41 #endif
42
43 /**
44  * @file
45  * Holds support for accessing JTAG-specific mechanisms from TCl scripts.
46  */
47
48 static const Jim_Nvp nvp_jtag_tap_event[] = {
49         { .value = JTAG_TRST_ASSERTED,          .name = "post-reset" },
50         { .value = JTAG_TAP_EVENT_SETUP,        .name = "setup" },
51         { .value = JTAG_TAP_EVENT_ENABLE,       .name = "tap-enable" },
52         { .value = JTAG_TAP_EVENT_DISABLE,      .name = "tap-disable" },
53
54         { .name = NULL, .value = -1 }
55 };
56
57 extern struct jtag_interface *jtag_interface;
58
59 struct jtag_tap *jtag_tap_by_jim_obj(Jim_Interp *interp, Jim_Obj *o)
60 {
61         const char *cp = Jim_GetString(o, NULL);
62         struct jtag_tap *t = cp ? jtag_tap_by_string(cp) : NULL;
63         if (NULL == cp)
64                 cp = "(unknown)";
65         if (NULL == t)
66                 Jim_SetResult_sprintf(interp, "Tap '%s' could not be found", cp);
67         return t;
68 }
69
70 static bool scan_is_safe(tap_state_t state)
71 {
72         switch (state)
73         {
74         case TAP_RESET:
75         case TAP_IDLE:
76         case TAP_DRPAUSE:
77         case TAP_IRPAUSE:
78                 return true;
79         default:
80                 return false;
81         }
82 }
83
84 static int Jim_Command_drscan(Jim_Interp *interp, int argc, Jim_Obj *const *args)
85 {
86         int retval;
87         struct scan_field *fields;
88         int num_fields;
89         int field_count = 0;
90         int i, e;
91         struct jtag_tap *tap;
92         tap_state_t endstate;
93
94         /* args[1] = device
95          * args[2] = num_bits
96          * args[3] = hex string
97          * ... repeat num bits and hex string ...
98          *
99          * .. optionally:
100         *     args[N-2] = "-endstate"
101          *     args[N-1] = statename
102          */
103         if ((argc < 4) || ((argc % 2) != 0))
104         {
105                 Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
106                 return JIM_ERR;
107         }
108
109         endstate = TAP_IDLE;
110
111         script_debug(interp, "drscan", argc, args);
112
113         /* validate arguments as numbers */
114         e = JIM_OK;
115         for (i = 2; i < argc; i += 2)
116         {
117                 long bits;
118                 const char *cp;
119
120                 e = Jim_GetLong(interp, args[i], &bits);
121                 /* If valid - try next arg */
122                 if (e == JIM_OK) {
123                         continue;
124                 }
125
126                 /* Not valid.. are we at the end? */
127                 if (((i + 2) != argc)) {
128                         /* nope, then error */
129                         return e;
130                 }
131
132                 /* it could be: "-endstate FOO"
133                  * e.g. DRPAUSE so we can issue more instructions
134                  * before entering RUN/IDLE and executing them.
135                  */
136
137                 /* get arg as a string. */
138                 cp = Jim_GetString(args[i], NULL);
139                 /* is it the magic? */
140                 if (0 == strcmp("-endstate", cp)) {
141                         /* is the statename valid? */
142                         cp = Jim_GetString(args[i + 1], NULL);
143
144                         /* see if it is a valid state name */
145                         endstate = tap_state_by_name(cp);
146                         if (endstate < 0) {
147                                 /* update the error message */
148                                 Jim_SetResult_sprintf(interp,"endstate: %s invalid", cp);
149                         } else {
150                                 if (!scan_is_safe(endstate))
151                                         LOG_WARNING("drscan with unsafe "
152                                                         "endstate \"%s\"", cp);
153
154                                 /* valid - so clear the error */
155                                 e = JIM_OK;
156                                 /* and remove the last 2 args */
157                                 argc -= 2;
158                         }
159                 }
160
161                 /* Still an error? */
162                 if (e != JIM_OK) {
163                         return e; /* too bad */
164                 }
165         } /* validate args */
166
167         tap = jtag_tap_by_jim_obj(interp, args[1]);
168         if (tap == NULL) {
169                 return JIM_ERR;
170         }
171
172         num_fields = (argc-2)/2;
173         fields = malloc(sizeof(struct scan_field) * num_fields);
174         for (i = 2; i < argc; i += 2)
175         {
176                 long bits;
177                 int len;
178                 const char *str;
179
180                 Jim_GetLong(interp, args[i], &bits);
181                 str = Jim_GetString(args[i + 1], &len);
182
183                 fields[field_count].num_bits = bits;
184                 void * t = malloc(DIV_ROUND_UP(bits, 8));
185                 fields[field_count].out_value = t;
186                 str_to_buf(str, len, t, bits, 0);
187                 fields[field_count].in_value = t;
188                 field_count++;
189         }
190
191         jtag_add_dr_scan(tap, num_fields, fields, endstate);
192
193         retval = jtag_execute_queue();
194         if (retval != ERROR_OK)
195         {
196                 Jim_SetResultString(interp, "drscan: jtag execute failed",-1);
197                 return JIM_ERR;
198         }
199
200         field_count = 0;
201         Jim_Obj *list = Jim_NewListObj(interp, NULL, 0);
202         for (i = 2; i < argc; i += 2)
203         {
204                 long bits;
205                 char *str;
206
207                 Jim_GetLong(interp, args[i], &bits);
208                 str = buf_to_str(fields[field_count].in_value, bits, 16);
209                 free((void *)fields[field_count].out_value);
210
211                 Jim_ListAppendElement(interp, list, Jim_NewStringObj(interp, str, strlen(str)));
212                 free(str);
213                 field_count++;
214         }
215
216         Jim_SetResult(interp, list);
217
218         free(fields);
219
220         return JIM_OK;
221 }
222
223
224 static int Jim_Command_pathmove(Jim_Interp *interp, int argc, Jim_Obj *const *args)
225 {
226         tap_state_t states[8];
227
228         if ((argc < 2) || ((size_t)argc > (ARRAY_SIZE(states) + 1)))
229         {
230                 Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
231                 return JIM_ERR;
232         }
233
234         script_debug(interp, "pathmove", argc, args);
235
236         int i;
237         for (i = 0; i < argc-1; i++)
238         {
239                 const char *cp;
240                 cp = Jim_GetString(args[i + 1], NULL);
241                 states[i] = tap_state_by_name(cp);
242                 if (states[i] < 0)
243                 {
244                         /* update the error message */
245                         Jim_SetResult_sprintf(interp,"endstate: %s invalid", cp);
246                         return JIM_ERR;
247                 }
248         }
249
250         if ((jtag_add_statemove(states[0]) != ERROR_OK) || (jtag_execute_queue()!= ERROR_OK))
251         {
252                 Jim_SetResultString(interp, "pathmove: jtag execute failed",-1);
253                 return JIM_ERR;
254         }
255
256         jtag_add_pathmove(argc-2, states + 1);
257
258         if (jtag_execute_queue()!= ERROR_OK)
259         {
260                 Jim_SetResultString(interp, "pathmove: failed",-1);
261                 return JIM_ERR;
262         }
263
264         return JIM_OK;
265 }
266
267
268 static int Jim_Command_flush_count(Jim_Interp *interp, int argc, Jim_Obj *const *args)
269 {
270         script_debug(interp, "flush_count", argc, args);
271
272         Jim_SetResult(interp, Jim_NewIntObj(interp, jtag_get_flush_queue_count()));
273
274         return JIM_OK;
275 }
276
277 /* REVISIT Just what about these should "move" ... ?
278  * These registrations, into the main JTAG table?
279  *
280  * There's a minor compatibility issue, these all show up twice;
281  * that's not desirable:
282  *  - jtag drscan ... NOT DOCUMENTED!
283  *  - drscan ...
284  *
285  * The "irscan" command (for example) doesn't show twice.
286  */
287 static const struct command_registration jtag_command_handlers_to_move[] = {
288         {
289                 .name = "drscan",
290                 .mode = COMMAND_EXEC,
291                 .jim_handler = Jim_Command_drscan,
292                 .help = "Execute Data Register (DR) scan for one TAP.  "
293                         "Other TAPs must be in BYPASS mode.",
294                 .usage = "tap_name [num_bits value]* ['-endstate' state_name]",
295         },
296         {
297                 .name = "flush_count",
298                 .mode = COMMAND_EXEC,
299                 .jim_handler = Jim_Command_flush_count,
300                 .help = "Returns the number of times the JTAG queue "
301                         "has been flushed.",
302         },
303         {
304                 .name = "pathmove",
305                 .mode = COMMAND_EXEC,
306                 .jim_handler = Jim_Command_pathmove,
307                 .usage = "start_state state1 [state2 [state3 ...]]",
308                 .help = "Move JTAG state machine from current state "
309                         "(start_state) to state1, then state2, state3, etc.",
310         },
311         COMMAND_REGISTRATION_DONE
312 };
313
314
315 enum jtag_tap_cfg_param {
316         JCFG_EVENT
317 };
318
319 static Jim_Nvp nvp_config_opts[] = {
320         { .name = "-event",      .value = JCFG_EVENT },
321
322         { .name = NULL,          .value = -1 }
323 };
324
325 static int jtag_tap_configure_event(Jim_GetOptInfo *goi, struct jtag_tap * tap)
326 {
327         if (goi->argc == 0)
328         {
329                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name> ...");
330                 return JIM_ERR;
331         }
332
333         Jim_Nvp *n;
334         int e = Jim_GetOpt_Nvp(goi, nvp_jtag_tap_event, &n);
335         if (e != JIM_OK)
336         {
337                 Jim_GetOpt_NvpUnknown(goi, nvp_jtag_tap_event, 1);
338                 return e;
339         }
340
341         if (goi->isconfigure) {
342                 if (goi->argc != 1) {
343                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name> <event-body>");
344                         return JIM_ERR;
345                 }
346         } else {
347                 if (goi->argc != 0) {
348                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name>");
349                         return JIM_ERR;
350                 }
351         }
352
353         struct jtag_tap_event_action *jteap  = tap->event_action;
354         /* replace existing event body */
355         bool found = false;
356         while (jteap)
357         {
358                 if (jteap->event == (enum jtag_event)n->value)
359                 {
360                         found = true;
361                         break;
362                 }
363                 jteap = jteap->next;
364         }
365
366         Jim_SetEmptyResult(goi->interp);
367
368         if (goi->isconfigure)
369         {
370                 if (!found)
371                         jteap = calloc(1, sizeof(*jteap));
372                 else if (NULL != jteap->body)
373                         Jim_DecrRefCount(goi->interp, jteap->body);
374
375                 jteap->interp = goi->interp;
376                 jteap->event = n->value;
377
378                 Jim_Obj *o;
379                 Jim_GetOpt_Obj(goi, &o);
380                 jteap->body = Jim_DuplicateObj(goi->interp, o);
381                 Jim_IncrRefCount(jteap->body);
382
383                 if (!found)
384                 {
385                         /* add to head of event list */
386                         jteap->next = tap->event_action;
387                         tap->event_action = jteap;
388                 }
389         }
390         else if (found)
391         {
392                 jteap->interp = goi->interp;
393                 Jim_SetResult(goi->interp,
394                         Jim_DuplicateObj(goi->interp, jteap->body));
395         }
396         return JIM_OK;
397 }
398
399 static int jtag_tap_configure_cmd(Jim_GetOptInfo *goi, struct jtag_tap * tap)
400 {
401         /* parse config or cget options */
402         while (goi->argc > 0)
403         {
404                 Jim_SetEmptyResult (goi->interp);
405
406                 Jim_Nvp *n;
407                 int e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
408                 if (e != JIM_OK)
409                 {
410                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
411                         return e;
412                 }
413
414                 switch (n->value)
415                 {
416                 case JCFG_EVENT:
417                         e = jtag_tap_configure_event(goi, tap);
418                         if (e != JIM_OK)
419                                 return e;
420                         break;
421                 default:
422                         Jim_SetResult_sprintf(goi->interp, "unknown event: %s", n->name);
423                         return JIM_ERR;
424                 }
425         }
426
427         return JIM_OK;
428 }
429
430 static int is_bad_irval(int ir_length, jim_wide w)
431 {
432         jim_wide v = 1;
433
434         v <<= ir_length;
435         v -= 1;
436         v = ~v;
437         return (w & v) != 0;
438 }
439
440 static int jim_newtap_expected_id(Jim_Nvp *n, Jim_GetOptInfo *goi,
441                 struct jtag_tap *pTap)
442 {
443         jim_wide w;
444         int e = Jim_GetOpt_Wide(goi, &w);
445         if (e != JIM_OK) {
446                 Jim_SetResult_sprintf(goi->interp, "option: %s bad parameter", n->name);
447                 return e;
448         }
449
450         unsigned expected_len = sizeof(uint32_t) * pTap->expected_ids_cnt;
451         uint32_t *new_expected_ids = malloc(expected_len + sizeof(uint32_t));
452         if (new_expected_ids == NULL)
453         {
454                 Jim_SetResult_sprintf(goi->interp, "no memory");
455                 return JIM_ERR;
456         }
457
458         memcpy(new_expected_ids, pTap->expected_ids, expected_len);
459
460         new_expected_ids[pTap->expected_ids_cnt] = w;
461
462         free(pTap->expected_ids);
463         pTap->expected_ids = new_expected_ids;
464         pTap->expected_ids_cnt++;
465
466         return JIM_OK;
467 }
468
469 #define NTAP_OPT_IRLEN     0
470 #define NTAP_OPT_IRMASK    1
471 #define NTAP_OPT_IRCAPTURE 2
472 #define NTAP_OPT_ENABLED   3
473 #define NTAP_OPT_DISABLED  4
474 #define NTAP_OPT_EXPECTED_ID 5
475 #define NTAP_OPT_VERSION   6
476
477 static int jim_newtap_ir_param(Jim_Nvp *n, Jim_GetOptInfo *goi,
478                 struct jtag_tap *pTap)
479 {
480         jim_wide w;
481         int e = Jim_GetOpt_Wide(goi, &w);
482         if (e != JIM_OK)
483         {
484                 Jim_SetResult_sprintf(goi->interp,
485                                 "option: %s bad parameter", n->name);
486                 free((void *)pTap->dotted_name);
487                 return e;
488         }
489         switch (n->value) {
490         case NTAP_OPT_IRLEN:
491                 if (w > (jim_wide) (8 * sizeof(pTap->ir_capture_value)))
492                 {
493                         LOG_WARNING("%s: huge IR length %d",
494                                         pTap->dotted_name, (int) w);
495                 }
496                 pTap->ir_length = w;
497                 break;
498         case NTAP_OPT_IRMASK:
499                 if (is_bad_irval(pTap->ir_length, w))
500                 {
501                         LOG_ERROR("%s: IR mask %x too big",
502                                         pTap->dotted_name,
503                                         (int) w);
504                         return JIM_ERR;
505                 }
506                 if ((w & 3) != 3)
507                         LOG_WARNING("%s: nonstandard IR mask", pTap->dotted_name);
508                 pTap->ir_capture_mask = w;
509                 break;
510         case NTAP_OPT_IRCAPTURE:
511                 if (is_bad_irval(pTap->ir_length, w))
512                 {
513                         LOG_ERROR("%s: IR capture %x too big",
514                                         pTap->dotted_name, (int) w);
515                         return JIM_ERR;
516                 }
517                 if ((w & 3) != 1)
518                         LOG_WARNING("%s: nonstandard IR value",
519                                         pTap->dotted_name);
520                 pTap->ir_capture_value = w;
521                 break;
522         default:
523                 return JIM_ERR;
524         }
525         return JIM_OK;
526 }
527
528 static int jim_newtap_cmd(Jim_GetOptInfo *goi)
529 {
530         struct jtag_tap *pTap;
531         int x;
532         int e;
533         Jim_Nvp *n;
534         char *cp;
535         const Jim_Nvp opts[] = {
536                 { .name = "-irlen"                      ,       .value = NTAP_OPT_IRLEN },
537                 { .name = "-irmask"                     ,       .value = NTAP_OPT_IRMASK },
538                 { .name = "-ircapture"          ,       .value = NTAP_OPT_IRCAPTURE },
539                 { .name = "-enable"                     ,       .value = NTAP_OPT_ENABLED },
540                 { .name = "-disable"            ,       .value = NTAP_OPT_DISABLED },
541                 { .name = "-expected-id"        ,       .value = NTAP_OPT_EXPECTED_ID },
542                 { .name = "-ignore-version"     ,       .value = NTAP_OPT_VERSION },
543                 { .name = NULL                          ,       .value = -1 },
544         };
545
546         pTap = calloc(1, sizeof(struct jtag_tap));
547         if (!pTap) {
548                 Jim_SetResult_sprintf(goi->interp, "no memory");
549                 return JIM_ERR;
550         }
551
552         /*
553          * we expect CHIP + TAP + OPTIONS
554          * */
555         if (goi->argc < 3) {
556                 Jim_SetResult_sprintf(goi->interp, "Missing CHIP TAP OPTIONS ....");
557                 free(pTap);
558                 return JIM_ERR;
559         }
560         Jim_GetOpt_String(goi, &cp, NULL);
561         pTap->chip = strdup(cp);
562
563         Jim_GetOpt_String(goi, &cp, NULL);
564         pTap->tapname = strdup(cp);
565
566         /* name + dot + name + null */
567         x = strlen(pTap->chip) + 1 + strlen(pTap->tapname) + 1;
568         cp = malloc(x);
569         sprintf(cp, "%s.%s", pTap->chip, pTap->tapname);
570         pTap->dotted_name = cp;
571
572         LOG_DEBUG("Creating New Tap, Chip: %s, Tap: %s, Dotted: %s, %d params",
573                           pTap->chip, pTap->tapname, pTap->dotted_name, goi->argc);
574
575         /* IEEE specifies that the two LSBs of an IR scan are 01, so make
576          * that the default.  The "-irlen" and "-irmask" options are only
577          * needed to cope with nonstandard TAPs, or to specify more bits.
578          */
579         pTap->ir_capture_mask = 0x03;
580         pTap->ir_capture_value = 0x01;
581
582         while (goi->argc) {
583                 e = Jim_GetOpt_Nvp(goi, opts, &n);
584                 if (e != JIM_OK) {
585                         Jim_GetOpt_NvpUnknown(goi, opts, 0);
586                         free((void *)pTap->dotted_name);
587                         free(pTap);
588                         return e;
589                 }
590                 LOG_DEBUG("Processing option: %s", n->name);
591                 switch (n->value) {
592                 case NTAP_OPT_ENABLED:
593                         pTap->disabled_after_reset = false;
594                         break;
595                 case NTAP_OPT_DISABLED:
596                         pTap->disabled_after_reset = true;
597                         break;
598                 case NTAP_OPT_EXPECTED_ID:
599                         e = jim_newtap_expected_id(n, goi, pTap);
600                         if (JIM_OK != e)
601                         {
602                                 free((void *)pTap->dotted_name);
603                                 free(pTap);
604                                 return e;
605                         }
606                         break;
607                 case NTAP_OPT_IRLEN:
608                 case NTAP_OPT_IRMASK:
609                 case NTAP_OPT_IRCAPTURE:
610                         e = jim_newtap_ir_param(n, goi, pTap);
611                         if (JIM_OK != e)
612                         {
613                                 free((void *)pTap->dotted_name);
614                                 free(pTap);
615                                 return e;
616                         }
617                         break;
618                 case NTAP_OPT_VERSION:
619                         pTap->ignore_version = true;
620                         break;
621                 } /* switch (n->value) */
622         } /* while (goi->argc) */
623
624         /* default is enabled-after-reset */
625         pTap->enabled = !pTap->disabled_after_reset;
626
627         /* Did all the required option bits get cleared? */
628         if (pTap->ir_length != 0)
629         {
630                 jtag_tap_init(pTap);
631                 return JIM_OK;
632         }
633
634         Jim_SetResult_sprintf(goi->interp,
635                         "newtap: %s missing IR length",
636                         pTap->dotted_name);
637         jtag_tap_free(pTap);
638         return JIM_ERR;
639 }
640
641 static void jtag_tap_handle_event(struct jtag_tap *tap, enum jtag_event e)
642 {
643         struct jtag_tap_event_action * jteap;
644
645         for (jteap = tap->event_action; jteap != NULL; jteap = jteap->next)
646         {
647                 if (jteap->event != e)
648                         continue;
649
650                 Jim_Nvp *nvp = Jim_Nvp_value2name_simple(nvp_jtag_tap_event, e);
651                 LOG_DEBUG("JTAG tap: %s event: %d (%s)\n\taction: %s",
652                                 tap->dotted_name, e, nvp->name,
653                                 Jim_GetString(jteap->body, NULL));
654
655                 if (Jim_EvalObj(jteap->interp, jteap->body) != JIM_OK)
656                 {
657                         Jim_PrintErrorMessage(jteap->interp);
658                         continue;
659                 }
660
661                 switch (e)
662                 {
663                 case JTAG_TAP_EVENT_ENABLE:
664                 case JTAG_TAP_EVENT_DISABLE:
665                         /* NOTE:  we currently assume the handlers
666                          * can't fail.  Right here is where we should
667                          * really be verifying the scan chains ...
668                          */
669                         tap->enabled = (e == JTAG_TAP_EVENT_ENABLE);
670                         LOG_INFO("JTAG tap: %s %s", tap->dotted_name,
671                                 tap->enabled ? "enabled" : "disabled");
672                         break;
673                 default:
674                         break;
675                 }
676         }
677 }
678
679 static int jim_jtag_arp_init(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
680 {
681         Jim_GetOptInfo goi;
682         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
683         if (goi.argc != 0) {
684                 Jim_WrongNumArgs(goi.interp, 1, goi.argv-1, "(no params)");
685                 return JIM_ERR;
686         }
687         struct command_context *context = Jim_GetAssocData(interp, "context");
688         int e = jtag_init_inner(context);
689         if (e != ERROR_OK) {
690                 Jim_SetResult_sprintf(goi.interp, "error: %d", e);
691                 return JIM_ERR;
692         }
693         return JIM_OK;
694 }
695
696 static int jim_jtag_arp_init_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
697 {
698         Jim_GetOptInfo goi;
699         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
700         if (goi.argc != 0) {
701                 Jim_WrongNumArgs(goi.interp, 1, goi.argv-1, "(no params)");
702                 return JIM_ERR;
703         }
704         struct command_context *context = Jim_GetAssocData(interp, "context");
705         int e = jtag_init_reset(context);
706         if (e != ERROR_OK) {
707                 Jim_SetResult_sprintf(goi.interp, "error: %d", e);
708                 return JIM_ERR;
709         }
710         return JIM_OK;
711 }
712
713 static int jim_jtag_newtap(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
714 {
715         Jim_GetOptInfo goi;
716         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
717         return jim_newtap_cmd(&goi);
718 }
719
720 static bool jtag_tap_enable(struct jtag_tap *t)
721 {
722         if (t->enabled)
723                 return false;
724         jtag_tap_handle_event(t, JTAG_TAP_EVENT_ENABLE);
725         if (!t->enabled)
726                 return false;
727
728         /* FIXME add JTAG sanity checks, w/o TLR
729          *  - scan chain length grew by one (this)
730          *  - IDs and IR lengths are as expected
731          */
732         jtag_call_event_callbacks(JTAG_TAP_EVENT_ENABLE);
733         return true;
734 }
735 static bool jtag_tap_disable(struct jtag_tap *t)
736 {
737         if (!t->enabled)
738                 return false;
739         jtag_tap_handle_event(t, JTAG_TAP_EVENT_DISABLE);
740         if (t->enabled)
741                 return false;
742
743         /* FIXME add JTAG sanity checks, w/o TLR
744          *  - scan chain length shrank by one (this)
745          *  - IDs and IR lengths are as expected
746          */
747         jtag_call_event_callbacks(JTAG_TAP_EVENT_DISABLE);
748         return true;
749 }
750
751 static int jim_jtag_tap_enabler(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
752 {
753         const char *cmd_name = Jim_GetString(argv[0], NULL);
754         Jim_GetOptInfo goi;
755         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
756         if (goi.argc != 1) {
757                 Jim_SetResult_sprintf(goi.interp, "usage: %s <name>", cmd_name);
758                 return JIM_ERR;
759         }
760
761         struct jtag_tap *t;
762
763         t = jtag_tap_by_jim_obj(goi.interp, goi.argv[0]);
764         if (t == NULL)
765                 return JIM_ERR;
766
767         if (strcasecmp(cmd_name, "tapisenabled") == 0) {
768                 // do nothing, just return the value
769         } else if (strcasecmp(cmd_name, "tapenable") == 0) {
770                 if (!jtag_tap_enable(t))
771                         LOG_WARNING("failed to disable tap");
772         } else if (strcasecmp(cmd_name, "tapdisable") == 0) {
773                 if (!jtag_tap_disable(t))
774                         LOG_WARNING("failed to disable tap");
775         } else {
776                 LOG_ERROR("command '%s' unknown", cmd_name);
777                 return JIM_ERR;
778         }
779         bool e = t->enabled;
780         Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, e));
781         return JIM_OK;
782 }
783
784 static int jim_jtag_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
785 {
786         const char *cmd_name = Jim_GetString(argv[0], NULL);
787         Jim_GetOptInfo goi;
788         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
789         goi.isconfigure = !strcmp(cmd_name, "configure");
790         if (goi.argc < 2 + goi.isconfigure) {
791                 Jim_WrongNumArgs(goi.interp, 0, NULL,
792                                 "<tap_name> <attribute> ...");
793                 return JIM_ERR;
794         }
795
796         struct jtag_tap *t;
797
798         Jim_Obj *o;
799         Jim_GetOpt_Obj(&goi, &o);
800         t = jtag_tap_by_jim_obj(goi.interp, o);
801         if (t == NULL) {
802                 return JIM_ERR;
803         }
804
805         return jtag_tap_configure_cmd(&goi, t);
806 }
807
808 static int jim_jtag_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
809 {
810         Jim_GetOptInfo goi;
811         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
812         if (goi.argc != 0) {
813                 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
814                 return JIM_ERR;
815         }
816         Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
817         struct jtag_tap *tap;
818
819         for (tap = jtag_all_taps(); tap; tap = tap->next_tap) {
820                 Jim_ListAppendElement(goi.interp,
821                         Jim_GetResult(goi.interp),
822                         Jim_NewStringObj(goi.interp,
823                                 tap->dotted_name, -1));
824         }
825         return JIM_OK;
826 }
827
828 COMMAND_HANDLER(handle_jtag_init_command)
829 {
830         if (CMD_ARGC != 0)
831                 return ERROR_COMMAND_SYNTAX_ERROR;
832
833         static bool jtag_initialized = false;
834         if (jtag_initialized)
835         {
836                 LOG_INFO("'jtag init' has already been called");
837                 return ERROR_OK;
838         }
839         jtag_initialized = true;
840
841         LOG_DEBUG("Initializing jtag devices...");
842         return jtag_init(CMD_CTX);
843 }
844
845 static const struct command_registration jtag_subcommand_handlers[] = {
846         {
847                 .name = "init",
848                 .mode = COMMAND_ANY,
849                 .handler = handle_jtag_init_command,
850                 .help = "initialize jtag scan chain",
851         },
852         {
853                 .name = "arp_init",
854                 .mode = COMMAND_ANY,
855                 .jim_handler = jim_jtag_arp_init,
856                 .help = "Validates JTAG scan chain against the list of "
857                         "declared TAPs using just the four standard JTAG "
858                         "signals.",
859         },
860         {
861                 .name = "arp_init-reset",
862                 .mode = COMMAND_ANY,
863                 .jim_handler = jim_jtag_arp_init_reset,
864                 .help = "Uses TRST and SRST to try resetting everything on "
865                         "the JTAG scan chain, then performs 'jtag arp_init'."
866         },
867         {
868                 .name = "newtap",
869                 .mode = COMMAND_CONFIG,
870                 .jim_handler = jim_jtag_newtap,
871                 .help = "Create a new TAP instance named basename.tap_type, "
872                         "and appends it to the scan chain.",
873                 .usage = "basename tap_type '-irlen' count "
874                         "['-enable'|'-disable'] "
875                         "['-expected_id' number] "
876                         "['-ignore-version'] "
877                         "['-ircapture' number] "
878                         "['-mask' number] ",
879         },
880         {
881                 .name = "tapisenabled",
882                 .mode = COMMAND_EXEC,
883                 .jim_handler = jim_jtag_tap_enabler,
884                 .help = "Returns a Tcl boolean (0/1) indicating whether "
885                         "the TAP is enabled (1) or not (0).",
886                 .usage = "tap_name",
887         },
888         {
889                 .name = "tapenable",
890                 .mode = COMMAND_EXEC,
891                 .jim_handler = jim_jtag_tap_enabler,
892                 .help = "Try to enable the specified TAP using the "
893                         "'tap-enable' TAP event.",
894                 .usage = "tap_name",
895         },
896         {
897                 .name = "tapdisable",
898                 .mode = COMMAND_EXEC,
899                 .jim_handler = jim_jtag_tap_enabler,
900                 .help = "Try to disable the specified TAP using the "
901                         "'tap-disable' TAP event.",
902                 .usage = "tap_name",
903         },
904         {
905                 .name = "configure",
906                 .mode = COMMAND_EXEC,
907                 .jim_handler = jim_jtag_configure,
908                 .help = "Provide a Tcl handler for the specified "
909                         "TAP event.",
910                 .usage = "tap_name '-event' event_name handler",
911         },
912         {
913                 .name = "cget",
914                 .mode = COMMAND_EXEC,
915                 .jim_handler = jim_jtag_configure,
916                 .help = "Return any Tcl handler for the specified "
917                         "TAP event.",
918                 .usage = "tap_name '-event' event_name",
919         },
920         {
921                 .name = "names",
922                 .mode = COMMAND_ANY,
923                 .jim_handler = jim_jtag_names,
924                 .help = "Returns list of all JTAG tap names.",
925         },
926         {
927                 .chain = jtag_command_handlers_to_move,
928         },
929         COMMAND_REGISTRATION_DONE
930 };
931
932 void jtag_notify_event(enum jtag_event event)
933 {
934         struct jtag_tap *tap;
935
936         for (tap = jtag_all_taps(); tap; tap = tap->next_tap)
937                 jtag_tap_handle_event(tap, event);
938 }
939
940
941 COMMAND_HANDLER(handle_scan_chain_command)
942 {
943         struct jtag_tap *tap;
944         char expected_id[12];
945
946         tap = jtag_all_taps();
947         command_print(CMD_CTX,
948 "   TapName             Enabled  IdCode     Expected   IrLen IrCap IrMask");
949         command_print(CMD_CTX,
950 "-- ------------------- -------- ---------- ---------- ----- ----- ------");
951
952         while (tap) {
953                 uint32_t expected, expected_mask, ii;
954
955                 snprintf(expected_id, sizeof expected_id, "0x%08x",
956                                 (unsigned)((tap->expected_ids_cnt > 0)
957                                         ? tap->expected_ids[0]
958                                         : 0));
959                 if (tap->ignore_version)
960                         expected_id[2] = '*';
961
962                 expected = buf_get_u32(tap->expected, 0, tap->ir_length);
963                 expected_mask = buf_get_u32(tap->expected_mask, 0, tap->ir_length);
964
965                 command_print(CMD_CTX,
966         "%2d %-18s     %c     0x%08x %s %5d 0x%02x  0x%02x",
967                                           tap->abs_chain_position,
968                                           tap->dotted_name,
969                                           tap->enabled ? 'Y' : 'n',
970                                           (unsigned int)(tap->idcode),
971                                           expected_id,
972                                           (unsigned int)(tap->ir_length),
973                                           (unsigned int)(expected),
974                                           (unsigned int)(expected_mask));
975
976                 for (ii = 1; ii < tap->expected_ids_cnt; ii++) {
977                         snprintf(expected_id, sizeof expected_id, "0x%08x",
978                                         (unsigned) tap->expected_ids[1]);
979                         if (tap->ignore_version)
980                                 expected_id[2] = '*';
981
982                         command_print(CMD_CTX,
983         "                                           %s",
984                                                   expected_id);
985                 }
986
987                 tap = tap->next_tap;
988         }
989
990         return ERROR_OK;
991 }
992
993 COMMAND_HANDLER(handle_jtag_ntrst_delay_command)
994 {
995         if (CMD_ARGC > 1)
996                 return ERROR_COMMAND_SYNTAX_ERROR;
997         if (CMD_ARGC == 1)
998         {
999                 unsigned delay;
1000                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1001
1002                 jtag_set_ntrst_delay(delay);
1003         }
1004         command_print(CMD_CTX, "jtag_ntrst_delay: %u", jtag_get_ntrst_delay());
1005         return ERROR_OK;
1006 }
1007
1008 COMMAND_HANDLER(handle_jtag_ntrst_assert_width_command)
1009 {
1010         if (CMD_ARGC > 1)
1011                 return ERROR_COMMAND_SYNTAX_ERROR;
1012         if (CMD_ARGC == 1)
1013         {
1014                 unsigned delay;
1015                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1016
1017                 jtag_set_ntrst_assert_width(delay);
1018         }
1019         command_print(CMD_CTX, "jtag_ntrst_assert_width: %u", jtag_get_ntrst_assert_width());
1020         return ERROR_OK;
1021 }
1022
1023 COMMAND_HANDLER(handle_jtag_rclk_command)
1024 {
1025         if (CMD_ARGC > 1)
1026                 return ERROR_COMMAND_SYNTAX_ERROR;
1027
1028         int retval = ERROR_OK;
1029         if (CMD_ARGC == 1)
1030         {
1031                 unsigned khz = 0;
1032                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], khz);
1033
1034                 retval = jtag_config_rclk(khz);
1035                 if (ERROR_OK != retval)
1036                         return retval;
1037         }
1038
1039         int cur_khz = jtag_get_speed_khz();
1040         retval = jtag_get_speed_readable(&cur_khz);
1041         if (ERROR_OK != retval)
1042                 return retval;
1043
1044         if (cur_khz)
1045                 command_print(CMD_CTX, "RCLK not supported - fallback to %d kHz", cur_khz);
1046         else
1047                 command_print(CMD_CTX, "RCLK - adaptive");
1048
1049         return retval;
1050 }
1051
1052 COMMAND_HANDLER(handle_jtag_reset_command)
1053 {
1054         if (CMD_ARGC != 2)
1055                 return ERROR_COMMAND_SYNTAX_ERROR;
1056
1057         int trst = -1;
1058         if (CMD_ARGV[0][0] == '1')
1059                 trst = 1;
1060         else if (CMD_ARGV[0][0] == '0')
1061                 trst = 0;
1062         else
1063                 return ERROR_COMMAND_SYNTAX_ERROR;
1064
1065         int srst = -1;
1066         if (CMD_ARGV[1][0] == '1')
1067                 srst = 1;
1068         else if (CMD_ARGV[1][0] == '0')
1069                 srst = 0;
1070         else
1071                 return ERROR_COMMAND_SYNTAX_ERROR;
1072
1073         if (adapter_init(CMD_CTX) != ERROR_OK)
1074                 return ERROR_JTAG_INIT_FAILED;
1075
1076         jtag_add_reset(trst, srst);
1077         return jtag_execute_queue();
1078 }
1079
1080 COMMAND_HANDLER(handle_runtest_command)
1081 {
1082         if (CMD_ARGC != 1)
1083                 return ERROR_COMMAND_SYNTAX_ERROR;
1084
1085         unsigned num_clocks;
1086         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num_clocks);
1087
1088         jtag_add_runtest(num_clocks, TAP_IDLE);
1089         return jtag_execute_queue();
1090 }
1091
1092 /*
1093  * For "irscan" or "drscan" commands, the "end" (really, "next") state
1094  * should be stable ... and *NOT* a shift state, otherwise free-running
1095  * jtag clocks could change the values latched by the update state.
1096  * Not surprisingly, this is the same constraint as SVF; the "irscan"
1097  * and "drscan" commands are a write-only subset of what SVF provides.
1098  */
1099
1100 COMMAND_HANDLER(handle_irscan_command)
1101 {
1102         int i;
1103         struct scan_field *fields;
1104         struct jtag_tap *tap = NULL;
1105         tap_state_t endstate;
1106
1107         if ((CMD_ARGC < 2) || (CMD_ARGC % 2))
1108         {
1109                 return ERROR_COMMAND_SYNTAX_ERROR;
1110         }
1111
1112         /* optional "-endstate" "statename" at the end of the arguments,
1113          * so that e.g. IRPAUSE can let us load the data register before
1114          * entering RUN/IDLE to execute the instruction we load here.
1115          */
1116         endstate = TAP_IDLE;
1117
1118         if (CMD_ARGC >= 4) {
1119                 /* have at least one pair of numbers. */
1120                 /* is last pair the magic text? */
1121                 if (strcmp("-endstate", CMD_ARGV[CMD_ARGC - 2]) == 0) {
1122                         endstate = tap_state_by_name(CMD_ARGV[CMD_ARGC - 1]);
1123                         if (endstate == TAP_INVALID)
1124                                 return ERROR_COMMAND_SYNTAX_ERROR;
1125                         if (!scan_is_safe(endstate))
1126                                 LOG_WARNING("unstable irscan endstate \"%s\"",
1127                                                 CMD_ARGV[CMD_ARGC - 1]);
1128                         CMD_ARGC -= 2;
1129                 }
1130         }
1131
1132         int num_fields = CMD_ARGC / 2;
1133         if (num_fields > 1)
1134         {
1135                 /* we really should be looking at plain_ir_scan if we want
1136                  * anything more fancy.
1137                  */
1138                 LOG_ERROR("Specify a single value for tap");
1139                 return ERROR_COMMAND_SYNTAX_ERROR;
1140         }
1141
1142         size_t fields_len = sizeof(struct scan_field) * num_fields;
1143         fields = malloc(fields_len);
1144         memset(fields, 0, fields_len);
1145
1146         int retval;
1147         for (i = 0; i < num_fields; i++)
1148         {
1149                 tap = jtag_tap_by_string(CMD_ARGV[i*2]);
1150                 if (tap == NULL)
1151                 {
1152                         int j;
1153                         for (j = 0; j < i; j++)
1154                                 free((void *)fields[j].out_value);
1155                         free(fields);
1156                         command_print(CMD_CTX, "Tap: %s unknown", CMD_ARGV[i*2]);
1157
1158                         return ERROR_FAIL;
1159                 }
1160                 int field_size = tap->ir_length;
1161                 fields[i].num_bits = field_size;
1162                 fields[i].out_value = malloc(DIV_ROUND_UP(field_size, 8));
1163
1164                 uint32_t value;
1165                 retval = parse_u32(CMD_ARGV[i * 2 + 1], &value);
1166                 if (ERROR_OK != retval)
1167                         goto error_return;
1168 void *v = (void *)fields[i].out_value;
1169                 buf_set_u32(v, 0, field_size, value);
1170                 fields[i].in_value = NULL;
1171         }
1172
1173         /* did we have an endstate? */
1174         jtag_add_ir_scan(tap, fields, endstate);
1175
1176         retval = jtag_execute_queue();
1177
1178 error_return:
1179         for (i = 0; i < num_fields; i++)
1180         {
1181                 if (NULL != fields[i].out_value)
1182                         free((void *)fields[i].out_value);
1183         }
1184
1185         free (fields);
1186
1187         return retval;
1188 }
1189
1190
1191 COMMAND_HANDLER(handle_verify_ircapture_command)
1192 {
1193         if (CMD_ARGC > 1)
1194                 return ERROR_COMMAND_SYNTAX_ERROR;
1195
1196         if (CMD_ARGC == 1)
1197         {
1198                 bool enable;
1199                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], enable);
1200                 jtag_set_verify_capture_ir(enable);
1201         }
1202
1203         const char *status = jtag_will_verify_capture_ir() ? "enabled": "disabled";
1204         command_print(CMD_CTX, "verify Capture-IR is %s", status);
1205
1206         return ERROR_OK;
1207 }
1208
1209 COMMAND_HANDLER(handle_verify_jtag_command)
1210 {
1211         if (CMD_ARGC > 1)
1212                 return ERROR_COMMAND_SYNTAX_ERROR;
1213
1214         if (CMD_ARGC == 1)
1215         {
1216                 bool enable;
1217                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], enable);
1218                 jtag_set_verify(enable);
1219         }
1220
1221         const char *status = jtag_will_verify() ? "enabled": "disabled";
1222         command_print(CMD_CTX, "verify jtag capture is %s", status);
1223
1224         return ERROR_OK;
1225 }
1226
1227 COMMAND_HANDLER(handle_tms_sequence_command)
1228 {
1229         if (CMD_ARGC > 1)
1230                 return ERROR_COMMAND_SYNTAX_ERROR;
1231
1232         if (CMD_ARGC == 1)
1233         {
1234                 bool use_new_table;
1235                 if (strcmp(CMD_ARGV[0], "short") == 0)
1236                         use_new_table = true;
1237                 else if (strcmp(CMD_ARGV[0], "long") == 0)
1238                         use_new_table = false;
1239                 else
1240                         return ERROR_COMMAND_SYNTAX_ERROR;
1241
1242                 tap_use_new_tms_table(use_new_table);
1243         }
1244
1245         command_print(CMD_CTX, "tms sequence is  %s",
1246                         tap_uses_new_tms_table() ? "short": "long");
1247
1248         return ERROR_OK;
1249 }
1250
1251 static const struct command_registration jtag_command_handlers[] = {
1252         {
1253                 .name = "jtag_rclk",
1254                 .handler = handle_jtag_rclk_command,
1255                 .mode = COMMAND_ANY,
1256                 .help = "With an argument, change to to use adaptive clocking "
1257                         "if possible; else to use the fallback speed.  "
1258                         "With or without argument, display current setting.",
1259                 .usage = "[fallback_speed_khz]",
1260         },
1261         {
1262                 .name = "jtag_ntrst_delay",
1263                 .handler = handle_jtag_ntrst_delay_command,
1264                 .mode = COMMAND_ANY,
1265                 .help = "delay after deasserting trst in ms",
1266                 .usage = "[milliseconds]",
1267         },
1268         {
1269                 .name = "jtag_ntrst_assert_width",
1270                 .handler = handle_jtag_ntrst_assert_width_command,
1271                 .mode = COMMAND_ANY,
1272                 .help = "delay after asserting trst in ms",
1273                 .usage = "[milliseconds]",
1274         },
1275         {
1276                 .name = "scan_chain",
1277                 .handler = handle_scan_chain_command,
1278                 .mode = COMMAND_ANY,
1279                 .help = "print current scan chain configuration",
1280         },
1281         {
1282                 .name = "jtag_reset",
1283                 .handler = handle_jtag_reset_command,
1284                 .mode = COMMAND_EXEC,
1285                 .help = "Set reset line values.  Value '1' is active, "
1286                         "value '0' is inactive.",
1287                 .usage = "trst_active srst_active",
1288         },
1289         {
1290                 .name = "runtest",
1291                 .handler = handle_runtest_command,
1292                 .mode = COMMAND_EXEC,
1293                 .help = "Move to Run-Test/Idle, and issue TCK for num_cycles.",
1294                 .usage = "num_cycles"
1295         },
1296         {
1297                 .name = "irscan",
1298                 .handler = handle_irscan_command,
1299                 .mode = COMMAND_EXEC,
1300                 .help = "Execute Instruction Register (DR) scan.  The "
1301                         "specified opcodes are put into each TAP's IR, "
1302                         "and other TAPs are put in BYPASS.",
1303                 .usage = "[tap_name instruction]* ['-endstate' state_name]",
1304         },
1305         {
1306                 .name = "verify_ircapture",
1307                 .handler = handle_verify_ircapture_command,
1308                 .mode = COMMAND_ANY,
1309                 .help = "Display or assign flag controlling whether to "
1310                         "verify values captured during Capture-IR.",
1311                 .usage = "['enable'|'disable']",
1312         },
1313         {
1314                 .name = "verify_jtag",
1315                 .handler = handle_verify_jtag_command,
1316                 .mode = COMMAND_ANY,
1317                 .help = "Display or assign flag controlling whether to "
1318                         "verify values captured during IR and DR scans.",
1319                 .usage = "['enable'|'disable']",
1320         },
1321         {
1322                 .name = "tms_sequence",
1323                 .handler = handle_tms_sequence_command,
1324                 .mode = COMMAND_ANY,
1325                 .help = "Display or change what style TMS sequences to use "
1326                         "for JTAG state transitions:  short (default) or "
1327                         "long.  Only for working around JTAG bugs.",
1328                         /* Specifically for working around DRIVER bugs... */
1329                 .usage = "['short'|'long']",
1330         },
1331         {
1332                 .name = "jtag",
1333                 .mode = COMMAND_ANY,
1334                 .help = "perform jtag tap actions",
1335
1336                 .chain = jtag_subcommand_handlers,
1337         },
1338         {
1339                 .chain = jtag_command_handlers_to_move,
1340         },
1341         COMMAND_REGISTRATION_DONE
1342 };
1343
1344 int jtag_register_commands(struct command_context *cmd_ctx)
1345 {
1346         return register_commands(cmd_ctx, NULL, jtag_command_handlers);
1347 }