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