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