]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/main.c
unify version_string
[karo-tx-uboot.git] / common / main.c
1 /*
2  * (C) Copyright 2000
3  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
4  *
5  * Add to readline cmdline-editing by
6  * (C) Copyright 2005
7  * JinHua Luo, GuangDong Linux Center, <luo.jinhua@gd-linux.com>
8  *
9  * See file CREDITS for list of people who contributed to this
10  * project.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License as
14  * published by the Free Software Foundation; either version 2 of
15  * the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
25  * MA 02111-1307 USA
26  */
27
28 /* #define      DEBUG   */
29
30 #include <common.h>
31 #include <watchdog.h>
32 #include <command.h>
33 #include <version.h>
34 #ifdef CONFIG_MODEM_SUPPORT
35 #include <malloc.h>             /* for free() prototype */
36 #endif
37
38 #ifdef CONFIG_SYS_HUSH_PARSER
39 #include <hush.h>
40 #endif
41
42 #include <post.h>
43
44 #if defined(CONFIG_SILENT_CONSOLE) || defined(CONFIG_POST) || defined(CONFIG_CMDLINE_EDITING)
45 DECLARE_GLOBAL_DATA_PTR;
46 #endif
47
48 /*
49  * Board-specific Platform code can reimplement show_boot_progress () if needed
50  */
51 void inline __show_boot_progress (int val) {}
52 void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress")));
53
54 #if defined(CONFIG_UPDATE_TFTP)
55 int update_tftp (ulong addr);
56 #endif /* CONFIG_UPDATE_TFTP */
57
58 #define MAX_DELAY_STOP_STR 32
59
60 #undef DEBUG_PARSER
61
62 char        console_buffer[CONFIG_SYS_CBSIZE + 1];      /* console I/O buffer   */
63
64 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen);
65 static const char erase_seq[] = "\b \b";                /* erase sequence       */
66 static const char   tab_seq[] = "        ";             /* used to expand TABs  */
67
68 #ifdef CONFIG_BOOT_RETRY_TIME
69 static uint64_t endtime = 0;  /* must be set, default is instant timeout */
70 static int      retry_time = -1; /* -1 so can call readline before main_loop */
71 #endif
72
73 #define endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk())
74
75 #ifndef CONFIG_BOOT_RETRY_MIN
76 #define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME
77 #endif
78
79 #ifdef CONFIG_MODEM_SUPPORT
80 int do_mdm_init = 0;
81 extern void mdm_init(void); /* defined in board.c */
82 #endif
83
84 /***************************************************************************
85  * Watch for 'delay' seconds for autoboot stop or autoboot delay string.
86  * returns: 0 -  no key string, allow autoboot
87  *          1 - got key string, abort
88  */
89 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
90 # if defined(CONFIG_AUTOBOOT_KEYED)
91 static inline int abortboot(int bootdelay)
92 {
93         int abort = 0;
94         uint64_t etime = endtick(bootdelay);
95         struct {
96                 char* str;
97                 u_int len;
98                 int retry;
99         }
100         delaykey [] = {
101                 { str: getenv ("bootdelaykey"),  retry: 1 },
102                 { str: getenv ("bootdelaykey2"), retry: 1 },
103                 { str: getenv ("bootstopkey"),   retry: 0 },
104                 { str: getenv ("bootstopkey2"),  retry: 0 },
105         };
106
107         char presskey [MAX_DELAY_STOP_STR];
108         u_int presskey_len = 0;
109         u_int presskey_max = 0;
110         u_int i;
111
112 #  ifdef CONFIG_AUTOBOOT_PROMPT
113         printf(CONFIG_AUTOBOOT_PROMPT);
114 #  endif
115
116 #  ifdef CONFIG_AUTOBOOT_DELAY_STR
117         if (delaykey[0].str == NULL)
118                 delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR;
119 #  endif
120 #  ifdef CONFIG_AUTOBOOT_DELAY_STR2
121         if (delaykey[1].str == NULL)
122                 delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2;
123 #  endif
124 #  ifdef CONFIG_AUTOBOOT_STOP_STR
125         if (delaykey[2].str == NULL)
126                 delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR;
127 #  endif
128 #  ifdef CONFIG_AUTOBOOT_STOP_STR2
129         if (delaykey[3].str == NULL)
130                 delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2;
131 #  endif
132
133         for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
134                 delaykey[i].len = delaykey[i].str == NULL ?
135                                     0 : strlen (delaykey[i].str);
136                 delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ?
137                                     MAX_DELAY_STOP_STR : delaykey[i].len;
138
139                 presskey_max = presskey_max > delaykey[i].len ?
140                                     presskey_max : delaykey[i].len;
141
142 #  if DEBUG_BOOTKEYS
143                 printf("%s key:<%s>\n",
144                        delaykey[i].retry ? "delay" : "stop",
145                        delaykey[i].str ? delaykey[i].str : "NULL");
146 #  endif
147         }
148
149         /* In order to keep up with incoming data, check timeout only
150          * when catch up.
151          */
152         do {
153                 if (tstc()) {
154                         if (presskey_len < presskey_max) {
155                                 presskey [presskey_len ++] = getc();
156                         }
157                         else {
158                                 for (i = 0; i < presskey_max - 1; i ++)
159                                         presskey [i] = presskey [i + 1];
160
161                                 presskey [i] = getc();
162                         }
163                 }
164
165                 for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) {
166                         if (delaykey[i].len > 0 &&
167                             presskey_len >= delaykey[i].len &&
168                             memcmp (presskey + presskey_len - delaykey[i].len,
169                                     delaykey[i].str,
170                                     delaykey[i].len) == 0) {
171 #  if DEBUG_BOOTKEYS
172                                 printf("got %skey\n",
173                                        delaykey[i].retry ? "delay" : "stop");
174 #  endif
175
176 #  ifdef CONFIG_BOOT_RETRY_TIME
177                                 /* don't retry auto boot */
178                                 if (! delaykey[i].retry)
179                                         retry_time = -1;
180 #  endif
181                                 abort = 1;
182                         }
183                 }
184         } while (!abort && get_ticks() <= etime);
185
186 #  if DEBUG_BOOTKEYS
187         if (!abort)
188                 puts("key timeout\n");
189 #  endif
190
191 #ifdef CONFIG_SILENT_CONSOLE
192         if (abort)
193                 gd->flags &= ~GD_FLG_SILENT;
194 #endif
195
196         return abort;
197 }
198
199 # else  /* !defined(CONFIG_AUTOBOOT_KEYED) */
200
201 #ifdef CONFIG_MENUKEY
202 static int menukey = 0;
203 #endif
204
205 static inline int abortboot(int bootdelay)
206 {
207         int abort = 0;
208
209 #ifdef CONFIG_MENUPROMPT
210         printf(CONFIG_MENUPROMPT);
211 #else
212         printf("Hit any key to stop autoboot: %2d ", bootdelay);
213 #endif
214
215 #if defined CONFIG_ZERO_BOOTDELAY_CHECK
216         /*
217          * Check if key already pressed
218          * Don't check if bootdelay < 0
219          */
220         if (bootdelay >= 0) {
221                 if (tstc()) {   /* we got a key press   */
222                         (void) getc();  /* consume input        */
223                         puts ("\b\b\b 0");
224                         abort = 1;      /* don't auto boot      */
225                 }
226         }
227 #endif
228
229         while ((bootdelay > 0) && (!abort)) {
230                 int i;
231
232                 --bootdelay;
233                 /* delay 100 * 10ms */
234                 for (i=0; !abort && i<100; ++i) {
235                         if (tstc()) {   /* we got a key press   */
236                                 abort  = 1;     /* don't auto boot      */
237                                 bootdelay = 0;  /* no more delay        */
238 # ifdef CONFIG_MENUKEY
239                                 menukey = getc();
240 # else
241                                 (void) getc();  /* consume input        */
242 # endif
243                                 break;
244                         }
245                         udelay(10000);
246                 }
247
248                 printf("\b\b\b%2d ", bootdelay);
249         }
250
251         putc('\n');
252
253 #ifdef CONFIG_SILENT_CONSOLE
254         if (abort)
255                 gd->flags &= ~GD_FLG_SILENT;
256 #endif
257
258         return abort;
259 }
260 # endif /* CONFIG_AUTOBOOT_KEYED */
261 #endif  /* CONFIG_BOOTDELAY >= 0  */
262
263 /****************************************************************************/
264
265 void main_loop (void)
266 {
267 #ifndef CONFIG_SYS_HUSH_PARSER
268         static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
269         int len;
270         int rc = 1;
271         int flag;
272 #endif
273
274 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
275         char *s;
276         int bootdelay;
277 #endif
278 #ifdef CONFIG_PREBOOT
279         char *p;
280 #endif
281 #ifdef CONFIG_BOOTCOUNT_LIMIT
282         unsigned long bootcount = 0;
283         unsigned long bootlimit = 0;
284         char *bcs;
285         char bcs_set[16];
286 #endif /* CONFIG_BOOTCOUNT_LIMIT */
287
288 #ifdef CONFIG_BOOTCOUNT_LIMIT
289         bootcount = bootcount_load();
290         bootcount++;
291         bootcount_store (bootcount);
292         sprintf (bcs_set, "%lu", bootcount);
293         setenv ("bootcount", bcs_set);
294         bcs = getenv ("bootlimit");
295         bootlimit = bcs ? simple_strtoul (bcs, NULL, 10) : 0;
296 #endif /* CONFIG_BOOTCOUNT_LIMIT */
297
298 #ifdef CONFIG_MODEM_SUPPORT
299         debug ("DEBUG: main_loop:   do_mdm_init=%d\n", do_mdm_init);
300         if (do_mdm_init) {
301                 char *str = strdup(getenv("mdm_cmd"));
302                 setenv ("preboot", str);  /* set or delete definition */
303                 if (str != NULL)
304                         free (str);
305                 mdm_init(); /* wait for modem connection */
306         }
307 #endif  /* CONFIG_MODEM_SUPPORT */
308
309 #ifdef CONFIG_VERSION_VARIABLE
310         {
311                 setenv ("ver", version_string);  /* set version variable */
312         }
313 #endif /* CONFIG_VERSION_VARIABLE */
314
315 #ifdef CONFIG_SYS_HUSH_PARSER
316         u_boot_hush_start ();
317 #endif
318
319 #if defined(CONFIG_HUSH_INIT_VAR)
320         hush_init_var ();
321 #endif
322
323 #ifdef CONFIG_PREBOOT
324         if ((p = getenv ("preboot")) != NULL) {
325 # ifdef CONFIG_AUTOBOOT_KEYED
326                 int prev = disable_ctrlc(1);    /* disable Control C checking */
327 # endif
328
329 # ifndef CONFIG_SYS_HUSH_PARSER
330                 run_command (p, 0);
331 # else
332                 parse_string_outer(p, FLAG_PARSE_SEMICOLON |
333                                     FLAG_EXIT_FROM_LOOP);
334 # endif
335
336 # ifdef CONFIG_AUTOBOOT_KEYED
337                 disable_ctrlc(prev);    /* restore Control C checking */
338 # endif
339         }
340 #endif /* CONFIG_PREBOOT */
341
342 #if defined(CONFIG_UPDATE_TFTP)
343         update_tftp (0UL);
344 #endif /* CONFIG_UPDATE_TFTP */
345
346 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
347         s = getenv ("bootdelay");
348         bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
349
350         debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);
351
352 # ifdef CONFIG_BOOT_RETRY_TIME
353         init_cmd_timeout ();
354 # endif /* CONFIG_BOOT_RETRY_TIME */
355
356 #ifdef CONFIG_POST
357         if (gd->flags & GD_FLG_POSTFAIL) {
358                 s = getenv("failbootcmd");
359         }
360         else
361 #endif /* CONFIG_POST */
362 #ifdef CONFIG_BOOTCOUNT_LIMIT
363         if (bootlimit && (bootcount > bootlimit)) {
364                 printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",
365                         (unsigned)bootlimit);
366                 s = getenv ("altbootcmd");
367         }
368         else
369 #endif /* CONFIG_BOOTCOUNT_LIMIT */
370                 s = getenv ("bootcmd");
371
372         debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");
373
374         if (bootdelay >= 0 && s && !abortboot (bootdelay)) {
375 # ifdef CONFIG_AUTOBOOT_KEYED
376                 int prev = disable_ctrlc(1);    /* disable Control C checking */
377 # endif
378
379 # ifndef CONFIG_SYS_HUSH_PARSER
380                 run_command (s, 0);
381 # else
382                 parse_string_outer(s, FLAG_PARSE_SEMICOLON |
383                                     FLAG_EXIT_FROM_LOOP);
384 # endif
385
386 # ifdef CONFIG_AUTOBOOT_KEYED
387                 disable_ctrlc(prev);    /* restore Control C checking */
388 # endif
389         }
390
391 # ifdef CONFIG_MENUKEY
392         if (menukey == CONFIG_MENUKEY) {
393                 s = getenv("menucmd");
394                 if (s) {
395 # ifndef CONFIG_SYS_HUSH_PARSER
396                         run_command(s, 0);
397 # else
398                         parse_string_outer(s, FLAG_PARSE_SEMICOLON |
399                                                 FLAG_EXIT_FROM_LOOP);
400 # endif
401                 }
402         }
403 #endif /* CONFIG_MENUKEY */
404 #endif /* CONFIG_BOOTDELAY */
405
406         /*
407          * Main Loop for Monitor Command Processing
408          */
409 #ifdef CONFIG_SYS_HUSH_PARSER
410         parse_file_outer();
411         /* This point is never reached */
412         for (;;);
413 #else
414         for (;;) {
415 #ifdef CONFIG_BOOT_RETRY_TIME
416                 if (rc >= 0) {
417                         /* Saw enough of a valid command to
418                          * restart the timeout.
419                          */
420                         reset_cmd_timeout();
421                 }
422 #endif
423                 len = readline (CONFIG_SYS_PROMPT);
424
425                 flag = 0;       /* assume no special flags for now */
426                 if (len > 0)
427                         strcpy (lastcommand, console_buffer);
428                 else if (len == 0)
429                         flag |= CMD_FLAG_REPEAT;
430 #ifdef CONFIG_BOOT_RETRY_TIME
431                 else if (len == -2) {
432                         /* -2 means timed out, retry autoboot
433                          */
434                         puts ("\nTimed out waiting for command\n");
435 # ifdef CONFIG_RESET_TO_RETRY
436                         /* Reinit board to run initialization code again */
437                         do_reset (NULL, 0, 0, NULL);
438 # else
439                         return;         /* retry autoboot */
440 # endif
441                 }
442 #endif
443
444                 if (len == -1)
445                         puts ("<INTERRUPT>\n");
446                 else
447                         rc = run_command (lastcommand, flag);
448
449                 if (rc <= 0) {
450                         /* invalid command or not repeatable, forget it */
451                         lastcommand[0] = 0;
452                 }
453         }
454 #endif /*CONFIG_SYS_HUSH_PARSER*/
455 }
456
457 #ifdef CONFIG_BOOT_RETRY_TIME
458 /***************************************************************************
459  * initialize command line timeout
460  */
461 void init_cmd_timeout(void)
462 {
463         char *s = getenv ("bootretry");
464
465         if (s != NULL)
466                 retry_time = (int)simple_strtol(s, NULL, 10);
467         else
468                 retry_time =  CONFIG_BOOT_RETRY_TIME;
469
470         if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN)
471                 retry_time = CONFIG_BOOT_RETRY_MIN;
472 }
473
474 /***************************************************************************
475  * reset command line timeout to retry_time seconds
476  */
477 void reset_cmd_timeout(void)
478 {
479         endtime = endtick(retry_time);
480 }
481 #endif
482
483 #ifdef CONFIG_CMDLINE_EDITING
484
485 /*
486  * cmdline-editing related codes from vivi.
487  * Author: Janghoon Lyu <nandy@mizi.com>
488  */
489
490 #define putnstr(str,n)  do {                    \
491                 printf ("%.*s", (int)n, str);   \
492         } while (0)
493
494 #define CTL_CH(c)               ((c) - 'a' + 1)
495 #define CTL_BACKSPACE           ('\b')
496 #define DEL                     ((char)255)
497 #define DEL7                    ((char)127)
498 #define CREAD_HIST_CHAR         ('!')
499
500 #define getcmd_putch(ch)        putc(ch)
501 #define getcmd_getch()          getc()
502 #define getcmd_cbeep()          getcmd_putch('\a')
503
504 #define HIST_MAX                20
505 #define HIST_SIZE               CONFIG_SYS_CBSIZE
506
507 static int hist_max = 0;
508 static int hist_add_idx = 0;
509 static int hist_cur = -1;
510 unsigned hist_num = 0;
511
512 char* hist_list[HIST_MAX];
513 char hist_lines[HIST_MAX][HIST_SIZE + 1];        /* Save room for NULL */
514
515 #define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1)
516
517 static void hist_init(void)
518 {
519         int i;
520
521         hist_max = 0;
522         hist_add_idx = 0;
523         hist_cur = -1;
524         hist_num = 0;
525
526         for (i = 0; i < HIST_MAX; i++) {
527                 hist_list[i] = hist_lines[i];
528                 hist_list[i][0] = '\0';
529         }
530 }
531
532 static void cread_add_to_hist(char *line)
533 {
534         strcpy(hist_list[hist_add_idx], line);
535
536         if (++hist_add_idx >= HIST_MAX)
537                 hist_add_idx = 0;
538
539         if (hist_add_idx > hist_max)
540                 hist_max = hist_add_idx;
541
542         hist_num++;
543 }
544
545 static char* hist_prev(void)
546 {
547         char *ret;
548         int old_cur;
549
550         if (hist_cur < 0)
551                 return NULL;
552
553         old_cur = hist_cur;
554         if (--hist_cur < 0)
555                 hist_cur = hist_max;
556
557         if (hist_cur == hist_add_idx) {
558                 hist_cur = old_cur;
559                 ret = NULL;
560         } else
561                 ret = hist_list[hist_cur];
562
563         return (ret);
564 }
565
566 static char* hist_next(void)
567 {
568         char *ret;
569
570         if (hist_cur < 0)
571                 return NULL;
572
573         if (hist_cur == hist_add_idx)
574                 return NULL;
575
576         if (++hist_cur > hist_max)
577                 hist_cur = 0;
578
579         if (hist_cur == hist_add_idx) {
580                 ret = "";
581         } else
582                 ret = hist_list[hist_cur];
583
584         return (ret);
585 }
586
587 #ifndef CONFIG_CMDLINE_EDITING
588 static void cread_print_hist_list(void)
589 {
590         int i;
591         unsigned long n;
592
593         n = hist_num - hist_max;
594
595         i = hist_add_idx + 1;
596         while (1) {
597                 if (i > hist_max)
598                         i = 0;
599                 if (i == hist_add_idx)
600                         break;
601                 printf("%s\n", hist_list[i]);
602                 n++;
603                 i++;
604         }
605 }
606 #endif /* CONFIG_CMDLINE_EDITING */
607
608 #define BEGINNING_OF_LINE() {                   \
609         while (num) {                           \
610                 getcmd_putch(CTL_BACKSPACE);    \
611                 num--;                          \
612         }                                       \
613 }
614
615 #define ERASE_TO_EOL() {                                \
616         if (num < eol_num) {                            \
617                 printf("%*s", (int)(eol_num - num), ""); \
618                 do {                                    \
619                         getcmd_putch(CTL_BACKSPACE);    \
620                 } while (--eol_num > num);              \
621         }                                               \
622 }
623
624 #define REFRESH_TO_EOL() {                      \
625         if (num < eol_num) {                    \
626                 wlen = eol_num - num;           \
627                 putnstr(buf + num, wlen);       \
628                 num = eol_num;                  \
629         }                                       \
630 }
631
632 static void cread_add_char(char ichar, int insert, unsigned long *num,
633                unsigned long *eol_num, char *buf, unsigned long len)
634 {
635         unsigned long wlen;
636
637         /* room ??? */
638         if (insert || *num == *eol_num) {
639                 if (*eol_num > len - 1) {
640                         getcmd_cbeep();
641                         return;
642                 }
643                 (*eol_num)++;
644         }
645
646         if (insert) {
647                 wlen = *eol_num - *num;
648                 if (wlen > 1) {
649                         memmove(&buf[*num+1], &buf[*num], wlen-1);
650                 }
651
652                 buf[*num] = ichar;
653                 putnstr(buf + *num, wlen);
654                 (*num)++;
655                 while (--wlen) {
656                         getcmd_putch(CTL_BACKSPACE);
657                 }
658         } else {
659                 /* echo the character */
660                 wlen = 1;
661                 buf[*num] = ichar;
662                 putnstr(buf + *num, wlen);
663                 (*num)++;
664         }
665 }
666
667 static void cread_add_str(char *str, int strsize, int insert, unsigned long *num,
668               unsigned long *eol_num, char *buf, unsigned long len)
669 {
670         while (strsize--) {
671                 cread_add_char(*str, insert, num, eol_num, buf, len);
672                 str++;
673         }
674 }
675
676 static int cread_line(const char *const prompt, char *buf, unsigned int *len)
677 {
678         unsigned long num = 0;
679         unsigned long eol_num = 0;
680         unsigned long wlen;
681         char ichar;
682         int insert = 1;
683         int esc_len = 0;
684         char esc_save[8];
685         int init_len = strlen(buf);
686
687         if (init_len)
688                 cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len);
689
690         while (1) {
691 #ifdef CONFIG_BOOT_RETRY_TIME
692                 while (!tstc()) {       /* while no incoming data */
693                         if (retry_time >= 0 && get_ticks() > endtime)
694                                 return (-2);    /* timed out */
695                         WATCHDOG_RESET();
696                 }
697 #endif
698
699                 ichar = getcmd_getch();
700
701                 if ((ichar == '\n') || (ichar == '\r')) {
702                         putc('\n');
703                         break;
704                 }
705
706                 /*
707                  * handle standard linux xterm esc sequences for arrow key, etc.
708                  */
709                 if (esc_len != 0) {
710                         if (esc_len == 1) {
711                                 if (ichar == '[') {
712                                         esc_save[esc_len] = ichar;
713                                         esc_len = 2;
714                                 } else {
715                                         cread_add_str(esc_save, esc_len, insert,
716                                                       &num, &eol_num, buf, *len);
717                                         esc_len = 0;
718                                 }
719                                 continue;
720                         }
721
722                         switch (ichar) {
723
724                         case 'D':       /* <- key */
725                                 ichar = CTL_CH('b');
726                                 esc_len = 0;
727                                 break;
728                         case 'C':       /* -> key */
729                                 ichar = CTL_CH('f');
730                                 esc_len = 0;
731                                 break;  /* pass off to ^F handler */
732                         case 'H':       /* Home key */
733                                 ichar = CTL_CH('a');
734                                 esc_len = 0;
735                                 break;  /* pass off to ^A handler */
736                         case 'A':       /* up arrow */
737                                 ichar = CTL_CH('p');
738                                 esc_len = 0;
739                                 break;  /* pass off to ^P handler */
740                         case 'B':       /* down arrow */
741                                 ichar = CTL_CH('n');
742                                 esc_len = 0;
743                                 break;  /* pass off to ^N handler */
744                         default:
745                                 esc_save[esc_len++] = ichar;
746                                 cread_add_str(esc_save, esc_len, insert,
747                                               &num, &eol_num, buf, *len);
748                                 esc_len = 0;
749                                 continue;
750                         }
751                 }
752
753                 switch (ichar) {
754                 case 0x1b:
755                         if (esc_len == 0) {
756                                 esc_save[esc_len] = ichar;
757                                 esc_len = 1;
758                         } else {
759                                 puts("impossible condition #876\n");
760                                 esc_len = 0;
761                         }
762                         break;
763
764                 case CTL_CH('a'):
765                         BEGINNING_OF_LINE();
766                         break;
767                 case CTL_CH('c'):       /* ^C - break */
768                         *buf = '\0';    /* discard input */
769                         return (-1);
770                 case CTL_CH('f'):
771                         if (num < eol_num) {
772                                 getcmd_putch(buf[num]);
773                                 num++;
774                         }
775                         break;
776                 case CTL_CH('b'):
777                         if (num) {
778                                 getcmd_putch(CTL_BACKSPACE);
779                                 num--;
780                         }
781                         break;
782                 case CTL_CH('d'):
783                         if (num < eol_num) {
784                                 wlen = eol_num - num - 1;
785                                 if (wlen) {
786                                         memmove(&buf[num], &buf[num+1], wlen);
787                                         putnstr(buf + num, wlen);
788                                 }
789
790                                 getcmd_putch(' ');
791                                 do {
792                                         getcmd_putch(CTL_BACKSPACE);
793                                 } while (wlen--);
794                                 eol_num--;
795                         }
796                         break;
797                 case CTL_CH('k'):
798                         ERASE_TO_EOL();
799                         break;
800                 case CTL_CH('e'):
801                         REFRESH_TO_EOL();
802                         break;
803                 case CTL_CH('o'):
804                         insert = !insert;
805                         break;
806                 case CTL_CH('x'):
807                 case CTL_CH('u'):
808                         BEGINNING_OF_LINE();
809                         ERASE_TO_EOL();
810                         break;
811                 case DEL:
812                 case DEL7:
813                 case 8:
814                         if (num) {
815                                 wlen = eol_num - num;
816                                 num--;
817                                 memmove(&buf[num], &buf[num+1], wlen);
818                                 getcmd_putch(CTL_BACKSPACE);
819                                 putnstr(buf + num, wlen);
820                                 getcmd_putch(' ');
821                                 do {
822                                         getcmd_putch(CTL_BACKSPACE);
823                                 } while (wlen--);
824                                 eol_num--;
825                         }
826                         break;
827                 case CTL_CH('p'):
828                 case CTL_CH('n'):
829                 {
830                         char * hline;
831
832                         esc_len = 0;
833
834                         if (ichar == CTL_CH('p'))
835                                 hline = hist_prev();
836                         else
837                                 hline = hist_next();
838
839                         if (!hline) {
840                                 getcmd_cbeep();
841                                 continue;
842                         }
843
844                         /* nuke the current line */
845                         /* first, go home */
846                         BEGINNING_OF_LINE();
847
848                         /* erase to end of line */
849                         ERASE_TO_EOL();
850
851                         /* copy new line into place and display */
852                         strcpy(buf, hline);
853                         eol_num = strlen(buf);
854                         REFRESH_TO_EOL();
855                         continue;
856                 }
857 #ifdef CONFIG_AUTO_COMPLETE
858                 case '\t': {
859                         int num2, col;
860
861                         /* do not autocomplete when in the middle */
862                         if (num < eol_num) {
863                                 getcmd_cbeep();
864                                 break;
865                         }
866
867                         buf[num] = '\0';
868                         col = strlen(prompt) + eol_num;
869                         num2 = num;
870                         if (cmd_auto_complete(prompt, buf, &num2, &col)) {
871                                 col = num2 - num;
872                                 num += col;
873                                 eol_num += col;
874                         }
875                         break;
876                 }
877 #endif
878                 default:
879                         cread_add_char(ichar, insert, &num, &eol_num, buf, *len);
880                         break;
881                 }
882         }
883         *len = eol_num;
884         buf[eol_num] = '\0';    /* lose the newline */
885
886         if (buf[0] && buf[0] != CREAD_HIST_CHAR)
887                 cread_add_to_hist(buf);
888         hist_cur = hist_add_idx;
889
890         return 0;
891 }
892
893 #endif /* CONFIG_CMDLINE_EDITING */
894
895 /****************************************************************************/
896
897 /*
898  * Prompt for input and read a line.
899  * If  CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0,
900  * time out when time goes past endtime (timebase time in ticks).
901  * Return:      number of read characters
902  *              -1 if break
903  *              -2 if timed out
904  */
905 int readline (const char *const prompt)
906 {
907         /*
908          * If console_buffer isn't 0-length the user will be prompted to modify
909          * it instead of entering it from scratch as desired.
910          */
911         console_buffer[0] = '\0';
912
913         return readline_into_buffer(prompt, console_buffer);
914 }
915
916
917 int readline_into_buffer (const char *const prompt, char * buffer)
918 {
919         char *p = buffer;
920 #ifdef CONFIG_CMDLINE_EDITING
921         unsigned int len = CONFIG_SYS_CBSIZE;
922         int rc;
923         static int initted = 0;
924
925         /*
926          * History uses a global array which is not
927          * writable until after relocation to RAM.
928          * Revert to non-history version if still
929          * running from flash.
930          */
931         if (gd->flags & GD_FLG_RELOC) {
932                 if (!initted) {
933                         hist_init();
934                         initted = 1;
935                 }
936
937                 if (prompt)
938                         puts (prompt);
939
940                 rc = cread_line(prompt, p, &len);
941                 return rc < 0 ? rc : len;
942
943         } else {
944 #endif  /* CONFIG_CMDLINE_EDITING */
945         char * p_buf = p;
946         int     n = 0;                          /* buffer index         */
947         int     plen = 0;                       /* prompt length        */
948         int     col;                            /* output column cnt    */
949         char    c;
950
951         /* print prompt */
952         if (prompt) {
953                 plen = strlen (prompt);
954                 puts (prompt);
955         }
956         col = plen;
957
958         for (;;) {
959 #ifdef CONFIG_BOOT_RETRY_TIME
960                 while (!tstc()) {       /* while no incoming data */
961                         if (retry_time >= 0 && get_ticks() > endtime)
962                                 return (-2);    /* timed out */
963                         WATCHDOG_RESET();
964                 }
965 #endif
966                 WATCHDOG_RESET();               /* Trigger watchdog, if needed */
967
968 #ifdef CONFIG_SHOW_ACTIVITY
969                 while (!tstc()) {
970                         extern void show_activity(int arg);
971                         show_activity(0);
972                         WATCHDOG_RESET();
973                 }
974 #endif
975                 c = getc();
976
977                 /*
978                  * Special character handling
979                  */
980                 switch (c) {
981                 case '\r':                              /* Enter                */
982                 case '\n':
983                         *p = '\0';
984                         puts ("\r\n");
985                         return (p - p_buf);
986
987                 case '\0':                              /* nul                  */
988                         continue;
989
990                 case 0x03:                              /* ^C - break           */
991                         p_buf[0] = '\0';        /* discard input */
992                         return (-1);
993
994                 case 0x15:                              /* ^U - erase line      */
995                         while (col > plen) {
996                                 puts (erase_seq);
997                                 --col;
998                         }
999                         p = p_buf;
1000                         n = 0;
1001                         continue;
1002
1003                 case 0x17:                              /* ^W - erase word      */
1004                         p=delete_char(p_buf, p, &col, &n, plen);
1005                         while ((n > 0) && (*p != ' ')) {
1006                                 p=delete_char(p_buf, p, &col, &n, plen);
1007                         }
1008                         continue;
1009
1010                 case 0x08:                              /* ^H  - backspace      */
1011                 case 0x7F:                              /* DEL - backspace      */
1012                         p=delete_char(p_buf, p, &col, &n, plen);
1013                         continue;
1014
1015                 default:
1016                         /*
1017                          * Must be a normal character then
1018                          */
1019                         if (n < CONFIG_SYS_CBSIZE-2) {
1020                                 if (c == '\t') {        /* expand TABs          */
1021 #ifdef CONFIG_AUTO_COMPLETE
1022                                         /* if auto completion triggered just continue */
1023                                         *p = '\0';
1024                                         if (cmd_auto_complete(prompt, console_buffer, &n, &col)) {
1025                                                 p = p_buf + n;  /* reset */
1026                                                 continue;
1027                                         }
1028 #endif
1029                                         puts (tab_seq+(col&07));
1030                                         col += 8 - (col&07);
1031                                 } else {
1032                                         ++col;          /* echo input           */
1033                                         putc (c);
1034                                 }
1035                                 *p++ = c;
1036                                 ++n;
1037                         } else {                        /* Buffer full          */
1038                                 putc ('\a');
1039                         }
1040                 }
1041         }
1042 #ifdef CONFIG_CMDLINE_EDITING
1043         }
1044 #endif
1045 }
1046
1047 /****************************************************************************/
1048
1049 static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen)
1050 {
1051         char *s;
1052
1053         if (*np == 0) {
1054                 return (p);
1055         }
1056
1057         if (*(--p) == '\t') {                   /* will retype the whole line   */
1058                 while (*colp > plen) {
1059                         puts (erase_seq);
1060                         (*colp)--;
1061                 }
1062                 for (s=buffer; s<p; ++s) {
1063                         if (*s == '\t') {
1064                                 puts (tab_seq+((*colp) & 07));
1065                                 *colp += 8 - ((*colp) & 07);
1066                         } else {
1067                                 ++(*colp);
1068                                 putc (*s);
1069                         }
1070                 }
1071         } else {
1072                 puts (erase_seq);
1073                 (*colp)--;
1074         }
1075         (*np)--;
1076         return (p);
1077 }
1078
1079 /****************************************************************************/
1080
1081 int parse_line (char *line, char *argv[])
1082 {
1083         int nargs = 0;
1084
1085 #ifdef DEBUG_PARSER
1086         printf ("parse_line: \"%s\"\n", line);
1087 #endif
1088         while (nargs < CONFIG_SYS_MAXARGS) {
1089
1090                 /* skip any white space */
1091                 while ((*line == ' ') || (*line == '\t')) {
1092                         ++line;
1093                 }
1094
1095                 if (*line == '\0') {    /* end of line, no more args    */
1096                         argv[nargs] = NULL;
1097 #ifdef DEBUG_PARSER
1098                 printf ("parse_line: nargs=%d\n", nargs);
1099 #endif
1100                         return (nargs);
1101                 }
1102
1103                 argv[nargs++] = line;   /* begin of argument string     */
1104
1105                 /* find end of string */
1106                 while (*line && (*line != ' ') && (*line != '\t')) {
1107                         ++line;
1108                 }
1109
1110                 if (*line == '\0') {    /* end of line, no more args    */
1111                         argv[nargs] = NULL;
1112 #ifdef DEBUG_PARSER
1113                 printf ("parse_line: nargs=%d\n", nargs);
1114 #endif
1115                         return (nargs);
1116                 }
1117
1118                 *line++ = '\0';         /* terminate current arg         */
1119         }
1120
1121         printf ("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS);
1122
1123 #ifdef DEBUG_PARSER
1124         printf ("parse_line: nargs=%d\n", nargs);
1125 #endif
1126         return (nargs);
1127 }
1128
1129 /****************************************************************************/
1130
1131 static void process_macros (const char *input, char *output)
1132 {
1133         char c, prev;
1134         const char *varname_start = NULL;
1135         int inputcnt = strlen (input);
1136         int outputcnt = CONFIG_SYS_CBSIZE;
1137         int state = 0;          /* 0 = waiting for '$'  */
1138
1139         /* 1 = waiting for '(' or '{' */
1140         /* 2 = waiting for ')' or '}' */
1141         /* 3 = waiting for '''  */
1142 #ifdef DEBUG_PARSER
1143         char *output_start = output;
1144
1145         printf ("[PROCESS_MACROS] INPUT len %d: \"%s\"\n", strlen (input),
1146                 input);
1147 #endif
1148
1149         prev = '\0';            /* previous character   */
1150
1151         while (inputcnt && outputcnt) {
1152                 c = *input++;
1153                 inputcnt--;
1154
1155                 if (state != 3) {
1156                         /* remove one level of escape characters */
1157                         if ((c == '\\') && (prev != '\\')) {
1158                                 if (inputcnt-- == 0)
1159                                         break;
1160                                 prev = c;
1161                                 c = *input++;
1162                         }
1163                 }
1164
1165                 switch (state) {
1166                 case 0: /* Waiting for (unescaped) $    */
1167                         if ((c == '\'') && (prev != '\\')) {
1168                                 state = 3;
1169                                 break;
1170                         }
1171                         if ((c == '$') && (prev != '\\')) {
1172                                 state++;
1173                         } else {
1174                                 *(output++) = c;
1175                                 outputcnt--;
1176                         }
1177                         break;
1178                 case 1: /* Waiting for (        */
1179                         if (c == '(' || c == '{') {
1180                                 state++;
1181                                 varname_start = input;
1182                         } else {
1183                                 state = 0;
1184                                 *(output++) = '$';
1185                                 outputcnt--;
1186
1187                                 if (outputcnt) {
1188                                         *(output++) = c;
1189                                         outputcnt--;
1190                                 }
1191                         }
1192                         break;
1193                 case 2: /* Waiting for )        */
1194                         if (c == ')' || c == '}') {
1195                                 int i;
1196                                 char envname[CONFIG_SYS_CBSIZE], *envval;
1197                                 int envcnt = input - varname_start - 1; /* Varname # of chars */
1198
1199                                 /* Get the varname */
1200                                 for (i = 0; i < envcnt; i++) {
1201                                         envname[i] = varname_start[i];
1202                                 }
1203                                 envname[i] = 0;
1204
1205                                 /* Get its value */
1206                                 envval = getenv (envname);
1207
1208                                 /* Copy into the line if it exists */
1209                                 if (envval != NULL)
1210                                         while ((*envval) && outputcnt) {
1211                                                 *(output++) = *(envval++);
1212                                                 outputcnt--;
1213                                         }
1214                                 /* Look for another '$' */
1215                                 state = 0;
1216                         }
1217                         break;
1218                 case 3: /* Waiting for '        */
1219                         if ((c == '\'') && (prev != '\\')) {
1220                                 state = 0;
1221                         } else {
1222                                 *(output++) = c;
1223                                 outputcnt--;
1224                         }
1225                         break;
1226                 }
1227                 prev = c;
1228         }
1229
1230         if (outputcnt)
1231                 *output = 0;
1232         else
1233                 *(output - 1) = 0;
1234
1235 #ifdef DEBUG_PARSER
1236         printf ("[PROCESS_MACROS] OUTPUT len %d: \"%s\"\n",
1237                 strlen (output_start), output_start);
1238 #endif
1239 }
1240
1241 /****************************************************************************
1242  * returns:
1243  *      1  - command executed, repeatable
1244  *      0  - command executed but not repeatable, interrupted commands are
1245  *           always considered not repeatable
1246  *      -1 - not executed (unrecognized, bootd recursion or too many args)
1247  *           (If cmd is NULL or "" or longer than CONFIG_SYS_CBSIZE-1 it is
1248  *           considered unrecognized)
1249  *
1250  * WARNING:
1251  *
1252  * We must create a temporary copy of the command since the command we get
1253  * may be the result from getenv(), which returns a pointer directly to
1254  * the environment data, which may change magicly when the command we run
1255  * creates or modifies environment variables (like "bootp" does).
1256  */
1257
1258 int run_command (const char *cmd, int flag)
1259 {
1260         cmd_tbl_t *cmdtp;
1261         char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd          */
1262         char *token;                    /* start of token in cmdbuf     */
1263         char *sep;                      /* end of token (separator) in cmdbuf */
1264         char finaltoken[CONFIG_SYS_CBSIZE];
1265         char *str = cmdbuf;
1266         char *argv[CONFIG_SYS_MAXARGS + 1];     /* NULL terminated      */
1267         int argc, inquotes;
1268         int repeatable = 1;
1269         int rc = 0;
1270
1271 #ifdef DEBUG_PARSER
1272         printf ("[RUN_COMMAND] cmd[%p]=\"", cmd);
1273         puts (cmd ? cmd : "NULL");      /* use puts - string may be loooong */
1274         puts ("\"\n");
1275 #endif
1276
1277         clear_ctrlc();          /* forget any previous Control C */
1278
1279         if (!cmd || !*cmd) {
1280                 return -1;      /* empty command */
1281         }
1282
1283         if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {
1284                 puts ("## Command too long!\n");
1285                 return -1;
1286         }
1287
1288         strcpy (cmdbuf, cmd);
1289
1290         /* Process separators and check for invalid
1291          * repeatable commands
1292          */
1293
1294 #ifdef DEBUG_PARSER
1295         printf ("[PROCESS_SEPARATORS] %s\n", cmd);
1296 #endif
1297         while (*str) {
1298
1299                 /*
1300                  * Find separator, or string end
1301                  * Allow simple escape of ';' by writing "\;"
1302                  */
1303                 for (inquotes = 0, sep = str; *sep; sep++) {
1304                         if ((*sep=='\'') &&
1305                             (*(sep-1) != '\\'))
1306                                 inquotes=!inquotes;
1307
1308                         if (!inquotes &&
1309                             (*sep == ';') &&    /* separator            */
1310                             ( sep != str) &&    /* past string start    */
1311                             (*(sep-1) != '\\')) /* and NOT escaped      */
1312                                 break;
1313                 }
1314
1315                 /*
1316                  * Limit the token to data between separators
1317                  */
1318                 token = str;
1319                 if (*sep) {
1320                         str = sep + 1;  /* start of command for next pass */
1321                         *sep = '\0';
1322                 }
1323                 else
1324                         str = sep;      /* no more commands for next pass */
1325 #ifdef DEBUG_PARSER
1326                 printf ("token: \"%s\"\n", token);
1327 #endif
1328
1329                 /* find macros in this token and replace them */
1330                 process_macros (token, finaltoken);
1331
1332                 /* Extract arguments */
1333                 if ((argc = parse_line (finaltoken, argv)) == 0) {
1334                         rc = -1;        /* no command at all */
1335                         continue;
1336                 }
1337
1338                 /* Look up command in command table */
1339                 if ((cmdtp = find_cmd(argv[0])) == NULL) {
1340                         printf ("Unknown command '%s' - try 'help'\n", argv[0]);
1341                         rc = -1;        /* give up after bad command */
1342                         continue;
1343                 }
1344
1345                 /* found - check max args */
1346                 if (argc > cmdtp->maxargs) {
1347                         cmd_usage(cmdtp);
1348                         rc = -1;
1349                         continue;
1350                 }
1351
1352 #if defined(CONFIG_CMD_BOOTD)
1353                 /* avoid "bootd" recursion */
1354                 if (cmdtp->cmd == do_bootd) {
1355 #ifdef DEBUG_PARSER
1356                         printf ("[%s]\n", finaltoken);
1357 #endif
1358                         if (flag & CMD_FLAG_BOOTD) {
1359                                 puts ("'bootd' recursion detected\n");
1360                                 rc = -1;
1361                                 continue;
1362                         } else {
1363                                 flag |= CMD_FLAG_BOOTD;
1364                         }
1365                 }
1366 #endif
1367
1368                 /* OK - call function to do the command */
1369                 if ((cmdtp->cmd) (cmdtp, flag, argc, argv) != 0) {
1370                         rc = -1;
1371                 }
1372
1373                 repeatable &= cmdtp->repeatable;
1374
1375                 /* Did the user stop this? */
1376                 if (had_ctrlc ())
1377                         return -1;      /* if stopped then not repeatable */
1378         }
1379
1380         return rc ? rc : repeatable;
1381 }
1382
1383 /****************************************************************************/
1384
1385 #if defined(CONFIG_CMD_RUN)
1386 int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[])
1387 {
1388         int i;
1389
1390         if (argc < 2)
1391                 return cmd_usage(cmdtp);
1392
1393         for (i=1; i<argc; ++i) {
1394                 char *arg;
1395
1396                 if ((arg = getenv (argv[i])) == NULL) {
1397                         printf ("## Error: \"%s\" not defined\n", argv[i]);
1398                         return 1;
1399                 }
1400 #ifndef CONFIG_SYS_HUSH_PARSER
1401                 if (run_command (arg, flag) == -1)
1402                         return 1;
1403 #else
1404                 if (parse_string_outer(arg,
1405                     FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP) != 0)
1406                         return 1;
1407 #endif
1408         }
1409         return 0;
1410 }
1411 #endif