1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright 2010-2011 Calxeda, Inc.
4 * Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved.
7 #define LOG_CATEGORY LOGC_BOOT
17 #include <fdt_support.h>
19 #include <linux/libfdt.h>
20 #include <linux/string.h>
21 #include <linux/ctype.h>
23 #include <linux/list.h>
33 #include "pxe_utils.h"
35 #define MAX_TFTP_PATH_LEN 512
37 int pxe_get_file_size(ulong *sizep)
41 val = from_env("filesize");
45 if (strict_strtoul(val, 16, sizep) < 0)
52 * format_mac_pxe() - obtain a MAC address in the PXE format
54 * This produces a MAC-address string in the format for the current ethernet
57 * 01-aa-bb-cc-dd-ee-ff
59 * where aa-ff is the MAC address in hex
61 * @outbuf: Buffer to write string to
62 * @outbuf_len: length of buffer
63 * Return: 1 if OK, -ENOSPC if buffer is too small, -ENOENT is there is no
64 * current ethernet device
66 int format_mac_pxe(char *outbuf, size_t outbuf_len)
70 if (outbuf_len < 21) {
71 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
75 if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
78 sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
79 ethaddr[0], ethaddr[1], ethaddr[2],
80 ethaddr[3], ethaddr[4], ethaddr[5]);
86 * get_relfile() - read a file relative to the PXE file
88 * As in pxelinux, paths to files referenced from files we retrieve are
89 * relative to the location of bootfile. get_relfile takes such a path and
90 * joins it with the bootfile path to get the full path to the target file. If
91 * the bootfile path is NULL, we use file_path as is.
94 * @file_path: File path to read (relative to the PXE file)
95 * @file_addr: Address to load file to
96 * @filesizep: If not NULL, returns the file size in bytes
97 * Returns 1 for success, or < 0 on error
99 static int get_relfile(struct pxe_context *ctx, const char *file_path,
100 unsigned long file_addr, ulong *filesizep)
103 char relfile[MAX_TFTP_PATH_LEN + 1];
108 if (file_path[0] == '/' && ctx->allow_abs_path)
111 strncpy(relfile, ctx->bootdir, MAX_TFTP_PATH_LEN);
113 path_len = strlen(file_path) + strlen(relfile);
115 if (path_len > MAX_TFTP_PATH_LEN) {
116 printf("Base path too long (%s%s)\n", relfile, file_path);
118 return -ENAMETOOLONG;
121 strcat(relfile, file_path);
123 printf("Retrieving file: %s\n", relfile);
125 sprintf(addr_buf, "%lx", file_addr);
127 ret = ctx->getfile(ctx, relfile, addr_buf, &size);
129 return log_msg_ret("get", ret);
137 * get_pxe_file() - read a file
139 * The file is read and nul-terminated
142 * @file_path: File path to read (relative to the PXE file)
143 * @file_addr: Address to load file to
144 * Returns 1 for success, or < 0 on error
146 int get_pxe_file(struct pxe_context *ctx, const char *file_path,
153 err = get_relfile(ctx, file_path, file_addr, &size);
157 buf = map_sysmem(file_addr + size, 1);
164 #define PXELINUX_DIR "pxelinux.cfg/"
167 * get_pxelinux_path() - Get a file in the pxelinux.cfg/ directory
170 * @file: Filename to process (relative to pxelinux.cfg/)
171 * Returns 1 for success, -ENAMETOOLONG if the resulting path is too long.
172 * or other value < 0 on other error
174 int get_pxelinux_path(struct pxe_context *ctx, const char *file,
175 unsigned long pxefile_addr_r)
177 size_t base_len = strlen(PXELINUX_DIR);
178 char path[MAX_TFTP_PATH_LEN + 1];
180 if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
181 printf("path (%s%s) too long, skipping\n",
183 return -ENAMETOOLONG;
186 sprintf(path, PXELINUX_DIR "%s", file);
188 return get_pxe_file(ctx, path, pxefile_addr_r);
192 * get_relfile_envaddr() - read a file to an address in an env var
194 * Wrapper to make it easier to store the file at file_path in the location
195 * specified by envaddr_name. file_path will be joined to the bootfile path,
196 * if any is specified.
199 * @file_path: File path to read (relative to the PXE file)
200 * @envaddr_name: Name of environment variable which contains the address to
202 * @filesizep: Returns the file size in bytes
203 * Returns 1 on success, -ENOENT if @envaddr_name does not exist as an
204 * environment variable, -EINVAL if its format is not valid hex, or other
205 * value < 0 on other error
207 static int get_relfile_envaddr(struct pxe_context *ctx, const char *file_path,
208 const char *envaddr_name, ulong *filesizep)
210 unsigned long file_addr;
213 envaddr = from_env(envaddr_name);
217 if (strict_strtoul(envaddr, 16, &file_addr) < 0)
220 return get_relfile(ctx, file_path, file_addr, filesizep);
224 * label_create() - crate a new PXE label
226 * Allocates memory for and initializes a pxe_label. This uses malloc, so the
227 * result must be free()'d to reclaim the memory.
229 * Returns a pointer to the label, or NULL if out of memory
231 static struct pxe_label *label_create(void)
233 struct pxe_label *label;
235 label = malloc(sizeof(struct pxe_label));
239 memset(label, 0, sizeof(struct pxe_label));
245 * label_destroy() - free the memory used by a pxe_label
247 * This frees @label itself as well as memory used by its name,
248 * kernel, config, append, initrd, fdt, fdtdir and fdtoverlay members, if
251 * So - be sure to only use dynamically allocated memory for the members of
252 * the pxe_label struct, unless you want to clean it up first. These are
253 * currently only created by the pxe file parsing code.
255 * @label: Label to free
257 static void label_destroy(struct pxe_label *label)
260 free(label->kernel_label);
267 free(label->fdtoverlays);
272 * label_print() - Print a label and its string members if they're defined
274 * This is passed as a callback to the menu code for displaying each
277 * @data: Label to print (is cast to struct pxe_label *)
279 static void label_print(void *data)
281 struct pxe_label *label = data;
282 const char *c = label->menu ? label->menu : label->name;
284 printf("%s:\t%s\n", label->num, c);
288 * label_localboot() - Boot a label that specified 'localboot'
290 * This requires that the 'localcmd' environment variable is defined. Its
291 * contents will be executed as U-Boot commands. If the label specified an
292 * 'append' line, its contents will be used to overwrite the contents of the
293 * 'bootargs' environment variable prior to running 'localcmd'.
295 * @label: Label to process
296 * Returns 1 on success or < 0 on error
298 static int label_localboot(struct pxe_label *label)
302 localcmd = from_env("localcmd");
307 char bootargs[CONFIG_SYS_CBSIZE];
309 cli_simple_process_macros(label->append, bootargs,
311 env_set("bootargs", bootargs);
314 debug("running: %s\n", localcmd);
316 return run_command_list(localcmd, strlen(localcmd), 0);
320 * label_boot_kaslrseed generate kaslrseed from hw rng
323 static void label_boot_kaslrseed(void)
325 #if CONFIG_IS_ENABLED(DM_RNG)
327 struct fdt_header *working_fdt;
330 /* Get the main fdt and map it */
331 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
332 working_fdt = map_sysmem(fdt_addr, 0);
333 err = fdt_check_header(working_fdt);
337 /* add extra size for holding kaslr-seed */
338 /* err is new fdt size, 0 or negtive */
339 err = fdt_shrink_to_minimum(working_fdt, 512);
343 fdt_kaslrseed(working_fdt, true);
349 * label_boot_fdtoverlay() - Loads fdt overlays specified in 'fdtoverlays'
350 * or 'devicetree-overlay'
353 * @label: Label to process
355 #ifdef CONFIG_OF_LIBFDT_OVERLAY
356 static void label_boot_fdtoverlay(struct pxe_context *ctx,
357 struct pxe_label *label)
359 char *fdtoverlay = label->fdtoverlays;
360 struct fdt_header *working_fdt;
361 char *fdtoverlay_addr_env;
362 ulong fdtoverlay_addr;
366 /* Get the main fdt and map it */
367 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
368 working_fdt = map_sysmem(fdt_addr, 0);
369 err = fdt_check_header(working_fdt);
373 /* Get the specific overlay loading address */
374 fdtoverlay_addr_env = env_get("fdtoverlay_addr_r");
375 if (!fdtoverlay_addr_env) {
376 printf("Invalid fdtoverlay_addr_r for loading overlays\n");
380 fdtoverlay_addr = hextoul(fdtoverlay_addr_env, NULL);
382 /* Cycle over the overlay files and apply them in order */
384 struct fdt_header *blob;
389 /* Drop leading spaces */
390 while (*fdtoverlay == ' ')
393 /* Copy a single filename if multiple provided */
394 end = strstr(fdtoverlay, " ");
396 len = (int)(end - fdtoverlay);
397 overlayfile = malloc(len + 1);
398 strncpy(overlayfile, fdtoverlay, len);
399 overlayfile[len] = '\0';
401 overlayfile = fdtoverlay;
403 if (!strlen(overlayfile))
406 /* Load overlay file */
407 err = get_relfile_envaddr(ctx, overlayfile, "fdtoverlay_addr_r",
410 printf("Failed loading overlay %s\n", overlayfile);
414 /* Resize main fdt */
415 fdt_shrink_to_minimum(working_fdt, 8192);
417 blob = map_sysmem(fdtoverlay_addr, 0);
418 err = fdt_check_header(blob);
420 printf("Invalid overlay %s, skipping\n",
425 err = fdt_overlay_apply_verbose(working_fdt, blob);
427 printf("Failed to apply overlay %s, skipping\n",
435 } while ((fdtoverlay = strstr(fdtoverlay, " ")));
440 * label_boot() - Boot according to the contents of a pxe_label
442 * If we can't boot for any reason, we return. A successful boot never
445 * The kernel will be stored in the location given by the 'kernel_addr_r'
446 * environment variable.
448 * If the label specifies an initrd file, it will be stored in the location
449 * given by the 'ramdisk_addr_r' environment variable.
451 * If the label specifies an 'append' line, its contents will overwrite that
452 * of the 'bootargs' environment variable.
455 * @label: Label to process
456 * Returns does not return on success, otherwise returns 0 if a localboot
457 * label was processed, or 1 on error
459 static int label_boot(struct pxe_context *ctx, struct pxe_label *label)
461 char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
462 char *zboot_argv[] = { "zboot", NULL, "0", NULL, NULL };
463 char *kernel_addr = NULL;
464 char *initrd_addr_str = NULL;
465 char initrd_filesize[10];
467 char mac_str[29] = "";
468 char ip_str[68] = "";
469 char *fit_addr = NULL;
478 label->attempted = 1;
480 if (label->localboot) {
481 if (label->localboot_val >= 0)
482 label_localboot(label);
486 if (!label->kernel) {
487 printf("No kernel given, skipping %s\n",
492 if (get_relfile_envaddr(ctx, label->kernel, "kernel_addr_r",
494 printf("Skipping %s for failure retrieving kernel\n",
499 kernel_addr = env_get("kernel_addr_r");
500 /* for FIT, append the configuration identifier */
502 int len = strlen(kernel_addr) + strlen(label->config) + 1;
504 fit_addr = malloc(len);
506 printf("malloc fail (FIT address)\n");
509 snprintf(fit_addr, len, "%s%s", kernel_addr, label->config);
510 kernel_addr = fit_addr;
513 /* For FIT, the label can be identical to kernel one */
514 if (label->initrd && !strcmp(label->kernel_label, label->initrd)) {
515 initrd_addr_str = kernel_addr;
516 } else if (label->initrd) {
518 if (get_relfile_envaddr(ctx, label->initrd, "ramdisk_addr_r",
520 printf("Skipping %s for failure retrieving initrd\n",
524 strcpy(initrd_filesize, simple_xtoa(size));
525 initrd_addr_str = env_get("ramdisk_addr_r");
526 size = snprintf(initrd_str, sizeof(initrd_str), "%s:%lx",
527 initrd_addr_str, size);
528 if (size >= sizeof(initrd_str))
532 if (label->ipappend & 0x1) {
533 sprintf(ip_str, " ip=%s:%s:%s:%s",
534 env_get("ipaddr"), env_get("serverip"),
535 env_get("gatewayip"), env_get("netmask"));
538 if (IS_ENABLED(CONFIG_CMD_NET)) {
539 if (label->ipappend & 0x2) {
542 strcpy(mac_str, " BOOTIF=");
543 err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
549 if ((label->ipappend & 0x3) || label->append) {
550 char bootargs[CONFIG_SYS_CBSIZE] = "";
551 char finalbootargs[CONFIG_SYS_CBSIZE];
553 if (strlen(label->append ?: "") +
554 strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
555 printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
556 strlen(label->append ?: ""),
557 strlen(ip_str), strlen(mac_str),
563 strncpy(bootargs, label->append, sizeof(bootargs));
565 strcat(bootargs, ip_str);
566 strcat(bootargs, mac_str);
568 cli_simple_process_macros(bootargs, finalbootargs,
569 sizeof(finalbootargs));
570 env_set("bootargs", finalbootargs);
571 printf("append: %s\n", finalbootargs);
575 * fdt usage is optional:
576 * It handles the following scenarios.
578 * Scenario 1: If fdt_addr_r specified and "fdt" or "fdtdir" label is
579 * defined in pxe file, retrieve fdt blob from server. Pass fdt_addr_r to
580 * bootm, and adjust argc appropriately.
582 * If retrieve fails and no exact fdt blob is specified in pxe file with
583 * "fdt" label, try Scenario 2.
585 * Scenario 2: If there is an fdt_addr specified, pass it along to
586 * bootm, and adjust argc appropriately.
588 * Scenario 3: If there is an fdtcontroladdr specified, pass it along to
589 * bootm, and adjust argc appropriately, unless the image type is fitImage.
591 * Scenario 4: fdt blob is not available.
593 bootm_argv[3] = env_get("fdt_addr_r");
595 /* For FIT, the label can be identical to kernel one */
596 if (label->fdt && !strcmp(label->kernel_label, label->fdt)) {
597 bootm_argv[3] = kernel_addr;
598 /* if fdt label is defined then get fdt from server */
599 } else if (bootm_argv[3]) {
600 char *fdtfile = NULL;
601 char *fdtfilefree = NULL;
604 if (IS_ENABLED(CONFIG_SUPPORT_PASSING_ATAGS)) {
605 if (strcmp("-", label->fdt))
606 fdtfile = label->fdt;
608 fdtfile = label->fdt;
610 } else if (label->fdtdir) {
611 char *f1, *f2, *f3, *f4, *slash;
613 f1 = env_get("fdtfile");
620 * For complex cases where this code doesn't
621 * generate the correct filename, the board
622 * code should set $fdtfile during early boot,
623 * or the boot scripts should set $fdtfile
624 * before invoking "pxe" or "sysboot".
628 f3 = env_get("board");
640 len = strlen(label->fdtdir);
643 else if (label->fdtdir[len - 1] != '/')
648 len = strlen(label->fdtdir) + strlen(slash) +
649 strlen(f1) + strlen(f2) + strlen(f3) +
651 fdtfilefree = malloc(len);
653 printf("malloc fail (FDT filename)\n");
657 snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
658 label->fdtdir, slash, f1, f2, f3, f4);
659 fdtfile = fdtfilefree;
663 int err = get_relfile_envaddr(ctx, fdtfile,
668 bootm_argv[3] = NULL;
671 printf("Skipping %s for failure retrieving FDT\n",
677 printf("Skipping fdtdir %s for failure retrieving dts\n",
682 if (label->kaslrseed)
683 label_boot_kaslrseed();
685 #ifdef CONFIG_OF_LIBFDT_OVERLAY
686 if (label->fdtoverlays)
687 label_boot_fdtoverlay(ctx, label);
690 bootm_argv[3] = NULL;
694 bootm_argv[1] = kernel_addr;
695 zboot_argv[1] = kernel_addr;
697 if (initrd_addr_str) {
698 bootm_argv[2] = initrd_str;
701 zboot_argv[3] = initrd_addr_str;
702 zboot_argv[4] = initrd_filesize;
706 if (!bootm_argv[3]) {
707 if (IS_ENABLED(CONFIG_SUPPORT_PASSING_ATAGS)) {
708 if (strcmp("-", label->fdt))
709 bootm_argv[3] = env_get("fdt_addr");
711 bootm_argv[3] = env_get("fdt_addr");
715 kernel_addr_r = genimg_get_kernel_addr(kernel_addr);
716 buf = map_sysmem(kernel_addr_r, 0);
718 if (!bootm_argv[3] && genimg_get_format(buf) != IMAGE_FORMAT_FIT) {
719 if (IS_ENABLED(CONFIG_SUPPORT_PASSING_ATAGS)) {
720 if (strcmp("-", label->fdt))
721 bootm_argv[3] = env_get("fdtcontroladdr");
723 bootm_argv[3] = env_get("fdtcontroladdr");
733 /* Try bootm for legacy and FIT format image */
734 if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID &&
735 IS_ENABLED(CONFIG_CMD_BOOTM)) {
736 log_debug("using bootm\n");
737 do_bootm(ctx->cmdtp, 0, bootm_argc, bootm_argv);
738 /* Try booting an AArch64 Linux kernel image */
739 } else if (IS_ENABLED(CONFIG_CMD_BOOTI)) {
740 log_debug("using booti\n");
741 do_booti(ctx->cmdtp, 0, bootm_argc, bootm_argv);
742 /* Try booting a Image */
743 } else if (IS_ENABLED(CONFIG_CMD_BOOTZ)) {
744 log_debug("using bootz\n");
745 do_bootz(ctx->cmdtp, 0, bootm_argc, bootm_argv);
746 /* Try booting an x86_64 Linux kernel image */
747 } else if (IS_ENABLED(CONFIG_CMD_ZBOOT)) {
748 log_debug("using zboot\n");
749 do_zboot_parent(ctx->cmdtp, 0, zboot_argc, zboot_argv, NULL);
760 /** enum token_type - Tokens for the pxe file parser */
788 /** struct token - token - given by a value and a type */
791 enum token_type type;
794 /* Keywords recognized */
795 static const struct token keywords[] = {
798 {"timeout", T_TIMEOUT},
799 {"default", T_DEFAULT},
800 {"prompt", T_PROMPT},
802 {"kernel", T_KERNEL},
804 {"localboot", T_LOCALBOOT},
805 {"append", T_APPEND},
806 {"initrd", T_INITRD},
807 {"include", T_INCLUDE},
808 {"devicetree", T_FDT},
810 {"devicetreedir", T_FDTDIR},
811 {"fdtdir", T_FDTDIR},
812 {"fdtoverlays", T_FDTOVERLAYS},
813 {"devicetree-overlay", T_FDTOVERLAYS},
814 {"ontimeout", T_ONTIMEOUT,},
815 {"ipappend", T_IPAPPEND,},
816 {"background", T_BACKGROUND,},
817 {"kaslrseed", T_KASLRSEED,},
818 {"fallback", T_FALLBACK,},
823 * enum lex_state - lexer state
825 * Since pxe(linux) files don't have a token to identify the start of a
826 * literal, we have to keep track of when we're in a state where a literal is
827 * expected vs when we're in a state a keyword is expected.
836 * get_string() - retrieves a string from *p and stores it as a token in *t.
838 * This is used for scanning both string literals and keywords.
840 * Characters from *p are copied into t-val until a character equal to
841 * delim is found, or a NUL byte is reached. If delim has the special value of
842 * ' ', any whitespace character will be used as a delimiter.
844 * If lower is unequal to 0, uppercase characters will be converted to
845 * lowercase in the result. This is useful to make keywords case
848 * The location of *p is updated to point to the first character after the end
849 * of the token - the ending delimiter.
851 * Memory for t->val is allocated using malloc and must be free()'d to reclaim
854 * @p: Points to a pointer to the current position in the input being processed.
855 * Updated to point at the first character after the current token
856 * @t: Pointers to a token to fill in
857 * @delim: Delimiter character to look for, either newline or space
858 * @lower: true to convert the string to lower case when storing
859 * Returns the new value of t->val, on success, NULL if out of memory
861 static char *get_string(char **p, struct token *t, char delim, int lower)
867 * b and e both start at the beginning of the input stream.
869 * e is incremented until we find the ending delimiter, or a NUL byte
870 * is reached. Then, we take e - b to find the length of the token.
875 if ((delim == ' ' && isspace(*e)) || delim == *e)
883 * Allocate memory to hold the string, and copy it in, converting
884 * characters to lowercase if lower is != 0.
886 t->val = malloc(len + 1);
890 for (i = 0; i < len; i++, b++) {
892 t->val[i] = tolower(*b);
899 /* Update *p so the caller knows where to continue scanning */
907 * get_keyword() - Populate a keyword token with a type and value
909 * Updates the ->type field based on the keyword string in @val
910 * @t: Token to populate
912 static void get_keyword(struct token *t)
916 for (i = 0; keywords[i].val; i++) {
917 if (!strcmp(t->val, keywords[i].val)) {
918 t->type = keywords[i].type;
925 * get_token() - Get the next token
927 * We have to keep track of which state we're in to know if we're looking to get
928 * a string literal or a keyword.
930 * @p: Points to a pointer to the current position in the input being processed.
931 * Updated to point at the first character after the current token
933 static void get_token(char **p, struct token *t, enum lex_state state)
939 /* eat non EOL whitespace */
944 * eat comments. note that string literals can't begin with #, but
945 * can contain a # after their first character.
948 while (*c && *c != '\n')
955 } else if (*c == '\0') {
958 } else if (state == L_SLITERAL) {
959 get_string(&c, t, '\n', 0);
960 } else if (state == L_KEYWORD) {
962 * when we expect a keyword, we first get the next string
963 * token delimited by whitespace, and then check if it
964 * matches a keyword in our keyword list. if it does, it's
965 * converted to a keyword token of the appropriate type, and
966 * if not, it remains a string token.
968 get_string(&c, t, ' ', 1);
976 * eol_or_eof() - Find end of line
978 * Increment *c until we get to the end of the current line, or EOF
980 * @c: Points to a pointer to the current position in the input being processed.
981 * Updated to point at the first character after the current token
983 static void eol_or_eof(char **c)
985 while (**c && **c != '\n')
990 * All of these parse_* functions share some common behavior.
992 * They finish with *c pointing after the token they parse, and return 1 on
993 * success, or < 0 on error.
997 * Parse a string literal and store a pointer it at *dst. String literals
998 * terminate at the end of the line.
1000 static int parse_sliteral(char **c, char **dst)
1005 get_token(c, &t, L_SLITERAL);
1007 if (t.type != T_STRING) {
1008 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
1018 * Parse a base 10 (unsigned) integer and store it at *dst.
1020 static int parse_integer(char **c, int *dst)
1025 get_token(c, &t, L_SLITERAL);
1026 if (t.type != T_STRING) {
1027 printf("Expected string: %.*s\n", (int)(*c - s), s);
1031 *dst = simple_strtol(t.val, NULL, 10);
1038 static int parse_pxefile_top(struct pxe_context *ctx, char *p, ulong base,
1039 struct pxe_menu *cfg, int nest_level);
1042 * Parse an include statement, and retrieve and parse the file it mentions.
1044 * base should point to a location where it's safe to store the file, and
1045 * nest_level should indicate how many nested includes have occurred. For this
1046 * include, nest_level has already been incremented and doesn't need to be
1049 static int handle_include(struct pxe_context *ctx, char **c, unsigned long base,
1050 struct pxe_menu *cfg, int nest_level)
1058 err = parse_sliteral(c, &include_path);
1060 printf("Expected include path: %.*s\n", (int)(*c - s), s);
1064 err = get_pxe_file(ctx, include_path, base);
1066 printf("Couldn't retrieve %s\n", include_path);
1070 buf = map_sysmem(base, 0);
1071 ret = parse_pxefile_top(ctx, buf, base, cfg, nest_level);
1078 * Parse lines that begin with 'menu'.
1080 * base and nest are provided to handle the 'menu include' case.
1082 * base should point to a location where it's safe to store the included file.
1084 * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1085 * a file it includes, 3 when parsing a file included by that file, and so on.
1087 static int parse_menu(struct pxe_context *ctx, char **c, struct pxe_menu *cfg,
1088 unsigned long base, int nest_level)
1094 get_token(c, &t, L_KEYWORD);
1098 err = parse_sliteral(c, &cfg->title);
1103 err = handle_include(ctx, c, base, cfg, nest_level + 1);
1107 err = parse_sliteral(c, &cfg->bmp);
1111 printf("Ignoring malformed menu command: %.*s\n",
1123 * Handles parsing a 'menu line' when we're parsing a label.
1125 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1126 struct pxe_label *label)
1133 get_token(c, &t, L_KEYWORD);
1137 if (!cfg->default_label)
1138 cfg->default_label = strdup(label->name);
1140 if (!cfg->default_label)
1145 parse_sliteral(c, &label->menu);
1148 printf("Ignoring malformed menu command: %.*s\n",
1158 * Handles parsing a 'kernel' label.
1159 * expecting "filename" or "<fit_filename>#cfg"
1161 static int parse_label_kernel(char **c, struct pxe_label *label)
1166 err = parse_sliteral(c, &label->kernel);
1170 /* copy the kernel label to compare with FDT / INITRD when FIT is used */
1171 label->kernel_label = strdup(label->kernel);
1172 if (!label->kernel_label)
1175 s = strstr(label->kernel, "#");
1179 label->config = strdup(s);
1189 * Parses a label and adds it to the list of labels for a menu.
1191 * A label ends when we either get to the end of a file, or
1192 * get some input we otherwise don't have a handler defined
1196 static int parse_label(char **c, struct pxe_menu *cfg)
1201 struct pxe_label *label;
1204 label = label_create();
1208 err = parse_sliteral(c, &label->name);
1210 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1211 label_destroy(label);
1215 list_add_tail(&label->list, &cfg->labels);
1219 get_token(c, &t, L_KEYWORD);
1224 err = parse_label_menu(c, cfg, label);
1229 err = parse_label_kernel(c, label);
1233 err = parse_sliteral(c, &label->append);
1236 s = strstr(label->append, "initrd=");
1240 len = (int)(strchr(s, ' ') - s);
1241 label->initrd = malloc(len + 1);
1242 strncpy(label->initrd, s, len);
1243 label->initrd[len] = '\0';
1249 err = parse_sliteral(c, &label->initrd);
1254 err = parse_sliteral(c, &label->fdt);
1259 err = parse_sliteral(c, &label->fdtdir);
1263 if (!label->fdtoverlays)
1264 err = parse_sliteral(c, &label->fdtoverlays);
1268 label->localboot = 1;
1269 err = parse_integer(c, &label->localboot_val);
1273 err = parse_integer(c, &label->ipappend);
1277 label->kaslrseed = 1;
1285 * put the token back! we don't want it - it's the end
1286 * of a label and whatever token this is, it's
1287 * something for the menu level context to handle.
1299 * This 16 comes from the limit pxelinux imposes on nested includes.
1301 * There is no reason at all we couldn't do more, but some limit helps prevent
1302 * infinite (until crash occurs) recursion if a file tries to include itself.
1304 #define MAX_NEST_LEVEL 16
1307 * Entry point for parsing a menu file. nest_level indicates how many times
1308 * we've nested in includes. It will be 1 for the top level menu file.
1310 * Returns 1 on success, < 0 on error.
1312 static int parse_pxefile_top(struct pxe_context *ctx, char *p, unsigned long base,
1313 struct pxe_menu *cfg, int nest_level)
1316 char *s, *b, *label_name;
1321 if (nest_level > MAX_NEST_LEVEL) {
1322 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1329 get_token(&p, &t, L_KEYWORD);
1335 err = parse_menu(ctx, &p, cfg,
1336 base + ALIGN(strlen(b) + 1, 4),
1341 err = parse_integer(&p, &cfg->timeout);
1345 err = parse_label(&p, cfg);
1350 err = parse_sliteral(&p, &label_name);
1353 if (cfg->default_label)
1354 free(cfg->default_label);
1356 cfg->default_label = label_name;
1362 err = parse_sliteral(&p, &label_name);
1365 if (cfg->fallback_label)
1366 free(cfg->fallback_label);
1368 cfg->fallback_label = label_name;
1374 err = handle_include(ctx, &p,
1375 base + ALIGN(strlen(b), 4), cfg,
1380 err = parse_integer(&p, &cfg->prompt);
1381 // Do not fail if prompt configuration is undefined
1393 printf("Ignoring unknown command: %.*s\n",
1405 void destroy_pxe_menu(struct pxe_menu *cfg)
1407 struct list_head *pos, *n;
1408 struct pxe_label *label;
1411 free(cfg->default_label);
1412 free(cfg->fallback_label);
1414 list_for_each_safe(pos, n, &cfg->labels) {
1415 label = list_entry(pos, struct pxe_label, list);
1417 label_destroy(label);
1423 struct pxe_menu *parse_pxefile(struct pxe_context *ctx, unsigned long menucfg)
1425 struct pxe_menu *cfg;
1429 cfg = malloc(sizeof(struct pxe_menu));
1433 memset(cfg, 0, sizeof(struct pxe_menu));
1435 INIT_LIST_HEAD(&cfg->labels);
1437 buf = map_sysmem(menucfg, 0);
1438 r = parse_pxefile_top(ctx, buf, menucfg, cfg, 1);
1440 if (ctx->use_fallback) {
1441 if (cfg->fallback_label) {
1442 printf("Setting use of fallback\n");
1443 cfg->default_label = cfg->fallback_label;
1445 printf("Selected fallback option, but not set\n");
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;
1498 if (label_override) {
1500 default_num = override_num;
1502 printf("Missing override pxe label: %s\n",
1507 * After we've created items for each label in the menu, set the
1508 * menu's default label if one was specified.
1511 err = menu_default_set(m, default_num);
1513 if (err != -ENOENT) {
1518 printf("Missing default: %s\n", cfg->default_label);
1526 * Try to boot any labels we have yet to attempt to boot.
1528 static void boot_unattempted_labels(struct pxe_context *ctx,
1529 struct pxe_menu *cfg)
1531 struct list_head *pos;
1532 struct pxe_label *label;
1534 list_for_each(pos, &cfg->labels) {
1535 label = list_entry(pos, struct pxe_label, list);
1537 if (!label->attempted)
1538 label_boot(ctx, label);
1542 void handle_pxe_menu(struct pxe_context *ctx, struct pxe_menu *cfg)
1548 if (IS_ENABLED(CONFIG_CMD_BMP)) {
1549 /* display BMP if available */
1551 if (get_relfile(ctx, cfg->bmp, image_load_addr, NULL)) {
1552 #if defined(CONFIG_VIDEO)
1553 struct udevice *dev;
1555 err = uclass_first_device_err(UCLASS_VIDEO, &dev);
1559 bmp_display(image_load_addr,
1560 BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1562 printf("Skipping background bmp %s for failure\n",
1568 m = pxe_menu_to_menu(cfg);
1572 err = menu_get_choice(m, &choice);
1576 * err == 1 means we got a choice back from menu_get_choice.
1578 * err == -ENOENT if the menu was setup to select the default but no
1579 * default was set. in that case, we should continue trying to boot
1580 * labels that haven't been attempted yet.
1582 * otherwise, the user interrupted or there was some other error and
1587 err = label_boot(ctx, choice);
1590 } else if (err != -ENOENT) {
1594 boot_unattempted_labels(ctx, cfg);
1597 int pxe_setup_ctx(struct pxe_context *ctx, struct cmd_tbl *cmdtp,
1598 pxe_getfile_func getfile, void *userdata,
1599 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;
1611 ctx->use_fallback = use_fallback;
1613 /* figure out the boot directory, if there is one */
1614 if (bootfile && strlen(bootfile) >= MAX_TFTP_PATH_LEN)
1616 ctx->bootdir = strdup(bootfile ? bootfile : "");
1621 last_slash = strrchr(bootfile, '/');
1623 path_len = (last_slash - bootfile) + 1;
1625 ctx->bootdir[path_len] = '\0';
1630 void pxe_destroy_ctx(struct pxe_context *ctx)
1635 int pxe_process(struct pxe_context *ctx, ulong pxefile_addr_r, bool prompt)
1637 struct pxe_menu *cfg;
1639 cfg = parse_pxefile(ctx, pxefile_addr_r);
1641 printf("Error parsing config file\n");
1648 handle_pxe_menu(ctx, cfg);
1650 destroy_pxe_menu(cfg);