move debugging output to common code
[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
262     free(sl);
263 }
264
265 void stlink_exit_debug_mode(stlink_t *sl) {
266     D(sl, "\n*** stlink_exit_debug_mode ***\n");
267     sl->backend->exit_debug_mode(sl);
268 }
269
270 void stlink_enter_swd_mode(stlink_t *sl) {
271     D(sl, "\n*** stlink_enter_swd_mode ***\n");
272     sl->backend->enter_swd_mode(sl);
273 }
274
275 void stlink_exit_dfu_mode(stlink_t *sl) {
276     D(sl, "\n*** stlink_exit_dfu_mode ***\n");
277     sl->backend->exit_dfu_mode(sl);
278 }
279
280 void stlink_core_id(stlink_t *sl) {
281     D(sl, "\n*** stlink_core_id ***\n");
282     sl->backend->core_id(sl);
283     if (sl->verbose > 2)
284         stlink_print_data(sl);
285     DD(sl, "core_id = 0x%08x\n", sl->core_id);
286 }
287
288 void stlink_reset(stlink_t *sl) {
289     D(sl, "\n*** stlink_reset ***\n");
290     sl->backend->reset(sl);
291
292 }
293
294 void stlink_run(stlink_t *sl) {
295     D(sl, "\n*** stlink_run ***\n");
296     sl->backend->run(sl);
297 }
298
299 void stlink_status(stlink_t *sl) {
300     D(sl, "\n*** stlink_status ***\n");
301     sl->backend->status(sl);
302     stlink_core_stat(sl);
303 }
304
305 void stlink_version(stlink_t *sl) {
306     D(sl, "*** looking up stlink version\n");
307     sl->backend->version(sl);
308 }
309
310 void stlink_write_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
311     D(sl, "\n*** stlink_write_mem32 ***\n");
312     if (len % 4 != 0) {
313         fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
314         return;
315     }
316     sl->backend->write_mem32(sl, addr, len);
317 }
318
319 void stlink_read_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
320     D(sl, "\n*** stlink_read_mem32 ***\n");
321     if (len % 4 != 0) { // !!! never ever: fw gives just wrong values
322         fprintf(stderr, "Error: Data length doesn't have a 32 bit alignment: +%d byte.\n",
323                 len % 4);
324         return;
325     }
326     sl->backend->read_mem32(sl, addr, len);
327 }
328
329 void stlink_write_mem8(stlink_t *sl, uint32_t addr, uint16_t len) {
330     D(sl, "\n*** stlink_write_mem8 ***\n");
331     sl->backend->write_mem8(sl, addr, len);
332 }
333
334 void stlink_read_all_regs(stlink_t *sl, reg *regp) {
335     D(sl, "\n*** stlink_read_all_regs ***\n");
336     sl->backend->read_all_regs(sl, regp);
337 }
338
339 void stlink_write_reg(stlink_t *sl, uint32_t reg, int idx) {
340     D(sl, "\n*** stlink_write_reg\n");
341     sl->backend->write_reg(sl, reg, idx);
342 }
343
344 void stlink_read_reg(stlink_t *sl, int r_idx, reg *regp) {
345     D(sl, "\n*** stlink_read_reg\n");
346     DD(sl, " (%d) ***\n", r_idx);
347
348     if (r_idx > 20 || r_idx < 0) {
349         fprintf(stderr, "Error: register index must be in [0..20]\n");
350         return;
351     }
352
353     sl->backend->read_reg(sl, r_idx, regp);
354 }
355
356 unsigned int is_core_halted(stlink_t *sl) {
357     /* return non zero if core is halted */
358     stlink_status(sl);
359     return sl->q_buf[0] == STLINK_CORE_HALTED;
360 }
361
362 void stlink_step(stlink_t *sl) {
363     D(sl, "\n*** stlink_step ***\n");
364     sl->backend->step(sl);
365 }
366
367 int stlink_current_mode(stlink_t *sl) {
368     D(sl, "\n*** stlink_current_mode ***\n");
369     int mode = sl->backend->current_mode(sl);
370     stlink_print_data(sl);
371     switch (mode) {
372         case STLINK_DEV_DFU_MODE:
373             DD(sl, "stlink mode: dfu\n");
374             return mode;
375         case STLINK_DEV_DEBUG_MODE:
376             DD(sl, "stlink mode: debug (jtag or swd)\n");
377             return mode;
378         case STLINK_DEV_MASS_MODE:
379             DD(sl, "stlink mode: mass\n");
380             return mode;
381     }
382     DD(sl, "stlink mode: unknown!\n");
383     return STLINK_DEV_UNKNOWN_MODE;
384 }
385
386
387
388
389 // End of delegates....  Common code below here...
390
391 // Endianness
392 // http://www.ibm.com/developerworks/aix/library/au-endianc/index.html
393 // const int i = 1;
394 // #define is_bigendian() ( (*(char*)&i) == 0 )
395
396 inline unsigned int is_bigendian(void) {
397     static volatile const unsigned int i = 1;
398     return *(volatile const char*) &i == 0;
399 }
400
401 uint16_t read_uint16(const unsigned char *c, const int pt) {
402     uint32_t ui;
403     char *p = (char *) &ui;
404
405     if (!is_bigendian()) { // le -> le (don't swap)
406         p[0] = c[pt];
407         p[1] = c[pt + 1];
408     } else {
409         p[0] = c[pt + 1];
410         p[1] = c[pt];
411     }
412     return ui;
413 }
414
415 // same as above with entrypoint.
416
417 void stlink_run_at(stlink_t *sl, stm32_addr_t addr) {
418     stlink_write_reg(sl, addr, 15); /* pc register */
419
420     stlink_run(sl);
421
422     while (is_core_halted(sl) == 0)
423         usleep(3000000);
424 }
425
426 void stlink_core_stat(stlink_t *sl) {
427     if (sl->q_len <= 0)
428         return;
429
430     stlink_print_data(sl);
431
432     switch (sl->q_buf[0]) {
433         case STLINK_CORE_RUNNING:
434             sl->core_stat = STLINK_CORE_RUNNING;
435             DD(sl, "  core status: running\n");
436             return;
437         case STLINK_CORE_HALTED:
438             sl->core_stat = STLINK_CORE_HALTED;
439             DD(sl, "  core status: halted\n");
440             return;
441         default:
442             sl->core_stat = STLINK_CORE_STAT_UNKNOWN;
443             fprintf(stderr, "  core status: unknown\n");
444     }
445 }
446
447 void stlink_print_data(stlink_t * sl) {
448     if (sl->q_len <= 0 || sl->verbose < 2)
449         return;
450     if (sl->verbose > 2)
451         fprintf(stdout, "data_len = %d 0x%x\n", sl->q_len, sl->q_len);
452
453     for (int i = 0; i < sl->q_len; i++) {
454         if (i % 16 == 0) {
455             /*
456                                     if (sl->q_data_dir == Q_DATA_OUT)
457                                             fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
458                                     else
459                                             fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
460              */
461         }
462         fprintf(stdout, " %02x", (unsigned int) sl->q_buf[i]);
463     }
464     fputs("\n\n", stdout);
465 }
466
467 /* memory mapped file */
468
469 typedef struct mapped_file {
470     uint8_t* base;
471     size_t len;
472 } mapped_file_t;
473
474 #define MAPPED_FILE_INITIALIZER { NULL, 0 }
475
476 static int map_file(mapped_file_t* mf, const char* path) {
477     int error = -1;
478     struct stat st;
479
480     const int fd = open(path, O_RDONLY);
481     if (fd == -1) {
482         fprintf(stderr, "open(%s) == -1\n", path);
483         return -1;
484     }
485
486     if (fstat(fd, &st) == -1) {
487         fprintf(stderr, "fstat() == -1\n");
488         goto on_error;
489     }
490
491     mf->base = (uint8_t*) mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
492     if (mf->base == MAP_FAILED) {
493         fprintf(stderr, "mmap() == MAP_FAILED\n");
494         goto on_error;
495     }
496
497     mf->len = st.st_size;
498
499     /* success */
500     error = 0;
501
502 on_error:
503     close(fd);
504
505     return error;
506 }
507
508 static void unmap_file(mapped_file_t * mf) {
509     munmap((void*) mf->base, mf->len);
510     mf->base = (unsigned char*) MAP_FAILED;
511     mf->len = 0;
512 }
513
514 static int check_file(stlink_t* sl, mapped_file_t* mf, stm32_addr_t addr) {
515     size_t off;
516
517     for (off = 0; off < mf->len; off += sl->flash_pgsz) {
518         size_t aligned_size;
519
520         /* adjust last page size */
521         size_t cmp_size = sl->flash_pgsz;
522         if ((off + sl->flash_pgsz) > mf->len)
523             cmp_size = mf->len - off;
524
525         aligned_size = cmp_size;
526         if (aligned_size & (4 - 1))
527             aligned_size = (cmp_size + 4) & ~(4 - 1);
528
529         stlink_read_mem32(sl, addr + off, aligned_size);
530
531         if (memcmp(sl->q_buf, mf->base + off, cmp_size))
532             return -1;
533     }
534
535     return 0;
536 }
537
538 int stlink_fwrite_sram
539 (stlink_t * sl, const char* path, stm32_addr_t addr) {
540     /* write the file in sram at addr */
541
542     int error = -1;
543     size_t off;
544     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
545
546     if (map_file(&mf, path) == -1) {
547         fprintf(stderr, "map_file() == -1\n");
548         return -1;
549     }
550
551     /* check addr range is inside the sram */
552     if (addr < sl->sram_base) {
553         fprintf(stderr, "addr too low\n");
554         goto on_error;
555     } else if ((addr + mf.len) < addr) {
556         fprintf(stderr, "addr overruns\n");
557         goto on_error;
558     } else if ((addr + mf.len) > (sl->sram_base + sl->sram_size)) {
559         fprintf(stderr, "addr too high\n");
560         goto on_error;
561     } else if ((addr & 3) || (mf.len & 3)) {
562         /* todo */
563         fprintf(stderr, "unaligned addr or size\n");
564         goto on_error;
565     }
566
567     /* do the copy by 1k blocks */
568     for (off = 0; off < mf.len; off += 1024) {
569         size_t size = 1024;
570         if ((off + size) > mf.len)
571             size = mf.len - off;
572
573         memcpy(sl->q_buf, mf.base + off, size);
574
575         /* round size if needed */
576         if (size & 3)
577             size += 2;
578
579         stlink_write_mem32(sl, addr + off, size);
580     }
581
582     /* check the file ha been written */
583     if (check_file(sl, &mf, addr) == -1) {
584         fprintf(stderr, "check_file() == -1\n");
585         goto on_error;
586     }
587
588     /* success */
589     error = 0;
590
591 on_error:
592     unmap_file(&mf);
593     return error;
594 }
595
596 int stlink_fread(stlink_t* sl, const char* path, stm32_addr_t addr, size_t size) {
597     /* read size bytes from addr to file */
598
599     int error = -1;
600     size_t off;
601
602     const int fd = open(path, O_RDWR | O_TRUNC | O_CREAT, 00700);
603     if (fd == -1) {
604         fprintf(stderr, "open(%s) == -1\n", path);
605         return -1;
606     }
607
608     /* do the copy by 1k blocks */
609     for (off = 0; off < size; off += 1024) {
610         size_t read_size = 1024;
611         if ((off + read_size) > size)
612             read_size = off + read_size;
613
614         /* round size if needed */
615         if (read_size & 3)
616             read_size = (read_size + 4) & ~(3);
617
618         stlink_read_mem32(sl, addr + off, read_size);
619
620         if (write(fd, sl->q_buf, read_size) != (ssize_t) read_size) {
621             fprintf(stderr, "write() != read_size\n");
622             goto on_error;
623         }
624     }
625
626     /* success */
627     error = 0;
628
629 on_error:
630     close(fd);
631
632     return error;
633 }
634
635 int write_buffer_to_sram(stlink_t *sl, flash_loader_t* fl, const uint8_t* buf, size_t size) {
636     /* write the buffer right after the loader */
637     memcpy(sl->q_buf, buf, size);
638     stlink_write_mem8(sl, fl->buf_addr, size);
639     return 0;
640 }
641
642 int stlink_erase_flash_page(stlink_t *sl, stm32_addr_t page) {
643     /* page an addr in the page to erase */
644
645     /* wait for ongoing op to finish */
646     wait_flash_busy(sl);
647
648     /* unlock if locked */
649     unlock_flash_if(sl);
650
651     /* set the page erase bit */
652     set_flash_cr_per(sl);
653
654     /* select the page to erase */
655     write_flash_ar(sl, page);
656
657     /* start erase operation, reset by hw with bsy bit */
658     set_flash_cr_strt(sl);
659
660     /* wait for completion */
661     wait_flash_busy(sl);
662
663     /* relock the flash */
664     lock_flash(sl);
665
666     /* todo: verify the erased page */
667
668     return 0;
669 }
670
671 int stlink_erase_flash_mass(stlink_t *sl) {
672     /* wait for ongoing op to finish */
673     wait_flash_busy(sl);
674
675     /* unlock if locked */
676     unlock_flash_if(sl);
677
678     /* set the mass erase bit */
679     set_flash_cr_mer(sl);
680
681     /* start erase operation, reset by hw with bsy bit */
682     set_flash_cr_strt(sl);
683
684     /* wait for completion */
685     wait_flash_busy(sl);
686
687     /* relock the flash */
688     lock_flash(sl);
689
690     /* todo: verify the erased memory */
691
692     return 0;
693 }
694
695 int init_flash_loader(stlink_t *sl, flash_loader_t* fl) {
696     size_t size;
697
698     /* allocate the loader in sram */
699     if (write_loader_to_sram(sl, &fl->loader_addr, &size) == -1) {
700         fprintf(stderr, "write_loader_to_sram() == -1\n");
701         return -1;
702     }
703
704     /* allocate a one page buffer in sram right after loader */
705     fl->buf_addr = fl->loader_addr + size;
706
707     return 0;
708 }
709
710 int write_loader_to_sram(stlink_t *sl, stm32_addr_t* addr, size_t* size) {
711     /* from openocd, contrib/loaders/flash/stm32.s */
712     static const uint8_t loader_code[] = {
713         0x08, 0x4c, /* ldr      r4, STM32_FLASH_BASE */
714         0x1c, 0x44, /* add      r4, r3 */
715         /* write_half_word: */
716         0x01, 0x23, /* movs     r3, #0x01 */
717         0x23, 0x61, /* str      r3, [r4, #STM32_FLASH_CR_OFFSET] */
718         0x30, 0xf8, 0x02, 0x3b, /* ldrh r3, [r0], #0x02 */
719         0x21, 0xf8, 0x02, 0x3b, /* strh r3, [r1], #0x02 */
720         /* busy: */
721         0xe3, 0x68, /* ldr      r3, [r4, #STM32_FLASH_SR_OFFSET] */
722         0x13, 0xf0, 0x01, 0x0f, /* tst  r3, #0x01 */
723         0xfb, 0xd0, /* beq      busy */
724         0x13, 0xf0, 0x14, 0x0f, /* tst  r3, #0x14 */
725         0x01, 0xd1, /* bne      exit */
726         0x01, 0x3a, /* subs     r2, r2, #0x01 */
727         0xf0, 0xd1, /* bne      write_half_word */
728         /* exit: */
729         0x00, 0xbe, /* bkpt     #0x00 */
730         0x00, 0x20, 0x02, 0x40, /* STM32_FLASH_BASE: .word 0x40022000 */
731     };
732
733     memcpy(sl->q_buf, loader_code, sizeof (loader_code));
734     stlink_write_mem32(sl, sl->sram_base, sizeof (loader_code));
735
736     *addr = sl->sram_base;
737     *size = sizeof (loader_code);
738
739     /* success */
740     return 0;
741 }
742
743 int stlink_fcheck_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
744     /* check the contents of path are at addr */
745
746     int res;
747     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
748
749     if (map_file(&mf, path) == -1)
750         return -1;
751
752     res = check_file(sl, &mf, addr);
753
754     unmap_file(&mf);
755
756     return res;
757 }
758
759 // The stlink_fwrite_flash should not muck with mmapped files inside itself,
760 // and should use this function instead. (Hell, what's the reason behind mmap
761 // there?!) But, as it is not actually used anywhere, nobody cares.
762
763 #define WRITE_BLOCK_SIZE 0x40
764
765 int stlink_write_flash(stlink_t *sl, stm32_addr_t addr, uint8_t* base, unsigned len) {
766     size_t off;
767     flash_loader_t fl;
768
769     /* check addr range is inside the flash */
770     if (addr < sl->flash_base) {
771         fprintf(stderr, "addr too low\n");
772         return -1;
773     } else if ((addr + len) < addr) {
774         fprintf(stderr, "addr overruns\n");
775         return -1;
776     } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
777         fprintf(stderr, "addr too high\n");
778         return -1;
779     } else if ((addr & 1) || (len & 1)) {
780         fprintf(stderr, "unaligned addr or size\n");
781         return -1;
782     }
783
784     /* flash loader initialization */
785     if (init_flash_loader(sl, &fl) == -1) {
786         fprintf(stderr, "init_flash_loader() == -1\n");
787         return -1;
788     }
789
790     /* write each page. above WRITE_BLOCK_SIZE fails? */
791     for (off = 0; off < len; off += WRITE_BLOCK_SIZE) {
792         /* adjust last write size */
793         size_t size = WRITE_BLOCK_SIZE;
794         if ((off + WRITE_BLOCK_SIZE) > len)
795             size = len - off;
796
797         if (run_flash_loader(sl, &fl, addr + off, base + off, size) == -1) {
798             fprintf(stderr, "run_flash_loader(0x%zx) == -1\n", addr + off);
799             return -1;
800         }
801     }
802
803     for (off = 0; off < len; off += sl->flash_pgsz) {
804         size_t aligned_size;
805
806         /* adjust last page size */
807         size_t cmp_size = sl->flash_pgsz;
808         if ((off + sl->flash_pgsz) > len)
809             cmp_size = len - off;
810
811         aligned_size = cmp_size;
812         if (aligned_size & (4 - 1))
813             aligned_size = (cmp_size + 4) & ~(4 - 1);
814
815         stlink_read_mem32(sl, addr + off, aligned_size);
816
817         if (memcmp(sl->q_buf, base + off, cmp_size))
818             return -1;
819     }
820
821     return 0;
822 }
823
824 int stlink_fwrite_flash(stlink_t *sl, const char* path, stm32_addr_t addr) {
825     /* write the file in flash at addr */
826
827     int error = -1;
828     size_t off;
829     mapped_file_t mf = MAPPED_FILE_INITIALIZER;
830     flash_loader_t fl;
831
832     if (map_file(&mf, path) == -1) {
833         fprintf(stderr, "map_file() == -1\n");
834         return -1;
835     }
836
837     /* check addr range is inside the flash */
838     if (addr < sl->flash_base) {
839         fprintf(stderr, "addr too low\n");
840         goto on_error;
841     } else if ((addr + mf.len) < addr) {
842         fprintf(stderr, "addr overruns\n");
843         goto on_error;
844     } else if ((addr + mf.len) > (sl->flash_base + sl->flash_size)) {
845         fprintf(stderr, "addr too high\n");
846         goto on_error;
847     } else if ((addr & 1) || (mf.len & 1)) {
848         /* todo */
849         fprintf(stderr, "unaligned addr or size\n");
850         goto on_error;
851     }
852
853     /* erase each page. todo: mass erase faster? */
854     for (off = 0; off < mf.len; off += sl->flash_pgsz) {
855         /* addr must be an addr inside the page */
856         if (stlink_erase_flash_page(sl, addr + off) == -1) {
857             fprintf(stderr, "erase_flash_page(0x%zx) == -1\n", addr + off);
858             goto on_error;
859         }
860     }
861
862     /* flash loader initialization */
863     if (init_flash_loader(sl, &fl) == -1) {
864         fprintf(stderr, "init_flash_loader() == -1\n");
865         goto on_error;
866     }
867
868     /* write each page. above WRITE_BLOCK_SIZE fails? */
869 #define WRITE_BLOCK_SIZE 0x40
870     for (off = 0; off < mf.len; off += WRITE_BLOCK_SIZE) {
871         /* adjust last write size */
872         size_t size = WRITE_BLOCK_SIZE;
873         if ((off + WRITE_BLOCK_SIZE) > mf.len)
874             size = mf.len - off;
875
876         if (run_flash_loader(sl, &fl, addr + off, mf.base + off, size) == -1) {
877             fprintf(stderr, "run_flash_loader(0x%zx) == -1\n", addr + off);
878             goto on_error;
879         }
880     }
881
882     /* check the file ha been written */
883     if (check_file(sl, &mf, addr) == -1) {
884         fprintf(stderr, "check_file() == -1\n");
885         goto on_error;
886     }
887
888     /* success */
889     error = 0;
890
891 on_error:
892     unmap_file(&mf);
893     return error;
894 }
895
896 int run_flash_loader(stlink_t *sl, flash_loader_t* fl, stm32_addr_t target, const uint8_t* buf, size_t size) {
897     const size_t count = size / sizeof (uint16_t);
898
899     if (write_buffer_to_sram(sl, fl, buf, size) == -1) {
900         fprintf(stderr, "write_buffer_to_sram() == -1\n");
901         return -1;
902     }
903
904     /* setup core */
905     stlink_write_reg(sl, fl->buf_addr, 0); /* source */
906     stlink_write_reg(sl, target, 1); /* target */
907     stlink_write_reg(sl, count, 2); /* count (16 bits half words) */
908     stlink_write_reg(sl, 0, 3); /* flash bank 0 (input) */
909     stlink_write_reg(sl, fl->loader_addr, 15); /* pc register */
910
911     /* unlock and set programming mode */
912     unlock_flash_if(sl);
913     set_flash_cr_pg(sl);
914
915     /* run loader */
916     stlink_run(sl);
917
918     while (is_core_halted(sl) == 0)
919         ;
920
921     lock_flash(sl);
922
923     /* not all bytes have been written */
924     reg rr;
925     stlink_read_reg(sl, 2, &rr);
926     if (rr.r[2] != 0) {
927         fprintf(stderr, "write error, count == %u\n", rr.r[2]);
928         return -1;
929     }
930
931     return 0;
932 }