cmd: pxe: use strdup to copy config
[platform/kernel/u-boot.git] / boot / pxe_utils.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2010-2011 Calxeda, Inc.
4  * Copyright (c) 2014, NVIDIA CORPORATION.  All rights reserved.
5  */
6
7 #include <common.h>
8 #include <command.h>
9 #include <dm.h>
10 #include <env.h>
11 #include <image.h>
12 #include <log.h>
13 #include <malloc.h>
14 #include <mapmem.h>
15 #include <net.h>
16 #include <fdt_support.h>
17 #include <video.h>
18 #include <linux/libfdt.h>
19 #include <linux/string.h>
20 #include <linux/ctype.h>
21 #include <errno.h>
22 #include <linux/list.h>
23
24 #ifdef CONFIG_DM_RNG
25 #include <rng.h>
26 #endif
27
28 #include <splash.h>
29 #include <asm/io.h>
30
31 #include "menu.h"
32 #include "cli.h"
33
34 #include "pxe_utils.h"
35
36 #define MAX_TFTP_PATH_LEN 512
37
38 int pxe_get_file_size(ulong *sizep)
39 {
40         const char *val;
41
42         val = from_env("filesize");
43         if (!val)
44                 return -ENOENT;
45
46         if (strict_strtoul(val, 16, sizep) < 0)
47                 return -EINVAL;
48
49         return 0;
50 }
51
52 /**
53  * format_mac_pxe() - obtain a MAC address in the PXE format
54  *
55  * This produces a MAC-address string in the format for the current ethernet
56  * device:
57  *
58  *   01-aa-bb-cc-dd-ee-ff
59  *
60  * where aa-ff is the MAC address in hex
61  *
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
66  */
67 int format_mac_pxe(char *outbuf, size_t outbuf_len)
68 {
69         uchar ethaddr[6];
70
71         if (outbuf_len < 21) {
72                 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
73                 return -ENOSPC;
74         }
75
76         if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
77                 return -ENOENT;
78
79         sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
80                 ethaddr[0], ethaddr[1], ethaddr[2],
81                 ethaddr[3], ethaddr[4], ethaddr[5]);
82
83         return 1;
84 }
85
86 /**
87  * get_relfile() - read a file relative to the PXE file
88  *
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.
93  *
94  * @ctx: PXE context
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
99  */
100 static int get_relfile(struct pxe_context *ctx, const char *file_path,
101                        unsigned long file_addr, ulong *filesizep)
102 {
103         size_t path_len;
104         char relfile[MAX_TFTP_PATH_LEN + 1];
105         char addr_buf[18];
106         ulong size;
107         int ret;
108
109         if (file_path[0] == '/' && ctx->allow_abs_path)
110                 *relfile = '\0';
111         else
112                 strncpy(relfile, ctx->bootdir, MAX_TFTP_PATH_LEN);
113
114         path_len = strlen(file_path) + strlen(relfile);
115
116         if (path_len > MAX_TFTP_PATH_LEN) {
117                 printf("Base path too long (%s%s)\n", relfile, file_path);
118
119                 return -ENAMETOOLONG;
120         }
121
122         strcat(relfile, file_path);
123
124         printf("Retrieving file: %s\n", relfile);
125
126         sprintf(addr_buf, "%lx", file_addr);
127
128         ret = ctx->getfile(ctx, relfile, addr_buf, &size);
129         if (ret < 0)
130                 return log_msg_ret("get", ret);
131         if (filesizep)
132                 *filesizep = size;
133
134         return 1;
135 }
136
137 /**
138  * get_pxe_file() - read a file
139  *
140  * The file is read and nul-terminated
141  *
142  * @ctx: PXE context
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
146  */
147 int get_pxe_file(struct pxe_context *ctx, const char *file_path,
148                  ulong file_addr)
149 {
150         ulong size;
151         int err;
152         char *buf;
153
154         err = get_relfile(ctx, file_path, file_addr, &size);
155         if (err < 0)
156                 return err;
157
158         buf = map_sysmem(file_addr + size, 1);
159         *buf = '\0';
160         unmap_sysmem(buf);
161
162         return 1;
163 }
164
165 #define PXELINUX_DIR "pxelinux.cfg/"
166
167 /**
168  * get_pxelinux_path() - Get a file in the pxelinux.cfg/ directory
169  *
170  * @ctx: PXE context
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
174  */
175 int get_pxelinux_path(struct pxe_context *ctx, const char *file,
176                       unsigned long pxefile_addr_r)
177 {
178         size_t base_len = strlen(PXELINUX_DIR);
179         char path[MAX_TFTP_PATH_LEN + 1];
180
181         if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
182                 printf("path (%s%s) too long, skipping\n",
183                        PXELINUX_DIR, file);
184                 return -ENAMETOOLONG;
185         }
186
187         sprintf(path, PXELINUX_DIR "%s", file);
188
189         return get_pxe_file(ctx, path, pxefile_addr_r);
190 }
191
192 /**
193  * get_relfile_envaddr() - read a file to an address in an env var
194  *
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.
198  *
199  * @ctx: PXE context
200  * @file_path: File path to read (relative to the PXE file)
201  * @envaddr_name: Name of environment variable which contains the address to
202  *      load 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
207  */
208 static int get_relfile_envaddr(struct pxe_context *ctx, const char *file_path,
209                                const char *envaddr_name, ulong *filesizep)
210 {
211         unsigned long file_addr;
212         char *envaddr;
213
214         envaddr = from_env(envaddr_name);
215         if (!envaddr)
216                 return -ENOENT;
217
218         if (strict_strtoul(envaddr, 16, &file_addr) < 0)
219                 return -EINVAL;
220
221         return get_relfile(ctx, file_path, file_addr, filesizep);
222 }
223
224 /**
225  * label_create() - crate a new PXE label
226  *
227  * Allocates memory for and initializes a pxe_label. This uses malloc, so the
228  * result must be free()'d to reclaim the memory.
229  *
230  * Returns a pointer to the label, or NULL if out of memory
231  */
232 static struct pxe_label *label_create(void)
233 {
234         struct pxe_label *label;
235
236         label = malloc(sizeof(struct pxe_label));
237         if (!label)
238                 return NULL;
239
240         memset(label, 0, sizeof(struct pxe_label));
241
242         return label;
243 }
244
245 /**
246  * label_destroy() - free the memory used by a pxe_label
247  *
248  * This frees @label itself as well as memory used by its name,
249  * kernel, config, append, initrd, fdt, fdtdir and fdtoverlay members, if
250  * they're non-NULL.
251  *
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.
255  *
256  * @label: Label to free
257  */
258 static void label_destroy(struct pxe_label *label)
259 {
260         free(label->name);
261         free(label->kernel_label);
262         free(label->kernel);
263         free(label->config);
264         free(label->append);
265         free(label->initrd);
266         free(label->fdt);
267         free(label->fdtdir);
268         free(label->fdtoverlays);
269         free(label);
270 }
271
272 /**
273  * label_print() - Print a label and its string members if they're defined
274  *
275  * This is passed as a callback to the menu code for displaying each
276  * menu entry.
277  *
278  * @data: Label to print (is cast to struct pxe_label *)
279  */
280 static void label_print(void *data)
281 {
282         struct pxe_label *label = data;
283         const char *c = label->menu ? label->menu : label->name;
284
285         printf("%s:\t%s\n", label->num, c);
286 }
287
288 /**
289  * label_localboot() - Boot a label that specified 'localboot'
290  *
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'.
295  *
296  * @label: Label to process
297  * Returns 1 on success or < 0 on error
298  */
299 static int label_localboot(struct pxe_label *label)
300 {
301         char *localcmd;
302
303         localcmd = from_env("localcmd");
304         if (!localcmd)
305                 return -ENOENT;
306
307         if (label->append) {
308                 char bootargs[CONFIG_SYS_CBSIZE];
309
310                 cli_simple_process_macros(label->append, bootargs,
311                                           sizeof(bootargs));
312                 env_set("bootargs", bootargs);
313         }
314
315         debug("running: %s\n", localcmd);
316
317         return run_command_list(localcmd, strlen(localcmd), 0);
318 }
319
320 /*
321  * label_boot_kaslrseed generate kaslrseed from hw rng
322  */
323
324 static void label_boot_kaslrseed(void)
325 {
326 #ifdef CONFIG_DM_RNG
327         ulong fdt_addr;
328         struct fdt_header *working_fdt;
329         size_t n = 0x8;
330         struct udevice *dev;
331         u64 *buf;
332         int nodeoffset;
333         int err;
334
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);
339         if (err)
340                 return;
341
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);
345         if (err <= 0)
346                 return;
347
348         if (uclass_get_device(UCLASS_RNG, 0, &dev) || !dev) {
349                 printf("No RNG device\n");
350                 return;
351         }
352
353         nodeoffset = fdt_find_or_add_subnode(working_fdt, 0, "chosen");
354         if (nodeoffset < 0) {
355                 printf("Reading chosen node failed\n");
356                 return;
357         }
358
359         buf = malloc(n);
360         if (!buf) {
361                 printf("Out of memory\n");
362                 return;
363         }
364
365         if (dm_rng_read(dev, buf, n)) {
366                 printf("Reading RNG failed\n");
367                 goto err;
368         }
369
370         err = fdt_setprop(working_fdt, nodeoffset, "kaslr-seed", buf, sizeof(buf));
371         if (err < 0) {
372                 printf("Unable to set kaslr-seed on chosen node: %s\n", fdt_strerror(err));
373                 goto err;
374         }
375 err:
376         free(buf);
377 #endif
378         return;
379 }
380
381 /**
382  * label_boot_fdtoverlay() - Loads fdt overlays specified in 'fdtoverlays'
383  * or 'devicetree-overlay'
384  *
385  * @ctx: PXE context
386  * @label: Label to process
387  */
388 #ifdef CONFIG_OF_LIBFDT_OVERLAY
389 static void label_boot_fdtoverlay(struct pxe_context *ctx,
390                                   struct pxe_label *label)
391 {
392         char *fdtoverlay = label->fdtoverlays;
393         struct fdt_header *working_fdt;
394         char *fdtoverlay_addr_env;
395         ulong fdtoverlay_addr;
396         ulong fdt_addr;
397         int err;
398
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);
403         if (err)
404                 return;
405
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");
410                 return;
411         }
412
413         fdtoverlay_addr = hextoul(fdtoverlay_addr_env, NULL);
414
415         /* Cycle over the overlay files and apply them in order */
416         do {
417                 struct fdt_header *blob;
418                 char *overlayfile;
419                 char *end;
420                 int len;
421
422                 /* Drop leading spaces */
423                 while (*fdtoverlay == ' ')
424                         ++fdtoverlay;
425
426                 /* Copy a single filename if multiple provided */
427                 end = strstr(fdtoverlay, " ");
428                 if (end) {
429                         len = (int)(end - fdtoverlay);
430                         overlayfile = malloc(len + 1);
431                         strncpy(overlayfile, fdtoverlay, len);
432                         overlayfile[len] = '\0';
433                 } else
434                         overlayfile = fdtoverlay;
435
436                 if (!strlen(overlayfile))
437                         goto skip_overlay;
438
439                 /* Load overlay file */
440                 err = get_relfile_envaddr(ctx, overlayfile, "fdtoverlay_addr_r",
441                                           NULL);
442                 if (err < 0) {
443                         printf("Failed loading overlay %s\n", overlayfile);
444                         goto skip_overlay;
445                 }
446
447                 /* Resize main fdt */
448                 fdt_shrink_to_minimum(working_fdt, 8192);
449
450                 blob = map_sysmem(fdtoverlay_addr, 0);
451                 err = fdt_check_header(blob);
452                 if (err) {
453                         printf("Invalid overlay %s, skipping\n",
454                                overlayfile);
455                         goto skip_overlay;
456                 }
457
458                 err = fdt_overlay_apply_verbose(working_fdt, blob);
459                 if (err) {
460                         printf("Failed to apply overlay %s, skipping\n",
461                                overlayfile);
462                         goto skip_overlay;
463                 }
464
465 skip_overlay:
466                 if (end)
467                         free(overlayfile);
468         } while ((fdtoverlay = strstr(fdtoverlay, " ")));
469 }
470 #endif
471
472 /**
473  * label_boot() - Boot according to the contents of a pxe_label
474  *
475  * If we can't boot for any reason, we return.  A successful boot never
476  * returns.
477  *
478  * The kernel will be stored in the location given by the 'kernel_addr_r'
479  * environment variable.
480  *
481  * If the label specifies an initrd file, it will be stored in the location
482  * given by the 'ramdisk_addr_r' environment variable.
483  *
484  * If the label specifies an 'append' line, its contents will overwrite that
485  * of the 'bootargs' environment variable.
486  *
487  * @ctx: PXE context
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
491  */
492 static int label_boot(struct pxe_context *ctx, struct pxe_label *label)
493 {
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];
499         char initrd_str[28];
500         char mac_str[29] = "";
501         char ip_str[68] = "";
502         char *fit_addr = NULL;
503         int bootm_argc = 2;
504         int zboot_argc = 3;
505         int len = 0;
506         ulong kernel_addr_r;
507         void *buf;
508
509         label_print(label);
510
511         label->attempted = 1;
512
513         if (label->localboot) {
514                 if (label->localboot_val >= 0)
515                         label_localboot(label);
516                 return 0;
517         }
518
519         if (!label->kernel) {
520                 printf("No kernel given, skipping %s\n",
521                        label->name);
522                 return 1;
523         }
524
525         if (get_relfile_envaddr(ctx, label->kernel, "kernel_addr_r",
526                                 NULL) < 0) {
527                 printf("Skipping %s for failure retrieving kernel\n",
528                        label->name);
529                 return 1;
530         }
531
532         kernel_addr = env_get("kernel_addr_r");
533         /* for FIT, append the configuration identifier */
534         if (label->config) {
535                 int len = strlen(kernel_addr) + strlen(label->config) + 1;
536
537                 fit_addr = malloc(len);
538                 if (!fit_addr) {
539                         printf("malloc fail (FIT address)\n");
540                         return 1;
541                 }
542                 snprintf(fit_addr, len, "%s%s", kernel_addr, label->config);
543                 kernel_addr = fit_addr;
544         }
545
546         /* For FIT, the label can be identical to kernel one */
547         if (label->initrd && !strcmp(label->kernel_label, label->initrd)) {
548                 initrd_addr_str =  kernel_addr;
549         } else if (label->initrd) {
550                 ulong size;
551                 if (get_relfile_envaddr(ctx, label->initrd, "ramdisk_addr_r",
552                                         &size) < 0) {
553                         printf("Skipping %s for failure retrieving initrd\n",
554                                label->name);
555                         goto cleanup;
556                 }
557
558                 initrd_addr_str = env_get("ramdisk_addr_r");
559                 size = snprintf(initrd_str, sizeof(initrd_str), "%s:%lx",
560                                 initrd_addr_str, size);
561                 if (size >= sizeof(initrd_str))
562                         goto cleanup;
563         }
564
565         if (label->ipappend & 0x1) {
566                 sprintf(ip_str, " ip=%s:%s:%s:%s",
567                         env_get("ipaddr"), env_get("serverip"),
568                         env_get("gatewayip"), env_get("netmask"));
569         }
570
571         if (IS_ENABLED(CONFIG_CMD_NET)) {
572                 if (label->ipappend & 0x2) {
573                         int err;
574
575                         strcpy(mac_str, " BOOTIF=");
576                         err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
577                         if (err < 0)
578                                 mac_str[0] = '\0';
579                 }
580         }
581
582         if ((label->ipappend & 0x3) || label->append) {
583                 char bootargs[CONFIG_SYS_CBSIZE] = "";
584                 char finalbootargs[CONFIG_SYS_CBSIZE];
585
586                 if (strlen(label->append ?: "") +
587                     strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
588                         printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
589                                strlen(label->append ?: ""),
590                                strlen(ip_str), strlen(mac_str),
591                                sizeof(bootargs));
592                         goto cleanup;
593                 }
594
595                 if (label->append)
596                         strncpy(bootargs, label->append, sizeof(bootargs));
597
598                 strcat(bootargs, ip_str);
599                 strcat(bootargs, mac_str);
600
601                 cli_simple_process_macros(bootargs, finalbootargs,
602                                           sizeof(finalbootargs));
603                 env_set("bootargs", finalbootargs);
604                 printf("append: %s\n", finalbootargs);
605         }
606
607         /*
608          * fdt usage is optional:
609          * It handles the following scenarios.
610          *
611          * Scenario 1: If fdt_addr_r specified and "fdt" or "fdtdir" label is
612          * defined in pxe file, retrieve fdt blob from server. Pass fdt_addr_r to
613          * bootm, and adjust argc appropriately.
614          *
615          * If retrieve fails and no exact fdt blob is specified in pxe file with
616          * "fdt" label, try Scenario 2.
617          *
618          * Scenario 2: If there is an fdt_addr specified, pass it along to
619          * bootm, and adjust argc appropriately.
620          *
621          * Scenario 3: If there is an fdtcontroladdr specified, pass it along to
622          * bootm, and adjust argc appropriately.
623          *
624          * Scenario 4: fdt blob is not available.
625          */
626         bootm_argv[3] = env_get("fdt_addr_r");
627
628         /* For FIT, the label can be identical to kernel one */
629         if (label->fdt && !strcmp(label->kernel_label, label->fdt)) {
630                 bootm_argv[3] = kernel_addr;
631         /* if fdt label is defined then get fdt from server */
632         } else if (bootm_argv[3]) {
633                 char *fdtfile = NULL;
634                 char *fdtfilefree = NULL;
635
636                 if (label->fdt) {
637                         fdtfile = label->fdt;
638                 } else if (label->fdtdir) {
639                         char *f1, *f2, *f3, *f4, *slash;
640
641                         f1 = env_get("fdtfile");
642                         if (f1) {
643                                 f2 = "";
644                                 f3 = "";
645                                 f4 = "";
646                         } else {
647                                 /*
648                                  * For complex cases where this code doesn't
649                                  * generate the correct filename, the board
650                                  * code should set $fdtfile during early boot,
651                                  * or the boot scripts should set $fdtfile
652                                  * before invoking "pxe" or "sysboot".
653                                  */
654                                 f1 = env_get("soc");
655                                 f2 = "-";
656                                 f3 = env_get("board");
657                                 f4 = ".dtb";
658                                 if (!f1) {
659                                         f1 = "";
660                                         f2 = "";
661                                 }
662                                 if (!f3) {
663                                         f2 = "";
664                                         f3 = "";
665                                 }
666                         }
667
668                         len = strlen(label->fdtdir);
669                         if (!len)
670                                 slash = "./";
671                         else if (label->fdtdir[len - 1] != '/')
672                                 slash = "/";
673                         else
674                                 slash = "";
675
676                         len = strlen(label->fdtdir) + strlen(slash) +
677                                 strlen(f1) + strlen(f2) + strlen(f3) +
678                                 strlen(f4) + 1;
679                         fdtfilefree = malloc(len);
680                         if (!fdtfilefree) {
681                                 printf("malloc fail (FDT filename)\n");
682                                 goto cleanup;
683                         }
684
685                         snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
686                                  label->fdtdir, slash, f1, f2, f3, f4);
687                         fdtfile = fdtfilefree;
688                 }
689
690                 if (fdtfile) {
691                         int err = get_relfile_envaddr(ctx, fdtfile,
692                                                       "fdt_addr_r", NULL);
693
694                         free(fdtfilefree);
695                         if (err < 0) {
696                                 bootm_argv[3] = NULL;
697
698                                 if (label->fdt) {
699                                         printf("Skipping %s for failure retrieving FDT\n",
700                                                label->name);
701                                         goto cleanup;
702                                 }
703                         }
704
705                 if (label->kaslrseed)
706                         label_boot_kaslrseed();
707
708 #ifdef CONFIG_OF_LIBFDT_OVERLAY
709                         if (label->fdtoverlays)
710                                 label_boot_fdtoverlay(ctx, label);
711 #endif
712                 } else {
713                         bootm_argv[3] = NULL;
714                 }
715         }
716
717         bootm_argv[1] = kernel_addr;
718         zboot_argv[1] = kernel_addr;
719
720         if (initrd_addr_str) {
721                 bootm_argv[2] = initrd_str;
722                 bootm_argc = 3;
723
724                 zboot_argv[3] = initrd_addr_str;
725                 zboot_argv[4] = initrd_filesize;
726                 zboot_argc = 5;
727         }
728
729         if (!bootm_argv[3])
730                 bootm_argv[3] = env_get("fdt_addr");
731
732         if (!bootm_argv[3])
733                 bootm_argv[3] = env_get("fdtcontroladdr");
734
735         if (bootm_argv[3]) {
736                 if (!bootm_argv[2])
737                         bootm_argv[2] = "-";
738                 bootm_argc = 4;
739         }
740
741         kernel_addr_r = genimg_get_kernel_addr(kernel_addr);
742         buf = map_sysmem(kernel_addr_r, 0);
743         /* Try bootm for legacy and FIT format image */
744         if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID &&
745             IS_ENABLED(CONFIG_CMD_BOOTM))
746                 do_bootm(ctx->cmdtp, 0, bootm_argc, bootm_argv);
747         /* Try booting an AArch64 Linux kernel image */
748         else if (IS_ENABLED(CONFIG_CMD_BOOTI))
749                 do_booti(ctx->cmdtp, 0, bootm_argc, bootm_argv);
750         /* Try booting a Image */
751         else if (IS_ENABLED(CONFIG_CMD_BOOTZ))
752                 do_bootz(ctx->cmdtp, 0, bootm_argc, bootm_argv);
753         /* Try booting an x86_64 Linux kernel image */
754         else if (IS_ENABLED(CONFIG_CMD_ZBOOT))
755                 do_zboot_parent(ctx->cmdtp, 0, zboot_argc, zboot_argv, NULL);
756
757         unmap_sysmem(buf);
758
759 cleanup:
760         free(fit_addr);
761
762         return 1;
763 }
764
765 /** enum token_type - Tokens for the pxe file parser */
766 enum token_type {
767         T_EOL,
768         T_STRING,
769         T_EOF,
770         T_MENU,
771         T_TITLE,
772         T_TIMEOUT,
773         T_LABEL,
774         T_KERNEL,
775         T_LINUX,
776         T_APPEND,
777         T_INITRD,
778         T_LOCALBOOT,
779         T_DEFAULT,
780         T_PROMPT,
781         T_INCLUDE,
782         T_FDT,
783         T_FDTDIR,
784         T_FDTOVERLAYS,
785         T_ONTIMEOUT,
786         T_IPAPPEND,
787         T_BACKGROUND,
788         T_KASLRSEED,
789         T_INVALID
790 };
791
792 /** struct token - token - given by a value and a type */
793 struct token {
794         char *val;
795         enum token_type type;
796 };
797
798 /* Keywords recognized */
799 static const struct token keywords[] = {
800         {"menu", T_MENU},
801         {"title", T_TITLE},
802         {"timeout", T_TIMEOUT},
803         {"default", T_DEFAULT},
804         {"prompt", T_PROMPT},
805         {"label", T_LABEL},
806         {"kernel", T_KERNEL},
807         {"linux", T_LINUX},
808         {"localboot", T_LOCALBOOT},
809         {"append", T_APPEND},
810         {"initrd", T_INITRD},
811         {"include", T_INCLUDE},
812         {"devicetree", T_FDT},
813         {"fdt", T_FDT},
814         {"devicetreedir", T_FDTDIR},
815         {"fdtdir", T_FDTDIR},
816         {"fdtoverlays", T_FDTOVERLAYS},
817         {"devicetree-overlay", T_FDTOVERLAYS},
818         {"ontimeout", T_ONTIMEOUT,},
819         {"ipappend", T_IPAPPEND,},
820         {"background", T_BACKGROUND,},
821         {"kaslrseed", T_KASLRSEED,},
822         {NULL, T_INVALID}
823 };
824
825 /**
826  * enum lex_state - lexer state
827  *
828  * Since pxe(linux) files don't have a token to identify the start of a
829  * literal, we have to keep track of when we're in a state where a literal is
830  * expected vs when we're in a state a keyword is expected.
831  */
832 enum lex_state {
833         L_NORMAL = 0,
834         L_KEYWORD,
835         L_SLITERAL
836 };
837
838 /**
839  * get_string() - retrieves a string from *p and stores it as a token in *t.
840  *
841  * This is used for scanning both string literals and keywords.
842  *
843  * Characters from *p are copied into t-val until a character equal to
844  * delim is found, or a NUL byte is reached. If delim has the special value of
845  * ' ', any whitespace character will be used as a delimiter.
846  *
847  * If lower is unequal to 0, uppercase characters will be converted to
848  * lowercase in the result. This is useful to make keywords case
849  * insensitive.
850  *
851  * The location of *p is updated to point to the first character after the end
852  * of the token - the ending delimiter.
853  *
854  * Memory for t->val is allocated using malloc and must be free()'d to reclaim
855  * it.
856  *
857  * @p: Points to a pointer to the current position in the input being processed.
858  *      Updated to point at the first character after the current token
859  * @t: Pointers to a token to fill in
860  * @delim: Delimiter character to look for, either newline or space
861  * @lower: true to convert the string to lower case when storing
862  * Returns the new value of t->val, on success, NULL if out of memory
863  */
864 static char *get_string(char **p, struct token *t, char delim, int lower)
865 {
866         char *b, *e;
867         size_t len, i;
868
869         /*
870          * b and e both start at the beginning of the input stream.
871          *
872          * e is incremented until we find the ending delimiter, or a NUL byte
873          * is reached. Then, we take e - b to find the length of the token.
874          */
875         b = *p;
876         e = *p;
877         while (*e) {
878                 if ((delim == ' ' && isspace(*e)) || delim == *e)
879                         break;
880                 e++;
881         }
882
883         len = e - b;
884
885         /*
886          * Allocate memory to hold the string, and copy it in, converting
887          * characters to lowercase if lower is != 0.
888          */
889         t->val = malloc(len + 1);
890         if (!t->val)
891                 return NULL;
892
893         for (i = 0; i < len; i++, b++) {
894                 if (lower)
895                         t->val[i] = tolower(*b);
896                 else
897                         t->val[i] = *b;
898         }
899
900         t->val[len] = '\0';
901
902         /* Update *p so the caller knows where to continue scanning */
903         *p = e;
904         t->type = T_STRING;
905
906         return t->val;
907 }
908
909 /**
910  * get_keyword() - Populate a keyword token with a type and value
911  *
912  * Updates the ->type field based on the keyword string in @val
913  * @t: Token to populate
914  */
915 static void get_keyword(struct token *t)
916 {
917         int i;
918
919         for (i = 0; keywords[i].val; i++) {
920                 if (!strcmp(t->val, keywords[i].val)) {
921                         t->type = keywords[i].type;
922                         break;
923                 }
924         }
925 }
926
927 /**
928  * get_token() - Get the next token
929  *
930  * We have to keep track of which state we're in to know if we're looking to get
931  * a string literal or a keyword.
932  *
933  * @p: Points to a pointer to the current position in the input being processed.
934  *      Updated to point at the first character after the current token
935  */
936 static void get_token(char **p, struct token *t, enum lex_state state)
937 {
938         char *c = *p;
939
940         t->type = T_INVALID;
941
942         /* eat non EOL whitespace */
943         while (isblank(*c))
944                 c++;
945
946         /*
947          * eat comments. note that string literals can't begin with #, but
948          * can contain a # after their first character.
949          */
950         if (*c == '#') {
951                 while (*c && *c != '\n')
952                         c++;
953         }
954
955         if (*c == '\n') {
956                 t->type = T_EOL;
957                 c++;
958         } else if (*c == '\0') {
959                 t->type = T_EOF;
960                 c++;
961         } else if (state == L_SLITERAL) {
962                 get_string(&c, t, '\n', 0);
963         } else if (state == L_KEYWORD) {
964                 /*
965                  * when we expect a keyword, we first get the next string
966                  * token delimited by whitespace, and then check if it
967                  * matches a keyword in our keyword list. if it does, it's
968                  * converted to a keyword token of the appropriate type, and
969                  * if not, it remains a string token.
970                  */
971                 get_string(&c, t, ' ', 1);
972                 get_keyword(t);
973         }
974
975         *p = c;
976 }
977
978 /**
979  * eol_or_eof() - Find end of line
980  *
981  * Increment *c until we get to the end of the current line, or EOF
982  *
983  * @c: Points to a pointer to the current position in the input being processed.
984  *      Updated to point at the first character after the current token
985  */
986 static void eol_or_eof(char **c)
987 {
988         while (**c && **c != '\n')
989                 (*c)++;
990 }
991
992 /*
993  * All of these parse_* functions share some common behavior.
994  *
995  * They finish with *c pointing after the token they parse, and return 1 on
996  * success, or < 0 on error.
997  */
998
999 /*
1000  * Parse a string literal and store a pointer it at *dst. String literals
1001  * terminate at the end of the line.
1002  */
1003 static int parse_sliteral(char **c, char **dst)
1004 {
1005         struct token t;
1006         char *s = *c;
1007
1008         get_token(c, &t, L_SLITERAL);
1009
1010         if (t.type != T_STRING) {
1011                 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
1012                 return -EINVAL;
1013         }
1014
1015         *dst = t.val;
1016
1017         return 1;
1018 }
1019
1020 /*
1021  * Parse a base 10 (unsigned) integer and store it at *dst.
1022  */
1023 static int parse_integer(char **c, int *dst)
1024 {
1025         struct token t;
1026         char *s = *c;
1027
1028         get_token(c, &t, L_SLITERAL);
1029         if (t.type != T_STRING) {
1030                 printf("Expected string: %.*s\n", (int)(*c - s), s);
1031                 return -EINVAL;
1032         }
1033
1034         *dst = simple_strtol(t.val, NULL, 10);
1035
1036         free(t.val);
1037
1038         return 1;
1039 }
1040
1041 static int parse_pxefile_top(struct pxe_context *ctx, char *p, ulong base,
1042                              struct pxe_menu *cfg, int nest_level);
1043
1044 /*
1045  * Parse an include statement, and retrieve and parse the file it mentions.
1046  *
1047  * base should point to a location where it's safe to store the file, and
1048  * nest_level should indicate how many nested includes have occurred. For this
1049  * include, nest_level has already been incremented and doesn't need to be
1050  * incremented here.
1051  */
1052 static int handle_include(struct pxe_context *ctx, char **c, unsigned long base,
1053                           struct pxe_menu *cfg, int nest_level)
1054 {
1055         char *include_path;
1056         char *s = *c;
1057         int err;
1058         char *buf;
1059         int ret;
1060
1061         err = parse_sliteral(c, &include_path);
1062         if (err < 0) {
1063                 printf("Expected include path: %.*s\n", (int)(*c - s), s);
1064                 return err;
1065         }
1066
1067         err = get_pxe_file(ctx, include_path, base);
1068         if (err < 0) {
1069                 printf("Couldn't retrieve %s\n", include_path);
1070                 return err;
1071         }
1072
1073         buf = map_sysmem(base, 0);
1074         ret = parse_pxefile_top(ctx, buf, base, cfg, nest_level);
1075         unmap_sysmem(buf);
1076
1077         return ret;
1078 }
1079
1080 /*
1081  * Parse lines that begin with 'menu'.
1082  *
1083  * base and nest are provided to handle the 'menu include' case.
1084  *
1085  * base should point to a location where it's safe to store the included file.
1086  *
1087  * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1088  * a file it includes, 3 when parsing a file included by that file, and so on.
1089  */
1090 static int parse_menu(struct pxe_context *ctx, char **c, struct pxe_menu *cfg,
1091                       unsigned long base, int nest_level)
1092 {
1093         struct token t;
1094         char *s = *c;
1095         int err = 0;
1096
1097         get_token(c, &t, L_KEYWORD);
1098
1099         switch (t.type) {
1100         case T_TITLE:
1101                 err = parse_sliteral(c, &cfg->title);
1102
1103                 break;
1104
1105         case T_INCLUDE:
1106                 err = handle_include(ctx, c, base, cfg, nest_level + 1);
1107                 break;
1108
1109         case T_BACKGROUND:
1110                 err = parse_sliteral(c, &cfg->bmp);
1111                 break;
1112
1113         default:
1114                 printf("Ignoring malformed menu command: %.*s\n",
1115                        (int)(*c - s), s);
1116         }
1117         if (err < 0)
1118                 return err;
1119
1120         eol_or_eof(c);
1121
1122         return 1;
1123 }
1124
1125 /*
1126  * Handles parsing a 'menu line' when we're parsing a label.
1127  */
1128 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1129                             struct pxe_label *label)
1130 {
1131         struct token t;
1132         char *s;
1133
1134         s = *c;
1135
1136         get_token(c, &t, L_KEYWORD);
1137
1138         switch (t.type) {
1139         case T_DEFAULT:
1140                 if (!cfg->default_label)
1141                         cfg->default_label = strdup(label->name);
1142
1143                 if (!cfg->default_label)
1144                         return -ENOMEM;
1145
1146                 break;
1147         case T_LABEL:
1148                 parse_sliteral(c, &label->menu);
1149                 break;
1150         default:
1151                 printf("Ignoring malformed menu command: %.*s\n",
1152                        (int)(*c - s), s);
1153         }
1154
1155         eol_or_eof(c);
1156
1157         return 0;
1158 }
1159
1160 /*
1161  * Handles parsing a 'kernel' label.
1162  * expecting "filename" or "<fit_filename>#cfg"
1163  */
1164 static int parse_label_kernel(char **c, struct pxe_label *label)
1165 {
1166         char *s;
1167         int err;
1168
1169         err = parse_sliteral(c, &label->kernel);
1170         if (err < 0)
1171                 return err;
1172
1173         /* copy the kernel label to compare with FDT / INITRD when FIT is used */
1174         label->kernel_label = strdup(label->kernel);
1175         if (!label->kernel_label)
1176                 return -ENOMEM;
1177
1178         s = strstr(label->kernel, "#");
1179         if (!s)
1180                 return 1;
1181
1182         label->config = strdup(s);
1183         if (!label->config)
1184                 return -ENOMEM;
1185
1186         *s = 0;
1187
1188         return 1;
1189 }
1190
1191 /*
1192  * Parses a label and adds it to the list of labels for a menu.
1193  *
1194  * A label ends when we either get to the end of a file, or
1195  * get some input we otherwise don't have a handler defined
1196  * for.
1197  *
1198  */
1199 static int parse_label(char **c, struct pxe_menu *cfg)
1200 {
1201         struct token t;
1202         int len;
1203         char *s = *c;
1204         struct pxe_label *label;
1205         int err;
1206
1207         label = label_create();
1208         if (!label)
1209                 return -ENOMEM;
1210
1211         err = parse_sliteral(c, &label->name);
1212         if (err < 0) {
1213                 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1214                 label_destroy(label);
1215                 return -EINVAL;
1216         }
1217
1218         list_add_tail(&label->list, &cfg->labels);
1219
1220         while (1) {
1221                 s = *c;
1222                 get_token(c, &t, L_KEYWORD);
1223
1224                 err = 0;
1225                 switch (t.type) {
1226                 case T_MENU:
1227                         err = parse_label_menu(c, cfg, label);
1228                         break;
1229
1230                 case T_KERNEL:
1231                 case T_LINUX:
1232                         err = parse_label_kernel(c, label);
1233                         break;
1234
1235                 case T_APPEND:
1236                         err = parse_sliteral(c, &label->append);
1237                         if (label->initrd)
1238                                 break;
1239                         s = strstr(label->append, "initrd=");
1240                         if (!s)
1241                                 break;
1242                         s += 7;
1243                         len = (int)(strchr(s, ' ') - s);
1244                         label->initrd = malloc(len + 1);
1245                         strncpy(label->initrd, s, len);
1246                         label->initrd[len] = '\0';
1247
1248                         break;
1249
1250                 case T_INITRD:
1251                         if (!label->initrd)
1252                                 err = parse_sliteral(c, &label->initrd);
1253                         break;
1254
1255                 case T_FDT:
1256                         if (!label->fdt)
1257                                 err = parse_sliteral(c, &label->fdt);
1258                         break;
1259
1260                 case T_FDTDIR:
1261                         if (!label->fdtdir)
1262                                 err = parse_sliteral(c, &label->fdtdir);
1263                         break;
1264
1265                 case T_FDTOVERLAYS:
1266                         if (!label->fdtoverlays)
1267                                 err = parse_sliteral(c, &label->fdtoverlays);
1268                         break;
1269
1270                 case T_LOCALBOOT:
1271                         label->localboot = 1;
1272                         err = parse_integer(c, &label->localboot_val);
1273                         break;
1274
1275                 case T_IPAPPEND:
1276                         err = parse_integer(c, &label->ipappend);
1277                         break;
1278
1279                 case T_KASLRSEED:
1280                         label->kaslrseed = 1;
1281                         break;
1282
1283                 case T_EOL:
1284                         break;
1285
1286                 default:
1287                         /*
1288                          * put the token back! we don't want it - it's the end
1289                          * of a label and whatever token this is, it's
1290                          * something for the menu level context to handle.
1291                          */
1292                         *c = s;
1293                         return 1;
1294                 }
1295
1296                 if (err < 0)
1297                         return err;
1298         }
1299 }
1300
1301 /*
1302  * This 16 comes from the limit pxelinux imposes on nested includes.
1303  *
1304  * There is no reason at all we couldn't do more, but some limit helps prevent
1305  * infinite (until crash occurs) recursion if a file tries to include itself.
1306  */
1307 #define MAX_NEST_LEVEL 16
1308
1309 /*
1310  * Entry point for parsing a menu file. nest_level indicates how many times
1311  * we've nested in includes.  It will be 1 for the top level menu file.
1312  *
1313  * Returns 1 on success, < 0 on error.
1314  */
1315 static int parse_pxefile_top(struct pxe_context *ctx, char *p, unsigned long base,
1316                              struct pxe_menu *cfg, int nest_level)
1317 {
1318         struct token t;
1319         char *s, *b, *label_name;
1320         int err;
1321
1322         b = p;
1323
1324         if (nest_level > MAX_NEST_LEVEL) {
1325                 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1326                 return -EMLINK;
1327         }
1328
1329         while (1) {
1330                 s = p;
1331
1332                 get_token(&p, &t, L_KEYWORD);
1333
1334                 err = 0;
1335                 switch (t.type) {
1336                 case T_MENU:
1337                         cfg->prompt = 1;
1338                         err = parse_menu(ctx, &p, cfg,
1339                                          base + ALIGN(strlen(b) + 1, 4),
1340                                          nest_level);
1341                         break;
1342
1343                 case T_TIMEOUT:
1344                         err = parse_integer(&p, &cfg->timeout);
1345                         break;
1346
1347                 case T_LABEL:
1348                         err = parse_label(&p, cfg);
1349                         break;
1350
1351                 case T_DEFAULT:
1352                 case T_ONTIMEOUT:
1353                         err = parse_sliteral(&p, &label_name);
1354
1355                         if (label_name) {
1356                                 if (cfg->default_label)
1357                                         free(cfg->default_label);
1358
1359                                 cfg->default_label = label_name;
1360                         }
1361
1362                         break;
1363
1364                 case T_INCLUDE:
1365                         err = handle_include(ctx, &p,
1366                                              base + ALIGN(strlen(b), 4), cfg,
1367                                              nest_level + 1);
1368                         break;
1369
1370                 case T_PROMPT:
1371                         eol_or_eof(&p);
1372                         break;
1373
1374                 case T_EOL:
1375                         break;
1376
1377                 case T_EOF:
1378                         return 1;
1379
1380                 default:
1381                         printf("Ignoring unknown command: %.*s\n",
1382                                (int)(p - s), s);
1383                         eol_or_eof(&p);
1384                 }
1385
1386                 if (err < 0)
1387                         return err;
1388         }
1389 }
1390
1391 /*
1392  */
1393 void destroy_pxe_menu(struct pxe_menu *cfg)
1394 {
1395         struct list_head *pos, *n;
1396         struct pxe_label *label;
1397
1398         free(cfg->title);
1399         free(cfg->default_label);
1400
1401         list_for_each_safe(pos, n, &cfg->labels) {
1402                 label = list_entry(pos, struct pxe_label, list);
1403
1404                 label_destroy(label);
1405         }
1406
1407         free(cfg);
1408 }
1409
1410 struct pxe_menu *parse_pxefile(struct pxe_context *ctx, unsigned long menucfg)
1411 {
1412         struct pxe_menu *cfg;
1413         char *buf;
1414         int r;
1415
1416         cfg = malloc(sizeof(struct pxe_menu));
1417         if (!cfg)
1418                 return NULL;
1419
1420         memset(cfg, 0, sizeof(struct pxe_menu));
1421
1422         INIT_LIST_HEAD(&cfg->labels);
1423
1424         buf = map_sysmem(menucfg, 0);
1425         r = parse_pxefile_top(ctx, buf, menucfg, cfg, 1);
1426         unmap_sysmem(buf);
1427         if (r < 0) {
1428                 destroy_pxe_menu(cfg);
1429                 return NULL;
1430         }
1431
1432         return cfg;
1433 }
1434
1435 /*
1436  * Converts a pxe_menu struct into a menu struct for use with U-Boot's generic
1437  * menu code.
1438  */
1439 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1440 {
1441         struct pxe_label *label;
1442         struct list_head *pos;
1443         struct menu *m;
1444         char *label_override;
1445         int err;
1446         int i = 1;
1447         char *default_num = NULL;
1448         char *override_num = NULL;
1449
1450         /*
1451          * Create a menu and add items for all the labels.
1452          */
1453         m = menu_create(cfg->title, DIV_ROUND_UP(cfg->timeout, 10),
1454                         cfg->prompt, NULL, label_print, NULL, NULL);
1455         if (!m)
1456                 return NULL;
1457
1458         label_override = env_get("pxe_label_override");
1459
1460         list_for_each(pos, &cfg->labels) {
1461                 label = list_entry(pos, struct pxe_label, list);
1462
1463                 sprintf(label->num, "%d", i++);
1464                 if (menu_item_add(m, label->num, label) != 1) {
1465                         menu_destroy(m);
1466                         return NULL;
1467                 }
1468                 if (cfg->default_label &&
1469                     (strcmp(label->name, cfg->default_label) == 0))
1470                         default_num = label->num;
1471                 if (label_override && !strcmp(label->name, label_override))
1472                         override_num = label->num;
1473         }
1474
1475
1476         if (label_override) {
1477                 if (override_num)
1478                         default_num = override_num;
1479                 else
1480                         printf("Missing override pxe label: %s\n",
1481                               label_override);
1482         }
1483
1484         /*
1485          * After we've created items for each label in the menu, set the
1486          * menu's default label if one was specified.
1487          */
1488         if (default_num) {
1489                 err = menu_default_set(m, default_num);
1490                 if (err != 1) {
1491                         if (err != -ENOENT) {
1492                                 menu_destroy(m);
1493                                 return NULL;
1494                         }
1495
1496                         printf("Missing default: %s\n", cfg->default_label);
1497                 }
1498         }
1499
1500         return m;
1501 }
1502
1503 /*
1504  * Try to boot any labels we have yet to attempt to boot.
1505  */
1506 static void boot_unattempted_labels(struct pxe_context *ctx,
1507                                     struct pxe_menu *cfg)
1508 {
1509         struct list_head *pos;
1510         struct pxe_label *label;
1511
1512         list_for_each(pos, &cfg->labels) {
1513                 label = list_entry(pos, struct pxe_label, list);
1514
1515                 if (!label->attempted)
1516                         label_boot(ctx, label);
1517         }
1518 }
1519
1520 void handle_pxe_menu(struct pxe_context *ctx, struct pxe_menu *cfg)
1521 {
1522         void *choice;
1523         struct menu *m;
1524         int err;
1525
1526         if (IS_ENABLED(CONFIG_CMD_BMP)) {
1527                 /* display BMP if available */
1528                 if (cfg->bmp) {
1529                         if (get_relfile(ctx, cfg->bmp, image_load_addr, NULL)) {
1530 #if defined(CONFIG_VIDEO)
1531                                 struct udevice *dev;
1532
1533                                 err = uclass_first_device_err(UCLASS_VIDEO, &dev);
1534                                 if (!err)
1535                                         video_clear(dev);
1536 #endif
1537                                 bmp_display(image_load_addr,
1538                                             BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1539                         } else {
1540                                 printf("Skipping background bmp %s for failure\n",
1541                                        cfg->bmp);
1542                         }
1543                 }
1544         }
1545
1546         m = pxe_menu_to_menu(cfg);
1547         if (!m)
1548                 return;
1549
1550         err = menu_get_choice(m, &choice);
1551         menu_destroy(m);
1552
1553         /*
1554          * err == 1 means we got a choice back from menu_get_choice.
1555          *
1556          * err == -ENOENT if the menu was setup to select the default but no
1557          * default was set. in that case, we should continue trying to boot
1558          * labels that haven't been attempted yet.
1559          *
1560          * otherwise, the user interrupted or there was some other error and
1561          * we give up.
1562          */
1563
1564         if (err == 1) {
1565                 err = label_boot(ctx, choice);
1566                 if (!err)
1567                         return;
1568         } else if (err != -ENOENT) {
1569                 return;
1570         }
1571
1572         boot_unattempted_labels(ctx, cfg);
1573 }
1574
1575 int pxe_setup_ctx(struct pxe_context *ctx, struct cmd_tbl *cmdtp,
1576                   pxe_getfile_func getfile, void *userdata,
1577                   bool allow_abs_path, const char *bootfile)
1578 {
1579         const char *last_slash;
1580         size_t path_len = 0;
1581
1582         memset(ctx, '\0', sizeof(*ctx));
1583         ctx->cmdtp = cmdtp;
1584         ctx->getfile = getfile;
1585         ctx->userdata = userdata;
1586         ctx->allow_abs_path = allow_abs_path;
1587
1588         /* figure out the boot directory, if there is one */
1589         if (bootfile && strlen(bootfile) >= MAX_TFTP_PATH_LEN)
1590                 return -ENOSPC;
1591         ctx->bootdir = strdup(bootfile ? bootfile : "");
1592         if (!ctx->bootdir)
1593                 return -ENOMEM;
1594
1595         if (bootfile) {
1596                 last_slash = strrchr(bootfile, '/');
1597                 if (last_slash)
1598                         path_len = (last_slash - bootfile) + 1;
1599         }
1600         ctx->bootdir[path_len] = '\0';
1601
1602         return 0;
1603 }
1604
1605 void pxe_destroy_ctx(struct pxe_context *ctx)
1606 {
1607         free(ctx->bootdir);
1608 }
1609
1610 int pxe_process(struct pxe_context *ctx, ulong pxefile_addr_r, bool prompt)
1611 {
1612         struct pxe_menu *cfg;
1613
1614         cfg = parse_pxefile(ctx, pxefile_addr_r);
1615         if (!cfg) {
1616                 printf("Error parsing config file\n");
1617                 return 1;
1618         }
1619
1620         if (prompt)
1621                 cfg->prompt = 1;
1622
1623         handle_pxe_menu(ctx, cfg);
1624
1625         destroy_pxe_menu(cfg);
1626
1627         return 0;
1628 }