optimize: this changes logik from commit c99e4b0f4e8dc636060fca152df271298caa8342...
[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 const uchar signatureBytes[4] = {
115 #ifdef SIGNATURE_BYTES
116 SIGNATURE_BYTES
117 #elif defined (__AVR_ATmega8__) || defined (__AVR_ATmega8HVA__)
118 0x1e, 0x93, 0x07, 0
119 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48P__)
120 0x1e, 0x92, 0x05, 0
121 #elif defined (__AVR_ATmega88__) || defined (__AVR_ATmega88P__)
122 0x1e, 0x93, 0x0a, 0
123 #elif defined (__AVR_ATmega168__) || defined (__AVR_ATmega168P__)
124 0x1e, 0x94, 0x06, 0
125 #elif defined (__AVR_ATmega328P__)
126 0x1e, 0x95, 0x0f, 0
127 #else
128 # error "Device signature is not known, please edit main.c!"
129 #endif
130 };
131
132 /* ------------------------------------------------------------------------ */
133
134 static void (*nullVector)(void) __attribute__((__noreturn__));
135
136 static void leaveBootloader()
137 {
138 DBG1(0x01, 0, 0);
139 cli();
140 usbDeviceDisconnect();
141 bootLoaderExit();
142 USB_INTR_ENABLE = 0;
143 USB_INTR_CFG = 0; /* also reset config bits */
144 GICR = (1 << IVCE); /* enable change of interrupt vectors */
145 GICR = (0 << IVSEL); /* move interrupts to application flash section */
146
147 /* We must go through a global function pointer variable instead of writing
148 * ((void (*)(void))0)();
149 * because the compiler optimizes a constant 0 to "rcall 0" which is not
150 * handled correctly by the assembler.
151 */
152 nullVector();
153 }
154
155 /* ------------------------------------------------------------------------ */
156
157 uchar usbFunctionSetup(uchar data[8])
158 {
159 usbRequest_t *rq = (void *)data;
160 uchar len = 0;
161 static uchar replyBuffer[4];
162
163 usbMsgPtr = replyBuffer;
164 if(rq->bRequest == USBASP_FUNC_TRANSMIT){ /* emulate parts of ISP protocol */
165 uchar rval = 0;
166 usbWord_t address;
167 address.bytes[1] = rq->wValue.bytes[1];
168 address.bytes[0] = rq->wIndex.bytes[0];
169 if(rq->wValue.bytes[0] == 0x30){ /* read signature */
170 rval = rq->wIndex.bytes[0] & 3;
171 rval = signatureBytes[rval];
172 #if HAVE_READ_LOCK_FUSE
173 #if defined (__AVR_ATmega8__)
174 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
175 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
176 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
177 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
178 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
179 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
180 #endif
181 #endif
182 #if HAVE_EEPROM_BYTE_ACCESS
183 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
184 rval = eeprom_read_byte((void *)address.word);
185 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
186 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
187 #endif
188 #if HAVE_CHIP_ERASE
189 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
190 addr_t addr;
191 for(addr = 0; addr < FLASHEND + 1 - 2048; addr += SPM_PAGESIZE) {
192 /* wait and erase page */
193 DBG1(0x33, 0, 0);
194 # ifndef NO_FLASH_WRITE
195 boot_spm_busy_wait();
196 cli();
197 boot_page_erase(addr);
198 sei();
199 # endif
200 }
201 #endif
202 }else{
203 /* ignore all others, return default value == 0 */
204 }
205 replyBuffer[3] = rval;
206 len = 4;
207 }else if(rq->bRequest == USBASP_FUNC_ENABLEPROG){
208 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
209 len = 1;
210 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
211 currentAddress.w[0] = rq->wValue.word;
212 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
213 #if (FLASHEND) > 0xffff
214 currentAddress.w[1] = rq->wIndex.word;
215 #endif
216 }else{
217 bytesRemaining = rq->wLength.bytes[0];
218 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
219 isLastPage = rq->wIndex.bytes[1] & 0x02;
220 #if HAVE_EEPROM_PAGED_ACCESS
221 currentRequest = rq->bRequest;
222 #endif
223 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
224 }
225
226 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
227 stayinloader &= (0xfe);
228 #if BOOTLOADER_CAN_EXIT
229 requestBootLoaderExit = 1; /* allow proper shutdown/close of connection */
230 #endif
231 }else{
232 /* ignore: others, but could be USBASP_FUNC_CONNECT */
233 stayinloader |= (0x01);
234 }
235 return len;
236 }
237
238 uchar usbFunctionWrite(uchar *data, uchar len)
239 {
240 uchar isLast;
241
242 DBG1(0x31, (void *)&currentAddress.l, 4);
243 if(len > bytesRemaining)
244 len = bytesRemaining;
245 bytesRemaining -= len;
246 isLast = bytesRemaining == 0;
247 if(currentRequest >= USBASP_FUNC_READEEPROM){
248 uchar i;
249 for(i = 0; i < len; i++){
250 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
251 }
252 }else{
253 uchar i;
254 for(i = 0; i < len;){
255 #if HAVE_BLB11_SOFTW_LOCKBIT
256 if (CURRENT_ADDRESS >= (addr_t)(BOOTLOADER_ADDRESS)) {
257 }
258 #endif
259 i += 2;
260 DBG1(0x32, 0, 0);
261 cli();
262 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
263 sei();
264 CURRENT_ADDRESS += 2;
265 data += 2;
266 /* write page when we cross page boundary or we have the last partial page */
267 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
268 #if !HAVE_CHIP_ERASE
269 DBG1(0x33, 0, 0);
270 # ifndef NO_FLASH_WRITE
271 cli();
272 boot_page_erase(CURRENT_ADDRESS - 2); /* erase page */
273 sei();
274 boot_spm_busy_wait(); /* wait until page is erased */
275 # endif
276 #endif
277 DBG1(0x34, 0, 0);
278 #ifndef NO_FLASH_WRITE
279 cli();
280 boot_page_write(CURRENT_ADDRESS - 2);
281 sei();
282 boot_spm_busy_wait();
283 cli();
284 boot_rww_enable();
285 sei();
286 #endif
287 }
288 }
289 DBG1(0x35, (void *)&currentAddress.l, 4);
290 }
291 return isLast;
292 }
293
294 uchar usbFunctionRead(uchar *data, uchar len)
295 {
296 uchar i;
297
298 if(len > bytesRemaining)
299 len = bytesRemaining;
300 bytesRemaining -= len;
301 for(i = 0; i < len; i++){
302 if(currentRequest >= USBASP_FUNC_READEEPROM){
303 *data = eeprom_read_byte((void *)currentAddress.w[0]);
304 }else{
305 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
306 }
307 data++;
308 CURRENT_ADDRESS++;
309 }
310 return len;
311 }
312
313 /* ------------------------------------------------------------------------ */
314
315 static void initForUsbConnectivity(void)
316 {
317 uchar i = 0;
318
319 usbInit();
320 /* enforce USB re-enumerate: */
321 usbDeviceDisconnect(); /* do this while interrupts are disabled */
322 while(--i){ /* fake USB disconnect for > 250 ms */
323 _delay_ms(1);
324 }
325 usbDeviceConnect();
326 sei();
327 }
328
329 int __attribute__((noreturn)) main(void)
330 {
331 /* initialize */
332 bootLoaderInit();
333 odDebugInit();
334 DBG1(0x00, 0, 0);
335 #ifndef NO_FLASH_WRITE
336 GICR = (1 << IVCE); /* enable change of interrupt vectors */
337 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
338 #endif
339 if(bootLoaderCondition()){
340 wdt_disable(); /* main app may have enabled watchdog */
341 #if BOOTLOADER_CAN_EXIT
342 uchar i = 0, j = 0;
343 #endif
344 initForUsbConnectivity();
345 do{
346 usbPoll();
347 #if BOOTLOADER_CAN_EXIT
348 if(requestBootLoaderExit){
349 if(--i == 0){
350 if(--j == 0)
351 break;
352 }
353 }
354 #endif
355 if (stayinloader >= 0x10) {
356 if (!bootLoaderCondition()) {
357 stayinloader-=0x10;
358 }
359 } else {
360 if (bootLoaderCondition()) {
361 if (stayinloader > 1) stayinloader-=2;
362 }
363 }
364
365 }while (stayinloader); /* main event loop */
366 }
367 leaveBootloader();
368 }
369
370 /* ------------------------------------------------------------------------ */