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