2 * Copyright © 2013 Keith Packard <keithp@keithp.com>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
22 /* Note that the HSI clock must be running for this code to work.
23 * Also, special care must be taken with the linker to ensure that the
24 * functions marked 'ramtext' land in ram and not rom. An example of that
25 * can be found in altos-loader.ld
29 ao_flash_is_locked(void)
31 return (stm_flash.cr & (1 << STM_FLASH_CR_LOCK)) != 0;
37 if (!ao_flash_is_locked())
40 /* Unlock FLASH_CR register */
41 stm_flash.keyr = STM_FLASH_KEYR_KEY1;
42 stm_flash.keyr = STM_FLASH_KEYR_KEY2;
43 if (ao_flash_is_locked())
44 ao_panic(AO_PANIC_FLASH);
50 stm_flash.cr |= (1 << STM_FLASH_CR_LOCK);
53 #define ao_flash_wait_bsy() do { while (stm_flash.sr & (1 << STM_FLASH_SR_BSY)); } while (0)
55 static void __attribute__ ((section(".sdata2.flash"), noinline))
56 _ao_flash_erase_page(uint32_t *page)
58 stm_flash.cr |= (1 << STM_FLASH_CR_PER);
60 stm_flash.ar = (uintptr_t) page;
62 stm_flash.cr |= (1 << STM_FLASH_CR_STRT);
66 stm_flash.cr &= ~(1UL << STM_FLASH_CR_PER);
70 stm_flash_page_size(void)
72 uint16_t dev_id = stm_dev_id();
75 case 0x440: /* stm32f05x */
76 case 0x444: /* stm32f03x */
77 case 0x445: /* stm32f04x */
79 case 0x442: /* stm32f09x */
80 case 0x448: /* stm32f07x */
83 ao_panic(AO_PANIC_FLASH);
88 ao_flash_erase_page(uint32_t *page)
90 /* Erase the whole page at the start. This assumes we'll be flashing things
94 if ((uintptr_t) page & (stm_flash_page_size() - 1))
97 ao_arch_block_interrupts();
100 _ao_flash_erase_page(page);
103 ao_arch_release_interrupts();
106 static void __attribute__ ((section(".sdata2.flash"), noinline))
107 _ao_flash_page(uint16_t *dst, uint16_t *src)
111 stm_flash.cr |= (1 << STM_FLASH_CR_PG);
113 for (i = 0; i < 128; i++) {
118 stm_flash.cr &= ~(1UL << STM_FLASH_CR_PG);
122 ao_flash_page(uint32_t *page, uint32_t *src)
124 ao_flash_erase_page(page);
126 ao_arch_block_interrupts();
129 _ao_flash_page((uint16_t *) page, (uint16_t *) src);
132 ao_arch_release_interrupts();