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