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