Support arm core cpuid register decoding
[fw/stlink] / src / stlink-common.c
1
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 <sys/mman.h>
13
14
15 #include "stlink-common.h"
16
17 void D(stlink_t *sl, char *txt) {
18     if (sl->verbose > 1)
19         fputs(txt, stderr);
20 }
21
22 void DD(stlink_t *sl, char *format, ...) {
23     if (sl->verbose > 0) {
24         va_list list;
25         va_start(list, format);
26         vfprintf(stderr, format, list);
27         va_end(list);
28     }
29 }
30
31
32
33 /* FPEC flash controller interface, pm0063 manual
34  */
35
36 #define FLASH_REGS_ADDR 0x40022000
37 #define FLASH_REGS_SIZE 0x28
38
39 #define FLASH_ACR (FLASH_REGS_ADDR + 0x00)
40 #define FLASH_KEYR (FLASH_REGS_ADDR + 0x04)
41 #define FLASH_SR (FLASH_REGS_ADDR + 0x0c)
42 #define FLASH_CR (FLASH_REGS_ADDR + 0x10)
43 #define FLASH_AR (FLASH_REGS_ADDR + 0x14)
44 #define FLASH_OBR (FLASH_REGS_ADDR + 0x1c)
45 #define FLASH_WRPR (FLASH_REGS_ADDR + 0x20)
46
47 #define FLASH_RDPTR_KEY 0x00a5
48 #define FLASH_KEY1 0x45670123
49 #define FLASH_KEY2 0xcdef89ab
50
51 #define FLASH_SR_BSY 0
52 #define FLASH_SR_EOP 5
53
54 #define FLASH_CR_PG 0
55 #define FLASH_CR_PER 1
56 #define FLASH_CR_MER 2
57 #define FLASH_CR_STRT 6
58 #define FLASH_CR_LOCK 7
59
60 void write_uint32(unsigned char* buf, uint32_t ui) {
61     if (!is_bigendian()) { // le -> le (don't swap)
62         buf[0] = ((unsigned char*) &ui)[0];
63         buf[1] = ((unsigned char*) &ui)[1];
64         buf[2] = ((unsigned char*) &ui)[2];
65         buf[3] = ((unsigned char*) &ui)[3];
66     } else {
67         buf[0] = ((unsigned char*) &ui)[3];
68         buf[1] = ((unsigned char*) &ui)[2];
69         buf[2] = ((unsigned char*) &ui)[1];
70         buf[3] = ((unsigned char*) &ui)[0];
71     }
72 }
73
74 void write_uint16(unsigned char* buf, uint16_t ui) {
75     if (!is_bigendian()) { // le -> le (don't swap)
76         buf[0] = ((unsigned char*) &ui)[0];
77         buf[1] = ((unsigned char*) &ui)[1];
78     } else {
79         buf[0] = ((unsigned char*) &ui)[1];
80         buf[1] = ((unsigned char*) &ui)[0];
81     }
82 }
83
84 uint32_t read_uint32(const unsigned char *c, const int pt) {
85     uint32_t ui;
86     char *p = (char *) &ui;
87
88     if (!is_bigendian()) { // le -> le (don't swap)
89         p[0] = c[pt];
90         p[1] = c[pt + 1];
91         p[2] = c[pt + 2];
92         p[3] = c[pt + 3];
93     } else {
94         p[0] = c[pt + 3];
95         p[1] = c[pt + 2];
96         p[2] = c[pt + 1];
97         p[3] = c[pt];
98     }
99     return ui;
100 }
101
102 static uint32_t __attribute__((unused)) read_flash_rdp(stlink_t *sl) {
103     stlink_read_mem32(sl, FLASH_WRPR, sizeof (uint32_t));
104     return (*(uint32_t*) sl->q_buf) & 0xff;
105 }
106
107 static inline uint32_t read_flash_wrpr(stlink_t *sl) {
108     stlink_read_mem32(sl, FLASH_WRPR, sizeof (uint32_t));
109     return *(uint32_t*) sl->q_buf;
110 }
111
112 static inline uint32_t read_flash_obr(stlink_t *sl) {
113     stlink_read_mem32(sl, FLASH_OBR, sizeof (uint32_t));
114     return *(uint32_t*) sl->q_buf;
115 }
116
117 static inline uint32_t read_flash_cr(stlink_t *sl) {
118     stlink_read_mem32(sl, FLASH_CR, sizeof (uint32_t));
119     return *(uint32_t*) sl->q_buf;
120 }
121
122 static inline unsigned int is_flash_locked(stlink_t *sl) {
123     /* return non zero for true */
124     return read_flash_cr(sl) & (1 << FLASH_CR_LOCK);
125 }
126
127 static void unlock_flash(stlink_t *sl) {
128     /* the unlock sequence consists of 2 write cycles where
129        2 key values are written to the FLASH_KEYR register.
130        an invalid sequence results in a definitive lock of
131        the FPEC block until next reset.
132      */
133
134     write_uint32(sl->q_buf, FLASH_KEY1);
135     stlink_write_mem32(sl, FLASH_KEYR, sizeof (uint32_t));
136
137     write_uint32(sl->q_buf, FLASH_KEY2);
138     stlink_write_mem32(sl, FLASH_KEYR, sizeof (uint32_t));
139 }
140
141 static int unlock_flash_if(stlink_t *sl) {
142     /* unlock flash if already locked */
143
144     if (is_flash_locked(sl)) {
145         unlock_flash(sl);
146         if (is_flash_locked(sl))
147             return -1;
148     }
149
150     return 0;
151 }
152
153 static void lock_flash(stlink_t *sl) {
154     /* write to 1 only. reset by hw at unlock sequence */
155
156     const uint32_t n = read_flash_cr(sl) | (1 << FLASH_CR_LOCK);
157
158     write_uint32(sl->q_buf, n);
159     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
160 }
161
162 static void set_flash_cr_pg(stlink_t *sl) {
163     const uint32_t n = 1 << FLASH_CR_PG;
164     write_uint32(sl->q_buf, n);
165     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
166 }
167
168 static void __attribute__((unused)) clear_flash_cr_pg(stlink_t *sl) {
169     const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PG);
170     write_uint32(sl->q_buf, n);
171     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
172 }
173
174 static void set_flash_cr_per(stlink_t *sl) {
175     const uint32_t n = 1 << FLASH_CR_PER;
176     write_uint32(sl->q_buf, n);
177     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
178 }
179
180 static void __attribute__((unused)) clear_flash_cr_per(stlink_t *sl) {
181     const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_PER);
182     write_uint32(sl->q_buf, n);
183     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
184 }
185
186 static void set_flash_cr_mer(stlink_t *sl) {
187     const uint32_t n = 1 << FLASH_CR_MER;
188     write_uint32(sl->q_buf, n);
189     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
190 }
191
192 static void __attribute__((unused)) clear_flash_cr_mer(stlink_t *sl) {
193     const uint32_t n = read_flash_cr(sl) & ~(1 << FLASH_CR_MER);
194     write_uint32(sl->q_buf, n);
195     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
196 }
197
198 static void set_flash_cr_strt(stlink_t *sl) {
199     /* assume come on the flash_cr_per path */
200     const uint32_t n = (1 << FLASH_CR_PER) | (1 << FLASH_CR_STRT);
201     write_uint32(sl->q_buf, n);
202     stlink_write_mem32(sl, FLASH_CR, sizeof (uint32_t));
203 }
204
205 static inline uint32_t read_flash_acr(stlink_t *sl) {
206     stlink_read_mem32(sl, FLASH_ACR, sizeof (uint32_t));
207     return *(uint32_t*) sl->q_buf;
208 }
209
210 static inline uint32_t read_flash_sr(stlink_t *sl) {
211     stlink_read_mem32(sl, FLASH_SR, sizeof (uint32_t));
212     return *(uint32_t*) sl->q_buf;
213 }
214
215 static inline unsigned int is_flash_busy(stlink_t *sl) {
216     return read_flash_sr(sl) & (1 << FLASH_SR_BSY);
217 }
218
219 static void wait_flash_busy(stlink_t *sl) {
220     /* todo: add some delays here */
221     while (is_flash_busy(sl))
222         ;
223 }
224
225 static inline unsigned int is_flash_eop(stlink_t *sl) {
226     return read_flash_sr(sl) & (1 << FLASH_SR_EOP);
227 }
228
229 static void __attribute__((unused)) clear_flash_sr_eop(stlink_t *sl) {
230     const uint32_t n = read_flash_sr(sl) & ~(1 << FLASH_SR_EOP);
231     write_uint32(sl->q_buf, n);
232     stlink_write_mem32(sl, FLASH_SR, sizeof (uint32_t));
233 }
234
235 static void __attribute__((unused)) wait_flash_eop(stlink_t *sl) {
236     /* todo: add some delays here */
237     while (is_flash_eop(sl) == 0)
238         ;
239 }
240
241 static inline void write_flash_ar(stlink_t *sl, uint32_t n) {
242     write_uint32(sl->q_buf, n);
243     stlink_write_mem32(sl, FLASH_AR, sizeof (uint32_t));
244 }
245
246 #if 0 /* todo */
247
248 static void disable_flash_read_protection(stlink_t *sl) {
249     /* erase the option byte area */
250     /* rdp = 0x00a5; */
251     /* reset */
252 }
253 #endif /* todo */
254
255
256 // Delegates to the backends...
257
258 void stlink_close(stlink_t *sl) {
259     D(sl, "\n*** stlink_close ***\n");
260     sl->backend->close(sl);
261     free(sl);
262 }
263
264 void stlink_exit_debug_mode(stlink_t *sl) {
265     D(sl, "\n*** stlink_exit_debug_mode ***\n");
266     sl->backend->exit_debug_mode(sl);
267 }
268
269 void stlink_enter_swd_mode(stlink_t *sl) {
270     D(sl, "\n*** stlink_enter_swd_mode ***\n");
271     sl->backend->enter_swd_mode(sl);
272 }
273
274 // Force the core into the debug mode -> halted state.
275 void stlink_force_debug(stlink_t *sl) {
276     D(sl, "\n*** stlink_force_debug_mode ***\n");
277     sl->backend->force_debug(sl);
278 }
279
280 void stlink_exit_dfu_mode(stlink_t *sl) {
281     D(sl, "\n*** stlink_exit_dfu_mode ***\n");
282     sl->backend->exit_dfu_mode(sl);
283 }
284
285 uint32_t stlink_core_id(stlink_t *sl) {
286     D(sl, "\n*** stlink_core_id ***\n");
287     sl->backend->core_id(sl);
288     if (sl->verbose > 2)
289         stlink_print_data(sl);
290     DD(sl, "core_id = 0x%08x\n", sl->core_id);
291     return sl->core_id;
292 }
293
294 uint16_t stlink_chip_id(stlink_t *sl) {
295     stlink_read_mem32(sl, 0xE0042000, 4);
296     uint32_t chip_id = sl->q_buf[0] | (sl->q_buf[1] << 8) | (sl->q_buf[2] << 16) |
297             (sl->q_buf[3] << 24);
298     return chip_id;
299 }
300
301 /**
302  * Cortex m3 tech ref manual, CPUID register description
303  * @param sl stlink context
304  * @param cpuid pointer to the result object
305  */
306 void stlink_cpu_id(stlink_t *sl, cortex_m3_cpuid_t *cpuid) {
307     stlink_read_mem32(sl, CM3_REG_CPUID, 4);
308     uint32_t raw = read_uint32(sl->q_buf, 0);
309     cpuid->implementer_id = (raw >> 24) & 0x7f;
310     cpuid->variant = (raw >> 20) & 0xf;
311     cpuid->part = (raw >> 4) & 0xfff;
312     cpuid->revision = raw & 0xf;
313     return;
314 }
315
316 void stlink_reset(stlink_t *sl) {
317     D(sl, "\n*** stlink_reset ***\n");
318     sl->backend->reset(sl);
319 }
320
321 void stlink_run(stlink_t *sl) {
322     D(sl, "\n*** stlink_run ***\n");
323     sl->backend->run(sl);
324 }
325
326 void stlink_status(stlink_t *sl) {
327     D(sl, "\n*** stlink_status ***\n");
328     sl->backend->status(sl);
329     stlink_core_stat(sl);
330 }
331
332 /**
333  * Decode the version bits, originally from -sg, verified with usb
334  * @param sl stlink context, assumed to contain valid data in the buffer
335  * @param slv output parsed version object
336  */
337 void _parse_version(stlink_t *sl, stlink_version_t *slv) {
338     uint32_t b0 = sl->q_buf[0]; //lsb
339     uint32_t b1 = sl->q_buf[1];
340     uint32_t b2 = sl->q_buf[2];
341     uint32_t b3 = sl->q_buf[3];
342     uint32_t b4 = sl->q_buf[4];
343     uint32_t b5 = sl->q_buf[5]; //msb
344
345     // b0 b1                       || b2 b3  | b4 b5
346     // 4b        | 6b     | 6b     || 2B     | 2B
347     // stlink_v  | jtag_v | swim_v || st_vid | stlink_pid
348
349     slv->stlink_v = (b0 & 0xf0) >> 4;
350     slv->jtag_v = ((b0 & 0x0f) << 2) | ((b1 & 0xc0) >> 6);
351     slv->swim_v = b1 & 0x3f;
352     slv->st_vid = (b3 << 8) | b2;
353     slv->stlink_pid = (b5 << 8) | b4;
354     return;
355 }
356
357 void stlink_version(stlink_t *sl) {
358     D(sl, "*** looking up stlink version\n");
359     stlink_version_t slv;
360     sl->backend->version(sl);
361     _parse_version(sl, &slv);
362     
363     DD(sl, "st vid         = 0x%04x (expect 0x%04x)\n", slv.st_vid, USB_ST_VID);
364     DD(sl, "stlink pid     = 0x%04x\n", slv.stlink_pid);
365     DD(sl, "stlink version = 0x%x\n", slv.stlink_v);
366     DD(sl, "jtag version   = 0x%x\n", slv.jtag_v);
367     DD(sl, "swim version   = 0x%x\n", slv.swim_v);
368     if (slv.jtag_v == 0) {
369         DD(sl, "    notice: the firmware doesn't support a jtag/swd interface\n");
370     }
371     if (slv.swim_v == 0) {
372         DD(sl, "    notice: the firmware doesn't support a swim interface\n");
373     }
374 }
375
376 void stlink_write_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
377     D(sl, "\n*** stlink_write_mem32 ***\n");
378     if (len % 4 != 0) {
379         fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
380         return;
381     }
382     sl->backend->write_mem32(sl, addr, len);
383 }
384
385 void stlink_read_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
386     D(sl, "\n*** stlink_read_mem32 ***\n");
387     if (len % 4 != 0) { // !!! never ever: fw gives just wrong values
388         fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n",
389                 len % 4);
390         return;
391     }
392     sl->backend->read_mem32(sl, addr, len);
393 }
394
395 void stlink_write_mem8(stlink_t *sl, uint32_t addr, uint16_t len) {
396     D(sl, "\n*** stlink_write_mem8 ***\n");
397     sl->backend->write_mem8(sl, addr, len);
398 }
399
400 void stlink_read_all_regs(stlink_t *sl, reg *regp) {
401     D(sl, "\n*** stlink_read_all_regs ***\n");
402     sl->backend->read_all_regs(sl, regp);
403 }
404
405 void stlink_write_reg(stlink_t *sl, uint32_t reg, int idx) {
406     D(sl, "\n*** stlink_write_reg\n");
407     sl->backend->write_reg(sl, reg, idx);
408 }
409
410 void stlink_read_reg(stlink_t *sl, int r_idx, reg *regp) {
411     D(sl, "\n*** stlink_read_reg\n");
412     DD(sl, " (%d) ***\n", r_idx);
413
414     if (r_idx > 20 || r_idx < 0) {
415         fprintf(stderr, "Error: register index must be in [0..20]\n");
416         return;
417     }
418
419     sl->backend->read_reg(sl, r_idx, regp);
420 }
421
422 unsigned int is_core_halted(stlink_t *sl) {
423     /* return non zero if core is halted */
424     stlink_status(sl);
425     return sl->q_buf[0] == STLINK_CORE_HALTED;
426 }
427
428 void stlink_step(stlink_t *sl) {
429     D(sl, "\n*** stlink_step ***\n");
430     sl->backend->step(sl);
431 }
432
433 int stlink_current_mode(stlink_t *sl) {
434     int mode = sl->backend->current_mode(sl);
435     switch (mode) {
436         case STLINK_DEV_DFU_MODE:
437             DD(sl, "stlink current mode: dfu\n");
438             return mode;
439         case STLINK_DEV_DEBUG_MODE:
440             DD(sl, "stlink current mode: debug (jtag or swd)\n");
441             return mode;
442         case STLINK_DEV_MASS_MODE:
443             DD(sl, "stlink current mode: mass\n");
444             return mode;
445     }
446     DD(sl, "stlink mode: unknown!\n");
447     return STLINK_DEV_UNKNOWN_MODE;
448 }
449
450
451
452
453 // End of delegates....  Common code below here...
454
455 // Endianness
456 // http://www.ibm.com/developerworks/aix/library/au-endianc/index.html
457 // const int i = 1;
458 // #define is_bigendian() ( (*(char*)&i) == 0 )
459
460 inline unsigned int is_bigendian(void) {
461     static volatile const unsigned int i = 1;
462     return *(volatile const char*) &i == 0;
463 }
464
465 uint16_t read_uint16(const unsigned char *c, const int pt) {
466     uint32_t ui;
467     char *p = (char *) &ui;
468
469     if (!is_bigendian()) { // le -> le (don't swap)
470         p[0] = c[pt];
471         p[1] = c[pt + 1];
472     } else {
473         p[0] = c[pt + 1];
474         p[1] = c[pt];
475     }
476     return ui;
477 }
478
479 // same as above with entrypoint.
480
481 void stlink_run_at(stlink_t *sl, stm32_addr_t addr) {
482     stlink_write_reg(sl, addr, 15); /* pc register */
483
484     stlink_run(sl);
485
486     while (is_core_halted(sl) == 0)
487         usleep(3000000);
488 }
489
490 void stlink_core_stat(stlink_t *sl) {
491     if (sl->q_len <= 0)
492         return;
493
494     stlink_print_data(sl);
495
496     switch (sl->q_buf[0]) {
497         case STLINK_CORE_RUNNING:
498             sl->core_stat = STLINK_CORE_RUNNING;
499             DD(sl, "  core status: running\n");
500             return;
501         case STLINK_CORE_HALTED:
502             sl->core_stat = STLINK_CORE_HALTED;
503             DD(sl, "  core status: halted\n");
504             return;
505         default:
506             sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
507             fprintf(stderr, "  core status: unknown\n");
508     }
509 }
510
511 void stlink_print_data(stlink_t * sl) {
512     if (sl->q_len <= 0 || sl->verbose < 2)
513         return;
514     if (sl->verbose > 2)
515         fprintf(stdout, "data_len = %d 0x%x\n", sl->q_len, sl->q_len);
516
517     for (int i = 0; i < sl->q_len; i++) {
518         if (i % 16 == 0) {
519             /*
520                                     if (sl->q_data_dir == Q_DATA_OUT)
521                                             fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
522                                     else
523                                             fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
524              */
525         }
526         fprintf(stdout, " %02x", (unsigned int) sl->q_buf[i]);
527     }
528     fputs("\n\n", stdout);
529 }
530
531 /* memory mapped file */
532
533 typedef struct mapped_file {
534     uint8_t* base;
535     size_t len;
536 } mapped_file_t;
537
538 #define MAPPED_FILE_INITIALIZER { NULL, 0 }
539
540 static int map_file(mapped_file_t* mf, const char* path) {
541     int error = -1;
542     struct stat st;
543
544     const int fd = open(path, O_RDONLY);
545     if (fd == -1) {
546         fprintf(stderr, "open(%s) == -1\n", path);
547         return -1;
548     }
549
550     if (fstat(fd, &st) == -1) {
551         fprintf(stderr, "fstat() == -1\n");
552         goto on_error;
553     }
554
555     mf->base = (uint8_t*) mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
556     if (mf->base == MAP_FAILED) {
557         fprintf(stderr, "mmap() == MAP_FAILED\n");
558         goto on_error;
559     }
560
561     mf->len = st.st_size;
562
563     /* success */
564     error = 0;
565
566 on_error:
567     close(fd);
568
569     return error;
570 }
571
572 static void unmap_file(mapped_file_t * mf) {
573     munmap((void*) mf->base, mf->len);
574     mf->base = (unsigned char*) MAP_FAILED;
575     mf->len = 0;
576 }
577
578 static int check_file(stlink_t* sl, mapped_file_t* mf, stm32_addr_t addr) {
579     size_t off;
580
581     for (off = 0; off < mf->len; off += sl->flash_pgsz) {
582         size_t aligned_size;
583
584         /* adjust last page size */
585         size_t cmp_size = sl->flash_pgsz;
586         if ((off + sl->flash_pgsz) > mf->len)
587             cmp_size = mf->len - off;
588
589         aligned_size = cmp_size;
590         if (aligned_size & (4 - 1))
591             aligned_size = (cmp_size + 4) & ~(4 - 1);
592
593         stlink_read_mem32(sl, addr + off, aligned_size);
594
595         if (memcmp(sl->q_buf, mf->base + off, cmp_size))
596             return -1;
597     }
598
599     return 0;
600 }
601
602 int stlink_fwrite_sram
603 (stlink_t * sl, const char* path, stm32_addr_t addr) {
604     /* write the file in sram at addr */
605
606     int error = -1;
607     size_t off;
608     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
609
610     if (map_file(&mf, path) == -1) {
611         fprintf(stderr, "map_file() == -1\n");
612         return -1;
613     }
614
615     /* check addr range is inside the sram */
616     if (addr < sl->sram_base) {
617         fprintf(stderr, "addr too low\n");
618         goto on_error;
619     } else if ((addr + mf.len) < addr) {
620         fprintf(stderr, "addr overruns\n");
621         goto on_error;
622     } else if ((addr + mf.len) > (sl->sram_base + sl->sram_size)) {
623         fprintf(stderr, "addr too high\n");
624         goto on_error;
625     } else if ((addr & 3) || (mf.len & 3)) {
626         /* todo */
627         fprintf(stderr, "unaligned addr or size\n");
628         goto on_error;
629     }
630
631     /* do the copy by 1k blocks */
632     for (off = 0; off < mf.len; off += 1024) {
633         size_t size = 1024;
634         if ((off + size) > mf.len)
635             size = mf.len - off;
636
637         memcpy(sl->q_buf, mf.base + off, size);
638
639         /* round size if needed */
640         if (size & 3)
641             size += 2;
642
643         stlink_write_mem32(sl, addr + off, size);
644     }
645
646     /* check the file ha been written */
647     if (check_file(sl, &mf, addr) == -1) {
648         fprintf(stderr, "check_file() == -1\n");
649         goto on_error;
650     }
651
652     /* success */
653     error = 0;
654
655 on_error:
656     unmap_file(&mf);
657     return error;
658 }
659
660 int stlink_fread(stlink_t* sl, const char* path, stm32_addr_t addr, size_t size) {
661     /* read size bytes from addr to file */
662
663     int error = -1;
664     size_t off;
665
666     const int fd = open(path, O_RDWR | O_TRUNC | O_CREAT, 00700);
667     if (fd == -1) {
668         fprintf(stderr, "open(%s) == -1\n", path);
669         return -1;
670     }
671
672     /* do the copy by 1k blocks */
673     for (off = 0; off < size; off += 1024) {
674         size_t read_size = 1024;
675         if ((off + read_size) > size)
676             read_size = off + read_size;
677
678         /* round size if needed */
679         if (read_size & 3)
680             read_size = (read_size + 4) & ~(3);
681
682         stlink_read_mem32(sl, addr + off, read_size);
683
684         if (write(fd, sl->q_buf, read_size) != (ssize_t) read_size) {
685             fprintf(stderr, "write() != read_size\n");
686             goto on_error;
687         }
688     }
689
690     /* success */
691     error = 0;
692
693 on_error:
694     close(fd);
695
696     return error;
697 }
698
699 int write_buffer_to_sram(stlink_t *sl, flash_loader_t* fl, const uint8_t* buf, size_t size) {
700     /* write the buffer right after the loader */
701     memcpy(sl->q_buf, buf, size);
702     stlink_write_mem8(sl, fl->buf_addr, size);
703     return 0;
704 }
705
706 int stlink_erase_flash_page(stlink_t *sl, stm32_addr_t page) {
707     /* page an addr in the page to erase */
708
709     /* wait for ongoing op to finish */
710     wait_flash_busy(sl);
711
712     /* unlock if locked */
713     unlock_flash_if(sl);
714
715     /* set the page erase bit */
716     set_flash_cr_per(sl);
717
718     /* select the page to erase */
719     write_flash_ar(sl, page);
720
721     /* start erase operation, reset by hw with bsy bit */
722     set_flash_cr_strt(sl);
723
724     /* wait for completion */
725     wait_flash_busy(sl);
726
727     /* relock the flash */
728     lock_flash(sl);
729
730     /* todo: verify the erased page */
731
732     return 0;
733 }
734
735 int stlink_erase_flash_mass(stlink_t *sl) {
736     /* wait for ongoing op to finish */
737     wait_flash_busy(sl);
738
739     /* unlock if locked */
740     unlock_flash_if(sl);
741
742     /* set the mass erase bit */
743     set_flash_cr_mer(sl);
744
745     /* start erase operation, reset by hw with bsy bit */
746     set_flash_cr_strt(sl);
747
748     /* wait for completion */
749     wait_flash_busy(sl);
750
751     /* relock the flash */
752     lock_flash(sl);
753
754     /* todo: verify the erased memory */
755
756     return 0;
757 }
758
759 int init_flash_loader(stlink_t *sl, flash_loader_t* fl) {
760     size_t size;
761
762     /* allocate the loader in sram */
763     if (write_loader_to_sram(sl, &fl->loader_addr, &size) == -1) {
764         fprintf(stderr, "write_loader_to_sram() == -1\n");
765         return -1;
766     }
767
768     /* allocate a one page buffer in sram right after loader */
769     fl->buf_addr = fl->loader_addr + size;
770
771     return 0;
772 }
773
774 int write_loader_to_sram(stlink_t *sl, stm32_addr_t* addr, size_t* size) {
775     /* from openocd, contrib/loaders/flash/stm32.s */
776     static const uint8_t loader_code[] = {
777         0x08, 0x4c, /* ldr      r4, STM32_FLASH_BASE */
778         0x1c, 0x44, /* add      r4, r3 */
779         /* write_half_word: */
780         0x01, 0x23, /* movs     r3, #0x01 */
781         0x23, 0x61, /* str      r3, [r4, #STM32_FLASH_CR_OFFSET] */
782         0x30, 0xf8, 0x02, 0x3b, /* ldrh r3, [r0], #0x02 */
783         0x21, 0xf8, 0x02, 0x3b, /* strh r3, [r1], #0x02 */
784         /* busy: */
785         0xe3, 0x68, /* ldr      r3, [r4, #STM32_FLASH_SR_OFFSET] */
786         0x13, 0xf0, 0x01, 0x0f, /* tst  r3, #0x01 */
787         0xfb, 0xd0, /* beq      busy */
788         0x13, 0xf0, 0x14, 0x0f, /* tst  r3, #0x14 */
789         0x01, 0xd1, /* bne      exit */
790         0x01, 0x3a, /* subs     r2, r2, #0x01 */
791         0xf0, 0xd1, /* bne      write_half_word */
792         /* exit: */
793         0x00, 0xbe, /* bkpt     #0x00 */
794         0x00, 0x20, 0x02, 0x40, /* STM32_FLASH_BASE: .word 0x40022000 */
795     };
796
797     memcpy(sl->q_buf, loader_code, sizeof (loader_code));
798     stlink_write_mem32(sl, sl->sram_base, sizeof (loader_code));
799
800     *addr = sl->sram_base;
801     *size = sizeof (loader_code);
802
803     /* success */
804     return 0;
805 }
806
807 int stlink_fcheck_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
808     /* check the contents of path are at addr */
809
810     int res;
811     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
812
813     if (map_file(&mf, path) == -1)
814         return -1;
815
816     res = check_file(sl, &mf, addr);
817
818     unmap_file(&mf);
819
820     return res;
821 }
822
823 // The stlink_fwrite_flash should not muck with mmapped files inside itself,
824 // and should use this function instead. (Hell, what's the reason behind mmap
825 // there?!) But, as it is not actually used anywhere, nobody cares.
826
827 #define WRITE_BLOCK_SIZE 0x40
828
829 int stlink_write_flash(stlink_t *sl, stm32_addr_t addr, uint8_t* base, unsigned len) {
830     size_t off;
831     flash_loader_t fl;
832
833     /* check addr range is inside the flash */
834     if (addr < sl->flash_base) {
835         fprintf(stderr, "addr too low\n");
836         return -1;
837     } else if ((addr + len) < addr) {
838         fprintf(stderr, "addr overruns\n");
839         return -1;
840     } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
841         fprintf(stderr, "addr too high\n");
842         return -1;
843     } else if ((addr & 1) || (len & 1)) {
844         fprintf(stderr, "unaligned addr or size\n");
845         return -1;
846     }
847
848     /* flash loader initialization */
849     if (init_flash_loader(sl, &fl) == -1) {
850         fprintf(stderr, "init_flash_loader() == -1\n");
851         return -1;
852     }
853
854     /* write each page. above WRITE_BLOCK_SIZE fails? */
855     for (off = 0; off < len; off += WRITE_BLOCK_SIZE) {
856         /* adjust last write size */
857         size_t size = WRITE_BLOCK_SIZE;
858         if ((off + WRITE_BLOCK_SIZE) > len)
859             size = len - off;
860
861         if (run_flash_loader(sl, &fl, addr + off, base + off, size) == -1) {
862             fprintf(stderr, "run_flash_loader(0x%zx) == -1\n", addr + off);
863             return -1;
864         }
865     }
866
867     for (off = 0; off < len; off += sl->flash_pgsz) {
868         size_t aligned_size;
869
870         /* adjust last page size */
871         size_t cmp_size = sl->flash_pgsz;
872         if ((off + sl->flash_pgsz) > len)
873             cmp_size = len - off;
874
875         aligned_size = cmp_size;
876         if (aligned_size & (4 - 1))
877             aligned_size = (cmp_size + 4) & ~(4 - 1);
878
879         stlink_read_mem32(sl, addr + off, aligned_size);
880
881         if (memcmp(sl->q_buf, base + off, cmp_size))
882             return -1;
883     }
884
885     return 0;
886 }
887
888 int stlink_fwrite_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
889     /* write the file in flash at addr */
890
891     int error = -1;
892     size_t off;
893     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
894     flash_loader_t fl;
895
896     if (map_file(&mf, path) == -1) {
897         fprintf(stderr, "map_file() == -1\n");
898         return -1;
899     }
900
901     /* check addr range is inside the flash */
902     if (addr < sl->flash_base) {
903         fprintf(stderr, "addr too low\n");
904         goto on_error;
905     } else if ((addr + mf.len) < addr) {
906         fprintf(stderr, "addr overruns\n");
907         goto on_error;
908     } else if ((addr + mf.len) > (sl->flash_base + sl->flash_size)) {
909         fprintf(stderr, "addr too high\n");
910         goto on_error;
911     } else if ((addr & 1) || (mf.len & 1)) {
912         /* todo */
913         fprintf(stderr, "unaligned addr or size\n");
914         goto on_error;
915     }
916
917     /* erase each page. todo: mass erase faster? */
918     for (off = 0; off < mf.len; off += sl->flash_pgsz) {
919         /* addr must be an addr inside the page */
920         if (stlink_erase_flash_page(sl, addr + off) == -1) {
921             fprintf(stderr, "erase_flash_page(0x%zx) == -1\n", addr + off);
922             goto on_error;
923         }
924     }
925
926     /* flash loader initialization */
927     if (init_flash_loader(sl, &fl) == -1) {
928         fprintf(stderr, "init_flash_loader() == -1\n");
929         goto on_error;
930     }
931
932     /* write each page. above WRITE_BLOCK_SIZE fails? */
933 #define WRITE_BLOCK_SIZE 0x40
934     for (off = 0; off < mf.len; off += WRITE_BLOCK_SIZE) {
935         /* adjust last write size */
936         size_t size = WRITE_BLOCK_SIZE;
937         if ((off + WRITE_BLOCK_SIZE) > mf.len)
938             size = mf.len - off;
939
940         if (run_flash_loader(sl, &fl, addr + off, mf.base + off, size) == -1) {
941             fprintf(stderr, "run_flash_loader(0x%zx) == -1\n", addr + off);
942             goto on_error;
943         }
944     }
945
946     /* check the file ha been written */
947     if (check_file(sl, &mf, addr) == -1) {
948         fprintf(stderr, "check_file() == -1\n");
949         goto on_error;
950     }
951
952     /* success */
953     error = 0;
954
955 on_error:
956     unmap_file(&mf);
957     return error;
958 }
959
960 int run_flash_loader(stlink_t *sl, flash_loader_t* fl, stm32_addr_t target, const uint8_t* buf, size_t size) {
961     const size_t count = size / sizeof (uint16_t);
962
963     if (write_buffer_to_sram(sl, fl, buf, size) == -1) {
964         fprintf(stderr, "write_buffer_to_sram() == -1\n");
965         return -1;
966     }
967
968     /* setup core */
969     stlink_write_reg(sl, fl->buf_addr, 0); /* source */
970     stlink_write_reg(sl, target, 1); /* target */
971     stlink_write_reg(sl, count, 2); /* count (16 bits half words) */
972     stlink_write_reg(sl, 0, 3); /* flash bank 0 (input) */
973     stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
974
975     /* unlock and set programming mode */
976     unlock_flash_if(sl);
977     set_flash_cr_pg(sl);
978
979     /* run loader */
980     stlink_run(sl);
981
982     while (is_core_halted(sl) == 0)
983         ;
984
985     lock_flash(sl);
986
987     /* not all bytes have been written */
988     reg rr;
989     stlink_read_reg(sl, 2, &rr);
990     if (rr.r[2] != 0) {
991         fprintf(stderr, "write error, count == %u\n", rr.r[2]);
992         return -1;
993     }
994
995     return 0;
996 }