1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright 2010-2011 Calxeda, Inc.
4 * Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved.
16 #include <fdt_support.h>
18 #include <linux/libfdt.h>
19 #include <linux/string.h>
20 #include <linux/ctype.h>
22 #include <linux/list.h>
34 #include "pxe_utils.h"
36 #define MAX_TFTP_PATH_LEN 512
38 int pxe_get_file_size(ulong *sizep)
42 val = from_env("filesize");
46 if (strict_strtoul(val, 16, sizep) < 0)
53 * format_mac_pxe() - obtain a MAC address in the PXE format
55 * This produces a MAC-address string in the format for the current ethernet
58 * 01-aa-bb-cc-dd-ee-ff
60 * where aa-ff is the MAC address in hex
62 * @outbuf: Buffer to write string to
63 * @outbuf_len: length of buffer
64 * Return: 1 if OK, -ENOSPC if buffer is too small, -ENOENT is there is no
65 * current ethernet device
67 int format_mac_pxe(char *outbuf, size_t outbuf_len)
71 if (outbuf_len < 21) {
72 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
76 if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
79 sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
80 ethaddr[0], ethaddr[1], ethaddr[2],
81 ethaddr[3], ethaddr[4], ethaddr[5]);
87 * get_relfile() - read a file relative to the PXE file
89 * As in pxelinux, paths to files referenced from files we retrieve are
90 * relative to the location of bootfile. get_relfile takes such a path and
91 * joins it with the bootfile path to get the full path to the target file. If
92 * the bootfile path is NULL, we use file_path as is.
95 * @file_path: File path to read (relative to the PXE file)
96 * @file_addr: Address to load file to
97 * @filesizep: If not NULL, returns the file size in bytes
98 * Returns 1 for success, or < 0 on error
100 static int get_relfile(struct pxe_context *ctx, const char *file_path,
101 unsigned long file_addr, ulong *filesizep)
104 char relfile[MAX_TFTP_PATH_LEN + 1];
109 if (file_path[0] == '/' && ctx->allow_abs_path)
112 strncpy(relfile, ctx->bootdir, MAX_TFTP_PATH_LEN);
114 path_len = strlen(file_path) + strlen(relfile);
116 if (path_len > MAX_TFTP_PATH_LEN) {
117 printf("Base path too long (%s%s)\n", relfile, file_path);
119 return -ENAMETOOLONG;
122 strcat(relfile, file_path);
124 printf("Retrieving file: %s\n", relfile);
126 sprintf(addr_buf, "%lx", file_addr);
128 ret = ctx->getfile(ctx, relfile, addr_buf, &size);
130 return log_msg_ret("get", ret);
138 * get_pxe_file() - read a file
140 * The file is read and nul-terminated
143 * @file_path: File path to read (relative to the PXE file)
144 * @file_addr: Address to load file to
145 * Returns 1 for success, or < 0 on error
147 int get_pxe_file(struct pxe_context *ctx, const char *file_path,
154 err = get_relfile(ctx, file_path, file_addr, &size);
158 buf = map_sysmem(file_addr + size, 1);
165 #define PXELINUX_DIR "pxelinux.cfg/"
168 * get_pxelinux_path() - Get a file in the pxelinux.cfg/ directory
171 * @file: Filename to process (relative to pxelinux.cfg/)
172 * Returns 1 for success, -ENAMETOOLONG if the resulting path is too long.
173 * or other value < 0 on other error
175 int get_pxelinux_path(struct pxe_context *ctx, const char *file,
176 unsigned long pxefile_addr_r)
178 size_t base_len = strlen(PXELINUX_DIR);
179 char path[MAX_TFTP_PATH_LEN + 1];
181 if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
182 printf("path (%s%s) too long, skipping\n",
184 return -ENAMETOOLONG;
187 sprintf(path, PXELINUX_DIR "%s", file);
189 return get_pxe_file(ctx, path, pxefile_addr_r);
193 * get_relfile_envaddr() - read a file to an address in an env var
195 * Wrapper to make it easier to store the file at file_path in the location
196 * specified by envaddr_name. file_path will be joined to the bootfile path,
197 * if any is specified.
200 * @file_path: File path to read (relative to the PXE file)
201 * @envaddr_name: Name of environment variable which contains the address to
203 * @filesizep: Returns the file size in bytes
204 * Returns 1 on success, -ENOENT if @envaddr_name does not exist as an
205 * environment variable, -EINVAL if its format is not valid hex, or other
206 * value < 0 on other error
208 static int get_relfile_envaddr(struct pxe_context *ctx, const char *file_path,
209 const char *envaddr_name, ulong *filesizep)
211 unsigned long file_addr;
214 envaddr = from_env(envaddr_name);
218 if (strict_strtoul(envaddr, 16, &file_addr) < 0)
221 return get_relfile(ctx, file_path, file_addr, filesizep);
225 * label_create() - crate a new PXE label
227 * Allocates memory for and initializes a pxe_label. This uses malloc, so the
228 * result must be free()'d to reclaim the memory.
230 * Returns a pointer to the label, or NULL if out of memory
232 static struct pxe_label *label_create(void)
234 struct pxe_label *label;
236 label = malloc(sizeof(struct pxe_label));
240 memset(label, 0, sizeof(struct pxe_label));
246 * label_destroy() - free the memory used by a pxe_label
248 * This frees @label itself as well as memory used by its name,
249 * kernel, config, append, initrd, fdt, fdtdir and fdtoverlay members, if
252 * So - be sure to only use dynamically allocated memory for the members of
253 * the pxe_label struct, unless you want to clean it up first. These are
254 * currently only created by the pxe file parsing code.
256 * @label: Label to free
258 static void label_destroy(struct pxe_label *label)
261 free(label->kernel_label);
268 free(label->fdtoverlays);
273 * label_print() - Print a label and its string members if they're defined
275 * This is passed as a callback to the menu code for displaying each
278 * @data: Label to print (is cast to struct pxe_label *)
280 static void label_print(void *data)
282 struct pxe_label *label = data;
283 const char *c = label->menu ? label->menu : label->name;
285 printf("%s:\t%s\n", label->num, c);
289 * label_localboot() - Boot a label that specified 'localboot'
291 * This requires that the 'localcmd' environment variable is defined. Its
292 * contents will be executed as U-Boot commands. If the label specified an
293 * 'append' line, its contents will be used to overwrite the contents of the
294 * 'bootargs' environment variable prior to running 'localcmd'.
296 * @label: Label to process
297 * Returns 1 on success or < 0 on error
299 static int label_localboot(struct pxe_label *label)
303 localcmd = from_env("localcmd");
308 char bootargs[CONFIG_SYS_CBSIZE];
310 cli_simple_process_macros(label->append, bootargs,
312 env_set("bootargs", bootargs);
315 debug("running: %s\n", localcmd);
317 return run_command_list(localcmd, strlen(localcmd), 0);
321 * label_boot_kaslrseed generate kaslrseed from hw rng
324 static void label_boot_kaslrseed(void)
328 struct fdt_header *working_fdt;
335 /* Get the main fdt and map it */
336 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
337 working_fdt = map_sysmem(fdt_addr, 0);
338 err = fdt_check_header(working_fdt);
342 /* add extra size for holding kaslr-seed */
343 /* err is new fdt size, 0 or negtive */
344 err = fdt_shrink_to_minimum(working_fdt, 512);
348 if (uclass_get_device(UCLASS_RNG, 0, &dev) || !dev) {
349 printf("No RNG device\n");
353 nodeoffset = fdt_find_or_add_subnode(working_fdt, 0, "chosen");
354 if (nodeoffset < 0) {
355 printf("Reading chosen node failed\n");
361 printf("Out of memory\n");
365 if (dm_rng_read(dev, buf, n)) {
366 printf("Reading RNG failed\n");
370 err = fdt_setprop(working_fdt, nodeoffset, "kaslr-seed", buf, sizeof(buf));
372 printf("Unable to set kaslr-seed on chosen node: %s\n", fdt_strerror(err));
382 * label_boot_fdtoverlay() - Loads fdt overlays specified in 'fdtoverlays'
383 * or 'devicetree-overlay'
386 * @label: Label to process
388 #ifdef CONFIG_OF_LIBFDT_OVERLAY
389 static void label_boot_fdtoverlay(struct pxe_context *ctx,
390 struct pxe_label *label)
392 char *fdtoverlay = label->fdtoverlays;
393 struct fdt_header *working_fdt;
394 char *fdtoverlay_addr_env;
395 ulong fdtoverlay_addr;
399 /* Get the main fdt and map it */
400 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
401 working_fdt = map_sysmem(fdt_addr, 0);
402 err = fdt_check_header(working_fdt);
406 /* Get the specific overlay loading address */
407 fdtoverlay_addr_env = env_get("fdtoverlay_addr_r");
408 if (!fdtoverlay_addr_env) {
409 printf("Invalid fdtoverlay_addr_r for loading overlays\n");
413 fdtoverlay_addr = hextoul(fdtoverlay_addr_env, NULL);
415 /* Cycle over the overlay files and apply them in order */
417 struct fdt_header *blob;
422 /* Drop leading spaces */
423 while (*fdtoverlay == ' ')
426 /* Copy a single filename if multiple provided */
427 end = strstr(fdtoverlay, " ");
429 len = (int)(end - fdtoverlay);
430 overlayfile = malloc(len + 1);
431 strncpy(overlayfile, fdtoverlay, len);
432 overlayfile[len] = '\0';
434 overlayfile = fdtoverlay;
436 if (!strlen(overlayfile))
439 /* Load overlay file */
440 err = get_relfile_envaddr(ctx, overlayfile, "fdtoverlay_addr_r",
443 printf("Failed loading overlay %s\n", overlayfile);
447 /* Resize main fdt */
448 fdt_shrink_to_minimum(working_fdt, 8192);
450 blob = map_sysmem(fdtoverlay_addr, 0);
451 err = fdt_check_header(blob);
453 printf("Invalid overlay %s, skipping\n",
458 err = fdt_overlay_apply_verbose(working_fdt, blob);
460 printf("Failed to apply overlay %s, skipping\n",
468 } while ((fdtoverlay = strstr(fdtoverlay, " ")));
473 * label_boot() - Boot according to the contents of a pxe_label
475 * If we can't boot for any reason, we return. A successful boot never
478 * The kernel will be stored in the location given by the 'kernel_addr_r'
479 * environment variable.
481 * If the label specifies an initrd file, it will be stored in the location
482 * given by the 'ramdisk_addr_r' environment variable.
484 * If the label specifies an 'append' line, its contents will overwrite that
485 * of the 'bootargs' environment variable.
488 * @label: Label to process
489 * Returns does not return on success, otherwise returns 0 if a localboot
490 * label was processed, or 1 on error
492 static int label_boot(struct pxe_context *ctx, struct pxe_label *label)
494 char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
495 char *zboot_argv[] = { "zboot", NULL, "0", NULL, NULL };
496 char *kernel_addr = NULL;
497 char *initrd_addr_str = NULL;
498 char initrd_filesize[10];
500 char mac_str[29] = "";
501 char ip_str[68] = "";
502 char *fit_addr = NULL;
511 label->attempted = 1;
513 if (label->localboot) {
514 if (label->localboot_val >= 0)
515 label_localboot(label);
519 if (!label->kernel) {
520 printf("No kernel given, skipping %s\n",
525 if (get_relfile_envaddr(ctx, label->kernel, "kernel_addr_r",
527 printf("Skipping %s for failure retrieving kernel\n",
532 kernel_addr = env_get("kernel_addr_r");
533 /* for FIT, append the configuration identifier */
535 int len = strlen(kernel_addr) + strlen(label->config) + 1;
537 fit_addr = malloc(len);
539 printf("malloc fail (FIT address)\n");
542 snprintf(fit_addr, len, "%s%s", kernel_addr, label->config);
543 kernel_addr = fit_addr;
546 /* For FIT, the label can be identical to kernel one */
547 if (label->initrd && !strcmp(label->kernel_label, label->initrd)) {
548 initrd_addr_str = kernel_addr;
549 } else if (label->initrd) {
551 if (get_relfile_envaddr(ctx, label->initrd, "ramdisk_addr_r",
553 printf("Skipping %s for failure retrieving initrd\n",
558 initrd_addr_str = env_get("ramdisk_addr_r");
559 size = snprintf(initrd_str, sizeof(initrd_str), "%s:%lx",
560 initrd_addr_str, size);
561 if (size >= sizeof(initrd_str))
565 if (label->ipappend & 0x1) {
566 sprintf(ip_str, " ip=%s:%s:%s:%s",
567 env_get("ipaddr"), env_get("serverip"),
568 env_get("gatewayip"), env_get("netmask"));
571 if (IS_ENABLED(CONFIG_CMD_NET)) {
572 if (label->ipappend & 0x2) {
575 strcpy(mac_str, " BOOTIF=");
576 err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
582 if ((label->ipappend & 0x3) || label->append) {
583 char bootargs[CONFIG_SYS_CBSIZE] = "";
584 char finalbootargs[CONFIG_SYS_CBSIZE];
586 if (strlen(label->append ?: "") +
587 strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
588 printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
589 strlen(label->append ?: ""),
590 strlen(ip_str), strlen(mac_str),
596 strncpy(bootargs, label->append, sizeof(bootargs));
598 strcat(bootargs, ip_str);
599 strcat(bootargs, mac_str);
601 cli_simple_process_macros(bootargs, finalbootargs,
602 sizeof(finalbootargs));
603 env_set("bootargs", finalbootargs);
604 printf("append: %s\n", finalbootargs);
608 * fdt usage is optional:
609 * It handles the following scenarios.
611 * Scenario 1: If fdt_addr_r specified and "fdt" or "fdtdir" label is
612 * defined in pxe file, retrieve fdt blob from server. Pass fdt_addr_r to
613 * bootm, and adjust argc appropriately.
615 * If retrieve fails and no exact fdt blob is specified in pxe file with
616 * "fdt" label, try Scenario 2.
618 * Scenario 2: If there is an fdt_addr specified, pass it along to
619 * bootm, and adjust argc appropriately.
621 * Scenario 3: If there is an fdtcontroladdr specified, pass it along to
622 * bootm, and adjust argc appropriately, unless the image type is fitImage.
624 * Scenario 4: fdt blob is not available.
626 bootm_argv[3] = env_get("fdt_addr_r");
628 /* For FIT, the label can be identical to kernel one */
629 if (label->fdt && !strcmp(label->kernel_label, label->fdt)) {
630 bootm_argv[3] = kernel_addr;
631 /* if fdt label is defined then get fdt from server */
632 } else if (bootm_argv[3]) {
633 char *fdtfile = NULL;
634 char *fdtfilefree = NULL;
637 fdtfile = label->fdt;
638 } else if (label->fdtdir) {
639 char *f1, *f2, *f3, *f4, *slash;
641 f1 = env_get("fdtfile");
648 * For complex cases where this code doesn't
649 * generate the correct filename, the board
650 * code should set $fdtfile during early boot,
651 * or the boot scripts should set $fdtfile
652 * before invoking "pxe" or "sysboot".
656 f3 = env_get("board");
668 len = strlen(label->fdtdir);
671 else if (label->fdtdir[len - 1] != '/')
676 len = strlen(label->fdtdir) + strlen(slash) +
677 strlen(f1) + strlen(f2) + strlen(f3) +
679 fdtfilefree = malloc(len);
681 printf("malloc fail (FDT filename)\n");
685 snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
686 label->fdtdir, slash, f1, f2, f3, f4);
687 fdtfile = fdtfilefree;
691 int err = get_relfile_envaddr(ctx, fdtfile,
696 bootm_argv[3] = NULL;
699 printf("Skipping %s for failure retrieving FDT\n",
705 if (label->kaslrseed)
706 label_boot_kaslrseed();
708 #ifdef CONFIG_OF_LIBFDT_OVERLAY
709 if (label->fdtoverlays)
710 label_boot_fdtoverlay(ctx, label);
713 bootm_argv[3] = NULL;
717 bootm_argv[1] = kernel_addr;
718 zboot_argv[1] = kernel_addr;
720 if (initrd_addr_str) {
721 bootm_argv[2] = initrd_str;
724 zboot_argv[3] = initrd_addr_str;
725 zboot_argv[4] = initrd_filesize;
730 bootm_argv[3] = env_get("fdt_addr");
732 kernel_addr_r = genimg_get_kernel_addr(kernel_addr);
733 buf = map_sysmem(kernel_addr_r, 0);
735 if (!bootm_argv[3] && genimg_get_format(buf) != IMAGE_FORMAT_FIT)
736 bootm_argv[3] = env_get("fdtcontroladdr");
744 /* Try bootm for legacy and FIT format image */
745 if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID &&
746 IS_ENABLED(CONFIG_CMD_BOOTM))
747 do_bootm(ctx->cmdtp, 0, bootm_argc, bootm_argv);
748 /* Try booting an AArch64 Linux kernel image */
749 else if (IS_ENABLED(CONFIG_CMD_BOOTI))
750 do_booti(ctx->cmdtp, 0, bootm_argc, bootm_argv);
751 /* Try booting a Image */
752 else if (IS_ENABLED(CONFIG_CMD_BOOTZ))
753 do_bootz(ctx->cmdtp, 0, bootm_argc, bootm_argv);
754 /* Try booting an x86_64 Linux kernel image */
755 else if (IS_ENABLED(CONFIG_CMD_ZBOOT))
756 do_zboot_parent(ctx->cmdtp, 0, zboot_argc, zboot_argv, NULL);
766 /** enum token_type - Tokens for the pxe file parser */
793 /** struct token - token - given by a value and a type */
796 enum token_type type;
799 /* Keywords recognized */
800 static const struct token keywords[] = {
803 {"timeout", T_TIMEOUT},
804 {"default", T_DEFAULT},
805 {"prompt", T_PROMPT},
807 {"kernel", T_KERNEL},
809 {"localboot", T_LOCALBOOT},
810 {"append", T_APPEND},
811 {"initrd", T_INITRD},
812 {"include", T_INCLUDE},
813 {"devicetree", T_FDT},
815 {"devicetreedir", T_FDTDIR},
816 {"fdtdir", T_FDTDIR},
817 {"fdtoverlays", T_FDTOVERLAYS},
818 {"devicetree-overlay", T_FDTOVERLAYS},
819 {"ontimeout", T_ONTIMEOUT,},
820 {"ipappend", T_IPAPPEND,},
821 {"background", T_BACKGROUND,},
822 {"kaslrseed", T_KASLRSEED,},
827 * enum lex_state - lexer state
829 * Since pxe(linux) files don't have a token to identify the start of a
830 * literal, we have to keep track of when we're in a state where a literal is
831 * expected vs when we're in a state a keyword is expected.
840 * get_string() - retrieves a string from *p and stores it as a token in *t.
842 * This is used for scanning both string literals and keywords.
844 * Characters from *p are copied into t-val until a character equal to
845 * delim is found, or a NUL byte is reached. If delim has the special value of
846 * ' ', any whitespace character will be used as a delimiter.
848 * If lower is unequal to 0, uppercase characters will be converted to
849 * lowercase in the result. This is useful to make keywords case
852 * The location of *p is updated to point to the first character after the end
853 * of the token - the ending delimiter.
855 * Memory for t->val is allocated using malloc and must be free()'d to reclaim
858 * @p: Points to a pointer to the current position in the input being processed.
859 * Updated to point at the first character after the current token
860 * @t: Pointers to a token to fill in
861 * @delim: Delimiter character to look for, either newline or space
862 * @lower: true to convert the string to lower case when storing
863 * Returns the new value of t->val, on success, NULL if out of memory
865 static char *get_string(char **p, struct token *t, char delim, int lower)
871 * b and e both start at the beginning of the input stream.
873 * e is incremented until we find the ending delimiter, or a NUL byte
874 * is reached. Then, we take e - b to find the length of the token.
879 if ((delim == ' ' && isspace(*e)) || delim == *e)
887 * Allocate memory to hold the string, and copy it in, converting
888 * characters to lowercase if lower is != 0.
890 t->val = malloc(len + 1);
894 for (i = 0; i < len; i++, b++) {
896 t->val[i] = tolower(*b);
903 /* Update *p so the caller knows where to continue scanning */
911 * get_keyword() - Populate a keyword token with a type and value
913 * Updates the ->type field based on the keyword string in @val
914 * @t: Token to populate
916 static void get_keyword(struct token *t)
920 for (i = 0; keywords[i].val; i++) {
921 if (!strcmp(t->val, keywords[i].val)) {
922 t->type = keywords[i].type;
929 * get_token() - Get the next token
931 * We have to keep track of which state we're in to know if we're looking to get
932 * a string literal or a keyword.
934 * @p: Points to a pointer to the current position in the input being processed.
935 * Updated to point at the first character after the current token
937 static void get_token(char **p, struct token *t, enum lex_state state)
943 /* eat non EOL whitespace */
948 * eat comments. note that string literals can't begin with #, but
949 * can contain a # after their first character.
952 while (*c && *c != '\n')
959 } else if (*c == '\0') {
962 } else if (state == L_SLITERAL) {
963 get_string(&c, t, '\n', 0);
964 } else if (state == L_KEYWORD) {
966 * when we expect a keyword, we first get the next string
967 * token delimited by whitespace, and then check if it
968 * matches a keyword in our keyword list. if it does, it's
969 * converted to a keyword token of the appropriate type, and
970 * if not, it remains a string token.
972 get_string(&c, t, ' ', 1);
980 * eol_or_eof() - Find end of line
982 * Increment *c until we get to the end of the current line, or EOF
984 * @c: Points to a pointer to the current position in the input being processed.
985 * Updated to point at the first character after the current token
987 static void eol_or_eof(char **c)
989 while (**c && **c != '\n')
994 * All of these parse_* functions share some common behavior.
996 * They finish with *c pointing after the token they parse, and return 1 on
997 * success, or < 0 on error.
1001 * Parse a string literal and store a pointer it at *dst. String literals
1002 * terminate at the end of the line.
1004 static int parse_sliteral(char **c, char **dst)
1009 get_token(c, &t, L_SLITERAL);
1011 if (t.type != T_STRING) {
1012 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
1022 * Parse a base 10 (unsigned) integer and store it at *dst.
1024 static int parse_integer(char **c, int *dst)
1029 get_token(c, &t, L_SLITERAL);
1030 if (t.type != T_STRING) {
1031 printf("Expected string: %.*s\n", (int)(*c - s), s);
1035 *dst = simple_strtol(t.val, NULL, 10);
1042 static int parse_pxefile_top(struct pxe_context *ctx, char *p, ulong base,
1043 struct pxe_menu *cfg, int nest_level);
1046 * Parse an include statement, and retrieve and parse the file it mentions.
1048 * base should point to a location where it's safe to store the file, and
1049 * nest_level should indicate how many nested includes have occurred. For this
1050 * include, nest_level has already been incremented and doesn't need to be
1053 static int handle_include(struct pxe_context *ctx, char **c, unsigned long base,
1054 struct pxe_menu *cfg, int nest_level)
1062 err = parse_sliteral(c, &include_path);
1064 printf("Expected include path: %.*s\n", (int)(*c - s), s);
1068 err = get_pxe_file(ctx, include_path, base);
1070 printf("Couldn't retrieve %s\n", include_path);
1074 buf = map_sysmem(base, 0);
1075 ret = parse_pxefile_top(ctx, buf, base, cfg, nest_level);
1082 * Parse lines that begin with 'menu'.
1084 * base and nest are provided to handle the 'menu include' case.
1086 * base should point to a location where it's safe to store the included file.
1088 * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1089 * a file it includes, 3 when parsing a file included by that file, and so on.
1091 static int parse_menu(struct pxe_context *ctx, char **c, struct pxe_menu *cfg,
1092 unsigned long base, int nest_level)
1098 get_token(c, &t, L_KEYWORD);
1102 err = parse_sliteral(c, &cfg->title);
1107 err = handle_include(ctx, c, base, cfg, nest_level + 1);
1111 err = parse_sliteral(c, &cfg->bmp);
1115 printf("Ignoring malformed menu command: %.*s\n",
1127 * Handles parsing a 'menu line' when we're parsing a label.
1129 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1130 struct pxe_label *label)
1137 get_token(c, &t, L_KEYWORD);
1141 if (!cfg->default_label)
1142 cfg->default_label = strdup(label->name);
1144 if (!cfg->default_label)
1149 parse_sliteral(c, &label->menu);
1152 printf("Ignoring malformed menu command: %.*s\n",
1162 * Handles parsing a 'kernel' label.
1163 * expecting "filename" or "<fit_filename>#cfg"
1165 static int parse_label_kernel(char **c, struct pxe_label *label)
1170 err = parse_sliteral(c, &label->kernel);
1174 /* copy the kernel label to compare with FDT / INITRD when FIT is used */
1175 label->kernel_label = strdup(label->kernel);
1176 if (!label->kernel_label)
1179 s = strstr(label->kernel, "#");
1183 label->config = strdup(s);
1193 * Parses a label and adds it to the list of labels for a menu.
1195 * A label ends when we either get to the end of a file, or
1196 * get some input we otherwise don't have a handler defined
1200 static int parse_label(char **c, struct pxe_menu *cfg)
1205 struct pxe_label *label;
1208 label = label_create();
1212 err = parse_sliteral(c, &label->name);
1214 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1215 label_destroy(label);
1219 list_add_tail(&label->list, &cfg->labels);
1223 get_token(c, &t, L_KEYWORD);
1228 err = parse_label_menu(c, cfg, label);
1233 err = parse_label_kernel(c, label);
1237 err = parse_sliteral(c, &label->append);
1240 s = strstr(label->append, "initrd=");
1244 len = (int)(strchr(s, ' ') - s);
1245 label->initrd = malloc(len + 1);
1246 strncpy(label->initrd, s, len);
1247 label->initrd[len] = '\0';
1253 err = parse_sliteral(c, &label->initrd);
1258 err = parse_sliteral(c, &label->fdt);
1263 err = parse_sliteral(c, &label->fdtdir);
1267 if (!label->fdtoverlays)
1268 err = parse_sliteral(c, &label->fdtoverlays);
1272 label->localboot = 1;
1273 err = parse_integer(c, &label->localboot_val);
1277 err = parse_integer(c, &label->ipappend);
1281 label->kaslrseed = 1;
1289 * put the token back! we don't want it - it's the end
1290 * of a label and whatever token this is, it's
1291 * something for the menu level context to handle.
1303 * This 16 comes from the limit pxelinux imposes on nested includes.
1305 * There is no reason at all we couldn't do more, but some limit helps prevent
1306 * infinite (until crash occurs) recursion if a file tries to include itself.
1308 #define MAX_NEST_LEVEL 16
1311 * Entry point for parsing a menu file. nest_level indicates how many times
1312 * we've nested in includes. It will be 1 for the top level menu file.
1314 * Returns 1 on success, < 0 on error.
1316 static int parse_pxefile_top(struct pxe_context *ctx, char *p, unsigned long base,
1317 struct pxe_menu *cfg, int nest_level)
1320 char *s, *b, *label_name;
1325 if (nest_level > MAX_NEST_LEVEL) {
1326 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1333 get_token(&p, &t, L_KEYWORD);
1339 err = parse_menu(ctx, &p, cfg,
1340 base + ALIGN(strlen(b) + 1, 4),
1345 err = parse_integer(&p, &cfg->timeout);
1349 err = parse_label(&p, cfg);
1354 err = parse_sliteral(&p, &label_name);
1357 if (cfg->default_label)
1358 free(cfg->default_label);
1360 cfg->default_label = label_name;
1366 err = handle_include(ctx, &p,
1367 base + ALIGN(strlen(b), 4), cfg,
1372 err = parse_integer(&p, &cfg->prompt);
1373 // Do not fail if prompt configuration is undefined
1385 printf("Ignoring unknown command: %.*s\n",
1397 void destroy_pxe_menu(struct pxe_menu *cfg)
1399 struct list_head *pos, *n;
1400 struct pxe_label *label;
1403 free(cfg->default_label);
1405 list_for_each_safe(pos, n, &cfg->labels) {
1406 label = list_entry(pos, struct pxe_label, list);
1408 label_destroy(label);
1414 struct pxe_menu *parse_pxefile(struct pxe_context *ctx, unsigned long menucfg)
1416 struct pxe_menu *cfg;
1420 cfg = malloc(sizeof(struct pxe_menu));
1424 memset(cfg, 0, sizeof(struct pxe_menu));
1426 INIT_LIST_HEAD(&cfg->labels);
1428 buf = map_sysmem(menucfg, 0);
1429 r = parse_pxefile_top(ctx, buf, menucfg, cfg, 1);
1432 destroy_pxe_menu(cfg);
1440 * Converts a pxe_menu struct into a menu struct for use with U-Boot's generic
1443 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1445 struct pxe_label *label;
1446 struct list_head *pos;
1448 char *label_override;
1451 char *default_num = NULL;
1452 char *override_num = NULL;
1455 * Create a menu and add items for all the labels.
1457 m = menu_create(cfg->title, DIV_ROUND_UP(cfg->timeout, 10),
1458 cfg->prompt, NULL, label_print, NULL, NULL);
1462 label_override = env_get("pxe_label_override");
1464 list_for_each(pos, &cfg->labels) {
1465 label = list_entry(pos, struct pxe_label, list);
1467 sprintf(label->num, "%d", i++);
1468 if (menu_item_add(m, label->num, label) != 1) {
1472 if (cfg->default_label &&
1473 (strcmp(label->name, cfg->default_label) == 0))
1474 default_num = label->num;
1475 if (label_override && !strcmp(label->name, label_override))
1476 override_num = label->num;
1480 if (label_override) {
1482 default_num = override_num;
1484 printf("Missing override pxe label: %s\n",
1489 * After we've created items for each label in the menu, set the
1490 * menu's default label if one was specified.
1493 err = menu_default_set(m, default_num);
1495 if (err != -ENOENT) {
1500 printf("Missing default: %s\n", cfg->default_label);
1508 * Try to boot any labels we have yet to attempt to boot.
1510 static void boot_unattempted_labels(struct pxe_context *ctx,
1511 struct pxe_menu *cfg)
1513 struct list_head *pos;
1514 struct pxe_label *label;
1516 list_for_each(pos, &cfg->labels) {
1517 label = list_entry(pos, struct pxe_label, list);
1519 if (!label->attempted)
1520 label_boot(ctx, label);
1524 void handle_pxe_menu(struct pxe_context *ctx, struct pxe_menu *cfg)
1530 if (IS_ENABLED(CONFIG_CMD_BMP)) {
1531 /* display BMP if available */
1533 if (get_relfile(ctx, cfg->bmp, image_load_addr, NULL)) {
1534 #if defined(CONFIG_VIDEO)
1535 struct udevice *dev;
1537 err = uclass_first_device_err(UCLASS_VIDEO, &dev);
1541 bmp_display(image_load_addr,
1542 BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1544 printf("Skipping background bmp %s for failure\n",
1550 m = pxe_menu_to_menu(cfg);
1554 err = menu_get_choice(m, &choice);
1558 * err == 1 means we got a choice back from menu_get_choice.
1560 * err == -ENOENT if the menu was setup to select the default but no
1561 * default was set. in that case, we should continue trying to boot
1562 * labels that haven't been attempted yet.
1564 * otherwise, the user interrupted or there was some other error and
1569 err = label_boot(ctx, choice);
1572 } else if (err != -ENOENT) {
1576 boot_unattempted_labels(ctx, cfg);
1579 int pxe_setup_ctx(struct pxe_context *ctx, struct cmd_tbl *cmdtp,
1580 pxe_getfile_func getfile, void *userdata,
1581 bool allow_abs_path, const char *bootfile, bool use_ipv6)
1583 const char *last_slash;
1584 size_t path_len = 0;
1586 memset(ctx, '\0', sizeof(*ctx));
1588 ctx->getfile = getfile;
1589 ctx->userdata = userdata;
1590 ctx->allow_abs_path = allow_abs_path;
1591 ctx->use_ipv6 = use_ipv6;
1593 /* figure out the boot directory, if there is one */
1594 if (bootfile && strlen(bootfile) >= MAX_TFTP_PATH_LEN)
1596 ctx->bootdir = strdup(bootfile ? bootfile : "");
1601 last_slash = strrchr(bootfile, '/');
1603 path_len = (last_slash - bootfile) + 1;
1605 ctx->bootdir[path_len] = '\0';
1610 void pxe_destroy_ctx(struct pxe_context *ctx)
1615 int pxe_process(struct pxe_context *ctx, ulong pxefile_addr_r, bool prompt)
1617 struct pxe_menu *cfg;
1619 cfg = parse_pxefile(ctx, pxefile_addr_r);
1621 printf("Error parsing config file\n");
1628 handle_pxe_menu(ctx, cfg);
1630 destroy_pxe_menu(cfg);