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