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>
17 #include <linux/libfdt.h>
18 #include <linux/string.h>
19 #include <linux/ctype.h>
21 #include <linux/list.h>
29 #include "pxe_utils.h"
31 #define MAX_TFTP_PATH_LEN 512
34 * format_mac_pxe() - obtain a MAC address in the PXE format
36 * This produces a MAC-address string in the format for the current ethernet
39 * 01-aa-bb-cc-dd-ee-ff
41 * where aa-ff is the MAC address in hex
43 * @outbuf: Buffer to write string to
44 * @outbuf_len: length of buffer
45 * @return 1 if OK, -ENOSPC if buffer is too small, -ENOENT is there is no
46 * current ethernet device
48 int format_mac_pxe(char *outbuf, size_t outbuf_len)
52 if (outbuf_len < 21) {
53 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
57 if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
60 sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
61 ethaddr[0], ethaddr[1], ethaddr[2],
62 ethaddr[3], ethaddr[4], ethaddr[5]);
68 * get_bootfile_path() - Figure out the path of a file to read
70 * Returns the directory the file specified in the 'bootfile' env variable is
71 * in. If bootfile isn't defined in the environment, return NULL, which should
72 * be interpreted as "don't prepend anything to paths".
74 * @file_path: File path to read (relative to the PXE file)
75 * @bootfile_path: Place to put the bootfile path
76 * @bootfile_path_size: Size of @bootfile_path in bytes
77 * @allow_abs_path: true to allow an absolute path (where @file_path starts with
78 * '/', false to return an empty path (and success) in that case
79 * Returns 1 for success, -ENOSPC if bootfile_path_size is to small to hold the
82 static int get_bootfile_path(const char *file_path, char *bootfile_path,
83 size_t bootfile_path_size, bool allow_abs_path)
85 char *bootfile, *last_slash;
88 /* Only syslinux allows absolute paths */
89 if (file_path[0] == '/' && allow_abs_path)
92 bootfile = from_env("bootfile");
96 last_slash = strrchr(bootfile, '/');
100 path_len = (last_slash - bootfile) + 1;
102 if (bootfile_path_size < path_len) {
103 printf("bootfile_path too small. (%zd < %zd)\n",
104 bootfile_path_size, path_len);
109 strncpy(bootfile_path, bootfile, path_len);
112 bootfile_path[path_len] = '\0';
118 * get_relfile() - read a file relative to the PXE file
120 * As in pxelinux, paths to files referenced from files we retrieve are
121 * relative to the location of bootfile. get_relfile takes such a path and
122 * joins it with the bootfile path to get the full path to the target file. If
123 * the bootfile path is NULL, we use file_path as is.
126 * @file_path: File path to read (relative to the PXE file)
127 * @file_addr: Address to load file to
128 * Returns 1 for success, or < 0 on error
130 static int get_relfile(struct pxe_context *ctx, const char *file_path,
131 unsigned long file_addr)
134 char relfile[MAX_TFTP_PATH_LEN + 1];
138 err = get_bootfile_path(file_path, relfile, sizeof(relfile),
139 ctx->allow_abs_path);
143 path_len = strlen(file_path);
144 path_len += strlen(relfile);
146 if (path_len > MAX_TFTP_PATH_LEN) {
147 printf("Base path too long (%s%s)\n", relfile, file_path);
149 return -ENAMETOOLONG;
152 strcat(relfile, file_path);
154 printf("Retrieving file: %s\n", relfile);
156 sprintf(addr_buf, "%lx", file_addr);
158 return ctx->getfile(ctx, relfile, addr_buf);
162 * get_pxe_file() - read a file
164 * The file is read and nul-terminated
167 * @file_path: File path to read (relative to the PXE file)
168 * @file_addr: Address to load file to
169 * Returns 1 for success, or < 0 on error
171 int get_pxe_file(struct pxe_context *ctx, const char *file_path,
172 unsigned long file_addr)
174 unsigned long config_file_size;
179 err = get_relfile(ctx, file_path, file_addr);
184 * the file comes without a NUL byte at the end, so find out its size
185 * and add the NUL byte.
187 tftp_filesize = from_env("filesize");
191 if (strict_strtoul(tftp_filesize, 16, &config_file_size) < 0)
194 buf = map_sysmem(file_addr + config_file_size, 1);
201 #define PXELINUX_DIR "pxelinux.cfg/"
204 * get_pxelinux_path() - Get a file in the pxelinux.cfg/ directory
207 * @file: Filename to process (relative to pxelinux.cfg/)
208 * Returns 1 for success, -ENAMETOOLONG if the resulting path is too long.
209 * or other value < 0 on other error
211 int get_pxelinux_path(struct pxe_context *ctx, const char *file,
212 unsigned long pxefile_addr_r)
214 size_t base_len = strlen(PXELINUX_DIR);
215 char path[MAX_TFTP_PATH_LEN + 1];
217 if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
218 printf("path (%s%s) too long, skipping\n",
220 return -ENAMETOOLONG;
223 sprintf(path, PXELINUX_DIR "%s", file);
225 return get_pxe_file(ctx, path, pxefile_addr_r);
229 * get_relfile_envaddr() - read a file to an address in an env var
231 * Wrapper to make it easier to store the file at file_path in the location
232 * specified by envaddr_name. file_path will be joined to the bootfile path,
233 * if any is specified.
236 * @file_path: File path to read (relative to the PXE file)
237 * @envaddr_name: Name of environment variable which contains the address to
239 * Returns 1 on success, -ENOENT if @envaddr_name does not exist as an
240 * environment variable, -EINVAL if its format is not valid hex, or other
241 * value < 0 on other error
243 static int get_relfile_envaddr(struct pxe_context *ctx, const char *file_path,
244 const char *envaddr_name)
246 unsigned long file_addr;
249 envaddr = from_env(envaddr_name);
253 if (strict_strtoul(envaddr, 16, &file_addr) < 0)
256 return get_relfile(ctx, file_path, file_addr);
260 * label_create() - crate a new PXE label
262 * Allocates memory for and initializes a pxe_label. This uses malloc, so the
263 * result must be free()'d to reclaim the memory.
265 * Returns a pointer to the label, or NULL if out of memory
267 static struct pxe_label *label_create(void)
269 struct pxe_label *label;
271 label = malloc(sizeof(struct pxe_label));
275 memset(label, 0, sizeof(struct pxe_label));
281 * label_destroy() - free the memory used by a pxe_label
283 * This frees @label itself as well as memory used by its name,
284 * kernel, config, append, initrd, fdt, fdtdir and fdtoverlay members, if
287 * So - be sure to only use dynamically allocated memory for the members of
288 * the pxe_label struct, unless you want to clean it up first. These are
289 * currently only created by the pxe file parsing code.
291 * @label: Label to free
293 static void label_destroy(struct pxe_label *label)
302 free(label->fdtoverlays);
307 * label_print() - Print a label and its string members if they're defined
309 * This is passed as a callback to the menu code for displaying each
312 * @data: Label to print (is cast to struct pxe_label *)
314 static void label_print(void *data)
316 struct pxe_label *label = data;
317 const char *c = label->menu ? label->menu : label->name;
319 printf("%s:\t%s\n", label->num, c);
323 * label_localboot() - Boot a label that specified 'localboot'
325 * This requires that the 'localcmd' environment variable is defined. Its
326 * contents will be executed as U-Boot commands. If the label specified an
327 * 'append' line, its contents will be used to overwrite the contents of the
328 * 'bootargs' environment variable prior to running 'localcmd'.
330 * @label: Label to process
331 * Returns 1 on success or < 0 on error
333 static int label_localboot(struct pxe_label *label)
337 localcmd = from_env("localcmd");
342 char bootargs[CONFIG_SYS_CBSIZE];
344 cli_simple_process_macros(label->append, bootargs,
346 env_set("bootargs", bootargs);
349 debug("running: %s\n", localcmd);
351 return run_command_list(localcmd, strlen(localcmd), 0);
355 * label_boot_fdtoverlay() - Loads fdt overlays specified in 'fdtoverlays'
358 * @label: Label to process
360 #ifdef CONFIG_OF_LIBFDT_OVERLAY
361 static void label_boot_fdtoverlay(struct pxe_context *ctx,
362 struct pxe_label *label)
364 char *fdtoverlay = label->fdtoverlays;
365 struct fdt_header *working_fdt;
366 char *fdtoverlay_addr_env;
367 ulong fdtoverlay_addr;
371 /* Get the main fdt and map it */
372 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
373 working_fdt = map_sysmem(fdt_addr, 0);
374 err = fdt_check_header(working_fdt);
378 /* Get the specific overlay loading address */
379 fdtoverlay_addr_env = env_get("fdtoverlay_addr_r");
380 if (!fdtoverlay_addr_env) {
381 printf("Invalid fdtoverlay_addr_r for loading overlays\n");
385 fdtoverlay_addr = hextoul(fdtoverlay_addr_env, NULL);
387 /* Cycle over the overlay files and apply them in order */
389 struct fdt_header *blob;
394 /* Drop leading spaces */
395 while (*fdtoverlay == ' ')
398 /* Copy a single filename if multiple provided */
399 end = strstr(fdtoverlay, " ");
401 len = (int)(end - fdtoverlay);
402 overlayfile = malloc(len + 1);
403 strncpy(overlayfile, fdtoverlay, len);
404 overlayfile[len] = '\0';
406 overlayfile = fdtoverlay;
408 if (!strlen(overlayfile))
411 /* Load overlay file */
412 err = get_relfile_envaddr(ctx, overlayfile,
413 "fdtoverlay_addr_r");
415 printf("Failed loading overlay %s\n", overlayfile);
419 /* Resize main fdt */
420 fdt_shrink_to_minimum(working_fdt, 8192);
422 blob = map_sysmem(fdtoverlay_addr, 0);
423 err = fdt_check_header(blob);
425 printf("Invalid overlay %s, skipping\n",
430 err = fdt_overlay_apply_verbose(working_fdt, blob);
432 printf("Failed to apply overlay %s, skipping\n",
440 } while ((fdtoverlay = strstr(fdtoverlay, " ")));
445 * label_boot() - Boot according to the contents of a pxe_label
447 * If we can't boot for any reason, we return. A successful boot never
450 * The kernel will be stored in the location given by the 'kernel_addr_r'
451 * environment variable.
453 * If the label specifies an initrd file, it will be stored in the location
454 * given by the 'ramdisk_addr_r' environment variable.
456 * If the label specifies an 'append' line, its contents will overwrite that
457 * of the 'bootargs' environment variable.
460 * @label: Label to process
461 * Returns does not return on success, otherwise returns 0 if a localboot
462 * label was processed, or 1 on error
464 static int label_boot(struct pxe_context *ctx, struct pxe_label *label)
466 char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
467 char *zboot_argv[] = { "zboot", NULL, "0", NULL, NULL };
468 char *kernel_addr = NULL;
469 char *initrd_addr_str = NULL;
470 char initrd_filesize[10];
472 char mac_str[29] = "";
473 char ip_str[68] = "";
474 char *fit_addr = NULL;
483 label->attempted = 1;
485 if (label->localboot) {
486 if (label->localboot_val >= 0)
487 label_localboot(label);
491 if (!label->kernel) {
492 printf("No kernel given, skipping %s\n",
498 if (get_relfile_envaddr(ctx, label->initrd, "ramdisk_addr_r") < 0) {
499 printf("Skipping %s for failure retrieving initrd\n",
504 initrd_addr_str = env_get("ramdisk_addr_r");
505 strncpy(initrd_filesize, env_get("filesize"), 9);
507 strncpy(initrd_str, initrd_addr_str, 18);
508 strcat(initrd_str, ":");
509 strncat(initrd_str, initrd_filesize, 9);
512 if (get_relfile_envaddr(ctx, label->kernel, "kernel_addr_r") < 0) {
513 printf("Skipping %s for failure retrieving kernel\n",
518 if (label->ipappend & 0x1) {
519 sprintf(ip_str, " ip=%s:%s:%s:%s",
520 env_get("ipaddr"), env_get("serverip"),
521 env_get("gatewayip"), env_get("netmask"));
524 if (IS_ENABLED(CONFIG_CMD_NET)) {
525 if (label->ipappend & 0x2) {
528 strcpy(mac_str, " BOOTIF=");
529 err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
535 if ((label->ipappend & 0x3) || label->append) {
536 char bootargs[CONFIG_SYS_CBSIZE] = "";
537 char finalbootargs[CONFIG_SYS_CBSIZE];
539 if (strlen(label->append ?: "") +
540 strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
541 printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
542 strlen(label->append ?: ""),
543 strlen(ip_str), strlen(mac_str),
549 strncpy(bootargs, label->append, sizeof(bootargs));
551 strcat(bootargs, ip_str);
552 strcat(bootargs, mac_str);
554 cli_simple_process_macros(bootargs, finalbootargs,
555 sizeof(finalbootargs));
556 env_set("bootargs", finalbootargs);
557 printf("append: %s\n", finalbootargs);
560 kernel_addr = env_get("kernel_addr_r");
562 /* for FIT, append the configuration identifier */
564 int len = strlen(kernel_addr) + strlen(label->config) + 1;
566 fit_addr = malloc(len);
568 printf("malloc fail (FIT address)\n");
571 snprintf(fit_addr, len, "%s%s", kernel_addr, label->config);
572 kernel_addr = fit_addr;
576 * fdt usage is optional:
577 * It handles the following scenarios.
579 * Scenario 1: If fdt_addr_r specified and "fdt" or "fdtdir" label is
580 * defined in pxe file, retrieve fdt blob from server. Pass fdt_addr_r to
581 * bootm, and adjust argc appropriately.
583 * If retrieve fails and no exact fdt blob is specified in pxe file with
584 * "fdt" label, try Scenario 2.
586 * Scenario 2: If there is an fdt_addr specified, pass it along to
587 * bootm, and adjust argc appropriately.
589 * Scenario 3: fdt blob is not available.
591 bootm_argv[3] = env_get("fdt_addr_r");
593 /* if fdt label is defined then get fdt from server */
595 char *fdtfile = NULL;
596 char *fdtfilefree = NULL;
599 fdtfile = label->fdt;
600 } else if (label->fdtdir) {
601 char *f1, *f2, *f3, *f4, *slash;
603 f1 = env_get("fdtfile");
610 * For complex cases where this code doesn't
611 * generate the correct filename, the board
612 * code should set $fdtfile during early boot,
613 * or the boot scripts should set $fdtfile
614 * before invoking "pxe" or "sysboot".
618 f3 = env_get("board");
630 len = strlen(label->fdtdir);
633 else if (label->fdtdir[len - 1] != '/')
638 len = strlen(label->fdtdir) + strlen(slash) +
639 strlen(f1) + strlen(f2) + strlen(f3) +
641 fdtfilefree = malloc(len);
643 printf("malloc fail (FDT filename)\n");
647 snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
648 label->fdtdir, slash, f1, f2, f3, f4);
649 fdtfile = fdtfilefree;
653 int err = get_relfile_envaddr(ctx, fdtfile,
658 bootm_argv[3] = NULL;
661 printf("Skipping %s for failure retrieving FDT\n",
667 #ifdef CONFIG_OF_LIBFDT_OVERLAY
668 if (label->fdtoverlays)
669 label_boot_fdtoverlay(ctx, label);
672 bootm_argv[3] = NULL;
676 bootm_argv[1] = kernel_addr;
677 zboot_argv[1] = kernel_addr;
679 if (initrd_addr_str) {
680 bootm_argv[2] = initrd_str;
683 zboot_argv[3] = initrd_addr_str;
684 zboot_argv[4] = initrd_filesize;
689 bootm_argv[3] = env_get("fdt_addr");
697 kernel_addr_r = genimg_get_kernel_addr(kernel_addr);
698 buf = map_sysmem(kernel_addr_r, 0);
699 /* Try bootm for legacy and FIT format image */
700 if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID)
701 do_bootm(ctx->cmdtp, 0, bootm_argc, bootm_argv);
702 /* Try booting an AArch64 Linux kernel image */
703 else if (IS_ENABLED(CONFIG_CMD_BOOTI))
704 do_booti(ctx->cmdtp, 0, bootm_argc, bootm_argv);
705 /* Try booting a Image */
706 else if (IS_ENABLED(CONFIG_CMD_BOOTZ))
707 do_bootz(ctx->cmdtp, 0, bootm_argc, bootm_argv);
708 /* Try booting an x86_64 Linux kernel image */
709 else if (IS_ENABLED(CONFIG_CMD_ZBOOT))
710 do_zboot_parent(ctx->cmdtp, 0, zboot_argc, zboot_argv, NULL);
720 /** enum token_type - Tokens for the pxe file parser */
746 /** struct token - token - given by a value and a type */
749 enum token_type type;
752 /* Keywords recognized */
753 static const struct token keywords[] = {
756 {"timeout", T_TIMEOUT},
757 {"default", T_DEFAULT},
758 {"prompt", T_PROMPT},
760 {"kernel", T_KERNEL},
762 {"localboot", T_LOCALBOOT},
763 {"append", T_APPEND},
764 {"initrd", T_INITRD},
765 {"include", T_INCLUDE},
766 {"devicetree", T_FDT},
768 {"devicetreedir", T_FDTDIR},
769 {"fdtdir", T_FDTDIR},
770 {"fdtoverlays", T_FDTOVERLAYS},
771 {"ontimeout", T_ONTIMEOUT,},
772 {"ipappend", T_IPAPPEND,},
773 {"background", T_BACKGROUND,},
778 * enum lex_state - lexer state
780 * Since pxe(linux) files don't have a token to identify the start of a
781 * literal, we have to keep track of when we're in a state where a literal is
782 * expected vs when we're in a state a keyword is expected.
791 * get_string() - retrieves a string from *p and stores it as a token in *t.
793 * This is used for scanning both string literals and keywords.
795 * Characters from *p are copied into t-val until a character equal to
796 * delim is found, or a NUL byte is reached. If delim has the special value of
797 * ' ', any whitespace character will be used as a delimiter.
799 * If lower is unequal to 0, uppercase characters will be converted to
800 * lowercase in the result. This is useful to make keywords case
803 * The location of *p is updated to point to the first character after the end
804 * of the token - the ending delimiter.
806 * Memory for t->val is allocated using malloc and must be free()'d to reclaim
809 * @p: Points to a pointer to the current position in the input being processed.
810 * Updated to point at the first character after the current token
811 * @t: Pointers to a token to fill in
812 * @delim: Delimiter character to look for, either newline or space
813 * @lower: true to convert the string to lower case when storing
814 * Returns the new value of t->val, on success, NULL if out of memory
816 static char *get_string(char **p, struct token *t, char delim, int lower)
822 * b and e both start at the beginning of the input stream.
824 * e is incremented until we find the ending delimiter, or a NUL byte
825 * is reached. Then, we take e - b to find the length of the token.
830 if ((delim == ' ' && isspace(*e)) || delim == *e)
838 * Allocate memory to hold the string, and copy it in, converting
839 * characters to lowercase if lower is != 0.
841 t->val = malloc(len + 1);
845 for (i = 0; i < len; i++, b++) {
847 t->val[i] = tolower(*b);
854 /* Update *p so the caller knows where to continue scanning */
862 * get_keyword() - Populate a keyword token with a type and value
864 * Updates the ->type field based on the keyword string in @val
865 * @t: Token to populate
867 static void get_keyword(struct token *t)
871 for (i = 0; keywords[i].val; i++) {
872 if (!strcmp(t->val, keywords[i].val)) {
873 t->type = keywords[i].type;
880 * get_token() - Get the next token
882 * We have to keep track of which state we're in to know if we're looking to get
883 * a string literal or a keyword.
885 * @p: Points to a pointer to the current position in the input being processed.
886 * Updated to point at the first character after the current token
888 static void get_token(char **p, struct token *t, enum lex_state state)
894 /* eat non EOL whitespace */
899 * eat comments. note that string literals can't begin with #, but
900 * can contain a # after their first character.
903 while (*c && *c != '\n')
910 } else if (*c == '\0') {
913 } else if (state == L_SLITERAL) {
914 get_string(&c, t, '\n', 0);
915 } else if (state == L_KEYWORD) {
917 * when we expect a keyword, we first get the next string
918 * token delimited by whitespace, and then check if it
919 * matches a keyword in our keyword list. if it does, it's
920 * converted to a keyword token of the appropriate type, and
921 * if not, it remains a string token.
923 get_string(&c, t, ' ', 1);
931 * eol_or_eof() - Find end of line
933 * Increment *c until we get to the end of the current line, or EOF
935 * @c: Points to a pointer to the current position in the input being processed.
936 * Updated to point at the first character after the current token
938 static void eol_or_eof(char **c)
940 while (**c && **c != '\n')
945 * All of these parse_* functions share some common behavior.
947 * They finish with *c pointing after the token they parse, and return 1 on
948 * success, or < 0 on error.
952 * Parse a string literal and store a pointer it at *dst. String literals
953 * terminate at the end of the line.
955 static int parse_sliteral(char **c, char **dst)
960 get_token(c, &t, L_SLITERAL);
962 if (t.type != T_STRING) {
963 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
973 * Parse a base 10 (unsigned) integer and store it at *dst.
975 static int parse_integer(char **c, int *dst)
980 get_token(c, &t, L_SLITERAL);
981 if (t.type != T_STRING) {
982 printf("Expected string: %.*s\n", (int)(*c - s), s);
986 *dst = simple_strtol(t.val, NULL, 10);
993 static int parse_pxefile_top(struct pxe_context *ctx, char *p, ulong base,
994 struct pxe_menu *cfg, int nest_level);
997 * Parse an include statement, and retrieve and parse the file it mentions.
999 * base should point to a location where it's safe to store the file, and
1000 * nest_level should indicate how many nested includes have occurred. For this
1001 * include, nest_level has already been incremented and doesn't need to be
1004 static int handle_include(struct pxe_context *ctx, char **c, unsigned long base,
1005 struct pxe_menu *cfg, int nest_level)
1013 err = parse_sliteral(c, &include_path);
1015 printf("Expected include path: %.*s\n", (int)(*c - s), s);
1019 err = get_pxe_file(ctx, include_path, base);
1021 printf("Couldn't retrieve %s\n", include_path);
1025 buf = map_sysmem(base, 0);
1026 ret = parse_pxefile_top(ctx, buf, base, cfg, nest_level);
1033 * Parse lines that begin with 'menu'.
1035 * base and nest are provided to handle the 'menu include' case.
1037 * base should point to a location where it's safe to store the included file.
1039 * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1040 * a file it includes, 3 when parsing a file included by that file, and so on.
1042 static int parse_menu(struct pxe_context *ctx, char **c, struct pxe_menu *cfg,
1043 unsigned long base, int nest_level)
1049 get_token(c, &t, L_KEYWORD);
1053 err = parse_sliteral(c, &cfg->title);
1058 err = handle_include(ctx, c, base, cfg, nest_level + 1);
1062 err = parse_sliteral(c, &cfg->bmp);
1066 printf("Ignoring malformed menu command: %.*s\n",
1078 * Handles parsing a 'menu line' when we're parsing a label.
1080 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1081 struct pxe_label *label)
1088 get_token(c, &t, L_KEYWORD);
1092 if (!cfg->default_label)
1093 cfg->default_label = strdup(label->name);
1095 if (!cfg->default_label)
1100 parse_sliteral(c, &label->menu);
1103 printf("Ignoring malformed menu command: %.*s\n",
1113 * Handles parsing a 'kernel' label.
1114 * expecting "filename" or "<fit_filename>#cfg"
1116 static int parse_label_kernel(char **c, struct pxe_label *label)
1121 err = parse_sliteral(c, &label->kernel);
1125 s = strstr(label->kernel, "#");
1129 label->config = malloc(strlen(s) + 1);
1133 strcpy(label->config, s);
1140 * Parses a label and adds it to the list of labels for a menu.
1142 * A label ends when we either get to the end of a file, or
1143 * get some input we otherwise don't have a handler defined
1147 static int parse_label(char **c, struct pxe_menu *cfg)
1152 struct pxe_label *label;
1155 label = label_create();
1159 err = parse_sliteral(c, &label->name);
1161 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1162 label_destroy(label);
1166 list_add_tail(&label->list, &cfg->labels);
1170 get_token(c, &t, L_KEYWORD);
1175 err = parse_label_menu(c, cfg, label);
1180 err = parse_label_kernel(c, label);
1184 err = parse_sliteral(c, &label->append);
1187 s = strstr(label->append, "initrd=");
1191 len = (int)(strchr(s, ' ') - s);
1192 label->initrd = malloc(len + 1);
1193 strncpy(label->initrd, s, len);
1194 label->initrd[len] = '\0';
1200 err = parse_sliteral(c, &label->initrd);
1205 err = parse_sliteral(c, &label->fdt);
1210 err = parse_sliteral(c, &label->fdtdir);
1214 if (!label->fdtoverlays)
1215 err = parse_sliteral(c, &label->fdtoverlays);
1219 label->localboot = 1;
1220 err = parse_integer(c, &label->localboot_val);
1224 err = parse_integer(c, &label->ipappend);
1232 * put the token back! we don't want it - it's the end
1233 * of a label and whatever token this is, it's
1234 * something for the menu level context to handle.
1246 * This 16 comes from the limit pxelinux imposes on nested includes.
1248 * There is no reason at all we couldn't do more, but some limit helps prevent
1249 * infinite (until crash occurs) recursion if a file tries to include itself.
1251 #define MAX_NEST_LEVEL 16
1254 * Entry point for parsing a menu file. nest_level indicates how many times
1255 * we've nested in includes. It will be 1 for the top level menu file.
1257 * Returns 1 on success, < 0 on error.
1259 static int parse_pxefile_top(struct pxe_context *ctx, char *p, unsigned long base,
1260 struct pxe_menu *cfg, int nest_level)
1263 char *s, *b, *label_name;
1268 if (nest_level > MAX_NEST_LEVEL) {
1269 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1276 get_token(&p, &t, L_KEYWORD);
1282 err = parse_menu(ctx, &p, cfg,
1283 base + ALIGN(strlen(b) + 1, 4),
1288 err = parse_integer(&p, &cfg->timeout);
1292 err = parse_label(&p, cfg);
1297 err = parse_sliteral(&p, &label_name);
1300 if (cfg->default_label)
1301 free(cfg->default_label);
1303 cfg->default_label = label_name;
1309 err = handle_include(ctx, &p,
1310 base + ALIGN(strlen(b), 4), cfg,
1325 printf("Ignoring unknown command: %.*s\n",
1337 void destroy_pxe_menu(struct pxe_menu *cfg)
1339 struct list_head *pos, *n;
1340 struct pxe_label *label;
1343 free(cfg->default_label);
1345 list_for_each_safe(pos, n, &cfg->labels) {
1346 label = list_entry(pos, struct pxe_label, list);
1348 label_destroy(label);
1354 struct pxe_menu *parse_pxefile(struct pxe_context *ctx, unsigned long menucfg)
1356 struct pxe_menu *cfg;
1360 cfg = malloc(sizeof(struct pxe_menu));
1364 memset(cfg, 0, sizeof(struct pxe_menu));
1366 INIT_LIST_HEAD(&cfg->labels);
1368 buf = map_sysmem(menucfg, 0);
1369 r = parse_pxefile_top(ctx, buf, menucfg, cfg, 1);
1372 destroy_pxe_menu(cfg);
1380 * Converts a pxe_menu struct into a menu struct for use with U-Boot's generic
1383 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1385 struct pxe_label *label;
1386 struct list_head *pos;
1390 char *default_num = NULL;
1393 * Create a menu and add items for all the labels.
1395 m = menu_create(cfg->title, DIV_ROUND_UP(cfg->timeout, 10),
1396 cfg->prompt, NULL, label_print, NULL, NULL);
1400 list_for_each(pos, &cfg->labels) {
1401 label = list_entry(pos, struct pxe_label, list);
1403 sprintf(label->num, "%d", i++);
1404 if (menu_item_add(m, label->num, label) != 1) {
1408 if (cfg->default_label &&
1409 (strcmp(label->name, cfg->default_label) == 0))
1410 default_num = label->num;
1414 * After we've created items for each label in the menu, set the
1415 * menu's default label if one was specified.
1418 err = menu_default_set(m, default_num);
1420 if (err != -ENOENT) {
1425 printf("Missing default: %s\n", cfg->default_label);
1433 * Try to boot any labels we have yet to attempt to boot.
1435 static void boot_unattempted_labels(struct pxe_context *ctx,
1436 struct pxe_menu *cfg)
1438 struct list_head *pos;
1439 struct pxe_label *label;
1441 list_for_each(pos, &cfg->labels) {
1442 label = list_entry(pos, struct pxe_label, list);
1444 if (!label->attempted)
1445 label_boot(ctx, label);
1449 void handle_pxe_menu(struct pxe_context *ctx, struct pxe_menu *cfg)
1455 if (IS_ENABLED(CONFIG_CMD_BMP)) {
1456 /* display BMP if available */
1458 if (get_relfile(ctx, cfg->bmp, image_load_addr)) {
1459 if (CONFIG_IS_ENABLED(CMD_CLS))
1460 run_command("cls", 0);
1461 bmp_display(image_load_addr,
1462 BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1464 printf("Skipping background bmp %s for failure\n",
1470 m = pxe_menu_to_menu(cfg);
1474 err = menu_get_choice(m, &choice);
1478 * err == 1 means we got a choice back from menu_get_choice.
1480 * err == -ENOENT if the menu was setup to select the default but no
1481 * default was set. in that case, we should continue trying to boot
1482 * labels that haven't been attempted yet.
1484 * otherwise, the user interrupted or there was some other error and
1489 err = label_boot(ctx, choice);
1492 } else if (err != -ENOENT) {
1496 boot_unattempted_labels(ctx, cfg);
1499 void pxe_setup_ctx(struct pxe_context *ctx, struct cmd_tbl *cmdtp,
1500 pxe_getfile_func getfile, void *userdata,
1501 bool allow_abs_path)
1504 ctx->getfile = getfile;
1505 ctx->userdata = userdata;
1506 ctx->allow_abs_path = allow_abs_path;