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