optimize initForUsbConnectivity
[pub/USBaspLoader.git] / firmware / main.c
1 /* Name: main.c
2 * Project: USBaspLoader
3 * Author: Christian Starkjohann
4 * Author: Stephan Baerwolf
5 * Creation Date: 2007-12-08
6 * Modification Date: 2012-11-10
7 * Tabsize: 4
8 * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
9 * License: GNU GPL v2 (see License.txt)
10 * This Revision: $Id: main.c 786 2010-05-30 20:41:40Z cs $
11 */
12
13 #include "spminterface.h" /* must be included as first! */
14
15 #include <avr/io.h>
16 #include <avr/interrupt.h>
17 #include <avr/pgmspace.h>
18 #include <avr/wdt.h>
19 #include <avr/boot.h>
20 #include <avr/eeprom.h>
21 #include <util/delay.h>
22
23
24 #if 0
25 /*
26 * 29.09.2012 / 30.09.2012
27 *
28 * Since cpufunc.h is not needed in this context and
29 * since it is not available in all toolchains, this include
30 * becomes deactivated by github issue-report.
31 * (In case of trouble it remains in sourcecode for reactivation.)
32 *
33 * The autor would like to thank Lena-M for reporting this
34 * issue (https://github.com/baerwolf/USBaspLoader/issues/1).
35 */
36 #include <avr/cpufunc.h>
37 #endif
38
39 #include <avr/boot.h>
40
41 #include <string.h>
42
43
44 #include "bootloaderconfig.h"
45 #include "usbdrv/usbdrv.c"
46
47 #if BOOTLOADER_CAN_EXIT
48 static void leaveBootloader() __attribute__((__noreturn__));
49 #endif
50
51 #ifndef BOOTLOADER_ADDRESS
52 #error need to know the bootloaders flash address!
53 #endif
54
55 /* ------------------------------------------------------------------------ */
56
57 /* Request constants used by USBasp */
58 #define USBASP_FUNC_CONNECT 1
59 #define USBASP_FUNC_DISCONNECT 2
60 #define USBASP_FUNC_TRANSMIT 3
61 #define USBASP_FUNC_READFLASH 4
62 #define USBASP_FUNC_ENABLEPROG 5
63 #define USBASP_FUNC_WRITEFLASH 6
64 #define USBASP_FUNC_READEEPROM 7
65 #define USBASP_FUNC_WRITEEEPROM 8
66 #define USBASP_FUNC_SETLONGADDRESS 9
67
68 // additional USBasp Commands
69 #define USBASP_FUNC_SETISPSCK 10
70 #define USBASP_FUNC_TPI_CONNECT 11
71 #define USBASP_FUNC_TPI_DISCONNECT 12
72 #define USBASP_FUNC_TPI_RAWREAD 13
73 #define USBASP_FUNC_TPI_RAWWRITE 14
74 #define USBASP_FUNC_TPI_READBLOCK 15
75 #define USBASP_FUNC_TPI_WRITEBLOCK 16
76 #define USBASP_FUNC_GETCAPABILITIES 127
77 /* ------------------------------------------------------------------------ */
78
79 #ifndef ulong
80 # define ulong unsigned long
81 #endif
82 #ifndef uint
83 # define uint unsigned int
84 #endif
85
86
87 /* allow compatibility with avrusbboot's bootloaderconfig.h: */
88 #ifdef BOOTLOADER_INIT
89 # define bootLoaderInit() BOOTLOADER_INIT
90 # define bootLoaderExit()
91 #endif
92 #ifdef BOOTLOADER_CONDITION
93 # define bootLoaderCondition() BOOTLOADER_CONDITION
94 #endif
95
96 /* device compatibility: */
97 #ifndef GICR /* ATMega*8 don't have GICR, use MCUCR instead */
98 # define GICR MCUCR
99 #endif
100
101 /* ------------------------------------------------------------------------ */
102
103 #if (FLASHEND) > 0xffff /* we need long addressing */
104 # define CURRENT_ADDRESS currentAddress.l
105 # define addr_t ulong
106 #else
107 # define CURRENT_ADDRESS currentAddress.w[0]
108 # define addr_t uint
109 #endif
110
111 typedef union longConverter{
112 addr_t l;
113 uint w[sizeof(addr_t)/2];
114 uchar b[sizeof(addr_t)];
115 }longConverter_t;
116
117
118 #if BOOTLOADER_CAN_EXIT
119 static volatile unsigned char stayinloader = 0xfe;
120 #endif
121
122 static longConverter_t currentAddress; /* in bytes */
123 static uchar bytesRemaining;
124 static uchar isLastPage;
125 #if HAVE_EEPROM_PAGED_ACCESS
126 static uchar currentRequest;
127 #else
128 static const uchar currentRequest = 0;
129 #endif
130
131 static const uchar signatureBytes[4] = {
132 #ifdef SIGNATURE_BYTES
133 SIGNATURE_BYTES
134 #elif defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega8HVA__)
135 0x1e, 0x93, 0x07, 0
136 #elif defined (__AVR_ATmega32__)
137 0x1e, 0x95, 0x02, 0
138 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__)
139 #error ATmega48 does not support bootloaders!
140 0x1e, 0x92, 0x05, 0
141 #elif defined (__AVR_ATmega48PA__)
142 #error ATmega48 does not support bootloaders!
143 0x1e, 0x92, 0x0A, 0
144 #elif defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__)
145 0x1e, 0x93, 0x0a, 0
146 #elif defined (__AVR_ATmega88PA__)
147 0x1e, 0x93, 0x0F, 0
148 #elif defined (__AVR_ATmega164A__)
149 0x1e, 0x94, 0x0f, 0
150 #elif defined (__AVR_ATmega164P__)
151 0x1e, 0x94, 0x0a, 0
152 #elif defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__)
153 0x1e, 0x94, 0x06, 0
154 #elif defined (__AVR_ATmega168PA__)
155 0x1e, 0x94, 0x0B, 0
156 #elif defined (__AVR_ATmega324A__)
157 0x1e, 0x95, 0x15, 0
158 #elif defined (__AVR_ATmega324P__)
159 0x1e, 0x95, 0x08, 0
160 #elif defined (__AVR_ATmega328__)
161 0x1e, 0x95, 0x14, 0
162 #elif defined (__AVR_ATmega328P__)
163 0x1e, 0x95, 0x0f, 0
164 #elif defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__)
165 0x1e, 0x96, 0x09, 0
166 #elif defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__)
167 0x1e, 0x96, 0x0a, 0
168 #elif defined (__AVR_ATmega128__)
169 0x1e, 0x97, 0x02, 0
170 #elif defined (__AVR_ATmega1284__)
171 0x1e, 0x97, 0x06, 0
172 #elif defined (__AVR_ATmega1284P__)
173 0x1e, 0x97, 0x05, 0
174 #else
175 # error "Device signature is not known, please edit main.c!"
176 #endif
177 };
178
179 /* ------------------------------------------------------------------------ */
180
181 #if BOOTLOADER_CAN_EXIT
182 static void (*nullVector)(void) __attribute__((__noreturn__));
183
184 static void leaveBootloader()
185 {
186 DBG1(0x01, 0, 0);
187 cli();
188 usbDeviceDisconnect();
189 bootLoaderExit();
190 USB_INTR_ENABLE = 0;
191 USB_INTR_CFG = 0; /* also reset config bits */
192 GICR = (1 << IVCE); /* enable change of interrupt vectors */
193 GICR = (0 << IVSEL); /* move interrupts to application flash section */
194
195 /* We must go through a global function pointer variable instead of writing
196 * ((void (*)(void))0)();
197 * because the compiler optimizes a constant 0 to "rcall 0" which is not
198 * handled correctly by the assembler.
199 */
200 nullVector();
201 }
202 #endif
203
204 /* ------------------------------------------------------------------------ */
205
206 uchar usbFunctionSetup(uchar data[8])
207 {
208 usbRequest_t *rq = (void *)data;
209 uchar len = 0;
210 static uchar replyBuffer[4];
211
212 usbMsgPtr = replyBuffer;
213 if(rq->bRequest == USBASP_FUNC_TRANSMIT){ /* emulate parts of ISP protocol */
214 uchar rval = 0;
215 usbWord_t address;
216 address.bytes[1] = rq->wValue.bytes[1];
217 address.bytes[0] = rq->wIndex.bytes[0];
218 if(rq->wValue.bytes[0] == 0x30){ /* read signature */
219 rval = rq->wIndex.bytes[0] & 3;
220 rval = signatureBytes[rval];
221 #if HAVE_READ_LOCK_FUSE
222 #if defined (__AVR_ATmega8__) || defined (__AVR_ATmega8A__) || defined (__AVR_ATmega32__)
223 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
224 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
225 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
226 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
227 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
228 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
229
230 #elif defined (__AVR_ATmega48__) || defined (__AVR_ATmega48A__) || defined (__AVR_ATmega48P__) || defined (__AVR_ATmega48PA__) || \
231 defined (__AVR_ATmega88__) || defined (__AVR_ATmega88A__) || defined (__AVR_ATmega88P__) || defined (__AVR_ATmega88PA__) || \
232 defined (__AVR_ATmega164A__) || defined (__AVR_ATmega164P__) || \
233 defined (__AVR_ATmega168__) || defined (__AVR_ATmega168A__) || defined (__AVR_ATmega168P__) || defined (__AVR_ATmega168PA__) || \
234 defined (__AVR_ATmega324A__) || defined (__AVR_ATmega324P__) || \
235 defined (__AVR_ATmega328__) || defined (__AVR_ATmega328P__) || \
236 defined (__AVR_ATmega644__) || defined (__AVR_ATmega644A__) || defined (__AVR_ATmega644P__) || defined (__AVR_ATmega644PA__) || \
237 defined (__AVR_ATmega128__) || \
238 defined (__AVR_ATmega1284__) || defined (__AVR_ATmega1284P__)
239 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x00){ /* read lock bits */
240 rval = boot_lock_fuse_bits_get(GET_LOCK_BITS);
241 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x00){ /* read lfuse bits */
242 rval = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
243 }else if(rq->wValue.bytes[0] == 0x58 && rq->wValue.bytes[1] == 0x08){ /* read hfuse bits */
244 rval = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
245 }else if(rq->wValue.bytes[0] == 0x50 && rq->wValue.bytes[1] == 0x08){ /* read efuse bits */
246 rval = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS );
247 #else
248 #warning "HAVE_READ_LOCK_FUSE is activated but MCU unknown -> will not support this feature"
249 #endif
250 #endif
251 #if HAVE_EEPROM_BYTE_ACCESS
252 }else if(rq->wValue.bytes[0] == 0xa0){ /* read EEPROM byte */
253 rval = eeprom_read_byte((void *)address.word);
254 }else if(rq->wValue.bytes[0] == 0xc0){ /* write EEPROM byte */
255 eeprom_write_byte((void *)address.word, rq->wIndex.bytes[1]);
256 #endif
257 #if HAVE_CHIP_ERASE
258 }else if(rq->wValue.bytes[0] == 0xac && rq->wValue.bytes[1] == 0x80){ /* chip erase */
259 addr_t addr;
260 for(addr = 0; addr < FLASHEND + 1 - 2048; addr += SPM_PAGESIZE) {
261 /* wait and erase page */
262 DBG1(0x33, 0, 0);
263 # ifndef NO_FLASH_WRITE
264 boot_spm_busy_wait();
265 cli();
266 boot_page_erase(addr);
267 sei();
268 # endif
269 }
270 #endif
271 }else{
272 /* ignore all others, return default value == 0 */
273 }
274 replyBuffer[3] = rval;
275 len = 4;
276 }else if((rq->bRequest == USBASP_FUNC_ENABLEPROG) || (rq->bRequest == USBASP_FUNC_SETISPSCK)){
277 /* replyBuffer[0] = 0; is never touched and thus always 0 which means success */
278 len = 1;
279 }else if(rq->bRequest >= USBASP_FUNC_READFLASH && rq->bRequest <= USBASP_FUNC_SETLONGADDRESS){
280 currentAddress.w[0] = rq->wValue.word;
281 if(rq->bRequest == USBASP_FUNC_SETLONGADDRESS){
282 #if (FLASHEND) > 0xffff
283 currentAddress.w[1] = rq->wIndex.word;
284 #endif
285 }else{
286 bytesRemaining = rq->wLength.bytes[0];
287 /* if(rq->bRequest == USBASP_FUNC_WRITEFLASH) only evaluated during writeFlash anyway */
288 isLastPage = rq->wIndex.bytes[1] & 0x02;
289 #if HAVE_EEPROM_PAGED_ACCESS
290 currentRequest = rq->bRequest;
291 #endif
292 len = 0xff; /* hand over to usbFunctionRead() / usbFunctionWrite() */
293 }
294
295 }else if(rq->bRequest == USBASP_FUNC_DISCONNECT){
296
297 #if BOOTLOADER_CAN_EXIT
298 stayinloader &= (0xfe);
299 #endif
300 }else{
301 /* ignore: others, but could be USBASP_FUNC_CONNECT */
302 #if BOOTLOADER_CAN_EXIT
303 stayinloader |= (0x01);
304 #endif
305 }
306 return len;
307 }
308
309 uchar usbFunctionWrite(uchar *data, uchar len)
310 {
311 uchar isLast;
312
313 DBG1(0x31, (void *)&currentAddress.l, 4);
314 if(len > bytesRemaining)
315 len = bytesRemaining;
316 bytesRemaining -= len;
317 isLast = bytesRemaining == 0;
318 if(currentRequest >= USBASP_FUNC_READEEPROM){
319 uchar i;
320 for(i = 0; i < len; i++){
321 eeprom_write_byte((void *)(currentAddress.w[0]++), *data++);
322 }
323 }else{
324 uchar i;
325 for(i = 0; i < len;){
326 #if HAVE_BLB11_SOFTW_LOCKBIT
327 if (CURRENT_ADDRESS >= (addr_t)(BOOTLOADER_ADDRESS)) {
328 return 1;
329 }
330 #endif
331 i += 2;
332 DBG1(0x32, 0, 0);
333 cli();
334 boot_page_fill(CURRENT_ADDRESS, *(short *)data);
335 sei();
336 CURRENT_ADDRESS += 2;
337 data += 2;
338 /* write page when we cross page boundary or we have the last partial page */
339 if((currentAddress.w[0] & (SPM_PAGESIZE - 1)) == 0 || (isLast && i >= len && isLastPage)){
340 #if !HAVE_CHIP_ERASE
341 DBG1(0x33, 0, 0);
342 # ifndef NO_FLASH_WRITE
343 cli();
344 boot_page_erase(CURRENT_ADDRESS - 2); /* erase page */
345 sei();
346 boot_spm_busy_wait(); /* wait until page is erased */
347 # endif
348 #endif
349 DBG1(0x34, 0, 0);
350 #ifndef NO_FLASH_WRITE
351 cli();
352 boot_page_write(CURRENT_ADDRESS - 2);
353 sei();
354 boot_spm_busy_wait();
355 cli();
356 boot_rww_enable();
357 sei();
358 #endif
359 }
360 }
361 DBG1(0x35, (void *)&currentAddress.l, 4);
362 }
363 return isLast;
364 }
365
366 uchar usbFunctionRead(uchar *data, uchar len)
367 {
368 uchar i;
369
370 if(len > bytesRemaining)
371 len = bytesRemaining;
372 bytesRemaining -= len;
373 for(i = 0; i < len; i++){
374 if(currentRequest >= USBASP_FUNC_READEEPROM){
375 *data = eeprom_read_byte((void *)currentAddress.w[0]);
376 }else{
377 *data = pgm_read_byte((void *)CURRENT_ADDRESS);
378 }
379 data++;
380 CURRENT_ADDRESS++;
381 }
382 return len;
383 }
384
385 /* ------------------------------------------------------------------------ */
386
387 static void initForUsbConnectivity(void)
388 {
389 usbInit();
390 /* enforce USB re-enumerate: */
391 usbDeviceDisconnect(); /* do this while interrupts are disabled */
392 _delay_ms(260); /* fake USB disconnect for > 250 ms */
393 usbDeviceConnect();
394 sei();
395 }
396
397 int __attribute__((noreturn)) main(void)
398 {
399 /* initialize */
400 bootLoaderInit();
401 odDebugInit();
402 DBG1(0x00, 0, 0);
403 #ifndef NO_FLASH_WRITE
404 GICR = (1 << IVCE); /* enable change of interrupt vectors */
405 GICR = (1 << IVSEL); /* move interrupts to boot flash section */
406 #endif
407 if(bootLoaderCondition()){
408 #if NEED_WATCHDOG
409 wdt_disable(); /* main app may have enabled watchdog */
410 #endif
411 initForUsbConnectivity();
412 do{
413 usbPoll();
414 #if BOOTLOADER_CAN_EXIT
415 if (stayinloader >= 0x10) {
416 if (!bootLoaderCondition()) {
417 stayinloader-=0x10;
418 }
419 } else {
420 if (bootLoaderCondition()) {
421 if (stayinloader > 1) stayinloader-=2;
422 }
423 }
424 #endif
425
426 #if BOOTLOADER_CAN_EXIT
427 }while (stayinloader); /* main event loop, if BOOTLOADER_CAN_EXIT*/
428 #else
429 }while (1); /* main event loop */
430 #endif
431 }
432 #if BOOTLOADER_CAN_EXIT
433 leaveBootloader();
434 #endif
435 }
436
437 /* ------------------------------------------------------------------------ */