- remove target specific variant and use target->variant member
[fw/openocd] / src / jtag / jtag.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007,2008 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include "replacements.h"
28
29 #include "jtag.h"
30
31 #include "command.h"
32 #include "log.h"
33
34 #include "stdlib.h"
35 #include "string.h"
36 #include <unistd.h>
37
38 /* note that this is not marked as static as it must be available from outside jtag.c for those
39    that implement the jtag_xxx() minidriver layer
40 */
41 int jtag_error=ERROR_OK;
42
43
44 char* tap_state_strings[16] =
45 {
46         "tlr",
47         "sds", "cd", "sd", "e1d", "pd", "e2d", "ud",
48         "rti",
49         "sis", "ci", "si", "e1i", "pi", "e2i", "ui"
50 };
51
52 typedef struct cmd_queue_page_s
53 {
54         void *address;
55         size_t used;
56         struct cmd_queue_page_s *next;
57 } cmd_queue_page_t;
58
59 #define CMD_QUEUE_PAGE_SIZE (1024 * 1024)
60 static cmd_queue_page_t *cmd_queue_pages = NULL;
61
62 /* tap_move[i][j]: tap movement command to go from state i to state j
63  * 0: Test-Logic-Reset
64  * 1: Run-Test/Idle
65  * 2: Shift-DR
66  * 3: Pause-DR
67  * 4: Shift-IR
68  * 5: Pause-IR
69  *
70  * DRSHIFT->DRSHIFT and IRSHIFT->IRSHIFT have to be caught in interface specific code
71  */
72 u8 tap_move[6][6] =
73 {
74 /*        RESET  IDLE  DRSHIFT  DRPAUSE  IRSHIFT  IRPAUSE             */
75         {  0x7f, 0x00,    0x17,    0x0a,    0x1b,    0x16},     /* RESET */
76         {  0x7f, 0x00,    0x25,    0x05,    0x2b,    0x0b},     /* IDLE */
77         {  0x7f, 0x31,    0x00,    0x01,    0x0f,    0x2f},     /* DRSHIFT  */
78         {  0x7f, 0x30,    0x20,    0x17,    0x1e,    0x2f},     /* DRPAUSE  */
79         {  0x7f, 0x31,    0x07,    0x17,    0x00,    0x01},     /* IRSHIFT  */
80         {  0x7f, 0x30,    0x1c,    0x17,    0x20,    0x2f}      /* IRPAUSE  */
81 };
82
83 int tap_move_map[16] = {
84         0, -1, -1,  2, -1,  3, -1, -1,
85         1, -1, -1,  4, -1,  5, -1, -1
86 };
87
88 tap_transition_t tap_transitions[16] =
89 {
90         {TAP_RESET, TAP_IDLE},          /* RESET */
91         {TAP_IRSELECT, TAP_DRCAPTURE},          /* DRSELECT */
92         {TAP_DREXIT1, TAP_DRSHIFT},             /* DRCAPTURE  */
93         {TAP_DREXIT1, TAP_DRSHIFT},             /* DRSHIFT  */
94         {TAP_DRUPDATE,  TAP_DRPAUSE},           /* DREXIT1 */
95         {TAP_DREXIT2, TAP_DRPAUSE},             /* DRPAUSE  */
96         {TAP_DRUPDATE,  TAP_DRSHIFT},           /* DREXIT2 */
97         {TAP_DRSELECT, TAP_IDLE},               /* DRUPDATE  */
98         {TAP_DRSELECT, TAP_IDLE},               /* IDLE */
99         {TAP_RESET, TAP_IRCAPTURE},             /* IRSELECT */
100         {TAP_IREXIT1, TAP_IRSHIFT},             /* IRCAPTURE  */
101         {TAP_IREXIT1, TAP_IRSHIFT},             /* IRSHIFT  */
102         {TAP_IRUPDATE,  TAP_IRPAUSE},           /* IREXIT1 */
103         {TAP_IREXIT2, TAP_IRPAUSE},             /* IRPAUSE  */
104         {TAP_IRUPDATE,  TAP_IRSHIFT},           /* IREXIT2 */
105         {TAP_DRSELECT, TAP_IDLE}                /* IRUPDATE  */
106 };
107
108 char* jtag_event_strings[] =
109 {
110         "JTAG controller reset (RESET or TRST)"
111 };
112
113 const Jim_Nvp nvp_jtag_tap_event[] = {
114         { .value = JTAG_TAP_EVENT_ENABLE,       .name = "tap-enable" },
115         { .value = JTAG_TAP_EVENT_DISABLE,      .name = "tap-disable" },
116
117         { .name = NULL, .value = -1 }
118 };
119
120 /* kludge!!!! these are just global variables that the
121  * interface use internally. They really belong
122  * inside the drivers, but we don't want to break
123  * linking the drivers!!!!
124  */
125 enum tap_state end_state = TAP_RESET;
126 enum tap_state cur_state = TAP_RESET;
127 int jtag_trst = 0;
128 int jtag_srst = 0;
129
130 jtag_command_t *jtag_command_queue = NULL;
131 jtag_command_t **last_comand_pointer = &jtag_command_queue;
132 static jtag_tap_t *jtag_all_taps = NULL;
133
134 enum reset_types jtag_reset_config = RESET_NONE;
135 enum tap_state cmd_queue_end_state = TAP_RESET;
136 enum tap_state cmd_queue_cur_state = TAP_RESET;
137
138 int jtag_verify_capture_ir = 1;
139
140 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines deasserted (in ms) */
141 int jtag_nsrst_delay = 0; /* default to no nSRST delay */
142 int jtag_ntrst_delay = 0; /* default to no nTRST delay */
143
144 /* maximum number of JTAG devices expected in the chain
145  */
146 #define JTAG_MAX_CHAIN_SIZE 20
147
148 /* callbacks to inform high-level handlers about JTAG state changes */
149 jtag_event_callback_t *jtag_event_callbacks;
150
151 /* speed in kHz*/
152 static int speed_khz = 0;
153 /* flag if the kHz speed was defined */
154 static int hasKHz = 0;
155
156 /* jtag interfaces (parport, FTDI-USB, TI-USB, ...)
157  */
158
159 #if BUILD_ECOSBOARD == 1
160         extern jtag_interface_t zy1000_interface;
161 #endif
162
163 #if BUILD_PARPORT == 1
164         extern jtag_interface_t parport_interface;
165 #endif
166
167 #if BUILD_DUMMY == 1
168         extern jtag_interface_t dummy_interface;
169 #endif
170
171 #if BUILD_FT2232_FTD2XX == 1
172         extern jtag_interface_t ft2232_interface;
173 #endif
174
175 #if BUILD_FT2232_LIBFTDI == 1
176         extern jtag_interface_t ft2232_interface;
177 #endif
178
179 #if BUILD_AMTJTAGACCEL == 1
180         extern jtag_interface_t amt_jtagaccel_interface;
181 #endif
182
183 #if BUILD_EP93XX == 1
184         extern jtag_interface_t ep93xx_interface;
185 #endif
186
187 #if BUILD_AT91RM9200 == 1
188         extern jtag_interface_t at91rm9200_interface;
189 #endif
190
191 #if BUILD_GW16012 == 1
192         extern jtag_interface_t gw16012_interface;
193 #endif
194
195 #if BUILD_PRESTO_LIBFTDI == 1 || BUILD_PRESTO_FTD2XX == 1
196         extern jtag_interface_t presto_interface;
197 #endif
198
199 #if BUILD_USBPROG == 1
200         extern jtag_interface_t usbprog_interface;
201 #endif
202
203 #if BUILD_JLINK == 1
204         extern jtag_interface_t jlink_interface;
205 #endif
206
207 jtag_interface_t *jtag_interfaces[] = {
208 #if BUILD_ECOSBOARD == 1
209         &zy1000_interface,
210 #endif
211 #if BUILD_PARPORT == 1
212         &parport_interface,
213 #endif
214 #if BUILD_DUMMY == 1
215         &dummy_interface,
216 #endif
217 #if BUILD_FT2232_FTD2XX == 1
218         &ft2232_interface,
219 #endif
220 #if BUILD_FT2232_LIBFTDI == 1
221         &ft2232_interface,
222 #endif
223 #if BUILD_AMTJTAGACCEL == 1
224         &amt_jtagaccel_interface,
225 #endif
226 #if BUILD_EP93XX == 1
227         &ep93xx_interface,
228 #endif
229 #if BUILD_AT91RM9200 == 1
230         &at91rm9200_interface,
231 #endif
232 #if BUILD_GW16012 == 1
233         &gw16012_interface,
234 #endif
235 #if BUILD_PRESTO_LIBFTDI == 1 || BUILD_PRESTO_FTD2XX == 1
236         &presto_interface,
237 #endif
238 #if BUILD_USBPROG == 1
239         &usbprog_interface,
240 #endif
241 #if BUILD_JLINK == 1
242         &jlink_interface,
243 #endif
244         NULL,
245 };
246
247 jtag_interface_t *jtag = NULL;
248
249 /* configuration */
250 jtag_interface_t *jtag_interface = NULL;
251 int jtag_speed = 0;
252
253 /* forward declarations */
254 void jtag_add_pathmove(int num_states, enum tap_state *path);
255 void jtag_add_runtest(int num_cycles, enum tap_state endstate);
256 void jtag_add_end_state(enum tap_state endstate);
257 void jtag_add_sleep(u32 us);
258 int jtag_execute_queue(void);
259
260
261 /* jtag commands */
262 int handle_interface_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
263 int handle_jtag_speed_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
264 int handle_jtag_khz_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
265 int handle_jtag_device_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
266 int handle_reset_config_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
267 int handle_jtag_nsrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
268 int handle_jtag_ntrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
269
270 int handle_scan_chain_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
271
272 int handle_endstate_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
273 int handle_jtag_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
274 int handle_runtest_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
275 int handle_irscan_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
276 int Jim_Command_drscan(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
277
278 int handle_verify_ircapture_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
279
280 jtag_tap_t *jtag_AllTaps(void)
281 {
282         return jtag_all_taps;
283 };
284
285 int jtag_NumTotalTaps(void)
286 {
287         jtag_tap_t *t;
288         int n;
289
290         n = 0;
291         t = jtag_AllTaps();
292         while(t){
293                 n++;
294                 t = t->next_tap;
295         }
296         return n;
297 }
298
299 int jtag_NumEnabledTaps(void)
300 {
301         jtag_tap_t *t;
302         int n;
303
304         n = 0;
305         t = jtag_AllTaps();
306         while(t){
307                 if( t->enabled ){
308                         n++;
309                 }
310                 t = t->next_tap;
311         }
312         return n;
313 }
314
315
316 jtag_tap_t *jtag_TapByString( const char *s )
317 {
318         jtag_tap_t *t;
319         char *cp;
320
321         t = jtag_AllTaps();
322         // try name first
323         while(t){
324                 if( 0 == strcmp( t->dotted_name, s ) ){
325                         break;
326                 } else {
327                         t = t->next_tap;
328                 }
329         }
330         // backup plan is by number
331         if( t == NULL ){
332                 /* ok - is "s" a number? */
333                 int n;
334                 n = strtol( s, &cp, 0 );
335                 if( (s != cp) && (*cp == 0) ){
336                         /* Then it is... */
337                         t = jtag_TapByAbsPosition(n);
338                 }
339         }
340         return t;
341 }
342
343 jtag_tap_t * jtag_TapByJimObj( Jim_Interp *interp, Jim_Obj *o )
344 {
345         jtag_tap_t *t;
346         const char *cp;
347
348         cp = Jim_GetString( o, NULL );
349         if(cp == NULL){
350                 cp = "(unknown)";
351                 t = NULL;
352         }  else {
353                 t = jtag_TapByString( cp );
354         }
355         if( t == NULL ){
356                 Jim_SetResult_sprintf(interp,"Tap: %s is unknown", cp );
357         }
358         return t;
359 }
360
361 /* returns a pointer to the n-th device in the scan chain */
362 jtag_tap_t * jtag_TapByAbsPosition( int n )
363 {
364         int orig_n;
365         jtag_tap_t *t;
366
367         orig_n = n;
368         t = jtag_AllTaps();
369
370         while( t && (n > 0)) {
371                 n--;
372                 t = t->next_tap;
373         }
374         return t;
375 }
376
377 int jtag_register_event_callback(int (*callback)(enum jtag_event event, void *priv), void *priv)
378 {
379         jtag_event_callback_t **callbacks_p = &jtag_event_callbacks;
380
381         if (callback == NULL)
382         {
383                 return ERROR_INVALID_ARGUMENTS;
384         }
385
386         if (*callbacks_p)
387         {
388                 while ((*callbacks_p)->next)
389                         callbacks_p = &((*callbacks_p)->next);
390                 callbacks_p = &((*callbacks_p)->next);
391         }
392
393         (*callbacks_p) = malloc(sizeof(jtag_event_callback_t));
394         (*callbacks_p)->callback = callback;
395         (*callbacks_p)->priv = priv;
396         (*callbacks_p)->next = NULL;
397
398         return ERROR_OK;
399 }
400
401 int jtag_unregister_event_callback(int (*callback)(enum jtag_event event, void *priv))
402 {
403         jtag_event_callback_t **callbacks_p = &jtag_event_callbacks;
404
405         if (callback == NULL)
406         {
407                 return ERROR_INVALID_ARGUMENTS;
408         }
409
410         while (*callbacks_p)
411         {
412                 jtag_event_callback_t **next = &((*callbacks_p)->next);
413                 if ((*callbacks_p)->callback == callback)
414                 {
415                         free(*callbacks_p);
416                         *callbacks_p = *next;
417                 }
418                 callbacks_p = next;
419         }
420
421         return ERROR_OK;
422 }
423
424 int jtag_call_event_callbacks(enum jtag_event event)
425 {
426         jtag_event_callback_t *callback = jtag_event_callbacks;
427
428         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
429
430         while (callback)
431         {
432                 callback->callback(event, callback->priv);
433                 callback = callback->next;
434         }
435
436         return ERROR_OK;
437 }
438
439 /* returns a pointer to the pointer of the last command in queue
440  * this may be a pointer to the root pointer (jtag_command_queue)
441  * or to the next member of the last but one command
442  */
443 jtag_command_t** jtag_get_last_command_p(void)
444 {
445 /*      jtag_command_t *cmd = jtag_command_queue;
446
447         if (cmd)
448                 while (cmd->next)
449                         cmd = cmd->next;
450         else
451                 return &jtag_command_queue;
452
453         return &cmd->next;*/
454
455         return last_comand_pointer;
456 }
457
458 void* cmd_queue_alloc(size_t size)
459 {
460         cmd_queue_page_t **p_page = &cmd_queue_pages;
461         int offset;
462         u8 *t;
463
464         /*
465          * WARNING:
466          *    We align/round the *SIZE* per below
467          *    so that all pointers returned by
468          *    this function are reasonably well
469          *    aligned.
470          *
471          * If we did not, then an "odd-length" request would cause the
472          * *next* allocation to be at an *odd* address, and because
473          * this function has the same type of api as malloc() - we
474          * must also return pointers that have the same type of
475          * alignment.
476          *
477          * What I do not/have is a reasonable portable means
478          * to align by...
479          *
480          * The solution here, is based on these suggestions.
481          * http://gcc.gnu.org/ml/gcc-help/2008-12/msg00041.html
482          *
483          */
484         union worse_case_align {
485                 int i;
486                 long l;
487                 float f;
488                 void *v;
489         };
490 #define ALIGN_SIZE  (sizeof(union worse_case_align))
491
492         /* The alignment process. */
493         size = (size + ALIGN_SIZE -1) & (~(ALIGN_SIZE-1));
494         /* Done... */
495
496         if (*p_page)
497         {
498                 while ((*p_page)->next)
499                         p_page = &((*p_page)->next);
500                 if (CMD_QUEUE_PAGE_SIZE - (*p_page)->used < size)
501                         p_page = &((*p_page)->next);
502         }
503
504         if (!*p_page)
505         {
506                 *p_page = malloc(sizeof(cmd_queue_page_t));
507                 (*p_page)->used = 0;
508                 (*p_page)->address = malloc(CMD_QUEUE_PAGE_SIZE);
509                 (*p_page)->next = NULL;
510         }
511
512         offset = (*p_page)->used;
513         (*p_page)->used += size;
514
515         t=(u8 *)((*p_page)->address);
516         return t + offset;
517 }
518
519 void cmd_queue_free(void)
520 {
521         cmd_queue_page_t *page = cmd_queue_pages;
522
523         while (page)
524         {
525                 cmd_queue_page_t *last = page;
526                 free(page->address);
527                 page = page->next;
528                 free(last);
529         }
530
531         cmd_queue_pages = NULL;
532 }
533
534 static void jtag_prelude1(void)
535 {
536         if (jtag_trst == 1)
537         {
538                 LOG_WARNING("JTAG command queued, while TRST is low (TAP in reset)");
539                 jtag_error=ERROR_JTAG_TRST_ASSERTED;
540                 return;
541         }
542
543         if (cmd_queue_end_state == TAP_RESET)
544                 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
545 }
546
547 static void jtag_prelude(enum tap_state state)
548 {
549         jtag_prelude1();
550
551         if (state != -1)
552                 jtag_add_end_state(state);
553
554         cmd_queue_cur_state = cmd_queue_end_state;
555 }
556
557 void jtag_add_ir_scan(int num_fields, scan_field_t *fields, enum tap_state state)
558 {
559         int retval;
560
561         jtag_prelude(state);
562
563         retval=interface_jtag_add_ir_scan(num_fields, fields, cmd_queue_end_state);
564         if (retval!=ERROR_OK)
565                 jtag_error=retval;
566 }
567
568 int MINIDRIVER(interface_jtag_add_ir_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
569 {
570         jtag_command_t **last_cmd;
571         jtag_tap_t *tap;
572         int j;
573         int x;
574         int nth_tap;
575         int scan_size = 0;
576
577
578         last_cmd = jtag_get_last_command_p();
579
580         /* allocate memory for a new list member */
581         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
582         (*last_cmd)->next = NULL;
583         last_comand_pointer = &((*last_cmd)->next);
584         (*last_cmd)->type = JTAG_SCAN;
585
586         /* allocate memory for ir scan command */
587         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
588         (*last_cmd)->cmd.scan->ir_scan = 1;
589         x = jtag_NumEnabledTaps();
590         (*last_cmd)->cmd.scan->num_fields = x;  /* one field per device */
591         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc(x  * sizeof(scan_field_t));
592         (*last_cmd)->cmd.scan->end_state = state;
593
594         nth_tap = -1;
595         tap = NULL;
596         for(;;){
597                 int found = 0;
598
599                 // do this here so it is not forgotten
600                 tap = jtag_NextEnabledTap(tap);
601                 if( tap == NULL ){
602                         break;
603                 }
604                 nth_tap++;
605                 scan_size = tap->ir_length;
606                 (*last_cmd)->cmd.scan->fields[nth_tap].tap = tap;
607                 (*last_cmd)->cmd.scan->fields[nth_tap].num_bits = scan_size;
608                 (*last_cmd)->cmd.scan->fields[nth_tap].in_value = NULL;
609                 (*last_cmd)->cmd.scan->fields[nth_tap].in_handler = NULL;       /* disable verification by default */
610
611                 /* search the list */
612                 for (j = 0; j < num_fields; j++)
613                 {
614                         if (tap == fields[j].tap)
615                         {
616                                 found = 1;
617                                 (*last_cmd)->cmd.scan->fields[nth_tap].out_value = buf_cpy(fields[j].out_value, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
618                                 (*last_cmd)->cmd.scan->fields[nth_tap].out_mask = buf_cpy(fields[j].out_mask, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
619
620                                 if (jtag_verify_capture_ir)
621                                 {
622                                         if (fields[j].in_handler==NULL)
623                                         {
624                                                 jtag_set_check_value((*last_cmd)->cmd.scan->fields+nth_tap, tap->expected, tap->expected_mask, NULL);
625                                         } else
626                                         {
627                                                 (*last_cmd)->cmd.scan->fields[nth_tap].in_handler = fields[j].in_handler;
628                                                 (*last_cmd)->cmd.scan->fields[nth_tap].in_handler_priv = fields[j].in_handler_priv;
629                                                 (*last_cmd)->cmd.scan->fields[nth_tap].in_check_value = tap->expected;
630                                                 (*last_cmd)->cmd.scan->fields[nth_tap].in_check_mask = tap->expected_mask;
631                                         }
632                                 }
633
634                                 tap->bypass = 0;
635                                 break;
636                         }
637                 }
638
639                 if (!found)
640                 {
641                         /* if a tap isn't listed, set it to BYPASS */
642                         (*last_cmd)->cmd.scan->fields[nth_tap].out_value = buf_set_ones(cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
643                         (*last_cmd)->cmd.scan->fields[nth_tap].out_mask = NULL;
644                         tap->bypass = 1;
645                 }
646
647                 /* update device information */
648                 buf_cpy((*last_cmd)->cmd.scan->fields[nth_tap].out_value, tap->cur_instr, scan_size);
649         }
650
651         return ERROR_OK;
652 }
653
654 void jtag_add_plain_ir_scan(int num_fields, scan_field_t *fields, enum tap_state state)
655 {
656         int retval;
657
658         jtag_prelude(state);
659
660         retval=interface_jtag_add_plain_ir_scan(num_fields, fields, cmd_queue_end_state);
661         if (retval!=ERROR_OK)
662                 jtag_error=retval;
663 }
664
665 int MINIDRIVER(interface_jtag_add_plain_ir_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
666 {
667         int i;
668         jtag_command_t **last_cmd;
669
670         last_cmd = jtag_get_last_command_p();
671
672         /* allocate memory for a new list member */
673         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
674         (*last_cmd)->next = NULL;
675         last_comand_pointer = &((*last_cmd)->next);
676         (*last_cmd)->type = JTAG_SCAN;
677
678         /* allocate memory for ir scan command */
679         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
680         (*last_cmd)->cmd.scan->ir_scan = 1;
681         (*last_cmd)->cmd.scan->num_fields = num_fields;
682         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc(num_fields * sizeof(scan_field_t));
683         (*last_cmd)->cmd.scan->end_state = state;
684
685         for( i = 0 ; i < num_fields ; i++ ){
686                 int num_bits = fields[i].num_bits;
687                 int num_bytes = CEIL(fields[i].num_bits, 8);
688                 (*last_cmd)->cmd.scan->fields[i].tap = fields[i].tap;
689                 (*last_cmd)->cmd.scan->fields[i].num_bits = num_bits;
690                 (*last_cmd)->cmd.scan->fields[i].out_value = buf_cpy(fields[i].out_value, cmd_queue_alloc(num_bytes), num_bits);
691                 (*last_cmd)->cmd.scan->fields[i].out_mask = buf_cpy(fields[i].out_mask, cmd_queue_alloc(num_bytes), num_bits);
692                 (*last_cmd)->cmd.scan->fields[i].in_value = fields[i].in_value;
693                 (*last_cmd)->cmd.scan->fields[i].in_check_value = fields[i].in_check_value;
694                 (*last_cmd)->cmd.scan->fields[i].in_check_mask = fields[i].in_check_mask;
695                 (*last_cmd)->cmd.scan->fields[i].in_handler = NULL;
696                 (*last_cmd)->cmd.scan->fields[i].in_handler_priv = NULL;
697         }
698         return ERROR_OK;
699 }
700
701 void jtag_add_dr_scan(int num_fields, scan_field_t *fields, enum tap_state state)
702 {
703         int retval;
704
705         jtag_prelude(state);
706
707         retval=interface_jtag_add_dr_scan(num_fields, fields, cmd_queue_end_state);
708         if (retval!=ERROR_OK)
709                 jtag_error=retval;
710 }
711
712 int MINIDRIVER(interface_jtag_add_dr_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
713 {
714         int j;
715         int nth_tap;
716         int bypass_devices = 0;
717         int field_count = 0;
718         int scan_size;
719
720         jtag_command_t **last_cmd = jtag_get_last_command_p();
721         jtag_tap_t *tap;
722
723         /* count devices in bypass */
724         tap = NULL;
725         bypass_devices = 0;
726         for(;;){
727                 tap = jtag_NextEnabledTap(tap);
728                 if( tap == NULL ){
729                         break;
730                 }
731                 if( tap->bypass ){
732                         bypass_devices++;
733                 }
734         }
735
736         /* allocate memory for a new list member */
737         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
738         last_comand_pointer = &((*last_cmd)->next);
739         (*last_cmd)->next = NULL;
740         (*last_cmd)->type = JTAG_SCAN;
741
742         /* allocate memory for dr scan command */
743         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
744         (*last_cmd)->cmd.scan->ir_scan = 0;
745         (*last_cmd)->cmd.scan->num_fields = num_fields + bypass_devices;
746         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc((num_fields + bypass_devices) * sizeof(scan_field_t));
747         (*last_cmd)->cmd.scan->end_state = state;
748
749         tap = NULL;
750         nth_tap = -1;
751         for(;;){
752                 nth_tap++;
753                 tap = jtag_NextEnabledTap(tap);
754                 if( tap == NULL ){
755                         break;
756                 }
757                 int found = 0;
758                 (*last_cmd)->cmd.scan->fields[field_count].tap = tap;
759
760                 for (j = 0; j < num_fields; j++)
761                 {
762                         if (tap == fields[j].tap)
763                         {
764                                 found = 1;
765                                 scan_size = fields[j].num_bits;
766                                 (*last_cmd)->cmd.scan->fields[field_count].num_bits = scan_size;
767                                 (*last_cmd)->cmd.scan->fields[field_count].out_value = buf_cpy(fields[j].out_value, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
768                                 (*last_cmd)->cmd.scan->fields[field_count].out_mask = buf_cpy(fields[j].out_mask, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
769                                 (*last_cmd)->cmd.scan->fields[field_count].in_value = fields[j].in_value;
770                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_value = fields[j].in_check_value;
771                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = fields[j].in_check_mask;
772                                 (*last_cmd)->cmd.scan->fields[field_count].in_handler = fields[j].in_handler;
773                                 (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = fields[j].in_handler_priv;
774                         }
775                 }
776                 if (!found)
777                 {
778 #ifdef _DEBUG_JTAG_IO_
779                         /* if a device isn't listed, the BYPASS register should be selected */
780                         if (! tap->bypass)
781                         {
782                                 LOG_ERROR("BUG: no scan data for a device not in BYPASS");
783                                 exit(-1);
784                         }
785 #endif
786                         /* program the scan field to 1 bit length, and ignore it's value */
787                         (*last_cmd)->cmd.scan->fields[field_count].num_bits = 1;
788                         (*last_cmd)->cmd.scan->fields[field_count].out_value = NULL;
789                         (*last_cmd)->cmd.scan->fields[field_count].out_mask = NULL;
790                         (*last_cmd)->cmd.scan->fields[field_count].in_value = NULL;
791                         (*last_cmd)->cmd.scan->fields[field_count].in_check_value = NULL;
792                         (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = NULL;
793                         (*last_cmd)->cmd.scan->fields[field_count].in_handler = NULL;
794                         (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = NULL;
795                 }
796                 else
797                 {
798 #ifdef _DEBUG_JTAG_IO_
799                         /* if a device is listed, the BYPASS register must not be selected */
800                         if (tap->bypass)
801                         {
802                                 LOG_ERROR("BUG: scan data for a device in BYPASS");
803                                 exit(-1);
804                         }
805 #endif
806                 }
807         }
808         return ERROR_OK;
809 }
810
811 void MINIDRIVER(interface_jtag_add_dr_out)(jtag_tap_t *target_tap,
812                 int num_fields,
813                 const int *num_bits,
814                 const u32 *value,
815                 enum tap_state end_state)
816 {
817         int nth_tap;
818         int field_count = 0;
819         int scan_size;
820         int bypass_devices = 0;
821
822         jtag_command_t **last_cmd = jtag_get_last_command_p();
823         jtag_tap_t *tap;
824
825         /* count devices in bypass */
826         tap = NULL;
827         bypass_devices = 0;
828         for(;;){
829                 tap = jtag_NextEnabledTap(tap);
830                 if( tap == NULL ){
831                         break;
832                 }
833                 if( tap->bypass ){
834                         bypass_devices++;
835                 }
836         }
837
838         /* allocate memory for a new list member */
839         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
840         last_comand_pointer = &((*last_cmd)->next);
841         (*last_cmd)->next = NULL;
842         (*last_cmd)->type = JTAG_SCAN;
843
844         /* allocate memory for dr scan command */
845         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
846         (*last_cmd)->cmd.scan->ir_scan = 0;
847         (*last_cmd)->cmd.scan->num_fields = num_fields + bypass_devices;
848         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc((num_fields + bypass_devices) * sizeof(scan_field_t));
849         (*last_cmd)->cmd.scan->end_state = end_state;
850
851         tap = NULL;
852         nth_tap = -1;
853         for(;;){
854                 tap = jtag_NextEnabledTap(tap);
855                 if( tap == NULL ){
856                         break;
857                 }
858                 nth_tap++;
859                 (*last_cmd)->cmd.scan->fields[field_count].tap = tap;
860
861                 if (tap == target_tap)
862                 {
863                         int j;
864 #ifdef _DEBUG_JTAG_IO_
865                         /* if a device is listed, the BYPASS register must not be selected */
866                         if (tap->bypass)
867                         {
868                                 LOG_ERROR("BUG: scan data for a device in BYPASS");
869                                 exit(-1);
870                         }
871 #endif
872                         for (j = 0; j < num_fields; j++)
873                         {
874                                 u8 out_value[4];
875                                 scan_size = num_bits[j];
876                                 buf_set_u32(out_value, 0, scan_size, value[j]);
877                                 (*last_cmd)->cmd.scan->fields[field_count].num_bits = scan_size;
878                                 (*last_cmd)->cmd.scan->fields[field_count].out_value = buf_cpy(out_value, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
879                                 (*last_cmd)->cmd.scan->fields[field_count].out_mask = NULL;
880                                 (*last_cmd)->cmd.scan->fields[field_count].in_value = NULL;
881                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_value = NULL;
882                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = NULL;
883                                 (*last_cmd)->cmd.scan->fields[field_count].in_handler = NULL;
884                                 (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = NULL;
885                         }
886                 } else
887                 {
888 #ifdef _DEBUG_JTAG_IO_
889                         /* if a device isn't listed, the BYPASS register should be selected */
890                         if (! tap->bypass)
891                         {
892                                 LOG_ERROR("BUG: no scan data for a device not in BYPASS");
893                                 exit(-1);
894                         }
895 #endif
896                         /* program the scan field to 1 bit length, and ignore it's value */
897                         (*last_cmd)->cmd.scan->fields[field_count].num_bits = 1;
898                         (*last_cmd)->cmd.scan->fields[field_count].out_value = NULL;
899                         (*last_cmd)->cmd.scan->fields[field_count].out_mask = NULL;
900                         (*last_cmd)->cmd.scan->fields[field_count].in_value = NULL;
901                         (*last_cmd)->cmd.scan->fields[field_count].in_check_value = NULL;
902                         (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = NULL;
903                         (*last_cmd)->cmd.scan->fields[field_count].in_handler = NULL;
904                         (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = NULL;
905                 }
906         }
907 }
908
909 void jtag_add_plain_dr_scan(int num_fields, scan_field_t *fields, enum tap_state state)
910 {
911         int retval;
912
913         jtag_prelude(state);
914
915         retval=interface_jtag_add_plain_dr_scan(num_fields, fields, cmd_queue_end_state);
916         if (retval!=ERROR_OK)
917                 jtag_error=retval;
918 }
919
920 int MINIDRIVER(interface_jtag_add_plain_dr_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
921 {
922         int i;
923         jtag_command_t **last_cmd = jtag_get_last_command_p();
924
925         /* allocate memory for a new list member */
926         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
927         last_comand_pointer = &((*last_cmd)->next);
928         (*last_cmd)->next = NULL;
929         (*last_cmd)->type = JTAG_SCAN;
930
931         /* allocate memory for scan command */
932         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
933         (*last_cmd)->cmd.scan->ir_scan = 0;
934         (*last_cmd)->cmd.scan->num_fields = num_fields;
935         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc(num_fields * sizeof(scan_field_t));
936         (*last_cmd)->cmd.scan->end_state = state;
937
938         for (i = 0; i < num_fields; i++)
939         {
940                 int num_bits = fields[i].num_bits;
941                 int num_bytes = CEIL(fields[i].num_bits, 8);
942                 (*last_cmd)->cmd.scan->fields[i].tap = fields[i].tap;
943                 (*last_cmd)->cmd.scan->fields[i].num_bits = num_bits;
944                 (*last_cmd)->cmd.scan->fields[i].out_value = buf_cpy(fields[i].out_value, cmd_queue_alloc(num_bytes), num_bits);
945                 (*last_cmd)->cmd.scan->fields[i].out_mask = buf_cpy(fields[i].out_mask, cmd_queue_alloc(num_bytes), num_bits);
946                 (*last_cmd)->cmd.scan->fields[i].in_value = fields[i].in_value;
947                 (*last_cmd)->cmd.scan->fields[i].in_check_value = fields[i].in_check_value;
948                 (*last_cmd)->cmd.scan->fields[i].in_check_mask = fields[i].in_check_mask;
949                 (*last_cmd)->cmd.scan->fields[i].in_handler = fields[i].in_handler;
950                 (*last_cmd)->cmd.scan->fields[i].in_handler_priv = fields[i].in_handler_priv;
951         }
952
953         return ERROR_OK;
954 }
955
956 void jtag_add_tlr(void)
957 {
958         jtag_prelude(TAP_RESET);
959
960         int retval;
961         retval=interface_jtag_add_tlr();
962         if (retval!=ERROR_OK)
963                 jtag_error=retval;
964 }
965
966 int MINIDRIVER(interface_jtag_add_tlr)()
967 {
968         enum tap_state state = TAP_RESET;
969         jtag_command_t **last_cmd = jtag_get_last_command_p();
970
971         /* allocate memory for a new list member */
972         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
973         last_comand_pointer = &((*last_cmd)->next);
974         (*last_cmd)->next = NULL;
975         (*last_cmd)->type = JTAG_STATEMOVE;
976
977         (*last_cmd)->cmd.statemove = cmd_queue_alloc(sizeof(statemove_command_t));
978         (*last_cmd)->cmd.statemove->end_state = state;
979
980
981         return ERROR_OK;
982 }
983
984 void jtag_add_pathmove(int num_states, enum tap_state *path)
985 {
986         enum tap_state cur_state=cmd_queue_cur_state;
987         int i;
988         int retval;
989
990         /* the last state has to be a stable state */
991         if (tap_move_map[path[num_states - 1]] == -1)
992         {
993                 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
994                 exit(-1);
995         }
996
997         for (i=0; i<num_states; i++)
998         {
999                 if (path[i] == TAP_RESET)
1000                 {
1001                         LOG_ERROR("BUG: TAP_RESET is not a valid state for pathmove sequences");
1002                         exit(-1);
1003                 }
1004                 if ((tap_transitions[cur_state].low != path[i])&&
1005                                 (tap_transitions[cur_state].high != path[i]))
1006                 {
1007                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition", tap_state_strings[cur_state], tap_state_strings[path[i]]);
1008                         exit(-1);
1009                 }
1010                 cur_state = path[i];
1011         }
1012
1013         jtag_prelude1();
1014
1015         retval=interface_jtag_add_pathmove(num_states, path);
1016         cmd_queue_cur_state = path[num_states - 1];
1017         if (retval!=ERROR_OK)
1018                 jtag_error=retval;
1019 }
1020
1021 int MINIDRIVER(interface_jtag_add_pathmove)(int num_states, enum tap_state *path)
1022 {
1023         jtag_command_t **last_cmd = jtag_get_last_command_p();
1024         int i;
1025
1026         /* allocate memory for a new list member */
1027         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
1028         last_comand_pointer = &((*last_cmd)->next);
1029         (*last_cmd)->next = NULL;
1030         (*last_cmd)->type = JTAG_PATHMOVE;
1031
1032         (*last_cmd)->cmd.pathmove = cmd_queue_alloc(sizeof(pathmove_command_t));
1033         (*last_cmd)->cmd.pathmove->num_states = num_states;
1034         (*last_cmd)->cmd.pathmove->path = cmd_queue_alloc(sizeof(enum tap_state) * num_states);
1035
1036         for (i = 0; i < num_states; i++)
1037                 (*last_cmd)->cmd.pathmove->path[i] = path[i];
1038
1039         return ERROR_OK;
1040 }
1041
1042 int MINIDRIVER(interface_jtag_add_runtest)(int num_cycles, enum tap_state state)
1043 {
1044         jtag_command_t **last_cmd = jtag_get_last_command_p();
1045
1046         /* allocate memory for a new list member */
1047         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
1048         (*last_cmd)->next = NULL;
1049         last_comand_pointer = &((*last_cmd)->next);
1050         (*last_cmd)->type = JTAG_RUNTEST;
1051
1052         (*last_cmd)->cmd.runtest = cmd_queue_alloc(sizeof(runtest_command_t));
1053         (*last_cmd)->cmd.runtest->num_cycles = num_cycles;
1054         (*last_cmd)->cmd.runtest->end_state = state;
1055
1056         return ERROR_OK;
1057 }
1058
1059 void jtag_add_runtest(int num_cycles, enum tap_state state)
1060 {
1061         int retval;
1062
1063         jtag_prelude(state);
1064
1065         /* executed by sw or hw fifo */
1066         retval=interface_jtag_add_runtest(num_cycles, cmd_queue_end_state);
1067         if (retval!=ERROR_OK)
1068                 jtag_error=retval;
1069 }
1070
1071 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
1072 {
1073         int trst_with_tlr = 0;
1074         int retval;
1075
1076         /* FIX!!! there are *many* different cases here. A better
1077          * approach is needed for legal combinations of transitions...
1078          */
1079         if ((jtag_reset_config & RESET_HAS_SRST)&&
1080                         (jtag_reset_config & RESET_HAS_TRST)&&
1081                         ((jtag_reset_config & RESET_SRST_PULLS_TRST)==0))
1082         {
1083                 if (((req_tlr_or_trst&&!jtag_trst)||
1084                                 (!req_tlr_or_trst&&jtag_trst))&&
1085                                 ((req_srst&&!jtag_srst)||
1086                                                 (!req_srst&&jtag_srst)))
1087                 {
1088                         /* FIX!!! srst_pulls_trst allows 1,1 => 0,0 transition.... */
1089                         //LOG_ERROR("BUG: transition of req_tlr_or_trst and req_srst in the same jtag_add_reset() call is undefined");
1090                 }
1091         }
1092
1093         /* Make sure that jtag_reset_config allows the requested reset */
1094         /* if SRST pulls TRST, we can't fulfill srst == 1 with trst == 0 */
1095         if (((jtag_reset_config & RESET_SRST_PULLS_TRST) && (req_srst == 1)) && (!req_tlr_or_trst))
1096         {
1097                 LOG_ERROR("BUG: requested reset would assert trst");
1098                 jtag_error=ERROR_FAIL;
1099                 return;
1100         }
1101
1102         /* if TRST pulls SRST, we reset with TAP T-L-R */
1103         if (((jtag_reset_config & RESET_TRST_PULLS_SRST) && (req_tlr_or_trst)) && (req_srst == 0))
1104         {
1105                 trst_with_tlr = 1;
1106         }
1107
1108         if (req_srst && !(jtag_reset_config & RESET_HAS_SRST))
1109         {
1110                 LOG_ERROR("BUG: requested SRST assertion, but the current configuration doesn't support this");
1111                 jtag_error=ERROR_FAIL;
1112                 return;
1113         }
1114
1115         if (req_tlr_or_trst)
1116         {
1117                 if (!trst_with_tlr && (jtag_reset_config & RESET_HAS_TRST))
1118                 {
1119                         jtag_trst = 1;
1120                 } else
1121                 {
1122                         trst_with_tlr = 1;
1123                 }
1124         } else
1125         {
1126                 jtag_trst = 0;
1127         }
1128
1129         jtag_srst = req_srst;
1130
1131         retval = interface_jtag_add_reset(jtag_trst, jtag_srst);
1132         if (retval!=ERROR_OK)
1133         {
1134                 jtag_error=retval;
1135                 return;
1136         }
1137
1138         if (jtag_srst)
1139         {
1140                 LOG_DEBUG("SRST line asserted");
1141         }
1142         else
1143         {
1144                 LOG_DEBUG("SRST line released");
1145                 if (jtag_nsrst_delay)
1146                         jtag_add_sleep(jtag_nsrst_delay * 1000);
1147         }
1148
1149         if (trst_with_tlr)
1150         {
1151                 LOG_DEBUG("JTAG reset with RESET instead of TRST");
1152                 jtag_add_end_state(TAP_RESET);
1153                 jtag_add_tlr();
1154                 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
1155                 return;
1156         }
1157
1158         if (jtag_trst)
1159         {
1160                 /* we just asserted nTRST, so we're now in Test-Logic-Reset,
1161                  * and inform possible listeners about this
1162                  */
1163                 LOG_DEBUG("TRST line asserted");
1164                 cmd_queue_cur_state = TAP_RESET;
1165                 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
1166         }
1167         else
1168         {
1169                 if (jtag_ntrst_delay)
1170                         jtag_add_sleep(jtag_ntrst_delay * 1000);
1171         }
1172 }
1173
1174 int MINIDRIVER(interface_jtag_add_reset)(int req_trst, int req_srst)
1175 {
1176         jtag_command_t **last_cmd = jtag_get_last_command_p();
1177
1178         /* allocate memory for a new list member */
1179         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
1180         (*last_cmd)->next = NULL;
1181         last_comand_pointer = &((*last_cmd)->next);
1182         (*last_cmd)->type = JTAG_RESET;
1183
1184         (*last_cmd)->cmd.reset = cmd_queue_alloc(sizeof(reset_command_t));
1185         (*last_cmd)->cmd.reset->trst = req_trst;
1186         (*last_cmd)->cmd.reset->srst = req_srst;
1187
1188         return ERROR_OK;
1189 }
1190
1191 void jtag_add_end_state(enum tap_state state)
1192 {
1193         cmd_queue_end_state = state;
1194         if ((cmd_queue_end_state == TAP_DRSHIFT)||(cmd_queue_end_state == TAP_IRSHIFT))
1195         {
1196                 LOG_ERROR("BUG: TAP_DRSHIFT/IRSHIFT can't be end state. Calling code should use a larger scan field");
1197         }
1198 }
1199
1200 int MINIDRIVER(interface_jtag_add_sleep)(u32 us)
1201 {
1202         jtag_command_t **last_cmd = jtag_get_last_command_p();
1203
1204         /* allocate memory for a new list member */
1205         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
1206         (*last_cmd)->next = NULL;
1207         last_comand_pointer = &((*last_cmd)->next);
1208         (*last_cmd)->type = JTAG_SLEEP;
1209
1210         (*last_cmd)->cmd.sleep = cmd_queue_alloc(sizeof(sleep_command_t));
1211         (*last_cmd)->cmd.sleep->us = us;
1212
1213         return ERROR_OK;
1214 }
1215
1216 void jtag_add_sleep(u32 us)
1217 {
1218         keep_alive(); /* we might be running on a very slow JTAG clk */
1219         int retval=interface_jtag_add_sleep(us);
1220         if (retval!=ERROR_OK)
1221                 jtag_error=retval;
1222         return;
1223 }
1224
1225 int jtag_scan_size(scan_command_t *cmd)
1226 {
1227         int bit_count = 0;
1228         int i;
1229
1230         /* count bits in scan command */
1231         for (i = 0; i < cmd->num_fields; i++)
1232         {
1233                 bit_count += cmd->fields[i].num_bits;
1234         }
1235
1236         return bit_count;
1237 }
1238
1239 int jtag_build_buffer(scan_command_t *cmd, u8 **buffer)
1240 {
1241         int bit_count = 0;
1242         int i;
1243
1244         bit_count = jtag_scan_size(cmd);
1245         *buffer = malloc(CEIL(bit_count, 8));
1246
1247         bit_count = 0;
1248
1249         for (i = 0; i < cmd->num_fields; i++)
1250         {
1251                 if (cmd->fields[i].out_value)
1252                 {
1253 #ifdef _DEBUG_JTAG_IO_
1254                         char* char_buf = buf_to_str(cmd->fields[i].out_value, (cmd->fields[i].num_bits > 64) ? 64 : cmd->fields[i].num_bits, 16);
1255 #endif
1256                         buf_set_buf(cmd->fields[i].out_value, 0, *buffer, bit_count, cmd->fields[i].num_bits);
1257 #ifdef _DEBUG_JTAG_IO_
1258                         LOG_DEBUG("fields[%i].out_value: 0x%s", i, char_buf);
1259                         free(char_buf);
1260 #endif
1261                 }
1262
1263                 bit_count += cmd->fields[i].num_bits;
1264         }
1265
1266         return bit_count;
1267 }
1268
1269 int jtag_read_buffer(u8 *buffer, scan_command_t *cmd)
1270 {
1271         int i;
1272         int bit_count = 0;
1273         int retval;
1274
1275         /* we return ERROR_OK, unless a check fails, or a handler reports a problem */
1276         retval = ERROR_OK;
1277
1278         for (i = 0; i < cmd->num_fields; i++)
1279         {
1280                 /* if neither in_value nor in_handler
1281                  * are specified we don't have to examine this field
1282                  */
1283                 if (cmd->fields[i].in_value || cmd->fields[i].in_handler)
1284                 {
1285                         int num_bits = cmd->fields[i].num_bits;
1286                         u8 *captured = buf_set_buf(buffer, bit_count, malloc(CEIL(num_bits, 8)), 0, num_bits);
1287
1288 #ifdef _DEBUG_JTAG_IO_
1289                         char *char_buf;
1290
1291                         char_buf = buf_to_str(captured, (num_bits > 64) ? 64 : num_bits, 16);
1292                         LOG_DEBUG("fields[%i].in_value: 0x%s", i, char_buf);
1293                         free(char_buf);
1294 #endif
1295
1296                         if (cmd->fields[i].in_value)
1297                         {
1298                                 buf_cpy(captured, cmd->fields[i].in_value, num_bits);
1299
1300                                 if (cmd->fields[i].in_handler)
1301                                 {
1302                                         if (cmd->fields[i].in_handler(cmd->fields[i].in_value, cmd->fields[i].in_handler_priv, cmd->fields+i) != ERROR_OK)
1303                                         {
1304                                                 LOG_WARNING("in_handler reported a failed check");
1305                                                 retval = ERROR_JTAG_QUEUE_FAILED;
1306                                         }
1307                                 }
1308                         }
1309
1310                         /* no in_value specified, but a handler takes care of the scanned data */
1311                         if (cmd->fields[i].in_handler && (!cmd->fields[i].in_value))
1312                         {
1313                                 if (cmd->fields[i].in_handler(captured, cmd->fields[i].in_handler_priv, cmd->fields+i) != ERROR_OK)
1314                                 {
1315                                         /* We're going to call the error:handler later, but if the in_handler
1316                                          * reported an error we report this failure upstream
1317                                          */
1318                                         LOG_WARNING("in_handler reported a failed check");
1319                                         retval = ERROR_JTAG_QUEUE_FAILED;
1320                                 }
1321                         }
1322
1323                         free(captured);
1324                 }
1325                 bit_count += cmd->fields[i].num_bits;
1326         }
1327
1328         return retval;
1329 }
1330
1331 int jtag_check_value(u8 *captured, void *priv, scan_field_t *field)
1332 {
1333         int retval = ERROR_OK;
1334         int num_bits = field->num_bits;
1335
1336         int compare_failed = 0;
1337
1338         if (field->in_check_mask)
1339                 compare_failed = buf_cmp_mask(captured, field->in_check_value, field->in_check_mask, num_bits);
1340         else
1341                 compare_failed = buf_cmp(captured, field->in_check_value, num_bits);
1342
1343         if (compare_failed){
1344                 /* An error handler could have caught the failing check
1345                  * only report a problem when there wasn't a handler, or if the handler
1346                  * acknowledged the error
1347                  */
1348                 LOG_WARNING("TAP %s:",
1349                                         (field->tap == NULL) ? "(unknown)" : field->tap->dotted_name );
1350                 if (compare_failed)
1351                 {
1352                         char *captured_char = buf_to_str(captured, (num_bits > 64) ? 64 : num_bits, 16);
1353                         char *in_check_value_char = buf_to_str(field->in_check_value, (num_bits > 64) ? 64 : num_bits, 16);
1354
1355                         if (field->in_check_mask)
1356                         {
1357                                 char *in_check_mask_char;
1358                                 in_check_mask_char = buf_to_str(field->in_check_mask, (num_bits > 64) ? 64 : num_bits, 16);
1359                                 LOG_WARNING("value captured during scan didn't pass the requested check:");
1360                                 LOG_WARNING("captured: 0x%s check_value: 0x%s check_mask: 0x%s",
1361                                                         captured_char, in_check_value_char, in_check_mask_char);
1362                                 free(in_check_mask_char);
1363                         }
1364                         else
1365                         {
1366                                 LOG_WARNING("value captured during scan didn't pass the requested check: captured: 0x%s check_value: 0x%s", captured_char, in_check_value_char);
1367                         }
1368
1369                         free(captured_char);
1370                         free(in_check_value_char);
1371
1372                         retval = ERROR_JTAG_QUEUE_FAILED;
1373                 }
1374
1375         }
1376         return retval;
1377 }
1378
1379 /*
1380   set up checking of this field using the in_handler. The values passed in must be valid until
1381   after jtag_execute() has completed.
1382  */
1383 void jtag_set_check_value(scan_field_t *field, u8 *value, u8 *mask, error_handler_t *in_error_handler)
1384 {
1385         if (value)
1386                 field->in_handler = jtag_check_value;
1387         else
1388                 field->in_handler = NULL;       /* No check, e.g. embeddedice uses value==NULL to indicate no check */
1389         field->in_handler_priv = NULL;
1390         field->in_check_value = value;
1391         field->in_check_mask = mask;
1392 }
1393
1394 enum scan_type jtag_scan_type(scan_command_t *cmd)
1395 {
1396         int i;
1397         int type = 0;
1398
1399         for (i = 0; i < cmd->num_fields; i++)
1400         {
1401                 if (cmd->fields[i].in_value || cmd->fields[i].in_handler)
1402                         type |= SCAN_IN;
1403                 if (cmd->fields[i].out_value)
1404                         type |= SCAN_OUT;
1405         }
1406
1407         return type;
1408 }
1409
1410 int MINIDRIVER(interface_jtag_execute_queue)(void)
1411 {
1412         int retval;
1413
1414         if (jtag==NULL)
1415         {
1416                 LOG_ERROR("No JTAG interface configured yet. Issue 'init' command in startup scripts before communicating with targets.");
1417                 return ERROR_FAIL;
1418         }
1419
1420         retval = jtag->execute_queue();
1421
1422         cmd_queue_free();
1423
1424         jtag_command_queue = NULL;
1425         last_comand_pointer = &jtag_command_queue;
1426
1427         return retval;
1428 }
1429
1430 int jtag_execute_queue(void)
1431 {
1432         int retval=interface_jtag_execute_queue();
1433         if (retval==ERROR_OK)
1434         {
1435                 retval=jtag_error;
1436         }
1437         jtag_error=ERROR_OK;
1438         return retval;
1439 }
1440
1441 int jtag_reset_callback(enum jtag_event event, void *priv)
1442 {
1443         jtag_tap_t *tap = priv;
1444
1445         LOG_DEBUG("-");
1446
1447         if (event == JTAG_TRST_ASSERTED)
1448         {
1449                 buf_set_ones(tap->cur_instr, tap->ir_length);
1450                 tap->bypass = 1;
1451         }
1452
1453         return ERROR_OK;
1454 }
1455
1456 void jtag_sleep(u32 us)
1457 {
1458         alive_sleep(us/1000);
1459 }
1460
1461 /* Try to examine chain layout according to IEEE 1149.1 Â§12
1462  */
1463 int jtag_examine_chain(void)
1464 {
1465         jtag_tap_t *tap;
1466         scan_field_t field;
1467         u8 idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
1468         int i;
1469         int bit_count;
1470         int device_count = 0;
1471         u8 zero_check = 0x0;
1472         u8 one_check = 0xff;
1473
1474         field.tap = NULL;
1475         field.num_bits = sizeof(idcode_buffer) * 8;
1476         field.out_value = idcode_buffer;
1477         field.out_mask = NULL;
1478         field.in_value = idcode_buffer;
1479         field.in_check_value = NULL;
1480         field.in_check_mask = NULL;
1481         field.in_handler = NULL;
1482         field.in_handler_priv = NULL;
1483
1484         for (i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
1485         {
1486                 buf_set_u32(idcode_buffer, i * 32, 32, 0x000000FF);
1487         }
1488
1489         jtag_add_plain_dr_scan(1, &field, TAP_RESET);
1490         jtag_execute_queue();
1491
1492         for (i = 0; i < JTAG_MAX_CHAIN_SIZE * 4; i++)
1493         {
1494                 zero_check |= idcode_buffer[i];
1495                 one_check &= idcode_buffer[i];
1496         }
1497
1498         /* if there wasn't a single non-zero bit or if all bits were one, the scan isn't valid */
1499         if ((zero_check == 0x00) || (one_check == 0xff))
1500         {
1501                 LOG_ERROR("JTAG communication failure, check connection, JTAG interface, target power etc.");
1502                 return ERROR_JTAG_INIT_FAILED;
1503         }
1504
1505         // point at the 1st tap
1506         tap = jtag_NextEnabledTap(NULL);
1507         if( tap == NULL ){
1508                 LOG_ERROR("JTAG: No taps enabled?");
1509                 return ERROR_JTAG_INIT_FAILED;
1510         }
1511
1512         for (bit_count = 0; bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;)
1513         {
1514                 u32 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1515                 if ((idcode & 1) == 0)
1516                 {
1517                         /* LSB must not be 0, this indicates a device in bypass */
1518                         LOG_WARNING("Tap/Device does not have IDCODE");
1519                         idcode=0;
1520
1521                         bit_count += 1;
1522                 }
1523                 else
1524                 {
1525                         u32 manufacturer;
1526                         u32 part;
1527                         u32 version;
1528
1529                         if (idcode == 0x000000FF)
1530                         {
1531                                 int unexpected=0;
1532                                 /* End of chain (invalid manufacturer ID)
1533                                  *
1534                                  * The JTAG examine is the very first thing that happens
1535                                  *
1536                                  * A single JTAG device requires only 64 bits to be read back correctly.
1537                                  *
1538                                  * The code below adds a check that the rest of the data scanned (640 bits)
1539                                  * are all as expected. This helps diagnose/catch problems with the JTAG chain
1540                                  *
1541                                  * earlier and gives more helpful/explicit error messages.
1542                                  */
1543                                 for (bit_count += 32; bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;bit_count += 32)
1544                                 {
1545                                         idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1546                                         if (unexpected||(idcode != 0x000000FF))
1547                                         {
1548                                                 LOG_WARNING("Unexpected idcode after end of chain! %d 0x%08x", bit_count, idcode);
1549                                                 unexpected = 1;
1550                                         }
1551                                 }
1552
1553                                 break;
1554                         }
1555
1556 #define EXTRACT_MFG(X)  (((X) & 0xffe) >> 1)
1557                         manufacturer = EXTRACT_MFG(idcode);
1558 #define EXTRACT_PART(X) (((X) & 0xffff000) >> 12)
1559                         part = EXTRACT_PART(idcode);
1560 #define EXTRACT_VER(X)  (((X) & 0xf0000000) >> 28)
1561                         version = EXTRACT_VER(idcode);
1562
1563                         LOG_INFO("JTAG tap: %s tap/device found: 0x%8.8x (Manufacturer: 0x%3.3x, Part: 0x%4.4x, Version: 0x%1.1x)",
1564                                          ((tap != NULL) ? (tap->dotted_name) : "(not-named)"),
1565                                 idcode, manufacturer, part, version);
1566
1567                         bit_count += 32;
1568                 }
1569                 if (tap)
1570                 {
1571                         tap->idcode = idcode;
1572
1573                         if (tap->expected_ids_cnt > 0) {
1574                                 /* Loop over the expected identification codes and test for a match */
1575                                 u8 ii;
1576                                 for (ii = 0; ii < tap->expected_ids_cnt; ii++) {
1577                                         if( tap->idcode == tap->expected_ids[ii] ){
1578                                                 break;
1579                                         }
1580                                 }
1581
1582                                 /* If none of the expected ids matched, log an error */
1583                                 if (ii == tap->expected_ids_cnt) {
1584                                         LOG_ERROR("JTAG tap: %s             got: 0x%08x (mfg: 0x%3.3x, part: 0x%4.4x, ver: 0x%1.1x)",
1585                                                           tap->dotted_name,
1586                                                           idcode,
1587                                                           EXTRACT_MFG( tap->idcode ),
1588                                                           EXTRACT_PART( tap->idcode ),
1589                                                           EXTRACT_VER( tap->idcode ) );
1590                                         for (ii = 0; ii < tap->expected_ids_cnt; ii++) {
1591                                                 LOG_ERROR("JTAG tap: %s expected %hhu of %hhu: 0x%08x (mfg: 0x%3.3x, part: 0x%4.4x, ver: 0x%1.1x)",
1592                                                                   tap->dotted_name,
1593                                                                   ii + 1,
1594                                                                   tap->expected_ids_cnt,
1595                                                                   tap->expected_ids[ii],
1596                                                                   EXTRACT_MFG( tap->expected_ids[ii] ),
1597                                                                   EXTRACT_PART( tap->expected_ids[ii] ),
1598                                                                   EXTRACT_VER( tap->expected_ids[ii] ) );
1599                                         }
1600
1601                                         return ERROR_JTAG_INIT_FAILED;
1602                                 } else {
1603                                         LOG_INFO("JTAG Tap/device matched");
1604                                 }
1605                         } else {
1606 #if 0
1607                                 LOG_INFO("JTAG TAP ID: 0x%08x - Unknown - please report (A) chipname and (B) idcode to the openocd project",
1608                                                  tap->idcode);
1609 #endif
1610                         }
1611                         tap = jtag_NextEnabledTap(tap);
1612                 }
1613                 device_count++;
1614         }
1615
1616         /* see if number of discovered devices matches configuration */
1617         if (device_count != jtag_NumEnabledTaps())
1618         {
1619                 LOG_ERROR("number of discovered devices in JTAG chain (%i) doesn't match (enabled) configuration (%i), total taps: %d",
1620                                   device_count, jtag_NumEnabledTaps(), jtag_NumTotalTaps());
1621                 LOG_ERROR("check the config file and ensure proper JTAG communication (connections, speed, ...)");
1622                 return ERROR_JTAG_INIT_FAILED;
1623         }
1624
1625         return ERROR_OK;
1626 }
1627
1628 int jtag_validate_chain(void)
1629 {
1630         jtag_tap_t *tap;
1631         int total_ir_length = 0;
1632         u8 *ir_test = NULL;
1633         scan_field_t field;
1634         int chain_pos = 0;
1635
1636         tap = NULL;
1637         total_ir_length = 0;
1638         for(;;){
1639                 tap = jtag_NextEnabledTap(tap);
1640                 if( tap == NULL ){
1641                         break;
1642                 }
1643                 total_ir_length += tap->ir_length;
1644         }
1645
1646         total_ir_length += 2;
1647         ir_test = malloc(CEIL(total_ir_length, 8));
1648         buf_set_ones(ir_test, total_ir_length);
1649
1650         field.tap = NULL;
1651         field.num_bits = total_ir_length;
1652         field.out_value = ir_test;
1653         field.out_mask = NULL;
1654         field.in_value = ir_test;
1655         field.in_check_value = NULL;
1656         field.in_check_mask = NULL;
1657         field.in_handler = NULL;
1658         field.in_handler_priv = NULL;
1659
1660         jtag_add_plain_ir_scan(1, &field, TAP_RESET);
1661         jtag_execute_queue();
1662
1663         tap = NULL;
1664         chain_pos = 0;
1665         for(;;){
1666                 tap = jtag_NextEnabledTap(tap);
1667                 if( tap == NULL ){
1668                         break;
1669                 }
1670
1671
1672                 if (buf_get_u32(ir_test, chain_pos, 2) != 0x1)
1673                 {
1674                         char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1675                         LOG_ERROR("Error validating JTAG scan chain, IR mismatch, scan returned 0x%s", cbuf);
1676                         free(cbuf);
1677                         free(ir_test);
1678                         return ERROR_JTAG_INIT_FAILED;
1679                 }
1680                 chain_pos += tap->ir_length;
1681         }
1682
1683         if (buf_get_u32(ir_test, chain_pos, 2) != 0x3)
1684         {
1685                 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1686                 LOG_ERROR("Error validating JTAG scan chain, IR mismatch, scan returned 0x%s", cbuf);
1687                 free(cbuf);
1688                 free(ir_test);
1689                 return ERROR_JTAG_INIT_FAILED;
1690         }
1691
1692         free(ir_test);
1693
1694         return ERROR_OK;
1695 }
1696
1697 enum jtag_tap_cfg_param {
1698         JCFG_EVENT
1699 };
1700
1701 static Jim_Nvp nvp_config_opts[] = {
1702         { .name = "-event",      .value = JCFG_EVENT },
1703
1704         { .name = NULL,          .value = -1 }
1705 };
1706
1707 static int
1708 jtag_tap_configure_cmd( Jim_GetOptInfo *goi,
1709                 jtag_tap_t * tap)
1710 {
1711         Jim_Nvp *n;
1712         Jim_Obj *o;
1713         int e;
1714
1715         /* parse config or cget options */
1716         while (goi->argc > 0) {
1717                 Jim_SetEmptyResult (goi->interp);
1718
1719                 e = Jim_GetOpt_Nvp(goi, nvp_config_opts, &n);
1720                 if (e != JIM_OK) {
1721                         Jim_GetOpt_NvpUnknown(goi, nvp_config_opts, 0);
1722                         return e;
1723                 }
1724
1725                 switch (n->value) {
1726                         case JCFG_EVENT:
1727                                 if (goi->argc == 0) {
1728                                         Jim_WrongNumArgs( goi->interp, goi->argc, goi->argv, "-event ?event-name? ..." );
1729                                         return JIM_ERR;
1730                                 }
1731
1732                                 e = Jim_GetOpt_Nvp( goi, nvp_jtag_tap_event, &n );
1733                                 if (e != JIM_OK) {
1734                                         Jim_GetOpt_NvpUnknown(goi, nvp_jtag_tap_event, 1);
1735                                         return e;
1736                                 }
1737
1738                                 if (goi->isconfigure) {
1739                                         if (goi->argc != 1) {
1740                                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name? ?EVENT-BODY?");
1741                                                 return JIM_ERR;
1742                                         }
1743                                 } else {
1744                                         if (goi->argc != 0) {
1745                                                 Jim_WrongNumArgs(goi->interp, goi->argc, goi->argv, "-event ?event-name?");
1746                                                 return JIM_ERR;
1747                                         }
1748                                 }
1749
1750                                 {
1751                                         jtag_tap_event_action_t *jteap;
1752
1753                                         jteap = tap->event_action;
1754                                         /* replace existing? */
1755                                         while (jteap) {
1756                                                 if (jteap->event == n->value) {
1757                                                         break;
1758                                                 }
1759                                                 jteap = jteap->next;
1760                                         }
1761
1762                                         if (goi->isconfigure) {
1763                                                 if (jteap == NULL) {
1764                                                         /* create new */
1765                                                         jteap = calloc(1, sizeof (*jteap));
1766                                                 }
1767                                                 jteap->event = n->value;
1768                                                 Jim_GetOpt_Obj( goi, &o);
1769                                                 if (jteap->body) {
1770                                                         Jim_DecrRefCount(interp, jteap->body);
1771                                                 }
1772                                                 jteap->body = Jim_DuplicateObj(goi->interp, o);
1773                                                 Jim_IncrRefCount(jteap->body);
1774
1775                                                 /* add to head of event list */
1776                                                 jteap->next = tap->event_action;
1777                                                 tap->event_action = jteap;
1778                                                 Jim_SetEmptyResult(goi->interp);
1779                                         } else {
1780                                                 /* get */
1781                                                 if (jteap == NULL) {
1782                                                         Jim_SetEmptyResult(goi->interp);
1783                                                 } else {
1784                                                         Jim_SetResult(goi->interp, Jim_DuplicateObj(goi->interp, jteap->body));
1785                                                 }
1786                                         }
1787                                 }
1788                                 /* loop for more */
1789                                 break;
1790                 }
1791         } /* while (goi->argc) */
1792
1793         return JIM_OK;
1794 }
1795
1796 static int jim_newtap_cmd( Jim_GetOptInfo *goi )
1797 {
1798         jtag_tap_t *pTap;
1799         jtag_tap_t **ppTap;
1800         jim_wide w;
1801         int x;
1802         int e;
1803         int reqbits;
1804         Jim_Nvp *n;
1805         char *cp;
1806         const Jim_Nvp opts[] = {
1807 #define NTAP_OPT_IRLEN     0
1808                 { .name = "-irlen"                      ,       .value = NTAP_OPT_IRLEN },
1809 #define NTAP_OPT_IRMASK    1
1810                 { .name = "-irmask"                     ,       .value = NTAP_OPT_IRMASK },
1811 #define NTAP_OPT_IRCAPTURE 2
1812                 { .name = "-ircapture"          ,       .value = NTAP_OPT_IRCAPTURE },
1813 #define NTAP_OPT_ENABLED   3
1814                 { .name = "-enable"                     ,       .value = NTAP_OPT_ENABLED },
1815 #define NTAP_OPT_DISABLED  4
1816                 { .name = "-disable"            ,       .value = NTAP_OPT_DISABLED },
1817 #define NTAP_OPT_EXPECTED_ID 5
1818                 { .name = "-expected-id"        ,       .value = NTAP_OPT_EXPECTED_ID },
1819                 { .name = NULL                          ,       .value = -1 },
1820         };
1821
1822         pTap = malloc( sizeof(jtag_tap_t) );
1823         memset( pTap, 0, sizeof(*pTap) );
1824         if( !pTap ){
1825                 Jim_SetResult_sprintf( goi->interp, "no memory");
1826                 return JIM_ERR;
1827         }
1828         /*
1829          * we expect CHIP + TAP + OPTIONS
1830          * */
1831         if( goi->argc < 3 ){
1832                 Jim_SetResult_sprintf(goi->interp, "Missing CHIP TAP OPTIONS ....");
1833                 return JIM_ERR;
1834         }
1835         Jim_GetOpt_String( goi, &cp, NULL );
1836         pTap->chip = strdup(cp);
1837
1838         Jim_GetOpt_String( goi, &cp, NULL );
1839         pTap->tapname = strdup(cp);
1840
1841         /* name + dot + name + null */
1842         x = strlen(pTap->chip) + 1 + strlen(pTap->tapname) + 1;
1843         cp = malloc( x );
1844         sprintf( cp, "%s.%s", pTap->chip, pTap->tapname );
1845         pTap->dotted_name = cp;
1846
1847         LOG_DEBUG("Creating New Tap, Chip: %s, Tap: %s, Dotted: %s, %d params",
1848                           pTap->chip, pTap->tapname, pTap->dotted_name, goi->argc);
1849
1850         /* default is enabled */
1851         pTap->enabled = 1;
1852
1853         /* deal with options */
1854 #define NTREQ_IRLEN      1
1855 #define NTREQ_IRCAPTURE  2
1856 #define NTREQ_IRMASK     4
1857
1858         /* clear them as we find them */
1859         reqbits = (NTREQ_IRLEN | NTREQ_IRCAPTURE | NTREQ_IRMASK);
1860
1861         while( goi->argc ){
1862                 e = Jim_GetOpt_Nvp( goi, opts, &n );
1863                 if( e != JIM_OK ){
1864                         Jim_GetOpt_NvpUnknown( goi, opts, 0 );
1865                         return e;
1866                 }
1867                 LOG_DEBUG("Processing option: %s", n->name );
1868                 switch( n->value ){
1869                 case NTAP_OPT_ENABLED:
1870                         pTap->enabled = 1;
1871                         break;
1872                 case NTAP_OPT_DISABLED:
1873                         pTap->enabled = 0;
1874                         break;
1875                 case NTAP_OPT_EXPECTED_ID:
1876                 {
1877                         u32 *new_expected_ids;
1878
1879                         e = Jim_GetOpt_Wide( goi, &w );
1880                         if( e != JIM_OK) {
1881                                 Jim_SetResult_sprintf(goi->interp, "option: %s bad parameter", n->name);
1882                                 return e;
1883                         }
1884
1885                         new_expected_ids = malloc(sizeof(u32) * (pTap->expected_ids_cnt + 1));
1886                         if (new_expected_ids == NULL) {
1887                                 Jim_SetResult_sprintf( goi->interp, "no memory");
1888                                 return JIM_ERR;
1889                         }
1890
1891                         memcpy(new_expected_ids, pTap->expected_ids, sizeof(u32) * pTap->expected_ids_cnt);
1892
1893                         new_expected_ids[pTap->expected_ids_cnt] = w;
1894
1895                         free(pTap->expected_ids);
1896                         pTap->expected_ids = new_expected_ids;
1897                         pTap->expected_ids_cnt++;
1898                         break;
1899                 }
1900                 case NTAP_OPT_IRLEN:
1901                 case NTAP_OPT_IRMASK:
1902                 case NTAP_OPT_IRCAPTURE:
1903                         e = Jim_GetOpt_Wide( goi, &w );
1904                         if( e != JIM_OK ){
1905                                 Jim_SetResult_sprintf( goi->interp, "option: %s bad parameter", n->name );
1906                                 return e;
1907                         }
1908                         if( (w < 0) || (w > 0xffff) ){
1909                                 /* wacky value */
1910                                 Jim_SetResult_sprintf( goi->interp, "option: %s - wacky value: %d (0x%x)",
1911                                                                            n->name, (int)(w), (int)(w));
1912                                 return JIM_ERR;
1913                         }
1914                         switch(n->value){
1915                         case NTAP_OPT_IRLEN:
1916                                 pTap->ir_length = w;
1917                                 reqbits &= (~(NTREQ_IRLEN));
1918                                 break;
1919                         case NTAP_OPT_IRMASK:
1920                                 pTap->ir_capture_mask = w;
1921                                 reqbits &= (~(NTREQ_IRMASK));
1922                                 break;
1923                         case NTAP_OPT_IRCAPTURE:
1924                                 pTap->ir_capture_value = w;
1925                                 reqbits &= (~(NTREQ_IRCAPTURE));
1926                                 break;
1927                         }
1928                 } /* switch(n->value) */
1929         } /* while( goi->argc ) */
1930
1931         /* Did we get all the options? */
1932         if( reqbits ){
1933                 // no
1934                 Jim_SetResult_sprintf( goi->interp,
1935                                                            "newtap: %s missing required parameters",
1936                                                            pTap->dotted_name);
1937                 /* TODO: Tell user what is missing :-( */
1938                 /* no memory leaks pelase */
1939                 free(((void *)(pTap->expected_ids)));
1940                 free(((void *)(pTap->chip)));
1941                 free(((void *)(pTap->tapname)));
1942                 free(((void *)(pTap->dotted_name)));
1943                 free(((void *)(pTap)));
1944                 return JIM_ERR;
1945         }
1946
1947         pTap->expected      = malloc( pTap->ir_length );
1948         pTap->expected_mask = malloc( pTap->ir_length );
1949         pTap->cur_instr     = malloc( pTap->ir_length );
1950
1951         buf_set_u32( pTap->expected,
1952                                  0,
1953                                  pTap->ir_length,
1954                                  pTap->ir_capture_value );
1955         buf_set_u32( pTap->expected_mask,
1956                                  0,
1957                                  pTap->ir_length,
1958                                  pTap->ir_capture_mask );
1959         buf_set_ones( pTap->cur_instr,
1960                                   pTap->ir_length );
1961
1962         pTap->bypass = 1;
1963
1964         jtag_register_event_callback(jtag_reset_callback, pTap );
1965
1966         ppTap = &(jtag_all_taps);
1967         while( (*ppTap) != NULL ){
1968                 ppTap = &((*ppTap)->next_tap);
1969         }
1970         *ppTap = pTap;
1971         {
1972                 static int n_taps = 0;
1973                 pTap->abs_chain_position = n_taps++;
1974         }
1975         LOG_DEBUG( "Created Tap: %s @ abs position %d, irlen %d, capture: 0x%x mask: 0x%x",
1976                                 (*ppTap)->dotted_name,
1977                                 (*ppTap)->abs_chain_position,
1978                                 (*ppTap)->ir_length,
1979                                 (*ppTap)->ir_capture_value,
1980                                 (*ppTap)->ir_capture_mask );
1981
1982         return ERROR_OK;
1983 }
1984
1985 static int jim_jtag_command( Jim_Interp *interp, int argc, Jim_Obj *const *argv )
1986 {
1987         Jim_GetOptInfo goi;
1988         int e;
1989         Jim_Nvp *n;
1990         Jim_Obj *o;
1991         struct command_context_s *context;
1992
1993         enum {
1994                 JTAG_CMD_INTERFACE,
1995                 JTAG_CMD_INIT_RESET,
1996                 JTAG_CMD_NEWTAP,
1997                 JTAG_CMD_TAPENABLE,
1998                 JTAG_CMD_TAPDISABLE,
1999                 JTAG_CMD_TAPISENABLED,
2000                 JTAG_CMD_CONFIGURE,
2001                 JTAG_CMD_CGET
2002         };
2003
2004         const Jim_Nvp jtag_cmds[] = {
2005                 { .name = "interface"     , .value = JTAG_CMD_INTERFACE },
2006                 { .name = "arp_init-reset", .value = JTAG_CMD_INIT_RESET },
2007                 { .name = "newtap"        , .value = JTAG_CMD_NEWTAP },
2008                 { .name = "tapisenabled"     , .value = JTAG_CMD_TAPISENABLED },
2009                 { .name = "tapenable"     , .value = JTAG_CMD_TAPENABLE },
2010                 { .name = "tapdisable"    , .value = JTAG_CMD_TAPDISABLE },
2011                 { .name = "configure"     , .value = JTAG_CMD_CONFIGURE },
2012                 { .name = "cget"          , .value = JTAG_CMD_CGET },
2013
2014                 { .name = NULL, .value = -1 },
2015         };
2016
2017         context = Jim_GetAssocData(interp, "context");
2018         /* go past the command */
2019         Jim_GetOpt_Setup( &goi, interp, argc-1, argv+1 );
2020
2021         e = Jim_GetOpt_Nvp( &goi, jtag_cmds, &n );
2022         if( e != JIM_OK ){
2023                 Jim_GetOpt_NvpUnknown( &goi, jtag_cmds, 0 );
2024                 return e;
2025         }
2026                 Jim_SetEmptyResult( goi.interp );
2027         switch( n->value ){
2028         case JTAG_CMD_INTERFACE:
2029                 /* return the name of the interface */
2030                 /* TCL code might need to know the exact type... */
2031                 /* FUTURE: we allow this as a means to "set" the interface. */
2032                 if( goi.argc != 0 ){
2033                         Jim_WrongNumArgs( goi.interp, 1, goi.argv-1, "(no params)");
2034                         return JIM_ERR;
2035                 }
2036                 Jim_SetResultString( goi.interp, jtag_interface->name, -1 );
2037                 return JIM_OK;
2038         case JTAG_CMD_INIT_RESET:
2039                 if( goi.argc != 0 ){
2040                         Jim_WrongNumArgs( goi.interp, 1, goi.argv-1, "(no params)");
2041                         return JIM_ERR;
2042                 }
2043                 e = jtag_init_reset(context);
2044                 if( e != ERROR_OK ){
2045                         Jim_SetResult_sprintf( goi.interp, "error: %d", e);
2046                         return JIM_ERR;
2047                 }
2048                 return JIM_OK;
2049         case JTAG_CMD_NEWTAP:
2050                 return jim_newtap_cmd( &goi );
2051                 break;
2052         case JTAG_CMD_TAPISENABLED:
2053         case JTAG_CMD_TAPENABLE:
2054         case JTAG_CMD_TAPDISABLE:
2055                 if( goi.argc != 1 ){
2056                         Jim_SetResultString( goi.interp, "Too many parameters",-1 );
2057                         return JIM_ERR;
2058                 }
2059
2060                 {
2061                         jtag_tap_t *t;
2062                         t = jtag_TapByJimObj( goi.interp, goi.argv[0] );
2063                         if( t == NULL ){
2064                                 return JIM_ERR;
2065                         }
2066                         switch( n->value ){
2067                         case JTAG_CMD_TAPISENABLED:
2068                                 // below
2069                                 break;
2070                         case JTAG_CMD_TAPENABLE:
2071                                 jtag_tap_handle_event( t, JTAG_TAP_EVENT_ENABLE);
2072                                 e = 1;
2073                                 t->enabled = e;
2074                                 break;
2075                         case JTAG_CMD_TAPDISABLE:
2076                                 jtag_tap_handle_event( t, JTAG_TAP_EVENT_DISABLE);
2077                                 e = 0;
2078                                 t->enabled = e;
2079                                 break;
2080                         }
2081                         Jim_SetResult( goi.interp, Jim_NewIntObj( goi.interp, e ) );
2082                         return JIM_OK;
2083                 }
2084                 break;
2085
2086         case JTAG_CMD_CGET:
2087                 if( goi.argc < 2 ){
2088                         Jim_WrongNumArgs( goi.interp, 0, NULL, "?tap-name? -option ...");
2089                         return JIM_ERR;
2090                 }
2091
2092                 {
2093                         jtag_tap_t *t;
2094
2095                         Jim_GetOpt_Obj(&goi, &o);
2096                         t = jtag_TapByJimObj( goi.interp, o );
2097                         if( t == NULL ){
2098                                 return JIM_ERR;
2099                         }
2100
2101                         goi.isconfigure = 0;
2102                         return jtag_tap_configure_cmd( &goi, t);
2103                 }
2104                 break;
2105
2106         case JTAG_CMD_CONFIGURE:
2107                 if( goi.argc < 3 ){
2108                         Jim_WrongNumArgs( goi.interp, 0, NULL, "?tap-name? -option ?VALUE? ...");
2109                         return JIM_ERR;
2110                 }
2111
2112                 {
2113                         jtag_tap_t *t;
2114
2115                         Jim_GetOpt_Obj(&goi, &o);
2116                         t = jtag_TapByJimObj( goi.interp, o );
2117                         if( t == NULL ){
2118                                 return JIM_ERR;
2119                         }
2120
2121                         goi.isconfigure = 1;
2122                         return jtag_tap_configure_cmd( &goi, t);
2123                 }
2124         }
2125
2126         return JIM_ERR;
2127 }
2128
2129 int jtag_register_commands(struct command_context_s *cmd_ctx)
2130 {
2131         register_jim( cmd_ctx, "jtag", jim_jtag_command, "perform jtag tap actions");
2132
2133         register_command(cmd_ctx, NULL, "interface", handle_interface_command,
2134                 COMMAND_CONFIG, "try to configure interface");
2135         register_command(cmd_ctx, NULL, "jtag_speed", handle_jtag_speed_command,
2136                 COMMAND_ANY, "set jtag speed (if supported)");
2137         register_command(cmd_ctx, NULL, "jtag_khz", handle_jtag_khz_command,
2138                 COMMAND_ANY, "same as jtag_speed, except it takes maximum khz as arguments. 0 KHz = RTCK.");
2139         register_command(cmd_ctx, NULL, "jtag_device", handle_jtag_device_command,
2140                 COMMAND_CONFIG, "jtag_device <ir_length> <ir_expected> <ir_mask>");
2141         register_command(cmd_ctx, NULL, "reset_config", handle_reset_config_command,
2142                 COMMAND_CONFIG, NULL);
2143         register_command(cmd_ctx, NULL, "jtag_nsrst_delay", handle_jtag_nsrst_delay_command,
2144                 COMMAND_ANY, "jtag_nsrst_delay <ms> - delay after deasserting srst in ms");
2145         register_command(cmd_ctx, NULL, "jtag_ntrst_delay", handle_jtag_ntrst_delay_command,
2146                 COMMAND_ANY, "jtag_ntrst_delay <ms> - delay after deasserting trst in ms");
2147
2148         register_command(cmd_ctx, NULL, "scan_chain", handle_scan_chain_command,
2149                 COMMAND_EXEC, "print current scan chain configuration");
2150
2151         register_command(cmd_ctx, NULL, "endstate", handle_endstate_command,
2152                 COMMAND_EXEC, "finish JTAG operations in <tap_state>");
2153         register_command(cmd_ctx, NULL, "jtag_reset", handle_jtag_reset_command,
2154                 COMMAND_EXEC, "toggle reset lines <trst> <srst>");
2155         register_command(cmd_ctx, NULL, "runtest", handle_runtest_command,
2156                 COMMAND_EXEC, "move to Run-Test/Idle, and execute <num_cycles>");
2157         register_command(cmd_ctx, NULL, "irscan", handle_irscan_command,
2158                 COMMAND_EXEC, "execute IR scan <device> <instr> [dev2] [instr2] ...");
2159         register_jim(cmd_ctx, "drscan", Jim_Command_drscan, "execute DR scan <device> <num_bits> <value> <num_bits1> <value2> ...");
2160
2161         register_command(cmd_ctx, NULL, "verify_ircapture", handle_verify_ircapture_command,
2162                 COMMAND_ANY, "verify value captured during Capture-IR <enable|disable>");
2163         return ERROR_OK;
2164 }
2165
2166 int jtag_interface_init(struct command_context_s *cmd_ctx)
2167 {
2168         if (jtag)
2169                 return ERROR_OK;
2170
2171         if (!jtag_interface)
2172         {
2173                 /* nothing was previously specified by "interface" command */
2174                 LOG_ERROR("JTAG interface has to be specified, see \"interface\" command");
2175                 return ERROR_JTAG_INVALID_INTERFACE;
2176         }
2177         if(hasKHz)
2178         {
2179                 jtag_interface->khz(speed_khz, &jtag_speed);
2180                 hasKHz = 0;
2181         }
2182
2183         if (jtag_interface->init() != ERROR_OK)
2184                 return ERROR_JTAG_INIT_FAILED;
2185
2186         jtag = jtag_interface;
2187         return ERROR_OK;
2188 }
2189
2190 static int jtag_init_inner(struct command_context_s *cmd_ctx)
2191 {
2192         jtag_tap_t *tap;
2193         int retval;
2194
2195         LOG_DEBUG("Init JTAG chain");
2196
2197         tap = jtag_NextEnabledTap(NULL);
2198         if( tap == NULL ){
2199                 LOG_ERROR("There are no enabled taps?");
2200                 return ERROR_JTAG_INIT_FAILED;
2201         }
2202
2203         jtag_add_tlr();
2204         if ((retval=jtag_execute_queue())!=ERROR_OK)
2205                 return retval;
2206
2207         /* examine chain first, as this could discover the real chain layout */
2208         if (jtag_examine_chain() != ERROR_OK)
2209         {
2210                 LOG_ERROR("trying to validate configured JTAG chain anyway...");
2211         }
2212
2213         if (jtag_validate_chain() != ERROR_OK)
2214         {
2215                 LOG_ERROR("Could not validate JTAG chain, continuing anyway...");
2216         }
2217
2218         return ERROR_OK;
2219 }
2220
2221 int jtag_init_reset(struct command_context_s *cmd_ctx)
2222 {
2223         int retval;
2224
2225         if ((retval=jtag_interface_init(cmd_ctx)) != ERROR_OK)
2226                 return retval;
2227
2228         LOG_DEBUG("Trying to bring the JTAG controller to life by asserting TRST / RESET");
2229
2230         /* Reset can happen after a power cycle.
2231          *
2232          * Ideally we would only assert TRST or run RESET before the target reset.
2233          *
2234          * However w/srst_pulls_trst, trst is asserted together with the target
2235          * reset whether we want it or not.
2236          *
2237          * NB! Some targets have JTAG circuitry disabled until a
2238          * trst & srst has been asserted.
2239          *
2240          * NB! here we assume nsrst/ntrst delay are sufficient!
2241          *
2242          * NB! order matters!!!! srst *can* disconnect JTAG circuitry
2243          *
2244          */
2245         jtag_add_reset(1, 0); /* RESET or TRST */
2246         if (jtag_reset_config & RESET_HAS_SRST)
2247         {
2248                 jtag_add_reset(1, 1);
2249                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST)==0)
2250                         jtag_add_reset(0, 1);
2251         }
2252         jtag_add_reset(0, 0);
2253         if ((retval = jtag_execute_queue()) != ERROR_OK)
2254                 return retval;
2255
2256         /* Check that we can communication on the JTAG chain + eventually we want to
2257          * be able to perform enumeration only after OpenOCD has started
2258          * telnet and GDB server
2259          *
2260          * That would allow users to more easily perform any magic they need to before
2261          * reset happens.
2262          */
2263         return jtag_init_inner(cmd_ctx);
2264 }
2265
2266 int jtag_init(struct command_context_s *cmd_ctx)
2267 {
2268         int retval;
2269         if ((retval=jtag_interface_init(cmd_ctx)) != ERROR_OK)
2270                 return retval;
2271         if (jtag_init_inner(cmd_ctx)==ERROR_OK)
2272         {
2273                 return ERROR_OK;
2274         }
2275         return jtag_init_reset(cmd_ctx);
2276 }
2277
2278 static int default_khz(int khz, int *jtag_speed)
2279 {
2280         LOG_ERROR("Translation from khz to jtag_speed not implemented");
2281         return ERROR_FAIL;
2282 }
2283
2284 static int default_speed_div(int speed, int *khz)
2285 {
2286         LOG_ERROR("Translation from jtag_speed to khz not implemented");
2287         return ERROR_FAIL;
2288 }
2289
2290 static int default_power_dropout(int *dropout)
2291 {
2292         *dropout=0; /* by default we can't detect power dropout */
2293         return ERROR_OK;
2294 }
2295
2296 static int default_srst_asserted(int *srst_asserted)
2297 {
2298         *srst_asserted=0; /* by default we can't detect srst asserted */
2299         return ERROR_OK;
2300 }
2301
2302 int handle_interface_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2303 {
2304         int i;
2305         int retval;
2306
2307         /* check whether the interface is already configured */
2308         if (jtag_interface)
2309         {
2310                 LOG_WARNING("Interface already configured, ignoring");
2311                 return ERROR_OK;
2312         }
2313
2314         /* interface name is a mandatory argument */
2315         if (argc < 1 || args[0][0] == '\0')
2316         {
2317                 return ERROR_COMMAND_SYNTAX_ERROR;
2318         }
2319
2320         for (i=0; jtag_interfaces[i]; i++)
2321         {
2322                 if (strcmp(args[0], jtag_interfaces[i]->name) == 0)
2323                 {
2324                         if ((retval = jtag_interfaces[i]->register_commands(cmd_ctx)) != ERROR_OK)
2325                         {
2326                                 return retval;
2327                         }
2328
2329                         jtag_interface = jtag_interfaces[i];
2330
2331                         if (jtag_interface->khz == NULL)
2332                         {
2333                                 jtag_interface->khz = default_khz;
2334                         }
2335                         if (jtag_interface->speed_div == NULL)
2336                         {
2337                                 jtag_interface->speed_div = default_speed_div;
2338                         }
2339                         if (jtag_interface->power_dropout == NULL)
2340                         {
2341                                 jtag_interface->power_dropout = default_power_dropout;
2342                         }
2343                         if (jtag_interface->srst_asserted == NULL)
2344                         {
2345                                 jtag_interface->srst_asserted = default_srst_asserted;
2346                         }
2347
2348                         return ERROR_OK;
2349                 }
2350         }
2351
2352         /* no valid interface was found (i.e. the configuration option,
2353          * didn't match one of the compiled-in interfaces
2354          */
2355         LOG_ERROR("No valid jtag interface found (%s)", args[0]);
2356         LOG_ERROR("compiled-in jtag interfaces:");
2357         for (i = 0; jtag_interfaces[i]; i++)
2358         {
2359                 LOG_ERROR("%i: %s", i, jtag_interfaces[i]->name);
2360         }
2361
2362         return ERROR_JTAG_INVALID_INTERFACE;
2363 }
2364
2365 int handle_jtag_device_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2366 {
2367         int e;
2368         char buf[1024];
2369         Jim_Obj *newargs[ 10 ];
2370         /*
2371          * CONVERT SYNTAX
2372          * argv[-1] = command
2373          * argv[ 0] = ir length
2374          * argv[ 1] = ir capture
2375          * argv[ 2] = ir mask
2376          * argv[ 3] = not actually used by anything but in the docs
2377          */
2378
2379         if( argc < 4 ){
2380                 command_print( cmd_ctx, "OLD DEPRECATED SYNTAX: Please use the NEW syntax");
2381                 return ERROR_OK;
2382         }
2383         command_print( cmd_ctx, "OLD SYNTAX: DEPRECATED - translating to new syntax");
2384         command_print( cmd_ctx, "jtag newtap CHIP TAP -irlen %s -ircapture %s -irvalue %s",
2385                                    args[0],
2386                                    args[1],
2387                                    args[2] );
2388         command_print( cmd_ctx, "Example: STM32 has 2 taps, the cortexM3(len4) + boundryscan(len5)");
2389         command_print( cmd_ctx, "jtag newtap stm32 cortexm3  ....., thus creating the tap: \"stm32.cortexm3\"");
2390         command_print( cmd_ctx, "jtag newtap stm32 boundry  ....., and the tap: \"stm32.boundery\"");
2391         command_print( cmd_ctx, "And then refer to the taps by the dotted name.");
2392
2393         newargs[0] = Jim_NewStringObj( interp, "jtag", -1   );
2394         newargs[1] = Jim_NewStringObj( interp, "newtap", -1 );
2395         sprintf( buf, "chip%d", jtag_NumTotalTaps() );
2396         newargs[2] = Jim_NewStringObj( interp, buf, -1 );
2397         sprintf( buf, "tap%d", jtag_NumTotalTaps() );
2398         newargs[3] = Jim_NewStringObj( interp, buf, -1  );
2399         newargs[4] = Jim_NewStringObj( interp, "-irlen", -1  );
2400         newargs[5] = Jim_NewStringObj( interp, args[0], -1  );
2401         newargs[6] = Jim_NewStringObj( interp, "-ircapture", -1  );
2402         newargs[7] = Jim_NewStringObj( interp, args[1], -1  );
2403         newargs[8] = Jim_NewStringObj( interp, "-irmask", -1  );
2404         newargs[9] = Jim_NewStringObj( interp, args[2], -1  );
2405
2406         command_print( cmd_ctx, "NEW COMMAND:");
2407         sprintf( buf, "%s %s %s %s %s %s %s %s %s %s",
2408                          Jim_GetString( newargs[0], NULL ),
2409                          Jim_GetString( newargs[1], NULL ),
2410                          Jim_GetString( newargs[2], NULL ),
2411                          Jim_GetString( newargs[3], NULL ),
2412                          Jim_GetString( newargs[4], NULL ),
2413                          Jim_GetString( newargs[5], NULL ),
2414                          Jim_GetString( newargs[6], NULL ),
2415                          Jim_GetString( newargs[7], NULL ),
2416                          Jim_GetString( newargs[8], NULL ),
2417                          Jim_GetString( newargs[9], NULL ) );
2418
2419         e = jim_jtag_command( interp, 10, newargs );
2420         if( e != JIM_OK ){
2421                 command_print( cmd_ctx, "%s", Jim_GetString( Jim_GetResult(interp), NULL ) );
2422         }
2423         return e;
2424 }
2425
2426 int handle_scan_chain_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2427 {
2428         jtag_tap_t *tap;
2429
2430         tap = jtag_all_taps;
2431         command_print(cmd_ctx, "     TapName            | Enabled |   IdCode      Expected    IrLen IrCap  IrMask Instr     ");
2432         command_print(cmd_ctx, "---|--------------------|---------|------------|------------|------|------|------|---------");
2433
2434         while( tap ){
2435                 u32 expected, expected_mask, cur_instr, ii;
2436                 expected = buf_get_u32(tap->expected, 0, tap->ir_length);
2437                 expected_mask = buf_get_u32(tap->expected_mask, 0, tap->ir_length);
2438                 cur_instr = buf_get_u32(tap->cur_instr, 0, tap->ir_length);
2439
2440                 command_print(cmd_ctx,
2441                                           "%2d | %-18s |    %c    | 0x%08x | 0x%08x | 0x%02x | 0x%02x | 0x%02x | 0x%02x",
2442                                           tap->abs_chain_position,
2443                                           tap->dotted_name,
2444                                           tap->enabled ? 'Y' : 'n',
2445                                           tap->idcode,
2446                                           (tap->expected_ids_cnt > 0 ? tap->expected_ids[0] : 0),
2447                                           tap->ir_length,
2448                                           expected,
2449                                           expected_mask,
2450                                           cur_instr);
2451
2452                 for (ii = 1; ii < tap->expected_ids_cnt; ii++) {
2453                         command_print(cmd_ctx, "   |                    |         |            | 0x%08x |      |      |      |         ",
2454                                                   tap->expected_ids[ii]);
2455                 }
2456
2457                 tap = tap->next_tap;
2458         }
2459
2460         return ERROR_OK;
2461 }
2462
2463 int handle_reset_config_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2464 {
2465         if (argc < 1)
2466                 return ERROR_COMMAND_SYNTAX_ERROR;
2467
2468         if (argc >= 1)
2469         {
2470                 if (strcmp(args[0], "none") == 0)
2471                         jtag_reset_config = RESET_NONE;
2472                 else if (strcmp(args[0], "trst_only") == 0)
2473                         jtag_reset_config = RESET_HAS_TRST;
2474                 else if (strcmp(args[0], "srst_only") == 0)
2475                         jtag_reset_config = RESET_HAS_SRST;
2476                 else if (strcmp(args[0], "trst_and_srst") == 0)
2477                         jtag_reset_config = RESET_TRST_AND_SRST;
2478                 else
2479                 {
2480                         LOG_ERROR("(1) invalid reset_config argument (%s), defaulting to none", args[0]);
2481                         jtag_reset_config = RESET_NONE;
2482                         return ERROR_INVALID_ARGUMENTS;
2483                 }
2484         }
2485
2486         if (argc >= 2)
2487         {
2488                 if (strcmp(args[1], "separate") == 0)
2489                 {
2490                         /* seperate reset lines - default */
2491                 } else
2492                 {
2493                         if (strcmp(args[1], "srst_pulls_trst") == 0)
2494                                 jtag_reset_config |= RESET_SRST_PULLS_TRST;
2495                         else if (strcmp(args[1], "trst_pulls_srst") == 0)
2496                                 jtag_reset_config |= RESET_TRST_PULLS_SRST;
2497                         else if (strcmp(args[1], "combined") == 0)
2498                                 jtag_reset_config |= RESET_SRST_PULLS_TRST | RESET_TRST_PULLS_SRST;
2499                         else
2500                         {
2501                                 LOG_ERROR("(2) invalid reset_config argument (%s), defaulting to none", args[1]);
2502                                 jtag_reset_config = RESET_NONE;
2503                                 return ERROR_INVALID_ARGUMENTS;
2504                         }
2505                 }
2506         }
2507
2508         if (argc >= 3)
2509         {
2510                 if (strcmp(args[2], "trst_open_drain") == 0)
2511                         jtag_reset_config |= RESET_TRST_OPEN_DRAIN;
2512                 else if (strcmp(args[2], "trst_push_pull") == 0)
2513                         jtag_reset_config &= ~RESET_TRST_OPEN_DRAIN;
2514                 else
2515                 {
2516                         LOG_ERROR("(3) invalid reset_config argument (%s) defaulting to none", args[2] );
2517                         jtag_reset_config = RESET_NONE;
2518                         return ERROR_INVALID_ARGUMENTS;
2519                 }
2520         }
2521
2522         if (argc >= 4)
2523         {
2524                 if (strcmp(args[3], "srst_push_pull") == 0)
2525                         jtag_reset_config |= RESET_SRST_PUSH_PULL;
2526                 else if (strcmp(args[3], "srst_open_drain") == 0)
2527                         jtag_reset_config &= ~RESET_SRST_PUSH_PULL;
2528                 else
2529                 {
2530                         LOG_ERROR("(4) invalid reset_config argument (%s), defaulting to none", args[3]);
2531                         jtag_reset_config = RESET_NONE;
2532                         return ERROR_INVALID_ARGUMENTS;
2533                 }
2534         }
2535
2536         return ERROR_OK;
2537 }
2538
2539 int handle_jtag_nsrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2540 {
2541         if (argc < 1)
2542         {
2543                 LOG_ERROR("jtag_nsrst_delay <ms> command takes one required argument");
2544                 exit(-1);
2545         }
2546         else
2547         {
2548                 jtag_nsrst_delay = strtoul(args[0], NULL, 0);
2549         }
2550
2551         return ERROR_OK;
2552 }
2553
2554 int handle_jtag_ntrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2555 {
2556         if (argc < 1)
2557         {
2558                 LOG_ERROR("jtag_ntrst_delay <ms> command takes one required argument");
2559                 exit(-1);
2560         }
2561         else
2562         {
2563                 jtag_ntrst_delay = strtoul(args[0], NULL, 0);
2564         }
2565
2566         return ERROR_OK;
2567 }
2568
2569 int handle_jtag_speed_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2570 {
2571         int retval=ERROR_OK;
2572
2573         if (argc == 1)
2574         {
2575                 LOG_DEBUG("handle jtag speed");
2576
2577                 int cur_speed = 0;
2578                 cur_speed = jtag_speed = strtoul(args[0], NULL, 0);
2579
2580                 /* this command can be called during CONFIG,
2581                  * in which case jtag isn't initialized */
2582                 if (jtag)
2583                 {
2584                         retval=jtag->speed(cur_speed);
2585                 }
2586         } else if (argc == 0)
2587         {
2588         } else
2589         {
2590                 return ERROR_COMMAND_SYNTAX_ERROR;
2591         }
2592         command_print(cmd_ctx, "jtag_speed: %d", jtag_speed);
2593
2594         return retval;
2595 }
2596
2597 int handle_jtag_khz_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2598 {
2599         int retval=ERROR_OK;
2600         LOG_DEBUG("handle jtag khz");
2601
2602         if(argc == 1)
2603         {
2604                 speed_khz = strtoul(args[0], NULL, 0);
2605                 if (jtag != NULL)
2606                 {
2607                         int cur_speed = 0;
2608                         LOG_DEBUG("have interface set up");
2609                         int speed_div1;
2610                         if ((retval=jtag->khz(speed_khz, &speed_div1))!=ERROR_OK)
2611                         {
2612                                 speed_khz = 0;
2613                                 return retval;
2614                         }
2615
2616                         cur_speed = jtag_speed = speed_div1;
2617
2618                         retval=jtag->speed(cur_speed);
2619                 } else
2620                 {
2621                         hasKHz = 1;
2622                 }
2623         } else if (argc==0)
2624         {
2625         } else
2626         {
2627                 return ERROR_COMMAND_SYNTAX_ERROR;
2628         }
2629
2630         if (jtag!=NULL)
2631         {
2632                 if ((retval=jtag->speed_div(jtag_speed, &speed_khz))!=ERROR_OK)
2633                         return retval;
2634         }
2635
2636         if (speed_khz==0)
2637         {
2638                 command_print(cmd_ctx, "RCLK - adaptive");
2639         } else
2640         {
2641                 command_print(cmd_ctx, "%d kHz", speed_khz);
2642         }
2643         return retval;
2644
2645 }
2646
2647 int handle_endstate_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2648 {
2649         enum tap_state state;
2650
2651         if (argc < 1)
2652         {
2653                 return ERROR_COMMAND_SYNTAX_ERROR;
2654         }
2655         else
2656         {
2657                 for (state = 0; state < 16; state++)
2658                 {
2659                         if (strcmp(args[0], tap_state_strings[state]) == 0)
2660                         {
2661                                 jtag_add_end_state(state);
2662                                 jtag_execute_queue();
2663                         }
2664                 }
2665         }
2666         command_print(cmd_ctx, "current endstate: %s", tap_state_strings[cmd_queue_end_state]);
2667
2668         return ERROR_OK;
2669 }
2670
2671 int handle_jtag_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2672 {
2673         int trst = -1;
2674         int srst = -1;
2675
2676         if (argc < 2)
2677         {
2678                 return ERROR_COMMAND_SYNTAX_ERROR;
2679         }
2680
2681         if (args[0][0] == '1')
2682                 trst = 1;
2683         else if (args[0][0] == '0')
2684                 trst = 0;
2685         else
2686         {
2687                 return ERROR_COMMAND_SYNTAX_ERROR;
2688         }
2689
2690         if (args[1][0] == '1')
2691                 srst = 1;
2692         else if (args[1][0] == '0')
2693                 srst = 0;
2694         else
2695         {
2696                 return ERROR_COMMAND_SYNTAX_ERROR;
2697         }
2698
2699         if (jtag_interface_init(cmd_ctx) != ERROR_OK)
2700                 return ERROR_JTAG_INIT_FAILED;
2701
2702         jtag_add_reset(trst, srst);
2703         jtag_execute_queue();
2704
2705         return ERROR_OK;
2706 }
2707
2708 int handle_runtest_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2709 {
2710         if (argc < 1)
2711         {
2712                 return ERROR_COMMAND_SYNTAX_ERROR;
2713         }
2714
2715         jtag_add_runtest(strtol(args[0], NULL, 0), -1);
2716         jtag_execute_queue();
2717
2718         return ERROR_OK;
2719
2720 }
2721
2722 int handle_irscan_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2723 {
2724         int i;
2725         scan_field_t *fields;
2726         jtag_tap_t *tap;
2727
2728         if ((argc < 2) || (argc % 2))
2729         {
2730                 return ERROR_COMMAND_SYNTAX_ERROR;
2731         }
2732
2733         fields = malloc(sizeof(scan_field_t) * argc / 2);
2734
2735         for (i = 0; i < argc / 2; i++)
2736         {
2737                 tap = jtag_TapByString( args[i*2] );
2738                 if (tap==NULL)
2739                 {
2740                         command_print( cmd_ctx, "Tap: %s unknown", args[i*2] );
2741                         return ERROR_FAIL;
2742                 }
2743                 int field_size = tap->ir_length;
2744                 fields[i].tap = tap;
2745                 fields[i].out_value = malloc(CEIL(field_size, 8));
2746                 buf_set_u32(fields[i].out_value, 0, field_size, strtoul(args[i*2+1], NULL, 0));
2747                 fields[i].out_mask = NULL;
2748                 fields[i].in_value = NULL;
2749                 fields[i].in_check_mask = NULL;
2750                 fields[i].in_handler = NULL;
2751                 fields[i].in_handler_priv = NULL;
2752         }
2753
2754         jtag_add_ir_scan(argc / 2, fields, -1);
2755         jtag_execute_queue();
2756
2757         for (i = 0; i < argc / 2; i++)
2758                 free(fields[i].out_value);
2759
2760         free (fields);
2761
2762         return ERROR_OK;
2763 }
2764
2765 int Jim_Command_drscan(Jim_Interp *interp, int argc, Jim_Obj *const *args)
2766 {
2767         int retval;
2768         scan_field_t *fields;
2769         int num_fields;
2770         int field_count = 0;
2771         int i, e;
2772         jtag_tap_t *tap;
2773
2774         /* args[1] = device
2775          * args[2] = num_bits
2776          * args[3] = hex string
2777          * ... repeat num bits and hex string ...
2778          */
2779         if ((argc < 4) || ((argc % 2)!=0))
2780         {
2781                 Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
2782                 return JIM_ERR;
2783         }
2784
2785         for (i = 2; i < argc; i+=2)
2786         {
2787                 long bits;
2788
2789                 e = Jim_GetLong(interp, args[i], &bits);
2790                 if (e != JIM_OK)
2791                         return e;
2792         }
2793
2794         tap = jtag_TapByJimObj( interp, args[1] );
2795         if( tap == NULL ){
2796                 return JIM_ERR;
2797         }
2798
2799         num_fields=(argc-2)/2;
2800         fields = malloc(sizeof(scan_field_t) * num_fields);
2801         for (i = 2; i < argc; i+=2)
2802         {
2803                 long bits;
2804                 int len;
2805                 const char *str;
2806
2807                 Jim_GetLong(interp, args[i], &bits);
2808                 str = Jim_GetString(args[i+1], &len);
2809
2810                 fields[field_count].tap = tap;
2811                 fields[field_count].num_bits = bits;
2812                 fields[field_count].out_value = malloc(CEIL(bits, 8));
2813                 str_to_buf(str, len, fields[field_count].out_value, bits, 0);
2814                 fields[field_count].out_mask = NULL;
2815                 fields[field_count].in_value = fields[field_count].out_value;
2816                 fields[field_count].in_check_mask = NULL;
2817                 fields[field_count].in_check_value = NULL;
2818                 fields[field_count].in_handler = NULL;
2819                 fields[field_count++].in_handler_priv = NULL;
2820         }
2821
2822         jtag_add_dr_scan(num_fields, fields, -1);
2823         retval = jtag_execute_queue();
2824         if (retval != ERROR_OK)
2825         {
2826                 Jim_SetResultString(interp, "drscan: jtag execute failed",-1);
2827                 return JIM_ERR;
2828         }
2829
2830         field_count=0;
2831         Jim_Obj *list = Jim_NewListObj(interp, NULL, 0);
2832         for (i = 2; i < argc; i+=2)
2833         {
2834                 long bits;
2835                 char *str;
2836
2837                 Jim_GetLong(interp, args[i], &bits);
2838                 str = buf_to_str(fields[field_count].in_value, bits, 16);
2839                 free(fields[field_count].out_value);
2840
2841                 Jim_ListAppendElement(interp, list, Jim_NewStringObj(interp, str, strlen(str)));
2842                 free(str);
2843                 field_count++;
2844         }
2845
2846         Jim_SetResult(interp, list);
2847
2848         free(fields);
2849
2850         return JIM_OK;
2851 }
2852
2853 int handle_verify_ircapture_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2854 {
2855         if (argc == 1)
2856         {
2857                 if (strcmp(args[0], "enable") == 0)
2858                 {
2859                         jtag_verify_capture_ir = 1;
2860                 }
2861                 else if (strcmp(args[0], "disable") == 0)
2862                 {
2863                         jtag_verify_capture_ir = 0;
2864                 } else
2865                 {
2866                         return ERROR_COMMAND_SYNTAX_ERROR;
2867                 }
2868         } else if (argc != 0)
2869         {
2870                 return ERROR_COMMAND_SYNTAX_ERROR;
2871         }
2872
2873         command_print(cmd_ctx, "verify Capture-IR is %s", (jtag_verify_capture_ir) ? "enabled": "disabled");
2874
2875         return ERROR_OK;
2876 }
2877
2878 int jtag_power_dropout(int *dropout)
2879 {
2880         return jtag->power_dropout(dropout);
2881 }
2882
2883 int jtag_srst_asserted(int *srst_asserted)
2884 {
2885         return jtag->srst_asserted(srst_asserted);
2886 }
2887
2888 void jtag_tap_handle_event( jtag_tap_t * tap, enum jtag_tap_event e)
2889 {
2890         jtag_tap_event_action_t * jteap;
2891         int done;
2892
2893         jteap = tap->event_action;
2894
2895         done = 0;
2896         while (jteap) {
2897                 if (jteap->event == e) {
2898                         done = 1;
2899                         LOG_DEBUG( "JTAG tap: %s event: %d (%s) action: %s\n",
2900                                         tap->dotted_name,
2901                                         e,
2902                                         Jim_Nvp_value2name_simple(nvp_jtag_tap_event, e)->name,
2903                                         Jim_GetString(jteap->body, NULL) );
2904                         if (Jim_EvalObj(interp, jteap->body) != JIM_OK) {
2905                                 Jim_PrintErrorMessage(interp);
2906                         }
2907                 }
2908
2909                 jteap = jteap->next;
2910         }
2911
2912         if (!done) {
2913                 LOG_DEBUG( "event %d %s - no action",
2914                                 e,
2915                                 Jim_Nvp_value2name_simple( nvp_jtag_tap_event, e)->name);
2916         }
2917 }