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