blob: 946466e9d22abed482974a3f3ab80e890365d3c5 [file] [log] [blame]
Jason Hobbs06283a62011-08-31 10:37:30 -05001/*
2 * Copyright 2010-2011 Calxeda, Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the Free
6 * Software Foundation; either version 2 of the License, or (at your option)
7 * any later version.
8 *
9 * This program is distributed in the hope it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along with
15 * this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17#include <common.h>
18#include <command.h>
19#include <malloc.h>
20#include <linux/string.h>
21#include <linux/ctype.h>
22#include <errno.h>
23#include <linux/list.h>
24
25#include "menu.h"
26
27#define MAX_TFTP_PATH_LEN 127
28
29
30/*
31 * Like getenv, but prints an error if envvar isn't defined in the
32 * environment. It always returns what getenv does, so it can be used in
33 * place of getenv without changing error handling otherwise.
34 */
35static char *from_env(char *envvar)
36{
37 char *ret;
38
39 ret = getenv(envvar);
40
41 if (!ret)
42 printf("missing environment variable: %s\n", envvar);
43
44 return ret;
45}
46
47/*
48 * Convert an ethaddr from the environment to the format used by pxelinux
49 * filenames based on mac addresses. Convert's ':' to '-', and adds "01-" to
50 * the beginning of the ethernet address to indicate a hardware type of
51 * Ethernet. Also converts uppercase hex characters into lowercase, to match
52 * pxelinux's behavior.
53 *
54 * Returns 1 for success, -ENOENT if 'ethaddr' is undefined in the
55 * environment, or some other value < 0 on error.
56 */
57static int format_mac_pxe(char *outbuf, size_t outbuf_len)
58{
59 size_t ethaddr_len;
60 char *p, *ethaddr;
61
62 ethaddr = from_env("ethaddr");
63
64 if (!ethaddr)
John Rigbybe99b9e2011-07-13 23:05:19 -060065 ethaddr = from_env("usbethaddr");
66
67 if (!ethaddr)
Jason Hobbs06283a62011-08-31 10:37:30 -050068 return -ENOENT;
69
70 ethaddr_len = strlen(ethaddr);
71
72 /*
73 * ethaddr_len + 4 gives room for "01-", ethaddr, and a NUL byte at
74 * the end.
75 */
76 if (outbuf_len < ethaddr_len + 4) {
77 printf("outbuf is too small (%d < %d)\n",
78 outbuf_len, ethaddr_len + 4);
79
80 return -EINVAL;
81 }
82
83 strcpy(outbuf, "01-");
84
85 for (p = outbuf + 3; *ethaddr; ethaddr++, p++) {
86 if (*ethaddr == ':')
87 *p = '-';
88 else
89 *p = tolower(*ethaddr);
90 }
91
92 *p = '\0';
93
94 return 1;
95}
96
97/*
98 * Returns the directory the file specified in the bootfile env variable is
99 * in. If bootfile isn't defined in the environment, return NULL, which should
100 * be interpreted as "don't prepend anything to paths".
101 */
102static int get_bootfile_path(char *bootfile_path, size_t bootfile_path_size)
103{
104 char *bootfile, *last_slash;
105 size_t path_len;
106
107 bootfile = from_env("bootfile");
108
109 if (!bootfile) {
110 bootfile_path[0] = '\0';
111 return 1;
112 }
113
114 last_slash = strrchr(bootfile, '/');
115
116 if (last_slash == NULL) {
117 bootfile_path[0] = '\0';
118 return 1;
119 }
120
121 path_len = (last_slash - bootfile) + 1;
122
123 if (bootfile_path_size < path_len) {
124 printf("bootfile_path too small. (%d < %d)\n",
125 bootfile_path_size, path_len);
126
127 return -1;
128 }
129
130 strncpy(bootfile_path, bootfile, path_len);
131
132 bootfile_path[path_len] = '\0';
133
134 return 1;
135}
136
137/*
138 * As in pxelinux, paths to files referenced from files we retrieve are
139 * relative to the location of bootfile. get_relfile takes such a path and
140 * joins it with the bootfile path to get the full path to the target file. If
141 * the bootfile path is NULL, we use file_path as is.
142 *
143 * Returns 1 for success, or < 0 on error.
144 */
145static int get_relfile(char *file_path, void *file_addr)
146{
147 size_t path_len;
148 char relfile[MAX_TFTP_PATH_LEN+1];
149 char addr_buf[10];
150 char *tftp_argv[] = {"tftp", NULL, NULL, NULL};
151 int err;
152
153 err = get_bootfile_path(relfile, sizeof(relfile));
154
155 if (err < 0)
156 return err;
157
158 path_len = strlen(file_path);
159 path_len += strlen(relfile);
160
161 if (path_len > MAX_TFTP_PATH_LEN) {
162 printf("Base path too long (%s%s)\n",
163 relfile,
164 file_path);
165
166 return -ENAMETOOLONG;
167 }
168
169 strcat(relfile, file_path);
170
171 printf("Retrieving file: %s\n", relfile);
172
173 sprintf(addr_buf, "%p", file_addr);
174
175 tftp_argv[1] = addr_buf;
176 tftp_argv[2] = relfile;
177
178 if (do_tftpb(NULL, 0, 3, tftp_argv))
179 return -ENOENT;
180
181 return 1;
182}
183
184/*
185 * Retrieve the file at 'file_path' to the locate given by 'file_addr'. If
186 * 'bootfile' was specified in the environment, the path to bootfile will be
187 * prepended to 'file_path' and the resulting path will be used.
188 *
189 * Returns 1 on success, or < 0 for error.
190 */
191static int get_pxe_file(char *file_path, void *file_addr)
192{
193 unsigned long config_file_size;
194 char *tftp_filesize;
195 int err;
196
197 err = get_relfile(file_path, file_addr);
198
199 if (err < 0)
200 return err;
201
202 /*
203 * the file comes without a NUL byte at the end, so find out its size
204 * and add the NUL byte.
205 */
206 tftp_filesize = from_env("filesize");
207
208 if (!tftp_filesize)
209 return -ENOENT;
210
211 if (strict_strtoul(tftp_filesize, 16, &config_file_size) < 0)
212 return -EINVAL;
213
214 *(char *)(file_addr + config_file_size) = '\0';
215
216 return 1;
217}
218
219#define PXELINUX_DIR "pxelinux.cfg/"
220
221/*
222 * Retrieves a file in the 'pxelinux.cfg' folder. Since this uses get_pxe_file
223 * to do the hard work, the location of the 'pxelinux.cfg' folder is generated
224 * from the bootfile path, as described above.
225 *
226 * Returns 1 on success or < 0 on error.
227 */
228static int get_pxelinux_path(char *file, void *pxefile_addr_r)
229{
230 size_t base_len = strlen(PXELINUX_DIR);
231 char path[MAX_TFTP_PATH_LEN+1];
232
233 if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
234 printf("path (%s%s) too long, skipping\n",
235 PXELINUX_DIR, file);
236 return -ENAMETOOLONG;
237 }
238
239 sprintf(path, PXELINUX_DIR "%s", file);
240
241 return get_pxe_file(path, pxefile_addr_r);
242}
243
244/*
245 * Looks for a pxe file with a name based on the pxeuuid environment variable.
246 *
247 * Returns 1 on success or < 0 on error.
248 */
249static int pxe_uuid_path(void *pxefile_addr_r)
250{
251 char *uuid_str;
252
253 uuid_str = from_env("pxeuuid");
254
255 if (!uuid_str)
256 return -ENOENT;
257
258 return get_pxelinux_path(uuid_str, pxefile_addr_r);
259}
260
261/*
262 * Looks for a pxe file with a name based on the 'ethaddr' environment
263 * variable.
264 *
265 * Returns 1 on success or < 0 on error.
266 */
267static int pxe_mac_path(void *pxefile_addr_r)
268{
269 char mac_str[21];
270 int err;
271
272 err = format_mac_pxe(mac_str, sizeof(mac_str));
273
274 if (err < 0)
275 return err;
276
277 return get_pxelinux_path(mac_str, pxefile_addr_r);
278}
279
280/*
281 * Looks for pxe files with names based on our IP address. See pxelinux
282 * documentation for details on what these file names look like. We match
283 * that exactly.
284 *
285 * Returns 1 on success or < 0 on error.
286 */
287static int pxe_ipaddr_paths(void *pxefile_addr_r)
288{
289 char ip_addr[9];
290 int mask_pos, err;
291
292 sprintf(ip_addr, "%08X", ntohl(NetOurIP));
293
294 for (mask_pos = 7; mask_pos >= 0; mask_pos--) {
295 err = get_pxelinux_path(ip_addr, pxefile_addr_r);
296
297 if (err > 0)
298 return err;
299
300 ip_addr[mask_pos] = '\0';
301 }
302
303 return -ENOENT;
304}
305
306/*
307 * Entry point for the 'pxe get' command.
308 * This Follows pxelinux's rules to download a config file from a tftp server.
309 * The file is stored at the location given by the pxefile_addr_r environment
310 * variable, which must be set.
311 *
312 * UUID comes from pxeuuid env variable, if defined
313 * MAC addr comes from ethaddr env variable, if defined
314 * IP
315 *
316 * see http://syslinux.zytor.com/wiki/index.php/PXELINUX
317 *
318 * Returns 0 on success or 1 on error.
319 */
320static int
321do_pxe_get(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
322{
323 char *pxefile_addr_str;
Jason Hobbs834c9382012-03-05 08:12:28 +0000324 unsigned long pxefile_addr_r;
Jason Hobbs06283a62011-08-31 10:37:30 -0500325 int err;
326
327 if (argc != 1)
Simon Glass4c12eeb2011-12-10 08:44:01 +0000328 return CMD_RET_USAGE;
Jason Hobbs06283a62011-08-31 10:37:30 -0500329
330
331 pxefile_addr_str = from_env("pxefile_addr_r");
332
333 if (!pxefile_addr_str)
334 return 1;
335
336 err = strict_strtoul(pxefile_addr_str, 16,
337 (unsigned long *)&pxefile_addr_r);
338 if (err < 0)
339 return 1;
340
341 /*
342 * Keep trying paths until we successfully get a file we're looking
343 * for.
344 */
Jason Hobbs834c9382012-03-05 08:12:28 +0000345 if (pxe_uuid_path((void *)pxefile_addr_r) > 0
346 || pxe_mac_path((void *)pxefile_addr_r) > 0
347 || pxe_ipaddr_paths((void *)pxefile_addr_r) > 0
348 || get_pxelinux_path("default", (void *)pxefile_addr_r) > 0) {
Jason Hobbs06283a62011-08-31 10:37:30 -0500349
350 printf("Config file found\n");
351
352 return 0;
353 }
354
355 printf("Config file not found\n");
356
357 return 1;
358}
359
360/*
361 * Wrapper to make it easier to store the file at file_path in the location
362 * specified by envaddr_name. file_path will be joined to the bootfile path,
363 * if any is specified.
364 *
365 * Returns 1 on success or < 0 on error.
366 */
367static int get_relfile_envaddr(char *file_path, char *envaddr_name)
368{
Jason Hobbs834c9382012-03-05 08:12:28 +0000369 unsigned long file_addr;
Jason Hobbs06283a62011-08-31 10:37:30 -0500370 char *envaddr;
371
372 envaddr = from_env(envaddr_name);
373
374 if (!envaddr)
375 return -ENOENT;
376
Jason Hobbs834c9382012-03-05 08:12:28 +0000377 if (strict_strtoul(envaddr, 16, &file_addr) < 0)
Jason Hobbs06283a62011-08-31 10:37:30 -0500378 return -EINVAL;
379
Jason Hobbs834c9382012-03-05 08:12:28 +0000380 return get_relfile(file_path, (void *)file_addr);
Jason Hobbs06283a62011-08-31 10:37:30 -0500381}
382
383/*
384 * A note on the pxe file parser.
385 *
386 * We're parsing files that use syslinux grammar, which has a few quirks.
387 * String literals must be recognized based on context - there is no
388 * quoting or escaping support. There's also nothing to explicitly indicate
389 * when a label section completes. We deal with that by ending a label
390 * section whenever we see a line that doesn't include.
391 *
392 * As with the syslinux family, this same file format could be reused in the
393 * future for non pxe purposes. The only action it takes during parsing that
394 * would throw this off is handling of include files. It assumes we're using
395 * pxe, and does a tftp download of a file listed as an include file in the
396 * middle of the parsing operation. That could be handled by refactoring it to
397 * take a 'include file getter' function.
398 */
399
400/*
401 * Describes a single label given in a pxe file.
402 *
403 * Create these with the 'label_create' function given below.
404 *
405 * name - the name of the menu as given on the 'menu label' line.
406 * kernel - the path to the kernel file to use for this label.
407 * append - kernel command line to use when booting this label
408 * initrd - path to the initrd to use for this label.
409 * attempted - 0 if we haven't tried to boot this label, 1 if we have.
410 * localboot - 1 if this label specified 'localboot', 0 otherwise.
411 * list - lets these form a list, which a pxe_menu struct will hold.
412 */
413struct pxe_label {
414 char *name;
Rob Herringe539d112012-03-28 05:51:34 +0000415 char *menu;
Jason Hobbs06283a62011-08-31 10:37:30 -0500416 char *kernel;
417 char *append;
418 char *initrd;
419 int attempted;
420 int localboot;
421 struct list_head list;
422};
423
424/*
425 * Describes a pxe menu as given via pxe files.
426 *
427 * title - the name of the menu as given by a 'menu title' line.
428 * default_label - the name of the default label, if any.
429 * timeout - time in tenths of a second to wait for a user key-press before
430 * booting the default label.
431 * prompt - if 0, don't prompt for a choice unless the timeout period is
432 * interrupted. If 1, always prompt for a choice regardless of
433 * timeout.
434 * labels - a list of labels defined for the menu.
435 */
436struct pxe_menu {
437 char *title;
438 char *default_label;
439 int timeout;
440 int prompt;
441 struct list_head labels;
442};
443
444/*
445 * Allocates memory for and initializes a pxe_label. This uses malloc, so the
446 * result must be free()'d to reclaim the memory.
447 *
448 * Returns NULL if malloc fails.
449 */
450static struct pxe_label *label_create(void)
451{
452 struct pxe_label *label;
453
454 label = malloc(sizeof(struct pxe_label));
455
456 if (!label)
457 return NULL;
458
459 memset(label, 0, sizeof(struct pxe_label));
460
461 return label;
462}
463
464/*
465 * Free the memory used by a pxe_label, including that used by its name,
466 * kernel, append and initrd members, if they're non NULL.
467 *
468 * So - be sure to only use dynamically allocated memory for the members of
469 * the pxe_label struct, unless you want to clean it up first. These are
470 * currently only created by the pxe file parsing code.
471 */
472static void label_destroy(struct pxe_label *label)
473{
474 if (label->name)
475 free(label->name);
476
477 if (label->kernel)
478 free(label->kernel);
479
480 if (label->append)
481 free(label->append);
482
483 if (label->initrd)
484 free(label->initrd);
485
486 free(label);
487}
488
489/*
490 * Print a label and its string members if they're defined.
491 *
492 * This is passed as a callback to the menu code for displaying each
493 * menu entry.
494 */
495static void label_print(void *data)
496{
497 struct pxe_label *label = data;
Rob Herringe539d112012-03-28 05:51:34 +0000498 const char *c = label->menu ? label->menu : label->kernel;
Jason Hobbs06283a62011-08-31 10:37:30 -0500499
Rob Herringe539d112012-03-28 05:51:34 +0000500 printf("%s:\t%s\n", label->name, c);
Jason Hobbs06283a62011-08-31 10:37:30 -0500501
502 if (label->kernel)
Rob Herringe539d112012-03-28 05:51:34 +0000503 printf("\t\tkernel: %s\n", label->kernel);
Jason Hobbs06283a62011-08-31 10:37:30 -0500504
505 if (label->append)
Rob Herringe539d112012-03-28 05:51:34 +0000506 printf("\t\tappend: %s\n", label->append);
Jason Hobbs06283a62011-08-31 10:37:30 -0500507
508 if (label->initrd)
Rob Herringe539d112012-03-28 05:51:34 +0000509 printf("\t\tinitrd: %s\n", label->initrd);
Jason Hobbs06283a62011-08-31 10:37:30 -0500510}
511
512/*
513 * Boot a label that specified 'localboot'. This requires that the 'localcmd'
514 * environment variable is defined. Its contents will be executed as U-boot
515 * command. If the label specified an 'append' line, its contents will be
516 * used to overwrite the contents of the 'bootargs' environment variable prior
517 * to running 'localcmd'.
518 *
519 * Returns 1 on success or < 0 on error.
520 */
521static int label_localboot(struct pxe_label *label)
522{
523 char *localcmd, *dupcmd;
524 int ret;
525
526 localcmd = from_env("localcmd");
527
528 if (!localcmd)
529 return -ENOENT;
530
531 /*
532 * dup the command to avoid any issues with the version of it existing
533 * in the environment changing during the execution of the command.
534 */
535 dupcmd = strdup(localcmd);
536
537 if (!dupcmd)
538 return -ENOMEM;
539
540 if (label->append)
541 setenv("bootargs", label->append);
542
543 printf("running: %s\n", dupcmd);
544
Simon Glass009dde12012-02-14 19:59:20 +0000545 ret = run_command(dupcmd, 0);
Jason Hobbs06283a62011-08-31 10:37:30 -0500546
547 free(dupcmd);
548
549 return ret;
550}
551
552/*
553 * Boot according to the contents of a pxe_label.
554 *
555 * If we can't boot for any reason, we return. A successful boot never
556 * returns.
557 *
558 * The kernel will be stored in the location given by the 'kernel_addr_r'
559 * environment variable.
560 *
561 * If the label specifies an initrd file, it will be stored in the location
562 * given by the 'ramdisk_addr_r' environment variable.
563 *
564 * If the label specifies an 'append' line, its contents will overwrite that
565 * of the 'bootargs' environment variable.
566 */
567static void label_boot(struct pxe_label *label)
568{
569 char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
570 int bootm_argc = 3;
571
572 label_print(label);
573
574 label->attempted = 1;
575
576 if (label->localboot) {
577 label_localboot(label);
578 return;
579 }
580
581 if (label->kernel == NULL) {
582 printf("No kernel given, skipping %s\n",
583 label->name);
584 return;
585 }
586
587 if (label->initrd) {
588 if (get_relfile_envaddr(label->initrd, "ramdisk_addr_r") < 0) {
589 printf("Skipping %s for failure retrieving initrd\n",
590 label->name);
591 return;
592 }
593
594 bootm_argv[2] = getenv("ramdisk_addr_r");
595 } else {
596 bootm_argv[2] = "-";
597 }
598
599 if (get_relfile_envaddr(label->kernel, "kernel_addr_r") < 0) {
600 printf("Skipping %s for failure retrieving kernel\n",
601 label->name);
602 return;
603 }
604
605 if (label->append)
606 setenv("bootargs", label->append);
607
608 bootm_argv[1] = getenv("kernel_addr_r");
609
610 /*
611 * fdt usage is optional. If there is an fdt_addr specified, we will
612 * pass it along to bootm, and adjust argc appropriately.
613 */
614 bootm_argv[3] = getenv("fdt_addr");
615
616 if (bootm_argv[3])
617 bootm_argc = 4;
618
619 do_bootm(NULL, 0, bootm_argc, bootm_argv);
620}
621
622/*
623 * Tokens for the pxe file parser.
624 */
625enum token_type {
626 T_EOL,
627 T_STRING,
628 T_EOF,
629 T_MENU,
630 T_TITLE,
631 T_TIMEOUT,
632 T_LABEL,
633 T_KERNEL,
Rob Herringa0854ad2012-03-28 05:51:35 +0000634 T_LINUX,
Jason Hobbs06283a62011-08-31 10:37:30 -0500635 T_APPEND,
636 T_INITRD,
637 T_LOCALBOOT,
638 T_DEFAULT,
639 T_PROMPT,
640 T_INCLUDE,
641 T_INVALID
642};
643
644/*
645 * A token - given by a value and a type.
646 */
647struct token {
648 char *val;
649 enum token_type type;
650};
651
652/*
653 * Keywords recognized.
654 */
655static const struct token keywords[] = {
656 {"menu", T_MENU},
657 {"title", T_TITLE},
658 {"timeout", T_TIMEOUT},
659 {"default", T_DEFAULT},
660 {"prompt", T_PROMPT},
661 {"label", T_LABEL},
662 {"kernel", T_KERNEL},
Rob Herringa0854ad2012-03-28 05:51:35 +0000663 {"linux", T_LINUX},
Jason Hobbs06283a62011-08-31 10:37:30 -0500664 {"localboot", T_LOCALBOOT},
665 {"append", T_APPEND},
666 {"initrd", T_INITRD},
667 {"include", T_INCLUDE},
668 {NULL, T_INVALID}
669};
670
671/*
672 * Since pxe(linux) files don't have a token to identify the start of a
673 * literal, we have to keep track of when we're in a state where a literal is
674 * expected vs when we're in a state a keyword is expected.
675 */
676enum lex_state {
677 L_NORMAL = 0,
678 L_KEYWORD,
679 L_SLITERAL
680};
681
682/*
683 * get_string retrieves a string from *p and stores it as a token in
684 * *t.
685 *
686 * get_string used for scanning both string literals and keywords.
687 *
688 * Characters from *p are copied into t-val until a character equal to
689 * delim is found, or a NUL byte is reached. If delim has the special value of
690 * ' ', any whitespace character will be used as a delimiter.
691 *
692 * If lower is unequal to 0, uppercase characters will be converted to
693 * lowercase in the result. This is useful to make keywords case
694 * insensitive.
695 *
696 * The location of *p is updated to point to the first character after the end
697 * of the token - the ending delimiter.
698 *
699 * On success, the new value of t->val is returned. Memory for t->val is
700 * allocated using malloc and must be free()'d to reclaim it. If insufficient
701 * memory is available, NULL is returned.
702 */
703static char *get_string(char **p, struct token *t, char delim, int lower)
704{
705 char *b, *e;
706 size_t len, i;
707
708 /*
709 * b and e both start at the beginning of the input stream.
710 *
711 * e is incremented until we find the ending delimiter, or a NUL byte
712 * is reached. Then, we take e - b to find the length of the token.
713 */
714 b = e = *p;
715
716 while (*e) {
717 if ((delim == ' ' && isspace(*e)) || delim == *e)
718 break;
719 e++;
720 }
721
722 len = e - b;
723
724 /*
725 * Allocate memory to hold the string, and copy it in, converting
726 * characters to lowercase if lower is != 0.
727 */
728 t->val = malloc(len + 1);
729 if (!t->val)
730 return NULL;
731
732 for (i = 0; i < len; i++, b++) {
733 if (lower)
734 t->val[i] = tolower(*b);
735 else
736 t->val[i] = *b;
737 }
738
739 t->val[len] = '\0';
740
741 /*
742 * Update *p so the caller knows where to continue scanning.
743 */
744 *p = e;
745
746 t->type = T_STRING;
747
748 return t->val;
749}
750
751/*
752 * Populate a keyword token with a type and value.
753 */
754static void get_keyword(struct token *t)
755{
756 int i;
757
758 for (i = 0; keywords[i].val; i++) {
759 if (!strcmp(t->val, keywords[i].val)) {
760 t->type = keywords[i].type;
761 break;
762 }
763 }
764}
765
766/*
767 * Get the next token. We have to keep track of which state we're in to know
768 * if we're looking to get a string literal or a keyword.
769 *
770 * *p is updated to point at the first character after the current token.
771 */
772static void get_token(char **p, struct token *t, enum lex_state state)
773{
774 char *c = *p;
775
776 t->type = T_INVALID;
777
778 /* eat non EOL whitespace */
779 while (isblank(*c))
780 c++;
781
782 /*
783 * eat comments. note that string literals can't begin with #, but
784 * can contain a # after their first character.
785 */
786 if (*c == '#') {
787 while (*c && *c != '\n')
788 c++;
789 }
790
791 if (*c == '\n') {
792 t->type = T_EOL;
793 c++;
794 } else if (*c == '\0') {
795 t->type = T_EOF;
796 c++;
797 } else if (state == L_SLITERAL) {
798 get_string(&c, t, '\n', 0);
799 } else if (state == L_KEYWORD) {
800 /*
801 * when we expect a keyword, we first get the next string
802 * token delimited by whitespace, and then check if it
803 * matches a keyword in our keyword list. if it does, it's
804 * converted to a keyword token of the appropriate type, and
805 * if not, it remains a string token.
806 */
807 get_string(&c, t, ' ', 1);
808 get_keyword(t);
809 }
810
811 *p = c;
812}
813
814/*
815 * Increment *c until we get to the end of the current line, or EOF.
816 */
817static void eol_or_eof(char **c)
818{
819 while (**c && **c != '\n')
820 (*c)++;
821}
822
823/*
824 * All of these parse_* functions share some common behavior.
825 *
826 * They finish with *c pointing after the token they parse, and return 1 on
827 * success, or < 0 on error.
828 */
829
830/*
831 * Parse a string literal and store a pointer it at *dst. String literals
832 * terminate at the end of the line.
833 */
834static int parse_sliteral(char **c, char **dst)
835{
836 struct token t;
837 char *s = *c;
838
839 get_token(c, &t, L_SLITERAL);
840
841 if (t.type != T_STRING) {
842 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
843 return -EINVAL;
844 }
845
846 *dst = t.val;
847
848 return 1;
849}
850
851/*
852 * Parse a base 10 (unsigned) integer and store it at *dst.
853 */
854static int parse_integer(char **c, int *dst)
855{
856 struct token t;
857 char *s = *c;
858 unsigned long temp;
859
860 get_token(c, &t, L_SLITERAL);
861
862 if (t.type != T_STRING) {
863 printf("Expected string: %.*s\n", (int)(*c - s), s);
864 return -EINVAL;
865 }
866
867 if (strict_strtoul(t.val, 10, &temp) < 0) {
868 printf("Expected unsigned integer: %s\n", t.val);
869 return -EINVAL;
870 }
871
872 *dst = (int)temp;
873
874 free(t.val);
875
876 return 1;
877}
878
879static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level);
880
881/*
882 * Parse an include statement, and retrieve and parse the file it mentions.
883 *
884 * base should point to a location where it's safe to store the file, and
885 * nest_level should indicate how many nested includes have occurred. For this
886 * include, nest_level has already been incremented and doesn't need to be
887 * incremented here.
888 */
889static int handle_include(char **c, char *base,
890 struct pxe_menu *cfg, int nest_level)
891{
892 char *include_path;
893 char *s = *c;
894 int err;
895
896 err = parse_sliteral(c, &include_path);
897
898 if (err < 0) {
899 printf("Expected include path: %.*s\n",
900 (int)(*c - s), s);
901 return err;
902 }
903
904 err = get_pxe_file(include_path, base);
905
906 if (err < 0) {
907 printf("Couldn't retrieve %s\n", include_path);
908 return err;
909 }
910
911 return parse_pxefile_top(base, cfg, nest_level);
912}
913
914/*
915 * Parse lines that begin with 'menu'.
916 *
917 * b and nest are provided to handle the 'menu include' case.
918 *
919 * b should be the address where the file currently being parsed is stored.
920 *
921 * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
922 * a file it includes, 3 when parsing a file included by that file, and so on.
923 */
924static int parse_menu(char **c, struct pxe_menu *cfg, char *b, int nest_level)
925{
926 struct token t;
927 char *s = *c;
Heiko Schocher43d4a5e2011-12-12 20:37:17 +0000928 int err = 0;
Jason Hobbs06283a62011-08-31 10:37:30 -0500929
930 get_token(c, &t, L_KEYWORD);
931
932 switch (t.type) {
933 case T_TITLE:
934 err = parse_sliteral(c, &cfg->title);
935
936 break;
937
938 case T_INCLUDE:
939 err = handle_include(c, b + strlen(b) + 1, cfg,
940 nest_level + 1);
941 break;
942
943 default:
944 printf("Ignoring malformed menu command: %.*s\n",
945 (int)(*c - s), s);
946 }
947
948 if (err < 0)
949 return err;
950
951 eol_or_eof(c);
952
953 return 1;
954}
955
956/*
957 * Handles parsing a 'menu line' when we're parsing a label.
958 */
959static int parse_label_menu(char **c, struct pxe_menu *cfg,
960 struct pxe_label *label)
961{
962 struct token t;
963 char *s;
964
965 s = *c;
966
967 get_token(c, &t, L_KEYWORD);
968
969 switch (t.type) {
970 case T_DEFAULT:
971 if (cfg->default_label)
972 free(cfg->default_label);
973
974 cfg->default_label = strdup(label->name);
975
976 if (!cfg->default_label)
977 return -ENOMEM;
978
979 break;
Rob Herringe539d112012-03-28 05:51:34 +0000980 case T_LABEL:
981 parse_sliteral(c, &label->menu);
982 break;
Jason Hobbs06283a62011-08-31 10:37:30 -0500983 default:
984 printf("Ignoring malformed menu command: %.*s\n",
985 (int)(*c - s), s);
986 }
987
988 eol_or_eof(c);
989
990 return 0;
991}
992
993/*
994 * Parses a label and adds it to the list of labels for a menu.
995 *
996 * A label ends when we either get to the end of a file, or
997 * get some input we otherwise don't have a handler defined
998 * for.
999 *
1000 */
1001static int parse_label(char **c, struct pxe_menu *cfg)
1002{
1003 struct token t;
1004 char *s = *c;
1005 struct pxe_label *label;
1006 int err;
1007
1008 label = label_create();
1009 if (!label)
1010 return -ENOMEM;
1011
1012 err = parse_sliteral(c, &label->name);
1013 if (err < 0) {
1014 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1015 label_destroy(label);
1016 return -EINVAL;
1017 }
1018
1019 list_add_tail(&label->list, &cfg->labels);
1020
1021 while (1) {
1022 s = *c;
1023 get_token(c, &t, L_KEYWORD);
1024
1025 err = 0;
1026 switch (t.type) {
1027 case T_MENU:
1028 err = parse_label_menu(c, cfg, label);
1029 break;
1030
1031 case T_KERNEL:
Rob Herringa0854ad2012-03-28 05:51:35 +00001032 case T_LINUX:
Jason Hobbs06283a62011-08-31 10:37:30 -05001033 err = parse_sliteral(c, &label->kernel);
1034 break;
1035
1036 case T_APPEND:
1037 err = parse_sliteral(c, &label->append);
1038 break;
1039
1040 case T_INITRD:
1041 err = parse_sliteral(c, &label->initrd);
1042 break;
1043
1044 case T_LOCALBOOT:
1045 err = parse_integer(c, &label->localboot);
1046 break;
1047
1048 case T_EOL:
1049 break;
1050
1051 default:
1052 /*
1053 * put the token back! we don't want it - it's the end
1054 * of a label and whatever token this is, it's
1055 * something for the menu level context to handle.
1056 */
1057 *c = s;
1058 return 1;
1059 }
1060
1061 if (err < 0)
1062 return err;
1063 }
1064}
1065
1066/*
1067 * This 16 comes from the limit pxelinux imposes on nested includes.
1068 *
1069 * There is no reason at all we couldn't do more, but some limit helps prevent
1070 * infinite (until crash occurs) recursion if a file tries to include itself.
1071 */
1072#define MAX_NEST_LEVEL 16
1073
1074/*
1075 * Entry point for parsing a menu file. nest_level indicates how many times
1076 * we've nested in includes. It will be 1 for the top level menu file.
1077 *
1078 * Returns 1 on success, < 0 on error.
1079 */
1080static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level)
1081{
1082 struct token t;
1083 char *s, *b, *label_name;
1084 int err;
1085
1086 b = p;
1087
1088 if (nest_level > MAX_NEST_LEVEL) {
1089 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1090 return -EMLINK;
1091 }
1092
1093 while (1) {
1094 s = p;
1095
1096 get_token(&p, &t, L_KEYWORD);
1097
1098 err = 0;
1099 switch (t.type) {
1100 case T_MENU:
1101 err = parse_menu(&p, cfg, b, nest_level);
1102 break;
1103
1104 case T_TIMEOUT:
1105 err = parse_integer(&p, &cfg->timeout);
1106 break;
1107
1108 case T_LABEL:
1109 err = parse_label(&p, cfg);
1110 break;
1111
1112 case T_DEFAULT:
1113 err = parse_sliteral(&p, &label_name);
1114
1115 if (label_name) {
1116 if (cfg->default_label)
1117 free(cfg->default_label);
1118
1119 cfg->default_label = label_name;
1120 }
1121
1122 break;
1123
Rob Herringf13fec52012-05-25 10:43:16 +00001124 case T_INCLUDE:
1125 err = handle_include(&p, b + ALIGN(strlen(b), 4), cfg,
1126 nest_level + 1);
1127 break;
1128
Jason Hobbs06283a62011-08-31 10:37:30 -05001129 case T_PROMPT:
1130 err = parse_integer(&p, &cfg->prompt);
1131 break;
1132
1133 case T_EOL:
1134 break;
1135
1136 case T_EOF:
1137 return 1;
1138
1139 default:
1140 printf("Ignoring unknown command: %.*s\n",
1141 (int)(p - s), s);
1142 eol_or_eof(&p);
1143 }
1144
1145 if (err < 0)
1146 return err;
1147 }
1148}
1149
1150/*
1151 * Free the memory used by a pxe_menu and its labels.
1152 */
1153static void destroy_pxe_menu(struct pxe_menu *cfg)
1154{
1155 struct list_head *pos, *n;
1156 struct pxe_label *label;
1157
1158 if (cfg->title)
1159 free(cfg->title);
1160
1161 if (cfg->default_label)
1162 free(cfg->default_label);
1163
1164 list_for_each_safe(pos, n, &cfg->labels) {
1165 label = list_entry(pos, struct pxe_label, list);
1166
1167 label_destroy(label);
1168 }
1169
1170 free(cfg);
1171}
1172
1173/*
1174 * Entry point for parsing a pxe file. This is only used for the top level
1175 * file.
1176 *
1177 * Returns NULL if there is an error, otherwise, returns a pointer to a
1178 * pxe_menu struct populated with the results of parsing the pxe file (and any
1179 * files it includes). The resulting pxe_menu struct can be free()'d by using
1180 * the destroy_pxe_menu() function.
1181 */
1182static struct pxe_menu *parse_pxefile(char *menucfg)
1183{
1184 struct pxe_menu *cfg;
1185
1186 cfg = malloc(sizeof(struct pxe_menu));
1187
1188 if (!cfg)
1189 return NULL;
1190
1191 memset(cfg, 0, sizeof(struct pxe_menu));
1192
1193 INIT_LIST_HEAD(&cfg->labels);
1194
1195 if (parse_pxefile_top(menucfg, cfg, 1) < 0) {
1196 destroy_pxe_menu(cfg);
1197 return NULL;
1198 }
1199
1200 return cfg;
1201}
1202
1203/*
1204 * Converts a pxe_menu struct into a menu struct for use with U-boot's generic
1205 * menu code.
1206 */
1207static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1208{
1209 struct pxe_label *label;
1210 struct list_head *pos;
1211 struct menu *m;
1212 int err;
1213
1214 /*
1215 * Create a menu and add items for all the labels.
1216 */
1217 m = menu_create(cfg->title, cfg->timeout, cfg->prompt, label_print);
1218
1219 if (!m)
1220 return NULL;
1221
1222 list_for_each(pos, &cfg->labels) {
1223 label = list_entry(pos, struct pxe_label, list);
1224
1225 if (menu_item_add(m, label->name, label) != 1) {
1226 menu_destroy(m);
1227 return NULL;
1228 }
1229 }
1230
1231 /*
1232 * After we've created items for each label in the menu, set the
1233 * menu's default label if one was specified.
1234 */
1235 if (cfg->default_label) {
1236 err = menu_default_set(m, cfg->default_label);
1237 if (err != 1) {
1238 if (err != -ENOENT) {
1239 menu_destroy(m);
1240 return NULL;
1241 }
1242
1243 printf("Missing default: %s\n", cfg->default_label);
1244 }
1245 }
1246
1247 return m;
1248}
1249
1250/*
1251 * Try to boot any labels we have yet to attempt to boot.
1252 */
1253static void boot_unattempted_labels(struct pxe_menu *cfg)
1254{
1255 struct list_head *pos;
1256 struct pxe_label *label;
1257
1258 list_for_each(pos, &cfg->labels) {
1259 label = list_entry(pos, struct pxe_label, list);
1260
1261 if (!label->attempted)
1262 label_boot(label);
1263 }
1264}
1265
1266/*
1267 * Boot the system as prescribed by a pxe_menu.
1268 *
1269 * Use the menu system to either get the user's choice or the default, based
1270 * on config or user input. If there is no default or user's choice,
1271 * attempted to boot labels in the order they were given in pxe files.
1272 * If the default or user's choice fails to boot, attempt to boot other
1273 * labels in the order they were given in pxe files.
1274 *
1275 * If this function returns, there weren't any labels that successfully
1276 * booted, or the user interrupted the menu selection via ctrl+c.
1277 */
1278static void handle_pxe_menu(struct pxe_menu *cfg)
1279{
1280 void *choice;
1281 struct menu *m;
1282 int err;
1283
1284 m = pxe_menu_to_menu(cfg);
1285 if (!m)
1286 return;
1287
1288 err = menu_get_choice(m, &choice);
1289
1290 menu_destroy(m);
1291
Jason Hobbs6f40f272011-11-07 03:07:15 +00001292 /*
1293 * err == 1 means we got a choice back from menu_get_choice.
1294 *
1295 * err == -ENOENT if the menu was setup to select the default but no
1296 * default was set. in that case, we should continue trying to boot
1297 * labels that haven't been attempted yet.
1298 *
1299 * otherwise, the user interrupted or there was some other error and
1300 * we give up.
1301 */
Jason Hobbs06283a62011-08-31 10:37:30 -05001302
Jason Hobbs6f40f272011-11-07 03:07:15 +00001303 if (err == 1)
1304 label_boot(choice);
1305 else if (err != -ENOENT)
1306 return;
Jason Hobbs06283a62011-08-31 10:37:30 -05001307
1308 boot_unattempted_labels(cfg);
1309}
1310
1311/*
1312 * Boots a system using a pxe file
1313 *
1314 * Returns 0 on success, 1 on error.
1315 */
1316static int
1317do_pxe_boot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1318{
1319 unsigned long pxefile_addr_r;
1320 struct pxe_menu *cfg;
1321 char *pxefile_addr_str;
1322
1323 if (argc == 1) {
1324 pxefile_addr_str = from_env("pxefile_addr_r");
1325 if (!pxefile_addr_str)
1326 return 1;
1327
1328 } else if (argc == 2) {
1329 pxefile_addr_str = argv[1];
1330 } else {
Simon Glass4c12eeb2011-12-10 08:44:01 +00001331 return CMD_RET_USAGE;
Jason Hobbs06283a62011-08-31 10:37:30 -05001332 }
1333
1334 if (strict_strtoul(pxefile_addr_str, 16, &pxefile_addr_r) < 0) {
1335 printf("Invalid pxefile address: %s\n", pxefile_addr_str);
1336 return 1;
1337 }
1338
1339 cfg = parse_pxefile((char *)(pxefile_addr_r));
1340
1341 if (cfg == NULL) {
1342 printf("Error parsing config file\n");
1343 return 1;
1344 }
1345
1346 handle_pxe_menu(cfg);
1347
1348 destroy_pxe_menu(cfg);
1349
1350 return 0;
1351}
1352
1353static cmd_tbl_t cmd_pxe_sub[] = {
1354 U_BOOT_CMD_MKENT(get, 1, 1, do_pxe_get, "", ""),
1355 U_BOOT_CMD_MKENT(boot, 2, 1, do_pxe_boot, "", "")
1356};
1357
1358int do_pxe(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1359{
1360 cmd_tbl_t *cp;
1361
1362 if (argc < 2)
Simon Glass4c12eeb2011-12-10 08:44:01 +00001363 return CMD_RET_USAGE;
Jason Hobbs06283a62011-08-31 10:37:30 -05001364
1365 /* drop initial "pxe" arg */
1366 argc--;
1367 argv++;
1368
1369 cp = find_cmd_tbl(argv[0], cmd_pxe_sub, ARRAY_SIZE(cmd_pxe_sub));
1370
1371 if (cp)
1372 return cp->cmd(cmdtp, flag, argc, argv);
1373
Simon Glass4c12eeb2011-12-10 08:44:01 +00001374 return CMD_RET_USAGE;
Jason Hobbs06283a62011-08-31 10:37:30 -05001375}
1376
1377U_BOOT_CMD(
1378 pxe, 3, 1, do_pxe,
1379 "commands to get and boot from pxe files",
1380 "get - try to retrieve a pxe file using tftp\npxe "
1381 "boot [pxefile_addr_r] - boot from the pxe file at pxefile_addr_r\n"
1382);