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