1 /*
2  * avrdude - A Downloader/Uploader for AVR device programmers
3  * Copyright (C) 2000-2004  Brian S. Dean <bsd@bsdhome.com>
4  * Copyright (C) 2011 Darell Tan <darell.tan@gmail.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 /* $Id: avr.c 1340 2014-11-14 10:22:52Z rliebscher $ */
21 
22 #include "ac_cfg.h"
23 
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <sys/time.h>
29 #include <time.h>
30 
31 #include "avrdude.h"
32 #include "libavrdude.h"
33 
34 #include "tpi.h"
35 
36 FP_UpdateProgress update_progress;
37 
38 #define DEBUG 0
39 
40 /* TPI: returns 1 if NVM controller busy, 0 if free */
avr_tpi_poll_nvmbsy(PROGRAMMER * pgm)41 int avr_tpi_poll_nvmbsy(PROGRAMMER *pgm)
42 {
43   unsigned char cmd;
44   unsigned char res;
45 
46   cmd = TPI_CMD_SIN | TPI_SIO_ADDR(TPI_IOREG_NVMCSR);
47   (void)pgm->cmd_tpi(pgm, &cmd, 1, &res, 1);
48   return (res & TPI_IOREG_NVMCSR_NVMBSY);
49 }
50 
51 /* TPI chip erase sequence */
avr_tpi_chip_erase(PROGRAMMER * pgm,AVRPART * p)52 int avr_tpi_chip_erase(PROGRAMMER * pgm, AVRPART * p)
53 {
54 	int err;
55   AVRMEM *mem;
56 
57   if (p->flags & AVRPART_HAS_TPI) {
58     pgm->pgm_led(pgm, ON);
59 
60     /* Set Pointer Register */
61     mem = avr_locate_mem(p, "flash");
62     if (mem == NULL) {
63       avrdude_message(MSG_INFO, "No flash memory to erase for part %s\n",
64           p->desc);
65       return -1;
66     }
67 
68 		unsigned char cmd[] = {
69 			/* write pointer register high byte */
70 			(TPI_CMD_SSTPR | 0),
71 			((mem->offset & 0xFF) | 1),
72 			/* and low byte */
73 			(TPI_CMD_SSTPR | 1),
74 			((mem->offset >> 8) & 0xFF),
75 	    /* write CHIP_ERASE command to NVMCMD register */
76 			(TPI_CMD_SOUT | TPI_SIO_ADDR(TPI_IOREG_NVMCMD)),
77 			TPI_NVMCMD_CHIP_ERASE,
78 			/* write dummy value to start erase */
79 			TPI_CMD_SST,
80 			0xFF
81 		};
82 
83     while (avr_tpi_poll_nvmbsy(pgm));
84 
85 		err = pgm->cmd_tpi(pgm, cmd, sizeof(cmd), NULL, 0);
86 		if(err)
87 			return err;
88 
89     while (avr_tpi_poll_nvmbsy(pgm));
90 
91     pgm->pgm_led(pgm, OFF);
92 
93     return 0;
94   } else {
95 		avrdude_message(MSG_INFO, "%s called for a part that has no TPI\n", __func__);
96 		return -1;
97 	}
98 }
99 
100 /* TPI program enable sequence */
avr_tpi_program_enable(PROGRAMMER * pgm,AVRPART * p,unsigned char guard_time)101 int avr_tpi_program_enable(PROGRAMMER * pgm, AVRPART * p, unsigned char guard_time)
102 {
103 	int err, retry;
104 	unsigned char cmd[2];
105 	unsigned char response;
106 
107 	if(p->flags & AVRPART_HAS_TPI) {
108 		/* set guard time */
109 		cmd[0] = (TPI_CMD_SSTCS | TPI_REG_TPIPCR);
110 		cmd[1] = guard_time;
111 
112 		err = pgm->cmd_tpi(pgm, cmd, sizeof(cmd), NULL, 0);
113     if(err)
114 			return err;
115 
116 		/* read TPI ident reg */
117     cmd[0] = (TPI_CMD_SLDCS | TPI_REG_TPIIR);
118 		err = pgm->cmd_tpi(pgm, cmd, 1, &response, sizeof(response));
119     if (err || response != TPI_IDENT_CODE) {
120       avrdude_message(MSG_INFO, "TPIIR not correct\n");
121       return -1;
122     }
123 
124 		/* send SKEY command + SKEY */
125 		err = pgm->cmd_tpi(pgm, tpi_skey_cmd, sizeof(tpi_skey_cmd), NULL, 0);
126 		if(err)
127 			return err;
128 
129 		/* check if device is ready */
130 		for(retry = 0; retry < 10; retry++)
131 		{
132 			cmd[0] =  (TPI_CMD_SLDCS | TPI_REG_TPISR);
133 			err = pgm->cmd_tpi(pgm, cmd, 1, &response, sizeof(response));
134 			if(err || !(response & TPI_REG_TPISR_NVMEN))
135 				continue;
136 
137 			return 0;
138 		}
139 
140 		avrdude_message(MSG_INFO, "Error enabling TPI external programming mode:");
141 		avrdude_message(MSG_INFO, "Target does not reply\n");
142 		return -1;
143 
144 	} else {
145 		avrdude_message(MSG_INFO, "%s called for a part that has no TPI\n", __func__);
146 		return -1;
147 	}
148 }
149 
150 /* TPI: setup NVMCMD register and pointer register (PR) for read/write/erase */
avr_tpi_setup_rw(PROGRAMMER * pgm,AVRMEM * mem,unsigned long addr,unsigned char nvmcmd)151 static int avr_tpi_setup_rw(PROGRAMMER * pgm, AVRMEM * mem,
152 			    unsigned long addr, unsigned char nvmcmd)
153 {
154   unsigned char cmd[4];
155   int rc;
156 
157   /* set NVMCMD register */
158   cmd[0] = TPI_CMD_SOUT | TPI_SIO_ADDR(TPI_IOREG_NVMCMD);
159   cmd[1] = nvmcmd;
160   rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
161   if (rc == -1)
162     return -1;
163 
164   /* set Pointer Register (PR) */
165   cmd[0] = TPI_CMD_SSTPR | 0;
166   cmd[1] = (mem->offset + addr) & 0xFF;
167   rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
168   if (rc == -1)
169     return -1;
170 
171   cmd[0] = TPI_CMD_SSTPR | 1;
172   cmd[1] = ((mem->offset + addr) >> 8) & 0xFF;
173   rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
174   if (rc == -1)
175     return -1;
176 
177   return 0;
178 }
179 
avr_read_byte_default(PROGRAMMER * pgm,AVRPART * p,AVRMEM * mem,unsigned long addr,unsigned char * value)180 int avr_read_byte_default(PROGRAMMER * pgm, AVRPART * p, AVRMEM * mem,
181                           unsigned long addr, unsigned char * value)
182 {
183   unsigned char cmd[4];
184   unsigned char res[4];
185   unsigned char data;
186   int r;
187   OPCODE * readop, * lext;
188 
189   if (pgm->cmd == NULL) {
190     avrdude_message(MSG_INFO, "%s: Error: %s programmer uses avr_read_byte_default() but does not\n"
191                     "provide a cmd() method.\n",
192                     progname, pgm->type);
193     return -1;
194   }
195 
196   pgm->pgm_led(pgm, ON);
197   pgm->err_led(pgm, OFF);
198 
199   if (p->flags & AVRPART_HAS_TPI) {
200     if (pgm->cmd_tpi == NULL) {
201       avrdude_message(MSG_INFO, "%s: Error: %s programmer does not support TPI\n",
202           progname, pgm->type);
203       return -1;
204     }
205 
206     while (avr_tpi_poll_nvmbsy(pgm));
207 
208     /* setup for read */
209     avr_tpi_setup_rw(pgm, mem, addr, TPI_NVMCMD_NO_OPERATION);
210 
211     /* load byte */
212     cmd[0] = TPI_CMD_SLD;
213     r = pgm->cmd_tpi(pgm, cmd, 1, value, 1);
214     if (r == -1)
215       return -1;
216 
217     return 0;
218   }
219 
220   /*
221    * figure out what opcode to use
222    */
223   if (mem->op[AVR_OP_READ_LO]) {
224     if (addr & 0x00000001)
225       readop = mem->op[AVR_OP_READ_HI];
226     else
227       readop = mem->op[AVR_OP_READ_LO];
228     addr = addr / 2;
229   }
230   else {
231     readop = mem->op[AVR_OP_READ];
232   }
233 
234   if (readop == NULL) {
235 #if DEBUG
236     avrdude_message(MSG_INFO, "avr_read_byte(): operation not supported on memory type \"%s\"\n",
237                     mem->desc);
238 #endif
239     return -1;
240   }
241 
242   /*
243    * If this device has a "load extended address" command, issue it.
244    */
245   lext = mem->op[AVR_OP_LOAD_EXT_ADDR];
246   if (lext != NULL) {
247     memset(cmd, 0, sizeof(cmd));
248 
249     avr_set_bits(lext, cmd);
250     avr_set_addr(lext, cmd, addr);
251     r = pgm->cmd(pgm, cmd, res);
252     if (r < 0)
253       return r;
254   }
255 
256   memset(cmd, 0, sizeof(cmd));
257 
258   avr_set_bits(readop, cmd);
259   avr_set_addr(readop, cmd, addr);
260   r = pgm->cmd(pgm, cmd, res);
261   if (r < 0)
262     return r;
263   data = 0;
264   avr_get_output(readop, res, &data);
265 
266   pgm->pgm_led(pgm, OFF);
267 
268   *value = data;
269 
270   return 0;
271 }
272 
273 
274 /*
275  * Return the number of "interesting" bytes in a memory buffer,
276  * "interesting" being defined as up to the last non-0xff data
277  * value. This is useful for determining where to stop when dealing
278  * with "flash" memory, since writing 0xff to flash is typically a
279  * no-op. Always return an even number since flash is word addressed.
280  */
avr_mem_hiaddr(AVRMEM * mem)281 int avr_mem_hiaddr(AVRMEM * mem)
282 {
283   int i, n;
284 
285   /* return the highest non-0xff address regardless of how much
286      memory was read */
287   for (i=mem->size-1; i>0; i--) {
288     if (mem->buf[i] != 0xff) {
289       n = i+1;
290       if (n & 0x01)
291         return n+1;
292       else
293         return n;
294     }
295   }
296 
297   return 0;
298 }
299 
300 
301 /*
302  * Read the entirety of the specified memory type into the
303  * corresponding buffer of the avrpart pointed to by 'p'.
304  * If v is non-NULL, verify against v's memory area, only
305  * those cells that are tagged TAG_ALLOCATED are verified.
306  *
307  * Return the number of bytes read, or < 0 if an error occurs.
308  */
avr_read(PROGRAMMER * pgm,AVRPART * p,char * memtype,AVRPART * v)309 int avr_read(PROGRAMMER * pgm, AVRPART * p, char * memtype,
310              AVRPART * v)
311 {
312   unsigned long    i, lastaddr;
313   unsigned char    cmd[4];
314   AVRMEM * mem, * vmem = NULL;
315   int rc;
316 
317   mem = avr_locate_mem(p, memtype);
318   if (v != NULL)
319       vmem = avr_locate_mem(v, memtype);
320   if (mem == NULL) {
321     avrdude_message(MSG_INFO, "No \"%s\" memory for part %s\n",
322             memtype, p->desc);
323     return -1;
324   }
325 
326   /*
327    * start with all 0xff
328    */
329   memset(mem->buf, 0xff, mem->size);
330 
331   /* supports "paged load" thru post-increment */
332   if ((p->flags & AVRPART_HAS_TPI) && mem->page_size != 0 &&
333       pgm->cmd_tpi != NULL) {
334 
335     while (avr_tpi_poll_nvmbsy(pgm));
336 
337     /* setup for read (NOOP) */
338     avr_tpi_setup_rw(pgm, mem, 0, TPI_NVMCMD_NO_OPERATION);
339 
340     /* load bytes */
341     for (lastaddr = i = 0; i < mem->size; i++) {
342       if (vmem == NULL ||
343           (vmem->tags[i] & TAG_ALLOCATED) != 0)
344       {
345         if (lastaddr != i) {
346           /* need to setup new address */
347           avr_tpi_setup_rw(pgm, mem, i, TPI_NVMCMD_NO_OPERATION);
348           lastaddr = i;
349         }
350         cmd[0] = TPI_CMD_SLD_PI;
351         rc = pgm->cmd_tpi(pgm, cmd, 1, mem->buf + i, 1);
352         lastaddr++;
353         if (rc == -1) {
354           avrdude_message(MSG_INFO, "avr_read(): error reading address 0x%04lx\n", i);
355           return -1;
356         }
357       }
358       report_progress(i, mem->size, NULL);
359     }
360     return avr_mem_hiaddr(mem);
361   }
362 
363   if (pgm->paged_load != NULL && mem->page_size != 0) {
364     /*
365      * the programmer supports a paged mode read
366      */
367     int need_read, failure;
368     unsigned int pageaddr;
369     unsigned int npages, nread;
370 
371     /* quickly scan number of pages to be written to first */
372     for (pageaddr = 0, npages = 0;
373          pageaddr < mem->size;
374          pageaddr += mem->page_size) {
375       /* check whether this page must be read */
376       for (i = pageaddr;
377            i < pageaddr + mem->page_size;
378            i++)
379         if (vmem == NULL /* no verify, read everything */ ||
380             (mem->tags[i] & TAG_ALLOCATED) != 0 /* verify, do only
381                                                     read pages that
382                                                     are needed in
383                                                     input file */) {
384           npages++;
385           break;
386         }
387     }
388 
389     for (pageaddr = 0, failure = 0, nread = 0;
390          !failure && pageaddr < mem->size;
391          pageaddr += mem->page_size) {
392       /* check whether this page must be read */
393       for (i = pageaddr, need_read = 0;
394            i < pageaddr + mem->page_size;
395            i++)
396         if (vmem == NULL /* no verify, read everything */ ||
397             (vmem->tags[i] & TAG_ALLOCATED) != 0 /* verify, do only
398                                                     read pages that
399                                                     are needed in
400                                                     input file */) {
401           need_read = 1;
402           break;
403         }
404       if (need_read) {
405         rc = pgm->paged_load(pgm, p, mem, mem->page_size,
406                             pageaddr, mem->page_size);
407         if (rc < 0)
408           /* paged load failed, fall back to byte-at-a-time read below */
409           failure = 1;
410       } else {
411         avrdude_message(MSG_DEBUG, "%s: avr_read(): skipping page %u: no interesting data\n",
412                         progname, pageaddr / mem->page_size);
413       }
414       nread++;
415       report_progress(nread, npages, NULL);
416     }
417     if (!failure) {
418       if (strcasecmp(mem->desc, "flash") == 0 ||
419           strcasecmp(mem->desc, "application") == 0 ||
420           strcasecmp(mem->desc, "apptable") == 0 ||
421           strcasecmp(mem->desc, "boot") == 0)
422         return avr_mem_hiaddr(mem);
423       else
424         return mem->size;
425     }
426     /* else: fall back to byte-at-a-time write, for historical reasons */
427   }
428 
429   if (strcmp(mem->desc, "signature") == 0) {
430     if (pgm->read_sig_bytes) {
431       return pgm->read_sig_bytes(pgm, p, mem);
432     }
433   }
434 
435   for (i=0; i < mem->size; i++) {
436     if (vmem == NULL ||
437 	(vmem->tags[i] & TAG_ALLOCATED) != 0)
438     {
439       rc = pgm->read_byte(pgm, p, mem, i, mem->buf + i);
440       if (rc != 0) {
441 	avrdude_message(MSG_INFO, "avr_read(): error reading address 0x%04lx\n", i);
442 	if (rc == -1)
443 	  avrdude_message(MSG_INFO, "    read operation not supported for memory \"%s\"\n",
444                           memtype);
445 	return -2;
446       }
447     }
448     report_progress(i, mem->size, NULL);
449   }
450 
451   if (strcasecmp(mem->desc, "flash") == 0 ||
452       strcasecmp(mem->desc, "application") == 0 ||
453       strcasecmp(mem->desc, "apptable") == 0 ||
454       strcasecmp(mem->desc, "boot") == 0)
455     return avr_mem_hiaddr(mem);
456   else
457     return i;
458 }
459 
460 
461 /*
462  * write a page data at the specified address
463  */
avr_write_page(PROGRAMMER * pgm,AVRPART * p,AVRMEM * mem,unsigned long addr)464 int avr_write_page(PROGRAMMER * pgm, AVRPART * p, AVRMEM * mem,
465                    unsigned long addr)
466 {
467   unsigned char cmd[4];
468   unsigned char res[4];
469   OPCODE * wp, * lext;
470 
471   if (pgm->cmd == NULL) {
472     avrdude_message(MSG_INFO, "%s: Error: %s programmer uses avr_write_page() but does not\n"
473                     "provide a cmd() method.\n",
474                     progname, pgm->type);
475     return -1;
476   }
477 
478   wp = mem->op[AVR_OP_WRITEPAGE];
479   if (wp == NULL) {
480     avrdude_message(MSG_INFO, "avr_write_page(): memory \"%s\" not configured for page writes\n",
481                     mem->desc);
482     return -1;
483   }
484 
485   /*
486    * if this memory is word-addressable, adjust the address
487    * accordingly
488    */
489   if ((mem->op[AVR_OP_LOADPAGE_LO]) || (mem->op[AVR_OP_READ_LO]))
490     addr = addr / 2;
491 
492   pgm->pgm_led(pgm, ON);
493   pgm->err_led(pgm, OFF);
494 
495   /*
496    * If this device has a "load extended address" command, issue it.
497    */
498   lext = mem->op[AVR_OP_LOAD_EXT_ADDR];
499   if (lext != NULL) {
500     memset(cmd, 0, sizeof(cmd));
501 
502     avr_set_bits(lext, cmd);
503     avr_set_addr(lext, cmd, addr);
504     pgm->cmd(pgm, cmd, res);
505   }
506 
507   memset(cmd, 0, sizeof(cmd));
508 
509   avr_set_bits(wp, cmd);
510   avr_set_addr(wp, cmd, addr);
511   pgm->cmd(pgm, cmd, res);
512 
513   /*
514    * since we don't know what voltage the target AVR is powered by, be
515    * conservative and delay the max amount the spec says to wait
516    */
517   usleep(mem->max_write_delay);
518 
519   pgm->pgm_led(pgm, OFF);
520   return 0;
521 }
522 
523 
avr_write_byte_default(PROGRAMMER * pgm,AVRPART * p,AVRMEM * mem,unsigned long addr,unsigned char data)524 int avr_write_byte_default(PROGRAMMER * pgm, AVRPART * p, AVRMEM * mem,
525                    unsigned long addr, unsigned char data)
526 {
527   unsigned char cmd[4];
528   unsigned char res[4];
529   unsigned char r;
530   int ready;
531   int tries;
532   unsigned long start_time;
533   unsigned long prog_time;
534   unsigned char b;
535   unsigned short caddr;
536   OPCODE * writeop;
537   int rc;
538   int readok=0;
539   struct timeval tv;
540 
541   if (pgm->cmd == NULL) {
542     avrdude_message(MSG_INFO, "%s: Error: %s programmer uses avr_write_byte_default() but does not\n"
543                     "provide a cmd() method.\n",
544                     progname, pgm->type);
545     return -1;
546   }
547 
548   if (p->flags & AVRPART_HAS_TPI) {
549     if (pgm->cmd_tpi == NULL) {
550       avrdude_message(MSG_INFO, "%s: Error: %s programmer does not support TPI\n",
551           progname, pgm->type);
552       return -1;
553     }
554 
555     if (strcmp(mem->desc, "flash") == 0) {
556       avrdude_message(MSG_INFO, "Writing a byte to flash is not supported for %s\n", p->desc);
557       return -1;
558     } else if ((mem->offset + addr) & 1) {
559       avrdude_message(MSG_INFO, "Writing a byte to an odd location is not supported for %s\n", p->desc);
560       return -1;
561     }
562 
563     while (avr_tpi_poll_nvmbsy(pgm));
564 
565     /* must erase fuse first */
566     if (strcmp(mem->desc, "fuse") == 0) {
567       /* setup for SECTION_ERASE (high byte) */
568       avr_tpi_setup_rw(pgm, mem, addr | 1, TPI_NVMCMD_SECTION_ERASE);
569 
570       /* write dummy byte */
571       cmd[0] = TPI_CMD_SST;
572       cmd[1] = 0xFF;
573       rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
574 
575       while (avr_tpi_poll_nvmbsy(pgm));
576     }
577 
578     /* setup for WORD_WRITE */
579     avr_tpi_setup_rw(pgm, mem, addr, TPI_NVMCMD_WORD_WRITE);
580 
581     cmd[0] = TPI_CMD_SST_PI;
582     cmd[1] = data;
583     rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
584     /* dummy high byte to start WORD_WRITE */
585     cmd[0] = TPI_CMD_SST_PI;
586     cmd[1] = data;
587     rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
588 
589     while (avr_tpi_poll_nvmbsy(pgm));
590 
591     return 0;
592   }
593 
594   if (!mem->paged &&
595       (p->flags & AVRPART_IS_AT90S1200) == 0) {
596     /*
597      * check to see if the write is necessary by reading the existing
598      * value and only write if we are changing the value; we can't
599      * use this optimization for paged addressing.
600      *
601      * For mysterious reasons, on the AT90S1200, this read operation
602      * sometimes causes the high byte of the same word to be
603      * programmed to the value of the low byte that has just been
604      * programmed before.  Avoid that optimization on this device.
605      */
606     rc = pgm->read_byte(pgm, p, mem, addr, &b);
607     if (rc != 0) {
608       if (rc != -1) {
609         return -2;
610       }
611       /*
612        * the read operation is not support on this memory type
613        */
614     }
615     else {
616       readok = 1;
617       if (b == data) {
618         return 0;
619       }
620     }
621   }
622 
623   /*
624    * determine which memory opcode to use
625    */
626   if (mem->op[AVR_OP_WRITE_LO]) {
627     if (addr & 0x01)
628       writeop = mem->op[AVR_OP_WRITE_HI];
629     else
630       writeop = mem->op[AVR_OP_WRITE_LO];
631     caddr = addr / 2;
632   }
633   else if (mem->paged && mem->op[AVR_OP_LOADPAGE_LO]) {
634     if (addr & 0x01)
635       writeop = mem->op[AVR_OP_LOADPAGE_HI];
636     else
637       writeop = mem->op[AVR_OP_LOADPAGE_LO];
638     caddr = addr / 2;
639   }
640   else {
641     writeop = mem->op[AVR_OP_WRITE];
642     caddr = addr;
643   }
644 
645   if (writeop == NULL) {
646 #if DEBUG
647     avrdude_message(MSG_INFO, "avr_write_byte(): write not supported for memory type \"%s\"\n",
648                     mem->desc);
649 #endif
650     return -1;
651   }
652 
653 
654   pgm->pgm_led(pgm, ON);
655   pgm->err_led(pgm, OFF);
656 
657   memset(cmd, 0, sizeof(cmd));
658 
659   avr_set_bits(writeop, cmd);
660   avr_set_addr(writeop, cmd, caddr);
661   avr_set_input(writeop, cmd, data);
662   pgm->cmd(pgm, cmd, res);
663 
664   if (mem->paged) {
665     /*
666      * in paged addressing, single bytes to be written to the memory
667      * page complete immediately, we only need to delay when we commit
668      * the whole page via the avr_write_page() routine.
669      */
670     pgm->pgm_led(pgm, OFF);
671     return 0;
672   }
673 
674   if (readok == 0) {
675     /*
676      * read operation not supported for this memory type, just wait
677      * the max programming time and then return
678      */
679     usleep(mem->max_write_delay); /* maximum write delay */
680     pgm->pgm_led(pgm, OFF);
681     return 0;
682   }
683 
684   tries = 0;
685   ready = 0;
686   while (!ready) {
687 
688     if ((data == mem->readback[0]) ||
689         (data == mem->readback[1])) {
690       /*
691        * use an extra long delay when we happen to be writing values
692        * used for polled data read-back.  In this case, polling
693        * doesn't work, and we need to delay the worst case write time
694        * specified for the chip.
695        */
696       usleep(mem->max_write_delay);
697       rc = pgm->read_byte(pgm, p, mem, addr, &r);
698       if (rc != 0) {
699         pgm->pgm_led(pgm, OFF);
700         pgm->err_led(pgm, OFF);
701         return -5;
702       }
703     }
704     else {
705       gettimeofday (&tv, NULL);
706       start_time = (tv.tv_sec * 1000000) + tv.tv_usec;
707       do {
708         /*
709          * Do polling, but timeout after max_write_delay.
710 	 */
711         rc = pgm->read_byte(pgm, p, mem, addr, &r);
712         if (rc != 0) {
713           pgm->pgm_led(pgm, OFF);
714           pgm->err_led(pgm, ON);
715           return -4;
716         }
717         gettimeofday (&tv, NULL);
718         prog_time = (tv.tv_sec * 1000000) + tv.tv_usec;
719       } while ((r != data) &&
720                ((prog_time-start_time) < mem->max_write_delay));
721     }
722 
723     /*
724      * At this point we either have a valid readback or the
725      * max_write_delay is expired.
726      */
727 
728     if (r == data) {
729       ready = 1;
730     }
731     else if (mem->pwroff_after_write) {
732       /*
733        * The device has been flagged as power-off after write to this
734        * memory type.  The reason we don't just blindly follow the
735        * flag is that the power-off advice may only apply to some
736        * memory bits but not all.  We only actually power-off the
737        * device if the data read back does not match what we wrote.
738        */
739       pgm->pgm_led(pgm, OFF);
740       avrdude_message(MSG_INFO, "%s: this device must be powered off and back on to continue\n",
741                       progname);
742       if (pgm->pinno[PPI_AVR_VCC]) {
743         avrdude_message(MSG_INFO, "%s: attempting to do this now ...\n", progname);
744         pgm->powerdown(pgm);
745         usleep(250000);
746         rc = pgm->initialize(pgm, p);
747         if (rc < 0) {
748           avrdude_message(MSG_INFO, "%s: initialization failed, rc=%d\n", progname, rc);
749           avrdude_message(MSG_INFO, "%s: can't re-initialize device after programming the "
750                           "%s bits\n", progname, mem->desc);
751           avrdude_message(MSG_INFO, "%s: you must manually power-down the device and restart\n"
752                           "%s:   %s to continue.\n",
753                           progname, progname, progname);
754           return -3;
755         }
756 
757         avrdude_message(MSG_INFO, "%s: device was successfully re-initialized\n",
758                 progname);
759         return 0;
760       }
761     }
762 
763     tries++;
764     if (!ready && tries > 5) {
765       /*
766        * we wrote the data, but after waiting for what should have
767        * been plenty of time, the memory cell still doesn't match what
768        * we wrote.  Indicate a write error.
769        */
770       pgm->pgm_led(pgm, OFF);
771       pgm->err_led(pgm, ON);
772 
773       return -6;
774     }
775   }
776 
777   pgm->pgm_led(pgm, OFF);
778   return 0;
779 }
780 
781 
782 /*
783  * write a byte of data at the specified address
784  */
avr_write_byte(PROGRAMMER * pgm,AVRPART * p,AVRMEM * mem,unsigned long addr,unsigned char data)785 int avr_write_byte(PROGRAMMER * pgm, AVRPART * p, AVRMEM * mem,
786                    unsigned long addr, unsigned char data)
787 {
788 
789   unsigned char safemode_lfuse;
790   unsigned char safemode_hfuse;
791   unsigned char safemode_efuse;
792   unsigned char safemode_fuse;
793 
794   /* If we write the fuses, then we need to tell safemode that they *should* change */
795   safemode_memfuses(0, &safemode_lfuse, &safemode_hfuse, &safemode_efuse, &safemode_fuse);
796 
797   if (strcmp(mem->desc, "fuse")==0) {
798       safemode_fuse = data;
799   }
800   if (strcmp(mem->desc, "lfuse")==0) {
801       safemode_lfuse = data;
802   }
803   if (strcmp(mem->desc, "hfuse")==0) {
804       safemode_hfuse = data;
805   }
806   if (strcmp(mem->desc, "efuse")==0) {
807       safemode_efuse = data;
808   }
809 
810   safemode_memfuses(1, &safemode_lfuse, &safemode_hfuse, &safemode_efuse, &safemode_fuse);
811 
812   return pgm->write_byte(pgm, p, mem, addr, data);
813 }
814 
815 
816 /*
817  * Write the whole memory region of the specified memory from the
818  * corresponding buffer of the avrpart pointed to by 'p'.  Write up to
819  * 'size' bytes from the buffer.  Data is only written if the new data
820  * value is different from the existing data value.  Data beyond
821  * 'size' bytes is not affected.
822  *
823  * Return the number of bytes written, or -1 if an error occurs.
824  */
avr_write(PROGRAMMER * pgm,AVRPART * p,char * memtype,int size,int auto_erase)825 int avr_write(PROGRAMMER * pgm, AVRPART * p, char * memtype, int size,
826               int auto_erase)
827 {
828   int              rc;
829   int              newpage, page_tainted, flush_page, do_write;
830   int              wsize;
831   unsigned int     i, lastaddr;
832   unsigned char    data;
833   int              werror;
834   unsigned char    cmd[4];
835   AVRMEM         * m;
836 
837   m = avr_locate_mem(p, memtype);
838   if (m == NULL) {
839     avrdude_message(MSG_INFO, "No \"%s\" memory for part %s\n",
840             memtype, p->desc);
841     return -1;
842   }
843 
844   pgm->err_led(pgm, OFF);
845 
846   werror  = 0;
847 
848   wsize = m->size;
849   if (size < wsize) {
850     wsize = size;
851   }
852   else if (size > wsize) {
853     avrdude_message(MSG_INFO, "%s: WARNING: %d bytes requested, but memory region is only %d"
854                     "bytes\n"
855                     "%sOnly %d bytes will actually be written\n",
856                     progname, size, wsize,
857                     progbuf, wsize);
858   }
859 
860 
861   if ((p->flags & AVRPART_HAS_TPI) && m->page_size != 0 &&
862       pgm->cmd_tpi != NULL) {
863 
864     while (avr_tpi_poll_nvmbsy(pgm));
865 
866     /* setup for WORD_WRITE */
867     avr_tpi_setup_rw(pgm, m, 0, TPI_NVMCMD_WORD_WRITE);
868 
869     /* make sure it's aligned to a word boundary */
870     if (wsize & 0x1) {
871       wsize++;
872     }
873 
874     /* write words, low byte first */
875     for (lastaddr = i = 0; i < wsize; i += 2) {
876       if ((m->tags[i] & TAG_ALLOCATED) != 0 ||
877           (m->tags[i + 1] & TAG_ALLOCATED) != 0) {
878 
879         if (lastaddr != i) {
880           /* need to setup new address */
881           avr_tpi_setup_rw(pgm, m, i, TPI_NVMCMD_WORD_WRITE);
882           lastaddr = i;
883         }
884 
885         cmd[0] = TPI_CMD_SST_PI;
886         cmd[1] = m->buf[i];
887         rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
888 
889         cmd[1] = m->buf[i + 1];
890         rc = pgm->cmd_tpi(pgm, cmd, 2, NULL, 0);
891 
892         lastaddr += 2;
893 
894         while (avr_tpi_poll_nvmbsy(pgm));
895       }
896       report_progress(i, wsize, NULL);
897     }
898     return i;
899   }
900 
901   if (pgm->paged_write != NULL && m->page_size != 0) {
902     /*
903      * the programmer supports a paged mode write
904      */
905     int need_write, failure;
906     unsigned int pageaddr;
907     unsigned int npages, nwritten;
908 
909     /* quickly scan number of pages to be written to first */
910     for (pageaddr = 0, npages = 0;
911          pageaddr < wsize;
912          pageaddr += m->page_size) {
913       /* check whether this page must be written to */
914       for (i = pageaddr;
915            i < pageaddr + m->page_size;
916            i++)
917         if ((m->tags[i] & TAG_ALLOCATED) != 0) {
918           npages++;
919           break;
920         }
921     }
922 
923     for (pageaddr = 0, failure = 0, nwritten = 0;
924          !failure && pageaddr < wsize;
925          pageaddr += m->page_size) {
926       /* check whether this page must be written to */
927       for (i = pageaddr, need_write = 0;
928            i < pageaddr + m->page_size;
929            i++)
930         if ((m->tags[i] & TAG_ALLOCATED) != 0) {
931           need_write = 1;
932           break;
933         }
934       if (need_write) {
935         rc = 0;
936         if (auto_erase)
937           rc = pgm->page_erase(pgm, p, m, pageaddr);
938         if (rc >= 0)
939           rc = pgm->paged_write(pgm, p, m, m->page_size, pageaddr, m->page_size);
940         if (rc < 0)
941           /* paged write failed, fall back to byte-at-a-time write below */
942           failure = 1;
943       } else {
944         avrdude_message(MSG_DEBUG, "%s: avr_write(): skipping page %u: no interesting data\n",
945                         progname, pageaddr / m->page_size);
946       }
947       nwritten++;
948       report_progress(nwritten, npages, NULL);
949     }
950     if (!failure)
951       return wsize;
952     /* else: fall back to byte-at-a-time write, for historical reasons */
953   }
954 
955   if (pgm->write_setup) {
956       pgm->write_setup(pgm, p, m);
957   }
958 
959   newpage = 1;
960   page_tainted = 0;
961   flush_page = 0;
962 
963   for (i=0; i<wsize; i++) {
964     data = m->buf[i];
965     report_progress(i, wsize, NULL);
966 
967     /*
968      * Find out whether the write action must be invoked for this
969      * byte.
970      *
971      * For non-paged memory, this only happens if TAG_ALLOCATED is
972      * set for the byte.
973      *
974      * For paged memory, TAG_ALLOCATED also invokes the write
975      * operation, which is actually a page buffer fill only.  This
976      * "taints" the page, and upon encountering the last byte of each
977      * tainted page, the write operation must also be invoked in order
978      * to actually write the page buffer to memory.
979      */
980     do_write = (m->tags[i] & TAG_ALLOCATED) != 0;
981     if (m->paged) {
982       if (newpage) {
983         page_tainted = do_write;
984       } else {
985         page_tainted |= do_write;
986       }
987       if (i % m->page_size == m->page_size - 1 ||
988           i == wsize - 1) {
989         /* last byte this page */
990         flush_page = page_tainted;
991         newpage = 1;
992       } else {
993         flush_page = newpage = 0;
994       }
995     }
996 
997     if (!do_write && !flush_page) {
998       continue;
999     }
1000 
1001     if (do_write) {
1002       rc = avr_write_byte(pgm, p, m, i, data);
1003       if (rc) {
1004         avrdude_message(MSG_INFO, " ***failed;  ");
1005         avrdude_message(MSG_INFO, "\n");
1006         pgm->err_led(pgm, ON);
1007         werror = 1;
1008       }
1009     }
1010 
1011     /*
1012      * check to see if it is time to flush the page with a page
1013      * write
1014      */
1015     if (flush_page) {
1016       rc = avr_write_page(pgm, p, m, i);
1017       if (rc) {
1018         avrdude_message(MSG_INFO, " *** page %d (addresses 0x%04x - 0x%04x) failed "
1019                         "to write\n",
1020                         i % m->page_size,
1021                         i - m->page_size + 1, i);
1022         avrdude_message(MSG_INFO, "\n");
1023         pgm->err_led(pgm, ON);
1024           werror = 1;
1025       }
1026     }
1027 
1028     if (werror) {
1029       /*
1030        * make sure the error led stay on if there was a previous write
1031        * error, otherwise it gets cleared in avr_write_byte()
1032        */
1033       pgm->err_led(pgm, ON);
1034     }
1035   }
1036 
1037   return i;
1038 }
1039 
1040 
1041 
1042 /*
1043  * read the AVR device's signature bytes
1044  */
avr_signature(PROGRAMMER * pgm,AVRPART * p)1045 int avr_signature(PROGRAMMER * pgm, AVRPART * p)
1046 {
1047   int rc;
1048 
1049   report_progress (0,1,"Reading");
1050   rc = avr_read(pgm, p, "signature", 0);
1051   if (rc < 0) {
1052     avrdude_message(MSG_INFO, "%s: error reading signature data for part \"%s\", rc=%d\n",
1053                     progname, p->desc, rc);
1054     return -1;
1055   }
1056   report_progress (1,1,NULL);
1057 
1058   return 0;
1059 }
1060 
get_fuse_bitmask(AVRMEM * m)1061 uint8_t get_fuse_bitmask(AVRMEM * m) {
1062   uint8_t bitmask_r = 0;
1063   uint8_t bitmask_w = 0;
1064   int i, j;
1065 
1066   if (m->size > 1) {
1067     // not a fuse, compare bytes directly
1068     return 0xFF;
1069   }
1070 
1071   for (i=0; i<AVR_OP_MAX; i++) {
1072     if (m->op[i] && i == AVR_OP_READ) {
1073       for (j=7; j>=0; j--) {
1074         bitmask_r |= (m->op[i]->bit[j].type != AVR_CMDBIT_IGNORE) << j;
1075       }
1076     }
1077     if (m->op[i] && i == AVR_OP_WRITE) {
1078       for (j=7; j>=0; j--) {
1079         bitmask_w |= (m->op[i]->bit[j].type != AVR_CMDBIT_VALUE  &&
1080           m->op[i]->bit[j].type != AVR_CMDBIT_IGNORE) << j;
1081       }
1082     }
1083   }
1084   return bitmask_r & bitmask_w;
1085 }
1086 
compare_memory_masked(AVRMEM * m,unsigned char buf1,unsigned char buf2)1087 int compare_memory_masked(AVRMEM * m, unsigned char buf1, unsigned char buf2) {
1088   uint8_t bitmask = 0xFF;
1089   if(m) {
1090     bitmask = get_fuse_bitmask(m);
1091   }
1092   return ((buf1 & bitmask) != (buf2 & bitmask));
1093 }
1094 
1095 /*
1096  * Verify the memory buffer of p with that of v.  The byte range of v,
1097  * may be a subset of p.  The byte range of p should cover the whole
1098  * chip's memory size.
1099  *
1100  * Return the number of bytes verified, or -1 if they don't match.
1101  */
avr_verify(AVRPART * p,AVRPART * v,char * memtype,int size)1102 int avr_verify(AVRPART * p, AVRPART * v, char * memtype, int size)
1103 {
1104   int i;
1105   unsigned char * buf1, * buf2;
1106   int vsize;
1107   AVRMEM * a, * b;
1108 
1109   a = avr_locate_mem(p, memtype);
1110   if (a == NULL) {
1111     avrdude_message(MSG_INFO, "avr_verify(): memory type \"%s\" not defined for part %s\n",
1112                     memtype, p->desc);
1113     return -1;
1114   }
1115 
1116   b = avr_locate_mem(v, memtype);
1117   if (b == NULL) {
1118     avrdude_message(MSG_INFO, "avr_verify(): memory type \"%s\" not defined for part %s\n",
1119                     memtype, v->desc);
1120     return -1;
1121   }
1122 
1123   buf1  = a->buf;
1124   buf2  = b->buf;
1125   vsize = a->size;
1126 
1127   if (vsize < size) {
1128     avrdude_message(MSG_INFO, "%s: WARNING: requested verification for %d bytes\n"
1129                     "%s%s memory region only contains %d bytes\n"
1130                     "%sOnly %d bytes will be verified.\n",
1131                     progname, size,
1132                     progbuf, memtype, vsize,
1133                     progbuf, vsize);
1134     size = vsize;
1135   }
1136 
1137   for (i=0; i<size; i++) {
1138     if ((b->tags[i] & TAG_ALLOCATED) != 0 &&
1139         buf1[i] != buf2[i]) {
1140       if(compare_memory_masked(a , buf1[i], buf2[i])) {
1141         avrdude_message(MSG_INFO, "%s: verification error, first mismatch at byte 0x%04x\n"
1142                         "%s0x%02x != 0x%02x\n",
1143                         progname, i,
1144                         progbuf, buf1[i], buf2[i]);
1145         return -1;
1146       } else {
1147         avrdude_message(MSG_INFO, "%s: WARNING: invalid value for unused bits in fuse \"%s\", should be set to 1 according to datasheet\n"
1148                         "This behaviour is deprecated and will result in an error in future version\n"
1149                         "You probably want to use 0x%02x instead of 0x%02x (double check with your datasheet first).\n",
1150                         progname, memtype, buf1[i], buf2[i]);
1151       }
1152     }
1153   }
1154 
1155   return size;
1156 }
1157 
1158 
avr_get_cycle_count(PROGRAMMER * pgm,AVRPART * p,int * cycles)1159 int avr_get_cycle_count(PROGRAMMER * pgm, AVRPART * p, int * cycles)
1160 {
1161   AVRMEM * a;
1162   unsigned int cycle_count = 0;
1163   unsigned char v1;
1164   int rc;
1165   int i;
1166 
1167   a = avr_locate_mem(p, "eeprom");
1168   if (a == NULL) {
1169     return -1;
1170   }
1171 
1172   for (i=4; i>0; i--) {
1173     rc = pgm->read_byte(pgm, p, a, a->size-i, &v1);
1174   if (rc < 0) {
1175     avrdude_message(MSG_INFO, "%s: WARNING: can't read memory for cycle count, rc=%d\n",
1176             progname, rc);
1177     return -1;
1178   }
1179     cycle_count = (cycle_count << 8) | v1;
1180   }
1181 
1182    /*
1183    * If the EEPROM is erased, the cycle count reads 0xffffffff.
1184    * In this case we return a cycle_count of zero.
1185    * So, the calling function don't have to care about whether or not
1186    * the cycle count was initialized.
1187    */
1188   if (cycle_count == 0xffffffff) {
1189     cycle_count = 0;
1190   }
1191 
1192   *cycles = (int) cycle_count;
1193 
1194   return 0;
1195 }
1196 
1197 
avr_put_cycle_count(PROGRAMMER * pgm,AVRPART * p,int cycles)1198 int avr_put_cycle_count(PROGRAMMER * pgm, AVRPART * p, int cycles)
1199 {
1200   AVRMEM * a;
1201   unsigned char v1;
1202   int rc;
1203   int i;
1204 
1205   a = avr_locate_mem(p, "eeprom");
1206   if (a == NULL) {
1207     return -1;
1208   }
1209 
1210   for (i=1; i<=4; i++) {
1211     v1 = cycles & 0xff;
1212     cycles = cycles >> 8;
1213 
1214     rc = avr_write_byte(pgm, p, a, a->size-i, v1);
1215     if (rc < 0) {
1216       avrdude_message(MSG_INFO, "%s: WARNING: can't write memory for cycle count, rc=%d\n",
1217               progname, rc);
1218       return -1;
1219     }
1220   }
1221 
1222   return 0;
1223   }
1224 
avr_chip_erase(PROGRAMMER * pgm,AVRPART * p)1225 int avr_chip_erase(PROGRAMMER * pgm, AVRPART * p)
1226 {
1227   int rc;
1228 
1229   rc = pgm->chip_erase(pgm, p);
1230 
1231   return rc;
1232 }
1233 
1234 /*
1235  * Report the progress of a read or write operation from/to the
1236  * device.
1237  *
1238  * The first call of report_progress() should look like this (for a write op):
1239  *
1240  * report_progress (0, 1, "Writing");
1241  *
1242  * Then hdr should be passed NULL on subsequent calls while the
1243  * operation is progressing. Once the operation is complete, a final
1244  * call should be made as such to ensure proper termination of the
1245  * progress report:
1246  *
1247  * report_progress (1, 1, NULL);
1248  *
1249  * It would be nice if we could reduce the usage to one and only one
1250  * call for each of start, during and end cases. As things stand now,
1251  * that is not possible and makes maintenance a bit more work.
1252  */
report_progress(int completed,int total,char * hdr)1253 void report_progress (int completed, int total, char *hdr)
1254 {
1255   static int last = 0;
1256   static double start_time;
1257   int percent = (total > 0) ? ((completed * 100) / total) : 100;
1258   struct timeval tv;
1259   double t;
1260 
1261   if (update_progress == NULL)
1262     return;
1263 
1264   gettimeofday(&tv, NULL);
1265   t = tv.tv_sec + ((double)tv.tv_usec)/1000000;
1266 
1267   if (hdr) {
1268     last = 0;
1269     start_time = t;
1270     update_progress (percent, t - start_time, hdr);
1271   }
1272 
1273   if (percent > 100)
1274     percent = 100;
1275 
1276   if (percent > last) {
1277     last = percent;
1278     update_progress (percent, t - start_time, hdr);
1279   }
1280 
1281   if (percent == 100)
1282     last = 0;                   /* Get ready for next time. */
1283 }
1284