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