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