-
- /* write each page. above WRITE_BLOCK_SIZE fails? */
-
- if (sl->core_id == 0x2ba01477) /* stm32l */
- {
- /* use fast word write. todo: half page. */
-
- uint32_t val;
-
- /* disable pecr protection */
- write_uint32(sl->q_buf, 0x89abcdef);
- stlink_write_mem32(sl, STM32L_FLASH_PEKEYR, sizeof(uint32_t));
- write_uint32(sl->q_buf, 0x02030405);
- stlink_write_mem32(sl, STM32L_FLASH_PEKEYR, sizeof(uint32_t));
-
- /* check pecr.pelock is cleared */
- stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
- val = read_uint32(sl->q_buf, 0);
- if (val & (1 << 0))
- {
- fprintf(stderr, "pecr.pelock not clear\n");
- goto on_error;
- }
-
- /* unlock program memory */
- write_uint32(sl->q_buf, 0x8c9daebf);
- stlink_write_mem32(sl, STM32L_FLASH_PRGKEYR, sizeof(uint32_t));
- write_uint32(sl->q_buf, 0x13141516);
- stlink_write_mem32(sl, STM32L_FLASH_PRGKEYR, sizeof(uint32_t));
-
- /* check pecr.prglock is cleared */
- stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
- val = read_uint32(sl->q_buf, 0);
- if (val & (1 << 1))
- {
- fprintf(stderr, "pecr.prglock not clear\n");
- goto on_error;
- }
-
- /* write a word in program memory */
- for (off = 0; off < mf.len; off += sizeof(uint32_t))
- {
- memcpy(sl->q_buf, (const void*)(mf.base + off), sizeof(uint32_t));
- stlink_write_mem32(sl, addr + off, sizeof(uint32_t));
-
- /* wait for sr.busy to be cleared */
- while (1)
- {
- stlink_read_mem32(sl, STM32L_FLASH_SR, sizeof(uint32_t));
- if ((read_uint32(sl->q_buf, 0) & (1 << 0)) == 0) break ;
- }
- }
-
- /* reset lock bits */
- stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
- val = read_uint32(sl->q_buf, 0) | (1 << 0) | (1 << 1) | (1 << 2);
- write_uint32(sl->q_buf, val);
- stlink_write_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
- }
- else /* stm32vl */
- {
-#define WRITE_BLOCK_SIZE 0x40
- for (off = 0; off < mf.len; off += WRITE_BLOCK_SIZE)
- {
- /* adjust last write size */
- size_t size = WRITE_BLOCK_SIZE;
- if ((off + WRITE_BLOCK_SIZE) > mf.len) size = mf.len - off;
-
- /* unlock and set programming mode */
- unlock_flash_if(sl);
- set_flash_cr_pg(sl);
-
- if (init_flash_loader(sl, &fl) == -1) {
- fprintf(stderr, "init_flash_loader() == -1\n");
- goto on_error;
- }
-
- if (run_flash_loader(sl, &fl, addr + off, mf.base + off, size) == -1)
- {
- fprintf(stderr, "run_flash_loader(0x%zx) == -1\n", addr + off);
- goto on_error;
- }
-
- lock_flash(sl);
- }
-
- } /* stm32vl */
-
- /* check the file ha been written */
- if (check_file(sl, &mf, addr) == -1) {
- fprintf(stderr, "check_file() == -1\n");
- goto on_error;
- }
-
- /* success */
- error = 0;
-
-on_error: