jtag/tcl: fix memory leak in error return
[fw/openocd] / src / xsvf / xsvf.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath                                    *
3  *   Dominic.Rath@gmx.de                                                   *
4  *                                                                         *
5  *   Copyright (C) 2007,2008 Ã˜yvind Harboe                                 *
6  *   oyvind.harboe@zylin.com                                               *
7  *                                                                         *
8  *   Copyright (C) 2008 Peter Hettkamp                                     *
9  *   peter.hettkamp@htp-tel.de                                             *
10  *                                                                         *
11  *   Copyright (C) 2009 SoftPLC Corporation. http://softplc.com            *
12  *   Dick Hollenbeck <dick@softplc.com>                                    *
13  *                                                                         *
14  *   This program is free software; you can redistribute it and/or modify  *
15  *   it under the terms of the GNU General Public License as published by  *
16  *   the Free Software Foundation; either version 2 of the License, or     *
17  *   (at your option) any later version.                                   *
18  *                                                                         *
19  *   This program is distributed in the hope that it will be useful,       *
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
22  *   GNU General Public License for more details.                          *
23  *                                                                         *
24  *   You should have received a copy of the GNU General Public License     *
25  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
26  ***************************************************************************/
27
28 /* The specification for SVF is available here:
29  * http://www.asset-intertech.com/support/svf.pdf
30  * Below, this document is referred to as the "SVF spec".
31  *
32  * The specification for XSVF is available here:
33  * http://www.xilinx.com/support/documentation/application_notes/xapp503.pdf
34  * Below, this document is referred to as the "XSVF spec".
35  */
36
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
40
41 #include "xsvf.h"
42 #include <jtag/jtag.h>
43 #include <svf/svf.h>
44
45 /* XSVF commands, from appendix B of xapp503.pdf  */
46 #define XCOMPLETE                       0x00
47 #define XTDOMASK                        0x01
48 #define XSIR                            0x02
49 #define XSDR                            0x03
50 #define XRUNTEST                        0x04
51 #define XREPEAT                         0x07
52 #define XSDRSIZE                        0x08
53 #define XSDRTDO                         0x09
54 #define XSETSDRMASKS            0x0A
55 #define XSDRINC                         0x0B
56 #define XSDRB                           0x0C
57 #define XSDRC                           0x0D
58 #define XSDRE                           0x0E
59 #define XSDRTDOB                        0x0F
60 #define XSDRTDOC                        0x10
61 #define XSDRTDOE                        0x11
62 #define XSTATE                          0x12
63 #define XENDIR                          0x13
64 #define XENDDR                          0x14
65 #define XSIR2                           0x15
66 #define XCOMMENT                        0x16
67 #define XWAIT                           0x17
68
69 /* XWAITSTATE is not in the xilinx XSVF spec, but the svf2xsvf.py translator
70  * generates this.  Arguably it is needed because the XSVF XRUNTEST command
71  * was ill conceived and does not directly flow out of the SVF RUNTEST command.
72  * This XWAITSTATE does map directly from the SVF RUNTEST command.
73  */
74 #define XWAITSTATE                      0x18
75
76 /* Lattice has extended the SVF file format, and Dick Hollenbeck's python based
77  * SVF2XSVF converter supports these 3 additional XSVF opcodes, LCOUNT, LDELAY, LSDR.
78  * Here is an example of usage of the 3 lattice opcode extensions:
79
80 ! Set the maximum loop count to 25.
81 LCOUNT  25;
82 ! Step to DRPAUSE give 5 clocks and wait for 1.00e + 000 SEC.
83 LDELAY  DRPAUSE 5 TCK   1.00E-003 SEC;
84 ! Test for the completed status. Match means pass.
85 ! Loop back to LDELAY line if not match and loop count less than 25.
86
87 LSDR 1  TDI  (0)
88 TDO  (1);
89 */
90
91 #define LCOUNT                          0x19
92 #define LDELAY                          0x1A
93 #define LSDR                            0x1B
94 #define XTRST                           0x1C
95
96 /* XSVF valid state values for the XSTATE command, from appendix B of xapp503.pdf */
97 #define XSV_RESET                       0x00
98 #define XSV_IDLE                        0x01
99 #define XSV_DRSELECT            0x02
100 #define XSV_DRCAPTURE           0x03
101 #define XSV_DRSHIFT                     0x04
102 #define XSV_DREXIT1                     0x05
103 #define XSV_DRPAUSE                     0x06
104 #define XSV_DREXIT2                     0x07
105 #define XSV_DRUPDATE            0x08
106 #define XSV_IRSELECT            0x09
107 #define XSV_IRCAPTURE           0x0A
108 #define XSV_IRSHIFT                     0x0B
109 #define XSV_IREXIT1                     0x0C
110 #define XSV_IRPAUSE                     0x0D
111 #define XSV_IREXIT2                     0x0E
112 #define XSV_IRUPDATE            0x0F
113
114 /* arguments to XTRST */
115 #define XTRST_ON                        0
116 #define XTRST_OFF                       1
117 #define XTRST_Z                         2
118 #define XTRST_ABSENT            3
119
120 #define XSTATE_MAX_PATH 12
121
122 static int xsvf_fd;
123
124 /* map xsvf tap state to an openocd "tap_state_t" */
125 static tap_state_t xsvf_to_tap(int xsvf_state)
126 {
127         tap_state_t ret;
128
129         switch (xsvf_state) {
130                 case XSV_RESET:
131                         ret = TAP_RESET;
132                         break;
133                 case XSV_IDLE:
134                         ret = TAP_IDLE;
135                         break;
136                 case XSV_DRSELECT:
137                         ret = TAP_DRSELECT;
138                         break;
139                 case XSV_DRCAPTURE:
140                         ret = TAP_DRCAPTURE;
141                         break;
142                 case XSV_DRSHIFT:
143                         ret = TAP_DRSHIFT;
144                         break;
145                 case XSV_DREXIT1:
146                         ret = TAP_DREXIT1;
147                         break;
148                 case XSV_DRPAUSE:
149                         ret = TAP_DRPAUSE;
150                         break;
151                 case XSV_DREXIT2:
152                         ret = TAP_DREXIT2;
153                         break;
154                 case XSV_DRUPDATE:
155                         ret = TAP_DRUPDATE;
156                         break;
157                 case XSV_IRSELECT:
158                         ret = TAP_IRSELECT;
159                         break;
160                 case XSV_IRCAPTURE:
161                         ret = TAP_IRCAPTURE;
162                         break;
163                 case XSV_IRSHIFT:
164                         ret = TAP_IRSHIFT;
165                         break;
166                 case XSV_IREXIT1:
167                         ret = TAP_IREXIT1;
168                         break;
169                 case XSV_IRPAUSE:
170                         ret = TAP_IRPAUSE;
171                         break;
172                 case XSV_IREXIT2:
173                         ret = TAP_IREXIT2;
174                         break;
175                 case XSV_IRUPDATE:
176                         ret = TAP_IRUPDATE;
177                         break;
178                 default:
179                         LOG_ERROR("UNKNOWN XSVF STATE 0x%02X", xsvf_state);
180                         exit(1);
181         }
182
183         return ret;
184 }
185
186 static int xsvf_read_buffer(int num_bits, int fd, uint8_t *buf)
187 {
188         int num_bytes;
189
190         for (num_bytes = (num_bits + 7) / 8; num_bytes > 0; num_bytes--) {
191                 /* reverse the order of bytes as they are read sequentially from file */
192                 if (read(fd, buf + num_bytes - 1, 1) < 0)
193                         return ERROR_XSVF_EOF;
194         }
195
196         return ERROR_OK;
197 }
198
199 COMMAND_HANDLER(handle_xsvf_command)
200 {
201         uint8_t *dr_out_buf = NULL;                             /* from host to device (TDI) */
202         uint8_t *dr_in_buf = NULL;                              /* from device to host (TDO) */
203         uint8_t *dr_in_mask = NULL;
204
205         int xsdrsize = 0;
206         int xruntest = 0;                                       /* number of TCK cycles OR *microseconds */
207         int xrepeat = 0;                                        /* number of retries */
208
209         tap_state_t xendir = TAP_IDLE;                  /* see page 8 of the SVF spec, initial
210                                                          *xendir to be TAP_IDLE */
211         tap_state_t xenddr = TAP_IDLE;
212
213         uint8_t opcode;
214         uint8_t uc = 0;
215         long file_offset = 0;
216
217         int loop_count = 0;
218         tap_state_t loop_state = TAP_IDLE;
219         int loop_clocks = 0;
220         int loop_usecs = 0;
221
222         int do_abort = 0;
223         int unsupported = 0;
224         int tdo_mismatch = 0;
225         int result;
226         int verbose = 1;
227
228         bool collecting_path = false;
229         tap_state_t path[XSTATE_MAX_PATH];
230         unsigned pathlen = 0;
231
232         /* a flag telling whether to clock TCK during waits,
233          * or simply sleep, controlled by virt2
234          */
235         int runtest_requires_tck = 0;
236
237         /* use NULL to indicate a "plain" xsvf file which accounts for
238          * additional devices in the scan chain, otherwise the device
239          * that should be affected
240         */
241         struct jtag_tap *tap = NULL;
242
243         if (CMD_ARGC < 2)
244                 return ERROR_COMMAND_SYNTAX_ERROR;
245
246         /* we mess with CMD_ARGV starting point below, snapshot filename here */
247         const char *filename = CMD_ARGV[1];
248
249         if (strcmp(CMD_ARGV[0], "plain") != 0) {
250                 tap = jtag_tap_by_string(CMD_ARGV[0]);
251                 if (!tap) {
252                         command_print(CMD, "Tap: %s unknown", CMD_ARGV[0]);
253                         return ERROR_FAIL;
254                 }
255         }
256
257         xsvf_fd = open(filename, O_RDONLY);
258         if (xsvf_fd < 0) {
259                 command_print(CMD, "file \"%s\" not found", filename);
260                 return ERROR_FAIL;
261         }
262
263         /* if this argument is present, then interpret xruntest counts as TCK cycles rather than as
264          *usecs */
265         if ((CMD_ARGC > 2) && (strcmp(CMD_ARGV[2], "virt2") == 0)) {
266                 runtest_requires_tck = 1;
267                 --CMD_ARGC;
268                 ++CMD_ARGV;
269         }
270
271         if ((CMD_ARGC > 2) && (strcmp(CMD_ARGV[2], "quiet") == 0))
272                 verbose = 0;
273
274         LOG_WARNING("XSVF support in OpenOCD is limited. Consider using SVF instead");
275         LOG_USER("xsvf processing file: \"%s\"", filename);
276
277         while (read(xsvf_fd, &opcode, 1) > 0) {
278                 /* record the position of this opcode within the file */
279                 file_offset = lseek(xsvf_fd, 0, SEEK_CUR) - 1;
280
281                 /* maybe collect another state for a pathmove();
282                  * or terminate a path.
283                  */
284                 if (collecting_path) {
285                         tap_state_t mystate;
286
287                         switch (opcode) {
288                                 case XCOMMENT:
289                                         /* ignore/show comments between XSTATE ops */
290                                         break;
291                                 case XSTATE:
292                                         /* try to collect another transition */
293                                         if (pathlen == XSTATE_MAX_PATH) {
294                                                 LOG_ERROR("XSVF: path too long");
295                                                 do_abort = 1;
296                                                 break;
297                                         }
298
299                                         if (read(xsvf_fd, &uc, 1) < 0) {
300                                                 do_abort = 1;
301                                                 break;
302                                         }
303
304                                         mystate = xsvf_to_tap(uc);
305                                         path[pathlen++] = mystate;
306
307                                         LOG_DEBUG("XSTATE 0x%02X %s", uc,
308                                         tap_state_name(mystate));
309
310                                         /* If path is incomplete, collect more */
311                                         if (!svf_tap_state_is_stable(mystate))
312                                                 continue;
313
314                                         /* Else execute the path transitions we've
315                                          * collected so far.
316                                          *
317                                          * NOTE:  Punting on the saved path is not
318                                          * strictly correct, but we must to do this
319                                          * unless jtag_add_pathmove() stops rejecting
320                                          * paths containing RESET.  This is probably
321                                          * harmless, since there aren't many options
322                                          * for going from a stable state to reset;
323                                          * at the worst, we may issue extra clocks
324                                          * once we get to RESET.
325                                          */
326                                         if (mystate == TAP_RESET) {
327                                                 LOG_WARNING("XSVF: dodgey RESET");
328                                                 path[0] = mystate;
329                                         }
330
331                                 /* FALL THROUGH */
332                                 default:
333                                         /* Execute the path we collected
334                                          *
335                                          * NOTE: OpenOCD requires something that XSVF
336                                          * doesn't:  the last TAP state in the path
337                                          * must be stable.  In practice, tools that
338                                          * create XSVF seem to follow that rule too.
339                                          */
340                                         collecting_path = false;
341
342                                         if (path[0] == TAP_RESET)
343                                                 jtag_add_tlr();
344                                         else
345                                                 jtag_add_pathmove(pathlen, path);
346
347                                         result = jtag_execute_queue();
348                                         if (result != ERROR_OK) {
349                                                 LOG_ERROR("XSVF: pathmove error %d", result);
350                                                 do_abort = 1;
351                                                 break;
352                                         }
353                                         continue;
354                         }
355                 }
356
357                 switch (opcode) {
358                         case XCOMPLETE:
359                                 LOG_DEBUG("XCOMPLETE");
360
361                                 result = jtag_execute_queue();
362                                 if (result != ERROR_OK) {
363                                         tdo_mismatch = 1;
364                                         break;
365                                 }
366                                 break;
367
368                         case XTDOMASK:
369                                 LOG_DEBUG("XTDOMASK");
370                                 if (dr_in_mask &&
371                                                 (xsvf_read_buffer(xsdrsize, xsvf_fd, dr_in_mask) != ERROR_OK))
372                                         do_abort = 1;
373                                 break;
374
375                         case XRUNTEST:
376                         {
377                                 uint8_t xruntest_buf[4];
378
379                                 if (read(xsvf_fd, xruntest_buf, 4) < 0) {
380                                         do_abort = 1;
381                                         break;
382                                 }
383
384                                 xruntest = be_to_h_u32(xruntest_buf);
385                                 LOG_DEBUG("XRUNTEST %d 0x%08X", xruntest, xruntest);
386                         }
387                         break;
388
389                         case XREPEAT:
390                         {
391                                 uint8_t myrepeat;
392
393                                 if (read(xsvf_fd, &myrepeat, 1) < 0)
394                                         do_abort = 1;
395                                 else {
396                                         xrepeat = myrepeat;
397                                         LOG_DEBUG("XREPEAT %d", xrepeat);
398                                 }
399                         }
400                         break;
401
402                         case XSDRSIZE:
403                         {
404                                 uint8_t xsdrsize_buf[4];
405
406                                 if (read(xsvf_fd, xsdrsize_buf, 4) < 0) {
407                                         do_abort = 1;
408                                         break;
409                                 }
410
411                                 xsdrsize = be_to_h_u32(xsdrsize_buf);
412                                 LOG_DEBUG("XSDRSIZE %d", xsdrsize);
413
414                                 free(dr_out_buf);
415                                 free(dr_in_buf);
416                                 free(dr_in_mask);
417
418                                 dr_out_buf = malloc((xsdrsize + 7) / 8);
419                                 dr_in_buf = malloc((xsdrsize + 7) / 8);
420                                 dr_in_mask = malloc((xsdrsize + 7) / 8);
421                         }
422                         break;
423
424                         case XSDR:              /* these two are identical except for the dr_in_buf */
425                         case XSDRTDO:
426                         {
427                                 int limit = xrepeat;
428                                 int matched = 0;
429                                 int attempt;
430
431                                 const char *op_name = (opcode == XSDR ? "XSDR" : "XSDRTDO");
432
433                                 if (xsvf_read_buffer(xsdrsize, xsvf_fd, dr_out_buf) != ERROR_OK) {
434                                         do_abort = 1;
435                                         break;
436                                 }
437
438                                 if (opcode == XSDRTDO) {
439                                         if (xsvf_read_buffer(xsdrsize, xsvf_fd,
440                                                 dr_in_buf)  != ERROR_OK) {
441                                                 do_abort = 1;
442                                                 break;
443                                         }
444                                 }
445
446                                 if (limit < 1)
447                                         limit = 1;
448
449                                 LOG_DEBUG("%s %d", op_name, xsdrsize);
450
451                                 for (attempt = 0; attempt < limit; ++attempt) {
452                                         struct scan_field field;
453
454                                         if (attempt > 0) {
455                                                 /* perform the XC9500 exception handling sequence shown in xapp067.pdf and
456                                                  * illustrated in pseudo code at end of this file.  We start from state
457                                                  * DRPAUSE:
458                                                  * go to Exit2-DR
459                                                  * go to Shift-DR
460                                                  * go to Exit1-DR
461                                                  * go to Update-DR
462                                                  * go to Run-Test/Idle
463                                                  *
464                                                  * This sequence should be harmless for other devices, and it
465                                                  * will be skipped entirely if xrepeat is set to zero.
466                                                  */
467
468                                                 static tap_state_t exception_path[] = {
469                                                         TAP_DREXIT2,
470                                                         TAP_DRSHIFT,
471                                                         TAP_DREXIT1,
472                                                         TAP_DRUPDATE,
473                                                         TAP_IDLE,
474                                                 };
475
476                                                 jtag_add_pathmove(ARRAY_SIZE(exception_path), exception_path);
477
478                                                 if (verbose)
479                                                         LOG_USER("%s mismatch, xsdrsize=%d retry=%d",
480                                                                         op_name,
481                                                                         xsdrsize,
482                                                                         attempt);
483                                         }
484
485                                         field.num_bits = xsdrsize;
486                                         field.out_value = dr_out_buf;
487                                         field.in_value = calloc(DIV_ROUND_UP(field.num_bits, 8), 1);
488
489                                         if (tap == NULL)
490                                                 jtag_add_plain_dr_scan(field.num_bits,
491                                                                 field.out_value,
492                                                                 field.in_value,
493                                                                 TAP_DRPAUSE);
494                                         else
495                                                 jtag_add_dr_scan(tap, 1, &field, TAP_DRPAUSE);
496
497                                         jtag_check_value_mask(&field, dr_in_buf, dr_in_mask);
498
499                                         free(field.in_value);
500
501                                         /* LOG_DEBUG("FLUSHING QUEUE"); */
502                                         result = jtag_execute_queue();
503                                         if (result == ERROR_OK) {
504                                                 matched = 1;
505                                                 break;
506                                         }
507                                 }
508
509                                 if (!matched) {
510                                         LOG_USER("%s mismatch", op_name);
511                                         tdo_mismatch = 1;
512                                         break;
513                                 }
514
515                                 /* See page 19 of XSVF spec regarding opcode "XSDR" */
516                                 if (xruntest) {
517                                         result = svf_add_statemove(TAP_IDLE);
518                                         if (result != ERROR_OK)
519                                                 return result;
520
521                                         if (runtest_requires_tck)
522                                                 jtag_add_clocks(xruntest);
523                                         else
524                                                 jtag_add_sleep(xruntest);
525                                 } else if (xendir != TAP_DRPAUSE) {
526                                         /* we are already in TAP_DRPAUSE */
527                                         result = svf_add_statemove(xenddr);
528                                         if (result != ERROR_OK)
529                                                 return result;
530                                 }
531                         }
532                         break;
533
534                         case XSETSDRMASKS:
535                                 LOG_ERROR("unsupported XSETSDRMASKS");
536                                 unsupported = 1;
537                                 break;
538
539                         case XSDRINC:
540                                 LOG_ERROR("unsupported XSDRINC");
541                                 unsupported = 1;
542                                 break;
543
544                         case XSDRB:
545                                 LOG_ERROR("unsupported XSDRB");
546                                 unsupported = 1;
547                                 break;
548
549                         case XSDRC:
550                                 LOG_ERROR("unsupported XSDRC");
551                                 unsupported = 1;
552                                 break;
553
554                         case XSDRE:
555                                 LOG_ERROR("unsupported XSDRE");
556                                 unsupported = 1;
557                                 break;
558
559                         case XSDRTDOB:
560                                 LOG_ERROR("unsupported XSDRTDOB");
561                                 unsupported = 1;
562                                 break;
563
564                         case XSDRTDOC:
565                                 LOG_ERROR("unsupported XSDRTDOC");
566                                 unsupported = 1;
567                                 break;
568
569                         case XSDRTDOE:
570                                 LOG_ERROR("unsupported XSDRTDOE");
571                                 unsupported = 1;
572                                 break;
573
574                         case XSTATE:
575                         {
576                                 tap_state_t mystate;
577
578                                 if (read(xsvf_fd, &uc, 1) < 0) {
579                                         do_abort = 1;
580                                         break;
581                                 }
582
583                                 mystate = xsvf_to_tap(uc);
584
585                                 LOG_DEBUG("XSTATE 0x%02X %s", uc, tap_state_name(mystate));
586
587                                 if (mystate == TAP_INVALID) {
588                                         LOG_ERROR("XSVF: bad XSTATE %02x", uc);
589                                         do_abort = 1;
590                                         break;
591                                 }
592
593                                 /* NOTE: the current state is SVF-stable! */
594
595                                 /* no change == NOP */
596                                 if (mystate == cmd_queue_cur_state
597                                                 && mystate != TAP_RESET)
598                                         break;
599
600                                 /* Hand off to SVF? */
601                                 if (svf_tap_state_is_stable(mystate)) {
602                                         result = svf_add_statemove(mystate);
603                                         if (result != ERROR_OK)
604                                                 unsupported = 1;
605                                         break;
606                                 }
607
608                                 /*
609                                  * A sequence of XSTATE transitions, each TAP
610                                  * state adjacent to the previous one.  Start
611                                  * collecting them.
612                                  */
613                                 collecting_path = true;
614                                 pathlen = 1;
615                                 path[0] = mystate;
616                         }
617                         break;
618
619                         case XENDIR:
620
621                                 if (read(xsvf_fd, &uc, 1) < 0) {
622                                         do_abort = 1;
623                                         break;
624                                 }
625
626                                 /* see page 22 of XSVF spec */
627                                 if (uc == 0)
628                                         xendir = TAP_IDLE;
629                                 else if (uc == 1)
630                                         xendir = TAP_IRPAUSE;
631                                 else {
632                                         LOG_ERROR("illegial XENDIR argument: 0x%02X", uc);
633                                         unsupported = 1;
634                                         break;
635                                 }
636
637                                 LOG_DEBUG("XENDIR 0x%02X %s", uc, tap_state_name(xendir));
638                                 break;
639
640                         case XENDDR:
641
642                                 if (read(xsvf_fd, &uc, 1) < 0) {
643                                         do_abort = 1;
644                                         break;
645                                 }
646
647                                 /* see page 22 of XSVF spec */
648                                 if (uc == 0)
649                                         xenddr = TAP_IDLE;
650                                 else if (uc == 1)
651                                         xenddr = TAP_DRPAUSE;
652                                 else {
653                                         LOG_ERROR("illegial XENDDR argument: 0x%02X", uc);
654                                         unsupported = 1;
655                                         break;
656                                 }
657
658                                 LOG_DEBUG("XENDDR %02X %s", uc, tap_state_name(xenddr));
659                                 break;
660
661                         case XSIR:
662                         case XSIR2:
663                         {
664                                 uint8_t short_buf[2];
665                                 uint8_t *ir_buf;
666                                 int bitcount;
667                                 tap_state_t my_end_state = xruntest ? TAP_IDLE : xendir;
668
669                                 if (opcode == XSIR) {
670                                         /* one byte bitcount */
671                                         if (read(xsvf_fd, short_buf, 1) < 0) {
672                                                 do_abort = 1;
673                                                 break;
674                                         }
675                                         bitcount = short_buf[0];
676                                         LOG_DEBUG("XSIR %d", bitcount);
677                                 } else {
678                                         if (read(xsvf_fd, short_buf, 2) < 0) {
679                                                 do_abort = 1;
680                                                 break;
681                                         }
682                                         bitcount = be_to_h_u16(short_buf);
683                                         LOG_DEBUG("XSIR2 %d", bitcount);
684                                 }
685
686                                 ir_buf = malloc((bitcount + 7) / 8);
687
688                                 if (xsvf_read_buffer(bitcount, xsvf_fd, ir_buf) != ERROR_OK)
689                                         do_abort = 1;
690                                 else {
691                                         struct scan_field field;
692
693                                         field.num_bits = bitcount;
694                                         field.out_value = ir_buf;
695
696                                         field.in_value = NULL;
697
698                                         if (tap == NULL)
699                                                 jtag_add_plain_ir_scan(field.num_bits,
700                                                                 field.out_value, field.in_value, my_end_state);
701                                         else
702                                                 jtag_add_ir_scan(tap, &field, my_end_state);
703
704                                         if (xruntest) {
705                                                 if (runtest_requires_tck)
706                                                         jtag_add_clocks(xruntest);
707                                                 else
708                                                         jtag_add_sleep(xruntest);
709                                         }
710
711                                         /* Note that an -irmask of non-zero in your config file
712                                          * can cause this to fail.  Setting -irmask to zero cand work
713                                          * around the problem.
714                                          */
715
716                                         /* LOG_DEBUG("FLUSHING QUEUE"); */
717                                         result = jtag_execute_queue();
718                                         if (result != ERROR_OK)
719                                                 tdo_mismatch = 1;
720                                 }
721                                 free(ir_buf);
722                         }
723                         break;
724
725                         case XCOMMENT:
726                         {
727                                 unsigned int ndx = 0;
728                                 char comment[128];
729
730                                 do {
731                                         if (read(xsvf_fd, &uc, 1) < 0) {
732                                                 do_abort = 1;
733                                                 break;
734                                         }
735
736                                         if (ndx < sizeof(comment)-1)
737                                                 comment[ndx++] = uc;
738
739                                 } while (uc != 0);
740
741                                 comment[sizeof(comment)-1] = 0;         /* regardless, terminate */
742                                 if (verbose)
743                                         LOG_USER("# %s", comment);
744                         }
745                         break;
746
747                         case XWAIT:
748                         {
749                                 /* expected in stream:
750                                    XWAIT <uint8_t wait_state> <uint8_t end_state> <uint32_t usecs>
751                                 */
752
753                                 uint8_t wait_local;
754                                 uint8_t end;
755                                 uint8_t delay_buf[4];
756
757                                 tap_state_t wait_state;
758                                 tap_state_t end_state;
759                                 int delay;
760
761                                 if (read(xsvf_fd, &wait_local, 1) < 0
762                                         || read(xsvf_fd, &end, 1) < 0
763                                         || read(xsvf_fd, delay_buf, 4) < 0) {
764                                                 do_abort = 1;
765                                                 break;
766                                 }
767
768                                 wait_state = xsvf_to_tap(wait_local);
769                                 end_state  = xsvf_to_tap(end);
770                                 delay = be_to_h_u32(delay_buf);
771
772                                 LOG_DEBUG("XWAIT %s %s usecs:%d", tap_state_name(
773                                                 wait_state), tap_state_name(end_state), delay);
774
775                                 if (runtest_requires_tck && wait_state == TAP_IDLE)
776                                         jtag_add_runtest(delay, end_state);
777                                 else {
778                                         /* FIXME handle statemove errors ... */
779                                         result = svf_add_statemove(wait_state);
780                                         if (result != ERROR_OK)
781                                                 return result;
782                                         jtag_add_sleep(delay);
783                                         result = svf_add_statemove(end_state);
784                                         if (result != ERROR_OK)
785                                                 return result;
786                                 }
787                         }
788                         break;
789
790                         case XWAITSTATE:
791                         {
792                                 /* expected in stream:
793                                  * XWAITSTATE <uint8_t wait_state> <uint8_t end_state> <uint32_t clock_count>
794                                  * <uint32_t usecs>
795                                 */
796
797                                 uint8_t clock_buf[4];
798                                 uint8_t usecs_buf[4];
799                                 uint8_t wait_local;
800                                 uint8_t end;
801                                 tap_state_t wait_state;
802                                 tap_state_t end_state;
803                                 int clock_count;
804                                 int usecs;
805
806                                 if (read(xsvf_fd, &wait_local, 1) < 0
807                                                 ||  read(xsvf_fd, &end, 1) < 0
808                                                 ||  read(xsvf_fd, clock_buf, 4) < 0
809                                                 ||  read(xsvf_fd, usecs_buf, 4) < 0) {
810                                         do_abort = 1;
811                                         break;
812                                 }
813
814                                 wait_state = xsvf_to_tap(wait_local);
815                                 end_state  = xsvf_to_tap(end);
816
817                                 clock_count = be_to_h_u32(clock_buf);
818                                 usecs = be_to_h_u32(usecs_buf);
819
820                                 LOG_DEBUG("XWAITSTATE %s %s clocks:%i usecs:%i",
821                                                 tap_state_name(wait_state),
822                                                 tap_state_name(end_state),
823                                                 clock_count, usecs);
824
825                                 /* the following states are 'stable', meaning that they have a transition
826                                  * in the state diagram back to themselves.  This is necessary because we will
827                                  * be issuing a number of clocks in this state.  This set of allowed states is also
828                                  * determined by the SVF RUNTEST command's allowed states.
829                                  */
830                                 if (!svf_tap_state_is_stable(wait_state)) {
831                                         LOG_ERROR("illegal XWAITSTATE wait_state: \"%s\"",
832                                                         tap_state_name(wait_state));
833                                         unsupported = 1;
834                                         /* REVISIT "break" so we won't run? */
835                                 }
836
837                                 /* FIXME handle statemove errors ... */
838                                 result = svf_add_statemove(wait_state);
839                                 if (result != ERROR_OK)
840                                         return result;
841
842                                 jtag_add_clocks(clock_count);
843                                 jtag_add_sleep(usecs);
844
845                                 result = svf_add_statemove(end_state);
846                                 if (result != ERROR_OK)
847                                         return result;
848                         }
849                         break;
850
851                         case LCOUNT:
852                         {
853                                 /* expected in stream:
854                                  * LCOUNT <uint32_t loop_count>
855                                 */
856                                 uint8_t count_buf[4];
857
858                                 if (read(xsvf_fd, count_buf, 4) < 0) {
859                                         do_abort = 1;
860                                         break;
861                                 }
862
863                                 loop_count = be_to_h_u32(count_buf);
864                                 LOG_DEBUG("LCOUNT %d", loop_count);
865                         }
866                         break;
867
868                         case LDELAY:
869                         {
870                                 /* expected in stream:
871                                  * LDELAY <uint8_t wait_state> <uint32_t clock_count> <uint32_t usecs_to_sleep>
872                                 */
873                                 uint8_t state;
874                                 uint8_t clock_buf[4];
875                                 uint8_t usecs_buf[4];
876
877                                 if (read(xsvf_fd, &state, 1) < 0
878                                                 || read(xsvf_fd, clock_buf, 4) < 0
879                                                 || read(xsvf_fd, usecs_buf, 4) < 0) {
880                                         do_abort = 1;
881                                         break;
882                                 }
883
884                                 /* NOTE:  loop_state must be stable! */
885                                 loop_state  = xsvf_to_tap(state);
886                                 loop_clocks = be_to_h_u32(clock_buf);
887                                 loop_usecs  = be_to_h_u32(usecs_buf);
888
889                                 LOG_DEBUG("LDELAY %s clocks:%d usecs:%d", tap_state_name(
890                                                 loop_state), loop_clocks, loop_usecs);
891                         }
892                         break;
893
894                         /* LSDR is more like XSDRTDO than it is like XSDR.  It uses LDELAY which
895                          * comes with clocks !AND! sleep requirements.
896                          */
897                         case LSDR:
898                         {
899                                 int limit = loop_count;
900                                 int matched = 0;
901                                 int attempt;
902
903                                 LOG_DEBUG("LSDR");
904
905                                 if (xsvf_read_buffer(xsdrsize, xsvf_fd, dr_out_buf) != ERROR_OK
906                                                 || xsvf_read_buffer(xsdrsize, xsvf_fd, dr_in_buf) != ERROR_OK) {
907                                         do_abort = 1;
908                                         break;
909                                 }
910
911                                 if (limit < 1)
912                                         limit = 1;
913
914                                 for (attempt = 0; attempt < limit; ++attempt) {
915                                         struct scan_field field;
916
917                                         result = svf_add_statemove(loop_state);
918                                         if (result != ERROR_OK) {
919                                                 free(dr_in_mask);
920                                                 return result;
921                                         }
922                                         jtag_add_clocks(loop_clocks);
923                                         jtag_add_sleep(loop_usecs);
924
925                                         field.num_bits = xsdrsize;
926                                         field.out_value = dr_out_buf;
927                                         field.in_value = calloc(DIV_ROUND_UP(field.num_bits, 8), 1);
928
929                                         if (attempt > 0 && verbose)
930                                                 LOG_USER("LSDR retry %d", attempt);
931
932                                         if (tap == NULL)
933                                                 jtag_add_plain_dr_scan(field.num_bits,
934                                                                 field.out_value,
935                                                                 field.in_value,
936                                                                 TAP_DRPAUSE);
937                                         else
938                                                 jtag_add_dr_scan(tap, 1, &field, TAP_DRPAUSE);
939
940                                         jtag_check_value_mask(&field, dr_in_buf, dr_in_mask);
941
942                                         free(field.in_value);
943
944
945                                         /* LOG_DEBUG("FLUSHING QUEUE"); */
946                                         result = jtag_execute_queue();
947                                         if (result == ERROR_OK) {
948                                                 matched = 1;
949                                                 break;
950                                         }
951                                 }
952
953                                 if (!matched) {
954                                         LOG_USER("LSDR mismatch");
955                                         tdo_mismatch = 1;
956                                         break;
957                                 }
958                         }
959                         break;
960
961                         case XTRST:
962                         {
963                                 uint8_t trst_mode;
964
965                                 if (read(xsvf_fd, &trst_mode, 1) < 0) {
966                                         do_abort = 1;
967                                         break;
968                                 }
969
970                                 switch (trst_mode) {
971                                 case XTRST_ON:
972                                         jtag_add_reset(1, 0);
973                                         break;
974                                 case XTRST_OFF:
975                                 case XTRST_Z:
976                                         jtag_add_reset(0, 0);
977                                         break;
978                                 case XTRST_ABSENT:
979                                         break;
980                                 default:
981                                         LOG_ERROR("XTRST mode argument (0x%02X) out of range", trst_mode);
982                                         do_abort = 1;
983                                 }
984                         }
985                         break;
986
987                         default:
988                                 LOG_ERROR("unknown xsvf command (0x%02X)", uc);
989                                 unsupported = 1;
990                 }
991
992                 if (do_abort || unsupported || tdo_mismatch) {
993                         LOG_DEBUG("xsvf failed, setting taps to reasonable state");
994
995                         /* upon error, return the TAPs to a reasonable state */
996                         result = svf_add_statemove(TAP_IDLE);
997                         if (result != ERROR_OK)
998                                 return result;
999                         result = jtag_execute_queue();
1000                         if (result != ERROR_OK)
1001                                 return result;
1002                         break;
1003                 }
1004         }
1005
1006         if (tdo_mismatch) {
1007                 command_print(CMD,
1008                         "TDO mismatch, somewhere near offset %lu in xsvf file, aborting",
1009                         file_offset);
1010
1011                 return ERROR_FAIL;
1012         }
1013
1014         if (unsupported) {
1015                 off_t offset = lseek(xsvf_fd, 0, SEEK_CUR) - 1;
1016                 command_print(CMD,
1017                         "unsupported xsvf command (0x%02X) at offset %jd, aborting",
1018                         uc, (intmax_t)offset);
1019                 return ERROR_FAIL;
1020         }
1021
1022         if (do_abort) {
1023                 command_print(CMD, "premature end of xsvf file detected, aborting");
1024                 return ERROR_FAIL;
1025         }
1026
1027         free(dr_out_buf);
1028         free(dr_in_buf);
1029         free(dr_in_mask);
1030
1031         close(xsvf_fd);
1032
1033         command_print(CMD, "XSVF file programmed successfully");
1034
1035         return ERROR_OK;
1036 }
1037
1038 static const struct command_registration xsvf_command_handlers[] = {
1039         {
1040                 .name = "xsvf",
1041                 .handler = handle_xsvf_command,
1042                 .mode = COMMAND_EXEC,
1043                 .help = "Runs a XSVF file.  If 'virt2' is given, xruntest "
1044                         "counts are interpreted as TCK cycles rather than "
1045                         "as microseconds.  Without the 'quiet' option, all "
1046                         "comments, retries, and mismatches will be reported.",
1047                 .usage = "(tapname|'plain') filename ['virt2'] ['quiet']",
1048         },
1049         COMMAND_REGISTRATION_DONE
1050 };
1051
1052 int xsvf_register_commands(struct command_context *cmd_ctx)
1053 {
1054         return register_commands(cmd_ctx, NULL, xsvf_command_handlers);
1055 }
1056
1057 /*
1058
1059 PSUEDO-Code from Xilinx Appnote XAPP067.pdf :
1060
1061 the following pseudo code clarifies the intent of the xrepeat support.The
1062 flow given is for the entire processing of an SVF file, not an XSVF file.
1063 No idea if this is just for the XC9500/XL/XV devices or all Xilinx parts.
1064
1065 "Pseudo-Code Algorithm for SVF-Based ISP"
1066
1067 1. Go to Test-Logic-Reset state
1068 2. Go to Run-Test Idle state
1069 3. Read SVF record
1070
1071 4. if SIR record then
1072 go to Shift-IR state
1073 Scan in <TDI value>
1074
1075 5. else if SDR record then
1076 set <repeat count> to 0
1077 store <TDI value> as <current TDI value>
1078 store <TDO value> as <current TDO value>
1079 6. go to Shift-DR state
1080 scan in <current TDI value>
1081 if < current TDO value > is specified then
1082 if < current TDO value > does not equal <actual TDO value> then
1083 if < repeat count > > 32 then
1084 LOG ERROR
1085 go to Run-Test Idle state
1086 go to Step 3
1087 end if
1088 go to Pause-DR
1089 go to Exit2-DR
1090 go to Shift-DR
1091 go to Exit1-DR
1092 go to Update-DR
1093 go to Run-Test/Idle
1094 increment <repeat count> by 1
1095 pause <current pause time> microseconds
1096 go to Step 6)
1097 end if
1098 else
1099         go to Run-Test Idle state
1100         go to Step 3
1101         endif
1102         else if RUNTEST record then
1103         pause tester for < TCK value > microseconds
1104         store <TCK value> as <current pause time>
1105         end if
1106
1107 */