1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright 2010-2011 Calxeda, Inc.
4 * Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved.
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>
35 #include "pxe_utils.h"
37 #define MAX_TFTP_PATH_LEN 512
39 int pxe_get_file_size(ulong *sizep)
43 val = from_env("filesize");
47 if (strict_strtoul(val, 16, sizep) < 0)
54 * format_mac_pxe() - obtain a MAC address in the PXE format
56 * This produces a MAC-address string in the format for the current ethernet
59 * 01-aa-bb-cc-dd-ee-ff
61 * where aa-ff is the MAC address in hex
63 * @outbuf: Buffer to write string to
64 * @outbuf_len: length of buffer
65 * Return: 1 if OK, -ENOSPC if buffer is too small, -ENOENT is there is no
66 * current ethernet device
68 int format_mac_pxe(char *outbuf, size_t outbuf_len)
72 if (outbuf_len < 21) {
73 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
77 if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
80 sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
81 ethaddr[0], ethaddr[1], ethaddr[2],
82 ethaddr[3], ethaddr[4], ethaddr[5]);
88 * get_relfile() - read a file relative to the PXE file
90 * As in pxelinux, paths to files referenced from files we retrieve are
91 * relative to the location of bootfile. get_relfile takes such a path and
92 * joins it with the bootfile path to get the full path to the target file. If
93 * the bootfile path is NULL, we use file_path as is.
96 * @file_path: File path to read (relative to the PXE file)
97 * @file_addr: Address to load file to
98 * @filesizep: If not NULL, returns the file size in bytes
99 * Returns 1 for success, or < 0 on error
101 static int get_relfile(struct pxe_context *ctx, const char *file_path,
102 unsigned long file_addr, ulong *filesizep)
105 char relfile[MAX_TFTP_PATH_LEN + 1];
110 if (file_path[0] == '/' && ctx->allow_abs_path)
113 strncpy(relfile, ctx->bootdir, MAX_TFTP_PATH_LEN);
115 path_len = strlen(file_path) + strlen(relfile);
117 if (path_len > MAX_TFTP_PATH_LEN) {
118 printf("Base path too long (%s%s)\n", relfile, file_path);
120 return -ENAMETOOLONG;
123 strcat(relfile, file_path);
125 printf("Retrieving file: %s\n", relfile);
127 sprintf(addr_buf, "%lx", file_addr);
129 ret = ctx->getfile(ctx, relfile, addr_buf, &size);
131 return log_msg_ret("get", ret);
139 * get_pxe_file() - read a file
141 * The file is read and nul-terminated
144 * @file_path: File path to read (relative to the PXE file)
145 * @file_addr: Address to load file to
146 * Returns 1 for success, or < 0 on error
148 int get_pxe_file(struct pxe_context *ctx, const char *file_path,
155 err = get_relfile(ctx, file_path, file_addr, &size);
159 buf = map_sysmem(file_addr + size, 1);
166 #define PXELINUX_DIR "pxelinux.cfg/"
169 * get_pxelinux_path() - Get a file in the pxelinux.cfg/ directory
172 * @file: Filename to process (relative to pxelinux.cfg/)
173 * Returns 1 for success, -ENAMETOOLONG if the resulting path is too long.
174 * or other value < 0 on other error
176 int get_pxelinux_path(struct pxe_context *ctx, const char *file,
177 unsigned long pxefile_addr_r)
179 size_t base_len = strlen(PXELINUX_DIR);
180 char path[MAX_TFTP_PATH_LEN + 1];
182 if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
183 printf("path (%s%s) too long, skipping\n",
185 return -ENAMETOOLONG;
188 sprintf(path, PXELINUX_DIR "%s", file);
190 return get_pxe_file(ctx, path, pxefile_addr_r);
194 * get_relfile_envaddr() - read a file to an address in an env var
196 * Wrapper to make it easier to store the file at file_path in the location
197 * specified by envaddr_name. file_path will be joined to the bootfile path,
198 * if any is specified.
201 * @file_path: File path to read (relative to the PXE file)
202 * @envaddr_name: Name of environment variable which contains the address to
204 * @filesizep: Returns the file size in bytes
205 * Returns 1 on success, -ENOENT if @envaddr_name does not exist as an
206 * environment variable, -EINVAL if its format is not valid hex, or other
207 * value < 0 on other error
209 static int get_relfile_envaddr(struct pxe_context *ctx, const char *file_path,
210 const char *envaddr_name, ulong *filesizep)
212 unsigned long file_addr;
215 envaddr = from_env(envaddr_name);
219 if (strict_strtoul(envaddr, 16, &file_addr) < 0)
222 return get_relfile(ctx, file_path, file_addr, filesizep);
226 * label_create() - crate a new PXE label
228 * Allocates memory for and initializes a pxe_label. This uses malloc, so the
229 * result must be free()'d to reclaim the memory.
231 * Returns a pointer to the label, or NULL if out of memory
233 static struct pxe_label *label_create(void)
235 struct pxe_label *label;
237 label = malloc(sizeof(struct pxe_label));
241 memset(label, 0, sizeof(struct pxe_label));
247 * label_destroy() - free the memory used by a pxe_label
249 * This frees @label itself as well as memory used by its name,
250 * kernel, config, append, initrd, fdt, fdtdir and fdtoverlay members, if
253 * So - be sure to only use dynamically allocated memory for the members of
254 * the pxe_label struct, unless you want to clean it up first. These are
255 * currently only created by the pxe file parsing code.
257 * @label: Label to free
259 static void label_destroy(struct pxe_label *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",
528 if (get_relfile_envaddr(ctx, label->initrd, "ramdisk_addr_r",
530 printf("Skipping %s for failure retrieving initrd\n",
535 initrd_addr_str = env_get("ramdisk_addr_r");
536 size = snprintf(initrd_str, sizeof(initrd_str), "%s:%lx",
537 initrd_addr_str, size);
538 if (size >= sizeof(initrd_str))
542 if (get_relfile_envaddr(ctx, label->kernel, "kernel_addr_r",
544 printf("Skipping %s for failure retrieving kernel\n",
549 if (label->ipappend & 0x1) {
550 sprintf(ip_str, " ip=%s:%s:%s:%s",
551 env_get("ipaddr"), env_get("serverip"),
552 env_get("gatewayip"), env_get("netmask"));
555 if (IS_ENABLED(CONFIG_CMD_NET)) {
556 if (label->ipappend & 0x2) {
559 strcpy(mac_str, " BOOTIF=");
560 err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
566 if ((label->ipappend & 0x3) || label->append) {
567 char bootargs[CONFIG_SYS_CBSIZE] = "";
568 char finalbootargs[CONFIG_SYS_CBSIZE];
570 if (strlen(label->append ?: "") +
571 strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
572 printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
573 strlen(label->append ?: ""),
574 strlen(ip_str), strlen(mac_str),
580 strncpy(bootargs, label->append, sizeof(bootargs));
582 strcat(bootargs, ip_str);
583 strcat(bootargs, mac_str);
585 cli_simple_process_macros(bootargs, finalbootargs,
586 sizeof(finalbootargs));
587 env_set("bootargs", finalbootargs);
588 printf("append: %s\n", finalbootargs);
591 kernel_addr = env_get("kernel_addr_r");
593 /* for FIT, append the configuration identifier */
595 int len = strlen(kernel_addr) + strlen(label->config) + 1;
597 fit_addr = malloc(len);
599 printf("malloc fail (FIT address)\n");
602 snprintf(fit_addr, len, "%s%s", kernel_addr, label->config);
603 kernel_addr = fit_addr;
607 * fdt usage is optional:
608 * It handles the following scenarios.
610 * Scenario 1: If fdt_addr_r specified and "fdt" or "fdtdir" label is
611 * defined in pxe file, retrieve fdt blob from server. Pass fdt_addr_r to
612 * bootm, and adjust argc appropriately.
614 * If retrieve fails and no exact fdt blob is specified in pxe file with
615 * "fdt" label, try Scenario 2.
617 * Scenario 2: If there is an fdt_addr specified, pass it along to
618 * bootm, and adjust argc appropriately.
620 * Scenario 3: If there is an fdtcontroladdr specified, pass it along to
621 * bootm, and adjust argc appropriately.
623 * Scenario 4: fdt blob is not available.
625 bootm_argv[3] = env_get("fdt_addr_r");
627 /* if fdt label is defined then get fdt from server */
629 char *fdtfile = NULL;
630 char *fdtfilefree = NULL;
633 fdtfile = label->fdt;
634 } else if (label->fdtdir) {
635 char *f1, *f2, *f3, *f4, *slash;
637 f1 = env_get("fdtfile");
644 * For complex cases where this code doesn't
645 * generate the correct filename, the board
646 * code should set $fdtfile during early boot,
647 * or the boot scripts should set $fdtfile
648 * before invoking "pxe" or "sysboot".
652 f3 = env_get("board");
664 len = strlen(label->fdtdir);
667 else if (label->fdtdir[len - 1] != '/')
672 len = strlen(label->fdtdir) + strlen(slash) +
673 strlen(f1) + strlen(f2) + strlen(f3) +
675 fdtfilefree = malloc(len);
677 printf("malloc fail (FDT filename)\n");
681 snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
682 label->fdtdir, slash, f1, f2, f3, f4);
683 fdtfile = fdtfilefree;
687 int err = get_relfile_envaddr(ctx, fdtfile,
692 bootm_argv[3] = NULL;
695 printf("Skipping %s for failure retrieving FDT\n",
701 if (label->kaslrseed)
702 label_boot_kaslrseed();
704 #ifdef CONFIG_OF_LIBFDT_OVERLAY
705 if (label->fdtoverlays)
706 label_boot_fdtoverlay(ctx, label);
709 bootm_argv[3] = NULL;
713 bootm_argv[1] = kernel_addr;
714 zboot_argv[1] = kernel_addr;
716 if (initrd_addr_str) {
717 bootm_argv[2] = initrd_str;
720 zboot_argv[3] = initrd_addr_str;
721 zboot_argv[4] = initrd_filesize;
726 bootm_argv[3] = env_get("fdt_addr");
729 bootm_argv[3] = env_get("fdtcontroladdr");
737 kernel_addr_r = genimg_get_kernel_addr(kernel_addr);
738 buf = map_sysmem(kernel_addr_r, 0);
739 /* Try bootm for legacy and FIT format image */
740 if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID &&
741 IS_ENABLED(CONFIG_CMD_BOOTM))
742 do_bootm(ctx->cmdtp, 0, bootm_argc, bootm_argv);
743 /* Try booting an AArch64 Linux kernel image */
744 else if (IS_ENABLED(CONFIG_CMD_BOOTI))
745 do_booti(ctx->cmdtp, 0, bootm_argc, bootm_argv);
746 /* Try booting a Image */
747 else if (IS_ENABLED(CONFIG_CMD_BOOTZ))
748 do_bootz(ctx->cmdtp, 0, bootm_argc, bootm_argv);
749 /* Try booting an x86_64 Linux kernel image */
750 else if (IS_ENABLED(CONFIG_CMD_ZBOOT))
751 do_zboot_parent(ctx->cmdtp, 0, zboot_argc, zboot_argv, NULL);
761 /** 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,},
822 * enum lex_state - lexer state
824 * Since pxe(linux) files don't have a token to identify the start of a
825 * literal, we have to keep track of when we're in a state where a literal is
826 * expected vs when we're in a state a keyword is expected.
835 * get_string() - retrieves a string from *p and stores it as a token in *t.
837 * This is used for scanning both string literals and keywords.
839 * Characters from *p are copied into t-val until a character equal to
840 * delim is found, or a NUL byte is reached. If delim has the special value of
841 * ' ', any whitespace character will be used as a delimiter.
843 * If lower is unequal to 0, uppercase characters will be converted to
844 * lowercase in the result. This is useful to make keywords case
847 * The location of *p is updated to point to the first character after the end
848 * of the token - the ending delimiter.
850 * Memory for t->val is allocated using malloc and must be free()'d to reclaim
853 * @p: Points to a pointer to the current position in the input being processed.
854 * Updated to point at the first character after the current token
855 * @t: Pointers to a token to fill in
856 * @delim: Delimiter character to look for, either newline or space
857 * @lower: true to convert the string to lower case when storing
858 * Returns the new value of t->val, on success, NULL if out of memory
860 static char *get_string(char **p, struct token *t, char delim, int lower)
866 * b and e both start at the beginning of the input stream.
868 * e is incremented until we find the ending delimiter, or a NUL byte
869 * is reached. Then, we take e - b to find the length of the token.
874 if ((delim == ' ' && isspace(*e)) || delim == *e)
882 * Allocate memory to hold the string, and copy it in, converting
883 * characters to lowercase if lower is != 0.
885 t->val = malloc(len + 1);
889 for (i = 0; i < len; i++, b++) {
891 t->val[i] = tolower(*b);
898 /* Update *p so the caller knows where to continue scanning */
906 * get_keyword() - Populate a keyword token with a type and value
908 * Updates the ->type field based on the keyword string in @val
909 * @t: Token to populate
911 static void get_keyword(struct token *t)
915 for (i = 0; keywords[i].val; i++) {
916 if (!strcmp(t->val, keywords[i].val)) {
917 t->type = keywords[i].type;
924 * get_token() - Get the next token
926 * We have to keep track of which state we're in to know if we're looking to get
927 * a string literal or a keyword.
929 * @p: Points to a pointer to the current position in the input being processed.
930 * Updated to point at the first character after the current token
932 static void get_token(char **p, struct token *t, enum lex_state state)
938 /* eat non EOL whitespace */
943 * eat comments. note that string literals can't begin with #, but
944 * can contain a # after their first character.
947 while (*c && *c != '\n')
954 } else if (*c == '\0') {
957 } else if (state == L_SLITERAL) {
958 get_string(&c, t, '\n', 0);
959 } else if (state == L_KEYWORD) {
961 * when we expect a keyword, we first get the next string
962 * token delimited by whitespace, and then check if it
963 * matches a keyword in our keyword list. if it does, it's
964 * converted to a keyword token of the appropriate type, and
965 * if not, it remains a string token.
967 get_string(&c, t, ' ', 1);
975 * eol_or_eof() - Find end of line
977 * Increment *c until we get to the end of the current line, or EOF
979 * @c: Points to a pointer to the current position in the input being processed.
980 * Updated to point at the first character after the current token
982 static void eol_or_eof(char **c)
984 while (**c && **c != '\n')
989 * All of these parse_* functions share some common behavior.
991 * They finish with *c pointing after the token they parse, and return 1 on
992 * success, or < 0 on error.
996 * Parse a string literal and store a pointer it at *dst. String literals
997 * terminate at the end of the line.
999 static int parse_sliteral(char **c, char **dst)
1004 get_token(c, &t, L_SLITERAL);
1006 if (t.type != T_STRING) {
1007 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
1017 * Parse a base 10 (unsigned) integer and store it at *dst.
1019 static int parse_integer(char **c, int *dst)
1024 get_token(c, &t, L_SLITERAL);
1025 if (t.type != T_STRING) {
1026 printf("Expected string: %.*s\n", (int)(*c - s), s);
1030 *dst = simple_strtol(t.val, NULL, 10);
1037 static int parse_pxefile_top(struct pxe_context *ctx, char *p, ulong base,
1038 struct pxe_menu *cfg, int nest_level);
1041 * Parse an include statement, and retrieve and parse the file it mentions.
1043 * base should point to a location where it's safe to store the file, and
1044 * nest_level should indicate how many nested includes have occurred. For this
1045 * include, nest_level has already been incremented and doesn't need to be
1048 static int handle_include(struct pxe_context *ctx, char **c, unsigned long base,
1049 struct pxe_menu *cfg, int nest_level)
1057 err = parse_sliteral(c, &include_path);
1059 printf("Expected include path: %.*s\n", (int)(*c - s), s);
1063 err = get_pxe_file(ctx, include_path, base);
1065 printf("Couldn't retrieve %s\n", include_path);
1069 buf = map_sysmem(base, 0);
1070 ret = parse_pxefile_top(ctx, buf, base, cfg, nest_level);
1077 * Parse lines that begin with 'menu'.
1079 * base and nest are provided to handle the 'menu include' case.
1081 * base should point to a location where it's safe to store the included file.
1083 * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1084 * a file it includes, 3 when parsing a file included by that file, and so on.
1086 static int parse_menu(struct pxe_context *ctx, char **c, struct pxe_menu *cfg,
1087 unsigned long base, int nest_level)
1093 get_token(c, &t, L_KEYWORD);
1097 err = parse_sliteral(c, &cfg->title);
1102 err = handle_include(ctx, c, base, cfg, nest_level + 1);
1106 err = parse_sliteral(c, &cfg->bmp);
1110 printf("Ignoring malformed menu command: %.*s\n",
1122 * Handles parsing a 'menu line' when we're parsing a label.
1124 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1125 struct pxe_label *label)
1132 get_token(c, &t, L_KEYWORD);
1136 if (!cfg->default_label)
1137 cfg->default_label = strdup(label->name);
1139 if (!cfg->default_label)
1144 parse_sliteral(c, &label->menu);
1147 printf("Ignoring malformed menu command: %.*s\n",
1157 * Handles parsing a 'kernel' label.
1158 * expecting "filename" or "<fit_filename>#cfg"
1160 static int parse_label_kernel(char **c, struct pxe_label *label)
1165 err = parse_sliteral(c, &label->kernel);
1169 s = strstr(label->kernel, "#");
1173 label->config = malloc(strlen(s) + 1);
1177 strcpy(label->config, s);
1184 * Parses a label and adds it to the list of labels for a menu.
1186 * A label ends when we either get to the end of a file, or
1187 * get some input we otherwise don't have a handler defined
1191 static int parse_label(char **c, struct pxe_menu *cfg)
1196 struct pxe_label *label;
1199 label = label_create();
1203 err = parse_sliteral(c, &label->name);
1205 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1206 label_destroy(label);
1210 list_add_tail(&label->list, &cfg->labels);
1214 get_token(c, &t, L_KEYWORD);
1219 err = parse_label_menu(c, cfg, label);
1224 err = parse_label_kernel(c, label);
1228 err = parse_sliteral(c, &label->append);
1231 s = strstr(label->append, "initrd=");
1235 len = (int)(strchr(s, ' ') - s);
1236 label->initrd = malloc(len + 1);
1237 strncpy(label->initrd, s, len);
1238 label->initrd[len] = '\0';
1244 err = parse_sliteral(c, &label->initrd);
1249 err = parse_sliteral(c, &label->fdt);
1254 err = parse_sliteral(c, &label->fdtdir);
1258 if (!label->fdtoverlays)
1259 err = parse_sliteral(c, &label->fdtoverlays);
1263 label->localboot = 1;
1264 err = parse_integer(c, &label->localboot_val);
1268 err = parse_integer(c, &label->ipappend);
1272 label->kaslrseed = 1;
1280 * put the token back! we don't want it - it's the end
1281 * of a label and whatever token this is, it's
1282 * something for the menu level context to handle.
1294 * This 16 comes from the limit pxelinux imposes on nested includes.
1296 * There is no reason at all we couldn't do more, but some limit helps prevent
1297 * infinite (until crash occurs) recursion if a file tries to include itself.
1299 #define MAX_NEST_LEVEL 16
1302 * Entry point for parsing a menu file. nest_level indicates how many times
1303 * we've nested in includes. It will be 1 for the top level menu file.
1305 * Returns 1 on success, < 0 on error.
1307 static int parse_pxefile_top(struct pxe_context *ctx, char *p, unsigned long base,
1308 struct pxe_menu *cfg, int nest_level)
1311 char *s, *b, *label_name;
1316 if (nest_level > MAX_NEST_LEVEL) {
1317 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1324 get_token(&p, &t, L_KEYWORD);
1330 err = parse_menu(ctx, &p, cfg,
1331 base + ALIGN(strlen(b) + 1, 4),
1336 err = parse_integer(&p, &cfg->timeout);
1340 err = parse_label(&p, cfg);
1345 err = parse_sliteral(&p, &label_name);
1348 if (cfg->default_label)
1349 free(cfg->default_label);
1351 cfg->default_label = label_name;
1357 err = handle_include(ctx, &p,
1358 base + ALIGN(strlen(b), 4), cfg,
1373 printf("Ignoring unknown command: %.*s\n",
1385 void destroy_pxe_menu(struct pxe_menu *cfg)
1387 struct list_head *pos, *n;
1388 struct pxe_label *label;
1391 free(cfg->default_label);
1393 list_for_each_safe(pos, n, &cfg->labels) {
1394 label = list_entry(pos, struct pxe_label, list);
1396 label_destroy(label);
1402 struct pxe_menu *parse_pxefile(struct pxe_context *ctx, unsigned long menucfg)
1404 struct pxe_menu *cfg;
1408 cfg = malloc(sizeof(struct pxe_menu));
1412 memset(cfg, 0, sizeof(struct pxe_menu));
1414 INIT_LIST_HEAD(&cfg->labels);
1416 buf = map_sysmem(menucfg, 0);
1417 r = parse_pxefile_top(ctx, buf, menucfg, cfg, 1);
1420 destroy_pxe_menu(cfg);
1428 * Converts a pxe_menu struct into a menu struct for use with U-Boot's generic
1431 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1433 struct pxe_label *label;
1434 struct list_head *pos;
1436 char *label_override;
1439 char *default_num = NULL;
1440 char *override_num = NULL;
1443 * Create a menu and add items for all the labels.
1445 m = menu_create(cfg->title, DIV_ROUND_UP(cfg->timeout, 10),
1446 cfg->prompt, NULL, label_print, NULL, NULL);
1450 label_override = env_get("pxe_label_override");
1452 list_for_each(pos, &cfg->labels) {
1453 label = list_entry(pos, struct pxe_label, list);
1455 sprintf(label->num, "%d", i++);
1456 if (menu_item_add(m, label->num, label) != 1) {
1460 if (cfg->default_label &&
1461 (strcmp(label->name, cfg->default_label) == 0))
1462 default_num = label->num;
1463 if (label_override && !strcmp(label->name, label_override))
1464 override_num = label->num;
1468 if (label_override) {
1470 default_num = override_num;
1472 printf("Missing override pxe label: %s\n",
1477 * After we've created items for each label in the menu, set the
1478 * menu's default label if one was specified.
1481 err = menu_default_set(m, default_num);
1483 if (err != -ENOENT) {
1488 printf("Missing default: %s\n", cfg->default_label);
1496 * Try to boot any labels we have yet to attempt to boot.
1498 static void boot_unattempted_labels(struct pxe_context *ctx,
1499 struct pxe_menu *cfg)
1501 struct list_head *pos;
1502 struct pxe_label *label;
1504 list_for_each(pos, &cfg->labels) {
1505 label = list_entry(pos, struct pxe_label, list);
1507 if (!label->attempted)
1508 label_boot(ctx, label);
1512 void handle_pxe_menu(struct pxe_context *ctx, struct pxe_menu *cfg)
1518 if (IS_ENABLED(CONFIG_CMD_BMP)) {
1519 /* display BMP if available */
1521 if (get_relfile(ctx, cfg->bmp, image_load_addr, NULL)) {
1522 #if defined(CONFIG_DM_VIDEO)
1523 struct udevice *dev;
1525 err = uclass_first_device_err(UCLASS_VIDEO, &dev);
1529 bmp_display(image_load_addr,
1530 BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1532 printf("Skipping background bmp %s for failure\n",
1538 m = pxe_menu_to_menu(cfg);
1542 err = menu_get_choice(m, &choice);
1546 * err == 1 means we got a choice back from menu_get_choice.
1548 * err == -ENOENT if the menu was setup to select the default but no
1549 * default was set. in that case, we should continue trying to boot
1550 * labels that haven't been attempted yet.
1552 * otherwise, the user interrupted or there was some other error and
1557 err = label_boot(ctx, choice);
1560 } else if (err != -ENOENT) {
1564 boot_unattempted_labels(ctx, cfg);
1567 int pxe_setup_ctx(struct pxe_context *ctx, struct cmd_tbl *cmdtp,
1568 pxe_getfile_func getfile, void *userdata,
1569 bool allow_abs_path, const char *bootfile)
1571 const char *last_slash;
1572 size_t path_len = 0;
1574 memset(ctx, '\0', sizeof(*ctx));
1576 ctx->getfile = getfile;
1577 ctx->userdata = userdata;
1578 ctx->allow_abs_path = allow_abs_path;
1580 /* figure out the boot directory, if there is one */
1581 if (bootfile && strlen(bootfile) >= MAX_TFTP_PATH_LEN)
1583 ctx->bootdir = strdup(bootfile ? bootfile : "");
1588 last_slash = strrchr(bootfile, '/');
1590 path_len = (last_slash - bootfile) + 1;
1592 ctx->bootdir[path_len] = '\0';
1597 void pxe_destroy_ctx(struct pxe_context *ctx)
1602 int pxe_process(struct pxe_context *ctx, ulong pxefile_addr_r, bool prompt)
1604 struct pxe_menu *cfg;
1606 cfg = parse_pxefile(ctx, pxefile_addr_r);
1608 printf("Error parsing config file\n");
1615 handle_pxe_menu(ctx, cfg);
1617 destroy_pxe_menu(cfg);