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