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