1 /*
2   stm32flash - Open Source ST STM32 flash program for *nix
3   Copyright 2010 Geoffrey McRae <geoff@spacevs.com>
4   Copyright 2012-2014 Tormod Volden <debian.tormod@gmail.com>
5 
6   This program is free software; you can redistribute it and/or
7   modify it under the terms of the GNU General Public License
8   as published by the Free Software Foundation; either version 2
9   of the License, or (at your option) any later version.
10 
11   This program is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15 
16   You should have received a copy of the GNU General Public License
17   along with this program; if not, write to the Free Software
18   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 */
20 
21 #include <stdlib.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <time.h>
26 #include <unistd.h>
27 
28 #include "stm32.h"
29 #include "port.h"
30 #include "utils.h"
31 
32 #define STM32_ACK	0x79
33 #define STM32_NACK	0x1F
34 #define STM32_BUSY	0x76
35 
36 #define STM32_CMD_INIT	0x7F
37 #define STM32_CMD_GET	0x00	/* get the version and command supported */
38 #define STM32_CMD_GVR	0x01	/* get version and read protection status */
39 #define STM32_CMD_GID	0x02	/* get ID */
40 #define STM32_CMD_RM	0x11	/* read memory */
41 #define STM32_CMD_GO	0x21	/* go */
42 #define STM32_CMD_WM	0x31	/* write memory */
43 #define STM32_CMD_WM_NS	0x32	/* no-stretch write memory */
44 #define STM32_CMD_ER	0x43	/* erase */
45 #define STM32_CMD_EE	0x44	/* extended erase */
46 #define STM32_CMD_EE_NS	0x45	/* extended erase no-stretch */
47 #define STM32_CMD_WP	0x63	/* write protect */
48 #define STM32_CMD_WP_NS	0x64	/* write protect no-stretch */
49 #define STM32_CMD_UW	0x73	/* write unprotect */
50 #define STM32_CMD_UW_NS	0x74	/* write unprotect no-stretch */
51 #define STM32_CMD_RP	0x82	/* readout protect */
52 #define STM32_CMD_RP_NS	0x83	/* readout protect no-stretch */
53 #define STM32_CMD_UR	0x92	/* readout unprotect */
54 #define STM32_CMD_UR_NS	0x93	/* readout unprotect no-stretch */
55 #define STM32_CMD_CRC	0xA1	/* compute CRC */
56 #define STM32_CMD_ERR	0xFF	/* not a valid command */
57 
58 #define STM32_RESYNC_TIMEOUT	35	/* seconds */
59 #define STM32_MASSERASE_TIMEOUT	35	/* seconds */
60 #define STM32_PAGEERASE_TIMEOUT	5	/* seconds */
61 #define STM32_BLKWRITE_TIMEOUT	1	/* seconds */
62 #define STM32_WUNPROT_TIMEOUT	1	/* seconds */
63 #define STM32_WPROT_TIMEOUT	1	/* seconds */
64 #define STM32_RPROT_TIMEOUT	1	/* seconds */
65 
66 #define STM32_CMD_GET_LENGTH	17	/* bytes in the reply */
67 
68 struct stm32_cmd {
69 	uint8_t get;
70 	uint8_t gvr;
71 	uint8_t gid;
72 	uint8_t rm;
73 	uint8_t go;
74 	uint8_t wm;
75 	uint8_t er; /* this may be extended erase */
76 	uint8_t wp;
77 	uint8_t uw;
78 	uint8_t rp;
79 	uint8_t ur;
80 	uint8_t	crc;
81 };
82 
83 /* Reset code for ARMv7-M (Cortex-M3) and ARMv6-M (Cortex-M0)
84  * see ARMv7-M or ARMv6-M Architecture Reference Manual (table B3-8)
85  * or "The definitive guide to the ARM Cortex-M3", section 14.4.
86  */
87 static const uint8_t stm_reset_code[] = {
88 	0x01, 0x49,		// ldr     r1, [pc, #4] ; (<AIRCR_OFFSET>)
89 	0x02, 0x4A,		// ldr     r2, [pc, #8] ; (<AIRCR_RESET_VALUE>)
90 	0x0A, 0x60,		// str     r2, [r1, #0]
91 	0xfe, 0xe7,		// endless: b endless
92 	0x0c, 0xed, 0x00, 0xe0,	// .word 0xe000ed0c <AIRCR_OFFSET> = NVIC AIRCR register address
93 	0x04, 0x00, 0xfa, 0x05	// .word 0x05fa0004 <AIRCR_RESET_VALUE> = VECTKEY | SYSRESETREQ
94 };
95 
96 static const uint32_t stm_reset_code_length = sizeof(stm_reset_code);
97 
98 /* RM0360, Empty check
99  * On STM32F070x6 and STM32F030xC devices only, internal empty check flag is
100  * implemented to allow easy programming of the virgin devices by the boot loader. This flag is
101  * used when BOOT0 pin is defining Main Flash memory as the target boot space. When the
102  * flag is set, the device is considered as empty and System memory (boot loader) is selected
103  * instead of the Main Flash as a boot space to allow user to program the Flash memory.
104  * This flag is updated only during Option bytes loading: it is set when the content of the
105  * address 0x08000 0000 is read as 0xFFFF FFFF, otherwise it is cleared. It means a power
106  * on or setting of OBL_LAUNCH bit in FLASH_CR register is needed to clear this flag after
107  * programming of a virgin device to execute user code after System reset.
108  */
109 static const uint8_t stm_obl_launch_code[] = {
110 	0x01, 0x49,		// ldr     r1, [pc, #4] ; (<FLASH_CR>)
111 	0x02, 0x4A,		// ldr     r2, [pc, #8] ; (<OBL_LAUNCH>)
112 	0x0A, 0x60,		// str     r2, [r1, #0]
113 	0xfe, 0xe7,		// endless: b endless
114 	0x10, 0x20, 0x02, 0x40, // address: FLASH_CR = 40022010
115 	0x00, 0x20, 0x00, 0x00  // value: OBL_LAUNCH = 00002000
116 };
117 
118 static const uint32_t stm_obl_launch_code_length = sizeof(stm_obl_launch_code);
119 
120 /* RM0394, Empty check
121  * On STM32L452 (and possibly all STM32L45xxx/46xxx) internal empty check flag is
122  * implemented to allow easy programming of the virgin devices by the boot loader. This flag is
123  * used when BOOT0 pin is defining Main Flash memory as the target boot space. When the
124  * flag is set, the device is considered as empty and System memory (boot loader) is selected
125  * instead of the Main Flash as a boot space to allow user to program the Flash memory.
126  * This flag is updated only during Option bytes loading: it is set when the content of the
127  * address 0x08000 0000 is read as 0xFFFF FFFF, otherwise it is cleared. It means a power
128  * on or setting of OBL_LAUNCH bit in FLASH_CR register or a toggle of PEMPTY bit in FLASH_SR
129  * register is needed to clear this flag after after programming of a virgin device to execute
130  * user code after System reset.
131  * In STM32L45xxx/46xxx the register FLASH_CR could be locked and a special SW sequence is
132  * required for unlocking it. If a previous unsuccessful unlock has happened, a reset is
133  * required before the unlock. Due to such complications, toggling the PEMPTY bit in FLASH_SR
134  * seams the most reasonable choice.
135  * The code below check first word in flash and flag PEMPTY. If they do not match, then it
136  * toggles PEMPTY. At last, it resets.
137  */
138 
139 static const uint8_t stm_pempty_launch_code[] = {
140 	0x08, 0x48,		//		ldr     r0, [pc, #32] ; (<BASE_FLASH>)
141 	0x00, 0x68,		//		ldr     r0, [r0, #0]
142 	0x01, 0x30,		//		adds    r0, #1
143 	0x41, 0x1e,		//		subs    r1, r0, #1
144 	0x88, 0x41,		//		sbcs    r0, r1
145 
146 	0x07, 0x49,		//		ldr     r1, [pc, #28] ; (<FLASH_SR>)
147 	0x07, 0x4a,		//		ldr     r2, [pc, #28] ; (<PEMPTY_MASK>)
148 	0x0b, 0x68,		//		ldr     r3, [r1, #0]
149 	0x13, 0x40,		//		ands    r3, r2
150 	0x5c, 0x1e,		//		subs    r4, r3, #1
151 	0xa3, 0x41,		//		sbcs    r3, r4
152 
153 	0x98, 0x42,		//		cmp     r0, r3
154 	0x00, 0xd1,		//		bne.n   skip1
155 
156 	0x0a, 0x60,		//		str     r2, [r1, #0]
157 
158 	0x04, 0x48,		// skip1:	ldr     r0, [pc, #16] ; (<AIRCR_OFFSET>)
159 	0x05, 0x49,		//		ldr     r1, [pc, #16] ; (<AIRCR_RESET_VALUE>)
160 	0x01, 0x60,		//		str     r1, [r0, #0]
161 
162 	0xfe, 0xe7,		// endless:	b.n	endless
163 
164 	0x00, 0x00, 0x00, 0x08,	// .word 0x08000000 <BASE_FLASH>
165 	0x10, 0x20, 0x02, 0x40,	// .word 0x40022010 <FLASH_SR>
166 	0x00, 0x00, 0x02, 0x00,	// .word 0x00020000 <PEMPTY_MASK>
167 	0x0c, 0xed, 0x00, 0xe0,	// .word 0xe000ed0c <AIRCR_OFFSET> = NVIC AIRCR register address
168 	0x04, 0x00, 0xfa, 0x05	// .word 0x05fa0004 <AIRCR_RESET_VALUE> = VECTKEY | SYSRESETREQ
169 };
170 
171 static const uint32_t stm_pempty_launch_code_length = sizeof(stm_pempty_launch_code);
172 
173 extern const stm32_dev_t devices[];
174 
175 int flash_addr_to_page_ceil(uint32_t addr);
176 
stm32_warn_stretching(const char * f)177 static void stm32_warn_stretching(const char *f)
178 {
179 	fprintf(stderr, "Attention !!!\n");
180 	fprintf(stderr, "\tThis %s error could be caused by your I2C\n", f);
181 	fprintf(stderr, "\tcontroller not accepting \"clock stretching\"\n");
182 	fprintf(stderr, "\tas required by bootloader.\n");
183 	fprintf(stderr, "\tCheck \"I2C.txt\" in stm32flash source code.\n");
184 }
185 
stm32_get_ack_timeout(const stm32_t * stm,time_t timeout)186 static stm32_err_t stm32_get_ack_timeout(const stm32_t *stm, time_t timeout)
187 {
188 	struct port_interface *port = stm->port;
189 	uint8_t byte;
190 	port_err_t p_err;
191 	time_t t0, t1;
192 
193 	if (!(port->flags & PORT_RETRY))
194 		timeout = 0;
195 
196 	if (timeout)
197 		time(&t0);
198 
199 	do {
200 		p_err = port->read(port, &byte, 1);
201 		if (p_err == PORT_ERR_TIMEDOUT && timeout) {
202 			time(&t1);
203 			if (t1 < t0 + timeout)
204 				continue;
205 		}
206 
207 		if (p_err != PORT_ERR_OK) {
208 			fprintf(stderr, "Failed to read ACK byte\n");
209 			return STM32_ERR_UNKNOWN;
210 		}
211 
212 		if (byte == STM32_ACK)
213 			return STM32_ERR_OK;
214 		if (byte == STM32_NACK)
215 			return STM32_ERR_NACK;
216 		if (byte != STM32_BUSY) {
217 			fprintf(stderr, "Got byte 0x%02x instead of ACK\n",
218 				byte);
219 			return STM32_ERR_UNKNOWN;
220 		}
221 	} while (1);
222 }
223 
stm32_get_ack(const stm32_t * stm)224 static stm32_err_t stm32_get_ack(const stm32_t *stm)
225 {
226 	return stm32_get_ack_timeout(stm, 0);
227 }
228 
stm32_send_command_timeout(const stm32_t * stm,const uint8_t cmd,time_t timeout)229 static stm32_err_t stm32_send_command_timeout(const stm32_t *stm,
230 					      const uint8_t cmd,
231 					      time_t timeout)
232 {
233 	struct port_interface *port = stm->port;
234 	stm32_err_t s_err;
235 	port_err_t p_err;
236 	uint8_t buf[2];
237 
238 	buf[0] = cmd;
239 	buf[1] = cmd ^ 0xFF;
240 	p_err = port->write(port, buf, 2);
241 	if (p_err != PORT_ERR_OK) {
242 		fprintf(stderr, "Failed to send command\n");
243 		return STM32_ERR_UNKNOWN;
244 	}
245 	s_err = stm32_get_ack_timeout(stm, timeout);
246 	if (s_err == STM32_ERR_OK)
247 		return STM32_ERR_OK;
248 	if (s_err == STM32_ERR_NACK)
249 		fprintf(stderr, "Got NACK from device on command 0x%02x\n", cmd);
250 	else
251 		fprintf(stderr, "Unexpected reply from device on command 0x%02x\n", cmd);
252 	return STM32_ERR_UNKNOWN;
253 }
254 
stm32_send_command(const stm32_t * stm,const uint8_t cmd)255 static stm32_err_t stm32_send_command(const stm32_t *stm, const uint8_t cmd)
256 {
257 	return stm32_send_command_timeout(stm, cmd, 0);
258 }
259 
260 /* if we have lost sync, send a wrong command and expect a NACK */
stm32_resync(const stm32_t * stm)261 static stm32_err_t stm32_resync(const stm32_t *stm)
262 {
263 	struct port_interface *port = stm->port;
264 	port_err_t p_err;
265 	uint8_t buf[2], ack;
266 	time_t t0, t1;
267 
268 	time(&t0);
269 	t1 = t0;
270 
271 	buf[0] = STM32_CMD_ERR;
272 	buf[1] = STM32_CMD_ERR ^ 0xFF;
273 	while (t1 < t0 + STM32_RESYNC_TIMEOUT) {
274 		p_err = port->write(port, buf, 2);
275 		if (p_err != PORT_ERR_OK) {
276 			usleep(500000);
277 			time(&t1);
278 			continue;
279 		}
280 		p_err = port->read(port, &ack, 1);
281 		if (p_err != PORT_ERR_OK) {
282 			time(&t1);
283 			continue;
284 		}
285 		if (ack == STM32_NACK)
286 			return STM32_ERR_OK;
287 		time(&t1);
288 	}
289 	return STM32_ERR_UNKNOWN;
290 }
291 
292 /*
293  * some command receive reply frame with variable length, and length is
294  * embedded in reply frame itself.
295  * We can guess the length, but if we guess wrong the protocol gets out
296  * of sync.
297  * Use resync for frame oriented interfaces (e.g. I2C) and byte-by-byte
298  * read for byte oriented interfaces (e.g. UART).
299  *
300  * to run safely, data buffer should be allocated for 256+1 bytes
301  *
302  * len is value of the first byte in the frame.
303  */
stm32_guess_len_cmd(const stm32_t * stm,uint8_t cmd,uint8_t * data,unsigned int len)304 static stm32_err_t stm32_guess_len_cmd(const stm32_t *stm, uint8_t cmd,
305 				       uint8_t *data, unsigned int len)
306 {
307 	struct port_interface *port = stm->port;
308 	port_err_t p_err;
309 
310 	if (stm32_send_command(stm, cmd) != STM32_ERR_OK)
311 		return STM32_ERR_UNKNOWN;
312 	if (port->flags & PORT_BYTE) {
313 		/* interface is UART-like */
314 		p_err = port->read(port, data, 1);
315 		if (p_err != PORT_ERR_OK)
316 			return STM32_ERR_UNKNOWN;
317 		len = data[0];
318 		p_err = port->read(port, data + 1, len + 1);
319 		if (p_err != PORT_ERR_OK)
320 			return STM32_ERR_UNKNOWN;
321 		return STM32_ERR_OK;
322 	}
323 
324 	p_err = port->read(port, data, len + 2);
325 	if (p_err == PORT_ERR_OK && len == data[0])
326 		return STM32_ERR_OK;
327 	if (p_err != PORT_ERR_OK) {
328 		/* restart with only one byte */
329 		if (stm32_resync(stm) != STM32_ERR_OK)
330 			return STM32_ERR_UNKNOWN;
331 		if (stm32_send_command(stm, cmd) != STM32_ERR_OK)
332 			return STM32_ERR_UNKNOWN;
333 		p_err = port->read(port, data, 1);
334 		if (p_err != PORT_ERR_OK)
335 			return STM32_ERR_UNKNOWN;
336 	}
337 
338 	fprintf(stderr, "Re sync (len = %d)\n", data[0]);
339 	if (stm32_resync(stm) != STM32_ERR_OK)
340 		return STM32_ERR_UNKNOWN;
341 
342 	len = data[0];
343 	if (stm32_send_command(stm, cmd) != STM32_ERR_OK)
344 		return STM32_ERR_UNKNOWN;
345 	p_err = port->read(port, data, len + 2);
346 	if (p_err != PORT_ERR_OK)
347 		return STM32_ERR_UNKNOWN;
348 	return STM32_ERR_OK;
349 }
350 
351 /*
352  * Some interface, e.g. UART, requires a specific init sequence to let STM32
353  * autodetect the interface speed.
354  * The sequence is only required one time after reset.
355  * stm32flash has command line flag "-c" to prevent sending the init sequence
356  * in case it was already sent before.
357  * User can easily forget adding "-c". In this case the bootloader would
358  * interpret the init sequence as part of a command message, then waiting for
359  * the rest of the message blocking the interface.
360  * This function sends the init sequence and, in case of timeout, recovers
361  * the interface.
362  */
stm32_send_init_seq(const stm32_t * stm)363 static stm32_err_t stm32_send_init_seq(const stm32_t *stm)
364 {
365 	struct port_interface *port = stm->port;
366 	port_err_t p_err;
367 	uint8_t byte, cmd = STM32_CMD_INIT;
368 
369 	p_err = port->write(port, &cmd, 1);
370 	if (p_err != PORT_ERR_OK) {
371 		fprintf(stderr, "Failed to send init to device\n");
372 		return STM32_ERR_UNKNOWN;
373 	}
374 	p_err = port->read(port, &byte, 1);
375 	if (p_err == PORT_ERR_OK && byte == STM32_ACK)
376 		return STM32_ERR_OK;
377 	if (p_err == PORT_ERR_OK && byte == STM32_NACK) {
378 		/* We could get error later, but let's continue, for now. */
379 		fprintf(stderr,
380 			"Warning: the interface was not closed properly.\n");
381 		return STM32_ERR_OK;
382 	}
383 	if (p_err != PORT_ERR_TIMEDOUT) {
384 		fprintf(stderr, "Failed to init device.\n");
385 		return STM32_ERR_UNKNOWN;
386 	}
387 
388 	/*
389 	 * Check if previous STM32_CMD_INIT was taken as first byte
390 	 * of a command. Send a new byte, we should get back a NACK.
391 	 */
392 	p_err = port->write(port, &cmd, 1);
393 	if (p_err != PORT_ERR_OK) {
394 		fprintf(stderr, "Failed to send init to device\n");
395 		return STM32_ERR_UNKNOWN;
396 	}
397 	p_err = port->read(port, &byte, 1);
398 	if (p_err == PORT_ERR_OK && byte == STM32_NACK)
399 		return STM32_ERR_OK;
400 	fprintf(stderr, "Failed to init device.\n");
401 	return STM32_ERR_UNKNOWN;
402 }
403 
404 /* find newer command by higher code */
405 #define newer(prev, a) (((prev) == STM32_CMD_ERR) \
406 			? (a) \
407 			: (((prev) > (a)) ? (prev) : (a)))
408 
stm32_init(struct port_interface * port,const char init)409 stm32_t *stm32_init(struct port_interface *port, const char init)
410 {
411 	uint8_t len, val, buf[257];
412 	stm32_t *stm;
413 	int i, new_cmds;
414 
415 	stm      = calloc(sizeof(stm32_t), 1);
416 	stm->cmd = malloc(sizeof(stm32_cmd_t));
417 	memset(stm->cmd, STM32_CMD_ERR, sizeof(stm32_cmd_t));
418 	stm->port = port;
419 
420 	if ((port->flags & PORT_CMD_INIT) && init)
421 		if (stm32_send_init_seq(stm) != STM32_ERR_OK)
422 			return NULL;
423 
424 	/* get the version and read protection status  */
425 	if (stm32_send_command(stm, STM32_CMD_GVR) != STM32_ERR_OK) {
426 		stm32_close(stm);
427 		return NULL;
428 	}
429 
430 	/* From AN, only UART bootloader returns 3 bytes */
431 	len = (port->flags & PORT_GVR_ETX) ? 3 : 1;
432 	if (port->read(port, buf, len) != PORT_ERR_OK)
433 		return NULL;
434 	stm->version = buf[0];
435 	stm->option1 = (port->flags & PORT_GVR_ETX) ? buf[1] : 0;
436 	stm->option2 = (port->flags & PORT_GVR_ETX) ? buf[2] : 0;
437 	if (stm32_get_ack(stm) != STM32_ERR_OK) {
438 		stm32_close(stm);
439 		return NULL;
440 	}
441 
442 	/* get the bootloader information */
443 	len = STM32_CMD_GET_LENGTH;
444 	if (port->cmd_get_reply)
445 		for (i = 0; port->cmd_get_reply[i].length; i++)
446 			if (stm->version == port->cmd_get_reply[i].version) {
447 				len = port->cmd_get_reply[i].length;
448 				break;
449 			}
450 	if (stm32_guess_len_cmd(stm, STM32_CMD_GET, buf, len) != STM32_ERR_OK)
451 		return NULL;
452 	len = buf[0] + 1;
453 	stm->bl_version = buf[1];
454 	new_cmds = 0;
455 	for (i = 1; i < len; i++) {
456 		val = buf[i + 1];
457 		switch (val) {
458 		case STM32_CMD_GET:
459 			stm->cmd->get = val; break;
460 		case STM32_CMD_GVR:
461 			stm->cmd->gvr = val; break;
462 		case STM32_CMD_GID:
463 			stm->cmd->gid = val; break;
464 		case STM32_CMD_RM:
465 			stm->cmd->rm = val; break;
466 		case STM32_CMD_GO:
467 			stm->cmd->go = val; break;
468 		case STM32_CMD_WM:
469 		case STM32_CMD_WM_NS:
470 			stm->cmd->wm = newer(stm->cmd->wm, val);
471 			break;
472 		case STM32_CMD_ER:
473 		case STM32_CMD_EE:
474 		case STM32_CMD_EE_NS:
475 			stm->cmd->er = newer(stm->cmd->er, val);
476 			break;
477 		case STM32_CMD_WP:
478 		case STM32_CMD_WP_NS:
479 			stm->cmd->wp = newer(stm->cmd->wp, val);
480 			break;
481 		case STM32_CMD_UW:
482 		case STM32_CMD_UW_NS:
483 			stm->cmd->uw = newer(stm->cmd->uw, val);
484 			break;
485 		case STM32_CMD_RP:
486 		case STM32_CMD_RP_NS:
487 			stm->cmd->rp = newer(stm->cmd->rp, val);
488 			break;
489 		case STM32_CMD_UR:
490 		case STM32_CMD_UR_NS:
491 			stm->cmd->ur = newer(stm->cmd->ur, val);
492 			break;
493 		case STM32_CMD_CRC:
494 			stm->cmd->crc = newer(stm->cmd->crc, val);
495 			break;
496 		default:
497 			if (new_cmds++ == 0)
498 				fprintf(stderr,
499 					"GET returns unknown commands (0x%2x",
500 					val);
501 			else
502 				fprintf(stderr, ", 0x%2x", val);
503 		}
504 	}
505 	if (new_cmds)
506 		fprintf(stderr, ")\n");
507 	if (stm32_get_ack(stm) != STM32_ERR_OK) {
508 		stm32_close(stm);
509 		return NULL;
510 	}
511 
512 	if (stm->cmd->get == STM32_CMD_ERR
513 	    || stm->cmd->gvr == STM32_CMD_ERR
514 	    || stm->cmd->gid == STM32_CMD_ERR) {
515 		fprintf(stderr, "Error: bootloader did not returned correct information from GET command\n");
516 		return NULL;
517 	}
518 
519 	/* get the device ID */
520 	if (stm32_guess_len_cmd(stm, stm->cmd->gid, buf, 1) != STM32_ERR_OK) {
521 		stm32_close(stm);
522 		return NULL;
523 	}
524 	len = buf[0] + 1;
525 	if (len < 2) {
526 		stm32_close(stm);
527 		fprintf(stderr, "Only %d bytes sent in the PID, unknown/unsupported device\n", len);
528 		return NULL;
529 	}
530 	stm->pid = (buf[1] << 8) | buf[2];
531 	if (len > 2) {
532 		fprintf(stderr, "This bootloader returns %d extra bytes in PID:", len);
533 		for (i = 2; i <= len ; i++)
534 			fprintf(stderr, " %02x", buf[i]);
535 		fprintf(stderr, "\n");
536 	}
537 	if (stm32_get_ack(stm) != STM32_ERR_OK) {
538 		stm32_close(stm);
539 		return NULL;
540 	}
541 
542 	stm->dev = devices;
543 	while (stm->dev->id != 0x00 && stm->dev->id != stm->pid)
544 		++stm->dev;
545 
546 	if (!stm->dev->id) {
547 		fprintf(stderr, "Unknown/unsupported device (Device ID: 0x%03x)\n", stm->pid);
548 		stm32_close(stm);
549 		return NULL;
550 	}
551 
552 	return stm;
553 }
554 
stm32_close(stm32_t * stm)555 void stm32_close(stm32_t *stm)
556 {
557 	if (stm)
558 		free(stm->cmd);
559 	free(stm);
560 }
561 
stm32_read_memory(const stm32_t * stm,uint32_t address,uint8_t data[],unsigned int len)562 stm32_err_t stm32_read_memory(const stm32_t *stm, uint32_t address,
563 			      uint8_t data[], unsigned int len)
564 {
565 	struct port_interface *port = stm->port;
566 	uint8_t buf[5];
567 
568 	if (!len)
569 		return STM32_ERR_OK;
570 
571 	if (len > 256) {
572 		fprintf(stderr, "Error: READ length limit at 256 bytes\n");
573 		return STM32_ERR_UNKNOWN;
574 	}
575 
576 	if (stm->cmd->rm == STM32_CMD_ERR) {
577 		fprintf(stderr, "Error: READ command not implemented in bootloader.\n");
578 		return STM32_ERR_NO_CMD;
579 	}
580 
581 	if (stm32_send_command(stm, stm->cmd->rm) != STM32_ERR_OK)
582 		return STM32_ERR_UNKNOWN;
583 
584 	buf[0] = address >> 24;
585 	buf[1] = (address >> 16) & 0xFF;
586 	buf[2] = (address >> 8) & 0xFF;
587 	buf[3] = address & 0xFF;
588 	buf[4] = buf[0] ^ buf[1] ^ buf[2] ^ buf[3];
589 	if (port->write(port, buf, 5) != PORT_ERR_OK)
590 		return STM32_ERR_UNKNOWN;
591 	if (stm32_get_ack(stm) != STM32_ERR_OK)
592 		return STM32_ERR_UNKNOWN;
593 
594 	if (stm32_send_command(stm, len - 1) != STM32_ERR_OK)
595 		return STM32_ERR_UNKNOWN;
596 
597 	if (port->read(port, data, len) != PORT_ERR_OK)
598 		return STM32_ERR_UNKNOWN;
599 
600 	return STM32_ERR_OK;
601 }
602 
stm32_write_memory(const stm32_t * stm,uint32_t address,const uint8_t data[],unsigned int len)603 stm32_err_t stm32_write_memory(const stm32_t *stm, uint32_t address,
604 			       const uint8_t data[], unsigned int len)
605 {
606 	struct port_interface *port = stm->port;
607 	uint8_t cs, buf[256 + 2];
608 	unsigned int i, aligned_len;
609 	stm32_err_t s_err;
610 
611 	if (!len)
612 		return STM32_ERR_OK;
613 
614 	if (len > 256) {
615 		fprintf(stderr, "Error: READ length limit at 256 bytes\n");
616 		return STM32_ERR_UNKNOWN;
617 	}
618 
619 	/* must be 32bit aligned */
620 	if (address & 0x3) {
621 		fprintf(stderr, "Error: WRITE address must be 4 byte aligned\n");
622 		return STM32_ERR_UNKNOWN;
623 	}
624 
625 	if (stm->cmd->wm == STM32_CMD_ERR) {
626 		fprintf(stderr, "Error: WRITE command not implemented in bootloader.\n");
627 		return STM32_ERR_NO_CMD;
628 	}
629 
630 	/* send the address and checksum */
631 	if (stm32_send_command(stm, stm->cmd->wm) != STM32_ERR_OK)
632 		return STM32_ERR_UNKNOWN;
633 
634 	buf[0] = address >> 24;
635 	buf[1] = (address >> 16) & 0xFF;
636 	buf[2] = (address >> 8) & 0xFF;
637 	buf[3] = address & 0xFF;
638 	buf[4] = buf[0] ^ buf[1] ^ buf[2] ^ buf[3];
639 	if (port->write(port, buf, 5) != PORT_ERR_OK)
640 		return STM32_ERR_UNKNOWN;
641 	if (stm32_get_ack(stm) != STM32_ERR_OK)
642 		return STM32_ERR_UNKNOWN;
643 
644 	aligned_len = (len + 3) & ~3;
645 	cs = aligned_len - 1;
646 	buf[0] = aligned_len - 1;
647 	for (i = 0; i < len; i++) {
648 		cs ^= data[i];
649 		buf[i + 1] = data[i];
650 	}
651 	/* padding data */
652 	for (i = len; i < aligned_len; i++) {
653 		cs ^= 0xFF;
654 		buf[i + 1] = 0xFF;
655 	}
656 	buf[aligned_len + 1] = cs;
657 	if (port->write(port, buf, aligned_len + 2) != PORT_ERR_OK)
658 		return STM32_ERR_UNKNOWN;
659 
660 	s_err = stm32_get_ack_timeout(stm, STM32_BLKWRITE_TIMEOUT);
661 	if (s_err != STM32_ERR_OK) {
662 		if ((port->flags & PORT_STRETCH_W)
663 		    && stm->cmd->wm != STM32_CMD_WM_NS)
664 			stm32_warn_stretching("write");
665 		return STM32_ERR_UNKNOWN;
666 	}
667 	return STM32_ERR_OK;
668 }
669 
stm32_wunprot_memory(const stm32_t * stm)670 stm32_err_t stm32_wunprot_memory(const stm32_t *stm)
671 {
672 	struct port_interface *port = stm->port;
673 	stm32_err_t s_err;
674 
675 	if (stm->cmd->uw == STM32_CMD_ERR) {
676 		fprintf(stderr, "Error: WRITE UNPROTECT command not implemented in bootloader.\n");
677 		return STM32_ERR_NO_CMD;
678 	}
679 
680 	if (stm32_send_command(stm, stm->cmd->uw) != STM32_ERR_OK)
681 		return STM32_ERR_UNKNOWN;
682 
683 	s_err = stm32_get_ack_timeout(stm, STM32_WUNPROT_TIMEOUT);
684 	if (s_err == STM32_ERR_NACK) {
685 		fprintf(stderr, "Error: Failed to WRITE UNPROTECT\n");
686 		return STM32_ERR_UNKNOWN;
687 	}
688 	if (s_err != STM32_ERR_OK) {
689 		if ((port->flags & PORT_STRETCH_W)
690 		    && stm->cmd->uw != STM32_CMD_UW_NS)
691 			stm32_warn_stretching("WRITE UNPROTECT");
692 		return STM32_ERR_UNKNOWN;
693 	}
694 	return STM32_ERR_OK;
695 }
696 
stm32_wprot_memory(const stm32_t * stm)697 stm32_err_t stm32_wprot_memory(const stm32_t *stm)
698 {
699 	struct port_interface *port = stm->port;
700 	stm32_err_t s_err;
701 
702 	if (stm->cmd->wp == STM32_CMD_ERR) {
703 		fprintf(stderr, "Error: WRITE PROTECT command not implemented in bootloader.\n");
704 		return STM32_ERR_NO_CMD;
705 	}
706 
707 	if (stm32_send_command(stm, stm->cmd->wp) != STM32_ERR_OK)
708 		return STM32_ERR_UNKNOWN;
709 
710 	s_err = stm32_get_ack_timeout(stm, STM32_WPROT_TIMEOUT);
711 	if (s_err == STM32_ERR_NACK) {
712 		fprintf(stderr, "Error: Failed to WRITE PROTECT\n");
713 		return STM32_ERR_UNKNOWN;
714 	}
715 	if (s_err != STM32_ERR_OK) {
716 		if ((port->flags & PORT_STRETCH_W)
717 		    && stm->cmd->wp != STM32_CMD_WP_NS)
718 			stm32_warn_stretching("WRITE PROTECT");
719 		return STM32_ERR_UNKNOWN;
720 	}
721 	return STM32_ERR_OK;
722 }
723 
stm32_runprot_memory(const stm32_t * stm)724 stm32_err_t stm32_runprot_memory(const stm32_t *stm)
725 {
726 	struct port_interface *port = stm->port;
727 	stm32_err_t s_err;
728 
729 	if (stm->cmd->ur == STM32_CMD_ERR) {
730 		fprintf(stderr, "Error: READOUT UNPROTECT command not implemented in bootloader.\n");
731 		return STM32_ERR_NO_CMD;
732 	}
733 
734 	if (stm32_send_command(stm, stm->cmd->ur) != STM32_ERR_OK)
735 		return STM32_ERR_UNKNOWN;
736 
737 	s_err = stm32_get_ack_timeout(stm, STM32_MASSERASE_TIMEOUT);
738 	if (s_err == STM32_ERR_NACK) {
739 		fprintf(stderr, "Error: Failed to READOUT UNPROTECT\n");
740 		return STM32_ERR_UNKNOWN;
741 	}
742 	if (s_err != STM32_ERR_OK) {
743 		if ((port->flags & PORT_STRETCH_W)
744 		    && stm->cmd->ur != STM32_CMD_UR_NS)
745 			stm32_warn_stretching("READOUT UNPROTECT");
746 		return STM32_ERR_UNKNOWN;
747 	}
748 	return STM32_ERR_OK;
749 }
750 
stm32_readprot_memory(const stm32_t * stm)751 stm32_err_t stm32_readprot_memory(const stm32_t *stm)
752 {
753 	struct port_interface *port = stm->port;
754 	stm32_err_t s_err;
755 
756 	if (stm->cmd->rp == STM32_CMD_ERR) {
757 		fprintf(stderr, "Error: READOUT PROTECT command not implemented in bootloader.\n");
758 		return STM32_ERR_NO_CMD;
759 	}
760 
761 	if (stm32_send_command(stm, stm->cmd->rp) != STM32_ERR_OK)
762 		return STM32_ERR_UNKNOWN;
763 
764 	s_err = stm32_get_ack_timeout(stm, STM32_RPROT_TIMEOUT);
765 	if (s_err == STM32_ERR_NACK) {
766 		fprintf(stderr, "Error: Failed to READOUT PROTECT\n");
767 		return STM32_ERR_UNKNOWN;
768 	}
769 	if (s_err != STM32_ERR_OK) {
770 		if ((port->flags & PORT_STRETCH_W)
771 		    && stm->cmd->rp != STM32_CMD_RP_NS)
772 			stm32_warn_stretching("READOUT PROTECT");
773 		return STM32_ERR_UNKNOWN;
774 	}
775 	return STM32_ERR_OK;
776 }
777 
stm32_mass_erase(const stm32_t * stm)778 static stm32_err_t stm32_mass_erase(const stm32_t *stm)
779 {
780 	struct port_interface *port = stm->port;
781 	stm32_err_t s_err;
782 	uint8_t buf[3];
783 
784 	if (stm32_send_command(stm, stm->cmd->er) != STM32_ERR_OK) {
785 		fprintf(stderr, "Can't initiate chip mass erase!\n");
786 		return STM32_ERR_UNKNOWN;
787 	}
788 
789 	/* regular erase (0x43) */
790 	if (stm->cmd->er == STM32_CMD_ER) {
791 		s_err = stm32_send_command_timeout(stm, 0xFF, STM32_MASSERASE_TIMEOUT);
792 		if (s_err != STM32_ERR_OK) {
793 			if (port->flags & PORT_STRETCH_W)
794 				stm32_warn_stretching("mass erase");
795 			return STM32_ERR_UNKNOWN;
796 		}
797 		return STM32_ERR_OK;
798 	}
799 
800 	/* extended erase */
801 	buf[0] = 0xFF;	/* 0xFFFF the magic number for mass erase */
802 	buf[1] = 0xFF;
803 	buf[2] = 0x00;  /* checksum */
804 	if (port->write(port, buf, 3) != PORT_ERR_OK) {
805 		fprintf(stderr, "Mass erase error.\n");
806 		return STM32_ERR_UNKNOWN;
807 	}
808 	s_err = stm32_get_ack_timeout(stm, STM32_MASSERASE_TIMEOUT);
809 	if (s_err != STM32_ERR_OK) {
810 		fprintf(stderr, "Mass erase failed. Try specifying the number of pages to be erased.\n");
811 		if ((port->flags & PORT_STRETCH_W)
812 		    && stm->cmd->er != STM32_CMD_EE_NS)
813 			stm32_warn_stretching("mass erase");
814 		return STM32_ERR_UNKNOWN;
815 	}
816 	return STM32_ERR_OK;
817 }
818 
stm32_pages_erase(const stm32_t * stm,uint32_t spage,uint32_t pages)819 static stm32_err_t stm32_pages_erase(const stm32_t *stm, uint32_t spage, uint32_t pages)
820 {
821 	struct port_interface *port = stm->port;
822 	stm32_err_t s_err;
823 	port_err_t p_err;
824 	uint32_t pg_num;
825 	uint8_t pg_byte;
826 	uint8_t cs = 0;
827 	uint8_t *buf;
828 	int i = 0;
829 
830 	/* The erase command reported by the bootloader is either 0x43, 0x44 or 0x45 */
831 	/* 0x44 is Extended Erase, a 2 byte based protocol and needs to be handled differently. */
832 	/* 0x45 is clock no-stretching version of Extended Erase for I2C port. */
833 	if (stm32_send_command(stm, stm->cmd->er) != STM32_ERR_OK) {
834 		fprintf(stderr, "Can't initiate chip mass erase!\n");
835 		return STM32_ERR_UNKNOWN;
836 	}
837 
838 	/* regular erase (0x43) */
839 	if (stm->cmd->er == STM32_CMD_ER) {
840 		buf = malloc(1 + pages + 1);
841 		if (!buf)
842 			return STM32_ERR_UNKNOWN;
843 
844 		buf[i++] = pages - 1;
845 		cs ^= (pages-1);
846 		for (pg_num = spage; pg_num < (pages + spage); pg_num++) {
847 			buf[i++] = pg_num;
848 			cs ^= pg_num;
849 		}
850 		buf[i++] = cs;
851 		p_err = port->write(port, buf, i);
852 		free(buf);
853 		if (p_err != PORT_ERR_OK) {
854 			fprintf(stderr, "Erase failed.\n");
855 			return STM32_ERR_UNKNOWN;
856 		}
857 		s_err = stm32_get_ack_timeout(stm, pages * STM32_PAGEERASE_TIMEOUT);
858 		if (s_err != STM32_ERR_OK) {
859 			if (port->flags & PORT_STRETCH_W)
860 				stm32_warn_stretching("erase");
861 			return STM32_ERR_UNKNOWN;
862 		}
863 		return STM32_ERR_OK;
864 	}
865 
866 	/* extended erase */
867 	buf = malloc(2 + 2 * pages + 1);
868 	if (!buf)
869 		return STM32_ERR_UNKNOWN;
870 
871 	/* Number of pages to be erased - 1, two bytes, MSB first */
872 	pg_byte = (pages - 1) >> 8;
873 	buf[i++] = pg_byte;
874 	cs ^= pg_byte;
875 	pg_byte = (pages - 1) & 0xFF;
876 	buf[i++] = pg_byte;
877 	cs ^= pg_byte;
878 
879 	for (pg_num = spage; pg_num < spage + pages; pg_num++) {
880 		pg_byte = pg_num >> 8;
881 		cs ^= pg_byte;
882 		buf[i++] = pg_byte;
883 		pg_byte = pg_num & 0xFF;
884 		cs ^= pg_byte;
885 		buf[i++] = pg_byte;
886 	}
887 	buf[i++] = cs;
888 	p_err = port->write(port, buf, i);
889 	free(buf);
890 	if (p_err != PORT_ERR_OK) {
891 		fprintf(stderr, "Page-by-page erase error.\n");
892 		return STM32_ERR_UNKNOWN;
893 	}
894 
895 	s_err = stm32_get_ack_timeout(stm, pages * STM32_PAGEERASE_TIMEOUT);
896 	if (s_err != STM32_ERR_OK) {
897 		fprintf(stderr, "Page-by-page erase failed. Check the maximum pages your device supports.\n");
898 		if ((port->flags & PORT_STRETCH_W)
899 		    && stm->cmd->er != STM32_CMD_EE_NS)
900 			stm32_warn_stretching("erase");
901 		return STM32_ERR_UNKNOWN;
902 	}
903 
904 	return STM32_ERR_OK;
905 }
906 
stm32_erase_memory(const stm32_t * stm,uint32_t spage,uint32_t pages)907 stm32_err_t stm32_erase_memory(const stm32_t *stm, uint32_t spage, uint32_t pages)
908 {
909 	uint32_t n;
910 	stm32_err_t s_err;
911 
912 	if (!pages || spage > STM32_MAX_PAGES ||
913 	    ((pages != STM32_MASS_ERASE) && ((spage + pages) > STM32_MAX_PAGES)))
914 		return STM32_ERR_OK;
915 
916 	if (stm->cmd->er == STM32_CMD_ERR) {
917 		fprintf(stderr, "Error: ERASE command not implemented in bootloader.\n");
918 		return STM32_ERR_NO_CMD;
919 	}
920 
921 	if (pages == STM32_MASS_ERASE) {
922 		/*
923 		 * Not all chips support mass erase.
924 		 * Mass erase can be obtained executing a "readout protect"
925 		 * followed by "readout un-protect". This method is not
926 		 * suggested because can hang the target if a debug SWD/JTAG
927 		 * is connected. When the target enters in "readout
928 		 * protection" mode it will consider the debug connection as
929 		 * a tentative of intrusion and will hang.
930 		 * Erasing the flash page-by-page is the safer way to go.
931 		 */
932 		if (!(stm->dev->flags & F_NO_ME))
933 			return stm32_mass_erase(stm);
934 
935 		pages = flash_addr_to_page_ceil(stm->dev->fl_end);
936 	}
937 
938 	/*
939 	 * Some device, like STM32L152, cannot erase more than 512 pages in
940 	 * one command, even 511 for STM32L082. Split the call.
941 	 */
942 	while (pages) {
943 		n = (pages <= 511) ? pages : 511;
944 		s_err = stm32_pages_erase(stm, spage, n);
945 		if (s_err != STM32_ERR_OK)
946 			return s_err;
947 		spage += n;
948 		pages -= n;
949 	}
950 	return STM32_ERR_OK;
951 }
952 
stm32_run_raw_code(const stm32_t * stm,uint32_t target_address,const uint8_t * code,uint32_t code_size)953 static stm32_err_t stm32_run_raw_code(const stm32_t *stm,
954 				      uint32_t target_address,
955 				      const uint8_t *code, uint32_t code_size)
956 {
957 	uint32_t stack_le = le_u32(0x20002000);
958 	uint32_t code_address_le = le_u32(target_address + 8 + 1); // thumb mode address (!)
959 	uint32_t length = code_size + 8;
960 	uint8_t *mem, *pos;
961 	uint32_t address, w;
962 
963 	/* Must be 32-bit aligned */
964 	if (target_address & 0x3) {
965 		fprintf(stderr, "Error: code address must be 4 byte aligned\n");
966 		return STM32_ERR_UNKNOWN;
967 	}
968 
969 	mem = malloc(length);
970 	if (!mem)
971 		return STM32_ERR_UNKNOWN;
972 
973 	memcpy(mem, &stack_le, sizeof(uint32_t));
974 	memcpy(mem + 4, &code_address_le, sizeof(uint32_t));
975 	memcpy(mem + 8, code, code_size);
976 
977 	pos = mem;
978 	address = target_address;
979 	while (length > 0) {
980 		w = length > 256 ? 256 : length;
981 		if (stm32_write_memory(stm, address, pos, w) != STM32_ERR_OK) {
982 			free(mem);
983 			return STM32_ERR_UNKNOWN;
984 		}
985 
986 		address += w;
987 		pos += w;
988 		length -= w;
989 	}
990 
991 	free(mem);
992 	return stm32_go(stm, target_address);
993 }
994 
stm32_go(const stm32_t * stm,uint32_t address)995 stm32_err_t stm32_go(const stm32_t *stm, uint32_t address)
996 {
997 	struct port_interface *port = stm->port;
998 	uint8_t buf[5];
999 
1000 	if (stm->cmd->go == STM32_CMD_ERR) {
1001 		fprintf(stderr, "Error: GO command not implemented in bootloader.\n");
1002 		return STM32_ERR_NO_CMD;
1003 	}
1004 
1005 	if (stm32_send_command(stm, stm->cmd->go) != STM32_ERR_OK)
1006 		return STM32_ERR_UNKNOWN;
1007 
1008 	buf[0] = address >> 24;
1009 	buf[1] = (address >> 16) & 0xFF;
1010 	buf[2] = (address >> 8) & 0xFF;
1011 	buf[3] = address & 0xFF;
1012 	buf[4] = buf[0] ^ buf[1] ^ buf[2] ^ buf[3];
1013 	if (port->write(port, buf, 5) != PORT_ERR_OK)
1014 		return STM32_ERR_UNKNOWN;
1015 
1016 	if (stm32_get_ack(stm) != STM32_ERR_OK)
1017 		return STM32_ERR_UNKNOWN;
1018 	return STM32_ERR_OK;
1019 }
1020 
stm32_reset_device(const stm32_t * stm)1021 stm32_err_t stm32_reset_device(const stm32_t *stm)
1022 {
1023 	uint32_t target_address = stm->dev->ram_start;
1024 
1025 	if (stm->dev->flags & F_OBLL) {
1026 		/* set the OBL_LAUNCH bit to reset device (see RM0360, 2.5) */
1027 		return stm32_run_raw_code(stm, target_address, stm_obl_launch_code, stm_obl_launch_code_length);
1028 	} else if (stm->dev->flags & F_PEMPTY) {
1029 		/* clear the PEMPTY bit to reset the device (see RM0394) */
1030 		return stm32_run_raw_code(stm, target_address, stm_pempty_launch_code, stm_pempty_launch_code_length);
1031 	} else {
1032 		return stm32_run_raw_code(stm, target_address, stm_reset_code, stm_reset_code_length);
1033 	}
1034 }
1035 
stm32_crc_memory(const stm32_t * stm,uint32_t address,uint32_t length,uint32_t * crc)1036 stm32_err_t stm32_crc_memory(const stm32_t *stm, uint32_t address,
1037 			     uint32_t length, uint32_t *crc)
1038 {
1039 	struct port_interface *port = stm->port;
1040 	uint8_t buf[5];
1041 
1042 	if ((address & 0x3) || (length & 0x3)) {
1043 		fprintf(stderr, "Start and end addresses must be 4 byte aligned\n");
1044 		return STM32_ERR_UNKNOWN;
1045 	}
1046 
1047 	if (stm->cmd->crc == STM32_CMD_ERR) {
1048 		fprintf(stderr, "Error: CRC command not implemented in bootloader.\n");
1049 		return STM32_ERR_NO_CMD;
1050 	}
1051 
1052 	if (stm32_send_command(stm, stm->cmd->crc) != STM32_ERR_OK)
1053 		return STM32_ERR_UNKNOWN;
1054 
1055 	buf[0] = address >> 24;
1056 	buf[1] = (address >> 16) & 0xFF;
1057 	buf[2] = (address >> 8) & 0xFF;
1058 	buf[3] = address & 0xFF;
1059 	buf[4] = buf[0] ^ buf[1] ^ buf[2] ^ buf[3];
1060 	if (port->write(port, buf, 5) != PORT_ERR_OK)
1061 		return STM32_ERR_UNKNOWN;
1062 
1063 	if (stm32_get_ack(stm) != STM32_ERR_OK)
1064 		return STM32_ERR_UNKNOWN;
1065 
1066 	buf[0] = length >> 24;
1067 	buf[1] = (length >> 16) & 0xFF;
1068 	buf[2] = (length >> 8) & 0xFF;
1069 	buf[3] = length & 0xFF;
1070 	buf[4] = buf[0] ^ buf[1] ^ buf[2] ^ buf[3];
1071 	if (port->write(port, buf, 5) != PORT_ERR_OK)
1072 		return STM32_ERR_UNKNOWN;
1073 
1074 	if (stm32_get_ack(stm) != STM32_ERR_OK)
1075 		return STM32_ERR_UNKNOWN;
1076 
1077 	if (stm32_get_ack(stm) != STM32_ERR_OK)
1078 		return STM32_ERR_UNKNOWN;
1079 
1080 	if (port->read(port, buf, 5) != PORT_ERR_OK)
1081 		return STM32_ERR_UNKNOWN;
1082 
1083 	if (buf[4] != (buf[0] ^ buf[1] ^ buf[2] ^ buf[3]))
1084 		return STM32_ERR_UNKNOWN;
1085 
1086 	*crc = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1087 	return STM32_ERR_OK;
1088 }
1089 
1090 /*
1091  * CRC computed by STM32 is similar to the standard crc32_be()
1092  * implemented, for example, in Linux kernel in ./lib/crc32.c
1093  * But STM32 computes it on units of 32 bits word and swaps the
1094  * bytes of the word before the computation.
1095  * Due to byte swap, I cannot use any CRC available in existing
1096  * libraries, so here is a simple not optimized implementation.
1097  */
1098 #define CRCPOLY_BE	0x04c11db7
1099 #define CRC_MSBMASK	0x80000000
1100 #define CRC_INIT_VALUE	0xFFFFFFFF
stm32_sw_crc(uint32_t crc,uint8_t * buf,unsigned int len)1101 uint32_t stm32_sw_crc(uint32_t crc, uint8_t *buf, unsigned int len)
1102 {
1103 	int i;
1104 	uint32_t data;
1105 
1106 	if (len & 0x3) {
1107 		fprintf(stderr, "Buffer length must be multiple of 4 bytes\n");
1108 		return 0;
1109 	}
1110 
1111 	while (len) {
1112 		data = *buf++;
1113 		data |= *buf++ << 8;
1114 		data |= *buf++ << 16;
1115 		data |= *buf++ << 24;
1116 		len -= 4;
1117 
1118 		crc ^= data;
1119 
1120 		for (i = 0; i < 32; i++)
1121 			if (crc & CRC_MSBMASK)
1122 				crc = (crc << 1) ^ CRCPOLY_BE;
1123 			else
1124 				crc = (crc << 1);
1125 	}
1126 	return crc;
1127 }
1128 
stm32_crc_wrapper(const stm32_t * stm,uint32_t address,uint32_t length,uint32_t * crc)1129 stm32_err_t stm32_crc_wrapper(const stm32_t *stm, uint32_t address,
1130 			      uint32_t length, uint32_t *crc)
1131 {
1132 	uint8_t buf[256];
1133 	uint32_t start, total_len, len, current_crc;
1134 
1135 	if ((address & 0x3) || (length & 0x3)) {
1136 		fprintf(stderr, "Start and end addresses must be 4 byte aligned\n");
1137 		return STM32_ERR_UNKNOWN;
1138 	}
1139 
1140 	if (stm->cmd->crc != STM32_CMD_ERR)
1141 		return stm32_crc_memory(stm, address, length, crc);
1142 
1143 	start = address;
1144 	total_len = length;
1145 	current_crc = CRC_INIT_VALUE;
1146 	while (length) {
1147 		len = length > 256 ? 256 : length;
1148 		if (stm32_read_memory(stm, address, buf, len) != STM32_ERR_OK) {
1149 			fprintf(stderr,
1150 				"Failed to read memory at address 0x%08x, target write-protected?\n",
1151 				address);
1152 			return STM32_ERR_UNKNOWN;
1153 		}
1154 		current_crc = stm32_sw_crc(current_crc, buf, len);
1155 		length -= len;
1156 		address += len;
1157 
1158 		fprintf(stderr,
1159 			"\rCRC address 0x%08x (%.2f%%) ",
1160 			address,
1161 			(100.0f / (float)total_len) * (float)(address - start)
1162 		);
1163 		fflush(stderr);
1164 	}
1165 	fprintf(stderr, "Done.\n");
1166 	*crc = current_crc;
1167 	return STM32_ERR_OK;
1168 }
1169