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