]> git.ozlabs.org Git - petitboot/blob - discover/platform-powerpc.c
Support HTTP(S) proxies when downloading resources
[petitboot] / discover / platform-powerpc.c
1
2 #include <assert.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <limits.h>
6 #include <errno.h>
7 #include <sys/types.h>
8 #include <sys/wait.h>
9 #include <sys/fcntl.h>
10 #include <sys/stat.h>
11 #include <asm/byteorder.h>
12
13 #include <file/file.h>
14 #include <talloc/talloc.h>
15 #include <list/list.h>
16 #include <log/log.h>
17 #include <process/process.h>
18 #include <types/types.h>
19
20 #include "hostboot.h"
21 #include "platform.h"
22 #include "ipmi.h"
23 #include "dt.h"
24
25 static const char *partition = "common";
26 static const char *sysparams_dir = "/sys/firmware/opal/sysparams/";
27 static const char *devtree_dir = "/proc/device-tree/";
28 static const int ipmi_timeout = 5000; /* milliseconds. */
29
30 struct param {
31         char                    *name;
32         char                    *value;
33         bool                    modified;
34         struct list_item        list;
35 };
36
37 struct platform_powerpc {
38         struct list     params;
39         struct ipmi     *ipmi;
40         bool            ipmi_bootdev_persistent;
41         int             (*get_ipmi_bootdev)(
42                                 struct platform_powerpc *platform,
43                                 uint8_t *bootdev, bool *persistent);
44         int             (*clear_ipmi_bootdev)(
45                                 struct platform_powerpc *platform,
46                                 bool persistent);
47         int             (*set_os_boot_sensor)(
48                                 struct platform_powerpc *platform);
49         void            (*get_platform_versions)(struct system_info *info);
50 };
51
52 static const char *known_params[] = {
53         "auto-boot?",
54         "petitboot,network",
55         "petitboot,timeout",
56         "petitboot,bootdev",
57         "petitboot,bootdevs",
58         "petitboot,language",
59         "petitboot,debug?",
60         "petitboot,write?",
61         "petitboot,snapshots?",
62         "petitboot,console",
63         "petitboot,http_proxy",
64         "petitboot,https_proxy",
65         NULL,
66 };
67
68 #define to_platform_powerpc(p) \
69         (struct platform_powerpc *)(p->platform_data)
70
71 /* a partition max a max size of 64k * 16bytes = 1M */
72 static const int max_partition_size = 64 * 1024 * 16;
73
74 static bool param_is_known(const char *param, unsigned int len)
75 {
76         const char *known_param;
77         unsigned int i;
78
79         for (i = 0; known_params[i]; i++) {
80                 known_param = known_params[i];
81                 if (len == strlen(known_param) &&
82                                 !strncmp(param, known_param, len))
83                         return true;
84         }
85
86         return false;
87 }
88
89 static int parse_nvram_params(struct platform_powerpc *platform,
90                 char *buf, int len)
91 {
92         char *pos, *name, *value;
93         unsigned int paramlen;
94         int i, count;
95
96         /* discard 2 header lines:
97          * "common" partiton"
98          * ------------------
99          */
100         pos = buf;
101         count = 0;
102
103         for (i = 0; i < len; i++) {
104                 if (pos[i] == '\n')
105                         count++;
106                 if (count == 2)
107                         break;
108         }
109
110         if (i == len) {
111                 fprintf(stderr, "failure parsing nvram output\n");
112                 return -1;
113         }
114
115         for (pos = buf + i; pos < buf + len; pos += paramlen + 1) {
116                 unsigned int namelen;
117                 struct param *param;
118                 char *newline;
119
120                 newline = strchr(pos, '\n');
121                 if (!newline)
122                         break;
123
124                 *newline = '\0';
125
126                 paramlen = strlen(pos);
127
128                 name = pos;
129                 value = strchr(pos, '=');
130                 if (!value)
131                         continue;
132
133                 namelen = value - name;
134                 if (namelen == 0)
135                         continue;
136
137                 if (!param_is_known(name, namelen))
138                         continue;
139
140                 value++;
141
142                 param = talloc(platform, struct param);
143                 param->modified = false;
144                 param->name = talloc_strndup(platform, name, namelen);
145                 param->value = talloc_strdup(platform, value);
146                 list_add(&platform->params, &param->list);
147         }
148
149         return 0;
150 }
151
152 static int parse_nvram(struct platform_powerpc *platform)
153 {
154         struct process *process;
155         const char *argv[5];
156         int rc;
157
158         argv[0] = "nvram";
159         argv[1] = "--print-config";
160         argv[2] = "--partition";
161         argv[3] = partition;
162         argv[4] = NULL;
163
164         process = process_create(platform);
165         process->path = "nvram";
166         process->argv = argv;
167         process->keep_stdout = true;
168
169         rc = process_run_sync(process);
170
171         if (rc || !process_exit_ok(process)) {
172                 fprintf(stderr, "nvram process returned "
173                                 "non-zero exit status\n");
174                 rc = -1;
175         } else {
176                 rc = parse_nvram_params(platform, process->stdout_buf,
177                                             process->stdout_len);
178         }
179
180         process_release(process);
181         return rc;
182 }
183
184 static int write_nvram(struct platform_powerpc *platform)
185 {
186         struct process *process;
187         struct param *param;
188         const char *argv[6];
189         int rc = 0;
190
191         argv[0] = "nvram";
192         argv[1] = "--update-config";
193         argv[2] = NULL;
194         argv[3] = "--partition";
195         argv[4] = partition;
196         argv[5] = NULL;
197
198         process = process_create(platform);
199         process->path = "nvram";
200         process->argv = argv;
201
202         list_for_each_entry(&platform->params, param, list) {
203                 char *paramstr;
204
205                 if (!param->modified)
206                         continue;
207
208                 paramstr = talloc_asprintf(platform, "%s=%s",
209                                 param->name, param->value);
210                 argv[2] = paramstr;
211
212                 rc = process_run_sync(process);
213
214                 talloc_free(paramstr);
215
216                 if (rc || !process_exit_ok(process)) {
217                         rc = -1;
218                         pb_log("nvram update process returned "
219                                         "non-zero exit status\n");
220                         break;
221                 }
222         }
223
224         process_release(process);
225         return rc;
226 }
227
228 static const char *get_param(struct platform_powerpc *platform,
229                 const char *name)
230 {
231         struct param *param;
232
233         list_for_each_entry(&platform->params, param, list)
234                 if (!strcmp(param->name, name))
235                         return param->value;
236         return NULL;
237 }
238
239 static void set_param(struct platform_powerpc *platform, const char *name,
240                 const char *value)
241 {
242         struct param *param;
243
244         list_for_each_entry(&platform->params, param, list) {
245                 if (strcmp(param->name, name))
246                         continue;
247
248                 if (!strcmp(param->value, value))
249                         return;
250
251                 talloc_free(param->value);
252                 param->value = talloc_strdup(param, value);
253                 param->modified = true;
254                 return;
255         }
256
257
258         param = talloc(platform, struct param);
259         param->modified = true;
260         param->name = talloc_strdup(platform, name);
261         param->value = talloc_strdup(platform, value);
262         list_add(&platform->params, &param->list);
263 }
264
265 static int parse_hwaddr(struct interface_config *ifconf, char *str)
266 {
267         int i;
268
269         if (strlen(str) != strlen("00:00:00:00:00:00"))
270                 return -1;
271
272         for (i = 0; i < HWADDR_SIZE; i++) {
273                 char byte[3], *endp;
274                 unsigned long x;
275
276                 byte[0] = str[i * 3 + 0];
277                 byte[1] = str[i * 3 + 1];
278                 byte[2] = '\0';
279
280                 x = strtoul(byte, &endp, 16);
281                 if (endp != byte + 2)
282                         return -1;
283
284                 ifconf->hwaddr[i] = x & 0xff;
285         }
286
287         return 0;
288 }
289
290 static int parse_one_interface_config(struct config *config,
291                 char *confstr)
292 {
293         struct interface_config *ifconf;
294         char *tok, *saveptr;
295
296         ifconf = talloc_zero(config, struct interface_config);
297
298         if (!confstr || !strlen(confstr))
299                 goto out_err;
300
301         /* first token should be the mac address */
302         tok = strtok_r(confstr, ",", &saveptr);
303         if (!tok)
304                 goto out_err;
305
306         if (parse_hwaddr(ifconf, tok))
307                 goto out_err;
308
309         /* second token is the method */
310         tok = strtok_r(NULL, ",", &saveptr);
311         if (!tok || !strlen(tok) || !strcmp(tok, "ignore")) {
312                 ifconf->ignore = true;
313
314         } else if (!strcmp(tok, "dhcp")) {
315                 ifconf->method = CONFIG_METHOD_DHCP;
316
317         } else if (!strcmp(tok, "static")) {
318                 ifconf->method = CONFIG_METHOD_STATIC;
319
320                 /* ip/mask, [optional] gateway, [optional] url */
321                 tok = strtok_r(NULL, ",", &saveptr);
322                 if (!tok)
323                         goto out_err;
324                 ifconf->static_config.address =
325                         talloc_strdup(ifconf, tok);
326
327                 tok = strtok_r(NULL, ",", &saveptr);
328                 if (tok) {
329                         ifconf->static_config.gateway =
330                                 talloc_strdup(ifconf, tok);
331                 }
332
333                 tok = strtok_r(NULL, ",", &saveptr);
334                 if (tok) {
335                         ifconf->static_config.url =
336                                 talloc_strdup(ifconf, tok);
337                 }
338
339         } else {
340                 pb_log("Unknown network configuration method %s\n", tok);
341                 goto out_err;
342         }
343
344         config->network.interfaces = talloc_realloc(config,
345                         config->network.interfaces,
346                         struct interface_config *,
347                         ++config->network.n_interfaces);
348
349         config->network.interfaces[config->network.n_interfaces - 1] = ifconf;
350
351         return 0;
352 out_err:
353         talloc_free(ifconf);
354         return -1;
355 }
356
357 static int parse_one_dns_config(struct config *config,
358                 char *confstr)
359 {
360         char *tok, *saveptr = NULL;
361
362         for (tok = strtok_r(confstr, ",", &saveptr); tok;
363                         tok = strtok_r(NULL, ",", &saveptr)) {
364
365                 char *server = talloc_strdup(config, tok);
366
367                 config->network.dns_servers = talloc_realloc(config,
368                                 config->network.dns_servers, const char *,
369                                 ++config->network.n_dns_servers);
370
371                 config->network.dns_servers[config->network.n_dns_servers - 1]
372                                 = server;
373         }
374
375         return 0;
376 }
377
378 static void populate_network_config(struct platform_powerpc *platform,
379                 struct config *config)
380 {
381         char *val, *saveptr = NULL;
382         const char *cval;
383         int i;
384
385         cval = get_param(platform, "petitboot,network");
386         if (!cval || !strlen(cval))
387                 return;
388
389         val = talloc_strdup(config, cval);
390
391         for (i = 0; ; i++) {
392                 char *tok;
393
394                 tok = strtok_r(i == 0 ? val : NULL, " ", &saveptr);
395                 if (!tok)
396                         break;
397
398                 if (!strncasecmp(tok, "dns,", strlen("dns,")))
399                         parse_one_dns_config(config, tok + strlen("dns,"));
400                 else
401                         parse_one_interface_config(config, tok);
402
403         }
404
405         talloc_free(val);
406 }
407
408 static int read_bootdev(void *ctx, char **pos, struct autoboot_option *opt)
409 {
410         char *delim = strchr(*pos, ' ');
411         int len, prefix = 0, rc = -1;
412         enum device_type type;
413
414         if (!strncmp(*pos, "uuid:", strlen("uuid:"))) {
415                 prefix = strlen("uuid:");
416                 opt->boot_type = BOOT_DEVICE_UUID;
417                 rc = 0;
418         } else if (!strncmp(*pos, "mac:", strlen("mac:"))) {
419                 prefix = strlen("mac:");
420                 opt->boot_type = BOOT_DEVICE_UUID;
421                 rc = 0;
422         } else {
423                 type = find_device_type(*pos);
424                 if (type != DEVICE_TYPE_UNKNOWN) {
425                         opt->type = type;
426                         opt->boot_type = BOOT_DEVICE_TYPE;
427                         rc = 0;
428                 }
429         }
430
431         if (opt->boot_type == BOOT_DEVICE_UUID) {
432                 if (delim)
433                         len = (int)(delim - *pos) - prefix;
434                 else
435                         len = strlen(*pos);
436
437                 opt->uuid = talloc_strndup(ctx, *pos + prefix, len);
438         }
439
440         /* Always advance pointer to next option or end */
441         if (delim)
442                 *pos = delim + 1;
443         else
444                 *pos += strlen(*pos);
445
446         return rc;
447 }
448
449 static void populate_bootdev_config(struct platform_powerpc *platform,
450                 struct config *config)
451 {
452         struct autoboot_option *opt, *new = NULL;
453         char *pos, *end, *old_dev = NULL;
454         unsigned int n_new = 0;
455         const char *val;
456         bool conflict;
457
458         /* Check for old-style bootdev */
459         val = get_param(platform, "petitboot,bootdev");
460         if (val && strlen(val)) {
461                 pos = talloc_strdup(config, val);
462                 if (!strncmp(val, "uuid:", strlen("uuid:")))
463                         old_dev = talloc_strdup(config,
464                                                 val + strlen("uuid:"));
465                 else if (!strncmp(val, "mac:", strlen("mac:")))
466                         old_dev = talloc_strdup(config,
467                                                 val + strlen("mac:"));
468         }
469
470         /* Check for ordered bootdevs */
471         val = get_param(platform, "petitboot,bootdevs");
472         if (!val || !strlen(val)) {
473                 pos = end = NULL;
474         } else {
475                 pos = talloc_strdup(config, val);
476                 end = strchr(pos, '\0');
477         }
478
479         while (pos && pos < end) {
480                 opt = talloc(config, struct autoboot_option);
481
482                 if (read_bootdev(config, &pos, opt)) {
483                         pb_log("bootdev config is in an unknown format "
484                                "(expected uuid:... or mac:...)\n");
485                         talloc_free(opt);
486                         continue;
487                 }
488
489                 new = talloc_realloc(config, new, struct autoboot_option,
490                                      n_new + 1);
491                 new[n_new] = *opt;
492                 n_new++;
493                 talloc_free(opt);
494
495         }
496
497         if (!n_new && !old_dev) {
498                 /* If autoboot has been disabled, clear the default options */
499                 if (!config->autoboot_enabled) {
500                         talloc_free(config->autoboot_opts);
501                         config->n_autoboot_opts = 0;
502                 }
503                 return;
504         }
505
506         conflict = old_dev && (!n_new ||
507                                     new[0].boot_type == BOOT_DEVICE_TYPE ||
508                                     /* Canonical UUIDs are 36 characters long */
509                                     strncmp(new[0].uuid, old_dev, 36));
510
511         if (!conflict) {
512                 talloc_free(config->autoboot_opts);
513                 config->autoboot_opts = new;
514                 config->n_autoboot_opts = n_new;
515                 return;
516         }
517
518         /*
519          * Difference detected, defer to old format in case it has been updated
520          * recently
521          */
522         pb_debug("Old autoboot bootdev detected\n");
523         talloc_free(config->autoboot_opts);
524         config->autoboot_opts = talloc(config, struct autoboot_option);
525         config->autoboot_opts[0].boot_type = BOOT_DEVICE_UUID;
526         config->autoboot_opts[0].uuid = talloc_strdup(config, old_dev);
527         config->n_autoboot_opts = 1;
528 }
529
530 static void set_proxy_variables(struct config *config)
531 {
532         if (config->http_proxy)
533                 setenv("http_proxy", config->http_proxy, 1);
534         else
535                 unsetenv("http_proxy");
536
537         if (config->https_proxy)
538                 setenv("https_proxy", config->https_proxy, 1);
539         else
540                 unsetenv("https_proxy");
541 }
542
543 static void populate_config(struct platform_powerpc *platform,
544                 struct config *config)
545 {
546         const char *val;
547         char *end;
548         unsigned long timeout;
549
550         /* if the "auto-boot?' property is present and "false", disable auto
551          * boot */
552         val = get_param(platform, "auto-boot?");
553         config->autoboot_enabled = !val || strcmp(val, "false");
554
555         val = get_param(platform, "petitboot,timeout");
556         if (val) {
557                 timeout = strtoul(val, &end, 10);
558                 if (end != val) {
559                         if (timeout >= INT_MAX)
560                                 timeout = INT_MAX;
561                         config->autoboot_timeout_sec = (int)timeout;
562                 }
563         }
564
565         val = get_param(platform, "petitboot,language");
566         config->lang = val ? talloc_strdup(config, val) : NULL;
567
568         populate_network_config(platform, config);
569
570         populate_bootdev_config(platform, config);
571
572         if (!config->debug) {
573                 val = get_param(platform, "petitboot,debug?");
574                 config->debug = val && !strcmp(val, "true");
575         }
576
577         val = get_param(platform, "petitboot,write?");
578         if (val)
579                 config->allow_writes = !strcmp(val, "true");
580
581         val = get_param(platform, "petitboot,snapshots?");
582         if (val)
583                 config->disable_snapshots = !strcmp(val, "false");
584
585         val = get_param(platform, "petitboot,console");
586         if (val)
587                 config->boot_console = talloc_strdup(config, val);
588         /* If a full path is already set we don't want to override it */
589         config->manual_console = config->boot_console &&
590                                         !strchr(config->boot_console, '[');
591
592         val = get_param(platform, "petitboot,http_proxy");
593         if (val)
594                 config->http_proxy = talloc_strdup(config, val);
595         val = get_param(platform, "petitboot,https_proxy");
596         if (val)
597                 config->https_proxy = talloc_strdup(config, val);
598         set_proxy_variables(config);
599 }
600
601 static char *iface_config_str(void *ctx, struct interface_config *config)
602 {
603         char *str;
604
605         /* todo: HWADDR size is hardcoded as 6, but we may need to handle
606          * different hardware address formats */
607         str = talloc_asprintf(ctx, "%02x:%02x:%02x:%02x:%02x:%02x,",
608                         config->hwaddr[0], config->hwaddr[1],
609                         config->hwaddr[2], config->hwaddr[3],
610                         config->hwaddr[4], config->hwaddr[5]);
611
612         if (config->ignore) {
613                 str = talloc_asprintf_append(str, "ignore");
614
615         } else if (config->method == CONFIG_METHOD_DHCP) {
616                 str = talloc_asprintf_append(str, "dhcp");
617
618         } else if (config->method == CONFIG_METHOD_STATIC) {
619                 str = talloc_asprintf_append(str, "static,%s%s%s%s%s",
620                                 config->static_config.address,
621                                 config->static_config.gateway ? "," : "",
622                                 config->static_config.gateway ?: "",
623                                 config->static_config.url ? "," : "",
624                                 config->static_config.url ?: "");
625         }
626         return str;
627 }
628
629 static char *dns_config_str(void *ctx, const char **dns_servers, int n)
630 {
631         char *str;
632         int i;
633
634         str = talloc_strdup(ctx, "dns,");
635         for (i = 0; i < n; i++) {
636                 str = talloc_asprintf_append(str, "%s%s",
637                                 i == 0 ? "" : ",",
638                                 dns_servers[i]);
639         }
640
641         return str;
642 }
643
644 static void update_string_config(struct platform_powerpc *platform,
645                 const char *name, const char *value)
646 {
647         const char *cur;
648
649         cur = get_param(platform, name);
650
651         /* don't set an empty parameter if it doesn't already exist */
652         if (!cur && !strlen(value))
653                 return;
654
655         set_param(platform, name, value);
656 }
657
658 static void update_network_config(struct platform_powerpc *platform,
659         struct config *config)
660 {
661         unsigned int i;
662         char *val;
663
664         /*
665          * Don't store IPMI overrides to NVRAM. If this was a persistent
666          * override it was already stored in NVRAM by
667          * get_ipmi_network_override()
668          */
669         if (config->network.n_interfaces &&
670                 config->network.interfaces[0]->override)
671                 return;
672
673         val = talloc_strdup(platform, "");
674
675         for (i = 0; i < config->network.n_interfaces; i++) {
676                 char *iface_str = iface_config_str(platform,
677                                         config->network.interfaces[i]);
678                 val = talloc_asprintf_append(val, "%s%s",
679                                 *val == '\0' ? "" : " ", iface_str);
680                 talloc_free(iface_str);
681         }
682
683         if (config->network.n_dns_servers) {
684                 char *dns_str = dns_config_str(platform,
685                                                 config->network.dns_servers,
686                                                 config->network.n_dns_servers);
687                 val = talloc_asprintf_append(val, "%s%s",
688                                 *val == '\0' ? "" : " ", dns_str);
689                 talloc_free(dns_str);
690         }
691
692         update_string_config(platform, "petitboot,network", val);
693
694         talloc_free(val);
695 }
696
697 static void update_bootdev_config(struct platform_powerpc *platform,
698                 struct config *config)
699 {
700         char *val = NULL, *boot_str = NULL, *tmp = NULL, *first = NULL;
701         struct autoboot_option *opt;
702         const char delim = ' ';
703         unsigned int i;
704
705         if (!config->n_autoboot_opts)
706                 first = val = "";
707         else if (config->autoboot_opts[0].boot_type == BOOT_DEVICE_UUID)
708                 first = talloc_asprintf(config, "uuid:%s",
709                                         config->autoboot_opts[0].uuid);
710         else
711                 first = "";
712
713         for (i = 0; i < config->n_autoboot_opts; i++) {
714                 opt = &config->autoboot_opts[i];
715                 switch (opt->boot_type) {
716                         case BOOT_DEVICE_TYPE:
717                                 boot_str = talloc_asprintf(config, "%s%c",
718                                                 device_type_name(opt->type),
719                                                 delim);
720                                 break;
721                         case BOOT_DEVICE_UUID:
722                                 boot_str = talloc_asprintf(config, "uuid:%s%c",
723                                                 opt->uuid, delim);
724                                 break;
725                         }
726                         tmp = val = talloc_asprintf_append(val, "%s", boot_str);
727         }
728
729         update_string_config(platform, "petitboot,bootdevs", val);
730         update_string_config(platform, "petitboot,bootdev", first);
731         talloc_free(tmp);
732         if (boot_str)
733                 talloc_free(boot_str);
734 }
735
736 static int update_config(struct platform_powerpc *platform,
737                 struct config *config, struct config *defaults)
738 {
739         char *tmp = NULL;
740         const char *val;
741
742         if (config->autoboot_enabled == defaults->autoboot_enabled)
743                 val = "";
744         else
745                 val = config->autoboot_enabled ? "true" : "false";
746         update_string_config(platform, "auto-boot?", val);
747
748         if (config->autoboot_timeout_sec == defaults->autoboot_timeout_sec)
749                 val = "";
750         else
751                 val = tmp = talloc_asprintf(platform, "%d",
752                                 config->autoboot_timeout_sec);
753
754         if (config->ipmi_bootdev == IPMI_BOOTDEV_INVALID &&
755             platform->clear_ipmi_bootdev) {
756                 platform->clear_ipmi_bootdev(platform,
757                                 config->ipmi_bootdev_persistent);
758                 config->ipmi_bootdev = IPMI_BOOTDEV_NONE;
759                 config->ipmi_bootdev_persistent = false;
760         }
761
762         update_string_config(platform, "petitboot,timeout", val);
763         if (tmp)
764                 talloc_free(tmp);
765
766         val = config->lang ?: "";
767         update_string_config(platform, "petitboot,language", val);
768
769         if (config->allow_writes == defaults->allow_writes)
770                 val = "";
771         else
772                 val = config->allow_writes ? "true" : "false";
773         update_string_config(platform, "petitboot,write?", val);
774
775         if (!config->manual_console) {
776                 val = config->boot_console ?: "";
777                 update_string_config(platform, "petitboot,console", val);
778         }
779
780         val = config->http_proxy ?: "";
781         update_string_config(platform, "petitboot,http_proxy", val);
782         val = config->https_proxy ?: "";
783         update_string_config(platform, "petitboot,https_proxy", val);
784         set_proxy_variables(config);
785
786         update_network_config(platform, config);
787
788         update_bootdev_config(platform, config);
789
790         return write_nvram(platform);
791 }
792
793 static void set_ipmi_bootdev(struct config *config, enum ipmi_bootdev bootdev,
794                 bool persistent)
795 {
796         config->ipmi_bootdev = bootdev;
797         config->ipmi_bootdev_persistent = persistent;
798
799         switch (bootdev) {
800         case IPMI_BOOTDEV_NONE:
801         case IPMI_BOOTDEV_DISK:
802         case IPMI_BOOTDEV_NETWORK:
803         case IPMI_BOOTDEV_CDROM:
804         default:
805                 break;
806         case IPMI_BOOTDEV_SETUP:
807                 config->autoboot_enabled = false;
808                 break;
809         case IPMI_BOOTDEV_SAFE:
810                 config->autoboot_enabled = false;
811                 config->safe_mode = true;
812                 break;
813         }
814 }
815
816 static int read_bootdev_sysparam(const char *name, uint8_t *val)
817 {
818         uint8_t buf[2];
819         char path[50];
820         int fd, rc;
821
822         assert(strlen(sysparams_dir) + strlen(name) < sizeof(path));
823         snprintf(path, sizeof(path), "%s%s", sysparams_dir, name);
824
825         fd = open(path, O_RDONLY);
826         if (fd < 0) {
827                 pb_debug("powerpc: can't access sysparam %s\n",
828                                 name);
829                 return -1;
830         }
831
832         rc = read(fd, buf, sizeof(buf));
833
834         close(fd);
835
836         /* bootdev definitions should only be one byte in size */
837         if (rc != 1) {
838                 pb_debug("powerpc: sysparam %s read returned %d\n",
839                                 name, rc);
840                 return -1;
841         }
842
843         pb_debug("powerpc: sysparam %s: 0x%02x\n", name, buf[0]);
844
845         if (!ipmi_bootdev_is_valid(buf[0]))
846                 return -1;
847
848         *val = buf[0];
849         return 0;
850 }
851
852 static int write_bootdev_sysparam(const char *name, uint8_t val)
853 {
854         char path[50];
855         int fd, rc;
856
857         assert(strlen(sysparams_dir) + strlen(name) < sizeof(path));
858         snprintf(path, sizeof(path), "%s%s", sysparams_dir, name);
859
860         fd = open(path, O_WRONLY);
861         if (fd < 0) {
862                 pb_debug("powerpc: can't access sysparam %s for writing\n",
863                                 name);
864                 return -1;
865         }
866
867         for (;;) {
868                 errno = 0;
869                 rc = write(fd, &val, sizeof(val));
870                 if (rc == sizeof(val)) {
871                         rc = 0;
872                         break;
873                 }
874
875                 if (rc <= 0 && errno != EINTR) {
876                         pb_log("powerpc: error updating sysparam %s: %s",
877                                         name, strerror(errno));
878                         rc = -1;
879                         break;
880                 }
881         }
882
883         close(fd);
884
885         if (!rc)
886                 pb_debug("powerpc: set sysparam %s: 0x%02x\n", name, val);
887
888         return rc;
889 }
890
891 static int clear_ipmi_bootdev_sysparams(
892                 struct platform_powerpc *platform __attribute__((unused)),
893                 bool persistent)
894 {
895         if (persistent) {
896                 /* invalidate default-boot-device setting */
897                 write_bootdev_sysparam("default-boot-device", 0xff);
898         } else {
899                 /* invalidate next-boot-device setting */
900                 write_bootdev_sysparam("next-boot-device", 0xff);
901         }
902         return 0;
903 }
904
905 static int get_ipmi_bootdev_sysparams(
906                 struct platform_powerpc *platform __attribute__((unused)),
907                 uint8_t *bootdev, bool *persistent)
908 {
909         uint8_t next_bootdev, default_bootdev;
910         bool next_valid, default_valid;
911         int rc;
912
913         rc = read_bootdev_sysparam("next-boot-device", &next_bootdev);
914         next_valid = rc == 0;
915
916         rc = read_bootdev_sysparam("default-boot-device", &default_bootdev);
917         default_valid = rc == 0;
918
919         /* nothing valid? no need to change the config */
920         if (!next_valid && !default_valid)
921                 return -1;
922
923         *persistent = !next_valid;
924         *bootdev = next_valid ? next_bootdev : default_bootdev;
925         return 0;
926 }
927
928 static int clear_ipmi_bootdev_ipmi(struct platform_powerpc *platform,
929                                    bool persistent __attribute__((unused)))
930 {
931         uint16_t resp_len;
932         uint8_t resp[1];
933         uint8_t req[] = {
934                 0x05, /* parameter selector: boot flags */
935                 0x80, /* data 1: valid */
936                 0x00, /* data 2: bootdev: no override */
937                 0x00, /* data 3: system defaults */
938                 0x00, /* data 4: no request for shared mode, mux defaults */
939                 0x00, /* data 5: no instance request */
940         };
941
942         resp_len = sizeof(resp);
943
944         ipmi_transaction(platform->ipmi, IPMI_NETFN_CHASSIS,
945                         IPMI_CMD_CHASSIS_SET_SYSTEM_BOOT_OPTIONS,
946                         req, sizeof(req),
947                         resp, &resp_len,
948                         ipmi_timeout);
949         return 0;
950 }
951
952 static int get_ipmi_bootdev_ipmi(struct platform_powerpc *platform,
953                 uint8_t *bootdev, bool *persistent)
954 {
955         uint16_t resp_len;
956         uint8_t resp[8];
957         int rc;
958         uint8_t req[] = {
959                 0x05, /* parameter selector: boot flags */
960                 0x00, /* no set selector */
961                 0x00, /* no block selector */
962         };
963
964         resp_len = sizeof(resp);
965         rc = ipmi_transaction(platform->ipmi, IPMI_NETFN_CHASSIS,
966                         IPMI_CMD_CHASSIS_GET_SYSTEM_BOOT_OPTIONS,
967                         req, sizeof(req),
968                         resp, &resp_len,
969                         ipmi_timeout);
970         if (rc) {
971                 pb_log("platform: error reading IPMI boot options\n");
972                 return -1;
973         }
974
975         if (resp_len != sizeof(resp)) {
976                 pb_log("platform: unexpected length (%d) in "
977                                 "boot options response\n", resp_len);
978                 return -1;
979         }
980
981         pb_debug("IPMI get_bootdev response:\n");
982         for (int i = 0; i < resp_len; i++)
983                 pb_debug("%x ", resp[i]);
984         pb_debug("\n");
985
986         if (resp[0] != 0) {
987                 pb_log("platform: non-zero completion code %d from IPMI req\n",
988                                 resp[0]);
989                 return -1;
990         }
991
992         /* check for correct parameter version */
993         if ((resp[1] & 0xf) != 0x1) {
994                 pb_log("platform: unexpected version (0x%x) in "
995                                 "boot options response\n", resp[0]);
996                 return -1;
997         }
998
999         /* check for valid paramters */
1000         if (resp[2] & 0x80) {
1001                 pb_debug("platform: boot options are invalid/locked\n");
1002                 return -1;
1003         }
1004
1005         *persistent = false;
1006
1007         /* check for valid flags */
1008         if (!(resp[3] & 0x80)) {
1009                 pb_debug("platform: boot flags are invalid, ignoring\n");
1010                 return -1;
1011         }
1012
1013         *persistent = resp[3] & 0x40;
1014         *bootdev = (resp[4] >> 2) & 0x0f;
1015         return 0;
1016 }
1017
1018 static int set_ipmi_os_boot_sensor(struct platform_powerpc *platform)
1019 {
1020         int sensor_number;
1021         uint16_t resp_len;
1022         uint8_t resp[1];
1023         uint8_t req[] = {
1024                 0x00, /* sensor number: os boot */
1025                 0xA9, /* operation: set everything */
1026                 0x00, /* sensor reading: none */
1027                 0x40, /* assertion mask lsb: set state 6 */
1028                 0x00, /* assertion mask msb: none */
1029                 0x00, /* deassertion mask lsb: none */
1030                 0x00, /* deassertion mask msb: none */
1031                 0x00, /* event data 1: none */
1032                 0x00, /* event data 2: none */
1033                 0x00, /* event data 3: none */
1034         };
1035
1036         sensor_number = get_ipmi_sensor(platform, IPMI_SENSOR_ID_OS_BOOT);
1037         if (sensor_number < 0) {
1038                 pb_log("Couldn't find OS boot sensor in device tree\n");
1039                 return -1;
1040         }
1041
1042         req[0] = sensor_number;
1043
1044         resp_len = sizeof(resp);
1045
1046         ipmi_transaction(platform->ipmi, IPMI_NETFN_SE,
1047                         IPMI_CMD_SENSOR_SET,
1048                         req, sizeof(req),
1049                         resp, &resp_len,
1050                         ipmi_timeout); return 0;
1051
1052         return 0;
1053 }
1054
1055 static void get_ipmi_bmc_mac(struct platform *p, uint8_t *buf)
1056 {
1057         struct platform_powerpc *platform = p->platform_data;
1058         uint16_t resp_len = 8;
1059         uint8_t resp[8];
1060         uint8_t req[] = { 0x1, 0x5, 0x0, 0x0 };
1061         int i, rc;
1062
1063         rc = ipmi_transaction(platform->ipmi, IPMI_NETFN_TRANSPORT,
1064                         IPMI_CMD_TRANSPORT_GET_LAN_PARAMS,
1065                         req, sizeof(req),
1066                         resp, &resp_len,
1067                         ipmi_timeout);
1068
1069         pb_debug("BMC MAC resp [%d][%d]:\n", rc, resp_len);
1070
1071         if (rc == 0 && resp_len > 0) {
1072                 for (i = 2; i < resp_len; i++) {
1073                         pb_debug(" %x", resp[i]);
1074                         buf[i - 2] = resp[i];
1075                 }
1076                 pb_debug("\n");
1077         }
1078
1079 }
1080
1081 /*
1082  * Retrieve info from the "Get Device ID" IPMI commands.
1083  * See Chapter 20.1 in the IPMIv2 specification.
1084  */
1085 static void get_ipmi_bmc_versions(struct platform *p, struct system_info *info)
1086 {
1087         struct platform_powerpc *platform = p->platform_data;
1088         uint16_t resp_len = 16;
1089         uint8_t resp[16], bcd;
1090         uint32_t aux_version;
1091         int i, rc;
1092
1093         /* Retrieve info from current side */
1094         rc = ipmi_transaction(platform->ipmi, IPMI_NETFN_APP,
1095                         IPMI_CMD_APP_GET_DEVICE_ID,
1096                         NULL, 0,
1097                         resp, &resp_len,
1098                         ipmi_timeout);
1099
1100         pb_debug("BMC version resp [%d][%d]:\n", rc, resp_len);
1101         if (resp_len > 0) {
1102                 for (i = 0; i < resp_len; i++) {
1103                         pb_debug(" %x", resp[i]);
1104                 }
1105                 pb_debug("\n");
1106         }
1107
1108         if (rc == 0 && resp_len == 16) {
1109                 info->bmc_current = talloc_array(info, char *, 4);
1110                 info->n_bmc_current = 4;
1111
1112                 info->bmc_current[0] = talloc_asprintf(info, "Device ID: 0x%x",
1113                                                 resp[1]);
1114                 info->bmc_current[1] = talloc_asprintf(info, "Device Rev: 0x%x",
1115                                                 resp[2]);
1116                 bcd = resp[4] & 0x0f;
1117                 bcd += 10 * (resp[4] >> 4);
1118                 memcpy(&aux_version, &resp[12], sizeof(aux_version));
1119                 info->bmc_current[2] = talloc_asprintf(info,
1120                                                 "Firmware version: %u.%02u.%05u",
1121                                                 resp[3], bcd, aux_version);
1122                 bcd = resp[5] & 0x0f;
1123                 bcd += 10 * (resp[5] >> 4);
1124                 info->bmc_current[3] = talloc_asprintf(info, "IPMI version: %u",
1125                                                 bcd);
1126         } else
1127                 pb_log("Failed to retrieve Device ID from IPMI\n");
1128
1129         /* Retrieve info from golden side */
1130         memset(resp, 0, sizeof(resp));
1131         resp_len = 16;
1132         rc = ipmi_transaction(platform->ipmi, IPMI_NETFN_AMI,
1133                         IPMI_CMD_APP_GET_DEVICE_ID_GOLDEN,
1134                         NULL, 0,
1135                         resp, &resp_len,
1136                         ipmi_timeout);
1137
1138         pb_debug("BMC golden resp [%d][%d]:\n", rc, resp_len);
1139         if (resp_len > 0) {
1140                 for (i = 0; i < resp_len; i++) {
1141                         pb_debug(" %x", resp[i]);
1142                 }
1143                 pb_debug("\n");
1144         }
1145
1146         if (rc == 0 && resp_len == 16) {
1147                 info->bmc_golden = talloc_array(info, char *, 4);
1148                 info->n_bmc_golden = 4;
1149
1150                 info->bmc_golden[0] = talloc_asprintf(info, "Device ID: 0x%x",
1151                                                 resp[1]);
1152                 info->bmc_golden[1] = talloc_asprintf(info, "Device Rev: 0x%x",
1153                                                 resp[2]);
1154                 bcd = resp[4] & 0x0f;
1155                 bcd += 10 * (resp[4] >> 4);
1156                 memcpy(&aux_version, &resp[12], sizeof(aux_version));
1157                 info->bmc_golden[2] = talloc_asprintf(info,
1158                                                 "Firmware version: %u.%02u.%u",
1159                                                 resp[3], bcd, aux_version);
1160                 bcd = resp[5] & 0x0f;
1161                 bcd += 10 * (resp[5] >> 4);
1162                 info->bmc_golden[3] = talloc_asprintf(info, "IPMI version: %u",
1163                                                 bcd);
1164         } else
1165                 pb_log("Failed to retrieve Golden Device ID from IPMI\n");
1166 }
1167
1168 static void get_ipmi_network_override(struct platform_powerpc *platform,
1169                         struct config *config)
1170 {
1171         uint16_t min_len = 12, resp_len = 53, version;
1172         const uint32_t magic_value = 0x21706221;
1173         uint8_t resp[resp_len];
1174         uint32_t cookie;
1175         bool persistent;
1176         int i, rc;
1177         uint8_t req[] = {
1178                 0x61, /* parameter selector: OEM section (network) */
1179                 0x00, /* no set selector */
1180                 0x00, /* no block selector */
1181         };
1182
1183         rc = ipmi_transaction(platform->ipmi, IPMI_NETFN_CHASSIS,
1184                         IPMI_CMD_CHASSIS_GET_SYSTEM_BOOT_OPTIONS,
1185                         req, sizeof(req),
1186                         resp, &resp_len,
1187                         ipmi_timeout);
1188
1189         pb_debug("IPMI net override resp [%d][%d]:\n", rc, resp_len);
1190         if (resp_len > 0) {
1191                 for (i = 0; i < resp_len; i++) {
1192                         pb_debug(" %02x", resp[i]);
1193                         if (i && (i + 1) % 16 == 0 && i != resp_len - 1)
1194                                 pb_debug("\n");
1195                         else if (i && (i + 1) % 8 == 0)
1196                                 pb_debug(" ");
1197                 }
1198                 pb_debug("\n");
1199         }
1200
1201         if (rc) {
1202                 pb_debug("IPMI network config option unavailable\n");
1203                 return;
1204         }
1205
1206         if (resp_len < min_len) {
1207                 pb_debug("IPMI net response too small\n");
1208                 return;
1209         }
1210
1211         if (resp[0] != 0) {
1212                 pb_log("platform: non-zero completion code %d from IPMI network req\n",
1213                        resp[0]);
1214                 return;
1215         }
1216
1217         /* Check for correct parameter version */
1218         if ((resp[1] & 0xf) != 0x1) {
1219                 pb_log("platform: unexpected version (0x%x) in network override response\n",
1220                        resp[0]);
1221                 return;
1222         }
1223
1224         /* Check that the parameters are valid */
1225         if (resp[2] & 0x80) {
1226                 pb_debug("platform: network override is invalid/locked\n");
1227                 return;
1228         }
1229
1230         /* Check for valid parameters in the boot flags section */
1231         if (!(resp[3] & 0x80)) {
1232                 pb_debug("platform: network override valid flag not set\n");
1233                 return;
1234         }
1235         /* Read the persistent flag; if it is set we need to save this config */
1236         persistent = resp[3] & 0x40;
1237         if (persistent)
1238                 pb_debug("platform: network override is persistent\n");
1239
1240         /* Check 4-byte cookie value */
1241         i = 4;
1242         memcpy(&cookie, &resp[i], sizeof(cookie));
1243         cookie = __be32_to_cpu(cookie);
1244         if (cookie != magic_value) {
1245                 pb_log("%s: Incorrect cookie %x\n", __func__, cookie);
1246                 return;
1247         }
1248         i += sizeof(cookie);
1249
1250         /* Check 2-byte version number */
1251         memcpy(&version, &resp[i], sizeof(version));
1252         version = __be16_to_cpu(version);
1253         i += sizeof(version);
1254         if (version != 1) {
1255                 pb_debug("Unexpected version: %u\n", version);
1256                 return;
1257         }
1258
1259         /* Interpret the rest of the interface config */
1260         rc = parse_ipmi_interface_override(config, &resp[i], resp_len - i);
1261
1262         if (!rc && persistent) {
1263                 /* Write this new config to NVRAM */
1264                 update_network_config(platform, config);
1265                 rc = write_nvram(platform);
1266                 if (rc)
1267                         pb_log("platform: Failed to save persistent interface override\n");
1268         }
1269 }
1270
1271 static void get_active_consoles(struct config *config)
1272 {
1273         struct stat sbuf;
1274         char *fsp_prop = NULL;
1275
1276         config->n_consoles = 2;
1277         config->consoles = talloc_array(config, char *, config->n_consoles);
1278         if (!config->consoles)
1279                 goto err;
1280
1281         config->consoles[0] = talloc_asprintf(config->consoles,
1282                                         "/dev/hvc0 [IPMI / Serial]");
1283         config->consoles[1] = talloc_asprintf(config->consoles,
1284                                         "/dev/tty1 [VGA]");
1285
1286         fsp_prop = talloc_asprintf(config, "%sfsps", devtree_dir);
1287         if (stat(fsp_prop, &sbuf) == 0) {
1288                 /* FSP based machines also have a separate serial console */
1289                 config->consoles = talloc_realloc(config, config->consoles,
1290                                                 char *, config->n_consoles + 1);
1291                 if (!config->consoles)
1292                         goto err;
1293                 config->consoles[config->n_consoles++] = talloc_asprintf(
1294                                                 config->consoles,
1295                                                 "/dev/hvc1 [Serial]");
1296         }
1297
1298         return;
1299 err:
1300         config->n_consoles = 0;
1301         pb_log("Failed to allocate memory for consoles\n");
1302 }
1303
1304 static int load_config(struct platform *p, struct config *config)
1305 {
1306         struct platform_powerpc *platform = to_platform_powerpc(p);
1307         int rc;
1308
1309         rc = parse_nvram(platform);
1310         if (rc)
1311                 return rc;
1312
1313         populate_config(platform, config);
1314
1315         if (platform->get_ipmi_bootdev) {
1316                 bool bootdev_persistent;
1317                 uint8_t bootdev = IPMI_BOOTDEV_INVALID;
1318                 rc = platform->get_ipmi_bootdev(platform, &bootdev,
1319                                 &bootdev_persistent);
1320                 if (!rc && ipmi_bootdev_is_valid(bootdev)) {
1321                         set_ipmi_bootdev(config, bootdev, bootdev_persistent);
1322                 }
1323         }
1324
1325         if (platform->ipmi)
1326                 get_ipmi_network_override(platform, config);
1327
1328         get_active_consoles(config);
1329
1330         return 0;
1331 }
1332
1333 static int save_config(struct platform *p, struct config *config)
1334 {
1335         struct platform_powerpc *platform = to_platform_powerpc(p);
1336         struct config *defaults;
1337         int rc;
1338
1339         defaults = talloc_zero(platform, struct config);
1340         config_set_defaults(defaults);
1341
1342         rc = update_config(platform, config, defaults);
1343
1344         talloc_free(defaults);
1345         return rc;
1346 }
1347
1348 static void pre_boot(struct platform *p, const struct config *config)
1349 {
1350         struct platform_powerpc *platform = to_platform_powerpc(p);
1351
1352         if (!config->ipmi_bootdev_persistent && platform->clear_ipmi_bootdev)
1353                 platform->clear_ipmi_bootdev(platform, false);
1354
1355         if (platform->set_os_boot_sensor)
1356                 platform->set_os_boot_sensor(platform);
1357 }
1358
1359 static int get_sysinfo(struct platform *p, struct system_info *sysinfo)
1360 {
1361         struct platform_powerpc *platform = p->platform_data;
1362         char *buf, *filename;
1363         int len, rc;
1364
1365         filename = talloc_asprintf(platform, "%smodel", devtree_dir);
1366         rc = read_file(platform, filename, &buf, &len);
1367         if (rc == 0)
1368                 sysinfo->type = talloc_steal(sysinfo, buf);
1369         talloc_free(filename);
1370
1371         filename = talloc_asprintf(platform, "%ssystem-id", devtree_dir);
1372         rc = read_file(platform, filename, &buf, &len);
1373         if (rc == 0)
1374                 sysinfo->identifier = talloc_steal(sysinfo, buf);
1375         talloc_free(filename);
1376
1377         sysinfo->bmc_mac = talloc_zero_size(sysinfo, HWADDR_SIZE);
1378         if (platform->ipmi)
1379                 get_ipmi_bmc_mac(p, sysinfo->bmc_mac);
1380
1381         if (platform->ipmi)
1382                 get_ipmi_bmc_versions(p, sysinfo);
1383
1384         if (platform->get_platform_versions)
1385                 platform->get_platform_versions(sysinfo);
1386
1387         return 0;
1388 }
1389
1390 static bool probe(struct platform *p, void *ctx)
1391 {
1392         struct platform_powerpc *platform;
1393         struct stat statbuf;
1394         bool bmc_present;
1395         int rc;
1396
1397         /* we need a device tree */
1398         rc = stat("/proc/device-tree", &statbuf);
1399         if (rc)
1400                 return false;
1401
1402         if (!S_ISDIR(statbuf.st_mode))
1403                 return false;
1404
1405         platform = talloc_zero(ctx, struct platform_powerpc);
1406         list_init(&platform->params);
1407
1408         p->platform_data = platform;
1409
1410         bmc_present = stat("/proc/device-tree/bmc", &statbuf) == 0;
1411
1412         if (ipmi_present() && bmc_present) {
1413                 pb_debug("platform: using direct IPMI for IPMI paramters\n");
1414                 platform->ipmi = ipmi_open(platform);
1415                 platform->get_ipmi_bootdev = get_ipmi_bootdev_ipmi;
1416                 platform->clear_ipmi_bootdev = clear_ipmi_bootdev_ipmi;
1417                 platform->set_os_boot_sensor = set_ipmi_os_boot_sensor;
1418         } else if (!stat(sysparams_dir, &statbuf)) {
1419                 pb_debug("platform: using sysparams for IPMI paramters\n");
1420                 platform->get_ipmi_bootdev = get_ipmi_bootdev_sysparams;
1421                 platform->clear_ipmi_bootdev = clear_ipmi_bootdev_sysparams;
1422
1423         } else {
1424                 pb_log("platform: no IPMI parameter support\n");
1425         }
1426
1427         if (bmc_present)
1428                 platform->get_platform_versions = hostboot_load_versions;
1429
1430         return true;
1431 }
1432
1433
1434 static struct platform platform_powerpc = {
1435         .name                   = "powerpc",
1436         .dhcp_arch_id           = 0x000e,
1437         .probe                  = probe,
1438         .load_config            = load_config,
1439         .save_config            = save_config,
1440         .pre_boot               = pre_boot,
1441         .get_sysinfo            = get_sysinfo,
1442 };
1443
1444 register_platform(platform_powerpc);