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