Rev Author Line No. Line
2697 miho 1 // MLAB Xilinx Virtual Cable Network Server
2 // ----------------------------------------
3 //
4 // (c) miho 2012 http://www.mlab.cz/PermaLink/XVC_SOFTWARE
5 //
6 // This program if free.
7 //
8 //
9 // History:
10 //
11 // 1.00 2012_09 Proof of concept (no configuration, not for public release)
12 // 1.01 2012_09 Added parameter for device selection
13 // 1.02 2012_12 Error handling and debugged
14 // 1.03 2012_12 Release version ready to publish
15 //
16 //
17 // Purpose:
18 //
19 // XILINX development software (ISE, WebPack) supports several types of JTAG programming
20 // cables. Among them there is one particularly interesting. It is Xilinx Virtual Cable
21 // which uses (documented) XVC network protocol to send JTAG commands across TCP/IP network.
22 // So it is possible to realize own hardware/software and have it directly supported by
23 // XILINX development software (both IMPACT and ChipScope).
24 //
25 // This program listens TCP data send by XILINX ISE IMAPACT (or ChipScope) and sends it
26 // to the JTAG device (typically FPGA) connected to FTDI USB Chip. You can use ordinary
27 // USB/RS232 translator based on FT232R chip or you can use our own module from
28 // http://www.mlab.cz/PermaLink/XVC_FT220X
29 //
30 // Target device JTAG port is connected to pins on FTDI USB chip. Program writes to standard
31 // output Which pins are used. Program writes what to set in ISE to enable XVC plugin.
32 //
33 //
34 // Environment:
35 //
36 // This is Win32 Console Application and run in WinXP / Win7 / Win8 both 32 and 64 bit.
37 //
38 // Program needs to listen to the network so it is necessary to allow doing so. In Windows
39 // firewall configuration enable networking for the exe file.
40 // WinXP: run as Administrator c:\WINDOWS\System32\firewall.cpl and add the exe file
41 // Win7: the system asks directly to do so
42 //
43 //
44 // Technology:
45 //
46 // The program uses Windows WINSOCK2 library for network communication
47 // and FTDI ftd2xx library for communication with FTDI USB chip.
48 // It can be staticly linked to minimize dependencies on libraries.
49 // Program requires FTDI drivers installed.
50 // Because of the usage of standard libraries you don't need to solve how to sign drivers.
51 //
52 // The program was debug with FT232R and FT220X device.
53 // It should work with any similar FTDI USB chip.
54 //
55 // XVC protocol is documented (you have to ask XILINX support to gain access).
56 // The program is inspired by the work http://debugmo.de/2012/02/xvcd-the-xilinx-virtual-cable-daemon/
57 // Ask Google about Xilinx Virtual Cable.
58 //
59 //
60 // Translation:
61 //
62 // MS Visual C++ 2010 Express (free, registration required)
63 // Create new empty project for Win32 Console Application and name project mlab_xvcd (to build mlab_xvcd.exe)
64 // Header Files / Add / Existing Items - all .h files
65 // Resource Files / Add / Existing Items - all .lib files
66 // Source Files / Add / Existing Items - all .cpp files
67 // Select Release version (no debug info)
68 // Set static linkage Project Properties / Configuration Release / Configuration Properties
69 // / Code Generation / Runtime Library = Multithreaded (/MT)
70 //
71 //
72 // Problems:
73 //
74 // Programming of SPI FLASH configuration memory connected to FPGA does not work. No idea why.
75 // It does not work for internal FLASH of Spartan XC3SxxAN either.
76 //
77 //
78 // Possible improvements:
79 //
80 // Linux version (Winsock library differs).
81 // External definition of JTAG pins.
82  
83  
84 // Library Definitions
85 // -------------------
86  
87 #undef UNICODE
88 #define WIN32_LEAN_AND_MEAN
89  
90 #include "mlab_xvcd.h" // Program Configuration
91 #include <windows.h> // Windows Console Application
92 #include <winsock2.h> // Windows WinSock2
93 #include <ws2tcpip.h> // Windows WinSock2
94 #include <stdlib.h> // Standard Library (exit, atoi, ...)
95 #include <stdio.h> // Standard IO (printf, ...)
96 #include <signal.h> // CTRL+C handling
97  
98 // Link with library
99 #pragma comment (lib, "Ws2_32.lib")
100  
101 #define XVC_RX_BUFLEN (XVC_JTAG_LEN/8*2+20) // Length of receive buffer in bytes (command+length+TMSbuffer+TDIbuffer)
102 #define XVC_TX_BUFLEN (XVC_JTAG_LEN/8) // Length of transmit buffer in bytes (TDObuffer)
103  
104  
105 // JTAG state machine
106 // ------------------
107  
108 // JTAG States
109 enum
110 {
111 test_logic_reset, run_test_idle, // Starts from 0
112  
113 select_dr_scan, capture_dr, shift_dr,
114 exit1_dr, pause_dr, exit2_dr, update_dr,
115  
116 select_ir_scan, capture_ir, shift_ir,
117 exit1_ir, pause_ir, exit2_ir, update_ir,
118  
119 num_states
120 };
121  
122  
123 // JTAG State Machine transfer Function
124 static int jtagStep(int state, int tms)
125 {
126 static const int next_state[num_states][2] =
127 {
128 /* JTAG State -->> New State */
129 /* -------------------------------------------------------------*/
130 /* | TMS=0 | TMS=1 */
131 /* -------------------------------------------------------------*/
132 /* [test_logic_reset] -> */ { run_test_idle, test_logic_reset },
133 /* [run_test_idle] -> */ { run_test_idle, select_dr_scan },
134 /* [select_dr_scan] -> */ { capture_dr, select_ir_scan },
135 /* [capture_dr] -> */ { shift_dr, exit1_dr },
136 /* [shift_dr] -> */ { shift_dr, exit1_dr },
137 /* [exit1_dr] -> */ { pause_dr, update_dr },
138 /* [pause_dr] -> */ { pause_dr, exit2_dr },
139 /* [exit2_dr] -> */ { shift_dr, update_dr },
140 /* [update_dr] -> */ { run_test_idle, select_dr_scan },
141 /* [select_ir_scan] -> */ { capture_ir, test_logic_reset },
142 /* [capture_ir] -> */ { shift_ir, exit1_ir },
143 /* [shift_ir] -> */ { shift_ir, exit1_ir },
144 /* [exit1_ir] -> */ { pause_ir, update_ir },
145 /* [pause_ir] -> */ { pause_ir, exit2_ir },
146 /* [exit2_ir] -> */ { shift_ir, update_ir },
147 /* [update_ir] -> */ { run_test_idle, select_dr_scan }
148 };
149  
150 return next_state[state][tms];
151 }
152  
153  
154 int handleData(SOCKET ClientSocket)
155 {
156  
157 bool seen_tlr = false;
158 bool jtagError = false;
159  
160 static int jtag_state;
161  
162 do
163 {
164 int iResult;
165  
166 // Read Command
167 char command[16];
168 int commandLen = 0;
169  
170 // Read String terminated by ':'
171 do
172 {
173 iResult = recv(ClientSocket, command+commandLen, 1, 0);
174 if (iResult==0)
175 {
176 printf("\n Connection Closed\n\n");
177 return -1;
178 }
179 else if (iResult==1)
180 {
181 commandLen++;
182 }
183 else
184 {
185 fprintf(stderr, "Error Reading Command\n");
186 return -2;
187 }
188 }
189 while (command[commandLen-1]!=':' && commandLen<sizeof(command)-1 );
190 command[commandLen] = char(0);
191  
192 if (0==strncmp(command, "shift:", sizeof(command)))
193 {
194  
195 }
196 else
197 {
198 fprintf(stderr, "Invalid Command '%s'\n", command);
199 return -2;
200 }
201  
202 // Read Length (in bits, 32bit integer)
203 int len;
204  
205 iResult = recv(ClientSocket, (char *)&len, 4, 0); // pøepsat pøenositelnì
206 if (iResult==0)
207 {
208 printf("\n Connection Closed\n\n");
209 return -1;
210 }
211 if (iResult != 4)
212 {
213 fprintf(stderr, "Reading Length Failed\n");
214 return -2;
215 }
216  
217 char buffer[2048];
218  
219 // Read Data (data string for TMS and TDI)
220 int nr_bytes = (len + 7) / 8;
221 if (nr_bytes * 2 > sizeof(buffer))
222 {
223 fprintf(stderr, "Buffer Size Exceeded\n");
224 return -2;
225 }
226  
227 int iReceivedBytes=0;
228 while (iReceivedBytes<nr_bytes * 2)
229 {
230 iResult = recv(ClientSocket, buffer+iReceivedBytes, nr_bytes * 2 - iReceivedBytes, 0);
231 if (iResult==0)
232 {
233 printf("\n Connection Closed\n\n");
234 return -1;
235 }
236 if (iResult<=0)
237 {
238 fprintf(stderr, "Reading Data Failed %d %d\n", iResult, nr_bytes * 2);
239 return -2;
240 }
241 iReceivedBytes += iResult;
242 }
243  
244 char result[1024];
245 memset(result, 0, nr_bytes);
246  
247 // Deal with JTAG
248  
249 // Only allow exiting if the state is rti and the IR
250 // has the default value (IDCODE) by going through test_logic_reset.
251 // As soon as going through capture_dr or capture_ir no exit is
252 // allowed as this will change DR/IR.
253 seen_tlr = (seen_tlr || jtag_state == test_logic_reset) && (jtag_state != capture_dr) && (jtag_state != capture_ir);
254  
255 // Due to a weird bug(??) xilinx impacts goes through another "capture_ir"/"capture_dr" cycle after
256 // reading IR/DR which unfortunately sets IR to the read-out IR value.
257 // Just ignore these transactions.
258 if ((jtag_state == exit1_ir && len == 5 && buffer[0] == 0x17) || (jtag_state == exit1_dr && len == 4 && buffer[0] == 0x0b))
259 {
260 // printf("Ignoring Bogus jtag State movement at jtag_state %d\n", jtag_state);
261 }
262 else
263 {
264 for (int i = 0; i < len; ++i)
265 {
266 //
267 // Do the actual cycle.
268 //
269 int tms = !!(buffer[i/8] & (1<<(i&7)));
270 //
271 // Track the state.
272 //
273 jtag_state = jtagStep(jtag_state, tms);
274 }
275 if (jtagScan((unsigned char *) buffer, (unsigned char *) buffer + nr_bytes, (unsigned char *) result, len) < 0)
276 {
277 //fprintf(stderr, "jtagScan failed\n");
278 // Can't stop now, have to sent (any) answer not to hung the IMPACT
279 jtagError = true;
280 }
281 }
282  
283 // Send the Ansver
284 iResult = send(ClientSocket, result, nr_bytes, 0 );
285 if (iResult == SOCKET_ERROR)
286 {
287 printf("Send Failed with Error: %d\n", WSAGetLastError());
288 closesocket(ClientSocket);
289 WSACleanup();
290 return -2;
291 }
292 // printf("Bytes Sent: %d\n", iSendResult);
293 // printf("jtag state %d\n", jtag_state);
294 }
295 while (!(seen_tlr && jtag_state == run_test_idle));
296  
297 return jtagError ? -2 : 0;
298 }
299  
300  
301 // Stop Handler - switch JTAG port off and stop program
302 void stopHandler(int sig)
303 {
304 jtagClosePort();
305 exit(1);
306 }
307  
308  
309 // Print help and stop program with error
310 void Help(char *progName)
311 {
312 fprintf(stderr, "Bad Parameters\n");
313 fprintf(stderr, "\n");
314 fprintf(stderr, "Usage: %s [arg]\n", progName);
315 fprintf(stderr, "\n");
316 fprintf(stderr, " Where [arg] is one of: \n");
317 fprintf(stderr, " -d Description Fing FTDI device by Description\n");
318 fprintf(stderr, " -l Location Fing FTDI device by Loaction\n");
319 fprintf(stderr, " -s Serial_number Fing FTDI device by it's SN\n");
320 fprintf(stderr, " -n Number Use N-th FTDI device\n");
321 fprintf(stderr, " The first FTDI device is used if no argument\n");
322 exit(2);
323 }
324  
325  
326 int __cdecl main(int argc, char *argv[])
327 {
328 // Variables
329 bool verbose = true;
330  
331 // Program Info
332 printf("\n");
333 printf("Xilinx Virtual Cable Network Server\n");
334 printf("===================================\n");
335 printf("(c) miho 2012 v " VERSION "\n\n");
336  
337 // Get program name
338 char *cp;
339 char *progName;
340 cp = argv[0];
341 progName=cp;
342 while (cp[0]!='\0')
343 {
344 if (cp[0]=='/' || cp[0]=='\\')
345 progName=cp+1;
346 cp++;
347 }
348  
349 // Process command line params
350 char *findDeviceByStr = 0; // String parameter
351 int findDeviceBy = 0; // What does the string means
352  
353 if (argc>1)
354 {
355 if (argc==3)
356 {
357 findDeviceByStr = argv[2];
358 if (strcmp(argv[1], "-d")==0)
359 {
360 findDeviceBy = OPEN_BY_DESCRIPTION;
361 }
362 else if (strcmp(argv[1], "-l")==0)
363 {
364 findDeviceBy = OPEN_BY_LOCATION;
365 }
366 else if (strcmp(argv[1], "-s")==0)
367 {
368 findDeviceBy = OPEN_BY_SERIAL_NUMBER;
369 }
370 else if (strcmp(argv[1], "-n")==0)
371 {
372 findDeviceBy = 0;
373 }
374 else
375 {
376 Help(progName);
377 }
378 }
379 else
380 {
381 Help(progName);
382 }
383 }
384 else
385 {
386 // Empty String - find device by number and number is empty
387 findDeviceBy = 0;
388 findDeviceByStr = "";
389 }
390  
391 // Find, Init and Open FTDI USB Chip
392 if (jtagOpenPort(findDeviceBy, findDeviceByStr)<0) {
393 // No Device Found
394 fprintf(stderr, "ERROR: No Device Found\n");
395 return -1;
396 }
397  
398 // Signal Handler (for CRTL+C)
399 signal(SIGINT, &stopHandler);
400  
401 printf("Starting Network Server\n");
402 WSADATA wsaData;
403 int iResult;
404  
405 SOCKET ListenSocket = INVALID_SOCKET;
406 SOCKET ClientSocket = INVALID_SOCKET;
407  
408 // Initialize Winsock
409 iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
410 if (iResult != 0)
411 {
412 fprintf(stderr, "WSAStartup failed with error: %d\n", iResult);
413 jtagClosePort();
414 return -2;
415 }
416  
417 // Display HostName and Address
418 char sMyName[255];
419 gethostname(sMyName, sizeof(sMyName));
420 printf(" Host Name %s\n", sMyName);
421 hostent * pHostInfo;
422 pHostInfo = gethostbyname(sMyName);
423 printf(" Network Name %s\n", pHostInfo->h_name);
424 if (pHostInfo->h_length>0 && pHostInfo->h_length<=16)
425 {
426 printf(" Host Address ");
427 for (int i=0; i<pHostInfo->h_length-1; i++)
428 {
429 printf("%d.", (unsigned char)pHostInfo->h_addr_list[0][i]);
430 }
431 printf("%d\n", (unsigned char)pHostInfo->h_addr_list[0][pHostInfo->h_length-1]);
432 }
433  
434 // Create Protocol Structure
435 struct addrinfo hints;
436 ZeroMemory(&hints, sizeof(hints));
437 hints.ai_family = AF_INET; // IP6
438 hints.ai_socktype = SOCK_STREAM; // Reliable two-way connection
439 hints.ai_protocol = IPPROTO_TCP; // Protocol TCP
440 hints.ai_flags = AI_PASSIVE;
441  
442 // Resolve the server address and port (allocate structure "result")
443 struct addrinfo *result = NULL;
444 iResult = getaddrinfo(NULL, XVC_TCP_PORT, &hints, &result);
445 if ( iResult != 0 )
446 {
447 fprintf(stderr, "getaddrinfo failed with error: %d\n", iResult);
448 WSACleanup();
449 jtagClosePort();
450 return -2;
451 }
452  
453 // Create a SOCKET
454 ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
455 if (ListenSocket == INVALID_SOCKET)
456 {
457 fprintf(stderr, "socket failed with error: %ld\n", WSAGetLastError());
458 freeaddrinfo(result);
459 WSACleanup();
460 jtagClosePort();
461 return -2;
462 }
463  
464 // Bind the SOCKED (assign the address)
465 iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
466 if (iResult == SOCKET_ERROR)
467 {
468 fprintf(stderr, "Bind failed with error: %d\n", WSAGetLastError());
469 freeaddrinfo(result);
470 closesocket(ListenSocket);
471 WSACleanup();
472 jtagClosePort();
473 return -2;
474 }
475  
476 if (verbose)
477 {
478 printf(" Bound Socket %s\n", XVC_TCP_PORT);
479 }
480  
481 // Help for user
482 printf(" Set in IMPACT xilinx_xvc host=%s:%s disableversioncheck=true\n", sMyName, XVC_TCP_PORT);
483  
484 freeaddrinfo(result);
485  
486 // Listen SOCKET
487 iResult = listen(ListenSocket, SOMAXCONN);
488 if (iResult == SOCKET_ERROR)
489 {
490 printf("listen failed with error: %d\n", WSAGetLastError());
491 closesocket(ListenSocket);
492 WSACleanup();
493 jtagClosePort();
494 return -2;
495 }
496  
497 printf("\n");
498  
499 do
500 {
501 printf(" Listen\n");
502 jtagSetLED(true);
503  
504 // Accept a client SOCKET
505 sockaddr ClientSocetAddr;
506 int ClientSocetAddrLen = sizeof(sockaddr);
507 ClientSocket = accept(ListenSocket, &ClientSocetAddr, &ClientSocetAddrLen);
508 if (ClientSocket == INVALID_SOCKET)
509 {
510 printf("accept failed with error: %d\n", WSAGetLastError());
511 closesocket(ListenSocket);
512 WSACleanup();
513 jtagClosePort();
514 return -2;
515 }
516  
517 // Print Accepted + Address
518 printf(" Accepted ");
519 jtagSetLED(false);
520 for (int i=2; i<2+4-1; i++)
521 {
522 printf("%d.", (unsigned char)ClientSocetAddr.sa_data[i]);
523 }
524 printf("%d:%d\n", (unsigned char)ClientSocetAddr.sa_data[2+4-1], (unsigned char)ClientSocetAddr.sa_data[0]*256+(unsigned char)ClientSocetAddr.sa_data[1]);
525  
526 // Process Data until the peer shuts down the connection
527 int Cnt = 0;
528 printf(" Handle Data ");
529 do
530 {
531 iResult = handleData(ClientSocket);
532 if (iResult>=0)
533 {
534 printf(".");
535 Cnt++;
536 if (Cnt>40)
537 {
538 Cnt = 0;
539 printf("\n ");
540 }
541 }
542 }
543 while (iResult >= 0);
544  
545 // Connection Closed by peer
546 if (iResult==-1)
547 {
548 // JTAG port
549 jtagSetIdle();
550 }
551  
552 // Error - shutdown the connection
553 if (iResult==-2)
554 {
555 fprintf(stderr, " Disconnect\n");
556 iResult = shutdown(ClientSocket, SD_SEND);
557 if (iResult == SOCKET_ERROR)
558 {
559 fprintf(stderr, "shutdown failed with error: %d\n", WSAGetLastError());
560 }
561 iResult=-2; // Error
562 }
563  
564 // cleanup
565 closesocket(ClientSocket);
566  
567 }
568 // If not Error Listen Again
569 while (iResult!=-2);
570  
571 // cleanup
572 closesocket(ListenSocket);
573 WSACleanup();
574 jtagClosePort();
575  
576 return 1;
577 }