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>
34 #include "pxe_utils.h"
36 #define MAX_TFTP_PATH_LEN 512
38 int pxe_get_file_size(ulong *sizep)
42 val = from_env("filesize");
46 if (strict_strtoul(val, 16, sizep) < 0)
53 * format_mac_pxe() - obtain a MAC address in the PXE format
55 * This produces a MAC-address string in the format for the current ethernet
58 * 01-aa-bb-cc-dd-ee-ff
60 * where aa-ff is the MAC address in hex
62 * @outbuf: Buffer to write string to
63 * @outbuf_len: length of buffer
64 * Return: 1 if OK, -ENOSPC if buffer is too small, -ENOENT is there is no
65 * current ethernet device
67 int format_mac_pxe(char *outbuf, size_t outbuf_len)
71 if (outbuf_len < 21) {
72 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
76 if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
79 sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
80 ethaddr[0], ethaddr[1], ethaddr[2],
81 ethaddr[3], ethaddr[4], ethaddr[5]);
87 * get_relfile() - read a file relative to the PXE file
89 * As in pxelinux, paths to files referenced from files we retrieve are
90 * relative to the location of bootfile. get_relfile takes such a path and
91 * joins it with the bootfile path to get the full path to the target file. If
92 * the bootfile path is NULL, we use file_path as is.
95 * @file_path: File path to read (relative to the PXE file)
96 * @file_addr: Address to load file to
97 * @filesizep: If not NULL, returns the file size in bytes
98 * Returns 1 for success, or < 0 on error
100 static int get_relfile(struct pxe_context *ctx, const char *file_path,
101 unsigned long file_addr, ulong *filesizep)
104 char relfile[MAX_TFTP_PATH_LEN + 1];
109 if (file_path[0] == '/' && ctx->allow_abs_path)
112 strncpy(relfile, ctx->bootdir, MAX_TFTP_PATH_LEN);
114 path_len = strlen(file_path) + strlen(relfile);
116 if (path_len > MAX_TFTP_PATH_LEN) {
117 printf("Base path too long (%s%s)\n", relfile, file_path);
119 return -ENAMETOOLONG;
122 strcat(relfile, file_path);
124 printf("Retrieving file: %s\n", relfile);
126 sprintf(addr_buf, "%lx", file_addr);
128 ret = ctx->getfile(ctx, relfile, addr_buf, &size);
130 return log_msg_ret("get", ret);
138 * get_pxe_file() - read a file
140 * The file is read and nul-terminated
143 * @file_path: File path to read (relative to the PXE file)
144 * @file_addr: Address to load file to
145 * Returns 1 for success, or < 0 on error
147 int get_pxe_file(struct pxe_context *ctx, const char *file_path,
154 err = get_relfile(ctx, file_path, file_addr, &size);
158 buf = map_sysmem(file_addr + size, 1);
165 #define PXELINUX_DIR "pxelinux.cfg/"
168 * get_pxelinux_path() - Get a file in the pxelinux.cfg/ directory
171 * @file: Filename to process (relative to pxelinux.cfg/)
172 * Returns 1 for success, -ENAMETOOLONG if the resulting path is too long.
173 * or other value < 0 on other error
175 int get_pxelinux_path(struct pxe_context *ctx, const char *file,
176 unsigned long pxefile_addr_r)
178 size_t base_len = strlen(PXELINUX_DIR);
179 char path[MAX_TFTP_PATH_LEN + 1];
181 if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
182 printf("path (%s%s) too long, skipping\n",
184 return -ENAMETOOLONG;
187 sprintf(path, PXELINUX_DIR "%s", file);
189 return get_pxe_file(ctx, path, pxefile_addr_r);
193 * get_relfile_envaddr() - read a file to an address in an env var
195 * Wrapper to make it easier to store the file at file_path in the location
196 * specified by envaddr_name. file_path will be joined to the bootfile path,
197 * if any is specified.
200 * @file_path: File path to read (relative to the PXE file)
201 * @envaddr_name: Name of environment variable which contains the address to
203 * @filesizep: Returns the file size in bytes
204 * Returns 1 on success, -ENOENT if @envaddr_name does not exist as an
205 * environment variable, -EINVAL if its format is not valid hex, or other
206 * value < 0 on other error
208 static int get_relfile_envaddr(struct pxe_context *ctx, const char *file_path,
209 const char *envaddr_name, ulong *filesizep)
211 unsigned long file_addr;
214 envaddr = from_env(envaddr_name);
218 if (strict_strtoul(envaddr, 16, &file_addr) < 0)
221 return get_relfile(ctx, file_path, file_addr, filesizep);
225 * label_create() - crate a new PXE label
227 * Allocates memory for and initializes a pxe_label. This uses malloc, so the
228 * result must be free()'d to reclaim the memory.
230 * Returns a pointer to the label, or NULL if out of memory
232 static struct pxe_label *label_create(void)
234 struct pxe_label *label;
236 label = malloc(sizeof(struct pxe_label));
240 memset(label, 0, sizeof(struct pxe_label));
246 * label_destroy() - free the memory used by a pxe_label
248 * This frees @label itself as well as memory used by its name,
249 * kernel, config, append, initrd, fdt, fdtdir and fdtoverlay members, if
252 * So - be sure to only use dynamically allocated memory for the members of
253 * the pxe_label struct, unless you want to clean it up first. These are
254 * currently only created by the pxe file parsing code.
256 * @label: Label to free
258 static void label_destroy(struct pxe_label *label)
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)
327 struct fdt_header *working_fdt;
334 /* Get the main fdt and map it */
335 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
336 working_fdt = map_sysmem(fdt_addr, 0);
337 err = fdt_check_header(working_fdt);
341 /* add extra size for holding kaslr-seed */
342 /* err is new fdt size, 0 or negtive */
343 err = fdt_shrink_to_minimum(working_fdt, 512);
347 if (uclass_get_device(UCLASS_RNG, 0, &dev) || !dev) {
348 printf("No RNG device\n");
352 nodeoffset = fdt_find_or_add_subnode(working_fdt, 0, "chosen");
353 if (nodeoffset < 0) {
354 printf("Reading chosen node failed\n");
360 printf("Out of memory\n");
364 if (dm_rng_read(dev, buf, n)) {
365 printf("Reading RNG failed\n");
369 err = fdt_setprop(working_fdt, nodeoffset, "kaslr-seed", buf, sizeof(buf));
371 printf("Unable to set kaslr-seed on chosen node: %s\n", fdt_strerror(err));
381 * label_boot_fdtoverlay() - Loads fdt overlays specified in 'fdtoverlays'
384 * @label: Label to process
386 #ifdef CONFIG_OF_LIBFDT_OVERLAY
387 static void label_boot_fdtoverlay(struct pxe_context *ctx,
388 struct pxe_label *label)
390 char *fdtoverlay = label->fdtoverlays;
391 struct fdt_header *working_fdt;
392 char *fdtoverlay_addr_env;
393 ulong fdtoverlay_addr;
397 /* Get the main fdt and map it */
398 fdt_addr = hextoul(env_get("fdt_addr_r"), NULL);
399 working_fdt = map_sysmem(fdt_addr, 0);
400 err = fdt_check_header(working_fdt);
404 /* Get the specific overlay loading address */
405 fdtoverlay_addr_env = env_get("fdtoverlay_addr_r");
406 if (!fdtoverlay_addr_env) {
407 printf("Invalid fdtoverlay_addr_r for loading overlays\n");
411 fdtoverlay_addr = hextoul(fdtoverlay_addr_env, NULL);
413 /* Cycle over the overlay files and apply them in order */
415 struct fdt_header *blob;
420 /* Drop leading spaces */
421 while (*fdtoverlay == ' ')
424 /* Copy a single filename if multiple provided */
425 end = strstr(fdtoverlay, " ");
427 len = (int)(end - fdtoverlay);
428 overlayfile = malloc(len + 1);
429 strncpy(overlayfile, fdtoverlay, len);
430 overlayfile[len] = '\0';
432 overlayfile = fdtoverlay;
434 if (!strlen(overlayfile))
437 /* Load overlay file */
438 err = get_relfile_envaddr(ctx, overlayfile, "fdtoverlay_addr_r",
441 printf("Failed loading overlay %s\n", overlayfile);
445 /* Resize main fdt */
446 fdt_shrink_to_minimum(working_fdt, 8192);
448 blob = map_sysmem(fdtoverlay_addr, 0);
449 err = fdt_check_header(blob);
451 printf("Invalid overlay %s, skipping\n",
456 err = fdt_overlay_apply_verbose(working_fdt, blob);
458 printf("Failed to apply overlay %s, skipping\n",
466 } while ((fdtoverlay = strstr(fdtoverlay, " ")));
471 * label_boot() - Boot according to the contents of a pxe_label
473 * If we can't boot for any reason, we return. A successful boot never
476 * The kernel will be stored in the location given by the 'kernel_addr_r'
477 * environment variable.
479 * If the label specifies an initrd file, it will be stored in the location
480 * given by the 'ramdisk_addr_r' environment variable.
482 * If the label specifies an 'append' line, its contents will overwrite that
483 * of the 'bootargs' environment variable.
486 * @label: Label to process
487 * Returns does not return on success, otherwise returns 0 if a localboot
488 * label was processed, or 1 on error
490 static int label_boot(struct pxe_context *ctx, struct pxe_label *label)
492 char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
493 char *zboot_argv[] = { "zboot", NULL, "0", NULL, NULL };
494 char *kernel_addr = NULL;
495 char *initrd_addr_str = NULL;
496 char initrd_filesize[10];
498 char mac_str[29] = "";
499 char ip_str[68] = "";
500 char *fit_addr = NULL;
509 label->attempted = 1;
511 if (label->localboot) {
512 if (label->localboot_val >= 0)
513 label_localboot(label);
517 if (!label->kernel) {
518 printf("No kernel given, skipping %s\n",
526 if (get_relfile_envaddr(ctx, label->initrd, "ramdisk_addr_r",
528 printf("Skipping %s for failure retrieving initrd\n",
533 initrd_addr_str = env_get("ramdisk_addr_r");
534 strcpy(initrd_filesize, simple_xtoa(size));
536 strncpy(initrd_str, initrd_addr_str, 18);
537 strcat(initrd_str, ":");
538 strncat(initrd_str, initrd_filesize, 9);
541 if (get_relfile_envaddr(ctx, label->kernel, "kernel_addr_r",
543 printf("Skipping %s for failure retrieving kernel\n",
548 if (label->ipappend & 0x1) {
549 sprintf(ip_str, " ip=%s:%s:%s:%s",
550 env_get("ipaddr"), env_get("serverip"),
551 env_get("gatewayip"), env_get("netmask"));
554 if (IS_ENABLED(CONFIG_CMD_NET)) {
555 if (label->ipappend & 0x2) {
558 strcpy(mac_str, " BOOTIF=");
559 err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
565 if ((label->ipappend & 0x3) || label->append) {
566 char bootargs[CONFIG_SYS_CBSIZE] = "";
567 char finalbootargs[CONFIG_SYS_CBSIZE];
569 if (strlen(label->append ?: "") +
570 strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
571 printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
572 strlen(label->append ?: ""),
573 strlen(ip_str), strlen(mac_str),
579 strncpy(bootargs, label->append, sizeof(bootargs));
581 strcat(bootargs, ip_str);
582 strcat(bootargs, mac_str);
584 cli_simple_process_macros(bootargs, finalbootargs,
585 sizeof(finalbootargs));
586 env_set("bootargs", finalbootargs);
587 printf("append: %s\n", finalbootargs);
590 kernel_addr = env_get("kernel_addr_r");
592 /* for FIT, append the configuration identifier */
594 int len = strlen(kernel_addr) + strlen(label->config) + 1;
596 fit_addr = malloc(len);
598 printf("malloc fail (FIT address)\n");
601 snprintf(fit_addr, len, "%s%s", kernel_addr, label->config);
602 kernel_addr = fit_addr;
606 * fdt usage is optional:
607 * It handles the following scenarios.
609 * Scenario 1: If fdt_addr_r specified and "fdt" or "fdtdir" label is
610 * defined in pxe file, retrieve fdt blob from server. Pass fdt_addr_r to
611 * bootm, and adjust argc appropriately.
613 * If retrieve fails and no exact fdt blob is specified in pxe file with
614 * "fdt" label, try Scenario 2.
616 * Scenario 2: If there is an fdt_addr specified, pass it along to
617 * bootm, and adjust argc appropriately.
619 * Scenario 3: If there is an fdtcontroladdr specified, pass it along to
620 * bootm, and adjust argc appropriately.
622 * Scenario 4: fdt blob is not available.
624 bootm_argv[3] = env_get("fdt_addr_r");
626 /* if fdt label is defined then get fdt from server */
628 char *fdtfile = NULL;
629 char *fdtfilefree = NULL;
632 fdtfile = label->fdt;
633 } else if (label->fdtdir) {
634 char *f1, *f2, *f3, *f4, *slash;
636 f1 = env_get("fdtfile");
643 * For complex cases where this code doesn't
644 * generate the correct filename, the board
645 * code should set $fdtfile during early boot,
646 * or the boot scripts should set $fdtfile
647 * before invoking "pxe" or "sysboot".
651 f3 = env_get("board");
663 len = strlen(label->fdtdir);
666 else if (label->fdtdir[len - 1] != '/')
671 len = strlen(label->fdtdir) + strlen(slash) +
672 strlen(f1) + strlen(f2) + strlen(f3) +
674 fdtfilefree = malloc(len);
676 printf("malloc fail (FDT filename)\n");
680 snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
681 label->fdtdir, slash, f1, f2, f3, f4);
682 fdtfile = fdtfilefree;
686 int err = get_relfile_envaddr(ctx, fdtfile,
691 bootm_argv[3] = NULL;
694 printf("Skipping %s for failure retrieving FDT\n",
700 if (label->kaslrseed)
701 label_boot_kaslrseed();
703 #ifdef CONFIG_OF_LIBFDT_OVERLAY
704 if (label->fdtoverlays)
705 label_boot_fdtoverlay(ctx, label);
708 bootm_argv[3] = NULL;
712 bootm_argv[1] = kernel_addr;
713 zboot_argv[1] = kernel_addr;
715 if (initrd_addr_str) {
716 bootm_argv[2] = initrd_str;
719 zboot_argv[3] = initrd_addr_str;
720 zboot_argv[4] = initrd_filesize;
725 bootm_argv[3] = env_get("fdt_addr");
728 bootm_argv[3] = env_get("fdtcontroladdr");
736 kernel_addr_r = genimg_get_kernel_addr(kernel_addr);
737 buf = map_sysmem(kernel_addr_r, 0);
738 /* Try bootm for legacy and FIT format image */
739 if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID)
740 do_bootm(ctx->cmdtp, 0, bootm_argc, bootm_argv);
741 /* Try booting an AArch64 Linux kernel image */
742 else if (IS_ENABLED(CONFIG_CMD_BOOTI))
743 do_booti(ctx->cmdtp, 0, bootm_argc, bootm_argv);
744 /* Try booting a Image */
745 else if (IS_ENABLED(CONFIG_CMD_BOOTZ))
746 do_bootz(ctx->cmdtp, 0, bootm_argc, bootm_argv);
747 /* Try booting an x86_64 Linux kernel image */
748 else if (IS_ENABLED(CONFIG_CMD_ZBOOT))
749 do_zboot_parent(ctx->cmdtp, 0, zboot_argc, zboot_argv, NULL);
759 /** enum token_type - Tokens for the pxe file parser */
786 /** struct token - token - given by a value and a type */
789 enum token_type type;
792 /* Keywords recognized */
793 static const struct token keywords[] = {
796 {"timeout", T_TIMEOUT},
797 {"default", T_DEFAULT},
798 {"prompt", T_PROMPT},
800 {"kernel", T_KERNEL},
802 {"localboot", T_LOCALBOOT},
803 {"append", T_APPEND},
804 {"initrd", T_INITRD},
805 {"include", T_INCLUDE},
806 {"devicetree", T_FDT},
808 {"devicetreedir", T_FDTDIR},
809 {"fdtdir", T_FDTDIR},
810 {"fdtoverlays", T_FDTOVERLAYS},
811 {"ontimeout", T_ONTIMEOUT,},
812 {"ipappend", T_IPAPPEND,},
813 {"background", T_BACKGROUND,},
814 {"kaslrseed", T_KASLRSEED,},
819 * enum lex_state - lexer state
821 * Since pxe(linux) files don't have a token to identify the start of a
822 * literal, we have to keep track of when we're in a state where a literal is
823 * expected vs when we're in a state a keyword is expected.
832 * get_string() - retrieves a string from *p and stores it as a token in *t.
834 * This is used for scanning both string literals and keywords.
836 * Characters from *p are copied into t-val until a character equal to
837 * delim is found, or a NUL byte is reached. If delim has the special value of
838 * ' ', any whitespace character will be used as a delimiter.
840 * If lower is unequal to 0, uppercase characters will be converted to
841 * lowercase in the result. This is useful to make keywords case
844 * The location of *p is updated to point to the first character after the end
845 * of the token - the ending delimiter.
847 * Memory for t->val is allocated using malloc and must be free()'d to reclaim
850 * @p: Points to a pointer to the current position in the input being processed.
851 * Updated to point at the first character after the current token
852 * @t: Pointers to a token to fill in
853 * @delim: Delimiter character to look for, either newline or space
854 * @lower: true to convert the string to lower case when storing
855 * Returns the new value of t->val, on success, NULL if out of memory
857 static char *get_string(char **p, struct token *t, char delim, int lower)
863 * b and e both start at the beginning of the input stream.
865 * e is incremented until we find the ending delimiter, or a NUL byte
866 * is reached. Then, we take e - b to find the length of the token.
871 if ((delim == ' ' && isspace(*e)) || delim == *e)
879 * Allocate memory to hold the string, and copy it in, converting
880 * characters to lowercase if lower is != 0.
882 t->val = malloc(len + 1);
886 for (i = 0; i < len; i++, b++) {
888 t->val[i] = tolower(*b);
895 /* Update *p so the caller knows where to continue scanning */
903 * get_keyword() - Populate a keyword token with a type and value
905 * Updates the ->type field based on the keyword string in @val
906 * @t: Token to populate
908 static void get_keyword(struct token *t)
912 for (i = 0; keywords[i].val; i++) {
913 if (!strcmp(t->val, keywords[i].val)) {
914 t->type = keywords[i].type;
921 * get_token() - Get the next token
923 * We have to keep track of which state we're in to know if we're looking to get
924 * a string literal or a keyword.
926 * @p: Points to a pointer to the current position in the input being processed.
927 * Updated to point at the first character after the current token
929 static void get_token(char **p, struct token *t, enum lex_state state)
935 /* eat non EOL whitespace */
940 * eat comments. note that string literals can't begin with #, but
941 * can contain a # after their first character.
944 while (*c && *c != '\n')
951 } else if (*c == '\0') {
954 } else if (state == L_SLITERAL) {
955 get_string(&c, t, '\n', 0);
956 } else if (state == L_KEYWORD) {
958 * when we expect a keyword, we first get the next string
959 * token delimited by whitespace, and then check if it
960 * matches a keyword in our keyword list. if it does, it's
961 * converted to a keyword token of the appropriate type, and
962 * if not, it remains a string token.
964 get_string(&c, t, ' ', 1);
972 * eol_or_eof() - Find end of line
974 * Increment *c until we get to the end of the current line, or EOF
976 * @c: Points to a pointer to the current position in the input being processed.
977 * Updated to point at the first character after the current token
979 static void eol_or_eof(char **c)
981 while (**c && **c != '\n')
986 * All of these parse_* functions share some common behavior.
988 * They finish with *c pointing after the token they parse, and return 1 on
989 * success, or < 0 on error.
993 * Parse a string literal and store a pointer it at *dst. String literals
994 * terminate at the end of the line.
996 static int parse_sliteral(char **c, char **dst)
1001 get_token(c, &t, L_SLITERAL);
1003 if (t.type != T_STRING) {
1004 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
1014 * Parse a base 10 (unsigned) integer and store it at *dst.
1016 static int parse_integer(char **c, int *dst)
1021 get_token(c, &t, L_SLITERAL);
1022 if (t.type != T_STRING) {
1023 printf("Expected string: %.*s\n", (int)(*c - s), s);
1027 *dst = simple_strtol(t.val, NULL, 10);
1034 static int parse_pxefile_top(struct pxe_context *ctx, char *p, ulong base,
1035 struct pxe_menu *cfg, int nest_level);
1038 * Parse an include statement, and retrieve and parse the file it mentions.
1040 * base should point to a location where it's safe to store the file, and
1041 * nest_level should indicate how many nested includes have occurred. For this
1042 * include, nest_level has already been incremented and doesn't need to be
1045 static int handle_include(struct pxe_context *ctx, char **c, unsigned long base,
1046 struct pxe_menu *cfg, int nest_level)
1054 err = parse_sliteral(c, &include_path);
1056 printf("Expected include path: %.*s\n", (int)(*c - s), s);
1060 err = get_pxe_file(ctx, include_path, base);
1062 printf("Couldn't retrieve %s\n", include_path);
1066 buf = map_sysmem(base, 0);
1067 ret = parse_pxefile_top(ctx, buf, base, cfg, nest_level);
1074 * Parse lines that begin with 'menu'.
1076 * base and nest are provided to handle the 'menu include' case.
1078 * base should point to a location where it's safe to store the included file.
1080 * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1081 * a file it includes, 3 when parsing a file included by that file, and so on.
1083 static int parse_menu(struct pxe_context *ctx, char **c, struct pxe_menu *cfg,
1084 unsigned long base, int nest_level)
1090 get_token(c, &t, L_KEYWORD);
1094 err = parse_sliteral(c, &cfg->title);
1099 err = handle_include(ctx, c, base, cfg, nest_level + 1);
1103 err = parse_sliteral(c, &cfg->bmp);
1107 printf("Ignoring malformed menu command: %.*s\n",
1119 * Handles parsing a 'menu line' when we're parsing a label.
1121 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1122 struct pxe_label *label)
1129 get_token(c, &t, L_KEYWORD);
1133 if (!cfg->default_label)
1134 cfg->default_label = strdup(label->name);
1136 if (!cfg->default_label)
1141 parse_sliteral(c, &label->menu);
1144 printf("Ignoring malformed menu command: %.*s\n",
1154 * Handles parsing a 'kernel' label.
1155 * expecting "filename" or "<fit_filename>#cfg"
1157 static int parse_label_kernel(char **c, struct pxe_label *label)
1162 err = parse_sliteral(c, &label->kernel);
1166 s = strstr(label->kernel, "#");
1170 label->config = malloc(strlen(s) + 1);
1174 strcpy(label->config, s);
1181 * Parses a label and adds it to the list of labels for a menu.
1183 * A label ends when we either get to the end of a file, or
1184 * get some input we otherwise don't have a handler defined
1188 static int parse_label(char **c, struct pxe_menu *cfg)
1193 struct pxe_label *label;
1196 label = label_create();
1200 err = parse_sliteral(c, &label->name);
1202 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1203 label_destroy(label);
1207 list_add_tail(&label->list, &cfg->labels);
1211 get_token(c, &t, L_KEYWORD);
1216 err = parse_label_menu(c, cfg, label);
1221 err = parse_label_kernel(c, label);
1225 err = parse_sliteral(c, &label->append);
1228 s = strstr(label->append, "initrd=");
1232 len = (int)(strchr(s, ' ') - s);
1233 label->initrd = malloc(len + 1);
1234 strncpy(label->initrd, s, len);
1235 label->initrd[len] = '\0';
1241 err = parse_sliteral(c, &label->initrd);
1246 err = parse_sliteral(c, &label->fdt);
1251 err = parse_sliteral(c, &label->fdtdir);
1255 if (!label->fdtoverlays)
1256 err = parse_sliteral(c, &label->fdtoverlays);
1260 label->localboot = 1;
1261 err = parse_integer(c, &label->localboot_val);
1265 err = parse_integer(c, &label->ipappend);
1269 label->kaslrseed = 1;
1277 * put the token back! we don't want it - it's the end
1278 * of a label and whatever token this is, it's
1279 * something for the menu level context to handle.
1291 * This 16 comes from the limit pxelinux imposes on nested includes.
1293 * There is no reason at all we couldn't do more, but some limit helps prevent
1294 * infinite (until crash occurs) recursion if a file tries to include itself.
1296 #define MAX_NEST_LEVEL 16
1299 * Entry point for parsing a menu file. nest_level indicates how many times
1300 * we've nested in includes. It will be 1 for the top level menu file.
1302 * Returns 1 on success, < 0 on error.
1304 static int parse_pxefile_top(struct pxe_context *ctx, char *p, unsigned long base,
1305 struct pxe_menu *cfg, int nest_level)
1308 char *s, *b, *label_name;
1313 if (nest_level > MAX_NEST_LEVEL) {
1314 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1321 get_token(&p, &t, L_KEYWORD);
1327 err = parse_menu(ctx, &p, cfg,
1328 base + ALIGN(strlen(b) + 1, 4),
1333 err = parse_integer(&p, &cfg->timeout);
1337 err = parse_label(&p, cfg);
1342 err = parse_sliteral(&p, &label_name);
1345 if (cfg->default_label)
1346 free(cfg->default_label);
1348 cfg->default_label = label_name;
1354 err = handle_include(ctx, &p,
1355 base + ALIGN(strlen(b), 4), cfg,
1370 printf("Ignoring unknown command: %.*s\n",
1382 void destroy_pxe_menu(struct pxe_menu *cfg)
1384 struct list_head *pos, *n;
1385 struct pxe_label *label;
1388 free(cfg->default_label);
1390 list_for_each_safe(pos, n, &cfg->labels) {
1391 label = list_entry(pos, struct pxe_label, list);
1393 label_destroy(label);
1399 struct pxe_menu *parse_pxefile(struct pxe_context *ctx, unsigned long menucfg)
1401 struct pxe_menu *cfg;
1405 cfg = malloc(sizeof(struct pxe_menu));
1409 memset(cfg, 0, sizeof(struct pxe_menu));
1411 INIT_LIST_HEAD(&cfg->labels);
1413 buf = map_sysmem(menucfg, 0);
1414 r = parse_pxefile_top(ctx, buf, menucfg, cfg, 1);
1417 destroy_pxe_menu(cfg);
1425 * Converts a pxe_menu struct into a menu struct for use with U-Boot's generic
1428 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1430 struct pxe_label *label;
1431 struct list_head *pos;
1433 char *label_override;
1436 char *default_num = NULL;
1437 char *override_num = NULL;
1440 * Create a menu and add items for all the labels.
1442 m = menu_create(cfg->title, DIV_ROUND_UP(cfg->timeout, 10),
1443 cfg->prompt, NULL, label_print, NULL, NULL);
1447 label_override = env_get("pxe_label_override");
1449 list_for_each(pos, &cfg->labels) {
1450 label = list_entry(pos, struct pxe_label, list);
1452 sprintf(label->num, "%d", i++);
1453 if (menu_item_add(m, label->num, label) != 1) {
1457 if (cfg->default_label &&
1458 (strcmp(label->name, cfg->default_label) == 0))
1459 default_num = label->num;
1460 if (label_override && !strcmp(label->name, label_override))
1461 override_num = label->num;
1465 if (label_override) {
1467 default_num = override_num;
1469 printf("Missing override pxe label: %s\n",
1474 * After we've created items for each label in the menu, set the
1475 * menu's default label if one was specified.
1478 err = menu_default_set(m, default_num);
1480 if (err != -ENOENT) {
1485 printf("Missing default: %s\n", cfg->default_label);
1493 * Try to boot any labels we have yet to attempt to boot.
1495 static void boot_unattempted_labels(struct pxe_context *ctx,
1496 struct pxe_menu *cfg)
1498 struct list_head *pos;
1499 struct pxe_label *label;
1501 list_for_each(pos, &cfg->labels) {
1502 label = list_entry(pos, struct pxe_label, list);
1504 if (!label->attempted)
1505 label_boot(ctx, label);
1509 void handle_pxe_menu(struct pxe_context *ctx, struct pxe_menu *cfg)
1515 if (IS_ENABLED(CONFIG_CMD_BMP)) {
1516 /* display BMP if available */
1518 if (get_relfile(ctx, cfg->bmp, image_load_addr, NULL)) {
1519 if (CONFIG_IS_ENABLED(CMD_CLS))
1520 run_command("cls", 0);
1521 bmp_display(image_load_addr,
1522 BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1524 printf("Skipping background bmp %s for failure\n",
1530 m = pxe_menu_to_menu(cfg);
1534 err = menu_get_choice(m, &choice);
1538 * err == 1 means we got a choice back from menu_get_choice.
1540 * err == -ENOENT if the menu was setup to select the default but no
1541 * default was set. in that case, we should continue trying to boot
1542 * labels that haven't been attempted yet.
1544 * otherwise, the user interrupted or there was some other error and
1549 err = label_boot(ctx, choice);
1552 } else if (err != -ENOENT) {
1556 boot_unattempted_labels(ctx, cfg);
1559 int pxe_setup_ctx(struct pxe_context *ctx, struct cmd_tbl *cmdtp,
1560 pxe_getfile_func getfile, void *userdata,
1561 bool allow_abs_path, const char *bootfile)
1563 const char *last_slash;
1564 size_t path_len = 0;
1566 memset(ctx, '\0', sizeof(*ctx));
1568 ctx->getfile = getfile;
1569 ctx->userdata = userdata;
1570 ctx->allow_abs_path = allow_abs_path;
1572 /* figure out the boot directory, if there is one */
1573 if (bootfile && strlen(bootfile) >= MAX_TFTP_PATH_LEN)
1575 ctx->bootdir = strdup(bootfile ? bootfile : "");
1580 last_slash = strrchr(bootfile, '/');
1582 path_len = (last_slash - bootfile) + 1;
1584 ctx->bootdir[path_len] = '\0';
1589 void pxe_destroy_ctx(struct pxe_context *ctx)
1594 int pxe_process(struct pxe_context *ctx, ulong pxefile_addr_r, bool prompt)
1596 struct pxe_menu *cfg;
1598 cfg = parse_pxefile(ctx, pxefile_addr_r);
1600 printf("Error parsing config file\n");
1607 handle_pxe_menu(ctx, cfg);
1609 destroy_pxe_menu(cfg);