add missing selection macro of ATmega164PA signature
[pub/USBaspLoader.git] / firmware / main.c
1 /* Name: main.c
2 * Project: USBaspLoader
3 * Author: Christian Starkjohann
4 * Author: Stephan Baerwolf
5 * Creation Date: 2007-12-08
6 * Modification Date: 2012-11-10
7 * Tabsize: 4
8 * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
9 * License: GNU GPL v2 (see License.txt)
10 * This Revision: $Id: main.c 786 2010-05-30 20:41:40Z cs $
11 */
12
13 #include "spminterface.h" /* must be included as first! */
14
15 #include <avr/io.h>
16 #include <avr/interrupt.h>
17 #include <avr/pgmspace.h>
18 #include <avr/wdt.h>
19 #include <avr/boot.h>
20 #include <avr/eeprom.h>
21 #include <util/delay.h>
22
23
24 #if 0
25 /*
26 * 29.09.2012 / 30.09.2012
27 *
28 * Since cpufunc.h is not needed in this context and
29 * since it is not available in all toolchains, this include
30 * becomes deactivated by github issue-report.
31 * (In case of trouble it remains in sourcecode for reactivation.)
32 *
33 * The autor would like to thank Lena-M for reporting this
34 * issue (https://github.com/baerwolf/USBaspLoader/issues/1).
35 */
36 #include <avr/cpufunc.h>
37 #endif
38
39 #include <avr/boot.h>
40
41 #include <string.h>
42
43
44
45 #include "bootloaderconfig.h"
46 #include "usbdrv/usbdrv.c"
47
48 #ifndef BOOTLOADER_ADDRESS
49 #error need to know the bootloaders flash address!
50 #endif
51 #define BOOTLOADER_PAGEADDR (BOOTLOADER_ADDRESS - (BOOTLOADER_ADDRESS % SPM_PAGESIZE))
52
53 /* ------------------------------------------------------------------------ */
54
55 /* Request constants used by USBasp */
56 #define USBASP_FUNC_CONNECT 1
57 #define USBASP_FUNC_DISCONNECT 2
58 #define USBASP_FUNC_TRANSMIT 3
59 #define USBASP_FUNC_READFLASH 4
60 #define USBASP_FUNC_ENABLEPROG 5
61 #define USBASP_FUNC_WRITEFLASH 6
62 #define USBASP_FUNC_READEEPROM 7
63 #define USBASP_FUNC_WRITEEEPROM 8
64 #define USBASP_FUNC_SETLONGADDRESS 9
65
66 // additional USBasp Commands
67 #define USBASP_FUNC_SETISPSCK 10
68 #define USBASP_FUNC_TPI_CONNECT 11
69 #define USBASP_FUNC_TPI_DISCONNECT 12
70 #define USBASP_FUNC_TPI_RAWREAD 13
71 #define USBASP_FUNC_TPI_RAWWRITE 14
72 #define USBASP_FUNC_TPI_READBLOCK 15
73 #define USBASP_FUNC_TPI_WRITEBLOCK 16
74 #define USBASP_FUNC_GETCAPABILITIES 127
75 /* ------------------------------------------------------------------------ */
76
77 #ifndef ulong
78 # define ulong unsigned long
79 #endif
80 #ifndef uint
81 # define uint unsigned int
82 #endif
83
84
85 /* allow compatibility with avrusbboot's bootloaderconfig.h: */
86 #ifdef BOOTLOADER_INIT
87 # define bootLoaderInit() BOOTLOADER_INIT
88 # define bootLoaderExit()
89 #endif
90 #ifdef BOOTLOADER_CONDITION
91 # define bootLoaderCondition() BOOTLOADER_CONDITION
92 #endif
93
94 /* device compatibility: */
95 #ifndef GICR /* ATMega*8 don't have GICR, use MCUCR instead */
96 # define GICR MCUCR
97 #endif
98
99 /* ------------------------------------------------------------------------ */
100
101 #if (FLASHEND) > 0xffff /* we need long addressing */
102 # define CURRENT_ADDRESS currentAddress.l
103 # define addr_t ulong
104 #else
105 # define CURRENT_ADDRESS currentAddress.w[0]
106 # define addr_t uint
107 #endif
108
109 typedef union longConverter{
110 addr_t l;
111 uint w[sizeof(addr_t)/2];
112 uchar b[sizeof(addr_t)];
113 }longConverter_t;
114
115
116 #if BOOTLOADER_CAN_EXIT
117 static volatile unsigned char stayinloader = 0xfe;
118 #endif
119
120 static longConverter_t currentAddress; /* in bytes */
121 static uchar bytesRemaining;
122 static uchar isLastPage;
123 #if HAVE_EEPROM_PAGED_ACCESS
124 static uchar currentRequest;
125 #else
126 static const uchar currentRequest = 0;
127 #endif
128
129 static const uchar signatureBytes[4] = {
130 #ifdef SIGNATURE_BYTES
131 SIGNATURE_BYTES
132 #elif defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega8HVA__)
133 0x1e, 0x93, 0x07, 0
134 #elif defined (__AVR_ATmega32__)
135 0x1e, 0x95, 0x02, 0
136 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__)
137 #error ATmega48 does not support bootloaders!
138 0x1e, 0x92, 0x05, 0
139 #elif defined (__AVR_ATmega48PA__)
140 #error ATmega48 does not support bootloaders!
141 0x1e, 0x92, 0x0A, 0
142 #elif defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__)
143 0x1e, 0x93, 0x0a, 0
144 #elif defined (__AVR_ATmega88PA__)
145 0x1e, 0x93, 0x0F, 0
146 #elif defined (__AVR_ATmega164A__)
147 0x1e, 0x94, 0x0f, 0
148 #elif defined (__AVR_ATmega164P__) || defined (__AVR_ATmega164PA__)
149 0x1e, 0x94, 0x0a, 0
150 #elif defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__)
151 0x1e, 0x94, 0x06, 0
152 #elif defined (__AVR_ATmega168PA__)
153 0x1e, 0x94, 0x0B, 0
154 #elif defined (__AVR_ATmega324A__)
155 0x1e, 0x95, 0x15, 0
156 #elif defined (__AVR_ATmega324P__)
157 0x1e, 0x95, 0x08, 0
158 #elif defined (__AVR_ATmega324PA__)
159 0x1e, 0x95, 0x11, 0
160 #elif defined (__AVR_ATmega328__)
161 0x1e, 0x95, 0x14, 0
162 #elif defined (__AVR_ATmega328P__)
163 0x1e, 0x95, 0x0f, 0
164 #elif defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__)
165 0x1e, 0x96, 0x09, 0
166 #elif defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__)
167 0x1e, 0x96, 0x0a, 0
168 #elif defined (__AVR_ATmega128__)
169 0x1e, 0x97, 0x02, 0
170 #elif defined (__AVR_ATmega1284__)
171 0x1e, 0x97, 0x06, 0
172 #elif defined (__AVR_ATmega1284P__)
173 0x1e, 0x97, 0x05, 0
174 #else
175 # error "Device signature is not known, please edit main.c!"
176 #endif
177 };
178
179 /* ------------------------------------------------------------------------ */
180
181 #if (!USE_EXCESSIVE_ASSEMBLER) || (!(defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega8HVA__)))
182 static void (*nullVector)(void) __attribute__((__noreturn__));
183 #endif
184
185 static void __attribute__((__noreturn__)) leaveBootloader()
186 {
187 #if (USE_EXCESSIVE_ASSEMBLER) && (defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega8HVA__))
188 asm volatile (
189 "cli\n\t"
190 "clr r30\n\t"
191 "sbi %[usbddr], %[usbminus]\n\t"
192 "cbi %[port], %[bit]\n\t"
193 "out %[usbintrenab], r30\n\t"
194 "out %[usbintrcfg], r30\n\t"
195 "ldi r31, %[ivce]\n\t"
196 "out %[mygicr], r31\n\t"
197 "out %[mygicr], r30\n\t"
198 "clr r31\n\t"
199 "icall\n\t"
200 :
201 : [port] "I" (_SFR_IO_ADDR(PIN_PORT(JUMPER_PORT))),
202 [bit] "I" (PIN(JUMPER_PORT, JUMPER_BIT)),
203 [usbintrenab] "I" (_SFR_IO_ADDR(USB_INTR_ENABLE)),
204 [usbintrcfg] "I" (_SFR_IO_ADDR(USB_INTR_CFG)),
205 [usbddr] "I" (_SFR_IO_ADDR(USBDDR)),
206 [usbminus] "I" (USBMINUS),
207 [mygicr] "I" (_SFR_IO_ADDR(GICR)),
208 [ivce] "I" (1<<IVCE)
209 );
210 /* TODO: compiler will put an unnecessary "ret" at this end ! */
211 #else
212 DBG1(0x01, 0, 0);
213 cli();
214 usbDeviceDisconnect();
215 bootLoaderExit();
216 USB_INTR_ENABLE = 0;
217 USB_INTR_CFG = 0; /* also reset config bits */
218 GICR = (1 << IVCE); /* enable change of interrupt vectors */
219 GICR = (0 << IVSEL); /* move interrupts to application flash section */
220
221 /* We must go through a global function pointer variable instead of writing
222 * ((void (*)(void))0)();
223 * because the compiler optimizes a constant 0 to "rcall 0" which is not
224 * handled correctly by the assembler.
225 */
226 nullVector();
227 #endif
228 }
229
230 /* ------------------------------------------------------------------------ */
231
232
233 uchar usbFunctionSetup_USBASP_FUNC_TRANSMIT(usbRequest_t *rq) {
234 uchar rval = 0;
235 usbWord_t address;
236 address.bytes[1] = rq->wValue.bytes[1];
237 address.bytes[0] = rq->wIndex.bytes[0];
238
239 if(rq->wValue.bytes[0] == 0x30){ /* read signature */
240 rval = rq->wIndex.bytes[0] & 3;
241 rval = signatureBytes[rval];
242 #if HAVE_READ_LOCK_FUSE
243 #if defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega32__)
244 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
245 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
246 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
247 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
248 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
249 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
250
251 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__) || defined (__AVR_ATmega48PA__) || \
252 defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__) || defined (__AVR_ATmega88PA__) || \
253 defined (__AVR_ATmega164A__) || defined (__AVR_ATmega164P__) || \
254 defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__) || defined (__AVR_ATmega168PA__) || \
255 defined (__AVR_ATmega324A__) || defined (__AVR_ATmega324P__) || \
256 defined (__AVR_ATmega328__) || defined (__AVR_ATmega328P__) || \
257 defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__) || defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__) || \
258 defined (__AVR_ATmega128__) || \
259 defined (__AVR_ATmega1284__) || defined (__AVR_ATmega1284P__)
260 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
261 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
262 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
263 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
264 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
265 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
266 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x08){ /* read efuse bits */
267 rval = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS );
268 #else
269 #warning "HAVE_READ_LOCK_FUSE is activated but MCU unknown -> will not support this feature"
270 #endif
271 #endif
272 #if HAVE_FLASH_BYTE_READACCESS
273 }else if(rq->wValue.bytes[0] == 0x20){ /* read FLASH low byte */
274 #if ((FLASHEND) > 65535)
275 rval = pgm_read_byte_far((((addr_t)address.word)<<1)+0);
276 #else
277 rval = pgm_read_byte((((addr_t)address.word)<<1)+0);
278 #endif
279 }else if(rq->wValue.bytes[0] == 0x28){ /* read FLASH high byte */
280 #if ((FLASHEND) > 65535)
281 rval = pgm_read_byte_far((((addr_t)address.word)<<1)+1);
282 #else
283 rval = pgm_read_byte((((addr_t)address.word)<<1)+1);
284 #endif
285 #endif
286 #if HAVE_EEPROM_BYTE_ACCESS
287 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
288 rval = eeprom_read_byte((void *)address.word);
289 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
290 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
291 #endif
292 #if HAVE_CHIP_ERASE
293 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
294 addr_t addr;
295 #if HAVE_BLB11_SOFTW_LOCKBIT
296 for(addr = 0; addr < (addr_t)(BOOTLOADER_PAGEADDR) ; addr += SPM_PAGESIZE) {
297 #else
298 for(addr = 0; addr <= (addr_t)(FLASHEND) ; addr += SPM_PAGESIZE) {
299 #endif
300 /* wait and erase page */
301 DBG1(0x33, 0, 0);
302 # ifndef NO_FLASH_WRITE
303 boot_spm_busy_wait();
304 cli();
305 boot_page_erase(addr);
306 sei();
307 # endif
308 }
309 #endif
310 }else{
311 /* ignore all others, return default value == 0 */
312 }
313
314 return rval;
315 }
316
317
318 uchar usbFunctionSetup(uchar data[8])
319 {
320 usbRequest_t *rq = (void *)data;
321 uchar len = 0;
322 static uchar replyBuffer[4];
323
324 usbMsgPtr = replyBuffer;
325 if(rq->bRequest == USBASP_FUNC_TRANSMIT){ /* emulate parts of ISP protocol */
326 replyBuffer[3] = usbFunctionSetup_USBASP_FUNC_TRANSMIT(rq);
327 len = 4;
328 }else if((rq->bRequest == USBASP_FUNC_ENABLEPROG) || (rq->bRequest == USBASP_FUNC_SETISPSCK)){
329 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
330 len = 1;
331 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
332 currentAddress.w[0] = rq->wValue.word;
333 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
334 #if (FLASHEND) > 0xffff
335 currentAddress.w[1] = rq->wIndex.word;
336 #endif
337 }else{
338 bytesRemaining = rq->wLength.bytes[0];
339 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
340 isLastPage = rq->wIndex.bytes[1] & 0x02;
341 #if HAVE_EEPROM_PAGED_ACCESS
342 currentRequest = rq->bRequest;
343 #endif
344 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
345 }
346
347 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
348
349 #if BOOTLOADER_CAN_EXIT
350 stayinloader &= (0xfe);
351 #endif
352 }else{
353 /* ignore: others, but could be USBASP_FUNC_CONNECT */
354 #if BOOTLOADER_CAN_EXIT
355 stayinloader |= (0x01);
356 #endif
357 }
358 return len;
359 }
360
361 #if (USE_EXCESSIVE_ASSEMBLER) && ((!HAVE_CHIP_ERASE) || (HAVE_ONDEMAND_PAGEERASE)) && (SPM_PAGESIZE <= 256) && (((BOOTLOADER_PAGEADDR>>0)&0xff) == 0)
362 uchar usbFunctionWrite(uchar *data, uchar len)
363 {
364 uchar isLast;
365
366 DBG1(0x31, (void *)&currentAddress.l, 4);
367 if(len > bytesRemaining)
368 len = bytesRemaining;
369 bytesRemaining -= len;
370 isLast = bytesRemaining == 0;
371 if(currentRequest >= USBASP_FUNC_READEEPROM){
372 uchar i;
373 for(i = 0; i < len; i++){
374 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
375 }
376 }else{
377 asm volatile (
378 "sbrc %[len], 0\n\t"
379 "inc %[len]\n\t"
380 "usbFunctionWrite_flashloop:\n\t"
381 "subi %[len], 2\n\t"
382 "brlo usbFunctionWrite_finished\n\t"
383
384 #if HAVE_BLB11_SOFTW_LOCKBIT
385 "cpi r31, %[blsaddrhi]\n\t" /* accelerated BLB11_SOFTW_LOCKBIT check */
386 "brsh usbFunctionWrite_finished\n\t"
387 // "brlo usbFunctionWrite_addrunlock_ok\n\t"
388 // "brne usbFunctionWrite_finished\n\t"
389 // "cpi r30, %[blsaddrlo]\n\t"
390 // "brlo usbFunctionWrite_addrunlock_ok\n\t"
391 // "rjmp usbFunctionWrite_finished\n\t"
392 // "usbFunctionWrite_addrunlock_ok:\n\t"
393 #endif
394 "rcall usbFunctionWrite_waitA\n\t"
395 "cli\n\t" /* r0 or r1 may be __zero_reg__ and may become dangerous nonzero within interrupts */
396 "ld r0, X+\n\t"
397 "ld r1, X+\n\t"
398
399 "ldi r18, %[pagfillval]\n\t"
400 "rcall usbFunctionWrite_saveflash\n\t" /* page fill */
401
402 "mov r18, r30\n\t"
403 "subi r18, 0xfe\n\t" /* add with 2 */
404 "andi r18, %[pagemask]\n\t"
405 "breq usbFunctionWrite_pageisfull\n\t"
406 "tst %[islast]\n\t"
407 "breq usbFunctionWrite_skippageisfull\n\t"
408 "tst %[isLastPage]\n\t"
409 "breq usbFunctionWrite_skippageisfull\n\t"
410 "cpi %[len], 0\n\t"
411 "brne usbFunctionWrite_skippageisfull\n\t"
412
413 "usbFunctionWrite_pageisfull:\n\t" /* start writing the page */
414 "ldi r18, %[pageraseval]\n\t"
415 "rcall usbFunctionWrite_saveflash\n\t" /* page erase */
416 "rcall usbFunctionWrite_waitA\n\t"
417
418 "ldi r18, %[pagwriteval]\n\t"
419 "rcall usbFunctionWrite_saveflash\n\t" /* page write */
420 "rcall usbFunctionWrite_waitA\n\t"
421
422 "in __tmp_reg__, %[spmcr]\n\t"
423 "sbrs __tmp_reg__, %[rwwsbbit]\n\t"
424 "rjmp usbFunctionWrite_skippageisfull\n\t"
425 "ldi r18, %[rwwenrval]\n\t"
426 "rcall usbFunctionWrite_saveflash\n\t" /* reenable rww*/
427 // "rcall usbFunctionWrite_waitA\n\t"
428
429
430 "usbFunctionWrite_skippageisfull:\n\t"
431 "adiw r30, 0x2\n\t"
432 "rjmp usbFunctionWrite_flashloop\n\t"
433
434 "usbFunctionWrite_saveflash:\n\t"
435 "cli\n\t"
436 "out %[spmcr], r18\n\t"
437 "spm\n\t"
438 "clr __zero_reg__\n\t" /* if r0 or r1 is __zero_reg__ it may have become inconsisten while page-fill */
439 "sei\n\t"
440 "ret\n\t"
441
442 "usbFunctionWrite_waitA:\n\t"
443 "in __tmp_reg__, %[spmcr]\n\t"
444 "sbrc __tmp_reg__, %[spmenbit]\n\t"
445 "rjmp usbFunctionWrite_waitA\n\t"
446 "ret\n\t"
447
448 "usbFunctionWrite_finished:\n\t"
449 : [addr] "+z" (currentAddress.l)
450
451 : [spmenbit] "I" (SPMEN),
452 [rwwsbbit] "I" (RWWSB),
453 [spmcr] "I" (_SFR_IO_ADDR(__SPM_REG)),
454 [pagfillval] "M" ((1<<SPMEN)),
455 [pageraseval] "M" ((1<<PGERS) | (1<<SPMEN)),
456 [pagwriteval] "M" ((1<<PGWRT) | (1<<SPMEN)),
457 [rwwenrval] "M" ((1<<RWWSRE) | (1<<SPMEN)),
458 [pagemask] "M" (SPM_PAGESIZE-1),
459 #if HAVE_BLB11_SOFTW_LOCKBIT
460 [blsaddrhi] "M" ((uint8_t)((BOOTLOADER_PAGEADDR>>8)&0xff)),
461 // [blsaddrlo] "M" ((uint8_t)((BOOTLOADER_PAGEADDR>>0)&0xff)),
462 #endif
463 [islast] "r" (isLast),
464 [isLastPage] "r" (isLastPage),
465 [len] "d" (len),
466 [dataptr] "x" (data)
467
468 : "r0", "r1", "r18"
469 );
470 }
471 return isLast;
472 }
473 #else
474 uchar usbFunctionWrite(uchar *data, uchar len)
475 {
476 uchar i,isLast;
477
478 DBG1(0x31, (void *)&currentAddress.l, 4);
479 if(len > bytesRemaining)
480 len = bytesRemaining;
481 bytesRemaining -= len;
482 isLast = bytesRemaining == 0;
483 for(i = 0; i < len;) {
484 if(currentRequest >= USBASP_FUNC_READEEPROM){
485 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
486 i++;
487 } else {
488 #if HAVE_BLB11_SOFTW_LOCKBIT
489 if (CURRENT_ADDRESS >= (addr_t)(BOOTLOADER_PAGEADDR)) {
490 return 1;
491 }
492 #endif
493 i += 2;
494 DBG1(0x32, 0, 0);
495 cli();
496 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
497 sei();
498 CURRENT_ADDRESS += 2;
499 data += 2;
500 /* write page when we cross page boundary or we have the last partial page */
501 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
502 #if (!HAVE_CHIP_ERASE) || (HAVE_ONDEMAND_PAGEERASE)
503 DBG1(0x33, 0, 0);
504 # ifndef NO_FLASH_WRITE
505 cli();
506 boot_page_erase(CURRENT_ADDRESS - 2); /* erase page */
507 sei();
508 boot_spm_busy_wait(); /* wait until page is erased */
509 # endif
510 #endif
511 DBG1(0x34, 0, 0);
512 #ifndef NO_FLASH_WRITE
513 cli();
514 boot_page_write(CURRENT_ADDRESS - 2);
515 sei();
516 boot_spm_busy_wait();
517 cli();
518 boot_rww_enable();
519 sei();
520 #endif
521 }
522 }
523 DBG1(0x35, (void *)&currentAddress.l, 4);
524 }
525 return isLast;
526 }
527 #endif
528
529 uchar usbFunctionRead(uchar *data, uchar len)
530 {
531 uchar i;
532
533 if(len > bytesRemaining)
534 len = bytesRemaining;
535 bytesRemaining -= len;
536 for(i = 0; i < len; i++){
537 if(currentRequest >= USBASP_FUNC_READEEPROM){
538 *data = eeprom_read_byte((void *)currentAddress.w[0]);
539 }else{
540 #if ((FLASHEND) > 65535)
541 *data = pgm_read_byte_far(CURRENT_ADDRESS);
542 #else
543 *data = pgm_read_byte(CURRENT_ADDRESS);
544 #endif
545 }
546 data++;
547 CURRENT_ADDRESS++;
548 }
549 return len;
550 }
551
552 /* ------------------------------------------------------------------------ */
553
554 static void initForUsbConnectivity(void)
555 {
556 #if HAVE_UNPRECISEWAIT
557 /* (0.25s*F_CPU)/(4 cycles per loop) ~ (65536*waitloopcnt)
558 * F_CPU/(16*65536) ~ waitloopcnt
559 * F_CPU / 1048576 ~ waitloopcnt
560 */
561 uint8_t waitloopcnt = 1 + (F_CPU/1048576);
562 #endif
563 usbInit();
564 /* enforce USB re-enumerate: */
565 usbDeviceDisconnect(); /* do this while interrupts are disabled */
566 #if HAVE_UNPRECISEWAIT
567 asm volatile (
568 /*we really don't care what value Z has...
569 * ...if we loop 65536/F_CPU more or less...
570 * ...unimportant - just save some opcodes
571 */
572 "initForUsbConnectivity_sleeploop: \n\t"
573 "sbiw r30, 1 \n\t"
574 "sbci %0, 0 \n\t"
575 "brne initForUsbConnectivity_sleeploop \n\t"
576 : "+d" (waitloopcnt)
577 :
578 : "r30","r31"
579 );
580 #else
581 _delay_ms(260); /* fake USB disconnect for > 250 ms */
582 #endif
583 usbDeviceConnect();
584 sei();
585 }
586
587 int __attribute__((__noreturn__)) main(void)
588 {
589 /* initialize */
590 bootLoaderInit();
591 odDebugInit();
592 DBG1(0x00, 0, 0);
593 #ifndef NO_FLASH_WRITE
594 GICR = (1 << IVCE); /* enable change of interrupt vectors */
595 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
596 #endif
597 if(bootLoaderCondition()){
598 #if NEED_WATCHDOG
599 wdt_disable(); /* main app may have enabled watchdog */
600 #endif
601 initForUsbConnectivity();
602 do{
603 usbPoll();
604 #if BOOTLOADER_CAN_EXIT
605 #if USE_EXCESSIVE_ASSEMBLER
606 asm volatile (
607 "cpi %[sil], 0x10\n\t"
608 "brlo main_stayinloader_smaller\n\t"
609 "sbic %[pin], %[bit]\n\t"
610 "subi %[sil], 0x10\n\t"
611 "rjmp main_stayinloader_finished\n\t"
612
613 "main_stayinloader_smaller:\n\t"
614 "cpi %[sil], 0x2\n\t"
615 "brlo main_stayinloader_finished\n\t"
616 "sbis %[pin], %[bit]\n\t"
617 "subi %[sil], 0x2\n\t"
618
619 "main_stayinloader_finished:\n\t"
620 : [sil] "+d" (stayinloader)
621 : [pin] "I" (_SFR_IO_ADDR(PIN_PIN(JUMPER_PORT))),
622 [bit] "I" (PIN(JUMPER_PORT, JUMPER_BIT))
623 );
624 #else
625 if (stayinloader >= 0x10) {
626 if (!bootLoaderCondition()) {
627 stayinloader-=0x10;
628 }
629 } else {
630 if (bootLoaderCondition()) {
631 if (stayinloader > 1) stayinloader-=2;
632 }
633 }
634 #endif
635 #endif
636
637 #if BOOTLOADER_CAN_EXIT
638 }while (stayinloader); /* main event loop, if BOOTLOADER_CAN_EXIT*/
639 #else
640 }while (1); /* main event loop */
641 #endif
642 }
643 leaveBootloader();
644 }
645
646 /* ------------------------------------------------------------------------ */