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