optimize: ah, found another 4 bytes to save
[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{
230 /* ignore: others, but could be USBASP_FUNC_CONNECT */
231 stayinloader |= (0x01);
232 }
233 return len;
234 }
235
236 uchar usbFunctionWrite(uchar *data, uchar len)
237 {
238 uchar isLast;
239
240 DBG1(0x31, (void *)&currentAddress.l, 4);
241 if(len > bytesRemaining)
242 len = bytesRemaining;
243 bytesRemaining -= len;
244 isLast = bytesRemaining == 0;
245 if(currentRequest >= USBASP_FUNC_READEEPROM){
246 uchar i;
247 for(i = 0; i < len; i++){
248 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
249 }
250 }else{
251 uchar i;
252 for(i = 0; i < len;){
253 #if HAVE_BLB11_SOFTW_LOCKBIT
254 uint8_t allowWrite = (CURRENT_ADDRESS < (addr_t)(BOOTLOADER_ADDRESS));
255 #if HAVE_BLB11_SOFTW_BACKDOOR
256 if ((stayinloader >= 0x10) && (bootLoaderCondition())) allowWrite=1;
257 #endif
258 #endif
259 #if !HAVE_CHIP_ERASE
260 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0){ /* if page start: erase */
261 DBG1(0x33, 0, 0);
262 # ifndef NO_FLASH_WRITE
263 # if HAVE_BLB11_SOFTW_LOCKBIT
264 if (allowWrite) {
265 # endif
266 cli();
267 boot_page_erase(CURRENT_ADDRESS); /* erase page */
268 sei();
269 boot_spm_busy_wait(); /* wait until page is erased */
270 # if HAVE_BLB11_SOFTW_LOCKBIT
271 }
272 # endif
273 # endif
274 }
275 #endif
276 i += 2;
277 DBG1(0x32, 0, 0);
278 # if HAVE_BLB11_SOFTW_LOCKBIT
279 if (allowWrite) {
280 # endif
281 cli();
282 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
283 sei();
284 # if HAVE_BLB11_SOFTW_LOCKBIT
285 }
286 # endif
287 CURRENT_ADDRESS += 2;
288 data += 2;
289 /* write page when we cross page boundary or we have the last partial page */
290 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
291 DBG1(0x34, 0, 0);
292 #ifndef NO_FLASH_WRITE
293 # if HAVE_BLB11_SOFTW_LOCKBIT
294 if (allowWrite) {
295 # endif
296 cli();
297 boot_page_write(CURRENT_ADDRESS - 2);
298 sei();
299 boot_spm_busy_wait();
300 cli();
301 boot_rww_enable();
302 sei();
303 # if HAVE_BLB11_SOFTW_LOCKBIT
304 }
305 # endif
306 #endif
307 }
308 }
309 DBG1(0x35, (void *)&currentAddress.l, 4);
310 }
311 return isLast;
312 }
313
314 uchar usbFunctionRead(uchar *data, uchar len)
315 {
316 uchar i;
317
318 if(len > bytesRemaining)
319 len = bytesRemaining;
320 bytesRemaining -= len;
321 for(i = 0; i < len; i++){
322 if(currentRequest >= USBASP_FUNC_READEEPROM){
323 *data = eeprom_read_byte((void *)currentAddress.w[0]);
324 }else{
325 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
326 }
327 data++;
328 CURRENT_ADDRESS++;
329 }
330 return len;
331 }
332
333 /* ------------------------------------------------------------------------ */
334
335 static void initForUsbConnectivity(void)
336 {
337 uchar i = 0;
338
339 usbInit();
340 /* enforce USB re-enumerate: */
341 usbDeviceDisconnect(); /* do this while interrupts are disabled */
342 while(--i){ /* fake USB disconnect for > 250 ms */
343 _delay_ms(1);
344 }
345 usbDeviceConnect();
346 sei();
347 }
348
349 int __attribute__((noreturn)) main(void)
350 {
351 /* initialize */
352 wdt_disable(); /* main app may have enabled watchdog */
353 bootLoaderInit();
354 odDebugInit();
355 DBG1(0x00, 0, 0);
356 #ifndef NO_FLASH_WRITE
357 GICR = (1 << IVCE); /* enable change of interrupt vectors */
358 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
359 #endif
360 if(bootLoaderCondition()){
361 #if BOOTLOADER_CAN_EXIT
362 uchar i = 0, j = 0;
363 #endif
364 initForUsbConnectivity();
365 do{
366 usbPoll();
367 #if BOOTLOADER_CAN_EXIT
368 if(requestBootLoaderExit){
369 if(--i == 0){
370 if(--j == 0)
371 break;
372 }
373 }
374 #endif
375 if (stayinloader >= 0x10) {
376 if (!bootLoaderCondition()) {
377 stayinloader-=0x10;
378 }
379 } else {
380 if (bootLoaderCondition()) {
381 if (stayinloader > 1) stayinloader-=2;
382 }
383 }
384
385 }while (stayinloader); /* main event loop */
386 }
387 leaveBootloader();
388 }
389
390 /* ------------------------------------------------------------------------ */