bd4eebf21a5992b2ce996b7a61753db34e5a2e3e
[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 = 1;
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 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
172 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
173 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
174 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
175 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
176 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
177 #endif
178 #if HAVE_EEPROM_BYTE_ACCESS
179 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
180 rval = eeprom_read_byte((void *)address.word);
181 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
182 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
183 #endif
184 #if HAVE_CHIP_ERASE
185 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
186 addr_t addr;
187 for(addr = 0; addr < FLASHEND + 1 - 2048; addr += SPM_PAGESIZE) {
188 /* wait and erase page */
189 DBG1(0x33, 0, 0);
190 # ifndef NO_FLASH_WRITE
191 boot_spm_busy_wait();
192 cli();
193 boot_page_erase(addr);
194 sei();
195 # endif
196 }
197 #endif
198 }else{
199 /* ignore all others, return default value == 0 */
200 }
201 replyBuffer[3] = rval;
202 len = 4;
203 }else if(rq->bRequest == USBASP_FUNC_ENABLEPROG){
204 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
205 len = 1;
206 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
207 currentAddress.w[0] = rq->wValue.word;
208 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
209 #if (FLASHEND) > 0xffff
210 currentAddress.w[1] = rq->wIndex.word;
211 #endif
212 }else{
213 bytesRemaining = rq->wLength.bytes[0];
214 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
215 isLastPage = rq->wIndex.bytes[1] & 0x02;
216 #if HAVE_EEPROM_PAGED_ACCESS
217 currentRequest = rq->bRequest;
218 #endif
219 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
220 }
221
222 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
223 stayinloader = 0;
224 #if BOOTLOADER_CAN_EXIT
225 requestBootLoaderExit = 1; /* allow proper shutdown/close of connection */
226 #endif
227 }else{
228 /* ignore: USBASP_FUNC_CONNECT */
229 }
230 return len;
231 }
232
233 uchar usbFunctionWrite(uchar *data, uchar len)
234 {
235 uchar isLast;
236
237 DBG1(0x31, (void *)&currentAddress.l, 4);
238 if(len > bytesRemaining)
239 len = bytesRemaining;
240 bytesRemaining -= len;
241 isLast = bytesRemaining == 0;
242 if(currentRequest >= USBASP_FUNC_READEEPROM){
243 uchar i;
244 for(i = 0; i < len; i++){
245 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
246 }
247 }else{
248 uchar i;
249 for(i = 0; i < len;){
250 #if !HAVE_CHIP_ERASE
251 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0){ /* if page start: erase */
252 DBG1(0x33, 0, 0);
253 # ifndef NO_FLASH_WRITE
254 # if HAVE_BLB11_SOFTW_LOCKBIT
255 if (CURRENT_ADDRESS < (addr_t)(BOOTLOADER_ADDRESS)) {
256 # endif
257 cli();
258 boot_page_erase(CURRENT_ADDRESS); /* erase page */
259 sei();
260 boot_spm_busy_wait(); /* wait until page is erased */
261 # if HAVE_BLB11_SOFTW_LOCKBIT
262 }
263 # endif
264 # endif
265 }
266 #endif
267 i += 2;
268 DBG1(0x32, 0, 0);
269 # if HAVE_BLB11_SOFTW_LOCKBIT
270 if (CURRENT_ADDRESS < (addr_t)(BOOTLOADER_ADDRESS)) {
271 # endif
272 cli();
273 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
274 sei();
275 # if HAVE_BLB11_SOFTW_LOCKBIT
276 }
277 # endif
278 CURRENT_ADDRESS += 2;
279 data += 2;
280 /* write page when we cross page boundary or we have the last partial page */
281 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
282 DBG1(0x34, 0, 0);
283 #ifndef NO_FLASH_WRITE
284 # if HAVE_BLB11_SOFTW_LOCKBIT
285 if ((CURRENT_ADDRESS - (addr_t)2) < (addr_t)(BOOTLOADER_ADDRESS)) {
286 # endif
287 cli();
288 boot_page_write(CURRENT_ADDRESS - 2);
289 sei();
290 boot_spm_busy_wait();
291 cli();
292 boot_rww_enable();
293 sei();
294 # if HAVE_BLB11_SOFTW_LOCKBIT
295 }
296 # endif
297 #endif
298 }
299 }
300 DBG1(0x35, (void *)&currentAddress.l, 4);
301 }
302 return isLast;
303 }
304
305 uchar usbFunctionRead(uchar *data, uchar len)
306 {
307 uchar i;
308
309 if(len > bytesRemaining)
310 len = bytesRemaining;
311 bytesRemaining -= len;
312 for(i = 0; i < len; i++){
313 if(currentRequest >= USBASP_FUNC_READEEPROM){
314 *data = eeprom_read_byte((void *)currentAddress.w[0]);
315 }else{
316 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
317 }
318 data++;
319 CURRENT_ADDRESS++;
320 }
321 return len;
322 }
323
324 /* ------------------------------------------------------------------------ */
325
326 static void initForUsbConnectivity(void)
327 {
328 uchar i = 0;
329
330 usbInit();
331 /* enforce USB re-enumerate: */
332 usbDeviceDisconnect(); /* do this while interrupts are disabled */
333 while(--i){ /* fake USB disconnect for > 250 ms */
334 wdt_reset();
335 _delay_ms(1);
336 }
337 usbDeviceConnect();
338 sei();
339 }
340
341 int __attribute__((noreturn)) main(void)
342 {
343 /* initialize */
344 wdt_disable(); /* main app may have enabled watchdog */
345 bootLoaderInit();
346 odDebugInit();
347 DBG1(0x00, 0, 0);
348 #ifndef NO_FLASH_WRITE
349 GICR = (1 << IVCE); /* enable change of interrupt vectors */
350 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
351 #endif
352 if(bootLoaderCondition()){
353 #if BOOTLOADER_CAN_EXIT
354 uchar i = 0, j = 0;
355 #endif
356 initForUsbConnectivity();
357 do{
358 usbPoll();
359 #if BOOTLOADER_CAN_EXIT
360 if(requestBootLoaderExit){
361 if(--i == 0){
362 if(--j == 0)
363 break;
364 }
365 }
366 #endif
367 }while ((stayinloader) || (!bootLoaderCondition())); /* main event loop */
368 }
369 leaveBootloader();
370 }
371
372 /* ------------------------------------------------------------------------ */