jtag: make out_value const
[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 static const Jim_Nvp nvp_jtag_tap_event[] = {
44         { .value = JTAG_TRST_ASSERTED,          .name = "post-reset" },
45         { .value = JTAG_TAP_EVENT_SETUP,        .name = "setup" },
46         { .value = JTAG_TAP_EVENT_ENABLE,       .name = "tap-enable" },
47         { .value = JTAG_TAP_EVENT_DISABLE,      .name = "tap-disable" },
48
49         { .name = NULL, .value = -1 }
50 };
51
52 extern struct jtag_interface *jtag_interface;
53
54 struct jtag_tap *jtag_tap_by_jim_obj(Jim_Interp *interp, Jim_Obj *o)
55 {
56         const char *cp = Jim_GetString(o, NULL);
57         struct jtag_tap *t = cp ? jtag_tap_by_string(cp) : NULL;
58         if (NULL == cp)
59                 cp = "(unknown)";
60         if (NULL == t)
61                 Jim_SetResult_sprintf(interp, "Tap '%s' could not be found", cp);
62         return t;
63 }
64
65 static bool scan_is_safe(tap_state_t state)
66 {
67         switch (state)
68         {
69         case TAP_RESET:
70         case TAP_IDLE:
71         case TAP_DRPAUSE:
72         case TAP_IRPAUSE:
73                 return true;
74         default:
75                 return false;
76         }
77 }
78
79 static int Jim_Command_drscan(Jim_Interp *interp, int argc, Jim_Obj *const *args)
80 {
81         int retval;
82         struct scan_field *fields;
83         int num_fields;
84         int field_count = 0;
85         int i, e;
86         struct jtag_tap *tap;
87         tap_state_t endstate;
88
89         /* args[1] = device
90          * args[2] = num_bits
91          * args[3] = hex string
92          * ... repeat num bits and hex string ...
93          *
94          * .. optionally:
95         *     args[N-2] = "-endstate"
96          *     args[N-1] = statename
97          */
98         if ((argc < 4) || ((argc % 2) != 0))
99         {
100                 Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
101                 return JIM_ERR;
102         }
103
104         endstate = TAP_IDLE;
105
106         script_debug(interp, "drscan", argc, args);
107
108         /* validate arguments as numbers */
109         e = JIM_OK;
110         for (i = 2; i < argc; i += 2)
111         {
112                 long bits;
113                 const char *cp;
114
115                 e = Jim_GetLong(interp, args[i], &bits);
116                 /* If valid - try next arg */
117                 if (e == JIM_OK) {
118                         continue;
119                 }
120
121                 /* Not valid.. are we at the end? */
122                 if (((i + 2) != argc)) {
123                         /* nope, then error */
124                         return e;
125                 }
126
127                 /* it could be: "-endstate FOO"
128                  * e.g. DRPAUSE so we can issue more instructions
129                  * before entering RUN/IDLE and executing them.
130                  */
131
132                 /* get arg as a string. */
133                 cp = Jim_GetString(args[i], NULL);
134                 /* is it the magic? */
135                 if (0 == strcmp("-endstate", cp)) {
136                         /* is the statename valid? */
137                         cp = Jim_GetString(args[i + 1], NULL);
138
139                         /* see if it is a valid state name */
140                         endstate = tap_state_by_name(cp);
141                         if (endstate < 0) {
142                                 /* update the error message */
143                                 Jim_SetResult_sprintf(interp,"endstate: %s invalid", cp);
144                         } else {
145                                 if (!scan_is_safe(endstate))
146                                         LOG_WARNING("drscan with unsafe "
147                                                         "endstate \"%s\"", cp);
148
149                                 /* valid - so clear the error */
150                                 e = JIM_OK;
151                                 /* and remove the last 2 args */
152                                 argc -= 2;
153                         }
154                 }
155
156                 /* Still an error? */
157                 if (e != JIM_OK) {
158                         return e; /* too bad */
159                 }
160         } /* validate args */
161
162         tap = jtag_tap_by_jim_obj(interp, args[1]);
163         if (tap == NULL) {
164                 return JIM_ERR;
165         }
166
167         num_fields = (argc-2)/2;
168         fields = malloc(sizeof(struct scan_field) * num_fields);
169         for (i = 2; i < argc; i += 2)
170         {
171                 long bits;
172                 int len;
173                 const char *str;
174
175                 Jim_GetLong(interp, args[i], &bits);
176                 str = Jim_GetString(args[i + 1], &len);
177
178                 fields[field_count].num_bits = bits;
179                 void * t = malloc(DIV_ROUND_UP(bits, 8));
180                 fields[field_count].out_value = t;
181                 str_to_buf(str, len, t, bits, 0);
182                 fields[field_count].in_value = t;
183                 field_count++;
184         }
185
186         jtag_add_dr_scan(tap, num_fields, fields, endstate);
187
188         retval = jtag_execute_queue();
189         if (retval != ERROR_OK)
190         {
191                 Jim_SetResultString(interp, "drscan: jtag execute failed",-1);
192                 return JIM_ERR;
193         }
194
195         field_count = 0;
196         Jim_Obj *list = Jim_NewListObj(interp, NULL, 0);
197         for (i = 2; i < argc; i += 2)
198         {
199                 long bits;
200                 char *str;
201
202                 Jim_GetLong(interp, args[i], &bits);
203                 str = buf_to_str(fields[field_count].in_value, bits, 16);
204                 free((void *)fields[field_count].out_value);
205
206                 Jim_ListAppendElement(interp, list, Jim_NewStringObj(interp, str, strlen(str)));
207                 free(str);
208                 field_count++;
209         }
210
211         Jim_SetResult(interp, list);
212
213         free(fields);
214
215         return JIM_OK;
216 }
217
218
219 static int Jim_Command_pathmove(Jim_Interp *interp, int argc, Jim_Obj *const *args)
220 {
221         tap_state_t states[8];
222
223         if ((argc < 2) || ((size_t)argc > (ARRAY_SIZE(states) + 1)))
224         {
225                 Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
226                 return JIM_ERR;
227         }
228
229         script_debug(interp, "pathmove", argc, args);
230
231         int i;
232         for (i = 0; i < argc-1; i++)
233         {
234                 const char *cp;
235                 cp = Jim_GetString(args[i + 1], NULL);
236                 states[i] = tap_state_by_name(cp);
237                 if (states[i] < 0)
238                 {
239                         /* update the error message */
240                         Jim_SetResult_sprintf(interp,"endstate: %s invalid", cp);
241                         return JIM_ERR;
242                 }
243         }
244
245         if ((jtag_add_statemove(states[0]) != ERROR_OK) || (jtag_execute_queue()!= ERROR_OK))
246         {
247                 Jim_SetResultString(interp, "pathmove: jtag execute failed",-1);
248                 return JIM_ERR;
249         }
250
251         jtag_add_pathmove(argc-2, states + 1);
252
253         if (jtag_execute_queue()!= ERROR_OK)
254         {
255                 Jim_SetResultString(interp, "pathmove: failed",-1);
256                 return JIM_ERR;
257         }
258
259         return JIM_OK;
260 }
261
262
263 static int Jim_Command_flush_count(Jim_Interp *interp, int argc, Jim_Obj *const *args)
264 {
265         script_debug(interp, "flush_count", argc, args);
266
267         Jim_SetResult(interp, Jim_NewIntObj(interp, jtag_get_flush_queue_count()));
268
269         return JIM_OK;
270 }
271
272 /* REVISIT Just what about these should "move" ... ?
273  * These registrations, into the main JTAG table?
274  *
275  * There's a minor compatibility issue, these all show up twice;
276  * that's not desirable:
277  *  - jtag drscan ... NOT DOCUMENTED!
278  *  - drscan ...
279  *
280  * The "irscan" command (for example) doesn't show twice.
281  */
282 static const struct command_registration jtag_command_handlers_to_move[] = {
283         {
284                 .name = "drscan",
285                 .mode = COMMAND_EXEC,
286                 .jim_handler = Jim_Command_drscan,
287                 .help = "Execute Data Register (DR) scan for one TAP.  "
288                         "Other TAPs must be in BYPASS mode.",
289                 .usage = "tap_name [num_bits value]* ['-endstate' state_name]",
290         },
291         {
292                 .name = "flush_count",
293                 .mode = COMMAND_EXEC,
294                 .jim_handler = Jim_Command_flush_count,
295                 .help = "Returns the number of times the JTAG queue "
296                         "has been flushed.",
297         },
298         {
299                 .name = "pathmove",
300                 .mode = COMMAND_EXEC,
301                 .jim_handler = Jim_Command_pathmove,
302                 .usage = "start_state state1 [state2 [state3 ...]]",
303                 .help = "Move JTAG state machine from current state "
304                         "(start_state) to state1, then state2, state3, etc.",
305         },
306         COMMAND_REGISTRATION_DONE
307 };
308
309
310 enum jtag_tap_cfg_param {
311         JCFG_EVENT
312 };
313
314 static Jim_Nvp nvp_config_opts[] = {
315         { .name = "-event",      .value = JCFG_EVENT },
316
317         { .name = NULL,          .value = -1 }
318 };
319
320 static int jtag_tap_configure_event(Jim_GetOptInfo *goi, struct jtag_tap * tap)
321 {
322         if (goi->argc == 0)
323         {
324                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name> ...");
325                 return JIM_ERR;
326         }
327
328         Jim_Nvp *n;
329         int e = Jim_GetOpt_Nvp(goi, nvp_jtag_tap_event, &n);
330         if (e != JIM_OK)
331         {
332                 Jim_GetOpt_NvpUnknown(goi, nvp_jtag_tap_event, 1);
333                 return e;
334         }
335
336         if (goi->isconfigure) {
337                 if (goi->argc != 1) {
338                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name> <event-body>");
339                         return JIM_ERR;
340                 }
341         } else {
342                 if (goi->argc != 0) {
343                         Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event <event-name>");
344                         return JIM_ERR;
345                 }
346         }
347
348         struct jtag_tap_event_action *jteap  = tap->event_action;
349         /* replace existing event body */
350         bool found = false;
351         while (jteap)
352         {
353                 if (jteap->event == (enum jtag_event)n->value)
354                 {
355                         found = true;
356                         break;
357                 }
358                 jteap = jteap->next;
359         }
360
361         Jim_SetEmptyResult(goi->interp);
362
363         if (goi->isconfigure)
364         {
365                 if (!found)
366                         jteap = calloc(1, sizeof(*jteap));
367                 else if (NULL != jteap->body)
368                         Jim_DecrRefCount(goi->interp, jteap->body);
369
370                 jteap->interp = goi->interp;
371                 jteap->event = n->value;
372
373                 Jim_Obj *o;
374                 Jim_GetOpt_Obj(goi, &o);
375                 jteap->body = Jim_DuplicateObj(goi->interp, o);
376                 Jim_IncrRefCount(jteap->body);
377
378                 if (!found)
379                 {
380                         /* add to head of event list */
381                         jteap->next = tap->event_action;
382                         tap->event_action = jteap;
383                 }
384         }
385         else if (found)
386         {
387                 jteap->interp = goi->interp;
388                 Jim_SetResult(goi->interp,
389                         Jim_DuplicateObj(goi->interp, jteap->body));
390         }
391         return JIM_OK;
392 }
393
394 static int jtag_tap_configure_cmd(Jim_GetOptInfo *goi, struct jtag_tap * tap)
395 {
396         /* parse config or cget options */
397         while (goi->argc > 0)
398         {
399                 Jim_SetEmptyResult (goi->interp);
400
401                 Jim_Nvp *n;
402                 int e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
403                 if (e != JIM_OK)
404                 {
405                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
406                         return e;
407                 }
408
409                 switch (n->value)
410                 {
411                 case JCFG_EVENT:
412                         e = jtag_tap_configure_event(goi, tap);
413                         if (e != JIM_OK)
414                                 return e;
415                         break;
416                 default:
417                         Jim_SetResult_sprintf(goi->interp, "unknown event: %s", n->name);
418                         return JIM_ERR;
419                 }
420         }
421
422         return JIM_OK;
423 }
424
425 static int is_bad_irval(int ir_length, jim_wide w)
426 {
427         jim_wide v = 1;
428
429         v <<= ir_length;
430         v -= 1;
431         v = ~v;
432         return (w & v) != 0;
433 }
434
435 static int jim_newtap_expected_id(Jim_Nvp *n, Jim_GetOptInfo *goi,
436                 struct jtag_tap *pTap)
437 {
438         jim_wide w;
439         int e = Jim_GetOpt_Wide(goi, &w);
440         if (e != JIM_OK) {
441                 Jim_SetResult_sprintf(goi->interp, "option: %s bad parameter", n->name);
442                 return e;
443         }
444
445         unsigned expected_len = sizeof(uint32_t) * pTap->expected_ids_cnt;
446         uint32_t *new_expected_ids = malloc(expected_len + sizeof(uint32_t));
447         if (new_expected_ids == NULL)
448         {
449                 Jim_SetResult_sprintf(goi->interp, "no memory");
450                 return JIM_ERR;
451         }
452
453         memcpy(new_expected_ids, pTap->expected_ids, expected_len);
454
455         new_expected_ids[pTap->expected_ids_cnt] = w;
456
457         free(pTap->expected_ids);
458         pTap->expected_ids = new_expected_ids;
459         pTap->expected_ids_cnt++;
460
461         return JIM_OK;
462 }
463
464 #define NTAP_OPT_IRLEN     0
465 #define NTAP_OPT_IRMASK    1
466 #define NTAP_OPT_IRCAPTURE 2
467 #define NTAP_OPT_ENABLED   3
468 #define NTAP_OPT_DISABLED  4
469 #define NTAP_OPT_EXPECTED_ID 5
470 #define NTAP_OPT_VERSION   6
471
472 static int jim_newtap_ir_param(Jim_Nvp *n, Jim_GetOptInfo *goi,
473                 struct jtag_tap *pTap)
474 {
475         jim_wide w;
476         int e = Jim_GetOpt_Wide(goi, &w);
477         if (e != JIM_OK)
478         {
479                 Jim_SetResult_sprintf(goi->interp,
480                                 "option: %s bad parameter", n->name);
481                 free((void *)pTap->dotted_name);
482                 return e;
483         }
484         switch (n->value) {
485         case NTAP_OPT_IRLEN:
486                 if (w > (jim_wide) (8 * sizeof(pTap->ir_capture_value)))
487                 {
488                         LOG_WARNING("%s: huge IR length %d",
489                                         pTap->dotted_name, (int) w);
490                 }
491                 pTap->ir_length = w;
492                 break;
493         case NTAP_OPT_IRMASK:
494                 if (is_bad_irval(pTap->ir_length, w))
495                 {
496                         LOG_ERROR("%s: IR mask %x too big",
497                                         pTap->dotted_name,
498                                         (int) w);
499                         return JIM_ERR;
500                 }
501                 if ((w & 3) != 3)
502                         LOG_WARNING("%s: nonstandard IR mask", pTap->dotted_name);
503                 pTap->ir_capture_mask = w;
504                 break;
505         case NTAP_OPT_IRCAPTURE:
506                 if (is_bad_irval(pTap->ir_length, w))
507                 {
508                         LOG_ERROR("%s: IR capture %x too big",
509                                         pTap->dotted_name, (int) w);
510                         return JIM_ERR;
511                 }
512                 if ((w & 3) != 1)
513                         LOG_WARNING("%s: nonstandard IR value",
514                                         pTap->dotted_name);
515                 pTap->ir_capture_value = w;
516                 break;
517         default:
518                 return JIM_ERR;
519         }
520         return JIM_OK;
521 }
522
523 static int jim_newtap_cmd(Jim_GetOptInfo *goi)
524 {
525         struct jtag_tap *pTap;
526         int x;
527         int e;
528         Jim_Nvp *n;
529         char *cp;
530         const Jim_Nvp opts[] = {
531                 { .name = "-irlen"                      ,       .value = NTAP_OPT_IRLEN },
532                 { .name = "-irmask"                     ,       .value = NTAP_OPT_IRMASK },
533                 { .name = "-ircapture"          ,       .value = NTAP_OPT_IRCAPTURE },
534                 { .name = "-enable"                     ,       .value = NTAP_OPT_ENABLED },
535                 { .name = "-disable"            ,       .value = NTAP_OPT_DISABLED },
536                 { .name = "-expected-id"        ,       .value = NTAP_OPT_EXPECTED_ID },
537                 { .name = "-ignore-version"     ,       .value = NTAP_OPT_VERSION },
538                 { .name = NULL                          ,       .value = -1 },
539         };
540
541         pTap = calloc(1, sizeof(struct jtag_tap));
542         if (!pTap) {
543                 Jim_SetResult_sprintf(goi->interp, "no memory");
544                 return JIM_ERR;
545         }
546
547         /*
548          * we expect CHIP + TAP + OPTIONS
549          * */
550         if (goi->argc < 3) {
551                 Jim_SetResult_sprintf(goi->interp, "Missing CHIP TAP OPTIONS ....");
552                 free(pTap);
553                 return JIM_ERR;
554         }
555         Jim_GetOpt_String(goi, &cp, NULL);
556         pTap->chip = strdup(cp);
557
558         Jim_GetOpt_String(goi, &cp, NULL);
559         pTap->tapname = strdup(cp);
560
561         /* name + dot + name + null */
562         x = strlen(pTap->chip) + 1 + strlen(pTap->tapname) + 1;
563         cp = malloc(x);
564         sprintf(cp, "%s.%s", pTap->chip, pTap->tapname);
565         pTap->dotted_name = cp;
566
567         LOG_DEBUG("Creating New Tap, Chip: %s, Tap: %s, Dotted: %s, %d params",
568                           pTap->chip, pTap->tapname, pTap->dotted_name, goi->argc);
569
570         /* IEEE specifies that the two LSBs of an IR scan are 01, so make
571          * that the default.  The "-irlen" and "-irmask" options are only
572          * needed to cope with nonstandard TAPs, or to specify more bits.
573          */
574         pTap->ir_capture_mask = 0x03;
575         pTap->ir_capture_value = 0x01;
576
577         while (goi->argc) {
578                 e = Jim_GetOpt_Nvp(goi, opts, &n);
579                 if (e != JIM_OK) {
580                         Jim_GetOpt_NvpUnknown(goi, opts, 0);
581                         free((void *)pTap->dotted_name);
582                         free(pTap);
583                         return e;
584                 }
585                 LOG_DEBUG("Processing option: %s", n->name);
586                 switch (n->value) {
587                 case NTAP_OPT_ENABLED:
588                         pTap->disabled_after_reset = false;
589                         break;
590                 case NTAP_OPT_DISABLED:
591                         pTap->disabled_after_reset = true;
592                         break;
593                 case NTAP_OPT_EXPECTED_ID:
594                         e = jim_newtap_expected_id(n, goi, pTap);
595                         if (JIM_OK != e)
596                         {
597                                 free((void *)pTap->dotted_name);
598                                 free(pTap);
599                                 return e;
600                         }
601                         break;
602                 case NTAP_OPT_IRLEN:
603                 case NTAP_OPT_IRMASK:
604                 case NTAP_OPT_IRCAPTURE:
605                         e = jim_newtap_ir_param(n, goi, pTap);
606                         if (JIM_OK != e)
607                         {
608                                 free((void *)pTap->dotted_name);
609                                 free(pTap);
610                                 return e;
611                         }
612                         break;
613                 case NTAP_OPT_VERSION:
614                         pTap->ignore_version = true;
615                         break;
616                 } /* switch (n->value) */
617         } /* while (goi->argc) */
618
619         /* default is enabled-after-reset */
620         pTap->enabled = !pTap->disabled_after_reset;
621
622         /* Did all the required option bits get cleared? */
623         if (pTap->ir_length != 0)
624         {
625                 jtag_tap_init(pTap);
626                 return JIM_OK;
627         }
628
629         Jim_SetResult_sprintf(goi->interp,
630                         "newtap: %s missing IR length",
631                         pTap->dotted_name);
632         jtag_tap_free(pTap);
633         return JIM_ERR;
634 }
635
636 static void jtag_tap_handle_event(struct jtag_tap *tap, enum jtag_event e)
637 {
638         struct jtag_tap_event_action * jteap;
639
640         for (jteap = tap->event_action; jteap != NULL; jteap = jteap->next)
641         {
642                 if (jteap->event != e)
643                         continue;
644
645                 Jim_Nvp *nvp = Jim_Nvp_value2name_simple(nvp_jtag_tap_event, e);
646                 LOG_DEBUG("JTAG tap: %s event: %d (%s)\n\taction: %s",
647                                 tap->dotted_name, e, nvp->name,
648                                 Jim_GetString(jteap->body, NULL));
649
650                 if (Jim_EvalObj(jteap->interp, jteap->body) != JIM_OK)
651                 {
652                         Jim_PrintErrorMessage(jteap->interp);
653                         continue;
654                 }
655
656                 switch (e)
657                 {
658                 case JTAG_TAP_EVENT_ENABLE:
659                 case JTAG_TAP_EVENT_DISABLE:
660                         /* NOTE:  we currently assume the handlers
661                          * can't fail.  Right here is where we should
662                          * really be verifying the scan chains ...
663                          */
664                         tap->enabled = (e == JTAG_TAP_EVENT_ENABLE);
665                         LOG_INFO("JTAG tap: %s %s", tap->dotted_name,
666                                 tap->enabled ? "enabled" : "disabled");
667                         break;
668                 default:
669                         break;
670                 }
671         }
672 }
673
674 static int
675 jim_jtag_interface(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
676 {
677         Jim_GetOptInfo goi;
678         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
679
680         /* return the name of the interface */
681         /* TCL code might need to know the exact type... */
682         /* FUTURE: we allow this as a means to "set" the interface. */
683         if (goi.argc != 0) {
684                 Jim_WrongNumArgs(goi.interp, 1, goi.argv-1, "(no params)");
685                 return JIM_ERR;
686         }
687         const char *name = jtag_interface ? jtag_interface->name : NULL;
688         Jim_SetResultString(goi.interp, name ? : "undefined", -1);
689         return JIM_OK;
690 }
691
692 static int jim_jtag_arp_init(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
693 {
694         Jim_GetOptInfo goi;
695         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
696         if (goi.argc != 0) {
697                 Jim_WrongNumArgs(goi.interp, 1, goi.argv-1, "(no params)");
698                 return JIM_ERR;
699         }
700         struct command_context *context = Jim_GetAssocData(interp, "context");
701         int e = jtag_init_inner(context);
702         if (e != ERROR_OK) {
703                 Jim_SetResult_sprintf(goi.interp, "error: %d", e);
704                 return JIM_ERR;
705         }
706         return JIM_OK;
707 }
708
709 static int jim_jtag_arp_init_reset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
710 {
711         Jim_GetOptInfo goi;
712         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
713         if (goi.argc != 0) {
714                 Jim_WrongNumArgs(goi.interp, 1, goi.argv-1, "(no params)");
715                 return JIM_ERR;
716         }
717         struct command_context *context = Jim_GetAssocData(interp, "context");
718         int e = jtag_init_reset(context);
719         if (e != ERROR_OK) {
720                 Jim_SetResult_sprintf(goi.interp, "error: %d", e);
721                 return JIM_ERR;
722         }
723         return JIM_OK;
724 }
725
726 static int jim_jtag_newtap(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
727 {
728         Jim_GetOptInfo goi;
729         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
730         return jim_newtap_cmd(&goi);
731 }
732
733 static bool jtag_tap_enable(struct jtag_tap *t)
734 {
735         if (t->enabled)
736                 return false;
737         jtag_tap_handle_event(t, JTAG_TAP_EVENT_ENABLE);
738         if (!t->enabled)
739                 return false;
740
741         /* FIXME add JTAG sanity checks, w/o TLR
742          *  - scan chain length grew by one (this)
743          *  - IDs and IR lengths are as expected
744          */
745         jtag_call_event_callbacks(JTAG_TAP_EVENT_ENABLE);
746         return true;
747 }
748 static bool jtag_tap_disable(struct jtag_tap *t)
749 {
750         if (!t->enabled)
751                 return false;
752         jtag_tap_handle_event(t, JTAG_TAP_EVENT_DISABLE);
753         if (t->enabled)
754                 return false;
755
756         /* FIXME add JTAG sanity checks, w/o TLR
757          *  - scan chain length shrank by one (this)
758          *  - IDs and IR lengths are as expected
759          */
760         jtag_call_event_callbacks(JTAG_TAP_EVENT_DISABLE);
761         return true;
762 }
763
764 static int jim_jtag_tap_enabler(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
765 {
766         const char *cmd_name = Jim_GetString(argv[0], NULL);
767         Jim_GetOptInfo goi;
768         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
769         if (goi.argc != 1) {
770                 Jim_SetResult_sprintf(goi.interp, "usage: %s <name>", cmd_name);
771                 return JIM_ERR;
772         }
773
774         struct jtag_tap *t;
775
776         t = jtag_tap_by_jim_obj(goi.interp, goi.argv[0]);
777         if (t == NULL)
778                 return JIM_ERR;
779
780         if (strcasecmp(cmd_name, "tapisenabled") == 0) {
781                 // do nothing, just return the value
782         } else if (strcasecmp(cmd_name, "tapenable") == 0) {
783                 if (!jtag_tap_enable(t))
784                         LOG_WARNING("failed to disable tap");
785         } else if (strcasecmp(cmd_name, "tapdisable") == 0) {
786                 if (!jtag_tap_disable(t))
787                         LOG_WARNING("failed to disable tap");
788         } else {
789                 LOG_ERROR("command '%s' unknown", cmd_name);
790                 return JIM_ERR;
791         }
792         bool e = t->enabled;
793         Jim_SetResult(goi.interp, Jim_NewIntObj(goi.interp, e));
794         return JIM_OK;
795 }
796
797 static int jim_jtag_configure(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
798 {
799         const char *cmd_name = Jim_GetString(argv[0], NULL);
800         Jim_GetOptInfo goi;
801         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
802         goi.isconfigure = !strcmp(cmd_name, "configure");
803         if (goi.argc < 2 + goi.isconfigure) {
804                 Jim_WrongNumArgs(goi.interp, 0, NULL,
805                                 "<tap_name> <attribute> ...");
806                 return JIM_ERR;
807         }
808
809         struct jtag_tap *t;
810
811         Jim_Obj *o;
812         Jim_GetOpt_Obj(&goi, &o);
813         t = jtag_tap_by_jim_obj(goi.interp, o);
814         if (t == NULL) {
815                 return JIM_ERR;
816         }
817
818         return jtag_tap_configure_cmd(&goi, t);
819 }
820
821 static int jim_jtag_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
822 {
823         Jim_GetOptInfo goi;
824         Jim_GetOpt_Setup(&goi, interp, argc-1, argv + 1);
825         if (goi.argc != 0) {
826                 Jim_WrongNumArgs(goi.interp, 1, goi.argv, "Too many parameters");
827                 return JIM_ERR;
828         }
829         Jim_SetResult(goi.interp, Jim_NewListObj(goi.interp, NULL, 0));
830         struct jtag_tap *tap;
831
832         for (tap = jtag_all_taps(); tap; tap = tap->next_tap) {
833                 Jim_ListAppendElement(goi.interp,
834                         Jim_GetResult(goi.interp),
835                         Jim_NewStringObj(goi.interp,
836                                 tap->dotted_name, -1));
837         }
838         return JIM_OK;
839 }
840
841 COMMAND_HANDLER(handle_jtag_init_command)
842 {
843         if (CMD_ARGC != 0)
844                 return ERROR_COMMAND_SYNTAX_ERROR;
845
846         static bool jtag_initialized = false;
847         if (jtag_initialized)
848         {
849                 LOG_INFO("'jtag init' has already been called");
850                 return ERROR_OK;
851         }
852         jtag_initialized = true;
853
854         LOG_DEBUG("Initializing jtag devices...");
855         return jtag_init(CMD_CTX);
856 }
857
858 static const struct command_registration jtag_subcommand_handlers[] = {
859         {
860                 .name = "init",
861                 .mode = COMMAND_ANY,
862                 .handler = handle_jtag_init_command,
863                 .help = "initialize jtag scan chain",
864         },
865         {
866                 .name = "interface",
867                 .mode = COMMAND_ANY,
868                 .jim_handler = jim_jtag_interface,
869                 .help = "Returns the name of the currently selected interface.",
870         },
871         {
872                 .name = "arp_init",
873                 .mode = COMMAND_ANY,
874                 .jim_handler = jim_jtag_arp_init,
875                 .help = "Validates JTAG scan chain against the list of "
876                         "declared TAPs using just the four standard JTAG "
877                         "signals.",
878         },
879         {
880                 .name = "arp_init-reset",
881                 .mode = COMMAND_ANY,
882                 .jim_handler = jim_jtag_arp_init_reset,
883                 .help = "Uses TRST and SRST to try resetting everything on "
884                         "the JTAG scan chain, then performs 'jtag arp_init'."
885         },
886         {
887                 .name = "newtap",
888                 .mode = COMMAND_CONFIG,
889                 .jim_handler = jim_jtag_newtap,
890                 .help = "Create a new TAP instance named basename.tap_type, "
891                         "and appends it to the scan chain.",
892                 .usage = "basename tap_type '-irlen' count "
893                         "['-enable'|'-disable'] "
894                         "['-expected_id' number] "
895                         "['-ignore-version'] "
896                         "['-ircapture' number] "
897                         "['-mask' number] ",
898         },
899         {
900                 .name = "tapisenabled",
901                 .mode = COMMAND_EXEC,
902                 .jim_handler = jim_jtag_tap_enabler,
903                 .help = "Returns a Tcl boolean (0/1) indicating whether "
904                         "the TAP is enabled (1) or not (0).",
905                 .usage = "tap_name",
906         },
907         {
908                 .name = "tapenable",
909                 .mode = COMMAND_EXEC,
910                 .jim_handler = jim_jtag_tap_enabler,
911                 .help = "Try to enable the specified TAP using the "
912                         "'tap-enable' TAP event.",
913                 .usage = "tap_name",
914         },
915         {
916                 .name = "tapdisable",
917                 .mode = COMMAND_EXEC,
918                 .jim_handler = jim_jtag_tap_enabler,
919                 .help = "Try to disable the specified TAP using the "
920                         "'tap-disable' TAP event.",
921                 .usage = "tap_name",
922         },
923         {
924                 .name = "configure",
925                 .mode = COMMAND_EXEC,
926                 .jim_handler = jim_jtag_configure,
927                 .help = "Provide a Tcl handler for the specified "
928                         "TAP event.",
929                 .usage = "tap_name '-event' event_name handler",
930         },
931         {
932                 .name = "cget",
933                 .mode = COMMAND_EXEC,
934                 .jim_handler = jim_jtag_configure,
935                 .help = "Return any Tcl handler for the specified "
936                         "TAP event.",
937                 .usage = "tap_name '-event' event_name",
938         },
939         {
940                 .name = "names",
941                 .mode = COMMAND_ANY,
942                 .jim_handler = jim_jtag_names,
943                 .help = "Returns list of all JTAG tap names.",
944         },
945         {
946                 .chain = jtag_command_handlers_to_move,
947         },
948         COMMAND_REGISTRATION_DONE
949 };
950
951 void jtag_notify_event(enum jtag_event event)
952 {
953         struct jtag_tap *tap;
954
955         for (tap = jtag_all_taps(); tap; tap = tap->next_tap)
956                 jtag_tap_handle_event(tap, event);
957 }
958
959
960 static int default_khz(int khz, int *jtag_speed)
961 {
962         LOG_ERROR("Translation from khz to jtag_speed not implemented");
963         return ERROR_FAIL;
964 }
965
966 static int default_speed_div(int speed, int *khz)
967 {
968         LOG_ERROR("Translation from jtag_speed to khz not implemented");
969         return ERROR_FAIL;
970 }
971
972 static int default_power_dropout(int *dropout)
973 {
974         *dropout = 0; /* by default we can't detect power dropout */
975         return ERROR_OK;
976 }
977
978 static int default_srst_asserted(int *srst_asserted)
979 {
980         *srst_asserted = 0; /* by default we can't detect srst asserted */
981         return ERROR_OK;
982 }
983
984 COMMAND_HANDLER(handle_interface_list_command)
985 {
986         if (strcmp(CMD_NAME, "interface_list") == 0 && CMD_ARGC > 0)
987                 return ERROR_COMMAND_SYNTAX_ERROR;
988
989         command_print(CMD_CTX, "The following debug interfaces are available:");
990         for (unsigned i = 0; NULL != jtag_interfaces[i]; i++)
991         {
992                 const char *name = jtag_interfaces[i]->name;
993                 command_print(CMD_CTX, "%u: %s", i + 1, name);
994         }
995
996         return ERROR_OK;
997 }
998
999 COMMAND_HANDLER(handle_interface_command)
1000 {
1001         /* check whether the interface is already configured */
1002         if (jtag_interface)
1003         {
1004                 LOG_WARNING("Interface already configured, ignoring");
1005                 return ERROR_OK;
1006         }
1007
1008         /* interface name is a mandatory argument */
1009         if (CMD_ARGC != 1 || CMD_ARGV[0][0] == '\0')
1010                 return ERROR_COMMAND_SYNTAX_ERROR;
1011
1012         for (unsigned i = 0; NULL != jtag_interfaces[i]; i++)
1013         {
1014                 if (strcmp(CMD_ARGV[0], jtag_interfaces[i]->name) != 0)
1015                         continue;
1016
1017                 if (NULL != jtag_interfaces[i]->commands)
1018                 {
1019                         int retval = register_commands(CMD_CTX, NULL,
1020                                         jtag_interfaces[i]->commands);
1021                         if (ERROR_OK != retval)
1022                                 return retval;
1023                 }
1024
1025                 jtag_interface = jtag_interfaces[i];
1026
1027                 if (jtag_interface->khz == NULL)
1028                         jtag_interface->khz = default_khz;
1029                 if (jtag_interface->speed_div == NULL)
1030                         jtag_interface->speed_div = default_speed_div;
1031                 if (jtag_interface->power_dropout == NULL)
1032                         jtag_interface->power_dropout = default_power_dropout;
1033                 if (jtag_interface->srst_asserted == NULL)
1034                         jtag_interface->srst_asserted = default_srst_asserted;
1035
1036                 return ERROR_OK;
1037         }
1038
1039         /* no valid interface was found (i.e. the configuration option,
1040          * didn't match one of the compiled-in interfaces
1041          */
1042         LOG_ERROR("The specified debug interface was not found (%s)", CMD_ARGV[0]);
1043         CALL_COMMAND_HANDLER(handle_interface_list_command);
1044         return ERROR_JTAG_INVALID_INTERFACE;
1045 }
1046
1047 COMMAND_HANDLER(handle_scan_chain_command)
1048 {
1049         struct jtag_tap *tap;
1050         char expected_id[12];
1051
1052         tap = jtag_all_taps();
1053         command_print(CMD_CTX,
1054 "   TapName             Enabled  IdCode     Expected   IrLen IrCap IrMask");
1055         command_print(CMD_CTX,
1056 "-- ------------------- -------- ---------- ---------- ----- ----- ------");
1057
1058         while (tap) {
1059                 uint32_t expected, expected_mask, ii;
1060
1061                 snprintf(expected_id, sizeof expected_id, "0x%08x",
1062                                 (unsigned)((tap->expected_ids_cnt > 0)
1063                                         ? tap->expected_ids[0]
1064                                         : 0));
1065                 if (tap->ignore_version)
1066                         expected_id[2] = '*';
1067
1068                 expected = buf_get_u32(tap->expected, 0, tap->ir_length);
1069                 expected_mask = buf_get_u32(tap->expected_mask, 0, tap->ir_length);
1070
1071                 command_print(CMD_CTX,
1072         "%2d %-18s     %c     0x%08x %s %5d 0x%02x  0x%02x",
1073                                           tap->abs_chain_position,
1074                                           tap->dotted_name,
1075                                           tap->enabled ? 'Y' : 'n',
1076                                           (unsigned int)(tap->idcode),
1077                                           expected_id,
1078                                           (unsigned int)(tap->ir_length),
1079                                           (unsigned int)(expected),
1080                                           (unsigned int)(expected_mask));
1081
1082                 for (ii = 1; ii < tap->expected_ids_cnt; ii++) {
1083                         snprintf(expected_id, sizeof expected_id, "0x%08x",
1084                                         (unsigned) tap->expected_ids[1]);
1085                         if (tap->ignore_version)
1086                                 expected_id[2] = '*';
1087
1088                         command_print(CMD_CTX,
1089         "                                           %s",
1090                                                   expected_id);
1091                 }
1092
1093                 tap = tap->next_tap;
1094         }
1095
1096         return ERROR_OK;
1097 }
1098
1099 COMMAND_HANDLER(handle_reset_config_command)
1100 {
1101         int new_cfg = 0;
1102         int mask = 0;
1103
1104         /* Original versions cared about the order of these tokens:
1105          *   reset_config signals [combination [trst_type [srst_type]]]
1106          * They also clobbered the previous configuration even on error.
1107          *
1108          * Here we don't care about the order, and only change values
1109          * which have been explicitly specified.
1110          */
1111         for (; CMD_ARGC; CMD_ARGC--, CMD_ARGV++) {
1112                 int tmp = 0;
1113                 int m;
1114
1115                 /* gating */
1116                 m = RESET_SRST_NO_GATING;
1117                 if (strcmp(*CMD_ARGV, "srst_gates_jtag") == 0)
1118                         /* default: don't use JTAG while SRST asserted */;
1119                 else if (strcmp(*CMD_ARGV, "srst_nogate") == 0)
1120                         tmp = RESET_SRST_NO_GATING;
1121                 else
1122                         m = 0;
1123                 if (mask & m) {
1124                         LOG_ERROR("extra reset_config %s spec (%s)",
1125                                         "gating", *CMD_ARGV);
1126                         return ERROR_INVALID_ARGUMENTS;
1127                 }
1128                 if (m)
1129                         goto next;
1130
1131                 /* signals */
1132                 m = RESET_HAS_TRST | RESET_HAS_SRST;
1133                 if (strcmp(*CMD_ARGV, "none") == 0)
1134                         tmp = RESET_NONE;
1135                 else if (strcmp(*CMD_ARGV, "trst_only") == 0)
1136                         tmp = RESET_HAS_TRST;
1137                 else if (strcmp(*CMD_ARGV, "srst_only") == 0)
1138                         tmp = RESET_HAS_SRST;
1139                 else if (strcmp(*CMD_ARGV, "trst_and_srst") == 0)
1140                         tmp = RESET_HAS_TRST | RESET_HAS_SRST;
1141                 else
1142                         m = 0;
1143                 if (mask & m) {
1144                         LOG_ERROR("extra reset_config %s spec (%s)",
1145                                         "signal", *CMD_ARGV);
1146                         return ERROR_INVALID_ARGUMENTS;
1147                 }
1148                 if (m)
1149                         goto next;
1150
1151                 /* combination (options for broken wiring) */
1152                 m = RESET_SRST_PULLS_TRST | RESET_TRST_PULLS_SRST;
1153                 if (strcmp(*CMD_ARGV, "separate") == 0)
1154                         /* separate reset lines - default */;
1155                 else if (strcmp(*CMD_ARGV, "srst_pulls_trst") == 0)
1156                         tmp |= RESET_SRST_PULLS_TRST;
1157                 else if (strcmp(*CMD_ARGV, "trst_pulls_srst") == 0)
1158                         tmp |= RESET_TRST_PULLS_SRST;
1159                 else if (strcmp(*CMD_ARGV, "combined") == 0)
1160                         tmp |= RESET_SRST_PULLS_TRST | RESET_TRST_PULLS_SRST;
1161                 else
1162                         m = 0;
1163                 if (mask & m) {
1164                         LOG_ERROR("extra reset_config %s spec (%s)",
1165                                         "combination", *CMD_ARGV);
1166                         return ERROR_INVALID_ARGUMENTS;
1167                 }
1168                 if (m)
1169                         goto next;
1170
1171                 /* trst_type (NOP without HAS_TRST) */
1172                 m = RESET_TRST_OPEN_DRAIN;
1173                 if (strcmp(*CMD_ARGV, "trst_open_drain") == 0)
1174                         tmp |= RESET_TRST_OPEN_DRAIN;
1175                 else if (strcmp(*CMD_ARGV, "trst_push_pull") == 0)
1176                         /* push/pull from adapter - default */;
1177                 else
1178                         m = 0;
1179                 if (mask & m) {
1180                         LOG_ERROR("extra reset_config %s spec (%s)",
1181                                         "trst_type", *CMD_ARGV);
1182                         return ERROR_INVALID_ARGUMENTS;
1183                 }
1184                 if (m)
1185                         goto next;
1186
1187                 /* srst_type (NOP without HAS_SRST) */
1188                 m |= RESET_SRST_PUSH_PULL;
1189                 if (strcmp(*CMD_ARGV, "srst_push_pull") == 0)
1190                         tmp |= RESET_SRST_PUSH_PULL;
1191                 else if (strcmp(*CMD_ARGV, "srst_open_drain") == 0)
1192                         /* open drain from adapter - default */;
1193                 else
1194                         m = 0;
1195                 if (mask & m) {
1196                         LOG_ERROR("extra reset_config %s spec (%s)",
1197                                         "srst_type", *CMD_ARGV);
1198                         return ERROR_INVALID_ARGUMENTS;
1199                 }
1200                 if (m)
1201                         goto next;
1202
1203                 /* caller provided nonsense; fail */
1204                 LOG_ERROR("unknown reset_config flag (%s)", *CMD_ARGV);
1205                 return ERROR_INVALID_ARGUMENTS;
1206
1207 next:
1208                 /* Remember the bits which were specified (mask)
1209                  * and their new values (new_cfg).
1210                  */
1211                 mask |= m;
1212                 new_cfg |= tmp;
1213         }
1214
1215         /* clear previous values of those bits, save new values */
1216         if (mask) {
1217                 int old_cfg = jtag_get_reset_config();
1218
1219                 old_cfg &= ~mask;
1220                 new_cfg |= old_cfg;
1221                 jtag_set_reset_config(new_cfg);
1222         } else
1223                 new_cfg = jtag_get_reset_config();
1224
1225
1226         /*
1227          * Display the (now-)current reset mode
1228          */
1229         char *modes[5];
1230
1231         /* minimal JTAG has neither SRST nor TRST (so that's the default) */
1232         switch (new_cfg & (RESET_HAS_TRST | RESET_HAS_SRST)) {
1233         case RESET_HAS_SRST:
1234                 modes[0] = "srst_only";
1235                 break;
1236         case RESET_HAS_TRST:
1237                 modes[0] = "trst_only";
1238                 break;
1239         case RESET_TRST_AND_SRST:
1240                 modes[0] = "trst_and_srst";
1241                 break;
1242         default:
1243                 modes[0] = "none";
1244                 break;
1245         }
1246
1247         /* normally SRST and TRST are decoupled; but bugs happen ... */
1248         switch (new_cfg & (RESET_SRST_PULLS_TRST | RESET_TRST_PULLS_SRST)) {
1249         case RESET_SRST_PULLS_TRST:
1250                 modes[1] = "srst_pulls_trst";
1251                 break;
1252         case RESET_TRST_PULLS_SRST:
1253                 modes[1] = "trst_pulls_srst";
1254                 break;
1255         case RESET_SRST_PULLS_TRST | RESET_TRST_PULLS_SRST:
1256                 modes[1] = "combined";
1257                 break;
1258         default:
1259                 modes[1] = "separate";
1260                 break;
1261         }
1262
1263         /* TRST-less connectors include Altera, Xilinx, and minimal JTAG */
1264         if (new_cfg & RESET_HAS_TRST) {
1265                 if (new_cfg & RESET_TRST_OPEN_DRAIN)
1266                         modes[3] = " trst_open_drain";
1267                 else
1268                         modes[3] = " trst_push_pull";
1269         } else
1270                 modes[3] = "";
1271
1272         /* SRST-less connectors include TI-14, Xilinx, and minimal JTAG */
1273         if (new_cfg & RESET_HAS_SRST) {
1274                 if (new_cfg & RESET_SRST_NO_GATING)
1275                         modes[2] = " srst_nogate";
1276                 else
1277                         modes[2] = " srst_gates_jtag";
1278
1279                 if (new_cfg & RESET_SRST_PUSH_PULL)
1280                         modes[4] = " srst_push_pull";
1281                 else
1282                         modes[4] = " srst_open_drain";
1283         } else {
1284                 modes[2] = "";
1285                 modes[4] = "";
1286         }
1287
1288         command_print(CMD_CTX, "%s %s%s%s%s",
1289                         modes[0], modes[1],
1290                         modes[2], modes[3], modes[4]);
1291
1292         return ERROR_OK;
1293 }
1294
1295 COMMAND_HANDLER(handle_adapter_nsrst_delay_command)
1296 {
1297         if (CMD_ARGC > 1)
1298                 return ERROR_COMMAND_SYNTAX_ERROR;
1299         if (CMD_ARGC == 1)
1300         {
1301                 unsigned delay;
1302                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1303
1304                 jtag_set_nsrst_delay(delay);
1305         }
1306         command_print(CMD_CTX, "adapter_nsrst_delay: %u", jtag_get_nsrst_delay());
1307         return ERROR_OK;
1308 }
1309
1310 COMMAND_HANDLER(handle_jtag_ntrst_delay_command)
1311 {
1312         if (CMD_ARGC > 1)
1313                 return ERROR_COMMAND_SYNTAX_ERROR;
1314         if (CMD_ARGC == 1)
1315         {
1316                 unsigned delay;
1317                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1318
1319                 jtag_set_ntrst_delay(delay);
1320         }
1321         command_print(CMD_CTX, "jtag_ntrst_delay: %u", jtag_get_ntrst_delay());
1322         return ERROR_OK;
1323 }
1324
1325 COMMAND_HANDLER(handle_adapter_nsrst_assert_width_command)
1326 {
1327         if (CMD_ARGC > 1)
1328                 return ERROR_COMMAND_SYNTAX_ERROR;
1329         if (CMD_ARGC == 1)
1330         {
1331                 unsigned delay;
1332                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1333
1334                 jtag_set_nsrst_assert_width(delay);
1335         }
1336         command_print(CMD_CTX, "adapter_nsrst_assert_width: %u", jtag_get_nsrst_assert_width());
1337         return ERROR_OK;
1338 }
1339
1340 COMMAND_HANDLER(handle_jtag_ntrst_assert_width_command)
1341 {
1342         if (CMD_ARGC > 1)
1343                 return ERROR_COMMAND_SYNTAX_ERROR;
1344         if (CMD_ARGC == 1)
1345         {
1346                 unsigned delay;
1347                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], delay);
1348
1349                 jtag_set_ntrst_assert_width(delay);
1350         }
1351         command_print(CMD_CTX, "jtag_ntrst_assert_width: %u", jtag_get_ntrst_assert_width());
1352         return ERROR_OK;
1353 }
1354
1355 COMMAND_HANDLER(handle_adapter_khz_command)
1356 {
1357         if (CMD_ARGC > 1)
1358                 return ERROR_COMMAND_SYNTAX_ERROR;
1359
1360         int retval = ERROR_OK;
1361         if (CMD_ARGC == 1)
1362         {
1363                 unsigned khz = 0;
1364                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], khz);
1365
1366                 retval = jtag_config_khz(khz);
1367                 if (ERROR_OK != retval)
1368                         return retval;
1369         }
1370
1371         int cur_speed = jtag_get_speed_khz();
1372         retval = jtag_get_speed_readable(&cur_speed);
1373         if (ERROR_OK != retval)
1374                 return retval;
1375
1376         if (cur_speed)
1377                 command_print(CMD_CTX, "%d kHz", cur_speed);
1378         else
1379                 command_print(CMD_CTX, "RCLK - adaptive");
1380
1381         return retval;
1382 }
1383
1384 COMMAND_HANDLER(handle_jtag_rclk_command)
1385 {
1386         if (CMD_ARGC > 1)
1387                 return ERROR_COMMAND_SYNTAX_ERROR;
1388
1389         int retval = ERROR_OK;
1390         if (CMD_ARGC == 1)
1391         {
1392                 unsigned khz = 0;
1393                 COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], khz);
1394
1395                 retval = jtag_config_rclk(khz);
1396                 if (ERROR_OK != retval)
1397                         return retval;
1398         }
1399
1400         int cur_khz = jtag_get_speed_khz();
1401         retval = jtag_get_speed_readable(&cur_khz);
1402         if (ERROR_OK != retval)
1403                 return retval;
1404
1405         if (cur_khz)
1406                 command_print(CMD_CTX, "RCLK not supported - fallback to %d kHz", cur_khz);
1407         else
1408                 command_print(CMD_CTX, "RCLK - adaptive");
1409
1410         return retval;
1411 }
1412
1413 COMMAND_HANDLER(handle_jtag_reset_command)
1414 {
1415         if (CMD_ARGC != 2)
1416                 return ERROR_COMMAND_SYNTAX_ERROR;
1417
1418         int trst = -1;
1419         if (CMD_ARGV[0][0] == '1')
1420                 trst = 1;
1421         else if (CMD_ARGV[0][0] == '0')
1422                 trst = 0;
1423         else
1424                 return ERROR_COMMAND_SYNTAX_ERROR;
1425
1426         int srst = -1;
1427         if (CMD_ARGV[1][0] == '1')
1428                 srst = 1;
1429         else if (CMD_ARGV[1][0] == '0')
1430                 srst = 0;
1431         else
1432                 return ERROR_COMMAND_SYNTAX_ERROR;
1433
1434         if (adapter_init(CMD_CTX) != ERROR_OK)
1435                 return ERROR_JTAG_INIT_FAILED;
1436
1437         jtag_add_reset(trst, srst);
1438         return jtag_execute_queue();
1439 }
1440
1441 COMMAND_HANDLER(handle_runtest_command)
1442 {
1443         if (CMD_ARGC != 1)
1444                 return ERROR_COMMAND_SYNTAX_ERROR;
1445
1446         unsigned num_clocks;
1447         COMMAND_PARSE_NUMBER(uint, CMD_ARGV[0], num_clocks);
1448
1449         jtag_add_runtest(num_clocks, TAP_IDLE);
1450         return jtag_execute_queue();
1451 }
1452
1453 /*
1454  * For "irscan" or "drscan" commands, the "end" (really, "next") state
1455  * should be stable ... and *NOT* a shift state, otherwise free-running
1456  * jtag clocks could change the values latched by the update state.
1457  * Not surprisingly, this is the same constraint as SVF; the "irscan"
1458  * and "drscan" commands are a write-only subset of what SVF provides.
1459  */
1460
1461 COMMAND_HANDLER(handle_irscan_command)
1462 {
1463         int i;
1464         struct scan_field *fields;
1465         struct jtag_tap *tap = NULL;
1466         tap_state_t endstate;
1467
1468         if ((CMD_ARGC < 2) || (CMD_ARGC % 2))
1469         {
1470                 return ERROR_COMMAND_SYNTAX_ERROR;
1471         }
1472
1473         /* optional "-endstate" "statename" at the end of the arguments,
1474          * so that e.g. IRPAUSE can let us load the data register before
1475          * entering RUN/IDLE to execute the instruction we load here.
1476          */
1477         endstate = TAP_IDLE;
1478
1479         if (CMD_ARGC >= 4) {
1480                 /* have at least one pair of numbers. */
1481                 /* is last pair the magic text? */
1482                 if (strcmp("-endstate", CMD_ARGV[CMD_ARGC - 2]) == 0) {
1483                         endstate = tap_state_by_name(CMD_ARGV[CMD_ARGC - 1]);
1484                         if (endstate == TAP_INVALID)
1485                                 return ERROR_COMMAND_SYNTAX_ERROR;
1486                         if (!scan_is_safe(endstate))
1487                                 LOG_WARNING("unstable irscan endstate \"%s\"",
1488                                                 CMD_ARGV[CMD_ARGC - 1]);
1489                         CMD_ARGC -= 2;
1490                 }
1491         }
1492
1493         int num_fields = CMD_ARGC / 2;
1494         if (num_fields > 1)
1495         {
1496                 /* we really should be looking at plain_ir_scan if we want
1497                  * anything more fancy.
1498                  */
1499                 LOG_ERROR("Specify a single value for tap");
1500                 return ERROR_COMMAND_SYNTAX_ERROR;
1501         }
1502
1503         size_t fields_len = sizeof(struct scan_field) * num_fields;
1504         fields = malloc(fields_len);
1505         memset(fields, 0, fields_len);
1506
1507         int retval;
1508         for (i = 0; i < num_fields; i++)
1509         {
1510                 tap = jtag_tap_by_string(CMD_ARGV[i*2]);
1511                 if (tap == NULL)
1512                 {
1513                         int j;
1514                         for (j = 0; j < i; j++)
1515                                 free((void *)fields[j].out_value);
1516                         free(fields);
1517                         command_print(CMD_CTX, "Tap: %s unknown", CMD_ARGV[i*2]);
1518
1519                         return ERROR_FAIL;
1520                 }
1521                 int field_size = tap->ir_length;
1522                 fields[i].num_bits = field_size;
1523                 fields[i].out_value = malloc(DIV_ROUND_UP(field_size, 8));
1524
1525                 uint32_t value;
1526                 retval = parse_u32(CMD_ARGV[i * 2 + 1], &value);
1527                 if (ERROR_OK != retval)
1528                         goto error_return;
1529                 buf_set_u32((void *)fields[i].out_value, 0, field_size, value);
1530                 fields[i].in_value = NULL;
1531         }
1532
1533         /* did we have an endstate? */
1534         jtag_add_ir_scan(tap, fields, endstate);
1535
1536         retval = jtag_execute_queue();
1537
1538 error_return:
1539         for (i = 0; i < num_fields; i++)
1540         {
1541                 if (NULL != fields[i].out_value)
1542                         free((void *)fields[i].out_value);
1543         }
1544
1545         free (fields);
1546
1547         return retval;
1548 }
1549
1550
1551 COMMAND_HANDLER(handle_verify_ircapture_command)
1552 {
1553         if (CMD_ARGC > 1)
1554                 return ERROR_COMMAND_SYNTAX_ERROR;
1555
1556         if (CMD_ARGC == 1)
1557         {
1558                 bool enable;
1559                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], enable);
1560                 jtag_set_verify_capture_ir(enable);
1561         }
1562
1563         const char *status = jtag_will_verify_capture_ir() ? "enabled": "disabled";
1564         command_print(CMD_CTX, "verify Capture-IR is %s", status);
1565
1566         return ERROR_OK;
1567 }
1568
1569 COMMAND_HANDLER(handle_verify_jtag_command)
1570 {
1571         if (CMD_ARGC > 1)
1572                 return ERROR_COMMAND_SYNTAX_ERROR;
1573
1574         if (CMD_ARGC == 1)
1575         {
1576                 bool enable;
1577                 COMMAND_PARSE_ENABLE(CMD_ARGV[0], enable);
1578                 jtag_set_verify(enable);
1579         }
1580
1581         const char *status = jtag_will_verify() ? "enabled": "disabled";
1582         command_print(CMD_CTX, "verify jtag capture is %s", status);
1583
1584         return ERROR_OK;
1585 }
1586
1587 COMMAND_HANDLER(handle_tms_sequence_command)
1588 {
1589         if (CMD_ARGC > 1)
1590                 return ERROR_COMMAND_SYNTAX_ERROR;
1591
1592         if (CMD_ARGC == 1)
1593         {
1594                 bool use_new_table;
1595                 if (strcmp(CMD_ARGV[0], "short") == 0)
1596                         use_new_table = true;
1597                 else if (strcmp(CMD_ARGV[0], "long") == 0)
1598                         use_new_table = false;
1599                 else
1600                         return ERROR_COMMAND_SYNTAX_ERROR;
1601
1602                 tap_use_new_tms_table(use_new_table);
1603         }
1604
1605         command_print(CMD_CTX, "tms sequence is  %s",
1606                         tap_uses_new_tms_table() ? "short": "long");
1607
1608         return ERROR_OK;
1609 }
1610
1611 static const struct command_registration interface_command_handlers[] = {
1612         {
1613                 .name = "adapter_khz",
1614                 .handler = handle_adapter_khz_command,
1615                 .mode = COMMAND_ANY,
1616                 .help = "With an argument, change to the specified maximum "
1617                         "jtag speed.  For JTAG, 0 KHz signifies adaptive "
1618                         " clocking. "
1619                         "With or without argument, display current setting.",
1620                 .usage = "[khz]",
1621         },
1622         {
1623                 .name = "adapter_nsrst_assert_width",
1624                 .handler = handle_adapter_nsrst_assert_width_command,
1625                 .mode = COMMAND_ANY,
1626                 .help = "delay after asserting SRST in ms",
1627                 .usage = "[milliseconds]",
1628         },
1629         {
1630                 .name = "adapter_nsrst_delay",
1631                 .handler = handle_adapter_nsrst_delay_command,
1632                 .mode = COMMAND_ANY,
1633                 .help = "delay after deasserting SRST in ms",
1634                 .usage = "[milliseconds]",
1635         },
1636         {
1637                 .name = "interface",
1638                 .handler = handle_interface_command,
1639                 .mode = COMMAND_CONFIG,
1640                 .help = "Select a debug adapter interface (driver)",
1641                 .usage = "driver_name",
1642         },
1643         {
1644                 .name = "interface_list",
1645                 .handler = handle_interface_list_command,
1646                 .mode = COMMAND_ANY,
1647                 .help = "List all built-in debug adapter interfaces (drivers)",
1648         },
1649         {
1650                 .name = "reset_config",
1651                 .handler = handle_reset_config_command,
1652                 .mode = COMMAND_ANY,
1653                 .help = "configure adapter reset behavior",
1654                 .usage = "[none|trst_only|srst_only|trst_and_srst] "
1655                         "[srst_pulls_trst|trst_pulls_srst|combined|separate] "
1656                         "[srst_gates_jtag|srst_nogate] "
1657                         "[trst_push_pull|trst_open_drain] "
1658                         "[srst_push_pull|srst_open_drain]",
1659         },
1660         COMMAND_REGISTRATION_DONE
1661 };
1662
1663 /**
1664  * Register the commands which deal with arbitrary debug adapter drivers.
1665  *
1666  * @todo Remove internal assumptions that all debug adapters use JTAG for
1667  * transport.  Various types and data structures are not named generically.
1668  */
1669 int interface_register_commands(struct command_context *ctx)
1670 {
1671         return register_commands(ctx, NULL, interface_command_handlers);
1672 }
1673
1674 static const struct command_registration jtag_command_handlers[] = {
1675         {
1676                 .name = "jtag_rclk",
1677                 .handler = handle_jtag_rclk_command,
1678                 .mode = COMMAND_ANY,
1679                 .help = "With an argument, change to to use adaptive clocking "
1680                         "if possible; else to use the fallback speed.  "
1681                         "With or without argument, display current setting.",
1682                 .usage = "[fallback_speed_khz]",
1683         },
1684         {
1685                 .name = "jtag_ntrst_delay",
1686                 .handler = handle_jtag_ntrst_delay_command,
1687                 .mode = COMMAND_ANY,
1688                 .help = "delay after deasserting trst in ms",
1689                 .usage = "[milliseconds]",
1690         },
1691         {
1692                 .name = "jtag_ntrst_assert_width",
1693                 .handler = handle_jtag_ntrst_assert_width_command,
1694                 .mode = COMMAND_ANY,
1695                 .help = "delay after asserting trst in ms",
1696                 .usage = "[milliseconds]",
1697         },
1698         {
1699                 .name = "scan_chain",
1700                 .handler = handle_scan_chain_command,
1701                 .mode = COMMAND_ANY,
1702                 .help = "print current scan chain configuration",
1703         },
1704         {
1705                 .name = "jtag_reset",
1706                 .handler = handle_jtag_reset_command,
1707                 .mode = COMMAND_EXEC,
1708                 .help = "Set reset line values.  Value '1' is active, "
1709                         "value '0' is inactive.",
1710                 .usage = "trst_active srst_active",
1711         },
1712         {
1713                 .name = "runtest",
1714                 .handler = handle_runtest_command,
1715                 .mode = COMMAND_EXEC,
1716                 .help = "Move to Run-Test/Idle, and issue TCK for num_cycles.",
1717                 .usage = "num_cycles"
1718         },
1719         {
1720                 .name = "irscan",
1721                 .handler = handle_irscan_command,
1722                 .mode = COMMAND_EXEC,
1723                 .help = "Execute Instruction Register (DR) scan.  The "
1724                         "specified opcodes are put into each TAP's IR, "
1725                         "and other TAPs are put in BYPASS.",
1726                 .usage = "[tap_name instruction]* ['-endstate' state_name]",
1727         },
1728         {
1729                 .name = "verify_ircapture",
1730                 .handler = handle_verify_ircapture_command,
1731                 .mode = COMMAND_ANY,
1732                 .help = "Display or assign flag controlling whether to "
1733                         "verify values captured during Capture-IR.",
1734                 .usage = "['enable'|'disable']",
1735         },
1736         {
1737                 .name = "verify_jtag",
1738                 .handler = handle_verify_jtag_command,
1739                 .mode = COMMAND_ANY,
1740                 .help = "Display or assign flag controlling whether to "
1741                         "verify values captured during IR and DR scans.",
1742                 .usage = "['enable'|'disable']",
1743         },
1744         {
1745                 .name = "tms_sequence",
1746                 .handler = handle_tms_sequence_command,
1747                 .mode = COMMAND_ANY,
1748                 .help = "Display or change what style TMS sequences to use "
1749                         "for JTAG state transitions:  short (default) or "
1750                         "long.  Only for working around JTAG bugs.",
1751                         /* Specifically for working around DRIVER bugs... */
1752                 .usage = "['short'|'long']",
1753         },
1754         {
1755                 .name = "jtag",
1756                 .mode = COMMAND_ANY,
1757                 .help = "perform jtag tap actions",
1758
1759                 .chain = jtag_subcommand_handlers,
1760         },
1761         {
1762                 .chain = jtag_command_handlers_to_move,
1763         },
1764         COMMAND_REGISTRATION_DONE
1765 };
1766
1767 int jtag_register_commands(struct command_context *cmd_ctx)
1768 {
1769         return register_commands(cmd_ctx, NULL, jtag_command_handlers);
1770 }