2 * Boot a Marvell SoC, with Xmodem over UART0.
3 * supports Kirkwood, Dove, Armada 370, Armada XP, Armada 375, Armada 38x and
6 * (c) 2012 Daniel Stodden <daniel.stodden@gmail.com>
7 * (c) 2021 Pali Rohár <pali@kernel.org>
8 * (c) 2021 Marek Behún <marek.behun@nic.cz>
10 * References: marvell.com, "88F6180, 88F6190, 88F6192, and 88F6281
11 * Integrated Controller: Functional Specifications" December 2,
12 * 2008. Chapter 24.2 "BootROM Firmware".
34 #include "termios_linux.h"
40 * These functions are in <term.h> header file, but this header file conflicts
41 * with "termios_linux.h" header file. So declare these functions manually.
43 extern int setupterm(const char *, int, int *);
44 extern char *tigetstr(const char *);
47 * Marvell BootROM UART Sensing
50 static unsigned char kwboot_msg_boot[] = {
51 0xBB, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77
54 static unsigned char kwboot_msg_debug[] = {
55 0xDD, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77
58 /* Defines known to work on Kirkwood */
59 #define KWBOOT_MSG_RSP_TIMEO 50 /* ms */
61 /* Defines known to work on Armada XP */
62 #define KWBOOT_MSG_RSP_TIMEO_AXP 1000 /* ms */
68 #define SOH 1 /* sender start of block header */
69 #define EOT 4 /* sender end of block transfer */
70 #define ACK 6 /* target block ack */
71 #define NAK 21 /* target block negative ack */
73 #define KWBOOT_XM_BLKSZ 128 /* xmodem block size */
79 uint8_t data[KWBOOT_XM_BLKSZ];
83 #define KWBOOT_BLK_RSP_TIMEO 2000 /* ms */
84 #define KWBOOT_HDR_RSP_TIMEO 10000 /* ms */
86 /* ARM code to change baudrate */
87 static unsigned char kwboot_baud_code[] = {
88 /* ; #define UART_BASE 0xd0012000 */
89 /* ; #define DLL 0x00 */
90 /* ; #define DLH 0x04 */
91 /* ; #define LCR 0x0c */
92 /* ; #define DLAB 0x80 */
93 /* ; #define LSR 0x14 */
94 /* ; #define TEMT 0x40 */
95 /* ; #define DIV_ROUND(a, b) ((a + b/2) / b) */
97 /* ; u32 set_baudrate(u32 old_b, u32 new_b) { */
99 /* ; (!(readl(UART_BASE + LSR) & TEMT)); */
100 /* ; u32 lcr = readl(UART_BASE + LCR); */
101 /* ; writel(UART_BASE + LCR, lcr | DLAB); */
102 /* ; u8 old_dll = readl(UART_BASE + DLL); */
103 /* ; u8 old_dlh = readl(UART_BASE + DLH); */
104 /* ; u16 old_dl = old_dll | (old_dlh << 8); */
105 /* ; u32 clk = old_b * old_dl; */
106 /* ; u16 new_dl = DIV_ROUND(clk, new_b); */
107 /* ; u8 new_dll = new_dl & 0xff; */
108 /* ; u8 new_dlh = (new_dl >> 8) & 0xff; */
109 /* ; writel(UART_BASE + DLL, new_dll); */
110 /* ; writel(UART_BASE + DLH, new_dlh); */
111 /* ; writel(UART_BASE + LCR, lcr & ~DLAB); */
116 /* ; r0 = UART_BASE */
117 0x0d, 0x02, 0xa0, 0xe3, /* mov r0, #0xd0000000 */
118 0x12, 0x0a, 0x80, 0xe3, /* orr r0, r0, #0x12000 */
120 /* ; Wait until Transmitter FIFO is Empty */
121 /* .Lloop_txempty: */
122 /* ; r1 = UART_BASE[LSR] & TEMT */
123 0x14, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x14] */
124 0x40, 0x00, 0x11, 0xe3, /* tst r1, #0x40 */
125 0xfc, 0xff, 0xff, 0x0a, /* beq .Lloop_txempty */
127 /* ; Set Divisor Latch Access Bit */
128 /* ; UART_BASE[LCR] |= DLAB */
129 0x0c, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x0c] */
130 0x80, 0x10, 0x81, 0xe3, /* orr r1, r1, #0x80 */
131 0x0c, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0c] */
133 /* ; Read current Divisor Latch */
134 /* ; r1 = UART_BASE[DLH]<<8 | UART_BASE[DLL] */
135 0x00, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x00] */
136 0xff, 0x10, 0x01, 0xe2, /* and r1, r1, #0xff */
137 0x01, 0x20, 0xa0, 0xe1, /* mov r2, r1 */
138 0x04, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x04] */
139 0xff, 0x10, 0x01, 0xe2, /* and r1, r1, #0xff */
140 0x41, 0x14, 0xa0, 0xe1, /* asr r1, r1, #8 */
141 0x02, 0x10, 0x81, 0xe1, /* orr r1, r1, r2 */
143 /* ; Read old baudrate value */
144 /* ; r2 = old_baudrate */
145 0x74, 0x20, 0x9f, 0xe5, /* ldr r2, old_baudrate */
147 /* ; Calculate base clock */
149 0x92, 0x01, 0x01, 0xe0, /* mul r1, r2, r1 */
151 /* ; Read new baudrate value */
152 /* ; r2 = new_baudrate */
153 0x70, 0x20, 0x9f, 0xe5, /* ldr r2, new_baudrate */
155 /* ; Calculate new Divisor Latch */
156 /* ; r1 = DIV_ROUND(r1, r2) = */
157 /* ; = (r1 + r2/2) / r2 */
158 0xa2, 0x10, 0x81, 0xe0, /* add r1, r1, r2, lsr #1 */
159 0x02, 0x40, 0xa0, 0xe1, /* mov r4, r2 */
160 0xa1, 0x00, 0x54, 0xe1, /* cmp r4, r1, lsr #1 */
162 0x84, 0x40, 0xa0, 0x91, /* movls r4, r4, lsl #1 */
163 0xa1, 0x00, 0x54, 0xe1, /* cmp r4, r1, lsr #1 */
164 0xfc, 0xff, 0xff, 0x9a, /* bls .Lloop_div1 */
165 0x00, 0x30, 0xa0, 0xe3, /* mov r3, #0 */
167 0x04, 0x00, 0x51, 0xe1, /* cmp r1, r4 */
168 0x04, 0x10, 0x41, 0x20, /* subhs r1, r1, r4 */
169 0x03, 0x30, 0xa3, 0xe0, /* adc r3, r3, r3 */
170 0xa4, 0x40, 0xa0, 0xe1, /* mov r4, r4, lsr #1 */
171 0x02, 0x00, 0x54, 0xe1, /* cmp r4, r2 */
172 0xf9, 0xff, 0xff, 0x2a, /* bhs .Lloop_div2 */
173 0x03, 0x10, 0xa0, 0xe1, /* mov r1, r3 */
175 /* ; Set new Divisor Latch Low */
176 /* ; UART_BASE[DLL] = r1 & 0xff */
177 0x01, 0x20, 0xa0, 0xe1, /* mov r2, r1 */
178 0xff, 0x20, 0x02, 0xe2, /* and r2, r2, #0xff */
179 0x00, 0x20, 0x80, 0xe5, /* str r2, [r0, #0x00] */
181 /* ; Set new Divisor Latch High */
182 /* ; UART_BASE[DLH] = r1>>8 & 0xff */
183 0x41, 0x24, 0xa0, 0xe1, /* asr r2, r1, #8 */
184 0xff, 0x20, 0x02, 0xe2, /* and r2, r2, #0xff */
185 0x04, 0x20, 0x80, 0xe5, /* str r2, [r0, #0x04] */
187 /* ; Clear Divisor Latch Access Bit */
188 /* ; UART_BASE[LCR] &= ~DLAB */
189 0x0c, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x0c] */
190 0x80, 0x10, 0xc1, 0xe3, /* bic r1, r1, #0x80 */
191 0x0c, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0c] */
193 /* ; Loop 0x2dc000 (2998272) cycles */
194 /* ; which is about 5ms on 1200 MHz CPU */
195 /* ; r1 = 0x2dc000 */
196 0xb7, 0x19, 0xa0, 0xe3, /* mov r1, #0x2dc000 */
198 0x01, 0x10, 0x41, 0xe2, /* sub r1, r1, #1 */
199 0x00, 0x00, 0x51, 0xe3, /* cmp r1, #0 */
200 0xfc, 0xff, 0xff, 0x1a, /* bne .Lloop_sleep */
202 /* ; Jump to the end of execution */
203 0x01, 0x00, 0x00, 0xea, /* b end */
205 /* ; Placeholder for old baudrate value */
207 0x00, 0x00, 0x00, 0x00, /* .word 0 */
209 /* ; Placeholder for new baudrate value */
211 0x00, 0x00, 0x00, 0x00, /* .word 0 */
216 /* ARM code from binary header executed by BootROM before changing baudrate */
217 static unsigned char kwboot_baud_code_binhdr_pre[] = {
218 /* ; #define UART_BASE 0xd0012000 */
219 /* ; #define THR 0x00 */
220 /* ; #define LSR 0x14 */
221 /* ; #define THRE 0x20 */
223 /* ; void send_preamble(void) { */
224 /* ; const u8 *str = "$baudratechange"; */
228 /* ; ((readl(UART_BASE + LSR) & THRE)); */
230 /* ; writel(UART_BASE + THR, c); */
234 /* ; Preserve registers for BootROM */
235 0xfe, 0x5f, 0x2d, 0xe9, /* push { r1 - r12, lr } */
237 /* ; r0 = UART_BASE */
238 0x0d, 0x02, 0xa0, 0xe3, /* mov r0, #0xd0000000 */
239 0x12, 0x0a, 0x80, 0xe3, /* orr r0, r0, #0x12000 */
241 /* ; r2 = address of preamble string */
242 0x00, 0x20, 0x8f, 0xe2, /* adr r2, .Lstr_preamble */
244 /* ; Skip preamble data section */
245 0x03, 0x00, 0x00, 0xea, /* b .Lloop_preamble */
247 /* ; Preamble string */
248 /* .Lstr_preamble: */
249 0x24, 0x62, 0x61, 0x75, /* .asciz "$baudratechange" */
250 0x64, 0x72, 0x61, 0x74,
251 0x65, 0x63, 0x68, 0x61,
252 0x6e, 0x67, 0x65, 0x00,
254 /* ; Send preamble string over UART */
255 /* .Lloop_preamble: */
257 /* ; Wait until Transmitter Holding is Empty */
259 /* ; r1 = UART_BASE[LSR] & THRE */
260 0x14, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x14] */
261 0x20, 0x00, 0x11, 0xe3, /* tst r1, #0x20 */
262 0xfc, 0xff, 0xff, 0x0a, /* beq .Lloop_thre */
264 /* ; Put character into Transmitter FIFO */
266 0x01, 0x10, 0xd2, 0xe4, /* ldrb r1, [r2], #1 */
267 /* ; UART_BASE[THR] = r1 */
268 0x00, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0] */
270 /* ; Loop until end of preamble string */
271 0x00, 0x00, 0x51, 0xe3, /* cmp r1, #0 */
272 0xf8, 0xff, 0xff, 0x1a, /* bne .Lloop_preamble */
275 /* ARM code for returning from binary header back to BootROM */
276 static unsigned char kwboot_baud_code_binhdr_post[] = {
277 /* ; Return 0 - no error */
278 0x00, 0x00, 0xa0, 0xe3, /* mov r0, #0 */
279 0xfe, 0x9f, 0xbd, 0xe8, /* pop { r1 - r12, pc } */
282 /* ARM code for jumping to the original image exec_addr */
283 static unsigned char kwboot_baud_code_data_jump[] = {
284 0x04, 0xf0, 0x1f, 0xe5, /* ldr pc, exec_addr */
285 /* ; Placeholder for exec_addr */
287 0x00, 0x00, 0x00, 0x00, /* .word 0 */
290 static const char kwb_baud_magic[16] = "$baudratechange";
292 static int kwboot_verbose;
294 static int msg_rsp_timeo = KWBOOT_MSG_RSP_TIMEO;
295 static int blk_rsp_timeo = KWBOOT_BLK_RSP_TIMEO;
298 kwboot_write(int fd, const char *buf, size_t len)
303 ssize_t wr = write(fd, buf + tot, len - tot);
305 if (wr < 0 && errno == EINTR)
317 kwboot_printv(const char *fmt, ...)
321 if (kwboot_verbose) {
332 const char seq[] = { '-', '\\', '|', '/' };
334 static int state, bs;
336 if (state % div == 0) {
338 fputc(seq[state / div % sizeof(seq)], stdout);
354 __progress(int pct, char c)
356 const int width = 70;
357 static const char *nl = "";
360 if (pos % width == 0)
361 printf("%s%3d %% [", nl, pct);
366 pos = (pos + 1) % width;
369 while (pos && pos++ < width)
381 kwboot_progress(int _pct, char c)
396 kwboot_tty_recv(int fd, void *buf, size_t len, int timeo)
409 tv.tv_usec = timeo * 1000;
410 if (tv.tv_usec > 1000000) {
411 tv.tv_sec += tv.tv_usec / 1000000;
412 tv.tv_usec %= 1000000;
416 nfds = select(fd + 1, &rfds, NULL, NULL, &tv);
417 if (nfds < 0 && errno == EINTR)
426 n = read(fd, buf, len);
427 if (n < 0 && errno == EINTR)
432 buf = (char *)buf + n;
442 kwboot_tty_send(int fd, const void *buf, size_t len, int nodrain)
447 if (kwboot_write(fd, buf, len) < 0)
457 kwboot_tty_send_char(int fd, unsigned char c)
459 return kwboot_tty_send(fd, &c, 1, 0);
463 kwboot_tty_baudrate_to_speed(int baudrate)
612 _is_within_tolerance(int value, int reference, int tolerance)
614 return 100 * value >= reference * (100 - tolerance) &&
615 100 * value <= reference * (100 + tolerance);
619 kwboot_tty_change_baudrate(int fd, int baudrate)
625 rc = tcgetattr(fd, &tio);
629 speed = kwboot_tty_baudrate_to_speed(baudrate);
637 tio.c_ospeed = tio.c_ispeed = baudrate;
640 rc = cfsetospeed(&tio, speed);
644 rc = cfsetispeed(&tio, speed);
648 rc = tcsetattr(fd, TCSANOW, &tio);
652 rc = tcgetattr(fd, &tio);
656 if (cfgetospeed(&tio) != speed || cfgetispeed(&tio) != speed)
661 * Check whether set baudrate is within 3% tolerance.
662 * If BOTHER is defined, Linux always fills out c_ospeed / c_ispeed
665 if (!_is_within_tolerance(tio.c_ospeed, baudrate, 3))
668 if (!_is_within_tolerance(tio.c_ispeed, baudrate, 3))
675 fprintf(stderr, "Could not set baudrate to requested value\n");
681 kwboot_open_tty(const char *path, int baudrate)
688 fd = open(path, O_RDWR | O_NOCTTY | O_NDELAY);
692 rc = tcgetattr(fd, &tio);
697 tio.c_cflag |= CREAD | CLOCAL;
698 tio.c_cflag &= ~(CSTOPB | HUPCL | CRTSCTS);
702 rc = tcsetattr(fd, TCSANOW, &tio);
706 flags = fcntl(fd, F_GETFL);
710 rc = fcntl(fd, F_SETFL, flags & ~O_NDELAY);
714 rc = kwboot_tty_change_baudrate(fd, baudrate);
729 kwboot_msg_write_handler(void *arg)
731 int tty = *(int *)((void **)arg)[0];
732 const void *msg = ((void **)arg)[1];
733 int rsp_timeo = msg_rsp_timeo;
734 int i, dummy_oldtype;
736 /* allow to cancel this thread at any time */
737 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &dummy_oldtype);
740 /* write 128 samples of message pattern into the output queue without waiting */
741 for (i = 0; i < 128; i++) {
742 if (kwboot_tty_send(tty, msg, 8, 1) < 0) {
743 perror("\nFailed to send message pattern");
747 /* wait until output queue is transmitted and then make pause */
748 if (tcdrain(tty) < 0) {
749 perror("\nFailed to send message pattern");
752 /* BootROM requires pause on UART after it detects message pattern */
753 usleep(rsp_timeo * 1000);
758 kwboot_msg_start_thread(pthread_t *thread, int *tty, void *msg)
765 rc = pthread_create(thread, NULL, kwboot_msg_write_handler, arg);
775 kwboot_msg_stop_thread(pthread_t thread)
779 rc = pthread_cancel(thread);
785 rc = pthread_join(thread, NULL);
795 kwboot_bootmsg(int tty)
797 struct kwboot_block block;
798 pthread_t write_thread;
802 /* flush input and output queue */
803 tcflush(tty, TCIOFLUSH);
805 rc = kwboot_msg_start_thread(&write_thread, &tty, kwboot_msg_boot);
807 perror("Failed to start write thread");
811 kwboot_printv("Sending boot message. Please reboot the target...");
817 rc = kwboot_tty_recv(tty, &c, 1, msg_rsp_timeo);
818 if (rc && errno == ETIMEDOUT) {
831 rc = kwboot_msg_stop_thread(write_thread);
833 perror("Failed to stop write thread");
839 perror("Failed to read response for boot message pattern");
844 * At this stage we have sent more boot message patterns and BootROM
845 * (at least on Armada XP and 385) started interpreting sent bytes as
846 * part of xmodem packets. If BootROM is expecting SOH byte as start of
847 * a xmodem packet and it receives byte 0xff, then it throws it away and
848 * sends a NAK reply to host. If BootROM does not receive any byte for
849 * 2s when expecting some continuation of the xmodem packet, it throws
850 * away the partially received xmodem data and sends NAK reply to host.
852 * Therefore for starting xmodem transfer we have two options: Either
853 * wait 2s or send 132 0xff bytes (which is the size of xmodem packet)
854 * to ensure that BootROM throws away any partially received data.
857 /* flush output queue with remaining boot message patterns */
858 rc = tcflush(tty, TCOFLUSH);
860 perror("Failed to flush output queue");
864 /* send one xmodem packet with 0xff bytes to force BootROM to re-sync */
865 memset(&block, 0xff, sizeof(block));
866 rc = kwboot_tty_send(tty, &block, sizeof(block), 0);
868 perror("Failed to send sync sequence");
873 * Sending 132 bytes via 115200B/8-N-1 takes 11.45 ms, reading 132 bytes
874 * takes 11.45 ms, so waiting for 30 ms should be enough.
878 /* flush remaining NAK replies from input queue */
879 rc = tcflush(tty, TCIFLUSH);
881 perror("Failed to flush input queue");
889 kwboot_debugmsg(int tty)
891 unsigned char buf[8192];
892 pthread_t write_thread;
896 /* flush input and output queue */
897 tcflush(tty, TCIOFLUSH);
899 rc = kwboot_msg_start_thread(&write_thread, &tty, kwboot_msg_debug);
901 perror("Failed to start write thread");
905 kwboot_printv("Sending debug message. Please reboot the target...");
911 /* Read immediately all bytes in queue without waiting */
912 rc = read(tty, buf + off, sizeof(buf) - off);
913 if ((rc < 0 && errno == EINTR) || rc == 0) {
924 * Check if we received at least 4 debug message patterns
925 * (console echo from BootROM) in cyclic buffer
928 for (pos = 0; pos < sizeof(kwboot_msg_debug); pos++)
929 if (buf[off] == kwboot_msg_debug[(pos + off) % sizeof(kwboot_msg_debug)])
932 for (i = off; i >= 0; i--)
933 if (buf[i] != kwboot_msg_debug[(pos + i) % sizeof(kwboot_msg_debug)])
938 if (off >= 4 * sizeof(kwboot_msg_debug))
941 /* If not move valid suffix from end of the buffer to the beginning of buffer */
942 memmove(buf, buf + i + 1, off);
947 rc = kwboot_msg_stop_thread(write_thread);
949 perror("Failed to stop write thread");
955 perror("Failed to read response for debug message pattern");
959 /* flush output queue with remaining debug message patterns */
960 rc = tcflush(tty, TCOFLUSH);
962 perror("Failed to flush output queue");
966 kwboot_printv("Clearing input buffer...\n");
969 * Wait until BootROM transmit all remaining echo characters.
970 * Experimentally it was measured that for Armada 385 BootROM
971 * it is required to wait at least 0.415s. So wait 0.5s.
976 * In off variable is stored number of characters received after the
977 * successful detection of echo reply. So these characters are console
978 * echo for other following debug message patterns. BootROM may have in
979 * its output queue other echo characters which were being transmitting
980 * before above sleep call. So read remaining number of echo characters
981 * sent by the BootROM now.
983 while ((rc = kwboot_tty_recv(tty, &buf[0], 1, 0)) == 0)
985 if (errno != ETIMEDOUT) {
986 perror("Failed to read response");
991 * Clear every echo character set by the BootROM by backspace byte.
992 * This is required prior writing any command to the BootROM debug
993 * because BootROM command line buffer has limited size. If length
994 * of the command is larger than buffer size then it looks like
995 * that Armada 385 BootROM crashes after sending ENTER. So erase it.
996 * Experimentally it was measured that for Armada 385 BootROM it is
997 * required to send at least 3 backspace bytes for one echo character.
998 * This is unknown why. But lets do it.
1001 memset(buf, '\x08', sizeof(buf));
1002 while (off > sizeof(buf)) {
1003 rc = kwboot_tty_send(tty, buf, sizeof(buf), 1);
1005 perror("Failed to send clear sequence");
1010 rc = kwboot_tty_send(tty, buf, off, 0);
1012 perror("Failed to send clear sequence");
1016 usleep(msg_rsp_timeo * 1000);
1017 rc = tcflush(tty, TCIFLUSH);
1019 perror("Failed to flush input queue");
1027 kwboot_xm_makeblock(struct kwboot_block *block, const void *data,
1028 size_t size, int pnum)
1034 block->_pnum = ~block->pnum;
1036 n = size < KWBOOT_XM_BLKSZ ? size : KWBOOT_XM_BLKSZ;
1037 memcpy(&block->data[0], data, n);
1038 memset(&block->data[n], 0, KWBOOT_XM_BLKSZ - n);
1041 for (i = 0; i < n; i++)
1042 block->csum += block->data[i];
1052 if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
1053 static int err_print;
1056 perror("clock_gettime() does not work");
1060 /* this will just make the timeout not work */
1064 return ts.tv_sec * 1000ULL + (ts.tv_nsec + 500000) / 1000000;
1068 _is_xm_reply(char c)
1070 return c == ACK || c == NAK;
1074 _xm_reply_to_error(int c)
1094 kwboot_baud_magic_handle(int fd, char c, int baudrate)
1096 static size_t rcv_len;
1098 if (rcv_len < sizeof(kwb_baud_magic)) {
1099 /* try to recognize whole magic word */
1100 if (c == kwb_baud_magic[rcv_len]) {
1103 printf("%.*s%c", (int)rcv_len, kwb_baud_magic, c);
1109 if (rcv_len == sizeof(kwb_baud_magic)) {
1110 /* magic word received */
1111 kwboot_printv("\nChanging baudrate to %d Bd\n", baudrate);
1113 return kwboot_tty_change_baudrate(fd, baudrate) ? : 1;
1120 kwboot_xm_recv_reply(int fd, char *c, int stop_on_non_xm,
1121 int ignore_nak_reply,
1122 int allow_non_xm, int *non_xm_print,
1123 int baudrate, int *baud_changed)
1125 int timeout = allow_non_xm ? KWBOOT_HDR_RSP_TIMEO : blk_rsp_timeo;
1126 uint64_t recv_until = _now() + timeout;
1130 rc = kwboot_tty_recv(fd, c, 1, timeout);
1132 if (errno != ETIMEDOUT)
1134 else if (allow_non_xm && *non_xm_print)
1140 /* If received xmodem reply, end. */
1141 if (_is_xm_reply(*c)) {
1142 if (*c == NAK && ignore_nak_reply) {
1143 timeout = recv_until - _now();
1151 * If receiving/printing non-xmodem text output is allowed and
1152 * such a byte was received, we want to increase receiving time
1154 * - print the byte, if it is not part of baudrate change magic
1155 * sequence while baudrate change was requested (-B option)
1157 * Otherwise decrease timeout by time elapsed.
1160 recv_until = _now() + timeout;
1162 if (baudrate && !*baud_changed) {
1163 rc = kwboot_baud_magic_handle(fd, *c, baudrate);
1170 } else if (!baudrate || !*baud_changed) {
1178 timeout = recv_until - _now();
1190 kwboot_xm_sendblock(int fd, struct kwboot_block *block, int allow_non_xm,
1191 int *done_print, int baudrate, int allow_retries)
1193 int non_xm_print, baud_changed;
1194 int rc, err, retries;
1203 rc = kwboot_tty_send(fd, block, sizeof(*block), 1);
1207 if (allow_non_xm && !*done_print) {
1208 kwboot_progress(100, '.');
1209 kwboot_printv("Done\n");
1213 rc = kwboot_xm_recv_reply(fd, &c, retries < 3,
1215 allow_non_xm, &non_xm_print,
1216 baudrate, &baud_changed);
1220 if (!allow_non_xm && c != ACK) {
1221 if (c == NAK && allow_retries && retries + 1 < 16)
1222 kwboot_progress(-1, '+');
1224 kwboot_progress(-1, 'E');
1226 } while (c == NAK && allow_retries && retries++ < 16);
1229 kwboot_printv("\n");
1231 if (allow_non_xm && baudrate && !baud_changed) {
1232 fprintf(stderr, "Baudrate was not changed\n");
1237 return _xm_reply_to_error(c);
1240 kwboot_printv("\n");
1246 kwboot_xm_finish(int fd)
1251 kwboot_printv("Finishing transfer\n");
1255 rc = kwboot_tty_send_char(fd, EOT);
1259 rc = kwboot_xm_recv_reply(fd, &c, retries < 3,
1264 } while (c == NAK && retries++ < 16);
1266 return _xm_reply_to_error(c);
1270 kwboot_xmodem_one(int tty, int *pnum, int header, const uint8_t *data,
1271 size_t size, int baudrate)
1277 kwboot_printv("Sending boot image %s (%zu bytes)...\n",
1278 header ? "header" : "data", size);
1283 while (sent < size) {
1284 struct kwboot_block block;
1288 blksz = kwboot_xm_makeblock(&block, data, left, (*pnum)++);
1291 last_block = (left <= blksz);
1294 * Handling of repeated xmodem packets is completely broken in
1295 * Armada 385 BootROM - it completely ignores xmodem packet
1296 * numbers, they are only used for checksum verification.
1297 * BootROM can handle a retry of the xmodem packet only during
1298 * the transmission of kwbimage header and only if BootROM
1299 * itself sent NAK response to previous attempt (it does it on
1300 * checksum failure). During the transmission of kwbimage data
1301 * part, BootROM always expects next xmodem packet, even if it
1302 * sent NAK to previous attempt - there is absolutely no way to
1303 * repair incorrectly transmitted xmodem packet during kwbimage
1304 * data part upload. Also, if kwboot receives non-ACK/NAK
1305 * response (meaning that original BootROM response was damaged
1306 * on UART) there is no way to detect if BootROM accepted xmodem
1307 * packet or not and no way to check if kwboot could repeat the
1310 * Stop transfer and return failure if kwboot receives unknown
1311 * reply if non-xmodem reply is not allowed (for all xmodem
1312 * packets except the last header packet) or when non-ACK reply
1313 * is received during data part transfer.
1315 rc = kwboot_xm_sendblock(tty, &block, header && last_block,
1316 &done_print, baudrate, header);
1324 kwboot_progress(sent * 100 / size, '.');
1328 kwboot_printv("Done\n");
1332 kwboot_printv("\n");
1337 kwboot_xmodem(int tty, const void *_img, size_t size, int baudrate)
1339 const uint8_t *img = _img;
1343 hdrsz = kwbheader_size(img);
1346 * If header size is not aligned to xmodem block size (which applies
1347 * for all images in kwbimage v0 format) then we have to ensure that
1348 * the last xmodem block of header contains beginning of the data
1349 * followed by the header. So align header size to xmodem block size.
1351 hdrsz += (KWBOOT_XM_BLKSZ - hdrsz % KWBOOT_XM_BLKSZ) % KWBOOT_XM_BLKSZ;
1355 rc = kwboot_xmodem_one(tty, &pnum, 1, img, hdrsz, baudrate);
1360 * If we have already sent image data as a part of the last
1361 * xmodem header block then we have nothing more to send.
1366 rc = kwboot_xmodem_one(tty, &pnum, 0, img, size, 0);
1371 rc = kwboot_xm_finish(tty);
1376 kwboot_printv("\nChanging baudrate back to 115200 Bd\n\n");
1377 rc = kwboot_tty_change_baudrate(tty, 115200);
1386 kwboot_term_pipe(int in, int out, const char *quit, int *s, const char *kbs, int *k)
1391 nin = read(in, buf, sizeof(buf));
1400 for (i = 0; i < nin; i++) {
1401 if ((quit || kbs) &&
1402 (!quit || buf[i] != quit[*s]) &&
1403 (!kbs || buf[i] != kbs[*k])) {
1408 prefix = (*s >= *k) ? quit : kbs;
1409 plen = (*s >= *k) ? *s : *k;
1418 if (plen > i && kwboot_write(out, prefix, plen - i) < 0)
1422 if (quit && buf[i] == quit[*s]) {
1425 nin = (i > *s) ? (i - *s) : 0;
1432 if (kbs && buf[i] == kbs[*k]) {
1435 if (i > *k + noff &&
1436 kwboot_write(out, buf + noff, i - *k - noff) < 0)
1439 * Replace backspace key by '\b' (0x08)
1440 * byte which is the only recognized
1441 * backspace byte by Marvell BootROM.
1443 if (write(out, "\x08", 1) < 0)
1459 nin -= (nin > i) ? i : nin;
1463 if (nin > noff && kwboot_write(out, buf + noff, nin - noff) < 0)
1470 kwboot_terminal(int tty)
1473 const char *kbs = NULL;
1474 const char *quit = "\34c";
1475 struct termios otio, tio;
1481 rc = tcgetattr(in, &otio);
1485 rc = tcsetattr(in, TCSANOW, &tio);
1488 perror("tcsetattr");
1493 * Get sequence for backspace key used by the current
1494 * terminal. Every occurrence of this sequence will be
1495 * replaced by '\b' byte which is the only recognized
1496 * backspace byte by Marvell BootROM.
1498 * Note that we cannot read this sequence from termios
1499 * c_cc[VERASE] as VERASE is valid only when ICANON is
1500 * set in termios c_lflag, which is not case for us.
1502 * Also most terminals do not set termios c_cc[VERASE]
1503 * as c_cc[VERASE] can specify only one-byte sequence
1504 * and instead let applications to read (possible
1505 * multi-byte) sequence for backspace key from "kbs"
1506 * terminfo database based on $TERM env variable.
1508 * So read "kbs" from terminfo database via tigetstr()
1509 * call after successful setupterm(). Most terminals
1510 * use byte 0x7F for backspace key, so replacement with
1513 if (setupterm(NULL, STDOUT_FILENO, &rc) == 0) {
1514 kbs = tigetstr("kbs");
1515 if (kbs == (char *)-1)
1519 kwboot_printv("[Type Ctrl-%c + %c to quit]\r\n",
1520 quit[0] | 0100, quit[1]);
1534 nfds = nfds < tty ? tty : nfds;
1538 nfds = nfds < in ? in : nfds;
1541 nfds = select(nfds + 1, &rfds, NULL, NULL, NULL);
1545 if (FD_ISSET(tty, &rfds)) {
1546 rc = kwboot_term_pipe(tty, STDOUT_FILENO, NULL, NULL, NULL, NULL);
1551 if (in >= 0 && FD_ISSET(in, &rfds)) {
1552 rc = kwboot_term_pipe(in, tty, quit, &s, kbs, &k);
1556 } while (quit[s] != 0);
1559 tcsetattr(in, TCSANOW, &otio);
1566 kwboot_read_image(const char *path, size_t *size, size_t reserve)
1576 fd = open(path, O_RDONLY);
1580 rc = fstat(fd, &st);
1584 img = malloc(st.st_size + reserve);
1589 while (tot < st.st_size) {
1590 ssize_t rd = read(fd, img + tot, st.st_size - tot);
1597 if (!rd && tot < st.st_size) {
1617 kwboot_hdr_csum8(const void *hdr)
1619 const uint8_t *data = hdr;
1623 size = kwbheader_size_for_csum(hdr);
1625 for (csum = 0; size-- > 0; data++)
1632 kwboot_img_csum32_ptr(void *img)
1634 struct main_hdr_v1 *hdr = img;
1637 datasz = le32_to_cpu(hdr->blocksize) - sizeof(uint32_t);
1639 return img + le32_to_cpu(hdr->srcaddr) + datasz;
1643 kwboot_img_csum32(const void *img)
1645 const struct main_hdr_v1 *hdr = img;
1646 uint32_t datasz, csum = 0;
1647 const uint32_t *data;
1649 datasz = le32_to_cpu(hdr->blocksize) - sizeof(csum);
1650 if (datasz % sizeof(uint32_t))
1653 data = img + le32_to_cpu(hdr->srcaddr);
1654 while (datasz > 0) {
1655 csum += le32_to_cpu(*data++);
1659 return cpu_to_le32(csum);
1663 kwboot_img_is_secure(void *img)
1665 struct opt_hdr_v1 *ohdr;
1667 for_each_opt_hdr_v1 (ohdr, img)
1668 if (ohdr->headertype == OPT_HDR_V1_SECURE_TYPE)
1675 kwboot_img_grow_data_right(void *img, size_t *size, size_t grow)
1677 struct main_hdr_v1 *hdr = img;
1681 * 32-bit checksum comes after end of image code, so we will be putting
1682 * new code there. So we get this pointer and then increase data size
1683 * (since increasing data size changes kwboot_img_csum32_ptr() return
1686 result = kwboot_img_csum32_ptr(img);
1687 hdr->blocksize = cpu_to_le32(le32_to_cpu(hdr->blocksize) + grow);
1694 kwboot_img_grow_hdr(void *img, size_t *size, size_t grow)
1696 uint32_t hdrsz, datasz, srcaddr;
1697 struct main_hdr_v1 *hdr = img;
1698 struct opt_hdr_v1 *ohdr;
1701 srcaddr = le32_to_cpu(hdr->srcaddr);
1703 /* calculate real used space in kwbimage header */
1704 if (kwbimage_version(img) == 0) {
1705 hdrsz = kwbheader_size(img);
1707 hdrsz = sizeof(*hdr);
1708 for_each_opt_hdr_v1 (ohdr, hdr)
1709 hdrsz += opt_hdr_v1_size(ohdr);
1712 data = (uint8_t *)img + srcaddr;
1713 datasz = *size - srcaddr;
1715 /* only move data if there is not enough space */
1716 if (hdrsz + grow > srcaddr) {
1717 size_t need = hdrsz + grow - srcaddr;
1719 /* move data by enough bytes */
1720 memmove(data + need, data, datasz);
1722 hdr->srcaddr = cpu_to_le32(srcaddr + need);
1726 if (kwbimage_version(img) == 1) {
1728 if (hdrsz > kwbheader_size(img)) {
1729 hdr->headersz_msb = hdrsz >> 16;
1730 hdr->headersz_lsb = cpu_to_le16(hdrsz & 0xffff);
1736 kwboot_add_bin_ohdr_v1(void *img, size_t *size, uint32_t binsz)
1738 struct main_hdr_v1 *hdr = img;
1739 struct opt_hdr_v1 *ohdr;
1746 for_each_opt_hdr_v1 (ohdr, img)
1747 if (opt_hdr_v1_next(ohdr) == NULL)
1750 prev_ext = opt_hdr_v1_ext(ohdr);
1751 ohdr = _opt_hdr_v1_next(ohdr);
1753 ohdr = (void *)(hdr + 1);
1754 prev_ext = &hdr->ext;
1758 * ARM executable code inside the BIN header on some mvebu platforms
1759 * (e.g. A370, AXP) must always be aligned with the 128-bit boundary.
1760 * This requirement can be met by inserting dummy arguments into
1761 * BIN header, if needed.
1763 offset = &ohdr->data[4] - (char *)img;
1764 num_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
1766 ohdrsz = sizeof(*ohdr) + 4 + 4 * num_args + binsz + 4;
1767 kwboot_img_grow_hdr(hdr, size, ohdrsz);
1771 ohdr->headertype = OPT_HDR_V1_BINARY_TYPE;
1772 ohdr->headersz_msb = ohdrsz >> 16;
1773 ohdr->headersz_lsb = cpu_to_le16(ohdrsz & 0xffff);
1775 memset(&ohdr->data[0], 0, ohdrsz - sizeof(*ohdr));
1776 *(uint32_t *)&ohdr->data[0] = cpu_to_le32(num_args);
1778 return &ohdr->data[4 + 4 * num_args];
1782 _inject_baudrate_change_code(void *img, size_t *size, int for_data,
1783 int old_baud, int new_baud)
1785 struct main_hdr_v1 *hdr = img;
1786 uint32_t orig_datasz;
1791 orig_datasz = le32_to_cpu(hdr->blocksize) - sizeof(uint32_t);
1793 codesz = sizeof(kwboot_baud_code) +
1794 sizeof(kwboot_baud_code_data_jump);
1795 code = kwboot_img_grow_data_right(img, size, codesz);
1797 codesz = sizeof(kwboot_baud_code_binhdr_pre) +
1798 sizeof(kwboot_baud_code) +
1799 sizeof(kwboot_baud_code_binhdr_post);
1800 code = kwboot_add_bin_ohdr_v1(img, size, codesz);
1802 codesz = sizeof(kwboot_baud_code_binhdr_pre);
1803 memcpy(code, kwboot_baud_code_binhdr_pre, codesz);
1807 codesz = sizeof(kwboot_baud_code) - 2 * sizeof(uint32_t);
1808 memcpy(code, kwboot_baud_code, codesz);
1810 *(uint32_t *)code = cpu_to_le32(old_baud);
1811 code += sizeof(uint32_t);
1812 *(uint32_t *)code = cpu_to_le32(new_baud);
1813 code += sizeof(uint32_t);
1816 codesz = sizeof(kwboot_baud_code_data_jump) - sizeof(uint32_t);
1817 memcpy(code, kwboot_baud_code_data_jump, codesz);
1819 *(uint32_t *)code = hdr->execaddr;
1820 code += sizeof(uint32_t);
1821 hdr->execaddr = cpu_to_le32(le32_to_cpu(hdr->destaddr) + orig_datasz);
1823 codesz = sizeof(kwboot_baud_code_binhdr_post);
1824 memcpy(code, kwboot_baud_code_binhdr_post, codesz);
1830 kwboot_img_patch(void *img, size_t *size, int baudrate)
1832 struct main_hdr_v1 *hdr;
1841 if (*size < sizeof(struct main_hdr_v1))
1844 image_ver = kwbimage_version(img);
1845 if (image_ver != 0 && image_ver != 1) {
1846 fprintf(stderr, "Invalid image header version\n");
1850 hdrsz = kwbheader_size(hdr);
1855 csum = kwboot_hdr_csum8(hdr) - hdr->checksum;
1856 if (csum != hdr->checksum)
1859 srcaddr = le32_to_cpu(hdr->srcaddr);
1861 switch (hdr->blockid) {
1862 case IBR_HDR_SATA_ID:
1866 hdr->srcaddr = cpu_to_le32((srcaddr - 1) * 512);
1869 case IBR_HDR_SDIO_ID:
1870 hdr->srcaddr = cpu_to_le32(srcaddr * 512);
1873 case IBR_HDR_PEX_ID:
1874 if (srcaddr == 0xFFFFFFFF)
1875 hdr->srcaddr = cpu_to_le32(hdrsz);
1878 case IBR_HDR_SPI_ID:
1879 if (hdr->destaddr == cpu_to_le32(0xFFFFFFFF)) {
1880 kwboot_printv("Patching destination and execution addresses from SPI/NOR XIP area to DDR area 0x00800000\n");
1881 hdr->destaddr = cpu_to_le32(0x00800000);
1882 hdr->execaddr = cpu_to_le32(0x00800000);
1887 if (hdrsz > le32_to_cpu(hdr->srcaddr) ||
1888 *size < le32_to_cpu(hdr->srcaddr) + le32_to_cpu(hdr->blocksize))
1891 if (kwboot_img_csum32(img) != *kwboot_img_csum32_ptr(img))
1894 is_secure = kwboot_img_is_secure(img);
1896 if (hdr->blockid != IBR_HDR_UART_ID) {
1899 "Image has secure header with signature for non-UART booting\n");
1903 kwboot_printv("Patching image boot signature to UART\n");
1904 hdr->blockid = IBR_HDR_UART_ID;
1908 if (image_ver == 1) {
1910 * Tell BootROM to send BootROM messages to UART port
1911 * number 0 (used also for UART booting) with default
1912 * baudrate (which should be 115200) and do not touch
1913 * UART MPP configuration.
1916 hdr->options &= ~0x1F;
1917 hdr->options |= MAIN_HDR_V1_OPT_BAUD_DEFAULT;
1918 hdr->options |= 0 << 3;
1921 ((struct main_hdr_v0 *)img)->nandeccmode = IBR_HDR_ECC_DISABLED;
1922 hdr->nandpagesize = 0;
1926 if (image_ver == 0) {
1928 "Cannot inject code for changing baudrate into v0 image header\n");
1934 "Cannot inject code for changing baudrate into image with secure header\n");
1939 * First inject code that changes the baudrate from the default
1940 * value of 115200 Bd to requested value. This code is inserted
1941 * as a new opt hdr, so it is executed by BootROM after the
1942 * header part is received.
1944 kwboot_printv("Injecting binary header code for changing baudrate to %d Bd\n",
1946 _inject_baudrate_change_code(img, size, 0, 115200, baudrate);
1949 * Now inject code that changes the baudrate back to 115200 Bd.
1950 * This code is appended after the data part of the image, and
1951 * execaddr is changed so that it is executed before U-Boot
1954 kwboot_printv("Injecting code for changing baudrate back\n");
1955 _inject_baudrate_change_code(img, size, 1, baudrate, 115200);
1957 /* Update the 32-bit data checksum */
1958 *kwboot_img_csum32_ptr(img) = kwboot_img_csum32(img);
1960 /* recompute header size */
1961 hdrsz = kwbheader_size(hdr);
1964 if (hdrsz % KWBOOT_XM_BLKSZ) {
1965 size_t grow = KWBOOT_XM_BLKSZ - hdrsz % KWBOOT_XM_BLKSZ;
1968 fprintf(stderr, "Cannot align image with secure header\n");
1972 kwboot_printv("Aligning image header to Xmodem block size\n");
1973 kwboot_img_grow_hdr(img, size, grow);
1976 hdr->checksum = kwboot_hdr_csum8(hdr) - csum;
1978 *size = le32_to_cpu(hdr->srcaddr) + le32_to_cpu(hdr->blocksize);
1986 kwboot_usage(FILE *stream, char *progname)
1989 "Usage: %s [OPTIONS] [-b <image> | -D <image> ] [-B <baud> ] <TTY>\n",
1991 fprintf(stream, "\n");
1993 " -b <image>: boot <image> with preamble (Kirkwood, Armada 370/XP)\n");
1995 " -D <image>: boot <image> without preamble (Dove)\n");
1996 fprintf(stream, " -d: enter debug mode\n");
1997 fprintf(stream, " -a: use timings for Armada XP\n");
1998 fprintf(stream, " -s <resp-timeo>: use specific response-timeout\n");
2000 " -o <block-timeo>: use specific xmodem block timeout\n");
2001 fprintf(stream, "\n");
2002 fprintf(stream, " -t: mini terminal\n");
2003 fprintf(stream, "\n");
2004 fprintf(stream, " -B <baud>: set baud rate\n");
2005 fprintf(stream, "\n");
2009 main(int argc, char **argv)
2011 const char *ttypath, *imgpath;
2012 int rv, rc, tty, term;
2017 size_t after_img_rsv;
2030 after_img_rsv = KWBOOT_XM_BLKSZ;
2033 printf("kwboot version %s\n", PLAIN_VERSION);
2035 kwboot_verbose = isatty(STDOUT_FILENO);
2038 prev_optind = optind;
2039 c = getopt(argc, argv, "hbptaB:dD:q:s:o:");
2045 if (imgpath || bootmsg || debugmsg)
2048 if (prev_optind == optind)
2050 if (optind < argc - 1 && argv[optind] && argv[optind][0] != '-')
2051 imgpath = argv[optind++];
2055 if (imgpath || bootmsg || debugmsg)
2062 if (imgpath || bootmsg || debugmsg)
2068 /* nop, for backward compatibility */
2076 msg_rsp_timeo = KWBOOT_MSG_RSP_TIMEO_AXP;
2080 /* nop, for backward compatibility */
2084 msg_rsp_timeo = atoi(optarg);
2088 blk_rsp_timeo = atoi(optarg);
2092 baudrate = atoi(optarg);
2102 if (!bootmsg && !term && !debugmsg && !imgpath)
2105 ttypath = argv[optind++];
2110 tty = kwboot_open_tty(ttypath, imgpath ? 115200 : baudrate);
2116 if (baudrate == 115200)
2117 /* do not change baudrate during Xmodem to the same value */
2120 /* ensure we have enough space for baudrate change code */
2121 after_img_rsv += sizeof(struct opt_hdr_v1) + 8 + 16 +
2122 sizeof(kwboot_baud_code_binhdr_pre) +
2123 sizeof(kwboot_baud_code) +
2124 sizeof(kwboot_baud_code_binhdr_post) +
2126 sizeof(kwboot_baud_code) +
2127 sizeof(kwboot_baud_code_data_jump) +
2131 img = kwboot_read_image(imgpath, &size, after_img_rsv);
2137 rc = kwboot_img_patch(img, &size, baudrate);
2139 fprintf(stderr, "%s: Invalid image.\n", imgpath);
2145 rc = kwboot_debugmsg(tty);
2148 } else if (bootmsg) {
2149 rc = kwboot_bootmsg(tty);
2155 rc = kwboot_xmodem(tty, img, size, baudrate);
2163 rc = kwboot_terminal(tty);
2164 if (rc && !(errno == EINTR)) {
2181 kwboot_usage(rv ? stderr : stdout, basename(argv[0]));