optiboot.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. #define FUNC_READ 1
  2. #define FUNC_WRITE 1
  3. /**********************************************************/
  4. /* Optiboot bootloader for Arduino */
  5. /* */
  6. /* http://optiboot.googlecode.com */
  7. /* */
  8. /* Arduino-maintained version : See README.TXT */
  9. /* http://code.google.com/p/arduino/ */
  10. /* It is the intent that changes not relevant to the */
  11. /* Arduino production envionment get moved from the */
  12. /* optiboot project to the arduino project in "lumps." */
  13. /* */
  14. /* Heavily optimised bootloader that is faster and */
  15. /* smaller than the Arduino standard bootloader */
  16. /* */
  17. /* Enhancements: */
  18. /* Fits in 512 bytes, saving 1.5K of code space */
  19. /* Higher baud rate speeds up programming */
  20. /* Written almost entirely in C */
  21. /* Customisable timeout with accurate timeconstant */
  22. /* Optional virtual UART. No hardware UART required. */
  23. /* Optional virtual boot partition for devices without. */
  24. /* */
  25. /* What you lose: */
  26. /* Implements a skeleton STK500 protocol which is */
  27. /* missing several features including EEPROM */
  28. /* programming and non-page-aligned writes */
  29. /* High baud rate breaks compatibility with standard */
  30. /* Arduino flash settings */
  31. /* */
  32. /* Fully supported: */
  33. /* ATmega168 based devices (Diecimila etc) */
  34. /* ATmega328P based devices (Duemilanove etc) */
  35. /* */
  36. /* Beta test (believed working.) */
  37. /* ATmega8 based devices (Arduino legacy) */
  38. /* ATmega328 non-picopower devices */
  39. /* ATmega644P based devices (Sanguino) */
  40. /* ATmega1284P based devices */
  41. /* ATmega1280 based devices (Arduino Mega) */
  42. /* */
  43. /* Alpha test */
  44. /* ATmega32 */
  45. /* */
  46. /* Work in progress: */
  47. /* ATtiny84 based devices (Luminet) */
  48. /* */
  49. /* Does not support: */
  50. /* USB based devices (eg. Teensy, Leonardo) */
  51. /* */
  52. /* Assumptions: */
  53. /* The code makes several assumptions that reduce the */
  54. /* code size. They are all true after a hardware reset, */
  55. /* but may not be true if the bootloader is called by */
  56. /* other means or on other hardware. */
  57. /* No interrupts can occur */
  58. /* UART and Timer 1 are set to their reset state */
  59. /* SP points to RAMEND */
  60. /* */
  61. /* Code builds on code, libraries and optimisations from: */
  62. /* stk500boot.c by Jason P. Kyle */
  63. /* Arduino bootloader http://arduino.cc */
  64. /* Spiff's 1K bootloader http://spiffie.org/know/arduino_1k_bootloader/bootloader.shtml */
  65. /* avr-libc project http://nongnu.org/avr-libc */
  66. /* Adaboot http://www.ladyada.net/library/arduino/bootloader.html */
  67. /* AVR305 Atmel Application Note */
  68. /* */
  69. /* Copyright 2013-2015 by Bill Westfield. */
  70. /* Copyright 2010 by Peter Knight. */
  71. /* */
  72. /* This program is free software; you can redistribute it */
  73. /* and/or modify it under the terms of the GNU General */
  74. /* Public License as published by the Free Software */
  75. /* Foundation; either version 2 of the License, or */
  76. /* (at your option) any later version. */
  77. /* */
  78. /* This program is distributed in the hope that it will */
  79. /* be useful, but WITHOUT ANY WARRANTY; without even the */
  80. /* implied warranty of MERCHANTABILITY or FITNESS FOR A */
  81. /* PARTICULAR PURPOSE. See the GNU General Public */
  82. /* License for more details. */
  83. /* */
  84. /* You should have received a copy of the GNU General */
  85. /* Public License along with this program; if not, write */
  86. /* to the Free Software Foundation, Inc., */
  87. /* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
  88. /* */
  89. /* Licence can be viewed at */
  90. /* http://www.fsf.org/licenses/gpl.txt */
  91. /* */
  92. /**********************************************************/
  93. /**********************************************************/
  94. /* */
  95. /* Optional defines: */
  96. /* */
  97. /**********************************************************/
  98. /* */
  99. /* BIGBOOT: */
  100. /* Build a 1k bootloader, not 512 bytes. This turns on */
  101. /* extra functionality. */
  102. /* */
  103. /* BAUD_RATE: */
  104. /* Set bootloader baud rate. */
  105. /* */
  106. /* SOFT_UART: */
  107. /* Use AVR305 soft-UART instead of hardware UART. */
  108. /* */
  109. /* LED_START_FLASHES: */
  110. /* Number of LED flashes on bootup. */
  111. /* */
  112. /* LED_DATA_FLASH: */
  113. /* Flash LED when transferring data. For boards without */
  114. /* TX or RX LEDs, or for people who like blinky lights. */
  115. /* */
  116. /* SUPPORT_EEPROM: */
  117. /* Support reading and writing from EEPROM. This is not */
  118. /* used by Arduino, so off by default. */
  119. /* */
  120. /* TIMEOUT_MS: */
  121. /* Bootloader timeout period, in milliseconds. */
  122. /* 500,1000,2000,4000,8000 supported. */
  123. /* */
  124. /* UART: */
  125. /* UART number (0..n) for devices with more than */
  126. /* one hardware uart (644P, 1284P, etc) */
  127. /* */
  128. /**********************************************************/
  129. /**********************************************************/
  130. /* Version Numbers! */
  131. /* */
  132. /* Arduino Optiboot now includes this Version number in */
  133. /* the source and object code. */
  134. /* */
  135. /* Version 3 was released as zip from the optiboot */
  136. /* repository and was distributed with Arduino 0022. */
  137. /* Version 4 starts with the arduino repository commit */
  138. /* that brought the arduino repository up-to-date with */
  139. /* the optiboot source tree changes since v3. */
  140. /* Version 5 was created at the time of the new Makefile */
  141. /* structure (Mar, 2013), even though no binaries changed*/
  142. /* It would be good if versions implemented outside the */
  143. /* official repository used an out-of-seqeunce version */
  144. /* number (like 104.6 if based on based on 4.5) to */
  145. /* prevent collisions. */
  146. /* */
  147. /**********************************************************/
  148. /**********************************************************/
  149. /* Edit History: */
  150. /* */
  151. /* Aug 2014 */
  152. /* 6.2 WestfW: make size of length variables dependent */
  153. /* on the SPM_PAGESIZE. This saves space */
  154. /* on the chips where it's most important. */
  155. /* 6.1 WestfW: Fix OPTIBOOT_CUSTOMVER (send it!) */
  156. /* Make no-wait mod less picky about */
  157. /* skipping the bootloader. */
  158. /* Remove some dead code */
  159. /* Jun 2014 */
  160. /* 6.0 WestfW: Modularize memory read/write functions */
  161. /* Remove serial/flash overlap */
  162. /* (and all references to NRWWSTART/etc) */
  163. /* Correctly handle pagesize > 255bytes */
  164. /* Add EEPROM support in BIGBOOT (1284) */
  165. /* EEPROM write on small chips now causes err */
  166. /* Split Makefile into smaller pieces */
  167. /* Add Wicked devices Wildfire */
  168. /* Move UART=n conditionals into pin_defs.h */
  169. /* Remove LUDICOUS_SPEED option */
  170. /* Replace inline assembler for .version */
  171. /* and add OPTIBOOT_CUSTOMVER for user code */
  172. /* Fix LED value for Bobuino (Makefile) */
  173. /* Make all functions explicitly inline or */
  174. /* noinline, so we fit when using gcc4.8 */
  175. /* Change optimization options for gcc4.8 */
  176. /* Make ENV=arduino work in 1.5.x trees. */
  177. /* May 2014 */
  178. /* 5.0 WestfW: Add support for 1Mbps UART */
  179. /* Mar 2013 */
  180. /* 5.0 WestfW: Major Makefile restructuring. */
  181. /* See Makefile and pin_defs.h */
  182. /* (no binary changes) */
  183. /* */
  184. /* 4.6 WestfW/Pito: Add ATmega32 support */
  185. /* 4.6 WestfW/radoni: Don't set LED_PIN as an output if */
  186. /* not used. (LED_START_FLASHES = 0) */
  187. /* Jan 2013 */
  188. /* 4.6 WestfW/dkinzer: use autoincrement lpm for read */
  189. /* 4.6 WestfW/dkinzer: pass reset cause to app in R2 */
  190. /* Mar 2012 */
  191. /* 4.5 WestfW: add infrastructure for non-zero UARTS. */
  192. /* 4.5 WestfW: fix SIGNATURE_2 for m644 (bad in avr-libc) */
  193. /* Jan 2012: */
  194. /* 4.5 WestfW: fix NRWW value for m1284. */
  195. /* 4.4 WestfW: use attribute OS_main instead of naked for */
  196. /* main(). This allows optimizations that we */
  197. /* count on, which are prohibited in naked */
  198. /* functions due to PR42240. (keeps us less */
  199. /* than 512 bytes when compiler is gcc4.5 */
  200. /* (code from 4.3.2 remains the same.) */
  201. /* 4.4 WestfW and Maniacbug: Add m1284 support. This */
  202. /* does not change the 328 binary, so the */
  203. /* version number didn't change either. (?) */
  204. /* June 2011: */
  205. /* 4.4 WestfW: remove automatic soft_uart detect (didn't */
  206. /* know what it was doing or why.) Added a */
  207. /* check of the calculated BRG value instead. */
  208. /* Version stays 4.4; existing binaries are */
  209. /* not changed. */
  210. /* 4.4 WestfW: add initialization of address to keep */
  211. /* the compiler happy. Change SC'ed targets. */
  212. /* Return the SW version via READ PARAM */
  213. /* 4.3 WestfW: catch framing errors in getch(), so that */
  214. /* AVRISP works without HW kludges. */
  215. /* http://code.google.com/p/arduino/issues/detail?id=368n*/
  216. /* 4.2 WestfW: reduce code size, fix timeouts, change */
  217. /* verifySpace to use WDT instead of appstart */
  218. /* 4.1 WestfW: put version number in binary. */
  219. /**********************************************************/
  220. #define OPTIBOOT_MAJVER 6
  221. #define OPTIBOOT_MINVER 2
  222. /*
  223. * OPTIBOOT_CUSTOMVER should be defined (by the makefile) for custom edits
  224. * of optiboot. That way you don't wind up with very different code that
  225. * matches the version number of a "released" optiboot.
  226. */
  227. #if !defined(OPTIBOOT_CUSTOMVER)
  228. #define OPTIBOOT_CUSTOMVER 0
  229. #endif
  230. unsigned const int __attribute__((section(".version")))
  231. optiboot_version = 256*(OPTIBOOT_MAJVER + OPTIBOOT_CUSTOMVER) + OPTIBOOT_MINVER;
  232. #include <inttypes.h>
  233. #include <avr/io.h>
  234. #include <avr/pgmspace.h>
  235. #include <avr/eeprom.h>
  236. /*
  237. * Note that we use our own version of "boot.h"
  238. * <avr/boot.h> uses sts instructions, but this version uses out instructions
  239. * This saves cycles and program memory. Sorry for the name overlap.
  240. */
  241. #include "boot.h"
  242. // We don't use <avr/wdt.h> as those routines have interrupt overhead we don't need.
  243. /*
  244. * pin_defs.h
  245. * This contains most of the rather ugly defines that implement our
  246. * ability to use UART=n and LED=D3, and some avr family bit name differences.
  247. */
  248. #include "pin_defs.h"
  249. /*
  250. * stk500.h contains the constant definitions for the stk500v1 comm protocol
  251. */
  252. #include "stk500.h"
  253. #ifndef LED_START_FLASHES
  254. #define LED_START_FLASHES 0
  255. #endif
  256. /* set the UART baud rate defaults */
  257. #ifndef BAUD_RATE
  258. #if F_CPU >= 8000000L
  259. #define BAUD_RATE 115200L // Highest rate Avrdude win32 will support
  260. #elif F_CPU >= 1000000L
  261. #define BAUD_RATE 9600L // 19200 also supported, but with significant error
  262. #elif F_CPU >= 128000L
  263. #define BAUD_RATE 4800L // Good for 128kHz internal RC
  264. #else
  265. #define BAUD_RATE 1200L // Good even at 32768Hz
  266. #endif
  267. #endif
  268. #ifndef UART
  269. #define UART 0
  270. #endif
  271. #define BAUD_SETTING (( (F_CPU + BAUD_RATE * 4L) / ((BAUD_RATE * 8L))) - 1 )
  272. #define BAUD_ACTUAL (F_CPU/(8 * ((BAUD_SETTING)+1)))
  273. #if BAUD_ACTUAL <= BAUD_RATE
  274. #define BAUD_ERROR (( 100*(BAUD_RATE - BAUD_ACTUAL) ) / BAUD_RATE)
  275. #if BAUD_ERROR >= 5
  276. #error BAUD_RATE error greater than -5%
  277. #elif BAUD_ERROR >= 2
  278. #warning BAUD_RATE error greater than -2%
  279. #endif
  280. #else
  281. #define BAUD_ERROR (( 100*(BAUD_ACTUAL - BAUD_RATE) ) / BAUD_RATE)
  282. #if BAUD_ERROR >= 5
  283. #error BAUD_RATE error greater than 5%
  284. #elif BAUD_ERROR >= 2
  285. #warning BAUD_RATE error greater than 2%
  286. #endif
  287. #endif
  288. #if (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 > 250
  289. #error Unachievable baud rate (too slow) BAUD_RATE
  290. #endif // baud rate slow check
  291. #if (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 < 3
  292. #if BAUD_ERROR != 0 // permit high bitrates (ie 1Mbps@16MHz) if error is zero
  293. #error Unachievable baud rate (too fast) BAUD_RATE
  294. #endif
  295. #endif // baud rate fastn check
  296. /* Watchdog settings */
  297. #define WATCHDOG_OFF (0)
  298. #define WATCHDOG_16MS (_BV(WDE))
  299. #define WATCHDOG_32MS (_BV(WDP0) | _BV(WDE))
  300. #define WATCHDOG_64MS (_BV(WDP1) | _BV(WDE))
  301. #define WATCHDOG_125MS (_BV(WDP1) | _BV(WDP0) | _BV(WDE))
  302. #define WATCHDOG_250MS (_BV(WDP2) | _BV(WDE))
  303. #define WATCHDOG_500MS (_BV(WDP2) | _BV(WDP0) | _BV(WDE))
  304. #define WATCHDOG_1S (_BV(WDP2) | _BV(WDP1) | _BV(WDE))
  305. #define WATCHDOG_2S (_BV(WDP2) | _BV(WDP1) | _BV(WDP0) | _BV(WDE))
  306. #ifndef __AVR_ATmega8__
  307. #define WATCHDOG_4S (_BV(WDP3) | _BV(WDE))
  308. #define WATCHDOG_8S (_BV(WDP3) | _BV(WDP0) | _BV(WDE))
  309. #endif
  310. /*
  311. * We can never load flash with more than 1 page at a time, so we can save
  312. * some code space on parts with smaller pagesize by using a smaller int.
  313. */
  314. #if SPM_PAGESIZE > 255
  315. typedef uint16_t pagelen_t ;
  316. #define GETLENGTH(len) len = getch()<<8; len |= getch()
  317. #else
  318. typedef uint8_t pagelen_t;
  319. #define GETLENGTH(len) (void) getch() /* skip high byte */; len = getch()
  320. #endif
  321. /* Function Prototypes
  322. * The main() function is in init9, which removes the interrupt vector table
  323. * we don't need. It is also 'OS_main', which means the compiler does not
  324. * generate any entry or exit code itself (but unlike 'naked', it doesn't
  325. * supress some compile-time options we want.)
  326. */
  327. int main(void) __attribute__ ((OS_main)) __attribute__ ((section (".init9")));
  328. void __attribute__((noinline)) putch(char);
  329. uint8_t __attribute__((noinline)) getch(void);
  330. void __attribute__((noinline)) verifySpace();
  331. void __attribute__((noinline)) watchdogConfig(uint8_t x);
  332. static inline void getNch(uint8_t);
  333. static inline void flash_led(uint8_t);
  334. static inline void watchdogReset();
  335. static inline void writebuffer(int8_t memtype, uint8_t *mybuff,
  336. uint16_t address, pagelen_t len);
  337. static inline void read_mem(uint8_t memtype,
  338. uint16_t address, pagelen_t len);
  339. #ifdef SOFT_UART
  340. void uartDelay() __attribute__ ((naked));
  341. #endif
  342. void appStart(uint8_t rstFlags) __attribute__ ((naked));
  343. /*
  344. * RAMSTART should be self-explanatory. It's bigger on parts with a
  345. * lot of peripheral registers. Let 0x100 be the default
  346. * Note that RAMSTART (for optiboot) need not be exactly at the start of RAM.
  347. */
  348. #if !defined(RAMSTART) // newer versions of gcc avr-libc define RAMSTART
  349. #define RAMSTART 0x100
  350. #if defined (__AVR_ATmega644P__)
  351. // correct for a bug in avr-libc
  352. #undef SIGNATURE_2
  353. #define SIGNATURE_2 0x0A
  354. #elif defined(__AVR_ATmega1280__)
  355. #undef RAMSTART
  356. #define RAMSTART (0x200)
  357. #endif
  358. #endif
  359. /* C zero initialises all global variables. However, that requires */
  360. /* These definitions are NOT zero initialised, but that doesn't matter */
  361. /* This allows us to drop the zero init code, saving us memory */
  362. #define buff ((uint8_t*)(RAMSTART))
  363. /* Virtual boot partition support */
  364. #ifdef VIRTUAL_BOOT_PARTITION
  365. #define rstVect0_sav (*(uint8_t*)(RAMSTART+SPM_PAGESIZE*2+4))
  366. #define rstVect1_sav (*(uint8_t*)(RAMSTART+SPM_PAGESIZE*2+5))
  367. #define saveVect0_sav (*(uint8_t*)(RAMSTART+SPM_PAGESIZE*2+6))
  368. #define saveVect1_sav (*(uint8_t*)(RAMSTART+SPM_PAGESIZE*2+7))
  369. // Vector to save original reset jump:
  370. // SPM Ready is least probably used, so it's default
  371. // if not, use old way WDT_vect_num,
  372. // or simply set custom save_vect_num in Makefile using vector name
  373. // or even raw number.
  374. #if !defined (save_vect_num)
  375. #if defined (SPM_RDY_vect_num)
  376. #define save_vect_num (SPM_RDY_vect_num)
  377. #elif defined (SPM_READY_vect_num)
  378. #define save_vect_num (SPM_READY_vect_num)
  379. #elif defined (WDT_vect_num)
  380. #define save_vect_num (WDT_vect_num)
  381. #else
  382. #error Cant find SPM or WDT interrupt vector for this CPU
  383. #endif
  384. #endif //save_vect_num
  385. // check if it's on the same page (code assumes that)
  386. #if (SPM_PAGESIZE <= save_vect_num)
  387. #error Save vector not in the same page as reset!
  388. #endif
  389. #if FLASHEND > 8192
  390. // AVRs with more than 8k of flash have 4-byte vectors, and use jmp.
  391. // We save only 16 bits of address, so devices with more than 128KB
  392. // may behave wrong for upper part of address space.
  393. #define rstVect0 2
  394. #define rstVect1 3
  395. #define saveVect0 (save_vect_num*4+2)
  396. #define saveVect1 (save_vect_num*4+3)
  397. #define appstart_vec (save_vect_num*2)
  398. #else
  399. // AVRs with up to 8k of flash have 2-byte vectors, and use rjmp.
  400. #define rstVect0 0
  401. #define rstVect1 1
  402. #define saveVect0 (save_vect_num*2)
  403. #define saveVect1 (save_vect_num*2+1)
  404. #define appstart_vec (save_vect_num)
  405. #endif
  406. #else
  407. #define appstart_vec (0)
  408. #endif // VIRTUAL_BOOT_PARTITION
  409. /* main program starts here */
  410. int main(void) {
  411. uint8_t ch;
  412. /*
  413. * Making these local and in registers prevents the need for initializing
  414. * them, and also saves space because code no longer stores to memory.
  415. * (initializing address keeps the compiler happy, but isn't really
  416. * necessary, and uses 4 bytes of flash.)
  417. */
  418. register uint16_t address = 0;
  419. register pagelen_t length;
  420. // After the zero init loop, this is the first code to run.
  421. //
  422. // This code makes the following assumptions:
  423. // No interrupts will execute
  424. // SP points to RAMEND
  425. // r1 contains zero
  426. //
  427. // If not, uncomment the following instructions:
  428. // cli();
  429. asm volatile ("clr __zero_reg__");
  430. #if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) || defined (__AVR_ATmega16__)
  431. SP=RAMEND; // This is done by hardware reset
  432. #endif
  433. /*
  434. * modified Adaboot no-wait mod.
  435. * Pass the reset reason to app. Also, it appears that an Uno poweron
  436. * can leave multiple reset flags set; we only want the bootloader to
  437. * run on an 'external reset only' status
  438. */
  439. #if !defined(__AVR_ATmega16__)
  440. ch = MCUSR;
  441. MCUSR = 0;
  442. #else
  443. ch = MCUCSR;
  444. MCUCSR = 0;
  445. #endif
  446. if (ch & (_BV(WDRF) | _BV(BORF) | _BV(PORF)))
  447. appStart(ch);
  448. #if LED_START_FLASHES > 0
  449. // Set up Timer 1 for timeout counter
  450. TCCR1B = _BV(CS12) | _BV(CS10); // div 1024
  451. #endif
  452. #ifndef SOFT_UART
  453. #if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) || defined (__AVR_ATmega16__)
  454. UCSRA = _BV(U2X); //Double speed mode USART
  455. UCSRB = _BV(RXEN) | _BV(TXEN); // enable Rx & Tx
  456. UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0); // config USART; 8N1
  457. UBRRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
  458. #else
  459. UART_SRA = _BV(U2X0); //Double speed mode USART0
  460. UART_SRB = _BV(RXEN0) | _BV(TXEN0);
  461. UART_SRC = _BV(UCSZ00) | _BV(UCSZ01);
  462. UART_SRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
  463. #endif
  464. #endif
  465. // Set up watchdog to trigger after 1s
  466. watchdogConfig(WATCHDOG_1S);
  467. #if (LED_START_FLASHES > 0) || defined(LED_DATA_FLASH)
  468. /* Set LED pin as output */
  469. LED_DDR |= _BV(LED);
  470. #endif
  471. #ifdef SOFT_UART
  472. /* Set TX pin as output */
  473. UART_DDR |= _BV(UART_TX_BIT);
  474. #endif
  475. #if LED_START_FLASHES > 0
  476. /* Flash onboard LED to signal entering of bootloader */
  477. flash_led(LED_START_FLASHES * 2);
  478. #endif
  479. /* Forever loop: exits by causing WDT reset */
  480. for (;;) {
  481. /* get character from UART */
  482. ch = getch();
  483. if(ch == STK_GET_PARAMETER) {
  484. unsigned char which = getch();
  485. verifySpace();
  486. /*
  487. * Send optiboot version as "SW version"
  488. * Note that the references to memory are optimized away.
  489. */
  490. if (which == 0x82) {
  491. putch(optiboot_version & 0xFF);
  492. } else if (which == 0x81) {
  493. putch(optiboot_version >> 8);
  494. } else {
  495. /*
  496. * GET PARAMETER returns a generic 0x03 reply for
  497. * other parameters - enough to keep Avrdude happy
  498. */
  499. putch(0x03);
  500. }
  501. }
  502. else if(ch == STK_SET_DEVICE) {
  503. // SET DEVICE is ignored
  504. getNch(20);
  505. }
  506. else if(ch == STK_SET_DEVICE_EXT) {
  507. // SET DEVICE EXT is ignored
  508. getNch(5);
  509. }
  510. else if(ch == STK_LOAD_ADDRESS) {
  511. // LOAD ADDRESS
  512. uint16_t newAddress;
  513. newAddress = getch();
  514. newAddress = (newAddress & 0xff) | (getch() << 8);
  515. #ifdef RAMPZ
  516. // Transfer top bit to RAMPZ
  517. RAMPZ = (newAddress & 0x8000) ? 1 : 0;
  518. #endif
  519. newAddress += newAddress; // Convert from word address to byte address
  520. address = newAddress;
  521. verifySpace();
  522. }
  523. else if(ch == STK_UNIVERSAL) {
  524. // UNIVERSAL command is ignored
  525. getNch(4);
  526. putch(0x00);
  527. }
  528. /* Write memory, length is big endian and is in bytes */
  529. else if(ch == STK_PROG_PAGE) {
  530. // PROGRAM PAGE - we support flash programming only, not EEPROM
  531. uint8_t desttype;
  532. uint8_t *bufPtr;
  533. pagelen_t savelength;
  534. GETLENGTH(length);
  535. savelength = length;
  536. desttype = getch();
  537. // read a page worth of contents
  538. bufPtr = buff;
  539. do *bufPtr++ = getch();
  540. while (--length);
  541. // Read command terminator, start reply
  542. verifySpace();
  543. #ifdef VIRTUAL_BOOT_PARTITION
  544. #if FLASHEND > 8192
  545. /*
  546. * AVR with 4-byte ISR Vectors and "jmp"
  547. * WARNING: this works only up to 128KB flash!
  548. */
  549. if (address == 0) {
  550. // This is the reset vector page. We need to live-patch the
  551. // code so the bootloader runs first.
  552. //
  553. // Save jmp targets (for "Verify")
  554. rstVect0_sav = buff[rstVect0];
  555. rstVect1_sav = buff[rstVect1];
  556. saveVect0_sav = buff[saveVect0];
  557. saveVect1_sav = buff[saveVect1];
  558. // Move RESET jmp target to 'save' vector
  559. buff[saveVect0] = rstVect0_sav;
  560. buff[saveVect1] = rstVect1_sav;
  561. // Add jump to bootloader at RESET vector
  562. // WARNING: this works as long as 'main' is in first section
  563. buff[rstVect0] = ((uint16_t)main) & 0xFF;
  564. buff[rstVect1] = ((uint16_t)main) >> 8;
  565. }
  566. #else
  567. /*
  568. * AVR with 2-byte ISR Vectors and rjmp
  569. */
  570. if ((uint16_t)(void*)address == rstVect0) {
  571. // This is the reset vector page. We need to live-patch
  572. // the code so the bootloader runs first.
  573. //
  574. // Move RESET vector to 'save' vector
  575. // Save jmp targets (for "Verify")
  576. rstVect0_sav = buff[rstVect0];
  577. rstVect1_sav = buff[rstVect1];
  578. saveVect0_sav = buff[saveVect0];
  579. saveVect1_sav = buff[saveVect1];
  580. // Instruction is a relative jump (rjmp), so recalculate.
  581. uint16_t vect=(rstVect0_sav & 0xff) | ((rstVect1_sav & 0x0f)<<8); //calculate 12b displacement
  582. vect = (vect-save_vect_num) & 0x0fff; //substract 'save' interrupt position and wrap around 4096
  583. // Move RESET jmp target to 'save' vector
  584. buff[saveVect0] = vect & 0xff;
  585. buff[saveVect1] = (vect >> 8) | 0xc0; //
  586. // Add rjump to bootloader at RESET vector
  587. vect = ((uint16_t)main) &0x0fff; //WARNIG: this works as long as 'main' is in first section
  588. buff[0] = vect & 0xFF; // rjmp 0x1c00 instruction
  589. buff[1] = (vect >> 8) | 0xC0;
  590. }
  591. #endif // FLASHEND
  592. #endif // VBP
  593. writebuffer(desttype, buff, address, savelength);
  594. }
  595. /* Read memory block mode, length is big endian. */
  596. else if(ch == STK_READ_PAGE) {
  597. uint8_t desttype;
  598. GETLENGTH(length);
  599. desttype = getch();
  600. verifySpace();
  601. read_mem(desttype, address, length);
  602. }
  603. /* Get device signature bytes */
  604. else if(ch == STK_READ_SIGN) {
  605. // READ SIGN - return what Avrdude wants to hear
  606. verifySpace();
  607. putch(SIGNATURE_0);
  608. putch(SIGNATURE_1);
  609. putch(SIGNATURE_2);
  610. }
  611. else if (ch == STK_LEAVE_PROGMODE) { /* 'Q' */
  612. // Adaboot no-wait mod
  613. watchdogConfig(WATCHDOG_16MS);
  614. verifySpace();
  615. }
  616. else {
  617. // This covers the response to commands like STK_ENTER_PROGMODE
  618. verifySpace();
  619. }
  620. putch(STK_OK);
  621. }
  622. }
  623. void putch(char ch) {
  624. #ifndef SOFT_UART
  625. while (!(UART_SRA & _BV(UDRE0)));
  626. UART_UDR = ch;
  627. #else
  628. __asm__ __volatile__ (
  629. " com %[ch]\n" // ones complement, carry set
  630. " sec\n"
  631. "1: brcc 2f\n"
  632. " cbi %[uartPort],%[uartBit]\n"
  633. " rjmp 3f\n"
  634. "2: sbi %[uartPort],%[uartBit]\n"
  635. " nop\n"
  636. "3: rcall uartDelay\n"
  637. " rcall uartDelay\n"
  638. " lsr %[ch]\n"
  639. " dec %[bitcnt]\n"
  640. " brne 1b\n"
  641. :
  642. :
  643. [bitcnt] "d" (10),
  644. [ch] "r" (ch),
  645. [uartPort] "I" (_SFR_IO_ADDR(UART_PORT)),
  646. [uartBit] "I" (UART_TX_BIT)
  647. :
  648. "r25"
  649. );
  650. #endif
  651. }
  652. uint8_t getch(void) {
  653. uint8_t ch;
  654. #ifdef LED_DATA_FLASH
  655. #if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) || defined (__AVR_ATmega16__)
  656. LED_PORT ^= _BV(LED);
  657. #else
  658. LED_PIN |= _BV(LED);
  659. #endif
  660. #endif
  661. #ifdef SOFT_UART
  662. watchdogReset();
  663. __asm__ __volatile__ (
  664. "1: sbic %[uartPin],%[uartBit]\n" // Wait for start edge
  665. " rjmp 1b\n"
  666. " rcall uartDelay\n" // Get to middle of start bit
  667. "2: rcall uartDelay\n" // Wait 1 bit period
  668. " rcall uartDelay\n" // Wait 1 bit period
  669. " clc\n"
  670. " sbic %[uartPin],%[uartBit]\n"
  671. " sec\n"
  672. " dec %[bitCnt]\n"
  673. " breq 3f\n"
  674. " ror %[ch]\n"
  675. " rjmp 2b\n"
  676. "3:\n"
  677. :
  678. [ch] "=r" (ch)
  679. :
  680. [bitCnt] "d" (9),
  681. [uartPin] "I" (_SFR_IO_ADDR(UART_PIN)),
  682. [uartBit] "I" (UART_RX_BIT)
  683. :
  684. "r25"
  685. );
  686. #else
  687. while(!(UART_SRA & _BV(RXC0)))
  688. ;
  689. if (!(UART_SRA & _BV(FE0))) {
  690. /*
  691. * A Framing Error indicates (probably) that something is talking
  692. * to us at the wrong bit rate. Assume that this is because it
  693. * expects to be talking to the application, and DON'T reset the
  694. * watchdog. This should cause the bootloader to abort and run
  695. * the application "soon", if it keeps happening. (Note that we
  696. * don't care that an invalid char is returned...)
  697. */
  698. watchdogReset();
  699. }
  700. ch = UART_UDR;
  701. #endif
  702. #ifdef LED_DATA_FLASH
  703. #if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) || defined (__AVR_ATmega16__)
  704. LED_PORT ^= _BV(LED);
  705. #else
  706. LED_PIN |= _BV(LED);
  707. #endif
  708. #endif
  709. return ch;
  710. }
  711. #ifdef SOFT_UART
  712. // AVR305 equation: #define UART_B_VALUE (((F_CPU/BAUD_RATE)-23)/6)
  713. // Adding 3 to numerator simulates nearest rounding for more accurate baud rates
  714. #define UART_B_VALUE (((F_CPU/BAUD_RATE)-20)/6)
  715. #if UART_B_VALUE > 255
  716. #error Baud rate too slow for soft UART
  717. #endif
  718. void uartDelay() {
  719. __asm__ __volatile__ (
  720. "ldi r25,%[count]\n"
  721. "1:dec r25\n"
  722. "brne 1b\n"
  723. "ret\n"
  724. ::[count] "M" (UART_B_VALUE)
  725. );
  726. }
  727. #endif
  728. void getNch(uint8_t count) {
  729. do getch(); while (--count);
  730. verifySpace();
  731. }
  732. void verifySpace() {
  733. if (getch() != CRC_EOP) {
  734. watchdogConfig(WATCHDOG_16MS); // shorten WD timeout
  735. while (1) // and busy-loop so that WD causes
  736. ; // a reset and app start.
  737. }
  738. putch(STK_INSYNC);
  739. }
  740. #if LED_START_FLASHES > 0
  741. void flash_led(uint8_t count) {
  742. do {
  743. TCNT1 = -(F_CPU/(1024*16));
  744. TIFR1 = _BV(TOV1);
  745. while(!(TIFR1 & _BV(TOV1)));
  746. #if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) || defined (__AVR_ATmega16__)
  747. LED_PORT ^= _BV(LED);
  748. #else
  749. LED_PIN |= _BV(LED);
  750. #endif
  751. watchdogReset();
  752. } while (--count);
  753. }
  754. #endif
  755. // Watchdog functions. These are only safe with interrupts turned off.
  756. void watchdogReset() {
  757. __asm__ __volatile__ (
  758. "wdr\n"
  759. );
  760. }
  761. void watchdogConfig(uint8_t x) {
  762. WDTCSR = _BV(WDCE) | _BV(WDE);
  763. WDTCSR = x;
  764. }
  765. void appStart(uint8_t rstFlags) {
  766. // save the reset flags in the designated register
  767. // This can be saved in a main program by putting code in .init0 (which
  768. // executes before normal c init code) to save R2 to a global variable.
  769. __asm__ __volatile__ ("mov r2, %0\n" :: "r" (rstFlags));
  770. watchdogConfig(WATCHDOG_OFF);
  771. // Note that appstart_vec is defined so that this works with either
  772. // real or virtual boot partitions.
  773. __asm__ __volatile__ (
  774. // Jump to 'save' or RST vector
  775. "ldi r30,%[rstvec]\n"
  776. "clr r31\n"
  777. "ijmp\n"::[rstvec] "M"(appstart_vec)
  778. );
  779. }
  780. /*
  781. * void writebuffer(memtype, buffer, address, length)
  782. */
  783. static inline void writebuffer(int8_t memtype, uint8_t *mybuff,
  784. uint16_t address, pagelen_t len)
  785. {
  786. switch (memtype) {
  787. case 'E': // EEPROM
  788. #if defined(SUPPORT_EEPROM) || defined(BIGBOOT)
  789. while(len--) {
  790. eeprom_write_byte((uint8_t *)(address++), *mybuff++);
  791. }
  792. #else
  793. /*
  794. * On systems where EEPROM write is not supported, just busy-loop
  795. * until the WDT expires, which will eventually cause an error on
  796. * host system (which is what it should do.)
  797. */
  798. while (1)
  799. ; // Error: wait for WDT
  800. #endif
  801. break;
  802. default: // FLASH
  803. /*
  804. * Default to writing to Flash program memory. By making this
  805. * the default rather than checking for the correct code, we save
  806. * space on chips that don't support any other memory types.
  807. */
  808. {
  809. // Copy buffer into programming buffer
  810. uint8_t *bufPtr = mybuff;
  811. uint16_t addrPtr = (uint16_t)(void*)address;
  812. /*
  813. * Start the page erase and wait for it to finish. There
  814. * used to be code to do this while receiving the data over
  815. * the serial link, but the performance improvement was slight,
  816. * and we needed the space back.
  817. */
  818. __boot_page_erase_short((uint16_t)(void*)address);
  819. boot_spm_busy_wait();
  820. /*
  821. * Copy data from the buffer into the flash write buffer.
  822. */
  823. do {
  824. uint16_t a;
  825. a = *bufPtr++;
  826. a |= (*bufPtr++) << 8;
  827. __boot_page_fill_short((uint16_t)(void*)addrPtr,a);
  828. addrPtr += 2;
  829. } while (len -= 2);
  830. /*
  831. * Actually Write the buffer to flash (and wait for it to finish.)
  832. */
  833. __boot_page_write_short((uint16_t)(void*)address);
  834. boot_spm_busy_wait();
  835. #if defined(RWWSRE)
  836. // Reenable read access to flash
  837. boot_rww_enable();
  838. #endif
  839. } // default block
  840. break;
  841. } // switch
  842. }
  843. static inline void read_mem(uint8_t memtype, uint16_t address, pagelen_t length)
  844. {
  845. uint8_t ch;
  846. switch (memtype) {
  847. #if defined(SUPPORT_EEPROM) || defined(BIGBOOT)
  848. case 'E': // EEPROM
  849. do {
  850. putch(eeprom_read_byte((uint8_t *)(address++)));
  851. } while (--length);
  852. break;
  853. #endif
  854. default:
  855. do {
  856. #ifdef VIRTUAL_BOOT_PARTITION
  857. // Undo vector patch in bottom page so verify passes
  858. if (address == rstVect0) ch = rstVect0_sav;
  859. else if (address == rstVect1) ch = rstVect1_sav;
  860. else if (address == saveVect0) ch = saveVect0_sav;
  861. else if (address == saveVect1) ch = saveVect1_sav;
  862. else ch = pgm_read_byte_near(address);
  863. address++;
  864. #elif defined(RAMPZ)
  865. // Since RAMPZ should already be set, we need to use EPLM directly.
  866. // Also, we can use the autoincrement version of lpm to update "address"
  867. // do putch(pgm_read_byte_near(address++));
  868. // while (--length);
  869. // read a Flash and increment the address (may increment RAMPZ)
  870. __asm__ ("elpm %0,Z+\n" : "=r" (ch), "=z" (address): "1" (address));
  871. #else
  872. // read a Flash byte and increment the address
  873. __asm__ ("lpm %0,Z+\n" : "=r" (ch), "=z" (address): "1" (address));
  874. #endif
  875. putch(ch);
  876. } while (--length);
  877. break;
  878. } // switch
  879. }