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