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