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