bugfix bootloader exit logik
[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 <avr/io.h>
12 #include <avr/interrupt.h>
13 #include <avr/pgmspace.h>
14 #include <avr/wdt.h>
15 #include <avr/boot.h>
16 #include <avr/eeprom.h>
17 #include <util/delay.h>
18
19 #include <avr/cpufunc.h>
20
21 #include <string.h>
22
23
24
25 static void leaveBootloader() __attribute__((__noreturn__));
26
27 #include "bootloaderconfig.h"
28 #include "usbdrv/usbdrv.c"
29
30 #ifndef BOOTLOADER_ADDRESS
31 #error need to know the bootloaders flash address!
32 #endif
33
34 /* ------------------------------------------------------------------------ */
35
36 /* Request constants used by USBasp */
37 #define USBASP_FUNC_CONNECT 1
38 #define USBASP_FUNC_DISCONNECT 2
39 #define USBASP_FUNC_TRANSMIT 3
40 #define USBASP_FUNC_READFLASH 4
41 #define USBASP_FUNC_ENABLEPROG 5
42 #define USBASP_FUNC_WRITEFLASH 6
43 #define USBASP_FUNC_READEEPROM 7
44 #define USBASP_FUNC_WRITEEEPROM 8
45 #define USBASP_FUNC_SETLONGADDRESS 9
46
47 /* ------------------------------------------------------------------------ */
48
49 #ifndef ulong
50 # define ulong unsigned long
51 #endif
52 #ifndef uint
53 # define uint unsigned int
54 #endif
55
56 /* defaults if not in config file: */
57 #ifndef HAVE_EEPROM_PAGED_ACCESS
58 # define HAVE_EEPROM_PAGED_ACCESS 0
59 #endif
60 #ifndef HAVE_EEPROM_BYTE_ACCESS
61 # define HAVE_EEPROM_BYTE_ACCESS 0
62 #endif
63 #ifndef BOOTLOADER_CAN_EXIT
64 # define BOOTLOADER_CAN_EXIT 0
65 #endif
66
67 /* allow compatibility with avrusbboot's bootloaderconfig.h: */
68 #ifdef BOOTLOADER_INIT
69 # define bootLoaderInit() BOOTLOADER_INIT
70 # define bootLoaderExit()
71 #endif
72 #ifdef BOOTLOADER_CONDITION
73 # define bootLoaderCondition() BOOTLOADER_CONDITION
74 #endif
75
76 /* device compatibility: */
77 #ifndef GICR /* ATMega*8 don't have GICR, use MCUCR instead */
78 # define GICR MCUCR
79 #endif
80
81 /* ------------------------------------------------------------------------ */
82
83 #if (FLASHEND) > 0xffff /* we need long addressing */
84 # define CURRENT_ADDRESS currentAddress.l
85 # define addr_t ulong
86 #else
87 # define CURRENT_ADDRESS currentAddress.w[0]
88 # define addr_t uint
89 #endif
90
91 typedef union longConverter{
92 addr_t l;
93 uint w[sizeof(addr_t)/2];
94 uchar b[sizeof(addr_t)];
95 }longConverter_t;
96
97
98
99 #if BOOTLOADER_CAN_EXIT
100 static uchar requestBootLoaderExit;
101 #endif
102 static volatile unsigned char stayinloader = 0xfe;
103
104 static longConverter_t currentAddress; /* in bytes */
105 static uchar bytesRemaining;
106 static uchar isLastPage;
107 #if HAVE_EEPROM_PAGED_ACCESS
108 static uchar currentRequest;
109 #else
110 static const uchar currentRequest = 0;
111 #endif
112
113 static const uchar signatureBytes[4] = {
114 #ifdef SIGNATURE_BYTES
115 SIGNATURE_BYTES
116 #elif defined (__AVR_ATmega8__) || defined (__AVR_ATmega8HVA__)
117 0x1e, 0x93, 0x07, 0
118 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48P__)
119 0x1e, 0x92, 0x05, 0
120 #elif defined (__AVR_ATmega88__) || defined (__AVR_ATmega88P__)
121 0x1e, 0x93, 0x0a, 0
122 #elif defined (__AVR_ATmega168__) || defined (__AVR_ATmega168P__)
123 0x1e, 0x94, 0x06, 0
124 #elif defined (__AVR_ATmega328P__)
125 0x1e, 0x95, 0x0f, 0
126 #else
127 # error "Device signature is not known, please edit main.c!"
128 #endif
129 };
130
131 /* ------------------------------------------------------------------------ */
132
133 static void (*nullVector)(void) __attribute__((__noreturn__));
134
135 static void leaveBootloader()
136 {
137 DBG1(0x01, 0, 0);
138 cli();
139 usbDeviceDisconnect();
140 bootLoaderExit();
141 USB_INTR_ENABLE = 0;
142 USB_INTR_CFG = 0; /* also reset config bits */
143 GICR = (1 << IVCE); /* enable change of interrupt vectors */
144 GICR = (0 << IVSEL); /* move interrupts to application flash section */
145 /* We must go through a global function pointer variable instead of writing
146 * ((void (*)(void))0)();
147 * because the compiler optimizes a constant 0 to "rcall 0" which is not
148 * handled correctly by the assembler.
149 */
150 nullVector();
151 }
152
153 /* ------------------------------------------------------------------------ */
154
155 uchar usbFunctionSetup(uchar data[8])
156 {
157 usbRequest_t *rq = (void *)data;
158 uchar len = 0;
159 static uchar replyBuffer[4];
160
161 usbMsgPtr = replyBuffer;
162 if(rq->bRequest == USBASP_FUNC_TRANSMIT){ /* emulate parts of ISP protocol */
163 uchar rval = 0;
164 usbWord_t address;
165 address.bytes[1] = rq->wValue.bytes[1];
166 address.bytes[0] = rq->wIndex.bytes[0];
167 if(rq->wValue.bytes[0] == 0x30){ /* read signature */
168 rval = rq->wIndex.bytes[0] & 3;
169 rval = signatureBytes[rval];
170 #if HAVE_READ_LOCK_FUSE
171 #if defined (__AVR_ATmega8__)
172 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
173 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
174 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
175 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
176 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
177 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
178 #endif
179 #endif
180 #if HAVE_EEPROM_BYTE_ACCESS
181 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
182 rval = eeprom_read_byte((void *)address.word);
183 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
184 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
185 #endif
186 #if HAVE_CHIP_ERASE
187 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
188 addr_t addr;
189 for(addr = 0; addr < FLASHEND + 1 - 2048; addr += SPM_PAGESIZE) {
190 /* wait and erase page */
191 DBG1(0x33, 0, 0);
192 # ifndef NO_FLASH_WRITE
193 boot_spm_busy_wait();
194 cli();
195 boot_page_erase(addr);
196 sei();
197 # endif
198 }
199 #endif
200 }else{
201 /* ignore all others, return default value == 0 */
202 }
203 replyBuffer[3] = rval;
204 len = 4;
205 }else if(rq->bRequest == USBASP_FUNC_ENABLEPROG){
206 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
207 len = 1;
208 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
209 currentAddress.w[0] = rq->wValue.word;
210 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
211 #if (FLASHEND) > 0xffff
212 currentAddress.w[1] = rq->wIndex.word;
213 #endif
214 }else{
215 bytesRemaining = rq->wLength.bytes[0];
216 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
217 isLastPage = rq->wIndex.bytes[1] & 0x02;
218 #if HAVE_EEPROM_PAGED_ACCESS
219 currentRequest = rq->bRequest;
220 #endif
221 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
222 }
223
224 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
225 stayinloader &= (0xfe);
226 #if BOOTLOADER_CAN_EXIT
227 requestBootLoaderExit = 1; /* allow proper shutdown/close of connection */
228 #endif
229 }else if(rq->bRequest == USBASP_FUNC_CONNECT){
230 stayinloader |= (0x01);
231 }else{
232 /* ignore: others */
233 }
234 return len;
235 }
236
237 uchar usbFunctionWrite(uchar *data, uchar len)
238 {
239 uchar isLast;
240
241 DBG1(0x31, (void *)&currentAddress.l, 4);
242 if(len > bytesRemaining)
243 len = bytesRemaining;
244 bytesRemaining -= len;
245 isLast = bytesRemaining == 0;
246 if(currentRequest >= USBASP_FUNC_READEEPROM){
247 uchar i;
248 for(i = 0; i < len; i++){
249 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
250 }
251 }else{
252 uchar i;
253 for(i = 0; i < len;){
254 #if !HAVE_CHIP_ERASE
255 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0){ /* if page start: erase */
256 DBG1(0x33, 0, 0);
257 # ifndef NO_FLASH_WRITE
258 # if HAVE_BLB11_SOFTW_LOCKBIT
259 if (CURRENT_ADDRESS < (addr_t)(BOOTLOADER_ADDRESS)) {
260 # endif
261 cli();
262 boot_page_erase(CURRENT_ADDRESS); /* erase page */
263 sei();
264 boot_spm_busy_wait(); /* wait until page is erased */
265 # if HAVE_BLB11_SOFTW_LOCKBIT
266 }
267 # endif
268 # endif
269 }
270 #endif
271 i += 2;
272 DBG1(0x32, 0, 0);
273 # if HAVE_BLB11_SOFTW_LOCKBIT
274 if (CURRENT_ADDRESS < (addr_t)(BOOTLOADER_ADDRESS)) {
275 # endif
276 cli();
277 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
278 sei();
279 # if HAVE_BLB11_SOFTW_LOCKBIT
280 }
281 # endif
282 CURRENT_ADDRESS += 2;
283 data += 2;
284 /* write page when we cross page boundary or we have the last partial page */
285 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
286 DBG1(0x34, 0, 0);
287 #ifndef NO_FLASH_WRITE
288 # if HAVE_BLB11_SOFTW_LOCKBIT
289 if ((CURRENT_ADDRESS - (addr_t)2) < (addr_t)(BOOTLOADER_ADDRESS)) {
290 # endif
291 cli();
292 boot_page_write(CURRENT_ADDRESS - 2);
293 sei();
294 boot_spm_busy_wait();
295 cli();
296 boot_rww_enable();
297 sei();
298 # if HAVE_BLB11_SOFTW_LOCKBIT
299 }
300 # endif
301 #endif
302 }
303 }
304 DBG1(0x35, (void *)&currentAddress.l, 4);
305 }
306 return isLast;
307 }
308
309 uchar usbFunctionRead(uchar *data, uchar len)
310 {
311 uchar i;
312
313 if(len > bytesRemaining)
314 len = bytesRemaining;
315 bytesRemaining -= len;
316 for(i = 0; i < len; i++){
317 if(currentRequest >= USBASP_FUNC_READEEPROM){
318 *data = eeprom_read_byte((void *)currentAddress.w[0]);
319 }else{
320 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
321 }
322 data++;
323 CURRENT_ADDRESS++;
324 }
325 return len;
326 }
327
328 /* ------------------------------------------------------------------------ */
329
330 static void initForUsbConnectivity(void)
331 {
332 uchar i = 0;
333
334 usbInit();
335 /* enforce USB re-enumerate: */
336 usbDeviceDisconnect(); /* do this while interrupts are disabled */
337 while(--i){ /* fake USB disconnect for > 250 ms */
338 wdt_reset();
339 _delay_ms(1);
340 }
341 usbDeviceConnect();
342 sei();
343 }
344
345 int __attribute__((noreturn)) main(void)
346 {
347 /* initialize */
348 wdt_disable(); /* main app may have enabled watchdog */
349 bootLoaderInit();
350 odDebugInit();
351 DBG1(0x00, 0, 0);
352 #ifndef NO_FLASH_WRITE
353 GICR = (1 << IVCE); /* enable change of interrupt vectors */
354 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
355 #endif
356 if(bootLoaderCondition()){
357 #if BOOTLOADER_CAN_EXIT
358 uchar i = 0, j = 0;
359 #endif
360 initForUsbConnectivity();
361 do{
362 usbPoll();
363 #if BOOTLOADER_CAN_EXIT
364 if(requestBootLoaderExit){
365 if(--i == 0){
366 if(--j == 0)
367 break;
368 }
369 }
370 #endif
371 if (stayinloader > 0x04) {
372 if (!bootLoaderCondition()) {
373 stayinloader-=0x04;
374 }
375 } else {
376 if (bootLoaderCondition()) {
377 stayinloader &= 0x01;
378 }
379 }
380
381 }while (stayinloader); /* main event loop */
382 }
383 leaveBootloader();
384 }
385
386 /* ------------------------------------------------------------------------ */