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