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