USBaspLoader eigth stable release v0.8
[pub/USBaspLoader.git] / firmware / main.c
1 /* Name: main.c
2 * Project: USBaspLoader
3 * Author: Christian Starkjohann
4 * Creation Date: 2007-12-08
5 * Tabsize: 4
6 * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
7 * License: GNU GPL v2 (see License.txt)
8 * This Revision: $Id: main.c 786 2010-05-30 20:41:40Z cs $
9 */
10
11 #include "spminterface.h" /* must be included as first! */
12
13 #include <avr/io.h>
14 #include <avr/interrupt.h>
15 #include <avr/pgmspace.h>
16 #include <avr/wdt.h>
17 #include <avr/boot.h>
18 #include <avr/eeprom.h>
19 #include <util/delay.h>
20
21
22 #if 0
23 /*
24 * 29.09.2012 / 30.09.2012
25 *
26 * Since cpufunc.h is not needed in this context and
27 * since it is not available in all toolchains, this include
28 * becomes deactivated by github issue-report.
29 * (In case of trouble it remains in sourcecode for reactivation.)
30 *
31 * The autor would like to thank Lena-M for reporting this
32 * issue (https://github.com/baerwolf/USBaspLoader/issues/1).
33 */
34 #include <avr/cpufunc.h>
35 #endif
36
37 #include <avr/boot.h>
38
39 #include <string.h>
40
41
42
43 static void leaveBootloader() __attribute__((__noreturn__));
44
45 #include "bootloaderconfig.h"
46 #include "usbdrv/usbdrv.c"
47
48 #ifndef BOOTLOADER_ADDRESS
49 #error need to know the bootloaders flash address!
50 #endif
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 /* defaults if not in config file: */
84 #ifndef HAVE_EEPROM_PAGED_ACCESS
85 # define HAVE_EEPROM_PAGED_ACCESS 0
86 #endif
87 #ifndef HAVE_EEPROM_BYTE_ACCESS
88 # define HAVE_EEPROM_BYTE_ACCESS 0
89 #endif
90 #ifndef BOOTLOADER_CAN_EXIT
91 # define BOOTLOADER_CAN_EXIT 0
92 #endif
93
94 /* allow compatibility with avrusbboot's bootloaderconfig.h: */
95 #ifdef BOOTLOADER_INIT
96 # define bootLoaderInit() BOOTLOADER_INIT
97 # define bootLoaderExit()
98 #endif
99 #ifdef BOOTLOADER_CONDITION
100 # define bootLoaderCondition() BOOTLOADER_CONDITION
101 #endif
102
103 /* device compatibility: */
104 #ifndef GICR /* ATMega*8 don't have GICR, use MCUCR instead */
105 # define GICR MCUCR
106 #endif
107
108 /* ------------------------------------------------------------------------ */
109
110 #if (FLASHEND) > 0xffff /* we need long addressing */
111 # define CURRENT_ADDRESS currentAddress.l
112 # define addr_t ulong
113 #else
114 # define CURRENT_ADDRESS currentAddress.w[0]
115 # define addr_t uint
116 #endif
117
118 typedef union longConverter{
119 addr_t l;
120 uint w[sizeof(addr_t)/2];
121 uchar b[sizeof(addr_t)];
122 }longConverter_t;
123
124
125 #if BOOTLOADER_CAN_EXIT
126 static uchar requestBootLoaderExit;
127 #endif
128 static volatile unsigned char stayinloader = 0xfe;
129
130 static longConverter_t currentAddress; /* in bytes */
131 static uchar bytesRemaining;
132 static uchar isLastPage;
133 #if HAVE_EEPROM_PAGED_ACCESS
134 static uchar currentRequest;
135 #else
136 static const uchar currentRequest = 0;
137 #endif
138
139 static const uchar signatureBytes[4] = {
140 #ifdef SIGNATURE_BYTES
141 SIGNATURE_BYTES
142 #elif defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega8HVA__)
143 0x1e, 0x93, 0x07, 0
144 #elif defined (__AVR_ATmega32__)
145 0x1e, 0x95, 0x02, 0
146 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__)
147 #error ATmega48 does not support bootloaders!
148 0x1e, 0x92, 0x05, 0
149 #elif defined (__AVR_ATmega48PA__)
150 #error ATmega48 does not support bootloaders!
151 0x1e, 0x92, 0x0A, 0
152 #elif defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__)
153 0x1e, 0x93, 0x0a, 0
154 #elif defined (__AVR_ATmega88PA__)
155 0x1e, 0x93, 0x0F, 0
156 #elif defined (__AVR_ATmega164A__)
157 0x1e, 0x94, 0x0f, 0
158 #elif defined (__AVR_ATmega164P__)
159 0x1e, 0x94, 0x0a, 0
160 #elif defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__)
161 0x1e, 0x94, 0x06, 0
162 #elif defined (__AVR_ATmega168PA__)
163 0x1e, 0x94, 0x0B, 0
164 #elif defined (__AVR_ATmega324A__)
165 0x1e, 0x95, 0x15, 0
166 #elif defined (__AVR_ATmega324P__)
167 0x1e, 0x95, 0x08, 0
168 #elif defined (__AVR_ATmega328__)
169 0x1e, 0x95, 0x14, 0
170 #elif defined (__AVR_ATmega328P__)
171 0x1e, 0x95, 0x0f, 0
172 #elif defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__)
173 0x1e, 0x96, 0x09, 0
174 #elif defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__)
175 0x1e, 0x96, 0x0a, 0
176 #elif defined (__AVR_ATmega128__)
177 0x1e, 0x97, 0x02, 0
178 #elif defined (__AVR_ATmega1284__)
179 0x1e, 0x97, 0x06, 0
180 #elif defined (__AVR_ATmega1284P__)
181 0x1e, 0x97, 0x05, 0
182 #else
183 # error "Device signature is not known, please edit main.c!"
184 #endif
185 };
186
187 /* ------------------------------------------------------------------------ */
188
189 static void (*nullVector)(void) __attribute__((__noreturn__));
190
191 static void leaveBootloader()
192 {
193 DBG1(0x01, 0, 0);
194 cli();
195 usbDeviceDisconnect();
196 bootLoaderExit();
197 USB_INTR_ENABLE = 0;
198 USB_INTR_CFG = 0; /* also reset config bits */
199 GICR = (1 << IVCE); /* enable change of interrupt vectors */
200 GICR = (0 << IVSEL); /* move interrupts to application flash section */
201
202 /* We must go through a global function pointer variable instead of writing
203 * ((void (*)(void))0)();
204 * because the compiler optimizes a constant 0 to "rcall 0" which is not
205 * handled correctly by the assembler.
206 */
207 nullVector();
208 }
209
210 /* ------------------------------------------------------------------------ */
211
212 uchar usbFunctionSetup(uchar data[8])
213 {
214 usbRequest_t *rq = (void *)data;
215 uchar len = 0;
216 static uchar replyBuffer[4];
217
218 usbMsgPtr = replyBuffer;
219 if(rq->bRequest == USBASP_FUNC_TRANSMIT){ /* emulate parts of ISP protocol */
220 uchar rval = 0;
221 usbWord_t address;
222 address.bytes[1] = rq->wValue.bytes[1];
223 address.bytes[0] = rq->wIndex.bytes[0];
224 if(rq->wValue.bytes[0] == 0x30){ /* read signature */
225 rval = rq->wIndex.bytes[0] & 3;
226 rval = signatureBytes[rval];
227 #if HAVE_READ_LOCK_FUSE
228 #if defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega32__)
229 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
230 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
231 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
232 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
233 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
234 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
235
236 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__) || defined (__AVR_ATmega48PA__) || \
237 defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__) || defined (__AVR_ATmega88PA__) || \
238 defined (__AVR_ATmega164A__) || defined (__AVR_ATmega164P__) || \
239 defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__) || defined (__AVR_ATmega168PA__) || \
240 defined (__AVR_ATmega324A__) || defined (__AVR_ATmega324P__) || \
241 defined (__AVR_ATmega328__) || defined (__AVR_ATmega328P__) || \
242 defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__) || defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__) || \
243 defined (__AVR_ATmega128__) || \
244 defined (__AVR_ATmega1284__) || defined (__AVR_ATmega1284P__)
245 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
246 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
247 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
248 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
249 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
250 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
251 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x08){ /* read efuse bits */
252 rval = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS );
253 #else
254 #warning "HAVE_READ_LOCK_FUSE is activated but MCU unknown -> will not support this feature"
255 #endif
256 #endif
257 #if HAVE_EEPROM_BYTE_ACCESS
258 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
259 rval = eeprom_read_byte((void *)address.word);
260 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
261 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
262 #endif
263 #if HAVE_CHIP_ERASE
264 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
265 addr_t addr;
266 for(addr = 0; addr < FLASHEND + 1 - 2048; addr += SPM_PAGESIZE) {
267 /* wait and erase page */
268 DBG1(0x33, 0, 0);
269 # ifndef NO_FLASH_WRITE
270 boot_spm_busy_wait();
271 cli();
272 boot_page_erase(addr);
273 sei();
274 # endif
275 }
276 #endif
277 }else{
278 /* ignore all others, return default value == 0 */
279 }
280 replyBuffer[3] = rval;
281 len = 4;
282 }else if((rq->bRequest == USBASP_FUNC_ENABLEPROG) || (rq->bRequest == USBASP_FUNC_SETISPSCK)){
283 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
284 len = 1;
285 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
286 currentAddress.w[0] = rq->wValue.word;
287 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
288 #if (FLASHEND) > 0xffff
289 currentAddress.w[1] = rq->wIndex.word;
290 #endif
291 }else{
292 bytesRemaining = rq->wLength.bytes[0];
293 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
294 isLastPage = rq->wIndex.bytes[1] & 0x02;
295 #if HAVE_EEPROM_PAGED_ACCESS
296 currentRequest = rq->bRequest;
297 #endif
298 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
299 }
300
301 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
302 stayinloader &= (0xfe);
303 #if BOOTLOADER_CAN_EXIT
304 requestBootLoaderExit = 1; /* allow proper shutdown/close of connection */
305 #endif
306 }else{
307 /* ignore: others, but could be USBASP_FUNC_CONNECT */
308 stayinloader |= (0x01);
309 }
310 return len;
311 }
312
313 uchar usbFunctionWrite(uchar *data, uchar len)
314 {
315 uchar isLast;
316
317 DBG1(0x31, (void *)&currentAddress.l, 4);
318 if(len > bytesRemaining)
319 len = bytesRemaining;
320 bytesRemaining -= len;
321 isLast = bytesRemaining == 0;
322 if(currentRequest >= USBASP_FUNC_READEEPROM){
323 uchar i;
324 for(i = 0; i < len; i++){
325 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
326 }
327 }else{
328 uchar i;
329 for(i = 0; i < len;){
330 #if HAVE_BLB11_SOFTW_LOCKBIT
331 if (CURRENT_ADDRESS >= (addr_t)(BOOTLOADER_ADDRESS)) {
332 return 1;
333 }
334 #endif
335 i += 2;
336 DBG1(0x32, 0, 0);
337 cli();
338 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
339 sei();
340 CURRENT_ADDRESS += 2;
341 data += 2;
342 /* write page when we cross page boundary or we have the last partial page */
343 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
344 #if !HAVE_CHIP_ERASE
345 DBG1(0x33, 0, 0);
346 # ifndef NO_FLASH_WRITE
347 cli();
348 boot_page_erase(CURRENT_ADDRESS - 2); /* erase page */
349 sei();
350 boot_spm_busy_wait(); /* wait until page is erased */
351 # endif
352 #endif
353 DBG1(0x34, 0, 0);
354 #ifndef NO_FLASH_WRITE
355 cli();
356 boot_page_write(CURRENT_ADDRESS - 2);
357 sei();
358 boot_spm_busy_wait();
359 cli();
360 boot_rww_enable();
361 sei();
362 #endif
363 }
364 }
365 DBG1(0x35, (void *)&currentAddress.l, 4);
366 }
367 return isLast;
368 }
369
370 uchar usbFunctionRead(uchar *data, uchar len)
371 {
372 uchar i;
373
374 if(len > bytesRemaining)
375 len = bytesRemaining;
376 bytesRemaining -= len;
377 for(i = 0; i < len; i++){
378 if(currentRequest >= USBASP_FUNC_READEEPROM){
379 *data = eeprom_read_byte((void *)currentAddress.w[0]);
380 }else{
381 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
382 }
383 data++;
384 CURRENT_ADDRESS++;
385 }
386 return len;
387 }
388
389 /* ------------------------------------------------------------------------ */
390
391 static void initForUsbConnectivity(void)
392 {
393 uchar i = 0;
394
395 usbInit();
396 /* enforce USB re-enumerate: */
397 usbDeviceDisconnect(); /* do this while interrupts are disabled */
398 while(--i){ /* fake USB disconnect for > 250 ms */
399 _delay_ms(1);
400 }
401 usbDeviceConnect();
402 sei();
403 }
404
405 int __attribute__((noreturn)) main(void)
406 {
407 /* initialize */
408 bootLoaderInit();
409 odDebugInit();
410 DBG1(0x00, 0, 0);
411 #ifndef NO_FLASH_WRITE
412 GICR = (1 << IVCE); /* enable change of interrupt vectors */
413 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
414 #endif
415 if(bootLoaderCondition()){
416 wdt_disable(); /* main app may have enabled watchdog */
417 #if BOOTLOADER_CAN_EXIT
418 uchar i = 0, j = 0;
419 #endif
420 initForUsbConnectivity();
421 do{
422 usbPoll();
423 #if BOOTLOADER_CAN_EXIT
424 if(requestBootLoaderExit){
425 if(--i == 0){
426 if(--j == 0)
427 break;
428 }
429 }
430 #endif
431 if (stayinloader >= 0x10) {
432 if (!bootLoaderCondition()) {
433 stayinloader-=0x10;
434 }
435 } else {
436 if (bootLoaderCondition()) {
437 if (stayinloader > 1) stayinloader-=2;
438 }
439 }
440
441 }while (stayinloader); /* main event loop */
442 }
443 leaveBootloader();
444 }
445
446 /* ------------------------------------------------------------------------ */