10 #include <sys/types.h>
14 #include "stlink-common.h"
15 #include "uglylogging.h"
21 /* todo: stm32l15xxx flash memory, pm0062 manual */
23 /* stm32f FPEC flash controller interface, pm0063 manual */
24 // TODO - all of this needs to be abstracted out....
25 // STM32F05x is identical, based on RM0091 (DM00031936, Doc ID 018940 Rev 2, August 2012)
26 #define FLASH_REGS_ADDR 0x40022000
27 #define FLASH_REGS_SIZE 0x28
29 #define FLASH_ACR (FLASH_REGS_ADDR + 0x00)
30 #define FLASH_KEYR (FLASH_REGS_ADDR + 0x04)
31 #define FLASH_SR (FLASH_REGS_ADDR + 0x0c)
32 #define FLASH_CR (FLASH_REGS_ADDR + 0x10)
33 #define FLASH_AR (FLASH_REGS_ADDR + 0x14)
34 #define FLASH_OBR (FLASH_REGS_ADDR + 0x1c)
35 #define FLASH_WRPR (FLASH_REGS_ADDR + 0x20)
37 // For STM32F05x, the RDPTR_KEY may be wrong, but as it is not used anywhere...
38 #define FLASH_RDPTR_KEY 0x00a5
39 #define FLASH_KEY1 0x45670123
40 #define FLASH_KEY2 0xcdef89ab
42 #define FLASH_SR_BSY 0
43 #define FLASH_SR_EOP 5
46 #define FLASH_CR_PER 1
47 #define FLASH_CR_MER 2
48 #define FLASH_CR_STRT 6
49 #define FLASH_CR_LOCK 7
52 //32L = 32F1 same CoreID as 32F4!
53 #define STM32L_FLASH_REGS_ADDR ((uint32_t)0x40023c00)
54 #define STM32L_FLASH_ACR (STM32L_FLASH_REGS_ADDR + 0x00)
55 #define STM32L_FLASH_PECR (STM32L_FLASH_REGS_ADDR + 0x04)
56 #define STM32L_FLASH_PDKEYR (STM32L_FLASH_REGS_ADDR + 0x08)
57 #define STM32L_FLASH_PEKEYR (STM32L_FLASH_REGS_ADDR + 0x0c)
58 #define STM32L_FLASH_PRGKEYR (STM32L_FLASH_REGS_ADDR + 0x10)
59 #define STM32L_FLASH_OPTKEYR (STM32L_FLASH_REGS_ADDR + 0x14)
60 #define STM32L_FLASH_SR (STM32L_FLASH_REGS_ADDR + 0x18)
61 #define STM32L_FLASH_OBR (STM32L_FLASH_REGS_ADDR + 0x1c)
62 #define STM32L_FLASH_WRPR (STM32L_FLASH_REGS_ADDR + 0x20)
63 #define FLASH_L1_FPRG 10
64 #define FLASH_L1_PROG 3
68 #define FLASH_F4_REGS_ADDR ((uint32_t)0x40023c00)
69 #define FLASH_F4_KEYR (FLASH_F4_REGS_ADDR + 0x04)
70 #define FLASH_F4_OPT_KEYR (FLASH_F4_REGS_ADDR + 0x08)
71 #define FLASH_F4_SR (FLASH_F4_REGS_ADDR + 0x0c)
72 #define FLASH_F4_CR (FLASH_F4_REGS_ADDR + 0x10)
73 #define FLASH_F4_OPT_CR (FLASH_F4_REGS_ADDR + 0x14)
74 #define FLASH_F4_CR_STRT 16
75 #define FLASH_F4_CR_LOCK 31
76 #define FLASH_F4_CR_SER 1
77 #define FLASH_F4_CR_SNB 3
78 #define FLASH_F4_CR_SNB_MASK 0x38
79 #define FLASH_F4_SR_BSY 16
82 void write_uint32(unsigned char* buf, uint32_t ui) {
83 if (!is_bigendian()) { // le -> le (don't swap)
84 buf[0] = ((unsigned char*) &ui)[0];
85 buf[1] = ((unsigned char*) &ui)[1];
86 buf[2] = ((unsigned char*) &ui)[2];
87 buf[3] = ((unsigned char*) &ui)[3];
89 buf[0] = ((unsigned char*) &ui)[3];
90 buf[1] = ((unsigned char*) &ui)[2];
91 buf[2] = ((unsigned char*) &ui)[1];
92 buf[3] = ((unsigned char*) &ui)[0];
96 void write_uint16(unsigned char* buf, uint16_t ui) {
97 if (!is_bigendian()) { // le -> le (don't swap)
98 buf[0] = ((unsigned char*) &ui)[0];
99 buf[1] = ((unsigned char*) &ui)[1];
101 buf[0] = ((unsigned char*) &ui)[1];
102 buf[1] = ((unsigned char*) &ui)[0];
106 uint32_t read_uint32(const unsigned char *c, const int pt) {
108 char *p = (char *) &ui;
110 if (!is_bigendian()) { // le -> le (don't swap)
124 static uint32_t __attribute__((unused)) read_flash_rdp(stlink_t *sl) {
125 return stlink_read_debug32(sl, FLASH_WRPR) & 0xff;
128 static inline uint32_t read_flash_wrpr(stlink_t *sl) {
129 return stlink_read_debug32(sl, FLASH_WRPR);
132 static inline uint32_t read_flash_obr(stlink_t *sl) {
133 return stlink_read_debug32(sl, FLASH_OBR);
136 static inline uint32_t read_flash_cr(stlink_t *sl) {
138 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) ||(sl->chip_id == STM32_CHIPID_F4_DE) ||
139 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD))
140 res = stlink_read_debug32(sl, FLASH_F4_CR);
142 res = stlink_read_debug32(sl, FLASH_CR);
144 fprintf(stdout, "CR:0x%x\n", res);
149 static inline unsigned int is_flash_locked(stlink_t *sl) {
150 /* return non zero for true */
151 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
152 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD))
153 return read_flash_cr(sl) & (1 << FLASH_F4_CR_LOCK);
155 return read_flash_cr(sl) & (1 << FLASH_CR_LOCK);
158 static void unlock_flash(stlink_t *sl) {
159 /* the unlock sequence consists of 2 write cycles where
160 2 key values are written to the FLASH_KEYR register.
161 an invalid sequence results in a definitive lock of
162 the FPEC block until next reset.
164 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
165 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD)) {
166 stlink_write_debug32(sl, FLASH_F4_KEYR, FLASH_KEY1);
167 stlink_write_debug32(sl, FLASH_F4_KEYR, FLASH_KEY2);
169 stlink_write_debug32(sl, FLASH_KEYR, FLASH_KEY1);
170 stlink_write_debug32(sl, FLASH_KEYR, FLASH_KEY2);
175 static int unlock_flash_if(stlink_t *sl) {
176 /* unlock flash if already locked */
178 if (is_flash_locked(sl)) {
180 if (is_flash_locked(sl)) {
181 WLOG("Failed to unlock flash!\n");
185 DLOG("Successfully unlocked flash\n");
189 static void lock_flash(stlink_t *sl) {
190 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
191 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD)) {
192 const uint32_t n = read_flash_cr(sl) | (1 << FLASH_F4_CR_LOCK);
193 stlink_write_debug32(sl, FLASH_F4_CR, n);
195 /* write to 1 only. reset by hw at unlock sequence */
196 const uint32_t n = read_flash_cr(sl) | (1 << FLASH_CR_LOCK);
197 stlink_write_debug32(sl, FLASH_CR, n);
202 static void set_flash_cr_pg(stlink_t *sl) {
203 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
204 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD)) {
205 uint32_t x = read_flash_cr(sl);
206 x |= (1 << FLASH_CR_PG);
207 stlink_write_debug32(sl, FLASH_F4_CR, x);
209 const uint32_t n = 1 << FLASH_CR_PG;
210 stlink_write_debug32(sl, FLASH_CR, n);
214 static void __attribute__((unused)) clear_flash_cr_pg(stlink_t *sl) {
215 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PG);
216 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
217 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD))
218 stlink_write_debug32(sl, FLASH_F4_CR, n);
220 stlink_write_debug32(sl, FLASH_CR, n);
223 static void set_flash_cr_per(stlink_t *sl) {
224 const uint32_t n = 1 << FLASH_CR_PER;
225 stlink_write_debug32(sl, FLASH_CR, n);
228 static void __attribute__((unused)) clear_flash_cr_per(stlink_t *sl) {
229 const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PER);
230 stlink_write_debug32(sl, FLASH_CR, n);
233 static void set_flash_cr_mer(stlink_t *sl) {
234 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
235 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD))
236 stlink_write_debug32(sl, FLASH_F4_CR,
237 stlink_read_debug32(sl, FLASH_F4_CR) | (1 << FLASH_CR_MER));
239 stlink_write_debug32(sl, FLASH_CR,
240 stlink_read_debug32(sl, FLASH_CR) | (1 << FLASH_CR_MER));
243 static void __attribute__((unused)) clear_flash_cr_mer(stlink_t *sl) {
244 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
245 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD))
246 stlink_write_debug32(sl, FLASH_F4_CR,
247 stlink_read_debug32(sl, FLASH_F4_CR) & ~(1 << FLASH_CR_MER));
249 stlink_write_debug32(sl, FLASH_CR,
250 stlink_read_debug32(sl, FLASH_CR) & ~(1 << FLASH_CR_MER));
253 static void set_flash_cr_strt(stlink_t *sl) {
254 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
255 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD)) {
256 uint32_t x = read_flash_cr(sl);
257 x |= (1 << FLASH_F4_CR_STRT);
258 stlink_write_debug32(sl, FLASH_F4_CR, x);
260 stlink_write_debug32(sl, FLASH_CR,
261 stlink_read_debug32(sl, FLASH_CR) | (1 << FLASH_CR_STRT) );
265 static inline uint32_t read_flash_acr(stlink_t *sl) {
266 return stlink_read_debug32(sl, FLASH_ACR);
269 static inline uint32_t read_flash_sr(stlink_t *sl) {
271 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
272 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD))
273 res = stlink_read_debug32(sl, FLASH_F4_SR);
275 res = stlink_read_debug32(sl, FLASH_SR);
276 //fprintf(stdout, "SR:0x%x\n", *(uint32_t*) sl->q_buf);
280 static inline unsigned int is_flash_busy(stlink_t *sl) {
281 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
282 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD))
283 return read_flash_sr(sl) & (1 << FLASH_F4_SR_BSY);
285 return read_flash_sr(sl) & (1 << FLASH_SR_BSY);
288 static void wait_flash_busy(stlink_t *sl) {
289 /* todo: add some delays here */
290 while (is_flash_busy(sl))
294 static void wait_flash_busy_progress(stlink_t *sl) {
296 fprintf(stdout, "Mass erasing");
298 while (is_flash_busy(sl)) {
302 fprintf(stdout, ".");
306 fprintf(stdout, "\n");
309 static inline unsigned int is_flash_eop(stlink_t *sl) {
310 return read_flash_sr(sl) & (1 << FLASH_SR_EOP);
313 static void __attribute__((unused)) clear_flash_sr_eop(stlink_t *sl) {
314 const uint32_t n = read_flash_sr(sl) & ~(1 << FLASH_SR_EOP);
315 stlink_write_debug32(sl, FLASH_SR, n);
318 static void __attribute__((unused)) wait_flash_eop(stlink_t *sl) {
319 /* todo: add some delays here */
320 while (is_flash_eop(sl) == 0)
324 static inline void write_flash_ar(stlink_t *sl, uint32_t n) {
325 stlink_write_debug32(sl, FLASH_AR, n);
328 static inline void write_flash_cr_psiz(stlink_t *sl, uint32_t n) {
329 uint32_t x = read_flash_cr(sl);
333 fprintf(stdout, "PSIZ:0x%x 0x%x\n", x, n);
335 stlink_write_debug32(sl, FLASH_F4_CR, x);
339 static inline void write_flash_cr_snb(stlink_t *sl, uint32_t n) {
340 uint32_t x = read_flash_cr(sl);
341 x &= ~FLASH_F4_CR_SNB_MASK;
342 x |= (n << FLASH_F4_CR_SNB);
343 x |= (1 << FLASH_F4_CR_SER);
345 fprintf(stdout, "SNB:0x%x 0x%x\n", x, n);
347 stlink_write_debug32(sl, FLASH_F4_CR, x);
350 // Delegates to the backends...
352 void stlink_close(stlink_t *sl) {
353 DLOG("*** stlink_close ***\n");
354 sl->backend->close(sl);
358 void stlink_exit_debug_mode(stlink_t *sl) {
359 DLOG("*** stlink_exit_debug_mode ***\n");
360 stlink_write_debug32(sl, DHCSR, DBGKEY);
361 sl->backend->exit_debug_mode(sl);
364 void stlink_enter_swd_mode(stlink_t *sl) {
365 DLOG("*** stlink_enter_swd_mode ***\n");
366 sl->backend->enter_swd_mode(sl);
369 // Force the core into the debug mode -> halted state.
370 void stlink_force_debug(stlink_t *sl) {
371 DLOG("*** stlink_force_debug_mode ***\n");
372 sl->backend->force_debug(sl);
375 void stlink_exit_dfu_mode(stlink_t *sl) {
376 DLOG("*** stlink_exit_dfu_mode ***\n");
377 sl->backend->exit_dfu_mode(sl);
380 uint32_t stlink_core_id(stlink_t *sl) {
381 DLOG("*** stlink_core_id ***\n");
382 sl->backend->core_id(sl);
384 stlink_print_data(sl);
385 DLOG("core_id = 0x%08x\n", sl->core_id);
389 uint32_t stlink_chip_id(stlink_t *sl) {
390 uint32_t chip_id = stlink_read_debug32(sl, 0xE0042000);
391 if (chip_id == 0) chip_id = stlink_read_debug32(sl, 0x40015800); //Try Corex M0 DBGMCU_IDCODE register address
396 * Cortex m3 tech ref manual, CPUID register description
397 * @param sl stlink context
398 * @param cpuid pointer to the result object
400 void stlink_cpu_id(stlink_t *sl, cortex_m3_cpuid_t *cpuid) {
401 uint32_t raw = stlink_read_debug32(sl, CM3_REG_CPUID);
402 cpuid->implementer_id = (raw >> 24) & 0x7f;
403 cpuid->variant = (raw >> 20) & 0xf;
404 cpuid->part = (raw >> 4) & 0xfff;
405 cpuid->revision = raw & 0xf;
410 * reads and decodes the flash parameters, as dynamically as possible
412 * @return 0 for success, or -1 for unsupported core type.
414 int stlink_load_device_params(stlink_t *sl) {
415 ILOG("Loading device parameters....\n");
416 const chip_params_t *params = NULL;
417 sl->core_id = stlink_core_id(sl);
418 uint32_t chip_id = stlink_chip_id(sl);
421 sl->chip_id = chip_id & 0xfff;
422 /* Fix chip_id for F4 rev A errata , Read CPU ID, as CoreID is the same for F2/F4*/
423 if (sl->chip_id == 0x411) {
424 uint32_t cpuid = stlink_read_debug32(sl, 0xE000ED00);
425 if ((cpuid & 0xfff0) == 0xc240)
429 for (size_t i = 0; i < sizeof(devices) / sizeof(devices[0]); i++) {
430 if(devices[i].chip_id == sl->chip_id) {
431 params = &devices[i];
435 if (params == NULL) {
436 WLOG("unknown chip id! %#x\n", chip_id);
440 // These are fixed...
441 sl->flash_base = STM32_FLASH_BASE;
442 sl->sram_base = STM32_SRAM_BASE;
443 flash_size = stlink_read_debug32(sl,(params->flash_size_reg) & ~3);
444 if (params->flash_size_reg & 2)
445 flash_size = flash_size >>16;
446 flash_size = flash_size & 0xffff;
448 if ((sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS) && ( flash_size == 0 )) {
449 sl->flash_size = 128 * 1024;
450 } else if ((sl->chip_id & 0xFFF) == STM32_CHIPID_L1_HIGH) {
451 // 0 is 384k and 1 is 256k
452 if ( flash_size == 0 ) {
453 sl->flash_size = 384 * 1024;
455 sl->flash_size = 256 * 1024;
458 sl->flash_size = flash_size * 1024;
460 sl->flash_pgsz = params->flash_pagesize;
461 sl->sram_size = params->sram_size;
462 sl->sys_base = params->bootrom_base;
463 sl->sys_size = params->bootrom_size;
465 ILOG("Device connected is: %s, id %#x\n", params->description, chip_id);
466 // TODO make note of variable page size here.....
467 ILOG("SRAM size: %#x bytes (%d KiB), Flash: %#x bytes (%d KiB) in pages of %zd bytes\n",
468 sl->sram_size, sl->sram_size / 1024, sl->flash_size, sl->flash_size / 1024,
473 void stlink_reset(stlink_t *sl) {
474 DLOG("*** stlink_reset ***\n");
475 sl->backend->reset(sl);
478 void stlink_jtag_reset(stlink_t *sl, int value) {
479 DLOG("*** stlink_jtag_reset ***\n");
480 sl->backend->jtag_reset(sl, value);
483 void stlink_run(stlink_t *sl) {
484 DLOG("*** stlink_run ***\n");
485 sl->backend->run(sl);
488 void stlink_status(stlink_t *sl) {
489 DLOG("*** stlink_status ***\n");
490 sl->backend->status(sl);
491 stlink_core_stat(sl);
495 * Decode the version bits, originally from -sg, verified with usb
496 * @param sl stlink context, assumed to contain valid data in the buffer
497 * @param slv output parsed version object
499 void _parse_version(stlink_t *sl, stlink_version_t *slv) {
500 uint32_t b0 = sl->q_buf[0]; //lsb
501 uint32_t b1 = sl->q_buf[1];
502 uint32_t b2 = sl->q_buf[2];
503 uint32_t b3 = sl->q_buf[3];
504 uint32_t b4 = sl->q_buf[4];
505 uint32_t b5 = sl->q_buf[5]; //msb
507 // b0 b1 || b2 b3 | b4 b5
508 // 4b | 6b | 6b || 2B | 2B
509 // stlink_v | jtag_v | swim_v || st_vid | stlink_pid
511 slv->stlink_v = (b0 & 0xf0) >> 4;
512 slv->jtag_v = ((b0 & 0x0f) << 2) | ((b1 & 0xc0) >> 6);
513 slv->swim_v = b1 & 0x3f;
514 slv->st_vid = (b3 << 8) | b2;
515 slv->stlink_pid = (b5 << 8) | b4;
519 void stlink_version(stlink_t *sl) {
520 DLOG("*** looking up stlink version\n");
521 sl->backend->version(sl);
522 _parse_version(sl, &sl->version);
524 DLOG("st vid = 0x%04x (expect 0x%04x)\n", sl->version.st_vid, USB_ST_VID);
525 DLOG("stlink pid = 0x%04x\n", sl->version.stlink_pid);
526 DLOG("stlink version = 0x%x\n", sl->version.stlink_v);
527 DLOG("jtag version = 0x%x\n", sl->version.jtag_v);
528 DLOG("swim version = 0x%x\n", sl->version.swim_v);
529 if (sl->version.jtag_v == 0) {
530 DLOG(" notice: the firmware doesn't support a jtag/swd interface\n");
532 if (sl->version.swim_v == 0) {
533 DLOG(" notice: the firmware doesn't support a swim interface\n");
537 int stlink_target_voltage(stlink_t *sl) {
539 DLOG("*** reading target voltage\n");
540 if (sl->backend->target_voltage != NULL) {
541 voltage = sl->backend->target_voltage(sl);
543 DLOG("target voltage = %ldmV\n", voltage);
545 DLOG("error reading target voltage\n");
548 DLOG("reading voltage not supported by backend\n");
553 uint32_t stlink_read_debug32(stlink_t *sl, uint32_t addr) {
554 uint32_t data = sl->backend->read_debug32(sl, addr);
555 DLOG("*** stlink_read_debug32 %x is %#x\n", data, addr);
559 void stlink_write_debug32(stlink_t *sl, uint32_t addr, uint32_t data) {
560 DLOG("*** stlink_write_debug32 %x to %#x\n", data, addr);
561 sl->backend->write_debug32(sl, addr, data);
564 void stlink_write_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
565 DLOG("*** stlink_write_mem32 %u bytes to %#x\n", len, addr);
567 fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
570 sl->backend->write_mem32(sl, addr, len);
573 void stlink_read_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
574 DLOG("*** stlink_read_mem32 ***\n");
575 if (len % 4 != 0) { // !!! never ever: fw gives just wrong values
576 fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n",
580 sl->backend->read_mem32(sl, addr, len);
583 void stlink_write_mem8(stlink_t *sl, uint32_t addr, uint16_t len) {
584 DLOG("*** stlink_write_mem8 ***\n");
585 if (len > 0x40 ) { // !!! never ever: Writing more then 0x40 bytes gives unexpected behaviour
586 fprintf(stderr, "Error: Data length > 64: +%d byte.\n",
590 sl->backend->write_mem8(sl, addr, len);
593 void stlink_read_all_regs(stlink_t *sl, reg *regp) {
594 DLOG("*** stlink_read_all_regs ***\n");
595 sl->backend->read_all_regs(sl, regp);
598 void stlink_read_all_unsupported_regs(stlink_t *sl, reg *regp) {
599 DLOG("*** stlink_read_all_unsupported_regs ***\n");
600 sl->backend->read_all_unsupported_regs(sl, regp);
603 void stlink_write_reg(stlink_t *sl, uint32_t reg, int idx) {
604 DLOG("*** stlink_write_reg\n");
605 sl->backend->write_reg(sl, reg, idx);
608 void stlink_read_reg(stlink_t *sl, int r_idx, reg *regp) {
609 DLOG("*** stlink_read_reg\n");
610 DLOG(" (%d) ***\n", r_idx);
612 if (r_idx > 20 || r_idx < 0) {
613 fprintf(stderr, "Error: register index must be in [0..20]\n");
617 sl->backend->read_reg(sl, r_idx, regp);
620 void stlink_read_unsupported_reg(stlink_t *sl, int r_idx, reg *regp) {
623 DLOG("*** stlink_read_unsupported_reg\n");
624 DLOG(" (%d) ***\n", r_idx);
626 /* Convert to values used by DCRSR */
627 if (r_idx >= 0x1C && r_idx <= 0x1F) { /* primask, basepri, faultmask, or control */
629 } else if (r_idx == 0x40) { /* FPSCR */
631 } else if (r_idx >= 0x20 && r_idx < 0x40) {
632 r_convert = 0x40 + (r_idx - 0x20);
634 fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
638 sl->backend->read_unsupported_reg(sl, r_convert, regp);
641 void stlink_write_unsupported_reg(stlink_t *sl, uint32_t val, int r_idx, reg *regp) {
644 DLOG("*** stlink_write_unsupported_reg\n");
645 DLOG(" (%d) ***\n", r_idx);
647 /* Convert to values used by DCRSR */
648 if (r_idx >= 0x1C && r_idx <= 0x1F) { /* primask, basepri, faultmask, or control */
649 r_convert = r_idx; /* The backend function handles this */
650 } else if (r_idx == 0x40) { /* FPSCR */
652 } else if (r_idx >= 0x20 && r_idx < 0x40) {
653 r_convert = 0x40 + (r_idx - 0x20);
655 fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
659 sl->backend->write_unsupported_reg(sl, val, r_convert, regp);
662 unsigned int is_core_halted(stlink_t *sl) {
663 /* return non zero if core is halted */
665 return sl->q_buf[0] == STLINK_CORE_HALTED;
668 void stlink_step(stlink_t *sl) {
669 DLOG("*** stlink_step ***\n");
670 sl->backend->step(sl);
673 int stlink_current_mode(stlink_t *sl) {
674 int mode = sl->backend->current_mode(sl);
676 case STLINK_DEV_DFU_MODE:
677 DLOG("stlink current mode: dfu\n");
679 case STLINK_DEV_DEBUG_MODE:
680 DLOG("stlink current mode: debug (jtag or swd)\n");
682 case STLINK_DEV_MASS_MODE:
683 DLOG("stlink current mode: mass\n");
686 DLOG("stlink mode: unknown!\n");
687 return STLINK_DEV_UNKNOWN_MODE;
693 // End of delegates.... Common code below here...
696 // http://www.ibm.com/developerworks/aix/library/au-endianc/index.html
698 // #define is_bigendian() ( (*(char*)&i) == 0 )
700 inline unsigned int is_bigendian(void) {
701 static volatile const unsigned int i = 1;
702 return *(volatile const char*) &i == 0;
705 uint16_t read_uint16(const unsigned char *c, const int pt) {
707 char *p = (char *) &ui;
709 if (!is_bigendian()) { // le -> le (don't swap)
719 // same as above with entrypoint.
721 void stlink_run_at(stlink_t *sl, stm32_addr_t addr) {
722 stlink_write_reg(sl, addr, 15); /* pc register */
726 while (is_core_halted(sl) == 0)
730 void stlink_core_stat(stlink_t *sl) {
734 switch (sl->q_buf[0]) {
735 case STLINK_CORE_RUNNING:
736 sl->core_stat = STLINK_CORE_RUNNING;
737 DLOG(" core status: running\n");
739 case STLINK_CORE_HALTED:
740 sl->core_stat = STLINK_CORE_HALTED;
741 DLOG(" core status: halted\n");
744 sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
745 fprintf(stderr, " core status: unknown\n");
749 void stlink_print_data(stlink_t * sl) {
750 if (sl->q_len <= 0 || sl->verbose < UDEBUG)
753 fprintf(stdout, "data_len = %d 0x%x\n", sl->q_len, sl->q_len);
755 for (int i = 0; i < sl->q_len; i++) {
758 if (sl->q_data_dir == Q_DATA_OUT)
759 fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
761 fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
764 fprintf(stdout, " %02x", (unsigned int) sl->q_buf[i]);
766 fputs("\n\n", stdout);
769 /* memory mapped file */
771 typedef struct mapped_file {
776 #define MAPPED_FILE_INITIALIZER { NULL, 0 }
778 static int map_file(mapped_file_t* mf, const char* path) {
782 const int fd = open(path, O_RDONLY | O_BINARY);
784 fprintf(stderr, "open(%s) == -1\n", path);
788 if (fstat(fd, &st) == -1) {
789 fprintf(stderr, "fstat() == -1\n");
793 mf->base = (uint8_t*) mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
794 if (mf->base == MAP_FAILED) {
795 fprintf(stderr, "mmap() == MAP_FAILED\n");
799 mf->len = st.st_size;
810 static void unmap_file(mapped_file_t * mf) {
811 munmap((void*) mf->base, mf->len);
812 mf->base = (unsigned char*) MAP_FAILED;
816 /* Limit the block size to compare to 0x1800
817 Anything larger will stall the STLINK2
818 Maybe STLINK V1 needs smaller value!*/
819 static int check_file(stlink_t* sl, mapped_file_t* mf, stm32_addr_t addr) {
821 size_t n_cmp = sl->flash_pgsz;
825 for (off = 0; off < mf->len; off += n_cmp) {
828 /* adjust last page size */
829 size_t cmp_size = n_cmp;
830 if ((off + n_cmp) > mf->len)
831 cmp_size = mf->len - off;
833 aligned_size = cmp_size;
834 if (aligned_size & (4 - 1))
835 aligned_size = (cmp_size + 4) & ~(4 - 1);
837 stlink_read_mem32(sl, addr + off, aligned_size);
839 if (memcmp(sl->q_buf, mf->base + off, cmp_size))
846 int stlink_fwrite_sram
847 (stlink_t * sl, const char* path, stm32_addr_t addr) {
848 /* write the file in sram at addr */
852 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
855 if (map_file(&mf, path) == -1) {
856 fprintf(stderr, "map_file() == -1\n");
860 /* check addr range is inside the sram */
861 if (addr < sl->sram_base) {
862 fprintf(stderr, "addr too low\n");
864 } else if ((addr + mf.len) < addr) {
865 fprintf(stderr, "addr overruns\n");
867 } else if ((addr + mf.len) > (sl->sram_base + sl->sram_size)) {
868 fprintf(stderr, "addr too high\n");
870 } else if ((addr & 3) || (mf.len & 3)) {
872 fprintf(stderr, "unaligned addr or size\n");
875 /* do the copy by 1k blocks */
876 for (off = 0; off < mf.len; off += 1024) {
878 if ((off + size) > mf.len)
881 memcpy(sl->q_buf, mf.base + off, size);
883 /* round size if needed */
887 stlink_write_mem32(sl, addr + off, size);
890 /* check the file ha been written */
891 if (check_file(sl, &mf, addr) == -1) {
892 fprintf(stderr, "check_file() == -1\n");
899 stlink_write_reg(sl, stlink_read_debug32(sl, addr ),13);
900 /* Set PC to the reset routine*/
901 stlink_write_reg(sl, stlink_read_debug32(sl, addr + 4),15);
909 int stlink_fread(stlink_t* sl, const char* path, stm32_addr_t addr, size_t size) {
910 /* read size bytes from addr to file */
915 unsigned char erased_pattern = (sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
916 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE) ? 0:0xff;
918 const int fd = open(path, O_RDWR | O_TRUNC | O_CREAT, 00700);
920 fprintf(stderr, "open(%s) == -1\n", path);
925 size = sl->flash_size;
927 if (size > sl->flash_size)
928 size = sl->flash_size;
930 /* do the copy by 1k blocks */
931 for (off = 0; off < size; off += 1024) {
932 size_t read_size = 1024;
935 if ((off + read_size) > size)
936 read_size = size - off;
938 /* round size if needed */
939 rounded_size = read_size;
940 if (rounded_size & 3)
941 rounded_size = (rounded_size + 4) & ~(3);
943 stlink_read_mem32(sl, addr + off, rounded_size);
945 for(index = 0; index < read_size; index ++) {
946 if (sl->q_buf[index] == erased_pattern)
951 if (write(fd, sl->q_buf, read_size) != (ssize_t) read_size) {
952 fprintf(stderr, "write() != read_size\n");
957 /* Ignore NULL Bytes at end of file */
958 if (!ftruncate(fd, size - num_empty)) {
971 int write_buffer_to_sram(stlink_t *sl, flash_loader_t* fl, const uint8_t* buf, size_t size) {
972 /* write the buffer right after the loader */
973 size_t chunk = size & ~0x3;
974 size_t rem = size & 0x3;
976 memcpy(sl->q_buf, buf, chunk);
977 stlink_write_mem32(sl, fl->buf_addr, chunk);
980 memcpy(sl->q_buf, buf+chunk, rem);
981 stlink_write_mem8(sl, (fl->buf_addr)+chunk, rem);
986 uint32_t calculate_F4_sectornum(uint32_t flashaddr){
987 flashaddr &= ~STM32_FLASH_BASE; //Page now holding the actual flash address
988 if (flashaddr<0x4000) return (0);
989 else if(flashaddr<0x8000) return(1);
990 else if(flashaddr<0xc000) return(2);
991 else if(flashaddr<0x10000) return(3);
992 else if(flashaddr<0x20000) return(4);
993 else return(flashaddr/0x20000)+4;
997 uint32_t stlink_calculate_pagesize(stlink_t *sl, uint32_t flashaddr){
998 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
999 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD)) {
1000 uint32_t sector=calculate_F4_sectornum(flashaddr);
1001 if (sector<4) sl->flash_pgsz=0x4000;
1002 else if(sector<5) sl->flash_pgsz=0x10000;
1003 else sl->flash_pgsz=0x20000;
1005 return (sl->flash_pgsz);
1009 * Erase a page of flash, assumes sl is fully populated with things like chip/core ids
1010 * @param sl stlink context
1011 * @param flashaddr an address in the flash page to erase
1012 * @return 0 on success -ve on failure
1014 int stlink_erase_flash_page(stlink_t *sl, stm32_addr_t flashaddr)
1016 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
1017 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD)) {
1018 /* wait for ongoing op to finish */
1019 wait_flash_busy(sl);
1021 /* unlock if locked */
1022 unlock_flash_if(sl);
1024 /* select the page to erase */
1025 // calculate the actual page from the address
1026 uint32_t sector=calculate_F4_sectornum(flashaddr);
1028 fprintf(stderr, "EraseFlash - Sector:0x%x Size:0x%x\n", sector, stlink_calculate_pagesize(sl, flashaddr));
1029 write_flash_cr_snb(sl, sector);
1031 /* start erase operation */
1032 set_flash_cr_strt(sl);
1034 /* wait for completion */
1035 wait_flash_busy(sl);
1037 /* relock the flash */
1038 //todo: fails to program if this is in
1041 fprintf(stdout, "Erase Final CR:0x%x\n", read_flash_cr(sl));
1043 } else if (sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
1044 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE) {
1048 /* check if the locks are set */
1049 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1050 if((val & (1<<0))||(val & (1<<1))) {
1051 /* disable pecr protection */
1052 stlink_write_debug32(sl, STM32L_FLASH_PEKEYR, 0x89abcdef);
1053 stlink_write_debug32(sl, STM32L_FLASH_PEKEYR, 0x02030405);
1055 /* check pecr.pelock is cleared */
1056 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1057 if (val & (1 << 0)) {
1058 WLOG("pecr.pelock not clear (%#x)\n", val);
1062 /* unlock program memory */
1063 stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x8c9daebf);
1064 stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x13141516);
1066 /* check pecr.prglock is cleared */
1067 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1068 if (val & (1 << 1)) {
1069 WLOG("pecr.prglock not clear (%#x)\n", val);
1074 /* set pecr.{erase,prog} */
1075 val |= (1 << 9) | (1 << 3);
1076 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1078 #if 0 /* fix_to_be_confirmed */
1080 /* wait for sr.busy to be cleared
1081 * MP: Test shows that busy bit is not set here. Perhaps, PM0062 is
1082 * wrong and we do not need to wait here for clearing the busy bit.
1083 * TEXANE: ok, if experience says so and it works for you, we comment
1084 * it. If someone has a problem, please drop an email.
1086 while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0)
1089 #endif /* fix_to_be_confirmed */
1091 /* write 0 to the first word of the page to be erased */
1092 stlink_write_debug32(sl, flashaddr, 0);
1094 /* MP: It is better to wait for clearing the busy bit after issuing
1095 page erase command, even though PM0062 recommends to wait before it.
1096 Test shows that a few iterations is performed in the following loop
1097 before busy bit is cleared.*/
1098 while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0)
1101 /* reset lock bits */
1102 val = stlink_read_debug32(sl, STM32L_FLASH_PECR)
1103 | (1 << 0) | (1 << 1) | (1 << 2);
1104 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1105 } else if (sl->core_id == STM32VL_CORE_ID
1106 || sl->core_id == STM32F0_CORE_ID
1107 || sl->chip_id == STM32_CHIPID_F3
1108 || sl->chip_id == STM32_CHIPID_F37x) {
1109 /* wait for ongoing op to finish */
1110 wait_flash_busy(sl);
1112 /* unlock if locked */
1113 unlock_flash_if(sl);
1115 /* set the page erase bit */
1116 set_flash_cr_per(sl);
1118 /* select the page to erase */
1119 write_flash_ar(sl, flashaddr);
1121 /* start erase operation, reset by hw with bsy bit */
1122 set_flash_cr_strt(sl);
1124 /* wait for completion */
1125 wait_flash_busy(sl);
1127 /* relock the flash */
1130 WLOG("unknown coreid %x, page erase failed\n", sl->core_id);
1134 /* todo: verify the erased page */
1139 int stlink_erase_flash_mass(stlink_t *sl) {
1140 if (sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
1141 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE) {
1142 /* erase each page */
1143 int i = 0, num_pages = sl->flash_size/sl->flash_pgsz;
1144 for (i = 0; i < num_pages; i++) {
1145 /* addr must be an addr inside the page */
1146 stm32_addr_t addr = sl->flash_base + i * sl->flash_pgsz;
1147 if (stlink_erase_flash_page(sl, addr) == -1) {
1148 WLOG("Failed to erase_flash_page(%#zx) == -1\n", addr);
1151 fprintf(stdout,"\rFlash page at %5d/%5d erased", i, num_pages);
1154 fprintf(stdout, "\n");
1156 /* wait for ongoing op to finish */
1157 wait_flash_busy(sl);
1159 /* unlock if locked */
1160 unlock_flash_if(sl);
1162 /* set the mass erase bit */
1163 set_flash_cr_mer(sl);
1165 /* start erase operation, reset by hw with bsy bit */
1166 set_flash_cr_strt(sl);
1168 /* wait for completion */
1169 wait_flash_busy_progress(sl);
1171 /* relock the flash */
1174 /* todo: verify the erased memory */
1179 int init_flash_loader(stlink_t *sl, flash_loader_t* fl) {
1182 /* allocate the loader in sram */
1183 if (write_loader_to_sram(sl, &fl->loader_addr, &size) == -1) {
1184 WLOG("Failed to write flash loader to sram!\n");
1188 /* allocate a one page buffer in sram right after loader */
1189 fl->buf_addr = fl->loader_addr + size;
1190 ILOG("Successfully loaded flash loader in sram\n");
1194 int write_loader_to_sram(stlink_t *sl, stm32_addr_t* addr, size_t* size) {
1195 /* from openocd, contrib/loaders/flash/stm32.s */
1196 static const uint8_t loader_code_stm32vl[] = {
1197 0x08, 0x4c, /* ldr r4, STM32_FLASH_BASE */
1198 0x1c, 0x44, /* add r4, r3 */
1199 /* write_half_word: */
1200 0x01, 0x23, /* movs r3, #0x01 */
1201 0x23, 0x61, /* str r3, [r4, #STM32_FLASH_CR_OFFSET] */
1202 0x30, 0xf8, 0x02, 0x3b, /* ldrh r3, [r0], #0x02 */
1203 0x21, 0xf8, 0x02, 0x3b, /* strh r3, [r1], #0x02 */
1205 0xe3, 0x68, /* ldr r3, [r4, #STM32_FLASH_SR_OFFSET] */
1206 0x13, 0xf0, 0x01, 0x0f, /* tst r3, #0x01 */
1207 0xfb, 0xd0, /* beq busy */
1208 0x13, 0xf0, 0x14, 0x0f, /* tst r3, #0x14 */
1209 0x01, 0xd1, /* bne exit */
1210 0x01, 0x3a, /* subs r2, r2, #0x01 */
1211 0xf0, 0xd1, /* bne write_half_word */
1213 0x00, 0xbe, /* bkpt #0x00 */
1214 0x00, 0x20, 0x02, 0x40, /* STM32_FLASH_BASE: .word 0x40022000 */
1217 /* flashloaders/stm32f0.s -- thumb1 only, same sequence as for STM32VL, bank ignored */
1218 static const uint8_t loader_code_stm32f0[] = {
1221 * These two NOPs here are a safety precaution, added by Pekka Nikander
1222 * while debugging the STM32F05x support. They may not be needed, but
1223 * there were strange problems with simpler programs, like a program
1224 * that had just a breakpoint or a program that first moved zero to register r2
1225 * and then had a breakpoint. So, it appears safest to have these two nops.
1227 * Feel free to remove them, if you dare, but then please do test the result
1228 * rigorously. Also, if you remove these, it may be a good idea first to
1229 * #if 0 them out, with a comment when these were taken out, and to remove
1230 * these only a few months later... But YMMV.
1232 0x00, 0x30, // nop /* add r0,#0 */
1233 0x00, 0x30, // nop /* add r0,#0 */
1235 0x0A, 0x4C, // ldr r4, STM32_FLASH_BASE
1236 0x01, 0x25, // mov r5, #1 /* FLASH_CR_PG, FLASH_SR_BUSY */
1237 0x04, 0x26, // mov r6, #4 /* PGERR */
1239 0x23, 0x69, // ldr r3, [r4, #16] /* FLASH->CR */
1240 0x2B, 0x43, // orr r3, r5
1241 0x23, 0x61, // str r3, [r4, #16] /* FLASH->CR |= FLASH_CR_PG */
1242 0x03, 0x88, // ldrh r3, [r0] /* r3 = *sram */
1243 0x0B, 0x80, // strh r3, [r1] /* *flash = r3 */
1245 0xE3, 0x68, // ldr r3, [r4, #12] /* FLASH->SR */
1246 0x2B, 0x42, // tst r3, r5 /* FLASH_SR_BUSY */
1247 0xFC, 0xD0, // beq busy
1249 0x33, 0x42, // tst r3, r6 /* PGERR */
1250 0x04, 0xD1, // bne exit
1252 0x02, 0x30, // add r0, r0, #2 /* sram += 2 */
1253 0x02, 0x31, // add r1, r1, #2 /* flash += 2 */
1254 0x01, 0x3A, // sub r2, r2, #0x01 /* count-- */
1255 0x00, 0x2A, // cmp r2, #0
1256 0xF0, 0xD1, // bne write_half_word
1258 0x23, 0x69, // ldr r3, [r4, #16] /* FLASH->CR */
1259 0xAB, 0x43, // bic r3, r5
1260 0x23, 0x61, // str r3, [r4, #16] /* FLASH->CR &= ~FLASH_CR_PG */
1261 0x00, 0xBE, // bkpt #0x00
1262 0x00, 0x20, 0x02, 0x40, /* STM32_FLASH_BASE: .word 0x40022000 */
1265 static const uint8_t loader_code_stm32l[] = {
1267 /* openocd.git/contrib/loaders/flash/stm32lx.S
1268 r0, input, dest addr
1269 r1, input, source addr
1270 r2, input, word count
1271 r3, output, word count
1277 0x51, 0xf8, 0x04, 0xcb,
1278 0x40, 0xf8, 0x04, 0xcb,
1286 static const uint8_t loader_code_stm32f4[] = {
1287 // flashloaders/stm32f4.s
1296 0x14, 0xf0, 0x01, 0x0f,
1298 0x00, 0xf1, 0x04, 0x00,
1299 0x01, 0xf1, 0x04, 0x01,
1300 0xa2, 0xf1, 0x01, 0x02,
1305 0x00, 0x3c, 0x02, 0x40,
1308 const uint8_t* loader_code;
1311 if (sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
1312 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE ) { /* stm32l */
1313 loader_code = loader_code_stm32l;
1314 loader_size = sizeof(loader_code_stm32l);
1315 } else if (sl->core_id == STM32VL_CORE_ID || sl->chip_id == STM32_CHIPID_F3 || sl->chip_id == STM32_CHIPID_F37x) {
1316 loader_code = loader_code_stm32vl;
1317 loader_size = sizeof(loader_code_stm32vl);
1318 } else if (sl->chip_id == STM32_CHIPID_F2 || sl->chip_id == STM32_CHIPID_F4 || (sl->chip_id == STM32_CHIPID_F4_DE) ||
1319 sl->chip_id == STM32_CHIPID_F4_LP || sl->chip_id == STM32_CHIPID_F4_HD){
1320 loader_code = loader_code_stm32f4;
1321 loader_size = sizeof(loader_code_stm32f4);
1322 } else if (sl->chip_id == STM32_CHIPID_F0 || sl->chip_id == STM32_CHIPID_F0_CAN || sl->chip_id == STM32_CHIPID_F0_SMALL) {
1323 loader_code = loader_code_stm32f0;
1324 loader_size = sizeof(loader_code_stm32f0);
1326 ELOG("unknown coreid, not sure what flash loader to use, aborting!: %x\n", sl->core_id);
1330 memcpy(sl->q_buf, loader_code, loader_size);
1331 stlink_write_mem32(sl, sl->sram_base, loader_size);
1333 *addr = sl->sram_base;
1334 *size = loader_size;
1340 int stlink_fcheck_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
1341 /* check the contents of path are at addr */
1344 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1346 if (map_file(&mf, path) == -1)
1349 res = check_file(sl, &mf, addr);
1357 * Verify addr..addr+len is binary identical to base...base+len
1358 * @param sl stlink context
1359 * @param address stm device address
1360 * @param data host side buffer to check against
1361 * @param length how much
1362 * @return 0 for success, -ve for failure
1364 int stlink_verify_write_flash(stlink_t *sl, stm32_addr_t address, uint8_t *data, unsigned length) {
1366 size_t cmp_size = (sl->flash_pgsz > 0x1800)? 0x1800:sl->flash_pgsz;
1367 ILOG("Starting verification of write complete\n");
1368 for (off = 0; off < length; off += cmp_size) {
1369 size_t aligned_size;
1371 /* adjust last page size */
1372 if ((off + cmp_size) > length)
1373 cmp_size = length - off;
1375 aligned_size = cmp_size;
1376 if (aligned_size & (4 - 1))
1377 aligned_size = (cmp_size + 4) & ~(4 - 1);
1379 stlink_read_mem32(sl, address + off, aligned_size);
1381 if (memcmp(sl->q_buf, data + off, cmp_size)) {
1382 ELOG("Verification of flash failed at offset: %zd\n", off);
1386 ILOG("Flash written and verified! jolly good!\n");
1391 int stm32l1_write_half_pages(stlink_t *sl, stm32_addr_t addr, uint8_t* base, unsigned num_half_pages)
1397 ILOG("Starting Half page flash write for STM32L core id\n");
1398 /* flash loader initialization */
1399 if (init_flash_loader(sl, &fl) == -1) {
1400 WLOG("init_flash_loader() == -1\n");
1403 /* Unlock already done */
1404 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1405 val |= (1 << FLASH_L1_FPRG);
1406 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1408 val |= (1 << FLASH_L1_PROG);
1409 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1410 while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0) {}
1412 #define L1_WRITE_BLOCK_SIZE 0x80
1413 for (count = 0; count < num_half_pages; count ++) {
1414 if (run_flash_loader(sl, &fl, addr + count * L1_WRITE_BLOCK_SIZE, base + count * L1_WRITE_BLOCK_SIZE, L1_WRITE_BLOCK_SIZE) == -1) {
1415 WLOG("l1_run_flash_loader(%#zx) failed! == -1\n", addr + count * L1_WRITE_BLOCK_SIZE);
1416 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1417 val &= ~((1 << FLASH_L1_FPRG) |(1 << FLASH_L1_PROG));
1418 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1421 /* wait for sr.busy to be cleared */
1422 if (sl->verbose >= 1) {
1423 /* show progress. writing procedure is slow
1424 and previous errors are misleading */
1425 fprintf(stdout, "\r%3u/%u halfpages written", count + 1, num_half_pages);
1428 while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0) {
1431 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1432 val &= ~(1 << FLASH_L1_PROG);
1433 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1434 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1435 val &= ~(1 << FLASH_L1_FPRG);
1436 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1441 int stlink_write_flash(stlink_t *sl, stm32_addr_t addr, uint8_t* base, uint32_t len) {
1444 ILOG("Attempting to write %d (%#x) bytes to stm32 address: %u (%#x)\n",
1445 len, len, addr, addr);
1446 /* check addr range is inside the flash */
1447 stlink_calculate_pagesize(sl, addr);
1448 if (addr < sl->flash_base) {
1449 ELOG("addr too low %#x < %#x\n", addr, sl->flash_base);
1451 } else if ((addr + len) < addr) {
1452 ELOG("addr overruns\n");
1454 } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
1455 ELOG("addr too high\n");
1457 } else if (addr & 1) {
1458 ELOG("unaligned addr 0x%x\n", addr);
1460 } else if (len & 1) {
1461 WLOG("unaligned len 0x%x -- padding with zero\n", len);
1463 } else if (addr & (sl->flash_pgsz - 1)) {
1464 ELOG("addr not a multiple of pagesize, not supported\n");
1468 // Make sure we've loaded the context with the chip details
1470 /* erase each page */
1472 for (off = 0; off < len; off += stlink_calculate_pagesize(sl, addr + off)) {
1473 /* addr must be an addr inside the page */
1474 if (stlink_erase_flash_page(sl, addr + off) == -1) {
1475 ELOG("Failed to erase_flash_page(%#zx) == -1\n", addr + off);
1478 fprintf(stdout,"\rFlash page at addr: 0x%08lx erased",
1479 (unsigned long)addr + off);
1483 fprintf(stdout,"\n");
1484 ILOG("Finished erasing %d pages of %d (%#x) bytes\n",
1485 page_count, sl->flash_pgsz, sl->flash_pgsz);
1487 if ((sl->chip_id == STM32_CHIPID_F2) || (sl->chip_id == STM32_CHIPID_F4) || (sl->chip_id == STM32_CHIPID_F4_DE) ||
1488 (sl->chip_id == STM32_CHIPID_F4_LP) || (sl->chip_id == STM32_CHIPID_F4_HD)) {
1489 /* todo: check write operation */
1491 ILOG("Starting Flash write for F2/F4\n");
1492 /* flash loader initialization */
1493 if (init_flash_loader(sl, &fl) == -1) {
1494 ELOG("init_flash_loader() == -1\n");
1498 /* First unlock the cr */
1499 unlock_flash_if(sl);
1501 /* TODO: Check that Voltage range is 2.7 - 3.6 V */
1502 /* set parallelisim to 32 bit*/
1503 write_flash_cr_psiz(sl, 2);
1505 /* set programming mode */
1506 set_flash_cr_pg(sl);
1508 for(off = 0; off < len;) {
1509 size_t size = len - off > 0x8000 ? 0x8000 : len - off;
1511 printf("size: %zu\n", size);
1513 if (run_flash_loader(sl, &fl, addr + off, base + off, size) == -1) {
1514 ELOG("run_flash_loader(%#zx) failed! == -1\n", addr + off);
1526 else if (sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
1527 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE ) {
1528 /* use fast word write. todo: half page. */
1531 /* todo: check write operation */
1533 /* disable pecr protection */
1534 stlink_write_debug32(sl, STM32L_FLASH_PEKEYR, 0x89abcdef);
1535 stlink_write_debug32(sl, STM32L_FLASH_PEKEYR, 0x02030405);
1537 /* check pecr.pelock is cleared */
1538 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1539 if (val & (1 << 0)) {
1540 fprintf(stderr, "pecr.pelock not clear\n");
1544 /* unlock program memory */
1545 stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x8c9daebf);
1546 stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x13141516);
1548 /* check pecr.prglock is cleared */
1549 val = stlink_read_debug32(sl, STM32L_FLASH_PECR);
1550 if (val & (1 << 1)) {
1551 fprintf(stderr, "pecr.prglock not clear\n");
1555 if (len > L1_WRITE_BLOCK_SIZE) {
1556 if (stm32l1_write_half_pages(sl, addr, base, len/L1_WRITE_BLOCK_SIZE) == -1) {
1557 /* This may happen on a blank device! */
1558 WLOG("\nwrite_half_pages failed == -1\n");
1560 off = (len /L1_WRITE_BLOCK_SIZE)*L1_WRITE_BLOCK_SIZE;
1564 /* write remainingword in program memory */
1565 for ( ; off < len; off += sizeof(uint32_t)) {
1568 fprintf(stdout, "\r");
1570 if ((off % sl->flash_pgsz) > (sl->flash_pgsz -5)) {
1571 fprintf(stdout, "\r%3zd/%3zd pages written",
1572 off/sl->flash_pgsz, len/sl->flash_pgsz);
1576 write_uint32((unsigned char*) &data, *(uint32_t*) (base + off));
1577 stlink_write_debug32(sl, addr + off, data);
1579 /* wait for sr.busy to be cleared */
1580 while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0)
1583 /* todo: check redo write operation */
1586 fprintf(stdout, "\n");
1587 /* reset lock bits */
1588 val = stlink_read_debug32(sl, STM32L_FLASH_PECR)
1589 | (1 << 0) | (1 << 1) | (1 << 2);
1590 stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1591 } else if (sl->core_id == STM32VL_CORE_ID || sl->core_id == STM32F0_CORE_ID || sl->chip_id == STM32_CHIPID_F3 || sl->chip_id == STM32_CHIPID_F37x) {
1592 ILOG("Starting Flash write for VL/F0 core id\n");
1593 /* flash loader initialization */
1594 if (init_flash_loader(sl, &fl) == -1) {
1595 ELOG("init_flash_loader() == -1\n");
1599 int write_block_count = 0;
1600 for (off = 0; off < len; off += sl->flash_pgsz) {
1601 /* adjust last write size */
1602 size_t size = sl->flash_pgsz;
1603 if ((off + sl->flash_pgsz) > len) size = len - off;
1605 /* unlock and set programming mode */
1606 unlock_flash_if(sl);
1607 set_flash_cr_pg(sl);
1608 //DLOG("Finished setting flash cr pg, running loader!\n");
1609 if (run_flash_loader(sl, &fl, addr + off, base + off, size) == -1) {
1610 ELOG("run_flash_loader(%#zx) failed! == -1\n", addr + off);
1614 if (sl->verbose >= 1) {
1615 /* show progress. writing procedure is slow
1616 and previous errors are misleading */
1617 fprintf(stdout, "\r%3u/%lu pages written", write_block_count++, (unsigned long)len/sl->flash_pgsz);
1621 fprintf(stdout, "\n");
1623 ELOG("unknown coreid, not sure how to write: %x\n", sl->core_id);
1627 return stlink_verify_write_flash(sl, addr, base, len);
1631 * Write the given binary file into flash at address "addr"
1633 * @param path readable file path, should be binary image
1634 * @param addr where to start writing
1635 * @return 0 on success, -ve on failure.
1637 int stlink_fwrite_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
1638 /* write the file in flash at addr */
1640 unsigned int num_empty = 0, index;
1641 unsigned char erased_pattern =(sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
1642 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE )?0:0xff;
1643 mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1644 if (map_file(&mf, path) == -1) {
1645 ELOG("map_file() == -1\n");
1648 for(index = 0; index < mf.len; index ++) {
1649 if (mf.base[index] == erased_pattern)
1654 /* Round down to words */
1655 num_empty -= (num_empty & 3);
1656 if(num_empty != 0) {
1657 ILOG("Ignoring %d bytes of 0x%02x at end of file\n", num_empty, erased_pattern);
1658 mf.len -= num_empty;
1660 err = stlink_write_flash(sl, addr, mf.base, mf.len);
1662 stlink_write_reg(sl, stlink_read_debug32(sl, addr ),13);
1663 /* Set PC to the reset routine*/
1664 stlink_write_reg(sl, stlink_read_debug32(sl, addr + 4),15);
1670 int run_flash_loader(stlink_t *sl, flash_loader_t* fl, stm32_addr_t target, const uint8_t* buf, size_t size) {
1674 DLOG("Running flash loader, write address:%#x, size: %zd\n", target, size);
1675 // FIXME This can never return -1
1676 if (write_buffer_to_sram(sl, fl, buf, size) == -1) {
1678 ELOG("write_buffer_to_sram() == -1\n");
1682 if (sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
1683 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE ) {
1685 size_t count = size / sizeof(uint32_t);
1686 if (size % sizeof(uint32_t)) ++count;
1689 stlink_write_reg(sl, target, 0); /* target */
1690 stlink_write_reg(sl, fl->buf_addr, 1); /* source */
1691 stlink_write_reg(sl, count, 2); /* count (32 bits words) */
1692 stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
1694 } else if (sl->core_id == STM32VL_CORE_ID || sl->core_id == STM32F0_CORE_ID || sl->chip_id == STM32_CHIPID_F3 || sl->chip_id == STM32_CHIPID_F37x) {
1696 size_t count = size / sizeof(uint16_t);
1697 if (size % sizeof(uint16_t)) ++count;
1700 stlink_write_reg(sl, fl->buf_addr, 0); /* source */
1701 stlink_write_reg(sl, target, 1); /* target */
1702 stlink_write_reg(sl, count, 2); /* count (16 bits half words) */
1703 stlink_write_reg(sl, 0, 3); /* flash bank 0 (input) */
1704 stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
1706 } else if (sl->chip_id == STM32_CHIPID_F2 || sl->chip_id == STM32_CHIPID_F4 || (sl->chip_id == STM32_CHIPID_F4_DE) ||
1707 sl->chip_id == STM32_CHIPID_F4_LP || sl->chip_id == STM32_CHIPID_F4_HD) {
1709 size_t count = size / sizeof(uint32_t);
1710 if (size % sizeof(uint32_t)) ++count;
1713 stlink_write_reg(sl, fl->buf_addr, 0); /* source */
1714 stlink_write_reg(sl, target, 1); /* target */
1715 stlink_write_reg(sl, count, 2); /* count (32 bits words) */
1716 stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
1719 fprintf(stderr, "unknown coreid 0x%x, don't know what flash loader to use\n", sl->core_id);
1726 #define WAIT_ROUNDS 10000
1727 /* wait until done (reaches breakpoint) */
1728 for (i = 0; i < WAIT_ROUNDS; i++) {
1730 if (is_core_halted(sl))
1734 if (i >= WAIT_ROUNDS) {
1735 ELOG("flash loader run error\n");
1739 /* check written byte count */
1740 if (sl->chip_id == STM32_CHIPID_L1_MEDIUM || sl->chip_id == STM32_CHIPID_L1_MEDIUM_PLUS
1741 || sl->chip_id == STM32_CHIPID_L1_HIGH || sl->chip_id == STM32_CHIPID_L152_RE ) {
1743 size_t count = size / sizeof(uint32_t);
1744 if (size % sizeof(uint32_t)) ++count;
1746 stlink_read_reg(sl, 3, &rr);
1747 if (rr.r[3] != count) {
1748 fprintf(stderr, "write error, count == %u\n", rr.r[3]);
1752 } else if (sl->core_id == STM32VL_CORE_ID || sl->core_id == STM32F0_CORE_ID || sl->chip_id == STM32_CHIPID_F3 || sl->chip_id == STM32_CHIPID_F37x) {
1754 stlink_read_reg(sl, 2, &rr);
1756 fprintf(stderr, "write error, count == %u\n", rr.r[2]);
1760 } else if (sl->chip_id == STM32_CHIPID_F2 || sl->chip_id == STM32_CHIPID_F4 || (sl->chip_id == STM32_CHIPID_F4_DE) ||
1761 sl->chip_id == STM32_CHIPID_F4_LP || sl->chip_id == STM32_CHIPID_F4_HD) {
1763 stlink_read_reg(sl, 2, &rr);
1765 fprintf(stderr, "write error, count == %u\n", rr.r[2]);
1771 fprintf(stderr, "unknown coreid 0x%x, can't check written byte count\n", sl->core_id);