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