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