Move STLINK_DEBUG_* defines into enum, move flash_loader code into seperate header...
[fw/stlink] / src / common.c
1 #define DEBUG_FLASH 0
2
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12
13 #include "stlink.h"
14 #include "stlink/mmap.h"
15 #include "stlink/logging.h"
16
17 #ifndef _WIN32
18 #define O_BINARY 0
19 #endif
20
21 /* todo: stm32l15xxx flash memory, pm0062 manual */
22
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
28
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)
36
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
41
42 #define FLASH_SR_BSY 0
43 #define FLASH_SR_EOP 5
44
45 #define FLASH_CR_PG 0
46 #define FLASH_CR_PER 1
47 #define FLASH_CR_MER 2
48 #define FLASH_CR_STRT 6
49 #define FLASH_CR_LOCK 7
50
51
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
65
66 //32L4 register base is at FLASH_REGS_ADDR (0x40022000)
67 #define STM32L4_FLASH_KEYR      (FLASH_REGS_ADDR + 0x08)
68 #define STM32L4_FLASH_SR        (FLASH_REGS_ADDR + 0x10)
69 #define STM32L4_FLASH_CR        (FLASH_REGS_ADDR + 0x14)
70 #define STM32L4_FLASH_OPTR      (FLASH_REGS_ADDR + 0x20)
71
72 #define STM32L4_FLASH_SR_BSY            16
73 #define STM32L4_FLASH_SR_ERRMASK        0x3f8 /* SR [9:3] */
74
75 #define STM32L4_FLASH_CR_LOCK   31      /* Lock control register */
76 #define STM32L4_FLASH_CR_PG     0       /* Program */
77 #define STM32L4_FLASH_CR_PER    1       /* Page erase */
78 #define STM32L4_FLASH_CR_MER1   2       /* Bank 1 erase */
79 #define STM32L4_FLASH_CR_MER2   15      /* Bank 2 erase */
80 #define STM32L4_FLASH_CR_STRT   16      /* Start command */
81 #define STM32L4_FLASH_CR_BKER   11      /* Bank select for page erase */
82 #define STM32L4_FLASH_CR_PNB    3       /* Page number (8 bits) */
83 // Bits requesting flash operations (useful when we want to clear them)
84 #define STM32L4_FLASH_CR_OPBITS                                     \
85     ((1lu<<STM32L4_FLASH_CR_PG) | (1lu<<STM32L4_FLASH_CR_PER)       \
86     | (1lu<<STM32L4_FLASH_CR_MER1) | (1lu<<STM32L4_FLASH_CR_MER1))
87 // Page is fully specified by BKER and PNB
88 #define STM32L4_FLASH_CR_PAGEMASK (0x1fflu << STM32L4_FLASH_CR_PNB)
89
90 #define STM32L4_FLASH_OPTR_DUALBANK     21
91
92 //STM32L0x flash register base and offsets
93 //same as 32L1 above
94 // RM0090 - DM00031020.pdf
95 #define STM32L0_FLASH_REGS_ADDR ((uint32_t)0x40022000)
96 #define FLASH_ACR_OFF     ((uint32_t) 0x00)
97 #define FLASH_PECR_OFF    ((uint32_t) 0x04)
98 #define FLASH_PDKEYR_OFF  ((uint32_t) 0x08)
99 #define FLASH_PEKEYR_OFF  ((uint32_t) 0x0c)
100 #define FLASH_PRGKEYR_OFF ((uint32_t) 0x10)
101 #define FLASH_OPTKEYR_OFF ((uint32_t) 0x14)
102 #define FLASH_SR_OFF      ((uint32_t) 0x18)
103 #define FLASH_OBR_OFF     ((uint32_t) 0x1c)
104 #define FLASH_WRPR_OFF    ((uint32_t) 0x20)
105
106
107
108 //STM32F4
109 #define FLASH_F4_REGS_ADDR ((uint32_t)0x40023c00)
110 #define FLASH_F4_KEYR (FLASH_F4_REGS_ADDR + 0x04)
111 #define FLASH_F4_OPT_KEYR (FLASH_F4_REGS_ADDR + 0x08)
112 #define FLASH_F4_SR (FLASH_F4_REGS_ADDR + 0x0c)
113 #define FLASH_F4_CR (FLASH_F4_REGS_ADDR + 0x10)
114 #define FLASH_F4_OPT_CR (FLASH_F4_REGS_ADDR + 0x14)
115 #define FLASH_F4_CR_STRT 16
116 #define FLASH_F4_CR_LOCK 31
117 #define FLASH_F4_CR_SER 1
118 #define FLASH_F4_CR_SNB 3
119 #define FLASH_F4_CR_SNB_MASK 0xf8
120 #define FLASH_F4_SR_BSY 16
121
122 #define L1_WRITE_BLOCK_SIZE 0x80
123 #define L0_WRITE_BLOCK_SIZE 0x40
124
125 void write_uint32(unsigned char* buf, uint32_t ui) {
126     if (!is_bigendian()) { // le -> le (don't swap)
127         buf[0] = ((unsigned char*) &ui)[0];
128         buf[1] = ((unsigned char*) &ui)[1];
129         buf[2] = ((unsigned char*) &ui)[2];
130         buf[3] = ((unsigned char*) &ui)[3];
131     } else {
132         buf[0] = ((unsigned char*) &ui)[3];
133         buf[1] = ((unsigned char*) &ui)[2];
134         buf[2] = ((unsigned char*) &ui)[1];
135         buf[3] = ((unsigned char*) &ui)[0];
136     }
137 }
138
139 void write_uint16(unsigned char* buf, uint16_t ui) {
140     if (!is_bigendian()) { // le -> le (don't swap)
141         buf[0] = ((unsigned char*) &ui)[0];
142         buf[1] = ((unsigned char*) &ui)[1];
143     } else {
144         buf[0] = ((unsigned char*) &ui)[1];
145         buf[1] = ((unsigned char*) &ui)[0];
146     }
147 }
148
149 uint32_t read_uint32(const unsigned char *c, const int pt) {
150     uint32_t ui;
151     char *p = (char *) &ui;
152
153     if (!is_bigendian()) { // le -> le (don't swap)
154         p[0] = c[pt + 0];
155         p[1] = c[pt + 1];
156         p[2] = c[pt + 2];
157         p[3] = c[pt + 3];
158     } else {
159         p[0] = c[pt + 3];
160         p[1] = c[pt + 2];
161         p[2] = c[pt + 1];
162         p[3] = c[pt + 0];
163     }
164     return ui;
165 }
166
167 static uint32_t __attribute__((unused)) read_flash_rdp(stlink_t *sl) {
168     uint32_t rdp;
169     stlink_read_debug32(sl, FLASH_WRPR, &rdp);
170     return rdp & 0xff;
171 }
172
173 static inline uint32_t read_flash_wrpr(stlink_t *sl) {
174     uint32_t wrpr;
175     stlink_read_debug32(sl, FLASH_WRPR, &wrpr);
176     return wrpr;
177 }
178
179 static inline uint32_t read_flash_obr(stlink_t *sl) {
180     uint32_t obr;
181     stlink_read_debug32(sl, FLASH_OBR, &obr);
182     return obr;
183 }
184
185 static inline uint32_t read_flash_cr(stlink_t *sl) {
186     uint32_t reg, res;
187
188     if (sl->flash_type == FLASH_TYPE_F4)
189         reg = FLASH_F4_CR;
190     else if (sl->flash_type == FLASH_TYPE_L4)
191         reg = STM32L4_FLASH_CR;
192     else
193         reg = FLASH_CR;
194
195     stlink_read_debug32(sl, reg, &res);
196
197 #if DEBUG_FLASH
198     fprintf(stdout, "CR:0x%x\n", res);
199 #endif
200     return res;
201 }
202
203 static inline unsigned int is_flash_locked(stlink_t *sl) {
204     /* return non zero for true */
205     uint32_t cr_lock_shift, cr = read_flash_cr(sl);
206
207     if (sl->flash_type == FLASH_TYPE_F4)
208         cr_lock_shift = FLASH_F4_CR_LOCK;
209     else if (sl->flash_type == FLASH_TYPE_L4)
210         cr_lock_shift = STM32L4_FLASH_CR_LOCK;
211     else
212         cr_lock_shift = FLASH_CR_LOCK;
213
214     return cr & (1 << cr_lock_shift);
215 }
216
217 static void unlock_flash(stlink_t *sl) {
218     uint32_t key_reg;
219     /* the unlock sequence consists of 2 write cycles where
220        2 key values are written to the FLASH_KEYR register.
221        an invalid sequence results in a definitive lock of
222        the FPEC block until next reset.
223        */
224     if (sl->flash_type == FLASH_TYPE_F4)
225         key_reg = FLASH_F4_KEYR;
226     else if (sl->flash_type == FLASH_TYPE_L4)
227         key_reg = STM32L4_FLASH_KEYR;
228     else
229         key_reg = FLASH_KEYR;
230
231     stlink_write_debug32(sl, key_reg, FLASH_KEY1);
232     stlink_write_debug32(sl, key_reg, FLASH_KEY2);
233 }
234
235 static int unlock_flash_if(stlink_t *sl) {
236     /* unlock flash if already locked */
237
238     if (is_flash_locked(sl)) {
239         unlock_flash(sl);
240         if (is_flash_locked(sl)) {
241             WLOG("Failed to unlock flash!\n");
242             return -1;
243         }
244     }
245     DLOG("Successfully unlocked flash\n");
246     return 0;
247 }
248
249 static void lock_flash(stlink_t *sl) {
250     uint32_t cr_lock_shift, cr_reg, n;
251
252     if (sl->flash_type == FLASH_TYPE_F4) {
253         cr_reg = FLASH_F4_CR;
254         cr_lock_shift = FLASH_F4_CR_LOCK;
255     } else if (sl->flash_type == FLASH_TYPE_L4) {
256         cr_reg = STM32L4_FLASH_CR;
257         cr_lock_shift = STM32L4_FLASH_CR_LOCK;
258     } else {
259         cr_reg = FLASH_CR;
260         cr_lock_shift = FLASH_CR_LOCK;
261     }
262
263     n = read_flash_cr(sl) | (1 << cr_lock_shift);
264     stlink_write_debug32(sl, cr_reg, n);
265 }
266
267
268 static void set_flash_cr_pg(stlink_t *sl) {
269     uint32_t cr_reg, x;
270
271     x = read_flash_cr(sl);
272
273     if (sl->flash_type == FLASH_TYPE_F4) {
274         cr_reg = FLASH_F4_CR;
275         x |= 1 << FLASH_CR_PG;
276     } else if (sl->flash_type == FLASH_TYPE_L4) {
277         cr_reg = STM32L4_FLASH_CR;
278         x &= ~STM32L4_FLASH_CR_OPBITS;
279         x |= 1 << STM32L4_FLASH_CR_PG;
280     } else {
281         cr_reg = FLASH_CR;
282         x = 1 << FLASH_CR_PG;
283     }
284
285     stlink_write_debug32(sl, cr_reg, x);
286 }
287
288 static void __attribute__((unused)) clear_flash_cr_pg(stlink_t *sl) {
289     uint32_t cr_reg, n;
290
291     if (sl->flash_type == FLASH_TYPE_F4)
292         cr_reg = FLASH_F4_CR;
293     else if (sl->flash_type == FLASH_TYPE_L4)
294         cr_reg = STM32L4_FLASH_CR;
295     else
296         cr_reg = FLASH_CR;
297
298     n = read_flash_cr(sl) & ~(1 << FLASH_CR_PG);
299     stlink_write_debug32(sl, cr_reg, n);
300 }
301
302 static void set_flash_cr_per(stlink_t *sl) {
303     const uint32_t n = 1 << FLASH_CR_PER;
304     stlink_write_debug32(sl, FLASH_CR, n);
305 }
306
307 static void __attribute__((unused)) clear_flash_cr_per(stlink_t *sl) {
308     const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PER);
309     stlink_write_debug32(sl, FLASH_CR, n);
310 }
311
312 static void set_flash_cr_mer(stlink_t *sl) {
313     uint32_t val, cr_reg, cr_mer;
314
315     if (sl->flash_type == FLASH_TYPE_F4) {
316         cr_reg = FLASH_F4_CR;
317         cr_mer = 1 << FLASH_CR_MER;
318     } else if (sl->flash_type == FLASH_TYPE_L4) {
319         cr_reg = STM32L4_FLASH_CR;
320         cr_mer = (1 << STM32L4_FLASH_CR_MER1) | (1 << STM32L4_FLASH_CR_MER2);
321     } else {
322         cr_reg = FLASH_CR;
323         cr_mer = 1 << FLASH_CR_MER;
324     }
325
326     stlink_read_debug32(sl, cr_reg, &val);
327     val |= cr_mer;
328     stlink_write_debug32(sl, cr_reg, val);
329 }
330
331 static void __attribute__((unused)) clear_flash_cr_mer(stlink_t *sl) {
332     uint32_t val, cr_reg, cr_mer;
333
334     if (sl->flash_type == FLASH_TYPE_F4) {
335         cr_reg = FLASH_F4_CR;
336         cr_mer = 1 << FLASH_CR_MER;
337     } else if (sl->flash_type == FLASH_TYPE_L4) {
338         cr_reg = STM32L4_FLASH_CR;
339         cr_mer = (1 << STM32L4_FLASH_CR_MER1) | (1 << STM32L4_FLASH_CR_MER2);
340     } else {
341         cr_reg = FLASH_CR;
342         cr_mer = 1 << FLASH_CR_MER;
343     }
344
345     stlink_read_debug32(sl, cr_reg, &val);
346     val &= ~cr_mer;
347     stlink_write_debug32(sl, cr_reg, val);
348 }
349
350 static void set_flash_cr_strt(stlink_t *sl) {
351     uint32_t val, cr_reg, cr_strt;
352
353     if (sl->flash_type == FLASH_TYPE_F4) {
354         cr_reg = FLASH_F4_CR;
355         cr_strt = 1 << FLASH_F4_CR_STRT;
356     } else if (sl->flash_type == FLASH_TYPE_L4) {
357         cr_reg = STM32L4_FLASH_CR;
358         cr_strt = 1 << STM32L4_FLASH_CR_STRT;
359     } else {
360         cr_reg = FLASH_CR;
361         cr_strt = 1 << FLASH_CR_STRT;
362     }
363
364     stlink_read_debug32(sl, cr_reg, &val);
365     val |= cr_strt;
366     stlink_write_debug32(sl, cr_reg, val);
367 }
368
369 static inline uint32_t read_flash_acr(stlink_t *sl) {
370     uint32_t acr;
371     stlink_read_debug32(sl, FLASH_ACR, &acr);
372     return acr;
373 }
374
375 static inline uint32_t read_flash_sr(stlink_t *sl) {
376     uint32_t res, sr_reg;
377
378     if (sl->flash_type == FLASH_TYPE_F4)
379         sr_reg = FLASH_F4_SR;
380     else if (sl->flash_type == FLASH_TYPE_L4)
381         sr_reg = STM32L4_FLASH_SR;
382     else
383         sr_reg = FLASH_SR;
384
385     stlink_read_debug32(sl, sr_reg, &res);
386
387     return res;
388 }
389
390 static inline unsigned int is_flash_busy(stlink_t *sl) {
391     uint32_t sr_busy_shift;
392
393     if (sl->flash_type == FLASH_TYPE_F4)
394         sr_busy_shift = FLASH_F4_SR_BSY;
395     else if (sl->flash_type == FLASH_TYPE_L4)
396         sr_busy_shift = STM32L4_FLASH_SR_BSY;
397     else
398         sr_busy_shift = FLASH_SR_BSY;
399
400     return read_flash_sr(sl) & (1 << sr_busy_shift);
401 }
402
403 static void wait_flash_busy(stlink_t *sl) {
404     /* todo: add some delays here */
405     while (is_flash_busy(sl))
406         ;
407 }
408
409 static void wait_flash_busy_progress(stlink_t *sl) {
410     int i = 0;
411     fprintf(stdout, "Mass erasing");
412     fflush(stdout);
413     while (is_flash_busy(sl)) {
414         usleep(10000);
415         i++;
416         if (i % 100 == 0) {
417             fprintf(stdout, ".");
418             fflush(stdout);
419         }
420     }
421     fprintf(stdout, "\n");
422 }
423
424 static inline unsigned int is_flash_eop(stlink_t *sl) {
425     return read_flash_sr(sl) & (1 << FLASH_SR_EOP);
426 }
427
428 static void __attribute__((unused)) clear_flash_sr_eop(stlink_t *sl) {
429     const uint32_t n = read_flash_sr(sl) & ~(1 << FLASH_SR_EOP);
430     stlink_write_debug32(sl, FLASH_SR, n);
431 }
432
433 static void __attribute__((unused)) wait_flash_eop(stlink_t *sl) {
434     /* todo: add some delays here */
435     while (is_flash_eop(sl) == 0)
436         ;
437 }
438
439 static inline void write_flash_ar(stlink_t *sl, uint32_t n) {
440     stlink_write_debug32(sl, FLASH_AR, n);
441 }
442
443 static inline void write_flash_cr_psiz(stlink_t *sl, uint32_t n) {
444     uint32_t x = read_flash_cr(sl);
445     x &= ~(0x03 << 8);
446     x |= (n << 8);
447 #if DEBUG_FLASH
448     fprintf(stdout, "PSIZ:0x%x 0x%x\n", x, n);
449 #endif
450     stlink_write_debug32(sl, FLASH_F4_CR, x);
451 }
452
453
454 static inline void write_flash_cr_snb(stlink_t *sl, uint32_t n) {
455     uint32_t x = read_flash_cr(sl);
456     x &= ~FLASH_F4_CR_SNB_MASK;
457     x |= (n << FLASH_F4_CR_SNB);
458     x |= (1 << FLASH_F4_CR_SER);
459 #if DEBUG_FLASH
460     fprintf(stdout, "SNB:0x%x 0x%x\n", x, n);
461 #endif
462     stlink_write_debug32(sl, FLASH_F4_CR, x);
463 }
464
465 static inline void write_flash_cr_bker_pnb(stlink_t *sl, uint32_t n) {
466     stlink_write_debug32(sl, STM32L4_FLASH_SR, 0xFFFFFFFF & ~(1<<STM32L4_FLASH_SR_BSY));
467     uint32_t x = read_flash_cr(sl);
468     x &=~ STM32L4_FLASH_CR_OPBITS;
469     x &=~ STM32L4_FLASH_CR_PAGEMASK;
470     x &= ~(1<<STM32L4_FLASH_CR_MER1);
471     x &= ~(1<<STM32L4_FLASH_CR_MER2);
472     x |= (n << STM32L4_FLASH_CR_PNB);
473     x |= (1lu << STM32L4_FLASH_CR_PER);
474 #if DEBUG_FLASH
475     fprintf(stdout, "BKER:PNB:0x%x 0x%x\n", x, n);
476 #endif
477     stlink_write_debug32(sl, STM32L4_FLASH_CR, x);
478 }
479
480 // Delegates to the backends...
481
482 void stlink_close(stlink_t *sl) {
483     DLOG("*** stlink_close ***\n");
484     if (!sl)
485          return;
486     sl->backend->close(sl);
487     free(sl);
488 }
489
490 int stlink_exit_debug_mode(stlink_t *sl) {
491     int ret;
492
493     DLOG("*** stlink_exit_debug_mode ***\n");
494     ret = stlink_write_debug32(sl, DHCSR, DBGKEY);
495     if (ret == -1)
496         return ret;
497
498     return sl->backend->exit_debug_mode(sl);
499 }
500
501 int stlink_enter_swd_mode(stlink_t *sl) {
502     DLOG("*** stlink_enter_swd_mode ***\n");
503     return sl->backend->enter_swd_mode(sl);
504 }
505
506 // Force the core into the debug mode -> halted state.
507 int stlink_force_debug(stlink_t *sl) {
508     DLOG("*** stlink_force_debug_mode ***\n");
509     return sl->backend->force_debug(sl);
510 }
511
512 int stlink_exit_dfu_mode(stlink_t *sl) {
513     DLOG("*** stlink_exit_dfu_mode ***\n");
514     return sl->backend->exit_dfu_mode(sl);
515 }
516
517 int stlink_core_id(stlink_t *sl) {
518     int ret;
519
520     DLOG("*** stlink_core_id ***\n");
521     ret = sl->backend->core_id(sl);
522     if (ret == -1) {
523         ELOG("Failed to read core_id\n");
524         return ret;
525     }
526     if (sl->verbose > 2)
527         stlink_print_data(sl);
528     DLOG("core_id = 0x%08x\n", sl->core_id);
529     return ret;
530 }
531
532 int stlink_chip_id(stlink_t *sl, uint32_t *chip_id) {
533     int ret;
534
535     ret = stlink_read_debug32(sl, 0xE0042000, chip_id);
536     if (ret == -1)
537         return ret;
538
539     if (*chip_id == 0)
540         ret = stlink_read_debug32(sl, 0x40015800, chip_id);    //Try Corex M0 DBGMCU_IDCODE register address
541
542     return ret;
543 }
544
545 /**
546  * Cortex m3 tech ref manual, CPUID register description
547  * @param sl stlink context
548  * @param cpuid pointer to the result object
549  */
550 int stlink_cpu_id(stlink_t *sl, cortex_m3_cpuid_t *cpuid) {
551     uint32_t raw;
552
553     if (stlink_read_debug32(sl, CM3_REG_CPUID, &raw))
554         return -1;
555
556     cpuid->implementer_id = (raw >> 24) & 0x7f;
557     cpuid->variant = (raw >> 20) & 0xf;
558     cpuid->part = (raw >> 4) & 0xfff;
559     cpuid->revision = raw & 0xf;
560     return 0;
561 }
562
563 /**
564  * reads and decodes the flash parameters, as dynamically as possible
565  * @param sl
566  * @return 0 for success, or -1 for unsupported core type.
567  */
568 int stlink_load_device_params(stlink_t *sl) {
569     ILOG("Loading device parameters....\n");
570     const struct stlink_chipid_params *params = NULL;
571     stlink_core_id(sl);
572     uint32_t chip_id;
573     uint32_t flash_size;
574
575     stlink_chip_id(sl, &chip_id);
576     sl->chip_id = chip_id & 0xfff;
577     /* Fix chip_id for F4 rev A errata , Read CPU ID, as CoreID is the same for F2/F4*/
578     if (sl->chip_id == 0x411) {
579         uint32_t cpuid;
580         stlink_read_debug32(sl, 0xE000ED00, &cpuid);
581         if ((cpuid  & 0xfff0) == 0xc240)
582             sl->chip_id = 0x413;
583     }
584
585     params = stlink_chipid_get_params(sl->chip_id);
586     if (params == NULL) {
587         WLOG("unknown chip id! %#x\n", chip_id);
588         return -1;
589     }
590
591     if (params->flash_type == FLASH_TYPE_UNKNOWN) {
592         WLOG("Invalid flash type, please check device declaration\n");
593         return -1;
594     }
595
596     // These are fixed...
597     sl->flash_base = STM32_FLASH_BASE;
598     sl->sram_base = STM32_SRAM_BASE;
599     stlink_read_debug32(sl,(params->flash_size_reg) & ~3, &flash_size);
600     if (params->flash_size_reg & 2)
601         flash_size = flash_size >>16;
602     flash_size = flash_size & 0xffff;
603
604     if ((sl->chip_id == STLINK_CHIPID_STM32_L1_MEDIUM || sl->chip_id == STLINK_CHIPID_STM32_L1_MEDIUM_PLUS) && ( flash_size == 0 )) {
605         sl->flash_size = 128 * 1024;
606     } else if (sl->chip_id == STLINK_CHIPID_STM32_L1_CAT2) {
607         sl->flash_size = (flash_size & 0xff) * 1024;
608     } else if ((sl->chip_id & 0xFFF) == STLINK_CHIPID_STM32_L1_HIGH) {
609         // 0 is 384k and 1 is 256k
610         if ( flash_size == 0 ) {
611             sl->flash_size = 384 * 1024;
612         } else {
613             sl->flash_size = 256 * 1024;
614         }
615     } else {
616         sl->flash_size = flash_size * 1024;
617     }
618     sl->flash_type = params->flash_type;
619     sl->flash_pgsz = params->flash_pagesize;
620     sl->sram_size = params->sram_size;
621     sl->sys_base = params->bootrom_base;
622     sl->sys_size = params->bootrom_size;
623
624     //medium and low devices have the same chipid. ram size depends on flash size.
625     //STM32F100xx datasheet Doc ID 16455 Table 2
626     if(sl->chip_id == STLINK_CHIPID_STM32_F1_VL_MEDIUM_LOW && sl->flash_size < 64 * 1024){
627         sl->sram_size = 0x1000;
628     }
629
630     ILOG("Device connected is: %s, id %#x\n", params->description, chip_id);
631     // TODO make note of variable page size here.....
632     ILOG("SRAM size: %#x bytes (%d KiB), Flash: %#x bytes (%d KiB) in pages of %zd bytes\n",
633             sl->sram_size, sl->sram_size / 1024, sl->flash_size, sl->flash_size / 1024,
634             sl->flash_pgsz);
635     return 0;
636 }
637
638 int stlink_reset(stlink_t *sl) {
639     DLOG("*** stlink_reset ***\n");
640     return sl->backend->reset(sl);
641 }
642
643 int stlink_jtag_reset(stlink_t *sl, int value) {
644     DLOG("*** stlink_jtag_reset ***\n");
645     return sl->backend->jtag_reset(sl, value);
646 }
647
648 int stlink_run(stlink_t *sl) {
649     DLOG("*** stlink_run ***\n");
650     return sl->backend->run(sl);
651 }
652
653 int stlink_status(stlink_t *sl) {
654     int ret;
655
656     DLOG("*** stlink_status ***\n");
657     ret = sl->backend->status(sl);
658     stlink_core_stat(sl);
659
660     return ret;
661 }
662
663 /**
664  * Decode the version bits, originally from -sg, verified with usb
665  * @param sl stlink context, assumed to contain valid data in the buffer
666  * @param slv output parsed version object
667  */
668 void _parse_version(stlink_t *sl, stlink_version_t *slv) {
669     uint32_t b0 = sl->q_buf[0]; //lsb
670     uint32_t b1 = sl->q_buf[1];
671     uint32_t b2 = sl->q_buf[2];
672     uint32_t b3 = sl->q_buf[3];
673     uint32_t b4 = sl->q_buf[4];
674     uint32_t b5 = sl->q_buf[5]; //msb
675
676     // b0 b1                       || b2 b3  | b4 b5
677     // 4b        | 6b     | 6b     || 2B     | 2B
678     // stlink_v  | jtag_v | swim_v || st_vid | stlink_pid
679
680     slv->stlink_v = (b0 & 0xf0) >> 4;
681     slv->jtag_v = ((b0 & 0x0f) << 2) | ((b1 & 0xc0) >> 6);
682     slv->swim_v = b1 & 0x3f;
683     slv->st_vid = (b3 << 8) | b2;
684     slv->stlink_pid = (b5 << 8) | b4;
685     return;
686 }
687
688 int stlink_version(stlink_t *sl) {
689     DLOG("*** looking up stlink version\n");
690     if (sl->backend->version(sl))
691         return -1;
692
693     _parse_version(sl, &sl->version);
694
695     DLOG("st vid         = 0x%04x (expect 0x%04x)\n", sl->version.st_vid, USB_ST_VID);
696     DLOG("stlink pid     = 0x%04x\n", sl->version.stlink_pid);
697     DLOG("stlink version = 0x%x\n", sl->version.stlink_v);
698     DLOG("jtag version   = 0x%x\n", sl->version.jtag_v);
699     DLOG("swim version   = 0x%x\n", sl->version.swim_v);
700     if (sl->version.jtag_v == 0) {
701         DLOG("    notice: the firmware doesn't support a jtag/swd interface\n");
702     }
703     if (sl->version.swim_v == 0) {
704         DLOG("    notice: the firmware doesn't support a swim interface\n");
705     }
706
707     return 0;
708 }
709
710 int stlink_target_voltage(stlink_t *sl) {
711     int voltage = -1;
712     DLOG("*** reading target voltage\n");
713     if (sl->backend->target_voltage != NULL) {
714         voltage = sl->backend->target_voltage(sl);
715         if (voltage != -1) {
716             DLOG("target voltage = %ldmV\n", voltage);
717         } else {
718             DLOG("error reading target voltage\n");
719         }
720     } else {
721         DLOG("reading voltage not supported by backend\n");
722     }
723     return voltage;
724 }
725
726 int stlink_read_debug32(stlink_t *sl, uint32_t addr, uint32_t *data) {
727     int ret;
728
729     ret = sl->backend->read_debug32(sl, addr, data);
730     if (!ret)
731             DLOG("*** stlink_read_debug32 %x is %#x\n", *data, addr);
732
733         return ret;
734 }
735
736 int stlink_write_debug32(stlink_t *sl, uint32_t addr, uint32_t data) {
737     DLOG("*** stlink_write_debug32 %x to %#x\n", data, addr);
738     return sl->backend->write_debug32(sl, addr, data);
739 }
740
741 int stlink_write_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
742     DLOG("*** stlink_write_mem32 %u bytes to %#x\n", len, addr);
743     if (len % 4 != 0) {
744         fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
745         abort();
746     }
747     return sl->backend->write_mem32(sl, addr, len);
748 }
749
750 int stlink_read_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
751     DLOG("*** stlink_read_mem32 ***\n");
752     if (len % 4 != 0) { // !!! never ever: fw gives just wrong values
753         fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n",
754                 len % 4);
755         abort();
756     }
757     return sl->backend->read_mem32(sl, addr, len);
758 }
759
760 int stlink_write_mem8(stlink_t *sl, uint32_t addr, uint16_t len) {
761     DLOG("*** stlink_write_mem8 ***\n");
762     if (len > 0x40 ) { // !!! never ever: Writing more then 0x40 bytes gives unexpected behaviour
763         fprintf(stderr, "Error: Data length > 64: +%d byte.\n",
764                 len);
765         abort();
766     }
767     return sl->backend->write_mem8(sl, addr, len);
768 }
769
770 int stlink_read_all_regs(stlink_t *sl, reg *regp) {
771     DLOG("*** stlink_read_all_regs ***\n");
772     return sl->backend->read_all_regs(sl, regp);
773 }
774
775 int stlink_read_all_unsupported_regs(stlink_t *sl, reg *regp) {
776     DLOG("*** stlink_read_all_unsupported_regs ***\n");
777     return sl->backend->read_all_unsupported_regs(sl, regp);
778 }
779
780 int stlink_write_reg(stlink_t *sl, uint32_t reg, int idx) {
781     DLOG("*** stlink_write_reg\n");
782     return sl->backend->write_reg(sl, reg, idx);
783 }
784
785 int stlink_read_reg(stlink_t *sl, int r_idx, reg *regp) {
786     DLOG("*** stlink_read_reg\n");
787     DLOG(" (%d) ***\n", r_idx);
788
789     if (r_idx > 20 || r_idx < 0) {
790         fprintf(stderr, "Error: register index must be in [0..20]\n");
791         return -1;
792     }
793
794     return sl->backend->read_reg(sl, r_idx, regp);
795 }
796
797 int stlink_read_unsupported_reg(stlink_t *sl, int r_idx, reg *regp) {
798     int r_convert;
799
800     DLOG("*** stlink_read_unsupported_reg\n");
801     DLOG(" (%d) ***\n", r_idx);
802
803     /* Convert to values used by DCRSR */
804     if (r_idx >= 0x1C && r_idx <= 0x1F) { /* primask, basepri, faultmask, or control */
805         r_convert = 0x14;
806     } else if (r_idx == 0x40) {     /* FPSCR */
807         r_convert = 0x21;
808     } else if (r_idx >= 0x20 && r_idx < 0x40) {
809         r_convert = 0x40 + (r_idx - 0x20);
810     } else {
811         fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
812         return -1;
813     }
814
815     return sl->backend->read_unsupported_reg(sl, r_convert, regp);
816 }
817
818 int stlink_write_unsupported_reg(stlink_t *sl, uint32_t val, int r_idx, reg *regp) {
819     int r_convert;
820
821     DLOG("*** stlink_write_unsupported_reg\n");
822     DLOG(" (%d) ***\n", r_idx);
823
824     /* Convert to values used by DCRSR */
825     if (r_idx >= 0x1C && r_idx <= 0x1F) { /* primask, basepri, faultmask, or control */
826         r_convert = r_idx;  /* The backend function handles this */
827     } else if (r_idx == 0x40) {     /* FPSCR */
828         r_convert = 0x21;
829     } else if (r_idx >= 0x20 && r_idx < 0x40) {
830         r_convert = 0x40 + (r_idx - 0x20);
831     } else {
832         fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
833         return -1;
834     }
835
836     return sl->backend->write_unsupported_reg(sl, val, r_convert, regp);
837 }
838
839 unsigned int is_core_halted(stlink_t *sl) {
840     /* return non zero if core is halted */
841     stlink_status(sl);
842     return sl->q_buf[0] == STLINK_CORE_HALTED;
843 }
844
845 int stlink_step(stlink_t *sl) {
846     DLOG("*** stlink_step ***\n");
847     return sl->backend->step(sl);
848 }
849
850 int stlink_current_mode(stlink_t *sl) {
851     int mode = sl->backend->current_mode(sl);
852     switch (mode) {
853     case STLINK_DEV_DFU_MODE:
854         DLOG("stlink current mode: dfu\n");
855         return mode;
856     case STLINK_DEV_DEBUG_MODE:
857         DLOG("stlink current mode: debug (jtag or swd)\n");
858         return mode;
859     case STLINK_DEV_MASS_MODE:
860         DLOG("stlink current mode: mass\n");
861         return mode;
862     }
863     DLOG("stlink mode: unknown!\n");
864     return STLINK_DEV_UNKNOWN_MODE;
865 }
866
867
868
869
870 // End of delegates....  Common code below here...
871
872 // Endianness
873 // http://www.ibm.com/developerworks/aix/library/au-endianc/index.html
874 // const int i = 1;
875 // #define is_bigendian() ( (*(char*)&i) == 0 )
876
877 inline unsigned int is_bigendian(void) {
878     static volatile const unsigned int i = 1;
879     return *(volatile const char*) &i == 0;
880 }
881
882 uint16_t read_uint16(const unsigned char *c, const int pt) {
883     uint32_t ui;
884     char *p = (char *) &ui;
885
886     if (!is_bigendian()) { // le -> le (don't swap)
887         p[0] = c[pt + 0];
888         p[1] = c[pt + 1];
889     } else {
890         p[0] = c[pt + 1];
891         p[1] = c[pt + 0];
892     }
893     return ui;
894 }
895
896 // same as above with entrypoint.
897
898 void stlink_run_at(stlink_t *sl, stm32_addr_t addr) {
899     stlink_write_reg(sl, addr, 15); /* pc register */
900
901     stlink_run(sl);
902
903     while (is_core_halted(sl) == 0)
904         usleep(3000000);
905 }
906
907 void stlink_core_stat(stlink_t *sl) {
908     if (sl->q_len <= 0)
909         return;
910
911     switch (sl->q_buf[0]) {
912     case STLINK_CORE_RUNNING:
913         sl->core_stat = STLINK_CORE_RUNNING;
914         DLOG("  core status: running\n");
915         return;
916     case STLINK_CORE_HALTED:
917         sl->core_stat = STLINK_CORE_HALTED;
918         DLOG("  core status: halted\n");
919         return;
920     default:
921         sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
922         fprintf(stderr, "  core status: unknown\n");
923     }
924 }
925
926 void stlink_print_data(stlink_t * sl) {
927     if (sl->q_len <= 0 || sl->verbose < UDEBUG)
928         return;
929     if (sl->verbose > 2)
930         fprintf(stdout, "data_len = %d 0x%x\n", sl->q_len, sl->q_len);
931
932     for (int i = 0; i < sl->q_len; i++) {
933         if (i % 16 == 0) {
934             /*
935                if (sl->q_data_dir == Q_DATA_OUT)
936                fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
937                else
938                fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
939                */
940         }
941         fprintf(stdout, " %02x", (unsigned int) sl->q_buf[i]);
942     }
943     fputs("\n\n", stdout);
944 }
945
946 /* memory mapped file */
947
948 typedef struct mapped_file {
949     uint8_t* base;
950     size_t len;
951 } mapped_file_t;
952
953 #define MAPPED_FILE_INITIALIZER { NULL, 0 }
954
955 static int map_file(mapped_file_t* mf, const char* path) {
956     int error = -1;
957     struct stat st;
958
959     const int fd = open(path, O_RDONLY | O_BINARY);
960     if (fd == -1) {
961         fprintf(stderr, "open(%s) == -1\n", path);
962         return -1;
963     }
964
965     if (fstat(fd, &st) == -1) {
966         fprintf(stderr, "fstat() == -1\n");
967         goto on_error;
968     }
969
970     mf->base = (uint8_t*) mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
971     if (mf->base == MAP_FAILED) {
972         fprintf(stderr, "mmap() == MAP_FAILED\n");
973         goto on_error;
974     }
975
976     mf->len = st.st_size;
977
978     /* success */
979     error = 0;
980
981 on_error:
982     close(fd);
983
984     return error;
985 }
986
987 static void unmap_file(mapped_file_t * mf) {
988     munmap((void*) mf->base, mf->len);
989     mf->base = (unsigned char*) MAP_FAILED;
990     mf->len = 0;
991 }
992
993 /* Limit the block size to compare to 0x1800
994    Anything larger will stall the STLINK2
995    Maybe STLINK V1 needs smaller value!*/
996 static int check_file(stlink_t* sl, mapped_file_t* mf, stm32_addr_t addr) {
997     size_t off;
998     size_t n_cmp = sl->flash_pgsz;
999     if ( n_cmp > 0x1800)
1000         n_cmp = 0x1800;
1001
1002     for (off = 0; off < mf->len; off += n_cmp) {
1003         size_t aligned_size;
1004
1005         /* adjust last page size */
1006         size_t cmp_size = n_cmp;
1007         if ((off + n_cmp) > mf->len)
1008             cmp_size = mf->len - off;
1009
1010         aligned_size = cmp_size;
1011         if (aligned_size & (4 - 1))
1012             aligned_size = (cmp_size + 4) & ~(4 - 1);
1013
1014         stlink_read_mem32(sl, addr + off, aligned_size);
1015
1016         if (memcmp(sl->q_buf, mf->base + off, cmp_size))
1017             return -1;
1018     }
1019
1020     return 0;
1021 }
1022
1023 int stlink_fwrite_sram
1024 (stlink_t * sl, const char* path, stm32_addr_t addr) {
1025     /* write the file in sram at addr */
1026
1027     int error = -1;
1028     size_t off;
1029     size_t len;
1030     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1031     uint32_t val;
1032
1033
1034     if (map_file(&mf, path) == -1) {
1035         fprintf(stderr, "map_file() == -1\n");
1036         return -1;
1037     }
1038
1039     /* check addr range is inside the sram */
1040     if (addr < sl->sram_base) {
1041         fprintf(stderr, "addr too low\n");
1042         goto on_error;
1043     } else if ((addr + mf.len) < addr) {
1044         fprintf(stderr, "addr overruns\n");
1045         goto on_error;
1046     } else if ((addr + mf.len) > (sl->sram_base + sl->sram_size)) {
1047         fprintf(stderr, "addr too high\n");
1048         goto on_error;
1049     } else if (addr & 3) {
1050         /* todo */
1051         fprintf(stderr, "unaligned addr\n");
1052         goto on_error;
1053     }
1054
1055     len = mf.len;
1056
1057     if(len & 3) {
1058       len -= len & 3;
1059     }
1060
1061     /* do the copy by 1k blocks */
1062     for (off = 0; off < len; off += 1024) {
1063         size_t size = 1024;
1064         if ((off + size) > len)
1065             size = len - off;
1066
1067         memcpy(sl->q_buf, mf.base + off, size);
1068
1069         /* round size if needed */
1070         if (size & 3)
1071             size += 2;
1072
1073         stlink_write_mem32(sl, addr + off, size);
1074     }
1075
1076     if(mf.len > len) {
1077         memcpy(sl->q_buf, mf.base + len, mf.len - len);
1078         stlink_write_mem8(sl, addr + len, mf.len - len);
1079     }
1080
1081     /* check the file ha been written */
1082     if (check_file(sl, &mf, addr) == -1) {
1083         fprintf(stderr, "check_file() == -1\n");
1084         goto on_error;
1085     }
1086
1087     /* success */
1088     error = 0;
1089     /* set stack*/
1090     stlink_read_debug32(sl, addr, &val);
1091     stlink_write_reg(sl, val, 13);
1092     /* Set PC to the reset routine*/
1093     stlink_read_debug32(sl, addr + 4, &val);
1094     stlink_write_reg(sl, val, 15);
1095     stlink_run(sl);
1096
1097 on_error:
1098     unmap_file(&mf);
1099     return error;
1100 }
1101
1102 int stlink_fread(stlink_t* sl, const char* path, stm32_addr_t addr, size_t size) {
1103     /* read size bytes from addr to file */
1104
1105     int error = -1;
1106     size_t off;
1107
1108     const int fd = open(path, O_RDWR | O_TRUNC | O_CREAT, 00700);
1109     if (fd == -1) {
1110         fprintf(stderr, "open(%s) == -1\n", path);
1111         return -1;
1112     }
1113
1114     if (size <1)
1115         size = sl->flash_size;
1116
1117     if (size > sl->flash_size)
1118         size = sl->flash_size;
1119
1120     size_t cmp_size = (sl->flash_pgsz > 0x1800)? 0x1800:sl->flash_pgsz;
1121     for (off = 0; off < size; off += cmp_size) {
1122         size_t aligned_size;
1123
1124         /* adjust last page size */
1125         if ((off + cmp_size) > size)
1126             cmp_size = size - off;
1127
1128         aligned_size = cmp_size;
1129         if (aligned_size & (4 - 1))
1130             aligned_size = (cmp_size + 4) & ~(4 - 1);
1131
1132         stlink_read_mem32(sl, addr + off, aligned_size);
1133
1134         if (write(fd, sl->q_buf, sl->q_len) != (ssize_t) aligned_size) {
1135             fprintf(stderr, "write() != aligned_size\n");
1136             goto on_error;
1137         }
1138     }
1139
1140     /* success */
1141     error = 0;
1142
1143 on_error:
1144     close(fd);
1145
1146     return error;
1147 }
1148
1149 int write_buffer_to_sram(stlink_t *sl, flash_loader_t* fl, const uint8_t* buf, size_t size) {
1150     /* write the buffer right after the loader */
1151     size_t chunk = size & ~0x3;
1152     size_t rem   = size & 0x3;
1153     if (chunk) {
1154         memcpy(sl->q_buf, buf, chunk);
1155         stlink_write_mem32(sl, fl->buf_addr, chunk);
1156     }
1157     if (rem) {
1158         memcpy(sl->q_buf, buf+chunk, rem);
1159         stlink_write_mem8(sl, (fl->buf_addr)+chunk, rem);
1160     }
1161     return 0;
1162 }
1163
1164 uint32_t calculate_F4_sectornum(uint32_t flashaddr){
1165     uint32_t offset = 0;
1166     flashaddr &= ~STM32_FLASH_BASE;     //Page now holding the actual flash address
1167     if (flashaddr >= 0x100000) {
1168         offset = 12;
1169         flashaddr -= 0x100000;
1170     } 
1171     if (flashaddr<0x4000) return (offset + 0);
1172     else if(flashaddr<0x8000) return(offset + 1);
1173     else if(flashaddr<0xc000) return(offset + 2);
1174     else if(flashaddr<0x10000) return(offset + 3);
1175     else if(flashaddr<0x20000) return(offset + 4);
1176     else return offset + (flashaddr/0x20000) +4;
1177
1178 }
1179
1180 uint32_t calculate_F7_sectornum(uint32_t flashaddr){
1181     flashaddr &= ~STM32_FLASH_BASE;     //Page now holding the actual flash address
1182         if(flashaddr<0x20000) return(flashaddr/0x8000);
1183     else if(flashaddr<0x40000) return(4);
1184     else return(flashaddr/0x40000) +4;
1185
1186 }
1187
1188 // Returns BKER:PNB for the given page address
1189 uint32_t calculate_L4_page(stlink_t *sl, uint32_t flashaddr) {
1190     uint32_t bker = 0;
1191     uint32_t flashopt;
1192     stlink_read_debug32(sl, STM32L4_FLASH_OPTR, &flashopt);
1193     flashaddr -= STM32_FLASH_BASE;
1194     if (flashopt & (1lu << STM32L4_FLASH_OPTR_DUALBANK)) {
1195         uint32_t banksize = sl->flash_size / 2;
1196         if (flashaddr >= banksize) {
1197             flashaddr -= banksize;
1198             bker = 0x100;
1199         }
1200     }
1201     // For 1MB chips without the dual-bank option set, the page address will
1202     // overflow into the BKER bit, which gives us the correct bank:page value.
1203     return bker | flashaddr/sl->flash_pgsz;
1204 }
1205
1206 uint32_t stlink_calculate_pagesize(stlink_t *sl, uint32_t flashaddr){
1207     if ((sl->chip_id == STLINK_CHIPID_STM32_F2) || (sl->chip_id == STLINK_CHIPID_STM32_F4) || (sl->chip_id == STLINK_CHIPID_STM32_F4_DE) ||
1208             (sl->chip_id == STLINK_CHIPID_STM32_F4_LP) || (sl->chip_id == STLINK_CHIPID_STM32_F4_HD) || (sl->chip_id == STLINK_CHIPID_STM32_F411RE) ||
1209             (sl->chip_id == STLINK_CHIPID_STM32_F446) || (sl->chip_id == STLINK_CHIPID_STM32_F4_DSI)) {
1210         uint32_t sector=calculate_F4_sectornum(flashaddr);
1211         if (sector>= 12) {
1212             sector -= 12;
1213         }
1214         if (sector<4) sl->flash_pgsz=0x4000;
1215         else if(sector<5) sl->flash_pgsz=0x10000;
1216         else sl->flash_pgsz=0x20000;
1217     }
1218     else if (sl->chip_id == STLINK_CHIPID_STM32_F7) {
1219         uint32_t sector=calculate_F7_sectornum(flashaddr);
1220         if (sector<4) sl->flash_pgsz=0x8000;
1221         else if(sector<5) sl->flash_pgsz=0x20000;
1222         else sl->flash_pgsz=0x40000;
1223     }
1224     return (sl->flash_pgsz);
1225 }
1226
1227 /**
1228  * Erase a page of flash, assumes sl is fully populated with things like chip/core ids
1229  * @param sl stlink context
1230  * @param flashaddr an address in the flash page to erase
1231  * @return 0 on success -ve on failure
1232  */
1233 int stlink_erase_flash_page(stlink_t *sl, stm32_addr_t flashaddr)
1234 {
1235     if (sl->flash_type == FLASH_TYPE_F4 || sl->flash_type == FLASH_TYPE_L4) {
1236         /* wait for ongoing op to finish */
1237         wait_flash_busy(sl);
1238
1239         /* unlock if locked */
1240         unlock_flash_if(sl);
1241
1242         /* select the page to erase */
1243         if (sl->chip_id == STLINK_CHIPID_STM32_L4) {
1244             // calculate the actual bank+page from the address
1245             uint32_t page = calculate_L4_page(sl, flashaddr);
1246
1247             fprintf(stderr, "EraseFlash - Page:0x%x Size:0x%x ", page, stlink_calculate_pagesize(sl, flashaddr));
1248
1249             write_flash_cr_bker_pnb(sl, page);
1250         } else if (sl->chip_id == STLINK_CHIPID_STM32_F7) {
1251             // calculate the actual page from the address
1252             uint32_t sector=calculate_F7_sectornum(flashaddr);
1253
1254             fprintf(stderr, "EraseFlash - Sector:0x%x Size:0x%x ", sector, stlink_calculate_pagesize(sl, flashaddr));
1255
1256             write_flash_cr_snb(sl, sector);
1257         } else {
1258             // calculate the actual page from the address
1259             uint32_t sector=calculate_F4_sectornum(flashaddr);
1260
1261             fprintf(stderr, "EraseFlash - Sector:0x%x Size:0x%x ", sector, stlink_calculate_pagesize(sl, flashaddr));
1262         
1263             //the SNB values for flash sectors in the second bank do not directly follow the values for the first bank on 2mb devices...
1264             if (sector >= 12) sector += 4;
1265
1266             write_flash_cr_snb(sl, sector);
1267         }
1268
1269         /* start erase operation */
1270         set_flash_cr_strt(sl);
1271
1272         /* wait for completion */
1273         wait_flash_busy(sl);
1274
1275         /* relock the flash */
1276         //todo: fails to program if this is in
1277         lock_flash(sl);
1278 #if DEBUG_FLASH
1279         fprintf(stdout, "Erase Final CR:0x%x\n", read_flash_cr(sl));
1280 #endif
1281     } else if (sl->flash_type == FLASH_TYPE_L0) {
1282
1283         uint32_t val;
1284         uint32_t flash_regs_base;
1285         if (sl->chip_id == STLINK_CHIPID_STM32_L0 || sl->chip_id == STLINK_CHIPID_STM32_L0_CAT5 || sl->chip_id == STLINK_CHIPID_STM32_L0_CAT2) {
1286             flash_regs_base = STM32L0_FLASH_REGS_ADDR;
1287         } else {
1288             flash_regs_base = STM32L_FLASH_REGS_ADDR;
1289         }
1290
1291         /* check if the locks are set */
1292         stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1293         if((val & (1<<0))||(val & (1<<1))) {
1294             /* disable pecr protection */
1295             stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF, 0x89abcdef);
1296             stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF, 0x02030405);
1297
1298             /* check pecr.pelock is cleared */
1299             stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1300             if (val & (1 << 0)) {
1301                 WLOG("pecr.pelock not clear (%#x)\n", val);
1302                 return -1;
1303             }
1304
1305             /* unlock program memory */
1306             stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF, 0x8c9daebf);
1307             stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF, 0x13141516);
1308
1309             /* check pecr.prglock is cleared */
1310             stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1311             if (val & (1 << 1)) {
1312                 WLOG("pecr.prglock not clear (%#x)\n", val);
1313                 return -1;
1314             }
1315         }
1316
1317         /* set pecr.{erase,prog} */
1318         val |= (1 << 9) | (1 << 3);
1319         stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1320 #if 0 /* fix_to_be_confirmed */
1321
1322         /* wait for sr.busy to be cleared
1323          * MP: Test shows that busy bit is not set here. Perhaps, PM0062 is
1324          * wrong and we do not need to wait here for clearing the busy bit.
1325          * TEXANE: ok, if experience says so and it works for you, we comment
1326          * it. If someone has a problem, please drop an email.
1327          */
1328         do {
1329             stlink_read_debug32(sl, STM32L_FLASH_SR, &val)
1330         } while((val & (1 << 0)) != 0);
1331
1332 #endif /* fix_to_be_confirmed */
1333
1334         /* write 0 to the first word of the page to be erased */
1335         stlink_write_debug32(sl, flashaddr, 0);
1336
1337         /* MP: It is better to wait for clearing the busy bit after issuing
1338            page erase command, even though PM0062 recommends to wait before it.
1339            Test shows that a few iterations is performed in the following loop
1340            before busy bit is cleared.*/
1341         do {
1342             stlink_read_debug32(sl, flash_regs_base + FLASH_SR_OFF, &val);
1343         } while ((val & (1 << 0)) != 0);
1344
1345         /* reset lock bits */
1346         stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1347         val |= (1 << 0) | (1 << 1) | (1 << 2);
1348         stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1349     } else if (sl->flash_type == FLASH_TYPE_F0)  {
1350         /* wait for ongoing op to finish */
1351         wait_flash_busy(sl);
1352
1353         /* unlock if locked */
1354         unlock_flash_if(sl);
1355
1356         /* set the page erase bit */
1357         set_flash_cr_per(sl);
1358
1359         /* select the page to erase */
1360         write_flash_ar(sl, flashaddr);
1361
1362         /* start erase operation, reset by hw with bsy bit */
1363         set_flash_cr_strt(sl);
1364
1365         /* wait for completion */
1366         wait_flash_busy(sl);
1367
1368         /* relock the flash */
1369         lock_flash(sl);
1370     } else {
1371         WLOG("unknown coreid %x, page erase failed\n", sl->core_id);
1372         return -1;
1373     }
1374
1375     /* todo: verify the erased page */
1376
1377     return 0;
1378 }
1379
1380 int stlink_erase_flash_mass(stlink_t *sl) {
1381     if (sl->flash_type == FLASH_TYPE_L0) {
1382         /* erase each page */
1383         int i = 0, num_pages = sl->flash_size/sl->flash_pgsz;
1384         for (i = 0; i < num_pages; i++) {
1385             /* addr must be an addr inside the page */
1386             stm32_addr_t addr = sl->flash_base + i * sl->flash_pgsz;
1387             if (stlink_erase_flash_page(sl, addr) == -1) {
1388                 WLOG("Failed to erase_flash_page(%#zx) == -1\n", addr);
1389                 return -1;
1390             }
1391             fprintf(stdout,"-> Flash page at %5d/%5d erased\n", i, num_pages);
1392             fflush(stdout);
1393         }
1394         fprintf(stdout, "\n");
1395     } else {
1396         /* wait for ongoing op to finish */
1397         wait_flash_busy(sl);
1398
1399         /* unlock if locked */
1400         unlock_flash_if(sl);
1401
1402         /* set the mass erase bit */
1403         set_flash_cr_mer(sl);
1404
1405         /* start erase operation, reset by hw with bsy bit */
1406         set_flash_cr_strt(sl);
1407
1408         /* wait for completion */
1409         wait_flash_busy_progress(sl);
1410
1411         /* relock the flash */
1412         lock_flash(sl);
1413
1414         /* todo: verify the erased memory */
1415     }
1416     return 0;
1417 }
1418
1419 int stlink_fcheck_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
1420     /* check the contents of path are at addr */
1421
1422     int res;
1423     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1424
1425     if (map_file(&mf, path) == -1)
1426         return -1;
1427
1428     res = check_file(sl, &mf, addr);
1429
1430     unmap_file(&mf);
1431
1432     return res;
1433 }
1434
1435 /**
1436  * Verify addr..addr+len is binary identical to base...base+len
1437  * @param sl stlink context
1438  * @param address stm device address
1439  * @param data host side buffer to check against
1440  * @param length how much
1441  * @return 0 for success, -ve for failure
1442  */
1443 int stlink_verify_write_flash(stlink_t *sl, stm32_addr_t address, uint8_t *data, unsigned length) {
1444     size_t off;
1445     size_t cmp_size = (sl->flash_pgsz > 0x1800)? 0x1800:sl->flash_pgsz;
1446     ILOG("Starting verification of write complete\n");
1447     for (off = 0; off < length; off += cmp_size) {
1448         size_t aligned_size;
1449
1450         /* adjust last page size */
1451         if ((off + cmp_size) > length)
1452             cmp_size = length - off;
1453
1454         aligned_size = cmp_size;
1455         if (aligned_size & (4 - 1))
1456             aligned_size = (cmp_size + 4) & ~(4 - 1);
1457
1458         stlink_read_mem32(sl, address + off, aligned_size);
1459
1460         if (memcmp(sl->q_buf, data + off, cmp_size)) {
1461             ELOG("Verification of flash failed at offset: %zd\n", off);
1462             return -1;
1463         }
1464     }
1465     ILOG("Flash written and verified! jolly good!\n");
1466     return 0;
1467
1468 }
1469
1470 int stm32l1_write_half_pages(stlink_t *sl, stm32_addr_t addr, uint8_t* base, uint32_t len, uint32_t pagesize)
1471 {
1472     unsigned int count;
1473     unsigned int num_half_pages = len / pagesize;
1474     uint32_t val;
1475     uint32_t flash_regs_base;
1476     flash_loader_t fl;
1477
1478     if (sl->chip_id == STLINK_CHIPID_STM32_L0 || sl->chip_id == STLINK_CHIPID_STM32_L0_CAT5 || sl->chip_id == STLINK_CHIPID_STM32_L0_CAT2) {
1479         flash_regs_base = STM32L0_FLASH_REGS_ADDR;
1480     } else {
1481         flash_regs_base = STM32L_FLASH_REGS_ADDR;
1482     }
1483
1484     ILOG("Starting Half page flash write for STM32L core id\n");
1485     /* flash loader initialization */
1486     if (stlink_flash_loader_init(sl, &fl) == -1) {
1487         WLOG("stlink_flash_loader_init() == -1\n");
1488         return -1;
1489     }
1490     /* Unlock already done */
1491     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1492     val |= (1 << FLASH_L1_FPRG);
1493     stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1494
1495     val |= (1 << FLASH_L1_PROG);
1496     stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1497     do {
1498         stlink_read_debug32(sl, flash_regs_base + FLASH_SR_OFF, &val);
1499     } while ((val & (1 << 0)) != 0);
1500
1501     for (count = 0; count  < num_half_pages; count ++) {
1502         if (stlink_flash_loader_run(sl, &fl, addr + count * pagesize, base + count * pagesize, pagesize) == -1) {
1503             WLOG("l1_stlink_flash_loader_run(%#zx) failed! == -1\n", addr + count * pagesize);
1504             stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1505             val &= ~((1 << FLASH_L1_FPRG) |(1 << FLASH_L1_PROG));
1506             stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1507             return -1;
1508         }
1509         /* wait for sr.busy to be cleared */
1510         if (sl->verbose >= 1) {
1511             /* show progress. writing procedure is slow
1512                and previous errors are misleading */
1513             fprintf(stdout, "\r%3u/%u halfpages written", count + 1, num_half_pages);
1514             fflush(stdout);
1515         }
1516         do {
1517             stlink_read_debug32(sl, flash_regs_base + FLASH_SR_OFF, &val);
1518         } while ((val & (1 << 0)) != 0);
1519     }
1520     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1521     val &= ~(1 << FLASH_L1_PROG);
1522     stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1523     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1524     val &= ~(1 << FLASH_L1_FPRG);
1525     stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1526
1527     return 0;
1528 }
1529
1530 int stlink_write_flash(stlink_t *sl, stm32_addr_t addr, uint8_t* base, uint32_t len, uint8_t eraseonly) {
1531     size_t off;
1532     flash_loader_t fl;
1533     ILOG("Attempting to write %d (%#x) bytes to stm32 address: %u (%#x)\n",
1534             len, len, addr, addr);
1535     /* check addr range is inside the flash */
1536     stlink_calculate_pagesize(sl, addr);
1537     if (addr < sl->flash_base) {
1538         ELOG("addr too low %#x < %#x\n", addr, sl->flash_base);
1539         return -1;
1540     } else if ((addr + len) < addr) {
1541         ELOG("addr overruns\n");
1542         return -1;
1543     } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
1544         ELOG("addr too high\n");
1545         return -1;
1546     } else if (addr & 1) {
1547         ELOG("unaligned addr 0x%x\n", addr);
1548         return -1;
1549     } else if (len & 1) {
1550         WLOG("unaligned len 0x%x -- padding with zero\n", len);
1551         len += 1;
1552     } else if (addr & (sl->flash_pgsz - 1)) {
1553         ELOG("addr not a multiple of pagesize, not supported\n");
1554         return -1;
1555     }
1556
1557     // Make sure we've loaded the context with the chip details
1558     stlink_core_id(sl);
1559     /* erase each page */
1560     int page_count = 0;
1561     for (off = 0; off < len; off += stlink_calculate_pagesize(sl, addr + off)) {
1562         /* addr must be an addr inside the page */
1563         if (stlink_erase_flash_page(sl, addr + off) == -1) {
1564             ELOG("Failed to erase_flash_page(%#zx) == -1\n", addr + off);
1565             return -1;
1566         }
1567         fprintf(stdout,"\rFlash page at addr: 0x%08lx erased",
1568                 (unsigned long)addr + off);
1569         fflush(stdout);
1570         page_count++;
1571     }
1572     fprintf(stdout,"\n");
1573     ILOG("Finished erasing %d pages of %d (%#x) bytes\n",
1574             page_count, sl->flash_pgsz, sl->flash_pgsz);
1575
1576     if (eraseonly)
1577         return 0;
1578
1579     if ((sl->flash_type == FLASH_TYPE_F4) || (sl->flash_type == FLASH_TYPE_L4)) {
1580         /* todo: check write operation */
1581
1582         ILOG("Starting Flash write for F2/F4/L4\n");
1583         /* flash loader initialization */
1584         if (stlink_flash_loader_init(sl, &fl) == -1) {
1585             ELOG("stlink_flash_loader_init() == -1\n");
1586             return -1;
1587         }
1588
1589         /* First unlock the cr */
1590         unlock_flash_if(sl);
1591
1592         /* TODO: Check that Voltage range is 2.7 - 3.6 V */
1593         if (sl->chip_id != STLINK_CHIPID_STM32_L4) {
1594             /* set parallelisim to 32 bit*/
1595             int voltage = stlink_target_voltage(sl);
1596             if (voltage == -1) {
1597                 printf("Failed to read Target voltage\n");
1598                 return voltage;
1599             } else if (voltage > 2700) {
1600                 printf("enabling 32-bit flash writes\n");
1601                 write_flash_cr_psiz(sl, 2);
1602             } else {
1603                 printf("Target voltage (%d mV) too low for 32-bit flash, using 8-bit flash writes\n", voltage);
1604                 write_flash_cr_psiz(sl, 0);
1605             }
1606         } else {
1607             /* L4 does not have a byte-write mode */
1608             int voltage = stlink_target_voltage(sl);
1609             if (voltage == -1) {
1610                 printf("Failed to read Target voltage\n");
1611                 return voltage;
1612             } else if (voltage < 1710) {
1613                 printf("Target voltage (%d mV) too low for flash writes!\n", voltage);
1614                 return -1;
1615             }
1616         }
1617
1618         /* set programming mode */
1619         set_flash_cr_pg(sl);
1620
1621         for(off = 0; off < len;) {
1622             size_t size = len - off > 0x8000 ? 0x8000 : len - off;
1623
1624             printf("size: %zu\n", size);
1625
1626             if (stlink_flash_loader_run(sl, &fl, addr + off, base + off, size) == -1) {
1627                 ELOG("stlink_flash_loader_run(%#zx) failed! == -1\n", addr + off);
1628                 return -1;
1629             }
1630
1631             off += size;
1632         }
1633
1634         /* Relock flash */
1635         lock_flash(sl);
1636
1637     }   //STM32F4END
1638
1639     else if (sl->flash_type == FLASH_TYPE_L0) {
1640         /* use fast word write. todo: half page. */
1641         uint32_t val;
1642         uint32_t flash_regs_base;
1643         uint32_t pagesize;
1644
1645         if (sl->chip_id == STLINK_CHIPID_STM32_L0 || sl->chip_id == STLINK_CHIPID_STM32_L0_CAT5 || sl->chip_id == STLINK_CHIPID_STM32_L0_CAT2) {
1646             flash_regs_base = STM32L0_FLASH_REGS_ADDR;
1647             pagesize = L0_WRITE_BLOCK_SIZE;
1648         } else {
1649             flash_regs_base = STM32L_FLASH_REGS_ADDR;
1650             pagesize = L1_WRITE_BLOCK_SIZE;
1651         }
1652
1653         /* todo: check write operation */
1654
1655         /* disable pecr protection */
1656         stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF, 0x89abcdef);
1657         stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF, 0x02030405);
1658
1659         /* check pecr.pelock is cleared */
1660         stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1661         if (val & (1 << 0)) {
1662             fprintf(stderr, "pecr.pelock not clear\n");
1663             return -1;
1664         }
1665
1666         /* unlock program memory */
1667         stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF, 0x8c9daebf);
1668         stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF, 0x13141516);
1669
1670         /* check pecr.prglock is cleared */
1671         stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1672         if (val & (1 << 1)) {
1673             fprintf(stderr, "pecr.prglock not clear\n");
1674             return -1;
1675         }
1676         off = 0;
1677         if (len > pagesize) {
1678             if (stm32l1_write_half_pages(sl, addr, base, len, pagesize) == -1) {
1679                 /* This may happen on a blank device! */
1680                 WLOG("\nwrite_half_pages failed == -1\n");
1681             } else {
1682                 off = (len / pagesize)*pagesize;
1683             }
1684         }
1685
1686         /* write remainingword in program memory */
1687         for ( ; off < len; off += sizeof(uint32_t)) {
1688             uint32_t data;
1689             if (off > 254)
1690                 fprintf(stdout, "\r");
1691
1692             if ((off % sl->flash_pgsz) > (sl->flash_pgsz -5)) {
1693                 fprintf(stdout, "\r%3zd/%3zd pages written",
1694                         off/sl->flash_pgsz, len/sl->flash_pgsz);
1695                 fflush(stdout);
1696             }
1697
1698             write_uint32((unsigned char*) &data, *(uint32_t*) (base + off));
1699             stlink_write_debug32(sl, addr + off, data);
1700
1701             /* wait for sr.busy to be cleared */
1702             do {
1703                 stlink_read_debug32(sl, flash_regs_base + FLASH_SR_OFF, &val);
1704             } while ((val & (1 << 0)) != 0);
1705
1706             /* todo: check redo write operation */
1707
1708         }
1709         fprintf(stdout, "\n");
1710         /* reset lock bits */
1711         stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
1712         val |= (1 << 0) | (1 << 1) | (1 << 2);
1713         stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
1714     } else if (sl->flash_type == FLASH_TYPE_F0) {
1715         ILOG("Starting Flash write for VL/F0/F3 core id\n");
1716         /* flash loader initialization */
1717         if (stlink_flash_loader_init(sl, &fl) == -1) {
1718             ELOG("stlink_flash_loader_init() == -1\n");
1719             return -1;
1720         }
1721
1722         int write_block_count = 0;
1723         for (off = 0; off < len; off += sl->flash_pgsz) {
1724             /* adjust last write size */
1725             size_t size = sl->flash_pgsz;
1726             if ((off + sl->flash_pgsz) > len) size = len - off;
1727
1728             /* unlock and set programming mode */
1729             unlock_flash_if(sl);
1730             set_flash_cr_pg(sl);
1731             DLOG("Finished setting flash cr pg, running loader!\n");
1732             if (stlink_flash_loader_run(sl, &fl, addr + off, base + off, size) == -1) {
1733                 ELOG("stlink_flash_loader_run(%#zx) failed! == -1\n", addr + off);
1734                 return -1;
1735             }
1736             lock_flash(sl);
1737             if (sl->verbose >= 1) {
1738                 /* show progress. writing procedure is slow
1739                    and previous errors are misleading */
1740                 fprintf(stdout, "\r%3u/%lu pages written", write_block_count++, (unsigned long)len/sl->flash_pgsz);
1741                 fflush(stdout);
1742             }
1743         }
1744         fprintf(stdout, "\n");
1745     } else {
1746         ELOG("unknown coreid, not sure how to write: %x\n", sl->core_id);
1747         return -1;
1748     }
1749
1750     return stlink_verify_write_flash(sl, addr, base, len);
1751 }
1752
1753 /**
1754  * Write the given binary file into flash at address "addr"
1755  * @param sl
1756  * @param path readable file path, should be binary image
1757  * @param addr where to start writing
1758  * @return 0 on success, -ve on failure.
1759  */
1760 int stlink_fwrite_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
1761     /* write the file in flash at addr */
1762     int err;
1763     unsigned int num_empty, index, val;
1764     unsigned char erased_pattern;
1765     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1766
1767     if (map_file(&mf, path) == -1) {
1768         ELOG("map_file() == -1\n");
1769         return -1;
1770     }
1771
1772     if (sl->flash_type == FLASH_TYPE_L0)
1773         erased_pattern = 0x00;
1774     else
1775         erased_pattern = 0xff;
1776
1777     index = mf.len;
1778     for(num_empty = 0; num_empty != mf.len; ++num_empty) {
1779         if (mf.base[--index] != erased_pattern) {
1780             break;
1781         }
1782     }
1783     /* Round down to words */
1784     num_empty -= (num_empty & 3);
1785     if(num_empty != 0) {
1786         ILOG("Ignoring %d bytes of 0x%02x at end of file\n", num_empty, erased_pattern);
1787     }
1788     err = stlink_write_flash(sl, addr, mf.base, num_empty == mf.len? mf.len : mf.len - num_empty, num_empty == mf.len);
1789     /* set stack*/
1790     stlink_read_debug32(sl, addr, &val);
1791     stlink_write_reg(sl, val, 13);
1792     /* Set PC to the reset routine*/
1793     stlink_read_debug32(sl, addr + 4, &val);
1794     stlink_write_reg(sl, val, 15);
1795     stlink_run(sl);
1796     unmap_file(&mf);
1797     return err;
1798 }