]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/cmd_pxe.c
Merge branch 'master' of /home/wd/git/u-boot/master
[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
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         void *pxefile_addr_r;
322         int err;
323
324         if (argc != 1)
325                 return cmd_usage(cmdtp);
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(pxefile_addr_r) > 0
343                 || pxe_mac_path(pxefile_addr_r) > 0
344                 || pxe_ipaddr_paths(pxefile_addr_r) > 0
345                 || get_pxelinux_path("default", 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         void *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, (unsigned long *)&file_addr) < 0)
375                 return -EINVAL;
376
377         return get_relfile(file_path, 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 *kernel;
413         char *append;
414         char *initrd;
415         int attempted;
416         int localboot;
417         struct list_head list;
418 };
419
420 /*
421  * Describes a pxe menu as given via pxe files.
422  *
423  * title - the name of the menu as given by a 'menu title' line.
424  * default_label - the name of the default label, if any.
425  * timeout - time in tenths of a second to wait for a user key-press before
426  *           booting the default label.
427  * prompt - if 0, don't prompt for a choice unless the timeout period is
428  *          interrupted.  If 1, always prompt for a choice regardless of
429  *          timeout.
430  * labels - a list of labels defined for the menu.
431  */
432 struct pxe_menu {
433         char *title;
434         char *default_label;
435         int timeout;
436         int prompt;
437         struct list_head labels;
438 };
439
440 /*
441  * Allocates memory for and initializes a pxe_label. This uses malloc, so the
442  * result must be free()'d to reclaim the memory.
443  *
444  * Returns NULL if malloc fails.
445  */
446 static struct pxe_label *label_create(void)
447 {
448         struct pxe_label *label;
449
450         label = malloc(sizeof(struct pxe_label));
451
452         if (!label)
453                 return NULL;
454
455         memset(label, 0, sizeof(struct pxe_label));
456
457         return label;
458 }
459
460 /*
461  * Free the memory used by a pxe_label, including that used by its name,
462  * kernel, append and initrd members, if they're non NULL.
463  *
464  * So - be sure to only use dynamically allocated memory for the members of
465  * the pxe_label struct, unless you want to clean it up first. These are
466  * currently only created by the pxe file parsing code.
467  */
468 static void label_destroy(struct pxe_label *label)
469 {
470         if (label->name)
471                 free(label->name);
472
473         if (label->kernel)
474                 free(label->kernel);
475
476         if (label->append)
477                 free(label->append);
478
479         if (label->initrd)
480                 free(label->initrd);
481
482         free(label);
483 }
484
485 /*
486  * Print a label and its string members if they're defined.
487  *
488  * This is passed as a callback to the menu code for displaying each
489  * menu entry.
490  */
491 static void label_print(void *data)
492 {
493         struct pxe_label *label = data;
494
495         printf("Label: %s\n", label->name);
496
497         if (label->kernel)
498                 printf("\tkernel: %s\n", label->kernel);
499
500         if (label->append)
501                 printf("\tappend: %s\n", label->append);
502
503         if (label->initrd)
504                 printf("\tinitrd: %s\n", label->initrd);
505 }
506
507 /*
508  * Boot a label that specified 'localboot'. This requires that the 'localcmd'
509  * environment variable is defined. Its contents will be executed as U-boot
510  * command.  If the label specified an 'append' line, its contents will be
511  * used to overwrite the contents of the 'bootargs' environment variable prior
512  * to running 'localcmd'.
513  *
514  * Returns 1 on success or < 0 on error.
515  */
516 static int label_localboot(struct pxe_label *label)
517 {
518         char *localcmd, *dupcmd;
519         int ret;
520
521         localcmd = from_env("localcmd");
522
523         if (!localcmd)
524                 return -ENOENT;
525
526         /*
527          * dup the command to avoid any issues with the version of it existing
528          * in the environment changing during the execution of the command.
529          */
530         dupcmd = strdup(localcmd);
531
532         if (!dupcmd)
533                 return -ENOMEM;
534
535         if (label->append)
536                 setenv("bootargs", label->append);
537
538         printf("running: %s\n", dupcmd);
539
540         ret = run_command2(dupcmd, 0);
541
542         free(dupcmd);
543
544         return ret;
545 }
546
547 /*
548  * Boot according to the contents of a pxe_label.
549  *
550  * If we can't boot for any reason, we return.  A successful boot never
551  * returns.
552  *
553  * The kernel will be stored in the location given by the 'kernel_addr_r'
554  * environment variable.
555  *
556  * If the label specifies an initrd file, it will be stored in the location
557  * given by the 'ramdisk_addr_r' environment variable.
558  *
559  * If the label specifies an 'append' line, its contents will overwrite that
560  * of the 'bootargs' environment variable.
561  */
562 static void label_boot(struct pxe_label *label)
563 {
564         char *bootm_argv[] = { "bootm", NULL, NULL, NULL, NULL };
565         int bootm_argc = 3;
566
567         label_print(label);
568
569         label->attempted = 1;
570
571         if (label->localboot) {
572                 label_localboot(label);
573                 return;
574         }
575
576         if (label->kernel == NULL) {
577                 printf("No kernel given, skipping %s\n",
578                                 label->name);
579                 return;
580         }
581
582         if (label->initrd) {
583                 if (get_relfile_envaddr(label->initrd, "ramdisk_addr_r") < 0) {
584                         printf("Skipping %s for failure retrieving initrd\n",
585                                         label->name);
586                         return;
587                 }
588
589                 bootm_argv[2] = getenv("ramdisk_addr_r");
590         } else {
591                 bootm_argv[2] = "-";
592         }
593
594         if (get_relfile_envaddr(label->kernel, "kernel_addr_r") < 0) {
595                 printf("Skipping %s for failure retrieving kernel\n",
596                                 label->name);
597                 return;
598         }
599
600         if (label->append)
601                 setenv("bootargs", label->append);
602
603         bootm_argv[1] = getenv("kernel_addr_r");
604
605         /*
606          * fdt usage is optional.  If there is an fdt_addr specified, we will
607          * pass it along to bootm, and adjust argc appropriately.
608          */
609         bootm_argv[3] = getenv("fdt_addr");
610
611         if (bootm_argv[3])
612                 bootm_argc = 4;
613
614         do_bootm(NULL, 0, bootm_argc, bootm_argv);
615 }
616
617 /*
618  * Tokens for the pxe file parser.
619  */
620 enum token_type {
621         T_EOL,
622         T_STRING,
623         T_EOF,
624         T_MENU,
625         T_TITLE,
626         T_TIMEOUT,
627         T_LABEL,
628         T_KERNEL,
629         T_APPEND,
630         T_INITRD,
631         T_LOCALBOOT,
632         T_DEFAULT,
633         T_PROMPT,
634         T_INCLUDE,
635         T_INVALID
636 };
637
638 /*
639  * A token - given by a value and a type.
640  */
641 struct token {
642         char *val;
643         enum token_type type;
644 };
645
646 /*
647  * Keywords recognized.
648  */
649 static const struct token keywords[] = {
650         {"menu", T_MENU},
651         {"title", T_TITLE},
652         {"timeout", T_TIMEOUT},
653         {"default", T_DEFAULT},
654         {"prompt", T_PROMPT},
655         {"label", T_LABEL},
656         {"kernel", T_KERNEL},
657         {"localboot", T_LOCALBOOT},
658         {"append", T_APPEND},
659         {"initrd", T_INITRD},
660         {"include", T_INCLUDE},
661         {NULL, T_INVALID}
662 };
663
664 /*
665  * Since pxe(linux) files don't have a token to identify the start of a
666  * literal, we have to keep track of when we're in a state where a literal is
667  * expected vs when we're in a state a keyword is expected.
668  */
669 enum lex_state {
670         L_NORMAL = 0,
671         L_KEYWORD,
672         L_SLITERAL
673 };
674
675 /*
676  * get_string retrieves a string from *p and stores it as a token in
677  * *t.
678  *
679  * get_string used for scanning both string literals and keywords.
680  *
681  * Characters from *p are copied into t-val until a character equal to
682  * delim is found, or a NUL byte is reached. If delim has the special value of
683  * ' ', any whitespace character will be used as a delimiter.
684  *
685  * If lower is unequal to 0, uppercase characters will be converted to
686  * lowercase in the result. This is useful to make keywords case
687  * insensitive.
688  *
689  * The location of *p is updated to point to the first character after the end
690  * of the token - the ending delimiter.
691  *
692  * On success, the new value of t->val is returned. Memory for t->val is
693  * allocated using malloc and must be free()'d to reclaim it.  If insufficient
694  * memory is available, NULL is returned.
695  */
696 static char *get_string(char **p, struct token *t, char delim, int lower)
697 {
698         char *b, *e;
699         size_t len, i;
700
701         /*
702          * b and e both start at the beginning of the input stream.
703          *
704          * e is incremented until we find the ending delimiter, or a NUL byte
705          * is reached. Then, we take e - b to find the length of the token.
706          */
707         b = e = *p;
708
709         while (*e) {
710                 if ((delim == ' ' && isspace(*e)) || delim == *e)
711                         break;
712                 e++;
713         }
714
715         len = e - b;
716
717         /*
718          * Allocate memory to hold the string, and copy it in, converting
719          * characters to lowercase if lower is != 0.
720          */
721         t->val = malloc(len + 1);
722         if (!t->val)
723                 return NULL;
724
725         for (i = 0; i < len; i++, b++) {
726                 if (lower)
727                         t->val[i] = tolower(*b);
728                 else
729                         t->val[i] = *b;
730         }
731
732         t->val[len] = '\0';
733
734         /*
735          * Update *p so the caller knows where to continue scanning.
736          */
737         *p = e;
738
739         t->type = T_STRING;
740
741         return t->val;
742 }
743
744 /*
745  * Populate a keyword token with a type and value.
746  */
747 static void get_keyword(struct token *t)
748 {
749         int i;
750
751         for (i = 0; keywords[i].val; i++) {
752                 if (!strcmp(t->val, keywords[i].val)) {
753                         t->type = keywords[i].type;
754                         break;
755                 }
756         }
757 }
758
759 /*
760  * Get the next token.  We have to keep track of which state we're in to know
761  * if we're looking to get a string literal or a keyword.
762  *
763  * *p is updated to point at the first character after the current token.
764  */
765 static void get_token(char **p, struct token *t, enum lex_state state)
766 {
767         char *c = *p;
768
769         t->type = T_INVALID;
770
771         /* eat non EOL whitespace */
772         while (isblank(*c))
773                 c++;
774
775         /*
776          * eat comments. note that string literals can't begin with #, but
777          * can contain a # after their first character.
778          */
779         if (*c == '#') {
780                 while (*c && *c != '\n')
781                         c++;
782         }
783
784         if (*c == '\n') {
785                 t->type = T_EOL;
786                 c++;
787         } else if (*c == '\0') {
788                 t->type = T_EOF;
789                 c++;
790         } else if (state == L_SLITERAL) {
791                 get_string(&c, t, '\n', 0);
792         } else if (state == L_KEYWORD) {
793                 /*
794                  * when we expect a keyword, we first get the next string
795                  * token delimited by whitespace, and then check if it
796                  * matches a keyword in our keyword list. if it does, it's
797                  * converted to a keyword token of the appropriate type, and
798                  * if not, it remains a string token.
799                  */
800                 get_string(&c, t, ' ', 1);
801                 get_keyword(t);
802         }
803
804         *p = c;
805 }
806
807 /*
808  * Increment *c until we get to the end of the current line, or EOF.
809  */
810 static void eol_or_eof(char **c)
811 {
812         while (**c && **c != '\n')
813                 (*c)++;
814 }
815
816 /*
817  * All of these parse_* functions share some common behavior.
818  *
819  * They finish with *c pointing after the token they parse, and return 1 on
820  * success, or < 0 on error.
821  */
822
823 /*
824  * Parse a string literal and store a pointer it at *dst. String literals
825  * terminate at the end of the line.
826  */
827 static int parse_sliteral(char **c, char **dst)
828 {
829         struct token t;
830         char *s = *c;
831
832         get_token(c, &t, L_SLITERAL);
833
834         if (t.type != T_STRING) {
835                 printf("Expected string literal: %.*s\n", (int)(*c - s), s);
836                 return -EINVAL;
837         }
838
839         *dst = t.val;
840
841         return 1;
842 }
843
844 /*
845  * Parse a base 10 (unsigned) integer and store it at *dst.
846  */
847 static int parse_integer(char **c, int *dst)
848 {
849         struct token t;
850         char *s = *c;
851         unsigned long temp;
852
853         get_token(c, &t, L_SLITERAL);
854
855         if (t.type != T_STRING) {
856                 printf("Expected string: %.*s\n", (int)(*c - s), s);
857                 return -EINVAL;
858         }
859
860         if (strict_strtoul(t.val, 10, &temp) < 0) {
861                 printf("Expected unsigned integer: %s\n", t.val);
862                 return -EINVAL;
863         }
864
865         *dst = (int)temp;
866
867         free(t.val);
868
869         return 1;
870 }
871
872 static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level);
873
874 /*
875  * Parse an include statement, and retrieve and parse the file it mentions.
876  *
877  * base should point to a location where it's safe to store the file, and
878  * nest_level should indicate how many nested includes have occurred. For this
879  * include, nest_level has already been incremented and doesn't need to be
880  * incremented here.
881  */
882 static int handle_include(char **c, char *base,
883                                 struct pxe_menu *cfg, int nest_level)
884 {
885         char *include_path;
886         char *s = *c;
887         int err;
888
889         err = parse_sliteral(c, &include_path);
890
891         if (err < 0) {
892                 printf("Expected include path: %.*s\n",
893                                  (int)(*c - s), s);
894                 return err;
895         }
896
897         err = get_pxe_file(include_path, base);
898
899         if (err < 0) {
900                 printf("Couldn't retrieve %s\n", include_path);
901                 return err;
902         }
903
904         return parse_pxefile_top(base, cfg, nest_level);
905 }
906
907 /*
908  * Parse lines that begin with 'menu'.
909  *
910  * b and nest are provided to handle the 'menu include' case.
911  *
912  * b should be the address where the file currently being parsed is stored.
913  *
914  * nest_level should be 1 when parsing the top level pxe file, 2 when parsing
915  * a file it includes, 3 when parsing a file included by that file, and so on.
916  */
917 static int parse_menu(char **c, struct pxe_menu *cfg, char *b, int nest_level)
918 {
919         struct token t;
920         char *s = *c;
921         int err;
922
923         get_token(c, &t, L_KEYWORD);
924
925         switch (t.type) {
926         case T_TITLE:
927                 err = parse_sliteral(c, &cfg->title);
928
929                 break;
930
931         case T_INCLUDE:
932                 err = handle_include(c, b + strlen(b) + 1, cfg,
933                                                 nest_level + 1);
934                 break;
935
936         default:
937                 printf("Ignoring malformed menu command: %.*s\n",
938                                 (int)(*c - s), s);
939         }
940
941         if (err < 0)
942                 return err;
943
944         eol_or_eof(c);
945
946         return 1;
947 }
948
949 /*
950  * Handles parsing a 'menu line' when we're parsing a label.
951  */
952 static int parse_label_menu(char **c, struct pxe_menu *cfg,
953                                 struct pxe_label *label)
954 {
955         struct token t;
956         char *s;
957
958         s = *c;
959
960         get_token(c, &t, L_KEYWORD);
961
962         switch (t.type) {
963         case T_DEFAULT:
964                 if (cfg->default_label)
965                         free(cfg->default_label);
966
967                 cfg->default_label = strdup(label->name);
968
969                 if (!cfg->default_label)
970                         return -ENOMEM;
971
972                 break;
973         default:
974                 printf("Ignoring malformed menu command: %.*s\n",
975                                 (int)(*c - s), s);
976         }
977
978         eol_or_eof(c);
979
980         return 0;
981 }
982
983 /*
984  * Parses a label and adds it to the list of labels for a menu.
985  *
986  * A label ends when we either get to the end of a file, or
987  * get some input we otherwise don't have a handler defined
988  * for.
989  *
990  */
991 static int parse_label(char **c, struct pxe_menu *cfg)
992 {
993         struct token t;
994         char *s = *c;
995         struct pxe_label *label;
996         int err;
997
998         label = label_create();
999         if (!label)
1000                 return -ENOMEM;
1001
1002         err = parse_sliteral(c, &label->name);
1003         if (err < 0) {
1004                 printf("Expected label name: %.*s\n", (int)(*c - s), s);
1005                 label_destroy(label);
1006                 return -EINVAL;
1007         }
1008
1009         list_add_tail(&label->list, &cfg->labels);
1010
1011         while (1) {
1012                 s = *c;
1013                 get_token(c, &t, L_KEYWORD);
1014
1015                 err = 0;
1016                 switch (t.type) {
1017                 case T_MENU:
1018                         err = parse_label_menu(c, cfg, label);
1019                         break;
1020
1021                 case T_KERNEL:
1022                         err = parse_sliteral(c, &label->kernel);
1023                         break;
1024
1025                 case T_APPEND:
1026                         err = parse_sliteral(c, &label->append);
1027                         break;
1028
1029                 case T_INITRD:
1030                         err = parse_sliteral(c, &label->initrd);
1031                         break;
1032
1033                 case T_LOCALBOOT:
1034                         err = parse_integer(c, &label->localboot);
1035                         break;
1036
1037                 case T_EOL:
1038                         break;
1039
1040                 default:
1041                         /*
1042                          * put the token back! we don't want it - it's the end
1043                          * of a label and whatever token this is, it's
1044                          * something for the menu level context to handle.
1045                          */
1046                         *c = s;
1047                         return 1;
1048                 }
1049
1050                 if (err < 0)
1051                         return err;
1052         }
1053 }
1054
1055 /*
1056  * This 16 comes from the limit pxelinux imposes on nested includes.
1057  *
1058  * There is no reason at all we couldn't do more, but some limit helps prevent
1059  * infinite (until crash occurs) recursion if a file tries to include itself.
1060  */
1061 #define MAX_NEST_LEVEL 16
1062
1063 /*
1064  * Entry point for parsing a menu file. nest_level indicates how many times
1065  * we've nested in includes.  It will be 1 for the top level menu file.
1066  *
1067  * Returns 1 on success, < 0 on error.
1068  */
1069 static int parse_pxefile_top(char *p, struct pxe_menu *cfg, int nest_level)
1070 {
1071         struct token t;
1072         char *s, *b, *label_name;
1073         int err;
1074
1075         b = p;
1076
1077         if (nest_level > MAX_NEST_LEVEL) {
1078                 printf("Maximum nesting (%d) exceeded\n", MAX_NEST_LEVEL);
1079                 return -EMLINK;
1080         }
1081
1082         while (1) {
1083                 s = p;
1084
1085                 get_token(&p, &t, L_KEYWORD);
1086
1087                 err = 0;
1088                 switch (t.type) {
1089                 case T_MENU:
1090                         err = parse_menu(&p, cfg, b, nest_level);
1091                         break;
1092
1093                 case T_TIMEOUT:
1094                         err = parse_integer(&p, &cfg->timeout);
1095                         break;
1096
1097                 case T_LABEL:
1098                         err = parse_label(&p, cfg);
1099                         break;
1100
1101                 case T_DEFAULT:
1102                         err = parse_sliteral(&p, &label_name);
1103
1104                         if (label_name) {
1105                                 if (cfg->default_label)
1106                                         free(cfg->default_label);
1107
1108                                 cfg->default_label = label_name;
1109                         }
1110
1111                         break;
1112
1113                 case T_PROMPT:
1114                         err = parse_integer(&p, &cfg->prompt);
1115                         break;
1116
1117                 case T_EOL:
1118                         break;
1119
1120                 case T_EOF:
1121                         return 1;
1122
1123                 default:
1124                         printf("Ignoring unknown command: %.*s\n",
1125                                                         (int)(p - s), s);
1126                         eol_or_eof(&p);
1127                 }
1128
1129                 if (err < 0)
1130                         return err;
1131         }
1132 }
1133
1134 /*
1135  * Free the memory used by a pxe_menu and its labels.
1136  */
1137 static void destroy_pxe_menu(struct pxe_menu *cfg)
1138 {
1139         struct list_head *pos, *n;
1140         struct pxe_label *label;
1141
1142         if (cfg->title)
1143                 free(cfg->title);
1144
1145         if (cfg->default_label)
1146                 free(cfg->default_label);
1147
1148         list_for_each_safe(pos, n, &cfg->labels) {
1149                 label = list_entry(pos, struct pxe_label, list);
1150
1151                 label_destroy(label);
1152         }
1153
1154         free(cfg);
1155 }
1156
1157 /*
1158  * Entry point for parsing a pxe file. This is only used for the top level
1159  * file.
1160  *
1161  * Returns NULL if there is an error, otherwise, returns a pointer to a
1162  * pxe_menu struct populated with the results of parsing the pxe file (and any
1163  * files it includes). The resulting pxe_menu struct can be free()'d by using
1164  * the destroy_pxe_menu() function.
1165  */
1166 static struct pxe_menu *parse_pxefile(char *menucfg)
1167 {
1168         struct pxe_menu *cfg;
1169
1170         cfg = malloc(sizeof(struct pxe_menu));
1171
1172         if (!cfg)
1173                 return NULL;
1174
1175         memset(cfg, 0, sizeof(struct pxe_menu));
1176
1177         INIT_LIST_HEAD(&cfg->labels);
1178
1179         if (parse_pxefile_top(menucfg, cfg, 1) < 0) {
1180                 destroy_pxe_menu(cfg);
1181                 return NULL;
1182         }
1183
1184         return cfg;
1185 }
1186
1187 /*
1188  * Converts a pxe_menu struct into a menu struct for use with U-boot's generic
1189  * menu code.
1190  */
1191 static struct menu *pxe_menu_to_menu(struct pxe_menu *cfg)
1192 {
1193         struct pxe_label *label;
1194         struct list_head *pos;
1195         struct menu *m;
1196         int err;
1197
1198         /*
1199          * Create a menu and add items for all the labels.
1200          */
1201         m = menu_create(cfg->title, cfg->timeout, cfg->prompt, label_print);
1202
1203         if (!m)
1204                 return NULL;
1205
1206         list_for_each(pos, &cfg->labels) {
1207                 label = list_entry(pos, struct pxe_label, list);
1208
1209                 if (menu_item_add(m, label->name, label) != 1) {
1210                         menu_destroy(m);
1211                         return NULL;
1212                 }
1213         }
1214
1215         /*
1216          * After we've created items for each label in the menu, set the
1217          * menu's default label if one was specified.
1218          */
1219         if (cfg->default_label) {
1220                 err = menu_default_set(m, cfg->default_label);
1221                 if (err != 1) {
1222                         if (err != -ENOENT) {
1223                                 menu_destroy(m);
1224                                 return NULL;
1225                         }
1226
1227                         printf("Missing default: %s\n", cfg->default_label);
1228                 }
1229         }
1230
1231         return m;
1232 }
1233
1234 /*
1235  * Try to boot any labels we have yet to attempt to boot.
1236  */
1237 static void boot_unattempted_labels(struct pxe_menu *cfg)
1238 {
1239         struct list_head *pos;
1240         struct pxe_label *label;
1241
1242         list_for_each(pos, &cfg->labels) {
1243                 label = list_entry(pos, struct pxe_label, list);
1244
1245                 if (!label->attempted)
1246                         label_boot(label);
1247         }
1248 }
1249
1250 /*
1251  * Boot the system as prescribed by a pxe_menu.
1252  *
1253  * Use the menu system to either get the user's choice or the default, based
1254  * on config or user input.  If there is no default or user's choice,
1255  * attempted to boot labels in the order they were given in pxe files.
1256  * If the default or user's choice fails to boot, attempt to boot other
1257  * labels in the order they were given in pxe files.
1258  *
1259  * If this function returns, there weren't any labels that successfully
1260  * booted, or the user interrupted the menu selection via ctrl+c.
1261  */
1262 static void handle_pxe_menu(struct pxe_menu *cfg)
1263 {
1264         void *choice;
1265         struct menu *m;
1266         int err;
1267
1268         m = pxe_menu_to_menu(cfg);
1269         if (!m)
1270                 return;
1271
1272         err = menu_get_choice(m, &choice);
1273
1274         menu_destroy(m);
1275
1276         if (err < 1)
1277                 return;
1278
1279         label_boot(choice);
1280
1281         boot_unattempted_labels(cfg);
1282 }
1283
1284 /*
1285  * Boots a system using a pxe file
1286  *
1287  * Returns 0 on success, 1 on error.
1288  */
1289 static int
1290 do_pxe_boot(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1291 {
1292         unsigned long pxefile_addr_r;
1293         struct pxe_menu *cfg;
1294         char *pxefile_addr_str;
1295
1296         if (argc == 1) {
1297                 pxefile_addr_str = from_env("pxefile_addr_r");
1298                 if (!pxefile_addr_str)
1299                         return 1;
1300
1301         } else if (argc == 2) {
1302                 pxefile_addr_str = argv[1];
1303         } else {
1304                 return cmd_usage(cmdtp);
1305         }
1306
1307         if (strict_strtoul(pxefile_addr_str, 16, &pxefile_addr_r) < 0) {
1308                 printf("Invalid pxefile address: %s\n", pxefile_addr_str);
1309                 return 1;
1310         }
1311
1312         cfg = parse_pxefile((char *)(pxefile_addr_r));
1313
1314         if (cfg == NULL) {
1315                 printf("Error parsing config file\n");
1316                 return 1;
1317         }
1318
1319         handle_pxe_menu(cfg);
1320
1321         destroy_pxe_menu(cfg);
1322
1323         return 0;
1324 }
1325
1326 static cmd_tbl_t cmd_pxe_sub[] = {
1327         U_BOOT_CMD_MKENT(get, 1, 1, do_pxe_get, "", ""),
1328         U_BOOT_CMD_MKENT(boot, 2, 1, do_pxe_boot, "", "")
1329 };
1330
1331 int do_pxe(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1332 {
1333         cmd_tbl_t *cp;
1334
1335         if (argc < 2)
1336                 return cmd_usage(cmdtp);
1337
1338         /* drop initial "pxe" arg */
1339         argc--;
1340         argv++;
1341
1342         cp = find_cmd_tbl(argv[0], cmd_pxe_sub, ARRAY_SIZE(cmd_pxe_sub));
1343
1344         if (cp)
1345                 return cp->cmd(cmdtp, flag, argc, argv);
1346
1347         return cmd_usage(cmdtp);
1348 }
1349
1350 U_BOOT_CMD(
1351         pxe, 3, 1, do_pxe,
1352         "commands to get and boot from pxe files",
1353         "get - try to retrieve a pxe file using tftp\npxe "
1354         "boot [pxefile_addr_r] - boot from the pxe file at pxefile_addr_r\n"
1355 );