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