Charles Hardin ckhardin at gmail.com
[fw/openocd] / src / jtag / jtag.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "replacements.h"
25
26 #include "jtag.h"
27
28 #include "command.h"
29 #include "log.h"
30
31 #include "stdlib.h"
32 #include "string.h"
33 #include <unistd.h>
34
35 #include "openocd_tcl.h"
36
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 jtag_device_t *jtag_devices = NULL;
126 int jtag_num_devices = 0;
127 int jtag_ir_scan_size = 0;
128 enum reset_types jtag_reset_config = RESET_NONE;
129 enum tap_state cmd_queue_end_state = TAP_TLR;
130 enum tap_state cmd_queue_cur_state = TAP_TLR;
131
132 int jtag_verify_capture_ir = 1;
133
134 /* how long the OpenOCD should wait before attempting JTAG communication after reset lines deasserted (in ms) */
135 int jtag_nsrst_delay = 0; /* default to no nSRST delay */
136 int jtag_ntrst_delay = 0; /* default to no nTRST delay */ 
137
138 /* maximum number of JTAG devices expected in the chain
139  */
140 #define JTAG_MAX_CHAIN_SIZE 20 
141
142 /* callbacks to inform high-level handlers about JTAG state changes */
143 jtag_event_callback_t *jtag_event_callbacks;
144
145 /* speed in kHz*/
146 static int speed1 = 0, speed2 = 0;
147 /* flag if the kHz speed was defined */
148 static int hasKHz = 0;
149
150 /* jtag interfaces (parport, FTDI-USB, TI-USB, ...)
151  */
152  
153 #if BUILD_ECOSBOARD == 1
154         extern jtag_interface_t eCosBoard_interface;
155 #endif
156  
157 #if BUILD_PARPORT == 1
158         extern jtag_interface_t parport_interface;
159 #endif
160          
161 #if BUILD_DUMMY == 1
162         extern jtag_interface_t dummy_interface;
163 #endif
164         
165 #if BUILD_FT2232_FTD2XX == 1
166         extern jtag_interface_t ft2232_interface;
167 #endif
168
169 #if BUILD_FT2232_LIBFTDI == 1
170         extern jtag_interface_t ft2232_interface;
171 #endif
172
173 #if BUILD_AMTJTAGACCEL == 1
174         extern jtag_interface_t amt_jtagaccel_interface;
175 #endif
176
177 #if BUILD_EP93XX == 1
178         extern jtag_interface_t ep93xx_interface;
179 #endif
180
181 #if BUILD_AT91RM9200 == 1
182         extern jtag_interface_t at91rm9200_interface;
183 #endif
184
185 #if BUILD_GW16012 == 1
186         extern jtag_interface_t gw16012_interface;
187 #endif
188
189 #if BUILD_PRESTO_LIBFTDI == 1 || BUILD_PRESTO_FTD2XX == 1
190         extern jtag_interface_t presto_interface;
191 #endif
192
193 #if BUILD_USBPROG == 1
194         extern jtag_interface_t usbprog_interface;
195 #endif
196
197 #if BUILD_JLINK == 1
198         extern jtag_interface_t jlink_interface;
199 #endif
200
201 jtag_interface_t *jtag_interfaces[] = {
202 #if BUILD_ECOSBOARD == 1
203         &eCosBoard_interface,
204 #endif
205 #if BUILD_PARPORT == 1
206         &parport_interface,
207 #endif
208 #if BUILD_DUMMY == 1
209         &dummy_interface,
210 #endif
211 #if BUILD_FT2232_FTD2XX == 1
212         &ft2232_interface,
213 #endif
214 #if BUILD_FT2232_LIBFTDI == 1
215         &ft2232_interface,
216 #endif
217 #if BUILD_AMTJTAGACCEL == 1
218         &amt_jtagaccel_interface,
219 #endif
220 #if BUILD_EP93XX == 1
221         &ep93xx_interface,
222 #endif
223 #if BUILD_AT91RM9200 == 1
224         &at91rm9200_interface,
225 #endif
226 #if BUILD_GW16012 == 1
227         &gw16012_interface,
228 #endif
229 #if BUILD_PRESTO_LIBFTDI == 1 || BUILD_PRESTO_FTD2XX == 1
230         &presto_interface,
231 #endif
232 #if BUILD_USBPROG == 1
233         &usbprog_interface,
234 #endif
235 #if BUILD_JLINK == 1
236         &jlink_interface,
237 #endif
238         NULL,
239 };
240
241 jtag_interface_t *jtag = NULL;
242
243 /* configuration */
244 jtag_interface_t *jtag_interface = NULL;
245 int jtag_speed = 0;
246 int jtag_speed_post_reset = 0;
247
248
249 /* forward declarations */
250 void jtag_add_pathmove(int num_states, enum tap_state *path);
251 void jtag_add_runtest(int num_cycles, enum tap_state endstate);
252 void jtag_add_end_state(enum tap_state endstate);
253 void jtag_add_sleep(u32 us);
254 int jtag_execute_queue(void);
255 int jtag_cancel_queue(void);
256
257 /* jtag commands */
258 int handle_interface_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
259 int handle_jtag_speed_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
260 int handle_jtag_khz_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
261 int handle_jtag_device_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
262 int handle_reset_config_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
263 int handle_jtag_nsrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
264 int handle_jtag_ntrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
265
266 int handle_scan_chain_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
267
268 int handle_endstate_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
269 int handle_jtag_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
270 int handle_runtest_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
271 int handle_irscan_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
272 int Jim_Command_drscan(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
273
274 int handle_verify_ircapture_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc);
275
276 int jtag_register_event_callback(int (*callback)(enum jtag_event event, void *priv), void *priv)
277 {
278         jtag_event_callback_t **callbacks_p = &jtag_event_callbacks;
279         
280         if (callback == NULL)
281         {
282                 return ERROR_INVALID_ARGUMENTS;
283         }
284         
285         if (*callbacks_p)
286         {
287                 while ((*callbacks_p)->next)
288                         callbacks_p = &((*callbacks_p)->next);
289                 callbacks_p = &((*callbacks_p)->next);
290         }
291         
292         (*callbacks_p) = malloc(sizeof(jtag_event_callback_t));
293         (*callbacks_p)->callback = callback;
294         (*callbacks_p)->priv = priv;
295         (*callbacks_p)->next = NULL;
296         
297         return ERROR_OK;
298 }
299
300 int jtag_unregister_event_callback(int (*callback)(enum jtag_event event, void *priv))
301 {
302         jtag_event_callback_t **callbacks_p = &jtag_event_callbacks;
303         
304         if (callback == NULL)
305         {
306                 return ERROR_INVALID_ARGUMENTS;
307         }
308                 
309         while (*callbacks_p)
310         {
311                 jtag_event_callback_t **next = &((*callbacks_p)->next);
312                 if ((*callbacks_p)->callback == callback)
313                 {
314                         free(*callbacks_p);
315                         *callbacks_p = *next;
316                 }
317                 callbacks_p = next;
318         }
319         
320         return ERROR_OK;
321 }
322
323 int jtag_call_event_callbacks(enum jtag_event event)
324 {
325         jtag_event_callback_t *callback = jtag_event_callbacks;
326         
327         LOG_DEBUG("jtag event: %s", jtag_event_strings[event]);
328         
329         while (callback)
330         {
331                 callback->callback(event, callback->priv);
332                 callback = callback->next;
333         }
334         
335         return ERROR_OK;
336 }
337
338 /* returns a pointer to the pointer of the last command in queue
339  * this may be a pointer to the root pointer (jtag_command_queue)
340  * or to the next member of the last but one command
341  */
342 jtag_command_t** jtag_get_last_command_p(void)
343 {
344 /*      jtag_command_t *cmd = jtag_command_queue;
345         
346         if (cmd)
347                 while (cmd->next)
348                         cmd = cmd->next;
349         else
350                 return &jtag_command_queue;
351         
352         return &cmd->next;*/
353         
354         return last_comand_pointer;
355 }
356
357 /* returns a pointer to the n-th device in the scan chain */
358 jtag_device_t* jtag_get_device(int num)
359 {
360         jtag_device_t *device = jtag_devices;
361         int i = 0;
362
363         while (device)
364         {
365                 if (num == i)
366                         return device;
367                 device = device->next;
368                 i++;
369         }
370         
371         LOG_ERROR("jtag device number %d not defined", num);
372         exit(-1);
373 }
374
375 void* cmd_queue_alloc(size_t size)
376 {
377         cmd_queue_page_t **p_page = &cmd_queue_pages;
378         int offset;
379         u8 *t;
380
381         if (*p_page)
382         {
383                 while ((*p_page)->next)
384                         p_page = &((*p_page)->next);
385                 if (CMD_QUEUE_PAGE_SIZE - (*p_page)->used < size)
386                         p_page = &((*p_page)->next);
387         }
388
389         if (!*p_page)
390         {
391                 *p_page = malloc(sizeof(cmd_queue_page_t));
392                 (*p_page)->used = 0;
393                 (*p_page)->address = malloc(CMD_QUEUE_PAGE_SIZE);
394                 (*p_page)->next = NULL;
395         }
396
397         offset = (*p_page)->used;
398         (*p_page)->used += size;
399         
400         t=(u8 *)((*p_page)->address);
401         return t + offset;
402 }
403
404 void cmd_queue_free()
405 {
406         cmd_queue_page_t *page = cmd_queue_pages;
407
408         while (page)
409         {
410                 cmd_queue_page_t *last = page;
411                 free(page->address);
412                 page = page->next;
413                 free(last);
414         }
415
416         cmd_queue_pages = NULL;
417 }
418
419 static void jtag_prelude1()
420 {
421         if (jtag_trst == 1)
422         {
423                 LOG_WARNING("JTAG command queued, while TRST is low (TAP in reset)");
424                 jtag_error=ERROR_JTAG_TRST_ASSERTED;
425                 return;
426         }
427
428         if (cmd_queue_end_state == TAP_TLR)
429                 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
430 }
431
432 static void jtag_prelude(enum tap_state state)
433 {
434         jtag_prelude1();
435         
436         if (state != -1)
437                 jtag_add_end_state(state);
438
439         cmd_queue_cur_state = cmd_queue_end_state;
440 }
441
442 void jtag_add_ir_scan(int num_fields, scan_field_t *fields, enum tap_state state)
443 {
444         int retval;
445         
446         jtag_prelude(state);
447         
448         retval=interface_jtag_add_ir_scan(num_fields, fields, cmd_queue_end_state);
449         if (retval!=ERROR_OK)
450                 jtag_error=retval;
451 }
452
453 int MINIDRIVER(interface_jtag_add_ir_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
454 {       
455         jtag_command_t **last_cmd;
456         jtag_device_t *device;
457         int i, j;
458         int scan_size = 0;
459
460
461         last_cmd = jtag_get_last_command_p();
462         
463         /* allocate memory for a new list member */
464         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
465         (*last_cmd)->next = NULL;
466         last_comand_pointer = &((*last_cmd)->next);
467         (*last_cmd)->type = JTAG_SCAN;
468
469         /* allocate memory for ir scan command */
470         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
471         (*last_cmd)->cmd.scan->ir_scan = 1;
472         (*last_cmd)->cmd.scan->num_fields = jtag_num_devices;   /* one field per device */
473         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc(jtag_num_devices * sizeof(scan_field_t));
474         (*last_cmd)->cmd.scan->end_state = state;
475
476         for (i = 0; i < jtag_num_devices; i++)
477         {
478                 int found = 0;
479                 device = jtag_get_device(i);
480                 scan_size = device->ir_length;
481                 (*last_cmd)->cmd.scan->fields[i].device = i;
482                 (*last_cmd)->cmd.scan->fields[i].num_bits = scan_size;
483                 (*last_cmd)->cmd.scan->fields[i].in_value = NULL;
484                 (*last_cmd)->cmd.scan->fields[i].in_handler = NULL;     /* disable verification by default */
485
486                 /* search the list */
487                 for (j = 0; j < num_fields; j++)
488                 {
489                         if (i == fields[j].device)
490                         {
491                                 found = 1;
492                                 (*last_cmd)->cmd.scan->fields[i].out_value = buf_cpy(fields[j].out_value, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
493                                 (*last_cmd)->cmd.scan->fields[i].out_mask = buf_cpy(fields[j].out_mask, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
494                         
495                                 if (jtag_verify_capture_ir)
496                                 {
497                                         if (fields[j].in_handler==NULL)
498                                         {
499                                                 jtag_set_check_value((*last_cmd)->cmd.scan->fields+i, device->expected, device->expected_mask, NULL);
500                                         } else
501                                         {
502                                                 (*last_cmd)->cmd.scan->fields[i].in_handler = fields[j].in_handler;
503                                                 (*last_cmd)->cmd.scan->fields[i].in_handler_priv = fields[j].in_handler_priv;
504                                                 (*last_cmd)->cmd.scan->fields[i].in_check_value = device->expected; 
505                                                 (*last_cmd)->cmd.scan->fields[i].in_check_mask = device->expected_mask;
506                                         }
507                                 }
508                                 
509                                 device->bypass = 0;
510                                 break;
511                         }
512                 }
513         
514                 if (!found)
515                 {
516                         /* if a device isn't listed, set it to BYPASS */
517                         (*last_cmd)->cmd.scan->fields[i].out_value = buf_set_ones(cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
518                         (*last_cmd)->cmd.scan->fields[i].out_mask = NULL;
519                         device->bypass = 1;
520                         
521                 }
522                 
523                 /* update device information */
524                 buf_cpy((*last_cmd)->cmd.scan->fields[i].out_value, jtag_get_device(i)->cur_instr, scan_size);
525         }
526         
527         return ERROR_OK;
528 }
529
530 void jtag_add_plain_ir_scan(int num_fields, scan_field_t *fields, enum tap_state state)
531 {
532         int retval;
533         
534         jtag_prelude(state);
535         
536         retval=interface_jtag_add_plain_ir_scan(num_fields, fields, cmd_queue_end_state);
537         if (retval!=ERROR_OK)
538                 jtag_error=retval;
539 }
540
541 int MINIDRIVER(interface_jtag_add_plain_ir_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
542 {
543         int i;
544         jtag_command_t **last_cmd;
545         
546         last_cmd = jtag_get_last_command_p();
547         
548         /* allocate memory for a new list member */
549         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
550         (*last_cmd)->next = NULL;
551         last_comand_pointer = &((*last_cmd)->next);
552         (*last_cmd)->type = JTAG_SCAN;
553
554         /* allocate memory for ir scan command */
555         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
556         (*last_cmd)->cmd.scan->ir_scan = 1;
557         (*last_cmd)->cmd.scan->num_fields = num_fields;
558         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc(num_fields * sizeof(scan_field_t));
559         (*last_cmd)->cmd.scan->end_state = state;
560
561         for (i = 0; i < num_fields; i++)
562         {
563                 int num_bits = fields[i].num_bits;
564                 int num_bytes = CEIL(fields[i].num_bits, 8);
565                 (*last_cmd)->cmd.scan->fields[i].device = fields[i].device;
566                 (*last_cmd)->cmd.scan->fields[i].num_bits = num_bits;
567                 (*last_cmd)->cmd.scan->fields[i].out_value = buf_cpy(fields[i].out_value, cmd_queue_alloc(num_bytes), num_bits);
568                 (*last_cmd)->cmd.scan->fields[i].out_mask = buf_cpy(fields[i].out_mask, cmd_queue_alloc(num_bytes), num_bits);
569                 (*last_cmd)->cmd.scan->fields[i].in_value = fields[i].in_value;
570                 (*last_cmd)->cmd.scan->fields[i].in_check_value = fields[i].in_check_value;
571                 (*last_cmd)->cmd.scan->fields[i].in_check_mask = fields[i].in_check_mask;
572                 (*last_cmd)->cmd.scan->fields[i].in_handler = NULL;
573                 (*last_cmd)->cmd.scan->fields[i].in_handler_priv = NULL;
574         }
575         return ERROR_OK;
576 }
577
578 void jtag_add_dr_scan(int num_fields, scan_field_t *fields, enum tap_state state)
579 {
580         int retval;
581         
582         jtag_prelude(state);
583
584         retval=interface_jtag_add_dr_scan(num_fields, fields, cmd_queue_end_state);
585         if (retval!=ERROR_OK)
586                 jtag_error=retval;
587 }
588
589 int MINIDRIVER(interface_jtag_add_dr_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
590 {
591         int i, j;
592         int bypass_devices = 0;
593         int field_count = 0;
594         int scan_size;
595
596         jtag_command_t **last_cmd = jtag_get_last_command_p();
597         jtag_device_t *device = jtag_devices;
598
599         /* count devices in bypass */
600         while (device)
601         {
602                 if (device->bypass)
603                         bypass_devices++;
604                 device = device->next;
605         }
606         if (bypass_devices >= jtag_num_devices)
607         {
608                 LOG_ERROR("all devices in bypass");
609                 return ERROR_JTAG_DEVICE_ERROR;
610         }
611         
612         /* allocate memory for a new list member */
613         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
614         last_comand_pointer = &((*last_cmd)->next);
615         (*last_cmd)->next = NULL;
616         (*last_cmd)->type = JTAG_SCAN;
617
618         /* allocate memory for dr scan command */
619         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
620         (*last_cmd)->cmd.scan->ir_scan = 0;
621         (*last_cmd)->cmd.scan->num_fields = num_fields + bypass_devices;
622         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc((num_fields + bypass_devices) * sizeof(scan_field_t));
623         (*last_cmd)->cmd.scan->end_state = state;
624         
625         for (i = 0; i < jtag_num_devices; i++)
626         {
627                 int found = 0;
628                 (*last_cmd)->cmd.scan->fields[field_count].device = i;
629         
630                 for (j = 0; j < num_fields; j++)
631                 {
632                         if (i == fields[j].device)
633                         {
634                                 found = 1;
635                                 scan_size = fields[j].num_bits;
636                                 (*last_cmd)->cmd.scan->fields[field_count].num_bits = scan_size;
637                                 (*last_cmd)->cmd.scan->fields[field_count].out_value = buf_cpy(fields[j].out_value, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
638                                 (*last_cmd)->cmd.scan->fields[field_count].out_mask = buf_cpy(fields[j].out_mask, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
639                                 (*last_cmd)->cmd.scan->fields[field_count].in_value = fields[j].in_value;
640                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_value = fields[j].in_check_value;
641                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = fields[j].in_check_mask;
642                                 (*last_cmd)->cmd.scan->fields[field_count].in_handler = fields[j].in_handler;
643                                 (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = fields[j].in_handler_priv;
644                         }
645                 }
646                 if (!found)
647                 {
648 #ifdef _DEBUG_JTAG_IO_
649                         /* if a device isn't listed, the BYPASS register should be selected */
650                         if (!jtag_get_device(i)->bypass)
651                         {
652                                 LOG_ERROR("BUG: no scan data for a device not in BYPASS");
653                                 exit(-1);
654                         }
655 #endif  
656                         /* program the scan field to 1 bit length, and ignore it's value */
657                         (*last_cmd)->cmd.scan->fields[field_count].num_bits = 1;
658                         (*last_cmd)->cmd.scan->fields[field_count].out_value = NULL;
659                         (*last_cmd)->cmd.scan->fields[field_count].out_mask = NULL;
660                         (*last_cmd)->cmd.scan->fields[field_count].in_value = NULL;
661                         (*last_cmd)->cmd.scan->fields[field_count].in_check_value = NULL;
662                         (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = NULL;
663                         (*last_cmd)->cmd.scan->fields[field_count].in_handler = NULL;
664                         (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = NULL;
665                 }
666                 else
667                 {
668 #ifdef _DEBUG_JTAG_IO_
669                         /* if a device is listed, the BYPASS register must not be selected */
670                         if (jtag_get_device(i)->bypass)
671                         {
672                                 LOG_ERROR("BUG: scan data for a device in BYPASS");
673                                 exit(-1);
674                         }
675 #endif
676                 }
677         }
678         return ERROR_OK;
679 }
680
681 void MINIDRIVER(interface_jtag_add_dr_out)(int device_num, 
682                 int num_fields,
683                 const int *num_bits,
684                 const u32 *value,
685                 enum tap_state end_state)
686 {
687         int i;
688         int field_count = 0;
689         int scan_size;
690         int bypass_devices = 0;
691
692         jtag_command_t **last_cmd = jtag_get_last_command_p();
693         jtag_device_t *device = jtag_devices;
694         /* count devices in bypass */
695         while (device)
696         {
697                 if (device->bypass)
698                         bypass_devices++;
699                 device = device->next;
700         }
701         
702         /* allocate memory for a new list member */
703         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
704         last_comand_pointer = &((*last_cmd)->next);
705         (*last_cmd)->next = NULL;
706         (*last_cmd)->type = JTAG_SCAN;
707
708         /* allocate memory for dr scan command */
709         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
710         (*last_cmd)->cmd.scan->ir_scan = 0;
711         (*last_cmd)->cmd.scan->num_fields = num_fields + bypass_devices;
712         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc((num_fields + bypass_devices) * sizeof(scan_field_t));
713         (*last_cmd)->cmd.scan->end_state = end_state;
714         
715         for (i = 0; i < jtag_num_devices; i++)
716         {
717                 (*last_cmd)->cmd.scan->fields[field_count].device = i;
718         
719                 if (i == device_num)
720                 {
721                         int j;
722 #ifdef _DEBUG_JTAG_IO_
723                         /* if a device is listed, the BYPASS register must not be selected */
724                         if (jtag_get_device(i)->bypass)
725                         {
726                                 LOG_ERROR("BUG: scan data for a device in BYPASS");
727                                 exit(-1);
728                         }
729 #endif
730                         for (j = 0; j < num_fields; j++)
731                         {
732                                 u8 out_value[4];
733                                 scan_size = num_bits[j];
734                                 buf_set_u32(out_value, 0, scan_size, value[j]);
735                                 (*last_cmd)->cmd.scan->fields[field_count].num_bits = scan_size;
736                                 (*last_cmd)->cmd.scan->fields[field_count].out_value = buf_cpy(out_value, cmd_queue_alloc(CEIL(scan_size, 8)), scan_size);
737                                 (*last_cmd)->cmd.scan->fields[field_count].out_mask = NULL;
738                                 (*last_cmd)->cmd.scan->fields[field_count].in_value = NULL;
739                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_value = NULL;
740                                 (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = NULL;
741                                 (*last_cmd)->cmd.scan->fields[field_count].in_handler = NULL;
742                                 (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = NULL;
743                         }
744                 } else
745                 {
746 #ifdef _DEBUG_JTAG_IO_
747                         /* if a device isn't listed, the BYPASS register should be selected */
748                         if (!jtag_get_device(i)->bypass)
749                         {
750                                 LOG_ERROR("BUG: no scan data for a device not in BYPASS");
751                                 exit(-1);
752                         }
753 #endif  
754                         /* program the scan field to 1 bit length, and ignore it's value */
755                         (*last_cmd)->cmd.scan->fields[field_count].num_bits = 1;
756                         (*last_cmd)->cmd.scan->fields[field_count].out_value = NULL;
757                         (*last_cmd)->cmd.scan->fields[field_count].out_mask = NULL;
758                         (*last_cmd)->cmd.scan->fields[field_count].in_value = NULL;
759                         (*last_cmd)->cmd.scan->fields[field_count].in_check_value = NULL;
760                         (*last_cmd)->cmd.scan->fields[field_count].in_check_mask = NULL;
761                         (*last_cmd)->cmd.scan->fields[field_count].in_handler = NULL;
762                         (*last_cmd)->cmd.scan->fields[field_count++].in_handler_priv = NULL;
763                 }
764         }
765 }
766
767
768
769
770 void jtag_add_plain_dr_scan(int num_fields, scan_field_t *fields, enum tap_state state)
771 {
772         int retval;
773         
774         jtag_prelude(state);
775
776         retval=interface_jtag_add_plain_dr_scan(num_fields, fields, cmd_queue_end_state);
777         if (retval!=ERROR_OK)
778                 jtag_error=retval;
779 }
780
781 int MINIDRIVER(interface_jtag_add_plain_dr_scan)(int num_fields, scan_field_t *fields, enum tap_state state)
782 {
783         int i;
784         jtag_command_t **last_cmd = jtag_get_last_command_p();
785         
786         /* allocate memory for a new list member */
787         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
788         last_comand_pointer = &((*last_cmd)->next);
789         (*last_cmd)->next = NULL;
790         (*last_cmd)->type = JTAG_SCAN;
791
792         /* allocate memory for scan command */
793         (*last_cmd)->cmd.scan = cmd_queue_alloc(sizeof(scan_command_t));
794         (*last_cmd)->cmd.scan->ir_scan = 0;
795         (*last_cmd)->cmd.scan->num_fields = num_fields;
796         (*last_cmd)->cmd.scan->fields = cmd_queue_alloc(num_fields * sizeof(scan_field_t));
797         (*last_cmd)->cmd.scan->end_state = state;
798         
799         for (i = 0; i < num_fields; i++)
800         {
801                 int num_bits = fields[i].num_bits;
802                 int num_bytes = CEIL(fields[i].num_bits, 8);
803                 (*last_cmd)->cmd.scan->fields[i].device = fields[i].device;
804                 (*last_cmd)->cmd.scan->fields[i].num_bits = num_bits;
805                 (*last_cmd)->cmd.scan->fields[i].out_value = buf_cpy(fields[i].out_value, cmd_queue_alloc(num_bytes), num_bits);
806                 (*last_cmd)->cmd.scan->fields[i].out_mask = buf_cpy(fields[i].out_mask, cmd_queue_alloc(num_bytes), num_bits);
807                 (*last_cmd)->cmd.scan->fields[i].in_value = fields[i].in_value;
808                 (*last_cmd)->cmd.scan->fields[i].in_check_value = fields[i].in_check_value;
809                 (*last_cmd)->cmd.scan->fields[i].in_check_mask = fields[i].in_check_mask;
810                 (*last_cmd)->cmd.scan->fields[i].in_handler = fields[i].in_handler;
811                 (*last_cmd)->cmd.scan->fields[i].in_handler_priv = fields[i].in_handler_priv;
812         }
813
814         return ERROR_OK;
815 }
816
817 void jtag_add_tlr()
818 {
819         jtag_prelude(TAP_TLR);
820         
821         int retval;
822         retval=interface_jtag_add_tlr();
823         if (retval!=ERROR_OK)
824                 jtag_error=retval;
825 }
826
827 int MINIDRIVER(interface_jtag_add_tlr)()
828 {
829         enum tap_state state = TAP_TLR;
830         jtag_command_t **last_cmd = jtag_get_last_command_p();
831         
832         /* allocate memory for a new list member */
833         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
834         last_comand_pointer = &((*last_cmd)->next);
835         (*last_cmd)->next = NULL;
836         (*last_cmd)->type = JTAG_STATEMOVE;
837
838         (*last_cmd)->cmd.statemove = cmd_queue_alloc(sizeof(statemove_command_t));
839         (*last_cmd)->cmd.statemove->end_state = state;
840         
841         
842         return ERROR_OK;
843 }
844
845 void jtag_add_pathmove(int num_states, enum tap_state *path)
846 {
847         enum tap_state cur_state=cmd_queue_cur_state;
848         int i;
849         int retval;
850
851         /* the last state has to be a stable state */
852         if (tap_move_map[path[num_states - 1]] == -1)
853         {
854                 LOG_ERROR("BUG: TAP path doesn't finish in a stable state");
855                 exit(-1);
856         }
857
858         for (i=0; i<num_states; i++)
859         {
860                 if ((tap_transitions[cur_state].low != path[i])&&
861                                 (tap_transitions[cur_state].high != path[i]))
862                 {
863                         LOG_ERROR("BUG: %s -> %s isn't a valid TAP transition", tap_state_strings[cur_state], tap_state_strings[path[i]]);
864                         exit(-1);
865                 }
866                 cur_state = path[i];
867         }
868         
869         jtag_prelude1();
870         
871         cmd_queue_cur_state = path[num_states - 1];
872
873         retval=interface_jtag_add_pathmove(num_states, path);
874         if (retval!=ERROR_OK)
875                 jtag_error=retval;
876 }
877
878
879 int MINIDRIVER(interface_jtag_add_pathmove)(int num_states, enum tap_state *path)
880 {
881         jtag_command_t **last_cmd = jtag_get_last_command_p();
882         int i;
883         
884         /* allocate memory for a new list member */
885         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
886         last_comand_pointer = &((*last_cmd)->next);
887         (*last_cmd)->next = NULL;
888         (*last_cmd)->type = JTAG_PATHMOVE;
889
890         (*last_cmd)->cmd.pathmove = cmd_queue_alloc(sizeof(pathmove_command_t));
891         (*last_cmd)->cmd.pathmove->num_states = num_states;
892         (*last_cmd)->cmd.pathmove->path = cmd_queue_alloc(sizeof(enum tap_state) * num_states);
893         
894         for (i = 0; i < num_states; i++)
895                 (*last_cmd)->cmd.pathmove->path[i] = path[i];
896         
897         return ERROR_OK;
898 }
899
900 int MINIDRIVER(interface_jtag_add_runtest)(int num_cycles, enum tap_state state)
901 {
902         jtag_command_t **last_cmd = jtag_get_last_command_p();
903         
904         /* allocate memory for a new list member */
905         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
906         (*last_cmd)->next = NULL;
907         last_comand_pointer = &((*last_cmd)->next);
908         (*last_cmd)->type = JTAG_RUNTEST;
909
910         (*last_cmd)->cmd.runtest = cmd_queue_alloc(sizeof(runtest_command_t));
911         (*last_cmd)->cmd.runtest->num_cycles = num_cycles;
912         (*last_cmd)->cmd.runtest->end_state = state;
913         
914         return ERROR_OK;
915 }
916
917 void jtag_add_runtest(int num_cycles, enum tap_state state)
918 {
919         int retval;
920         
921         jtag_prelude(state);
922         
923         /* executed by sw or hw fifo */
924         retval=interface_jtag_add_runtest(num_cycles, cmd_queue_end_state);
925         if (retval!=ERROR_OK)
926                 jtag_error=retval;
927 }
928
929 void jtag_add_reset(int req_tlr_or_trst, int req_srst)
930 {
931         int trst_with_tlr = 0;
932         int retval;
933         
934         /* FIX!!! there are *many* different cases here. A better
935          * approach is needed for legal combinations of transitions...
936          */
937         if ((jtag_reset_config & RESET_HAS_SRST)&&
938                         (jtag_reset_config & RESET_HAS_TRST)&& 
939                         ((jtag_reset_config & RESET_SRST_PULLS_TRST)==0))
940         {
941                 if (((req_tlr_or_trst&&!jtag_trst)||
942                                 (!req_tlr_or_trst&&jtag_trst))&&
943                                 ((req_srst&&!jtag_srst)||
944                                                 (!req_srst&&jtag_srst)))
945                 {
946                         /* FIX!!! srst_pulls_trst allows 1,1 => 0,0 transition.... */
947                         //LOG_ERROR("BUG: transition of req_tlr_or_trst and req_srst in the same jtag_add_reset() call is undefined");
948                 }
949         }
950         
951         /* Make sure that jtag_reset_config allows the requested reset */
952         /* if SRST pulls TRST, we can't fulfill srst == 1 with trst == 0 */
953         if (((jtag_reset_config & RESET_SRST_PULLS_TRST) && (req_srst == 1)) && (!req_tlr_or_trst))
954         {
955                 LOG_ERROR("BUG: requested reset would assert trst");
956                 jtag_error=ERROR_FAIL;
957                 return;
958         }
959                 
960         /* if TRST pulls SRST, we reset with TAP T-L-R */
961         if (((jtag_reset_config & RESET_TRST_PULLS_SRST) && (req_tlr_or_trst)) && (req_srst == 0))
962         {
963                 trst_with_tlr = 1;
964         }
965         
966         if (req_srst && !(jtag_reset_config & RESET_HAS_SRST))
967         {
968                 LOG_ERROR("BUG: requested SRST assertion, but the current configuration doesn't support this");
969                 jtag_error=ERROR_FAIL;
970                 return;
971         }
972         
973         if (req_tlr_or_trst)
974         {
975                 if (!trst_with_tlr && (jtag_reset_config & RESET_HAS_TRST))
976                 {
977                         jtag_trst = 1;
978                 } else
979                 {
980                         trst_with_tlr = 1;
981                 }
982         } else
983         {
984                 jtag_trst = 0;
985         }
986         
987         jtag_srst = req_srst;
988
989         retval = interface_jtag_add_reset(jtag_trst, jtag_srst);
990         if (retval!=ERROR_OK)
991         {
992                 jtag_error=retval;
993                 return;
994         }
995
996         if (jtag_srst)
997         {
998                 LOG_DEBUG("SRST line asserted");
999         }
1000         else
1001         {
1002                 LOG_DEBUG("SRST line released");
1003                 if (jtag_nsrst_delay)
1004                         jtag_add_sleep(jtag_nsrst_delay * 1000);
1005         }
1006         
1007         if (trst_with_tlr)
1008         {
1009                 LOG_DEBUG("JTAG reset with TLR instead of TRST");
1010                 jtag_add_end_state(TAP_TLR);
1011                 jtag_add_tlr();
1012                 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
1013                 return;
1014         }
1015         
1016         if (jtag_trst)
1017         {
1018                 /* we just asserted nTRST, so we're now in Test-Logic-Reset,
1019                  * and inform possible listeners about this
1020                  */
1021                 LOG_DEBUG("TRST line asserted");
1022                 cmd_queue_cur_state = TAP_TLR;
1023                 jtag_call_event_callbacks(JTAG_TRST_ASSERTED);
1024         }
1025         else
1026         {
1027                 if (jtag_ntrst_delay)
1028                         jtag_add_sleep(jtag_ntrst_delay * 1000);
1029         }
1030 }
1031
1032 int MINIDRIVER(interface_jtag_add_reset)(int req_trst, int req_srst)
1033 {
1034         jtag_command_t **last_cmd = jtag_get_last_command_p();
1035
1036         /* allocate memory for a new list member */
1037         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
1038         (*last_cmd)->next = NULL;
1039         last_comand_pointer = &((*last_cmd)->next);
1040         (*last_cmd)->type = JTAG_RESET;
1041
1042         (*last_cmd)->cmd.reset = cmd_queue_alloc(sizeof(reset_command_t));
1043         (*last_cmd)->cmd.reset->trst = req_trst;
1044         (*last_cmd)->cmd.reset->srst = req_srst;
1045
1046         
1047         return ERROR_OK;
1048 }
1049
1050 void jtag_add_end_state(enum tap_state state)
1051 {
1052         cmd_queue_end_state = state;
1053         if ((cmd_queue_end_state == TAP_SD)||(cmd_queue_end_state == TAP_SD))
1054         {
1055                 LOG_ERROR("BUG: TAP_SD/SI can't be end state. Calling code should use a larger scan field");
1056         }
1057 }
1058
1059 int MINIDRIVER(interface_jtag_add_sleep)(u32 us)
1060 {
1061         jtag_command_t **last_cmd = jtag_get_last_command_p();
1062         
1063         /* allocate memory for a new list member */
1064         *last_cmd = cmd_queue_alloc(sizeof(jtag_command_t));
1065         (*last_cmd)->next = NULL;
1066         last_comand_pointer = &((*last_cmd)->next);
1067         (*last_cmd)->type = JTAG_SLEEP;
1068
1069         (*last_cmd)->cmd.sleep = cmd_queue_alloc(sizeof(sleep_command_t));
1070         (*last_cmd)->cmd.sleep->us = us;
1071         
1072         return ERROR_OK;
1073 }
1074
1075 void jtag_add_sleep(u32 us)
1076 {
1077         int retval=interface_jtag_add_sleep(us);
1078         if (retval!=ERROR_OK)
1079                 jtag_error=retval;
1080         return;
1081 }
1082
1083 int jtag_scan_size(scan_command_t *cmd)
1084 {
1085         int bit_count = 0;
1086         int i;
1087
1088         /* count bits in scan command */
1089         for (i = 0; i < cmd->num_fields; i++)
1090         {
1091                 bit_count += cmd->fields[i].num_bits;
1092         }
1093
1094         return bit_count;
1095 }
1096
1097 int jtag_build_buffer(scan_command_t *cmd, u8 **buffer)
1098 {
1099         int bit_count = 0;
1100         int i;
1101         
1102         bit_count = jtag_scan_size(cmd);
1103         *buffer = malloc(CEIL(bit_count, 8));
1104         
1105         bit_count = 0;
1106
1107         for (i = 0; i < cmd->num_fields; i++)
1108         {
1109                 if (cmd->fields[i].out_value)
1110                 {
1111 #ifdef _DEBUG_JTAG_IO_
1112                         char* char_buf = buf_to_str(cmd->fields[i].out_value, (cmd->fields[i].num_bits > 64) ? 64 : cmd->fields[i].num_bits, 16);
1113 #endif
1114                         buf_set_buf(cmd->fields[i].out_value, 0, *buffer, bit_count, cmd->fields[i].num_bits);
1115 #ifdef _DEBUG_JTAG_IO_
1116                         LOG_DEBUG("fields[%i].out_value: 0x%s", i, char_buf);
1117                         free(char_buf);
1118 #endif
1119                 }
1120                 
1121                 bit_count += cmd->fields[i].num_bits;
1122         }
1123
1124         return bit_count;
1125
1126 }
1127
1128 int jtag_read_buffer(u8 *buffer, scan_command_t *cmd)
1129 {
1130         int i;
1131         int bit_count = 0;
1132         int retval;
1133         
1134         /* we return ERROR_OK, unless a check fails, or a handler reports a problem */
1135         retval = ERROR_OK;
1136         
1137         for (i = 0; i < cmd->num_fields; i++)
1138         {
1139                 /* if neither in_value nor in_handler
1140                  * are specified we don't have to examine this field
1141                  */
1142                 if (cmd->fields[i].in_value || cmd->fields[i].in_handler)
1143                 {
1144                         int num_bits = cmd->fields[i].num_bits;
1145                         u8 *captured = buf_set_buf(buffer, bit_count, malloc(CEIL(num_bits, 8)), 0, num_bits);
1146                         
1147 #ifdef _DEBUG_JTAG_IO_
1148                         char *char_buf;
1149
1150                         char_buf = buf_to_str(captured, (num_bits > 64) ? 64 : num_bits, 16);
1151                         LOG_DEBUG("fields[%i].in_value: 0x%s", i, char_buf);
1152                         free(char_buf);
1153 #endif
1154                         
1155                         if (cmd->fields[i].in_value)
1156                         {
1157                                 buf_cpy(captured, cmd->fields[i].in_value, num_bits);
1158                                 
1159                                 if (cmd->fields[i].in_handler)
1160                                 {
1161                                         if (cmd->fields[i].in_handler(cmd->fields[i].in_value, cmd->fields[i].in_handler_priv, cmd->fields+i) != ERROR_OK)
1162                                         {
1163                                                 LOG_WARNING("in_handler reported a failed check");
1164                                                 retval = ERROR_JTAG_QUEUE_FAILED;
1165                                         }
1166                                 }
1167                         }
1168                         
1169                         /* no in_value specified, but a handler takes care of the scanned data */
1170                         if (cmd->fields[i].in_handler && (!cmd->fields[i].in_value))
1171                         {
1172                                 if (cmd->fields[i].in_handler(captured, cmd->fields[i].in_handler_priv, cmd->fields+i) != ERROR_OK)
1173                                 {
1174                                         /* We're going to call the error:handler later, but if the in_handler
1175                                          * reported an error we report this failure upstream
1176                                          */
1177                                         LOG_WARNING("in_handler reported a failed check");
1178                                         retval = ERROR_JTAG_QUEUE_FAILED;
1179                                 }
1180                         }
1181
1182                         free(captured);
1183                 }
1184                 bit_count += cmd->fields[i].num_bits;
1185         }
1186
1187         return retval;
1188 }
1189
1190 int jtag_check_value(u8 *captured, void *priv, scan_field_t *field)
1191 {
1192         int retval = ERROR_OK;
1193         int num_bits = field->num_bits;
1194         
1195         int compare_failed = 0;
1196         
1197         if (field->in_check_mask)
1198                 compare_failed = buf_cmp_mask(captured, field->in_check_value, field->in_check_mask, num_bits);
1199         else
1200                 compare_failed = buf_cmp(captured, field->in_check_value, num_bits);
1201         
1202         if (compare_failed)
1203                 {
1204                 /* An error handler could have caught the failing check
1205                  * only report a problem when there wasn't a handler, or if the handler
1206                  * acknowledged the error
1207                  */ 
1208                 if (compare_failed)
1209                 {
1210                         char *captured_char = buf_to_str(captured, (num_bits > 64) ? 64 : num_bits, 16);
1211                         char *in_check_value_char = buf_to_str(field->in_check_value, (num_bits > 64) ? 64 : num_bits, 16);
1212
1213                         if (field->in_check_mask)
1214                         {
1215                                 char *in_check_mask_char;
1216                                 in_check_mask_char = buf_to_str(field->in_check_mask, (num_bits > 64) ? 64 : num_bits, 16);
1217                                 LOG_WARNING("value captured during scan didn't pass the requested check: captured: 0x%s check_value: 0x%s check_mask: 0x%s", captured_char, in_check_value_char, in_check_mask_char);
1218                                 free(in_check_mask_char);
1219                         }
1220                         else
1221                         {
1222                                 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);
1223                         }
1224
1225                         free(captured_char);
1226                         free(in_check_value_char);
1227                         
1228                         retval = ERROR_JTAG_QUEUE_FAILED;
1229                 }
1230                 
1231         }
1232         return retval;
1233 }
1234
1235 /* 
1236   set up checking of this field using the in_handler. The values passed in must be valid until
1237   after jtag_execute() has completed.
1238  */
1239 void jtag_set_check_value(scan_field_t *field, u8 *value, u8 *mask, error_handler_t *in_error_handler)
1240 {
1241         if (value)
1242                 field->in_handler = jtag_check_value;
1243         else
1244                 field->in_handler = NULL;       /* No check, e.g. embeddedice uses value==NULL to indicate no check */
1245         field->in_handler_priv = NULL;
1246         field->in_check_value = value;
1247         field->in_check_mask = mask;
1248 }
1249
1250 enum scan_type jtag_scan_type(scan_command_t *cmd)
1251 {
1252         int i;
1253         int type = 0;
1254         
1255         for (i = 0; i < cmd->num_fields; i++)
1256         {
1257                 if (cmd->fields[i].in_value || cmd->fields[i].in_handler)
1258                         type |= SCAN_IN;
1259                 if (cmd->fields[i].out_value)
1260                         type |= SCAN_OUT;
1261         }
1262
1263         return type;
1264 }
1265
1266 int MINIDRIVER(interface_jtag_execute_queue)(void)
1267 {
1268         int retval;
1269         
1270         if (jtag==NULL)
1271         {
1272                 LOG_ERROR("No JTAG interface configured yet. Issue 'init' command in startup scripts before communicating with targets.");
1273                 return ERROR_FAIL;
1274         }
1275         
1276         retval = jtag->execute_queue();
1277         
1278         cmd_queue_free();
1279
1280         jtag_command_queue = NULL;
1281         last_comand_pointer = &jtag_command_queue;
1282
1283         return retval;
1284 }
1285
1286 int jtag_execute_queue(void)
1287 {
1288         int retval=interface_jtag_execute_queue();
1289         if (retval==ERROR_OK)
1290         {
1291                 retval=jtag_error;
1292         }
1293         jtag_error=ERROR_OK;
1294         return retval;
1295 }
1296
1297 int jtag_reset_callback(enum jtag_event event, void *priv)
1298 {
1299         jtag_device_t *device = priv;
1300
1301         LOG_DEBUG("-");
1302         
1303         if (event == JTAG_TRST_ASSERTED)
1304         {
1305                 buf_set_ones(device->cur_instr, device->ir_length);
1306                 device->bypass = 1;
1307         }
1308         
1309         return ERROR_OK;
1310 }
1311
1312 void jtag_sleep(u32 us)
1313 {
1314         usleep(us);
1315 }
1316
1317 /* Try to examine chain layout according to IEEE 1149.1 Â§12
1318  */
1319 int jtag_examine_chain()
1320 {
1321         jtag_device_t *device = jtag_devices;
1322         scan_field_t field;
1323         u8 idcode_buffer[JTAG_MAX_CHAIN_SIZE * 4];
1324         int i;
1325         int bit_count;
1326         int device_count = 0;
1327         u8 zero_check = 0x0;
1328         u8 one_check = 0xff;
1329         
1330         field.device = 0;
1331         field.num_bits = sizeof(idcode_buffer) * 8;
1332         field.out_value = idcode_buffer;
1333         field.out_mask = NULL;
1334         field.in_value = idcode_buffer;
1335         field.in_check_value = NULL;
1336         field.in_check_mask = NULL;
1337         field.in_handler = NULL;
1338         field.in_handler_priv = NULL;
1339         
1340         for (i = 0; i < JTAG_MAX_CHAIN_SIZE; i++)
1341         {
1342                 buf_set_u32(idcode_buffer, i * 32, 32, 0x000000FF);
1343         }
1344         
1345         jtag_add_plain_dr_scan(1, &field, TAP_TLR);
1346         jtag_execute_queue();
1347         
1348         for (i = 0; i < JTAG_MAX_CHAIN_SIZE * 4; i++)
1349         {
1350                 zero_check |= idcode_buffer[i];
1351                 one_check &= idcode_buffer[i];
1352         }
1353         
1354         /* if there wasn't a single non-zero bit or if all bits were one, the scan isn't valid */
1355         if ((zero_check == 0x00) || (one_check == 0xff))
1356         {
1357                 LOG_ERROR("JTAG communication failure, check connection, JTAG interface, target power etc.");
1358                 return ERROR_JTAG_INIT_FAILED;
1359         }
1360         
1361         for (bit_count = 0; bit_count < (JTAG_MAX_CHAIN_SIZE * 32) - 31;)
1362         {
1363                 u32 idcode = buf_get_u32(idcode_buffer, bit_count, 32);
1364                 if ((idcode & 1) == 0)
1365                 {
1366                         /* LSB must not be 0, this indicates a device in bypass */
1367                         device_count++;
1368                         
1369                         bit_count += 1;
1370                 }
1371                 else
1372                 {
1373                         u32 manufacturer;
1374                         u32 part;
1375                         u32 version;
1376                         
1377                         if (idcode == 0x000000FF)
1378                         {
1379                                 /* End of chain (invalid manufacturer ID) */
1380                                 break;
1381                         }
1382                         
1383                         if (device)
1384                         {
1385                                 device->idcode = idcode;
1386                                 device = device->next;
1387                         }
1388                         device_count++;
1389                         
1390                         manufacturer = (idcode & 0xffe) >> 1;
1391                         part = (idcode & 0xffff000) >> 12;
1392                         version = (idcode & 0xf0000000) >> 28;
1393
1394                         LOG_INFO("JTAG device found: 0x%8.8x (Manufacturer: 0x%3.3x, Part: 0x%4.4x, Version: 0x%1.1x)", 
1395                                 idcode, manufacturer, part, version);
1396                         
1397                         bit_count += 32;
1398                 }
1399         }
1400         
1401         /* see if number of discovered devices matches configuration */
1402         if (device_count != jtag_num_devices)
1403         {
1404                 LOG_ERROR("number of discovered devices in JTAG chain (%i) doesn't match configuration (%i)", 
1405                                 device_count, jtag_num_devices);
1406                 LOG_ERROR("check the config file and ensure proper JTAG communication (connections, speed, ...)");
1407                 return ERROR_JTAG_INIT_FAILED;
1408         }
1409         
1410         return ERROR_OK;
1411 }
1412
1413 int jtag_validate_chain()
1414 {
1415         jtag_device_t *device = jtag_devices;
1416         int total_ir_length = 0;
1417         u8 *ir_test = NULL;
1418         scan_field_t field;
1419         int chain_pos = 0;
1420         
1421         while (device)
1422         {
1423                 total_ir_length += device->ir_length;
1424                 device = device->next;
1425         }
1426         
1427         total_ir_length += 2;
1428         ir_test = malloc(CEIL(total_ir_length, 8));
1429         buf_set_ones(ir_test, total_ir_length);
1430         
1431         field.device = 0;
1432         field.num_bits = total_ir_length;
1433         field.out_value = ir_test;
1434         field.out_mask = NULL;
1435         field.in_value = ir_test;
1436         field.in_check_value = NULL;
1437         field.in_check_mask = NULL;
1438         field.in_handler = NULL;
1439         field.in_handler_priv = NULL;
1440         
1441         jtag_add_plain_ir_scan(1, &field, TAP_TLR);
1442         jtag_execute_queue();
1443         
1444         device = jtag_devices;
1445         while (device)
1446         {
1447                 if (buf_get_u32(ir_test, chain_pos, 2) != 0x1)
1448                 {
1449                         char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1450                         LOG_ERROR("Error validating JTAG scan chain, IR mismatch, scan returned 0x%s", cbuf);
1451                         free(cbuf);
1452                         free(ir_test);
1453                         return ERROR_JTAG_INIT_FAILED;
1454                 }
1455                 chain_pos += device->ir_length;
1456                 device = device->next;
1457         }
1458         
1459         if (buf_get_u32(ir_test, chain_pos, 2) != 0x3)
1460         {
1461                 char *cbuf = buf_to_str(ir_test, total_ir_length, 16);
1462                 LOG_ERROR("Error validating JTAG scan chain, IR mismatch, scan returned 0x%s", cbuf);
1463                 free(cbuf);
1464                 free(ir_test);
1465                 return ERROR_JTAG_INIT_FAILED;
1466         }
1467         
1468         free(ir_test);
1469         
1470         return ERROR_OK;
1471 }
1472
1473 int jtag_register_commands(struct command_context_s *cmd_ctx)
1474 {
1475         register_command(cmd_ctx, NULL, "interface", handle_interface_command,
1476                 COMMAND_CONFIG, NULL);
1477         register_command(cmd_ctx, NULL, "jtag_speed", handle_jtag_speed_command,
1478                 COMMAND_ANY, "set jtag speed (if supported) <reset speed> [<post reset speed, default value is reset speed>]");
1479         register_command(cmd_ctx, NULL, "jtag_khz", handle_jtag_khz_command,
1480                 COMMAND_ANY, "same as jtag_speed, except it takes maximum khz as arguments. 0 KHz = RTCK.");
1481         register_command(cmd_ctx, NULL, "jtag_device", handle_jtag_device_command,
1482                 COMMAND_CONFIG, "jtag_device <ir_length> <ir_expected> <ir_mask>");
1483         register_command(cmd_ctx, NULL, "reset_config", handle_reset_config_command,
1484                 COMMAND_CONFIG, NULL);
1485         register_command(cmd_ctx, NULL, "jtag_nsrst_delay", handle_jtag_nsrst_delay_command,
1486                 COMMAND_ANY, "jtag_nsrst_delay <ms> - delay after deasserting srst in ms");
1487         register_command(cmd_ctx, NULL, "jtag_ntrst_delay", handle_jtag_ntrst_delay_command,
1488                 COMMAND_ANY, "jtag_ntrst_delay <ms> - delay after deasserting trst in ms");
1489                 
1490         register_command(cmd_ctx, NULL, "scan_chain", handle_scan_chain_command,
1491                 COMMAND_EXEC, "print current scan chain configuration");
1492
1493         register_command(cmd_ctx, NULL, "endstate", handle_endstate_command,
1494                 COMMAND_EXEC, "finish JTAG operations in <tap_state>");
1495         register_command(cmd_ctx, NULL, "jtag_reset", handle_jtag_reset_command,
1496                 COMMAND_EXEC, "toggle reset lines <trst> <srst>");
1497         register_command(cmd_ctx, NULL, "runtest", handle_runtest_command,
1498                 COMMAND_EXEC, "move to Run-Test/Idle, and execute <num_cycles>");
1499         register_command(cmd_ctx, NULL, "irscan", handle_irscan_command,
1500                 COMMAND_EXEC, "execute IR scan <device> <instr> [dev2] [instr2] ...");
1501         add_jim("drscan", Jim_Command_drscan, "execute DR scan <device> <num_bits> <value> <num_bits1> <value2> ...");
1502
1503         register_command(cmd_ctx, NULL, "verify_ircapture", handle_verify_ircapture_command,
1504                 COMMAND_ANY, "verify value captured during Capture-IR <enable|disable>");
1505         return ERROR_OK;
1506 }
1507
1508 int jtag_interface_init(struct command_context_s *cmd_ctx)
1509 {
1510         if (jtag)
1511                 return ERROR_OK;
1512         
1513         if (!jtag_interface)
1514         {
1515                 /* nothing was previously specified by "interface" command */
1516                 LOG_ERROR("JTAG interface has to be specified, see \"interface\" command");
1517                 return ERROR_JTAG_INVALID_INTERFACE;
1518         }
1519         if(hasKHz)
1520         {
1521                 /*stay on "reset speed"*/
1522                 jtag_interface->khz(speed1, &jtag_speed);
1523                 jtag_interface->khz(speed2, &jtag_speed_post_reset);
1524                 hasKHz = 0;
1525         }
1526
1527         if (jtag_interface->init() != ERROR_OK)
1528                 return ERROR_JTAG_INIT_FAILED;
1529
1530         
1531         
1532         jtag = jtag_interface;
1533         return ERROR_OK;
1534 }
1535
1536 static int jtag_init_inner(struct command_context_s *cmd_ctx)
1537 {
1538         int validate_tries = 0;
1539         jtag_device_t *device;
1540         int retval;
1541
1542         LOG_DEBUG("Init JTAG chain");
1543         
1544         device = jtag_devices;
1545         jtag_ir_scan_size = 0;
1546         jtag_num_devices = 0;
1547         while (device != NULL)
1548         {
1549                 jtag_ir_scan_size += device->ir_length;
1550                 jtag_num_devices++;
1551                 device = device->next;
1552         }
1553         
1554         jtag_add_tlr();
1555         if ((retval=jtag_execute_queue())!=ERROR_OK)
1556                 return retval;
1557
1558         /* examine chain first, as this could discover the real chain layout */
1559         if (jtag_examine_chain() != ERROR_OK)
1560         {
1561                 LOG_ERROR("trying to validate configured JTAG chain anyway...");
1562         }
1563         
1564         while (jtag_validate_chain() != ERROR_OK)
1565         {
1566                 validate_tries++;
1567                 
1568                 if (validate_tries > 5)
1569                 {
1570                         LOG_ERROR("Could not validate JTAG chain, exit");
1571                         return ERROR_JTAG_INVALID_INTERFACE;
1572                 }
1573                 usleep(10000);
1574         }
1575         
1576         return ERROR_OK;
1577 }
1578
1579 int jtag_init_reset(struct command_context_s *cmd_ctx)
1580 {
1581         int retval;
1582
1583         if ((retval=jtag_interface_init(cmd_ctx)) != ERROR_OK)
1584                 return retval;
1585
1586         LOG_DEBUG("Trying to bring the JTAG controller to life by asserting TRST / TLR");
1587
1588         /* Reset can happen after a power cycle.
1589          * 
1590          * Ideally we would only assert TRST or run TLR before the target reset.
1591          * 
1592          * However w/srst_pulls_trst, trst is asserted together with the target
1593          * reset whether we want it or not.
1594          * 
1595          * NB! Some targets have JTAG circuitry disabled until a 
1596          * trst & srst has been asserted.
1597          * 
1598          * NB! here we assume nsrst/ntrst delay are sufficient!
1599          * 
1600          * NB! order matters!!!! srst *can* disconnect JTAG circuitry
1601          * 
1602          */
1603         jtag_add_reset(1, 0); /* TLR or TRST */
1604         if (jtag_reset_config & RESET_HAS_SRST)
1605         {
1606                 jtag_add_reset(1, 1);
1607                 if ((jtag_reset_config & RESET_SRST_PULLS_TRST)==0)
1608                         jtag_add_reset(0, 1);
1609         }
1610         jtag_add_reset(0, 0);
1611         if ((retval = jtag_execute_queue()) != ERROR_OK)
1612                 return retval;
1613         
1614         /* Check that we can communication on the JTAG chain + eventually we want to
1615          * be able to perform enumeration only after OpenOCD has started 
1616          * telnet and GDB server
1617          * 
1618          * That would allow users to more easily perform any magic they need to before
1619          * reset happens.
1620          */
1621         return jtag_init_inner(cmd_ctx);
1622 }
1623
1624 int jtag_init(struct command_context_s *cmd_ctx)
1625 {
1626         int retval;
1627         if ((retval=jtag_interface_init(cmd_ctx)) != ERROR_OK)
1628                 return retval;
1629         if (jtag_init_inner(cmd_ctx)==ERROR_OK)
1630         {
1631                 return ERROR_OK;
1632         }
1633         return jtag_init_reset(cmd_ctx);
1634 }
1635
1636
1637 static int default_khz(int khz, int *jtag_speed)
1638 {
1639         LOG_ERROR("Translation from khz to jtag_speed not implemented");
1640         return ERROR_FAIL;
1641 }
1642
1643 static int default_speed_div(int speed, int *khz)
1644 {
1645         return ERROR_FAIL;      
1646 }
1647
1648 int handle_interface_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1649 {
1650         int i;
1651
1652         /* check whether the interface is already configured */
1653         if (jtag_interface)
1654         {
1655                 LOG_WARNING("Interface already configured, ignoring");
1656                 return ERROR_OK;
1657         }
1658
1659         /* interface name is a mandatory argument */
1660         if (argc < 1 || args[0][0] == '\0')
1661         {
1662                 return ERROR_COMMAND_SYNTAX_ERROR;
1663         }
1664
1665         for (i=0; jtag_interfaces[i]; i++)
1666         {
1667                 if (strcmp(args[0], jtag_interfaces[i]->name) == 0)
1668                 {
1669                         if (jtag_interfaces[i]->register_commands(cmd_ctx) != ERROR_OK)
1670                                 exit(-1);
1671
1672                         jtag_interface = jtag_interfaces[i];
1673                         
1674                         if (jtag_interface->khz == NULL)
1675                         {
1676                                 jtag_interface->khz = default_khz;
1677                         }
1678                         if (jtag_interface->speed_div == NULL)
1679                         {
1680                                 jtag_interface->speed_div = default_speed_div;
1681                         }
1682                         return ERROR_OK;
1683                 }
1684         }
1685
1686         /* no valid interface was found (i.e. the configuration option,
1687          * didn't match one of the compiled-in interfaces
1688          */
1689         LOG_ERROR("No valid jtag interface found (%s)", args[0]);
1690         LOG_ERROR("compiled-in jtag interfaces:");
1691         for (i = 0; jtag_interfaces[i]; i++)
1692         {
1693                 LOG_ERROR("%i: %s", i, jtag_interfaces[i]->name);
1694         }
1695
1696         return ERROR_JTAG_INVALID_INTERFACE;
1697 }
1698
1699 int handle_jtag_device_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1700 {
1701         jtag_device_t **last_device_p = &jtag_devices;
1702
1703         if (*last_device_p)
1704         {
1705                 while ((*last_device_p)->next)
1706                         last_device_p = &((*last_device_p)->next);
1707                 last_device_p = &((*last_device_p)->next);
1708         }
1709
1710         if (argc < 3)
1711                 return ERROR_OK;
1712
1713         *last_device_p = malloc(sizeof(jtag_device_t));
1714         (*last_device_p)->ir_length = strtoul(args[0], NULL, 0);
1715
1716         (*last_device_p)->expected = malloc((*last_device_p)->ir_length);
1717         buf_set_u32((*last_device_p)->expected, 0, (*last_device_p)->ir_length, strtoul(args[1], NULL, 0));
1718         (*last_device_p)->expected_mask = malloc((*last_device_p)->ir_length);
1719         buf_set_u32((*last_device_p)->expected_mask, 0, (*last_device_p)->ir_length, strtoul(args[2], NULL, 0));
1720
1721         (*last_device_p)->cur_instr = malloc((*last_device_p)->ir_length);
1722         (*last_device_p)->bypass = 1;
1723         buf_set_ones((*last_device_p)->cur_instr, (*last_device_p)->ir_length);
1724         
1725         (*last_device_p)->next = NULL;
1726         
1727         jtag_register_event_callback(jtag_reset_callback, (*last_device_p));
1728         
1729         jtag_num_devices++;
1730         
1731         return ERROR_OK;
1732 }
1733
1734 int handle_scan_chain_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1735 {
1736         jtag_device_t *device = jtag_devices;
1737         int device_count = 0;
1738         
1739         while (device)
1740         {
1741                 u32 expected, expected_mask, cur_instr;
1742                 expected = buf_get_u32(device->expected, 0, device->ir_length);
1743                 expected_mask = buf_get_u32(device->expected_mask, 0, device->ir_length);
1744                 cur_instr = buf_get_u32(device->cur_instr, 0, device->ir_length);
1745                 command_print(cmd_ctx, "%i: idcode: 0x%8.8x ir length %i, ir capture 0x%x, ir mask 0x%x, current instruction 0x%x", device_count, device->idcode, device->ir_length, expected, expected_mask, cur_instr);
1746                 device = device->next;
1747                 device_count++;
1748         }
1749
1750         return ERROR_OK;
1751 }
1752
1753 int handle_reset_config_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1754 {
1755         if (argc < 1)
1756                 return ERROR_COMMAND_SYNTAX_ERROR;
1757         
1758         if (argc >= 1)
1759         {
1760                 if (strcmp(args[0], "none") == 0)
1761                         jtag_reset_config = RESET_NONE;
1762                 else if (strcmp(args[0], "trst_only") == 0)
1763                         jtag_reset_config = RESET_HAS_TRST;
1764                 else if (strcmp(args[0], "srst_only") == 0)
1765                         jtag_reset_config = RESET_HAS_SRST;
1766                 else if (strcmp(args[0], "trst_and_srst") == 0)
1767                         jtag_reset_config = RESET_TRST_AND_SRST;
1768                 else
1769                 {
1770                         LOG_ERROR("invalid reset_config argument, defaulting to none");
1771                         jtag_reset_config = RESET_NONE;
1772                         return ERROR_INVALID_ARGUMENTS;
1773                 }
1774         }
1775         
1776         if (argc >= 2)
1777         {
1778                 if (strcmp(args[1], "separate") == 0)
1779                 {
1780                         /* seperate reset lines - default */
1781                 } else
1782                 {
1783                         if (strcmp(args[1], "srst_pulls_trst") == 0)
1784                                 jtag_reset_config |= RESET_SRST_PULLS_TRST;
1785                         else if (strcmp(args[1], "trst_pulls_srst") == 0)
1786                                 jtag_reset_config |= RESET_TRST_PULLS_SRST;
1787                         else if (strcmp(args[1], "combined") == 0)
1788                                 jtag_reset_config |= RESET_SRST_PULLS_TRST | RESET_TRST_PULLS_SRST;
1789                         else
1790                         {
1791                                 LOG_ERROR("invalid reset_config argument, defaulting to none");
1792                                 jtag_reset_config = RESET_NONE;
1793                                 return ERROR_INVALID_ARGUMENTS;
1794                         }
1795                 }
1796         }
1797         
1798         if (argc >= 3)
1799         {
1800                 if (strcmp(args[2], "trst_open_drain") == 0)
1801                         jtag_reset_config |= RESET_TRST_OPEN_DRAIN;
1802                 else if (strcmp(args[2], "trst_push_pull") == 0)
1803                         jtag_reset_config &= ~RESET_TRST_OPEN_DRAIN;
1804                 else
1805                 {
1806                         LOG_ERROR("invalid reset_config argument, defaulting to none");
1807                         jtag_reset_config = RESET_NONE;
1808                         return ERROR_INVALID_ARGUMENTS;
1809                 }
1810         }
1811
1812         if (argc >= 4)
1813         {
1814                 if (strcmp(args[3], "srst_push_pull") == 0)
1815                         jtag_reset_config |= RESET_SRST_PUSH_PULL;
1816                 else if (strcmp(args[3], "srst_open_drain") == 0)
1817                         jtag_reset_config &= ~RESET_SRST_PUSH_PULL;
1818                 else
1819                 {
1820                         LOG_ERROR("invalid reset_config argument, defaulting to none");
1821                         jtag_reset_config = RESET_NONE;
1822                         return ERROR_INVALID_ARGUMENTS;
1823                 }
1824         }
1825         
1826         return ERROR_OK;
1827 }
1828
1829 int handle_jtag_nsrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1830 {
1831         if (argc < 1)
1832         {
1833                 LOG_ERROR("jtag_nsrst_delay <ms> command takes one required argument");
1834                 exit(-1);
1835         }
1836         else
1837         {
1838                 jtag_nsrst_delay = strtoul(args[0], NULL, 0);
1839         }
1840         
1841         return ERROR_OK;
1842 }
1843
1844 int handle_jtag_ntrst_delay_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1845 {
1846         if (argc < 1)
1847         {
1848                 LOG_ERROR("jtag_ntrst_delay <ms> command takes one required argument");
1849                 exit(-1);
1850         }
1851         else
1852         {
1853                 jtag_ntrst_delay = strtoul(args[0], NULL, 0);
1854         }
1855         
1856         return ERROR_OK;
1857 }
1858
1859 int handle_jtag_speed_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1860 {
1861         int cur_speed = 0;
1862         
1863         if (argc != 0)
1864         {
1865                 if ((argc<1) || (argc>2))
1866                         return ERROR_COMMAND_SYNTAX_ERROR;
1867                 
1868                 LOG_DEBUG("handle jtag speed");
1869                 
1870                 if (argc >= 1)
1871                         cur_speed = jtag_speed = jtag_speed_post_reset = strtoul(args[0], NULL, 0);
1872                 if (argc == 2)
1873                         cur_speed = jtag_speed_post_reset = strtoul(args[1], NULL, 0);
1874                         
1875                 /* this command can be called during CONFIG, 
1876                  * in which case jtag isn't initialized */
1877                 if (jtag)
1878                 {
1879                         jtag->speed_div(jtag_speed, &speed1);
1880                         jtag->speed_div(jtag_speed_post_reset, &speed2);
1881                         jtag->speed(cur_speed);
1882                 }
1883         }               
1884         command_print(cmd_ctx, "jtag_speed: %d, %d", jtag_speed, jtag_speed_post_reset);
1885         
1886         return ERROR_OK;
1887 }
1888
1889 int handle_jtag_khz_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1890 {
1891         LOG_DEBUG("handle jtag khz");
1892         
1893         if (argc>2)
1894                 return ERROR_COMMAND_SYNTAX_ERROR;
1895
1896         if(argc != 0)
1897         {
1898                 
1899                 if (argc >= 1)
1900                         speed1 = speed2 = strtoul(args[0], NULL, 0);
1901                 if (argc == 2)
1902                         speed2 = strtoul(args[1], NULL, 0);
1903         
1904                 if (jtag != NULL)
1905                 {
1906                         int cur_speed = 0;
1907                         LOG_DEBUG("have interface set up");
1908                         int speed_div1, speed_div2;
1909                         if (jtag->khz(speed1, &speed_div1)!=ERROR_OK)
1910                         {
1911                                 speed1 = speed2 = 0;
1912                                 return ERROR_OK;
1913                         }
1914                         if (jtag->khz(speed2, &speed_div2)!=ERROR_OK)
1915                         {
1916                                 speed1 = speed2 = 0;
1917                                 return ERROR_OK;
1918                         }
1919         
1920                         if (argc >= 1)
1921                                 cur_speed = jtag_speed = jtag_speed_post_reset = speed_div1;
1922                         if (argc == 2)
1923                                 cur_speed = jtag_speed_post_reset = speed_div2;
1924         
1925                         jtag->speed(cur_speed);
1926                 } else
1927                 {
1928                         hasKHz = 1;
1929                 }
1930         }
1931         command_print(cmd_ctx, "jtag_khz: %d, %d", speed1, speed2);
1932         
1933         return ERROR_OK;
1934 }
1935
1936
1937 int handle_endstate_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1938 {
1939         enum tap_state state;
1940
1941         if (argc < 1)
1942         {
1943                 return ERROR_COMMAND_SYNTAX_ERROR;
1944         }
1945         else
1946         {
1947                 for (state = 0; state < 16; state++)
1948                 {
1949                         if (strcmp(args[0], tap_state_strings[state]) == 0)
1950                         {
1951                                 jtag_add_end_state(state);
1952                                 jtag_execute_queue();
1953                         }
1954                 }
1955         }
1956         command_print(cmd_ctx, "current endstate: %s", tap_state_strings[cmd_queue_end_state]);
1957         
1958         return ERROR_OK;
1959 }
1960
1961 int handle_jtag_reset_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1962 {
1963         int trst = -1;
1964         int srst = -1;
1965         
1966         if (argc < 2)
1967         {
1968                 return ERROR_COMMAND_SYNTAX_ERROR;
1969         }
1970
1971         if (args[0][0] == '1')
1972                 trst = 1;
1973         else if (args[0][0] == '0')
1974                 trst = 0;
1975         else
1976         {
1977                 return ERROR_COMMAND_SYNTAX_ERROR;
1978         }
1979
1980         if (args[1][0] == '1')
1981                 srst = 1;
1982         else if (args[1][0] == '0')
1983                 srst = 0;
1984         else
1985         {
1986                 return ERROR_COMMAND_SYNTAX_ERROR;
1987         }
1988
1989         if (jtag_interface_init(cmd_ctx) != ERROR_OK)
1990                 return ERROR_JTAG_INIT_FAILED;
1991
1992         jtag_add_reset(trst, srst);
1993         jtag_execute_queue();
1994
1995         return ERROR_OK;
1996 }
1997
1998 int handle_runtest_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
1999 {
2000         if (argc < 1)
2001         {
2002                 return ERROR_COMMAND_SYNTAX_ERROR;
2003         }
2004
2005         jtag_add_runtest(strtol(args[0], NULL, 0), -1);
2006         jtag_execute_queue();
2007
2008         return ERROR_OK;
2009
2010 }
2011
2012
2013 int handle_irscan_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2014 {
2015         int i;
2016         scan_field_t *fields;
2017         
2018         if ((argc < 2) || (argc % 2))
2019         {
2020                 return ERROR_COMMAND_SYNTAX_ERROR;
2021         }
2022
2023         fields = malloc(sizeof(scan_field_t) * argc / 2);
2024         
2025         for (i = 0; i < argc / 2; i++)
2026         {
2027                 int device = strtoul(args[i*2], NULL, 0);
2028                 int field_size = jtag_get_device(device)->ir_length;
2029                 fields[i].device = device;
2030                 fields[i].out_value = malloc(CEIL(field_size, 8));
2031                 buf_set_u32(fields[i].out_value, 0, field_size, strtoul(args[i*2+1], NULL, 0));
2032                 fields[i].out_mask = NULL;
2033                 fields[i].in_value = NULL;
2034                 fields[i].in_check_mask = NULL;
2035                 fields[i].in_handler = NULL;
2036                 fields[i].in_handler_priv = NULL;
2037         }
2038
2039         jtag_add_ir_scan(argc / 2, fields, -1);
2040         jtag_execute_queue();
2041
2042         for (i = 0; i < argc / 2; i++)
2043                 free(fields[i].out_value);
2044
2045         free (fields);
2046
2047         return ERROR_OK;
2048 }
2049
2050 int Jim_Command_drscan(Jim_Interp *interp, int argc, Jim_Obj *const *args)
2051 {
2052         int retval;
2053         scan_field_t *fields;
2054         int num_fields;
2055         int field_count = 0;
2056         int i, j, e;
2057         long device;
2058
2059         /* args[1] = device
2060          * args[2] = num_bits
2061          * args[3] = hex string
2062          * ... repeat num bits and hex string ...
2063          */
2064         if ((argc < 4) || ((argc % 2)!=0))
2065         {
2066                 Jim_WrongNumArgs(interp, 1, args, "wrong arguments");
2067                 return JIM_ERR;
2068         }
2069
2070         for (i = 2; i < argc; i+=2)
2071         {
2072                 long bits;
2073
2074                 e = Jim_GetLong(interp, args[i], &bits);
2075                 if (e != JIM_OK)
2076                         return e;
2077         }
2078
2079         e = Jim_GetLong(interp, args[1], &device);
2080         if (e != JIM_OK)
2081                 return e;
2082
2083         num_fields=(argc-2)/2;
2084         fields = malloc(sizeof(scan_field_t) * num_fields);
2085         for (i = 2; i < argc; i+=2)
2086         {
2087                 long bits;
2088                 int len;
2089                 const char *str;
2090
2091                 Jim_GetLong(interp, args[i], &bits);
2092                 str = Jim_GetString(args[i+1], &len);
2093                 
2094                 fields[field_count].device = device;
2095                 fields[field_count].num_bits = bits;
2096                 fields[field_count].out_value = malloc(CEIL(bits, 8));
2097                 str_to_buf(str, len, fields[field_count].out_value, bits, 0);
2098                 fields[field_count].out_mask = NULL;
2099                 fields[field_count].in_value = fields[field_count].out_value;
2100                 fields[field_count].in_check_mask = NULL;
2101                 fields[field_count].in_check_value = NULL;
2102                 fields[field_count].in_handler = NULL;
2103                 fields[field_count++].in_handler_priv = NULL;
2104         }
2105
2106         jtag_add_dr_scan(num_fields, fields, -1);
2107         retval = jtag_execute_queue();
2108         if (retval != ERROR_OK)
2109         {
2110                 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
2111                 Jim_AppendStrings(interp, Jim_GetResult(interp), "drscan: jtag execute failed", NULL);
2112                 return JIM_ERR;
2113         }
2114
2115         field_count=0;
2116         Jim_Obj *list = Jim_NewListObj(interp, NULL, 0);
2117         for (i = 2; i < argc; i+=2)
2118         {
2119                 long bits;
2120                 char *str;
2121
2122                 Jim_GetLong(interp, args[i], &bits);
2123                 str = buf_to_str(fields[field_count].in_value, bits, 16);
2124                 free(fields[field_count].out_value);
2125
2126                 Jim_ListAppendElement(interp, list, Jim_NewStringObj(interp, str, strlen(str)));
2127                 free(str);
2128                 field_count++;
2129         }
2130
2131         Jim_SetResult(interp, list);
2132         
2133         free(fields);
2134
2135         return JIM_OK;
2136 }
2137
2138 int handle_verify_ircapture_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
2139 {
2140         if (argc == 1)
2141         {
2142                 if (strcmp(args[0], "enable") == 0)
2143                 {
2144                         jtag_verify_capture_ir = 1;
2145                 }
2146                 else if (strcmp(args[0], "disable") == 0)
2147                 {
2148                         jtag_verify_capture_ir = 0;
2149                 } else
2150                 {
2151                         return ERROR_COMMAND_SYNTAX_ERROR;
2152                 }
2153         } else if (argc != 0)
2154         {
2155                 return ERROR_COMMAND_SYNTAX_ERROR;
2156         }
2157         
2158         command_print(cmd_ctx, "verify Capture-IR is %s", (jtag_verify_capture_ir) ? "enabled": "disabled");
2159         
2160         return ERROR_OK;
2161 }