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