1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright 2010-2011 Calxeda, Inc.
4 * Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved.
15 #include <fdt_support.h>
17 #include <linux/libfdt.h>
18 #include <linux/string.h>
19 #include <linux/ctype.h>
21 #include <linux/list.h>
31 #include "pxe_utils.h"
33 #define MAX_TFTP_PATH_LEN 512
35 int pxe_get_file_size(ulong *sizep)
39 val = from_env("filesize");
43 if (strict_strtoul(val, 16, sizep) < 0)
50 * format_mac_pxe() - obtain a MAC address in the PXE format
52 * This produces a MAC-address string in the format for the current ethernet
55 * 01-aa-bb-cc-dd-ee-ff
57 * where aa-ff is the MAC address in hex
59 * @outbuf: Buffer to write string to
60 * @outbuf_len: length of buffer
61 * Return: 1 if OK, -ENOSPC if buffer is too small, -ENOENT is there is no
62 * current ethernet device
64 int format_mac_pxe(char *outbuf, size_t outbuf_len)
68 if (outbuf_len < 21) {
69 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
73 if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
76 sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
77 ethaddr[0], ethaddr[1], ethaddr[2],
78 ethaddr[3], ethaddr[4], ethaddr[5]);
84 * get_relfile() - read a file relative to the PXE file
86 * As in pxelinux, paths to files referenced from files we retrieve are
87 * relative to the location of bootfile. get_relfile takes such a path and
88 * joins it with the bootfile path to get the full path to the target file. If
89 * the bootfile path is NULL, we use file_path as is.
92 * @file_path: File path to read (relative to the PXE file)
93 * @file_addr: Address to load file to
94 * @filesizep: If not NULL, returns the file size in bytes
95 * Returns 1 for success, or < 0 on error
97 static int get_relfile(struct pxe_context *ctx, const char *file_path,
98 unsigned long file_addr, ulong *filesizep)
101 char relfile[MAX_TFTP_PATH_LEN + 1];
106 if (file_path[0] == '/' && ctx->allow_abs_path)
109 strncpy(relfile, ctx->bootdir, MAX_TFTP_PATH_LEN);
111 path_len = strlen(file_path) + strlen(relfile);
113 if (path_len > MAX_TFTP_PATH_LEN) {
114 printf("Base path too long (%s%s)\n", relfile, file_path);
116 return -ENAMETOOLONG;
119 strcat(relfile, file_path);
121 printf("Retrieving file: %s\n", relfile);
123 sprintf(addr_buf, "%lx", file_addr);
125 ret = ctx->getfile(ctx, relfile, addr_buf, &size);
127 return log_msg_ret("get", ret);
135 * get_pxe_file() - read a file
137 * The file is read and nul-terminated
140 * @file_path: File path to read (relative to the PXE file)
141 * @file_addr: Address to load file to
142 * Returns 1 for success, or < 0 on error
144 int get_pxe_file(struct pxe_context *ctx, const char *file_path,
151 err = get_relfile(ctx, file_path, file_addr, &size);
155 buf = map_sysmem(file_addr + size, 1);
162 #define PXELINUX_DIR "pxelinux.cfg/"
165 * get_pxelinux_path() - Get a file in the pxelinux.cfg/ directory
168 * @file: Filename to process (relative to pxelinux.cfg/)
169 * Returns 1 for success, -ENAMETOOLONG if the resulting path is too long.
170 * or other value < 0 on other error
172 int get_pxelinux_path(struct pxe_context *ctx, const char *file,
173 unsigned long pxefile_addr_r)
175 size_t base_len = strlen(PXELINUX_DIR);
176 char path[MAX_TFTP_PATH_LEN + 1];
178 if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
179 printf("path (%s%s) too long, skipping\n",
181 return -ENAMETOOLONG;
184 sprintf(path, PXELINUX_DIR "%s", file);
186 return get_pxe_file(ctx, path, pxefile_addr_r);
190 * get_relfile_envaddr() - read a file to an address in an env var
192 * Wrapper to make it easier to store the file at file_path in the location
193 * specified by envaddr_name. file_path will be joined to the bootfile path,
194 * if any is specified.
197 * @file_path: File path to read (relative to the PXE file)
198 * @envaddr_name: Name of environment variable which contains the address to
200 * @filesizep: Returns the file size in bytes
201 * Returns 1 on success, -ENOENT if @envaddr_name does not exist as an
202 * environment variable, -EINVAL if its format is not valid hex, or other
203 * value < 0 on other error
205 static int get_relfile_envaddr(struct pxe_context *ctx, const char *file_path,
206 const char *envaddr_name, ulong *filesizep)
208 unsigned long file_addr;
211 envaddr = from_env(envaddr_name);
215 if (strict_strtoul(envaddr, 16, &file_addr) < 0)
218 return get_relfile(ctx, file_path, file_addr, filesizep);
222 * label_create() - crate a new PXE label
224 * Allocates memory for and initializes a pxe_label. This uses malloc, so the
225 * result must be free()'d to reclaim the memory.
227 * Returns a pointer to the label, or NULL if out of memory
229 static struct pxe_label *label_create(void)
231 struct pxe_label *label;
233 label = malloc(sizeof(struct pxe_label));
237 memset(label, 0, sizeof(struct pxe_label));
243 * label_destroy() - free the memory used by a pxe_label
245 * This frees @label itself as well as memory used by its name,
246 * kernel, config, append, initrd, fdt, fdtdir and fdtoverlay members, if
249 * So - be sure to only use dynamically allocated memory for the members of
250 * the pxe_label struct, unless you want to clean it up first. These are
251 * currently only created by the pxe file parsing code.
253 * @label: Label to free
255 static void label_destroy(struct pxe_label *label)
258 free(label->kernel_label);
265 free(label->fdtoverlays);
270 * label_print() - Print a label and its string members if they're defined
272 * This is passed as a callback to the menu code for displaying each
275 * @data: Label to print (is cast to struct pxe_label *)
277 static void label_print(void *data)
279 struct pxe_label *label = data;
280 const char *c = label->menu ? label->menu : label->name;
282 printf("%s:\t%s\n", label->num, c);
286 * label_localboot() - Boot a label that specified 'localboot'
288 * This requires that the 'localcmd' environment variable is defined. Its
289 * contents will be executed as U-Boot commands. If the label specified an
290 * 'append' line, its contents will be used to overwrite the contents of the
291 * 'bootargs' environment variable prior to running 'localcmd'.
293 * @label: Label to process
294 * Returns 1 on success or < 0 on error
296 static int label_localboot(struct pxe_label *label)
300 localcmd = from_env("localcmd");
305 char bootargs[CONFIG_SYS_CBSIZE];
307 cli_simple_process_macros(label->append, bootargs,
309 env_set("bootargs", bootargs);
312 debug("running: %s\n", localcmd);
314 return run_command_list(localcmd, strlen(localcmd), 0);
318 * label_boot_kaslrseed generate kaslrseed from hw rng
321 static void label_boot_kaslrseed(void)
323 #if CONFIG_IS_ENABLED(DM_RNG)
325 struct fdt_header *working_fdt;
332 /* Get the main fdt and map it */
333 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
334 working_fdt = map_sysmem(fdt_addr, 0);
335 err = fdt_check_header(working_fdt);
339 /* add extra size for holding kaslr-seed */
340 /* err is new fdt size, 0 or negtive */
341 err = fdt_shrink_to_minimum(working_fdt, 512);
345 if (uclass_get_device(UCLASS_RNG, 0, &dev) || !dev) {
346 printf("No RNG device\n");
350 nodeoffset = fdt_find_or_add_subnode(working_fdt, 0, "chosen");
351 if (nodeoffset < 0) {
352 printf("Reading chosen node failed\n");
358 printf("Out of memory\n");
362 if (dm_rng_read(dev, buf, n)) {
363 printf("Reading RNG failed\n");
367 err = fdt_setprop(working_fdt, nodeoffset, "kaslr-seed", buf, sizeof(buf));
369 printf("Unable to set kaslr-seed on chosen node: %s\n", fdt_strerror(err));
379 * label_boot_fdtoverlay() - Loads fdt overlays specified in 'fdtoverlays'
380 * or 'devicetree-overlay'
383 * @label: Label to process
385 #ifdef CONFIG_OF_LIBFDT_OVERLAY
386 static void label_boot_fdtoverlay(struct pxe_context *ctx,
387 struct pxe_label *label)
389 char *fdtoverlay = label->fdtoverlays;
390 struct fdt_header *working_fdt;
391 char *fdtoverlay_addr_env;
392 ulong fdtoverlay_addr;
396 /* Get the main fdt and map it */
397 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
398 working_fdt = map_sysmem(fdt_addr, 0);
399 err = fdt_check_header(working_fdt);
403 /* Get the specific overlay loading address */
404 fdtoverlay_addr_env = env_get("fdtoverlay_addr_r");
405 if (!fdtoverlay_addr_env) {
406 printf("Invalid fdtoverlay_addr_r for loading overlays\n");
410 fdtoverlay_addr = hextoul(fdtoverlay_addr_env, NULL);
412 /* Cycle over the overlay files and apply them in order */
414 struct fdt_header *blob;
419 /* Drop leading spaces */
420 while (*fdtoverlay == ' ')
423 /* Copy a single filename if multiple provided */
424 end = strstr(fdtoverlay, " ");
426 len = (int)(end - fdtoverlay);
427 overlayfile = malloc(len + 1);
428 strncpy(overlayfile, fdtoverlay, len);
429 overlayfile[len] = '\0';
431 overlayfile = fdtoverlay;
433 if (!strlen(overlayfile))
436 /* Load overlay file */
437 err = get_relfile_envaddr(ctx, overlayfile, "fdtoverlay_addr_r",
440 printf("Failed loading overlay %s\n", overlayfile);
444 /* Resize main fdt */
445 fdt_shrink_to_minimum(working_fdt, 8192);
447 blob = map_sysmem(fdtoverlay_addr, 0);
448 err = fdt_check_header(blob);
450 printf("Invalid overlay %s, skipping\n",
455 err = fdt_overlay_apply_verbose(working_fdt, blob);
457 printf("Failed to apply overlay %s, skipping\n",
465 } while ((fdtoverlay = strstr(fdtoverlay, " ")));
470 * label_boot() - Boot according to the contents of a pxe_label
472 * If we can't boot for any reason, we return. A successful boot never
475 * The kernel will be stored in the location given by the 'kernel_addr_r'
476 * environment variable.
478 * If the label specifies an initrd file, it will be stored in the location
479 * given by the 'ramdisk_addr_r' environment variable.
481 * If the label specifies an 'append' line, its contents will overwrite that
482 * of the 'bootargs' environment variable.
485 * @label: Label to process
486 * Returns does not return on success, otherwise returns 0 if a localboot
487 * label was processed, or 1 on error
489 static int label_boot(struct pxe_context *ctx, struct pxe_label *label)
491 char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
492 char *zboot_argv[] = { "zboot", NULL, "0", NULL, NULL };
493 char *kernel_addr = NULL;
494 char *initrd_addr_str = NULL;
495 char initrd_filesize[10];
497 char mac_str[29] = "";
498 char ip_str[68] = "";
499 char *fit_addr = NULL;
508 label->attempted = 1;
510 if (label->localboot) {
511 if (label->localboot_val >= 0)
512 label_localboot(label);
516 if (!label->kernel) {
517 printf("No kernel given, skipping %s\n",
522 if (get_relfile_envaddr(ctx, label->kernel, "kernel_addr_r",
524 printf("Skipping %s for failure retrieving kernel\n",
529 kernel_addr = env_get("kernel_addr_r");
530 /* for FIT, append the configuration identifier */
532 int len = strlen(kernel_addr) + strlen(label->config) + 1;
534 fit_addr = malloc(len);
536 printf("malloc fail (FIT address)\n");
539 snprintf(fit_addr, len, "%s%s", kernel_addr, label->config);
540 kernel_addr = fit_addr;
543 /* For FIT, the label can be identical to kernel one */
544 if (label->initrd && !strcmp(label->kernel_label, label->initrd)) {
545 initrd_addr_str = kernel_addr;
546 } else if (label->initrd) {
548 if (get_relfile_envaddr(ctx, label->initrd, "ramdisk_addr_r",
550 printf("Skipping %s for failure retrieving initrd\n",
554 strcpy(initrd_filesize, simple_xtoa(size));
555 initrd_addr_str = env_get("ramdisk_addr_r");
556 size = snprintf(initrd_str, sizeof(initrd_str), "%s:%lx",
557 initrd_addr_str, size);
558 if (size >= sizeof(initrd_str))
562 if (label->ipappend & 0x1) {
563 sprintf(ip_str, " ip=%s:%s:%s:%s",
564 env_get("ipaddr"), env_get("serverip"),
565 env_get("gatewayip"), env_get("netmask"));
568 if (IS_ENABLED(CONFIG_CMD_NET)) {
569 if (label->ipappend & 0x2) {
572 strcpy(mac_str, " BOOTIF=");
573 err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
579 if ((label->ipappend & 0x3) || label->append) {
580 char bootargs[CONFIG_SYS_CBSIZE] = "";
581 char finalbootargs[CONFIG_SYS_CBSIZE];
583 if (strlen(label->append ?: "") +
584 strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
585 printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
586 strlen(label->append ?: ""),
587 strlen(ip_str), strlen(mac_str),
593 strncpy(bootargs, label->append, sizeof(bootargs));
595 strcat(bootargs, ip_str);
596 strcat(bootargs, mac_str);
598 cli_simple_process_macros(bootargs, finalbootargs,
599 sizeof(finalbootargs));
600 env_set("bootargs", finalbootargs);
601 printf("append: %s\n", finalbootargs);
605 * fdt usage is optional:
606 * It handles the following scenarios.
608 * Scenario 1: If fdt_addr_r specified and "fdt" or "fdtdir" label is
609 * defined in pxe file, retrieve fdt blob from server. Pass fdt_addr_r to
610 * bootm, and adjust argc appropriately.
612 * If retrieve fails and no exact fdt blob is specified in pxe file with
613 * "fdt" label, try Scenario 2.
615 * Scenario 2: If there is an fdt_addr specified, pass it along to
616 * bootm, and adjust argc appropriately.
618 * Scenario 3: If there is an fdtcontroladdr specified, pass it along to
619 * bootm, and adjust argc appropriately, unless the image type is fitImage.
621 * Scenario 4: fdt blob is not available.
623 bootm_argv[3] = env_get("fdt_addr_r");
625 /* For FIT, the label can be identical to kernel one */
626 if (label->fdt && !strcmp(label->kernel_label, label->fdt)) {
627 bootm_argv[3] = kernel_addr;
628 /* if fdt label is defined then get fdt from server */
629 } else if (bootm_argv[3]) {
630 char *fdtfile = NULL;
631 char *fdtfilefree = NULL;
634 if (IS_ENABLED(CONFIG_SUPPORT_PASSING_ATAGS)) {
635 if (strcmp("-", label->fdt))
636 fdtfile = label->fdt;
638 fdtfile = label->fdt;
640 } else if (label->fdtdir) {
641 char *f1, *f2, *f3, *f4, *slash;
643 f1 = env_get("fdtfile");
650 * For complex cases where this code doesn't
651 * generate the correct filename, the board
652 * code should set $fdtfile during early boot,
653 * or the boot scripts should set $fdtfile
654 * before invoking "pxe" or "sysboot".
658 f3 = env_get("board");
670 len = strlen(label->fdtdir);
673 else if (label->fdtdir[len - 1] != '/')
678 len = strlen(label->fdtdir) + strlen(slash) +
679 strlen(f1) + strlen(f2) + strlen(f3) +
681 fdtfilefree = malloc(len);
683 printf("malloc fail (FDT filename)\n");
687 snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
688 label->fdtdir, slash, f1, f2, f3, f4);
689 fdtfile = fdtfilefree;
693 int err = get_relfile_envaddr(ctx, fdtfile,
698 bootm_argv[3] = NULL;
701 printf("Skipping %s for failure retrieving FDT\n",
707 printf("Skipping fdtdir %s for failure retrieving dts\n",
712 if (label->kaslrseed)
713 label_boot_kaslrseed();
715 #ifdef CONFIG_OF_LIBFDT_OVERLAY
716 if (label->fdtoverlays)
717 label_boot_fdtoverlay(ctx, label);
720 bootm_argv[3] = NULL;
724 bootm_argv[1] = kernel_addr;
725 zboot_argv[1] = kernel_addr;
727 if (initrd_addr_str) {
728 bootm_argv[2] = initrd_str;
731 zboot_argv[3] = initrd_addr_str;
732 zboot_argv[4] = initrd_filesize;
736 if (!bootm_argv[3]) {
737 if (IS_ENABLED(CONFIG_SUPPORT_PASSING_ATAGS)) {
738 if (strcmp("-", label->fdt))
739 bootm_argv[3] = env_get("fdt_addr");
741 bootm_argv[3] = env_get("fdt_addr");
745 kernel_addr_r = genimg_get_kernel_addr(kernel_addr);
746 buf = map_sysmem(kernel_addr_r, 0);
748 if (!bootm_argv[3] && genimg_get_format(buf) != IMAGE_FORMAT_FIT) {
749 if (IS_ENABLED(CONFIG_SUPPORT_PASSING_ATAGS)) {
750 if (strcmp("-", label->fdt))
751 bootm_argv[3] = env_get("fdtcontroladdr");
753 bootm_argv[3] = env_get("fdtcontroladdr");
763 /* Try bootm for legacy and FIT format image */
764 if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID &&
765 IS_ENABLED(CONFIG_CMD_BOOTM))
766 do_bootm(ctx->cmdtp, 0, bootm_argc, bootm_argv);
767 /* Try booting an AArch64 Linux kernel image */
768 else if (IS_ENABLED(CONFIG_CMD_BOOTI))
769 do_booti(ctx->cmdtp, 0, bootm_argc, bootm_argv);
770 /* Try booting a Image */
771 else if (IS_ENABLED(CONFIG_CMD_BOOTZ))
772 do_bootz(ctx->cmdtp, 0, bootm_argc, bootm_argv);
773 /* Try booting an x86_64 Linux kernel image */
774 else if (IS_ENABLED(CONFIG_CMD_ZBOOT))
775 do_zboot_parent(ctx->cmdtp, 0, zboot_argc, zboot_argv, NULL);
785 /** enum token_type - Tokens for the pxe file parser */
812 /** struct token - token - given by a value and a type */
815 enum token_type type;
818 /* Keywords recognized */
819 static const struct token keywords[] = {
822 {"timeout", T_TIMEOUT},
823 {"default", T_DEFAULT},
824 {"prompt", T_PROMPT},
826 {"kernel", T_KERNEL},
828 {"localboot", T_LOCALBOOT},
829 {"append", T_APPEND},
830 {"initrd", T_INITRD},
831 {"include", T_INCLUDE},
832 {"devicetree", T_FDT},
834 {"devicetreedir", T_FDTDIR},
835 {"fdtdir", T_FDTDIR},
836 {"fdtoverlays", T_FDTOVERLAYS},
837 {"devicetree-overlay", T_FDTOVERLAYS},
838 {"ontimeout", T_ONTIMEOUT,},
839 {"ipappend", T_IPAPPEND,},
840 {"background", T_BACKGROUND,},
841 {"kaslrseed", T_KASLRSEED,},
846 * enum lex_state - lexer state
848 * Since pxe(linux) files don't have a token to identify the start of a
849 * literal, we have to keep track of when we're in a state where a literal is
850 * expected vs when we're in a state a keyword is expected.
859 * get_string() - retrieves a string from *p and stores it as a token in *t.
861 * This is used for scanning both string literals and keywords.
863 * Characters from *p are copied into t-val until a character equal to
864 * delim is found, or a NUL byte is reached. If delim has the special value of
865 * ' ', any whitespace character will be used as a delimiter.
867 * If lower is unequal to 0, uppercase characters will be converted to
868 * lowercase in the result. This is useful to make keywords case
871 * The location of *p is updated to point to the first character after the end
872 * of the token - the ending delimiter.
874 * Memory for t->val is allocated using malloc and must be free()'d to reclaim
877 * @p: Points to a pointer to the current position in the input being processed.
878 * Updated to point at the first character after the current token
879 * @t: Pointers to a token to fill in
880 * @delim: Delimiter character to look for, either newline or space
881 * @lower: true to convert the string to lower case when storing
882 * Returns the new value of t->val, on success, NULL if out of memory
884 static char *get_string(char **p, struct token *t, char delim, int lower)
890 * b and e both start at the beginning of the input stream.
892 * e is incremented until we find the ending delimiter, or a NUL byte
893 * is reached. Then, we take e - b to find the length of the token.
898 if ((delim == ' ' && isspace(*e)) || delim == *e)
906 * Allocate memory to hold the string, and copy it in, converting
907 * characters to lowercase if lower is != 0.
909 t->val = malloc(len + 1);
913 for (i = 0; i < len; i++, b++) {
915 t->val[i] = tolower(*b);
922 /* Update *p so the caller knows where to continue scanning */
930 * get_keyword() - Populate a keyword token with a type and value
932 * Updates the ->type field based on the keyword string in @val
933 * @t: Token to populate
935 static void get_keyword(struct token *t)
939 for (i = 0; keywords[i].val; i++) {
940 if (!strcmp(t->val, keywords[i].val)) {
941 t->type = keywords[i].type;
948 * get_token() - Get the next token
950 * We have to keep track of which state we're in to know if we're looking to get
951 * a string literal or a keyword.
953 * @p: Points to a pointer to the current position in the input being processed.
954 * Updated to point at the first character after the current token
956 static void get_token(char **p, struct token *t, enum lex_state state)
962 /* eat non EOL whitespace */
967 * eat comments. note that string literals can't begin with #, but
968 * can contain a # after their first character.
971 while (*c && *c != '\n')
978 } else if (*c == '\0') {
981 } else if (state == L_SLITERAL) {
982 get_string(&c, t, '\n', 0);
983 } else if (state == L_KEYWORD) {
985 * when we expect a keyword, we first get the next string
986 * token delimited by whitespace, and then check if it
987 * matches a keyword in our keyword list. if it does, it's
988 * converted to a keyword token of the appropriate type, and
989 * if not, it remains a string token.
991 get_string(&c, t, ' ', 1);
999 * eol_or_eof() - Find end of line
1001 * Increment *c until we get to the end of the current line, or EOF
1003 * @c: Points to a pointer to the current position in the input being processed.
1004 * Updated to point at the first character after the current token
1006 static void eol_or_eof(char **c)
1008 while (**c && **c != '\n')
1013 * All of these parse_* functions share some common behavior.
1015 * They finish with *c pointing after the token they parse, and return 1 on
1016 * success, or < 0 on error.
1020 * Parse a string literal and store a pointer it at *dst. String literals
1021 * terminate at the end of the line.
1023 static int parse_sliteral(char **c, char **dst)
1028 get_token(c, &t, L_SLITERAL);
1030 if (t.type != T_STRING) {
1031 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
1041 * Parse a base 10 (unsigned) integer and store it at *dst.
1043 static int parse_integer(char **c, int *dst)
1048 get_token(c, &t, L_SLITERAL);
1049 if (t.type != T_STRING) {
1050 printf("Expected string: %.*s\n", (int)(*c - s), s);
1054 *dst = simple_strtol(t.val, NULL, 10);
1061 static int parse_pxefile_top(struct pxe_context *ctx, char *p, ulong base,
1062 struct pxe_menu *cfg, int nest_level);
1065 * Parse an include statement, and retrieve and parse the file it mentions.
1067 * base should point to a location where it's safe to store the file, and
1068 * nest_level should indicate how many nested includes have occurred. For this
1069 * include, nest_level has already been incremented and doesn't need to be
1072 static int handle_include(struct pxe_context *ctx, char **c, unsigned long base,
1073 struct pxe_menu *cfg, int nest_level)
1081 err = parse_sliteral(c, &include_path);
1083 printf("Expected include path: %.*s\n", (int)(*c - s), s);
1087 err = get_pxe_file(ctx, include_path, base);
1089 printf("Couldn't retrieve %s\n", include_path);
1093 buf = map_sysmem(base, 0);
1094 ret = parse_pxefile_top(ctx, buf, base, cfg, nest_level);
1101 * Parse lines that begin with 'menu'.
1103 * base and nest are provided to handle the 'menu include' case.
1105 * base should point to a location where it's safe to store the included file.
1107 * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1108 * a file it includes, 3 when parsing a file included by that file, and so on.
1110 static int parse_menu(struct pxe_context *ctx, char **c, struct pxe_menu *cfg,
1111 unsigned long base, int nest_level)
1117 get_token(c, &t, L_KEYWORD);
1121 err = parse_sliteral(c, &cfg->title);
1126 err = handle_include(ctx, c, base, cfg, nest_level + 1);
1130 err = parse_sliteral(c, &cfg->bmp);
1134 printf("Ignoring malformed menu command: %.*s\n",
1146 * Handles parsing a 'menu line' when we're parsing a label.
1148 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1149 struct pxe_label *label)
1156 get_token(c, &t, L_KEYWORD);
1160 if (!cfg->default_label)
1161 cfg->default_label = strdup(label->name);
1163 if (!cfg->default_label)
1168 parse_sliteral(c, &label->menu);
1171 printf("Ignoring malformed menu command: %.*s\n",
1181 * Handles parsing a 'kernel' label.
1182 * expecting "filename" or "<fit_filename>#cfg"
1184 static int parse_label_kernel(char **c, struct pxe_label *label)
1189 err = parse_sliteral(c, &label->kernel);
1193 /* copy the kernel label to compare with FDT / INITRD when FIT is used */
1194 label->kernel_label = strdup(label->kernel);
1195 if (!label->kernel_label)
1198 s = strstr(label->kernel, "#");
1202 label->config = strdup(s);
1212 * Parses a label and adds it to the list of labels for a menu.
1214 * A label ends when we either get to the end of a file, or
1215 * get some input we otherwise don't have a handler defined
1219 static int parse_label(char **c, struct pxe_menu *cfg)
1224 struct pxe_label *label;
1227 label = label_create();
1231 err = parse_sliteral(c, &label->name);
1233 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1234 label_destroy(label);
1238 list_add_tail(&label->list, &cfg->labels);
1242 get_token(c, &t, L_KEYWORD);
1247 err = parse_label_menu(c, cfg, label);
1252 err = parse_label_kernel(c, label);
1256 err = parse_sliteral(c, &label->append);
1259 s = strstr(label->append, "initrd=");
1263 len = (int)(strchr(s, ' ') - s);
1264 label->initrd = malloc(len + 1);
1265 strncpy(label->initrd, s, len);
1266 label->initrd[len] = '\0';
1272 err = parse_sliteral(c, &label->initrd);
1277 err = parse_sliteral(c, &label->fdt);
1282 err = parse_sliteral(c, &label->fdtdir);
1286 if (!label->fdtoverlays)
1287 err = parse_sliteral(c, &label->fdtoverlays);
1291 label->localboot = 1;
1292 err = parse_integer(c, &label->localboot_val);
1296 err = parse_integer(c, &label->ipappend);
1300 label->kaslrseed = 1;
1308 * put the token back! we don't want it - it's the end
1309 * of a label and whatever token this is, it's
1310 * something for the menu level context to handle.
1322 * This 16 comes from the limit pxelinux imposes on nested includes.
1324 * There is no reason at all we couldn't do more, but some limit helps prevent
1325 * infinite (until crash occurs) recursion if a file tries to include itself.
1327 #define MAX_NEST_LEVEL 16
1330 * Entry point for parsing a menu file. nest_level indicates how many times
1331 * we've nested in includes. It will be 1 for the top level menu file.
1333 * Returns 1 on success, < 0 on error.
1335 static int parse_pxefile_top(struct pxe_context *ctx, char *p, unsigned long base,
1336 struct pxe_menu *cfg, int nest_level)
1339 char *s, *b, *label_name;
1344 if (nest_level > MAX_NEST_LEVEL) {
1345 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1352 get_token(&p, &t, L_KEYWORD);
1358 err = parse_menu(ctx, &p, cfg,
1359 base + ALIGN(strlen(b) + 1, 4),
1364 err = parse_integer(&p, &cfg->timeout);
1368 err = parse_label(&p, cfg);
1373 err = parse_sliteral(&p, &label_name);
1376 if (cfg->default_label)
1377 free(cfg->default_label);
1379 cfg->default_label = label_name;
1385 err = handle_include(ctx, &p,
1386 base + ALIGN(strlen(b), 4), cfg,
1391 err = parse_integer(&p, &cfg->prompt);
1392 // Do not fail if prompt configuration is undefined
1404 printf("Ignoring unknown command: %.*s\n",
1416 void destroy_pxe_menu(struct pxe_menu *cfg)
1418 struct list_head *pos, *n;
1419 struct pxe_label *label;
1422 free(cfg->default_label);
1424 list_for_each_safe(pos, n, &cfg->labels) {
1425 label = list_entry(pos, struct pxe_label, list);
1427 label_destroy(label);
1433 struct pxe_menu *parse_pxefile(struct pxe_context *ctx, unsigned long menucfg)
1435 struct pxe_menu *cfg;
1439 cfg = malloc(sizeof(struct pxe_menu));
1443 memset(cfg, 0, sizeof(struct pxe_menu));
1445 INIT_LIST_HEAD(&cfg->labels);
1447 buf = map_sysmem(menucfg, 0);
1448 r = parse_pxefile_top(ctx, buf, menucfg, cfg, 1);
1451 destroy_pxe_menu(cfg);
1459 * Converts a pxe_menu struct into a menu struct for use with U-Boot's generic
1462 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1464 struct pxe_label *label;
1465 struct list_head *pos;
1467 char *label_override;
1470 char *default_num = NULL;
1471 char *override_num = NULL;
1474 * Create a menu and add items for all the labels.
1476 m = menu_create(cfg->title, DIV_ROUND_UP(cfg->timeout, 10),
1477 cfg->prompt, NULL, label_print, NULL, NULL);
1481 label_override = env_get("pxe_label_override");
1483 list_for_each(pos, &cfg->labels) {
1484 label = list_entry(pos, struct pxe_label, list);
1486 sprintf(label->num, "%d", i++);
1487 if (menu_item_add(m, label->num, label) != 1) {
1491 if (cfg->default_label &&
1492 (strcmp(label->name, cfg->default_label) == 0))
1493 default_num = label->num;
1494 if (label_override && !strcmp(label->name, label_override))
1495 override_num = label->num;
1499 if (label_override) {
1501 default_num = override_num;
1503 printf("Missing override pxe label: %s\n",
1508 * After we've created items for each label in the menu, set the
1509 * menu's default label if one was specified.
1512 err = menu_default_set(m, default_num);
1514 if (err != -ENOENT) {
1519 printf("Missing default: %s\n", cfg->default_label);
1527 * Try to boot any labels we have yet to attempt to boot.
1529 static void boot_unattempted_labels(struct pxe_context *ctx,
1530 struct pxe_menu *cfg)
1532 struct list_head *pos;
1533 struct pxe_label *label;
1535 list_for_each(pos, &cfg->labels) {
1536 label = list_entry(pos, struct pxe_label, list);
1538 if (!label->attempted)
1539 label_boot(ctx, label);
1543 void handle_pxe_menu(struct pxe_context *ctx, struct pxe_menu *cfg)
1549 if (IS_ENABLED(CONFIG_CMD_BMP)) {
1550 /* display BMP if available */
1552 if (get_relfile(ctx, cfg->bmp, image_load_addr, NULL)) {
1553 #if defined(CONFIG_VIDEO)
1554 struct udevice *dev;
1556 err = uclass_first_device_err(UCLASS_VIDEO, &dev);
1560 bmp_display(image_load_addr,
1561 BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1563 printf("Skipping background bmp %s for failure\n",
1569 m = pxe_menu_to_menu(cfg);
1573 err = menu_get_choice(m, &choice);
1577 * err == 1 means we got a choice back from menu_get_choice.
1579 * err == -ENOENT if the menu was setup to select the default but no
1580 * default was set. in that case, we should continue trying to boot
1581 * labels that haven't been attempted yet.
1583 * otherwise, the user interrupted or there was some other error and
1588 err = label_boot(ctx, choice);
1591 } else if (err != -ENOENT) {
1595 boot_unattempted_labels(ctx, cfg);
1598 int pxe_setup_ctx(struct pxe_context *ctx, struct cmd_tbl *cmdtp,
1599 pxe_getfile_func getfile, void *userdata,
1600 bool allow_abs_path, const char *bootfile, bool use_ipv6)
1602 const char *last_slash;
1603 size_t path_len = 0;
1605 memset(ctx, '\0', sizeof(*ctx));
1607 ctx->getfile = getfile;
1608 ctx->userdata = userdata;
1609 ctx->allow_abs_path = allow_abs_path;
1610 ctx->use_ipv6 = use_ipv6;
1612 /* figure out the boot directory, if there is one */
1613 if (bootfile && strlen(bootfile) >= MAX_TFTP_PATH_LEN)
1615 ctx->bootdir = strdup(bootfile ? bootfile : "");
1620 last_slash = strrchr(bootfile, '/');
1622 path_len = (last_slash - bootfile) + 1;
1624 ctx->bootdir[path_len] = '\0';
1629 void pxe_destroy_ctx(struct pxe_context *ctx)
1634 int pxe_process(struct pxe_context *ctx, ulong pxefile_addr_r, bool prompt)
1636 struct pxe_menu *cfg;
1638 cfg = parse_pxefile(ctx, pxefile_addr_r);
1640 printf("Error parsing config file\n");
1647 handle_pxe_menu(ctx, cfg);
1649 destroy_pxe_menu(cfg);