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