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