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>
31 /* Assumption - run xyzModem protocol over the console port */
33 /* Values magic to the protocol */
36 #define ETX 0x03 /* ^C for interrupt */
42 #define EOF 0x1A /* ^Z for DOS officionados */
44 /* Data & state local to the protocol */
48 unsigned char pkt[1024], *bufp;
49 unsigned char blk, cblk, crc1, crc2;
50 unsigned char next_blk; /* Expected block */
51 int len, mode, total_retries;
52 int total_SOH, total_STX, total_CAN;
53 bool crc_mode, at_eof, tx_ack;
54 bool first_xmodem_packet;
55 ulong initial_time, timeout;
56 unsigned long file_length, read_length;
59 #define xyzModem_CHAR_TIMEOUT 2000 /* 2 seconds */
60 #define xyzModem_MAX_RETRIES 20
61 #define xyzModem_MAX_RETRIES_WITH_CRC 10
62 #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)
180 #if defined(DEBUG) && !CONFIG_IS_ENABLED(USE_TINY_PRINTF)
182 * Note: this debug setup works by storing the strings in a fixed buffer
184 static char zm_debug_buf[8192];
185 static char *zm_out = zm_debug_buf;
186 static char *zm_out_start = zm_debug_buf;
189 zm_dprintf(char *fmt, ...)
195 len = diag_vsprintf(zm_out, fmt, args);
204 zm_out = zm_out_start;
208 zm_dump_buf (void *buf, int len)
213 static unsigned char zm_buf[2048];
214 static unsigned char *zm_bp;
223 zm_save (unsigned char c)
231 zm_dprintf ("Packet at line: %d\n", line);
232 zm_dump_buf (zm_buf, zm_bp - zm_buf);
235 #define ZM_DEBUG(x) x
240 /* Wait for the line to go idle */
242 xyzModem_flush (void)
248 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
255 xyzModem_get_hdr (void)
259 bool hdr_found = false;
260 int i, can_total, hdr_chars;
261 unsigned short cksum;
263 ZM_DEBUG (zm_new ());
264 /* Find the start of a header */
270 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
275 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
276 ZM_DEBUG (zm_save (c));
292 ZM_DEBUG (zm_dump (__LINE__));
293 if (++can_total == xyzModem_CAN_COUNT)
295 return xyzModem_cancel;
299 /* Wait for multiple CAN to avoid early quits */
303 /* EOT only supported if no noise */
306 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
307 ZM_DEBUG (zm_dprintf ("ACK on EOT #%d\n", __LINE__));
308 ZM_DEBUG (zm_dump (__LINE__));
312 /* Ignore, waiting for start of header */
318 /* Data stream timed out */
319 xyzModem_flush (); /* Toss any current input */
320 ZM_DEBUG (zm_dump (__LINE__));
321 CYGACC_CALL_IF_DELAY_US ((cyg_int32) 250000);
322 return xyzModem_timeout;
326 /* Header found, now read the data */
327 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.blk);
328 ZM_DEBUG (zm_save (xyz.blk));
331 ZM_DEBUG (zm_dump (__LINE__));
332 return xyzModem_timeout;
334 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.cblk);
335 ZM_DEBUG (zm_save (xyz.cblk));
338 ZM_DEBUG (zm_dump (__LINE__));
339 return xyzModem_timeout;
341 xyz.len = (c == SOH) ? 128 : 1024;
343 for (i = 0; i < xyz.len; i++)
345 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, &c);
346 ZM_DEBUG (zm_save (c));
353 ZM_DEBUG (zm_dump (__LINE__));
354 return xyzModem_timeout;
357 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.crc1);
358 ZM_DEBUG (zm_save (xyz.crc1));
361 ZM_DEBUG (zm_dump (__LINE__));
362 return xyzModem_timeout;
366 res = CYGACC_COMM_IF_GETC_TIMEOUT (*xyz.__chan, (char *) &xyz.crc2);
367 ZM_DEBUG (zm_save (xyz.crc2));
370 ZM_DEBUG (zm_dump (__LINE__));
371 return xyzModem_timeout;
374 ZM_DEBUG (zm_dump (__LINE__));
375 /* Validate the message */
376 if ((xyz.blk ^ xyz.cblk) != (unsigned char) 0xFF)
379 ("Framing error - blk: %x/%x/%x\n", xyz.blk, xyz.cblk,
380 (xyz.blk ^ xyz.cblk)));
381 ZM_DEBUG (zm_dump_buf (xyz.pkt, xyz.len));
383 return xyzModem_frame;
385 /* Verify checksum/CRC */
388 cksum = crc16_ccitt(0, xyz.pkt, xyz.len);
389 if (cksum != ((xyz.crc1 << 8) | xyz.crc2))
391 ZM_DEBUG (zm_dprintf ("CRC error - recvd: %02x%02x, computed: %x\n",
392 xyz.crc1, xyz.crc2, cksum & 0xFFFF));
393 return xyzModem_cksum;
399 for (i = 0; i < xyz.len; i++)
403 if (xyz.crc1 != (cksum & 0xFF))
406 ("Checksum error - recvd: %x, computed: %x\n", xyz.crc1,
408 return xyzModem_cksum;
411 /* If we get here, the message passes [structural] muster */
417 xyzModem_get_initial_timeout (void)
419 /* timeout is in seconds, non-positive timeout value is infinity */
420 #if CONFIG_IS_ENABLED(ENV_SUPPORT)
421 const char *timeout_str = env_get("loadxy_timeout");
423 return 1000 * simple_strtol(timeout_str, NULL, 10);
425 return 1000 * CONFIG_CMD_LOADXY_TIMEOUT;
429 xyzModem_stream_open (connection_info_t * info, int *err)
432 int retries = xyzModem_MAX_RETRIES;
433 int crc_retries = xyzModem_MAX_RETRIES_WITH_CRC;
435 /* ZM_DEBUG(zm_out = zm_out_start); */
436 #ifdef xyzModem_zmodem
437 if (info->mode == xyzModem_zmodem)
439 *err = xyzModem_noZmodem;
451 xyz.mode = info->mode;
452 xyz.total_retries = 0;
458 xyz.first_xmodem_packet = false;
459 xyz.initial_time = get_timer(0);
460 xyz.timeout = xyzModem_get_initial_timeout();
462 CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
464 if (xyz.mode == xyzModem_xmodem)
466 /* X-modem doesn't have an information header - exit here */
467 xyz.first_xmodem_packet = true;
472 while (!(xyz.timeout && get_timer(xyz.initial_time) > xyz.timeout))
476 retries = xyzModem_MAX_RETRIES;
477 crc_retries = xyzModem_MAX_RETRIES_WITH_CRC;
480 stat = xyzModem_get_hdr ();
483 /* Y-modem file information header */
489 parse_num ((char *) xyz.bufp, &xyz.file_length, NULL, " ");
490 /* The rest of the file name data block quietly discarded */
497 else if (stat == xyzModem_timeout)
499 if (--crc_retries <= 0)
500 xyz.crc_mode = false;
501 CYGACC_CALL_IF_DELAY_US (5 * 100000); /* Extra delay for startup */
502 CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
504 ZM_DEBUG (zm_dprintf ("NAK (%d)\n", __LINE__));
506 if (stat == xyzModem_cancel)
512 ZM_DEBUG (zm_flush ());
517 xyzModem_stream_read (char *buf, int size, int *err)
519 int stat, total, len;
523 stat = xyzModem_cancel;
524 /* Try and get 'size' bytes into the buffer */
525 while (!xyz.at_eof && xyz.len >= 0 && (size > 0))
529 retries = xyzModem_MAX_RETRIES;
530 while (retries-- > 0)
532 if (xyz.first_xmodem_packet && xyz.timeout &&
533 get_timer(xyz.initial_time) > xyz.timeout)
535 *err = xyzModem_timeout;
540 stat = xyzModem_get_hdr ();
543 if (xyz.mode == xyzModem_xmodem && xyz.first_xmodem_packet)
544 xyz.first_xmodem_packet = false;
545 if (xyz.blk == xyz.next_blk)
549 ("ACK block %d (%d)\n", xyz.blk, __LINE__));
550 xyz.next_blk = (xyz.next_blk + 1) & 0xFF;
552 if (xyz.mode == xyzModem_xmodem || xyz.file_length == 0)
554 /* Data blocks can be padded with ^Z (EOF) characters */
555 /* This code tries to detect and remove them */
556 if ((xyz.bufp[xyz.len - 1] == EOF) &&
557 (xyz.bufp[xyz.len - 2] == EOF) &&
558 (xyz.bufp[xyz.len - 3] == EOF))
561 && (xyz.bufp[xyz.len - 1] == EOF))
569 * See if accumulated length exceeds that of the file.
570 * If so, reduce size (i.e., cut out pad bytes)
571 * Only do this for Y-modem (and Z-modem should it ever
572 * be supported since it can fall back to Y-modem mode).
574 if (xyz.mode != xyzModem_xmodem && 0 != xyz.file_length)
576 xyz.read_length += xyz.len;
577 if (xyz.read_length > xyz.file_length)
579 xyz.len -= (xyz.read_length - xyz.file_length);
584 else if (xyz.blk == ((xyz.next_blk - 1) & 0xFF))
586 /* Just re-ACK this so sender will get on with it */
587 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
588 continue; /* Need new header */
592 stat = xyzModem_sequence;
595 if (stat == xyzModem_cancel)
599 if (stat == xyzModem_eof)
601 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
602 ZM_DEBUG (zm_dprintf ("ACK (%d)\n", __LINE__));
603 if (xyz.mode == xyzModem_ymodem)
605 CYGACC_COMM_IF_PUTC (*xyz.__chan,
606 (xyz.crc_mode ? 'C' : NAK));
608 ZM_DEBUG (zm_dprintf ("Reading Final Header\n"));
609 stat = xyzModem_get_hdr ();
610 CYGACC_COMM_IF_PUTC (*xyz.__chan, ACK);
611 ZM_DEBUG (zm_dprintf ("FINAL ACK (%d)\n", __LINE__));
618 CYGACC_COMM_IF_PUTC (*xyz.__chan, (xyz.crc_mode ? 'C' : NAK));
620 ZM_DEBUG (zm_dprintf ("NAK (%d)\n", __LINE__));
622 if (stat < 0 && (!xyz.first_xmodem_packet || stat != xyzModem_timeout))
629 /* Don't "read" data from the EOF protocol package */
630 if (!xyz.at_eof && xyz.len > 0)
635 memcpy (buf, xyz.bufp, len);
647 xyzModem_stream_close (int *err)
650 ("xyzModem - %s mode, %d(SOH)/%d(STX)/%d(CAN) packets, %d retries\n",
651 xyz.crc_mode ? "CRC" : "Cksum", xyz.total_SOH, xyz.total_STX,
652 xyz.total_CAN, xyz.total_retries));
653 ZM_DEBUG (zm_flush ());
656 /* Need to be able to clean out the input buffer, so have to take the */
659 xyzModem_stream_terminate (bool abort, int (*getc) (void))
665 ZM_DEBUG (zm_dprintf ("!!!! TRANSFER ABORT !!!!\n"));
668 case xyzModem_xmodem:
669 case xyzModem_ymodem:
670 /* The X/YMODEM Spec seems to suggest that multiple CAN followed by an equal */
671 /* number of Backspaces is a friendly way to get the other end to abort. */
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, CAN);
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 CYGACC_COMM_IF_PUTC (*xyz.__chan, BSP);
680 /* Now consume the rest of what's waiting on the line. */
681 ZM_DEBUG (zm_dprintf ("Flushing serial line.\n"));
685 #ifdef xyzModem_zmodem
686 case xyzModem_zmodem:
687 /* Might support it some day I suppose. */
694 ZM_DEBUG (zm_dprintf ("Engaging cleanup mode...\n"));
696 * Consume any trailing crap left in the inbuffer from
697 * previous received blocks. Since very few files are an exact multiple
698 * of the transfer block size, there will almost always be some gunk here.
699 * If we don't eat it now, RedBoot will think the user typed it.
701 ZM_DEBUG (zm_dprintf ("Trailing gunk:\n"));
702 while ((c = (*getc) ()) > -1)
704 ZM_DEBUG (zm_dprintf ("\n"));
706 * Make a small delay to give terminal programs like minicom
707 * time to get control again after their file transfer program
710 CYGACC_CALL_IF_DELAY_US ((cyg_int32) 250000);
715 xyzModem_error (int err)
719 case xyzModem_access:
720 return "Can't access file";
722 case xyzModem_noZmodem:
723 return "Sorry, zModem not available yet";
725 case xyzModem_timeout:
729 return "End of file";
731 case xyzModem_cancel:
735 return "Invalid framing";
738 return "CRC/checksum error";
740 case xyzModem_sequence:
741 return "Block sequence error";
744 return "Unknown error";