1dd0a74ea392b2682e01ca1609aa2b39a17b8022
[oweals/u-boot.git] / cmd / pxe.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 <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 #include <fs.h>
17 #include <splash.h>
18 #include <asm/io.h>
19
20 #include "menu.h"
21 #include "cli.h"
22
23 #define MAX_TFTP_PATH_LEN 127
24
25 const char *pxe_default_paths[] = {
26 #ifdef CONFIG_SYS_SOC
27 #ifdef CONFIG_SYS_BOARD
28         "default-" CONFIG_SYS_ARCH "-" CONFIG_SYS_SOC "-" CONFIG_SYS_BOARD,
29 #endif
30         "default-" CONFIG_SYS_ARCH "-" CONFIG_SYS_SOC,
31 #endif
32         "default-" CONFIG_SYS_ARCH,
33         "default",
34         NULL
35 };
36
37 static bool is_pxe;
38
39 /*
40  * Like env_get, but prints an error if envvar isn't defined in the
41  * environment.  It always returns what env_get does, so it can be used in
42  * place of env_get without changing error handling otherwise.
43  */
44 static char *from_env(const char *envvar)
45 {
46         char *ret;
47
48         ret = env_get(envvar);
49
50         if (!ret)
51                 printf("missing environment variable: %s\n", envvar);
52
53         return ret;
54 }
55
56 #ifdef CONFIG_CMD_NET
57 /*
58  * Convert an ethaddr from the environment to the format used by pxelinux
59  * filenames based on mac addresses. Convert's ':' to '-', and adds "01-" to
60  * the beginning of the ethernet address to indicate a hardware type of
61  * Ethernet. Also converts uppercase hex characters into lowercase, to match
62  * pxelinux's behavior.
63  *
64  * Returns 1 for success, -ENOENT if 'ethaddr' is undefined in the
65  * environment, or some other value < 0 on error.
66  */
67 static int format_mac_pxe(char *outbuf, size_t outbuf_len)
68 {
69         uchar ethaddr[6];
70
71         if (outbuf_len < 21) {
72                 printf("outbuf is too small (%zd < 21)\n", outbuf_len);
73
74                 return -EINVAL;
75         }
76
77         if (!eth_env_get_enetaddr_by_index("eth", eth_get_dev_index(), ethaddr))
78                 return -ENOENT;
79
80         sprintf(outbuf, "01-%02x-%02x-%02x-%02x-%02x-%02x",
81                 ethaddr[0], ethaddr[1], ethaddr[2],
82                 ethaddr[3], ethaddr[4], ethaddr[5]);
83
84         return 1;
85 }
86 #endif
87
88 /*
89  * Returns the directory the file specified in the bootfile env variable is
90  * in. If bootfile isn't defined in the environment, return NULL, which should
91  * be interpreted as "don't prepend anything to paths".
92  */
93 static int get_bootfile_path(const char *file_path, char *bootfile_path,
94                              size_t bootfile_path_size)
95 {
96         char *bootfile, *last_slash;
97         size_t path_len = 0;
98
99         /* Only syslinux allows absolute paths */
100         if (file_path[0] == '/' && !is_pxe)
101                 goto ret;
102
103         bootfile = from_env("bootfile");
104
105         if (!bootfile)
106                 goto ret;
107
108         last_slash = strrchr(bootfile, '/');
109
110         if (last_slash == NULL)
111                 goto ret;
112
113         path_len = (last_slash - bootfile) + 1;
114
115         if (bootfile_path_size < path_len) {
116                 printf("bootfile_path too small. (%zd < %zd)\n",
117                                 bootfile_path_size, path_len);
118
119                 return -1;
120         }
121
122         strncpy(bootfile_path, bootfile, path_len);
123
124  ret:
125         bootfile_path[path_len] = '\0';
126
127         return 1;
128 }
129
130 static int (*do_getfile)(cmd_tbl_t *cmdtp, const char *file_path, char *file_addr);
131
132 #ifdef CONFIG_CMD_NET
133 static int do_get_tftp(cmd_tbl_t *cmdtp, const char *file_path, char *file_addr)
134 {
135         char *tftp_argv[] = {"tftp", NULL, NULL, NULL};
136
137         tftp_argv[1] = file_addr;
138         tftp_argv[2] = (void *)file_path;
139
140         if (do_tftpb(cmdtp, 0, 3, tftp_argv))
141                 return -ENOENT;
142
143         return 1;
144 }
145 #endif
146
147 static char *fs_argv[5];
148
149 static int do_get_ext2(cmd_tbl_t *cmdtp, const char *file_path, char *file_addr)
150 {
151 #ifdef CONFIG_CMD_EXT2
152         fs_argv[0] = "ext2load";
153         fs_argv[3] = file_addr;
154         fs_argv[4] = (void *)file_path;
155
156         if (!do_ext2load(cmdtp, 0, 5, fs_argv))
157                 return 1;
158 #endif
159         return -ENOENT;
160 }
161
162 static int do_get_fat(cmd_tbl_t *cmdtp, const char *file_path, char *file_addr)
163 {
164 #ifdef CONFIG_CMD_FAT
165         fs_argv[0] = "fatload";
166         fs_argv[3] = file_addr;
167         fs_argv[4] = (void *)file_path;
168
169         if (!do_fat_fsload(cmdtp, 0, 5, fs_argv))
170                 return 1;
171 #endif
172         return -ENOENT;
173 }
174
175 static int do_get_any(cmd_tbl_t *cmdtp, const char *file_path, char *file_addr)
176 {
177 #ifdef CONFIG_CMD_FS_GENERIC
178         fs_argv[0] = "load";
179         fs_argv[3] = file_addr;
180         fs_argv[4] = (void *)file_path;
181
182         if (!do_load(cmdtp, 0, 5, fs_argv, FS_TYPE_ANY))
183                 return 1;
184 #endif
185         return -ENOENT;
186 }
187
188 /*
189  * As in pxelinux, paths to files referenced from files we retrieve are
190  * relative to the location of bootfile. get_relfile takes such a path and
191  * joins it with the bootfile path to get the full path to the target file. If
192  * the bootfile path is NULL, we use file_path as is.
193  *
194  * Returns 1 for success, or < 0 on error.
195  */
196 static int get_relfile(cmd_tbl_t *cmdtp, const char *file_path,
197         unsigned long file_addr)
198 {
199         size_t path_len;
200         char relfile[MAX_TFTP_PATH_LEN+1];
201         char addr_buf[18];
202         int err;
203
204         err = get_bootfile_path(file_path, relfile, sizeof(relfile));
205
206         if (err < 0)
207                 return err;
208
209         path_len = strlen(file_path);
210         path_len += strlen(relfile);
211
212         if (path_len > MAX_TFTP_PATH_LEN) {
213                 printf("Base path too long (%s%s)\n",
214                                         relfile,
215                                         file_path);
216
217                 return -ENAMETOOLONG;
218         }
219
220         strcat(relfile, file_path);
221
222         printf("Retrieving file: %s\n", relfile);
223
224         sprintf(addr_buf, "%lx", file_addr);
225
226         return do_getfile(cmdtp, relfile, addr_buf);
227 }
228
229 /*
230  * Retrieve the file at 'file_path' to the locate given by 'file_addr'. If
231  * 'bootfile' was specified in the environment, the path to bootfile will be
232  * prepended to 'file_path' and the resulting path will be used.
233  *
234  * Returns 1 on success, or < 0 for error.
235  */
236 static int get_pxe_file(cmd_tbl_t *cmdtp, const char *file_path,
237         unsigned long file_addr)
238 {
239         unsigned long config_file_size;
240         char *tftp_filesize;
241         int err;
242         char *buf;
243
244         err = get_relfile(cmdtp, file_path, file_addr);
245
246         if (err < 0)
247                 return err;
248
249         /*
250          * the file comes without a NUL byte at the end, so find out its size
251          * and add the NUL byte.
252          */
253         tftp_filesize = from_env("filesize");
254
255         if (!tftp_filesize)
256                 return -ENOENT;
257
258         if (strict_strtoul(tftp_filesize, 16, &config_file_size) < 0)
259                 return -EINVAL;
260
261         buf = map_sysmem(file_addr + config_file_size, 1);
262         *buf = '\0';
263         unmap_sysmem(buf);
264
265         return 1;
266 }
267
268 #ifdef CONFIG_CMD_NET
269
270 #define PXELINUX_DIR "pxelinux.cfg/"
271
272 /*
273  * Retrieves a file in the 'pxelinux.cfg' folder. Since this uses get_pxe_file
274  * to do the hard work, the location of the 'pxelinux.cfg' folder is generated
275  * from the bootfile path, as described above.
276  *
277  * Returns 1 on success or < 0 on error.
278  */
279 static int get_pxelinux_path(cmd_tbl_t *cmdtp, const char *file,
280         unsigned long pxefile_addr_r)
281 {
282         size_t base_len = strlen(PXELINUX_DIR);
283         char path[MAX_TFTP_PATH_LEN+1];
284
285         if (base_len + strlen(file) > MAX_TFTP_PATH_LEN) {
286                 printf("path (%s%s) too long, skipping\n",
287                                 PXELINUX_DIR, file);
288                 return -ENAMETOOLONG;
289         }
290
291         sprintf(path, PXELINUX_DIR "%s", file);
292
293         return get_pxe_file(cmdtp, path, pxefile_addr_r);
294 }
295
296 /*
297  * Looks for a pxe file with a name based on the pxeuuid environment variable.
298  *
299  * Returns 1 on success or < 0 on error.
300  */
301 static int pxe_uuid_path(cmd_tbl_t *cmdtp, unsigned long pxefile_addr_r)
302 {
303         char *uuid_str;
304
305         uuid_str = from_env("pxeuuid");
306
307         if (!uuid_str)
308                 return -ENOENT;
309
310         return get_pxelinux_path(cmdtp, uuid_str, pxefile_addr_r);
311 }
312
313 /*
314  * Looks for a pxe file with a name based on the 'ethaddr' environment
315  * variable.
316  *
317  * Returns 1 on success or < 0 on error.
318  */
319 static int pxe_mac_path(cmd_tbl_t *cmdtp, unsigned long pxefile_addr_r)
320 {
321         char mac_str[21];
322         int err;
323
324         err = format_mac_pxe(mac_str, sizeof(mac_str));
325
326         if (err < 0)
327                 return err;
328
329         return get_pxelinux_path(cmdtp, mac_str, pxefile_addr_r);
330 }
331
332 /*
333  * Looks for pxe files with names based on our IP address. See pxelinux
334  * documentation for details on what these file names look like.  We match
335  * that exactly.
336  *
337  * Returns 1 on success or < 0 on error.
338  */
339 static int pxe_ipaddr_paths(cmd_tbl_t *cmdtp, unsigned long pxefile_addr_r)
340 {
341         char ip_addr[9];
342         int mask_pos, err;
343
344         sprintf(ip_addr, "%08X", ntohl(net_ip.s_addr));
345
346         for (mask_pos = 7; mask_pos >= 0;  mask_pos--) {
347                 err = get_pxelinux_path(cmdtp, ip_addr, pxefile_addr_r);
348
349                 if (err > 0)
350                         return err;
351
352                 ip_addr[mask_pos] = '\0';
353         }
354
355         return -ENOENT;
356 }
357
358 /*
359  * Entry point for the 'pxe get' command.
360  * This Follows pxelinux's rules to download a config file from a tftp server.
361  * The file is stored at the location given by the pxefile_addr_r environment
362  * variable, which must be set.
363  *
364  * UUID comes from pxeuuid env variable, if defined
365  * MAC addr comes from ethaddr env variable, if defined
366  * IP
367  *
368  * see http://syslinux.zytor.com/wiki/index.php/PXELINUX
369  *
370  * Returns 0 on success or 1 on error.
371  */
372 static int
373 do_pxe_get(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
374 {
375         char *pxefile_addr_str;
376         unsigned long pxefile_addr_r;
377         int err, i = 0;
378
379         do_getfile = do_get_tftp;
380
381         if (argc != 1)
382                 return CMD_RET_USAGE;
383
384         pxefile_addr_str = from_env("pxefile_addr_r");
385
386         if (!pxefile_addr_str)
387                 return 1;
388
389         err = strict_strtoul(pxefile_addr_str, 16,
390                                 (unsigned long *)&pxefile_addr_r);
391         if (err < 0)
392                 return 1;
393
394         /*
395          * Keep trying paths until we successfully get a file we're looking
396          * for.
397          */
398         if (pxe_uuid_path(cmdtp, pxefile_addr_r) > 0 ||
399             pxe_mac_path(cmdtp, pxefile_addr_r) > 0 ||
400             pxe_ipaddr_paths(cmdtp, pxefile_addr_r) > 0) {
401                 printf("Config file found\n");
402
403                 return 0;
404         }
405
406         while (pxe_default_paths[i]) {
407                 if (get_pxelinux_path(cmdtp, pxe_default_paths[i],
408                                       pxefile_addr_r) > 0) {
409                         printf("Config file found\n");
410                         return 0;
411                 }
412                 i++;
413         }
414
415         printf("Config file not found\n");
416
417         return 1;
418 }
419 #endif
420
421 /*
422  * Wrapper to make it easier to store the file at file_path in the location
423  * specified by envaddr_name. file_path will be joined to the bootfile path,
424  * if any is specified.
425  *
426  * Returns 1 on success or < 0 on error.
427  */
428 static int get_relfile_envaddr(cmd_tbl_t *cmdtp, const char *file_path, const char *envaddr_name)
429 {
430         unsigned long file_addr;
431         char *envaddr;
432
433         envaddr = from_env(envaddr_name);
434
435         if (!envaddr)
436                 return -ENOENT;
437
438         if (strict_strtoul(envaddr, 16, &file_addr) < 0)
439                 return -EINVAL;
440
441         return get_relfile(cmdtp, file_path, file_addr);
442 }
443
444 /*
445  * A note on the pxe file parser.
446  *
447  * We're parsing files that use syslinux grammar, which has a few quirks.
448  * String literals must be recognized based on context - there is no
449  * quoting or escaping support. There's also nothing to explicitly indicate
450  * when a label section completes. We deal with that by ending a label
451  * section whenever we see a line that doesn't include.
452  *
453  * As with the syslinux family, this same file format could be reused in the
454  * future for non pxe purposes. The only action it takes during parsing that
455  * would throw this off is handling of include files. It assumes we're using
456  * pxe, and does a tftp download of a file listed as an include file in the
457  * middle of the parsing operation. That could be handled by refactoring it to
458  * take a 'include file getter' function.
459  */
460
461 /*
462  * Describes a single label given in a pxe file.
463  *
464  * Create these with the 'label_create' function given below.
465  *
466  * name - the name of the menu as given on the 'menu label' line.
467  * kernel - the path to the kernel file to use for this label.
468  * append - kernel command line to use when booting this label
469  * initrd - path to the initrd to use for this label.
470  * attempted - 0 if we haven't tried to boot this label, 1 if we have.
471  * localboot - 1 if this label specified 'localboot', 0 otherwise.
472  * list - lets these form a list, which a pxe_menu struct will hold.
473  */
474 struct pxe_label {
475         char num[4];
476         char *name;
477         char *menu;
478         char *kernel;
479         char *config;
480         char *append;
481         char *initrd;
482         char *fdt;
483         char *fdtdir;
484         int ipappend;
485         int attempted;
486         int localboot;
487         int localboot_val;
488         struct list_head list;
489 };
490
491 /*
492  * Describes a pxe menu as given via pxe files.
493  *
494  * title - the name of the menu as given by a 'menu title' line.
495  * default_label - the name of the default label, if any.
496  * bmp - the bmp file name which is displayed in background
497  * timeout - time in tenths of a second to wait for a user key-press before
498  *           booting the default label.
499  * prompt - if 0, don't prompt for a choice unless the timeout period is
500  *          interrupted.  If 1, always prompt for a choice regardless of
501  *          timeout.
502  * labels - a list of labels defined for the menu.
503  */
504 struct pxe_menu {
505         char *title;
506         char *default_label;
507         char *bmp;
508         int timeout;
509         int prompt;
510         struct list_head labels;
511 };
512
513 /*
514  * Allocates memory for and initializes a pxe_label. This uses malloc, so the
515  * result must be free()'d to reclaim the memory.
516  *
517  * Returns NULL if malloc fails.
518  */
519 static struct pxe_label *label_create(void)
520 {
521         struct pxe_label *label;
522
523         label = malloc(sizeof(struct pxe_label));
524
525         if (!label)
526                 return NULL;
527
528         memset(label, 0, sizeof(struct pxe_label));
529
530         return label;
531 }
532
533 /*
534  * Free the memory used by a pxe_label, including that used by its name,
535  * kernel, append and initrd members, if they're non NULL.
536  *
537  * So - be sure to only use dynamically allocated memory for the members of
538  * the pxe_label struct, unless you want to clean it up first. These are
539  * currently only created by the pxe file parsing code.
540  */
541 static void label_destroy(struct pxe_label *label)
542 {
543         if (label->name)
544                 free(label->name);
545
546         if (label->kernel)
547                 free(label->kernel);
548
549         if (label->config)
550                 free(label->config);
551
552         if (label->append)
553                 free(label->append);
554
555         if (label->initrd)
556                 free(label->initrd);
557
558         if (label->fdt)
559                 free(label->fdt);
560
561         if (label->fdtdir)
562                 free(label->fdtdir);
563
564         free(label);
565 }
566
567 /*
568  * Print a label and its string members if they're defined.
569  *
570  * This is passed as a callback to the menu code for displaying each
571  * menu entry.
572  */
573 static void label_print(void *data)
574 {
575         struct pxe_label *label = data;
576         const char *c = label->menu ? label->menu : label->name;
577
578         printf("%s:\t%s\n", label->num, c);
579 }
580
581 /*
582  * Boot a label that specified 'localboot'. This requires that the 'localcmd'
583  * environment variable is defined. Its contents will be executed as U-Boot
584  * command.  If the label specified an 'append' line, its contents will be
585  * used to overwrite the contents of the 'bootargs' environment variable prior
586  * to running 'localcmd'.
587  *
588  * Returns 1 on success or < 0 on error.
589  */
590 static int label_localboot(struct pxe_label *label)
591 {
592         char *localcmd;
593
594         localcmd = from_env("localcmd");
595
596         if (!localcmd)
597                 return -ENOENT;
598
599         if (label->append) {
600                 char bootargs[CONFIG_SYS_CBSIZE];
601
602                 cli_simple_process_macros(label->append, bootargs);
603                 env_set("bootargs", bootargs);
604         }
605
606         debug("running: %s\n", localcmd);
607
608         return run_command_list(localcmd, strlen(localcmd), 0);
609 }
610
611 /*
612  * Boot according to the contents of a pxe_label.
613  *
614  * If we can't boot for any reason, we return.  A successful boot never
615  * returns.
616  *
617  * The kernel will be stored in the location given by the 'kernel_addr_r'
618  * environment variable.
619  *
620  * If the label specifies an initrd file, it will be stored in the location
621  * given by the 'ramdisk_addr_r' environment variable.
622  *
623  * If the label specifies an 'append' line, its contents will overwrite that
624  * of the 'bootargs' environment variable.
625  */
626 static int label_boot(cmd_tbl_t *cmdtp, struct pxe_label *label)
627 {
628         char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
629         char initrd_str[28];
630         char mac_str[29] = "";
631         char ip_str[68] = "";
632         char *fit_addr = NULL;
633         int bootm_argc = 2;
634         int len = 0;
635         ulong kernel_addr;
636         void *buf;
637
638         label_print(label);
639
640         label->attempted = 1;
641
642         if (label->localboot) {
643                 if (label->localboot_val >= 0)
644                         label_localboot(label);
645                 return 0;
646         }
647
648         if (label->kernel == NULL) {
649                 printf("No kernel given, skipping %s\n",
650                                 label->name);
651                 return 1;
652         }
653
654         if (label->initrd) {
655                 if (get_relfile_envaddr(cmdtp, label->initrd, "ramdisk_addr_r") < 0) {
656                         printf("Skipping %s for failure retrieving initrd\n",
657                                         label->name);
658                         return 1;
659                 }
660
661                 bootm_argv[2] = initrd_str;
662                 strncpy(bootm_argv[2], env_get("ramdisk_addr_r"), 18);
663                 strcat(bootm_argv[2], ":");
664                 strncat(bootm_argv[2], env_get("filesize"), 9);
665         }
666
667         if (get_relfile_envaddr(cmdtp, label->kernel, "kernel_addr_r") < 0) {
668                 printf("Skipping %s for failure retrieving kernel\n",
669                                 label->name);
670                 return 1;
671         }
672
673         if (label->ipappend & 0x1) {
674                 sprintf(ip_str, " ip=%s:%s:%s:%s",
675                         env_get("ipaddr"), env_get("serverip"),
676                         env_get("gatewayip"), env_get("netmask"));
677         }
678
679 #ifdef CONFIG_CMD_NET
680         if (label->ipappend & 0x2) {
681                 int err;
682                 strcpy(mac_str, " BOOTIF=");
683                 err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8);
684                 if (err < 0)
685                         mac_str[0] = '\0';
686         }
687 #endif
688
689         if ((label->ipappend & 0x3) || label->append) {
690                 char bootargs[CONFIG_SYS_CBSIZE] = "";
691                 char finalbootargs[CONFIG_SYS_CBSIZE];
692
693                 if (strlen(label->append ?: "") +
694                     strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) {
695                         printf("bootarg overflow %zd+%zd+%zd+1 > %zd\n",
696                                strlen(label->append ?: ""),
697                                strlen(ip_str), strlen(mac_str),
698                                sizeof(bootargs));
699                         return 1;
700                 } else {
701                         if (label->append)
702                                 strncpy(bootargs, label->append,
703                                         sizeof(bootargs));
704                         strcat(bootargs, ip_str);
705                         strcat(bootargs, mac_str);
706
707                         cli_simple_process_macros(bootargs, finalbootargs);
708                         env_set("bootargs", finalbootargs);
709                         printf("append: %s\n", finalbootargs);
710                 }
711         }
712
713         bootm_argv[1] = env_get("kernel_addr_r");
714         /* for FIT, append the configuration identifier */
715         if (label->config) {
716                 int len = strlen(bootm_argv[1]) + strlen(label->config) + 1;
717
718                 fit_addr = malloc(len);
719                 if (!fit_addr) {
720                         printf("malloc fail (FIT address)\n");
721                         return 1;
722                 }
723                 snprintf(fit_addr, len, "%s%s", bootm_argv[1], label->config);
724                 bootm_argv[1] = fit_addr;
725         }
726
727         /*
728          * fdt usage is optional:
729          * It handles the following scenarios. All scenarios are exclusive
730          *
731          * Scenario 1: If fdt_addr_r specified and "fdt" label is defined in
732          * pxe file, retrieve fdt blob from server. Pass fdt_addr_r to bootm,
733          * and adjust argc appropriately.
734          *
735          * Scenario 2: If there is an fdt_addr specified, pass it along to
736          * bootm, and adjust argc appropriately.
737          *
738          * Scenario 3: fdt blob is not available.
739          */
740         bootm_argv[3] = env_get("fdt_addr_r");
741
742         /* if fdt label is defined then get fdt from server */
743         if (bootm_argv[3]) {
744                 char *fdtfile = NULL;
745                 char *fdtfilefree = NULL;
746
747                 if (label->fdt) {
748                         fdtfile = label->fdt;
749                 } else if (label->fdtdir) {
750                         char *f1, *f2, *f3, *f4, *slash;
751
752                         f1 = env_get("fdtfile");
753                         if (f1) {
754                                 f2 = "";
755                                 f3 = "";
756                                 f4 = "";
757                         } else {
758                                 /*
759                                  * For complex cases where this code doesn't
760                                  * generate the correct filename, the board
761                                  * code should set $fdtfile during early boot,
762                                  * or the boot scripts should set $fdtfile
763                                  * before invoking "pxe" or "sysboot".
764                                  */
765                                 f1 = env_get("soc");
766                                 f2 = "-";
767                                 f3 = env_get("board");
768                                 f4 = ".dtb";
769                         }
770
771                         len = strlen(label->fdtdir);
772                         if (!len)
773                                 slash = "./";
774                         else if (label->fdtdir[len - 1] != '/')
775                                 slash = "/";
776                         else
777                                 slash = "";
778
779                         len = strlen(label->fdtdir) + strlen(slash) +
780                                 strlen(f1) + strlen(f2) + strlen(f3) +
781                                 strlen(f4) + 1;
782                         fdtfilefree = malloc(len);
783                         if (!fdtfilefree) {
784                                 printf("malloc fail (FDT filename)\n");
785                                 goto cleanup;
786                         }
787
788                         snprintf(fdtfilefree, len, "%s%s%s%s%s%s",
789                                  label->fdtdir, slash, f1, f2, f3, f4);
790                         fdtfile = fdtfilefree;
791                 }
792
793                 if (fdtfile) {
794                         int err = get_relfile_envaddr(cmdtp, fdtfile, "fdt_addr_r");
795                         free(fdtfilefree);
796                         if (err < 0) {
797                                 printf("Skipping %s for failure retrieving fdt\n",
798                                                 label->name);
799                                 goto cleanup;
800                         }
801                 } else {
802                         bootm_argv[3] = NULL;
803                 }
804         }
805
806         if (!bootm_argv[3])
807                 bootm_argv[3] = env_get("fdt_addr");
808
809         if (bootm_argv[3]) {
810                 if (!bootm_argv[2])
811                         bootm_argv[2] = "-";
812                 bootm_argc = 4;
813         }
814
815         kernel_addr = genimg_get_kernel_addr(bootm_argv[1]);
816         buf = map_sysmem(kernel_addr, 0);
817         /* Try bootm for legacy and FIT format image */
818         if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID)
819                 do_bootm(cmdtp, 0, bootm_argc, bootm_argv);
820 #ifdef CONFIG_CMD_BOOTI
821         /* Try booting an AArch64 Linux kernel image */
822         else
823                 do_booti(cmdtp, 0, bootm_argc, bootm_argv);
824 #elif defined(CONFIG_CMD_BOOTZ)
825         /* Try booting a Image */
826         else
827                 do_bootz(cmdtp, 0, bootm_argc, bootm_argv);
828 #endif
829         unmap_sysmem(buf);
830
831 cleanup:
832         if (fit_addr)
833                 free(fit_addr);
834         return 1;
835 }
836
837 /*
838  * Tokens for the pxe file parser.
839  */
840 enum token_type {
841         T_EOL,
842         T_STRING,
843         T_EOF,
844         T_MENU,
845         T_TITLE,
846         T_TIMEOUT,
847         T_LABEL,
848         T_KERNEL,
849         T_LINUX,
850         T_APPEND,
851         T_INITRD,
852         T_LOCALBOOT,
853         T_DEFAULT,
854         T_PROMPT,
855         T_INCLUDE,
856         T_FDT,
857         T_FDTDIR,
858         T_ONTIMEOUT,
859         T_IPAPPEND,
860         T_BACKGROUND,
861         T_INVALID
862 };
863
864 /*
865  * A token - given by a value and a type.
866  */
867 struct token {
868         char *val;
869         enum token_type type;
870 };
871
872 /*
873  * Keywords recognized.
874  */
875 static const struct token keywords[] = {
876         {"menu", T_MENU},
877         {"title", T_TITLE},
878         {"timeout", T_TIMEOUT},
879         {"default", T_DEFAULT},
880         {"prompt", T_PROMPT},
881         {"label", T_LABEL},
882         {"kernel", T_KERNEL},
883         {"linux", T_LINUX},
884         {"localboot", T_LOCALBOOT},
885         {"append", T_APPEND},
886         {"initrd", T_INITRD},
887         {"include", T_INCLUDE},
888         {"devicetree", T_FDT},
889         {"fdt", T_FDT},
890         {"devicetreedir", T_FDTDIR},
891         {"fdtdir", T_FDTDIR},
892         {"ontimeout", T_ONTIMEOUT,},
893         {"ipappend", T_IPAPPEND,},
894         {"background", T_BACKGROUND,},
895         {NULL, T_INVALID}
896 };
897
898 /*
899  * Since pxe(linux) files don't have a token to identify the start of a
900  * literal, we have to keep track of when we're in a state where a literal is
901  * expected vs when we're in a state a keyword is expected.
902  */
903 enum lex_state {
904         L_NORMAL = 0,
905         L_KEYWORD,
906         L_SLITERAL
907 };
908
909 /*
910  * get_string retrieves a string from *p and stores it as a token in
911  * *t.
912  *
913  * get_string used for scanning both string literals and keywords.
914  *
915  * Characters from *p are copied into t-val until a character equal to
916  * delim is found, or a NUL byte is reached. If delim has the special value of
917  * ' ', any whitespace character will be used as a delimiter.
918  *
919  * If lower is unequal to 0, uppercase characters will be converted to
920  * lowercase in the result. This is useful to make keywords case
921  * insensitive.
922  *
923  * The location of *p is updated to point to the first character after the end
924  * of the token - the ending delimiter.
925  *
926  * On success, the new value of t->val is returned. Memory for t->val is
927  * allocated using malloc and must be free()'d to reclaim it.  If insufficient
928  * memory is available, NULL is returned.
929  */
930 static char *get_string(char **p, struct token *t, char delim, int lower)
931 {
932         char *b, *e;
933         size_t len, i;
934
935         /*
936          * b and e both start at the beginning of the input stream.
937          *
938          * e is incremented until we find the ending delimiter, or a NUL byte
939          * is reached. Then, we take e - b to find the length of the token.
940          */
941         b = e = *p;
942
943         while (*e) {
944                 if ((delim == ' ' && isspace(*e)) || delim == *e)
945                         break;
946                 e++;
947         }
948
949         len = e - b;
950
951         /*
952          * Allocate memory to hold the string, and copy it in, converting
953          * characters to lowercase if lower is != 0.
954          */
955         t->val = malloc(len + 1);
956         if (!t->val)
957                 return NULL;
958
959         for (i = 0; i < len; i++, b++) {
960                 if (lower)
961                         t->val[i] = tolower(*b);
962                 else
963                         t->val[i] = *b;
964         }
965
966         t->val[len] = '\0';
967
968         /*
969          * Update *p so the caller knows where to continue scanning.
970          */
971         *p = e;
972
973         t->type = T_STRING;
974
975         return t->val;
976 }
977
978 /*
979  * Populate a keyword token with a type and value.
980  */
981 static void get_keyword(struct token *t)
982 {
983         int i;
984
985         for (i = 0; keywords[i].val; i++) {
986                 if (!strcmp(t->val, keywords[i].val)) {
987                         t->type = keywords[i].type;
988                         break;
989                 }
990         }
991 }
992
993 /*
994  * Get the next token.  We have to keep track of which state we're in to know
995  * if we're looking to get a string literal or a keyword.
996  *
997  * *p is updated to point at the first character after the current token.
998  */
999 static void get_token(char **p, struct token *t, enum lex_state state)
1000 {
1001         char *c = *p;
1002
1003         t->type = T_INVALID;
1004
1005         /* eat non EOL whitespace */
1006         while (isblank(*c))
1007                 c++;
1008
1009         /*
1010          * eat comments. note that string literals can't begin with #, but
1011          * can contain a # after their first character.
1012          */
1013         if (*c == '#') {
1014                 while (*c && *c != '\n')
1015                         c++;
1016         }
1017
1018         if (*c == '\n') {
1019                 t->type = T_EOL;
1020                 c++;
1021         } else if (*c == '\0') {
1022                 t->type = T_EOF;
1023                 c++;
1024         } else if (state == L_SLITERAL) {
1025                 get_string(&c, t, '\n', 0);
1026         } else if (state == L_KEYWORD) {
1027                 /*
1028                  * when we expect a keyword, we first get the next string
1029                  * token delimited by whitespace, and then check if it
1030                  * matches a keyword in our keyword list. if it does, it's
1031                  * converted to a keyword token of the appropriate type, and
1032                  * if not, it remains a string token.
1033                  */
1034                 get_string(&c, t, ' ', 1);
1035                 get_keyword(t);
1036         }
1037
1038         *p = c;
1039 }
1040
1041 /*
1042  * Increment *c until we get to the end of the current line, or EOF.
1043  */
1044 static void eol_or_eof(char **c)
1045 {
1046         while (**c && **c != '\n')
1047                 (*c)++;
1048 }
1049
1050 /*
1051  * All of these parse_* functions share some common behavior.
1052  *
1053  * They finish with *c pointing after the token they parse, and return 1 on
1054  * success, or < 0 on error.
1055  */
1056
1057 /*
1058  * Parse a string literal and store a pointer it at *dst. String literals
1059  * terminate at the end of the line.
1060  */
1061 static int parse_sliteral(char **c, char **dst)
1062 {
1063         struct token t;
1064         char *s = *c;
1065
1066         get_token(c, &t, L_SLITERAL);
1067
1068         if (t.type != T_STRING) {
1069                 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
1070                 return -EINVAL;
1071         }
1072
1073         *dst = t.val;
1074
1075         return 1;
1076 }
1077
1078 /*
1079  * Parse a base 10 (unsigned) integer and store it at *dst.
1080  */
1081 static int parse_integer(char **c, int *dst)
1082 {
1083         struct token t;
1084         char *s = *c;
1085
1086         get_token(c, &t, L_SLITERAL);
1087
1088         if (t.type != T_STRING) {
1089                 printf("Expected string: %.*s\n", (int)(*c - s), s);
1090                 return -EINVAL;
1091         }
1092
1093         *dst = simple_strtol(t.val, NULL, 10);
1094
1095         free(t.val);
1096
1097         return 1;
1098 }
1099
1100 static int parse_pxefile_top(cmd_tbl_t *cmdtp, char *p, unsigned long base,
1101         struct pxe_menu *cfg, int nest_level);
1102
1103 /*
1104  * Parse an include statement, and retrieve and parse the file it mentions.
1105  *
1106  * base should point to a location where it's safe to store the file, and
1107  * nest_level should indicate how many nested includes have occurred. For this
1108  * include, nest_level has already been incremented and doesn't need to be
1109  * incremented here.
1110  */
1111 static int handle_include(cmd_tbl_t *cmdtp, char **c, unsigned long base,
1112                                 struct pxe_menu *cfg, int nest_level)
1113 {
1114         char *include_path;
1115         char *s = *c;
1116         int err;
1117         char *buf;
1118         int ret;
1119
1120         err = parse_sliteral(c, &include_path);
1121
1122         if (err < 0) {
1123                 printf("Expected include path: %.*s\n",
1124                                  (int)(*c - s), s);
1125                 return err;
1126         }
1127
1128         err = get_pxe_file(cmdtp, include_path, base);
1129
1130         if (err < 0) {
1131                 printf("Couldn't retrieve %s\n", include_path);
1132                 return err;
1133         }
1134
1135         buf = map_sysmem(base, 0);
1136         ret = parse_pxefile_top(cmdtp, buf, base, cfg, nest_level);
1137         unmap_sysmem(buf);
1138
1139         return ret;
1140 }
1141
1142 /*
1143  * Parse lines that begin with 'menu'.
1144  *
1145  * base and nest are provided to handle the 'menu include' case.
1146  *
1147  * base should point to a location where it's safe to store the included file.
1148  *
1149  * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
1150  * a file it includes, 3 when parsing a file included by that file, and so on.
1151  */
1152 static int parse_menu(cmd_tbl_t *cmdtp, char **c, struct pxe_menu *cfg,
1153                                 unsigned long base, int nest_level)
1154 {
1155         struct token t;
1156         char *s = *c;
1157         int err = 0;
1158
1159         get_token(c, &t, L_KEYWORD);
1160
1161         switch (t.type) {
1162         case T_TITLE:
1163                 err = parse_sliteral(c, &cfg->title);
1164
1165                 break;
1166
1167         case T_INCLUDE:
1168                 err = handle_include(cmdtp, c, base, cfg,
1169                                                 nest_level + 1);
1170                 break;
1171
1172         case T_BACKGROUND:
1173                 err = parse_sliteral(c, &cfg->bmp);
1174                 break;
1175
1176         default:
1177                 printf("Ignoring malformed menu command: %.*s\n",
1178                                 (int)(*c - s), s);
1179         }
1180
1181         if (err < 0)
1182                 return err;
1183
1184         eol_or_eof(c);
1185
1186         return 1;
1187 }
1188
1189 /*
1190  * Handles parsing a 'menu line' when we're parsing a label.
1191  */
1192 static int parse_label_menu(char **c, struct pxe_menu *cfg,
1193                                 struct pxe_label *label)
1194 {
1195         struct token t;
1196         char *s;
1197
1198         s = *c;
1199
1200         get_token(c, &t, L_KEYWORD);
1201
1202         switch (t.type) {
1203         case T_DEFAULT:
1204                 if (!cfg->default_label)
1205                         cfg->default_label = strdup(label->name);
1206
1207                 if (!cfg->default_label)
1208                         return -ENOMEM;
1209
1210                 break;
1211         case T_LABEL:
1212                 parse_sliteral(c, &label->menu);
1213                 break;
1214         default:
1215                 printf("Ignoring malformed menu command: %.*s\n",
1216                                 (int)(*c - s), s);
1217         }
1218
1219         eol_or_eof(c);
1220
1221         return 0;
1222 }
1223
1224 /*
1225  * Handles parsing a 'kernel' label.
1226  * expecting "filename" or "<fit_filename>#cfg"
1227  */
1228 static int parse_label_kernel(char **c, struct pxe_label *label)
1229 {
1230         char *s;
1231         int err;
1232
1233         err = parse_sliteral(c, &label->kernel);
1234         if (err < 0)
1235                 return err;
1236
1237         s = strstr(label->kernel, "#");
1238         if (!s)
1239                 return 1;
1240
1241         label->config = malloc(strlen(s) + 1);
1242         if (!label->config)
1243                 return -ENOMEM;
1244
1245         strcpy(label->config, s);
1246         *s = 0;
1247
1248         return 1;
1249 }
1250
1251 /*
1252  * Parses a label and adds it to the list of labels for a menu.
1253  *
1254  * A label ends when we either get to the end of a file, or
1255  * get some input we otherwise don't have a handler defined
1256  * for.
1257  *
1258  */
1259 static int parse_label(char **c, struct pxe_menu *cfg)
1260 {
1261         struct token t;
1262         int len;
1263         char *s = *c;
1264         struct pxe_label *label;
1265         int err;
1266
1267         label = label_create();
1268         if (!label)
1269                 return -ENOMEM;
1270
1271         err = parse_sliteral(c, &label->name);
1272         if (err < 0) {
1273                 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1274                 label_destroy(label);
1275                 return -EINVAL;
1276         }
1277
1278         list_add_tail(&label->list, &cfg->labels);
1279
1280         while (1) {
1281                 s = *c;
1282                 get_token(c, &t, L_KEYWORD);
1283
1284                 err = 0;
1285                 switch (t.type) {
1286                 case T_MENU:
1287                         err = parse_label_menu(c, cfg, label);
1288                         break;
1289
1290                 case T_KERNEL:
1291                 case T_LINUX:
1292                         err = parse_label_kernel(c, label);
1293                         break;
1294
1295                 case T_APPEND:
1296                         err = parse_sliteral(c, &label->append);
1297                         if (label->initrd)
1298                                 break;
1299                         s = strstr(label->append, "initrd=");
1300                         if (!s)
1301                                 break;
1302                         s += 7;
1303                         len = (int)(strchr(s, ' ') - s);
1304                         label->initrd = malloc(len + 1);
1305                         strncpy(label->initrd, s, len);
1306                         label->initrd[len] = '\0';
1307
1308                         break;
1309
1310                 case T_INITRD:
1311                         if (!label->initrd)
1312                                 err = parse_sliteral(c, &label->initrd);
1313                         break;
1314
1315                 case T_FDT:
1316                         if (!label->fdt)
1317                                 err = parse_sliteral(c, &label->fdt);
1318                         break;
1319
1320                 case T_FDTDIR:
1321                         if (!label->fdtdir)
1322                                 err = parse_sliteral(c, &label->fdtdir);
1323                         break;
1324
1325                 case T_LOCALBOOT:
1326                         label->localboot = 1;
1327                         err = parse_integer(c, &label->localboot_val);
1328                         break;
1329
1330                 case T_IPAPPEND:
1331                         err = parse_integer(c, &label->ipappend);
1332                         break;
1333
1334                 case T_EOL:
1335                         break;
1336
1337                 default:
1338                         /*
1339                          * put the token back! we don't want it - it's the end
1340                          * of a label and whatever token this is, it's
1341                          * something for the menu level context to handle.
1342                          */
1343                         *c = s;
1344                         return 1;
1345                 }
1346
1347                 if (err < 0)
1348                         return err;
1349         }
1350 }
1351
1352 /*
1353  * This 16 comes from the limit pxelinux imposes on nested includes.
1354  *
1355  * There is no reason at all we couldn't do more, but some limit helps prevent
1356  * infinite (until crash occurs) recursion if a file tries to include itself.
1357  */
1358 #define MAX_NEST_LEVEL 16
1359
1360 /*
1361  * Entry point for parsing a menu file. nest_level indicates how many times
1362  * we've nested in includes.  It will be 1 for the top level menu file.
1363  *
1364  * Returns 1 on success, < 0 on error.
1365  */
1366 static int parse_pxefile_top(cmd_tbl_t *cmdtp, char *p, unsigned long base,
1367                                 struct pxe_menu *cfg, int nest_level)
1368 {
1369         struct token t;
1370         char *s, *b, *label_name;
1371         int err;
1372
1373         b = p;
1374
1375         if (nest_level > MAX_NEST_LEVEL) {
1376                 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1377                 return -EMLINK;
1378         }
1379
1380         while (1) {
1381                 s = p;
1382
1383                 get_token(&p, &t, L_KEYWORD);
1384
1385                 err = 0;
1386                 switch (t.type) {
1387                 case T_MENU:
1388                         cfg->prompt = 1;
1389                         err = parse_menu(cmdtp, &p, cfg,
1390                                 base + ALIGN(strlen(b) + 1, 4),
1391                                 nest_level);
1392                         break;
1393
1394                 case T_TIMEOUT:
1395                         err = parse_integer(&p, &cfg->timeout);
1396                         break;
1397
1398                 case T_LABEL:
1399                         err = parse_label(&p, cfg);
1400                         break;
1401
1402                 case T_DEFAULT:
1403                 case T_ONTIMEOUT:
1404                         err = parse_sliteral(&p, &label_name);
1405
1406                         if (label_name) {
1407                                 if (cfg->default_label)
1408                                         free(cfg->default_label);
1409
1410                                 cfg->default_label = label_name;
1411                         }
1412
1413                         break;
1414
1415                 case T_INCLUDE:
1416                         err = handle_include(cmdtp, &p,
1417                                 base + ALIGN(strlen(b), 4), cfg,
1418                                 nest_level + 1);
1419                         break;
1420
1421                 case T_PROMPT:
1422                         eol_or_eof(&p);
1423                         break;
1424
1425                 case T_EOL:
1426                         break;
1427
1428                 case T_EOF:
1429                         return 1;
1430
1431                 default:
1432                         printf("Ignoring unknown command: %.*s\n",
1433                                                         (int)(p - s), s);
1434                         eol_or_eof(&p);
1435                 }
1436
1437                 if (err < 0)
1438                         return err;
1439         }
1440 }
1441
1442 /*
1443  * Free the memory used by a pxe_menu and its labels.
1444  */
1445 static void destroy_pxe_menu(struct pxe_menu *cfg)
1446 {
1447         struct list_head *pos, *n;
1448         struct pxe_label *label;
1449
1450         if (cfg->title)
1451                 free(cfg->title);
1452
1453         if (cfg->default_label)
1454                 free(cfg->default_label);
1455
1456         list_for_each_safe(pos, n, &cfg->labels) {
1457                 label = list_entry(pos, struct pxe_label, list);
1458
1459                 label_destroy(label);
1460         }
1461
1462         free(cfg);
1463 }
1464
1465 /*
1466  * Entry point for parsing a pxe file. This is only used for the top level
1467  * file.
1468  *
1469  * Returns NULL if there is an error, otherwise, returns a pointer to a
1470  * pxe_menu struct populated with the results of parsing the pxe file (and any
1471  * files it includes). The resulting pxe_menu struct can be free()'d by using
1472  * the destroy_pxe_menu() function.
1473  */
1474 static struct pxe_menu *parse_pxefile(cmd_tbl_t *cmdtp, unsigned long menucfg)
1475 {
1476         struct pxe_menu *cfg;
1477         char *buf;
1478         int r;
1479
1480         cfg = malloc(sizeof(struct pxe_menu));
1481
1482         if (!cfg)
1483                 return NULL;
1484
1485         memset(cfg, 0, sizeof(struct pxe_menu));
1486
1487         INIT_LIST_HEAD(&cfg->labels);
1488
1489         buf = map_sysmem(menucfg, 0);
1490         r = parse_pxefile_top(cmdtp, buf, menucfg, cfg, 1);
1491         unmap_sysmem(buf);
1492
1493         if (r < 0) {
1494                 destroy_pxe_menu(cfg);
1495                 return NULL;
1496         }
1497
1498         return cfg;
1499 }
1500
1501 /*
1502  * Converts a pxe_menu struct into a menu struct for use with U-Boot's generic
1503  * menu code.
1504  */
1505 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1506 {
1507         struct pxe_label *label;
1508         struct list_head *pos;
1509         struct menu *m;
1510         int err;
1511         int i = 1;
1512         char *default_num = NULL;
1513
1514         /*
1515          * Create a menu and add items for all the labels.
1516          */
1517         m = menu_create(cfg->title, DIV_ROUND_UP(cfg->timeout, 10),
1518                         cfg->prompt, label_print, NULL, NULL);
1519
1520         if (!m)
1521                 return NULL;
1522
1523         list_for_each(pos, &cfg->labels) {
1524                 label = list_entry(pos, struct pxe_label, list);
1525
1526                 sprintf(label->num, "%d", i++);
1527                 if (menu_item_add(m, label->num, label) != 1) {
1528                         menu_destroy(m);
1529                         return NULL;
1530                 }
1531                 if (cfg->default_label &&
1532                     (strcmp(label->name, cfg->default_label) == 0))
1533                         default_num = label->num;
1534
1535         }
1536
1537         /*
1538          * After we've created items for each label in the menu, set the
1539          * menu's default label if one was specified.
1540          */
1541         if (default_num) {
1542                 err = menu_default_set(m, default_num);
1543                 if (err != 1) {
1544                         if (err != -ENOENT) {
1545                                 menu_destroy(m);
1546                                 return NULL;
1547                         }
1548
1549                         printf("Missing default: %s\n", cfg->default_label);
1550                 }
1551         }
1552
1553         return m;
1554 }
1555
1556 /*
1557  * Try to boot any labels we have yet to attempt to boot.
1558  */
1559 static void boot_unattempted_labels(cmd_tbl_t *cmdtp, struct pxe_menu *cfg)
1560 {
1561         struct list_head *pos;
1562         struct pxe_label *label;
1563
1564         list_for_each(pos, &cfg->labels) {
1565                 label = list_entry(pos, struct pxe_label, list);
1566
1567                 if (!label->attempted)
1568                         label_boot(cmdtp, label);
1569         }
1570 }
1571
1572 /*
1573  * Boot the system as prescribed by a pxe_menu.
1574  *
1575  * Use the menu system to either get the user's choice or the default, based
1576  * on config or user input.  If there is no default or user's choice,
1577  * attempted to boot labels in the order they were given in pxe files.
1578  * If the default or user's choice fails to boot, attempt to boot other
1579  * labels in the order they were given in pxe files.
1580  *
1581  * If this function returns, there weren't any labels that successfully
1582  * booted, or the user interrupted the menu selection via ctrl+c.
1583  */
1584 static void handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg)
1585 {
1586         void *choice;
1587         struct menu *m;
1588         int err;
1589
1590 #ifdef CONFIG_CMD_BMP
1591         /* display BMP if available */
1592         if (cfg->bmp) {
1593                 if (get_relfile(cmdtp, cfg->bmp, load_addr)) {
1594                         run_command("cls", 0);
1595                         bmp_display(load_addr,
1596                                     BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
1597                 } else {
1598                         printf("Skipping background bmp %s for failure\n",
1599                                cfg->bmp);
1600                 }
1601         }
1602 #endif
1603
1604         m = pxe_menu_to_menu(cfg);
1605         if (!m)
1606                 return;
1607
1608         err = menu_get_choice(m, &choice);
1609
1610         menu_destroy(m);
1611
1612         /*
1613          * err == 1 means we got a choice back from menu_get_choice.
1614          *
1615          * err == -ENOENT if the menu was setup to select the default but no
1616          * default was set. in that case, we should continue trying to boot
1617          * labels that haven't been attempted yet.
1618          *
1619          * otherwise, the user interrupted or there was some other error and
1620          * we give up.
1621          */
1622
1623         if (err == 1) {
1624                 err = label_boot(cmdtp, choice);
1625                 if (!err)
1626                         return;
1627         } else if (err != -ENOENT) {
1628                 return;
1629         }
1630
1631         boot_unattempted_labels(cmdtp, cfg);
1632 }
1633
1634 #ifdef CONFIG_CMD_NET
1635 /*
1636  * Boots a system using a pxe file
1637  *
1638  * Returns 0 on success, 1 on error.
1639  */
1640 static int
1641 do_pxe_boot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1642 {
1643         unsigned long pxefile_addr_r;
1644         struct pxe_menu *cfg;
1645         char *pxefile_addr_str;
1646
1647         do_getfile = do_get_tftp;
1648
1649         if (argc == 1) {
1650                 pxefile_addr_str = from_env("pxefile_addr_r");
1651                 if (!pxefile_addr_str)
1652                         return 1;
1653
1654         } else if (argc == 2) {
1655                 pxefile_addr_str = argv[1];
1656         } else {
1657                 return CMD_RET_USAGE;
1658         }
1659
1660         if (strict_strtoul(pxefile_addr_str, 16, &pxefile_addr_r) < 0) {
1661                 printf("Invalid pxefile address: %s\n", pxefile_addr_str);
1662                 return 1;
1663         }
1664
1665         cfg = parse_pxefile(cmdtp, pxefile_addr_r);
1666
1667         if (cfg == NULL) {
1668                 printf("Error parsing config file\n");
1669                 return 1;
1670         }
1671
1672         handle_pxe_menu(cmdtp, cfg);
1673
1674         destroy_pxe_menu(cfg);
1675
1676         copy_filename(net_boot_file_name, "", sizeof(net_boot_file_name));
1677
1678         return 0;
1679 }
1680
1681 static cmd_tbl_t cmd_pxe_sub[] = {
1682         U_BOOT_CMD_MKENT(get, 1, 1, do_pxe_get, "", ""),
1683         U_BOOT_CMD_MKENT(boot, 2, 1, do_pxe_boot, "", "")
1684 };
1685
1686 static int do_pxe(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1687 {
1688         cmd_tbl_t *cp;
1689
1690         if (argc < 2)
1691                 return CMD_RET_USAGE;
1692
1693         is_pxe = true;
1694
1695         /* drop initial "pxe" arg */
1696         argc--;
1697         argv++;
1698
1699         cp = find_cmd_tbl(argv[0], cmd_pxe_sub, ARRAY_SIZE(cmd_pxe_sub));
1700
1701         if (cp)
1702                 return cp->cmd(cmdtp, flag, argc, argv);
1703
1704         return CMD_RET_USAGE;
1705 }
1706
1707 U_BOOT_CMD(
1708         pxe, 3, 1, do_pxe,
1709         "commands to get and boot from pxe files",
1710         "get - try to retrieve a pxe file using tftp\npxe "
1711         "boot [pxefile_addr_r] - boot from the pxe file at pxefile_addr_r\n"
1712 );
1713 #endif
1714
1715 /*
1716  * Boots a system using a local disk syslinux/extlinux file
1717  *
1718  * Returns 0 on success, 1 on error.
1719  */
1720 static int do_sysboot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1721 {
1722         unsigned long pxefile_addr_r;
1723         struct pxe_menu *cfg;
1724         char *pxefile_addr_str;
1725         char *filename;
1726         int prompt = 0;
1727
1728         is_pxe = false;
1729
1730         if (argc > 1 && strstr(argv[1], "-p")) {
1731                 prompt = 1;
1732                 argc--;
1733                 argv++;
1734         }
1735
1736         if (argc < 4)
1737                 return cmd_usage(cmdtp);
1738
1739         if (argc < 5) {
1740                 pxefile_addr_str = from_env("pxefile_addr_r");
1741                 if (!pxefile_addr_str)
1742                         return 1;
1743         } else {
1744                 pxefile_addr_str = argv[4];
1745         }
1746
1747         if (argc < 6)
1748                 filename = env_get("bootfile");
1749         else {
1750                 filename = argv[5];
1751                 env_set("bootfile", filename);
1752         }
1753
1754         if (strstr(argv[3], "ext2"))
1755                 do_getfile = do_get_ext2;
1756         else if (strstr(argv[3], "fat"))
1757                 do_getfile = do_get_fat;
1758         else if (strstr(argv[3], "any"))
1759                 do_getfile = do_get_any;
1760         else {
1761                 printf("Invalid filesystem: %s\n", argv[3]);
1762                 return 1;
1763         }
1764         fs_argv[1] = argv[1];
1765         fs_argv[2] = argv[2];
1766
1767         if (strict_strtoul(pxefile_addr_str, 16, &pxefile_addr_r) < 0) {
1768                 printf("Invalid pxefile address: %s\n", pxefile_addr_str);
1769                 return 1;
1770         }
1771
1772         if (get_pxe_file(cmdtp, filename, pxefile_addr_r) < 0) {
1773                 printf("Error reading config file\n");
1774                 return 1;
1775         }
1776
1777         cfg = parse_pxefile(cmdtp, pxefile_addr_r);
1778
1779         if (cfg == NULL) {
1780                 printf("Error parsing config file\n");
1781                 return 1;
1782         }
1783
1784         if (prompt)
1785                 cfg->prompt = 1;
1786
1787         handle_pxe_menu(cmdtp, cfg);
1788
1789         destroy_pxe_menu(cfg);
1790
1791         return 0;
1792 }
1793
1794 U_BOOT_CMD(
1795         sysboot, 7, 1, do_sysboot,
1796         "command to get and boot from syslinux files",
1797         "[-p] <interface> <dev[:part]> <ext2|fat|any> [addr] [filename]\n"
1798         "    - load and parse syslinux menu file 'filename' from ext2, fat\n"
1799         "      or any filesystem on 'dev' on 'interface' to address 'addr'"
1800 );