Debian Codegraph @

src/jtag3io.cc

raw symbols SCIP
1 /*
2 * avarice - The "avarice" program.
3 * Copyright (C) 2012 Joerg Wunsch
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 Version 2
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
17 *
18 * This file implements the basic IO handling for the JTAGICE3 protocol.
19 *
20 * $Id: jtag3io.cc 427 2022-01-20 09:28:04Z joerg_wunsch $
21 */
22
23
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30 #include <termios.h>
31 #include <fcntl.h>
32 #include <signal.h>
33 #include <string.h>
34 #include <errno.h>
35
36 #include "avarice.h"
37 #include "jtag.h"
38 #include "jtag3.h"
39
40 jtag3_io_exception::jtag3_io_exception(unsigned int code)
41 {
42 static char buffer[50];
43 response_code = code;
44
45 switch (code)
46 {
47 case RSP3_FAIL_DEBUGWIRE:
48 reason = "debugWIRE failed"; break;
49
50 case RSP3_FAIL_PDI:
51 reason = "PDI failed"; break;
52
53 case RSP3_FAIL_NO_ANSWER:
54 reason = "no answer from target"; break;
55
56 case RSP3_FAIL_NO_TARGET_POWER:
57 reason = "No target power present"; break;
58
59 case RSP3_FAIL_WRONG_MODE:
60 reason = "wrong mode"; break;
61
62 case RSP3_FAIL_UNSUPP_MEMORY:
63 reason = "unsupported memory type"; break;
64
65 case RSP3_FAIL_WRONG_LENGTH:
66 reason = "wrong length for memory access"; break;
67
68 case RSP3_FAIL_NOT_UNDERSTOOD:
69 reason = "command not understood"; break;
70
71 default:
72 snprintf(buffer, sizeof buffer, "Unknown response code 0x%0x", code);
73 reason = buffer;
74 }
75 }
76
77 jtag3::~jtag3(void)
78 {
79 // Terminate connection to JTAG box.
80 if (signedIn)
81 {
82 if (debug_active)
83 {
84 try
85 {
86 doSimpleJtagCommand(CMD3_STOP_DEBUG, "stop debugging");
87 }
88 catch (jtag_exception&)
89 {
90 // just proceed with the sign-off
91 }
92
93 try
94 {
95 doSimpleJtagCommand(CMD3_SIGN_OFF, "AVR sign-off");
96 }
97 catch (jtag_exception&)
98 {
99 // just proceed with the sign-off
100 }
101 }
102
103 try
104 {
105 doSimpleJtagCommand(CMD3_SIGN_OFF, "sign-off", SCOPE_GENERAL);
106 }
107 catch (jtag_exception&)
108 {
109 // just proceed with the sign-off
110 }
111 signedIn = false;
112 }
113 }
114
115
116 /*
117 * Send one frame. Adds the required preamble and CRC, and ensures
118 * the frame could be written correctly.
119 */
120 void jtag3::sendFrame(uchar *command, int commandSize)
121 {
122 unsigned char *buf = new unsigned char[commandSize + 4];
123
124 buf[0] = TOKEN;
125 buf[1] = 0;
126 u16_to_b2(buf + 2, command_sequence);
127 memcpy(buf + 4, command, commandSize);
128
129 for (int i = 0; i < commandSize + 4; i++)
130 debugOut("%.2X ", buf[i]);
131 debugOut("\n");
132
133 int count = safewrite(buf, commandSize + 4);
134
135 delete [] buf;
136
137 if (count < 0)
138 throw jtag_exception();
139 else if (count != commandSize + 4)
140 // this shouldn't happen
141 throw jtag_exception("Invalid write size");
142 }
143
144 /*
145 * Receive one frame, return it in &msg. Received sequence number is
146 * returned in &seqno. Any valid frame will be returned, regardless
147 * whether it matches the expected sequence number, including event
148 * notification frames (seqno == 0xffff).
149 *
150 * Caller must eventually free the buffer.
151 */
152 int jtag3::recvFrame(unsigned char *&msg, unsigned short &seqno)
153 {
154 uchar tempbuf[MAX_MESSAGE_SIZE_JTAGICE3];
155 int rv, l;
156
157 msg = NULL;
158
159 int amnt;
160 rv = timeout_read((void *)&amnt, sizeof amnt, JTAG_RESPONSE_TIMEOUT);
161 if (rv == 0)
162 {
163 /* timeout */
164 debugOut("read() timed out\n");
165
166 return 0;
167 }
168 else if (rv < 0)
169 {
170 /* error */
171 debugOut("read() error %d\n", rv);
172 throw jtag_exception("read error");
173 }
174 if (amnt <= 0 || amnt > MAX_MESSAGE_SIZE_JTAGICE3)
175 {
176 debugOut("unexpected message size from pipe: %d\n", amnt);
177 return 0;
178 }
179
180 rv = timeout_read(tempbuf, amnt, JTAG3_PIPE_TIMEOUT);
181 if (rv > 0)
182 {
183 bool istoken = tempbuf[0] == TOKEN_EVT3;
184 if (istoken)
185 tempbuf[0] = TOKEN;
186
187 debugOut("read: ");
188 for (l = 0; l < rv; l++) {
189 debugOut(" %02x", tempbuf[l]);
190 }
191 debugOut("\n");
192
193 if (istoken)
194 {
195 unsigned int serial = tempbuf[2] + (tempbuf[3] << 8);
196 debugOut("Event serial 0x%04x\n", serial);
197
198 rv -= 4;
199 msg = new unsigned char[rv];
200 seqno = 0xffff;
201 memcpy(msg, tempbuf + 4, rv);
202
203 return rv;
204 }
205 else
206 {
207 seqno = tempbuf[1] + (tempbuf[2] << 8);
208 rv -= 3;
209 msg = new unsigned char[rv];
210 memcpy(msg, tempbuf + 3, rv);
211
212 return rv;
213 }
214 }
215 else if (rv == 0)
216 {
217 /* timeout */
218 debugOut("read() timed out\n");
219
220 return 0;
221 }
222 else
223 {
224 /* error */
225 debugOut("read() error %d\n", rv);
226 throw jtag_exception("read error");
227 }
228 }
229
230 /*
231 * Try receiving frames, until we get the reply we are expecting.
232 * Caller must delete[] the msg after processing it.
233 */
234 int jtag3::recv(uchar *&msg)
235 {
236 unsigned short r_seqno;
237 int rv;
238
239 for (;;) {
240 if ((rv = recvFrame(msg, r_seqno)) <= 0)
241 return rv;
242 debugOut("\nGot message seqno %d (command_sequence == %d)\n",
243 r_seqno, command_sequence);
244 if (r_seqno == command_sequence) {
245 if (++command_sequence == 0xffff)
246 command_sequence = 0;
247 return rv;
248 }
249 if (r_seqno == 0xffff) {
250 debugOut("\ngot asynchronous event: 0x%02x, 0x%02x\n",
251 msg[0], msg[1]);
252 if (cached_event == NULL)
253 {
254 cached_event = msg;
255 // do *not* delete[] it here
256 continue;
257 }
258 } else {
259 debugOut("\ngot wrong sequence number, %u != %u\n",
260 r_seqno, command_sequence);
261 }
262 delete [] msg;
263 }
264 }
265
266 /** Send a command to the jtag, and check result.
267
268 Reads first response byte. If no response is received within
269 JTAG_RESPONSE_TIMEOUT, returns false. If response is
270 positive returns true, otherwise returns false.
271
272 If response is positive, message (including response code) is
273 returned in &msg, caller must delete [] it. The message size is
274 returned in &msgsize.
275 **/
276
277 bool jtag3::sendJtagCommand(uchar *command, int commandSize,
278 const char *name,
279 uchar *&msg, int &msgsize)
280 {
281 debugOut("\ncommand \"%s\" [0x%02x, 0x%02x]\n",
282 name, command[0], command[1]);
283
284 sendFrame(command, commandSize);
285
286 msgsize = recv(msg);
287 if (msgsize < 1)
288 return false;
289
290 debugOut("response: ");
291 for (int i = 0; i < msgsize; i++)
292 {
293 debugOut("%.2X ", msg[i]);
294 }
295 debugOut("\n");
296
297 unsigned char c = msg[1];
298
299 if (c >= RSP3_OK && c < RSP3_FAILED)
300 return true;
301
302 return false;
303 }
304
305
306 void jtag3::doJtagCommand(uchar *command, int commandSize,
307 const char *name,
308 uchar *&response, int &responseSize)
309 {
310 if (sendJtagCommand(command, commandSize, name, response, responseSize))
311 return;
312
313 if (responseSize == 0)
314 throw jtag_timeout_exception();
315 else
316 throw jtag3_io_exception(response[3]);
317 }
318
319 void jtag3::doSimpleJtagCommand(uchar command, const char *name, uchar scope)
320 {
321 int dummy;
322 uchar *replydummy, cmd[3];
323 int tries;
324
325 cmd[0] = scope;
326 cmd[1] = command;
327 cmd[2] = 0;
328
329 // Send command until we get an OK response
330 for (tries = 0; tries < 10; tries++)
331 {
332 if (sendJtagCommand(cmd, 3, name, replydummy, dummy)) {
333 if (replydummy == NULL)
334 throw jtag_io_exception();
335 if (dummy < 3)
336 throw jtag_exception("Unexpected response size in doSimpleJtagCommand");
337 if (replydummy[1] != RSP3_OK)
338 {
339 if (replydummy[1] < RSP3_FAILED)
340 throw jtag_exception("Unexpected positive reply in doSimpleJtagCommand");
341 else
342 throw jtag_io_exception(dummy >= 4? replydummy[3]: 0);
343 }
344 delete [] replydummy;
345 return;
346 }
347 }
348 throw jtag_exception("doSimpleJtagCommand(): too many failures");
349 }
350
351 void jtag3::changeBitRate(int newBitRate __attribute__((unused)))
352 {
353 throw;
354 }
355
356 bool jtag3::synchroniseAt(int bitrate __attribute__((unused)))
357 {
358 throw;
359 }
360
361 void jtag3::setDeviceDescriptor(jtag_device_def_type *dev)
362 {
363 uchar *param, paramsize;
364 jtag3_device_desc_type d3;
365
366 if (is_xmega)
367 {
368 param = (uchar *)&dev->dev_desc3 + 4;
369 paramsize = sizeof dev->dev_desc3 - 4;
370
371 appsize = b4_to_u32(dev->dev_desc3.app_size);
372 }
373 else
374 {
375 param = (uchar *)&d3;
376 paramsize = sizeof d3;
377 memset(&d3, 0, sizeof d3);
378
379 // Copy over all the data that can be derived from the existing
380 // JTAG ICE mkII device descriptor.
381 memcpy(d3.flash_page_size, dev->dev_desc2.uiFlashPageSize, 2);
382 memcpy(d3.flash_size, dev->dev_desc2.ulFlashSize, 4);
383 memcpy(d3.boot_address, dev->dev_desc2.ulBootAddress, 4);
384 memcpy(d3.sram_offset, dev->dev_desc2.uiSramStartAddr, 2);
385
386 unsigned int eesize = dev->eeprom_page_size * dev->eeprom_page_count;
387 d3.eeprom_size[0] = eesize & 0xff;
388 d3.eeprom_size[1] = (eesize >> 8) & 0xff;
389 d3.eeprom_page_size = dev->eeprom_page_size;
390 d3.always_one = 1;
391 d3.allow_full_page_bitstream = dev->dev_desc2.ucAllowFullPageBitstream;
392 d3.idr_address = dev->dev_desc2.ucIDRAddress;
393 d3.eearh_address = dev->dev_desc2.EECRAddress[0] + 3;
394 d3.eearl_address = dev->dev_desc2.EECRAddress[0] + 2;
395 d3.eecr_address = dev->dev_desc2.EECRAddress[0];
396 d3.eedr_address = dev->dev_desc2.EECRAddress[0] + 1;
397 d3.spmcr_address = dev->dev_desc2.ucSPMCRAddress;
398
399 // These data have to be recorded separately.
400 d3.osccal_address = dev->osccal - 0x20;
401 d3.ocd_revision = dev->ocdrev;
402 }
403
404 try
405 {
406 setJtagParameter(SCOPE_AVR, 2, PARM3_DEVICEDESC, param, paramsize);
407 }
408 catch (jtag_exception& e)
409 {
410 fprintf(stderr, "JTAG ICE: Failed to set device description: %s\n",
411 e.what());
412 throw;
413 }
414 }
415
416 void jtag3::startJtagLink(void)
417 {
418 doSimpleJtagCommand(CMD3_SIGN_ON, "sign-on", SCOPE_GENERAL);
419
420 signedIn = true;
421
422 uchar cmd[4], *resp;
423 int respsize;
424
425 cmd[0] = SCOPE_INFO;
426 cmd[1] = CMD3_GET_INFO;
427 cmd[2] = 0;
428 cmd[3] = CMD3_INFO_SERIAL;
429
430 doJtagCommand(cmd, 4, "get info (serial number)", resp, respsize);
431
432 if (resp[1] != RSP3_INFO)
433 debugOut("Unexpected positive response to get info: 0x%02x\n",
434 resp[1]);
435 else if (respsize < 4)
436 debugOut("Unexpected response size to get info: %d\n", respsize);
437 else
438 {
439 memmove(resp, resp + 3, respsize - 3);
440 resp[respsize - 3] = 0;
441 statusOut("Found a device, serial number: %s\n", resp);
442 }
443 delete [] resp;
444
445 getJtagParameter(SCOPE_GENERAL, 0, PARM3_HW_VER, 5, resp);
446
447 debugOut("ICE hardware version: %d\n", resp[3]);
448 debugOut("ICE firmware version: %d.%02d (rel. %d)\n",
449 resp[4], resp[5], (resp[6] | (resp[7] << 8)));
450
451 delete[] resp;
452
453 uchar paramdata[1];
454
455 if (is_xmega)
456 paramdata[0] = PARM3_ARCH_XMEGA;
457 else if (proto == PROTO_DW)
458 paramdata[0] = PARM3_ARCH_TINY;
459 else
460 paramdata[0] = PARM3_ARCH_MEGA;
461 setJtagParameter(SCOPE_AVR, 0, PARM3_ARCH, paramdata, 1);
462
463 paramdata[0] = PARM3_SESS_DEBUGGING;
464 setJtagParameter(SCOPE_AVR, 0, PARM3_SESS_PURPOSE, paramdata, 1);
465
466 switch (proto)
467 {
468 case PROTO_JTAG:
469 paramdata[0] = PARM3_CONN_JTAG;
470 break;
471
472 case PROTO_DW:
473 paramdata[0] = PARM3_CONN_DW;
474 softbp_only = true;
475 break;
476
477 case PROTO_PDI:
478 paramdata[0] = PARM3_CONN_PDI;
479 break;
480 }
481 setJtagParameter(SCOPE_AVR, 1, PARM3_CONNECTION, paramdata, 1);
482
483 if (proto == PROTO_JTAG)
484 configDaisyChain();
485
486 cmd[0] = SCOPE_AVR;
487 cmd[1] = CMD3_SIGN_ON;
488 cmd[2] = 0;
489 cmd[3] = proto == PROTO_JTAG && apply_nSRST;
490
491 doJtagCommand(cmd, 4, "AVR sign-on", resp, respsize);
492
493 if (resp[1] == RSP3_DATA && respsize >= 6)
494 {
495 unsigned int did = resp[3] | (resp[4] << 8) | (resp[5] << 16) | resp[6] << 24;
496 delete [] resp;
497
498 if (proto == PROTO_JTAG)
499 {
500 debugOut("AVR sign-on responded with device ID = 0x%0X : Ver = 0x%0x : Device = 0x%0x : Manuf = 0x%0x\n",
501 did,
502 (did & 0xF0000000) >> 28,
503 (did & 0x0FFFF000) >> 12,
504 (did & 0x00000FFE) >> 1);
505
506 device_id = (did & 0x0FFFF000) >> 12;
507 }
508 else // debugWIRE
509 {
510 debugOut("AVR sign-on responded with device ID = 0x%0X\n", did);
511 device_id = did;
512 }
513 }
514 else
515 {
516 delete [] resp;
517
518 /* Read in the JTAG device ID to determine device */
519 uchar cmd[] = { SCOPE_AVR, CMD3_DEVICE_ID, 0 };
520 try
521 {
522 doJtagCommand(cmd, sizeof cmd, "device ID", resp, respsize);
523
524 unsigned int did = resp[3] | (resp[4] << 8) | (resp[5] << 16) | resp[6] << 24;
525 delete [] resp;
526
527 debugOut("Device ID = 0x%0X : Ver = 0x%0x : Device = 0x%0x : Manuf = 0x%0x\n",
528 did,
529 (did & 0xF0000000) >> 28,
530 (did & 0x0FFFF000) >> 12,
531 (did & 0x00000FFE) >> 1);
532
533 device_id = (did & 0x0FFFF000) >> 12;
534 }
535 catch (jtag_exception&)
536 {
537 // ignore
538 }
539 }
540
541 debug_active = true;
542 }
543
544 /** Device automatic configuration
545 Determines the device being controlled by the JTAG ICE and configures
546 the system accordingly.
547
548 May be overridden by command line parameter.
549
550 */
551 void jtag3::deviceAutoConfig(void)
552 {
553 uchar *resp;
554 jtag_device_def_type *pDevice = deviceDefinitions;
555
556 // Auto config
557 debugOut("Automatic device detection: ");
558
559 if (device_id == 0)
560 {
561 /* Read in the JTAG device ID to determine device */
562
563 if (is_xmega)
564 {
565 /*
566 * Unfortunately, for Xmega devices, there's a
567 * chicken-and-egg problem here. Xmega devices connected
568 * through JTAG should already have responded with a device
569 * ID above, but those connected through PDI didn't, so the
570 * last resort is to read the respective signature memory
571 * area. However, in order to do this, the JTAGICE3 needs a
572 * valid device descriptor already. :-(
573 *
574 * Hopefully, the values below will remain constant for all
575 * Xmega devices ...
576 */
577 jtag_device_def_type desc = { "dummy", 0,
578 0, 0, 0, 0, 0, DEVFL_NONE,
579 nullptr, true, 0, 0, 0, 0,
580 {}, {}, {} };
581
582 u32_to_b4(desc.dev_desc3.nvm_data_offset, 0x1000000);
583 u16_to_b2(desc.dev_desc3.mcu_base_addr, 0x90);
584 setDeviceDescriptor(&desc);
585 }
586
587 resp = jtagRead(SIG_SPACE_ADDR_OFFSET, 3);
588 device_id = resp[2] | (resp[1] << 8);
589 delete [] resp;
590 }
591
592 statusOut("Reported device ID: 0x%0X\n", device_id);
593
594 if (device_name == 0)
595 {
596 while (pDevice->name)
597 {
598 if (pDevice->device_id == device_id)
599 break;
600
601 pDevice++;
602 }
603 if (pDevice->name == 0)
604 {
605 unknownDevice(device_id);
606 throw jtag_exception();
607 }
608 }
609 else
610 {
611 debugOut("Looking for device: %s\n", device_name);
612
613 while (pDevice->name)
614 {
615 if (strcasecmp(pDevice->name, device_name) == 0)
616 break;
617
618 pDevice++;
619 }
620 if (pDevice->name == 0)
621 {
622 unknownDevice(device_id, false);
623 throw jtag_exception();
624 }
625 }
626
627 if (device_name)
628 {
629 if (device_id != pDevice->device_id)
630 {
631 statusOut("Configured for device ID: 0x%0X %s -- FORCED with %s\n",
632 pDevice->device_id, pDevice->name, device_name);
633 }
634 else
635 {
636 statusOut("Configured for device ID: 0x%0X %s -- Matched with "
637 "%s\n", pDevice->device_id, pDevice->name, device_name);
638 }
639 }
640 else
641 {
642 statusOut("Configured for device ID: 0x%0X %s\n",
643 pDevice->device_id, pDevice->name);
644 }
645
646 device_name = (char*)pDevice->name;
647
648 deviceDef = pDevice;
649
650 setDeviceDescriptor(pDevice);
651 }
652
653
654 void jtag3::initJtagBox(void)
655 {
656 statusOut("JTAG config starting.\n");
657
658 if (device_name != 0)
659 {
660 jtag_device_def_type *pDevice = deviceDefinitions;
661
662 while (pDevice->name)
663 {
664 if (strcasecmp(pDevice->name, device_name) == 0)
665 break;
666
667 pDevice++;
668 }
669
670 if (pDevice->name != 0)
671 {
672 // If a device name has been specified on the command-line,
673 // this overrides the is_xmega setting.
674 is_xmega = pDevice->is_xmega;
675 }
676 }
677
678 try
679 {
680 startJtagLink();
681
682 //interruptProgram();
683
684 deviceAutoConfig();
685
686 // Clear out the breakpoints.
687 deleteAllBreakpoints();
688
689 statusOut("JTAG config complete.\n");
690 }
691 catch (jtag_exception& e)
692 {
693 fprintf(stderr, "initJtagBox() failed: %s\n",
694 e.what());
695 throw;
696 }
697 }
698
699
700 void jtag3::initJtagOnChipDebugging(unsigned long bitrate)
701 {
702 statusOut("Preparing the target device for On Chip Debugging.\n");
703
704 bitrate /= 1000; // JTAGICE3 always uses kHz
705
706 uchar value[2];
707 value[0] = bitrate & 0xff;
708 value[1] = (bitrate >> 8) & 0xff;
709
710 uchar param = 0;
711 if (proto == PROTO_JTAG)
712 {
713 if (is_xmega)
714 param = PARM3_CLK_XMEGA_JTAG;
715 else
716 param = PARM3_CLK_MEGA_DEBUG;
717 }
718 else if (proto == PROTO_PDI)
719 {
720 // trying to set the PDI clock doesn't work here
721 // param = PARM3_CLK_XMEGA_PDI;
722 }
723 if (param != 0)
724 {
725 setJtagParameter(SCOPE_AVR, 1, param, value, 2);
726 }
727
728 // Ensure on-chip debug enable fuse is enabled ie '0'
729 jtagActivateOcdenFuse();
730
731 uchar timers = 0; // stopped
732 setJtagParameter(SCOPE_AVR, 3, PARM3_TIMERS_RUNNING, &timers, 1);
733
734 if (proto == PROTO_DW || is_xmega)
735 {
736 uchar cmd[] = { SCOPE_AVR, CMD3_START_DEBUG, 0, 1 };
737 uchar *resp;
738 int respsize;
739
740 doJtagCommand(cmd, sizeof cmd, "start debugging", resp, respsize);
741 delete [] resp;
742 }
743
744 // Sometimes (like, after just enabling the OCDEN fuse), the first
745 // resetProgram() runs into an error code 0x32. Just retry it once.
746 try
747 {
748 resetProgram();
749 }
750 catch (jtag_exception &e)
751 {
752 debugOut("retrying reset ...\n");
753 resetProgram();
754 }
755
756 cached_pc_is_valid = false;
757 }
758
759 void jtag3::configDaisyChain(void)
760 {
761 unsigned char buf[4];
762
763 if ((dchain.units_before > 0) ||
764 (dchain.units_after > 0) ||
765 (dchain.bits_before > 0) ||
766 (dchain.bits_after > 0) ){
767 buf[0] = dchain.units_before;
768 buf[1] = dchain.units_after;
769 buf[2] = dchain.bits_before;
770 buf[3] = dchain.bits_after;
771 setJtagParameter(SCOPE_AVR, 1, PARM3_JTAGCHAIN, buf, 4);
772 }
773 }