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