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