gdbserver: use uglylogging logging
[fw/stlink] / src / stlink-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 #include "mmap.h"
13
14 #include "stlink-common.h"
15 #include "uglylogging.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
67 //STM32F4
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
80
81
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];
88     } else {
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];
93     }
94 }
95
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];
100     } else {
101         buf[0] = ((unsigned char*) &ui)[1];
102         buf[1] = ((unsigned char*) &ui)[0];
103     }
104 }
105
106 uint32_t read_uint32(const unsigned char *c, const int pt) {
107     uint32_t ui;
108     char *p = (char *) &ui;
109
110     if (!is_bigendian()) { // le -> le (don't swap)
111         p[0] = c[pt + 0];
112         p[1] = c[pt + 1];
113         p[2] = c[pt + 2];
114         p[3] = c[pt + 3];
115     } else {
116         p[0] = c[pt + 3];
117         p[1] = c[pt + 2];
118         p[2] = c[pt + 1];
119         p[3] = c[pt + 0];
120     }
121     return ui;
122 }
123
124 static uint32_t __attribute__((unused)) read_flash_rdp(stlink_t *sl) {
125     return stlink_read_debug32(sl, FLASH_WRPR) & 0xff;
126 }
127
128 static inline uint32_t read_flash_wrpr(stlink_t *sl) {
129     return stlink_read_debug32(sl, FLASH_WRPR);
130 }
131
132 static inline uint32_t read_flash_obr(stlink_t *sl) {
133     return stlink_read_debug32(sl, FLASH_OBR);
134 }
135
136 static inline uint32_t read_flash_cr(stlink_t *sl) {
137     uint32_t res;
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);
141     else
142         res = stlink_read_debug32(sl, FLASH_CR);
143 #if DEBUG_FLASH
144     fprintf(stdout, "CR:0x%x\n", res);
145 #endif
146     return res;
147 }
148
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);
154     else
155         return read_flash_cr(sl) & (1 << FLASH_CR_LOCK);
156 }
157
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.
163        */
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);
168     } else {
169         stlink_write_debug32(sl, FLASH_KEYR, FLASH_KEY1);
170         stlink_write_debug32(sl, FLASH_KEYR, FLASH_KEY2);
171     }
172
173 }
174
175 static int unlock_flash_if(stlink_t *sl) {
176     /* unlock flash if already locked */
177
178     if (is_flash_locked(sl)) {
179         unlock_flash(sl);
180         if (is_flash_locked(sl)) {
181             WLOG("Failed to unlock flash!\n");
182             return -1;
183         }
184     }
185     DLOG("Successfully unlocked flash\n");
186     return 0;
187 }
188
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);
194     } else {
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);
198     }
199 }
200
201
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);
208     } else {
209         const uint32_t n = 1 << FLASH_CR_PG;
210         stlink_write_debug32(sl, FLASH_CR, n);
211     }
212 }
213
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);
219     else
220         stlink_write_debug32(sl, FLASH_CR, n);
221 }
222
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);
226 }
227
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);
231 }
232
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));
238     else
239         stlink_write_debug32(sl, FLASH_CR,
240                 stlink_read_debug32(sl, FLASH_CR) | (1 << FLASH_CR_MER));
241 }
242
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));
248     else
249         stlink_write_debug32(sl, FLASH_CR,
250                 stlink_read_debug32(sl, FLASH_CR) & ~(1 << FLASH_CR_MER));
251 }
252
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);
259     } else {
260         stlink_write_debug32(sl, FLASH_CR,
261                 stlink_read_debug32(sl, FLASH_CR) | (1 << FLASH_CR_STRT) );
262     }
263 }
264
265 static inline uint32_t read_flash_acr(stlink_t *sl) {
266     return stlink_read_debug32(sl, FLASH_ACR);
267 }
268
269 static inline uint32_t read_flash_sr(stlink_t *sl) {
270     uint32_t res;
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);
274     else
275         res = stlink_read_debug32(sl, FLASH_SR);
276     //fprintf(stdout, "SR:0x%x\n", *(uint32_t*) sl->q_buf);
277     return res;
278 }
279
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);
284     else
285         return read_flash_sr(sl) & (1 << FLASH_SR_BSY);
286 }
287
288 static void wait_flash_busy(stlink_t *sl) {
289     /* todo: add some delays here */
290     while (is_flash_busy(sl))
291         ;
292 }
293
294 static void wait_flash_busy_progress(stlink_t *sl) {
295     int i = 0;
296     fprintf(stdout, "Mass erasing");
297     fflush(stdout);
298     while (is_flash_busy(sl)) {
299         usleep(10000);
300         i++;
301         if (i % 100 == 0) {
302             fprintf(stdout, ".");
303             fflush(stdout);
304         }
305     }
306     fprintf(stdout, "\n");
307 }
308
309 static inline unsigned int is_flash_eop(stlink_t *sl) {
310     return read_flash_sr(sl) & (1 << FLASH_SR_EOP);
311 }
312
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);
316 }
317
318 static void __attribute__((unused)) wait_flash_eop(stlink_t *sl) {
319     /* todo: add some delays here */
320     while (is_flash_eop(sl) == 0)
321         ;
322 }
323
324 static inline void write_flash_ar(stlink_t *sl, uint32_t n) {
325     stlink_write_debug32(sl, FLASH_AR, n);
326 }
327
328 static inline void write_flash_cr_psiz(stlink_t *sl, uint32_t n) {
329     uint32_t x = read_flash_cr(sl);
330     x &= ~(0x03 << 8);
331     x |= (n << 8);
332 #if DEBUG_FLASH
333     fprintf(stdout, "PSIZ:0x%x 0x%x\n", x, n);
334 #endif
335     stlink_write_debug32(sl, FLASH_F4_CR, x);
336 }
337
338
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);
344 #if DEBUG_FLASH
345     fprintf(stdout, "SNB:0x%x 0x%x\n", x, n);
346 #endif
347     stlink_write_debug32(sl, FLASH_F4_CR, x);
348 }
349
350 // Delegates to the backends...
351
352 void stlink_close(stlink_t *sl) {
353     DLOG("*** stlink_close ***\n");
354     sl->backend->close(sl);
355     free(sl);
356 }
357
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);
362 }
363
364 void stlink_enter_swd_mode(stlink_t *sl) {
365     DLOG("*** stlink_enter_swd_mode ***\n");
366     sl->backend->enter_swd_mode(sl);
367 }
368
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);
373 }
374
375 void stlink_exit_dfu_mode(stlink_t *sl) {
376     DLOG("*** stlink_exit_dfu_mode ***\n");
377     sl->backend->exit_dfu_mode(sl);
378 }
379
380 uint32_t stlink_core_id(stlink_t *sl) {
381     DLOG("*** stlink_core_id ***\n");
382     sl->backend->core_id(sl);
383     if (sl->verbose > 2)
384         stlink_print_data(sl);
385     DLOG("core_id = 0x%08x\n", sl->core_id);
386     return sl->core_id;
387 }
388
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
392     return chip_id;
393 }
394
395 /**
396  * Cortex m3 tech ref manual, CPUID register description
397  * @param sl stlink context
398  * @param cpuid pointer to the result object
399  */
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;
406     return;
407 }
408
409 /**
410  * reads and decodes the flash parameters, as dynamically as possible
411  * @param sl
412  * @return 0 for success, or -1 for unsupported core type.
413  */
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);
419     uint32_t flash_size;
420
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)
426             sl->chip_id = 0x413;
427     }
428
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];
432             break;
433         }
434     }
435     if (params == NULL) {
436         WLOG("unknown chip id! %#x\n", chip_id);
437         return -1;
438     }
439
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;
447
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;
454         } else {
455             sl->flash_size = 256 * 1024;
456         }
457     } else {
458         sl->flash_size = flash_size * 1024;
459     }
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;
464
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,
469             sl->flash_pgsz);
470     return 0;
471 }
472
473 void stlink_reset(stlink_t *sl) {
474     DLOG("*** stlink_reset ***\n");
475     sl->backend->reset(sl);
476 }
477
478 void stlink_jtag_reset(stlink_t *sl, int value) {
479     DLOG("*** stlink_jtag_reset ***\n");
480     sl->backend->jtag_reset(sl, value);
481 }
482
483 void stlink_run(stlink_t *sl) {
484     DLOG("*** stlink_run ***\n");
485     sl->backend->run(sl);
486 }
487
488 void stlink_status(stlink_t *sl) {
489     DLOG("*** stlink_status ***\n");
490     sl->backend->status(sl);
491     stlink_core_stat(sl);
492 }
493
494 /**
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
498  */
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
506
507     // b0 b1                       || b2 b3  | b4 b5
508     // 4b        | 6b     | 6b     || 2B     | 2B
509     // stlink_v  | jtag_v | swim_v || st_vid | stlink_pid
510
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;
516     return;
517 }
518
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);
523
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");
531     }
532     if (sl->version.swim_v == 0) {
533         DLOG("    notice: the firmware doesn't support a swim interface\n");
534     }
535 }
536
537 int stlink_target_voltage(stlink_t *sl) {
538     int voltage = -1;
539     DLOG("*** reading target voltage\n");
540     if (sl->backend->target_voltage != NULL) {
541         voltage = sl->backend->target_voltage(sl);
542         if (voltage != -1) {
543             DLOG("target voltage = %ldmV\n", voltage);
544         } else {
545             DLOG("error reading target voltage\n");
546         }
547     } else {
548         DLOG("reading voltage not supported by backend\n");
549     }
550     return voltage;
551 }
552
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);
556     return data;
557 }
558
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);
562 }
563
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);
566     if (len % 4 != 0) {
567         fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
568         abort();
569     }
570     sl->backend->write_mem32(sl, addr, len);
571 }
572
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",
577                 len % 4);
578         abort();
579     }
580     sl->backend->read_mem32(sl, addr, len);
581 }
582
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",
587                 len);
588         abort();
589     }
590     sl->backend->write_mem8(sl, addr, len);
591 }
592
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);
596 }
597
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);
601 }
602
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);
606 }
607
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);
611
612     if (r_idx > 20 || r_idx < 0) {
613         fprintf(stderr, "Error: register index must be in [0..20]\n");
614         return;
615     }
616
617     sl->backend->read_reg(sl, r_idx, regp);
618 }
619
620 void stlink_read_unsupported_reg(stlink_t *sl, int r_idx, reg *regp) {
621     int r_convert;
622
623     DLOG("*** stlink_read_unsupported_reg\n");
624     DLOG(" (%d) ***\n", r_idx);
625
626     /* Convert to values used by DCRSR */
627     if (r_idx >= 0x1C && r_idx <= 0x1F) { /* primask, basepri, faultmask, or control */
628         r_convert = 0x14;
629     } else if (r_idx == 0x40) {     /* FPSCR */
630         r_convert = 0x21;
631     } else if (r_idx >= 0x20 && r_idx < 0x40) {
632         r_convert = 0x40 + (r_idx - 0x20);
633     } else {
634         fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
635         return;
636     }
637
638     sl->backend->read_unsupported_reg(sl, r_convert, regp);
639 }
640
641 void stlink_write_unsupported_reg(stlink_t *sl, uint32_t val, int r_idx, reg *regp) {
642     int r_convert;
643
644     DLOG("*** stlink_write_unsupported_reg\n");
645     DLOG(" (%d) ***\n", r_idx);
646
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 */
651         r_convert = 0x21;
652     } else if (r_idx >= 0x20 && r_idx < 0x40) {
653         r_convert = 0x40 + (r_idx - 0x20);
654     } else {
655         fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
656         return;
657     }
658
659     sl->backend->write_unsupported_reg(sl, val, r_convert, regp);
660 }
661
662 unsigned int is_core_halted(stlink_t *sl) {
663     /* return non zero if core is halted */
664     stlink_status(sl);
665     return sl->q_buf[0] == STLINK_CORE_HALTED;
666 }
667
668 void stlink_step(stlink_t *sl) {
669     DLOG("*** stlink_step ***\n");
670     sl->backend->step(sl);
671 }
672
673 int stlink_current_mode(stlink_t *sl) {
674     int mode = sl->backend->current_mode(sl);
675     switch (mode) {
676     case STLINK_DEV_DFU_MODE:
677         DLOG("stlink current mode: dfu\n");
678         return mode;
679     case STLINK_DEV_DEBUG_MODE:
680         DLOG("stlink current mode: debug (jtag or swd)\n");
681         return mode;
682     case STLINK_DEV_MASS_MODE:
683         DLOG("stlink current mode: mass\n");
684         return mode;
685     }
686     DLOG("stlink mode: unknown!\n");
687     return STLINK_DEV_UNKNOWN_MODE;
688 }
689
690
691
692
693 // End of delegates....  Common code below here...
694
695 // Endianness
696 // http://www.ibm.com/developerworks/aix/library/au-endianc/index.html
697 // const int i = 1;
698 // #define is_bigendian() ( (*(char*)&i) == 0 )
699
700 inline unsigned int is_bigendian(void) {
701     static volatile const unsigned int i = 1;
702     return *(volatile const char*) &i == 0;
703 }
704
705 uint16_t read_uint16(const unsigned char *c, const int pt) {
706     uint32_t ui;
707     char *p = (char *) &ui;
708
709     if (!is_bigendian()) { // le -> le (don't swap)
710         p[0] = c[pt + 0];
711         p[1] = c[pt + 1];
712     } else {
713         p[0] = c[pt + 1];
714         p[1] = c[pt + 0];
715     }
716     return ui;
717 }
718
719 // same as above with entrypoint.
720
721 void stlink_run_at(stlink_t *sl, stm32_addr_t addr) {
722     stlink_write_reg(sl, addr, 15); /* pc register */
723
724     stlink_run(sl);
725
726     while (is_core_halted(sl) == 0)
727         usleep(3000000);
728 }
729
730 void stlink_core_stat(stlink_t *sl) {
731     if (sl->q_len <= 0)
732         return;
733
734     switch (sl->q_buf[0]) {
735     case STLINK_CORE_RUNNING:
736         sl->core_stat = STLINK_CORE_RUNNING;
737         DLOG("  core status: running\n");
738         return;
739     case STLINK_CORE_HALTED:
740         sl->core_stat = STLINK_CORE_HALTED;
741         DLOG("  core status: halted\n");
742         return;
743     default:
744         sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
745         fprintf(stderr, "  core status: unknown\n");
746     }
747 }
748
749 void stlink_print_data(stlink_t * sl) {
750     if (sl->q_len <= 0 || sl->verbose < UDEBUG)
751         return;
752     if (sl->verbose > 2)
753         fprintf(stdout, "data_len = %d 0x%x\n", sl->q_len, sl->q_len);
754
755     for (int i = 0; i < sl->q_len; i++) {
756         if (i % 16 == 0) {
757             /*
758                if (sl->q_data_dir == Q_DATA_OUT)
759                fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
760                else
761                fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
762                */
763         }
764         fprintf(stdout, " %02x", (unsigned int) sl->q_buf[i]);
765     }
766     fputs("\n\n", stdout);
767 }
768
769 /* memory mapped file */
770
771 typedef struct mapped_file {
772     uint8_t* base;
773     size_t len;
774 } mapped_file_t;
775
776 #define MAPPED_FILE_INITIALIZER { NULL, 0 }
777
778 static int map_file(mapped_file_t* mf, const char* path) {
779     int error = -1;
780     struct stat st;
781
782     const int fd = open(path, O_RDONLY | O_BINARY);
783     if (fd == -1) {
784         fprintf(stderr, "open(%s) == -1\n", path);
785         return -1;
786     }
787
788     if (fstat(fd, &st) == -1) {
789         fprintf(stderr, "fstat() == -1\n");
790         goto on_error;
791     }
792
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");
796         goto on_error;
797     }
798
799     mf->len = st.st_size;
800
801     /* success */
802     error = 0;
803
804 on_error:
805     close(fd);
806
807     return error;
808 }
809
810 static void unmap_file(mapped_file_t * mf) {
811     munmap((void*) mf->base, mf->len);
812     mf->base = (unsigned char*) MAP_FAILED;
813     mf->len = 0;
814 }
815
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) {
820     size_t off;
821     size_t n_cmp = sl->flash_pgsz;
822     if ( n_cmp > 0x1800)
823         n_cmp = 0x1800;
824
825     for (off = 0; off < mf->len; off += n_cmp) {
826         size_t aligned_size;
827
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;
832
833         aligned_size = cmp_size;
834         if (aligned_size & (4 - 1))
835             aligned_size = (cmp_size + 4) & ~(4 - 1);
836
837         stlink_read_mem32(sl, addr + off, aligned_size);
838
839         if (memcmp(sl->q_buf, mf->base + off, cmp_size))
840             return -1;
841     }
842
843     return 0;
844 }
845
846 int stlink_fwrite_sram
847 (stlink_t * sl, const char* path, stm32_addr_t addr) {
848     /* write the file in sram at addr */
849
850     int error = -1;
851     size_t off;
852     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
853
854
855     if (map_file(&mf, path) == -1) {
856         fprintf(stderr, "map_file() == -1\n");
857         return -1;
858     }
859
860     /* check addr range is inside the sram */
861     if (addr < sl->sram_base) {
862         fprintf(stderr, "addr too low\n");
863         goto on_error;
864     } else if ((addr + mf.len) < addr) {
865         fprintf(stderr, "addr overruns\n");
866         goto on_error;
867     } else if ((addr + mf.len) > (sl->sram_base + sl->sram_size)) {
868         fprintf(stderr, "addr too high\n");
869         goto on_error;
870     } else if ((addr & 3) || (mf.len & 3)) {
871         /* todo */
872         fprintf(stderr, "unaligned addr or size\n");
873         goto on_error;
874     }
875     /* do the copy by 1k blocks */
876     for (off = 0; off < mf.len; off += 1024) {
877         size_t size = 1024;
878         if ((off + size) > mf.len)
879             size = mf.len - off;
880
881         memcpy(sl->q_buf, mf.base + off, size);
882
883         /* round size if needed */
884         if (size & 3)
885             size += 2;
886
887         stlink_write_mem32(sl, addr + off, size);
888     }
889
890     /* check the file ha been written */
891     if (check_file(sl, &mf, addr) == -1) {
892         fprintf(stderr, "check_file() == -1\n");
893         goto on_error;
894     }
895
896     /* success */
897     error = 0;
898     /* set stack*/
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);
902     stlink_run(sl);
903
904 on_error:
905     unmap_file(&mf);
906     return error;
907 }
908
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 */
911
912     int error = -1;
913     size_t off;
914     int num_empty = 0;
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;
917
918     const int fd = open(path, O_RDWR | O_TRUNC | O_CREAT, 00700);
919     if (fd == -1) {
920         fprintf(stderr, "open(%s) == -1\n", path);
921         return -1;
922     }
923
924     if (size <1)
925         size = sl->flash_size;
926
927     if (size > sl->flash_size)
928         size = sl->flash_size;
929
930     /* do the copy by 1k blocks */
931     for (off = 0; off < size; off += 1024) {
932         size_t read_size = 1024;
933         size_t rounded_size;
934         size_t index;
935         if ((off + read_size) > size)
936             read_size = size - off;
937
938         /* round size if needed */
939         rounded_size = read_size;
940         if (rounded_size & 3)
941             rounded_size = (rounded_size + 4) & ~(3);
942
943         stlink_read_mem32(sl, addr + off, rounded_size);
944
945         for(index = 0; index < read_size; index ++) {
946             if (sl->q_buf[index] == erased_pattern)
947                 num_empty ++;
948             else
949                 num_empty = 0;
950         }
951         if (write(fd, sl->q_buf, read_size) != (ssize_t) read_size) {
952             fprintf(stderr, "write() != read_size\n");
953             goto on_error;
954         }
955     }
956
957     /* Ignore NULL Bytes at end of file */
958     if (!ftruncate(fd, size - num_empty)) {
959         error = -1;
960     }
961
962     /* success */
963     error = 0;
964
965 on_error:
966     close(fd);
967
968     return error;
969 }
970
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;
975     if (chunk) {
976         memcpy(sl->q_buf, buf, chunk);
977         stlink_write_mem32(sl, fl->buf_addr, chunk);
978     }
979     if (rem) {
980         memcpy(sl->q_buf, buf+chunk, rem);
981         stlink_write_mem8(sl, (fl->buf_addr)+chunk, rem);
982     }
983     return 0;
984 }
985
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;
994
995 }
996
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;
1004     }
1005     return (sl->flash_pgsz);
1006 }
1007
1008 /**
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
1013  */
1014 int stlink_erase_flash_page(stlink_t *sl, stm32_addr_t flashaddr)
1015 {
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);
1020
1021         /* unlock if locked */
1022         unlock_flash_if(sl);
1023
1024         /* select the page to erase */
1025         // calculate the actual page from the address
1026         uint32_t sector=calculate_F4_sectornum(flashaddr);
1027
1028         fprintf(stderr, "EraseFlash - Sector:0x%x Size:0x%x\n", sector, stlink_calculate_pagesize(sl, flashaddr));
1029         write_flash_cr_snb(sl, sector);
1030
1031         /* start erase operation */
1032         set_flash_cr_strt(sl);
1033
1034         /* wait for completion */
1035         wait_flash_busy(sl);
1036
1037         /* relock the flash */
1038         //todo: fails to program if this is in
1039         lock_flash(sl);
1040 #if DEBUG_FLASH
1041         fprintf(stdout, "Erase Final CR:0x%x\n", read_flash_cr(sl));
1042 #endif
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) {
1045
1046         uint32_t val;
1047
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);
1054
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);
1059                 return -1;
1060             }
1061
1062             /* unlock program memory */
1063             stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x8c9daebf);
1064             stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x13141516);
1065
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);
1070                 return -1;
1071             }
1072         }
1073
1074         /* set pecr.{erase,prog} */
1075         val |= (1 << 9) | (1 << 3);
1076         stlink_write_debug32(sl, STM32L_FLASH_PECR, val);
1077
1078 #if 0 /* fix_to_be_confirmed */
1079
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.
1085          */
1086         while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0)
1087             ;
1088
1089 #endif /* fix_to_be_confirmed */
1090
1091         /* write 0 to the first word of the page to be erased */
1092         stlink_write_debug32(sl, flashaddr, 0);
1093
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)
1099             ;
1100
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);
1111
1112         /* unlock if locked */
1113         unlock_flash_if(sl);
1114
1115         /* set the page erase bit */
1116         set_flash_cr_per(sl);
1117
1118         /* select the page to erase */
1119         write_flash_ar(sl, flashaddr);
1120
1121         /* start erase operation, reset by hw with bsy bit */
1122         set_flash_cr_strt(sl);
1123
1124         /* wait for completion */
1125         wait_flash_busy(sl);
1126
1127         /* relock the flash */
1128         lock_flash(sl);
1129     } else {
1130         WLOG("unknown coreid %x, page erase failed\n", sl->core_id);
1131         return -1;
1132     }
1133
1134     /* todo: verify the erased page */
1135
1136     return 0;
1137 }
1138
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);
1149                 return -1;
1150             }
1151             fprintf(stdout,"\rFlash page at %5d/%5d erased", i, num_pages);
1152             fflush(stdout);
1153         }
1154         fprintf(stdout, "\n");
1155     } else {
1156         /* wait for ongoing op to finish */
1157         wait_flash_busy(sl);
1158
1159         /* unlock if locked */
1160         unlock_flash_if(sl);
1161
1162         /* set the mass erase bit */
1163         set_flash_cr_mer(sl);
1164
1165         /* start erase operation, reset by hw with bsy bit */
1166         set_flash_cr_strt(sl);
1167
1168         /* wait for completion */
1169         wait_flash_busy_progress(sl);
1170
1171         /* relock the flash */
1172         lock_flash(sl);
1173
1174         /* todo: verify the erased memory */
1175     }
1176     return 0;
1177 }
1178
1179 int init_flash_loader(stlink_t *sl, flash_loader_t* fl) {
1180     size_t size;
1181
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");
1185         return -1;
1186     }
1187
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");
1191     return 0;
1192 }
1193
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 */
1204         /* busy: */
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 */
1212         /* exit: */
1213         0x00, 0xbe, /* bkpt     #0x00 */
1214         0x00, 0x20, 0x02, 0x40, /* STM32_FLASH_BASE: .word 0x40022000 */
1215     };
1216
1217     /* flashloaders/stm32f0.s -- thumb1 only, same sequence as for STM32VL, bank ignored */
1218     static const uint8_t loader_code_stm32f0[] = {
1219 #if 1
1220         /*
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.
1226          *
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.
1231          */
1232         0x00, 0x30, //     nop     /* add r0,#0 */
1233         0x00, 0x30, //     nop     /* add r0,#0 */
1234 #endif
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  */
1238         // write_half_word:
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 */
1244         // busy:
1245         0xE3, 0x68, //     ldr     r3, [r4, #12]     /*  FLASH->SR  */
1246         0x2B, 0x42, //     tst     r3, r5            /*  FLASH_SR_BUSY  */
1247         0xFC, 0xD0, //     beq     busy
1248
1249         0x33, 0x42, //     tst     r3, r6            /*  PGERR  */
1250         0x04, 0xD1, //     bne     exit
1251
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
1257         // exit:
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 */
1263     };
1264
1265     static const uint8_t loader_code_stm32l[] = {
1266
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
1272            */
1273
1274         0x00, 0x23,
1275         0x04, 0xe0,
1276
1277         0x51, 0xf8, 0x04, 0xcb,
1278         0x40, 0xf8, 0x04, 0xcb,
1279         0x01, 0x33,
1280
1281         0x93, 0x42,
1282         0xf8, 0xd3,
1283         0x00, 0xbe
1284     };
1285
1286     static const uint8_t loader_code_stm32f4[] = {
1287         // flashloaders/stm32f4.s
1288
1289         0x07, 0x4b,
1290
1291         0x62, 0xb1,
1292         0x04, 0x68,
1293         0x0c, 0x60,
1294
1295         0xdc, 0x89,
1296         0x14, 0xf0, 0x01, 0x0f,
1297         0xfb, 0xd1,
1298         0x00, 0xf1, 0x04, 0x00,
1299         0x01, 0xf1, 0x04, 0x01,
1300         0xa2, 0xf1, 0x01, 0x02,
1301         0xf1, 0xe7,
1302
1303         0x00, 0xbe,
1304
1305         0x00, 0x3c, 0x02, 0x40,
1306     };
1307
1308     const uint8_t* loader_code;
1309     size_t loader_size;
1310
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);
1325     } else {
1326         ELOG("unknown coreid, not sure what flash loader to use, aborting!: %x\n", sl->core_id);
1327         return -1;
1328     }
1329
1330     memcpy(sl->q_buf, loader_code, loader_size);
1331     stlink_write_mem32(sl, sl->sram_base, loader_size);
1332
1333     *addr = sl->sram_base;
1334     *size = loader_size;
1335
1336     /* success */
1337     return 0;
1338 }
1339
1340 int stlink_fcheck_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
1341     /* check the contents of path are at addr */
1342
1343     int res;
1344     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
1345
1346     if (map_file(&mf, path) == -1)
1347         return -1;
1348
1349     res = check_file(sl, &mf, addr);
1350
1351     unmap_file(&mf);
1352
1353     return res;
1354 }
1355
1356 /**
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
1363  */
1364 int stlink_verify_write_flash(stlink_t *sl, stm32_addr_t address, uint8_t *data, unsigned length) {
1365     size_t off;
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;
1370
1371         /* adjust last page size */
1372         if ((off + cmp_size) > length)
1373             cmp_size = length - off;
1374
1375         aligned_size = cmp_size;
1376         if (aligned_size & (4 - 1))
1377             aligned_size = (cmp_size + 4) & ~(4 - 1);
1378
1379         stlink_read_mem32(sl, address + off, aligned_size);
1380
1381         if (memcmp(sl->q_buf, data + off, cmp_size)) {
1382             ELOG("Verification of flash failed at offset: %zd\n", off);
1383             return -1;
1384         }
1385     }
1386     ILOG("Flash written and verified! jolly good!\n");
1387     return 0;
1388
1389 }
1390
1391 int stm32l1_write_half_pages(stlink_t *sl, stm32_addr_t addr, uint8_t* base, unsigned num_half_pages)
1392 {
1393     unsigned int count;
1394     uint32_t val;
1395     flash_loader_t fl;
1396
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");
1401         return -1;
1402     }
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);
1407
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) {}
1411
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);
1419             return -1;
1420         }
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);
1426             fflush(stdout);
1427         }
1428         while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0) {
1429         }
1430     }
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);
1437
1438     return 0;
1439 }
1440
1441 int stlink_write_flash(stlink_t *sl, stm32_addr_t addr, uint8_t* base, uint32_t len) {
1442     size_t off;
1443     flash_loader_t fl;
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);
1450         return -1;
1451     } else if ((addr + len) < addr) {
1452         ELOG("addr overruns\n");
1453         return -1;
1454     } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
1455         ELOG("addr too high\n");
1456         return -1;
1457     } else if (addr & 1) {
1458         ELOG("unaligned addr 0x%x\n", addr);
1459         return -1;
1460     } else if (len & 1) {
1461         WLOG("unaligned len 0x%x -- padding with zero\n", len);
1462         len += 1;
1463     } else if (addr & (sl->flash_pgsz - 1)) {
1464         ELOG("addr not a multiple of pagesize, not supported\n");
1465         return -1;
1466     }
1467
1468     // Make sure we've loaded the context with the chip details
1469     stlink_core_id(sl);
1470     /* erase each page */
1471     int page_count = 0;
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);
1476             return -1;
1477         }
1478         fprintf(stdout,"\rFlash page at addr: 0x%08lx erased",
1479                 (unsigned long)addr + off);
1480         fflush(stdout);
1481         page_count++;
1482     }
1483     fprintf(stdout,"\n");
1484     ILOG("Finished erasing %d pages of %d (%#x) bytes\n",
1485             page_count, sl->flash_pgsz, sl->flash_pgsz);
1486
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 */
1490
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");
1495             return -1;
1496         }
1497
1498         /* First unlock the cr */
1499         unlock_flash_if(sl);
1500
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);
1504
1505         /* set programming mode */
1506         set_flash_cr_pg(sl);
1507
1508         for(off = 0; off < len;) {
1509             size_t size = len - off > 0x8000 ? 0x8000 : len - off;
1510
1511             printf("size: %zu\n", size);
1512
1513             if (run_flash_loader(sl, &fl, addr + off, base + off, size) == -1) {
1514                 ELOG("run_flash_loader(%#zx) failed! == -1\n", addr + off);
1515                 return -1;
1516             }
1517
1518             off += size;
1519         }
1520
1521         /* Relock flash */
1522         lock_flash(sl);
1523
1524     }   //STM32F4END
1525
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. */
1529         uint32_t val;
1530
1531         /* todo: check write operation */
1532
1533         /* disable pecr protection */
1534         stlink_write_debug32(sl, STM32L_FLASH_PEKEYR, 0x89abcdef);
1535         stlink_write_debug32(sl, STM32L_FLASH_PEKEYR, 0x02030405);
1536
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");
1541             return -1;
1542         }
1543
1544         /* unlock program memory */
1545         stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x8c9daebf);
1546         stlink_write_debug32(sl, STM32L_FLASH_PRGKEYR, 0x13141516);
1547
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");
1552             return -1;
1553         }
1554         off = 0;
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");
1559             } else {
1560                 off = (len /L1_WRITE_BLOCK_SIZE)*L1_WRITE_BLOCK_SIZE;
1561             }
1562         }
1563
1564         /* write remainingword in program memory */
1565         for ( ; off < len; off += sizeof(uint32_t)) {
1566             uint32_t data;
1567             if (off > 254)
1568                 fprintf(stdout, "\r");
1569
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);
1573                 fflush(stdout);
1574             }
1575
1576             write_uint32((unsigned char*) &data, *(uint32_t*) (base + off));
1577             stlink_write_debug32(sl, addr + off, data);
1578
1579             /* wait for sr.busy to be cleared */
1580             while ((stlink_read_debug32(sl, STM32L_FLASH_SR) & (1 << 0)) != 0)
1581                 ;
1582
1583             /* todo: check redo write operation */
1584
1585         }
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");
1596             return -1;
1597         }
1598
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;
1604
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);
1611                 return -1;
1612             }
1613             lock_flash(sl);
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);
1618                 fflush(stdout);
1619             }
1620         }
1621         fprintf(stdout, "\n");
1622     } else {
1623         ELOG("unknown coreid, not sure how to write: %x\n", sl->core_id);
1624         return -1;
1625     }
1626
1627     return stlink_verify_write_flash(sl, addr, base, len);
1628 }
1629
1630 /**
1631  * Write the given binary file into flash at address "addr"
1632  * @param sl
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.
1636  */
1637 int stlink_fwrite_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
1638     /* write the file in flash at addr */
1639     int err;
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");
1646         return -1;
1647     }
1648     for(index = 0; index < mf.len; index ++) {
1649         if (mf.base[index] == erased_pattern)
1650             num_empty ++;
1651         else
1652             num_empty = 0;
1653     }
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;
1659     }
1660     err = stlink_write_flash(sl, addr, mf.base, mf.len);
1661     /* set stack*/
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);
1665     stlink_run(sl);
1666     unmap_file(&mf);
1667     return err;
1668 }
1669
1670 int run_flash_loader(stlink_t *sl, flash_loader_t* fl, stm32_addr_t target, const uint8_t* buf, size_t size) {
1671
1672     reg rr;
1673     int i = 0;
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) {
1677         // IMPOSSIBLE!
1678         ELOG("write_buffer_to_sram() == -1\n");
1679         return -1;
1680     }
1681
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 ) {
1684
1685         size_t count = size / sizeof(uint32_t);
1686         if (size % sizeof(uint32_t)) ++count;
1687
1688         /* setup core */
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 */
1693
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) {
1695
1696         size_t count = size / sizeof(uint16_t);
1697         if (size % sizeof(uint16_t)) ++count;
1698
1699         /* setup core */
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 */
1705
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) {
1708
1709         size_t count = size / sizeof(uint32_t);
1710         if (size % sizeof(uint32_t)) ++count;
1711
1712         /* setup core */
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 */
1717
1718     } else {
1719         fprintf(stderr, "unknown coreid 0x%x, don't know what flash loader to use\n", sl->core_id);
1720         return -1;
1721     }
1722
1723     /* run loader */
1724     stlink_run(sl);
1725
1726 #define WAIT_ROUNDS 10000
1727     /* wait until done (reaches breakpoint) */
1728     for (i = 0; i < WAIT_ROUNDS; i++) {
1729         usleep(10);
1730         if (is_core_halted(sl))
1731             break;
1732     }
1733
1734     if (i >= WAIT_ROUNDS) {
1735         ELOG("flash loader run error\n");
1736         return -1;
1737     }
1738
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 ) {
1742
1743         size_t count = size / sizeof(uint32_t);
1744         if (size % sizeof(uint32_t)) ++count;
1745
1746         stlink_read_reg(sl, 3, &rr);
1747         if (rr.r[3] != count) {
1748             fprintf(stderr, "write error, count == %u\n", rr.r[3]);
1749             return -1;
1750         }
1751
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) {
1753
1754         stlink_read_reg(sl, 2, &rr);
1755         if (rr.r[2] != 0) {
1756             fprintf(stderr, "write error, count == %u\n", rr.r[2]);
1757             return -1;
1758         }
1759
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) {
1762
1763         stlink_read_reg(sl, 2, &rr);
1764         if (rr.r[2] != 0) {
1765             fprintf(stderr, "write error, count == %u\n", rr.r[2]);
1766             return -1;
1767         }
1768
1769     } else {
1770
1771         fprintf(stderr, "unknown coreid 0x%x, can't check written byte count\n", sl->core_id);
1772         return -1;
1773
1774     }
1775
1776     return 0;
1777 }