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