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