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