10 #include <sys/types.h>
15 #include "stlink-common.h"
16 #include "uglylogging.h"
18 #define LOG_TAG __FILE__
19 #define DLOG(format, args...) ugly_log(UDEBUG, LOG_TAG, format, ## args)
20 #define ILOG(format, args...) ugly_log(UINFO, LOG_TAG, format, ## args)
21 #define WLOG(format, args...) ugly_log(UWARN, LOG_TAG, format, ## args)
22 #define fatal(format, args...) ugly_log(UFATAL, LOG_TAG, format, ## args)
24 /* todo: stm32l15xxx flash memory, pm0062 manual */
26 /* stm32f FPEC flash controller interface, pm0063 manual */
27 // TODO - all of this needs to be abstracted out....
28 #define FLASH_REGS_ADDR 0x40022000
29 #define FLASH_REGS_SIZE 0x28
31 #define FLASH_ACR (FLASH_REGS_ADDR + 0x00)
32 #define FLASH_KEYR (FLASH_REGS_ADDR + 0x04)
33 #define FLASH_SR (FLASH_REGS_ADDR + 0x0c)
34 #define FLASH_CR (FLASH_REGS_ADDR + 0x10)
35 #define FLASH_AR (FLASH_REGS_ADDR + 0x14)
36 #define FLASH_OBR (FLASH_REGS_ADDR + 0x1c)
37 #define FLASH_WRPR (FLASH_REGS_ADDR + 0x20)
39 #define FLASH_RDPTR_KEY 0x00a5
40 #define FLASH_KEY1 0x45670123
41 #define FLASH_KEY2 0xcdef89ab
43 #define FLASH_SR_BSY 0
44 #define FLASH_SR_EOP 5
47 #define FLASH_CR_PER 1
48 #define FLASH_CR_MER 2
49 #define FLASH_CR_STRT 6
50 #define FLASH_CR_LOCK 7
52 void write_uint32(unsigned char* buf, uint32_t ui) {
53 if (!is_bigendian()) { // le -> le (don't swap)
54 buf[0] = ((unsigned char*) &ui)[0];
55 buf[1] = ((unsigned char*) &ui)[1];
56 buf[2] = ((unsigned char*) &ui)[2];
57 buf[3] = ((unsigned char*) &ui)[3];
59 buf[0] = ((unsigned char*) &ui)[3];
60 buf[1] = ((unsigned char*) &ui)[2];
61 buf[2] = ((unsigned char*) &ui)[1];
62 buf[3] = ((unsigned char*) &ui)[0];
66 void write_uint16(unsigned char* buf, uint16_t ui) {
67 if (!is_bigendian()) { // le -> le (don't swap)
68 buf[0] = ((unsigned char*) &ui)[0];
69 buf[1] = ((unsigned char*) &ui)[1];
71 buf[0] = ((unsigned char*) &ui)[1];
72 buf[1] = ((unsigned char*) &ui)[0];
76 uint32_t read_uint32(const unsigned char *c, const int pt) {
78 char *p = (char *) &ui;
80 if (!is_bigendian()) { // le -> le (don't swap)
94 static uint32_t __attribute__((unused)) read_flash_rdp(stlink_t *sl) {
95 stlink_read_mem32(sl, FLASH_WRPR, sizeof (uint32_t));
96 return (*(uint32_t*) sl->q_buf) & 0xff;
99 static inline uint32_t read_flash_wrpr(stlink_t *sl) {
100 stlink_read_mem32(sl, FLASH_WRPR, sizeof (uint32_t));
101 return *(uint32_t*) sl->q_buf;
104 static inline uint32_t read_flash_obr(stlink_t *sl) {
105 stlink_read_mem32(sl, FLASH_OBR, sizeof (uint32_t));
106 return *(uint32_t*) sl->q_buf;
109 static inline uint32_t read_flash_cr(stlink_t *sl) {
110 stlink_read_mem32(sl, FLASH_CR, sizeof (uint32_t));
111 return *(uint32_t*) sl->q_buf;
114 static inline unsigned int is_flash_locked(stlink_t *sl) {
115 /* return non zero for true */
116 return read_flash_cr(sl) & (1 << FLASH_CR_LOCK);
119 static void unlock_flash(stlink_t *sl) {
120 /* the unlock sequence consists of 2 write cycles where
121 2 key values are written to the FLASH_KEYR register.
122 an invalid sequence results in a definitive lock of
123 the FPEC block until next reset.
126 write_uint32(sl->q_buf, FLASH_KEY1);
127 stlink_write_mem32(sl, FLASH_KEYR, sizeof (uint32_t));
129 write_uint32(sl->q_buf, FLASH_KEY2);
130 stlink_write_mem32(sl, FLASH_KEYR, sizeof (uint32_t));
133 static int unlock_flash_if(stlink_t *sl) {
134 /* unlock flash if already locked */
136 if (is_flash_locked(sl)) {
138 if (is_flash_locked(sl)) {
139 WLOG("Failed to unlock flash!\n");
143 ILOG("Successfully unlocked flash\n");
147 static void lock_flash(stlink_t *sl) {
148 /* write to 1 only. reset by hw at unlock sequence */
150 const uint32_t n = read_flash_cr(sl) | (1 << FLASH_CR_LOCK);
152 write_uint32(sl->q_buf, n);
153 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
156 static void set_flash_cr_pg(stlink_t *sl) {
157 const uint32_t n = 1 << FLASH_CR_PG;
158 write_uint32(sl->q_buf, n);
159 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
162 static void __attribute__((unused)) clear_flash_cr_pg(stlink_t *sl) {
163 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PG);
164 write_uint32(sl->q_buf, n);
165 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
168 static void set_flash_cr_per(stlink_t *sl) {
169 const uint32_t n = 1 << FLASH_CR_PER;
170 write_uint32(sl->q_buf, n);
171 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
174 static void __attribute__((unused)) clear_flash_cr_per(stlink_t *sl) {
175 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PER);
176 write_uint32(sl->q_buf, n);
177 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
180 static void set_flash_cr_mer(stlink_t *sl) {
181 const uint32_t n = 1 << FLASH_CR_MER;
182 write_uint32(sl->q_buf, n);
183 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
186 static void __attribute__((unused)) clear_flash_cr_mer(stlink_t *sl) {
187 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_MER);
188 write_uint32(sl->q_buf, n);
189 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
192 static void set_flash_cr_strt(stlink_t *sl) {
193 /* assume come on the flash_cr_per path */
194 const uint32_t n = (1 << FLASH_CR_PER) | (1 << FLASH_CR_STRT);
195 write_uint32(sl->q_buf, n);
196 stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
199 static inline uint32_t read_flash_acr(stlink_t *sl) {
200 stlink_read_mem32(sl, FLASH_ACR, sizeof (uint32_t));
201 return *(uint32_t*) sl->q_buf;
204 static inline uint32_t read_flash_sr(stlink_t *sl) {
205 stlink_read_mem32(sl, FLASH_SR, sizeof (uint32_t));
206 return *(uint32_t*) sl->q_buf;
209 static inline unsigned int is_flash_busy(stlink_t *sl) {
210 return read_flash_sr(sl) & (1 << FLASH_SR_BSY);
213 static void wait_flash_busy(stlink_t *sl) {
214 /* todo: add some delays here */
215 while (is_flash_busy(sl))
219 static inline unsigned int is_flash_eop(stlink_t *sl) {
220 return read_flash_sr(sl) & (1 << FLASH_SR_EOP);
223 static void __attribute__((unused)) clear_flash_sr_eop(stlink_t *sl) {
224 const uint32_t n = read_flash_sr(sl) & ~(1 << FLASH_SR_EOP);
225 write_uint32(sl->q_buf, n);
226 stlink_write_mem32(sl, FLASH_SR, sizeof (uint32_t));
229 static void __attribute__((unused)) wait_flash_eop(stlink_t *sl) {
230 /* todo: add some delays here */
231 while (is_flash_eop(sl) == 0)
235 static inline void write_flash_ar(stlink_t *sl, uint32_t n) {
236 write_uint32(sl->q_buf, n);
237 stlink_write_mem32(sl, FLASH_AR, sizeof (uint32_t));
242 static void disable_flash_read_protection(stlink_t *sl) {
243 /* erase the option byte area */
250 // Delegates to the backends...
252 void stlink_close(stlink_t *sl) {
253 DLOG("*** stlink_close ***\n");
254 sl->backend->close(sl);
258 void stlink_exit_debug_mode(stlink_t *sl) {
259 DLOG("*** stlink_exit_debug_mode ***\n");
260 sl->backend->exit_debug_mode(sl);
263 void stlink_enter_swd_mode(stlink_t *sl) {
264 DLOG("*** stlink_enter_swd_mode ***\n");
265 sl->backend->enter_swd_mode(sl);
268 // Force the core into the debug mode -> halted state.
269 void stlink_force_debug(stlink_t *sl) {
270 DLOG("*** stlink_force_debug_mode ***\n");
271 sl->backend->force_debug(sl);
274 void stlink_exit_dfu_mode(stlink_t *sl) {
275 DLOG("*** stlink_exit_dfu_mode ***\n");
276 sl->backend->exit_dfu_mode(sl);
279 uint32_t stlink_core_id(stlink_t *sl) {
280 DLOG("*** stlink_core_id ***\n");
281 sl->backend->core_id(sl);
283 stlink_print_data(sl);
284 DLOG("core_id = 0x%08x\n", sl->core_id);
288 uint16_t stlink_chip_id(stlink_t *sl) {
289 stlink_read_mem32(sl, 0xE0042000, 4);
290 uint32_t chip_id = sl->q_buf[0] | (sl->q_buf[1] << 8) | (sl->q_buf[2] << 16) |
291 (sl->q_buf[3] << 24);
296 * Cortex m3 tech ref manual, CPUID register description
297 * @param sl stlink context
298 * @param cpuid pointer to the result object
300 void stlink_cpu_id(stlink_t *sl, cortex_m3_cpuid_t *cpuid) {
301 stlink_read_mem32(sl, CM3_REG_CPUID, 4);
302 uint32_t raw = read_uint32(sl->q_buf, 0);
303 cpuid->implementer_id = (raw >> 24) & 0x7f;
304 cpuid->variant = (raw >> 20) & 0xf;
305 cpuid->part = (raw >> 4) & 0xfff;
306 cpuid->revision = raw & 0xf;
311 * reads and decodes the flash parameters, as dynamically as possible
313 * @return 0 for success, or -1 for unsupported core type.
315 int stlink_load_device_params(stlink_t *sl) {
316 ILOG("Loading device parameters....\n");
317 const chip_params_t *params = NULL;
318 uint32_t chip_id = stlink_chip_id(sl);
319 sl->chip_id = chip_id;
320 for(size_t i = 0; i < sizeof(devices) / sizeof(devices[0]); i++) {
321 if(devices[i].chip_id == (chip_id & 0xFFF)) {
322 params = &devices[i];
326 if (params == NULL) {
327 WLOG("unknown chip id! %#x\n", chip_id);
331 // These are fixed...
332 sl->flash_base = STM32_FLASH_BASE;
333 sl->sram_base = STM32_SRAM_BASE;
335 // read flash size from hardware, if possible...
336 if ((chip_id & 0xFFF) == STM32_CHIPID_F2) {
337 sl->flash_size = 0; // FIXME - need to work this out some other way, just set to max possible?
339 stlink_read_mem32(sl, params->flash_size_reg, 4);
340 uint32_t flash_size = sl->q_buf[0] | (sl->q_buf[1] << 8);
341 sl->flash_size = flash_size * 1024;
343 sl->flash_pgsz = params->flash_pagesize;
344 sl->sram_size = params->sram_size;
345 sl->sys_base = params->bootrom_base;
346 sl->sys_size = params->bootrom_size;
348 sl->core_id = stlink_core_id(sl);
350 ILOG("Device connected is: %s\n", params->description);
351 ILOG("SRAM size: %#x bytes (%d KiB), Flash: %#x bytes (%d KiB) in pages of %zd bytes\n",
352 sl->sram_size, sl->sram_size / 1024, sl->flash_size, sl->flash_size / 1024,
357 void stlink_reset(stlink_t *sl) {
358 DLOG("*** stlink_reset ***\n");
359 sl->backend->reset(sl);
362 void stlink_run(stlink_t *sl) {
363 DLOG("*** stlink_run ***\n");
364 sl->backend->run(sl);
367 void stlink_status(stlink_t *sl) {
368 DLOG("*** stlink_status ***\n");
369 sl->backend->status(sl);
370 stlink_core_stat(sl);
374 * Decode the version bits, originally from -sg, verified with usb
375 * @param sl stlink context, assumed to contain valid data in the buffer
376 * @param slv output parsed version object
378 void _parse_version(stlink_t *sl, stlink_version_t *slv) {
379 uint32_t b0 = sl->q_buf[0]; //lsb
380 uint32_t b1 = sl->q_buf[1];
381 uint32_t b2 = sl->q_buf[2];
382 uint32_t b3 = sl->q_buf[3];
383 uint32_t b4 = sl->q_buf[4];
384 uint32_t b5 = sl->q_buf[5]; //msb
386 // b0 b1 || b2 b3 | b4 b5
387 // 4b | 6b | 6b || 2B | 2B
388 // stlink_v | jtag_v | swim_v || st_vid | stlink_pid
390 slv->stlink_v = (b0 & 0xf0) >> 4;
391 slv->jtag_v = ((b0 & 0x0f) << 2) | ((b1 & 0xc0) >> 6);
392 slv->swim_v = b1 & 0x3f;
393 slv->st_vid = (b3 << 8) | b2;
394 slv->stlink_pid = (b5 << 8) | b4;
398 void stlink_version(stlink_t *sl) {
399 DLOG("*** looking up stlink version\n");
400 sl->backend->version(sl);
401 _parse_version(sl, &sl->version);
403 DLOG("st vid = 0x%04x (expect 0x%04x)\n", sl->version.st_vid, USB_ST_VID);
404 DLOG("stlink pid = 0x%04x\n", sl->version.stlink_pid);
405 DLOG("stlink version = 0x%x\n", sl->version.stlink_v);
406 DLOG("jtag version = 0x%x\n", sl->version.jtag_v);
407 DLOG("swim version = 0x%x\n", sl->version.swim_v);
408 if (sl->version.jtag_v == 0) {
409 DLOG(" notice: the firmware doesn't support a jtag/swd interface\n");
411 if (sl->version.swim_v == 0) {
412 DLOG(" notice: the firmware doesn't support a swim interface\n");
416 void stlink_write_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
417 DLOG("*** stlink_write_mem32 %u bytes to %#x\n", len, addr);
419 fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
422 sl->backend->write_mem32(sl, addr, len);
425 void stlink_read_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
426 DLOG("*** stlink_read_mem32 ***\n");
427 if (len % 4 != 0) { // !!! never ever: fw gives just wrong values
428 fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n",
432 sl->backend->read_mem32(sl, addr, len);
435 void stlink_write_mem8(stlink_t *sl, uint32_t addr, uint16_t len) {
436 DLOG("*** stlink_write_mem8 ***\n");
437 sl->backend->write_mem8(sl, addr, len);
440 void stlink_read_all_regs(stlink_t *sl, reg *regp) {
441 DLOG("*** stlink_read_all_regs ***\n");
442 sl->backend->read_all_regs(sl, regp);
445 void stlink_write_reg(stlink_t *sl, uint32_t reg, int idx) {
446 DLOG("*** stlink_write_reg\n");
447 sl->backend->write_reg(sl, reg, idx);
450 void stlink_read_reg(stlink_t *sl, int r_idx, reg *regp) {
451 DLOG("*** stlink_read_reg\n");
452 DLOG(" (%d) ***\n", r_idx);
454 if (r_idx > 20 || r_idx < 0) {
455 fprintf(stderr, "Error: register index must be in [0..20]\n");
459 sl->backend->read_reg(sl, r_idx, regp);
462 unsigned int is_core_halted(stlink_t *sl) {
463 /* return non zero if core is halted */
465 return sl->q_buf[0] == STLINK_CORE_HALTED;
468 void stlink_step(stlink_t *sl) {
469 DLOG("*** stlink_step ***\n");
470 sl->backend->step(sl);
473 int stlink_current_mode(stlink_t *sl) {
474 int mode = sl->backend->current_mode(sl);
476 case STLINK_DEV_DFU_MODE:
477 DLOG("stlink current mode: dfu\n");
479 case STLINK_DEV_DEBUG_MODE:
480 DLOG("stlink current mode: debug (jtag or swd)\n");
482 case STLINK_DEV_MASS_MODE:
483 DLOG("stlink current mode: mass\n");
486 DLOG("stlink mode: unknown!\n");
487 return STLINK_DEV_UNKNOWN_MODE;
493 // End of delegates.... Common code below here...
496 // http://www.ibm.com/developerworks/aix/library/au-endianc/index.html
498 // #define is_bigendian() ( (*(char*)&i) == 0 )
500 inline unsigned int is_bigendian(void) {
501 static volatile const unsigned int i = 1;
502 return *(volatile const char*) &i == 0;
505 uint16_t read_uint16(const unsigned char *c, const int pt) {
507 char *p = (char *) &ui;
509 if (!is_bigendian()) { // le -> le (don't swap)
519 // same as above with entrypoint.
521 void stlink_run_at(stlink_t *sl, stm32_addr_t addr) {
522 stlink_write_reg(sl, addr, 15); /* pc register */
526 while (is_core_halted(sl) == 0)
530 void stlink_core_stat(stlink_t *sl) {
534 switch (sl->q_buf[0]) {
535 case STLINK_CORE_RUNNING:
536 sl->core_stat = STLINK_CORE_RUNNING;
537 DLOG(" core status: running\n");
539 case STLINK_CORE_HALTED:
540 sl->core_stat = STLINK_CORE_HALTED;
541 DLOG(" core status: halted\n");
544 sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
545 fprintf(stderr, " core status: unknown\n");
549 void stlink_print_data(stlink_t * sl) {
550 if (sl->q_len <= 0 || sl->verbose < UDEBUG)
553 fprintf(stdout, "data_len = %d 0x%x\n", sl->q_len, sl->q_len);
555 for (int i = 0; i < sl->q_len; i++) {
558 if (sl->q_data_dir == Q_DATA_OUT)
559 fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
561 fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
564 fprintf(stdout, " %02x", (unsigned int) sl->q_buf[i]);
566 fputs("\n\n", stdout);
569 /* memory mapped file */
571 typedef struct mapped_file {
576 #define MAPPED_FILE_INITIALIZER { NULL, 0 }
578 static int map_file(mapped_file_t* mf, const char* path) {
582 const int fd = open(path, O_RDONLY);
584 fprintf(stderr, "open(%s) == -1\n", path);
588 if (fstat(fd, &st) == -1) {
589 fprintf(stderr, "fstat() == -1\n");
593 mf->base = (uint8_t*) mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
594 if (mf->base == MAP_FAILED) {
595 fprintf(stderr, "mmap() == MAP_FAILED\n");
599 mf->len = st.st_size;
610 static void unmap_file(mapped_file_t * mf) {
611 munmap((void*) mf->base, mf->len);
612 mf->base = (unsigned char*) MAP_FAILED;
616 static int check_file(stlink_t* sl, mapped_file_t* mf, stm32_addr_t addr) {
619 for (off = 0; off < mf->len; off += sl->flash_pgsz) {
622 /* adjust last page size */
623 size_t cmp_size = sl->flash_pgsz;
624 if ((off + sl->flash_pgsz) > mf->len)
625 cmp_size = mf->len - off;
627 aligned_size = cmp_size;
628 if (aligned_size & (4 - 1))
629 aligned_size = (cmp_size + 4) & ~(4 - 1);
631 stlink_read_mem32(sl, addr + off, aligned_size);
633 if (memcmp(sl->q_buf, mf->base + off, cmp_size))
640 int stlink_fwrite_sram
641 (stlink_t * sl, const char* path, stm32_addr_t addr) {
642 /* write the file in sram at addr */
646 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
648 if (map_file(&mf, path) == -1) {
649 fprintf(stderr, "map_file() == -1\n");
653 /* check addr range is inside the sram */
654 if (addr < sl->sram_base) {
655 fprintf(stderr, "addr too low\n");
657 } else if ((addr + mf.len) < addr) {
658 fprintf(stderr, "addr overruns\n");
660 } else if ((addr + mf.len) > (sl->sram_base + sl->sram_size)) {
661 fprintf(stderr, "addr too high\n");
663 } else if ((addr & 3) || (mf.len & 3)) {
665 fprintf(stderr, "unaligned addr or size\n");
669 /* do the copy by 1k blocks */
670 for (off = 0; off < mf.len; off += 1024) {
672 if ((off + size) > mf.len)
675 memcpy(sl->q_buf, mf.base + off, size);
677 /* round size if needed */
681 stlink_write_mem32(sl, addr + off, size);
684 /* check the file ha been written */
685 if (check_file(sl, &mf, addr) == -1) {
686 fprintf(stderr, "check_file() == -1\n");
698 int stlink_fread(stlink_t* sl, const char* path, stm32_addr_t addr, size_t size) {
699 /* read size bytes from addr to file */
704 const int fd = open(path, O_RDWR | O_TRUNC | O_CREAT, 00700);
706 fprintf(stderr, "open(%s) == -1\n", path);
710 /* do the copy by 1k blocks */
711 for (off = 0; off < size; off += 1024) {
712 size_t read_size = 1024;
714 if ((off + read_size) > size)
715 read_size = size - off;
717 /* round size if needed */
718 rounded_size = read_size;
719 if (rounded_size & 3)
720 rounded_size = (rounded_size + 4) & ~(3);
722 stlink_read_mem32(sl, addr + off, rounded_size);
724 if (write(fd, sl->q_buf, read_size) != (ssize_t) read_size) {
725 fprintf(stderr, "write() != read_size\n");
739 int write_buffer_to_sram(stlink_t *sl, flash_loader_t* fl, const uint8_t* buf, size_t size) {
740 /* write the buffer right after the loader */
741 memcpy(sl->q_buf, buf, size);
742 stlink_write_mem8(sl, fl->buf_addr, size);
747 * Erase a page of flash, assumes sl is fully populated with things like chip/core ids
748 * @param sl stlink context
750 * @return 0 on success -ve on failure
752 int stlink_erase_flash_page(stlink_t *sl, stm32_addr_t page)
754 /* page an addr in the page to erase */
755 ILOG("Erasing flash page at addr: %#x\n", page);
756 if (sl->core_id == STM32L_CORE_ID)
758 #define STM32L_FLASH_REGS_ADDR ((uint32_t)0x40023c00)
759 #define STM32L_FLASH_ACR (STM32L_FLASH_REGS_ADDR + 0x00)
760 #define STM32L_FLASH_PECR (STM32L_FLASH_REGS_ADDR + 0x04)
761 #define STM32L_FLASH_PDKEYR (STM32L_FLASH_REGS_ADDR + 0x08)
762 #define STM32L_FLASH_PEKEYR (STM32L_FLASH_REGS_ADDR + 0x0c)
763 #define STM32L_FLASH_PRGKEYR (STM32L_FLASH_REGS_ADDR + 0x10)
764 #define STM32L_FLASH_OPTKEYR (STM32L_FLASH_REGS_ADDR + 0x14)
765 #define STM32L_FLASH_SR (STM32L_FLASH_REGS_ADDR + 0x18)
766 #define STM32L_FLASH_OBR (STM32L_FLASH_REGS_ADDR + 0x0c)
767 #define STM32L_FLASH_WRPR (STM32L_FLASH_REGS_ADDR + 0x20)
771 /* disable pecr protection */
772 write_uint32(sl->q_buf, 0x89abcdef);
773 stlink_write_mem32(sl, STM32L_FLASH_PEKEYR, sizeof(uint32_t));
774 write_uint32(sl->q_buf, 0x02030405);
775 stlink_write_mem32(sl, STM32L_FLASH_PEKEYR, sizeof(uint32_t));
777 /* check pecr.pelock is cleared */
778 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
779 val = read_uint32(sl->q_buf, 0);
782 WLOG("pecr.pelock not clear (%#x)\n", val);
786 /* unlock program memory */
787 write_uint32(sl->q_buf, 0x8c9daebf);
788 stlink_write_mem32(sl, STM32L_FLASH_PRGKEYR, sizeof(uint32_t));
789 write_uint32(sl->q_buf, 0x13141516);
790 stlink_write_mem32(sl, STM32L_FLASH_PRGKEYR, sizeof(uint32_t));
792 /* check pecr.prglock is cleared */
793 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
794 val = read_uint32(sl->q_buf, 0);
797 WLOG("pecr.prglock not clear (%#x)\n", val);
801 /* unused: unlock the option byte block */
803 write_uint32(sl->q_buf, 0xfbead9c8);
804 stlink_write_mem32(sl, STM32L_FLASH_OPTKEYR, sizeof(uint32_t));
805 write_uint32(sl->q_buf, 0x24252627);
806 stlink_write_mem32(sl, STM32L_FLASH_OPTKEYR, sizeof(uint32_t));
808 /* check pecr.optlock is cleared */
809 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
810 val = read_uint32(sl->q_buf, 0);
813 fprintf(stderr, "pecr.prglock not clear\n");
818 /* set pecr.{erase,prog} */
819 val |= (1 << 9) | (1 << 3);
820 write_uint32(sl->q_buf, val);
821 stlink_write_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
823 /* wait for sr.busy to be cleared */
826 stlink_read_mem32(sl, STM32L_FLASH_SR, sizeof(uint32_t));
827 if ((read_uint32(sl->q_buf, 0) & (1 << 0)) == 0) break ;
830 /* write 0 to the first word of the page to be erased */
831 memset(sl->q_buf, 0, sizeof(uint32_t));
832 stlink_write_mem32(sl, page, sizeof(uint32_t));
834 /* reset lock bits */
835 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
836 val = read_uint32(sl->q_buf, 0) | (1 << 0) | (1 << 1) | (1 << 2);
837 write_uint32(sl->q_buf, val);
838 stlink_write_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
840 else if (sl->core_id == STM32VL_CORE_ID)
842 /* wait for ongoing op to finish */
845 /* unlock if locked */
848 /* set the page erase bit */
849 set_flash_cr_per(sl);
851 /* select the page to erase */
852 write_flash_ar(sl, page);
854 /* start erase operation, reset by hw with bsy bit */
855 set_flash_cr_strt(sl);
857 /* wait for completion */
860 /* relock the flash */
864 WLOG("unknown coreid: %x\n", sl->core_id);
868 /* todo: verify the erased page */
873 int stlink_erase_flash_mass(stlink_t *sl) {
874 /* wait for ongoing op to finish */
877 /* unlock if locked */
880 /* set the mass erase bit */
881 set_flash_cr_mer(sl);
883 /* start erase operation, reset by hw with bsy bit */
884 set_flash_cr_strt(sl);
886 /* wait for completion */
889 /* relock the flash */
892 /* todo: verify the erased memory */
897 int init_flash_loader(stlink_t *sl, flash_loader_t* fl) {
900 /* allocate the loader in sram */
901 if (write_loader_to_sram(sl, &fl->loader_addr, &size) == -1) {
902 WLOG("Failed to write flash loader to sram!\n");
906 /* allocate a one page buffer in sram right after loader */
907 fl->buf_addr = fl->loader_addr + size;
908 ILOG("Successfully loaded flash loader in sram\n");
912 int write_loader_to_sram(stlink_t *sl, stm32_addr_t* addr, size_t* size) {
913 /* from openocd, contrib/loaders/flash/stm32.s */
914 static const uint8_t loader_code_stm32vl[] = {
915 0x08, 0x4c, /* ldr r4, STM32_FLASH_BASE */
916 0x1c, 0x44, /* add r4, r3 */
917 /* write_half_word: */
918 0x01, 0x23, /* movs r3, #0x01 */
919 0x23, 0x61, /* str r3, [r4, #STM32_FLASH_CR_OFFSET] */
920 0x30, 0xf8, 0x02, 0x3b, /* ldrh r3, [r0], #0x02 */
921 0x21, 0xf8, 0x02, 0x3b, /* strh r3, [r1], #0x02 */
923 0xe3, 0x68, /* ldr r3, [r4, #STM32_FLASH_SR_OFFSET] */
924 0x13, 0xf0, 0x01, 0x0f, /* tst r3, #0x01 */
925 0xfb, 0xd0, /* beq busy */
926 0x13, 0xf0, 0x14, 0x0f, /* tst r3, #0x14 */
927 0x01, 0xd1, /* bne exit */
928 0x01, 0x3a, /* subs r2, r2, #0x01 */
929 0xf0, 0xd1, /* bne write_half_word */
931 0x00, 0xbe, /* bkpt #0x00 */
932 0x00, 0x20, 0x02, 0x40, /* STM32_FLASH_BASE: .word 0x40022000 */
935 static const uint8_t loader_code_stm32l[] = {
937 /* openocd.git/contrib/loaders/flash/stm32lx.S
939 r1, input, source addr
940 r2, input, word count
941 r3, output, word count
947 0x51, 0xf8, 0x04, 0xcb,
948 0x40, 0xf8, 0x04, 0xcb,
956 const uint8_t* loader_code;
959 if (sl->core_id == STM32L_CORE_ID) /* stm32l */
961 loader_code = loader_code_stm32l;
962 loader_size = sizeof(loader_code_stm32l);
964 else if (sl->core_id == STM32VL_CORE_ID)
966 loader_code = loader_code_stm32vl;
967 loader_size = sizeof(loader_code_stm32vl);
971 WLOG("unknown coreid, not sure what flash loader to use, aborting!: %x\n", sl->core_id);
975 memcpy(sl->q_buf, loader_code, loader_size);
976 stlink_write_mem32(sl, sl->sram_base, loader_size);
978 *addr = sl->sram_base;
985 int stlink_fcheck_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
986 /* check the contents of path are at addr */
989 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
991 if (map_file(&mf, path) == -1)
994 res = check_file(sl, &mf, addr);
1002 int stlink_write_flash(stlink_t *sl, stm32_addr_t addr, uint8_t* base, unsigned len) {
1005 ILOG("Attempting to write %d (%#x) bytes to stm32 address: %u (%#x)\n",
1006 len, len, addr, addr);
1007 /* check addr range is inside the flash */
1008 if (addr < sl->flash_base) {
1009 WLOG("addr too low %#x < %#x\n", addr, sl->flash_base);
1011 } else if ((addr + len) < addr) {
1012 WLOG("addr overruns\n");
1014 } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
1015 WLOG("addr too high\n");
1017 } else if ((addr & 1) || (len & 1)) {
1018 WLOG("unaligned addr or size\n");
1020 } else if (addr & (sl->flash_pgsz - 1)) {
1021 WLOG("addr not a multiple of pagesize, not supported\n");
1025 // Make sure we've loaded the context with the chip details
1027 /* erase each page */
1029 for (off = 0; off < len; off += sl->flash_pgsz) {
1030 /* addr must be an addr inside the page */
1031 if (stlink_erase_flash_page(sl, addr + off) == -1) {
1032 WLOG("Failed to erase_flash_page(%#zx) == -1\n", addr + off);
1037 ILOG("Finished erasing %d pages of %d (%#x) bytes\n",
1038 page_count, sl->flash_pgsz, sl->flash_pgsz);
1040 if (sl->core_id == STM32L_CORE_ID)
1042 /* use fast word write. todo: half page. */
1046 #if 0 /* todo: check write operation */
1048 uint32_t nwrites = sl->flash_pgsz;
1052 #endif /* todo: check write operation */
1054 /* disable pecr protection */
1055 write_uint32(sl->q_buf, 0x89abcdef);
1056 stlink_write_mem32(sl, STM32L_FLASH_PEKEYR, sizeof(uint32_t));
1057 write_uint32(sl->q_buf, 0x02030405);
1058 stlink_write_mem32(sl, STM32L_FLASH_PEKEYR, sizeof(uint32_t));
1060 /* check pecr.pelock is cleared */
1061 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
1062 val = read_uint32(sl->q_buf, 0);
1065 fprintf(stderr, "pecr.pelock not clear\n");
1069 /* unlock program memory */
1070 write_uint32(sl->q_buf, 0x8c9daebf);
1071 stlink_write_mem32(sl, STM32L_FLASH_PRGKEYR, sizeof(uint32_t));
1072 write_uint32(sl->q_buf, 0x13141516);
1073 stlink_write_mem32(sl, STM32L_FLASH_PRGKEYR, sizeof(uint32_t));
1075 /* check pecr.prglock is cleared */
1076 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
1077 val = read_uint32(sl->q_buf, 0);
1080 fprintf(stderr, "pecr.prglock not clear\n");
1084 /* write a word in program memory */
1085 for (off = 0; off < len; off += sizeof(uint32_t))
1087 if (sl->verbose >= 1)
1089 if ((off & (sl->flash_pgsz - 1)) == 0)
1091 /* show progress. writing procedure is slow
1092 and previous errors are misleading */
1093 const uint32_t pgnum = off / sl->flash_pgsz;
1094 const uint32_t pgcount = len / sl->flash_pgsz;
1095 fprintf(stdout, "%u pages written out of %u\n", pgnum, pgcount);
1099 memcpy(sl->q_buf, (const void*)(base + off), sizeof(uint32_t));
1100 stlink_write_mem32(sl, addr + off, sizeof(uint32_t));
1102 /* wait for sr.busy to be cleared */
1105 stlink_read_mem32(sl, STM32L_FLASH_SR, sizeof(uint32_t));
1106 if ((read_uint32(sl->q_buf, 0) & (1 << 0)) == 0) break ;
1109 #if 0 /* todo: check redo write operation */
1111 /* check written bytes. todo: should be on a per page basis. */
1112 stlink_read_mem32(sl, addr + off, sizeof(uint32_t));
1113 if (memcmp(sl->q_buf, base + off, sizeof(uint32_t)))
1115 /* re erase the page and redo the write operation */
1119 /* fail if successive write count too low */
1120 if (nwrites < sl->flash_pgsz) {
1121 fprintf(stderr, "writes operation failure count too high, aborting\n");
1127 /* assume addr aligned */
1128 if (off % sl->flash_pgsz) off &= ~(sl->flash_pgsz - 1);
1131 fprintf(stderr, "invalid write @%x(%x): %x != %x. retrying.\n",
1132 page, addr + off, read_uint32(base + off, 0), read_uint32(sl->q_buf, 0));
1134 /* reset lock bits */
1135 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
1136 val = read_uint32(sl->q_buf, 0) | (1 << 0) | (1 << 1) | (1 << 2);
1137 write_uint32(sl->q_buf, val);
1138 stlink_write_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
1140 stlink_erase_flash_page(sl, page);
1145 /* increment successive writes counter */
1148 #endif /* todo: check redo write operation */
1152 /* reset lock bits */
1153 stlink_read_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
1154 val = read_uint32(sl->q_buf, 0) | (1 << 0) | (1 << 1) | (1 << 2);
1155 write_uint32(sl->q_buf, val);
1156 stlink_write_mem32(sl, STM32L_FLASH_PECR, sizeof(uint32_t));
1157 } else if (sl->core_id == STM32VL_CORE_ID) {
1158 ILOG("Starting Flash write for VL core id\n");
1159 /* flash loader initialization */
1160 if (init_flash_loader(sl, &fl) == -1) {
1161 WLOG("init_flash_loader() == -1\n");
1165 /* write each page. above WRITE_BLOCK_SIZE fails? */
1166 #define WRITE_BLOCK_SIZE 0x40
1167 int write_block_count = 0;
1168 for (off = 0; off < len; off += WRITE_BLOCK_SIZE) {
1169 ILOG("Writing flash block %d of size %d (%#x)\n", write_block_count,
1170 WRITE_BLOCK_SIZE, WRITE_BLOCK_SIZE);
1171 /* adjust last write size */
1172 size_t size = WRITE_BLOCK_SIZE;
1173 if ((off + WRITE_BLOCK_SIZE) > len) size = len - off;
1175 /* unlock and set programming mode */
1176 unlock_flash_if(sl);
1177 set_flash_cr_pg(sl);
1178 //DLOG("Finished setting flash cr pg, running loader!\n");
1179 if (run_flash_loader(sl, &fl, addr + off, base + off, size) == -1) {
1180 WLOG("run_flash_loader(%#zx) failed! == -1\n", addr + off);
1184 DLOG("Finished writing block %d\n", write_block_count++);
1187 WLOG("unknown coreid, not sure how to write: %x\n", sl->core_id);
1191 ILOG("Starting verification of write complete\n");
1192 for (off = 0; off < len; off += sl->flash_pgsz) {
1193 size_t aligned_size;
1195 /* adjust last page size */
1196 size_t cmp_size = sl->flash_pgsz;
1197 if ((off + sl->flash_pgsz) > len)
1198 cmp_size = len - off;
1200 aligned_size = cmp_size;
1201 if (aligned_size & (4 - 1))
1202 aligned_size = (cmp_size + 4) & ~(4 - 1);
1204 stlink_read_mem32(sl, addr + off, aligned_size);
1206 if (memcmp(sl->q_buf, base + off, cmp_size))
1209 ILOG("Flash written and verified! jolly good!\n");
1214 * Write the given binary file into flash at address "addr"
1216 * @param path readable file path, should be binary image
1217 * @param addr where to start writing
1218 * @return 0 on success, -ve on failure.
1220 int stlink_fwrite_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
1221 /* write the file in flash at addr */
1223 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1224 if (map_file(&mf, path) == -1) {
1225 WLOG("map_file() == -1\n");
1228 err = stlink_write_flash(sl, addr, mf.base, mf.len);
1233 int run_flash_loader(stlink_t *sl, flash_loader_t* fl, stm32_addr_t target, const uint8_t* buf, size_t size) {
1236 DLOG("Running flash loader, write address:%#x, size: %zd\n", target, size);
1237 // FIXME This can never return -1
1238 if (write_buffer_to_sram(sl, fl, buf, size) == -1) {
1240 WLOG("write_buffer_to_sram() == -1\n");
1244 if (sl->core_id == STM32L_CORE_ID) {
1246 size_t count = size / sizeof(uint32_t);
1247 if (size % sizeof(uint32_t)) ++count;
1250 stlink_write_reg(sl, target, 0); /* target */
1251 stlink_write_reg(sl, fl->buf_addr, 1); /* source */
1252 stlink_write_reg(sl, count, 2); /* count (32 bits words) */
1253 stlink_write_reg(sl, 0, 3); /* output count */
1254 stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
1256 } else if (sl->core_id == STM32VL_CORE_ID) {
1258 size_t count = size / sizeof(uint16_t);
1259 if (size % sizeof(uint16_t)) ++count;
1262 stlink_write_reg(sl, fl->buf_addr, 0); /* source */
1263 stlink_write_reg(sl, target, 1); /* target */
1264 stlink_write_reg(sl, count, 2); /* count (16 bits half words) */
1265 stlink_write_reg(sl, 0, 3); /* flash bank 0 (input) */
1266 stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
1269 fprintf(stderr, "unknown coreid: %x\n", sl->core_id);
1276 /* wait until done (reaches breakpoint) */
1277 while (is_core_halted(sl) == 0) ;
1279 /* check written byte count */
1280 if (sl->core_id == STM32L_CORE_ID) {
1282 size_t count = size / sizeof(uint32_t);
1283 if (size % sizeof(uint32_t)) ++count;
1285 stlink_read_reg(sl, 3, &rr);
1286 if (rr.r[3] != count) {
1287 fprintf(stderr, "write error, count == %u\n", rr.r[3]);
1291 } else if (sl->core_id == STM32VL_CORE_ID) {
1293 stlink_read_reg(sl, 2, &rr);
1295 fprintf(stderr, "write error, count == %u\n", rr.r[2]);
1301 fprintf(stderr, "unknown coreid: %x\n", sl->core_id);