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