common: Move serial functions out of common.h
[oweals/u-boot.git] / cmd / load.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2000-2004
4  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5  */
6
7 /*
8  * Serial up- and download support
9  */
10 #include <common.h>
11 #include <command.h>
12 #include <console.h>
13 #include <env.h>
14 #include <s_record.h>
15 #include <net.h>
16 #include <exports.h>
17 #include <serial.h>
18 #include <xyzModem.h>
19
20 DECLARE_GLOBAL_DATA_PTR;
21
22 #if defined(CONFIG_CMD_LOADB)
23 static ulong load_serial_ymodem(ulong offset, int mode);
24 #endif
25
26 #if defined(CONFIG_CMD_LOADS)
27 static ulong load_serial(long offset);
28 static int read_record(char *buf, ulong len);
29 # if defined(CONFIG_CMD_SAVES)
30 static int save_serial(ulong offset, ulong size);
31 static int write_record(char *buf);
32 #endif
33
34 static int do_echo = 1;
35 #endif
36
37 /* -------------------------------------------------------------------- */
38
39 #if defined(CONFIG_CMD_LOADS)
40 static int do_load_serial(cmd_tbl_t *cmdtp, int flag, int argc,
41                           char * const argv[])
42 {
43         long offset = 0;
44         ulong addr;
45         int i;
46         char *env_echo;
47         int rcode = 0;
48 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
49         int load_baudrate, current_baudrate;
50
51         load_baudrate = current_baudrate = gd->baudrate;
52 #endif
53
54         env_echo = env_get("loads_echo");
55         if (env_echo && *env_echo == '1')
56                 do_echo = 1;
57         else
58                 do_echo = 0;
59
60 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
61         if (argc >= 2) {
62                 offset = simple_strtol(argv[1], NULL, 16);
63         }
64         if (argc == 3) {
65                 load_baudrate = (int)simple_strtoul(argv[2], NULL, 10);
66
67                 /* default to current baudrate */
68                 if (load_baudrate == 0)
69                         load_baudrate = current_baudrate;
70         }
71         if (load_baudrate != current_baudrate) {
72                 printf("## Switch baudrate to %d bps and press ENTER ...\n",
73                         load_baudrate);
74                 udelay(50000);
75                 gd->baudrate = load_baudrate;
76                 serial_setbrg();
77                 udelay(50000);
78                 for (;;) {
79                         if (getc() == '\r')
80                                 break;
81                 }
82         }
83 #else   /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
84         if (argc == 2) {
85                 offset = simple_strtol(argv[1], NULL, 16);
86         }
87 #endif  /* CONFIG_SYS_LOADS_BAUD_CHANGE */
88
89         printf("## Ready for S-Record download ...\n");
90
91         addr = load_serial(offset);
92
93         /*
94          * Gather any trailing characters (for instance, the ^D which
95          * is sent by 'cu' after sending a file), and give the
96          * box some time (100 * 1 ms)
97          */
98         for (i=0; i<100; ++i) {
99                 if (tstc()) {
100                         (void) getc();
101                 }
102                 udelay(1000);
103         }
104
105         if (addr == ~0) {
106                 printf("## S-Record download aborted\n");
107                 rcode = 1;
108         } else {
109                 printf("## Start Addr      = 0x%08lX\n", addr);
110                 load_addr = addr;
111         }
112
113 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
114         if (load_baudrate != current_baudrate) {
115                 printf("## Switch baudrate to %d bps and press ESC ...\n",
116                         current_baudrate);
117                 udelay(50000);
118                 gd->baudrate = current_baudrate;
119                 serial_setbrg();
120                 udelay(50000);
121                 for (;;) {
122                         if (getc() == 0x1B) /* ESC */
123                                 break;
124                 }
125         }
126 #endif
127         return rcode;
128 }
129
130 static ulong load_serial(long offset)
131 {
132         char    record[SREC_MAXRECLEN + 1];     /* buffer for one S-Record      */
133         char    binbuf[SREC_MAXBINLEN];         /* buffer for binary data       */
134         int     binlen;                         /* no. of data bytes in S-Rec.  */
135         int     type;                           /* return code for record type  */
136         ulong   addr;                           /* load address from S-Record   */
137         ulong   size;                           /* number of bytes transferred  */
138         ulong   store_addr;
139         ulong   start_addr = ~0;
140         ulong   end_addr   =  0;
141         int     line_count =  0;
142
143         while (read_record(record, SREC_MAXRECLEN + 1) >= 0) {
144                 type = srec_decode(record, &binlen, &addr, binbuf);
145
146                 if (type < 0) {
147                         return (~0);            /* Invalid S-Record             */
148                 }
149
150                 switch (type) {
151                 case SREC_DATA2:
152                 case SREC_DATA3:
153                 case SREC_DATA4:
154                     store_addr = addr + offset;
155 #ifdef CONFIG_MTD_NOR_FLASH
156                     if (addr2info(store_addr)) {
157                         int rc;
158
159                         rc = flash_write((char *)binbuf,store_addr,binlen);
160                         if (rc != 0) {
161                                 flash_perror(rc);
162                                 return (~0);
163                         }
164                     } else
165 #endif
166                     {
167                         memcpy((char *)(store_addr), binbuf, binlen);
168                     }
169                     if ((store_addr) < start_addr)
170                         start_addr = store_addr;
171                     if ((store_addr + binlen - 1) > end_addr)
172                         end_addr = store_addr + binlen - 1;
173                     break;
174                 case SREC_END2:
175                 case SREC_END3:
176                 case SREC_END4:
177                     udelay(10000);
178                     size = end_addr - start_addr + 1;
179                     printf("\n"
180                             "## First Load Addr = 0x%08lX\n"
181                             "## Last  Load Addr = 0x%08lX\n"
182                             "## Total Size      = 0x%08lX = %ld Bytes\n",
183                             start_addr, end_addr, size, size
184                     );
185                     flush_cache(start_addr, size);
186                     env_set_hex("filesize", size);
187                     return (addr);
188                 case SREC_START:
189                     break;
190                 default:
191                     break;
192                 }
193                 if (!do_echo) { /* print a '.' every 100 lines */
194                         if ((++line_count % 100) == 0)
195                                 putc('.');
196                 }
197         }
198
199         return (~0);                    /* Download aborted             */
200 }
201
202 static int read_record(char *buf, ulong len)
203 {
204         char *p;
205         char c;
206
207         --len;  /* always leave room for terminating '\0' byte */
208
209         for (p=buf; p < buf+len; ++p) {
210                 c = getc();             /* read character               */
211                 if (do_echo)
212                         putc(c);        /* ... and echo it              */
213
214                 switch (c) {
215                 case '\r':
216                 case '\n':
217                         *p = '\0';
218                         return (p - buf);
219                 case '\0':
220                 case 0x03:                      /* ^C - Control C               */
221                         return (-1);
222                 default:
223                         *p = c;
224                 }
225
226             /* Check for the console hangup (if any different from serial) */
227             if (gd->jt->getc != getc) {
228                 if (ctrlc()) {
229                     return (-1);
230                 }
231             }
232         }
233
234         /* line too long - truncate */
235         *p = '\0';
236         return (p - buf);
237 }
238
239 #if defined(CONFIG_CMD_SAVES)
240
241 int do_save_serial (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
242 {
243         ulong offset = 0;
244         ulong size   = 0;
245 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
246         int save_baudrate, current_baudrate;
247
248         save_baudrate = current_baudrate = gd->baudrate;
249 #endif
250
251         if (argc >= 2) {
252                 offset = simple_strtoul(argv[1], NULL, 16);
253         }
254 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
255         if (argc >= 3) {
256                 size = simple_strtoul(argv[2], NULL, 16);
257         }
258         if (argc == 4) {
259                 save_baudrate = (int)simple_strtoul(argv[3], NULL, 10);
260
261                 /* default to current baudrate */
262                 if (save_baudrate == 0)
263                         save_baudrate = current_baudrate;
264         }
265         if (save_baudrate != current_baudrate) {
266                 printf("## Switch baudrate to %d bps and press ENTER ...\n",
267                         save_baudrate);
268                 udelay(50000);
269                 gd->baudrate = save_baudrate;
270                 serial_setbrg();
271                 udelay(50000);
272                 for (;;) {
273                         if (getc() == '\r')
274                                 break;
275                 }
276         }
277 #else   /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
278         if (argc == 3) {
279                 size = simple_strtoul(argv[2], NULL, 16);
280         }
281 #endif  /* CONFIG_SYS_LOADS_BAUD_CHANGE */
282
283         printf("## Ready for S-Record upload, press ENTER to proceed ...\n");
284         for (;;) {
285                 if (getc() == '\r')
286                         break;
287         }
288         if (save_serial(offset, size)) {
289                 printf("## S-Record upload aborted\n");
290         } else {
291                 printf("## S-Record upload complete\n");
292         }
293 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
294         if (save_baudrate != current_baudrate) {
295                 printf("## Switch baudrate to %d bps and press ESC ...\n",
296                         (int)current_baudrate);
297                 udelay(50000);
298                 gd->baudrate = current_baudrate;
299                 serial_setbrg();
300                 udelay(50000);
301                 for (;;) {
302                         if (getc() == 0x1B) /* ESC */
303                                 break;
304                 }
305         }
306 #endif
307         return 0;
308 }
309
310 #define SREC3_START                             "S0030000FC\n"
311 #define SREC3_FORMAT                    "S3%02X%08lX%s%02X\n"
312 #define SREC3_END                               "S70500000000FA\n"
313 #define SREC_BYTES_PER_RECORD   16
314
315 static int save_serial(ulong address, ulong count)
316 {
317         int i, c, reclen, checksum, length;
318         char *hex = "0123456789ABCDEF";
319         char    record[2*SREC_BYTES_PER_RECORD+16];     /* buffer for one S-Record      */
320         char    data[2*SREC_BYTES_PER_RECORD+1];        /* buffer for hex data  */
321
322         reclen = 0;
323         checksum  = 0;
324
325         if(write_record(SREC3_START))                   /* write the header */
326                 return (-1);
327         do {
328                 if(count) {                                             /* collect hex data in the buffer  */
329                         c = *(volatile uchar*)(address + reclen);       /* get one byte    */
330                         checksum += c;                                                  /* accumulate checksum */
331                         data[2*reclen]   = hex[(c>>4)&0x0f];
332                         data[2*reclen+1] = hex[c & 0x0f];
333                         data[2*reclen+2] = '\0';
334                         ++reclen;
335                         --count;
336                 }
337                 if(reclen == SREC_BYTES_PER_RECORD || count == 0) {
338                         /* enough data collected for one record: dump it */
339                         if(reclen) {    /* build & write a data record: */
340                                 /* address + data + checksum */
341                                 length = 4 + reclen + 1;
342
343                                 /* accumulate length bytes into checksum */
344                                 for(i = 0; i < 2; i++)
345                                         checksum += (length >> (8*i)) & 0xff;
346
347                                 /* accumulate address bytes into checksum: */
348                                 for(i = 0; i < 4; i++)
349                                         checksum += (address >> (8*i)) & 0xff;
350
351                                 /* make proper checksum byte: */
352                                 checksum = ~checksum & 0xff;
353
354                                 /* output one record: */
355                                 sprintf(record, SREC3_FORMAT, length, address, data, checksum);
356                                 if(write_record(record))
357                                         return (-1);
358                         }
359                         address  += reclen;  /* increment address */
360                         checksum  = 0;
361                         reclen    = 0;
362                 }
363         }
364         while(count);
365         if(write_record(SREC3_END))     /* write the final record */
366                 return (-1);
367         return(0);
368 }
369
370 static int write_record(char *buf)
371 {
372         char c;
373
374         while((c = *buf++))
375                 putc(c);
376
377         /* Check for the console hangup (if any different from serial) */
378
379         if (ctrlc()) {
380             return (-1);
381         }
382         return (0);
383 }
384 # endif
385
386 #endif
387
388
389 #if defined(CONFIG_CMD_LOADB)
390 /*
391  * loadb command (load binary) included
392  */
393 #define XON_CHAR        17
394 #define XOFF_CHAR       19
395 #define START_CHAR      0x01
396 #define ETX_CHAR        0x03
397 #define END_CHAR        0x0D
398 #define SPACE           0x20
399 #define K_ESCAPE        0x23
400 #define SEND_TYPE       'S'
401 #define DATA_TYPE       'D'
402 #define ACK_TYPE        'Y'
403 #define NACK_TYPE       'N'
404 #define BREAK_TYPE      'B'
405 #define tochar(x) ((char) (((x) + SPACE) & 0xff))
406 #define untochar(x) ((int) (((x) - SPACE) & 0xff))
407
408 static void set_kerm_bin_mode(unsigned long *);
409 static int k_recv(void);
410 static ulong load_serial_bin(ulong offset);
411
412
413 static char his_eol;        /* character he needs at end of packet */
414 static int  his_pad_count;  /* number of pad chars he needs */
415 static char his_pad_char;   /* pad chars he needs */
416 static char his_quote;      /* quote chars he'll use */
417
418 static int do_load_serial_bin(cmd_tbl_t *cmdtp, int flag, int argc,
419                               char * const argv[])
420 {
421         ulong offset = 0;
422         ulong addr;
423         int load_baudrate, current_baudrate;
424         int rcode = 0;
425         char *s;
426
427         /* pre-set offset from CONFIG_SYS_LOAD_ADDR */
428         offset = CONFIG_SYS_LOAD_ADDR;
429
430         /* pre-set offset from $loadaddr */
431         s = env_get("loadaddr");
432         if (s)
433                 offset = simple_strtoul(s, NULL, 16);
434
435         load_baudrate = current_baudrate = gd->baudrate;
436
437         if (argc >= 2) {
438                 offset = simple_strtoul(argv[1], NULL, 16);
439         }
440         if (argc == 3) {
441                 load_baudrate = (int)simple_strtoul(argv[2], NULL, 10);
442
443                 /* default to current baudrate */
444                 if (load_baudrate == 0)
445                         load_baudrate = current_baudrate;
446         }
447
448         if (load_baudrate != current_baudrate) {
449                 printf("## Switch baudrate to %d bps and press ENTER ...\n",
450                         load_baudrate);
451                 udelay(50000);
452                 gd->baudrate = load_baudrate;
453                 serial_setbrg();
454                 udelay(50000);
455                 for (;;) {
456                         if (getc() == '\r')
457                                 break;
458                 }
459         }
460
461         if (strcmp(argv[0],"loady")==0) {
462                 printf("## Ready for binary (ymodem) download "
463                         "to 0x%08lX at %d bps...\n",
464                         offset,
465                         load_baudrate);
466
467                 addr = load_serial_ymodem(offset, xyzModem_ymodem);
468
469         } else if (strcmp(argv[0],"loadx")==0) {
470                 printf("## Ready for binary (xmodem) download "
471                         "to 0x%08lX at %d bps...\n",
472                         offset,
473                         load_baudrate);
474
475                 addr = load_serial_ymodem(offset, xyzModem_xmodem);
476
477         } else {
478
479                 printf("## Ready for binary (kermit) download "
480                         "to 0x%08lX at %d bps...\n",
481                         offset,
482                         load_baudrate);
483                 addr = load_serial_bin(offset);
484
485                 if (addr == ~0) {
486                         load_addr = 0;
487                         printf("## Binary (kermit) download aborted\n");
488                         rcode = 1;
489                 } else {
490                         printf("## Start Addr      = 0x%08lX\n", addr);
491                         load_addr = addr;
492                 }
493         }
494         if (load_baudrate != current_baudrate) {
495                 printf("## Switch baudrate to %d bps and press ESC ...\n",
496                         current_baudrate);
497                 udelay(50000);
498                 gd->baudrate = current_baudrate;
499                 serial_setbrg();
500                 udelay(50000);
501                 for (;;) {
502                         if (getc() == 0x1B) /* ESC */
503                                 break;
504                 }
505         }
506
507         return rcode;
508 }
509
510
511 static ulong load_serial_bin(ulong offset)
512 {
513         int size, i;
514
515         set_kerm_bin_mode((ulong *) offset);
516         size = k_recv();
517
518         /*
519          * Gather any trailing characters (for instance, the ^D which
520          * is sent by 'cu' after sending a file), and give the
521          * box some time (100 * 1 ms)
522          */
523         for (i=0; i<100; ++i) {
524                 if (tstc()) {
525                         (void) getc();
526                 }
527                 udelay(1000);
528         }
529
530         flush_cache(offset, size);
531
532         printf("## Total Size      = 0x%08x = %d Bytes\n", size, size);
533         env_set_hex("filesize", size);
534
535         return offset;
536 }
537
538 static void send_pad(void)
539 {
540         int count = his_pad_count;
541
542         while (count-- > 0)
543                 putc(his_pad_char);
544 }
545
546 /* converts escaped kermit char to binary char */
547 static char ktrans(char in)
548 {
549         if ((in & 0x60) == 0x40) {
550                 return (char) (in & ~0x40);
551         } else if ((in & 0x7f) == 0x3f) {
552                 return (char) (in | 0x40);
553         } else
554                 return in;
555 }
556
557 static int chk1(char *buffer)
558 {
559         int total = 0;
560
561         while (*buffer) {
562                 total += *buffer++;
563         }
564         return (int) ((total + ((total >> 6) & 0x03)) & 0x3f);
565 }
566
567 static void s1_sendpacket(char *packet)
568 {
569         send_pad();
570         while (*packet) {
571                 putc(*packet++);
572         }
573 }
574
575 static char a_b[24];
576 static void send_ack(int n)
577 {
578         a_b[0] = START_CHAR;
579         a_b[1] = tochar(3);
580         a_b[2] = tochar(n);
581         a_b[3] = ACK_TYPE;
582         a_b[4] = '\0';
583         a_b[4] = tochar(chk1(&a_b[1]));
584         a_b[5] = his_eol;
585         a_b[6] = '\0';
586         s1_sendpacket(a_b);
587 }
588
589 static void send_nack(int n)
590 {
591         a_b[0] = START_CHAR;
592         a_b[1] = tochar(3);
593         a_b[2] = tochar(n);
594         a_b[3] = NACK_TYPE;
595         a_b[4] = '\0';
596         a_b[4] = tochar(chk1(&a_b[1]));
597         a_b[5] = his_eol;
598         a_b[6] = '\0';
599         s1_sendpacket(a_b);
600 }
601
602
603 static void (*os_data_init)(void);
604 static void (*os_data_char)(char new_char);
605 static int os_data_state, os_data_state_saved;
606 static char *os_data_addr, *os_data_addr_saved;
607 static char *bin_start_address;
608
609 static void bin_data_init(void)
610 {
611         os_data_state = 0;
612         os_data_addr = bin_start_address;
613 }
614
615 static void os_data_save(void)
616 {
617         os_data_state_saved = os_data_state;
618         os_data_addr_saved = os_data_addr;
619 }
620
621 static void os_data_restore(void)
622 {
623         os_data_state = os_data_state_saved;
624         os_data_addr = os_data_addr_saved;
625 }
626
627 static void bin_data_char(char new_char)
628 {
629         switch (os_data_state) {
630         case 0:                                 /* data */
631                 *os_data_addr++ = new_char;
632                 break;
633         }
634 }
635
636 static void set_kerm_bin_mode(unsigned long *addr)
637 {
638         bin_start_address = (char *) addr;
639         os_data_init = bin_data_init;
640         os_data_char = bin_data_char;
641 }
642
643
644 /* k_data_* simply handles the kermit escape translations */
645 static int k_data_escape, k_data_escape_saved;
646 static void k_data_init(void)
647 {
648         k_data_escape = 0;
649         os_data_init();
650 }
651
652 static void k_data_save(void)
653 {
654         k_data_escape_saved = k_data_escape;
655         os_data_save();
656 }
657
658 static void k_data_restore(void)
659 {
660         k_data_escape = k_data_escape_saved;
661         os_data_restore();
662 }
663
664 static void k_data_char(char new_char)
665 {
666         if (k_data_escape) {
667                 /* last char was escape - translate this character */
668                 os_data_char(ktrans(new_char));
669                 k_data_escape = 0;
670         } else {
671                 if (new_char == his_quote) {
672                         /* this char is escape - remember */
673                         k_data_escape = 1;
674                 } else {
675                         /* otherwise send this char as-is */
676                         os_data_char(new_char);
677                 }
678         }
679 }
680
681 #define SEND_DATA_SIZE  20
682 static char send_parms[SEND_DATA_SIZE];
683 static char *send_ptr;
684
685 /* handle_send_packet interprits the protocol info and builds and
686    sends an appropriate ack for what we can do */
687 static void handle_send_packet(int n)
688 {
689         int length = 3;
690         int bytes;
691
692         /* initialize some protocol parameters */
693         his_eol = END_CHAR;             /* default end of line character */
694         his_pad_count = 0;
695         his_pad_char = '\0';
696         his_quote = K_ESCAPE;
697
698         /* ignore last character if it filled the buffer */
699         if (send_ptr == &send_parms[SEND_DATA_SIZE - 1])
700                 --send_ptr;
701         bytes = send_ptr - send_parms;  /* how many bytes we'll process */
702         do {
703                 if (bytes-- <= 0)
704                         break;
705                 /* handle MAXL - max length */
706                 /* ignore what he says - most I'll take (here) is 94 */
707                 a_b[++length] = tochar(94);
708                 if (bytes-- <= 0)
709                         break;
710                 /* handle TIME - time you should wait for my packets */
711                 /* ignore what he says - don't wait for my ack longer than 1 second */
712                 a_b[++length] = tochar(1);
713                 if (bytes-- <= 0)
714                         break;
715                 /* handle NPAD - number of pad chars I need */
716                 /* remember what he says - I need none */
717                 his_pad_count = untochar(send_parms[2]);
718                 a_b[++length] = tochar(0);
719                 if (bytes-- <= 0)
720                         break;
721                 /* handle PADC - pad chars I need */
722                 /* remember what he says - I need none */
723                 his_pad_char = ktrans(send_parms[3]);
724                 a_b[++length] = 0x40;   /* He should ignore this */
725                 if (bytes-- <= 0)
726                         break;
727                 /* handle EOL - end of line he needs */
728                 /* remember what he says - I need CR */
729                 his_eol = untochar(send_parms[4]);
730                 a_b[++length] = tochar(END_CHAR);
731                 if (bytes-- <= 0)
732                         break;
733                 /* handle QCTL - quote control char he'll use */
734                 /* remember what he says - I'll use '#' */
735                 his_quote = send_parms[5];
736                 a_b[++length] = '#';
737                 if (bytes-- <= 0)
738                         break;
739                 /* handle QBIN - 8-th bit prefixing */
740                 /* ignore what he says - I refuse */
741                 a_b[++length] = 'N';
742                 if (bytes-- <= 0)
743                         break;
744                 /* handle CHKT - the clock check type */
745                 /* ignore what he says - I do type 1 (for now) */
746                 a_b[++length] = '1';
747                 if (bytes-- <= 0)
748                         break;
749                 /* handle REPT - the repeat prefix */
750                 /* ignore what he says - I refuse (for now) */
751                 a_b[++length] = 'N';
752                 if (bytes-- <= 0)
753                         break;
754                 /* handle CAPAS - the capabilities mask */
755                 /* ignore what he says - I only do long packets - I don't do windows */
756                 a_b[++length] = tochar(2);      /* only long packets */
757                 a_b[++length] = tochar(0);      /* no windows */
758                 a_b[++length] = tochar(94);     /* large packet msb */
759                 a_b[++length] = tochar(94);     /* large packet lsb */
760         } while (0);
761
762         a_b[0] = START_CHAR;
763         a_b[1] = tochar(length);
764         a_b[2] = tochar(n);
765         a_b[3] = ACK_TYPE;
766         a_b[++length] = '\0';
767         a_b[length] = tochar(chk1(&a_b[1]));
768         a_b[++length] = his_eol;
769         a_b[++length] = '\0';
770         s1_sendpacket(a_b);
771 }
772
773 /* k_recv receives a OS Open image file over kermit line */
774 static int k_recv(void)
775 {
776         char new_char;
777         char k_state, k_state_saved;
778         int sum;
779         int done;
780         int length;
781         int n, last_n;
782         int len_lo, len_hi;
783
784         /* initialize some protocol parameters */
785         his_eol = END_CHAR;             /* default end of line character */
786         his_pad_count = 0;
787         his_pad_char = '\0';
788         his_quote = K_ESCAPE;
789
790         /* initialize the k_recv and k_data state machine */
791         done = 0;
792         k_state = 0;
793         k_data_init();
794         k_state_saved = k_state;
795         k_data_save();
796         n = 0;                          /* just to get rid of a warning */
797         last_n = -1;
798
799         /* expect this "type" sequence (but don't check):
800            S: send initiate
801            F: file header
802            D: data (multiple)
803            Z: end of file
804            B: break transmission
805          */
806
807         /* enter main loop */
808         while (!done) {
809                 /* set the send packet pointer to begining of send packet parms */
810                 send_ptr = send_parms;
811
812                 /* With each packet, start summing the bytes starting with the length.
813                    Save the current sequence number.
814                    Note the type of the packet.
815                    If a character less than SPACE (0x20) is received - error.
816                  */
817
818 #if 0
819                 /* OLD CODE, Prior to checking sequence numbers */
820                 /* first have all state machines save current states */
821                 k_state_saved = k_state;
822                 k_data_save ();
823 #endif
824
825                 /* get a packet */
826                 /* wait for the starting character or ^C */
827                 for (;;) {
828                         switch (getc ()) {
829                         case START_CHAR:        /* start packet */
830                                 goto START;
831                         case ETX_CHAR:          /* ^C waiting for packet */
832                                 return (0);
833                         default:
834                                 ;
835                         }
836                 }
837 START:
838                 /* get length of packet */
839                 sum = 0;
840                 new_char = getc();
841                 if ((new_char & 0xE0) == 0)
842                         goto packet_error;
843                 sum += new_char & 0xff;
844                 length = untochar(new_char);
845                 /* get sequence number */
846                 new_char = getc();
847                 if ((new_char & 0xE0) == 0)
848                         goto packet_error;
849                 sum += new_char & 0xff;
850                 n = untochar(new_char);
851                 --length;
852
853                 /* NEW CODE - check sequence numbers for retried packets */
854                 /* Note - this new code assumes that the sequence number is correctly
855                  * received.  Handling an invalid sequence number adds another layer
856                  * of complexity that may not be needed - yet!  At this time, I'm hoping
857                  * that I don't need to buffer the incoming data packets and can write
858                  * the data into memory in real time.
859                  */
860                 if (n == last_n) {
861                         /* same sequence number, restore the previous state */
862                         k_state = k_state_saved;
863                         k_data_restore();
864                 } else {
865                         /* new sequence number, checkpoint the download */
866                         last_n = n;
867                         k_state_saved = k_state;
868                         k_data_save();
869                 }
870                 /* END NEW CODE */
871
872                 /* get packet type */
873                 new_char = getc();
874                 if ((new_char & 0xE0) == 0)
875                         goto packet_error;
876                 sum += new_char & 0xff;
877                 k_state = new_char;
878                 --length;
879                 /* check for extended length */
880                 if (length == -2) {
881                         /* (length byte was 0, decremented twice) */
882                         /* get the two length bytes */
883                         new_char = getc();
884                         if ((new_char & 0xE0) == 0)
885                                 goto packet_error;
886                         sum += new_char & 0xff;
887                         len_hi = untochar(new_char);
888                         new_char = getc();
889                         if ((new_char & 0xE0) == 0)
890                                 goto packet_error;
891                         sum += new_char & 0xff;
892                         len_lo = untochar(new_char);
893                         length = len_hi * 95 + len_lo;
894                         /* check header checksum */
895                         new_char = getc();
896                         if ((new_char & 0xE0) == 0)
897                                 goto packet_error;
898                         if (new_char != tochar((sum + ((sum >> 6) & 0x03)) & 0x3f))
899                                 goto packet_error;
900                         sum += new_char & 0xff;
901 /* --length; */ /* new length includes only data and block check to come */
902                 }
903                 /* bring in rest of packet */
904                 while (length > 1) {
905                         new_char = getc();
906                         if ((new_char & 0xE0) == 0)
907                                 goto packet_error;
908                         sum += new_char & 0xff;
909                         --length;
910                         if (k_state == DATA_TYPE) {
911                                 /* pass on the data if this is a data packet */
912                                 k_data_char (new_char);
913                         } else if (k_state == SEND_TYPE) {
914                                 /* save send pack in buffer as is */
915                                 *send_ptr++ = new_char;
916                                 /* if too much data, back off the pointer */
917                                 if (send_ptr >= &send_parms[SEND_DATA_SIZE])
918                                         --send_ptr;
919                         }
920                 }
921                 /* get and validate checksum character */
922                 new_char = getc();
923                 if ((new_char & 0xE0) == 0)
924                         goto packet_error;
925                 if (new_char != tochar((sum + ((sum >> 6) & 0x03)) & 0x3f))
926                         goto packet_error;
927                 /* get END_CHAR */
928                 new_char = getc();
929                 if (new_char != END_CHAR) {
930                   packet_error:
931                         /* restore state machines */
932                         k_state = k_state_saved;
933                         k_data_restore();
934                         /* send a negative acknowledge packet in */
935                         send_nack(n);
936                 } else if (k_state == SEND_TYPE) {
937                         /* crack the protocol parms, build an appropriate ack packet */
938                         handle_send_packet(n);
939                 } else {
940                         /* send simple acknowledge packet in */
941                         send_ack(n);
942                         /* quit if end of transmission */
943                         if (k_state == BREAK_TYPE)
944                                 done = 1;
945                 }
946         }
947         return ((ulong) os_data_addr - (ulong) bin_start_address);
948 }
949
950 static int getcxmodem(void) {
951         if (tstc())
952                 return (getc());
953         return -1;
954 }
955 static ulong load_serial_ymodem(ulong offset, int mode)
956 {
957         int size;
958         int err;
959         int res;
960         connection_info_t info;
961         char ymodemBuf[1024];
962         ulong store_addr = ~0;
963         ulong addr = 0;
964
965         size = 0;
966         info.mode = mode;
967         res = xyzModem_stream_open(&info, &err);
968         if (!res) {
969
970                 while ((res =
971                         xyzModem_stream_read(ymodemBuf, 1024, &err)) > 0) {
972                         store_addr = addr + offset;
973                         size += res;
974                         addr += res;
975 #ifdef CONFIG_MTD_NOR_FLASH
976                         if (addr2info(store_addr)) {
977                                 int rc;
978
979                                 rc = flash_write((char *) ymodemBuf,
980                                                   store_addr, res);
981                                 if (rc != 0) {
982                                         flash_perror (rc);
983                                         return (~0);
984                                 }
985                         } else
986 #endif
987                         {
988                                 memcpy((char *)(store_addr), ymodemBuf,
989                                         res);
990                         }
991
992                 }
993         } else {
994                 printf("%s\n", xyzModem_error(err));
995         }
996
997         xyzModem_stream_close(&err);
998         xyzModem_stream_terminate(false, &getcxmodem);
999
1000
1001         flush_cache(offset, ALIGN(size, ARCH_DMA_MINALIGN));
1002
1003         printf("## Total Size      = 0x%08x = %d Bytes\n", size, size);
1004         env_set_hex("filesize", size);
1005
1006         return offset;
1007 }
1008
1009 #endif
1010
1011 /* -------------------------------------------------------------------- */
1012
1013 #if defined(CONFIG_CMD_LOADS)
1014
1015 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
1016 U_BOOT_CMD(
1017         loads, 3, 0,    do_load_serial,
1018         "load S-Record file over serial line",
1019         "[ off ] [ baud ]\n"
1020         "    - load S-Record file over serial line"
1021         " with offset 'off' and baudrate 'baud'"
1022 );
1023
1024 #else   /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
1025 U_BOOT_CMD(
1026         loads, 2, 0,    do_load_serial,
1027         "load S-Record file over serial line",
1028         "[ off ]\n"
1029         "    - load S-Record file over serial line with offset 'off'"
1030 );
1031 #endif  /* CONFIG_SYS_LOADS_BAUD_CHANGE */
1032
1033 /*
1034  * SAVES always requires LOADS support, but not vice versa
1035  */
1036
1037
1038 #if defined(CONFIG_CMD_SAVES)
1039 #ifdef  CONFIG_SYS_LOADS_BAUD_CHANGE
1040 U_BOOT_CMD(
1041         saves, 4, 0,    do_save_serial,
1042         "save S-Record file over serial line",
1043         "[ off ] [size] [ baud ]\n"
1044         "    - save S-Record file over serial line"
1045         " with offset 'off', size 'size' and baudrate 'baud'"
1046 );
1047 #else   /* ! CONFIG_SYS_LOADS_BAUD_CHANGE */
1048 U_BOOT_CMD(
1049         saves, 3, 0,    do_save_serial,
1050         "save S-Record file over serial line",
1051         "[ off ] [size]\n"
1052         "    - save S-Record file over serial line with offset 'off' and size 'size'"
1053 );
1054 #endif  /* CONFIG_SYS_LOADS_BAUD_CHANGE */
1055 #endif  /* CONFIG_CMD_SAVES */
1056 #endif  /* CONFIG_CMD_LOADS */
1057
1058
1059 #if defined(CONFIG_CMD_LOADB)
1060 U_BOOT_CMD(
1061         loadb, 3, 0,    do_load_serial_bin,
1062         "load binary file over serial line (kermit mode)",
1063         "[ off ] [ baud ]\n"
1064         "    - load binary file over serial line"
1065         " with offset 'off' and baudrate 'baud'"
1066 );
1067
1068 U_BOOT_CMD(
1069         loadx, 3, 0,    do_load_serial_bin,
1070         "load binary file over serial line (xmodem mode)",
1071         "[ off ] [ baud ]\n"
1072         "    - load binary file over serial line"
1073         " with offset 'off' and baudrate 'baud'"
1074 );
1075
1076 U_BOOT_CMD(
1077         loady, 3, 0,    do_load_serial_bin,
1078         "load binary file over serial line (ymodem mode)",
1079         "[ off ] [ baud ]\n"
1080         "    - load binary file over serial line"
1081         " with offset 'off' and baudrate 'baud'"
1082 );
1083
1084 #endif  /* CONFIG_CMD_LOADB */