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