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