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