Fix usage of timeval_ms()
[fw/openocd] / src / svf / svf.c
1 /***************************************************************************
2  *    Copyright (C) 2009 by Simon Qian                                     *
3  *    SimonQian@SimonQian.com                                              *
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, see <http://www.gnu.org/licenses/>. *
17  ***************************************************************************/
18
19 /* The specification for SVF is available here:
20  * http://www.asset-intertech.com/support/svf.pdf
21  * Below, this document is refered to as the "SVF spec".
22  *
23  * The specification for XSVF is available here:
24  * http://www.xilinx.com/support/documentation/application_notes/xapp503.pdf
25  * Below, this document is refered to as the "XSVF spec".
26  */
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #include <jtag/jtag.h>
33 #include "svf.h"
34 #include <helper/time_support.h>
35
36 /* SVF command */
37 enum svf_command {
38         ENDDR,
39         ENDIR,
40         FREQUENCY,
41         HDR,
42         HIR,
43         PIO,
44         PIOMAP,
45         RUNTEST,
46         SDR,
47         SIR,
48         STATE,
49         TDR,
50         TIR,
51         TRST,
52 };
53
54 static const char *svf_command_name[14] = {
55         "ENDDR",
56         "ENDIR",
57         "FREQUENCY",
58         "HDR",
59         "HIR",
60         "PIO",
61         "PIOMAP",
62         "RUNTEST",
63         "SDR",
64         "SIR",
65         "STATE",
66         "TDR",
67         "TIR",
68         "TRST"
69 };
70
71 enum trst_mode {
72         TRST_ON,
73         TRST_OFF,
74         TRST_Z,
75         TRST_ABSENT
76 };
77
78 static const char *svf_trst_mode_name[4] = {
79         "ON",
80         "OFF",
81         "Z",
82         "ABSENT"
83 };
84
85 struct svf_statemove {
86         tap_state_t from;
87         tap_state_t to;
88         uint32_t num_of_moves;
89         tap_state_t paths[8];
90 };
91
92 /*
93  * These paths are from the SVF specification for the STATE command, to be
94  * used when the STATE command only includes the final state.  The first
95  * element of the path is the "from" (current) state, and the last one is
96  * the "to" (target) state.
97  *
98  * All specified paths are the shortest ones in the JTAG spec, and are thus
99  * not (!!) exact matches for the paths used elsewhere in OpenOCD.  Note
100  * that PAUSE-to-PAUSE transitions all go through UPDATE and then CAPTURE,
101  * which has specific effects on the various registers; they are not NOPs.
102  *
103  * Paths to RESET are disabled here.  As elsewhere in OpenOCD, and in XSVF
104  * and many SVF implementations, we don't want to risk missing that state.
105  * To get to RESET, always we ignore the current state.
106  */
107 static const struct svf_statemove svf_statemoves[] = {
108         /* from                 to                              num_of_moves,   paths[8] */
109 /*      {TAP_RESET,             TAP_RESET,              1,                              {TAP_RESET}}, */
110         {TAP_RESET,             TAP_IDLE,               2,                              {TAP_RESET, TAP_IDLE} },
111         {TAP_RESET,             TAP_DRPAUSE,    6,                              {TAP_RESET, TAP_IDLE, TAP_DRSELECT,
112                                                                                                                 TAP_DRCAPTURE, TAP_DREXIT1, TAP_DRPAUSE} },
113         {TAP_RESET,             TAP_IRPAUSE,    7,                              {TAP_RESET, TAP_IDLE, TAP_DRSELECT,
114                                                                                                                 TAP_IRSELECT, TAP_IRCAPTURE,
115                                                                                                                 TAP_IREXIT1, TAP_IRPAUSE} },
116
117 /*      {TAP_IDLE,              TAP_RESET,              4,                              {TAP_IDLE,
118  * TAP_DRSELECT, TAP_IRSELECT, TAP_RESET}}, */
119         {TAP_IDLE,              TAP_IDLE,               1,                              {TAP_IDLE} },
120         {TAP_IDLE,              TAP_DRPAUSE,    5,                              {TAP_IDLE, TAP_DRSELECT, TAP_DRCAPTURE,
121                                                                                                                 TAP_DREXIT1, TAP_DRPAUSE} },
122         {TAP_IDLE,              TAP_IRPAUSE,    6,                              {TAP_IDLE, TAP_DRSELECT, TAP_IRSELECT,
123                                                                                                                 TAP_IRCAPTURE, TAP_IREXIT1, TAP_IRPAUSE} },
124
125 /*      {TAP_DRPAUSE,   TAP_RESET,              6,                              {TAP_DRPAUSE,
126  * TAP_DREXIT2, TAP_DRUPDATE, TAP_DRSELECT, TAP_IRSELECT, TAP_RESET}}, */
127         {TAP_DRPAUSE,   TAP_IDLE,               4,                              {TAP_DRPAUSE, TAP_DREXIT2, TAP_DRUPDATE,
128                                                                                                                 TAP_IDLE} },
129         {TAP_DRPAUSE,   TAP_DRPAUSE,    7,                              {TAP_DRPAUSE, TAP_DREXIT2, TAP_DRUPDATE,
130                                                                                                                 TAP_DRSELECT, TAP_DRCAPTURE,
131                                                                                                                 TAP_DREXIT1, TAP_DRPAUSE} },
132         {TAP_DRPAUSE,   TAP_IRPAUSE,    8,                              {TAP_DRPAUSE, TAP_DREXIT2, TAP_DRUPDATE,
133                                                                                                                 TAP_DRSELECT, TAP_IRSELECT,
134                                                                                                                 TAP_IRCAPTURE, TAP_IREXIT1, TAP_IRPAUSE} },
135
136 /*      {TAP_IRPAUSE,   TAP_RESET,              6,                              {TAP_IRPAUSE,
137  * TAP_IREXIT2, TAP_IRUPDATE, TAP_DRSELECT, TAP_IRSELECT, TAP_RESET}}, */
138         {TAP_IRPAUSE,   TAP_IDLE,               4,                              {TAP_IRPAUSE, TAP_IREXIT2, TAP_IRUPDATE,
139                                                                                                                 TAP_IDLE} },
140         {TAP_IRPAUSE,   TAP_DRPAUSE,    7,                              {TAP_IRPAUSE, TAP_IREXIT2, TAP_IRUPDATE,
141                                                                                                                 TAP_DRSELECT, TAP_DRCAPTURE,
142                                                                                                                 TAP_DREXIT1, TAP_DRPAUSE} },
143         {TAP_IRPAUSE,   TAP_IRPAUSE,    8,                              {TAP_IRPAUSE, TAP_IREXIT2, TAP_IRUPDATE,
144                                                                                                                 TAP_DRSELECT, TAP_IRSELECT,
145                                                                                                                 TAP_IRCAPTURE, TAP_IREXIT1, TAP_IRPAUSE} }
146 };
147
148 #define XXR_TDI                         (1 << 0)
149 #define XXR_TDO                         (1 << 1)
150 #define XXR_MASK                        (1 << 2)
151 #define XXR_SMASK                       (1 << 3)
152 struct svf_xxr_para {
153         int len;
154         int data_mask;
155         uint8_t *tdi;
156         uint8_t *tdo;
157         uint8_t *mask;
158         uint8_t *smask;
159 };
160
161 struct svf_para {
162         float frequency;
163         tap_state_t ir_end_state;
164         tap_state_t dr_end_state;
165         tap_state_t runtest_run_state;
166         tap_state_t runtest_end_state;
167         enum trst_mode trst_mode;
168
169         struct svf_xxr_para hir_para;
170         struct svf_xxr_para hdr_para;
171         struct svf_xxr_para tir_para;
172         struct svf_xxr_para tdr_para;
173         struct svf_xxr_para sir_para;
174         struct svf_xxr_para sdr_para;
175 };
176
177 static struct svf_para svf_para;
178 static const struct svf_para svf_para_init = {
179 /*      frequency, ir_end_state, dr_end_state, runtest_run_state, runtest_end_state, trst_mode */
180         0,                      TAP_IDLE,               TAP_IDLE,       TAP_IDLE,               TAP_IDLE,               TRST_Z,
181 /*      hir_para */
182 /*      {len,   data_mask,      tdi,    tdo,    mask,   smask}, */
183         {0,                     0,              NULL,   NULL,   NULL,   NULL},
184 /*      hdr_para */
185 /*      {len,   data_mask,      tdi,    tdo,    mask,   smask}, */
186         {0,                     0,              NULL,   NULL,   NULL,   NULL},
187 /*      tir_para */
188 /*      {len,   data_mask,      tdi,    tdo,    mask,   smask}, */
189         {0,                     0,              NULL,   NULL,   NULL,   NULL},
190 /*      tdr_para */
191 /*      {len,   data_mask,      tdi,    tdo,    mask,   smask}, */
192         {0,                     0,              NULL,   NULL,   NULL,   NULL},
193 /*      sir_para */
194 /*      {len,   data_mask,      tdi,    tdo,    mask,   smask}, */
195         {0,                     0,              NULL,   NULL,   NULL,   NULL},
196 /*      sdr_para */
197 /*      {len,   data_mask,      tdi,    tdo,    mask,   smask}, */
198         {0,                     0,              NULL,   NULL,   NULL,   NULL},
199 };
200
201 struct svf_check_tdo_para {
202         int line_num;           /* used to record line number of the check operation */
203         /* so more information could be printed */
204         int enabled;            /* check is enabled or not */
205         int buffer_offset;      /* buffer_offset to buffers */
206         int bit_len;            /* bit length to check */
207 };
208
209 #define SVF_CHECK_TDO_PARA_SIZE 1024
210 static struct svf_check_tdo_para *svf_check_tdo_para;
211 static int svf_check_tdo_para_index;
212
213 static int svf_read_command_from_file(FILE *fd);
214 static int svf_check_tdo(void);
215 static int svf_add_check_para(uint8_t enabled, int buffer_offset, int bit_len);
216 static int svf_run_command(struct command_context *cmd_ctx, char *cmd_str);
217 static int svf_execute_tap(void);
218
219 static FILE *svf_fd;
220 static char *svf_read_line;
221 static size_t svf_read_line_size;
222 static char *svf_command_buffer;
223 static size_t svf_command_buffer_size;
224 static int svf_line_number;
225 static int svf_getline(char **lineptr, size_t *n, FILE *stream);
226
227 #define SVF_MAX_BUFFER_SIZE_TO_COMMIT   (1024 * 1024)
228 static uint8_t *svf_tdi_buffer, *svf_tdo_buffer, *svf_mask_buffer;
229 static int svf_buffer_index, svf_buffer_size ;
230 static int svf_quiet;
231 static int svf_nil;
232 static int svf_ignore_error;
233
234 /* Targetting particular tap */
235 static int svf_tap_is_specified;
236 static int svf_set_padding(struct svf_xxr_para *para, int len, unsigned char tdi);
237
238 /* Progress Indicator */
239 static int svf_progress_enabled;
240 static long svf_total_lines;
241 static int svf_percentage;
242 static int svf_last_printed_percentage = -1;
243
244 /*
245  * macro is used to print the svf hex buffer at desired debug level
246  * DEBUG, INFO, ERROR, USER
247  */
248 #define SVF_BUF_LOG(_lvl, _buf, _nbits, _desc)                                                  \
249         svf_hexbuf_print(LOG_LVL_##_lvl ,  __FILE__, __LINE__, __func__, _buf, _nbits, _desc)
250
251 static void svf_hexbuf_print(int dbg_lvl, const char *file, unsigned line,
252                                                          const char *function, const uint8_t *buf,
253                                                          int bit_len, const char *desc)
254 {
255         int j, len = 0;
256         int byte_len = DIV_ROUND_UP(bit_len, 8);
257         int msbits = bit_len % 8;
258
259         /* allocate 2 bytes per hex digit */
260         char *prbuf = malloc((byte_len * 2) + 2 + 1);
261         if (!prbuf)
262                 return;
263
264         /* print correct number of bytes, mask excess bits where applicable */
265         uint8_t msb = buf[byte_len - 1] & (msbits ? (1 << msbits) - 1 : 0xff);
266         len = sprintf(prbuf, msbits <= 4 ? "0x%01"PRIx8 : "0x%02"PRIx8, msb);
267         for (j = byte_len - 2; j >= 0; j--)
268                 len += sprintf(prbuf + len, "%02"PRIx8, buf[j]);
269
270         log_printf_lf(dbg_lvl, file, line, function, "%8s = %s", desc ? desc : " ", prbuf);
271
272         free(prbuf);
273 }
274
275 static int svf_realloc_buffers(size_t len)
276 {
277         void *ptr;
278
279         if (svf_execute_tap() != ERROR_OK)
280                 return ERROR_FAIL;
281
282         ptr = realloc(svf_tdi_buffer, len);
283         if (!ptr)
284                 return ERROR_FAIL;
285         svf_tdi_buffer = ptr;
286
287         ptr = realloc(svf_tdo_buffer, len);
288         if (!ptr)
289                 return ERROR_FAIL;
290         svf_tdo_buffer = ptr;
291
292         ptr = realloc(svf_mask_buffer, len);
293         if (!ptr)
294                 return ERROR_FAIL;
295         svf_mask_buffer = ptr;
296
297         svf_buffer_size = len;
298
299         return ERROR_OK;
300 }
301
302 static void svf_free_xxd_para(struct svf_xxr_para *para)
303 {
304         if (NULL != para) {
305                 if (para->tdi != NULL) {
306                         free(para->tdi);
307                         para->tdi = NULL;
308                 }
309                 if (para->tdo != NULL) {
310                         free(para->tdo);
311                         para->tdo = NULL;
312                 }
313                 if (para->mask != NULL) {
314                         free(para->mask);
315                         para->mask = NULL;
316                 }
317                 if (para->smask != NULL) {
318                         free(para->smask);
319                         para->smask = NULL;
320                 }
321         }
322 }
323
324 int svf_add_statemove(tap_state_t state_to)
325 {
326         tap_state_t state_from = cmd_queue_cur_state;
327         unsigned index_var;
328
329         /* when resetting, be paranoid and ignore current state */
330         if (state_to == TAP_RESET) {
331                 if (svf_nil)
332                         return ERROR_OK;
333
334                 jtag_add_tlr();
335                 return ERROR_OK;
336         }
337
338         for (index_var = 0; index_var < ARRAY_SIZE(svf_statemoves); index_var++) {
339                 if ((svf_statemoves[index_var].from == state_from)
340                                 && (svf_statemoves[index_var].to == state_to)) {
341                         if (svf_nil)
342                                 continue;
343                                                 /* recorded path includes current state ... avoid
344                                                  *extra TCKs! */
345                         if (svf_statemoves[index_var].num_of_moves > 1)
346                                 jtag_add_pathmove(svf_statemoves[index_var].num_of_moves - 1,
347                                         svf_statemoves[index_var].paths + 1);
348                         else
349                                 jtag_add_pathmove(svf_statemoves[index_var].num_of_moves,
350                                         svf_statemoves[index_var].paths);
351                         return ERROR_OK;
352                 }
353         }
354         LOG_ERROR("SVF: can not move to %s", tap_state_name(state_to));
355         return ERROR_FAIL;
356 }
357
358 COMMAND_HANDLER(handle_svf_command)
359 {
360 #define SVF_MIN_NUM_OF_OPTIONS 1
361 #define SVF_MAX_NUM_OF_OPTIONS 5
362         int command_num = 0;
363         int ret = ERROR_OK;
364         int64_t time_measure_ms;
365         int time_measure_s, time_measure_m;
366
367         /* use NULL to indicate a "plain" svf file which accounts for
368          * any additional devices in the scan chain, otherwise the device
369          * that should be affected
370         */
371         struct jtag_tap *tap = NULL;
372
373         if ((CMD_ARGC < SVF_MIN_NUM_OF_OPTIONS) || (CMD_ARGC > SVF_MAX_NUM_OF_OPTIONS))
374                 return ERROR_COMMAND_SYNTAX_ERROR;
375
376         /* parse command line */
377         svf_quiet = 0;
378         svf_nil = 0;
379         svf_progress_enabled = 0;
380         svf_ignore_error = 0;
381         for (unsigned int i = 0; i < CMD_ARGC; i++) {
382                 if (strcmp(CMD_ARGV[i], "-tap") == 0) {
383                         tap = jtag_tap_by_string(CMD_ARGV[i+1]);
384                         if (!tap) {
385                                 command_print(CMD_CTX, "Tap: %s unknown", CMD_ARGV[i+1]);
386                                 return ERROR_FAIL;
387                         }
388                         i++;
389                 } else if ((strcmp(CMD_ARGV[i],
390                                 "quiet") == 0) || (strcmp(CMD_ARGV[i], "-quiet") == 0))
391                         svf_quiet = 1;
392                 else if ((strcmp(CMD_ARGV[i], "nil") == 0) || (strcmp(CMD_ARGV[i], "-nil") == 0))
393                         svf_nil = 1;
394                 else if ((strcmp(CMD_ARGV[i],
395                                   "progress") == 0) || (strcmp(CMD_ARGV[i], "-progress") == 0))
396                         svf_progress_enabled = 1;
397                 else if ((strcmp(CMD_ARGV[i],
398                                   "ignore_error") == 0) || (strcmp(CMD_ARGV[i], "-ignore_error") == 0))
399                         svf_ignore_error = 1;
400                 else {
401                         svf_fd = fopen(CMD_ARGV[i], "r");
402                         if (svf_fd == NULL) {
403                                 int err = errno;
404                                 command_print(CMD_CTX, "open(\"%s\"): %s", CMD_ARGV[i], strerror(err));
405                                 /* no need to free anything now */
406                                 return ERROR_COMMAND_SYNTAX_ERROR;
407                         } else
408                                 LOG_USER("svf processing file: \"%s\"", CMD_ARGV[i]);
409                 }
410         }
411
412         if (svf_fd == NULL)
413                 return ERROR_COMMAND_SYNTAX_ERROR;
414
415         /* get time */
416         time_measure_ms = timeval_ms();
417
418         /* init */
419         svf_line_number = 0;
420         svf_command_buffer_size = 0;
421
422         svf_check_tdo_para_index = 0;
423         svf_check_tdo_para = malloc(sizeof(struct svf_check_tdo_para) * SVF_CHECK_TDO_PARA_SIZE);
424         if (NULL == svf_check_tdo_para) {
425                 LOG_ERROR("not enough memory");
426                 ret = ERROR_FAIL;
427                 goto free_all;
428         }
429
430         svf_buffer_index = 0;
431         /* double the buffer size */
432         /* in case current command cannot be committed, and next command is a bit scan command */
433         /* here is 32K bits for this big scan command, it should be enough */
434         /* buffer will be reallocated if buffer size is not enough */
435         if (svf_realloc_buffers(2 * SVF_MAX_BUFFER_SIZE_TO_COMMIT) != ERROR_OK) {
436                 ret = ERROR_FAIL;
437                 goto free_all;
438         }
439
440         memcpy(&svf_para, &svf_para_init, sizeof(svf_para));
441
442         if (!svf_nil) {
443                 /* TAP_RESET */
444                 jtag_add_tlr();
445         }
446
447         if (tap) {
448                 /* Tap is specified, set header/trailer paddings */
449                 int header_ir_len = 0, header_dr_len = 0, trailer_ir_len = 0, trailer_dr_len = 0;
450                 struct jtag_tap *check_tap;
451
452                 svf_tap_is_specified = 1;
453
454                 for (check_tap = jtag_all_taps(); check_tap; check_tap = check_tap->next_tap) {
455                         if (check_tap->abs_chain_position < tap->abs_chain_position) {
456                                 /* Header */
457                                 header_ir_len += check_tap->ir_length;
458                                 header_dr_len++;
459                         } else if (check_tap->abs_chain_position > tap->abs_chain_position) {
460                                 /* Trailer */
461                                 trailer_ir_len += check_tap->ir_length;
462                                 trailer_dr_len++;
463                         }
464                 }
465
466                 /* HDR %d TDI (0) */
467                 if (ERROR_OK != svf_set_padding(&svf_para.hdr_para, header_dr_len, 0)) {
468                         LOG_ERROR("failed to set data header");
469                         return ERROR_FAIL;
470                 }
471
472                 /* HIR %d TDI (0xFF) */
473                 if (ERROR_OK != svf_set_padding(&svf_para.hir_para, header_ir_len, 0xFF)) {
474                         LOG_ERROR("failed to set instruction header");
475                         return ERROR_FAIL;
476                 }
477
478                 /* TDR %d TDI (0) */
479                 if (ERROR_OK != svf_set_padding(&svf_para.tdr_para, trailer_dr_len, 0)) {
480                         LOG_ERROR("failed to set data trailer");
481                         return ERROR_FAIL;
482                 }
483
484                 /* TIR %d TDI (0xFF) */
485                 if (ERROR_OK != svf_set_padding(&svf_para.tir_para, trailer_ir_len, 0xFF)) {
486                         LOG_ERROR("failed to set instruction trailer");
487                         return ERROR_FAIL;
488                 }
489         }
490
491         if (svf_progress_enabled) {
492                 /* Count total lines in file. */
493                 while (!feof(svf_fd)) {
494                         svf_getline(&svf_command_buffer, &svf_command_buffer_size, svf_fd);
495                         svf_total_lines++;
496                 }
497                 rewind(svf_fd);
498         }
499         while (ERROR_OK == svf_read_command_from_file(svf_fd)) {
500                 /* Log Output */
501                 if (svf_quiet) {
502                         if (svf_progress_enabled) {
503                                 svf_percentage = ((svf_line_number * 20) / svf_total_lines) * 5;
504                                 if (svf_last_printed_percentage != svf_percentage) {
505                                         LOG_USER_N("\r%d%%    ", svf_percentage);
506                                         svf_last_printed_percentage = svf_percentage;
507                                 }
508                         }
509                 } else {
510                         if (svf_progress_enabled) {
511                                 svf_percentage = ((svf_line_number * 20) / svf_total_lines) * 5;
512                                 LOG_USER_N("%3d%%  %s", svf_percentage, svf_read_line);
513                         } else
514                                 LOG_USER_N("%s", svf_read_line);
515                 }
516                 /* Run Command */
517                 if (ERROR_OK != svf_run_command(CMD_CTX, svf_command_buffer)) {
518                         LOG_ERROR("fail to run command at line %d", svf_line_number);
519                         ret = ERROR_FAIL;
520                         break;
521                 }
522                 command_num++;
523         }
524
525         if ((!svf_nil) && (ERROR_OK != jtag_execute_queue()))
526                 ret = ERROR_FAIL;
527         else if (ERROR_OK != svf_check_tdo())
528                 ret = ERROR_FAIL;
529
530         /* print time */
531         time_measure_ms = timeval_ms() - time_measure_ms;
532         time_measure_s = time_measure_ms / 1000;
533         time_measure_ms %= 1000;
534         time_measure_m = time_measure_s / 60;
535         time_measure_s %= 60;
536         if (time_measure_ms < 1000)
537                 command_print(CMD_CTX,
538                         "\r\nTime used: %dm%ds%" PRId64 "ms ",
539                         time_measure_m,
540                         time_measure_s,
541                         time_measure_ms);
542
543 free_all:
544
545         fclose(svf_fd);
546         svf_fd = 0;
547
548         /* free buffers */
549         if (svf_command_buffer) {
550                 free(svf_command_buffer);
551                 svf_command_buffer = NULL;
552                 svf_command_buffer_size = 0;
553         }
554         if (svf_check_tdo_para) {
555                 free(svf_check_tdo_para);
556                 svf_check_tdo_para = NULL;
557                 svf_check_tdo_para_index = 0;
558         }
559         if (svf_tdi_buffer) {
560                 free(svf_tdi_buffer);
561                 svf_tdi_buffer = NULL;
562         }
563         if (svf_tdo_buffer) {
564                 free(svf_tdo_buffer);
565                 svf_tdo_buffer = NULL;
566         }
567         if (svf_mask_buffer) {
568                 free(svf_mask_buffer);
569                 svf_mask_buffer = NULL;
570         }
571         svf_buffer_index = 0;
572         svf_buffer_size = 0;
573
574         svf_free_xxd_para(&svf_para.hdr_para);
575         svf_free_xxd_para(&svf_para.hir_para);
576         svf_free_xxd_para(&svf_para.tdr_para);
577         svf_free_xxd_para(&svf_para.tir_para);
578         svf_free_xxd_para(&svf_para.sdr_para);
579         svf_free_xxd_para(&svf_para.sir_para);
580
581         if (ERROR_OK == ret)
582                 command_print(CMD_CTX,
583                               "svf file programmed %s for %d commands with %d errors",
584                               (svf_ignore_error > 1) ? "unsuccessfully" : "successfully",
585                               command_num,
586                               (svf_ignore_error > 1) ? (svf_ignore_error - 1) : 0);
587         else
588                 command_print(CMD_CTX, "svf file programmed failed");
589
590         svf_ignore_error = 0;
591         return ret;
592 }
593
594 static int svf_getline(char **lineptr, size_t *n, FILE *stream)
595 {
596 #define MIN_CHUNK 16    /* Buffer is increased by this size each time as required */
597         size_t i = 0;
598
599         if (*lineptr == NULL) {
600                 *n = MIN_CHUNK;
601                 *lineptr = malloc(*n);
602                 if (!*lineptr)
603                         return -1;
604         }
605
606         (*lineptr)[0] = fgetc(stream);
607         while ((*lineptr)[i] != '\n') {
608                 (*lineptr)[++i] = fgetc(stream);
609                 if (feof(stream)) {
610                         (*lineptr)[0] = 0;
611                         return -1;
612                 }
613                 if ((i + 2) > *n) {
614                         *n += MIN_CHUNK;
615                         *lineptr = realloc(*lineptr, *n);
616                 }
617         }
618
619         (*lineptr)[++i] = 0;
620
621         return sizeof(*lineptr);
622 }
623
624 #define SVFP_CMD_INC_CNT 1024
625 static int svf_read_command_from_file(FILE *fd)
626 {
627         unsigned char ch;
628         int i = 0;
629         size_t cmd_pos = 0;
630         int cmd_ok = 0, slash = 0;
631
632         if (svf_getline(&svf_read_line, &svf_read_line_size, svf_fd) <= 0)
633                 return ERROR_FAIL;
634         svf_line_number++;
635         ch = svf_read_line[0];
636         while (!cmd_ok && (ch != 0)) {
637                 switch (ch) {
638                         case '!':
639                                 slash = 0;
640                                 if (svf_getline(&svf_read_line, &svf_read_line_size, svf_fd) <= 0)
641                                         return ERROR_FAIL;
642                                 svf_line_number++;
643                                 i = -1;
644                                 break;
645                         case '/':
646                                 if (++slash == 2) {
647                                         slash = 0;
648                                         if (svf_getline(&svf_read_line, &svf_read_line_size,
649                                                 svf_fd) <= 0)
650                                                 return ERROR_FAIL;
651                                         svf_line_number++;
652                                         i = -1;
653                                 }
654                                 break;
655                         case ';':
656                                 slash = 0;
657                                 cmd_ok = 1;
658                                 break;
659                         case '\n':
660                                 svf_line_number++;
661                                 if (svf_getline(&svf_read_line, &svf_read_line_size, svf_fd) <= 0)
662                                         return ERROR_FAIL;
663                                 i = -1;
664                         case '\r':
665                                 slash = 0;
666                                 /* Don't save '\r' and '\n' if no data is parsed */
667                                 if (!cmd_pos)
668                                         break;
669                         default:
670                                 /* The parsing code currently expects a space
671                                  * before parentheses -- "TDI (123)".  Also a
672                                  * space afterwards -- "TDI (123) TDO(456)".
673                                  * But such spaces are optional... instead of
674                                  * parser updates, cope with that by adding the
675                                  * spaces as needed.
676                                  *
677                                  * Ensure there are 3 bytes available, for:
678                                  *  - current character
679                                  *  - added space.
680                                  *  - terminating NUL ('\0')
681                                  */
682                                 if (cmd_pos + 3 > svf_command_buffer_size) {
683                                         svf_command_buffer = realloc(svf_command_buffer, cmd_pos + 3);
684                                         svf_command_buffer_size = cmd_pos + 3;
685                                         if (svf_command_buffer == NULL) {
686                                                 LOG_ERROR("not enough memory");
687                                                 return ERROR_FAIL;
688                                         }
689                                 }
690
691                                 /* insert a space before '(' */
692                                 if ('(' == ch)
693                                         svf_command_buffer[cmd_pos++] = ' ';
694
695                                 svf_command_buffer[cmd_pos++] = (char)toupper(ch);
696
697                                 /* insert a space after ')' */
698                                 if (')' == ch)
699                                         svf_command_buffer[cmd_pos++] = ' ';
700                                 break;
701                 }
702                 ch = svf_read_line[++i];
703         }
704
705         if (cmd_ok) {
706                 svf_command_buffer[cmd_pos] = '\0';
707                 return ERROR_OK;
708         } else
709                 return ERROR_FAIL;
710 }
711
712 static int svf_parse_cmd_string(char *str, int len, char **argus, int *num_of_argu)
713 {
714         int pos = 0, num = 0, space_found = 1, in_bracket = 0;
715
716         while (pos < len) {
717                 switch (str[pos]) {
718                         case '!':
719                         case '/':
720                                 LOG_ERROR("fail to parse svf command");
721                                 return ERROR_FAIL;
722                         case '(':
723                                 in_bracket = 1;
724                                 goto parse_char;
725                         case ')':
726                                 in_bracket = 0;
727                                 goto parse_char;
728                         default:
729 parse_char:
730                                 if (!in_bracket && isspace((int) str[pos])) {
731                                         space_found = 1;
732                                         str[pos] = '\0';
733                                 } else if (space_found) {
734                                         argus[num++] = &str[pos];
735                                         space_found = 0;
736                                 }
737                                 break;
738                 }
739                 pos++;
740         }
741
742         *num_of_argu = num;
743
744         return ERROR_OK;
745 }
746
747 bool svf_tap_state_is_stable(tap_state_t state)
748 {
749         return (TAP_RESET == state) || (TAP_IDLE == state)
750                         || (TAP_DRPAUSE == state) || (TAP_IRPAUSE == state);
751 }
752
753 static int svf_find_string_in_array(char *str, char **strs, int num_of_element)
754 {
755         int i;
756
757         for (i = 0; i < num_of_element; i++) {
758                 if (!strcmp(str, strs[i]))
759                         return i;
760         }
761         return 0xFF;
762 }
763
764 static int svf_adjust_array_length(uint8_t **arr, int orig_bit_len, int new_bit_len)
765 {
766         int new_byte_len = (new_bit_len + 7) >> 3;
767
768         if ((NULL == *arr) || (((orig_bit_len + 7) >> 3) < ((new_bit_len + 7) >> 3))) {
769                 if (*arr != NULL) {
770                         free(*arr);
771                         *arr = NULL;
772                 }
773                 *arr = malloc(new_byte_len);
774                 if (NULL == *arr) {
775                         LOG_ERROR("not enough memory");
776                         return ERROR_FAIL;
777                 }
778                 memset(*arr, 0, new_byte_len);
779         }
780         return ERROR_OK;
781 }
782
783 static int svf_set_padding(struct svf_xxr_para *para, int len, unsigned char tdi)
784 {
785         int error = ERROR_OK;
786         error |= svf_adjust_array_length(&para->tdi, para->len, len);
787         memset(para->tdi, tdi, (len + 7) >> 3);
788         error |= svf_adjust_array_length(&para->tdo, para->len, len);
789         error |= svf_adjust_array_length(&para->mask, para->len, len);
790         para->len = len;
791         para->data_mask = XXR_TDI;
792
793         return error;
794 }
795
796 static int svf_copy_hexstring_to_binary(char *str, uint8_t **bin, int orig_bit_len, int bit_len)
797 {
798         int i, str_len = strlen(str), str_hbyte_len = (bit_len + 3) >> 2;
799         uint8_t ch = 0;
800
801         if (ERROR_OK != svf_adjust_array_length(bin, orig_bit_len, bit_len)) {
802                 LOG_ERROR("fail to adjust length of array");
803                 return ERROR_FAIL;
804         }
805
806         /* fill from LSB (end of str) to MSB (beginning of str) */
807         for (i = 0; i < str_hbyte_len; i++) {
808                 ch = 0;
809                 while (str_len > 0) {
810                         ch = str[--str_len];
811
812                         /* Skip whitespace.  The SVF specification (rev E) is
813                          * deficient in terms of basic lexical issues like
814                          * where whitespace is allowed.  Long bitstrings may
815                          * require line ends for correctness, since there is
816                          * a hard limit on line length.
817                          */
818                         if (!isspace(ch)) {
819                                 if ((ch >= '0') && (ch <= '9')) {
820                                         ch = ch - '0';
821                                         break;
822                                 } else if ((ch >= 'A') && (ch <= 'F')) {
823                                         ch = ch - 'A' + 10;
824                                         break;
825                                 } else {
826                                         LOG_ERROR("invalid hex string");
827                                         return ERROR_FAIL;
828                                 }
829                         }
830
831                         ch = 0;
832                 }
833
834                 /* write bin */
835                 if (i % 2) {
836                         /* MSB */
837                         (*bin)[i / 2] |= ch << 4;
838                 } else {
839                         /* LSB */
840                         (*bin)[i / 2] = 0;
841                         (*bin)[i / 2] |= ch;
842                 }
843         }
844
845         /* consume optional leading '0' MSBs or whitespace */
846         while (str_len > 0 && ((str[str_len - 1] == '0')
847                         || isspace((int) str[str_len - 1])))
848                 str_len--;
849
850         /* check validity: we must have consumed everything */
851         if (str_len > 0 || (ch & ~((2 << ((bit_len - 1) % 4)) - 1)) != 0) {
852                 LOG_ERROR("value execeeds length");
853                 return ERROR_FAIL;
854         }
855
856         return ERROR_OK;
857 }
858
859 static int svf_check_tdo(void)
860 {
861         int i, len, index_var;
862
863         for (i = 0; i < svf_check_tdo_para_index; i++) {
864                 index_var = svf_check_tdo_para[i].buffer_offset;
865                 len = svf_check_tdo_para[i].bit_len;
866                 if ((svf_check_tdo_para[i].enabled)
867                                 && buf_cmp_mask(&svf_tdi_buffer[index_var], &svf_tdo_buffer[index_var],
868                                 &svf_mask_buffer[index_var], len)) {
869                         LOG_ERROR("tdo check error at line %d",
870                                 svf_check_tdo_para[i].line_num);
871                         SVF_BUF_LOG(ERROR, &svf_tdi_buffer[index_var], len, "READ");
872                         SVF_BUF_LOG(ERROR, &svf_tdo_buffer[index_var], len, "WANT");
873                         SVF_BUF_LOG(ERROR, &svf_mask_buffer[index_var], len, "MASK");
874
875                         if (svf_ignore_error == 0)
876                                 return ERROR_FAIL;
877                         else
878                                 svf_ignore_error++;
879                 }
880         }
881         svf_check_tdo_para_index = 0;
882
883         return ERROR_OK;
884 }
885
886 static int svf_add_check_para(uint8_t enabled, int buffer_offset, int bit_len)
887 {
888         if (svf_check_tdo_para_index >= SVF_CHECK_TDO_PARA_SIZE) {
889                 LOG_ERROR("toooooo many operation undone");
890                 return ERROR_FAIL;
891         }
892
893         svf_check_tdo_para[svf_check_tdo_para_index].line_num = svf_line_number;
894         svf_check_tdo_para[svf_check_tdo_para_index].bit_len = bit_len;
895         svf_check_tdo_para[svf_check_tdo_para_index].enabled = enabled;
896         svf_check_tdo_para[svf_check_tdo_para_index].buffer_offset = buffer_offset;
897         svf_check_tdo_para_index++;
898
899         return ERROR_OK;
900 }
901
902 static int svf_execute_tap(void)
903 {
904         if ((!svf_nil) && (ERROR_OK != jtag_execute_queue()))
905                 return ERROR_FAIL;
906         else if (ERROR_OK != svf_check_tdo())
907                 return ERROR_FAIL;
908
909         svf_buffer_index = 0;
910
911         return ERROR_OK;
912 }
913
914 static int svf_run_command(struct command_context *cmd_ctx, char *cmd_str)
915 {
916         char *argus[256], command;
917         int num_of_argu = 0, i;
918
919         /* tmp variable */
920         int i_tmp;
921
922         /* for RUNTEST */
923         int run_count;
924         float min_time;
925         /* for XXR */
926         struct svf_xxr_para *xxr_para_tmp;
927         uint8_t **pbuffer_tmp;
928         struct scan_field field;
929         /* for STATE */
930         tap_state_t *path = NULL, state;
931         /* flag padding commands skipped due to -tap command */
932         int padding_command_skipped = 0;
933
934         if (ERROR_OK != svf_parse_cmd_string(cmd_str, strlen(cmd_str), argus, &num_of_argu))
935                 return ERROR_FAIL;
936
937         /* NOTE: we're a bit loose here, because we ignore case in
938          * TAP state names (instead of insisting on uppercase).
939          */
940
941         command = svf_find_string_in_array(argus[0],
942                         (char **)svf_command_name, ARRAY_SIZE(svf_command_name));
943         switch (command) {
944                 case ENDDR:
945                 case ENDIR:
946                         if (num_of_argu != 2) {
947                                 LOG_ERROR("invalid parameter of %s", argus[0]);
948                                 return ERROR_FAIL;
949                         }
950
951                         i_tmp = tap_state_by_name(argus[1]);
952
953                         if (svf_tap_state_is_stable(i_tmp)) {
954                                 if (command == ENDIR) {
955                                         svf_para.ir_end_state = i_tmp;
956                                         LOG_DEBUG("\tIR end_state = %s",
957                                                         tap_state_name(i_tmp));
958                                 } else {
959                                         svf_para.dr_end_state = i_tmp;
960                                         LOG_DEBUG("\tDR end_state = %s",
961                                                         tap_state_name(i_tmp));
962                                 }
963                         } else {
964                                 LOG_ERROR("%s: %s is not a stable state",
965                                                 argus[0], argus[1]);
966                                 return ERROR_FAIL;
967                         }
968                         break;
969                 case FREQUENCY:
970                         if ((num_of_argu != 1) && (num_of_argu != 3)) {
971                                 LOG_ERROR("invalid parameter of %s", argus[0]);
972                                 return ERROR_FAIL;
973                         }
974                         if (1 == num_of_argu) {
975                                 /* TODO: set jtag speed to full speed */
976                                 svf_para.frequency = 0;
977                         } else {
978                                 if (strcmp(argus[2], "HZ")) {
979                                         LOG_ERROR("HZ not found in FREQUENCY command");
980                                         return ERROR_FAIL;
981                                 }
982                                 if (ERROR_OK != svf_execute_tap())
983                                         return ERROR_FAIL;
984                                 svf_para.frequency = atof(argus[1]);
985                                 /* TODO: set jtag speed to */
986                                 if (svf_para.frequency > 0) {
987                                         command_run_linef(cmd_ctx,
988                                                         "adapter_khz %d",
989                                                         (int)svf_para.frequency / 1000);
990                                         LOG_DEBUG("\tfrequency = %f", svf_para.frequency);
991                                 }
992                         }
993                         break;
994                 case HDR:
995                         if (svf_tap_is_specified) {
996                                 padding_command_skipped = 1;
997                                 break;
998                         }
999                         xxr_para_tmp = &svf_para.hdr_para;
1000                         goto XXR_common;
1001                 case HIR:
1002                         if (svf_tap_is_specified) {
1003                                 padding_command_skipped = 1;
1004                                 break;
1005                         }
1006                         xxr_para_tmp = &svf_para.hir_para;
1007                         goto XXR_common;
1008                 case TDR:
1009                         if (svf_tap_is_specified) {
1010                                 padding_command_skipped = 1;
1011                                 break;
1012                         }
1013                         xxr_para_tmp = &svf_para.tdr_para;
1014                         goto XXR_common;
1015                 case TIR:
1016                         if (svf_tap_is_specified) {
1017                                 padding_command_skipped = 1;
1018                                 break;
1019                         }
1020                         xxr_para_tmp = &svf_para.tir_para;
1021                         goto XXR_common;
1022                 case SDR:
1023                         xxr_para_tmp = &svf_para.sdr_para;
1024                         goto XXR_common;
1025                 case SIR:
1026                         xxr_para_tmp = &svf_para.sir_para;
1027                         goto XXR_common;
1028 XXR_common:
1029                         /* XXR length [TDI (tdi)] [TDO (tdo)][MASK (mask)] [SMASK (smask)] */
1030                         if ((num_of_argu > 10) || (num_of_argu % 2)) {
1031                                 LOG_ERROR("invalid parameter of %s", argus[0]);
1032                                 return ERROR_FAIL;
1033                         }
1034                         i_tmp = xxr_para_tmp->len;
1035                         xxr_para_tmp->len = atoi(argus[1]);
1036                         /* If we are to enlarge the buffers, all parts of xxr_para_tmp
1037                          * need to be freed */
1038                         if (i_tmp < xxr_para_tmp->len) {
1039                                 free(xxr_para_tmp->tdi);
1040                                 xxr_para_tmp->tdi = NULL;
1041                                 free(xxr_para_tmp->tdo);
1042                                 xxr_para_tmp->tdo = NULL;
1043                                 free(xxr_para_tmp->mask);
1044                                 xxr_para_tmp->mask = NULL;
1045                                 free(xxr_para_tmp->smask);
1046                                 xxr_para_tmp->smask = NULL;
1047                         }
1048
1049                         LOG_DEBUG("\tlength = %d", xxr_para_tmp->len);
1050                         xxr_para_tmp->data_mask = 0;
1051                         for (i = 2; i < num_of_argu; i += 2) {
1052                                 if ((strlen(argus[i + 1]) < 3) || (argus[i + 1][0] != '(') ||
1053                                 (argus[i + 1][strlen(argus[i + 1]) - 1] != ')')) {
1054                                         LOG_ERROR("data section error");
1055                                         return ERROR_FAIL;
1056                                 }
1057                                 argus[i + 1][strlen(argus[i + 1]) - 1] = '\0';
1058                                 /* TDI, TDO, MASK, SMASK */
1059                                 if (!strcmp(argus[i], "TDI")) {
1060                                         /* TDI */
1061                                         pbuffer_tmp = &xxr_para_tmp->tdi;
1062                                         xxr_para_tmp->data_mask |= XXR_TDI;
1063                                 } else if (!strcmp(argus[i], "TDO")) {
1064                                         /* TDO */
1065                                         pbuffer_tmp = &xxr_para_tmp->tdo;
1066                                         xxr_para_tmp->data_mask |= XXR_TDO;
1067                                 } else if (!strcmp(argus[i], "MASK")) {
1068                                         /* MASK */
1069                                         pbuffer_tmp = &xxr_para_tmp->mask;
1070                                         xxr_para_tmp->data_mask |= XXR_MASK;
1071                                 } else if (!strcmp(argus[i], "SMASK")) {
1072                                         /* SMASK */
1073                                         pbuffer_tmp = &xxr_para_tmp->smask;
1074                                         xxr_para_tmp->data_mask |= XXR_SMASK;
1075                                 } else {
1076                                         LOG_ERROR("unknow parameter: %s", argus[i]);
1077                                         return ERROR_FAIL;
1078                                 }
1079                                 if (ERROR_OK !=
1080                                 svf_copy_hexstring_to_binary(&argus[i + 1][1], pbuffer_tmp, i_tmp,
1081                                         xxr_para_tmp->len)) {
1082                                         LOG_ERROR("fail to parse hex value");
1083                                         return ERROR_FAIL;
1084                                 }
1085                                 SVF_BUF_LOG(DEBUG, *pbuffer_tmp, xxr_para_tmp->len, argus[i]);
1086                         }
1087                         /* If a command changes the length of the last scan of the same type and the
1088                          * MASK parameter is absent, */
1089                         /* the mask pattern used is all cares */
1090                         if (!(xxr_para_tmp->data_mask & XXR_MASK) && (i_tmp != xxr_para_tmp->len)) {
1091                                 /* MASK not defined and length changed */
1092                                 if (ERROR_OK !=
1093                                 svf_adjust_array_length(&xxr_para_tmp->mask, i_tmp,
1094                                         xxr_para_tmp->len)) {
1095                                         LOG_ERROR("fail to adjust length of array");
1096                                         return ERROR_FAIL;
1097                                 }
1098                                 buf_set_ones(xxr_para_tmp->mask, xxr_para_tmp->len);
1099                         }
1100                         /* If TDO is absent, no comparison is needed, set the mask to 0 */
1101                         if (!(xxr_para_tmp->data_mask & XXR_TDO)) {
1102                                 if (NULL == xxr_para_tmp->tdo) {
1103                                         if (ERROR_OK !=
1104                                         svf_adjust_array_length(&xxr_para_tmp->tdo, i_tmp,
1105                                                 xxr_para_tmp->len)) {
1106                                                 LOG_ERROR("fail to adjust length of array");
1107                                                 return ERROR_FAIL;
1108                                         }
1109                                 }
1110                                 if (NULL == xxr_para_tmp->mask) {
1111                                         if (ERROR_OK !=
1112                                         svf_adjust_array_length(&xxr_para_tmp->mask, i_tmp,
1113                                                 xxr_para_tmp->len)) {
1114                                                 LOG_ERROR("fail to adjust length of array");
1115                                                 return ERROR_FAIL;
1116                                         }
1117                                 }
1118                                 memset(xxr_para_tmp->mask, 0, (xxr_para_tmp->len + 7) >> 3);
1119                         }
1120                         /* do scan if necessary */
1121                         if (SDR == command) {
1122                                 /* check buffer size first, reallocate if necessary */
1123                                 i = svf_para.hdr_para.len + svf_para.sdr_para.len +
1124                                                 svf_para.tdr_para.len;
1125                                 if ((svf_buffer_size - svf_buffer_index) < ((i + 7) >> 3)) {
1126                                         /* reallocate buffer */
1127                                         if (svf_realloc_buffers(svf_buffer_index + ((i + 7) >> 3)) != ERROR_OK) {
1128                                                 LOG_ERROR("not enough memory");
1129                                                 return ERROR_FAIL;
1130                                         }
1131                                 }
1132
1133                                 /* assemble dr data */
1134                                 i = 0;
1135                                 buf_set_buf(svf_para.hdr_para.tdi,
1136                                                 0,
1137                                                 &svf_tdi_buffer[svf_buffer_index],
1138                                                 i,
1139                                                 svf_para.hdr_para.len);
1140                                 i += svf_para.hdr_para.len;
1141                                 buf_set_buf(svf_para.sdr_para.tdi,
1142                                                 0,
1143                                                 &svf_tdi_buffer[svf_buffer_index],
1144                                                 i,
1145                                                 svf_para.sdr_para.len);
1146                                 i += svf_para.sdr_para.len;
1147                                 buf_set_buf(svf_para.tdr_para.tdi,
1148                                                 0,
1149                                                 &svf_tdi_buffer[svf_buffer_index],
1150                                                 i,
1151                                                 svf_para.tdr_para.len);
1152                                 i += svf_para.tdr_para.len;
1153
1154                                 /* add check data */
1155                                 if (svf_para.sdr_para.data_mask & XXR_TDO) {
1156                                         /* assemble dr mask data */
1157                                         i = 0;
1158                                         buf_set_buf(svf_para.hdr_para.mask,
1159                                                         0,
1160                                                         &svf_mask_buffer[svf_buffer_index],
1161                                                         i,
1162                                                         svf_para.hdr_para.len);
1163                                         i += svf_para.hdr_para.len;
1164                                         buf_set_buf(svf_para.sdr_para.mask,
1165                                                         0,
1166                                                         &svf_mask_buffer[svf_buffer_index],
1167                                                         i,
1168                                                         svf_para.sdr_para.len);
1169                                         i += svf_para.sdr_para.len;
1170                                         buf_set_buf(svf_para.tdr_para.mask,
1171                                                         0,
1172                                                         &svf_mask_buffer[svf_buffer_index],
1173                                                         i,
1174                                                         svf_para.tdr_para.len);
1175
1176                                         /* assemble dr check data */
1177                                         i = 0;
1178                                         buf_set_buf(svf_para.hdr_para.tdo,
1179                                                         0,
1180                                                         &svf_tdo_buffer[svf_buffer_index],
1181                                                         i,
1182                                                         svf_para.hdr_para.len);
1183                                         i += svf_para.hdr_para.len;
1184                                         buf_set_buf(svf_para.sdr_para.tdo,
1185                                                         0,
1186                                                         &svf_tdo_buffer[svf_buffer_index],
1187                                                         i,
1188                                                         svf_para.sdr_para.len);
1189                                         i += svf_para.sdr_para.len;
1190                                         buf_set_buf(svf_para.tdr_para.tdo,
1191                                                         0,
1192                                                         &svf_tdo_buffer[svf_buffer_index],
1193                                                         i,
1194                                                         svf_para.tdr_para.len);
1195                                         i += svf_para.tdr_para.len;
1196
1197                                         svf_add_check_para(1, svf_buffer_index, i);
1198                                 } else
1199                                         svf_add_check_para(0, svf_buffer_index, i);
1200                                 field.num_bits = i;
1201                                 field.out_value = &svf_tdi_buffer[svf_buffer_index];
1202                                 field.in_value = (xxr_para_tmp->data_mask & XXR_TDO) ? &svf_tdi_buffer[svf_buffer_index] : NULL;
1203                                 if (!svf_nil) {
1204                                         /* NOTE:  doesn't use SVF-specified state paths */
1205                                         jtag_add_plain_dr_scan(field.num_bits,
1206                                                         field.out_value,
1207                                                         field.in_value,
1208                                                         svf_para.dr_end_state);
1209                                 }
1210
1211                                 svf_buffer_index += (i + 7) >> 3;
1212                         } else if (SIR == command) {
1213                                 /* check buffer size first, reallocate if necessary */
1214                                 i = svf_para.hir_para.len + svf_para.sir_para.len +
1215                                                 svf_para.tir_para.len;
1216                                 if ((svf_buffer_size - svf_buffer_index) < ((i + 7) >> 3)) {
1217                                         if (svf_realloc_buffers(svf_buffer_index + ((i + 7) >> 3)) != ERROR_OK) {
1218                                                 LOG_ERROR("not enough memory");
1219                                                 return ERROR_FAIL;
1220                                         }
1221                                 }
1222
1223                                 /* assemble ir data */
1224                                 i = 0;
1225                                 buf_set_buf(svf_para.hir_para.tdi,
1226                                                 0,
1227                                                 &svf_tdi_buffer[svf_buffer_index],
1228                                                 i,
1229                                                 svf_para.hir_para.len);
1230                                 i += svf_para.hir_para.len;
1231                                 buf_set_buf(svf_para.sir_para.tdi,
1232                                                 0,
1233                                                 &svf_tdi_buffer[svf_buffer_index],
1234                                                 i,
1235                                                 svf_para.sir_para.len);
1236                                 i += svf_para.sir_para.len;
1237                                 buf_set_buf(svf_para.tir_para.tdi,
1238                                                 0,
1239                                                 &svf_tdi_buffer[svf_buffer_index],
1240                                                 i,
1241                                                 svf_para.tir_para.len);
1242                                 i += svf_para.tir_para.len;
1243
1244                                 /* add check data */
1245                                 if (svf_para.sir_para.data_mask & XXR_TDO) {
1246                                         /* assemble dr mask data */
1247                                         i = 0;
1248                                         buf_set_buf(svf_para.hir_para.mask,
1249                                                         0,
1250                                                         &svf_mask_buffer[svf_buffer_index],
1251                                                         i,
1252                                                         svf_para.hir_para.len);
1253                                         i += svf_para.hir_para.len;
1254                                         buf_set_buf(svf_para.sir_para.mask,
1255                                                         0,
1256                                                         &svf_mask_buffer[svf_buffer_index],
1257                                                         i,
1258                                                         svf_para.sir_para.len);
1259                                         i += svf_para.sir_para.len;
1260                                         buf_set_buf(svf_para.tir_para.mask,
1261                                                         0,
1262                                                         &svf_mask_buffer[svf_buffer_index],
1263                                                         i,
1264                                                         svf_para.tir_para.len);
1265
1266                                         /* assemble dr check data */
1267                                         i = 0;
1268                                         buf_set_buf(svf_para.hir_para.tdo,
1269                                                         0,
1270                                                         &svf_tdo_buffer[svf_buffer_index],
1271                                                         i,
1272                                                         svf_para.hir_para.len);
1273                                         i += svf_para.hir_para.len;
1274                                         buf_set_buf(svf_para.sir_para.tdo,
1275                                                         0,
1276                                                         &svf_tdo_buffer[svf_buffer_index],
1277                                                         i,
1278                                                         svf_para.sir_para.len);
1279                                         i += svf_para.sir_para.len;
1280                                         buf_set_buf(svf_para.tir_para.tdo,
1281                                                         0,
1282                                                         &svf_tdo_buffer[svf_buffer_index],
1283                                                         i,
1284                                                         svf_para.tir_para.len);
1285                                         i += svf_para.tir_para.len;
1286
1287                                         svf_add_check_para(1, svf_buffer_index, i);
1288                                 } else
1289                                         svf_add_check_para(0, svf_buffer_index, i);
1290                                 field.num_bits = i;
1291                                 field.out_value = &svf_tdi_buffer[svf_buffer_index];
1292                                 field.in_value = (xxr_para_tmp->data_mask & XXR_TDO) ? &svf_tdi_buffer[svf_buffer_index] : NULL;
1293                                 if (!svf_nil) {
1294                                         /* NOTE:  doesn't use SVF-specified state paths */
1295                                         jtag_add_plain_ir_scan(field.num_bits,
1296                                                         field.out_value,
1297                                                         field.in_value,
1298                                                         svf_para.ir_end_state);
1299                                 }
1300
1301                                 svf_buffer_index += (i + 7) >> 3;
1302                         }
1303                         break;
1304                 case PIO:
1305                 case PIOMAP:
1306                         LOG_ERROR("PIO and PIOMAP are not supported");
1307                         return ERROR_FAIL;
1308                         break;
1309                 case RUNTEST:
1310                         /* RUNTEST [run_state] run_count run_clk [min_time SEC [MAXIMUM max_time
1311                          * SEC]] [ENDSTATE end_state] */
1312                         /* RUNTEST [run_state] min_time SEC [MAXIMUM max_time SEC] [ENDSTATE
1313                          * end_state] */
1314                         if ((num_of_argu < 3) && (num_of_argu > 11)) {
1315                                 LOG_ERROR("invalid parameter of %s", argus[0]);
1316                                 return ERROR_FAIL;
1317                         }
1318                         /* init */
1319                         run_count = 0;
1320                         min_time = 0;
1321                         i = 1;
1322
1323                         /* run_state */
1324                         i_tmp = tap_state_by_name(argus[i]);
1325                         if (i_tmp != TAP_INVALID) {
1326                                 if (svf_tap_state_is_stable(i_tmp)) {
1327                                         svf_para.runtest_run_state = i_tmp;
1328
1329                                         /* When a run_state is specified, the new
1330                                          * run_state becomes the default end_state.
1331                                          */
1332                                         svf_para.runtest_end_state = i_tmp;
1333                                         LOG_DEBUG("\trun_state = %s", tap_state_name(i_tmp));
1334                                         i++;
1335                                 } else {
1336                                         LOG_ERROR("%s: %s is not a stable state", argus[0], tap_state_name(i_tmp));
1337                                         return ERROR_FAIL;
1338                                 }
1339                         }
1340
1341                         /* run_count run_clk */
1342                         if (((i + 2) <= num_of_argu) && strcmp(argus[i + 1], "SEC")) {
1343                                 if (!strcmp(argus[i + 1], "TCK")) {
1344                                         /* clock source is TCK */
1345                                         run_count = atoi(argus[i]);
1346                                         LOG_DEBUG("\trun_count@TCK = %d", run_count);
1347                                 } else {
1348                                         LOG_ERROR("%s not supported for clock", argus[i + 1]);
1349                                         return ERROR_FAIL;
1350                                 }
1351                                 i += 2;
1352                         }
1353                         /* min_time SEC */
1354                         if (((i + 2) <= num_of_argu) && !strcmp(argus[i + 1], "SEC")) {
1355                                 min_time = atof(argus[i]);
1356                                 LOG_DEBUG("\tmin_time = %fs", min_time);
1357                                 i += 2;
1358                         }
1359                         /* MAXIMUM max_time SEC */
1360                         if (((i + 3) <= num_of_argu) &&
1361                         !strcmp(argus[i], "MAXIMUM") && !strcmp(argus[i + 2], "SEC")) {
1362                                 float max_time = 0;
1363                                 max_time = atof(argus[i + 1]);
1364                                 LOG_DEBUG("\tmax_time = %fs", max_time);
1365                                 i += 3;
1366                         }
1367                         /* ENDSTATE end_state */
1368                         if (((i + 2) <= num_of_argu) && !strcmp(argus[i], "ENDSTATE")) {
1369                                 i_tmp = tap_state_by_name(argus[i + 1]);
1370
1371                                 if (svf_tap_state_is_stable(i_tmp)) {
1372                                         svf_para.runtest_end_state = i_tmp;
1373                                         LOG_DEBUG("\tend_state = %s", tap_state_name(i_tmp));
1374                                 } else {
1375                                         LOG_ERROR("%s: %s is not a stable state", argus[0], tap_state_name(i_tmp));
1376                                         return ERROR_FAIL;
1377                                 }
1378                                 i += 2;
1379                         }
1380
1381                         /* all parameter should be parsed */
1382                         if (i == num_of_argu) {
1383 #if 1
1384                                 /* FIXME handle statemove failures */
1385                                 uint32_t min_usec = 1000000 * min_time;
1386
1387                                 /* enter into run_state if necessary */
1388                                 if (cmd_queue_cur_state != svf_para.runtest_run_state)
1389                                         svf_add_statemove(svf_para.runtest_run_state);
1390
1391                                 /* add clocks and/or min wait */
1392                                 if (run_count > 0) {
1393                                         if (!svf_nil)
1394                                                 jtag_add_clocks(run_count);
1395                                 }
1396
1397                                 if (min_usec > 0) {
1398                                         if (!svf_nil)
1399                                                 jtag_add_sleep(min_usec);
1400                                 }
1401
1402                                 /* move to end_state if necessary */
1403                                 if (svf_para.runtest_end_state != svf_para.runtest_run_state)
1404                                         svf_add_statemove(svf_para.runtest_end_state);
1405
1406 #else
1407                                 if (svf_para.runtest_run_state != TAP_IDLE) {
1408                                         LOG_ERROR("cannot runtest in %s state",
1409                                                         tap_state_name(svf_para.runtest_run_state));
1410                                         return ERROR_FAIL;
1411                                 }
1412
1413                                 if (!svf_nil)
1414                                         jtag_add_runtest(run_count, svf_para.runtest_end_state);
1415 #endif
1416                         } else {
1417                                 LOG_ERROR("fail to parse parameter of RUNTEST, %d out of %d is parsed",
1418                                                 i,
1419                                                 num_of_argu);
1420                                 return ERROR_FAIL;
1421                         }
1422                         break;
1423                 case STATE:
1424                         /* STATE [pathstate1 [pathstate2 ...[pathstaten]]] stable_state */
1425                         if (num_of_argu < 2) {
1426                                 LOG_ERROR("invalid parameter of %s", argus[0]);
1427                                 return ERROR_FAIL;
1428                         }
1429                         if (num_of_argu > 2) {
1430                                 /* STATE pathstate1 ... stable_state */
1431                                 path = malloc((num_of_argu - 1) * sizeof(tap_state_t));
1432                                 if (NULL == path) {
1433                                         LOG_ERROR("not enough memory");
1434                                         return ERROR_FAIL;
1435                                 }
1436                                 num_of_argu--;  /* num of path */
1437                                 i_tmp = 1;              /* path is from parameter 1 */
1438                                 for (i = 0; i < num_of_argu; i++, i_tmp++) {
1439                                         path[i] = tap_state_by_name(argus[i_tmp]);
1440                                         if (path[i] == TAP_INVALID) {
1441                                                 LOG_ERROR("%s: %s is not a valid state", argus[0], argus[i_tmp]);
1442                                                 free(path);
1443                                                 return ERROR_FAIL;
1444                                         }
1445                                         /* OpenOCD refuses paths containing TAP_RESET */
1446                                         if (TAP_RESET == path[i]) {
1447                                                 /* FIXME last state MUST be stable! */
1448                                                 if (i > 0) {
1449                                                         if (!svf_nil)
1450                                                                 jtag_add_pathmove(i, path);
1451                                                 }
1452                                                 if (!svf_nil)
1453                                                         jtag_add_tlr();
1454                                                 num_of_argu -= i + 1;
1455                                                 i = -1;
1456                                         }
1457                                 }
1458                                 if (num_of_argu > 0) {
1459                                         /* execute last path if necessary */
1460                                         if (svf_tap_state_is_stable(path[num_of_argu - 1])) {
1461                                                 /* last state MUST be stable state */
1462                                                 if (!svf_nil)
1463                                                         jtag_add_pathmove(num_of_argu, path);
1464                                                 LOG_DEBUG("\tmove to %s by path_move",
1465                                                                 tap_state_name(path[num_of_argu - 1]));
1466                                         } else {
1467                                                 LOG_ERROR("%s: %s is not a stable state",
1468                                                                 argus[0],
1469                                                                 tap_state_name(path[num_of_argu - 1]));
1470                                                 free(path);
1471                                                 return ERROR_FAIL;
1472                                         }
1473                                 }
1474
1475                                 free(path);
1476                                 path = NULL;
1477                         } else {
1478                                 /* STATE stable_state */
1479                                 state = tap_state_by_name(argus[1]);
1480                                 if (svf_tap_state_is_stable(state)) {
1481                                         LOG_DEBUG("\tmove to %s by svf_add_statemove",
1482                                                         tap_state_name(state));
1483                                         /* FIXME handle statemove failures */
1484                                         svf_add_statemove(state);
1485                                 } else {
1486                                         LOG_ERROR("%s: %s is not a stable state",
1487                                                         argus[0], tap_state_name(state));
1488                                         return ERROR_FAIL;
1489                                 }
1490                         }
1491                         break;
1492                 case TRST:
1493                         /* TRST trst_mode */
1494                         if (num_of_argu != 2) {
1495                                 LOG_ERROR("invalid parameter of %s", argus[0]);
1496                                 return ERROR_FAIL;
1497                         }
1498                         if (svf_para.trst_mode != TRST_ABSENT) {
1499                                 if (ERROR_OK != svf_execute_tap())
1500                                         return ERROR_FAIL;
1501                                 i_tmp = svf_find_string_in_array(argus[1],
1502                                                 (char **)svf_trst_mode_name,
1503                                                 ARRAY_SIZE(svf_trst_mode_name));
1504                                 switch (i_tmp) {
1505                                 case TRST_ON:
1506                                         if (!svf_nil)
1507                                                 jtag_add_reset(1, 0);
1508                                         break;
1509                                 case TRST_Z:
1510                                 case TRST_OFF:
1511                                         if (!svf_nil)
1512                                                 jtag_add_reset(0, 0);
1513                                         break;
1514                                 case TRST_ABSENT:
1515                                         break;
1516                                 default:
1517                                         LOG_ERROR("unknown TRST mode: %s", argus[1]);
1518                                         return ERROR_FAIL;
1519                                 }
1520                                 svf_para.trst_mode = i_tmp;
1521                                 LOG_DEBUG("\ttrst_mode = %s", svf_trst_mode_name[svf_para.trst_mode]);
1522                         } else {
1523                                 LOG_ERROR("can not accpet TRST command if trst_mode is ABSENT");
1524                                 return ERROR_FAIL;
1525                         }
1526                         break;
1527                 default:
1528                         LOG_ERROR("invalid svf command: %s", argus[0]);
1529                         return ERROR_FAIL;
1530                         break;
1531         }
1532
1533         if (!svf_quiet) {
1534                 if (padding_command_skipped)
1535                         LOG_USER("(Above Padding command skipped, as per -tap argument)");
1536         }
1537
1538         if (debug_level >= LOG_LVL_DEBUG) {
1539                 /* for convenient debugging, execute tap if possible */
1540                 if ((svf_buffer_index > 0) && \
1541                                 (((command != STATE) && (command != RUNTEST)) || \
1542                                                 ((command == STATE) && (num_of_argu == 2)))) {
1543                         if (ERROR_OK != svf_execute_tap())
1544                                 return ERROR_FAIL;
1545
1546                         /* output debug info */
1547                         if ((SIR == command) || (SDR == command)) {
1548                                 SVF_BUF_LOG(DEBUG, svf_tdi_buffer, svf_check_tdo_para[0].bit_len, "TDO read");
1549                         }
1550                 }
1551         } else {
1552                 /* for fast executing, execute tap if necessary */
1553                 /* half of the buffer is for the next command */
1554                 if (((svf_buffer_index >= SVF_MAX_BUFFER_SIZE_TO_COMMIT) ||
1555                                 (svf_check_tdo_para_index >= SVF_CHECK_TDO_PARA_SIZE / 2)) && \
1556                                 (((command != STATE) && (command != RUNTEST)) || \
1557                                                 ((command == STATE) && (num_of_argu == 2))))
1558                         return svf_execute_tap();
1559         }
1560
1561         return ERROR_OK;
1562 }
1563
1564 static const struct command_registration svf_command_handlers[] = {
1565         {
1566                 .name = "svf",
1567                 .handler = handle_svf_command,
1568                 .mode = COMMAND_EXEC,
1569                 .help = "Runs a SVF file.",
1570                 .usage = "svf [-tap device.tap] <file> [quiet] [nil] [progress] [ignore_error]",
1571         },
1572         COMMAND_REGISTRATION_DONE
1573 };
1574
1575 int svf_register_commands(struct command_context *cmd_ctx)
1576 {
1577         return register_commands(cmd_ctx, NULL, svf_command_handlers);
1578 }