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