blob: 6bef4610ff8f8b3d4b3c7db4b0a748d12aac5cfc [file] [log] [blame]
Luka Perkovd131ad62012-05-27 11:44:51 +00001/*
Stefan Roese84899e22014-10-22 12:13:21 +02002 * Boot a Marvell SoC, with Xmodem over UART0.
Pali Rohár0b5909d2022-03-02 11:49:26 +01003 * supports Kirkwood, Dove, Avanta, Armada 370, Armada XP, Armada 375,
4 * Armada 38x and Armada 39x.
Luka Perkovd131ad62012-05-27 11:44:51 +00005 *
6 * (c) 2012 Daniel Stodden <daniel.stodden@gmail.com>
Pali Rohárcf8c9322021-09-24 23:07:14 +02007 * (c) 2021 Pali Rohár <pali@kernel.org>
Marek Behún61143f72022-06-01 17:17:06 +02008 * (c) 2021 Marek Behún <kabel@kernel.org>
Luka Perkovd131ad62012-05-27 11:44:51 +00009 *
Pali Rohárf4fa9622022-03-02 11:49:27 +010010 * References:
11 * - "88F6180, 88F6190, 88F6192, and 88F6281: Integrated Controller: Functional
12 * Specifications" December 2, 2008. Chapter 24.2 "BootROM Firmware".
13 * https://web.archive.org/web/20130730091033/https://www.marvell.com/embedded-processors/kirkwood/assets/FS_88F6180_9x_6281_OpenSource.pdf
14 * - "88AP510: High-Performance SoC with Integrated CPU, 2D/3D Graphics
15 * Processor, and High-Definition Video Decoder: Functional Specifications"
16 * August 3, 2011. Chapter 5 "BootROM Firmware"
17 * https://web.archive.org/web/20120130172443/https://www.marvell.com/application-processors/armada-500/assets/Armada-510-Functional-Spec.pdf
Pali Rohár29b92bb2023-01-08 13:34:24 +010018 * - "88F6665, 88F6660, 88F6658, 88F6655, 88F6655F, 88F6650, 88F6650F, 88F6610,
19 * and 88F6610F Avanta LP Family Integrated Single/Dual CPU Ecosystem for
20 * Gateway (GW), Home Gateway Unit (HGU), and Single Family Unit (SFU)
21 * Functional Specifications" Doc. No. MV-S108952-00, Rev. A. November 7, 2013.
22 * Chapter 7 "Boot Flow"
23 * CONFIDENTIAL, no public documentation available
Pali Rohárf4fa9622022-03-02 11:49:27 +010024 * - "88F6710, 88F6707, and 88F6W11: ARMADA(R) 370 SoC: Functional Specifications"
25 * May 26, 2014. Chapter 6 "BootROM Firmware".
26 * https://web.archive.org/web/20140617183701/https://www.marvell.com/embedded-processors/armada-300/assets/ARMADA370-FunctionalSpec-datasheet.pdf
27 * - "MV78230, MV78260, and MV78460: ARMADA(R) XP Family of Highly Integrated
28 * Multi-Core ARMv7 Based SoC Processors: Functional Specifications"
29 * May 29, 2014. Chapter 6 "BootROM Firmware".
30 * https://web.archive.org/web/20180829171131/https://www.marvell.com/embedded-processors/armada-xp/assets/ARMADA-XP-Functional-SpecDatasheet.pdf
Pali Rohár29b92bb2023-01-08 13:34:24 +010031 * - "BobCat2 Control and Management Subsystem Functional Specifications"
32 * Doc. No. MV-S109400-00, Rev. A. December 4, 2014.
33 * Chapter 1.6 BootROM Firmware
34 * CONFIDENTIAL, no public documentation available
35 * - "AlleyCat3 and PONCat3 Highly Integrated 1/10 Gigabit Ethernet Switch
36 * Control and Management Subsystem: Functional Specifications"
37 * Doc. No. MV-S109693-00, Rev. A. May 20, 2014.
38 * Chapter 1.6 BootROM Firmware
39 * CONFIDENTIAL, no public documentation available
Pali Rohárf4fa9622022-03-02 11:49:27 +010040 * - "ARMADA(R) 375 Value-Performance Dual Core CPU System on Chip: Functional
41 * Specifications" Doc. No. MV-S109377-00, Rev. A. September 18, 2013.
42 * Chapter 7 "Boot Sequence"
43 * CONFIDENTIAL, no public documentation available
44 * - "88F6810, 88F6811, 88F6821, 88F6W21, 88F6820, and 88F6828: ARMADA(R) 38x
45 * Family High-Performance Single/Dual CPU System on Chip: Functional
46 * Specifications" Doc. No. MV-S109094-00, Rev. C. August 2, 2015.
47 * Chapter 7 "Boot Flow"
48 * CONFIDENTIAL, no public documentation available
49 * - "88F6920, 88F6925 and 88F6928: ARMADA(R) 39x High-Performance Dual Core CPU
50 * System on Chip Functional Specifications" Doc. No. MV-S109896-00, Rev. B.
51 * December 22, 2015. Chapter 7 "Boot Flow"
52 * CONFIDENTIAL, no public documentation available
Pali Rohár29b92bb2023-01-08 13:34:24 +010053 * - "Marvell boot image parser", Marvell U-Boot 2013.01, version 18.06. September 17, 2015.
54 * https://github.com/MarvellEmbeddedProcessors/u-boot-marvell/blob/u-boot-2013.01-armada-18.06/tools/marvell/doimage_mv/hdrparser.c
55 * - "Marvell doimage Tool", Marvell U-Boot 2013.01, version 18.06. August 30, 2015.
56 * https://github.com/MarvellEmbeddedProcessors/u-boot-marvell/blob/u-boot-2013.01-armada-18.06/tools/marvell/doimage_mv/doimage.c
Pali Rohárfa032792023-01-21 19:57:28 +010057 *
58 * Storage location / offset of different image types:
59 * - IBR_HDR_SPI_ID (0x5A):
60 * SPI image can be stored at any 2 MB aligned offset in the first 16 MB of
61 * SPI-NOR or parallel-NOR. Despite the type name it really can be stored on
62 * parallel-NOR and cannot be stored on other SPI devices, like SPI-NAND.
63 * So it should have been named NOR image, not SPI image. This image type
Pali Rohár66cf9772023-03-23 21:00:07 +010064 * supports XIP - Execute In Place directly from NOR memory. Destination
65 * address of the XIP image is set to 0xFFFFFFFF and execute address to the
66 * absolute offset in bytes from the beginning of NOR memory.
Pali Rohárfa032792023-01-21 19:57:28 +010067 *
68 * - IBR_HDR_NAND_ID (0x8B):
69 * NAND image can be stored either at any 2 MB aligned offset in the first
70 * 16 MB of SPI-NAND or at any blocksize aligned offset in the first 64 MB
71 * of parallel-NAND.
72 *
73 * - IBR_HDR_PEX_ID (0x9C):
74 * PEX image is used for booting from PCI Express device. Source address
75 * stored in image is ignored by BootROM. It is not the BootROM who parses
76 * or loads data part of the PEX image. BootROM just configures SoC to the
77 * PCIe endpoint mode and let the PCIe device on the other end of the PCIe
78 * link (which must be in Root Complex mode) to load kwbimage into SoC's
79 * memory and tell BootROM physical address.
80 *
81 * - IBR_HDR_UART_ID (0x69):
82 * UART image can be transfered via xmodem protocol over first UART.
Pali Rohárc2b9eda2023-03-23 20:57:55 +010083 * Unlike all other image types, header size stored in the image must be
84 * multiply of the 128 bytes (for all other image types it can be any size)
85 * and data part of the image does not have to contain 32-bit checksum
86 * (all other image types must have valid 32-bit checksum in its data part).
87 * And data size stored in the image is ignored. A38x BootROM determinates
88 * size of the data part implicitly by the end of the xmodem transfer.
89 * A38x BootROM has a bug which cause that BootROM loads data part of UART
90 * image into RAM target address increased by one byte when source address
91 * and header size stored in the image header are not same. So UART image
92 * should be constructed in a way that there is no gap between header and
93 * data part.
Pali Rohárfa032792023-01-21 19:57:28 +010094 *
95 * - IBR_HDR_I2C_ID (0x4D):
96 * It is unknown for what kind of storage is used this image. It is not
97 * specified in any document from References section.
98 *
99 * - IBR_HDR_SATA_ID (0x78):
100 * SATA image can be stored at sector 1 (after the MBR table), sector 34
101 * (after the GPT table) or at any next sector which is aligned to 2 MB and
102 * is in the first 16 MB of SATA disk. Note that source address in SATA image
103 * is stored in sector unit and not in bytes like for any other images.
104 * Unfortunately sector size is disk specific, in most cases it is 512 bytes
105 * but there are also Native 4K SATA disks which have 4096 bytes long sectors.
106 *
107 * - IBR_HDR_SDIO_ID (0xAE):
108 * SDIO image can be stored on different medias:
109 * - SD(SC) card
110 * - SDHC/SDXC card
111 * - eMMC HW boot partition
112 * - eMMC user data partition / MMC card
113 * It cannot be stored on SDIO card despite the image name.
114 *
115 * For SD(SC)/SDHC/SDXC cards, image can be stored at the same locations as
116 * the SATA image (sector 1, sector 34 or any 2 MB aligned sector) but within
117 * the first 64 MB. SDHC and SDXC cards have fixed 512 bytes long sector size.
118 * Old SD(SC) cards unfortunately can have also different sector sizes, mostly
119 * 1024 bytes long sector sizes and also can be changed at runtime.
120 *
121 * For MMC-compatible devices, image can be stored at offset 0 or at offset
122 * 2 MB. If MMC device supports HW boot partitions then image must be stored
123 * on the HW partition as is configured in the EXT_CSC register (it can be
124 * either boot or user data).
125 *
126 * Note that source address for SDIO image is stored in byte unit, like for
127 * any other images (except SATA). Marvell Functional Specifications for
128 * A38x and A39x SoCs say that source address is in sector units, but this
129 * is purely incorrect information. A385 BootROM really expects source address
130 * for SDIO images in bytes and also Marvell tools generate SDIO image with
131 * source address in byte units.
Luka Perkovd131ad62012-05-27 11:44:51 +0000132 */
133
Stefan Roesef4db6c92016-01-07 14:12:04 +0100134#include "kwbimage.h"
135#include "mkimage.h"
Pali Rohára050a862021-09-24 23:06:42 +0200136#include "version.h"
Stefan Roesef4db6c92016-01-07 14:12:04 +0100137
Luka Perkovd131ad62012-05-27 11:44:51 +0000138#include <stdlib.h>
139#include <stdio.h>
140#include <string.h>
141#include <stdarg.h>
Stefan Roesef4db6c92016-01-07 14:12:04 +0100142#include <image.h>
Luka Perkovd131ad62012-05-27 11:44:51 +0000143#include <libgen.h>
144#include <fcntl.h>
145#include <errno.h>
146#include <unistd.h>
147#include <stdint.h>
Marek Behún12df7b72021-09-24 23:06:52 +0200148#include <time.h>
Luka Perkovd131ad62012-05-27 11:44:51 +0000149#include <sys/stat.h>
Pali Rohár913866a2022-03-02 11:49:21 +0100150#include <pthread.h>
Luka Perkovd131ad62012-05-27 11:44:51 +0000151
Pali Rohár93b55632021-09-24 23:07:06 +0200152#ifdef __linux__
153#include "termios_linux.h"
154#else
155#include <termios.h>
156#endif
157
Luka Perkovd131ad62012-05-27 11:44:51 +0000158/*
Pali Roháre8d26e82022-03-02 11:49:23 +0100159 * These functions are in <term.h> header file, but this header file conflicts
160 * with "termios_linux.h" header file. So declare these functions manually.
161 */
162extern int setupterm(const char *, int, int *);
163extern char *tigetstr(const char *);
164
165/*
Luka Perkovd131ad62012-05-27 11:44:51 +0000166 * Marvell BootROM UART Sensing
167 */
168
169static unsigned char kwboot_msg_boot[] = {
170 0xBB, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77
171};
172
Stefan Roese84899e22014-10-22 12:13:21 +0200173static unsigned char kwboot_msg_debug[] = {
174 0xDD, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77
175};
176
177/* Defines known to work on Kirkwood */
Luka Perkovd131ad62012-05-27 11:44:51 +0000178#define KWBOOT_MSG_RSP_TIMEO 50 /* ms */
179
Stefan Roese84899e22014-10-22 12:13:21 +0200180/* Defines known to work on Armada XP */
Stefan Roeseca076d92022-08-19 09:43:59 +0200181#define KWBOOT_MSG_RSP_TIMEO_AXP 10 /* ms */
Stefan Roese84899e22014-10-22 12:13:21 +0200182
Luka Perkovd131ad62012-05-27 11:44:51 +0000183/*
184 * Xmodem Transfers
185 */
186
187#define SOH 1 /* sender start of block header */
188#define EOT 4 /* sender end of block transfer */
189#define ACK 6 /* target block ack */
190#define NAK 21 /* target block negative ack */
Luka Perkovd131ad62012-05-27 11:44:51 +0000191
Pali Rohár2ef87f72021-09-24 23:06:48 +0200192#define KWBOOT_XM_BLKSZ 128 /* xmodem block size */
193
Luka Perkovd131ad62012-05-27 11:44:51 +0000194struct kwboot_block {
195 uint8_t soh;
196 uint8_t pnum;
197 uint8_t _pnum;
Pali Rohár2ef87f72021-09-24 23:06:48 +0200198 uint8_t data[KWBOOT_XM_BLKSZ];
Luka Perkovd131ad62012-05-27 11:44:51 +0000199 uint8_t csum;
Pali Rohára107c612021-07-23 11:14:14 +0200200} __packed;
Luka Perkovd131ad62012-05-27 11:44:51 +0000201
Pali Roháref951432022-01-25 18:13:00 +0100202#define KWBOOT_BLK_RSP_TIMEO 2000 /* ms */
Marek Behún12df7b72021-09-24 23:06:52 +0200203#define KWBOOT_HDR_RSP_TIMEO 10000 /* ms */
Luka Perkovd131ad62012-05-27 11:44:51 +0000204
Pali Rohár8dbe0272021-10-27 20:57:02 +0200205/* ARM code to change baudrate */
Pali Rohárca272042021-09-24 23:07:05 +0200206static unsigned char kwboot_baud_code[] = {
207 /* ; #define UART_BASE 0xd0012000 */
Pali Rohárca272042021-09-24 23:07:05 +0200208 /* ; #define DLL 0x00 */
209 /* ; #define DLH 0x04 */
210 /* ; #define LCR 0x0c */
211 /* ; #define DLAB 0x80 */
212 /* ; #define LSR 0x14 */
Pali Rohárca272042021-09-24 23:07:05 +0200213 /* ; #define TEMT 0x40 */
214 /* ; #define DIV_ROUND(a, b) ((a + b/2) / b) */
215 /* ; */
216 /* ; u32 set_baudrate(u32 old_b, u32 new_b) { */
Pali Rohárca272042021-09-24 23:07:05 +0200217 /* ; while */
218 /* ; (!(readl(UART_BASE + LSR) & TEMT)); */
219 /* ; u32 lcr = readl(UART_BASE + LCR); */
220 /* ; writel(UART_BASE + LCR, lcr | DLAB); */
221 /* ; u8 old_dll = readl(UART_BASE + DLL); */
222 /* ; u8 old_dlh = readl(UART_BASE + DLH); */
223 /* ; u16 old_dl = old_dll | (old_dlh << 8); */
224 /* ; u32 clk = old_b * old_dl; */
225 /* ; u16 new_dl = DIV_ROUND(clk, new_b); */
226 /* ; u8 new_dll = new_dl & 0xff; */
227 /* ; u8 new_dlh = (new_dl >> 8) & 0xff; */
228 /* ; writel(UART_BASE + DLL, new_dll); */
229 /* ; writel(UART_BASE + DLH, new_dlh); */
230 /* ; writel(UART_BASE + LCR, lcr & ~DLAB); */
Pali Rohár56452292021-10-27 20:57:00 +0200231 /* ; msleep(5); */
Pali Rohárca272042021-09-24 23:07:05 +0200232 /* ; return 0; */
233 /* ; } */
234
Pali Rohárca272042021-09-24 23:07:05 +0200235 /* ; r0 = UART_BASE */
Pali Rohár558176d2021-10-27 20:57:01 +0200236 0x0d, 0x02, 0xa0, 0xe3, /* mov r0, #0xd0000000 */
237 0x12, 0x0a, 0x80, 0xe3, /* orr r0, r0, #0x12000 */
Pali Rohárca272042021-09-24 23:07:05 +0200238
Pali Rohárca272042021-09-24 23:07:05 +0200239 /* ; Wait until Transmitter FIFO is Empty */
240 /* .Lloop_txempty: */
241 /* ; r1 = UART_BASE[LSR] & TEMT */
242 0x14, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x14] */
243 0x40, 0x00, 0x11, 0xe3, /* tst r1, #0x40 */
244 0xfc, 0xff, 0xff, 0x0a, /* beq .Lloop_txempty */
245
246 /* ; Set Divisor Latch Access Bit */
247 /* ; UART_BASE[LCR] |= DLAB */
248 0x0c, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x0c] */
249 0x80, 0x10, 0x81, 0xe3, /* orr r1, r1, #0x80 */
250 0x0c, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0c] */
251
252 /* ; Read current Divisor Latch */
253 /* ; r1 = UART_BASE[DLH]<<8 | UART_BASE[DLL] */
254 0x00, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x00] */
255 0xff, 0x10, 0x01, 0xe2, /* and r1, r1, #0xff */
256 0x01, 0x20, 0xa0, 0xe1, /* mov r2, r1 */
257 0x04, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x04] */
258 0xff, 0x10, 0x01, 0xe2, /* and r1, r1, #0xff */
259 0x41, 0x14, 0xa0, 0xe1, /* asr r1, r1, #8 */
260 0x02, 0x10, 0x81, 0xe1, /* orr r1, r1, r2 */
261
262 /* ; Read old baudrate value */
263 /* ; r2 = old_baudrate */
Pali Rohár62a98f42021-11-01 14:00:02 +0100264 0x74, 0x20, 0x9f, 0xe5, /* ldr r2, old_baudrate */
Pali Rohárca272042021-09-24 23:07:05 +0200265
266 /* ; Calculate base clock */
267 /* ; r1 = r2 * r1 */
268 0x92, 0x01, 0x01, 0xe0, /* mul r1, r2, r1 */
269
270 /* ; Read new baudrate value */
Pali Rohár56452292021-10-27 20:57:00 +0200271 /* ; r2 = new_baudrate */
Pali Rohár62a98f42021-11-01 14:00:02 +0100272 0x70, 0x20, 0x9f, 0xe5, /* ldr r2, new_baudrate */
Pali Rohárca272042021-09-24 23:07:05 +0200273
274 /* ; Calculate new Divisor Latch */
275 /* ; r1 = DIV_ROUND(r1, r2) = */
276 /* ; = (r1 + r2/2) / r2 */
277 0xa2, 0x10, 0x81, 0xe0, /* add r1, r1, r2, lsr #1 */
278 0x02, 0x40, 0xa0, 0xe1, /* mov r4, r2 */
279 0xa1, 0x00, 0x54, 0xe1, /* cmp r4, r1, lsr #1 */
280 /* .Lloop_div1: */
281 0x84, 0x40, 0xa0, 0x91, /* movls r4, r4, lsl #1 */
282 0xa1, 0x00, 0x54, 0xe1, /* cmp r4, r1, lsr #1 */
283 0xfc, 0xff, 0xff, 0x9a, /* bls .Lloop_div1 */
284 0x00, 0x30, 0xa0, 0xe3, /* mov r3, #0 */
285 /* .Lloop_div2: */
286 0x04, 0x00, 0x51, 0xe1, /* cmp r1, r4 */
287 0x04, 0x10, 0x41, 0x20, /* subhs r1, r1, r4 */
288 0x03, 0x30, 0xa3, 0xe0, /* adc r3, r3, r3 */
289 0xa4, 0x40, 0xa0, 0xe1, /* mov r4, r4, lsr #1 */
290 0x02, 0x00, 0x54, 0xe1, /* cmp r4, r2 */
291 0xf9, 0xff, 0xff, 0x2a, /* bhs .Lloop_div2 */
292 0x03, 0x10, 0xa0, 0xe1, /* mov r1, r3 */
293
294 /* ; Set new Divisor Latch Low */
295 /* ; UART_BASE[DLL] = r1 & 0xff */
296 0x01, 0x20, 0xa0, 0xe1, /* mov r2, r1 */
297 0xff, 0x20, 0x02, 0xe2, /* and r2, r2, #0xff */
298 0x00, 0x20, 0x80, 0xe5, /* str r2, [r0, #0x00] */
299
300 /* ; Set new Divisor Latch High */
301 /* ; UART_BASE[DLH] = r1>>8 & 0xff */
302 0x41, 0x24, 0xa0, 0xe1, /* asr r2, r1, #8 */
303 0xff, 0x20, 0x02, 0xe2, /* and r2, r2, #0xff */
304 0x04, 0x20, 0x80, 0xe5, /* str r2, [r0, #0x04] */
305
306 /* ; Clear Divisor Latch Access Bit */
307 /* ; UART_BASE[LCR] &= ~DLAB */
308 0x0c, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x0c] */
309 0x80, 0x10, 0xc1, 0xe3, /* bic r1, r1, #0x80 */
310 0x0c, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0c] */
311
Pali Rohár56452292021-10-27 20:57:00 +0200312 /* ; Loop 0x2dc000 (2998272) cycles */
313 /* ; which is about 5ms on 1200 MHz CPU */
314 /* ; r1 = 0x2dc000 */
315 0xb7, 0x19, 0xa0, 0xe3, /* mov r1, #0x2dc000 */
Pali Rohárca272042021-09-24 23:07:05 +0200316 /* .Lloop_sleep: */
317 0x01, 0x10, 0x41, 0xe2, /* sub r1, r1, #1 */
318 0x00, 0x00, 0x51, 0xe3, /* cmp r1, #0 */
319 0xfc, 0xff, 0xff, 0x1a, /* bne .Lloop_sleep */
320
Pali Rohár62a98f42021-11-01 14:00:02 +0100321 /* ; Jump to the end of execution */
322 0x01, 0x00, 0x00, 0xea, /* b end */
Pali Rohárca272042021-09-24 23:07:05 +0200323
324 /* ; Placeholder for old baudrate value */
325 /* old_baudrate: */
326 0x00, 0x00, 0x00, 0x00, /* .word 0 */
327
328 /* ; Placeholder for new baudrate value */
329 /* new_baudrate: */
330 0x00, 0x00, 0x00, 0x00, /* .word 0 */
Pali Rohár8dbe0272021-10-27 20:57:02 +0200331
332 /* end: */
Pali Rohárca272042021-09-24 23:07:05 +0200333};
334
Pali Rohár62a98f42021-11-01 14:00:02 +0100335/* ARM code from binary header executed by BootROM before changing baudrate */
Pali Rohár8dbe0272021-10-27 20:57:02 +0200336static unsigned char kwboot_baud_code_binhdr_pre[] = {
Pali Rohár62a98f42021-11-01 14:00:02 +0100337 /* ; #define UART_BASE 0xd0012000 */
338 /* ; #define THR 0x00 */
339 /* ; #define LSR 0x14 */
340 /* ; #define THRE 0x20 */
341 /* ; */
342 /* ; void send_preamble(void) { */
343 /* ; const u8 *str = "$baudratechange"; */
344 /* ; u8 c; */
345 /* ; do { */
346 /* ; while */
347 /* ; ((readl(UART_BASE + LSR) & THRE)); */
348 /* ; c = *str++; */
349 /* ; writel(UART_BASE + THR, c); */
350 /* ; } while (c); */
351 /* ; } */
352
353 /* ; Preserve registers for BootROM */
Pali Rohár8dbe0272021-10-27 20:57:02 +0200354 0xfe, 0x5f, 0x2d, 0xe9, /* push { r1 - r12, lr } */
Pali Rohár62a98f42021-11-01 14:00:02 +0100355
356 /* ; r0 = UART_BASE */
357 0x0d, 0x02, 0xa0, 0xe3, /* mov r0, #0xd0000000 */
358 0x12, 0x0a, 0x80, 0xe3, /* orr r0, r0, #0x12000 */
359
360 /* ; r2 = address of preamble string */
361 0x00, 0x20, 0x8f, 0xe2, /* adr r2, .Lstr_preamble */
362
363 /* ; Skip preamble data section */
364 0x03, 0x00, 0x00, 0xea, /* b .Lloop_preamble */
365
366 /* ; Preamble string */
367 /* .Lstr_preamble: */
368 0x24, 0x62, 0x61, 0x75, /* .asciz "$baudratechange" */
369 0x64, 0x72, 0x61, 0x74,
370 0x65, 0x63, 0x68, 0x61,
371 0x6e, 0x67, 0x65, 0x00,
372
373 /* ; Send preamble string over UART */
374 /* .Lloop_preamble: */
375 /* */
376 /* ; Wait until Transmitter Holding is Empty */
377 /* .Lloop_thre: */
378 /* ; r1 = UART_BASE[LSR] & THRE */
379 0x14, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x14] */
380 0x20, 0x00, 0x11, 0xe3, /* tst r1, #0x20 */
381 0xfc, 0xff, 0xff, 0x0a, /* beq .Lloop_thre */
382
383 /* ; Put character into Transmitter FIFO */
384 /* ; r1 = *r2++ */
385 0x01, 0x10, 0xd2, 0xe4, /* ldrb r1, [r2], #1 */
386 /* ; UART_BASE[THR] = r1 */
387 0x00, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0] */
388
389 /* ; Loop until end of preamble string */
390 0x00, 0x00, 0x51, 0xe3, /* cmp r1, #0 */
391 0xf8, 0xff, 0xff, 0x1a, /* bne .Lloop_preamble */
Pali Rohár8dbe0272021-10-27 20:57:02 +0200392};
393
Pali Rohár62a98f42021-11-01 14:00:02 +0100394/* ARM code for returning from binary header back to BootROM */
Pali Rohár8dbe0272021-10-27 20:57:02 +0200395static unsigned char kwboot_baud_code_binhdr_post[] = {
396 /* ; Return 0 - no error */
397 0x00, 0x00, 0xa0, 0xe3, /* mov r0, #0 */
398 0xfe, 0x9f, 0xbd, 0xe8, /* pop { r1 - r12, pc } */
399};
400
401/* ARM code for jumping to the original image exec_addr */
402static unsigned char kwboot_baud_code_data_jump[] = {
403 0x04, 0xf0, 0x1f, 0xe5, /* ldr pc, exec_addr */
404 /* ; Placeholder for exec_addr */
405 /* exec_addr: */
406 0x00, 0x00, 0x00, 0x00, /* .word 0 */
407};
Pali Rohárca272042021-09-24 23:07:05 +0200408
409static const char kwb_baud_magic[16] = "$baudratechange";
410
Luka Perkovd131ad62012-05-27 11:44:51 +0000411static int kwboot_verbose;
412
Stefan Roese84899e22014-10-22 12:13:21 +0200413static int msg_rsp_timeo = KWBOOT_MSG_RSP_TIMEO;
Kevin Smith7497a6a2016-02-16 21:28:19 +0000414static int blk_rsp_timeo = KWBOOT_BLK_RSP_TIMEO;
Stefan Roese84899e22014-10-22 12:13:21 +0200415
Marek Behúne453bb42021-09-24 23:06:41 +0200416static ssize_t
417kwboot_write(int fd, const char *buf, size_t len)
418{
Pali Rohár6ba7d632022-01-25 18:13:10 +0100419 ssize_t tot = 0;
Marek Behúne453bb42021-09-24 23:06:41 +0200420
421 while (tot < len) {
422 ssize_t wr = write(fd, buf + tot, len - tot);
423
Pali Rohár6ba7d632022-01-25 18:13:10 +0100424 if (wr < 0 && errno == EINTR)
425 continue;
426 else if (wr < 0)
427 return wr;
Marek Behúne453bb42021-09-24 23:06:41 +0200428
429 tot += wr;
430 }
431
432 return tot;
433}
434
Luka Perkovd131ad62012-05-27 11:44:51 +0000435static void
436kwboot_printv(const char *fmt, ...)
437{
438 va_list ap;
439
440 if (kwboot_verbose) {
441 va_start(ap, fmt);
442 vprintf(fmt, ap);
443 va_end(ap);
444 fflush(stdout);
445 }
446}
447
448static void
449__spinner(void)
450{
451 const char seq[] = { '-', '\\', '|', '/' };
452 const int div = 8;
453 static int state, bs;
454
455 if (state % div == 0) {
456 fputc(bs, stdout);
457 fputc(seq[state / div % sizeof(seq)], stdout);
458 fflush(stdout);
459 }
460
461 bs = '\b';
462 state++;
463}
464
465static void
466kwboot_spinner(void)
467{
468 if (kwboot_verbose)
469 __spinner();
470}
471
472static void
473__progress(int pct, char c)
474{
475 const int width = 70;
476 static const char *nl = "";
477 static int pos;
478
479 if (pos % width == 0)
480 printf("%s%3d %% [", nl, pct);
481
482 fputc(c, stdout);
483
484 nl = "]\n";
Pali Rohár5a1f8cb2021-09-24 23:06:46 +0200485 pos = (pos + 1) % width;
Luka Perkovd131ad62012-05-27 11:44:51 +0000486
487 if (pct == 100) {
Pali Rohár5a1f8cb2021-09-24 23:06:46 +0200488 while (pos && pos++ < width)
Luka Perkovd131ad62012-05-27 11:44:51 +0000489 fputc(' ', stdout);
490 fputs(nl, stdout);
Pali Rohár5a1f8cb2021-09-24 23:06:46 +0200491 nl = "";
492 pos = 0;
Luka Perkovd131ad62012-05-27 11:44:51 +0000493 }
494
495 fflush(stdout);
496
497}
498
499static void
500kwboot_progress(int _pct, char c)
501{
502 static int pct;
503
504 if (_pct != -1)
505 pct = _pct;
506
507 if (kwboot_verbose)
508 __progress(pct, c);
Pali Rohár5a1f8cb2021-09-24 23:06:46 +0200509
510 if (pct == 100)
511 pct = 0;
Luka Perkovd131ad62012-05-27 11:44:51 +0000512}
513
514static int
515kwboot_tty_recv(int fd, void *buf, size_t len, int timeo)
516{
517 int rc, nfds;
518 fd_set rfds;
519 struct timeval tv;
520 ssize_t n;
521
522 rc = -1;
523
524 FD_ZERO(&rfds);
525 FD_SET(fd, &rfds);
526
527 tv.tv_sec = 0;
528 tv.tv_usec = timeo * 1000;
529 if (tv.tv_usec > 1000000) {
530 tv.tv_sec += tv.tv_usec / 1000000;
531 tv.tv_usec %= 1000000;
532 }
533
534 do {
535 nfds = select(fd + 1, &rfds, NULL, NULL, &tv);
Pali Rohár91fb0952022-01-25 18:13:11 +0100536 if (nfds < 0 && errno == EINTR)
537 continue;
538 else if (nfds < 0)
Luka Perkovd131ad62012-05-27 11:44:51 +0000539 goto out;
Pali Rohár91fb0952022-01-25 18:13:11 +0100540 else if (!nfds) {
Luka Perkovd131ad62012-05-27 11:44:51 +0000541 errno = ETIMEDOUT;
542 goto out;
543 }
544
545 n = read(fd, buf, len);
Pali Rohár91fb0952022-01-25 18:13:11 +0100546 if (n < 0 && errno == EINTR)
547 continue;
548 else if (n <= 0)
Luka Perkovd131ad62012-05-27 11:44:51 +0000549 goto out;
550
551 buf = (char *)buf + n;
552 len -= n;
553 } while (len > 0);
554
555 rc = 0;
556out:
557 return rc;
558}
559
560static int
Pali Rohárcab817d2021-10-27 20:56:59 +0200561kwboot_tty_send(int fd, const void *buf, size_t len, int nodrain)
Luka Perkovd131ad62012-05-27 11:44:51 +0000562{
Stefan Roese84899e22014-10-22 12:13:21 +0200563 if (!buf)
564 return 0;
565
Marek Behúne453bb42021-09-24 23:06:41 +0200566 if (kwboot_write(fd, buf, len) < 0)
567 return -1;
Luka Perkovd131ad62012-05-27 11:44:51 +0000568
Pali Rohárcab817d2021-10-27 20:56:59 +0200569 if (nodrain)
570 return 0;
571
Marek Behúne453bb42021-09-24 23:06:41 +0200572 return tcdrain(fd);
Luka Perkovd131ad62012-05-27 11:44:51 +0000573}
574
575static int
576kwboot_tty_send_char(int fd, unsigned char c)
577{
Pali Rohárcab817d2021-10-27 20:56:59 +0200578 return kwboot_tty_send(fd, &c, 1, 0);
Luka Perkovd131ad62012-05-27 11:44:51 +0000579}
580
581static speed_t
Pali Rohárca272042021-09-24 23:07:05 +0200582kwboot_tty_baudrate_to_speed(int baudrate)
Luka Perkovd131ad62012-05-27 11:44:51 +0000583{
584 switch (baudrate) {
Pali Rohárca272042021-09-24 23:07:05 +0200585#ifdef B4000000
586 case 4000000:
587 return B4000000;
588#endif
589#ifdef B3500000
590 case 3500000:
591 return B3500000;
592#endif
593#ifdef B3000000
594 case 3000000:
595 return B3000000;
596#endif
597#ifdef B2500000
598 case 2500000:
599 return B2500000;
600#endif
601#ifdef B2000000
602 case 2000000:
603 return B2000000;
604#endif
605#ifdef B1500000
606 case 1500000:
607 return B1500000;
608#endif
609#ifdef B1152000
610 case 1152000:
611 return B1152000;
612#endif
613#ifdef B1000000
614 case 1000000:
615 return B1000000;
616#endif
617#ifdef B921600
618 case 921600:
619 return B921600;
620#endif
621#ifdef B614400
622 case 614400:
623 return B614400;
624#endif
625#ifdef B576000
626 case 576000:
627 return B576000;
628#endif
629#ifdef B500000
630 case 500000:
631 return B500000;
632#endif
633#ifdef B460800
634 case 460800:
635 return B460800;
636#endif
637#ifdef B307200
638 case 307200:
639 return B307200;
640#endif
641#ifdef B230400
642 case 230400:
643 return B230400;
644#endif
645#ifdef B153600
646 case 153600:
647 return B153600;
648#endif
649#ifdef B115200
Luka Perkovd131ad62012-05-27 11:44:51 +0000650 case 115200:
651 return B115200;
Pali Rohárca272042021-09-24 23:07:05 +0200652#endif
653#ifdef B76800
654 case 76800:
655 return B76800;
656#endif
657#ifdef B57600
Luka Perkovd131ad62012-05-27 11:44:51 +0000658 case 57600:
659 return B57600;
Pali Rohárca272042021-09-24 23:07:05 +0200660#endif
661#ifdef B38400
Luka Perkovd131ad62012-05-27 11:44:51 +0000662 case 38400:
663 return B38400;
Pali Rohárca272042021-09-24 23:07:05 +0200664#endif
665#ifdef B19200
Luka Perkovd131ad62012-05-27 11:44:51 +0000666 case 19200:
667 return B19200;
Pali Rohárca272042021-09-24 23:07:05 +0200668#endif
669#ifdef B9600
Luka Perkovd131ad62012-05-27 11:44:51 +0000670 case 9600:
671 return B9600;
Pali Rohárca272042021-09-24 23:07:05 +0200672#endif
673#ifdef B4800
674 case 4800:
675 return B4800;
676#endif
677#ifdef B2400
678 case 2400:
679 return B2400;
680#endif
681#ifdef B1800
682 case 1800:
683 return B1800;
684#endif
685#ifdef B1200
686 case 1200:
687 return B1200;
688#endif
689#ifdef B600
690 case 600:
691 return B600;
692#endif
693#ifdef B300
694 case 300:
695 return B300;
696#endif
697#ifdef B200
698 case 200:
699 return B200;
700#endif
701#ifdef B150
702 case 150:
703 return B150;
704#endif
705#ifdef B134
706 case 134:
707 return B134;
708#endif
709#ifdef B110
710 case 110:
711 return B110;
712#endif
713#ifdef B75
714 case 75:
715 return B75;
716#endif
717#ifdef B50
718 case 50:
719 return B50;
720#endif
721 default:
Pali Rohár93b55632021-09-24 23:07:06 +0200722#ifdef BOTHER
723 return BOTHER;
724#else
Pali Rohárca272042021-09-24 23:07:05 +0200725 return B0;
Pali Rohár93b55632021-09-24 23:07:06 +0200726#endif
Luka Perkovd131ad62012-05-27 11:44:51 +0000727 }
Luka Perkovd131ad62012-05-27 11:44:51 +0000728}
729
730static int
Marek Behún99a3d0232021-09-24 23:07:07 +0200731_is_within_tolerance(int value, int reference, int tolerance)
732{
733 return 100 * value >= reference * (100 - tolerance) &&
734 100 * value <= reference * (100 + tolerance);
735}
736
737static int
Pali Rohárca272042021-09-24 23:07:05 +0200738kwboot_tty_change_baudrate(int fd, int baudrate)
739{
740 struct termios tio;
741 speed_t speed;
742 int rc;
743
744 rc = tcgetattr(fd, &tio);
745 if (rc)
746 return rc;
747
748 speed = kwboot_tty_baudrate_to_speed(baudrate);
749 if (speed == B0) {
750 errno = EINVAL;
751 return -1;
752 }
753
Pali Rohár93b55632021-09-24 23:07:06 +0200754#ifdef BOTHER
755 if (speed == BOTHER)
756 tio.c_ospeed = tio.c_ispeed = baudrate;
757#endif
758
Pali Rohárca272042021-09-24 23:07:05 +0200759 rc = cfsetospeed(&tio, speed);
760 if (rc)
761 return rc;
762
763 rc = cfsetispeed(&tio, speed);
764 if (rc)
765 return rc;
766
767 rc = tcsetattr(fd, TCSANOW, &tio);
768 if (rc)
769 return rc;
770
Marek Behún99a3d0232021-09-24 23:07:07 +0200771 rc = tcgetattr(fd, &tio);
772 if (rc)
773 return rc;
774
775 if (cfgetospeed(&tio) != speed || cfgetispeed(&tio) != speed)
776 goto baud_fail;
777
778#ifdef BOTHER
779 /*
780 * Check whether set baudrate is within 3% tolerance.
781 * If BOTHER is defined, Linux always fills out c_ospeed / c_ispeed
782 * with real values.
783 */
784 if (!_is_within_tolerance(tio.c_ospeed, baudrate, 3))
785 goto baud_fail;
786
787 if (!_is_within_tolerance(tio.c_ispeed, baudrate, 3))
788 goto baud_fail;
789#endif
790
Pali Rohárca272042021-09-24 23:07:05 +0200791 return 0;
Marek Behún99a3d0232021-09-24 23:07:07 +0200792
793baud_fail:
794 fprintf(stderr, "Could not set baudrate to requested value\n");
795 errno = EINVAL;
796 return -1;
Pali Rohárca272042021-09-24 23:07:05 +0200797}
798
799static int
800kwboot_open_tty(const char *path, int baudrate)
Luka Perkovd131ad62012-05-27 11:44:51 +0000801{
Pali Rohár911515b2021-09-24 23:07:10 +0200802 int rc, fd, flags;
Luka Perkovd131ad62012-05-27 11:44:51 +0000803 struct termios tio;
804
805 rc = -1;
806
Marek Behún5fa04f42021-09-24 23:07:11 +0200807 fd = open(path, O_RDWR | O_NOCTTY | O_NDELAY);
Luka Perkovd131ad62012-05-27 11:44:51 +0000808 if (fd < 0)
809 goto out;
810
Pali Rohárc704e0e2021-09-24 23:07:08 +0200811 rc = tcgetattr(fd, &tio);
812 if (rc)
813 goto out;
Luka Perkovd131ad62012-05-27 11:44:51 +0000814
Pali Rohárc704e0e2021-09-24 23:07:08 +0200815 cfmakeraw(&tio);
Marek Behún5fa04f42021-09-24 23:07:11 +0200816 tio.c_cflag |= CREAD | CLOCAL;
Pali Rohár2ecca3d2021-10-25 15:12:53 +0200817 tio.c_cflag &= ~(CSTOPB | HUPCL | CRTSCTS);
Luka Perkovd131ad62012-05-27 11:44:51 +0000818 tio.c_cc[VMIN] = 1;
Pali Rohár24a471b2021-09-24 23:07:09 +0200819 tio.c_cc[VTIME] = 0;
Luka Perkovd131ad62012-05-27 11:44:51 +0000820
Luka Perkovd131ad62012-05-27 11:44:51 +0000821 rc = tcsetattr(fd, TCSANOW, &tio);
822 if (rc)
823 goto out;
824
Pali Rohár911515b2021-09-24 23:07:10 +0200825 flags = fcntl(fd, F_GETFL);
826 if (flags < 0)
827 goto out;
828
829 rc = fcntl(fd, F_SETFL, flags & ~O_NDELAY);
830 if (rc)
831 goto out;
832
Pali Rohárca272042021-09-24 23:07:05 +0200833 rc = kwboot_tty_change_baudrate(fd, baudrate);
834 if (rc)
835 goto out;
836
Luka Perkovd131ad62012-05-27 11:44:51 +0000837 rc = fd;
838out:
839 if (rc < 0) {
840 if (fd >= 0)
841 close(fd);
842 }
843
844 return rc;
845}
846
Pali Rohár913866a2022-03-02 11:49:21 +0100847static void *
848kwboot_msg_write_handler(void *arg)
849{
850 int tty = *(int *)((void **)arg)[0];
851 const void *msg = ((void **)arg)[1];
852 int rsp_timeo = msg_rsp_timeo;
853 int i, dummy_oldtype;
854
855 /* allow to cancel this thread at any time */
856 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &dummy_oldtype);
857
858 while (1) {
859 /* write 128 samples of message pattern into the output queue without waiting */
860 for (i = 0; i < 128; i++) {
861 if (kwboot_tty_send(tty, msg, 8, 1) < 0) {
862 perror("\nFailed to send message pattern");
863 exit(1);
864 }
865 }
866 /* wait until output queue is transmitted and then make pause */
867 if (tcdrain(tty) < 0) {
868 perror("\nFailed to send message pattern");
869 exit(1);
870 }
871 /* BootROM requires pause on UART after it detects message pattern */
872 usleep(rsp_timeo * 1000);
873 }
874}
875
876static int
877kwboot_msg_start_thread(pthread_t *thread, int *tty, void *msg)
878{
879 void *arg[2];
880 int rc;
881
882 arg[0] = tty;
883 arg[1] = msg;
884 rc = pthread_create(thread, NULL, kwboot_msg_write_handler, arg);
885 if (rc) {
886 errno = rc;
887 return -1;
888 }
889
890 return 0;
891}
892
893static int
894kwboot_msg_stop_thread(pthread_t thread)
895{
896 int rc;
897
898 rc = pthread_cancel(thread);
899 if (rc) {
900 errno = rc;
901 return -1;
902 }
903
904 rc = pthread_join(thread, NULL);
905 if (rc) {
906 errno = rc;
907 return -1;
908 }
909
910 return 0;
911}
912
Luka Perkovd131ad62012-05-27 11:44:51 +0000913static int
Pali Rohárc1d911f2022-03-02 11:49:20 +0100914kwboot_bootmsg(int tty)
Luka Perkovd131ad62012-05-27 11:44:51 +0000915{
Pali Rohár2bcd5b12022-01-25 18:13:08 +0100916 struct kwboot_block block;
Pali Rohár913866a2022-03-02 11:49:21 +0100917 pthread_t write_thread;
918 int rc, err;
Luka Perkovd131ad62012-05-27 11:44:51 +0000919 char c;
Pali Rohár913866a2022-03-02 11:49:21 +0100920
921 /* flush input and output queue */
922 tcflush(tty, TCIOFLUSH);
923
924 rc = kwboot_msg_start_thread(&write_thread, &tty, kwboot_msg_boot);
925 if (rc) {
926 perror("Failed to start write thread");
927 return rc;
928 }
Luka Perkovd131ad62012-05-27 11:44:51 +0000929
Pali Rohárc1d911f2022-03-02 11:49:20 +0100930 kwboot_printv("Sending boot message. Please reboot the target...");
Luka Perkovd131ad62012-05-27 11:44:51 +0000931
Pali Rohár913866a2022-03-02 11:49:21 +0100932 err = 0;
933 while (1) {
Luka Perkovd131ad62012-05-27 11:44:51 +0000934 kwboot_spinner();
935
Pali Rohár913866a2022-03-02 11:49:21 +0100936 rc = kwboot_tty_recv(tty, &c, 1, msg_rsp_timeo);
937 if (rc && errno == ETIMEDOUT) {
938 continue;
939 } else if (rc) {
940 err = errno;
941 break;
942 }
943
944 if (c == NAK)
945 break;
946 }
Luka Perkovd131ad62012-05-27 11:44:51 +0000947
948 kwboot_printv("\n");
949
Pali Rohár913866a2022-03-02 11:49:21 +0100950 rc = kwboot_msg_stop_thread(write_thread);
951 if (rc) {
952 perror("Failed to stop write thread");
Pali Rohár2bcd5b12022-01-25 18:13:08 +0100953 return rc;
Pali Rohár913866a2022-03-02 11:49:21 +0100954 }
955
956 if (err) {
957 errno = err;
958 perror("Failed to read response for boot message pattern");
959 return -1;
960 }
Pali Rohár2bcd5b12022-01-25 18:13:08 +0100961
962 /*
963 * At this stage we have sent more boot message patterns and BootROM
964 * (at least on Armada XP and 385) started interpreting sent bytes as
965 * part of xmodem packets. If BootROM is expecting SOH byte as start of
966 * a xmodem packet and it receives byte 0xff, then it throws it away and
967 * sends a NAK reply to host. If BootROM does not receive any byte for
968 * 2s when expecting some continuation of the xmodem packet, it throws
969 * away the partially received xmodem data and sends NAK reply to host.
970 *
971 * Therefore for starting xmodem transfer we have two options: Either
972 * wait 2s or send 132 0xff bytes (which is the size of xmodem packet)
973 * to ensure that BootROM throws away any partially received data.
974 */
975
976 /* flush output queue with remaining boot message patterns */
Pali Rohárd8865f82022-03-02 11:49:18 +0100977 rc = tcflush(tty, TCOFLUSH);
978 if (rc) {
979 perror("Failed to flush output queue");
980 return rc;
981 }
Pali Rohár2bcd5b12022-01-25 18:13:08 +0100982
983 /* send one xmodem packet with 0xff bytes to force BootROM to re-sync */
984 memset(&block, 0xff, sizeof(block));
Pali Rohárd8865f82022-03-02 11:49:18 +0100985 rc = kwboot_tty_send(tty, &block, sizeof(block), 0);
986 if (rc) {
987 perror("Failed to send sync sequence");
988 return rc;
989 }
Pali Rohár2bcd5b12022-01-25 18:13:08 +0100990
991 /*
992 * Sending 132 bytes via 115200B/8-N-1 takes 11.45 ms, reading 132 bytes
993 * takes 11.45 ms, so waiting for 30 ms should be enough.
994 */
995 usleep(30 * 1000);
996
997 /* flush remaining NAK replies from input queue */
Pali Rohárd8865f82022-03-02 11:49:18 +0100998 rc = tcflush(tty, TCIFLUSH);
999 if (rc) {
1000 perror("Failed to flush input queue");
1001 return rc;
1002 }
Pali Rohár2bcd5b12022-01-25 18:13:08 +01001003
1004 return 0;
Luka Perkovd131ad62012-05-27 11:44:51 +00001005}
1006
1007static int
Pali Rohárc1d911f2022-03-02 11:49:20 +01001008kwboot_debugmsg(int tty)
Stefan Roese84899e22014-10-22 12:13:21 +02001009{
Pali Rohár93976af2022-03-02 11:49:22 +01001010 unsigned char buf[8192];
1011 pthread_t write_thread;
1012 int rc, err, i, pos;
1013 size_t off;
1014
1015 /* flush input and output queue */
1016 tcflush(tty, TCIOFLUSH);
1017
1018 rc = kwboot_msg_start_thread(&write_thread, &tty, kwboot_msg_debug);
1019 if (rc) {
1020 perror("Failed to start write thread");
1021 return rc;
1022 }
Stefan Roese84899e22014-10-22 12:13:21 +02001023
1024 kwboot_printv("Sending debug message. Please reboot the target...");
Pali Rohár93976af2022-03-02 11:49:22 +01001025 kwboot_spinner();
Stefan Roese84899e22014-10-22 12:13:21 +02001026
Pali Rohár93976af2022-03-02 11:49:22 +01001027 err = 0;
1028 off = 0;
1029 while (1) {
1030 /* Read immediately all bytes in queue without waiting */
1031 rc = read(tty, buf + off, sizeof(buf) - off);
1032 if ((rc < 0 && errno == EINTR) || rc == 0) {
1033 continue;
1034 } else if (rc < 0) {
1035 err = errno;
Stefan Roese84899e22014-10-22 12:13:21 +02001036 break;
Pali Rohár93976af2022-03-02 11:49:22 +01001037 }
1038 off += rc - 1;
Stefan Roese84899e22014-10-22 12:13:21 +02001039
1040 kwboot_spinner();
1041
Pali Rohár93976af2022-03-02 11:49:22 +01001042 /*
1043 * Check if we received at least 4 debug message patterns
1044 * (console echo from BootROM) in cyclic buffer
1045 */
1046
1047 for (pos = 0; pos < sizeof(kwboot_msg_debug); pos++)
1048 if (buf[off] == kwboot_msg_debug[(pos + off) % sizeof(kwboot_msg_debug)])
1049 break;
1050
1051 for (i = off; i >= 0; i--)
1052 if (buf[i] != kwboot_msg_debug[(pos + i) % sizeof(kwboot_msg_debug)])
1053 break;
1054
1055 off -= i;
1056
1057 if (off >= 4 * sizeof(kwboot_msg_debug))
1058 break;
1059
1060 /* If not move valid suffix from end of the buffer to the beginning of buffer */
1061 memmove(buf, buf + i + 1, off);
1062 }
Stefan Roese84899e22014-10-22 12:13:21 +02001063
1064 kwboot_printv("\n");
1065
Pali Rohár93976af2022-03-02 11:49:22 +01001066 rc = kwboot_msg_stop_thread(write_thread);
1067 if (rc) {
1068 perror("Failed to stop write thread");
1069 return rc;
1070 }
1071
1072 if (err) {
1073 errno = err;
1074 perror("Failed to read response for debug message pattern");
1075 return -1;
1076 }
1077
1078 /* flush output queue with remaining debug message patterns */
1079 rc = tcflush(tty, TCOFLUSH);
1080 if (rc) {
1081 perror("Failed to flush output queue");
1082 return rc;
1083 }
1084
1085 kwboot_printv("Clearing input buffer...\n");
1086
1087 /*
1088 * Wait until BootROM transmit all remaining echo characters.
1089 * Experimentally it was measured that for Armada 385 BootROM
1090 * it is required to wait at least 0.415s. So wait 0.5s.
1091 */
1092 usleep(500 * 1000);
1093
1094 /*
1095 * In off variable is stored number of characters received after the
1096 * successful detection of echo reply. So these characters are console
1097 * echo for other following debug message patterns. BootROM may have in
1098 * its output queue other echo characters which were being transmitting
1099 * before above sleep call. So read remaining number of echo characters
1100 * sent by the BootROM now.
1101 */
1102 while ((rc = kwboot_tty_recv(tty, &buf[0], 1, 0)) == 0)
1103 off++;
1104 if (errno != ETIMEDOUT) {
1105 perror("Failed to read response");
1106 return rc;
1107 }
1108
1109 /*
1110 * Clear every echo character set by the BootROM by backspace byte.
1111 * This is required prior writing any command to the BootROM debug
1112 * because BootROM command line buffer has limited size. If length
1113 * of the command is larger than buffer size then it looks like
1114 * that Armada 385 BootROM crashes after sending ENTER. So erase it.
1115 * Experimentally it was measured that for Armada 385 BootROM it is
1116 * required to send at least 3 backspace bytes for one echo character.
1117 * This is unknown why. But lets do it.
1118 */
1119 off *= 3;
1120 memset(buf, '\x08', sizeof(buf));
1121 while (off > sizeof(buf)) {
1122 rc = kwboot_tty_send(tty, buf, sizeof(buf), 1);
1123 if (rc) {
1124 perror("Failed to send clear sequence");
1125 return rc;
1126 }
1127 off -= sizeof(buf);
1128 }
1129 rc = kwboot_tty_send(tty, buf, off, 0);
1130 if (rc) {
1131 perror("Failed to send clear sequence");
1132 return rc;
1133 }
1134
1135 usleep(msg_rsp_timeo * 1000);
1136 rc = tcflush(tty, TCIFLUSH);
1137 if (rc) {
1138 perror("Failed to flush input queue");
1139 return rc;
1140 }
1141
1142 return 0;
Stefan Roese84899e22014-10-22 12:13:21 +02001143}
1144
Pali Rohárc5d666a2021-09-24 23:06:44 +02001145static size_t
Luka Perkovd131ad62012-05-27 11:44:51 +00001146kwboot_xm_makeblock(struct kwboot_block *block, const void *data,
1147 size_t size, int pnum)
1148{
Marek Behúnd8cc8512021-09-24 23:06:45 +02001149 size_t i, n;
Luka Perkovd131ad62012-05-27 11:44:51 +00001150
Stefan Roese84899e22014-10-22 12:13:21 +02001151 block->soh = SOH;
Luka Perkovd131ad62012-05-27 11:44:51 +00001152 block->pnum = pnum;
1153 block->_pnum = ~block->pnum;
1154
Pali Rohár2ef87f72021-09-24 23:06:48 +02001155 n = size < KWBOOT_XM_BLKSZ ? size : KWBOOT_XM_BLKSZ;
Luka Perkovd131ad62012-05-27 11:44:51 +00001156 memcpy(&block->data[0], data, n);
Pali Rohár2ef87f72021-09-24 23:06:48 +02001157 memset(&block->data[n], 0, KWBOOT_XM_BLKSZ - n);
Luka Perkovd131ad62012-05-27 11:44:51 +00001158
1159 block->csum = 0;
1160 for (i = 0; i < n; i++)
1161 block->csum += block->data[i];
1162
1163 return n;
1164}
1165
Marek Behún12df7b72021-09-24 23:06:52 +02001166static uint64_t
1167_now(void)
1168{
1169 struct timespec ts;
1170
1171 if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
1172 static int err_print;
1173
1174 if (!err_print) {
1175 perror("clock_gettime() does not work");
1176 err_print = 1;
1177 }
1178
1179 /* this will just make the timeout not work */
1180 return -1ULL;
1181 }
1182
1183 return ts.tv_sec * 1000ULL + (ts.tv_nsec + 500000) / 1000000;
1184}
1185
Luka Perkovd131ad62012-05-27 11:44:51 +00001186static int
Marek Behún408ea612021-09-24 23:06:49 +02001187_is_xm_reply(char c)
1188{
Pali Rohár94c906a2022-01-25 18:13:03 +01001189 return c == ACK || c == NAK;
Marek Behún408ea612021-09-24 23:06:49 +02001190}
1191
1192static int
Pali Rohár9cdc2642021-09-24 23:06:54 +02001193_xm_reply_to_error(int c)
1194{
1195 int rc = -1;
1196
1197 switch (c) {
1198 case ACK:
1199 rc = 0;
1200 break;
1201 case NAK:
1202 errno = EBADMSG;
1203 break;
Pali Rohár9cdc2642021-09-24 23:06:54 +02001204 default:
1205 errno = EPROTO;
1206 break;
1207 }
1208
1209 return rc;
1210}
1211
1212static int
Pali Rohárca272042021-09-24 23:07:05 +02001213kwboot_baud_magic_handle(int fd, char c, int baudrate)
1214{
1215 static size_t rcv_len;
1216
1217 if (rcv_len < sizeof(kwb_baud_magic)) {
1218 /* try to recognize whole magic word */
1219 if (c == kwb_baud_magic[rcv_len]) {
1220 rcv_len++;
1221 } else {
1222 printf("%.*s%c", (int)rcv_len, kwb_baud_magic, c);
1223 fflush(stdout);
1224 rcv_len = 0;
1225 }
1226 }
1227
1228 if (rcv_len == sizeof(kwb_baud_magic)) {
1229 /* magic word received */
1230 kwboot_printv("\nChanging baudrate to %d Bd\n", baudrate);
1231
1232 return kwboot_tty_change_baudrate(fd, baudrate) ? : 1;
1233 } else {
1234 return 0;
1235 }
1236}
1237
1238static int
Pali Rohár950ed242022-01-25 18:13:04 +01001239kwboot_xm_recv_reply(int fd, char *c, int stop_on_non_xm,
Pali Rohár82a9e132022-01-25 18:13:02 +01001240 int ignore_nak_reply,
Pali Rohára6fcac22021-10-25 15:13:04 +02001241 int allow_non_xm, int *non_xm_print,
Pali Rohárca272042021-09-24 23:07:05 +02001242 int baudrate, int *baud_changed)
Pali Rohár48b3ea62021-09-24 23:06:50 +02001243{
Marek Behún12df7b72021-09-24 23:06:52 +02001244 int timeout = allow_non_xm ? KWBOOT_HDR_RSP_TIMEO : blk_rsp_timeo;
Marek Behún819cd322021-09-24 23:06:53 +02001245 uint64_t recv_until = _now() + timeout;
Pali Rohár48b3ea62021-09-24 23:06:50 +02001246 int rc;
1247
1248 while (1) {
Marek Behún12df7b72021-09-24 23:06:52 +02001249 rc = kwboot_tty_recv(fd, c, 1, timeout);
Pali Rohár48b3ea62021-09-24 23:06:50 +02001250 if (rc) {
1251 if (errno != ETIMEDOUT)
1252 return rc;
Marek Behún819cd322021-09-24 23:06:53 +02001253 else if (allow_non_xm && *non_xm_print)
Marek Behún12df7b72021-09-24 23:06:52 +02001254 return -1;
1255 else
1256 *c = NAK;
Pali Rohár48b3ea62021-09-24 23:06:50 +02001257 }
1258
1259 /* If received xmodem reply, end. */
Pali Rohár82a9e132022-01-25 18:13:02 +01001260 if (_is_xm_reply(*c)) {
1261 if (*c == NAK && ignore_nak_reply) {
1262 timeout = recv_until - _now();
1263 if (timeout >= 0)
1264 continue;
1265 }
Pali Rohár48b3ea62021-09-24 23:06:50 +02001266 break;
Pali Rohár82a9e132022-01-25 18:13:02 +01001267 }
Pali Rohár48b3ea62021-09-24 23:06:50 +02001268
1269 /*
Pali Rohárca272042021-09-24 23:07:05 +02001270 * If receiving/printing non-xmodem text output is allowed and
1271 * such a byte was received, we want to increase receiving time
1272 * and either:
1273 * - print the byte, if it is not part of baudrate change magic
1274 * sequence while baudrate change was requested (-B option)
1275 * - change baudrate
Marek Behún819cd322021-09-24 23:06:53 +02001276 * Otherwise decrease timeout by time elapsed.
Pali Rohár48b3ea62021-09-24 23:06:50 +02001277 */
1278 if (allow_non_xm) {
Marek Behún12df7b72021-09-24 23:06:52 +02001279 recv_until = _now() + timeout;
Pali Rohárca272042021-09-24 23:07:05 +02001280
1281 if (baudrate && !*baud_changed) {
1282 rc = kwboot_baud_magic_handle(fd, *c, baudrate);
1283 if (rc == 1)
1284 *baud_changed = 1;
1285 else if (!rc)
1286 *non_xm_print = 1;
1287 else
1288 return rc;
1289 } else if (!baudrate || !*baud_changed) {
1290 putchar(*c);
1291 fflush(stdout);
1292 *non_xm_print = 1;
1293 }
Marek Behún819cd322021-09-24 23:06:53 +02001294 } else {
Pali Rohár950ed242022-01-25 18:13:04 +01001295 if (stop_on_non_xm)
Pali Rohára6fcac22021-10-25 15:13:04 +02001296 break;
Marek Behún819cd322021-09-24 23:06:53 +02001297 timeout = recv_until - _now();
1298 if (timeout < 0) {
1299 errno = ETIMEDOUT;
1300 return -1;
1301 }
Pali Rohár48b3ea62021-09-24 23:06:50 +02001302 }
1303 }
1304
1305 return 0;
1306}
1307
1308static int
1309kwboot_xm_sendblock(int fd, struct kwboot_block *block, int allow_non_xm,
Pali Rohár5875ad42022-01-25 18:13:05 +01001310 int *done_print, int baudrate, int allow_retries)
Luka Perkovd131ad62012-05-27 11:44:51 +00001311{
Pali Rohárca272042021-09-24 23:07:05 +02001312 int non_xm_print, baud_changed;
1313 int rc, err, retries;
Luka Perkovd131ad62012-05-27 11:44:51 +00001314 char c;
1315
Pali Rohár48b3ea62021-09-24 23:06:50 +02001316 *done_print = 0;
Pali Rohár455c0d22021-10-27 20:56:58 +02001317 non_xm_print = 0;
1318 baud_changed = 0;
Pali Rohár48b3ea62021-09-24 23:06:50 +02001319
Pali Rohárd14a3422021-10-25 15:13:03 +02001320 retries = 0;
Luka Perkovd131ad62012-05-27 11:44:51 +00001321 do {
Pali Rohárcab817d2021-10-27 20:56:59 +02001322 rc = kwboot_tty_send(fd, block, sizeof(*block), 1);
Luka Perkovd131ad62012-05-27 11:44:51 +00001323 if (rc)
Pali Rohár94c906a2022-01-25 18:13:03 +01001324 goto err;
Luka Perkovd131ad62012-05-27 11:44:51 +00001325
Pali Rohár48b3ea62021-09-24 23:06:50 +02001326 if (allow_non_xm && !*done_print) {
1327 kwboot_progress(100, '.');
1328 kwboot_printv("Done\n");
1329 *done_print = 1;
1330 }
Stefan Roese84899e22014-10-22 12:13:21 +02001331
Pali Rohára6fcac22021-10-25 15:13:04 +02001332 rc = kwboot_xm_recv_reply(fd, &c, retries < 3,
Pali Rohár82a9e132022-01-25 18:13:02 +01001333 retries > 8,
Pali Rohára6fcac22021-10-25 15:13:04 +02001334 allow_non_xm, &non_xm_print,
Pali Rohárca272042021-09-24 23:07:05 +02001335 baudrate, &baud_changed);
Pali Rohár48b3ea62021-09-24 23:06:50 +02001336 if (rc)
Pali Rohár94c906a2022-01-25 18:13:03 +01001337 goto err;
Stefan Roese84899e22014-10-22 12:13:21 +02001338
Pali Rohár5d8aa4c2022-01-25 18:13:06 +01001339 if (!allow_non_xm && c != ACK) {
1340 if (c == NAK && allow_retries && retries + 1 < 16)
1341 kwboot_progress(-1, '+');
1342 else
1343 kwboot_progress(-1, 'E');
1344 }
Pali Rohár5875ad42022-01-25 18:13:05 +01001345 } while (c == NAK && allow_retries && retries++ < 16);
Luka Perkovd131ad62012-05-27 11:44:51 +00001346
Marek Behún2e81b3a2021-09-24 23:06:51 +02001347 if (non_xm_print)
1348 kwboot_printv("\n");
1349
Pali Rohárca272042021-09-24 23:07:05 +02001350 if (allow_non_xm && baudrate && !baud_changed) {
1351 fprintf(stderr, "Baudrate was not changed\n");
Pali Rohárca272042021-09-24 23:07:05 +02001352 errno = EPROTO;
Pali Rohár94c906a2022-01-25 18:13:03 +01001353 return -1;
Pali Rohárca272042021-09-24 23:07:05 +02001354 }
1355
Pali Rohár9cdc2642021-09-24 23:06:54 +02001356 return _xm_reply_to_error(c);
Pali Rohár94c906a2022-01-25 18:13:03 +01001357err:
Pali Rohárca272042021-09-24 23:07:05 +02001358 err = errno;
Pali Rohárca272042021-09-24 23:07:05 +02001359 kwboot_printv("\n");
1360 errno = err;
1361 return rc;
Pali Rohár9cdc2642021-09-24 23:06:54 +02001362}
Luka Perkovd131ad62012-05-27 11:44:51 +00001363
Pali Rohár9cdc2642021-09-24 23:06:54 +02001364static int
1365kwboot_xm_finish(int fd)
1366{
1367 int rc, retries;
1368 char c;
Luka Perkovd131ad62012-05-27 11:44:51 +00001369
Pali Rohár9cdc2642021-09-24 23:06:54 +02001370 kwboot_printv("Finishing transfer\n");
1371
Pali Rohárd14a3422021-10-25 15:13:03 +02001372 retries = 0;
Pali Rohár9cdc2642021-09-24 23:06:54 +02001373 do {
1374 rc = kwboot_tty_send_char(fd, EOT);
1375 if (rc)
1376 return rc;
1377
Pali Rohára6fcac22021-10-25 15:13:04 +02001378 rc = kwboot_xm_recv_reply(fd, &c, retries < 3,
Pali Rohár82a9e132022-01-25 18:13:02 +01001379 retries > 8,
Pali Rohára6fcac22021-10-25 15:13:04 +02001380 0, NULL, 0, NULL);
Pali Rohár9cdc2642021-09-24 23:06:54 +02001381 if (rc)
1382 return rc;
Pali Rohárd14a3422021-10-25 15:13:03 +02001383 } while (c == NAK && retries++ < 16);
Pali Rohár9cdc2642021-09-24 23:06:54 +02001384
1385 return _xm_reply_to_error(c);
Luka Perkovd131ad62012-05-27 11:44:51 +00001386}
1387
1388static int
Pali Rohár2ef87f72021-09-24 23:06:48 +02001389kwboot_xmodem_one(int tty, int *pnum, int header, const uint8_t *data,
Pali Rohárca272042021-09-24 23:07:05 +02001390 size_t size, int baudrate)
Luka Perkovd131ad62012-05-27 11:44:51 +00001391{
Pali Rohár48b3ea62021-09-24 23:06:50 +02001392 int done_print = 0;
Pali Rohár2ef87f72021-09-24 23:06:48 +02001393 size_t sent, left;
1394 int rc;
Luka Perkovd131ad62012-05-27 11:44:51 +00001395
Pali Rohár2ef87f72021-09-24 23:06:48 +02001396 kwboot_printv("Sending boot image %s (%zu bytes)...\n",
1397 header ? "header" : "data", size);
Luka Perkovd131ad62012-05-27 11:44:51 +00001398
Pali Rohár2ef87f72021-09-24 23:06:48 +02001399 left = size;
1400 sent = 0;
Luka Perkovd131ad62012-05-27 11:44:51 +00001401
Pali Rohár2ef87f72021-09-24 23:06:48 +02001402 while (sent < size) {
Luka Perkovd131ad62012-05-27 11:44:51 +00001403 struct kwboot_block block;
Pali Rohár48b3ea62021-09-24 23:06:50 +02001404 int last_block;
Pali Rohár2ef87f72021-09-24 23:06:48 +02001405 size_t blksz;
Luka Perkovd131ad62012-05-27 11:44:51 +00001406
Pali Rohár2ef87f72021-09-24 23:06:48 +02001407 blksz = kwboot_xm_makeblock(&block, data, left, (*pnum)++);
1408 data += blksz;
Luka Perkovd131ad62012-05-27 11:44:51 +00001409
Pali Rohár48b3ea62021-09-24 23:06:50 +02001410 last_block = (left <= blksz);
1411
Pali Rohár5875ad42022-01-25 18:13:05 +01001412 /*
1413 * Handling of repeated xmodem packets is completely broken in
1414 * Armada 385 BootROM - it completely ignores xmodem packet
1415 * numbers, they are only used for checksum verification.
1416 * BootROM can handle a retry of the xmodem packet only during
1417 * the transmission of kwbimage header and only if BootROM
1418 * itself sent NAK response to previous attempt (it does it on
1419 * checksum failure). During the transmission of kwbimage data
1420 * part, BootROM always expects next xmodem packet, even if it
1421 * sent NAK to previous attempt - there is absolutely no way to
1422 * repair incorrectly transmitted xmodem packet during kwbimage
1423 * data part upload. Also, if kwboot receives non-ACK/NAK
1424 * response (meaning that original BootROM response was damaged
1425 * on UART) there is no way to detect if BootROM accepted xmodem
1426 * packet or not and no way to check if kwboot could repeat the
1427 * packet or not.
1428 *
1429 * Stop transfer and return failure if kwboot receives unknown
1430 * reply if non-xmodem reply is not allowed (for all xmodem
1431 * packets except the last header packet) or when non-ACK reply
1432 * is received during data part transfer.
1433 */
Pali Rohár48b3ea62021-09-24 23:06:50 +02001434 rc = kwboot_xm_sendblock(tty, &block, header && last_block,
Pali Rohár5875ad42022-01-25 18:13:05 +01001435 &done_print, baudrate, header);
Luka Perkovd131ad62012-05-27 11:44:51 +00001436 if (rc)
1437 goto out;
1438
Pali Rohár2ef87f72021-09-24 23:06:48 +02001439 sent += blksz;
1440 left -= blksz;
Luka Perkovd131ad62012-05-27 11:44:51 +00001441
Pali Rohár48b3ea62021-09-24 23:06:50 +02001442 if (!done_print)
1443 kwboot_progress(sent * 100 / size, '.');
Pali Rohár2ef87f72021-09-24 23:06:48 +02001444 }
Luka Perkovd131ad62012-05-27 11:44:51 +00001445
Pali Rohár48b3ea62021-09-24 23:06:50 +02001446 if (!done_print)
1447 kwboot_printv("Done\n");
Pali Rohár2ef87f72021-09-24 23:06:48 +02001448
1449 return 0;
Luka Perkovd131ad62012-05-27 11:44:51 +00001450out:
Pali Rohárd5ba8db2021-09-24 23:06:47 +02001451 kwboot_printv("\n");
Luka Perkovd131ad62012-05-27 11:44:51 +00001452 return rc;
Pali Rohár2ef87f72021-09-24 23:06:48 +02001453}
Luka Perkovd131ad62012-05-27 11:44:51 +00001454
Pali Rohár2ef87f72021-09-24 23:06:48 +02001455static int
Pali Rohárca272042021-09-24 23:07:05 +02001456kwboot_xmodem(int tty, const void *_img, size_t size, int baudrate)
Pali Rohár2ef87f72021-09-24 23:06:48 +02001457{
1458 const uint8_t *img = _img;
1459 int rc, pnum;
1460 size_t hdrsz;
1461
Marek Behúnfe2fd732021-09-24 23:07:01 +02001462 hdrsz = kwbheader_size(img);
Pali Rohár2ef87f72021-09-24 23:06:48 +02001463
Pali Rohárf8017c32021-11-05 23:29:58 +01001464 /*
1465 * If header size is not aligned to xmodem block size (which applies
1466 * for all images in kwbimage v0 format) then we have to ensure that
1467 * the last xmodem block of header contains beginning of the data
1468 * followed by the header. So align header size to xmodem block size.
1469 */
1470 hdrsz += (KWBOOT_XM_BLKSZ - hdrsz % KWBOOT_XM_BLKSZ) % KWBOOT_XM_BLKSZ;
Pali Rohárbb949e12023-03-23 20:57:54 +01001471 if (hdrsz > size)
1472 hdrsz = size;
Pali Rohárf8017c32021-11-05 23:29:58 +01001473
Pali Rohár2ef87f72021-09-24 23:06:48 +02001474 pnum = 1;
1475
Pali Rohárca272042021-09-24 23:07:05 +02001476 rc = kwboot_xmodem_one(tty, &pnum, 1, img, hdrsz, baudrate);
Pali Rohár2ef87f72021-09-24 23:06:48 +02001477 if (rc)
1478 return rc;
1479
Pali Rohárf8017c32021-11-05 23:29:58 +01001480 /*
1481 * If we have already sent image data as a part of the last
1482 * xmodem header block then we have nothing more to send.
1483 */
1484 if (hdrsz < size) {
1485 img += hdrsz;
1486 size -= hdrsz;
1487 rc = kwboot_xmodem_one(tty, &pnum, 0, img, size, 0);
1488 if (rc)
1489 return rc;
1490 }
Pali Rohár2ef87f72021-09-24 23:06:48 +02001491
Pali Rohárca272042021-09-24 23:07:05 +02001492 rc = kwboot_xm_finish(tty);
1493 if (rc)
1494 return rc;
1495
1496 if (baudrate) {
Pali Rohárca272042021-09-24 23:07:05 +02001497 kwboot_printv("\nChanging baudrate back to 115200 Bd\n\n");
1498 rc = kwboot_tty_change_baudrate(tty, 115200);
1499 if (rc)
1500 return rc;
1501 }
1502
1503 return 0;
Luka Perkovd131ad62012-05-27 11:44:51 +00001504}
1505
1506static int
Pali Roháre8d26e82022-03-02 11:49:23 +01001507kwboot_term_pipe(int in, int out, const char *quit, int *s, const char *kbs, int *k)
Luka Perkovd131ad62012-05-27 11:44:51 +00001508{
Pali Rohárde751402022-02-03 17:45:20 +01001509 char buf[128];
Pali Roháre8d26e82022-03-02 11:49:23 +01001510 ssize_t nin, noff;
Luka Perkovd131ad62012-05-27 11:44:51 +00001511
Pali Rohárde751402022-02-03 17:45:20 +01001512 nin = read(in, buf, sizeof(buf));
Willy Tarreau4469bd72018-07-03 12:10:31 -04001513 if (nin <= 0)
Luka Perkovd131ad62012-05-27 11:44:51 +00001514 return -1;
1515
Pali Roháre8d26e82022-03-02 11:49:23 +01001516 noff = 0;
1517
1518 if (quit || kbs) {
Luka Perkovd131ad62012-05-27 11:44:51 +00001519 int i;
1520
1521 for (i = 0; i < nin; i++) {
Pali Roháre8d26e82022-03-02 11:49:23 +01001522 if ((quit || kbs) &&
1523 (!quit || buf[i] != quit[*s]) &&
1524 (!kbs || buf[i] != kbs[*k])) {
1525 const char *prefix;
1526 int plen;
1527
1528 if (quit && kbs) {
1529 prefix = (*s >= *k) ? quit : kbs;
1530 plen = (*s >= *k) ? *s : *k;
1531 } else if (quit) {
1532 prefix = quit;
1533 plen = *s;
1534 } else {
1535 prefix = kbs;
1536 plen = *k;
1537 }
1538
1539 if (plen > i && kwboot_write(out, prefix, plen - i) < 0)
1540 return -1;
1541 }
1542
1543 if (quit && buf[i] == quit[*s]) {
Luka Perkovd131ad62012-05-27 11:44:51 +00001544 (*s)++;
Pali Rohárde751402022-02-03 17:45:20 +01001545 if (!quit[*s]) {
Pali Rohár7938b3b2022-02-18 12:24:13 +01001546 nin = (i > *s) ? (i - *s) : 0;
Pali Rohárde751402022-02-03 17:45:20 +01001547 break;
1548 }
Pali Roháre8d26e82022-03-02 11:49:23 +01001549 } else if (quit) {
Marek Behúne453bb42021-09-24 23:06:41 +02001550 *s = 0;
Pali Rohárb943eee2021-07-23 11:14:20 +02001551 }
Pali Roháre8d26e82022-03-02 11:49:23 +01001552
1553 if (kbs && buf[i] == kbs[*k]) {
1554 (*k)++;
1555 if (!kbs[*k]) {
1556 if (i > *k + noff &&
1557 kwboot_write(out, buf + noff, i - *k - noff) < 0)
1558 return -1;
1559 /*
1560 * Replace backspace key by '\b' (0x08)
1561 * byte which is the only recognized
1562 * backspace byte by Marvell BootROM.
1563 */
1564 if (write(out, "\x08", 1) < 0)
1565 return -1;
1566 noff = i + 1;
1567 *k = 0;
1568 }
1569 } else if (kbs) {
1570 *k = 0;
1571 }
Luka Perkovd131ad62012-05-27 11:44:51 +00001572 }
Pali Rohárde751402022-02-03 17:45:20 +01001573
Pali Roháre8d26e82022-03-02 11:49:23 +01001574 if (i == nin) {
1575 i = 0;
1576 if (quit && i < *s)
1577 i = *s;
1578 if (kbs && i < *k)
1579 i = *k;
1580 nin -= (nin > i) ? i : nin;
1581 }
Luka Perkovd131ad62012-05-27 11:44:51 +00001582 }
1583
Pali Roháre8d26e82022-03-02 11:49:23 +01001584 if (nin > noff && kwboot_write(out, buf + noff, nin - noff) < 0)
Marek Behúne453bb42021-09-24 23:06:41 +02001585 return -1;
Luka Perkovd131ad62012-05-27 11:44:51 +00001586
1587 return 0;
1588}
1589
1590static int
1591kwboot_terminal(int tty)
1592{
Pali Roháre8d26e82022-03-02 11:49:23 +01001593 int rc, in, s, k;
1594 const char *kbs = NULL;
Marek Behún46237e62021-09-24 23:06:40 +02001595 const char *quit = "\34c";
Luka Perkovd131ad62012-05-27 11:44:51 +00001596 struct termios otio, tio;
1597
1598 rc = -1;
1599
1600 in = STDIN_FILENO;
1601 if (isatty(in)) {
1602 rc = tcgetattr(in, &otio);
1603 if (!rc) {
1604 tio = otio;
1605 cfmakeraw(&tio);
1606 rc = tcsetattr(in, TCSANOW, &tio);
1607 }
1608 if (rc) {
1609 perror("tcsetattr");
1610 goto out;
1611 }
1612
Pali Roháre8d26e82022-03-02 11:49:23 +01001613 /*
1614 * Get sequence for backspace key used by the current
1615 * terminal. Every occurrence of this sequence will be
1616 * replaced by '\b' byte which is the only recognized
1617 * backspace byte by Marvell BootROM.
1618 *
1619 * Note that we cannot read this sequence from termios
1620 * c_cc[VERASE] as VERASE is valid only when ICANON is
1621 * set in termios c_lflag, which is not case for us.
1622 *
1623 * Also most terminals do not set termios c_cc[VERASE]
1624 * as c_cc[VERASE] can specify only one-byte sequence
1625 * and instead let applications to read (possible
1626 * multi-byte) sequence for backspace key from "kbs"
1627 * terminfo database based on $TERM env variable.
1628 *
1629 * So read "kbs" from terminfo database via tigetstr()
1630 * call after successful setupterm(). Most terminals
1631 * use byte 0x7F for backspace key, so replacement with
1632 * '\b' is required.
1633 */
1634 if (setupterm(NULL, STDOUT_FILENO, &rc) == 0) {
1635 kbs = tigetstr("kbs");
1636 if (kbs == (char *)-1)
1637 kbs = NULL;
1638 }
1639
Luka Perkovd131ad62012-05-27 11:44:51 +00001640 kwboot_printv("[Type Ctrl-%c + %c to quit]\r\n",
Marek Behún5fa04f42021-09-24 23:07:11 +02001641 quit[0] | 0100, quit[1]);
Luka Perkovd131ad62012-05-27 11:44:51 +00001642 } else
1643 in = -1;
1644
1645 rc = 0;
1646 s = 0;
Pali Roháre8d26e82022-03-02 11:49:23 +01001647 k = 0;
Luka Perkovd131ad62012-05-27 11:44:51 +00001648
1649 do {
1650 fd_set rfds;
1651 int nfds = 0;
1652
Pali Rohár0a143412021-10-25 15:12:52 +02001653 FD_ZERO(&rfds);
Luka Perkovd131ad62012-05-27 11:44:51 +00001654 FD_SET(tty, &rfds);
1655 nfds = nfds < tty ? tty : nfds;
1656
1657 if (in >= 0) {
1658 FD_SET(in, &rfds);
1659 nfds = nfds < in ? in : nfds;
1660 }
1661
1662 nfds = select(nfds + 1, &rfds, NULL, NULL, NULL);
1663 if (nfds < 0)
1664 break;
1665
1666 if (FD_ISSET(tty, &rfds)) {
Pali Roháre8d26e82022-03-02 11:49:23 +01001667 rc = kwboot_term_pipe(tty, STDOUT_FILENO, NULL, NULL, NULL, NULL);
Luka Perkovd131ad62012-05-27 11:44:51 +00001668 if (rc)
1669 break;
1670 }
1671
Marek Behúnf30cb0d2021-09-24 23:06:39 +02001672 if (in >= 0 && FD_ISSET(in, &rfds)) {
Pali Roháre8d26e82022-03-02 11:49:23 +01001673 rc = kwboot_term_pipe(in, tty, quit, &s, kbs, &k);
Luka Perkovd131ad62012-05-27 11:44:51 +00001674 if (rc)
1675 break;
1676 }
1677 } while (quit[s] != 0);
1678
Pali Rohárec0fe5b2021-07-23 11:14:18 +02001679 if (in >= 0)
1680 tcsetattr(in, TCSANOW, &otio);
Pali Rohár49a0a3b2021-07-23 11:14:19 +02001681 printf("\n");
Luka Perkovd131ad62012-05-27 11:44:51 +00001682out:
1683 return rc;
1684}
1685
1686static void *
Pali Rohár04ced022021-09-24 23:07:03 +02001687kwboot_read_image(const char *path, size_t *size, size_t reserve)
Luka Perkovd131ad62012-05-27 11:44:51 +00001688{
Pali Rohárddc04fa2021-09-24 23:06:55 +02001689 int rc, fd;
Luka Perkovd131ad62012-05-27 11:44:51 +00001690 void *img;
Pali Rohára339d6c2022-04-06 15:18:59 +02001691 off_t len;
Pali Rohár04ced022021-09-24 23:07:03 +02001692 off_t tot;
Luka Perkovd131ad62012-05-27 11:44:51 +00001693
1694 rc = -1;
Luka Perkovd131ad62012-05-27 11:44:51 +00001695 img = NULL;
1696
1697 fd = open(path, O_RDONLY);
1698 if (fd < 0)
1699 goto out;
1700
Pali Rohára339d6c2022-04-06 15:18:59 +02001701 len = lseek(fd, 0, SEEK_END);
1702 if (len == (off_t)-1)
Luka Perkovd131ad62012-05-27 11:44:51 +00001703 goto out;
1704
Pali Rohára339d6c2022-04-06 15:18:59 +02001705 if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
1706 goto out;
1707
1708 img = malloc(len + reserve);
Pali Rohár04ced022021-09-24 23:07:03 +02001709 if (!img)
Luka Perkovd131ad62012-05-27 11:44:51 +00001710 goto out;
Pali Rohár04ced022021-09-24 23:07:03 +02001711
1712 tot = 0;
Pali Rohára339d6c2022-04-06 15:18:59 +02001713 while (tot < len) {
1714 ssize_t rd = read(fd, img + tot, len - tot);
Pali Rohár04ced022021-09-24 23:07:03 +02001715
1716 if (rd < 0)
1717 goto out;
1718
1719 tot += rd;
1720
Pali Rohára339d6c2022-04-06 15:18:59 +02001721 if (!rd && tot < len) {
Pali Rohár04ced022021-09-24 23:07:03 +02001722 errno = EIO;
1723 goto out;
1724 }
Luka Perkovd131ad62012-05-27 11:44:51 +00001725 }
1726
1727 rc = 0;
Pali Rohára339d6c2022-04-06 15:18:59 +02001728 *size = len;
Luka Perkovd131ad62012-05-27 11:44:51 +00001729out:
1730 if (rc && img) {
Pali Rohár04ced022021-09-24 23:07:03 +02001731 free(img);
Luka Perkovd131ad62012-05-27 11:44:51 +00001732 img = NULL;
1733 }
1734 if (fd >= 0)
1735 close(fd);
1736
1737 return img;
1738}
1739
1740static uint8_t
Marek Behúnfe2fd732021-09-24 23:07:01 +02001741kwboot_hdr_csum8(const void *hdr)
Luka Perkovd131ad62012-05-27 11:44:51 +00001742{
Marek Behúnfe2fd732021-09-24 23:07:01 +02001743 const uint8_t *data = hdr;
1744 uint8_t csum;
1745 size_t size;
1746
1747 size = kwbheader_size_for_csum(hdr);
Luka Perkovd131ad62012-05-27 11:44:51 +00001748
1749 for (csum = 0; size-- > 0; data++)
1750 csum += *data;
1751
1752 return csum;
1753}
1754
Pali Rohárad9a3ac2021-10-25 15:12:55 +02001755static uint32_t *
1756kwboot_img_csum32_ptr(void *img)
1757{
1758 struct main_hdr_v1 *hdr = img;
1759 uint32_t datasz;
1760
1761 datasz = le32_to_cpu(hdr->blocksize) - sizeof(uint32_t);
1762
1763 return img + le32_to_cpu(hdr->srcaddr) + datasz;
1764}
1765
1766static uint32_t
1767kwboot_img_csum32(const void *img)
1768{
1769 const struct main_hdr_v1 *hdr = img;
1770 uint32_t datasz, csum = 0;
1771 const uint32_t *data;
1772
1773 datasz = le32_to_cpu(hdr->blocksize) - sizeof(csum);
1774 if (datasz % sizeof(uint32_t))
1775 return 0;
1776
1777 data = img + le32_to_cpu(hdr->srcaddr);
1778 while (datasz > 0) {
1779 csum += le32_to_cpu(*data++);
1780 datasz -= 4;
1781 }
1782
1783 return cpu_to_le32(csum);
1784}
1785
Luka Perkovd131ad62012-05-27 11:44:51 +00001786static int
Pali Rohár550c9302021-09-24 23:06:57 +02001787kwboot_img_is_secure(void *img)
1788{
1789 struct opt_hdr_v1 *ohdr;
1790
1791 for_each_opt_hdr_v1 (ohdr, img)
1792 if (ohdr->headertype == OPT_HDR_V1_SECURE_TYPE)
1793 return 1;
1794
1795 return 0;
1796}
1797
Pali Rohára1906672023-01-08 13:46:14 +01001798static int
1799kwboot_img_has_ddr_init(void *img)
1800{
1801 const struct register_set_hdr_v1 *rhdr;
1802 const struct main_hdr_v0 *hdr0;
1803 struct opt_hdr_v1 *ohdr;
1804 u32 ohdrsz;
1805 int last;
1806
1807 /*
1808 * kwbimage v0 image headers contain DDR init code either in
1809 * extension header or in binary code header.
1810 */
1811 if (kwbimage_version(img) == 0) {
1812 hdr0 = img;
1813 return hdr0->ext || hdr0->bin;
1814 }
1815
1816 /*
1817 * kwbimage v1 image headers contain DDR init code either in binary
1818 * code header or in a register set list header with SDRAM_SETUP.
1819 */
1820 for_each_opt_hdr_v1 (ohdr, img) {
1821 if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE)
1822 return 1;
1823 if (ohdr->headertype == OPT_HDR_V1_REGISTER_TYPE) {
1824 rhdr = (const struct register_set_hdr_v1 *)ohdr;
1825 ohdrsz = opt_hdr_v1_size(ohdr);
1826 if (ohdrsz >= sizeof(*ohdr) + sizeof(rhdr->data[0].last_entry)) {
1827 ohdrsz -= sizeof(*ohdr) + sizeof(rhdr->data[0].last_entry);
1828 last = ohdrsz / sizeof(rhdr->data[0].entry);
1829 if (rhdr->data[last].last_entry.delay ==
1830 REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP)
1831 return 1;
1832 }
1833 }
1834 }
1835
1836 return 0;
1837}
1838
Pali Rohárca272042021-09-24 23:07:05 +02001839static void *
Pali Rohár063cb352021-10-25 15:12:56 +02001840kwboot_img_grow_data_right(void *img, size_t *size, size_t grow)
Pali Rohárca272042021-09-24 23:07:05 +02001841{
Pali Rohárca272042021-09-24 23:07:05 +02001842 struct main_hdr_v1 *hdr = img;
Pali Rohár063cb352021-10-25 15:12:56 +02001843 void *result;
Pali Rohárca272042021-09-24 23:07:05 +02001844
Pali Rohár063cb352021-10-25 15:12:56 +02001845 /*
1846 * 32-bit checksum comes after end of image code, so we will be putting
1847 * new code there. So we get this pointer and then increase data size
1848 * (since increasing data size changes kwboot_img_csum32_ptr() return
1849 * value).
1850 */
1851 result = kwboot_img_csum32_ptr(img);
Pali Rohárca272042021-09-24 23:07:05 +02001852 hdr->blocksize = cpu_to_le32(le32_to_cpu(hdr->blocksize) + grow);
Pali Rohár063cb352021-10-25 15:12:56 +02001853 *size += grow;
Pali Rohárca272042021-09-24 23:07:05 +02001854
Pali Rohár063cb352021-10-25 15:12:56 +02001855 return result;
Pali Rohárca272042021-09-24 23:07:05 +02001856}
1857
Pali Rohár04ced022021-09-24 23:07:03 +02001858static void
1859kwboot_img_grow_hdr(void *img, size_t *size, size_t grow)
1860{
1861 uint32_t hdrsz, datasz, srcaddr;
1862 struct main_hdr_v1 *hdr = img;
Pali Rohárd656f5a2021-10-25 15:13:02 +02001863 struct opt_hdr_v1 *ohdr;
Pali Rohár04ced022021-09-24 23:07:03 +02001864 uint8_t *data;
1865
1866 srcaddr = le32_to_cpu(hdr->srcaddr);
1867
Pali Rohárd656f5a2021-10-25 15:13:02 +02001868 /* calculate real used space in kwbimage header */
1869 if (kwbimage_version(img) == 0) {
1870 hdrsz = kwbheader_size(img);
1871 } else {
1872 hdrsz = sizeof(*hdr);
1873 for_each_opt_hdr_v1 (ohdr, hdr)
1874 hdrsz += opt_hdr_v1_size(ohdr);
1875 }
1876
Pali Rohár04ced022021-09-24 23:07:03 +02001877 data = (uint8_t *)img + srcaddr;
1878 datasz = *size - srcaddr;
1879
1880 /* only move data if there is not enough space */
1881 if (hdrsz + grow > srcaddr) {
1882 size_t need = hdrsz + grow - srcaddr;
1883
1884 /* move data by enough bytes */
1885 memmove(data + need, data, datasz);
1886
1887 hdr->srcaddr = cpu_to_le32(srcaddr + need);
1888 *size += need;
1889 }
1890
1891 if (kwbimage_version(img) == 1) {
1892 hdrsz += grow;
Pali Rohárd656f5a2021-10-25 15:13:02 +02001893 if (hdrsz > kwbheader_size(img)) {
1894 hdr->headersz_msb = hdrsz >> 16;
1895 hdr->headersz_lsb = cpu_to_le16(hdrsz & 0xffff);
1896 }
Pali Rohár04ced022021-09-24 23:07:03 +02001897 }
1898}
1899
Pali Rohárca272042021-09-24 23:07:05 +02001900static void *
1901kwboot_add_bin_ohdr_v1(void *img, size_t *size, uint32_t binsz)
1902{
1903 struct main_hdr_v1 *hdr = img;
1904 struct opt_hdr_v1 *ohdr;
Pali Rohára85a71d2021-10-21 16:46:06 +02001905 uint32_t num_args;
1906 uint32_t offset;
Pali Rohárca272042021-09-24 23:07:05 +02001907 uint32_t ohdrsz;
Pali Roháre511cc32021-10-25 15:13:01 +02001908 uint8_t *prev_ext;
Pali Rohárca272042021-09-24 23:07:05 +02001909
Pali Rohár44691032022-01-12 18:20:52 +01001910 if (hdr->ext) {
Pali Rohárca272042021-09-24 23:07:05 +02001911 for_each_opt_hdr_v1 (ohdr, img)
1912 if (opt_hdr_v1_next(ohdr) == NULL)
1913 break;
1914
Pali Roháre511cc32021-10-25 15:13:01 +02001915 prev_ext = opt_hdr_v1_ext(ohdr);
1916 ohdr = _opt_hdr_v1_next(ohdr);
Pali Rohárca272042021-09-24 23:07:05 +02001917 } else {
Pali Rohárca272042021-09-24 23:07:05 +02001918 ohdr = (void *)(hdr + 1);
Pali Roháre511cc32021-10-25 15:13:01 +02001919 prev_ext = &hdr->ext;
Pali Rohárca272042021-09-24 23:07:05 +02001920 }
1921
Pali Rohára85a71d2021-10-21 16:46:06 +02001922 /*
1923 * ARM executable code inside the BIN header on some mvebu platforms
1924 * (e.g. A370, AXP) must always be aligned with the 128-bit boundary.
1925 * This requirement can be met by inserting dummy arguments into
1926 * BIN header, if needed.
1927 */
1928 offset = &ohdr->data[4] - (char *)img;
1929 num_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
1930
1931 ohdrsz = sizeof(*ohdr) + 4 + 4 * num_args + binsz + 4;
1932 kwboot_img_grow_hdr(hdr, size, ohdrsz);
1933
Pali Rohár44691032022-01-12 18:20:52 +01001934 *prev_ext = 1;
Pali Roháre511cc32021-10-25 15:13:01 +02001935
Pali Rohárca272042021-09-24 23:07:05 +02001936 ohdr->headertype = OPT_HDR_V1_BINARY_TYPE;
1937 ohdr->headersz_msb = ohdrsz >> 16;
1938 ohdr->headersz_lsb = cpu_to_le16(ohdrsz & 0xffff);
1939
1940 memset(&ohdr->data[0], 0, ohdrsz - sizeof(*ohdr));
Pali Rohára85a71d2021-10-21 16:46:06 +02001941 *(uint32_t *)&ohdr->data[0] = cpu_to_le32(num_args);
Pali Rohárca272042021-09-24 23:07:05 +02001942
Pali Rohára85a71d2021-10-21 16:46:06 +02001943 return &ohdr->data[4 + 4 * num_args];
Pali Rohárca272042021-09-24 23:07:05 +02001944}
1945
1946static void
Pali Rohár8dbe0272021-10-27 20:57:02 +02001947_inject_baudrate_change_code(void *img, size_t *size, int for_data,
Pali Rohár063cb352021-10-25 15:12:56 +02001948 int old_baud, int new_baud)
Pali Rohárca272042021-09-24 23:07:05 +02001949{
Pali Rohár063cb352021-10-25 15:12:56 +02001950 struct main_hdr_v1 *hdr = img;
Pali Rohár8dbe0272021-10-27 20:57:02 +02001951 uint32_t orig_datasz;
1952 uint32_t codesz;
Pali Rohár063cb352021-10-25 15:12:56 +02001953 uint8_t *code;
Pali Rohárca272042021-09-24 23:07:05 +02001954
Pali Rohár8dbe0272021-10-27 20:57:02 +02001955 if (for_data) {
Pali Rohár063cb352021-10-25 15:12:56 +02001956 orig_datasz = le32_to_cpu(hdr->blocksize) - sizeof(uint32_t);
1957
Pali Rohár8dbe0272021-10-27 20:57:02 +02001958 codesz = sizeof(kwboot_baud_code) +
1959 sizeof(kwboot_baud_code_data_jump);
1960 code = kwboot_img_grow_data_right(img, size, codesz);
Pali Rohár063cb352021-10-25 15:12:56 +02001961 } else {
Pali Rohár8dbe0272021-10-27 20:57:02 +02001962 codesz = sizeof(kwboot_baud_code_binhdr_pre) +
1963 sizeof(kwboot_baud_code) +
1964 sizeof(kwboot_baud_code_binhdr_post);
Pali Rohár063cb352021-10-25 15:12:56 +02001965 code = kwboot_add_bin_ohdr_v1(img, size, codesz);
Pali Rohár8dbe0272021-10-27 20:57:02 +02001966
1967 codesz = sizeof(kwboot_baud_code_binhdr_pre);
1968 memcpy(code, kwboot_baud_code_binhdr_pre, codesz);
1969 code += codesz;
Pali Rohárca272042021-09-24 23:07:05 +02001970 }
1971
Pali Rohár8dbe0272021-10-27 20:57:02 +02001972 codesz = sizeof(kwboot_baud_code) - 2 * sizeof(uint32_t);
1973 memcpy(code, kwboot_baud_code, codesz);
1974 code += codesz;
1975 *(uint32_t *)code = cpu_to_le32(old_baud);
1976 code += sizeof(uint32_t);
1977 *(uint32_t *)code = cpu_to_le32(new_baud);
1978 code += sizeof(uint32_t);
1979
1980 if (for_data) {
1981 codesz = sizeof(kwboot_baud_code_data_jump) - sizeof(uint32_t);
1982 memcpy(code, kwboot_baud_code_data_jump, codesz);
1983 code += codesz;
1984 *(uint32_t *)code = hdr->execaddr;
1985 code += sizeof(uint32_t);
1986 hdr->execaddr = cpu_to_le32(le32_to_cpu(hdr->destaddr) + orig_datasz);
1987 } else {
1988 codesz = sizeof(kwboot_baud_code_binhdr_post);
1989 memcpy(code, kwboot_baud_code_binhdr_post, codesz);
1990 code += codesz;
1991 }
Pali Rohárca272042021-09-24 23:07:05 +02001992}
1993
Pali Rohár5d817852023-03-29 21:25:57 +02001994static int
1995kwboot_img_guess_sata_blksz(void *img, uint32_t blkoff, uint32_t data_size, size_t total_size)
1996{
1997 uint32_t sum, *ptr, *end;
1998 int blksz;
1999
2000 /*
2001 * Try all possible sector sizes which are power of two,
2002 * at least 512 bytes and up to the 32 kB.
2003 */
2004 for (blksz = 512; blksz < 0x10000; blksz *= 2) {
2005 if (blkoff * blksz > total_size ||
2006 blkoff * blksz + data_size > total_size ||
2007 data_size % 4)
2008 break;
2009
2010 /*
2011 * Calculate data checksum and if it matches
2012 * then tried blksz should be correct.
2013 */
2014 ptr = img + blkoff * blksz;
2015 end = (void *)ptr + data_size - 4;
2016 for (sum = 0; ptr < end; ptr++)
2017 sum += *ptr;
2018
2019 if (sum == *end)
2020 return blksz;
2021 }
2022
2023 /* Fallback to 512 bytes */
2024 return 512;
2025}
2026
Pali Rohár5b039dc2023-01-10 22:33:56 +01002027static const char *
2028kwboot_img_type(uint8_t blockid)
2029{
2030 switch (blockid) {
2031 case IBR_HDR_I2C_ID: return "I2C";
2032 case IBR_HDR_SPI_ID: return "SPI";
2033 case IBR_HDR_NAND_ID: return "NAND";
2034 case IBR_HDR_SATA_ID: return "SATA";
2035 case IBR_HDR_PEX_ID: return "PEX";
2036 case IBR_HDR_UART_ID: return "UART";
2037 case IBR_HDR_SDIO_ID: return "SDIO";
2038 default: return "unknown";
2039 }
2040}
2041
Pali Rohár550c9302021-09-24 23:06:57 +02002042static int
Pali Rohárca272042021-09-24 23:07:05 +02002043kwboot_img_patch(void *img, size_t *size, int baudrate)
Luka Perkovd131ad62012-05-27 11:44:51 +00002044{
Stefan Roesee29f1db2015-09-29 09:19:59 +02002045 struct main_hdr_v1 *hdr;
Pali Rohár53ee6ec2023-01-08 13:42:07 +01002046 struct opt_hdr_v1 *ohdr;
Pali Rohár792e4232021-09-24 23:06:58 +02002047 uint32_t srcaddr;
Luka Perkovd131ad62012-05-27 11:44:51 +00002048 uint8_t csum;
Marek Behún5c8f8122021-09-24 23:07:04 +02002049 size_t hdrsz;
Stefan Roesee29f1db2015-09-29 09:19:59 +02002050 int image_ver;
Pali Rohár550c9302021-09-24 23:06:57 +02002051 int is_secure;
Luka Perkovd131ad62012-05-27 11:44:51 +00002052
Luka Perkovd131ad62012-05-27 11:44:51 +00002053 hdr = img;
2054
Pali Rohár5b039dc2023-01-10 22:33:56 +01002055 if (*size < sizeof(struct main_hdr_v1)) {
2056 fprintf(stderr, "Invalid image header size\n");
Marek Behúnb4eea8f2021-09-24 23:07:12 +02002057 goto err;
Pali Rohár5b039dc2023-01-10 22:33:56 +01002058 }
Luka Perkovd131ad62012-05-27 11:44:51 +00002059
Marek Behúnacb0b382021-09-24 23:07:00 +02002060 image_ver = kwbimage_version(img);
Pali Rohár5029d7b2021-07-23 11:14:22 +02002061 if (image_ver != 0 && image_ver != 1) {
Stefan Roesee29f1db2015-09-29 09:19:59 +02002062 fprintf(stderr, "Invalid image header version\n");
Marek Behúnb4eea8f2021-09-24 23:07:12 +02002063 goto err;
Stefan Roesee29f1db2015-09-29 09:19:59 +02002064 }
2065
Marek Behúnfe2fd732021-09-24 23:07:01 +02002066 hdrsz = kwbheader_size(hdr);
Stefan Roesee29f1db2015-09-29 09:19:59 +02002067
Pali Rohár5b039dc2023-01-10 22:33:56 +01002068 if (*size < hdrsz) {
2069 fprintf(stderr, "Invalid image header size\n");
Marek Behúnb4eea8f2021-09-24 23:07:12 +02002070 goto err;
Pali Rohár5b039dc2023-01-10 22:33:56 +01002071 }
2072
2073 kwboot_printv("Detected kwbimage v%d with %s boot signature\n", image_ver, kwboot_img_type(hdr->blockid));
Pali Rohár825a2ca2021-07-23 11:14:21 +02002074
Marek Behúnfe2fd732021-09-24 23:07:01 +02002075 csum = kwboot_hdr_csum8(hdr) - hdr->checksum;
Pali Rohár5b039dc2023-01-10 22:33:56 +01002076 if (csum != hdr->checksum) {
2077 fprintf(stderr, "Image has invalid header checksum stored in image header\n");
Marek Behúnb4eea8f2021-09-24 23:07:12 +02002078 goto err;
Pali Rohár5b039dc2023-01-10 22:33:56 +01002079 }
Luka Perkovd131ad62012-05-27 11:44:51 +00002080
Pali Rohár792e4232021-09-24 23:06:58 +02002081 srcaddr = le32_to_cpu(hdr->srcaddr);
2082
2083 switch (hdr->blockid) {
2084 case IBR_HDR_SATA_ID:
Pali Rohár5d817852023-03-29 21:25:57 +02002085 hdr->srcaddr = cpu_to_le32(srcaddr * kwboot_img_guess_sata_blksz(img, srcaddr, le32_to_cpu(hdr->blocksize), *size));
Pali Rohár792e4232021-09-24 23:06:58 +02002086 break;
2087
Pali Rohár792e4232021-09-24 23:06:58 +02002088 case IBR_HDR_PEX_ID:
2089 if (srcaddr == 0xFFFFFFFF)
2090 hdr->srcaddr = cpu_to_le32(hdrsz);
2091 break;
Pali Rohárf2c644e2021-09-24 23:06:59 +02002092
2093 case IBR_HDR_SPI_ID:
2094 if (hdr->destaddr == cpu_to_le32(0xFFFFFFFF)) {
2095 kwboot_printv("Patching destination and execution addresses from SPI/NOR XIP area to DDR area 0x00800000\n");
Pali Rohár7bfc15e2023-01-21 12:59:20 +01002096 hdr->destaddr = cpu_to_le32(0x00800000 + le32_to_cpu(hdr->srcaddr));
2097 hdr->execaddr = cpu_to_le32(0x00800000 + le32_to_cpu(hdr->execaddr));
Pali Rohárf2c644e2021-09-24 23:06:59 +02002098 }
2099 break;
Pali Rohár792e4232021-09-24 23:06:58 +02002100 }
2101
Pali Rohár5b039dc2023-01-10 22:33:56 +01002102 if (hdrsz > le32_to_cpu(hdr->srcaddr)) {
2103 fprintf(stderr, "Image has invalid data offset stored in image header\n");
Marek Behúnb4eea8f2021-09-24 23:07:12 +02002104 goto err;
Pali Rohár5b039dc2023-01-10 22:33:56 +01002105 }
2106
2107 if (*size < le32_to_cpu(hdr->srcaddr) + le32_to_cpu(hdr->blocksize)) {
2108 fprintf(stderr, "Image has invalid data size stored in image header\n");
2109 goto err;
2110 }
Pali Rohár04ced022021-09-24 23:07:03 +02002111
Pali Rohár53ee6ec2023-01-08 13:42:07 +01002112 for_each_opt_hdr_v1 (ohdr, hdr) {
2113 if (!opt_hdr_v1_valid_size(ohdr, (const uint8_t *)hdr + hdrsz)) {
2114 fprintf(stderr, "Invalid optional image header\n");
2115 goto err;
2116 }
2117 }
2118
Pali Rohár7665ed22023-01-08 13:38:27 +01002119 /*
2120 * The 32-bit data checksum is optional for UART image. If it is not
2121 * present (checksum detected as invalid) then grow data part of the
2122 * image for the checksum, so it can be inserted there.
2123 */
2124 if (kwboot_img_csum32(img) != *kwboot_img_csum32_ptr(img)) {
2125 if (hdr->blockid != IBR_HDR_UART_ID) {
2126 fprintf(stderr, "Image has invalid data checksum\n");
2127 goto err;
2128 }
2129 kwboot_img_grow_data_right(img, size, sizeof(uint32_t));
Pali Rohár2b7852c2023-03-23 20:57:53 +01002130 /* Update the 32-bit data checksum */
2131 *kwboot_img_csum32_ptr(img) = kwboot_img_csum32(img);
Pali Rohár7665ed22023-01-08 13:38:27 +01002132 }
Pali Rohárad9a3ac2021-10-25 15:12:55 +0200