1 // SPDX-License-Identifier: eCos-2.0
3 *==========================================================================
7 * RedBoot stream handler for xyzModem protocol
9 *==========================================================================
10 *#####DESCRIPTIONBEGIN####
13 * Contributors: gthomas, tsmith, Yoshinori Sato
18 * This code is part of RedBoot (tm).
20 *####DESCRIPTIONEND####
22 *==========================================================================
27 #include <u-boot/crc.h>
32 /* Assumption - run xyzModem protocol over the console port */
34 /* Values magic to the protocol */
37 #define ETX 0x03 /* ^C for interrupt */
43 #define EOF 0x1A /* ^Z for DOS officionados */
45 /* Data & state local to the protocol */
49 unsigned char pkt[1024], *bufp;
50 unsigned char blk, cblk, crc1, crc2;
51 unsigned char next_blk; /* Expected block */
52 int len, mode, total_retries;
53 int total_SOH, total_STX, total_CAN;
54 bool crc_mode, at_eof, tx_ack;
55 bool first_xmodem_packet;
56 ulong initial_time, timeout;
57 unsigned long file_length, read_length;
60 #define xyzModem_CHAR_TIMEOUT 2000 /* 2 seconds */
61 #define xyzModem_MAX_RETRIES 20
62 #define xyzModem_MAX_RETRIES_WITH_CRC 10
63 #define xyzModem_CAN_COUNT 3 /* Wait for 3 CAN before quitting */
65 typedef int cyg_int32;
67 CYGACC_COMM_IF_GETC_TIMEOUT (char chan, char *c)
70 ulong now = get_timer(0);
74 if (get_timer(now) > xyzModem_CHAR_TIMEOUT)
86 CYGACC_COMM_IF_PUTC (char x, char y)
91 /* Validate a hex character */
92 __inline__ static bool
95 return (((c >= '0') && (c <= '9')) ||
96 ((c >= 'A') && (c <= 'F')) || ((c >= 'a') && (c <= 'f')));
99 /* Convert a single hex nibble */
100 __inline__ static int
105 if ((c >= '0') && (c <= '9'))
109 else if ((c >= 'a') && (c <= 'f'))
111 ret = (c - 'a' + 0x0a);
113 else if ((c >= 'A') && (c <= 'F'))
115 ret = (c - 'A' + 0x0A);
120 /* Convert a character to lower case */
121 __inline__ static char
124 if ((c >= 'A') && (c <= 'Z'))
131 /* Parse (scan) a number */
133 parse_num (char *s, unsigned long *val, char **es, char *delim)
138 unsigned long result = 0;
145 if (first && (s[0] == '0') && (_tolower (s[1]) == 'x'))
152 if (_is_hex (c) && ((digit = _from_hex (c)) < radix))
155 result = (result * radix) + digit;
159 if (delim != (char *) 0)
161 /* See if this character is one of the delimiters */
163 while (*dp && (c != *dp))
166 break; /* Found a good delimiter */
168 return false; /* Malformatted number */
172 if (es != (char **) 0)
179 #if defined(DEBUG) && !CONFIG_IS_ENABLED(USE_TINY_PRINTF)
181 * Note: this debug setup works by storing the strings in a fixed buffer
183 static char zm_debug_buf[8192];
184 static char *zm_out = zm_debug_buf;
185 static char *zm_out_start = zm_debug_buf;
188 zm_dprintf(char *fmt, ...)
194 len = diag_vsprintf(zm_out, fmt, args);
203 zm_out = zm_out_start;
207 zm_dump_buf (void *buf, int len)
212 static unsigned char zm_buf[2048];
213 static unsigned char *zm_bp;
222 zm_save (unsigned char c)
230 zm_dprintf ("Packet at line: %d\n", line);
231 zm_dump_buf (zm_buf, zm_bp - zm_buf);
234 #define ZM_DEBUG(x) x
239 /* Wait for the line to go idle */
241 xyzModem_flush (void)
247 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
254 xyzModem_get_hdr (void)
258 bool hdr_found = false;
259 int i, can_total, hdr_chars;
260 unsigned short cksum;
262 ZM_DEBUG (zm_new ());
263 /* Find the start of a header */
269 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
274 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
275 ZM_DEBUG (zm_save (c));
291 ZM_DEBUG (zm_dump (__LINE__));
292 if (++can_total == xyzModem_CAN_COUNT)
294 return xyzModem_cancel;
298 /* Wait for multiple CAN to avoid early quits */
302 /* EOT only supported if no noise */
305 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
306 ZM_DEBUG (zm_dprintf ("ACK on EOT #%d\n", __LINE__));
307 ZM_DEBUG (zm_dump (__LINE__));
311 /* Ignore, waiting for start of header */
317 /* Data stream timed out */
318 xyzModem_flush (); /* Toss any current input */
319 ZM_DEBUG (zm_dump (__LINE__));
320 CYGACC_CALL_IF_DELAY_US ((cyg_int32) 250000);
321 return xyzModem_timeout;
325 /* Header found, now read the data */
326 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.blk);
327 ZM_DEBUG (zm_save (xyz.blk));
330 ZM_DEBUG (zm_dump (__LINE__));
331 return xyzModem_timeout;
333 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.cblk);
334 ZM_DEBUG (zm_save (xyz.cblk));
337 ZM_DEBUG (zm_dump (__LINE__));
338 return xyzModem_timeout;
340 xyz.len = (c == SOH) ? 128 : 1024;
342 for (i = 0; i < xyz.len; i++)
344 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
345 ZM_DEBUG (zm_save (c));
352 ZM_DEBUG (zm_dump (__LINE__));
353 return xyzModem_timeout;
356 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.crc1);
357 ZM_DEBUG (zm_save (xyz.crc1));
360 ZM_DEBUG (zm_dump (__LINE__));
361 return xyzModem_timeout;
365 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.crc2);
366 ZM_DEBUG (zm_save (xyz.crc2));
369 ZM_DEBUG (zm_dump (__LINE__));
370 return xyzModem_timeout;
373 ZM_DEBUG (zm_dump (__LINE__));
374 /* Validate the message */
375 if ((xyz.blk ^ xyz.cblk) != (unsigned char) 0xFF)
378 ("Framing error - blk: %x/%x/%x\n", xyz.blk, xyz.cblk,
379 (xyz.blk ^ xyz.cblk)));
380 ZM_DEBUG (zm_dump_buf (xyz.pkt, xyz.len));
382 return xyzModem_frame;
384 /* Verify checksum/CRC */
387 cksum = crc16_ccitt(0, xyz.pkt, xyz.len);
388 if (cksum != ((xyz.crc1 << 8) | xyz.crc2))
390 ZM_DEBUG (zm_dprintf ("CRC error - recvd: %02x%02x, computed: %x\n",
391 xyz.crc1, xyz.crc2, cksum & 0xFFFF));
392 return xyzModem_cksum;
398 for (i = 0; i < xyz.len; i++)
402 if (xyz.crc1 != (cksum & 0xFF))
405 ("Checksum error - recvd: %x, computed: %x\n", xyz.crc1,
407 return xyzModem_cksum;
410 /* If we get here, the message passes [structural] muster */
416 xyzModem_get_initial_timeout (void)
418 /* timeout is in seconds, non-positive timeout value is infinity */
419 #if CONFIG_IS_ENABLED(ENV_SUPPORT)
420 const char *timeout_str = env_get("loadxy_timeout");
422 return 1000 * simple_strtol(timeout_str, NULL, 10);
424 return 1000 * CONFIG_CMD_LOADXY_TIMEOUT;
428 xyzModem_stream_open (connection_info_t * info, int *err)
431 int retries = xyzModem_MAX_RETRIES;
432 int crc_retries = xyzModem_MAX_RETRIES_WITH_CRC;
434 /* ZM_DEBUG(zm_out = zm_out_start); */
435 #ifdef xyzModem_zmodem
436 if (info->mode == xyzModem_zmodem)
438 *err = xyzModem_noZmodem;
450 xyz.mode = info->mode;
451 xyz.total_retries = 0;
457 xyz.first_xmodem_packet = false;
458 xyz.initial_time = get_timer(0);
459 xyz.timeout = xyzModem_get_initial_timeout();
461 CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
463 if (xyz.mode == xyzModem_xmodem)
465 /* X-modem doesn't have an information header - exit here */
466 xyz.first_xmodem_packet = true;
471 while (!(xyz.timeout && get_timer(xyz.initial_time) > xyz.timeout))
475 retries = xyzModem_MAX_RETRIES;
476 crc_retries = xyzModem_MAX_RETRIES_WITH_CRC;
479 stat = xyzModem_get_hdr ();
482 /* Y-modem file information header */
488 parse_num ((char *) xyz.bufp, &xyz.file_length, NULL, " ");
489 /* The rest of the file name data block quietly discarded */
496 else if (stat == xyzModem_timeout)
498 if (--crc_retries <= 0)
499 xyz.crc_mode = false;
500 CYGACC_CALL_IF_DELAY_US (5 * 100000); /* Extra delay for startup */
501 CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
503 ZM_DEBUG (zm_dprintf ("NAK (%d)\n", __LINE__));
505 if (stat == xyzModem_cancel)
511 ZM_DEBUG (zm_flush ());
516 xyzModem_stream_read (char *buf, int size, int *err)
518 int stat, total, len;
522 stat = xyzModem_cancel;
523 /* Try and get 'size' bytes into the buffer */
524 while (!xyz.at_eof && xyz.len >= 0 && (size > 0))
528 retries = xyzModem_MAX_RETRIES;
529 while (retries-- > 0)
531 if (xyz.first_xmodem_packet && xyz.timeout &&
532 get_timer(xyz.initial_time) > xyz.timeout)
534 *err = xyzModem_timeout;
539 stat = xyzModem_get_hdr ();
542 if (xyz.mode == xyzModem_xmodem && xyz.first_xmodem_packet)
543 xyz.first_xmodem_packet = false;
544 if (xyz.blk == xyz.next_blk)
548 ("ACK block %d (%d)\n", xyz.blk, __LINE__));
549 xyz.next_blk = (xyz.next_blk + 1) & 0xFF;
551 if (xyz.mode == xyzModem_xmodem || xyz.file_length == 0)
553 /* Data blocks can be padded with ^Z (EOF) characters */
554 /* This code tries to detect and remove them */
555 if ((xyz.bufp[xyz.len - 1] == EOF) &&
556 (xyz.bufp[xyz.len - 2] == EOF) &&
557 (xyz.bufp[xyz.len - 3] == EOF))
560 && (xyz.bufp[xyz.len - 1] == EOF))
568 * See if accumulated length exceeds that of the file.
569 * If so, reduce size (i.e., cut out pad bytes)
570 * Only do this for Y-modem (and Z-modem should it ever
571 * be supported since it can fall back to Y-modem mode).
573 if (xyz.mode != xyzModem_xmodem && 0 != xyz.file_length)
575 xyz.read_length += xyz.len;
576 if (xyz.read_length > xyz.file_length)
578 xyz.len -= (xyz.read_length - xyz.file_length);
583 else if (xyz.blk == ((xyz.next_blk - 1) & 0xFF))
585 /* Just re-ACK this so sender will get on with it */
586 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
587 continue; /* Need new header */
591 stat = xyzModem_sequence;
594 if (stat == xyzModem_cancel)
598 if (stat == xyzModem_eof)
600 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
601 ZM_DEBUG (zm_dprintf ("ACK (%d)\n", __LINE__));
602 if (xyz.mode == xyzModem_ymodem)
604 CYGACC_COMM_IF_PUTC (*xyz.__chan,
605 (xyz.crc_mode ? 'C' : NAK));
607 ZM_DEBUG (zm_dprintf ("Reading Final Header\n"));
608 stat = xyzModem_get_hdr ();
609 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
610 ZM_DEBUG (zm_dprintf ("FINAL ACK (%d)\n", __LINE__));
617 CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
619 ZM_DEBUG (zm_dprintf ("NAK (%d)\n", __LINE__));
621 if (stat < 0 && (!xyz.first_xmodem_packet || stat != xyzModem_timeout))
628 /* Don't "read" data from the EOF protocol package */
629 if (!xyz.at_eof && xyz.len > 0)
634 memcpy (buf, xyz.bufp, len);
646 xyzModem_stream_close (int *err)
649 ("xyzModem - %s mode, %d(SOH)/%d(STX)/%d(CAN) packets, %d retries\n",
650 xyz.crc_mode ? "CRC" : "Cksum", xyz.total_SOH, xyz.total_STX,
651 xyz.total_CAN, xyz.total_retries));
652 ZM_DEBUG (zm_flush ());
655 /* Need to be able to clean out the input buffer, so have to take the */
658 xyzModem_stream_terminate (bool abort, int (*getc) (void))
664 ZM_DEBUG (zm_dprintf ("!!!! TRANSFER ABORT !!!!\n"));
667 case xyzModem_xmodem:
668 case xyzModem_ymodem:
669 /* The X/YMODEM Spec seems to suggest that multiple CAN followed by an equal */
670 /* number of Backspaces is a friendly way to get the other end to abort. */
671 CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
672 CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
673 CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
674 CYGACC_COMM_IF_PUTC (*xyz.__chan, CAN);
675 CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
676 CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
677 CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
678 CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
679 /* Now consume the rest of what's waiting on the line. */
680 ZM_DEBUG (zm_dprintf ("Flushing serial line.\n"));
684 #ifdef xyzModem_zmodem
685 case xyzModem_zmodem:
686 /* Might support it some day I suppose. */
693 ZM_DEBUG (zm_dprintf ("Engaging cleanup mode...\n"));
695 * Consume any trailing crap left in the inbuffer from
696 * previous received blocks. Since very few files are an exact multiple
697 * of the transfer block size, there will almost always be some gunk here.
698 * If we don't eat it now, RedBoot will think the user typed it.
700 ZM_DEBUG (zm_dprintf ("Trailing gunk:\n"));
701 while ((c = (*getc) ()) > -1)
703 ZM_DEBUG (zm_dprintf ("\n"));
705 * Make a small delay to give terminal programs like minicom
706 * time to get control again after their file transfer program
709 CYGACC_CALL_IF_DELAY_US ((cyg_int32) 250000);
714 xyzModem_error (int err)
718 case xyzModem_access:
719 return "Can't access file";
721 case xyzModem_noZmodem:
722 return "Sorry, zModem not available yet";
724 case xyzModem_timeout:
728 return "End of file";
730 case xyzModem_cancel:
734 return "Invalid framing";
737 return "CRC/checksum error";
739 case xyzModem_sequence:
740 return "Block sequence error";
743 return "Unknown error";