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