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