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