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