Clean up and add new features
[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_ATmega328__)
160 0x1e, 0x95, 0x14, 0
161 #elif defined (__AVR_ATmega328P__)
162 0x1e, 0x95, 0x0f, 0
163 #elif defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__)
164 0x1e, 0x96, 0x09, 0
165 #elif defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__)
166 0x1e, 0x96, 0x0a, 0
167 #elif defined (__AVR_ATmega128__)
168 0x1e, 0x97, 0x02, 0
169 #elif defined (__AVR_ATmega1284__)
170 0x1e, 0x97, 0x06, 0
171 #elif defined (__AVR_ATmega1284P__)
172 0x1e, 0x97, 0x05, 0
173 #else
174 # error "Device signature is not known, please edit main.c!"
175 #endif
176 };
177
178 /* ------------------------------------------------------------------------ */
179
180 static void (*nullVector)(void) __attribute__((__noreturn__));
181
182 static void leaveBootloader()
183 {
184 DBG1(0x01, 0, 0);
185 cli();
186 usbDeviceDisconnect();
187 bootLoaderExit();
188 USB_INTR_ENABLE = 0;
189 USB_INTR_CFG = 0; /* also reset config bits */
190 GICR = (1 << IVCE); /* enable change of interrupt vectors */
191 GICR = (0 << IVSEL); /* move interrupts to application flash section */
192
193 /* We must go through a global function pointer variable instead of writing
194 * ((void (*)(void))0)();
195 * because the compiler optimizes a constant 0 to "rcall 0" which is not
196 * handled correctly by the assembler.
197 */
198 nullVector();
199 }
200
201 /* ------------------------------------------------------------------------ */
202
203 uchar usbFunctionSetup(uchar data[8])
204 {
205 usbRequest_t *rq = (void *)data;
206 uchar len = 0;
207 static uchar replyBuffer[4];
208
209 usbMsgPtr = replyBuffer;
210 if(rq->bRequest == USBASP_FUNC_TRANSMIT){ /* emulate parts of ISP protocol */
211 uchar rval = 0;
212 usbWord_t address;
213 address.bytes[1] = rq->wValue.bytes[1];
214 address.bytes[0] = rq->wIndex.bytes[0];
215 if(rq->wValue.bytes[0] == 0x30){ /* read signature */
216 rval = rq->wIndex.bytes[0] & 3;
217 rval = signatureBytes[rval];
218 #if HAVE_READ_LOCK_FUSE
219 #if defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega32__)
220 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
221 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
222 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
223 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
224 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
225 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
226
227 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__) || defined (__AVR_ATmega48PA__) || \
228 defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__) || defined (__AVR_ATmega88PA__) || \
229 defined (__AVR_ATmega164A__) || defined (__AVR_ATmega164P__) || \
230 defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__) || defined (__AVR_ATmega168PA__) || \
231 defined (__AVR_ATmega324A__) || defined (__AVR_ATmega324P__) || \
232 defined (__AVR_ATmega328__) || defined (__AVR_ATmega328P__) || \
233 defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__) || defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__) || \
234 defined (__AVR_ATmega128__) || \
235 defined (__AVR_ATmega1284__) || defined (__AVR_ATmega1284P__)
236 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
237 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
238 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
239 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
240 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
241 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
242 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x08){ /* read efuse bits */
243 rval = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS );
244 #else
245 #warning "HAVE_READ_LOCK_FUSE is activated but MCU unknown -> will not support this feature"
246 #endif
247 #endif
248 #if HAVE_EEPROM_BYTE_ACCESS
249 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
250 rval = eeprom_read_byte((void *)address.word);
251 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
252 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
253 #endif
254 #if HAVE_CHIP_ERASE
255 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
256 addr_t addr;
257 for(addr = 0; addr < FLASHEND + 1 - 2048; addr += SPM_PAGESIZE) {
258 /* wait and erase page */
259 DBG1(0x33, 0, 0);
260 # ifndef NO_FLASH_WRITE
261 boot_spm_busy_wait();
262 cli();
263 boot_page_erase(addr);
264 sei();
265 # endif
266 }
267 #endif
268 }else{
269 /* ignore all others, return default value == 0 */
270 }
271 replyBuffer[3] = rval;
272 len = 4;
273 }else if((rq->bRequest == USBASP_FUNC_ENABLEPROG) || (rq->bRequest == USBASP_FUNC_SETISPSCK)){
274 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
275 len = 1;
276 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
277 currentAddress.w[0] = rq->wValue.word;
278 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
279 #if (FLASHEND) > 0xffff
280 currentAddress.w[1] = rq->wIndex.word;
281 #endif
282 }else{
283 bytesRemaining = rq->wLength.bytes[0];
284 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
285 isLastPage = rq->wIndex.bytes[1] & 0x02;
286 #if HAVE_EEPROM_PAGED_ACCESS
287 currentRequest = rq->bRequest;
288 #endif
289 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
290 }
291
292 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
293
294 #if BOOTLOADER_CAN_EXIT
295 stayinloader &= (0xfe);
296 #endif
297 }else{
298 /* ignore: others, but could be USBASP_FUNC_CONNECT */
299 #if BOOTLOADER_CAN_EXIT
300 stayinloader |= (0x01);
301 #endif
302 }
303 return len;
304 }
305
306 uchar usbFunctionWrite(uchar *data, uchar len)
307 {
308 uchar isLast;
309
310 DBG1(0x31, (void *)&currentAddress.l, 4);
311 if(len > bytesRemaining)
312 len = bytesRemaining;
313 bytesRemaining -= len;
314 isLast = bytesRemaining == 0;
315 if(currentRequest >= USBASP_FUNC_READEEPROM){
316 uchar i;
317 for(i = 0; i < len; i++){
318 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
319 }
320 }else{
321 uchar i;
322 for(i = 0; i < len;){
323 #if HAVE_BLB11_SOFTW_LOCKBIT
324 if (CURRENT_ADDRESS >= (addr_t)(BOOTLOADER_ADDRESS)) {
325 return 1;
326 }
327 #endif
328 i += 2;
329 DBG1(0x32, 0, 0);
330 cli();
331 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
332 sei();
333 CURRENT_ADDRESS += 2;
334 data += 2;
335 /* write page when we cross page boundary or we have the last partial page */
336 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
337 #if !HAVE_CHIP_ERASE
338 DBG1(0x33, 0, 0);
339 # ifndef NO_FLASH_WRITE
340 cli();
341 boot_page_erase(CURRENT_ADDRESS - 2); /* erase page */
342 sei();
343 boot_spm_busy_wait(); /* wait until page is erased */
344 # endif
345 #endif
346 DBG1(0x34, 0, 0);
347 #ifndef NO_FLASH_WRITE
348 cli();
349 boot_page_write(CURRENT_ADDRESS - 2);
350 sei();
351 boot_spm_busy_wait();
352 cli();
353 boot_rww_enable();
354 sei();
355 #endif
356 }
357 }
358 DBG1(0x35, (void *)&currentAddress.l, 4);
359 }
360 return isLast;
361 }
362
363 uchar usbFunctionRead(uchar *data, uchar len)
364 {
365 uchar i;
366
367 if(len > bytesRemaining)
368 len = bytesRemaining;
369 bytesRemaining -= len;
370 for(i = 0; i < len; i++){
371 if(currentRequest >= USBASP_FUNC_READEEPROM){
372 *data = eeprom_read_byte((void *)currentAddress.w[0]);
373 }else{
374 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
375 }
376 data++;
377 CURRENT_ADDRESS++;
378 }
379 return len;
380 }
381
382 /* ------------------------------------------------------------------------ */
383
384 static void initForUsbConnectivity(void)
385 {
386 uchar i = 0;
387
388 usbInit();
389 /* enforce USB re-enumerate: */
390 usbDeviceDisconnect(); /* do this while interrupts are disabled */
391 while(--i){ /* fake USB disconnect for > 250 ms */
392 _delay_ms(1);
393 }
394 usbDeviceConnect();
395 sei();
396 }
397
398 int __attribute__((noreturn)) main(void)
399 {
400 /* initialize */
401 bootLoaderInit();
402 odDebugInit();
403 DBG1(0x00, 0, 0);
404 #ifndef NO_FLASH_WRITE
405 GICR = (1 << IVCE); /* enable change of interrupt vectors */
406 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
407 #endif
408 if(bootLoaderCondition()){
409 #if NEED_WATCHDOG
410 wdt_disable(); /* main app may have enabled watchdog */
411 #endif
412 initForUsbConnectivity();
413 do{
414 usbPoll();
415 #if BOOTLOADER_CAN_EXIT
416 if (stayinloader >= 0x10) {
417 if (!bootLoaderCondition()) {
418 stayinloader-=0x10;
419 }
420 } else {
421 if (bootLoaderCondition()) {
422 if (stayinloader > 1) stayinloader-=2;
423 }
424 }
425 #endif
426
427 #if BOOTLOADER_CAN_EXIT
428 }while (stayinloader); /* main event loop, if BOOTLOADER_CAN_EXIT*/
429 #else
430 }while (1); /* main event loop */
431 #endif
432 }
433 leaveBootloader();
434 }
435
436 /* ------------------------------------------------------------------------ */