Revert "save some more memory in case "BOOTLOADER_CAN_EXIT" is deactivated"
[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 static void leaveBootloader() __attribute__((__noreturn__));
46
47 #include "bootloaderconfig.h"
48 #include "usbdrv/usbdrv.c"
49
50 #ifndef BOOTLOADER_ADDRESS
51 #error need to know the bootloaders flash address!
52 #endif
53
54 /* ------------------------------------------------------------------------ */
55
56 /* Request constants used by USBasp */
57 #define USBASP_FUNC_CONNECT 1
58 #define USBASP_FUNC_DISCONNECT 2
59 #define USBASP_FUNC_TRANSMIT 3
60 #define USBASP_FUNC_READFLASH 4
61 #define USBASP_FUNC_ENABLEPROG 5
62 #define USBASP_FUNC_WRITEFLASH 6
63 #define USBASP_FUNC_READEEPROM 7
64 #define USBASP_FUNC_WRITEEEPROM 8
65 #define USBASP_FUNC_SETLONGADDRESS 9
66
67 // additional USBasp Commands
68 #define USBASP_FUNC_SETISPSCK 10
69 #define USBASP_FUNC_TPI_CONNECT 11
70 #define USBASP_FUNC_TPI_DISCONNECT 12
71 #define USBASP_FUNC_TPI_RAWREAD 13
72 #define USBASP_FUNC_TPI_RAWWRITE 14
73 #define USBASP_FUNC_TPI_READBLOCK 15
74 #define USBASP_FUNC_TPI_WRITEBLOCK 16
75 #define USBASP_FUNC_GETCAPABILITIES 127
76 /* ------------------------------------------------------------------------ */
77
78 #ifndef ulong
79 # define ulong unsigned long
80 #endif
81 #ifndef uint
82 # define uint unsigned int
83 #endif
84
85
86 /* allow compatibility with avrusbboot's bootloaderconfig.h: */
87 #ifdef BOOTLOADER_INIT
88 # define bootLoaderInit() BOOTLOADER_INIT
89 # define bootLoaderExit()
90 #endif
91 #ifdef BOOTLOADER_CONDITION
92 # define bootLoaderCondition() BOOTLOADER_CONDITION
93 #endif
94
95 /* device compatibility: */
96 #ifndef GICR /* ATMega*8 don't have GICR, use MCUCR instead */
97 # define GICR MCUCR
98 #endif
99
100 /* ------------------------------------------------------------------------ */
101
102 #if (FLASHEND) > 0xffff /* we need long addressing */
103 # define CURRENT_ADDRESS currentAddress.l
104 # define addr_t ulong
105 #else
106 # define CURRENT_ADDRESS currentAddress.w[0]
107 # define addr_t uint
108 #endif
109
110 typedef union longConverter{
111 addr_t l;
112 uint w[sizeof(addr_t)/2];
113 uchar b[sizeof(addr_t)];
114 }longConverter_t;
115
116
117 #if BOOTLOADER_CAN_EXIT
118 static volatile unsigned char stayinloader = 0xfe;
119 #endif
120
121 static longConverter_t currentAddress; /* in bytes */
122 static uchar bytesRemaining;
123 static uchar isLastPage;
124 #if HAVE_EEPROM_PAGED_ACCESS
125 static uchar currentRequest;
126 #else
127 static const uchar currentRequest = 0;
128 #endif
129
130 static const uchar signatureBytes[4] = {
131 #ifdef SIGNATURE_BYTES
132 SIGNATURE_BYTES
133 #elif defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega8HVA__)
134 0x1e, 0x93, 0x07, 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__)
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_ATmega644__) || defined (__AVR_ATmega644A__)
166 0x1e, 0x96, 0x09, 0
167 #elif defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__)
168 0x1e, 0x96, 0x0a, 0
169 #elif defined (__AVR_ATmega128__)
170 0x1e, 0x97, 0x02, 0
171 #elif defined (__AVR_ATmega1284__)
172 0x1e, 0x97, 0x06, 0
173 #elif defined (__AVR_ATmega1284P__)
174 0x1e, 0x97, 0x05, 0
175 #else
176 # error "Device signature is not known, please edit main.c!"
177 #endif
178 };
179
180 /* ------------------------------------------------------------------------ */
181
182 static void (*nullVector)(void) __attribute__((__noreturn__));
183
184 static void leaveBootloader()
185 {
186 DBG1(0x01, 0, 0);
187 cli();
188 usbDeviceDisconnect();
189 bootLoaderExit();
190 USB_INTR_ENABLE = 0;
191 USB_INTR_CFG = 0; /* also reset config bits */
192 GICR = (1 << IVCE); /* enable change of interrupt vectors */
193 GICR = (0 << IVSEL); /* move interrupts to application flash section */
194
195 /* We must go through a global function pointer variable instead of writing
196 * ((void (*)(void))0)();
197 * because the compiler optimizes a constant 0 to "rcall 0" which is not
198 * handled correctly by the assembler.
199 */
200 nullVector();
201 }
202
203 /* ------------------------------------------------------------------------ */
204
205 uchar usbFunctionSetup(uchar data[8])
206 {
207 usbRequest_t *rq = (void *)data;
208 uchar len = 0;
209 static uchar replyBuffer[4];
210
211 usbMsgPtr = replyBuffer;
212 if(rq->bRequest == USBASP_FUNC_TRANSMIT){ /* emulate parts of ISP protocol */
213 uchar rval = 0;
214 usbWord_t address;
215 address.bytes[1] = rq->wValue.bytes[1];
216 address.bytes[0] = rq->wIndex.bytes[0];
217 if(rq->wValue.bytes[0] == 0x30){ /* read signature */
218 rval = rq->wIndex.bytes[0] & 3;
219 rval = signatureBytes[rval];
220 #if HAVE_READ_LOCK_FUSE
221 #if defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega32__)
222 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
223 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
224 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
225 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
226 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
227 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
228
229 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__) || defined (__AVR_ATmega48PA__) || \
230 defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__) || defined (__AVR_ATmega88PA__) || \
231 defined (__AVR_ATmega164A__) || defined (__AVR_ATmega164P__) || \
232 defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__) || defined (__AVR_ATmega168PA__) || \
233 defined (__AVR_ATmega324A__) || defined (__AVR_ATmega324P__) || \
234 defined (__AVR_ATmega328__) || defined (__AVR_ATmega328P__) || \
235 defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__) || defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__) || \
236 defined (__AVR_ATmega128__) || \
237 defined (__AVR_ATmega1284__) || defined (__AVR_ATmega1284P__)
238 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
239 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
240 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
241 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
242 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
243 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
244 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x08){ /* read efuse bits */
245 rval = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS );
246 #else
247 #warning "HAVE_READ_LOCK_FUSE is activated but MCU unknown -> will not support this feature"
248 #endif
249 #endif
250 #if HAVE_EEPROM_BYTE_ACCESS
251 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
252 rval = eeprom_read_byte((void *)address.word);
253 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
254 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
255 #endif
256 #if HAVE_CHIP_ERASE
257 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
258 addr_t addr;
259 for(addr = 0; addr < FLASHEND + 1 - 2048; addr += SPM_PAGESIZE) {
260 /* wait and erase page */
261 DBG1(0x33, 0, 0);
262 # ifndef NO_FLASH_WRITE
263 boot_spm_busy_wait();
264 cli();
265 boot_page_erase(addr);
266 sei();
267 # endif
268 }
269 #endif
270 }else{
271 /* ignore all others, return default value == 0 */
272 }
273 replyBuffer[3] = rval;
274 len = 4;
275 }else if((rq->bRequest == USBASP_FUNC_ENABLEPROG) || (rq->bRequest == USBASP_FUNC_SETISPSCK)){
276 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
277 len = 1;
278 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
279 currentAddress.w[0] = rq->wValue.word;
280 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
281 #if (FLASHEND) > 0xffff
282 currentAddress.w[1] = rq->wIndex.word;
283 #endif
284 }else{
285 bytesRemaining = rq->wLength.bytes[0];
286 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
287 isLastPage = rq->wIndex.bytes[1] & 0x02;
288 #if HAVE_EEPROM_PAGED_ACCESS
289 currentRequest = rq->bRequest;
290 #endif
291 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
292 }
293
294 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
295
296 #if BOOTLOADER_CAN_EXIT
297 stayinloader &= (0xfe);
298 #endif
299 }else{
300 /* ignore: others, but could be USBASP_FUNC_CONNECT */
301 #if BOOTLOADER_CAN_EXIT
302 stayinloader |= (0x01);
303 #endif
304 }
305 return len;
306 }
307
308 uchar usbFunctionWrite(uchar *data, uchar len)
309 {
310 uchar isLast;
311
312 DBG1(0x31, (void *)&currentAddress.l, 4);
313 if(len > bytesRemaining)
314 len = bytesRemaining;
315 bytesRemaining -= len;
316 isLast = bytesRemaining == 0;
317 if(currentRequest >= USBASP_FUNC_READEEPROM){
318 uchar i;
319 for(i = 0; i < len; i++){
320 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
321 }
322 }else{
323 uchar i;
324 for(i = 0; i < len;){
325 #if HAVE_BLB11_SOFTW_LOCKBIT
326 if (CURRENT_ADDRESS >= (addr_t)(BOOTLOADER_ADDRESS)) {
327 return 1;
328 }
329 #endif
330 i += 2;
331 DBG1(0x32, 0, 0);
332 cli();
333 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
334 sei();
335 CURRENT_ADDRESS += 2;
336 data += 2;
337 /* write page when we cross page boundary or we have the last partial page */
338 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
339 #if !HAVE_CHIP_ERASE
340 DBG1(0x33, 0, 0);
341 # ifndef NO_FLASH_WRITE
342 cli();
343 boot_page_erase(CURRENT_ADDRESS - 2); /* erase page */
344 sei();
345 boot_spm_busy_wait(); /* wait until page is erased */
346 # endif
347 #endif
348 DBG1(0x34, 0, 0);
349 #ifndef NO_FLASH_WRITE
350 cli();
351 boot_page_write(CURRENT_ADDRESS - 2);
352 sei();
353 boot_spm_busy_wait();
354 cli();
355 boot_rww_enable();
356 sei();
357 #endif
358 }
359 }
360 DBG1(0x35, (void *)&currentAddress.l, 4);
361 }
362 return isLast;
363 }
364
365 uchar usbFunctionRead(uchar *data, uchar len)
366 {
367 uchar i;
368
369 if(len > bytesRemaining)
370 len = bytesRemaining;
371 bytesRemaining -= len;
372 for(i = 0; i < len; i++){
373 if(currentRequest >= USBASP_FUNC_READEEPROM){
374 *data = eeprom_read_byte((void *)currentAddress.w[0]);
375 }else{
376 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
377 }
378 data++;
379 CURRENT_ADDRESS++;
380 }
381 return len;
382 }
383
384 /* ------------------------------------------------------------------------ */
385
386 static void initForUsbConnectivity(void)
387 {
388 #if HAVE_UNPRECISEWAIT
389 /* (0.25s*F_CPU)/(4 cycles per loop) ~ (65536*waitloopcnt)
390 * F_CPU/(16*65536) ~ waitloopcnt
391 * F_CPU / 1048576 ~ waitloopcnt
392 */
393 uint8_t waitloopcnt = 1 + (F_CPU/1048576);
394 #endif
395 usbInit();
396 /* enforce USB re-enumerate: */
397 usbDeviceDisconnect(); /* do this while interrupts are disabled */
398 #if HAVE_UNPRECISEWAIT
399 asm volatile (
400 /*we really don't care what value Z has...
401 * ...if we loop 65536/F_CPU more or less...
402 * ...unimportant - just save some opcodes
403 */
404 "initForUsbConnectivity_sleeploop: \n\t"
405 "sbiw r30, 1 \n\t"
406 "sbci %0, 0 \n\t"
407 "brne initForUsbConnectivity_sleeploop \n\t"
408 : "+d" (waitloopcnt)
409 :
410 : "r30","r31"
411 );
412 #else
413 _delay_ms(260); /* fake USB disconnect for > 250 ms */
414 #endif
415 usbDeviceConnect();
416 sei();
417 }
418
419 int __attribute__((noreturn)) main(void)
420 {
421 /* initialize */
422 bootLoaderInit();
423 odDebugInit();
424 DBG1(0x00, 0, 0);
425 #ifndef NO_FLASH_WRITE
426 GICR = (1 << IVCE); /* enable change of interrupt vectors */
427 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
428 #endif
429 if(bootLoaderCondition()){
430 #if NEED_WATCHDOG
431 wdt_disable(); /* main app may have enabled watchdog */
432 #endif
433 initForUsbConnectivity();
434 do{
435 usbPoll();
436 #if BOOTLOADER_CAN_EXIT
437 if (stayinloader >= 0x10) {
438 if (!bootLoaderCondition()) {
439 stayinloader-=0x10;
440 }
441 } else {
442 if (bootLoaderCondition()) {
443 if (stayinloader > 1) stayinloader-=2;
444 }
445 }
446 #endif
447
448 #if BOOTLOADER_CAN_EXIT
449 }while (stayinloader); /* main event loop, if BOOTLOADER_CAN_EXIT*/
450 #else
451 }while (1); /* main event loop */
452 #endif
453 }
454 leaveBootloader();
455 }
456
457 /* ------------------------------------------------------------------------ */