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