1 #define DEBUG_FLASH 0
2 #include <limits.h>
3 #include <stdarg.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 
15 #include <helper.h>
16 #include <logging.h>
17 #include <md5.h>
18 #include <stlink.h>
19 
20 #ifdef STLINK_HAVE_SYS_MMAN_H
21 #include <sys/mman.h>
22 #else
23 #include <mmap.h>
24 #endif
25 
26 #ifndef O_BINARY
27 #define O_BINARY 0
28 #endif
29 
30 #ifdef _MSC_VER
31 #define __attribute__(x)
32 #endif
33 
34 #define BANK_1 0
35 #define BANK_2 1
36 
37 /* stm32f FPEC flash controller interface, pm0063 manual */
38 // TODO - all of this needs to be abstracted out....
39 // STM32F05x is identical, based on RM0091 (DM00031936, Doc ID 018940 Rev 2,
40 // August 2012)
41 #define FLASH_REGS_ADDR 0x40022000
42 #define FLASH_REGS_SIZE 0x28
43 
44 #define FLASH_ACR (FLASH_REGS_ADDR + 0x00)
45 #define FLASH_KEYR (FLASH_REGS_ADDR + 0x04)
46 #define FLASH_OPTKEYR (FLASH_REGS_ADDR + 0x08)
47 #define FLASH_SR (FLASH_REGS_ADDR + 0x0c)
48 #define FLASH_CR (FLASH_REGS_ADDR + 0x10)
49 #define FLASH_AR (FLASH_REGS_ADDR + 0x14)
50 #define FLASH_OBR (FLASH_REGS_ADDR + 0x1c)
51 #define FLASH_WRPR (FLASH_REGS_ADDR + 0x20)
52 
53 // STM32F10x_XL has two flash memory banks with separate registers to control
54 // the second bank.
55 #define FLASH_KEYR2 (FLASH_REGS_ADDR + 0x44)
56 #define FLASH_SR2 (FLASH_REGS_ADDR + 0x4c)
57 #define FLASH_CR2 (FLASH_REGS_ADDR + 0x50)
58 #define FLASH_AR2 (FLASH_REGS_ADDR + 0x54)
59 
60 // For STM32F05x, the RDPTR_KEY may be wrong, but as it is not used anywhere...
61 #define FLASH_RDPTR_KEY 0x00a5
62 #define FLASH_KEY1 0x45670123
63 #define FLASH_KEY2 0xcdef89ab
64 
65 #define FLASH_L0_PRGKEY1 0x8c9daebf
66 #define FLASH_L0_PRGKEY2 0x13141516
67 
68 #define FLASH_L0_PEKEY1 0x89abcdef
69 #define FLASH_L0_PEKEY2 0x02030405
70 
71 #define FLASH_OPTKEY1 0x08192A3B
72 #define FLASH_OPTKEY2 0x4C5D6E7F
73 
74 #define FLASH_F0_OPTKEY1 0x45670123
75 #define FLASH_F0_OPTKEY2 0xCDEF89AB
76 
77 #define FLASH_L0_OPTKEY1 0xFBEAD9C8
78 #define FLASH_L0_OPTKEY2 0x24252627
79 
80 #define FLASH_SR_BSY 0
81 #define FLASH_SR_PG_ERR 2
82 #define FLASH_SR_WRPRT_ERR 4
83 #define FLASH_SR_EOP 5
84 
85 #define FLASH_SR_ERROR_MASK ((1 << FLASH_SR_PG_ERR) | (1 << FLASH_SR_WRPRT_ERR))
86 
87 #define FLASH_CR_PG 0
88 #define FLASH_CR_PER 1
89 #define FLASH_CR_MER 2
90 #define FLASH_CR_OPTPG 4
91 #define FLASH_CR_STRT 6
92 #define FLASH_CR_LOCK 7
93 #define FLASH_CR_OPTWRE 9
94 
95 #define STM32L_FLASH_REGS_ADDR ((uint32_t)0x40023c00)
96 #define STM32L_FLASH_ACR (STM32L_FLASH_REGS_ADDR + 0x00)
97 #define STM32L_FLASH_PECR (STM32L_FLASH_REGS_ADDR + 0x04)
98 #define STM32L_FLASH_PDKEYR (STM32L_FLASH_REGS_ADDR + 0x08)
99 #define STM32L_FLASH_PEKEYR (STM32L_FLASH_REGS_ADDR + 0x0c)
100 #define STM32L_FLASH_PRGKEYR (STM32L_FLASH_REGS_ADDR + 0x10)
101 #define STM32L_FLASH_OPTKEYR (STM32L_FLASH_REGS_ADDR + 0x14)
102 #define STM32L_FLASH_SR (STM32L_FLASH_REGS_ADDR + 0x18)
103 #define STM32L_FLASH_OBR (STM32L_FLASH_REGS_ADDR + 0x1c)
104 #define STM32L_FLASH_WRPR (STM32L_FLASH_REGS_ADDR + 0x20)
105 #define FLASH_L1_FPRG 10
106 #define FLASH_L1_PROG 3
107 
108 // Flash registers common to STM32G0 and STM32G4 series.
109 #define STM32Gx_FLASH_REGS_ADDR ((uint32_t)0x40022000)
110 #define STM32Gx_FLASH_ACR (STM32Gx_FLASH_REGS_ADDR + 0x00)
111 #define STM32Gx_FLASH_KEYR (STM32Gx_FLASH_REGS_ADDR + 0x08)
112 #define STM32Gx_FLASH_OPTKEYR (STM32Gx_FLASH_REGS_ADDR + 0x0c)
113 #define STM32Gx_FLASH_SR (STM32Gx_FLASH_REGS_ADDR + 0x10)
114 #define STM32Gx_FLASH_CR (STM32Gx_FLASH_REGS_ADDR + 0x14)
115 #define STM32Gx_FLASH_ECCR (STM32Gx_FLASH_REGS_ADDR + 0x18)
116 #define STM32Gx_FLASH_OPTR (STM32Gx_FLASH_REGS_ADDR + 0x20)
117 
118 // G0 (RM0444 Table 1, sec 3.7)
119 // Mostly the same as G4 chips, but the notation
120 // varies a bit after the 'OPTR' register.
121 #define STM32G0_FLASH_REGS_ADDR (STM32Gx_FLASH_REGS_ADDR)
122 #define STM32G0_FLASH_PCROP1ASR (STM32G0_FLASH_REGS_ADDR + 0x24)
123 #define STM32G0_FLASH_PCROP1AER (STM32G0_FLASH_REGS_ADDR + 0x28)
124 #define STM32G0_FLASH_WRP1AR (STM32G0_FLASH_REGS_ADDR + 0x2C)
125 #define STM32G0_FLASH_WRP1BR (STM32G0_FLASH_REGS_ADDR + 0x30)
126 #define STM32G0_FLASH_PCROP1BSR (STM32G0_FLASH_REGS_ADDR + 0x34)
127 #define STM32G0_FLASH_PCROP1BER (STM32G0_FLASH_REGS_ADDR + 0x38)
128 #define STM32G0_FLASH_SECR (STM32G0_FLASH_REGS_ADDR + 0x80)
129 
130 // G4 (RM0440 Table 17, sec 3.7.19)
131 // Mostly the same as STM32G0 chips, but there are a few extra
132 // registers because 'cat 3' devices can have two Flash banks.
133 #define STM32G4_FLASH_REGS_ADDR (STM32Gx_FLASH_REGS_ADDR)
134 #define STM32G4_FLASH_PDKEYR (STM32G4_FLASH_REGS_ADDR + 0x04)
135 #define STM32G4_FLASH_PCROP1SR (STM32G4_FLASH_REGS_ADDR + 0x24)
136 #define STM32G4_FLASH_PCROP1ER (STM32G4_FLASH_REGS_ADDR + 0x28)
137 #define STM32G4_FLASH_WRP1AR (STM32G4_FLASH_REGS_ADDR + 0x2C)
138 #define STM32G4_FLASH_WRP1BR (STM32G4_FLASH_REGS_ADDR + 0x30)
139 #define STM32G4_FLASH_PCROP2SR (STM32G4_FLASH_REGS_ADDR + 0x44)
140 #define STM32G4_FLASH_PCROP2ER (STM32G4_FLASH_REGS_ADDR + 0x48)
141 #define STM32G4_FLASH_WRP2AR (STM32G4_FLASH_REGS_ADDR + 0x4C)
142 #define STM32G4_FLASH_WRP2BR (STM32G4_FLASH_REGS_ADDR + 0x50)
143 #define STM32G4_FLASH_SEC1R (STM32G4_FLASH_REGS_ADDR + 0x70)
144 #define STM32G4_FLASH_SEC2R (STM32G4_FLASH_REGS_ADDR + 0x74)
145 
146 // G0/G4 FLASH control register
147 #define STM32Gx_FLASH_CR_PG (0)      /* Program */
148 #define STM32Gx_FLASH_CR_PER (1)     /* Page erase */
149 #define STM32Gx_FLASH_CR_MER1 (2)    /* Mass erase */
150 #define STM32Gx_FLASH_CR_PNB (3)     /* Page number */
151 #define STM32G0_FLASH_CR_PNG_LEN (5) /* STM32G0: 5 page number bits */
152 #define STM32G4_FLASH_CR_PNG_LEN (7) /* STM32G4: 7 page number bits */
153 #define STM32Gx_FLASH_CR_MER2 (15)   /* Mass erase (2nd bank)*/
154 #define STM32Gx_FLASH_CR_STRT (16)   /* Start */
155 #define STM32Gx_FLASH_CR_OPTSTRT                                               \
156   (17)                              /* Start of modification of option bytes */
157 #define STM32Gx_FLASH_CR_FSTPG (18) /* Fast programming */
158 #define STM32Gx_FLASH_CR_EOPIE (24) /* End of operation interrupt enable */
159 #define STM32Gx_FLASH_CR_ERRIE (25) /* Error interrupt enable */
160 #define STM32Gx_FLASH_CR_OBL_LAUNCH (27) /* Forces the option byte loading */
161 #define STM32Gx_FLASH_CR_OPTLOCK (30)    /* Options Lock */
162 #define STM32Gx_FLASH_CR_LOCK (31)       /* FLASH_CR Lock */
163 
164 // G0/G4 FLASH status register
165 #define STM32Gx_FLASH_SR_ERROR_MASK (0x3fa)
166 #define STM32Gx_FLASH_SR_PROGERR (3)
167 #define STM32Gx_FLASH_SR_WRPERR (4)
168 #define STM32Gx_FLASH_SR_PGAERR (5)
169 #define STM32Gx_FLASH_SR_BSY (16) /* FLASH_SR Busy */
170 #define STM32Gx_FLASH_SR_EOP (0)  /* FLASH_EOP End of Operation */
171 
172 // G4 FLASH option register
173 #define STM32G4_FLASH_OPTR_DBANK (22) /* FLASH_OPTR Dual Bank Mode */
174 
175 // WB (RM0434)
176 #define STM32WB_FLASH_REGS_ADDR ((uint32_t)0x58004000)
177 #define STM32WB_FLASH_ACR (STM32WB_FLASH_REGS_ADDR + 0x00)
178 #define STM32WB_FLASH_KEYR (STM32WB_FLASH_REGS_ADDR + 0x08)
179 #define STM32WB_FLASH_OPT_KEYR (STM32WB_FLASH_REGS_ADDR + 0x0C)
180 #define STM32WB_FLASH_SR (STM32WB_FLASH_REGS_ADDR + 0x10)
181 #define STM32WB_FLASH_CR (STM32WB_FLASH_REGS_ADDR + 0x14)
182 #define STM32WB_FLASH_ECCR (STM32WB_FLASH_REGS_ADDR + 0x18)
183 #define STM32WB_FLASH_OPTR (STM32WB_FLASH_REGS_ADDR + 0x20)
184 #define STM32WB_FLASH_PCROP1ASR (STM32WB_FLASH_REGS_ADDR + 0x24)
185 #define STM32WB_FLASH_PCROP1AER (STM32WB_FLASH_REGS_ADDR + 0x28)
186 #define STM32WB_FLASH_WRP1AR (STM32WB_FLASH_REGS_ADDR + 0x2C)
187 #define STM32WB_FLASH_WRP1BR (STM32WB_FLASH_REGS_ADDR + 0x30)
188 #define STM32WB_FLASH_PCROP1BSR (STM32WB_FLASH_REGS_ADDR + 0x34)
189 #define STM32WB_FLASH_PCROP1BER (STM32WB_FLASH_REGS_ADDR + 0x38)
190 #define STM32WB_FLASH_IPCCBR (STM32WB_FLASH_REGS_ADDR + 0x3C)
191 #define STM32WB_FLASH_C2ACR (STM32WB_FLASH_REGS_ADDR + 0x5C)
192 #define STM32WB_FLASH_C2SR (STM32WB_FLASH_REGS_ADDR + 0x60)
193 #define STM32WB_FLASH_C2CR (STM32WB_FLASH_REGS_ADDR + 0x64)
194 #define STM32WB_FLASH_SFR (STM32WB_FLASH_REGS_ADDR + 0x80)
195 #define STM32WB_FLASH_SRRVR (STM32WB_FLASH_REGS_ADDR + 0x84)
196 
197 // WB Flash control register.
198 #define STM32WB_FLASH_CR_STRT (16)    /* Start */
199 #define STM32WB_FLASH_CR_OPTLOCK (30) /* Option Lock */
200 #define STM32WB_FLASH_CR_LOCK (31)    /* Lock */
201 // WB Flash status register.
202 #define STM32WB_FLASH_SR_ERROR_MASK (0x3f8) /* SR [9:3] */
203 #define STM32WB_FLASH_SR_PROGERR (3)        /* Programming alignment error */
204 #define STM32WB_FLASH_SR_WRPERR (4)         /* Write protection error */
205 #define STM32WB_FLASH_SR_PGAERR (5)         /* Programming error */
206 #define STM32WB_FLASH_SR_BSY (16)           /* Busy */
207 
208 // 32L4 register base is at FLASH_REGS_ADDR (0x40022000)
209 #define STM32L4_FLASH_KEYR (FLASH_REGS_ADDR + 0x08)
210 #define STM32L4_FLASH_OPTKEYR (FLASH_REGS_ADDR + 0x0C)
211 #define STM32L4_FLASH_SR (FLASH_REGS_ADDR + 0x10)
212 #define STM32L4_FLASH_CR (FLASH_REGS_ADDR + 0x14)
213 #define STM32L4_FLASH_OPTR (FLASH_REGS_ADDR + 0x20)
214 
215 #define STM32L4_FLASH_SR_ERROR_MASK 0x3f8 /* SR [9:3] */
216 #define STM32L4_FLASH_SR_PROGERR 3
217 #define STM32L4_FLASH_SR_WRPERR 4
218 #define STM32L4_FLASH_SR_PGAERR 5
219 #define STM32L4_FLASH_SR_BSY 16
220 
221 #define STM32L4_FLASH_CR_LOCK 31       /* Lock control register */
222 #define STM32L4_FLASH_CR_OPTLOCK 30    /* Lock option bytes */
223 #define STM32L4_FLASH_CR_PG 0          /* Program */
224 #define STM32L4_FLASH_CR_PER 1         /* Page erase */
225 #define STM32L4_FLASH_CR_MER1 2        /* Bank 1 erase */
226 #define STM32L4_FLASH_CR_MER2 15       /* Bank 2 erase */
227 #define STM32L4_FLASH_CR_STRT 16       /* Start command */
228 #define STM32L4_FLASH_CR_OPTSTRT 17    /* Start writing option bytes */
229 #define STM32L4_FLASH_CR_BKER 11       /* Bank select for page erase */
230 #define STM32L4_FLASH_CR_PNB 3         /* Page number (8 bits) */
231 #define STM32L4_FLASH_CR_OBL_LAUNCH 27 /* Option bytes reload */
232 // Bits requesting flash operations (useful when we want to clear them)
233 #define STM32L4_FLASH_CR_OPBITS                                                \
234   (uint32_t)((1lu << STM32L4_FLASH_CR_PG) | (1lu << STM32L4_FLASH_CR_PER) |    \
235              (1lu << STM32L4_FLASH_CR_MER1) | (1lu << STM32L4_FLASH_CR_MER1))
236 // Page is fully specified by BKER and PNB
237 #define STM32L4_FLASH_CR_PAGEMASK (uint32_t)(0x1fflu << STM32L4_FLASH_CR_PNB)
238 
239 #define STM32L4_FLASH_OPTR_DUALBANK 21
240 
241 // STM32L0x flash register base and offsets RM0090 - DM00031020.pdf
242 #define STM32L0_FLASH_REGS_ADDR ((uint32_t)0x40022000)
243 #define STM32L1_FLASH_REGS_ADDR ((uint32_t)0x40023c00)
244 
245 #define STM32L0_FLASH_PELOCK (0)
246 #define STM32L0_FLASH_OPTLOCK (2)
247 #define STM32L0_FLASH_OBL_LAUNCH (18)
248 
249 #define STM32L0_FLASH_SR_ERROR_MASK 0x00013F00
250 #define STM32L0_FLASH_SR_WRPERR 8
251 #define STM32L0_FLASH_SR_PGAERR 9
252 #define STM32L0_FLASH_SR_NOTZEROERR 16
253 
254 #define FLASH_ACR_OFF ((uint32_t)0x00)
255 #define FLASH_PECR_OFF ((uint32_t)0x04)
256 #define FLASH_PDKEYR_OFF ((uint32_t)0x08)
257 #define FLASH_PEKEYR_OFF ((uint32_t)0x0c)
258 #define FLASH_PRGKEYR_OFF ((uint32_t)0x10)
259 #define FLASH_OPTKEYR_OFF ((uint32_t)0x14)
260 #define FLASH_SR_OFF ((uint32_t)0x18)
261 #define FLASH_OBR_OFF ((uint32_t)0x1c)
262 #define FLASH_WRPR_OFF ((uint32_t)0x20)
263 
264 // STM32F7
265 #define FLASH_F7_REGS_ADDR ((uint32_t)0x40023c00)
266 #define FLASH_F7_KEYR (FLASH_F7_REGS_ADDR + 0x04)
267 #define FLASH_F7_OPT_KEYR (FLASH_F7_REGS_ADDR + 0x08)
268 #define FLASH_F7_SR (FLASH_F7_REGS_ADDR + 0x0c)
269 #define FLASH_F7_CR (FLASH_F7_REGS_ADDR + 0x10)
270 #define FLASH_F7_OPTCR (FLASH_F7_REGS_ADDR + 0x14)
271 #define FLASH_F7_OPTCR1 (FLASH_F7_REGS_ADDR + 0x18)
272 #define FLASH_F7_OPTCR_LOCK 0
273 #define FLASH_F7_OPTCR_START 1
274 #define FLASH_F7_CR_STRT 16
275 #define FLASH_F7_CR_LOCK 31
276 #define FLASH_F7_CR_SER 1
277 #define FLASH_F7_CR_SNB 3
278 #define FLASH_F7_CR_SNB_MASK 0xf8
279 #define FLASH_F7_SR_BSY 16
280 #define FLASH_F7_SR_ERS_ERR 7 /* Erase Sequence Error */
281 #define FLASH_F7_SR_PGP_ERR 6 /* Programming parallelism error */
282 #define FLASH_F7_SR_PGA_ERR 5 /* Programming alignment error */
283 #define FLASH_F7_SR_WRP_ERR 4 /* Write protection error */
284 #define FLASH_F7_SR_OP_ERR 1  /* Operation error */
285 #define FLASH_F7_SR_EOP 0     /* End of operation */
286 #define FLASH_F7_OPTCR1_BOOT_ADD0 0
287 #define FLASH_F7_OPTCR1_BOOT_ADD1 16
288 
289 #define FLASH_F7_SR_ERROR_MASK                                                 \
290   ((1 << FLASH_F7_SR_ERS_ERR) | (1 << FLASH_F7_SR_PGP_ERR) |                   \
291    (1 << FLASH_F7_SR_PGA_ERR) | (1 << FLASH_F7_SR_WRP_ERR) |                   \
292    (1 << FLASH_F7_SR_OP_ERR))
293 
294 // STM32F4
295 #define FLASH_F4_REGS_ADDR ((uint32_t)0x40023c00)
296 #define FLASH_F4_KEYR (FLASH_F4_REGS_ADDR + 0x04)
297 #define FLASH_F4_OPT_KEYR (FLASH_F4_REGS_ADDR + 0x08)
298 #define FLASH_F4_SR (FLASH_F4_REGS_ADDR + 0x0c)
299 #define FLASH_F4_CR (FLASH_F4_REGS_ADDR + 0x10)
300 #define FLASH_F4_OPTCR (FLASH_F4_REGS_ADDR + 0x14)
301 #define FLASH_F4_OPTCR_LOCK 0
302 #define FLASH_F4_OPTCR_START 1
303 #define FLASH_F4_CR_STRT 16
304 #define FLASH_F4_CR_LOCK 31
305 #define FLASH_F4_CR_SER 1
306 #define FLASH_F4_CR_SNB 3
307 #define FLASH_F4_CR_SNB_MASK 0xf8
308 #define FLASH_F4_SR_ERROR_MASK 0x000000F0
309 #define FLASH_F4_SR_PGAERR 5
310 #define FLASH_F4_SR_WRPERR 4
311 #define FLASH_F4_SR_BSY 16
312 
313 // STM32F2
314 #define FLASH_F2_REGS_ADDR ((uint32_t)0x40023c00)
315 #define FLASH_F2_KEYR (FLASH_F2_REGS_ADDR + 0x04)
316 #define FLASH_F2_OPT_KEYR (FLASH_F2_REGS_ADDR + 0x08)
317 #define FLASH_F2_SR (FLASH_F2_REGS_ADDR + 0x0c)
318 #define FLASH_F2_CR (FLASH_F2_REGS_ADDR + 0x10)
319 #define FLASH_F2_OPT_CR (FLASH_F2_REGS_ADDR + 0x14)
320 #define FLASH_F2_OPT_LOCK_BIT (1u << 0)
321 #define FLASH_F2_CR_STRT 16
322 #define FLASH_F2_CR_LOCK 31
323 
324 #define FLASH_F2_CR_SER 1
325 #define FLASH_F2_CR_SNB 3
326 #define FLASH_F2_CR_SNB_MASK 0x78
327 #define FLASH_F2_SR_BSY 16
328 
329 // STM32H7xx
330 #define FLASH_H7_CR_LOCK 0
331 #define FLASH_H7_CR_PG 1
332 #define FLASH_H7_CR_SER 2
333 #define FLASH_H7_CR_BER 3
334 #define FLASH_H7_CR_PSIZE 4
335 #define FLASH_H7_CR_START(chipid) (chipid == STLINK_CHIPID_STM32_H7AX ? 5 : 7)
336 #define FLASH_H7_CR_SNB 8
337 #define FLASH_H7_CR_SNB_MASK 0x700
338 
339 #define FLASH_H7_SR_QW 2
340 #define FLASH_H7_SR_WRPERR 17
341 #define FLASH_H7_SR_PGSERR 18
342 #define FLASH_H7_SR_STRBERR 19
343 #define FLASH_H7_SR_ERROR_MASK                                                 \
344   ((1 << FLASH_H7_SR_PGSERR) | (1 << FLASH_H7_SR_STRBERR) |                    \
345    (1 << FLASH_H7_SR_WRPERR))
346 
347 #define FLASH_H7_OPTCR_OPTLOCK 0
348 #define FLASH_H7_OPTCR_OPTSTART 1
349 #define FLASH_H7_OPTCR_MER 4
350 
351 #define FLASH_H7_OPTSR_OPT_BUSY 0
352 #define FLASH_H7_OPTSR_OPTCHANGEERR 30
353 
354 #define FLASH_H7_OPTCCR_CLR_OPTCHANGEERR 30
355 
356 #define FLASH_H7_REGS_ADDR ((uint32_t)0x52002000)
357 #define FLASH_H7_KEYR1 (FLASH_H7_REGS_ADDR + 0x04)
358 #define FLASH_H7_KEYR2 (FLASH_H7_REGS_ADDR + 0x104)
359 #define FLASH_H7_OPT_KEYR (FLASH_H7_REGS_ADDR + 0x08)
360 #define FLASH_H7_OPT_KEYR2 (FLASH_H7_REGS_ADDR + 0x108)
361 #define FLASH_H7_CR1 (FLASH_H7_REGS_ADDR + 0x0c)
362 #define FLASH_H7_CR2 (FLASH_H7_REGS_ADDR + 0x10c)
363 #define FLASH_H7_SR1 (FLASH_H7_REGS_ADDR + 0x10)
364 #define FLASH_H7_SR2 (FLASH_H7_REGS_ADDR + 0x110)
365 #define FLASH_H7_CCR1 (FLASH_H7_REGS_ADDR + 0x14)
366 #define FLASH_H7_CCR2 (FLASH_H7_REGS_ADDR + 0x114)
367 #define FLASH_H7_OPTCR (FLASH_H7_REGS_ADDR + 0x18)
368 #define FLASH_H7_OPTCR2 (FLASH_H7_REGS_ADDR + 0x118)
369 #define FLASH_H7_OPTSR_CUR (FLASH_H7_REGS_ADDR + 0x1c)
370 #define FLASH_H7_OPTCCR (FLASH_H7_REGS_ADDR + 0x24)
371 
372 #define STM32F0_DBGMCU_CR 0xE0042004
373 #define STM32F0_DBGMCU_CR_IWDG_STOP 8
374 #define STM32F0_DBGMCU_CR_WWDG_STOP 9
375 
376 #define STM32F4_DBGMCU_APB1FZR1 0xE0042008
377 #define STM32F4_DBGMCU_APB1FZR1_WWDG_STOP 11
378 #define STM32F4_DBGMCU_APB1FZR1_IWDG_STOP 12
379 
380 #define STM32L0_DBGMCU_APB1_FZ 0x40015808
381 #define STM32L0_DBGMCU_APB1_FZ_WWDG_STOP 11
382 #define STM32L0_DBGMCU_APB1_FZ_IWDG_STOP 12
383 
384 #define STM32H7_DBGMCU_APB1HFZ 0x5C001054
385 #define STM32H7_DBGMCU_APB1HFZ_IWDG_STOP 18
386 
387 #define STM32WB_DBGMCU_APB1FZR1 0xE004203C
388 #define STM32WB_DBGMCU_APB1FZR1_WWDG_STOP 11
389 #define STM32WB_DBGMCU_APB1FZR1_IWDG_STOP 12
390 
391 #define STM32F1_RCC_AHBENR 0x40021014
392 #define STM32F1_RCC_DMAEN 0x00000003 // DMA2EN | DMA1EN
393 
394 #define STM32F4_RCC_AHB1ENR 0x40023830
395 #define STM32F4_RCC_DMAEN 0x00600000 // DMA2EN | DMA1EN
396 
397 #define STM32G0_RCC_AHBENR 0x40021038
398 #define STM32G0_RCC_DMAEN 0x00000003 // DMA2EN | DMA1EN
399 
400 #define STM32G4_RCC_AHB1ENR 0x40021048
401 #define STM32G4_RCC_DMAEN 0x00000003 // DMA2EN | DMA1EN
402 
403 #define STM32L0_RCC_AHBENR 0x40021030
404 #define STM32L0_RCC_DMAEN 0x00000001 // DMAEN
405 
406 #define STM32H7_RCC_AHB1ENR 0x58024538
407 #define STM32H7_RCC_DMAEN 0x00000003 // DMA2EN | DMA1EN
408 
409 #define STM32WB_RCC_AHB1ENR 0x58000048
410 #define STM32WB_RCC_DMAEN 0x00000003 // DMA2EN | DMA1EN
411 
412 #define L1_WRITE_BLOCK_SIZE 0x80
413 #define L0_WRITE_BLOCK_SIZE 0x40
414 
415 // Endianness
416 // https://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html
417 // These functions encode and decode little endian uint16 and uint32 values.
418 
write_uint32(unsigned char * buf,uint32_t ui)419 void write_uint32(unsigned char *buf, uint32_t ui) {
420   buf[0] = ui;
421   buf[1] = ui >> 8;
422   buf[2] = ui >> 16;
423   buf[3] = ui >> 24;
424 }
425 
write_uint16(unsigned char * buf,uint16_t ui)426 void write_uint16(unsigned char *buf, uint16_t ui) {
427   buf[0] = ui;
428   buf[1] = ui >> 8;
429 }
430 
read_uint32(const unsigned char * c,const int pt)431 uint32_t read_uint32(const unsigned char *c, const int pt) {
432   return ((uint32_t)c[pt]) | ((uint32_t)c[pt + 1] << 8) |
433          ((uint32_t)c[pt + 2] << 16) | ((uint32_t)c[pt + 3] << 24);
434 }
435 
read_uint16(const unsigned char * c,const int pt)436 uint16_t read_uint16(const unsigned char *c, const int pt) {
437   return ((uint16_t)c[pt]) | ((uint16_t)c[pt + 1] << 8);
438 }
439 
get_stm32l0_flash_base(stlink_t * sl)440 static uint32_t get_stm32l0_flash_base(stlink_t *sl) {
441   switch (sl->chip_id) {
442   case STLINK_CHIPID_STM32_L0:
443   case STLINK_CHIPID_STM32_L0_CAT5:
444   case STLINK_CHIPID_STM32_L0_CAT2:
445   case STLINK_CHIPID_STM32_L011:
446     return (STM32L0_FLASH_REGS_ADDR);
447 
448   case STLINK_CHIPID_STM32_L1_CAT2:
449   case STLINK_CHIPID_STM32_L1_MEDIUM:
450   case STLINK_CHIPID_STM32_L1_MEDIUM_PLUS:
451   case STLINK_CHIPID_STM32_L1_HIGH:
452     return (STM32L1_FLASH_REGS_ADDR);
453 
454   default:
455     WLOG("Flash base use default L0 address");
456     return (STM32L0_FLASH_REGS_ADDR);
457   }
458 }
459 
read_flash_rdp(stlink_t * sl)460 static uint32_t __attribute__((unused)) read_flash_rdp(stlink_t *sl) {
461   uint32_t rdp;
462   stlink_read_debug32(sl, FLASH_WRPR, &rdp);
463   return (rdp & 0xff);
464 }
465 
read_flash_cr(stlink_t * sl,unsigned bank)466 static inline uint32_t read_flash_cr(stlink_t *sl, unsigned bank) {
467   uint32_t reg, res;
468 
469   if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
470     reg = FLASH_F4_CR;
471   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
472     reg = FLASH_F7_CR;
473   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
474     reg = STM32L4_FLASH_CR;
475   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
476              sl->flash_type == STLINK_FLASH_TYPE_G4) {
477     reg = STM32Gx_FLASH_CR;
478   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
479     reg = STM32WB_FLASH_CR;
480   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
481     reg = (bank == BANK_1) ? FLASH_H7_CR1 : FLASH_H7_CR2;
482   } else {
483     reg = (bank == BANK_1) ? FLASH_CR : FLASH_CR2;
484   }
485 
486   stlink_read_debug32(sl, reg, &res);
487 
488 #if DEBUG_FLASH
489   fprintf(stdout, "CR:0x%x\n", res);
490 #endif
491   return (res);
492 }
493 
is_flash_locked(stlink_t * sl)494 static inline unsigned int is_flash_locked(stlink_t *sl) {
495   /* return non zero for true */
496   uint32_t cr_lock_shift;
497   uint32_t cr_reg;
498   uint32_t n;
499 
500   if ((sl->flash_type == STLINK_FLASH_TYPE_F0) ||
501       (sl->flash_type == STLINK_FLASH_TYPE_F1_XL)) {
502     cr_reg = FLASH_CR;
503     cr_lock_shift = FLASH_CR_LOCK;
504   } else if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
505     cr_reg = FLASH_F4_CR;
506     cr_lock_shift = FLASH_F4_CR_LOCK;
507   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
508     cr_reg = FLASH_F7_CR;
509     cr_lock_shift = FLASH_F7_CR_LOCK;
510   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
511     cr_reg = get_stm32l0_flash_base(sl) + FLASH_PECR_OFF;
512     cr_lock_shift = STM32L0_FLASH_PELOCK;
513   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
514     cr_reg = STM32L4_FLASH_CR;
515     cr_lock_shift = STM32L4_FLASH_CR_LOCK;
516   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
517              sl->flash_type == STLINK_FLASH_TYPE_G4) {
518     cr_reg = STM32Gx_FLASH_CR;
519     cr_lock_shift = STM32Gx_FLASH_CR_LOCK;
520   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
521     cr_reg = STM32WB_FLASH_CR;
522     cr_lock_shift = STM32WB_FLASH_CR_LOCK;
523   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
524     cr_reg = FLASH_H7_CR1;
525     cr_lock_shift = FLASH_H7_CR_LOCK;
526   } else {
527     ELOG("unsupported flash method, abort\n");
528     return (-1);
529   }
530 
531   stlink_read_debug32(sl, cr_reg, &n);
532   return (n & (1u << cr_lock_shift));
533 }
534 
unlock_flash(stlink_t * sl)535 static void unlock_flash(stlink_t *sl) {
536   uint32_t key_reg, key2_reg = 0;
537   uint32_t flash_key1 = FLASH_KEY1;
538   uint32_t flash_key2 = FLASH_KEY2;
539   /* The unlock sequence consists of 2 write cycles where 2 key values are
540    * written to the FLASH_KEYR register. An invalid sequence results in a
541    * definitive lock of the FPEC block until next reset.
542    */
543 
544   if (sl->flash_type == STLINK_FLASH_TYPE_F0) {
545     key_reg = FLASH_KEYR;
546   } else if (sl->flash_type == STLINK_FLASH_TYPE_F1_XL) {
547     key_reg = FLASH_KEYR;
548     key2_reg = FLASH_KEYR2;
549   } else if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
550     key_reg = FLASH_F4_KEYR;
551   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
552     key_reg = FLASH_F7_KEYR;
553   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
554     key_reg = get_stm32l0_flash_base(sl) + FLASH_PEKEYR_OFF;
555     flash_key1 = FLASH_L0_PEKEY1;
556     flash_key2 = FLASH_L0_PEKEY2;
557   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
558     key_reg = STM32L4_FLASH_KEYR;
559   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
560              sl->flash_type == STLINK_FLASH_TYPE_G4) {
561     key_reg = STM32Gx_FLASH_KEYR;
562   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
563     key_reg = STM32WB_FLASH_KEYR;
564   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
565     key_reg = FLASH_H7_KEYR1;
566     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
567       key2_reg = FLASH_H7_KEYR2;
568     }
569   } else {
570     ELOG("unsupported flash method, abort\n");
571     return;
572   }
573 
574   stlink_write_debug32(sl, key_reg, flash_key1);
575   stlink_write_debug32(sl, key_reg, flash_key2);
576 
577   if (key2_reg) {
578     stlink_write_debug32(sl, key2_reg, flash_key1);
579     stlink_write_debug32(sl, key2_reg, flash_key2);
580   }
581 }
582 
583 /* unlock flash if already locked */
unlock_flash_if(stlink_t * sl)584 static int unlock_flash_if(stlink_t *sl) {
585   if (is_flash_locked(sl)) {
586     unlock_flash(sl);
587 
588     if (is_flash_locked(sl)) {
589       WLOG("Failed to unlock flash!\n");
590       return (-1);
591     }
592   }
593 
594   DLOG("Successfully unlocked flash\n");
595   return (0);
596 }
597 
lock_flash(stlink_t * sl)598 static void lock_flash(stlink_t *sl) {
599   uint32_t cr_lock_shift, cr_reg, n, cr2_reg = 0;
600   uint32_t cr_mask = 0xffffffffu;
601 
602   if (sl->flash_type == STLINK_FLASH_TYPE_F0) {
603     cr_reg = FLASH_CR;
604     cr_lock_shift = FLASH_CR_LOCK;
605   } else if (sl->flash_type == STLINK_FLASH_TYPE_F1_XL) {
606     cr_reg = FLASH_CR;
607     cr2_reg = FLASH_CR2;
608     cr_lock_shift = FLASH_CR_LOCK;
609   } else if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
610     cr_reg = FLASH_F4_CR;
611     cr_lock_shift = FLASH_F4_CR_LOCK;
612   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
613     cr_reg = FLASH_F7_CR;
614     cr_lock_shift = FLASH_F7_CR_LOCK;
615   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
616     cr_reg = get_stm32l0_flash_base(sl) + FLASH_PECR_OFF;
617     cr_lock_shift = STM32L0_FLASH_PELOCK;
618   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
619     cr_reg = STM32L4_FLASH_CR;
620     cr_lock_shift = STM32L4_FLASH_CR_LOCK;
621   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
622              sl->flash_type == STLINK_FLASH_TYPE_G4) {
623     cr_reg = STM32Gx_FLASH_CR;
624     cr_lock_shift = STM32Gx_FLASH_CR_LOCK;
625   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
626     cr_reg = STM32WB_FLASH_CR;
627     cr_lock_shift = STM32WB_FLASH_CR_LOCK;
628   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
629     cr_reg = FLASH_H7_CR1;
630     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
631       cr2_reg = FLASH_H7_CR2;
632     }
633     cr_lock_shift = FLASH_H7_CR_LOCK;
634     cr_mask = ~(1u << FLASH_H7_CR_SER);
635   } else {
636     ELOG("unsupported flash method, abort\n");
637     return;
638   }
639 
640   stlink_read_debug32(sl, cr_reg, &n);
641   n &= cr_mask;
642   n |= (1u << cr_lock_shift);
643   stlink_write_debug32(sl, cr_reg, n);
644 
645   if (cr2_reg) {
646     n = read_flash_cr(sl, BANK_2) | (1u << cr_lock_shift);
647     stlink_write_debug32(sl, cr2_reg, n);
648   }
649 }
650 
is_flash_option_locked(stlink_t * sl)651 static bool is_flash_option_locked(stlink_t *sl) {
652   uint32_t optlock_shift, optcr_reg;
653   int active_bit_level = 1;
654   uint32_t n;
655 
656   switch (sl->flash_type) {
657   case STLINK_FLASH_TYPE_F0:
658   case STLINK_FLASH_TYPE_F1_XL:
659     optcr_reg = FLASH_CR;
660     optlock_shift = FLASH_CR_OPTWRE;
661     active_bit_level = 0; /* bit is "option write enable", not lock */
662     break;
663   case STLINK_FLASH_TYPE_F4:
664     optcr_reg = FLASH_F4_OPTCR;
665     optlock_shift = FLASH_F4_OPTCR_LOCK;
666     break;
667   case STLINK_FLASH_TYPE_F7:
668     optcr_reg = FLASH_F7_OPTCR;
669     optlock_shift = FLASH_F7_OPTCR_LOCK;
670     break;
671   case STLINK_FLASH_TYPE_L0:
672     optcr_reg = get_stm32l0_flash_base(sl) + FLASH_PECR_OFF;
673     optlock_shift = STM32L0_FLASH_OPTLOCK;
674     break;
675   case STLINK_FLASH_TYPE_L4:
676     optcr_reg = STM32L4_FLASH_CR;
677     optlock_shift = STM32L4_FLASH_CR_OPTLOCK;
678     break;
679   case STLINK_FLASH_TYPE_G0:
680   case STLINK_FLASH_TYPE_G4:
681     optcr_reg = STM32Gx_FLASH_CR;
682     optlock_shift = STM32Gx_FLASH_CR_OPTLOCK;
683     break;
684   case STLINK_FLASH_TYPE_WB:
685     optcr_reg = STM32WB_FLASH_CR;
686     optlock_shift = STM32WB_FLASH_CR_OPTLOCK;
687     break;
688   case STLINK_FLASH_TYPE_H7:
689     optcr_reg = FLASH_H7_OPTCR;
690     optlock_shift = FLASH_H7_OPTCR_OPTLOCK;
691     break;
692   default:
693     ELOG("unsupported flash method, abort\n");
694     return -1;
695   }
696 
697   stlink_read_debug32(sl, optcr_reg, &n);
698 
699   if (active_bit_level == 0) {
700     return (!(n & (1u << optlock_shift)));
701   }
702 
703   return (n & (1u << optlock_shift));
704 }
705 
lock_flash_option(stlink_t * sl)706 static int lock_flash_option(stlink_t *sl) {
707   uint32_t optlock_shift, optcr_reg, n, optcr2_reg = 0;
708   int active_bit_level = 1;
709 
710   switch (sl->flash_type) {
711   case STLINK_FLASH_TYPE_F0:
712   case STLINK_FLASH_TYPE_F1_XL:
713     optcr_reg = FLASH_CR;
714     optlock_shift = FLASH_CR_OPTWRE;
715     active_bit_level = 0;
716     break;
717   case STLINK_FLASH_TYPE_F4:
718     optcr_reg = FLASH_F4_OPTCR;
719     optlock_shift = FLASH_F4_OPTCR_LOCK;
720     break;
721   case STLINK_FLASH_TYPE_F7:
722     optcr_reg = FLASH_F7_OPTCR;
723     optlock_shift = FLASH_F7_OPTCR_LOCK;
724     break;
725   case STLINK_FLASH_TYPE_L0:
726     optcr_reg = get_stm32l0_flash_base(sl) + FLASH_PECR_OFF;
727     optlock_shift = STM32L0_FLASH_OPTLOCK;
728     break;
729   case STLINK_FLASH_TYPE_L4:
730     optcr_reg = STM32L4_FLASH_CR;
731     optlock_shift = STM32L4_FLASH_CR_OPTLOCK;
732     break;
733   case STLINK_FLASH_TYPE_G0:
734   case STLINK_FLASH_TYPE_G4:
735     optcr_reg = STM32Gx_FLASH_CR;
736     optlock_shift = STM32Gx_FLASH_CR_OPTLOCK;
737     break;
738   case STLINK_FLASH_TYPE_WB:
739     optcr_reg = STM32WB_FLASH_CR;
740     optlock_shift = STM32WB_FLASH_CR_OPTLOCK;
741     break;
742   case STLINK_FLASH_TYPE_H7:
743     optcr_reg = FLASH_H7_OPTCR;
744     optlock_shift = FLASH_H7_OPTCR_OPTLOCK;
745     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK)
746       optcr2_reg = FLASH_H7_OPTCR2;
747     break;
748   default:
749     ELOG("unsupported flash method, abort\n");
750     return -1;
751   }
752 
753   stlink_read_debug32(sl, optcr_reg, &n);
754 
755   if (active_bit_level == 0) {
756     n &= ~(1u << optlock_shift);
757   } else {
758     n |= (1u << optlock_shift);
759   }
760 
761   stlink_write_debug32(sl, optcr_reg, n);
762 
763   if (optcr2_reg) {
764     stlink_read_debug32(sl, optcr2_reg, &n);
765 
766     if (active_bit_level == 0) {
767       n &= ~(1u << optlock_shift);
768     } else {
769       n |= (1u << optlock_shift);
770     }
771 
772     stlink_write_debug32(sl, optcr2_reg, n);
773   }
774 
775   return (0);
776 }
777 
unlock_flash_option(stlink_t * sl)778 static int unlock_flash_option(stlink_t *sl) {
779   uint32_t optkey_reg, optkey2_reg = 0;
780   uint32_t optkey1 = FLASH_OPTKEY1;
781   uint32_t optkey2 = FLASH_OPTKEY2;
782 
783   switch (sl->flash_type) {
784   case STLINK_FLASH_TYPE_F0:
785   case STLINK_FLASH_TYPE_F1_XL:
786     optkey_reg = FLASH_OPTKEYR;
787     optkey1 = FLASH_F0_OPTKEY1;
788     optkey2 = FLASH_F0_OPTKEY2;
789     break;
790   case STLINK_FLASH_TYPE_F4:
791     optkey_reg = FLASH_F4_OPT_KEYR;
792     break;
793   case STLINK_FLASH_TYPE_F7:
794     optkey_reg = FLASH_F7_OPT_KEYR;
795     break;
796   case STLINK_FLASH_TYPE_L0:
797     optkey_reg = get_stm32l0_flash_base(sl) + FLASH_OPTKEYR_OFF;
798     optkey1 = FLASH_L0_OPTKEY1;
799     optkey2 = FLASH_L0_OPTKEY2;
800     break;
801   case STLINK_FLASH_TYPE_L4:
802     optkey_reg = STM32L4_FLASH_OPTKEYR;
803     break;
804   case STLINK_FLASH_TYPE_G0:
805   case STLINK_FLASH_TYPE_G4:
806     optkey_reg = STM32Gx_FLASH_OPTKEYR;
807     break;
808   case STLINK_FLASH_TYPE_WB:
809     optkey_reg = STM32WB_FLASH_OPT_KEYR;
810     break;
811   case STLINK_FLASH_TYPE_H7:
812     optkey_reg = FLASH_H7_OPT_KEYR;
813     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK)
814       optkey2_reg = FLASH_H7_OPT_KEYR2;
815     break;
816   default:
817     ELOG("unsupported flash method, abort\n");
818     return (-1);
819   }
820 
821   stlink_write_debug32(sl, optkey_reg, optkey1);
822   stlink_write_debug32(sl, optkey_reg, optkey2);
823 
824   if (optkey2_reg) {
825     stlink_write_debug32(sl, optkey2_reg, optkey1);
826     stlink_write_debug32(sl, optkey2_reg, optkey2);
827   }
828 
829   return (0);
830 }
831 
unlock_flash_option_if(stlink_t * sl)832 static int unlock_flash_option_if(stlink_t *sl) {
833   if (is_flash_option_locked(sl)) {
834     if (unlock_flash_option(sl)) {
835       ELOG("Could not unlock flash option!\n");
836       return (-1);
837     }
838 
839     if (is_flash_option_locked(sl)) {
840       ELOG("Failed to unlock flash option!\n");
841       return (-1);
842     }
843   }
844 
845   DLOG("Successfully unlocked flash option\n");
846   return (0);
847 }
848 
set_flash_cr_pg(stlink_t * sl,unsigned bank)849 static void set_flash_cr_pg(stlink_t *sl, unsigned bank) {
850   uint32_t cr_reg, x;
851 
852   x = read_flash_cr(sl, bank);
853 
854   if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
855     cr_reg = FLASH_F4_CR;
856     x |= 1 << FLASH_CR_PG;
857   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
858     cr_reg = FLASH_F7_CR;
859     x |= 1 << FLASH_CR_PG;
860   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
861     cr_reg = STM32L4_FLASH_CR;
862     x &= ~STM32L4_FLASH_CR_OPBITS;
863     x |= (1 << STM32L4_FLASH_CR_PG);
864   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
865              sl->flash_type == STLINK_FLASH_TYPE_G4) {
866     cr_reg = STM32Gx_FLASH_CR;
867     x |= (1 << FLASH_CR_PG);
868   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
869     cr_reg = STM32WB_FLASH_CR;
870     x |= (1 << FLASH_CR_PG);
871   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
872     cr_reg = (bank == BANK_1) ? FLASH_H7_CR1 : FLASH_H7_CR2;
873     x |= (1 << FLASH_H7_CR_PG);
874   } else {
875     cr_reg = FLASH_CR;
876     x = (1 << FLASH_CR_PG);
877   }
878 
879   stlink_write_debug32(sl, cr_reg, x);
880 }
881 
clear_flash_cr_pg(stlink_t * sl,unsigned bank)882 static void clear_flash_cr_pg(stlink_t *sl, unsigned bank) {
883   uint32_t cr_reg, n;
884   uint32_t bit = FLASH_CR_PG;
885 
886   if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
887     cr_reg = FLASH_F4_CR;
888   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
889     cr_reg = FLASH_F7_CR;
890   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
891     cr_reg = STM32L4_FLASH_CR;
892   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
893              sl->flash_type == STLINK_FLASH_TYPE_G4) {
894     cr_reg = STM32Gx_FLASH_CR;
895   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
896     cr_reg = STM32WB_FLASH_CR;
897   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
898     cr_reg = (bank == BANK_1) ? FLASH_H7_CR1 : FLASH_H7_CR2;
899     bit = FLASH_H7_CR_PG;
900   } else {
901     cr_reg = FLASH_CR;
902   }
903 
904   n = read_flash_cr(sl, bank) & ~(1 << bit);
905   stlink_write_debug32(sl, cr_reg, n);
906 }
907 
set_flash_cr_per(stlink_t * sl,unsigned bank)908 static void set_flash_cr_per(stlink_t *sl, unsigned bank) {
909   uint32_t cr_reg, val;
910 
911   if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
912       sl->flash_type == STLINK_FLASH_TYPE_G4) {
913     cr_reg = STM32Gx_FLASH_CR;
914   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
915     cr_reg = STM32WB_FLASH_CR;
916   } else {
917     cr_reg = (bank == BANK_1) ? FLASH_CR : FLASH_CR2;
918   }
919 
920   stlink_read_debug32(sl, cr_reg, &val);
921   val |= (1 << FLASH_CR_PER);
922   stlink_write_debug32(sl, cr_reg, val);
923 }
924 
clear_flash_cr_per(stlink_t * sl,unsigned bank)925 static void clear_flash_cr_per(stlink_t *sl, unsigned bank) {
926   uint32_t cr_reg;
927 
928   if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
929       sl->flash_type == STLINK_FLASH_TYPE_G4) {
930     cr_reg = STM32Gx_FLASH_CR;
931   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
932     cr_reg = STM32WB_FLASH_CR;
933   } else {
934     cr_reg = (bank == BANK_1) ? FLASH_CR : FLASH_CR2;
935   }
936 
937   const uint32_t n = read_flash_cr(sl, bank) & ~(1 << FLASH_CR_PER);
938   stlink_write_debug32(sl, cr_reg, n);
939 }
940 
set_flash_cr_mer(stlink_t * sl,bool v,unsigned bank)941 static void set_flash_cr_mer(stlink_t *sl, bool v, unsigned bank) {
942   uint32_t val, cr_reg, cr_mer, cr_pg;
943 
944   if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
945     cr_reg = FLASH_F4_CR;
946     cr_mer = 1 << FLASH_CR_MER;
947     cr_pg = 1 << FLASH_CR_PG;
948   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
949     cr_reg = FLASH_F7_CR;
950     cr_mer = 1 << FLASH_CR_MER;
951     cr_pg = 1 << FLASH_CR_PG;
952   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
953     cr_reg = STM32L4_FLASH_CR;
954     cr_mer = (1 << STM32L4_FLASH_CR_MER1) | (1 << STM32L4_FLASH_CR_MER2);
955     cr_pg = (1 << STM32L4_FLASH_CR_PG);
956   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
957              sl->flash_type == STLINK_FLASH_TYPE_G4) {
958     cr_reg = STM32Gx_FLASH_CR;
959     cr_mer = (1 << STM32Gx_FLASH_CR_MER1);
960 
961     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
962       cr_mer |= (1 << STM32Gx_FLASH_CR_MER2);
963     }
964 
965     cr_pg = (1 << FLASH_CR_PG);
966   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
967     cr_reg = STM32WB_FLASH_CR;
968     cr_mer = (1 << FLASH_CR_MER);
969     cr_pg = (1 << FLASH_CR_PG);
970   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
971     cr_reg = (bank == BANK_1) ? FLASH_H7_CR1 : FLASH_H7_CR2;
972     cr_mer = (1 << FLASH_H7_CR_BER);
973     cr_pg = (1 << FLASH_H7_CR_PG);
974   } else {
975     cr_reg = (bank == BANK_1) ? FLASH_CR : FLASH_CR2;
976     cr_mer = (1 << FLASH_CR_MER);
977     cr_pg = (1 << FLASH_CR_PG);
978   }
979 
980   stlink_read_debug32(sl, cr_reg, &val);
981 
982   if (val & cr_pg) {
983     // STM32F030 will drop MER bit if PG was set
984     val &= ~cr_pg;
985     stlink_write_debug32(sl, cr_reg, val);
986   }
987 
988   if (v) {
989     val |= cr_mer;
990   } else {
991     val &= ~cr_mer;
992   }
993 
994   stlink_write_debug32(sl, cr_reg, val);
995 }
996 
set_flash_cr_strt(stlink_t * sl,unsigned bank)997 static void set_flash_cr_strt(stlink_t *sl, unsigned bank) {
998   uint32_t val, cr_reg, cr_strt;
999 
1000   if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
1001     cr_reg = FLASH_F4_CR;
1002     cr_strt = 1 << FLASH_F4_CR_STRT;
1003   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
1004     cr_reg = FLASH_F7_CR;
1005     cr_strt = 1 << FLASH_F7_CR_STRT;
1006   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
1007     cr_reg = STM32L4_FLASH_CR;
1008     cr_strt = (1 << STM32L4_FLASH_CR_STRT);
1009   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
1010              sl->flash_type == STLINK_FLASH_TYPE_G4) {
1011     cr_reg = STM32Gx_FLASH_CR;
1012     cr_strt = (1 << STM32Gx_FLASH_CR_STRT);
1013   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
1014     cr_reg = STM32WB_FLASH_CR;
1015     cr_strt = (1 << STM32WB_FLASH_CR_STRT);
1016   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
1017     cr_reg = (bank == BANK_1) ? FLASH_H7_CR1 : FLASH_H7_CR2;
1018     cr_strt = 1 << FLASH_H7_CR_START(sl->chip_id);
1019   } else {
1020     cr_reg = (bank == BANK_1) ? FLASH_CR : FLASH_CR2;
1021     cr_strt = (1 << FLASH_CR_STRT);
1022   }
1023 
1024   stlink_read_debug32(sl, cr_reg, &val);
1025   val |= cr_strt;
1026   stlink_write_debug32(sl, cr_reg, val);
1027 }
1028 
read_flash_sr(stlink_t * sl,unsigned bank)1029 static inline uint32_t read_flash_sr(stlink_t *sl, unsigned bank) {
1030   uint32_t res, sr_reg;
1031 
1032   if ((sl->flash_type == STLINK_FLASH_TYPE_F0) ||
1033       (sl->flash_type == STLINK_FLASH_TYPE_F1_XL)) {
1034     sr_reg = (bank == BANK_1) ? FLASH_SR : FLASH_SR2;
1035   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
1036     sr_reg = get_stm32l0_flash_base(sl) + FLASH_SR_OFF;
1037   } else if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
1038     sr_reg = FLASH_F4_SR;
1039   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
1040     sr_reg = FLASH_F7_SR;
1041   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
1042     sr_reg = STM32L4_FLASH_SR;
1043   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
1044              sl->flash_type == STLINK_FLASH_TYPE_G4) {
1045     sr_reg = STM32Gx_FLASH_SR;
1046   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
1047     sr_reg = STM32WB_FLASH_SR;
1048   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
1049     sr_reg = (bank == BANK_1) ? FLASH_H7_SR1 : FLASH_H7_SR2;
1050   } else {
1051     ELOG("method 'read_flash_sr' is unsupported\n");
1052     return (-1);
1053   }
1054 
1055   stlink_read_debug32(sl, sr_reg, &res);
1056   return (res);
1057 }
1058 
write_flash_sr(stlink_t * sl,unsigned bank,uint32_t val)1059 static inline int write_flash_sr(stlink_t *sl, unsigned bank, uint32_t val) {
1060   uint32_t sr_reg;
1061 
1062   if ((sl->flash_type == STLINK_FLASH_TYPE_F0) ||
1063       (sl->flash_type == STLINK_FLASH_TYPE_F1_XL)) {
1064     sr_reg = (bank == BANK_1) ? FLASH_SR : FLASH_SR2;
1065   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
1066     sr_reg = get_stm32l0_flash_base(sl) + FLASH_SR_OFF;
1067   } else if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
1068     sr_reg = FLASH_F4_SR;
1069   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
1070     sr_reg = FLASH_F7_SR;
1071   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
1072     sr_reg = STM32L4_FLASH_SR;
1073   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
1074              sl->flash_type == STLINK_FLASH_TYPE_G4) {
1075     sr_reg = STM32Gx_FLASH_SR;
1076   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
1077     sr_reg = STM32WB_FLASH_SR;
1078   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
1079     sr_reg = (bank == BANK_1) ? FLASH_H7_SR1 : FLASH_H7_SR2;
1080   } else {
1081     ELOG("method 'write_flash_sr' is unsupported\n");
1082     return (-1);
1083   }
1084 
1085   return stlink_write_debug32(sl, sr_reg, val);
1086 }
1087 
is_flash_busy(stlink_t * sl)1088 static inline unsigned int is_flash_busy(stlink_t *sl) {
1089   uint32_t sr_busy_shift;
1090   unsigned int res;
1091 
1092   if ((sl->flash_type == STLINK_FLASH_TYPE_F0) ||
1093       (sl->flash_type == STLINK_FLASH_TYPE_F1_XL) ||
1094       (sl->flash_type == STLINK_FLASH_TYPE_L0)) {
1095     sr_busy_shift = FLASH_SR_BSY;
1096   } else if (sl->flash_type == STLINK_FLASH_TYPE_F4) {
1097     sr_busy_shift = FLASH_F4_SR_BSY;
1098   } else if (sl->flash_type == STLINK_FLASH_TYPE_F7) {
1099     sr_busy_shift = FLASH_F7_SR_BSY;
1100   } else if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
1101     sr_busy_shift = STM32L4_FLASH_SR_BSY;
1102   } else if (sl->flash_type == STLINK_FLASH_TYPE_G0 ||
1103              sl->flash_type == STLINK_FLASH_TYPE_G4) {
1104     sr_busy_shift = STM32Gx_FLASH_SR_BSY;
1105   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
1106     sr_busy_shift = STM32WB_FLASH_SR_BSY;
1107   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
1108     sr_busy_shift = FLASH_H7_SR_QW;
1109   } else {
1110     ELOG("method 'is_flash_busy' is unsupported\n");
1111     return (-1);
1112   }
1113 
1114   res = read_flash_sr(sl, BANK_1) & (1 << sr_busy_shift);
1115 
1116   if (sl->flash_type == STLINK_FLASH_TYPE_F1_XL ||
1117       (sl->flash_type == STLINK_FLASH_TYPE_H7 &&
1118        sl->chip_flags & CHIP_F_HAS_DUAL_BANK)) {
1119     res |= read_flash_sr(sl, BANK_2) & (1 << sr_busy_shift);
1120   }
1121 
1122   return (res);
1123 }
1124 
wait_flash_busy(stlink_t * sl)1125 static void wait_flash_busy(stlink_t *sl) {
1126   // TODO: add some delays here
1127   while (is_flash_busy(sl))
1128     ;
1129 }
1130 
wait_flash_busy_progress(stlink_t * sl)1131 static void wait_flash_busy_progress(stlink_t *sl) {
1132   int i = 0;
1133   fprintf(stdout, "Mass erasing");
1134   fflush(stdout);
1135 
1136   while (is_flash_busy(sl)) {
1137     usleep(10000);
1138     i++;
1139 
1140     if (i % 100 == 0) {
1141       fprintf(stdout, ".");
1142       fflush(stdout);
1143     }
1144   }
1145 
1146   fprintf(stdout, "\n");
1147 }
1148 
clear_flash_error(stlink_t * sl)1149 static void clear_flash_error(stlink_t *sl) {
1150   switch (sl->flash_type) {
1151   case STLINK_FLASH_TYPE_F0:
1152     write_flash_sr(sl, BANK_1, FLASH_SR_ERROR_MASK);
1153     break;
1154   case STLINK_FLASH_TYPE_F4:
1155     write_flash_sr(sl, BANK_1, FLASH_F4_SR_ERROR_MASK);
1156     break;
1157   case STLINK_FLASH_TYPE_F7:
1158     write_flash_sr(sl, BANK_1, FLASH_F7_SR_ERROR_MASK);
1159     break;
1160   case STLINK_FLASH_TYPE_G0:
1161   case STLINK_FLASH_TYPE_G4:
1162     write_flash_sr(sl, BANK_1, STM32Gx_FLASH_SR_ERROR_MASK);
1163     break;
1164   case STLINK_FLASH_TYPE_L0:
1165     write_flash_sr(sl, BANK_1, STM32L0_FLASH_SR_ERROR_MASK);
1166     break;
1167   case STLINK_FLASH_TYPE_L4:
1168     write_flash_sr(sl, BANK_1, STM32L4_FLASH_SR_ERROR_MASK);
1169     break;
1170   case STLINK_FLASH_TYPE_H7:
1171     write_flash_sr(sl, BANK_1, FLASH_H7_SR_ERROR_MASK);
1172     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
1173       write_flash_sr(sl, BANK_2, FLASH_H7_SR_ERROR_MASK);
1174     }
1175     break;
1176   case STLINK_FLASH_TYPE_WB:
1177     write_flash_sr(sl, BANK_1, STM32WB_FLASH_SR_ERROR_MASK);
1178     break;
1179   default:
1180     break;
1181   }
1182 }
1183 
check_flash_error(stlink_t * sl)1184 static int check_flash_error(stlink_t *sl) {
1185   uint32_t res = 0;
1186   uint32_t WRPERR, PROGERR, PGAERR;
1187 
1188   WRPERR = PROGERR = PGAERR = 0;
1189 
1190   switch (sl->flash_type) {
1191   case STLINK_FLASH_TYPE_F0:
1192   case STLINK_FLASH_TYPE_F1_XL:
1193     res = read_flash_sr(sl, BANK_1) & FLASH_SR_ERROR_MASK;
1194     if (sl->flash_type == STLINK_FLASH_TYPE_F1_XL) {
1195       res |= read_flash_sr(sl, BANK_2) & FLASH_SR_ERROR_MASK;
1196     }
1197     WRPERR = (1 << FLASH_SR_WRPRT_ERR);
1198     PROGERR = (1 << FLASH_SR_PG_ERR);
1199     break;
1200   case STLINK_FLASH_TYPE_F4:
1201     res = read_flash_sr(sl, BANK_1) & FLASH_F4_SR_ERROR_MASK;
1202     WRPERR = (1 << FLASH_F4_SR_WRPERR);
1203     PGAERR = (1 << FLASH_F4_SR_PGAERR);
1204     break;
1205   case STLINK_FLASH_TYPE_F7:
1206     res = read_flash_sr(sl, BANK_1) & FLASH_F7_SR_ERROR_MASK;
1207     WRPERR = (1 << FLASH_F7_SR_WRP_ERR);
1208     PROGERR = (1 << FLASH_F7_SR_PGP_ERR);
1209     break;
1210   case STLINK_FLASH_TYPE_G0:
1211   case STLINK_FLASH_TYPE_G4:
1212     res = read_flash_sr(sl, BANK_1) & STM32Gx_FLASH_SR_ERROR_MASK;
1213     WRPERR = (1 << STM32Gx_FLASH_SR_WRPERR);
1214     PROGERR = (1 << STM32Gx_FLASH_SR_PROGERR);
1215     PGAERR = (1 << STM32Gx_FLASH_SR_PGAERR);
1216     break;
1217   case STLINK_FLASH_TYPE_L0:
1218     res = read_flash_sr(sl, BANK_1) & STM32L0_FLASH_SR_ERROR_MASK;
1219     WRPERR = (1 << STM32L0_FLASH_SR_WRPERR);
1220     PROGERR = (1 << STM32L0_FLASH_SR_NOTZEROERR);
1221     PGAERR = (1 << STM32L0_FLASH_SR_PGAERR);
1222     break;
1223   case STLINK_FLASH_TYPE_L4:
1224     res = read_flash_sr(sl, BANK_1) & STM32L4_FLASH_SR_ERROR_MASK;
1225     WRPERR = (1 << STM32L4_FLASH_SR_WRPERR);
1226     PROGERR = (1 << STM32L4_FLASH_SR_PROGERR);
1227     PGAERR = (1 << STM32L4_FLASH_SR_PGAERR);
1228     break;
1229   case STLINK_FLASH_TYPE_H7:
1230     res = read_flash_sr(sl, BANK_1) & FLASH_H7_SR_ERROR_MASK;
1231     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
1232       res |= read_flash_sr(sl, BANK_2) & FLASH_H7_SR_ERROR_MASK;
1233     }
1234     WRPERR = (1 << FLASH_H7_SR_WRPERR);
1235     break;
1236   case STLINK_FLASH_TYPE_WB:
1237     res = read_flash_sr(sl, BANK_1) & STM32WB_FLASH_SR_ERROR_MASK;
1238     WRPERR = (1 << STM32WB_FLASH_SR_WRPERR);
1239     PROGERR = (1 << STM32WB_FLASH_SR_PROGERR);
1240     PGAERR = (1 << STM32WB_FLASH_SR_PGAERR);
1241     break;
1242   default:
1243     break;
1244   }
1245 
1246   if (res) {
1247     if (WRPERR && (WRPERR & res) == WRPERR) {
1248       ELOG("Flash memory is write protected\n");
1249       res &= ~WRPERR;
1250     } else if (PROGERR && (PROGERR & res) == PROGERR) {
1251       ELOG("Flash memory contains a non-erased value\n");
1252       res &= ~PROGERR;
1253     } else if (PGAERR && (PGAERR & res) == PGAERR) {
1254       ELOG("Invalid flash address\n");
1255       res &= ~PGAERR;
1256     }
1257 
1258     if (res) {
1259       ELOG("Flash programming error: %#010x\n", res);
1260     }
1261     return (-1);
1262   }
1263 
1264   return (0);
1265 }
1266 
stop_wdg_in_debug(stlink_t * sl)1267 static void stop_wdg_in_debug(stlink_t *sl) {
1268   uint32_t dbgmcu_cr;
1269   uint32_t set;
1270   uint32_t value;
1271 
1272   switch (sl->flash_type) {
1273   case STLINK_FLASH_TYPE_F0:
1274   case STLINK_FLASH_TYPE_F1_XL:
1275   case STLINK_FLASH_TYPE_G4:
1276     dbgmcu_cr = STM32F0_DBGMCU_CR;
1277     set =
1278         (1 << STM32F0_DBGMCU_CR_IWDG_STOP) | (1 << STM32F0_DBGMCU_CR_WWDG_STOP);
1279     break;
1280   case STLINK_FLASH_TYPE_F4:
1281   case STLINK_FLASH_TYPE_F7:
1282   case STLINK_FLASH_TYPE_L4:
1283     dbgmcu_cr = STM32F4_DBGMCU_APB1FZR1;
1284     set = (1 << STM32F4_DBGMCU_APB1FZR1_IWDG_STOP) |
1285           (1 << STM32F4_DBGMCU_APB1FZR1_WWDG_STOP);
1286     break;
1287   case STLINK_FLASH_TYPE_L0:
1288   case STLINK_FLASH_TYPE_G0:
1289     dbgmcu_cr = STM32L0_DBGMCU_APB1_FZ;
1290     set = (1 << STM32L0_DBGMCU_APB1_FZ_IWDG_STOP) |
1291           (1 << STM32L0_DBGMCU_APB1_FZ_WWDG_STOP);
1292     break;
1293   case STLINK_FLASH_TYPE_H7:
1294     dbgmcu_cr = STM32H7_DBGMCU_APB1HFZ;
1295     set = (1 << STM32H7_DBGMCU_APB1HFZ_IWDG_STOP);
1296     break;
1297   case STLINK_FLASH_TYPE_WB:
1298     dbgmcu_cr = STM32WB_DBGMCU_APB1FZR1;
1299     set = (1 << STM32WB_DBGMCU_APB1FZR1_IWDG_STOP) |
1300           (1 << STM32WB_DBGMCU_APB1FZR1_WWDG_STOP);
1301     break;
1302   default:
1303     return;
1304   }
1305 
1306   if (!stlink_read_debug32(sl, dbgmcu_cr, &value)) {
1307     stlink_write_debug32(sl, dbgmcu_cr, value | set);
1308   }
1309 }
1310 
set_dma_state(stlink_t * sl,flash_loader_t * fl,int bckpRstr)1311 static void set_dma_state(stlink_t *sl, flash_loader_t *fl, int bckpRstr) {
1312   uint32_t rcc, rcc_dma_mask, value;
1313 
1314   rcc = rcc_dma_mask = value = 0;
1315 
1316   switch (sl->flash_type) {
1317   case STLINK_FLASH_TYPE_F0:
1318   case STLINK_FLASH_TYPE_F1_XL:
1319     rcc = STM32F1_RCC_AHBENR;
1320     rcc_dma_mask = STM32F1_RCC_DMAEN;
1321     break;
1322   case STLINK_FLASH_TYPE_F4:
1323   case STLINK_FLASH_TYPE_F7:
1324     rcc = STM32F4_RCC_AHB1ENR;
1325     rcc_dma_mask = STM32F4_RCC_DMAEN;
1326     break;
1327   case STLINK_FLASH_TYPE_G0:
1328     rcc = STM32G0_RCC_AHBENR;
1329     rcc_dma_mask = STM32G0_RCC_DMAEN;
1330     break;
1331   case STLINK_FLASH_TYPE_G4:
1332   case STLINK_FLASH_TYPE_L4:
1333     rcc = STM32G4_RCC_AHB1ENR;
1334     rcc_dma_mask = STM32G4_RCC_DMAEN;
1335     break;
1336   case STLINK_FLASH_TYPE_L0:
1337     rcc = STM32L0_RCC_AHBENR;
1338     rcc_dma_mask = STM32L0_RCC_DMAEN;
1339     break;
1340   case STLINK_FLASH_TYPE_H7:
1341     rcc = STM32H7_RCC_AHB1ENR;
1342     rcc_dma_mask = STM32H7_RCC_DMAEN;
1343     break;
1344   case STLINK_FLASH_TYPE_WB:
1345     rcc = STM32WB_RCC_AHB1ENR;
1346     rcc_dma_mask = STM32WB_RCC_DMAEN;
1347     break;
1348   default:
1349     return;
1350   }
1351 
1352   if (!stlink_read_debug32(sl, rcc, &value)) {
1353     if (bckpRstr) {
1354       value = (value & (~rcc_dma_mask)) | fl->rcc_dma_bkp;
1355     } else {
1356       fl->rcc_dma_bkp = value & rcc_dma_mask;
1357       value &= ~rcc_dma_mask;
1358     }
1359     stlink_write_debug32(sl, rcc, value);
1360   }
1361 }
1362 
write_flash_ar(stlink_t * sl,uint32_t n,unsigned bank)1363 static inline void write_flash_ar(stlink_t *sl, uint32_t n, unsigned bank) {
1364   stlink_write_debug32(sl, (bank == BANK_1) ? FLASH_AR : FLASH_AR2, n);
1365 }
1366 
write_flash_cr_psiz(stlink_t * sl,uint32_t n,unsigned bank)1367 static inline void write_flash_cr_psiz(stlink_t *sl, uint32_t n,
1368                                        unsigned bank) {
1369   uint32_t cr_reg, psize_shift;
1370   uint32_t x = read_flash_cr(sl, bank);
1371 
1372   if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
1373     cr_reg = (bank == BANK_1) ? FLASH_H7_CR1 : FLASH_H7_CR2;
1374     psize_shift = FLASH_H7_CR_PSIZE;
1375   } else {
1376     cr_reg = FLASH_F4_CR;
1377     psize_shift = 8;
1378   }
1379 
1380   x &= ~(0x03 << psize_shift);
1381   x |= (n << psize_shift);
1382 #if DEBUG_FLASH
1383   fprintf(stdout, "PSIZ:0x%x 0x%x\n", x, n);
1384 #endif
1385   stlink_write_debug32(sl, cr_reg, x);
1386 }
1387 
write_flash_cr_snb(stlink_t * sl,uint32_t n,unsigned bank)1388 static inline void write_flash_cr_snb(stlink_t *sl, uint32_t n, unsigned bank) {
1389   uint32_t cr_reg, snb_mask, snb_shift, ser_shift;
1390   uint32_t x = read_flash_cr(sl, bank);
1391 
1392   if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
1393     cr_reg = (bank == BANK_1) ? FLASH_H7_CR1 : FLASH_H7_CR2;
1394     snb_mask = FLASH_H7_CR_SNB_MASK;
1395     snb_shift = FLASH_H7_CR_SNB;
1396     ser_shift = FLASH_H7_CR_SER;
1397   } else {
1398     cr_reg = FLASH_F4_CR;
1399     snb_mask = FLASH_F4_CR_SNB_MASK;
1400     snb_shift = FLASH_F4_CR_SNB;
1401     ser_shift = FLASH_F4_CR_SER;
1402   }
1403 
1404   x &= ~snb_mask;
1405   x |= (n << snb_shift);
1406   x |= (1 << ser_shift);
1407 #if DEBUG_FLASH
1408   fprintf(stdout, "SNB:0x%x 0x%x\n", x, n);
1409 #endif
1410   stlink_write_debug32(sl, cr_reg, x);
1411 }
1412 
write_flash_cr_bker_pnb(stlink_t * sl,uint32_t n)1413 static inline void write_flash_cr_bker_pnb(stlink_t *sl, uint32_t n) {
1414   stlink_write_debug32(sl, STM32L4_FLASH_SR,
1415                        0xFFFFFFFF & ~(1 << STM32L4_FLASH_SR_BSY));
1416   uint32_t x = read_flash_cr(sl, BANK_1);
1417   x &= ~STM32L4_FLASH_CR_OPBITS;
1418   x &= ~STM32L4_FLASH_CR_PAGEMASK;
1419   x &= ~(1 << STM32L4_FLASH_CR_MER1);
1420   x &= ~(1 << STM32L4_FLASH_CR_MER2);
1421   x |= (n << STM32L4_FLASH_CR_PNB);
1422   x |= (uint32_t)(1lu << STM32L4_FLASH_CR_PER);
1423 #if DEBUG_FLASH
1424   fprintf(stdout, "BKER:PNB:0x%x 0x%x\n", x, n);
1425 #endif
1426   stlink_write_debug32(sl, STM32L4_FLASH_CR, x);
1427 }
1428 
1429 // Delegates to the backends...
1430 
stlink_close(stlink_t * sl)1431 void stlink_close(stlink_t *sl) {
1432   DLOG("*** stlink_close ***\n");
1433 
1434   if (!sl) {
1435     return;
1436   }
1437 
1438   sl->backend->close(sl);
1439   free(sl);
1440 }
1441 
stlink_exit_debug_mode(stlink_t * sl)1442 int stlink_exit_debug_mode(stlink_t *sl) {
1443   int ret;
1444 
1445   DLOG("*** stlink_exit_debug_mode ***\n");
1446   ret = stlink_write_debug32(sl, STLINK_REG_DHCSR, STLINK_REG_DHCSR_DBGKEY);
1447 
1448   if (ret == -1) {
1449     return (ret);
1450   }
1451 
1452   return (sl->backend->exit_debug_mode(sl));
1453 }
1454 
stlink_enter_swd_mode(stlink_t * sl)1455 int stlink_enter_swd_mode(stlink_t *sl) {
1456   DLOG("*** stlink_enter_swd_mode ***\n");
1457   return (sl->backend->enter_swd_mode(sl));
1458 }
1459 
1460 // Force the core into the debug mode -> halted state.
stlink_force_debug(stlink_t * sl)1461 int stlink_force_debug(stlink_t *sl) {
1462   DLOG("*** stlink_force_debug_mode ***\n");
1463   int res = sl->backend->force_debug(sl);
1464   // Stop the watchdogs in the halted state for suppress target reboot
1465   stop_wdg_in_debug(sl);
1466   return (res);
1467 }
1468 
stlink_exit_dfu_mode(stlink_t * sl)1469 int stlink_exit_dfu_mode(stlink_t *sl) {
1470   DLOG("*** stlink_exit_dfu_mode ***\n");
1471   return (sl->backend->exit_dfu_mode(sl));
1472 }
1473 
stlink_core_id(stlink_t * sl)1474 int stlink_core_id(stlink_t *sl) {
1475   int ret;
1476 
1477   DLOG("*** stlink_core_id ***\n");
1478   ret = sl->backend->core_id(sl);
1479 
1480   if (ret == -1) {
1481     ELOG("Failed to read core_id\n");
1482     return (ret);
1483   }
1484 
1485   if (sl->verbose > 2) {
1486     stlink_print_data(sl);
1487   }
1488 
1489   DLOG("core_id = 0x%08x\n", sl->core_id);
1490   return (ret);
1491 }
1492 
1493 // stlink_chip_id() is called by stlink_load_device_params()
1494 // do not call this procedure directly.
stlink_chip_id(stlink_t * sl,uint32_t * chip_id)1495 int stlink_chip_id(stlink_t *sl, uint32_t *chip_id) {
1496   int ret;
1497   cortex_m3_cpuid_t cpu_id;
1498 
1499   // Read the CPU ID to determine where to read the core id
1500   if (stlink_cpu_id(sl, &cpu_id) ||
1501       cpu_id.implementer_id != STLINK_REG_CMx_CPUID_IMPL_ARM) {
1502     ELOG("Can not connect to target. Please use \'connect under reset\' and "
1503          "try again\n");
1504     return -1;
1505   }
1506 
1507   /*
1508    * the chip_id register in the reference manual have
1509    * DBGMCU_IDCODE / DBG_IDCODE name
1510    *
1511    */
1512 
1513   if ((sl->core_id == STM32H7_CORE_ID || sl->core_id == STM32H7_CORE_ID_JTAG) &&
1514       cpu_id.part == STLINK_REG_CMx_CPUID_PARTNO_CM7) {
1515     // STM32H7 chipid in 0x5c001000 (RM0433 pg3189)
1516     ret = stlink_read_debug32(sl, 0x5c001000, chip_id);
1517   } else if (cpu_id.part == STLINK_REG_CMx_CPUID_PARTNO_CM0 ||
1518              cpu_id.part == STLINK_REG_CMx_CPUID_PARTNO_CM0P) {
1519     // STM32F0 (RM0091, pg914; RM0360, pg713)
1520     // STM32L0 (RM0377, pg813; RM0367, pg915; RM0376, pg917)
1521     // STM32G0 (RM0444, pg1367)
1522     ret = stlink_read_debug32(sl, 0x40015800, chip_id);
1523   } else if (cpu_id.part == STLINK_REG_CMx_CPUID_PARTNO_CM33) {
1524     // STM32L5 (RM0438, pg2157)
1525     ret = stlink_read_debug32(sl, 0xE0044000, chip_id);
1526   } else /* СM3, СM4, CM7 */ {
1527     // default chipid address
1528 
1529     // STM32F1 (RM0008, pg1087; RM0041, pg681)
1530     // STM32F2 (RM0033, pg1326)
1531     // STM32F3 (RM0316, pg1095; RM0313, pg874)
1532     // STM32F7 (RM0385, pg1676; RM0410, pg1912)
1533     // STM32L1 (RM0038, pg861)
1534     // STM32L4 (RM0351, pg1840; RM0394, pg1560)
1535     // STM32G4 (RM0440, pg2086)
1536     // STM32WB (RM0434, pg1406)
1537     ret = stlink_read_debug32(sl, 0xE0042000, chip_id);
1538   }
1539 
1540   if (ret || !(*chip_id)) {
1541     *chip_id = 0;
1542     ELOG("Could not find chip id!\n");
1543   } else {
1544     *chip_id = (*chip_id) & 0xfff;
1545 
1546     // Fix chip_id for F4 rev A errata, read CPU ID, as CoreID is the same for
1547     // F2/F4
1548     if (*chip_id == 0x411 && cpu_id.part == STLINK_REG_CMx_CPUID_PARTNO_CM4) {
1549       *chip_id = 0x413;
1550     }
1551   }
1552 
1553   return (ret);
1554 }
1555 
1556 /**
1557  * Cortex M tech ref manual, CPUID register description
1558  * @param sl stlink context
1559  * @param cpuid pointer to the result object
1560  */
stlink_cpu_id(stlink_t * sl,cortex_m3_cpuid_t * cpuid)1561 int stlink_cpu_id(stlink_t *sl, cortex_m3_cpuid_t *cpuid) {
1562   uint32_t raw;
1563 
1564   if (stlink_read_debug32(sl, STLINK_REG_CM3_CPUID, &raw)) {
1565     cpuid->implementer_id = 0;
1566     cpuid->variant = 0;
1567     cpuid->part = 0;
1568     cpuid->revision = 0;
1569     return (-1);
1570   }
1571 
1572   cpuid->implementer_id = (raw >> 24) & 0x7f;
1573   cpuid->variant = (raw >> 20) & 0xf;
1574   cpuid->part = (raw >> 4) & 0xfff;
1575   cpuid->revision = raw & 0xf;
1576   return (0);
1577 }
1578 
1579 /**
1580  * Reads and decodes the flash parameters, as dynamically as possible
1581  * @param sl
1582  * @return 0 for success, or -1 for unsupported core type.
1583  */
stlink_load_device_params(stlink_t * sl)1584 int stlink_load_device_params(stlink_t *sl) {
1585   // This seems to normally work so is unnecessary info for a normal user.
1586   // Demoted to debug. -- REW
1587   DLOG("Loading device parameters....\n");
1588   const struct stlink_chipid_params *params = NULL;
1589   stlink_core_id(sl);
1590   uint32_t flash_size;
1591 
1592   if (stlink_chip_id(sl, &sl->chip_id)) {
1593     return (-1);
1594   }
1595 
1596   params = stlink_chipid_get_params(sl->chip_id);
1597 
1598   if (params == NULL) {
1599     WLOG("unknown chip id! %#x\n", sl->chip_id);
1600     return (-1);
1601   }
1602 
1603   if (params->flash_type == STLINK_FLASH_TYPE_UNKNOWN) {
1604     WLOG("Invalid flash type, please check device declaration\n");
1605     sl->flash_size = 0;
1606     return (0);
1607   }
1608 
1609   // These are fixed...
1610   sl->flash_base = STM32_FLASH_BASE;
1611   sl->sram_base = STM32_SRAM_BASE;
1612   stlink_read_debug32(sl, (params->flash_size_reg) & ~3, &flash_size);
1613 
1614   if (params->flash_size_reg & 2) {
1615     flash_size = flash_size >> 16;
1616   }
1617 
1618   flash_size = flash_size & 0xffff;
1619 
1620   if ((sl->chip_id == STLINK_CHIPID_STM32_L1_MEDIUM ||
1621        sl->chip_id == STLINK_CHIPID_STM32_F1_VL_MEDIUM_LOW ||
1622        sl->chip_id == STLINK_CHIPID_STM32_L1_MEDIUM_PLUS) &&
1623       (flash_size == 0)) {
1624     sl->flash_size = 128 * 1024;
1625   } else if (sl->chip_id == STLINK_CHIPID_STM32_L1_CAT2) {
1626     sl->flash_size = (flash_size & 0xff) * 1024;
1627   } else if ((sl->chip_id & 0xFFF) == STLINK_CHIPID_STM32_L1_HIGH) {
1628     // 0 is 384k and 1 is 256k
1629     if (flash_size == 0) {
1630       sl->flash_size = 384 * 1024;
1631     } else {
1632       sl->flash_size = 256 * 1024;
1633     }
1634   } else {
1635     sl->flash_size = flash_size * 1024;
1636   }
1637 
1638   sl->flash_type = params->flash_type;
1639   sl->flash_pgsz = params->flash_pagesize;
1640   sl->sram_size = params->sram_size;
1641   sl->sys_base = params->bootrom_base;
1642   sl->sys_size = params->bootrom_size;
1643   sl->option_base = params->option_base;
1644   sl->option_size = params->option_size;
1645   sl->chip_flags = params->flags;
1646 
1647   // medium and low devices have the same chipid. ram size depends on flash
1648   // size. STM32F100xx datasheet Doc ID 16455 Table 2
1649   if (sl->chip_id == STLINK_CHIPID_STM32_F1_VL_MEDIUM_LOW &&
1650       sl->flash_size < 64 * 1024) {
1651     sl->sram_size = 0x1000;
1652   }
1653 
1654   if (sl->chip_id == STLINK_CHIPID_STM32_G4_CAT3) {
1655     uint32_t flash_optr;
1656     stlink_read_debug32(sl, STM32Gx_FLASH_OPTR, &flash_optr);
1657 
1658     if (!(flash_optr & (1 << STM32G4_FLASH_OPTR_DBANK))) {
1659       sl->flash_pgsz <<= 1;
1660     }
1661   }
1662 
1663   // H7 devices with small flash has one bank
1664   if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK &&
1665       sl->flash_type == STLINK_FLASH_TYPE_H7) {
1666     if ((flash_size / sl->flash_pgsz) <= 1)
1667       sl->chip_flags &= ~CHIP_F_HAS_DUAL_BANK;
1668   }
1669 
1670   ILOG("%s: %u KiB SRAM, %u KiB flash in at least %u %s pages.\n",
1671        params->description, (unsigned)(sl->sram_size / 1024),
1672        (unsigned)(sl->flash_size / 1024),
1673        (sl->flash_pgsz < 1024) ? (unsigned)(sl->flash_pgsz)
1674                                : (unsigned)(sl->flash_pgsz / 1024),
1675        (sl->flash_pgsz < 1024) ? "byte" : "KiB");
1676 
1677   return (0);
1678 }
1679 
stlink_jtag_reset(stlink_t * sl,int value)1680 int stlink_jtag_reset(stlink_t *sl, int value) {
1681   DLOG("*** stlink_jtag_reset ***\n");
1682   return (sl->backend->jtag_reset(sl, value));
1683 }
1684 
stlink_soft_reset(stlink_t * sl,int halt_on_reset)1685 int stlink_soft_reset(stlink_t *sl, int halt_on_reset) {
1686   int ret;
1687   unsigned timeout;
1688   uint32_t dhcsr, dfsr;
1689 
1690   DLOG("*** stlink_soft_reset %s***\n", halt_on_reset ? "(halt) " : "");
1691 
1692   // halt core and enable debugging (if not already done)
1693   // C_DEBUGEN is required to Halt on reset (DDI0337E, p. 10-6)
1694   stlink_write_debug32(sl, STLINK_REG_DHCSR,
1695                        STLINK_REG_DHCSR_DBGKEY | STLINK_REG_DHCSR_C_HALT |
1696                            STLINK_REG_DHCSR_C_DEBUGEN);
1697 
1698   // enable Halt on reset by set VC_CORERESET and TRCENA (DDI0337E, p. 10-10)
1699   if (halt_on_reset) {
1700     stlink_write_debug32(
1701         sl, STLINK_REG_CM3_DEMCR,
1702         STLINK_REG_CM3_DEMCR_TRCENA | STLINK_REG_CM3_DEMCR_VC_HARDERR |
1703             STLINK_REG_CM3_DEMCR_VC_BUSERR | STLINK_REG_CM3_DEMCR_VC_CORERESET);
1704 
1705     // clear VCATCH in the DFSR register
1706     stlink_write_debug32(sl, STLINK_REG_DFSR, STLINK_REG_DFSR_VCATCH);
1707   } else {
1708     stlink_write_debug32(sl, STLINK_REG_CM3_DEMCR,
1709                          STLINK_REG_CM3_DEMCR_TRCENA |
1710                              STLINK_REG_CM3_DEMCR_VC_HARDERR |
1711                              STLINK_REG_CM3_DEMCR_VC_BUSERR);
1712   }
1713 
1714   // clear S_RESET_ST in the DHCSR register
1715   stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr);
1716 
1717   // soft reset (core reset) by SYSRESETREQ (DDI0337E, p. 8-23)
1718   ret = stlink_write_debug32(sl, STLINK_REG_AIRCR,
1719                              STLINK_REG_AIRCR_VECTKEY |
1720                                  STLINK_REG_AIRCR_SYSRESETREQ);
1721   if (ret) {
1722     ELOG("Soft reset failed: error write to AIRCR\n");
1723     return (ret);
1724   }
1725 
1726   // waiting for a reset within 500ms
1727   // DDI0337E, p. 10-4, Debug Halting Control and Status Register
1728   timeout = time_ms() + 500;
1729   while (time_ms() < timeout) {
1730     // DDI0337E, p. 10-4, Debug Halting Control and Status Register
1731     dhcsr = STLINK_REG_DHCSR_S_RESET_ST;
1732     stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr);
1733     if ((dhcsr & STLINK_REG_DHCSR_S_RESET_ST) == 0) {
1734       if (halt_on_reset) {
1735         // waiting halt by the SYSRESETREQ exception
1736         // DDI0403E, p. C1-699, Debug Fault Status Register
1737         dfsr = 0;
1738         stlink_read_debug32(sl, STLINK_REG_DFSR, &dfsr);
1739         if ((dfsr & STLINK_REG_DFSR_VCATCH) == 0) {
1740           continue;
1741         }
1742       }
1743       timeout = 0;
1744       break;
1745     }
1746   }
1747 
1748   // reset DFSR register. DFSR is power-on reset only (DDI0337H, p. 7-5)
1749   stlink_write_debug32(sl, STLINK_REG_DFSR, STLINK_REG_DFSR_CLEAR);
1750 
1751   if (timeout) {
1752     ELOG("Soft reset failed: timeout\n");
1753     return (-1);
1754   }
1755 
1756   return (0);
1757 }
1758 
stlink_reset(stlink_t * sl,enum reset_type type)1759 int stlink_reset(stlink_t *sl, enum reset_type type) {
1760   uint32_t dhcsr;
1761   unsigned timeout;
1762 
1763   DLOG("*** stlink_reset ***\n");
1764 
1765   if (type == RESET_AUTO) {
1766     // clear S_RESET_ST in DHCSR register for reset state detection
1767     stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr);
1768   }
1769 
1770   if (type == RESET_HARD || type == RESET_AUTO) {
1771     // hardware target reset
1772     if (sl->version.stlink_v > 1) {
1773       stlink_jtag_reset(sl, STLINK_JTAG_DRIVE_NRST_LOW);
1774       // minimum reset pulse duration of 20 us (RM0008, 8.1.2 Power reset)
1775       usleep(100);
1776       stlink_jtag_reset(sl, STLINK_JTAG_DRIVE_NRST_HIGH);
1777     }
1778     if (sl->backend->reset(sl)) {
1779       return (-1);
1780     }
1781     usleep(10000);
1782   }
1783 
1784   if (type == RESET_AUTO) {
1785     /* Check if the S_RESET_ST bit is set in DHCSR
1786      * This means that a reset has occurred
1787      * DDI0337E, p. 10-4, Debug Halting Control and Status Register */
1788 
1789     dhcsr = 0;
1790     stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr);
1791     if ((dhcsr & STLINK_REG_DHCSR_S_RESET_ST) == 0) {
1792       // reset not done yet
1793       // try reset through AIRCR so that NRST does not need to be connected
1794 
1795       WLOG("NRST is not connected\n");
1796       DLOG("Using reset through SYSRESETREQ\n");
1797       return stlink_soft_reset(sl, 0);
1798     }
1799 
1800     // waiting for reset the S_RESET_ST bit within 500ms
1801     timeout = time_ms() + 500;
1802     while (time_ms() < timeout) {
1803       dhcsr = STLINK_REG_DHCSR_S_RESET_ST;
1804       stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr);
1805       if ((dhcsr & STLINK_REG_DHCSR_S_RESET_ST) == 0)
1806         return (0);
1807     }
1808 
1809     return (-1);
1810   }
1811 
1812   if (type == RESET_SOFT || type == RESET_SOFT_AND_HALT) {
1813     return stlink_soft_reset(sl, (type == RESET_SOFT_AND_HALT));
1814   }
1815 
1816   return (0);
1817 }
1818 
stlink_run(stlink_t * sl,enum run_type type)1819 int stlink_run(stlink_t *sl, enum run_type type) {
1820   struct stlink_reg rr;
1821   DLOG("*** stlink_run ***\n");
1822 
1823   /* Make sure we are in Thumb mode
1824    * Cortex-M chips don't support ARM mode instructions
1825    * xPSR may be incorrect if the vector table has invalid data */
1826   stlink_read_reg(sl, 16, &rr);
1827   if ((rr.xpsr & (1 << 24)) == 0) {
1828     ILOG("Go to Thumb mode\n");
1829     stlink_write_reg(sl, rr.xpsr | (1 << 24), 16);
1830   }
1831 
1832   return (sl->backend->run(sl, type));
1833 }
1834 
stlink_set_swdclk(stlink_t * sl,int freq_khz)1835 int stlink_set_swdclk(stlink_t *sl, int freq_khz) {
1836   DLOG("*** set_swdclk ***\n");
1837   return (sl->backend->set_swdclk(sl, freq_khz));
1838 }
1839 
stlink_status(stlink_t * sl)1840 int stlink_status(stlink_t *sl) {
1841   int ret;
1842 
1843   DLOG("*** stlink_status ***\n");
1844   ret = sl->backend->status(sl);
1845   stlink_core_stat(sl);
1846   return (ret);
1847 }
1848 
1849 /**
1850  * Decode the version bits, originally from -sg, verified with usb
1851  * @param sl stlink context, assumed to contain valid data in the buffer
1852  * @param slv output parsed version object
1853  */
_parse_version(stlink_t * sl,stlink_version_t * slv)1854 void _parse_version(stlink_t *sl, stlink_version_t *slv) {
1855   sl->version.flags = 0;
1856 
1857   if (sl->version.stlink_v < 3) {
1858     uint32_t b0 = sl->q_buf[0]; // lsb
1859     uint32_t b1 = sl->q_buf[1];
1860     uint32_t b2 = sl->q_buf[2];
1861     uint32_t b3 = sl->q_buf[3];
1862     uint32_t b4 = sl->q_buf[4];
1863     uint32_t b5 = sl->q_buf[5]; // msb
1864 
1865     // b0 b1                       || b2 b3  | b4 b5
1866     // 4b        | 6b     | 6b     || 2B     | 2B
1867     // stlink_v  | jtag_v | swim_v || st_vid | stlink_pid
1868 
1869     slv->stlink_v = (b0 & 0xf0) >> 4;
1870     slv->jtag_v = ((b0 & 0x0f) << 2) | ((b1 & 0xc0) >> 6);
1871     slv->swim_v = b1 & 0x3f;
1872     slv->st_vid = (b3 << 8) | b2;
1873     slv->stlink_pid = (b5 << 8) | b4;
1874 
1875     // ST-LINK/V1 from J11 switch to api-v2 (and support SWD)
1876     if (slv->stlink_v == 1) {
1877       slv->jtag_api =
1878           slv->jtag_v > 11 ? STLINK_JTAG_API_V2 : STLINK_JTAG_API_V1;
1879     } else {
1880       slv->jtag_api = STLINK_JTAG_API_V2;
1881 
1882       // preferred API to get last R/W status from J15
1883       if (sl->version.jtag_v >= 15) {
1884         sl->version.flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1885       }
1886 
1887       if (sl->version.jtag_v >= 13) {
1888         sl->version.flags |= STLINK_F_HAS_TRACE;
1889         sl->max_trace_freq = STLINK_V2_MAX_TRACE_FREQUENCY;
1890       }
1891     }
1892   } else {
1893     // V3 uses different version format, for reference see OpenOCD source
1894     // (that was written from docs available from ST under NDA):
1895     // https://github.com/ntfreak/openocd/blob/a6dacdff58ef36fcdac00c53ec27f19de1fbce0d/src/jtag/drivers/stlink_usb.c#L965
1896     slv->stlink_v = sl->q_buf[0];
1897     slv->swim_v = sl->q_buf[1];
1898     slv->jtag_v = sl->q_buf[2];
1899     slv->st_vid = (uint32_t)((sl->q_buf[9] << 8) | sl->q_buf[8]);
1900     slv->stlink_pid = (uint32_t)((sl->q_buf[11] << 8) | sl->q_buf[10]);
1901     slv->jtag_api = STLINK_JTAG_API_V3;
1902     /* preferred API to get last R/W status */
1903     sl->version.flags |= STLINK_F_HAS_GETLASTRWSTATUS2;
1904     sl->version.flags |= STLINK_F_HAS_TRACE;
1905     sl->max_trace_freq = STLINK_V3_MAX_TRACE_FREQUENCY;
1906   }
1907 
1908   return;
1909 }
1910 
stlink_version(stlink_t * sl)1911 int stlink_version(stlink_t *sl) {
1912   DLOG("*** looking up stlink version\n");
1913 
1914   if (sl->backend->version(sl)) {
1915     return (-1);
1916   }
1917 
1918   _parse_version(sl, &sl->version);
1919 
1920   DLOG("st vid         = 0x%04x (expect 0x%04x)\n", sl->version.st_vid,
1921        STLINK_USB_VID_ST);
1922   DLOG("stlink pid     = 0x%04x\n", sl->version.stlink_pid);
1923   DLOG("stlink version = 0x%x\n", sl->version.stlink_v);
1924   DLOG("jtag version   = 0x%x\n", sl->version.jtag_v);
1925   DLOG("swim version   = 0x%x\n", sl->version.swim_v);
1926 
1927   if (sl->version.jtag_v == 0) {
1928     DLOG("    notice: the firmware doesn't support a jtag/swd interface\n");
1929   }
1930 
1931   if (sl->version.swim_v == 0) {
1932     DLOG("    notice: the firmware doesn't support a swim interface\n");
1933   }
1934 
1935   return (0);
1936 }
1937 
stlink_target_voltage(stlink_t * sl)1938 int stlink_target_voltage(stlink_t *sl) {
1939   int voltage = -1;
1940   DLOG("*** reading target voltage\n");
1941 
1942   if (sl->backend->target_voltage != NULL) {
1943     voltage = sl->backend->target_voltage(sl);
1944 
1945     if (voltage != -1) {
1946       DLOG("target voltage = %imV\n", voltage);
1947     } else {
1948       DLOG("error reading target voltage\n");
1949     }
1950   } else {
1951     DLOG("reading voltage not supported by backend\n");
1952   }
1953 
1954   return (voltage);
1955 }
1956 
stlink_read_debug32(stlink_t * sl,uint32_t addr,uint32_t * data)1957 int stlink_read_debug32(stlink_t *sl, uint32_t addr, uint32_t *data) {
1958   int ret;
1959 
1960   ret = sl->backend->read_debug32(sl, addr, data);
1961   if (!ret)
1962     DLOG("*** stlink_read_debug32 %#010x at %#010x\n", *data, addr);
1963 
1964   return (ret);
1965 }
1966 
stlink_write_debug32(stlink_t * sl,uint32_t addr,uint32_t data)1967 int stlink_write_debug32(stlink_t *sl, uint32_t addr, uint32_t data) {
1968   DLOG("*** stlink_write_debug32 %#010x to %#010x\n", data, addr);
1969   return sl->backend->write_debug32(sl, addr, data);
1970 }
1971 
stlink_write_mem32(stlink_t * sl,uint32_t addr,uint16_t len)1972 int stlink_write_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
1973   DLOG("*** stlink_write_mem32 %u bytes to %#x\n", len, addr);
1974 
1975   if (len % 4 != 0) {
1976     ELOG("Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
1977     return (-1);
1978   }
1979 
1980   return (sl->backend->write_mem32(sl, addr, len));
1981 }
1982 
stlink_read_mem32(stlink_t * sl,uint32_t addr,uint16_t len)1983 int stlink_read_mem32(stlink_t *sl, uint32_t addr, uint16_t len) {
1984   DLOG("*** stlink_read_mem32 ***\n");
1985 
1986   if (len % 4 != 0) { // !!! never ever: fw gives just wrong values
1987     ELOG("Data length doesn't have a 32 bit alignment: +%d byte.\n", len % 4);
1988     return (-1);
1989   }
1990 
1991   return (sl->backend->read_mem32(sl, addr, len));
1992 }
1993 
stlink_write_mem8(stlink_t * sl,uint32_t addr,uint16_t len)1994 int stlink_write_mem8(stlink_t *sl, uint32_t addr, uint16_t len) {
1995   DLOG("*** stlink_write_mem8 ***\n");
1996 
1997   if (len > 0x40) { // !!! never ever: Writing more then 0x40 bytes gives
1998                     // unexpected behaviour
1999     ELOG("Data length > 64: +%d byte.\n", len);
2000     return (-1);
2001   }
2002 
2003   return (sl->backend->write_mem8(sl, addr, len));
2004 }
2005 
stlink_read_all_regs(stlink_t * sl,struct stlink_reg * regp)2006 int stlink_read_all_regs(stlink_t *sl, struct stlink_reg *regp) {
2007   DLOG("*** stlink_read_all_regs ***\n");
2008   return (sl->backend->read_all_regs(sl, regp));
2009 }
2010 
stlink_read_all_unsupported_regs(stlink_t * sl,struct stlink_reg * regp)2011 int stlink_read_all_unsupported_regs(stlink_t *sl, struct stlink_reg *regp) {
2012   DLOG("*** stlink_read_all_unsupported_regs ***\n");
2013   return (sl->backend->read_all_unsupported_regs(sl, regp));
2014 }
2015 
stlink_write_reg(stlink_t * sl,uint32_t reg,int idx)2016 int stlink_write_reg(stlink_t *sl, uint32_t reg, int idx) {
2017   DLOG("*** stlink_write_reg\n");
2018   return (sl->backend->write_reg(sl, reg, idx));
2019 }
2020 
stlink_read_reg(stlink_t * sl,int r_idx,struct stlink_reg * regp)2021 int stlink_read_reg(stlink_t *sl, int r_idx, struct stlink_reg *regp) {
2022   DLOG("*** stlink_read_reg\n");
2023   DLOG(" (%d) ***\n", r_idx);
2024 
2025   if (r_idx > 20 || r_idx < 0) {
2026     fprintf(stderr, "Error: register index must be in [0..20]\n");
2027     return (-1);
2028   }
2029 
2030   return (sl->backend->read_reg(sl, r_idx, regp));
2031 }
2032 
stlink_read_unsupported_reg(stlink_t * sl,int r_idx,struct stlink_reg * regp)2033 int stlink_read_unsupported_reg(stlink_t *sl, int r_idx,
2034                                 struct stlink_reg *regp) {
2035   int r_convert;
2036 
2037   DLOG("*** stlink_read_unsupported_reg\n");
2038   DLOG(" (%d) ***\n", r_idx);
2039 
2040   /* Convert to values used by STLINK_REG_DCRSR */
2041   if (r_idx >= 0x1C &&
2042       r_idx <= 0x1F) { // primask, basepri, faultmask, or control
2043     r_convert = 0x14;
2044   } else if (r_idx == 0x40) { // FPSCR
2045     r_convert = 0x21;
2046   } else if (r_idx >= 0x20 && r_idx < 0x40) {
2047     r_convert = 0x40 + (r_idx - 0x20);
2048   } else {
2049     fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
2050     return (-1);
2051   }
2052 
2053   return (sl->backend->read_unsupported_reg(sl, r_convert, regp));
2054 }
2055 
stlink_write_unsupported_reg(stlink_t * sl,uint32_t val,int r_idx,struct stlink_reg * regp)2056 int stlink_write_unsupported_reg(stlink_t *sl, uint32_t val, int r_idx,
2057                                  struct stlink_reg *regp) {
2058   int r_convert;
2059 
2060   DLOG("*** stlink_write_unsupported_reg\n");
2061   DLOG(" (%d) ***\n", r_idx);
2062 
2063   /* Convert to values used by STLINK_REG_DCRSR */
2064   if (r_idx >= 0x1C &&
2065       r_idx <= 0x1F) {        /* primask, basepri, faultmask, or control */
2066     r_convert = r_idx;        // the backend function handles this
2067   } else if (r_idx == 0x40) { // FPSCR
2068     r_convert = 0x21;
2069   } else if (r_idx >= 0x20 && r_idx < 0x40) {
2070     r_convert = 0x40 + (r_idx - 0x20);
2071   } else {
2072     fprintf(stderr, "Error: register address must be in [0x1C..0x40]\n");
2073     return (-1);
2074   }
2075 
2076   return (sl->backend->write_unsupported_reg(sl, val, r_convert, regp));
2077 }
2078 
stlink_is_core_halted(stlink_t * sl)2079 bool stlink_is_core_halted(stlink_t *sl) {
2080   stlink_status(sl);
2081   return (sl->core_stat == TARGET_HALTED);
2082 }
2083 
stlink_step(stlink_t * sl)2084 int stlink_step(stlink_t *sl) {
2085   DLOG("*** stlink_step ***\n");
2086   return (sl->backend->step(sl));
2087 }
2088 
stlink_current_mode(stlink_t * sl)2089 int stlink_current_mode(stlink_t *sl) {
2090   int mode = sl->backend->current_mode(sl);
2091 
2092   switch (mode) {
2093   case STLINK_DEV_DFU_MODE:
2094     DLOG("stlink current mode: dfu\n");
2095     return (mode);
2096   case STLINK_DEV_DEBUG_MODE:
2097     DLOG("stlink current mode: debug (jtag or swd)\n");
2098     return (mode);
2099   case STLINK_DEV_MASS_MODE:
2100     DLOG("stlink current mode: mass\n");
2101     return (mode);
2102   }
2103 
2104   DLOG("stlink mode: unknown!\n");
2105   return (STLINK_DEV_UNKNOWN_MODE);
2106 }
2107 
stlink_trace_enable(stlink_t * sl,uint32_t frequency)2108 int stlink_trace_enable(stlink_t *sl, uint32_t frequency) {
2109   DLOG("*** stlink_trace_enable ***\n");
2110   return (sl->backend->trace_enable(sl, frequency));
2111 }
2112 
stlink_trace_disable(stlink_t * sl)2113 int stlink_trace_disable(stlink_t *sl) {
2114   DLOG("*** stlink_trace_disable ***\n");
2115   return (sl->backend->trace_disable(sl));
2116 }
2117 
stlink_trace_read(stlink_t * sl,uint8_t * buf,size_t size)2118 int stlink_trace_read(stlink_t *sl, uint8_t *buf, size_t size) {
2119   return (sl->backend->trace_read(sl, buf, size));
2120 }
2121 
2122 // End of delegates....  Common code below here...
2123 
2124 // same as above with entrypoint.
2125 
stlink_run_at(stlink_t * sl,stm32_addr_t addr)2126 void stlink_run_at(stlink_t *sl, stm32_addr_t addr) {
2127   stlink_write_reg(sl, addr, 15); /* pc register */
2128   stlink_run(sl, RUN_NORMAL);
2129 
2130   while (stlink_is_core_halted(sl)) {
2131     usleep(3000000);
2132   }
2133 }
2134 
2135 // this function is called by stlink_status()
2136 // do not call stlink_core_stat() directly, always use stlink_status()
stlink_core_stat(stlink_t * sl)2137 void stlink_core_stat(stlink_t *sl) {
2138   switch (sl->core_stat) {
2139   case TARGET_RUNNING:
2140     DLOG("  core status: running\n");
2141     return;
2142   case TARGET_HALTED:
2143     DLOG("  core status: halted\n");
2144     return;
2145   case TARGET_RESET:
2146     DLOG("  core status: reset\n");
2147     return;
2148   case TARGET_DEBUG_RUNNING:
2149     DLOG("  core status: debug running\n");
2150     return;
2151   default:
2152     DLOG("  core status: unknown\n");
2153   }
2154 }
2155 
stlink_print_data(stlink_t * sl)2156 void stlink_print_data(stlink_t *sl) {
2157   if (sl->q_len <= 0 || sl->verbose < UDEBUG) {
2158     return;
2159   }
2160 
2161   if (sl->verbose > 2) {
2162     DLOG("data_len = %d 0x%x\n", sl->q_len, sl->q_len);
2163   }
2164 
2165   for (int i = 0; i < sl->q_len; i++) {
2166     if (i % 16 == 0) {
2167       /*
2168       if (sl->q_data_dir == Q_DATA_OUT) {
2169           fprintf(stdout, "\n<- 0x%08x ", sl->q_addr + i);
2170       } else {
2171           fprintf(stdout, "\n-> 0x%08x ", sl->q_addr + i);
2172       }
2173       */
2174     }
2175     // DLOG(" %02x", (unsigned int) sl->q_buf[i]);
2176     fprintf(stderr, " %02x", (unsigned int)sl->q_buf[i]);
2177   }
2178   // DLOG("\n\n");
2179   fprintf(stderr, "\n");
2180 }
2181 
2182 /* Memory mapped file */
2183 typedef struct mapped_file {
2184   uint8_t *base;
2185   size_t len;
2186 } mapped_file_t;
2187 
2188 #define MAPPED_FILE_INITIALIZER                                                \
2189   { NULL, 0 }
2190 
map_file(mapped_file_t * mf,const char * path)2191 static int map_file(mapped_file_t *mf, const char *path) {
2192   int error = -1;
2193   struct stat st;
2194 
2195   const int fd = open(path, O_RDONLY | O_BINARY);
2196 
2197   if (fd == -1) {
2198     fprintf(stderr, "open(%s) == -1\n", path);
2199     return (-1);
2200   }
2201 
2202   if (fstat(fd, &st) == -1) {
2203     fprintf(stderr, "fstat(%s) == -1\n", path);
2204     goto on_error;
2205   }
2206 
2207   if (sizeof(st.st_size) != sizeof(size_t)) {
2208     // on 32 bit systems, check if there is an overflow
2209     if (st.st_size > (off_t)SSIZE_MAX) {
2210       fprintf(stderr, "mmap() size_t overflow for file %s\n", path);
2211       goto on_error;
2212     }
2213   }
2214 
2215   mf->base =
2216       (uint8_t *)mmap(NULL, (size_t)(st.st_size), PROT_READ, MAP_SHARED, fd, 0);
2217 
2218   if (mf->base == MAP_FAILED) {
2219     fprintf(stderr, "mmap() == MAP_FAILED for file %s\n", path);
2220     goto on_error;
2221   }
2222 
2223   mf->len = (size_t)st.st_size;
2224   error = 0; // success
2225 
2226 on_error:
2227   close(fd);
2228   return (error);
2229 }
2230 
unmap_file(mapped_file_t * mf)2231 static void unmap_file(mapped_file_t *mf) {
2232   munmap((void *)mf->base, mf->len);
2233   mf->base = (unsigned char *)MAP_FAILED;
2234   mf->len = 0;
2235 }
2236 
2237 /* Limit the block size to compare to 0x1800 as anything larger will stall the
2238  * STLINK2 Maybe STLINK V1 needs smaller value!
2239  */
check_file(stlink_t * sl,mapped_file_t * mf,stm32_addr_t addr)2240 static int check_file(stlink_t *sl, mapped_file_t *mf, stm32_addr_t addr) {
2241   size_t off;
2242   size_t n_cmp = sl->flash_pgsz;
2243 
2244   if (n_cmp > 0x1800) {
2245     n_cmp = 0x1800;
2246   }
2247 
2248   for (off = 0; off < mf->len; off += n_cmp) {
2249     size_t aligned_size;
2250 
2251     size_t cmp_size = n_cmp; // adjust last page size
2252 
2253     if ((off + n_cmp) > mf->len) {
2254       cmp_size = mf->len - off;
2255     }
2256 
2257     aligned_size = cmp_size;
2258 
2259     if (aligned_size & (4 - 1)) {
2260       aligned_size = (cmp_size + 4) & ~(4 - 1);
2261     }
2262 
2263     stlink_read_mem32(sl, addr + (uint32_t)off, aligned_size);
2264 
2265     if (memcmp(sl->q_buf, mf->base + off, cmp_size)) {
2266       return (-1);
2267     }
2268   }
2269 
2270   return (0);
2271 }
2272 
md5_calculate(mapped_file_t * mf)2273 static void md5_calculate(mapped_file_t *mf) {
2274   // calculate md5 checksum of given binary file
2275   Md5Context md5Context;
2276   MD5_HASH md5Hash;
2277   Md5Initialise(&md5Context);
2278   Md5Update(&md5Context, mf->base, (uint32_t)mf->len);
2279   Md5Finalise(&md5Context, &md5Hash);
2280   printf("md5 checksum: ");
2281 
2282   for (int i = 0; i < (int)sizeof(md5Hash); i++) {
2283     printf("%x", md5Hash.bytes[i]);
2284   }
2285 
2286   printf(", ");
2287 }
2288 
stlink_checksum(mapped_file_t * mp)2289 static void stlink_checksum(mapped_file_t *mp) {
2290   /* checksum that backward compatible with official ST tools */
2291   uint32_t sum = 0;
2292   uint8_t *mp_byte = (uint8_t *)mp->base;
2293 
2294   for (size_t i = 0; i < mp->len; ++i) {
2295     sum += mp_byte[i];
2296   }
2297 
2298   printf("stlink checksum: 0x%08x\n", sum);
2299 }
2300 
stlink_fwrite_finalize(stlink_t * sl,stm32_addr_t addr)2301 static void stlink_fwrite_finalize(stlink_t *sl, stm32_addr_t addr) {
2302   unsigned int val;
2303   // set stack
2304   stlink_read_debug32(sl, addr, &val);
2305   stlink_write_reg(sl, val, 13);
2306   // set PC to the reset routine
2307   stlink_read_debug32(sl, addr + 4, &val);
2308   stlink_write_reg(sl, val, 15);
2309   stlink_run(sl, RUN_NORMAL);
2310 }
2311 
stlink_mwrite_sram(stlink_t * sl,uint8_t * data,uint32_t length,stm32_addr_t addr)2312 int stlink_mwrite_sram(stlink_t *sl, uint8_t *data, uint32_t length,
2313                        stm32_addr_t addr) {
2314   // write the file in sram at addr
2315 
2316   int error = -1;
2317   size_t off;
2318   size_t len;
2319 
2320   // check addr range is inside the sram
2321   if (addr < sl->sram_base) {
2322     fprintf(stderr, "addr too low\n");
2323     goto on_error;
2324   } else if ((addr + length) < addr) {
2325     fprintf(stderr, "addr overruns\n");
2326     goto on_error;
2327   } else if ((addr + length) > (sl->sram_base + sl->sram_size)) {
2328     fprintf(stderr, "addr too high\n");
2329     goto on_error;
2330   } else if (addr & 3) {
2331     fprintf(stderr, "unaligned addr\n");
2332     goto on_error;
2333   }
2334 
2335   len = length;
2336 
2337   if (len & 3) {
2338     len -= len & 3;
2339   }
2340 
2341   // do the copy by 1kB blocks
2342   for (off = 0; off < len; off += 1024) {
2343     size_t size = 1024;
2344 
2345     if ((off + size) > len) {
2346       size = len - off;
2347     }
2348 
2349     memcpy(sl->q_buf, data + off, size);
2350 
2351     if (size & 3) {
2352       size += 2;
2353     } // round size if needed
2354 
2355     stlink_write_mem32(sl, addr + (uint32_t)off, size);
2356   }
2357 
2358   if (length > len) {
2359     memcpy(sl->q_buf, data + len, length - len);
2360     stlink_write_mem8(sl, addr + (uint32_t)len, length - len);
2361   }
2362 
2363   error = 0; // success
2364   stlink_fwrite_finalize(sl, addr);
2365 
2366 on_error:
2367   return (error);
2368 }
2369 
stlink_fwrite_sram(stlink_t * sl,const char * path,stm32_addr_t addr)2370 int stlink_fwrite_sram(stlink_t *sl, const char *path, stm32_addr_t addr) {
2371   // write the file in sram at addr
2372 
2373   int error = -1;
2374   size_t off;
2375   size_t len;
2376   mapped_file_t mf = MAPPED_FILE_INITIALIZER;
2377 
2378   if (map_file(&mf, path) == -1) {
2379     fprintf(stderr, "map_file() == -1\n");
2380     return (-1);
2381   }
2382 
2383   printf("file %s ", path);
2384   md5_calculate(&mf);
2385   stlink_checksum(&mf);
2386 
2387   // check if addr range is inside the SRAM
2388   if (addr < sl->sram_base) {
2389     fprintf(stderr, "addr too low\n");
2390     goto on_error;
2391   } else if ((addr + mf.len) < addr) {
2392     fprintf(stderr, "addr overruns\n");
2393     goto on_error;
2394   } else if ((addr + mf.len) > (sl->sram_base + sl->sram_size)) {
2395     fprintf(stderr, "addr too high\n");
2396     goto on_error;
2397   } else if (addr & 3) {
2398     fprintf(stderr, "unaligned addr\n");
2399     goto on_error;
2400   }
2401 
2402   len = mf.len;
2403 
2404   if (len & 3) {
2405     len -= len & 3;
2406   }
2407 
2408   // do the copy by 1kB blocks
2409   for (off = 0; off < len; off += 1024) {
2410     size_t size = 1024;
2411 
2412     if ((off + size) > len) {
2413       size = len - off;
2414     }
2415 
2416     memcpy(sl->q_buf, mf.base + off, size);
2417 
2418     if (size & 3) {
2419       size += 2;
2420     } // round size if needed
2421 
2422     stlink_write_mem32(sl, addr + (uint32_t)off, size);
2423   }
2424 
2425   if (mf.len > len) {
2426     memcpy(sl->q_buf, mf.base + len, mf.len - len);
2427     stlink_write_mem8(sl, addr + (uint32_t)len, mf.len - len);
2428   }
2429 
2430   // check the file has been written
2431   if (check_file(sl, &mf, addr) == -1) {
2432     fprintf(stderr, "check_file() == -1\n");
2433     goto on_error;
2434   }
2435 
2436   error = 0; // success
2437   stlink_fwrite_finalize(sl, addr);
2438 
2439 on_error:
2440   unmap_file(&mf);
2441   return (error);
2442 }
2443 
2444 typedef bool (*save_block_fn)(void *arg, uint8_t *block, ssize_t len);
2445 
stlink_read(stlink_t * sl,stm32_addr_t addr,size_t size,save_block_fn fn,void * fn_arg)2446 static int stlink_read(stlink_t *sl, stm32_addr_t addr, size_t size,
2447                        save_block_fn fn, void *fn_arg) {
2448 
2449   int error = -1;
2450 
2451   if (size < 1) {
2452     size = sl->flash_size;
2453   }
2454 
2455   if (size > sl->flash_size) {
2456     size = sl->flash_size;
2457   }
2458 
2459   size_t cmp_size = (sl->flash_pgsz > 0x1800) ? 0x1800 : sl->flash_pgsz;
2460 
2461   for (size_t off = 0; off < size; off += cmp_size) {
2462     size_t aligned_size;
2463 
2464     // adjust last page size
2465     if ((off + cmp_size) > size) {
2466       cmp_size = size - off;
2467     }
2468 
2469     aligned_size = cmp_size;
2470 
2471     if (aligned_size & (4 - 1)) {
2472       aligned_size = (cmp_size + 4) & ~(4 - 1);
2473     }
2474 
2475     stlink_read_mem32(sl, addr + (uint32_t)off, aligned_size);
2476 
2477     if (!fn(fn_arg, sl->q_buf, aligned_size)) {
2478       goto on_error;
2479     }
2480   }
2481 
2482   error = 0; // success
2483 
2484 on_error:
2485   return (error);
2486 }
2487 
2488 struct stlink_fread_worker_arg {
2489   int fd;
2490 };
2491 
stlink_fread_worker(void * arg,uint8_t * block,ssize_t len)2492 static bool stlink_fread_worker(void *arg, uint8_t *block, ssize_t len) {
2493   struct stlink_fread_worker_arg *the_arg =
2494       (struct stlink_fread_worker_arg *)arg;
2495 
2496   if (write(the_arg->fd, block, len) != len) {
2497     fprintf(stderr, "write() != aligned_size\n");
2498     return (false);
2499   } else {
2500     return (true);
2501   }
2502 }
2503 
2504 struct stlink_fread_ihex_worker_arg {
2505   FILE *file;
2506   uint32_t addr;
2507   uint32_t lba;
2508   uint8_t buf[16];
2509   uint8_t buf_pos;
2510 };
2511 
2512 static bool
stlink_fread_ihex_newsegment(struct stlink_fread_ihex_worker_arg * the_arg)2513 stlink_fread_ihex_newsegment(struct stlink_fread_ihex_worker_arg *the_arg) {
2514   uint32_t addr = the_arg->addr;
2515   uint8_t sum = 2 + 4 + (uint8_t)((addr & 0xFF000000) >> 24) +
2516                 (uint8_t)((addr & 0x00FF0000) >> 16);
2517 
2518   if (17 != fprintf(the_arg->file, ":02000004%04X%02X\r\n",
2519                     (addr & 0xFFFF0000) >> 16, (uint8_t)(0x100 - sum))) {
2520     return (false);
2521   }
2522 
2523   the_arg->lba = (addr & 0xFFFF0000);
2524   return (true);
2525 }
2526 
2527 static bool
stlink_fread_ihex_writeline(struct stlink_fread_ihex_worker_arg * the_arg)2528 stlink_fread_ihex_writeline(struct stlink_fread_ihex_worker_arg *the_arg) {
2529   uint8_t count = the_arg->buf_pos;
2530 
2531   if (count == 0) {
2532     return (true);
2533   }
2534 
2535   uint32_t addr = the_arg->addr;
2536 
2537   if (the_arg->lba != (addr & 0xFFFF0000)) { // segment changed
2538     if (!stlink_fread_ihex_newsegment(the_arg)) {
2539       return (false);
2540     }
2541   }
2542 
2543   uint8_t sum = count + (uint8_t)((addr & 0x0000FF00) >> 8) +
2544                 (uint8_t)(addr & 0x000000FF);
2545 
2546   if (9 != fprintf(the_arg->file, ":%02X%04X00", count, (addr & 0x0000FFFF))) {
2547     return (false);
2548   }
2549 
2550   for (uint8_t i = 0; i < count; ++i) {
2551     uint8_t b = the_arg->buf[i];
2552     sum += b;
2553 
2554     if (2 != fprintf(the_arg->file, "%02X", b)) {
2555       return (false);
2556     }
2557   }
2558 
2559   if (4 != fprintf(the_arg->file, "%02X\r\n", (uint8_t)(0x100 - sum))) {
2560     return (false);
2561   }
2562 
2563   the_arg->addr += count;
2564   the_arg->buf_pos = 0;
2565 
2566   return (true);
2567 }
2568 
stlink_fread_ihex_init(struct stlink_fread_ihex_worker_arg * the_arg,int fd,stm32_addr_t addr)2569 static bool stlink_fread_ihex_init(struct stlink_fread_ihex_worker_arg *the_arg,
2570                                    int fd, stm32_addr_t addr) {
2571   the_arg->file = fdopen(fd, "w");
2572   the_arg->addr = addr;
2573   the_arg->lba = 0;
2574   the_arg->buf_pos = 0;
2575 
2576   return (the_arg->file != NULL);
2577 }
2578 
stlink_fread_ihex_worker(void * arg,uint8_t * block,ssize_t len)2579 static bool stlink_fread_ihex_worker(void *arg, uint8_t *block, ssize_t len) {
2580   struct stlink_fread_ihex_worker_arg *the_arg =
2581       (struct stlink_fread_ihex_worker_arg *)arg;
2582 
2583   for (ssize_t i = 0; i < len; ++i) {
2584     if (the_arg->buf_pos == sizeof(the_arg->buf)) { // line is full
2585       if (!stlink_fread_ihex_writeline(the_arg)) {
2586         return (false);
2587       }
2588     }
2589 
2590     the_arg->buf[the_arg->buf_pos++] = block[i];
2591   }
2592 
2593   return (true);
2594 }
2595 
2596 static bool
stlink_fread_ihex_finalize(struct stlink_fread_ihex_worker_arg * the_arg)2597 stlink_fread_ihex_finalize(struct stlink_fread_ihex_worker_arg *the_arg) {
2598   if (!stlink_fread_ihex_writeline(the_arg)) {
2599     return (false);
2600   }
2601 
2602   // FIXME: do we need the Start Linear Address?
2603 
2604   if (13 != fprintf(the_arg->file, ":00000001FF\r\n")) { // EoF
2605     return (false);
2606   }
2607 
2608   return (0 == fclose(the_arg->file));
2609 }
2610 
stlink_fread(stlink_t * sl,const char * path,bool is_ihex,stm32_addr_t addr,size_t size)2611 int stlink_fread(stlink_t *sl, const char *path, bool is_ihex,
2612                  stm32_addr_t addr, size_t size) {
2613   // read size bytes from addr to file
2614   ILOG("read from address %#010x size %u\n", addr, (unsigned)size);
2615 
2616   int error;
2617   int fd = open(path, O_RDWR | O_TRUNC | O_CREAT | O_BINARY, 00700);
2618 
2619   if (fd == -1) {
2620     fprintf(stderr, "open(%s) == -1\n", path);
2621     return (-1);
2622   }
2623 
2624   if (is_ihex) {
2625     struct stlink_fread_ihex_worker_arg arg;
2626 
2627     if (stlink_fread_ihex_init(&arg, fd, addr)) {
2628       error = stlink_read(sl, addr, size, &stlink_fread_ihex_worker, &arg);
2629 
2630       if (!stlink_fread_ihex_finalize(&arg)) {
2631         error = -1;
2632       }
2633     } else {
2634       error = -1;
2635     }
2636   } else {
2637     struct stlink_fread_worker_arg arg = {fd};
2638     error = stlink_read(sl, addr, size, &stlink_fread_worker, &arg);
2639   }
2640 
2641   close(fd);
2642   return (error);
2643 }
2644 
write_buffer_to_sram(stlink_t * sl,flash_loader_t * fl,const uint8_t * buf,size_t size)2645 int write_buffer_to_sram(stlink_t *sl, flash_loader_t *fl, const uint8_t *buf,
2646                          size_t size) {
2647   // write the buffer right after the loader
2648   size_t chunk = size & ~0x3;
2649   size_t rem = size & 0x3;
2650 
2651   if (chunk) {
2652     memcpy(sl->q_buf, buf, chunk);
2653     stlink_write_mem32(sl, fl->buf_addr, chunk);
2654   }
2655 
2656   if (rem) {
2657     memcpy(sl->q_buf, buf + chunk, rem);
2658     stlink_write_mem8(sl, (fl->buf_addr) + (uint32_t)chunk, rem);
2659   }
2660 
2661   return (0);
2662 }
2663 
calculate_F4_sectornum(uint32_t flashaddr)2664 uint32_t calculate_F4_sectornum(uint32_t flashaddr) {
2665   uint32_t offset = 0;
2666   flashaddr &= ~STM32_FLASH_BASE; // page now holding the actual flash address
2667 
2668   if (flashaddr >= 0x100000) {
2669     offset = 12;
2670     flashaddr -= 0x100000;
2671   }
2672 
2673   if (flashaddr < 0x4000) {
2674     return (offset + 0);
2675   } else if (flashaddr < 0x8000) {
2676     return (offset + 1);
2677   } else if (flashaddr < 0xc000) {
2678     return (offset + 2);
2679   } else if (flashaddr < 0x10000) {
2680     return (offset + 3);
2681   } else if (flashaddr < 0x20000) {
2682     return (offset + 4);
2683   } else {
2684     return (offset + (flashaddr / 0x20000) + 4);
2685   }
2686 }
2687 
calculate_F7_sectornum(uint32_t flashaddr)2688 uint32_t calculate_F7_sectornum(uint32_t flashaddr) {
2689   flashaddr &= ~STM32_FLASH_BASE; // Page now holding the actual flash address
2690 
2691   if (flashaddr < 0x20000) {
2692     return (flashaddr / 0x8000);
2693   } else if (flashaddr < 0x40000) {
2694     return (4);
2695   } else {
2696     return ((flashaddr / 0x40000) + 4);
2697   }
2698 }
2699 
calculate_H7_sectornum(stlink_t * sl,uint32_t flashaddr,unsigned bank)2700 uint32_t calculate_H7_sectornum(stlink_t *sl, uint32_t flashaddr,
2701                                 unsigned bank) {
2702   flashaddr &=
2703       ~((bank == BANK_1)
2704             ? STM32_FLASH_BASE
2705             : STM32_H7_FLASH_BANK2_BASE); // sector holding the flash address
2706   return (flashaddr / sl->flash_pgsz);
2707 }
2708 
2709 // returns BKER:PNB for the given page address
calculate_L4_page(stlink_t * sl,uint32_t flashaddr)2710 uint32_t calculate_L4_page(stlink_t *sl, uint32_t flashaddr) {
2711   uint32_t bker = 0;
2712   uint32_t flashopt;
2713   stlink_read_debug32(sl, STM32L4_FLASH_OPTR, &flashopt);
2714   flashaddr -= STM32_FLASH_BASE;
2715 
2716   if (sl->chip_id == STLINK_CHIPID_STM32_L4 ||
2717       sl->chip_id == STLINK_CHIPID_STM32_L496X ||
2718       sl->chip_id == STLINK_CHIPID_STM32_L4RX) {
2719     // this chip use dual banked flash
2720     if (flashopt & (uint32_t)(1lu << STM32L4_FLASH_OPTR_DUALBANK)) {
2721       uint32_t banksize = (uint32_t)sl->flash_size / 2;
2722 
2723       if (flashaddr >= banksize) {
2724         flashaddr -= banksize;
2725         bker = 0x100;
2726       }
2727     }
2728   }
2729 
2730   // For 1MB chips without the dual-bank option set, the page address will
2731   // overflow into the BKER bit, which gives us the correct bank:page value.
2732   return (bker | flashaddr / (uint32_t)sl->flash_pgsz);
2733 }
2734 
stlink_calculate_pagesize(stlink_t * sl,uint32_t flashaddr)2735 uint32_t stlink_calculate_pagesize(stlink_t *sl, uint32_t flashaddr) {
2736   if ((sl->chip_id == STLINK_CHIPID_STM32_F2) ||
2737       (sl->chip_id == STLINK_CHIPID_STM32_F4) ||
2738       (sl->chip_id == STLINK_CHIPID_STM32_F4_DE) ||
2739       (sl->chip_id == STLINK_CHIPID_STM32_F4_LP) ||
2740       (sl->chip_id == STLINK_CHIPID_STM32_F4_HD) ||
2741       (sl->chip_id == STLINK_CHIPID_STM32_F411RE) ||
2742       (sl->chip_id == STLINK_CHIPID_STM32_F446) ||
2743       (sl->chip_id == STLINK_CHIPID_STM32_F4_DSI) ||
2744       (sl->chip_id == STLINK_CHIPID_STM32_F72XXX) ||
2745       (sl->chip_id == STLINK_CHIPID_STM32_F412)) {
2746     uint32_t sector = calculate_F4_sectornum(flashaddr);
2747 
2748     if (sector >= 12) {
2749       sector -= 12;
2750     }
2751 
2752     if (sector < 4) {
2753       sl->flash_pgsz = 0x4000;
2754     } else if (sector < 5) {
2755       sl->flash_pgsz = 0x10000;
2756     } else {
2757       sl->flash_pgsz = 0x20000;
2758     }
2759   } else if (sl->chip_id == STLINK_CHIPID_STM32_F7 ||
2760              sl->chip_id == STLINK_CHIPID_STM32_F7XXXX) {
2761     uint32_t sector = calculate_F7_sectornum(flashaddr);
2762 
2763     if (sector < 4) {
2764       sl->flash_pgsz = 0x8000;
2765     } else if (sector < 5) {
2766       sl->flash_pgsz = 0x20000;
2767     } else {
2768       sl->flash_pgsz = 0x40000;
2769     }
2770   }
2771 
2772   return ((uint32_t)sl->flash_pgsz);
2773 }
2774 
2775 /**
2776  * Erase a page of flash, assumes sl is fully populated with things like
2777  * chip/core ids
2778  * @param sl stlink context
2779  * @param flashaddr an address in the flash page to erase
2780  * @return 0 on success -ve on failure
2781  */
stlink_erase_flash_page(stlink_t * sl,stm32_addr_t flashaddr)2782 int stlink_erase_flash_page(stlink_t *sl, stm32_addr_t flashaddr) {
2783   // wait for ongoing op to finish
2784   wait_flash_busy(sl);
2785   // clear flash IO errors
2786   clear_flash_error(sl);
2787 
2788   if (sl->flash_type == STLINK_FLASH_TYPE_F4 ||
2789       sl->flash_type == STLINK_FLASH_TYPE_F7 ||
2790       sl->flash_type == STLINK_FLASH_TYPE_L4) {
2791     // unlock if locked
2792     unlock_flash_if(sl);
2793 
2794     // select the page to erase
2795     if ((sl->chip_id == STLINK_CHIPID_STM32_L4) ||
2796         (sl->chip_id == STLINK_CHIPID_STM32_L43X) ||
2797         (sl->chip_id == STLINK_CHIPID_STM32_L46X) ||
2798         (sl->chip_id == STLINK_CHIPID_STM32_L496X) ||
2799         (sl->chip_id == STLINK_CHIPID_STM32_L4RX)) {
2800       // calculate the actual bank+page from the address
2801       uint32_t page = calculate_L4_page(sl, flashaddr);
2802 
2803       fprintf(stderr, "EraseFlash - Page:0x%x Size:0x%x ", page,
2804               stlink_calculate_pagesize(sl, flashaddr));
2805 
2806       write_flash_cr_bker_pnb(sl, page);
2807     } else if (sl->chip_id == STLINK_CHIPID_STM32_F7 ||
2808                sl->chip_id == STLINK_CHIPID_STM32_F7XXXX) {
2809       // calculate the actual page from the address
2810       uint32_t sector = calculate_F7_sectornum(flashaddr);
2811 
2812       fprintf(stderr, "EraseFlash - Sector:0x%x Size:0x%x ", sector,
2813               stlink_calculate_pagesize(sl, flashaddr));
2814       write_flash_cr_snb(sl, sector, BANK_1);
2815     } else {
2816       // calculate the actual page from the address
2817       uint32_t sector = calculate_F4_sectornum(flashaddr);
2818 
2819       fprintf(stderr, "EraseFlash - Sector:0x%x Size:0x%x ", sector,
2820               stlink_calculate_pagesize(sl, flashaddr));
2821 
2822       // the SNB values for flash sectors in the second bank do not directly
2823       // follow the values for the first bank on 2mb devices...
2824       if (sector >= 12) {
2825         sector += 4;
2826       }
2827 
2828       write_flash_cr_snb(sl, sector, BANK_1);
2829     }
2830 
2831     set_flash_cr_strt(sl, BANK_1); // start erase operation
2832     wait_flash_busy(sl);           // wait for completion
2833     lock_flash(sl);                // TODO: fails to program if this is in
2834 #if DEBUG_FLASH
2835     fprintf(stdout, "Erase Final CR:0x%x\n", read_flash_cr(sl, BANK_1));
2836 #endif
2837   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
2838 
2839     uint32_t val;
2840     uint32_t flash_regs_base = get_stm32l0_flash_base(sl);
2841 
2842     // check if the locks are set
2843     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
2844 
2845     if ((val & (1 << 0)) || (val & (1 << 1))) {
2846       // disable pecr protection
2847       stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF,
2848                            FLASH_L0_PEKEY1);
2849       stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF,
2850                            FLASH_L0_PEKEY2);
2851 
2852       // check pecr.pelock is cleared
2853       stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
2854 
2855       if (val & (1 << 0)) {
2856         WLOG("pecr.pelock not clear (%#x)\n", val);
2857         return (-1);
2858       }
2859 
2860       // unlock program memory
2861       stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF,
2862                            FLASH_L0_PRGKEY1);
2863       stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF,
2864                            FLASH_L0_PRGKEY2);
2865 
2866       // check pecr.prglock is cleared
2867       stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
2868 
2869       if (val & (1 << 1)) {
2870         WLOG("pecr.prglock not clear (%#x)\n", val);
2871         return (-1);
2872       }
2873     }
2874 
2875     // set pecr.{erase,prog}
2876     val |= (1 << 9) | (1 << 3);
2877     stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
2878 
2879     // write 0 to the first word of the page to be erased
2880     stlink_write_debug32(sl, flashaddr, 0);
2881 
2882     /* MP: It is better to wait for clearing the busy bit after issuing page
2883      * erase command, even though PM0062 recommends to wait before it.
2884      * Test shows that a few iterations is performed in the following loop
2885      * before busy bit is cleared.
2886      */
2887     wait_flash_busy(sl);
2888 
2889     // reset lock bits
2890     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
2891     val |= (1 << 0) | (1 << 1) | (1 << 2);
2892     stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
2893   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB ||
2894              sl->flash_type == STLINK_FLASH_TYPE_G0 ||
2895              sl->flash_type == STLINK_FLASH_TYPE_G4) {
2896     uint32_t val;
2897     unlock_flash_if(sl);
2898     set_flash_cr_per(sl, BANK_1); // set the 'enable Flash erase' bit
2899 
2900     // set the page to erase
2901     if (sl->flash_type == STLINK_FLASH_TYPE_WB) {
2902       uint32_t flash_page =
2903           ((flashaddr - STM32_FLASH_BASE) / (uint32_t)(sl->flash_pgsz));
2904       stlink_read_debug32(sl, STM32WB_FLASH_CR, &val);
2905 
2906       // sec 3.10.5 - PNB[7:0] is offset by 3.
2907       val &= ~(0xFF << 3); // Clear previously set page number (if any)
2908       val |= ((flash_page & 0xFF) << 3);
2909 
2910       stlink_write_debug32(sl, STM32WB_FLASH_CR, val);
2911     } else if (sl->flash_type == STLINK_FLASH_TYPE_G0) {
2912       uint32_t flash_page =
2913           ((flashaddr - STM32_FLASH_BASE) / (uint32_t)(sl->flash_pgsz));
2914       stlink_read_debug32(sl, STM32Gx_FLASH_CR, &val);
2915       // sec 3.7.5 - PNB[5:0] is offset by 3. PER is 0x2.
2916       val &= ~(0x3F << 3);
2917       val |= ((flash_page & 0x3F) << 3) | (1 << FLASH_CR_PER);
2918       stlink_write_debug32(sl, STM32Gx_FLASH_CR, val);
2919     } else if (sl->flash_type == STLINK_FLASH_TYPE_G4) {
2920       uint32_t flash_page =
2921           ((flashaddr - STM32_FLASH_BASE) / (uint32_t)(sl->flash_pgsz));
2922       stlink_read_debug32(sl, STM32Gx_FLASH_CR, &val);
2923       // sec 3.7.5 - PNB[6:0] is offset by 3. PER is 0x2.
2924       val &= ~(0x7F << 3);
2925       val |= ((flash_page & 0x7F) << 3) | (1 << FLASH_CR_PER);
2926       stlink_write_debug32(sl, STM32Gx_FLASH_CR, val);
2927     }
2928 
2929     set_flash_cr_strt(sl, BANK_1);  // set the 'start operation' bit
2930     wait_flash_busy(sl);            // wait for the 'busy' bit to clear
2931     clear_flash_cr_per(sl, BANK_1); // clear the 'enable page erase' bit
2932     lock_flash(sl);
2933   } else if (sl->flash_type == STLINK_FLASH_TYPE_F0 ||
2934              sl->flash_type == STLINK_FLASH_TYPE_F1_XL) {
2935     unsigned bank = (flashaddr < STM32_F1_FLASH_BANK2_BASE) ? BANK_1 : BANK_2;
2936     unlock_flash_if(sl);
2937     clear_flash_cr_pg(sl, bank);         // clear the pg bit
2938     set_flash_cr_per(sl, bank);          // set the page erase bit
2939     write_flash_ar(sl, flashaddr, bank); // select the page to erase
2940     set_flash_cr_strt(sl,
2941                       bank); // start erase operation, reset by hw with busy bit
2942     wait_flash_busy(sl);
2943     clear_flash_cr_per(sl, bank); // clear the page erase bit
2944     lock_flash(sl);
2945   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
2946     unsigned bank = (flashaddr < STM32_H7_FLASH_BANK2_BASE) ? BANK_1 : BANK_2;
2947     unlock_flash_if(sl); // unlock if locked
2948     uint32_t sector = calculate_H7_sectornum(
2949         sl, flashaddr, bank); // calculate the actual page from the address
2950     write_flash_cr_snb(sl, sector, bank); // select the page to erase
2951     set_flash_cr_strt(sl, bank);          // start erase operation
2952     wait_flash_busy(sl);                  // wait for completion
2953     lock_flash(sl);
2954   } else {
2955     WLOG("unknown coreid %x, page erase failed\n", sl->core_id);
2956     return (-1);
2957   }
2958 
2959   return check_flash_error(sl);
2960 }
2961 
stlink_erase_flash_mass(stlink_t * sl)2962 int stlink_erase_flash_mass(stlink_t *sl) {
2963   int err = 0;
2964 
2965   // TODO: User MER bit to mass-erase WB series.
2966   if (sl->flash_type == STLINK_FLASH_TYPE_L0 ||
2967       sl->flash_type == STLINK_FLASH_TYPE_WB) {
2968     // erase each page
2969     int i = 0, num_pages = (int)(sl->flash_size / sl->flash_pgsz);
2970 
2971     for (i = 0; i < num_pages; i++) {
2972       // addr must be an addr inside the page
2973       stm32_addr_t addr =
2974           (stm32_addr_t)sl->flash_base + i * (stm32_addr_t)sl->flash_pgsz;
2975 
2976       if (stlink_erase_flash_page(sl, addr)) {
2977         WLOG("Failed to erase_flash_page(%#x) == -1\n", addr);
2978         return (-1);
2979       }
2980 
2981       fprintf(stdout, "-> Flash page at %5d/%5d erased\n", i, num_pages);
2982       fflush(stdout);
2983     }
2984 
2985     fprintf(stdout, "\n");
2986   } else {
2987     wait_flash_busy(sl);
2988     clear_flash_error(sl);
2989     unlock_flash_if(sl);
2990 
2991     if (sl->flash_type == STLINK_FLASH_TYPE_H7 &&
2992         sl->chip_id != STLINK_CHIPID_STM32_H7AX) {
2993       // set parallelism
2994       write_flash_cr_psiz(sl, 3 /*64it*/, BANK_1);
2995       if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
2996         write_flash_cr_psiz(sl, 3 /*64bit*/, BANK_2);
2997       }
2998     }
2999 
3000     set_flash_cr_mer(sl, 1, BANK_1); // set the mass erase bit
3001     set_flash_cr_strt(
3002         sl, BANK_1); // start erase operation, reset by hw with busy bit
3003 
3004     if (sl->flash_type == STLINK_FLASH_TYPE_F1_XL ||
3005         (sl->flash_type == STLINK_FLASH_TYPE_H7 &&
3006          sl->chip_flags & CHIP_F_HAS_DUAL_BANK)) {
3007       set_flash_cr_mer(sl, 1, BANK_2); // set the mass erase bit in bank 2
3008       set_flash_cr_strt(sl, BANK_2);   // start erase operation in bank 2
3009     }
3010 
3011     wait_flash_busy_progress(sl);
3012     lock_flash(sl);
3013 
3014     // reset the mass erase bit
3015     set_flash_cr_mer(sl, 0, BANK_1);
3016     if (sl->flash_type == STLINK_FLASH_TYPE_F1_XL ||
3017         (sl->flash_type == STLINK_FLASH_TYPE_H7 &&
3018          sl->chip_flags & CHIP_F_HAS_DUAL_BANK)) {
3019       set_flash_cr_mer(sl, 0, BANK_2);
3020     }
3021 
3022     err = check_flash_error(sl);
3023   }
3024 
3025   return (err);
3026 }
3027 
stlink_fcheck_flash(stlink_t * sl,const char * path,stm32_addr_t addr)3028 int stlink_fcheck_flash(stlink_t *sl, const char *path, stm32_addr_t addr) {
3029   // check the contents of path are at addr
3030 
3031   int res;
3032   mapped_file_t mf = MAPPED_FILE_INITIALIZER;
3033 
3034   if (map_file(&mf, path) == -1) {
3035     return (-1);
3036   }
3037 
3038   res = check_file(sl, &mf, addr);
3039   unmap_file(&mf);
3040   return (res);
3041 }
3042 
3043 /**
3044  * Verify addr..addr+len is binary identical to base...base+len
3045  * @param sl stlink context
3046  * @param address stm device address
3047  * @param data host side buffer to check against
3048  * @param length how much
3049  * @return 0 for success, -ve for failure
3050  */
stlink_verify_write_flash(stlink_t * sl,stm32_addr_t address,uint8_t * data,unsigned length)3051 int stlink_verify_write_flash(stlink_t *sl, stm32_addr_t address, uint8_t *data,
3052                               unsigned length) {
3053   size_t off;
3054   size_t cmp_size = (sl->flash_pgsz > 0x1800) ? 0x1800 : sl->flash_pgsz;
3055   ILOG("Starting verification of write complete\n");
3056 
3057   for (off = 0; off < length; off += cmp_size) {
3058     size_t aligned_size;
3059 
3060     // adjust last page size
3061     if ((off + cmp_size) > length) {
3062       cmp_size = length - off;
3063     }
3064 
3065     aligned_size = cmp_size;
3066 
3067     if (aligned_size & (4 - 1)) {
3068       aligned_size = (cmp_size + 4) & ~(4 - 1);
3069     }
3070 
3071     stlink_read_mem32(sl, address + (uint32_t)off, aligned_size);
3072 
3073     if (memcmp(sl->q_buf, data + off, cmp_size)) {
3074       ELOG("Verification of flash failed at offset: %u\n", (unsigned int)off);
3075       return (-1);
3076     }
3077   }
3078 
3079   ILOG("Flash written and verified! jolly good!\n");
3080   return (0);
3081 }
3082 
stm32l1_write_half_pages(stlink_t * sl,stm32_addr_t addr,uint8_t * base,uint32_t len,uint32_t pagesize)3083 int stm32l1_write_half_pages(stlink_t *sl, stm32_addr_t addr, uint8_t *base,
3084                              uint32_t len, uint32_t pagesize) {
3085   unsigned int count;
3086   unsigned int num_half_pages = len / pagesize;
3087   uint32_t val;
3088   uint32_t flash_regs_base = get_stm32l0_flash_base(sl);
3089   flash_loader_t fl;
3090 
3091   ILOG("Starting Half page flash write for STM32L core id\n");
3092 
3093   /* Flash loader initialisation */
3094   if (stlink_flash_loader_init(sl, &fl) == -1) {
3095     WLOG("stlink_flash_loader_init() == -1\n");
3096     return (-1);
3097   }
3098 
3099   // unlock already done
3100   stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
3101   val |= (1 << FLASH_L1_FPRG);
3102   stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
3103 
3104   val |= (1 << FLASH_L1_PROG);
3105   stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
3106 
3107   wait_flash_busy(sl);
3108 
3109   for (count = 0; count < num_half_pages; count++) {
3110     if (stlink_flash_loader_run(sl, &fl, addr + count * pagesize,
3111                                 base + count * pagesize, pagesize) == -1) {
3112       WLOG("l1_stlink_flash_loader_run(%#x) failed! == -1\n",
3113            addr + count * pagesize);
3114       stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
3115       val &= ~((1 << FLASH_L1_FPRG) | (1 << FLASH_L1_PROG));
3116       stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
3117       return (-1);
3118     }
3119 
3120     // wait for sr.busy to be cleared
3121     if (sl->verbose >= 1) {
3122       // show progress; writing procedure is slow and previous errors are
3123       // misleading
3124       fprintf(stdout, "\r%3u/%u halfpages written", count + 1, num_half_pages);
3125       fflush(stdout);
3126     }
3127 
3128     wait_flash_busy(sl);
3129   }
3130 
3131   stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
3132   val &= ~(1 << FLASH_L1_PROG);
3133   stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
3134   stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
3135   val &= ~(1 << FLASH_L1_FPRG);
3136   stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
3137   return (0);
3138 }
3139 
stlink_flashloader_start(stlink_t * sl,flash_loader_t * fl)3140 int stlink_flashloader_start(stlink_t *sl, flash_loader_t *fl) {
3141 
3142   // According to DDI0419C, Table C1-7 firstly force halt
3143   stlink_write_debug32(sl, STLINK_REG_DHCSR,
3144                        STLINK_REG_DHCSR_DBGKEY | STLINK_REG_DHCSR_C_DEBUGEN |
3145                            STLINK_REG_DHCSR_C_HALT);
3146   // and only then disable interrupts
3147   stlink_write_debug32(sl, STLINK_REG_DHCSR,
3148                        STLINK_REG_DHCSR_DBGKEY | STLINK_REG_DHCSR_C_DEBUGEN |
3149                            STLINK_REG_DHCSR_C_HALT |
3150                            STLINK_REG_DHCSR_C_MASKINTS);
3151 
3152   // disable DMA
3153   set_dma_state(sl, fl, 0);
3154 
3155   // wait for ongoing op to finish
3156   wait_flash_busy(sl);
3157   // Clear errors
3158   clear_flash_error(sl);
3159 
3160   if ((sl->flash_type == STLINK_FLASH_TYPE_F4) ||
3161       (sl->flash_type == STLINK_FLASH_TYPE_F7) ||
3162       (sl->flash_type == STLINK_FLASH_TYPE_L4)) {
3163     ILOG("Starting Flash write for F2/F4/F7/L4\n");
3164 
3165     // Flash loader initialisation
3166     if (stlink_flash_loader_init(sl, fl) == -1) {
3167       ELOG("stlink_flash_loader_init() == -1\n");
3168       return (-1);
3169     }
3170 
3171     unlock_flash_if(sl); // first unlock the cr
3172 
3173     int voltage;
3174     if (sl->version.stlink_v == 1) {
3175       WLOG("STLINK V1 cannot read voltage, use default voltage 3.2V\n");
3176       voltage = 3200;
3177     } else {
3178       voltage = stlink_target_voltage(sl);
3179     }
3180 
3181     if (voltage == -1) {
3182       ELOG("Failed to read Target voltage\n");
3183       return (-1);
3184     }
3185 
3186     if (sl->flash_type == STLINK_FLASH_TYPE_L4) {
3187       // L4 does not have a byte-write mode
3188       if (voltage < 1710) {
3189         ELOG("Target voltage (%d mV) too low for flash writes!\n", voltage);
3190         return (-1);
3191       }
3192     } else {
3193       if (voltage > 2700) {
3194         ILOG("enabling 32-bit flash writes\n");
3195         write_flash_cr_psiz(sl, 2, BANK_1);
3196       } else {
3197         ILOG("Target voltage (%d mV) too low for 32-bit flash, "
3198              "using 8-bit flash writes\n",
3199              voltage);
3200         write_flash_cr_psiz(sl, 0, BANK_1);
3201       }
3202     }
3203 
3204     // set programming mode
3205     set_flash_cr_pg(sl, BANK_1);
3206   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB ||
3207              sl->flash_type == STLINK_FLASH_TYPE_G0 ||
3208              sl->flash_type == STLINK_FLASH_TYPE_G4) {
3209     ILOG("Starting Flash write for WB/G0/G4\n");
3210 
3211     unlock_flash_if(sl);         // unlock flash if necessary
3212     set_flash_cr_pg(sl, BANK_1); // set PG 'allow programming' bit
3213   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
3214     ILOG("Starting Flash write for L0\n");
3215 
3216     uint32_t val;
3217     uint32_t flash_regs_base;
3218     if (sl->chip_id == STLINK_CHIPID_STM32_L0 ||
3219         sl->chip_id == STLINK_CHIPID_STM32_L0_CAT5 ||
3220         sl->chip_id == STLINK_CHIPID_STM32_L0_CAT2 ||
3221         sl->chip_id == STLINK_CHIPID_STM32_L011) {
3222       flash_regs_base = STM32L0_FLASH_REGS_ADDR;
3223     } else {
3224       flash_regs_base = STM32L_FLASH_REGS_ADDR;
3225     }
3226 
3227     // disable pecr protection
3228     stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF,
3229                          FLASH_L0_PEKEY1);
3230     stlink_write_debug32(sl, flash_regs_base + FLASH_PEKEYR_OFF,
3231                          FLASH_L0_PEKEY2);
3232 
3233     // check pecr.pelock is cleared
3234     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
3235     if (val & (1 << 0)) {
3236       ELOG("pecr.pelock not clear\n");
3237       return (-1);
3238     }
3239 
3240     // unlock program memory
3241     stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF,
3242                          FLASH_L0_PRGKEY1);
3243     stlink_write_debug32(sl, flash_regs_base + FLASH_PRGKEYR_OFF,
3244                          FLASH_L0_PRGKEY2);
3245 
3246     // check pecr.prglock is cleared
3247     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
3248     if (val & (1 << 1)) {
3249       ELOG("pecr.prglock not clear\n");
3250       return (-1);
3251     }
3252   } else if ((sl->flash_type == STLINK_FLASH_TYPE_F0) ||
3253              (sl->flash_type == STLINK_FLASH_TYPE_F1_XL)) {
3254     ILOG("Starting Flash write for VL/F0/F3/F1_XL\n");
3255 
3256     // flash loader initialisation
3257     if (stlink_flash_loader_init(sl, fl) == -1) {
3258       ELOG("stlink_flash_loader_init() == -1\n");
3259       return (-1);
3260     }
3261   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
3262     ILOG("Starting Flash write for H7\n");
3263 
3264     unlock_flash_if(sl);         // unlock the cr
3265     set_flash_cr_pg(sl, BANK_1); // set programming mode
3266     if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
3267       set_flash_cr_pg(sl, BANK_2);
3268     }
3269     if (sl->chip_id != STLINK_CHIPID_STM32_H7AX) {
3270       // set parallelism
3271       write_flash_cr_psiz(sl, 3 /*64it*/, BANK_1);
3272       if (sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
3273         write_flash_cr_psiz(sl, 3 /*64bit*/, BANK_2);
3274       }
3275     }
3276   } else {
3277     ELOG("unknown coreid, not sure how to write: %x\n", sl->core_id);
3278     return (-1);
3279   }
3280 
3281   return (0);
3282 }
3283 
stlink_flashloader_write(stlink_t * sl,flash_loader_t * fl,stm32_addr_t addr,uint8_t * base,uint32_t len)3284 int stlink_flashloader_write(stlink_t *sl, flash_loader_t *fl,
3285                              stm32_addr_t addr, uint8_t *base, uint32_t len) {
3286   size_t off;
3287   if ((sl->flash_type == STLINK_FLASH_TYPE_F4) ||
3288       (sl->flash_type == STLINK_FLASH_TYPE_F7) ||
3289       (sl->flash_type == STLINK_FLASH_TYPE_L4)) {
3290     size_t buf_size = (sl->sram_size > 0x8000) ? 0x8000 : 0x4000;
3291     for (off = 0; off < len;) {
3292       size_t size = len - off > buf_size ? buf_size : len - off;
3293       if (stlink_flash_loader_run(sl, fl, addr + (uint32_t)off, base + off,
3294                                   size) == -1) {
3295         ELOG("stlink_flash_loader_run(%#x) failed! == -1\n",
3296              (unsigned)(addr + off));
3297         check_flash_error(sl);
3298         return (-1);
3299       }
3300 
3301       off += size;
3302     }
3303   } else if (sl->flash_type == STLINK_FLASH_TYPE_WB ||
3304              sl->flash_type == STLINK_FLASH_TYPE_G0 ||
3305              sl->flash_type == STLINK_FLASH_TYPE_G4) {
3306     DLOG("Starting %3u page write\r\n", (unsigned int)(len / sl->flash_pgsz));
3307     for (off = 0; off < len; off += sizeof(uint32_t)) {
3308       uint32_t data;
3309 
3310       if ((off % sl->flash_pgsz) > (sl->flash_pgsz - 5)) {
3311         fprintf(stdout, "\r%3u/%3u pages written",
3312                 (unsigned int)(off / sl->flash_pgsz),
3313                 (unsigned int)(len / sl->flash_pgsz));
3314         fflush(stdout);
3315       }
3316 
3317       write_uint32((unsigned char *)&data, *(uint32_t *)(base + off));
3318       stlink_write_debug32(sl, addr + (uint32_t)off, data);
3319       wait_flash_busy(sl); // wait for 'busy' bit in FLASH_SR to clear
3320     }
3321     fprintf(stdout, "\n");
3322 
3323     // flash writes happen as 2 words at a time
3324     if ((off / sizeof(uint32_t)) % 2 != 0) {
3325       stlink_write_debug32(sl, addr + (uint32_t)off,
3326                            0); // write a single word of zeros
3327       wait_flash_busy(sl);     // wait for 'busy' bit in FLASH_SR to clear
3328     }
3329   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
3330     uint32_t val;
3331     uint32_t flash_regs_base;
3332     uint32_t pagesize;
3333 
3334     if (sl->chip_id == STLINK_CHIPID_STM32_L0 ||
3335         sl->chip_id == STLINK_CHIPID_STM32_L0_CAT5 ||
3336         sl->chip_id == STLINK_CHIPID_STM32_L0_CAT2 ||
3337         sl->chip_id == STLINK_CHIPID_STM32_L011) {
3338       flash_regs_base = STM32L0_FLASH_REGS_ADDR;
3339       pagesize = L0_WRITE_BLOCK_SIZE;
3340     } else {
3341       flash_regs_base = STM32L_FLASH_REGS_ADDR;
3342       pagesize = L1_WRITE_BLOCK_SIZE;
3343     }
3344 
3345     off = 0;
3346 
3347     if (len > pagesize) {
3348       if (stm32l1_write_half_pages(sl, addr, base, len, pagesize) == -1) {
3349         // this may happen on a blank device!
3350         WLOG("\nwrite_half_pages failed == -1\n");
3351       } else {
3352         off = (size_t)(len / pagesize) * pagesize;
3353       }
3354     }
3355 
3356     // write remaining word in program memory
3357     for (; off < len; off += sizeof(uint32_t)) {
3358       uint32_t data;
3359 
3360       if ((off % sl->flash_pgsz) > (sl->flash_pgsz - 5)) {
3361         fprintf(stdout, "\r%3u/%3u pages written",
3362                 (unsigned int)(off / sl->flash_pgsz),
3363                 (unsigned int)(len / sl->flash_pgsz));
3364         fflush(stdout);
3365       }
3366 
3367       write_uint32((unsigned char *)&data, *(uint32_t *)(base + off));
3368       stlink_write_debug32(sl, addr + (uint32_t)off, data);
3369 
3370       // wait for sr.busy to be cleared
3371       do {
3372         stlink_read_debug32(sl, flash_regs_base + FLASH_SR_OFF, &val);
3373       } while ((val & (1 << 0)) != 0);
3374 
3375       // TODO: check redo write operation
3376     }
3377     fprintf(stdout, "\n");
3378   } else if ((sl->flash_type == STLINK_FLASH_TYPE_F0) ||
3379              (sl->flash_type == STLINK_FLASH_TYPE_F1_XL)) {
3380     int write_block_count = 0;
3381     for (off = 0; off < len; off += sl->flash_pgsz) {
3382       // adjust last write size
3383       size_t size = len - off > sl->flash_pgsz ? sl->flash_pgsz : len - off;
3384 
3385       // unlock and set programming mode
3386       unlock_flash_if(sl);
3387 
3388       DLOG("Finished unlocking flash, running loader!\n");
3389 
3390       if (stlink_flash_loader_run(sl, fl, addr + (uint32_t)off, base + off,
3391                                   size) == -1) {
3392         ELOG("stlink_flash_loader_run(%#x) failed! == -1\n",
3393              (unsigned)(addr + off));
3394         check_flash_error(sl);
3395         return (-1);
3396       }
3397 
3398       lock_flash(sl);
3399 
3400       if (sl->verbose >= 1) {
3401         // show progress; writing procedure is slow and previous errors are
3402         // misleading
3403         fprintf(stdout, "\r%3u/%3u pages written", ++write_block_count,
3404                 (unsigned int)((len + sl->flash_pgsz - 1) / sl->flash_pgsz));
3405         fflush(stdout);
3406       }
3407     }
3408     if (sl->verbose >= 1) {
3409       fprintf(stdout, "\n");
3410     }
3411   } else if (sl->flash_type == STLINK_FLASH_TYPE_H7) {
3412     for (off = 0; off < len;) {
3413       // Program STM32H7x with 64-byte Flash words
3414       size_t chunk = (len - off > 64) ? 64 : len - off;
3415       memcpy(sl->q_buf, base + off, chunk);
3416       stlink_write_mem32(sl, addr + (uint32_t)off, 64);
3417       wait_flash_busy(sl);
3418 
3419       off += chunk;
3420 
3421       if (sl->verbose >= 1) {
3422         // show progress
3423         fprintf(stdout, "\r%u/%u bytes written", (unsigned int)off,
3424                 (unsigned int)len);
3425         fflush(stdout);
3426       }
3427     }
3428     if (sl->verbose >= 1) {
3429       fprintf(stdout, "\n");
3430     }
3431   } else {
3432     return (-1);
3433   }
3434 
3435   return check_flash_error(sl);
3436 }
3437 
stlink_flashloader_stop(stlink_t * sl,flash_loader_t * fl)3438 int stlink_flashloader_stop(stlink_t *sl, flash_loader_t *fl) {
3439   uint32_t dhcsr;
3440 
3441   if ((sl->flash_type == STLINK_FLASH_TYPE_F4) ||
3442       (sl->flash_type == STLINK_FLASH_TYPE_F7) ||
3443       (sl->flash_type == STLINK_FLASH_TYPE_L4) ||
3444       (sl->flash_type == STLINK_FLASH_TYPE_WB) ||
3445       (sl->flash_type == STLINK_FLASH_TYPE_G0) ||
3446       (sl->flash_type == STLINK_FLASH_TYPE_G4) ||
3447       (sl->flash_type == STLINK_FLASH_TYPE_H7)) {
3448 
3449     clear_flash_cr_pg(sl, BANK_1);
3450     if (sl->flash_type == STLINK_FLASH_TYPE_H7 &&
3451         sl->chip_flags & CHIP_F_HAS_DUAL_BANK) {
3452       clear_flash_cr_pg(sl, BANK_2);
3453     }
3454     lock_flash(sl);
3455   } else if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
3456     uint32_t val;
3457     uint32_t flash_regs_base;
3458     if (sl->chip_id == STLINK_CHIPID_STM32_L0 ||
3459         sl->chip_id == STLINK_CHIPID_STM32_L0_CAT5 ||
3460         sl->chip_id == STLINK_CHIPID_STM32_L0_CAT2 ||
3461         sl->chip_id == STLINK_CHIPID_STM32_L011) {
3462       flash_regs_base = STM32L0_FLASH_REGS_ADDR;
3463     } else {
3464       flash_regs_base = STM32L_FLASH_REGS_ADDR;
3465     }
3466     // reset lock bits
3467     stlink_read_debug32(sl, flash_regs_base + FLASH_PECR_OFF, &val);
3468     val |= (1 << 0) | (1 << 1) | (1 << 2);
3469     stlink_write_debug32(sl, flash_regs_base + FLASH_PECR_OFF, val);
3470   }
3471 
3472   // enable interrupt
3473   if (!stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr)) {
3474     stlink_write_debug32(sl, STLINK_REG_DHCSR,
3475                          STLINK_REG_DHCSR_DBGKEY | STLINK_REG_DHCSR_C_DEBUGEN |
3476                              (dhcsr & (~STLINK_REG_DHCSR_C_MASKINTS)));
3477   }
3478 
3479   // restore DMA state
3480   set_dma_state(sl, fl, 1);
3481 
3482   return (0);
3483 }
3484 
stlink_write_flash(stlink_t * sl,stm32_addr_t addr,uint8_t * base,uint32_t len,uint8_t eraseonly)3485 int stlink_write_flash(stlink_t *sl, stm32_addr_t addr, uint8_t *base,
3486                        uint32_t len, uint8_t eraseonly) {
3487   size_t off;
3488   int ret;
3489   flash_loader_t fl;
3490   ILOG("Attempting to write %d (%#x) bytes to stm32 address: %u (%#x)\n", len,
3491        len, addr, addr);
3492   // check addr range is inside the flash
3493   stlink_calculate_pagesize(sl, addr);
3494 
3495   if (addr < sl->flash_base) {
3496     ELOG("addr too low %#x < %#x\n", addr, sl->flash_base);
3497     return (-1);
3498   } else if ((addr + len) < addr) {
3499     ELOG("addr overruns\n");
3500     return (-1);
3501   } else if ((addr + len) > (sl->flash_base + sl->flash_size)) {
3502     ELOG("addr too high\n");
3503     return (-1);
3504   } else if (addr & 1) {
3505     ELOG("unaligned addr 0x%x\n", addr);
3506     return (-1);
3507   } else if (len & 1) {
3508     WLOG("unaligned len 0x%x -- padding with zero\n", len);
3509     len += 1;
3510   } else if (addr & (sl->flash_pgsz - 1)) {
3511     ELOG("addr not a multiple of current pagesize (%u bytes), not supported, "
3512          "check page start address and compare with flash module organisation "
3513          "in related ST reference manual of your device.\n",
3514          (unsigned)(sl->flash_pgsz));
3515     return (-1);
3516   }
3517 
3518   // make sure we've loaded the context with the chip details
3519   stlink_core_id(sl);
3520 
3521   // Erase each page
3522   int page_count = 0;
3523 
3524   for (off = 0; off < len;
3525        off += stlink_calculate_pagesize(sl, addr + (uint32_t)off)) {
3526     // addr must be an addr inside the page
3527     if (stlink_erase_flash_page(sl, addr + (uint32_t)off) == -1) {
3528       ELOG("Failed to erase_flash_page(%#x) == -1\n", (unsigned)(addr + off));
3529       return (-1);
3530     }
3531 
3532     ILOG("Flash page at addr: 0x%08lx erased\n", (unsigned long)(addr + off));
3533     page_count++;
3534   }
3535 
3536   ILOG("Finished erasing %d pages of %u (%#x) bytes\n", page_count,
3537        (unsigned)(sl->flash_pgsz), (unsigned)(sl->flash_pgsz));
3538 
3539   if (eraseonly) {
3540     return (0);
3541   }
3542 
3543   ret = stlink_flashloader_start(sl, &fl);
3544   if (ret)
3545     return ret;
3546   ret = stlink_flashloader_write(sl, &fl, addr, base, len);
3547   if (ret)
3548     return ret;
3549   ret = stlink_flashloader_stop(sl, &fl);
3550   if (ret)
3551     return ret;
3552 
3553   return (stlink_verify_write_flash(sl, addr, base, len));
3554 }
3555 
3556 // TODO: length not checked
stlink_parse_hex(const char * hex)3557 static uint8_t stlink_parse_hex(const char *hex) {
3558   uint8_t d[2];
3559 
3560   for (int i = 0; i < 2; ++i) {
3561     char c = *(hex + i);
3562 
3563     if (c >= '0' && c <= '9') {
3564       d[i] = c - '0';
3565     } else if (c >= 'A' && c <= 'F') {
3566       d[i] = c - 'A' + 10;
3567     } else if (c >= 'a' && c <= 'f') {
3568       d[i] = c - 'a' + 10;
3569     } else {
3570       return (0); // error
3571     }
3572   }
3573 
3574   return ((d[0] << 4) | (d[1]));
3575 }
3576 
stlink_parse_ihex(const char * path,uint8_t erased_pattern,uint8_t ** mem,size_t * size,uint32_t * begin)3577 int stlink_parse_ihex(const char *path, uint8_t erased_pattern, uint8_t **mem,
3578                       size_t *size, uint32_t *begin) {
3579   int res = 0;
3580   *begin = UINT32_MAX;
3581   uint8_t *data = NULL;
3582   uint32_t end = 0;
3583   bool eof_found = false;
3584 
3585   for (int scan = 0; (res == 0) && (scan < 2); ++scan) {
3586     // parse file two times - first to find memory range, second - to fill it
3587     if (scan == 1) {
3588       if (!eof_found) {
3589         ELOG("No EoF recond\n");
3590         res = -1;
3591         break;
3592       }
3593 
3594       if (*begin >= end) {
3595         ELOG("No data found in file\n");
3596         res = -1;
3597         break;
3598       }
3599 
3600       *size = (end - *begin) + 1;
3601       data = calloc(*size, 1); // use calloc to get NULL if out of memory
3602 
3603       if (!data) {
3604         ELOG("Cannot allocate %u bytes\n", (unsigned)(*size));
3605         res = -1;
3606         break;
3607       }
3608 
3609       memset(data, erased_pattern, *size);
3610     }
3611 
3612     FILE *file = fopen(path, "r");
3613 
3614     if (!file) {
3615       ELOG("Cannot open file\n");
3616       res = -1;
3617       break;
3618     }
3619 
3620     uint32_t lba = 0;
3621     char line[1 + 5 * 2 + 255 * 2 + 2];
3622 
3623     while (fgets(line, sizeof(line), file)) {
3624       if (line[0] == '\n' || line[0] == '\r') {
3625         continue;
3626       } // skip empty lines
3627 
3628       if (line[0] != ':') { // no marker - wrong file format
3629         ELOG("Wrong file format - no marker\n");
3630         res = -1;
3631         break;
3632       }
3633 
3634       size_t l = strlen(line);
3635 
3636       while (l > 0 && (line[l - 1] == '\n' || line[l - 1] == '\r')) {
3637         --l;
3638       } // trim EoL
3639 
3640       if ((l < 11) ||
3641           (l ==
3642            (sizeof(line) - 1))) { // line too short or long - wrong file format
3643         ELOG("Wrong file format - wrong line length\n");
3644         res = -1;
3645         break;
3646       }
3647 
3648       uint8_t chksum = 0; // check sum
3649 
3650       for (size_t i = 1; i < l; i += 2) {
3651         chksum += stlink_parse_hex(line + i);
3652       }
3653 
3654       if (chksum != 0) {
3655         ELOG("Wrong file format - checksum mismatch\n");
3656         res = -1;
3657         break;
3658       }
3659 
3660       uint8_t reclen = stlink_parse_hex(line + 1);
3661 
3662       if (((uint32_t)reclen + 5) * 2 + 1 != l) {
3663         ELOG("Wrong file format - record length mismatch\n");
3664         res = -1;
3665         break;
3666       }
3667 
3668       uint16_t offset = ((uint16_t)stlink_parse_hex(line + 3) << 8) |
3669                         ((uint16_t)stlink_parse_hex(line + 5));
3670       uint8_t rectype = stlink_parse_hex(line + 7);
3671 
3672       switch (rectype) {
3673       case 0: /* Data */
3674         if (scan == 0) {
3675           uint32_t b = lba + offset;
3676           uint32_t e = b + reclen - 1;
3677 
3678           if (b < *begin) {
3679             *begin = b;
3680           }
3681 
3682           if (e > end) {
3683             end = e;
3684           }
3685         } else {
3686           for (uint8_t i = 0; i < reclen; ++i) {
3687             uint8_t b = stlink_parse_hex(line + 9 + i * 2);
3688             uint32_t addr = lba + offset + i;
3689 
3690             if (addr >= *begin && addr <= end) {
3691               data[addr - *begin] = b;
3692             }
3693           }
3694         }
3695         break;
3696       case 1: /* EoF */
3697         eof_found = true;
3698         break;
3699       case 2: /* Extended Segment Address, unexpected */
3700         res = -1;
3701         break;
3702       case 3: /* Start Segment Address, unexpected */
3703         res = -1;
3704         break;
3705       case 4: /* Extended Linear Address */
3706         if (reclen == 2) {
3707           lba = ((uint32_t)stlink_parse_hex(line + 9) << 24) |
3708                 ((uint32_t)stlink_parse_hex(line + 11) << 16);
3709         } else {
3710           ELOG("Wrong file format - wrong LBA length\n");
3711           res = -1;
3712         }
3713         break;
3714       case 5: /* Start Linear Address - expected, but ignore */
3715         break;
3716       default:
3717         ELOG("Wrong file format - unexpected record type %d\n", rectype);
3718         res = -1;
3719       }
3720 
3721       if (res != 0) {
3722         break;
3723       }
3724     }
3725 
3726     fclose(file);
3727   }
3728 
3729   if (res == 0) {
3730     *mem = data;
3731   } else {
3732     free(data);
3733   }
3734 
3735   return (res);
3736 }
3737 
stlink_get_erased_pattern(stlink_t * sl)3738 uint8_t stlink_get_erased_pattern(stlink_t *sl) {
3739   if (sl->flash_type == STLINK_FLASH_TYPE_L0) {
3740     return (0x00);
3741   } else {
3742     return (0xff);
3743   }
3744 }
3745 
stlink_mwrite_flash(stlink_t * sl,uint8_t * data,uint32_t length,stm32_addr_t addr)3746 int stlink_mwrite_flash(stlink_t *sl, uint8_t *data, uint32_t length,
3747                         stm32_addr_t addr) {
3748   /* Write the block in flash at addr */
3749   int err;
3750   unsigned int num_empty, idx;
3751   uint8_t erased_pattern = stlink_get_erased_pattern(sl);
3752 
3753   /*
3754    * This optimisation may cause unexpected garbage data remaining.
3755    * Therfore it is turned off by default.
3756    */
3757   if (sl->opt) {
3758     idx = (unsigned int)length;
3759 
3760     for (num_empty = 0; num_empty != length; ++num_empty)
3761       if (data[--idx] != erased_pattern) {
3762         break;
3763       }
3764 
3765     num_empty -= (num_empty & 3); // Round down to words
3766 
3767     if (num_empty != 0) {
3768       ILOG("Ignoring %d bytes of 0x%02x at end of file\n", num_empty,
3769            erased_pattern);
3770     }
3771   } else {
3772     num_empty = 0;
3773   }
3774 
3775   /*
3776    * TODO: investigate a kind of weird behaviour here:
3777    * If the file is identified to be all-empty and four-bytes aligned,
3778    * still flash the whole file even if ignoring message is printed.
3779    */
3780   err = stlink_write_flash(sl, addr, data,
3781                            (num_empty == length) ? (uint32_t)length
3782                                                  : (uint32_t)length - num_empty,
3783                            num_empty == length);
3784   stlink_fwrite_finalize(sl, addr);
3785   return (err);
3786 }
3787 
3788 /**
3789  * Write the given binary file into flash at address "addr"
3790  * @param sl
3791  * @param path readable file path, should be binary image
3792  * @param addr where to start writing
3793  * @return 0 on success, -ve on failure.
3794  */
stlink_fwrite_flash(stlink_t * sl,const char * path,stm32_addr_t addr)3795 int stlink_fwrite_flash(stlink_t *sl, const char *path, stm32_addr_t addr) {
3796   /* Write the file in flash at addr */
3797   int err;
3798   unsigned int num_empty, idx;
3799   uint8_t erased_pattern = stlink_get_erased_pattern(sl);
3800   mapped_file_t mf = MAPPED_FILE_INITIALIZER;
3801 
3802   if (map_file(&mf, path) == -1) {
3803     ELOG("map_file() == -1\n");
3804     return (-1);
3805   }
3806 
3807   printf("file %s ", path);
3808   md5_calculate(&mf);
3809   stlink_checksum(&mf);
3810 
3811   if (sl->opt) {
3812     idx = (unsigned int)mf.len;
3813 
3814     for (num_empty = 0; num_empty != mf.len; ++num_empty) {
3815       if (mf.base[--idx] != erased_pattern) {
3816         break;
3817       }
3818     }
3819 
3820     num_empty -= (num_empty & 3); // round down to words
3821 
3822     if (num_empty != 0) {
3823       ILOG("Ignoring %d bytes of 0x%02x at end of file\n", num_empty,
3824            erased_pattern);
3825     }
3826   } else {
3827     num_empty = 0;
3828   }
3829 
3830   /*
3831    * TODO: investigate a kind of weird behaviour here:
3832    * If the file is identified to be all-empty and four-bytes aligned,
3833    * still flash the whole file even if ignoring message is printed.
3834    */
3835   err = stlink_write_flash(sl, addr, mf.base,
3836                            (num_empty == mf.len) ? (uint32_t)mf.len
3837                                                  : (uint32_t)mf.len - num_empty,
3838                            num_empty == mf.len);
3839   stlink_fwrite_finalize(sl, addr);
3840   unmap_file(&mf);
3841   return (err);
3842 }
3843 
3844 /**
3845  * Write option bytes
3846  * @param sl
3847  * @param addr of the memory mapped option bytes
3848  * @param base option bytes to write
3849  * @return 0 on success, -ve on failure.
3850  */
stlink_write_option_bytes_gx(stlink_t * sl,uint8_t * base,stm32_addr_t addr,uint32_t len)3851 static int stlink_write_option_bytes_gx(stlink_t *sl, uint8_t *base,
3852                                         stm32_addr_t addr, uint32_t len) {
3853   /* Write options bytes */
3854   uint32_t val;
3855   int ret = 0;
3856   (void)len;
3857   uint32_t data;
3858 
3859   clear_flash_error(sl);
3860 
3861   write_uint32((unsigned char *)&data, *(uint32_t *)(base));
3862   WLOG("Writing option bytes %#10x to %#10x\n", data, addr);
3863   stlink_write_debug32(sl, STM32Gx_FLASH_OPTR, data);
3864 
3865   // Set Options Start bit
3866   stlink_read_debug32(sl, STM32Gx_FLASH_CR, &val);
3867   val |= (1 << STM32Gx_FLASH_CR_OPTSTRT);
3868   stlink_write_debug32(sl, STM32Gx_FLASH_CR, val);
3869 
3870   wait_flash_busy(sl);
3871 
3872   ret = check_flash_error(sl);
3873 
3874   // Reload options
3875   stlink_read_debug32(sl, STM32Gx_FLASH_CR, &val);
3876   val |= (1 << STM32Gx_FLASH_CR_OBL_LAUNCH);
3877   stlink_write_debug32(sl, STM32Gx_FLASH_CR, val);
3878 
3879   return (ret);
3880 }
3881 
3882 /**
3883  * Write option bytes
3884  * @param sl
3885  * @param addr of the memory mapped option bytes
3886  * @param base option bytes to write
3887  * @return 0 on success, -ve on failure.
3888  */
stlink_write_option_bytes_l0(stlink_t * sl,uint8_t * base,stm32_addr_t addr,uint32_t len)3889 static int stlink_write_option_bytes_l0(stlink_t *sl, uint8_t *base,
3890                                         stm32_addr_t addr, uint32_t len) {
3891   uint32_t flash_base = get_stm32l0_flash_base(sl);
3892   uint32_t val;
3893   uint32_t data;
3894   int ret = 0;
3895 
3896   // Clear errors
3897   clear_flash_error(sl);
3898 
3899   while (len != 0) {
3900     write_uint32((unsigned char *)&data,
3901                  *(uint32_t *)(base)); // write options bytes
3902 
3903     WLOG("Writing option bytes %#10x to %#10x\n", data, addr);
3904     stlink_write_debug32(sl, addr, data);
3905     wait_flash_busy(sl);
3906 
3907     if ((ret = check_flash_error(sl))) {
3908       break;
3909     }
3910 
3911     len -= 4;
3912     addr += 4;
3913     base += 4;
3914   }
3915 
3916   // Reload options
3917   stlink_read_debug32(sl, flash_base + FLASH_PECR_OFF, &val);
3918   val |= (1 << STM32L0_FLASH_OBL_LAUNCH);
3919   stlink_write_debug32(sl, flash_base + FLASH_PECR_OFF, val);
3920 
3921   return (ret);
3922 }
3923 
3924 /**
3925  * Write option bytes
3926  * @param sl
3927  * @param addr of the memory mapped option bytes
3928  * @param base option bytes to write
3929  * @return 0 on success, -ve on failure.
3930  */
stlink_write_option_bytes_l4(stlink_t * sl,uint8_t * base,stm32_addr_t addr,uint32_t len)3931 static int stlink_write_option_bytes_l4(stlink_t *sl, uint8_t *base,
3932                                         stm32_addr_t addr, uint32_t len) {
3933 
3934   uint32_t val;
3935   int ret = 0;
3936   (void)addr;
3937   (void)len;
3938 
3939   // Clear errors
3940   clear_flash_error(sl);
3941 
3942   // write options bytes
3943   uint32_t data;
3944   write_uint32((unsigned char *)&data, *(uint32_t *)(base));
3945   WLOG("Writing option bytes 0x%04x\n", data);
3946   stlink_write_debug32(sl, STM32L4_FLASH_OPTR, data);
3947 
3948   // set options start bit
3949   stlink_read_debug32(sl, STM32L4_FLASH_CR, &val);
3950   val |= (1 << STM32L4_FLASH_CR_OPTSTRT);
3951   stlink_write_debug32(sl, STM32L4_FLASH_CR, val);
3952 
3953   wait_flash_busy(sl);
3954   ret = check_flash_error(sl);
3955 
3956   // apply options bytes immediate
3957   stlink_read_debug32(sl, STM32L4_FLASH_CR, &val);
3958   val |= (1 << STM32L4_FLASH_CR_OBL_LAUNCH);
3959   stlink_write_debug32(sl, STM32L4_FLASH_CR, val);
3960 
3961   return (ret);
3962 }
3963 
3964 /**
3965  * Write option bytes
3966  * @param sl
3967  * @param option_byte value to write
3968  * @return 0 on success, -ve on failure.
3969  */
stlink_write_option_bytes_f4(stlink_t * sl,uint8_t * base,stm32_addr_t addr,uint32_t len)3970 static int stlink_write_option_bytes_f4(stlink_t *sl, uint8_t *base,
3971                                         stm32_addr_t addr, uint32_t len) {
3972   uint32_t option_byte;
3973   int ret = 0;
3974   (void)addr;
3975   (void)len;
3976 
3977   // Clear errors
3978   clear_flash_error(sl);
3979 
3980   write_uint32((unsigned char *)&option_byte, *(uint32_t *)(base));
3981 
3982   // write option byte, ensuring we dont lock opt, and set strt bit
3983   stlink_write_debug32(sl, FLASH_F4_OPTCR,
3984                        (option_byte & ~(1 << FLASH_F4_OPTCR_LOCK)) |
3985                            (1 << FLASH_F4_OPTCR_START));
3986 
3987   wait_flash_busy(sl);
3988   ret = check_flash_error(sl);
3989 
3990   // option bytes are reloaded at reset only, no obl. */
3991   return (ret);
3992 }
3993 
3994 /**
3995  * Write option bytes
3996  * @param sl
3997  * @param option_byte value to write
3998  * @return 0 on success, -ve on failure.
3999  */
stlink_write_option_bytes_f7(stlink_t * sl,uint8_t * base,stm32_addr_t addr,uint32_t len)4000 static int stlink_write_option_bytes_f7(stlink_t *sl, uint8_t *base,
4001                                         stm32_addr_t addr, uint32_t len) {
4002   uint32_t option_byte;
4003   int ret = 0;
4004 
4005   // Clear errors
4006   clear_flash_error(sl);
4007 
4008   ILOG("Asked to write option byte %#10x to %#010x.\n", *(uint32_t *)(base),
4009        addr);
4010   write_uint32((unsigned char *)&option_byte, *(uint32_t *)(base));
4011   ILOG("Write %d option bytes %#010x to %#010x!\n", len, option_byte, addr);
4012 
4013   if (addr == 0) {
4014     addr = FLASH_F7_OPTCR;
4015     ILOG("No address provided, using %#10x\n", addr);
4016   }
4017 
4018   if (addr == FLASH_F7_OPTCR) {
4019     /* write option byte, ensuring we dont lock opt, and set strt bit */
4020     stlink_write_debug32(sl, FLASH_F7_OPTCR,
4021                          (option_byte & ~(1 << FLASH_F7_OPTCR_LOCK)) |
4022                              (1 << FLASH_F7_OPTCR_START));
4023   } else if (addr == FLASH_F7_OPTCR1) {
4024     // Read FLASH_F7_OPTCR
4025     uint32_t oldvalue;
4026     stlink_read_debug32(sl, FLASH_F7_OPTCR, &oldvalue);
4027     /* write option byte */
4028     stlink_write_debug32(sl, FLASH_F7_OPTCR1, option_byte);
4029     // Write FLASH_F7_OPTCR lock and start address
4030     stlink_write_debug32(sl, FLASH_F7_OPTCR,
4031                          (oldvalue & ~(1 << FLASH_F7_OPTCR_LOCK)) |
4032                              (1 << FLASH_F7_OPTCR_START));
4033   } else {
4034     WLOG("WIP: write %#010x to address %#010x\n", option_byte, addr);
4035     stlink_write_debug32(sl, addr, option_byte);
4036   }
4037 
4038   wait_flash_busy(sl);
4039 
4040   ret = check_flash_error(sl);
4041   if (!ret)
4042     ILOG("Wrote %d option bytes %#010x to %#010x!\n", len, *(uint32_t *)base,
4043          addr);
4044 
4045   /* option bytes are reloaded at reset only, no obl. */
4046 
4047   return ret;
4048 }
4049 
4050 /**
4051  * Write STM32H7xx option bytes
4052  * @param sl
4053  * @param base option bytes to write
4054  * @param addr of the memory mapped option bytes
4055  * @param len number of bytes to write (must be multiple of 4)
4056  * @return 0 on success, -ve on failure.
4057  */
stlink_write_option_bytes_h7(stlink_t * sl,uint8_t * base,stm32_addr_t addr,uint32_t len)4058 static int stlink_write_option_bytes_h7(stlink_t *sl, uint8_t *base,
4059                                         stm32_addr_t addr, uint32_t len) {
4060   uint32_t val;
4061   uint32_t data;
4062 
4063   // Wait until previous flash option has completed
4064   wait_flash_busy(sl);
4065 
4066   // Clear previous error
4067   stlink_write_debug32(sl, FLASH_H7_OPTCCR,
4068                        1 << FLASH_H7_OPTCCR_CLR_OPTCHANGEERR);
4069 
4070   while (len != 0) {
4071     switch (addr) {
4072     case FLASH_H7_REGS_ADDR + 0x20: // FLASH_OPTSR_PRG
4073     case FLASH_H7_REGS_ADDR + 0x2c: // FLASH_PRAR_PRG1
4074     case FLASH_H7_REGS_ADDR + 0x34: // FLASH_SCAR_PRG1
4075     case FLASH_H7_REGS_ADDR + 0x3c: // FLASH_WPSN_PRG1
4076     case FLASH_H7_REGS_ADDR + 0x44: // FLASH_BOOT_PRG
4077       /* Write to FLASH_xxx_PRG registers */
4078       write_uint32((unsigned char *)&data,
4079                    *(uint32_t *)(base)); // write options bytes
4080 
4081       WLOG("Writing option bytes %#10x to %#10x\n", data, addr);
4082 
4083       /* Skip if the value in the CUR register is identical */
4084       stlink_read_debug32(sl, addr - 4, &val);
4085       if (val == data) {
4086         break;
4087       }
4088 
4089       /* Write new option byte values and start modification */
4090       stlink_write_debug32(sl, addr, data);
4091       stlink_read_debug32(sl, FLASH_H7_OPTCR, &val);
4092       val |= (1 << FLASH_H7_OPTCR_OPTSTART);
4093       stlink_write_debug32(sl, FLASH_H7_OPTCR, val);
4094 
4095       /* Wait for the option bytes modification to complete */
4096       do {
4097         stlink_read_debug32(sl, FLASH_H7_OPTSR_CUR, &val);
4098       } while ((val & (1 << FLASH_H7_OPTSR_OPT_BUSY)) != 0);
4099 
4100       /* Check for errors */
4101       if ((val & (1 << FLASH_H7_OPTSR_OPTCHANGEERR)) != 0) {
4102         stlink_write_debug32(sl, FLASH_H7_OPTCCR,
4103                              1 << FLASH_H7_OPTCCR_CLR_OPTCHANGEERR);
4104         return -1;
4105       }
4106       break;
4107 
4108     default:
4109       /* Skip non-programmable registers */
4110       break;
4111     }
4112 
4113     len -= 4;
4114     addr += 4;
4115     base += 4;
4116   }
4117 
4118   return 0;
4119 }
4120 
4121 /**
4122  * Read option bytes
4123  * @param sl
4124  * @param option_byte value to write
4125  * @return 0 on success, -ve on failure.
4126  */
stlink_read_option_control_register_Gx(stlink_t * sl,uint32_t * option_byte)4127 int stlink_read_option_control_register_Gx(stlink_t *sl,
4128                                            uint32_t *option_byte) {
4129   return stlink_read_debug32(sl, STM32Gx_FLASH_OPTR, option_byte);
4130 }
4131 
4132 /**
4133  * Read option bytes
4134  * @param sl
4135  * @param option_byte value to write
4136  * @return 0 on success, -ve on failure.
4137  */
stlink_read_option_bytes_Gx(stlink_t * sl,uint32_t * option_byte)4138 int stlink_read_option_bytes_Gx(stlink_t *sl, uint32_t *option_byte) {
4139   return stlink_read_option_control_register_Gx(sl, option_byte);
4140 }
4141 
4142 /**
4143  * Read option bytes
4144  * @param sl
4145  * @param option_byte value to write
4146  * @return 0 on success, -ve on failure.
4147  */
stlink_read_option_control_register_f2(stlink_t * sl,uint32_t * option_byte)4148 int stlink_read_option_control_register_f2(stlink_t *sl,
4149                                            uint32_t *option_byte) {
4150   return stlink_read_debug32(sl, FLASH_F2_OPT_CR, option_byte);
4151 }
4152 
4153 /**
4154  * Read option bytes
4155  * @param sl
4156  * @param option_byte value to write
4157  * @return 0 on success, -ve on failure.
4158  */
stlink_read_option_bytes_f2(stlink_t * sl,uint32_t * option_byte)4159 int stlink_read_option_bytes_f2(stlink_t *sl, uint32_t *option_byte) {
4160   return stlink_read_option_control_register_f2(sl, option_byte);
4161 }
4162 
4163 /**
4164  * Read option bytes
4165  * @param sl
4166  * @param option_byte value to read
4167  * @return 0 on success, -ve on failure.
4168  */
stlink_read_option_control_register_f4(stlink_t * sl,uint32_t * option_byte)4169 int stlink_read_option_control_register_f4(stlink_t *sl,
4170                                            uint32_t *option_byte) {
4171   return stlink_read_debug32(sl, FLASH_F4_OPTCR, option_byte);
4172 }
4173 
4174 /**
4175  * Read option bytes
4176  * @param sl
4177  * @param option_byte value to read
4178  * @return 0 on success, -ve on failure.
4179  */
stlink_read_option_bytes_f4(stlink_t * sl,uint32_t * option_byte)4180 int stlink_read_option_bytes_f4(stlink_t *sl, uint32_t *option_byte) {
4181   return stlink_read_option_control_register_f4(sl, option_byte);
4182 }
4183 
4184 /**
4185  * Read option bytes
4186  * @param sl
4187  * @param option_byte value to read
4188  * @return 0 on success, -ve on failure.
4189  */
stlink_read_option_control_register_f7(stlink_t * sl,uint32_t * option_byte)4190 int stlink_read_option_control_register_f7(stlink_t *sl,
4191                                            uint32_t *option_byte) {
4192   DLOG("@@@@ Read option control register byte from %#10x\n", FLASH_F7_OPTCR);
4193   return stlink_read_debug32(sl, FLASH_F7_OPTCR, option_byte);
4194 }
4195 
4196 /**
4197  * Read option bytes
4198  * @param sl
4199  * @param option_byte value to read
4200  * @return 0 on success, -ve on failure.
4201  */
stlink_read_option_control_register1_f7(stlink_t * sl,uint32_t * option_byte)4202 int stlink_read_option_control_register1_f7(stlink_t *sl,
4203                                             uint32_t *option_byte) {
4204   DLOG("@@@@ Read option control register 1 byte from %#10x\n",
4205        FLASH_F7_OPTCR1);
4206   return stlink_read_debug32(sl, FLASH_F7_OPTCR1, option_byte);
4207 }
4208 
4209 /**
4210  * Read option bytes
4211  * @param sl
4212  * @param option_byte value to read
4213  * @return 0 on success, -ve on failure.
4214  */
stlink_read_option_bytes_boot_add_f7(stlink_t * sl,uint32_t * option_byte)4215 int stlink_read_option_bytes_boot_add_f7(stlink_t *sl, uint32_t *option_byte) {
4216   DLOG("@@@@ Read option byte boot address\n");
4217   return stlink_read_option_control_register1_f7(sl, option_byte);
4218 }
4219 
4220 /**
4221  * Read option bytes
4222  * @param sl
4223  * @param option_byte value to read
4224  * @return 0 on success, -ve on failure.
4225  *
4226  * Since multiple bytes can be read, we read and print all but one here
4227  * and then return the last one just like other devices
4228  */
stlink_read_option_bytes_f7(stlink_t * sl,uint32_t * option_byte)4229 int stlink_read_option_bytes_f7(stlink_t *sl, uint32_t *option_byte) {
4230   int err = -1;
4231   for (uint32_t counter = 0; counter < (sl->option_size / 4 - 1); counter++) {
4232     err = stlink_read_debug32(sl, sl->option_base + counter * sizeof(uint32_t),
4233                               option_byte);
4234     if (err == -1) {
4235       return err;
4236     } else {
4237       printf("%08x\n", *option_byte);
4238     }
4239   }
4240 
4241   return stlink_read_debug32(
4242       sl,
4243       sl->option_base + (uint32_t)(sl->option_size / 4 - 1) * sizeof(uint32_t),
4244       option_byte);
4245 }
4246 
4247 /**
4248  * Read first option bytes
4249  * @param sl
4250  * @param option_byte option value
4251  * @return 0 on success, -ve on failure.
4252  */
stlink_read_option_bytes_generic(stlink_t * sl,uint32_t * option_byte)4253 int stlink_read_option_bytes_generic(stlink_t *sl, uint32_t *option_byte) {
4254   DLOG("@@@@ Read option bytes boot address from %#10x\n", sl->option_base);
4255   return stlink_read_debug32(sl, sl->option_base, option_byte);
4256 }
4257 
4258 /**
4259  * Read option bytes
4260  * @param sl
4261  * @param option_byte value to read
4262  * @return 0 on success, -ve on failure.
4263  */
4264 // int stlink_read_option_bytes_boot_add_generic(stlink_t *sl, uint32_t*
4265 // option_byte) {
4266 //    DLOG("@@@@ Read option bytes boot address from %#10x\n", sl->option_base);
4267 //    return stlink_read_debug32(sl, sl->option_base, option_byte);
4268 //}
4269 
4270 /**
4271  * Read option bytes
4272  * @param sl
4273  * @param option_byte value to read
4274  * @return 0 on success, -ve on failure.
4275  */
4276 // int stlink_read_option_control_register_generic(stlink_t *sl, uint32_t*
4277 // option_byte) {
4278 //    DLOG("@@@@ Read option control register byte from %#10x\n",
4279 //    sl->option_base); return stlink_read_debug32(sl, sl->option_base,
4280 //    option_byte);
4281 //}
4282 
4283 /**
4284  * Read option bytes
4285  * @param sl
4286  * @param option_byte value to read
4287  * @return 0 on success, -ve on failure.
4288  */
4289 // int stlink_read_option_control_register1_generic(stlink_t *sl, uint32_t*
4290 // option_byte) {
4291 //    DLOG("@@@@ Read option control register 1 byte from %#10x\n",
4292 //    sl->option_base); return stlink_read_debug32(sl, sl->option_base,
4293 //    option_byte);
4294 //}
4295 
4296 /**
4297  * Read option bytes
4298  * @param sl
4299  * @param option_byte option value
4300  * @return 0 on success, -ve on failure.
4301  */
stlink_read_option_bytes32(stlink_t * sl,uint32_t * option_byte)4302 int stlink_read_option_bytes32(stlink_t *sl, uint32_t *option_byte) {
4303   if (sl->option_base == 0) {
4304     ELOG("Option bytes read is currently not supported for connected chip\n");
4305     return (-1);
4306   }
4307 
4308   switch (sl->chip_id) {
4309   case STLINK_CHIPID_STM32_F2:
4310     return stlink_read_option_bytes_f2(sl, option_byte);
4311   case STLINK_CHIPID_STM32_F4:
4312   case STLINK_CHIPID_STM32_F446:
4313     return stlink_read_option_bytes_f4(sl, option_byte);
4314   case STLINK_CHIPID_STM32_F7XXXX:
4315     return stlink_read_option_bytes_f7(sl, option_byte);
4316   case STLINK_CHIPID_STM32_G0_CAT1:
4317   case STLINK_CHIPID_STM32_G0_CAT2:
4318   case STLINK_CHIPID_STM32_G4_CAT2:
4319   case STLINK_CHIPID_STM32_G4_CAT3:
4320     return stlink_read_option_bytes_Gx(sl, option_byte);
4321   default:
4322     return stlink_read_option_bytes_generic(sl, option_byte);
4323   }
4324 }
4325 
4326 /**
4327  * Read option bytes
4328  * @param sl
4329  * @param option_byte option value
4330  * @return 0 on success, -ve on failure.
4331  */
stlink_read_option_bytes_boot_add32(stlink_t * sl,uint32_t * option_byte)4332 int stlink_read_option_bytes_boot_add32(stlink_t *sl, uint32_t *option_byte) {
4333   if (sl->option_base == 0) {
4334     ELOG("Option bytes boot address read is currently not supported for "
4335          "connected chip\n");
4336     return -1;
4337   }
4338 
4339   switch (sl->chip_id) {
4340   case STLINK_CHIPID_STM32_F7XXXX:
4341     return stlink_read_option_bytes_boot_add_f7(sl, option_byte);
4342   default:
4343     return -1;
4344     // return stlink_read_option_bytes_boot_add_generic(sl, option_byte);
4345   }
4346 }
4347 
4348 /**
4349  * Read option bytes
4350  * @param sl
4351  * @param option_byte option value
4352  * @return 0 on success, -ve on failure.
4353  */
stlink_read_option_control_register32(stlink_t * sl,uint32_t * option_byte)4354 int stlink_read_option_control_register32(stlink_t *sl, uint32_t *option_byte) {
4355   if (sl->option_base == 0) {
4356     ELOG("Option bytes read is currently not supported for connected chip\n");
4357     return -1;
4358   }
4359 
4360   switch (sl->chip_id) {
4361   case STLINK_CHIPID_STM32_F7XXXX:
4362     return stlink_read_option_control_register_f7(sl, option_byte);
4363   default:
4364     return -1;
4365     // return stlink_read_option_control_register_generic(sl, option_byte);
4366   }
4367 }
4368 
4369 /**
4370  * Read option bytes
4371  * @param sl
4372  * @param option_byte option value
4373  * @return 0 on success, -ve on failure.
4374  */
stlink_read_option_control_register1_32(stlink_t * sl,uint32_t * option_byte)4375 int stlink_read_option_control_register1_32(stlink_t *sl,
4376                                             uint32_t *option_byte) {
4377   if (sl->option_base == 0) {
4378     ELOG("Option bytes read is currently not supported for connected chip\n");
4379     return -1;
4380   }
4381 
4382   switch (sl->chip_id) {
4383   case STLINK_CHIPID_STM32_F7XXXX:
4384     return stlink_read_option_control_register1_f7(sl, option_byte);
4385   default:
4386     return -1;
4387     // return stlink_read_option_control_register1_generic(sl, option_byte);
4388   }
4389 }
4390 
4391 /**
4392  * Write option bytes
4393  * @param sl
4394  * @param option_byte value to write
4395  * @return 0 on success, -ve on failure.
4396  */
stlink_write_option_bytes32(stlink_t * sl,uint32_t option_byte)4397 int stlink_write_option_bytes32(stlink_t *sl, uint32_t option_byte) {
4398   WLOG("About to write option byte %#10x to %#10x.\n", option_byte,
4399        sl->option_base);
4400   return stlink_write_option_bytes(sl, sl->option_base, (uint8_t *)&option_byte,
4401                                    4);
4402 }
4403 
4404 /**
4405  * Write option bytes
4406  * @param sl
4407  * @param addr of the memory mapped option bytes
4408  * @param base option bytes to write
4409  * @return 0 on success, -ve on failure.
4410  */
stlink_write_option_bytes(stlink_t * sl,stm32_addr_t addr,uint8_t * base,uint32_t len)4411 int stlink_write_option_bytes(stlink_t *sl, stm32_addr_t addr, uint8_t *base,
4412                               uint32_t len) {
4413   int ret = -1;
4414 
4415   if (sl->option_base == 0) {
4416     ELOG(
4417         "Option bytes writing is currently not supported for connected chip\n");
4418     return (-1);
4419   }
4420 
4421   if ((addr < sl->option_base) || addr > sl->option_base + sl->option_size) {
4422     ELOG("Option bytes start address out of Option bytes range\n");
4423     return (-1);
4424   }
4425 
4426   if (addr + len > sl->option_base + sl->option_size) {
4427     ELOG("Option bytes data too long\n");
4428     return (-1);
4429   }
4430 
4431   wait_flash_busy(sl);
4432 
4433   if (unlock_flash_if(sl)) {
4434     ELOG("Flash unlock failed! System reset required to be able to unlock it "
4435          "again!\n");
4436     return (-1);
4437   }
4438 
4439   if (unlock_flash_option_if(sl)) {
4440     ELOG("Flash option unlock failed!\n");
4441     return (-1);
4442   }
4443 
4444   switch (sl->flash_type) {
4445   case STLINK_FLASH_TYPE_F4:
4446     ret = stlink_write_option_bytes_f4(sl, base, addr, len);
4447     break;
4448   case STLINK_FLASH_TYPE_F7:
4449     ret = stlink_write_option_bytes_f7(sl, base, addr, len);
4450     break;
4451   case STLINK_FLASH_TYPE_L0:
4452     ret = stlink_write_option_bytes_l0(sl, base, addr, len);
4453     break;
4454   case STLINK_FLASH_TYPE_L4:
4455     ret = stlink_write_option_bytes_l4(sl, base, addr, len);
4456     break;
4457   case STLINK_FLASH_TYPE_G0:
4458   case STLINK_FLASH_TYPE_G4:
4459     ret = stlink_write_option_bytes_gx(sl, base, addr, len);
4460     break;
4461   case STLINK_FLASH_TYPE_H7:
4462     ret = stlink_write_option_bytes_h7(sl, base, addr, len);
4463     break;
4464   default:
4465     ELOG("Option bytes writing is currently not implemented for connected "
4466          "chip\n");
4467     break;
4468   }
4469 
4470   if (ret) {
4471     ELOG("Flash option write failed!\n");
4472   } else {
4473     ILOG("Wrote %d option bytes to %#010x!\n", len, addr);
4474   }
4475 
4476   /* Re-lock flash. */
4477   lock_flash_option(sl);
4478   lock_flash(sl);
4479 
4480   return ret;
4481 }
4482 
4483 /**
4484  * Write option bytes
4485  * @param sl
4486  * @param option_byte value to write
4487  * @return 0 on success, -ve on failure.
4488  */
4489 static int
stlink_write_option_control_register_f7(stlink_t * sl,uint32_t option_control_register)4490 stlink_write_option_control_register_f7(stlink_t *sl,
4491                                         uint32_t option_control_register) {
4492   int ret = 0;
4493 
4494   // Clear errors
4495   clear_flash_error(sl);
4496 
4497   ILOG("Asked to write option control register 1 %#10x to %#010x.\n",
4498        option_control_register, FLASH_F7_OPTCR);
4499 
4500   /* write option byte, ensuring we dont lock opt, and set strt bit */
4501   stlink_write_debug32(sl, FLASH_F7_OPTCR,
4502                        (option_control_register & ~(1 << FLASH_F7_OPTCR_LOCK)) |
4503                            (1 << FLASH_F7_OPTCR_START));
4504 
4505   wait_flash_busy(sl);
4506 
4507   ret = check_flash_error(sl);
4508   if (!ret)
4509     ILOG("Wrote option bytes %#010x to %#010x!\n", option_control_register,
4510          FLASH_F7_OPTCR);
4511 
4512   return ret;
4513 }
4514 
4515 /**
4516  * Write option bytes
4517  * @param sl
4518  * @param option_byte value to write
4519  * @return 0 on success, -ve on failure.
4520  */
4521 static int
stlink_write_option_control_register1_f7(stlink_t * sl,uint32_t option_control_register1)4522 stlink_write_option_control_register1_f7(stlink_t *sl,
4523                                          uint32_t option_control_register1) {
4524   int ret = 0;
4525 
4526   // Clear errors
4527   clear_flash_error(sl);
4528 
4529   ILOG("Asked to write option control register 1 %#010x to %#010x.\n",
4530        option_control_register1, FLASH_F7_OPTCR1);
4531 
4532   /* write option byte, ensuring we dont lock opt, and set strt bit */
4533   uint32_t current_control_register_value;
4534   stlink_read_debug32(sl, FLASH_F7_OPTCR, &current_control_register_value);
4535 
4536   /* write option byte */
4537   stlink_write_debug32(sl, FLASH_F7_OPTCR1, option_control_register1);
4538   stlink_write_debug32(
4539       sl, FLASH_F7_OPTCR,
4540       (current_control_register_value & ~(1 << FLASH_F7_OPTCR_LOCK)) |
4541           (1 << FLASH_F7_OPTCR_START));
4542 
4543   wait_flash_busy(sl);
4544 
4545   ret = check_flash_error(sl);
4546   if (!ret)
4547     ILOG("Wrote option bytes %#010x to %#010x!\n", option_control_register1,
4548          FLASH_F7_OPTCR1);
4549 
4550   return ret;
4551 }
4552 
4553 /**
4554  * Write option bytes
4555  * @param sl
4556  * @param option_byte value to write
4557  * @return 0 on success, -ve on failure.
4558  */
4559 static int
stlink_write_option_bytes_boot_add_f7(stlink_t * sl,uint32_t option_byte_boot_add)4560 stlink_write_option_bytes_boot_add_f7(stlink_t *sl,
4561                                       uint32_t option_byte_boot_add) {
4562   ILOG("Asked to write option byte boot add %#010x.\n", option_byte_boot_add);
4563   return stlink_write_option_control_register1_f7(sl, option_byte_boot_add);
4564 }
4565 
4566 /**
4567  * Write option bytes
4568  * @param sl
4569  * @param option bytes boot address to write
4570  * @return 0 on success, -ve on failure.
4571  */
stlink_write_option_bytes_boot_add32(stlink_t * sl,uint32_t option_bytes_boot_add)4572 int stlink_write_option_bytes_boot_add32(stlink_t *sl,
4573                                          uint32_t option_bytes_boot_add) {
4574   int ret = -1;
4575 
4576   wait_flash_busy(sl);
4577 
4578   if (unlock_flash_if(sl)) {
4579     ELOG("Flash unlock failed! System reset required to be able to unlock it "
4580          "again!\n");
4581     return -1;
4582   }
4583 
4584   if (unlock_flash_option_if(sl)) {
4585     ELOG("Flash option unlock failed!\n");
4586     return -1;
4587   }
4588 
4589   switch (sl->flash_type) {
4590   case STLINK_FLASH_TYPE_F7:
4591     ret = stlink_write_option_bytes_boot_add_f7(sl, option_bytes_boot_add);
4592     break;
4593   default:
4594     ELOG("Option bytes boot address writing is currently not implemented for "
4595          "connected chip\n");
4596     break;
4597   }
4598 
4599   if (ret)
4600     ELOG("Flash option write failed!\n");
4601   else
4602     ILOG("Wrote option bytes boot address %#010x!\n", option_bytes_boot_add);
4603 
4604   /* Re-lock flash. */
4605   lock_flash_option(sl);
4606   lock_flash(sl);
4607 
4608   return ret;
4609 }
4610 
4611 /**
4612  * Write option bytes
4613  * @param sl
4614  * @param option bytes boot address to write
4615  * @return 0 on success, -ve on failure.
4616  */
stlink_write_option_control_register32(stlink_t * sl,uint32_t option_control_register)4617 int stlink_write_option_control_register32(stlink_t *sl,
4618                                            uint32_t option_control_register) {
4619   int ret = -1;
4620 
4621   wait_flash_busy(sl);
4622 
4623   if (unlock_flash_if(sl)) {
4624     ELOG("Flash unlock failed! System reset required to be able to unlock it "
4625          "again!\n");
4626     return -1;
4627   }
4628 
4629   if (unlock_flash_option_if(sl)) {
4630     ELOG("Flash option unlock failed!\n");
4631     return -1;
4632   }
4633 
4634   switch (sl->flash_type) {
4635   case STLINK_FLASH_TYPE_F7:
4636     ret = stlink_write_option_control_register_f7(sl, option_control_register);
4637     break;
4638   default:
4639     ELOG("Option control register writing is currently not implemented for "
4640          "connected chip\n");
4641     break;
4642   }
4643 
4644   if (ret)
4645     ELOG("Flash option write failed!\n");
4646   else
4647     ILOG("Wrote option control register %#010x!\n", option_control_register);
4648 
4649   /* Re-lock flash. */
4650   lock_flash_option(sl);
4651   lock_flash(sl);
4652 
4653   return ret;
4654 }
4655 
4656 /**
4657  * Write option bytes
4658  * @param sl
4659  * @param option bytes boot address to write
4660  * @return 0 on success, -ve on failure.
4661  */
stlink_write_option_control_register1_32(stlink_t * sl,uint32_t option_control_register1)4662 int stlink_write_option_control_register1_32(
4663     stlink_t *sl, uint32_t option_control_register1) {
4664   int ret = -1;
4665 
4666   wait_flash_busy(sl);
4667 
4668   if (unlock_flash_if(sl)) {
4669     ELOG("Flash unlock failed! System reset required to be able to unlock it "
4670          "again!\n");
4671     return -1;
4672   }
4673 
4674   if (unlock_flash_option_if(sl)) {
4675     ELOG("Flash option unlock failed!\n");
4676     return -1;
4677   }
4678 
4679   switch (sl->flash_type) {
4680   case STLINK_FLASH_TYPE_F7:
4681     ret =
4682         stlink_write_option_control_register1_f7(sl, option_control_register1);
4683     break;
4684   default:
4685     ELOG("Option control register 1 writing is currently not implemented for "
4686          "connected chip\n");
4687     break;
4688   }
4689 
4690   if (ret)
4691     ELOG("Flash option write failed!\n");
4692   else
4693     ILOG("Wrote option control register 1 %#010x!\n", option_control_register1);
4694 
4695   lock_flash_option(sl);
4696   lock_flash(sl);
4697 
4698   return (ret);
4699 }
4700 
4701 /**
4702  * Write the given binary file with option bytes
4703  * @param sl
4704  * @param path readable file path, should be binary image
4705  * @param addr of the memory mapped option bytes
4706  * @return 0 on success, -ve on failure.
4707  */
stlink_fwrite_option_bytes(stlink_t * sl,const char * path,stm32_addr_t addr)4708 int stlink_fwrite_option_bytes(stlink_t *sl, const char *path,
4709                                stm32_addr_t addr) {
4710   /* Write the file in flash at addr */
4711   int err;
4712   mapped_file_t mf = MAPPED_FILE_INITIALIZER;
4713 
4714   if (map_file(&mf, path) == -1) {
4715     ELOG("map_file() == -1\n");
4716     return (-1);
4717   }
4718 
4719   printf("file %s ", path);
4720   md5_calculate(&mf);
4721   stlink_checksum(&mf);
4722 
4723   err = stlink_write_option_bytes(sl, addr, mf.base, (uint32_t)mf.len);
4724   stlink_fwrite_finalize(sl, addr);
4725   unmap_file(&mf);
4726 
4727   return (err);
4728 }
4729 
stlink_target_connect(stlink_t * sl,enum connect_type connect)4730 int stlink_target_connect(stlink_t *sl, enum connect_type connect) {
4731   uint32_t dhcsr;
4732 
4733   if (connect == CONNECT_UNDER_RESET) {
4734     stlink_jtag_reset(sl, STLINK_JTAG_DRIVE_NRST_LOW);
4735 
4736     // minimum reset pulse duration of 20 us (RM0008, 8.1.2 Power reset)
4737     usleep(20);
4738 
4739     if (stlink_current_mode(sl) != STLINK_DEV_DEBUG_MODE) {
4740       stlink_enter_swd_mode(sl);
4741     }
4742     stlink_force_debug(sl);
4743 
4744     // clear S_RESET_ST in DHCSR register
4745     stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr);
4746 
4747     stlink_jtag_reset(sl, STLINK_JTAG_DRIVE_NRST_HIGH);
4748     usleep(10000);
4749 
4750     // check NRST connection
4751     dhcsr = 0;
4752     stlink_read_debug32(sl, STLINK_REG_DHCSR, &dhcsr);
4753     if ((dhcsr & STLINK_REG_DHCSR_S_RESET_ST) == 0) {
4754       WLOG("NRST is not connected\n");
4755     }
4756 
4757     // addition soft reset for halt before the first instruction
4758     stlink_soft_reset(sl, 1 /* halt on reset */);
4759   }
4760 
4761   if (stlink_current_mode(sl) != STLINK_DEV_DEBUG_MODE) {
4762     stlink_enter_swd_mode(sl);
4763   }
4764 
4765   if (connect == CONNECT_NORMAL) {
4766     stlink_reset(sl, RESET_AUTO);
4767   }
4768 
4769   return stlink_load_device_params(sl);
4770 }
4771