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