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