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