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