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