1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * PowerNV OPAL high level interfaces
4  *
5  * Copyright 2011 IBM Corp.
6  */
7 
8 #define pr_fmt(fmt)	"opal: " fmt
9 
10 #include <linux/printk.h>
11 #include <linux/types.h>
12 #include <linux/of.h>
13 #include <linux/of_fdt.h>
14 #include <linux/of_platform.h>
15 #include <linux/of_address.h>
16 #include <linux/interrupt.h>
17 #include <linux/notifier.h>
18 #include <linux/slab.h>
19 #include <linux/sched.h>
20 #include <linux/kobject.h>
21 #include <linux/delay.h>
22 #include <linux/memblock.h>
23 #include <linux/kthread.h>
24 #include <linux/freezer.h>
25 #include <linux/kmsg_dump.h>
26 #include <linux/console.h>
27 #include <linux/sched/debug.h>
28 
29 #include <asm/machdep.h>
30 #include <asm/opal.h>
31 #include <asm/firmware.h>
32 #include <asm/mce.h>
33 #include <asm/imc-pmu.h>
34 #include <asm/bug.h>
35 
36 #include "powernv.h"
37 
38 /* /sys/firmware/opal */
39 struct kobject *opal_kobj;
40 
41 struct opal {
42 	u64 base;
43 	u64 entry;
44 	u64 size;
45 } opal;
46 
47 struct mcheck_recoverable_range {
48 	u64 start_addr;
49 	u64 end_addr;
50 	u64 recover_addr;
51 };
52 
53 static struct mcheck_recoverable_range *mc_recoverable_range;
54 static int mc_recoverable_range_len;
55 
56 struct device_node *opal_node;
57 static DEFINE_SPINLOCK(opal_write_lock);
58 static struct atomic_notifier_head opal_msg_notifier_head[OPAL_MSG_TYPE_MAX];
59 static uint32_t opal_heartbeat;
60 static struct task_struct *kopald_tsk;
61 
62 void opal_configure_cores(void)
63 {
64 	u64 reinit_flags = 0;
65 
66 	/* Do the actual re-init, This will clobber all FPRs, VRs, etc...
67 	 *
68 	 * It will preserve non volatile GPRs and HSPRG0/1. It will
69 	 * also restore HIDs and other SPRs to their original value
70 	 * but it might clobber a bunch.
71 	 */
72 #ifdef __BIG_ENDIAN__
73 	reinit_flags |= OPAL_REINIT_CPUS_HILE_BE;
74 #else
75 	reinit_flags |= OPAL_REINIT_CPUS_HILE_LE;
76 #endif
77 
78 	/*
79 	 * POWER9 always support running hash:
80 	 *  ie. Host hash  supports  hash guests
81 	 *      Host radix supports  hash/radix guests
82 	 */
83 	if (early_cpu_has_feature(CPU_FTR_ARCH_300)) {
84 		reinit_flags |= OPAL_REINIT_CPUS_MMU_HASH;
85 		if (early_radix_enabled())
86 			reinit_flags |= OPAL_REINIT_CPUS_MMU_RADIX;
87 	}
88 
89 	opal_reinit_cpus(reinit_flags);
90 
91 	/* Restore some bits */
92 	if (cur_cpu_spec->cpu_restore)
93 		cur_cpu_spec->cpu_restore();
94 }
95 
96 int __init early_init_dt_scan_opal(unsigned long node,
97 				   const char *uname, int depth, void *data)
98 {
99 	const void *basep, *entryp, *sizep;
100 	int basesz, entrysz, runtimesz;
101 
102 	if (depth != 1 || strcmp(uname, "ibm,opal") != 0)
103 		return 0;
104 
105 	basep  = of_get_flat_dt_prop(node, "opal-base-address", &basesz);
106 	entryp = of_get_flat_dt_prop(node, "opal-entry-address", &entrysz);
107 	sizep = of_get_flat_dt_prop(node, "opal-runtime-size", &runtimesz);
108 
109 	if (!basep || !entryp || !sizep)
110 		return 1;
111 
112 	opal.base = of_read_number(basep, basesz/4);
113 	opal.entry = of_read_number(entryp, entrysz/4);
114 	opal.size = of_read_number(sizep, runtimesz/4);
115 
116 	pr_debug("OPAL Base  = 0x%llx (basep=%p basesz=%d)\n",
117 		 opal.base, basep, basesz);
118 	pr_debug("OPAL Entry = 0x%llx (entryp=%p basesz=%d)\n",
119 		 opal.entry, entryp, entrysz);
120 	pr_debug("OPAL Entry = 0x%llx (sizep=%p runtimesz=%d)\n",
121 		 opal.size, sizep, runtimesz);
122 
123 	if (of_flat_dt_is_compatible(node, "ibm,opal-v3")) {
124 		powerpc_firmware_features |= FW_FEATURE_OPAL;
125 		pr_debug("OPAL detected !\n");
126 	} else {
127 		panic("OPAL != V3 detected, no longer supported.\n");
128 	}
129 
130 	return 1;
131 }
132 
133 int __init early_init_dt_scan_recoverable_ranges(unsigned long node,
134 				   const char *uname, int depth, void *data)
135 {
136 	int i, psize, size;
137 	const __be32 *prop;
138 
139 	if (depth != 1 || strcmp(uname, "ibm,opal") != 0)
140 		return 0;
141 
142 	prop = of_get_flat_dt_prop(node, "mcheck-recoverable-ranges", &psize);
143 
144 	if (!prop)
145 		return 1;
146 
147 	pr_debug("Found machine check recoverable ranges.\n");
148 
149 	/*
150 	 * Calculate number of available entries.
151 	 *
152 	 * Each recoverable address range entry is (start address, len,
153 	 * recovery address), 2 cells each for start and recovery address,
154 	 * 1 cell for len, totalling 5 cells per entry.
155 	 */
156 	mc_recoverable_range_len = psize / (sizeof(*prop) * 5);
157 
158 	/* Sanity check */
159 	if (!mc_recoverable_range_len)
160 		return 1;
161 
162 	/* Size required to hold all the entries. */
163 	size = mc_recoverable_range_len *
164 			sizeof(struct mcheck_recoverable_range);
165 
166 	/*
167 	 * Allocate a buffer to hold the MC recoverable ranges.
168 	 */
169 	mc_recoverable_range = memblock_alloc(size, __alignof__(u64));
170 	if (!mc_recoverable_range)
171 		panic("%s: Failed to allocate %u bytes align=0x%lx\n",
172 		      __func__, size, __alignof__(u64));
173 
174 	for (i = 0; i < mc_recoverable_range_len; i++) {
175 		mc_recoverable_range[i].start_addr =
176 					of_read_number(prop + (i * 5) + 0, 2);
177 		mc_recoverable_range[i].end_addr =
178 					mc_recoverable_range[i].start_addr +
179 					of_read_number(prop + (i * 5) + 2, 1);
180 		mc_recoverable_range[i].recover_addr =
181 					of_read_number(prop + (i * 5) + 3, 2);
182 
183 		pr_debug("Machine check recoverable range: %llx..%llx: %llx\n",
184 				mc_recoverable_range[i].start_addr,
185 				mc_recoverable_range[i].end_addr,
186 				mc_recoverable_range[i].recover_addr);
187 	}
188 	return 1;
189 }
190 
191 static int __init opal_register_exception_handlers(void)
192 {
193 #ifdef __BIG_ENDIAN__
194 	u64 glue;
195 
196 	if (!(powerpc_firmware_features & FW_FEATURE_OPAL))
197 		return -ENODEV;
198 
199 	/* Hookup some exception handlers except machine check. We use the
200 	 * fwnmi area at 0x7000 to provide the glue space to OPAL
201 	 */
202 	glue = 0x7000;
203 
204 	/*
205 	 * Only ancient OPAL firmware requires this.
206 	 * Specifically, firmware from FW810.00 (released June 2014)
207 	 * through FW810.20 (Released October 2014).
208 	 *
209 	 * Check if we are running on newer (post Oct 2014) firmware that
210 	 * exports the OPAL_HANDLE_HMI token. If yes, then don't ask OPAL to
211 	 * patch the HMI interrupt and we catch it directly in Linux.
212 	 *
213 	 * For older firmware (i.e < FW810.20), we fallback to old behavior and
214 	 * let OPAL patch the HMI vector and handle it inside OPAL firmware.
215 	 *
216 	 * For newer firmware we catch/handle the HMI directly in Linux.
217 	 */
218 	if (!opal_check_token(OPAL_HANDLE_HMI)) {
219 		pr_info("Old firmware detected, OPAL handles HMIs.\n");
220 		opal_register_exception_handler(
221 				OPAL_HYPERVISOR_MAINTENANCE_HANDLER,
222 				0, glue);
223 		glue += 128;
224 	}
225 
226 	/*
227 	 * Only applicable to ancient firmware, all modern
228 	 * (post March 2015/skiboot 5.0) firmware will just return
229 	 * OPAL_UNSUPPORTED.
230 	 */
231 	opal_register_exception_handler(OPAL_SOFTPATCH_HANDLER, 0, glue);
232 #endif
233 
234 	return 0;
235 }
236 machine_early_initcall(powernv, opal_register_exception_handlers);
237 
238 /*
239  * Opal message notifier based on message type. Allow subscribers to get
240  * notified for specific messgae type.
241  */
242 int opal_message_notifier_register(enum opal_msg_type msg_type,
243 					struct notifier_block *nb)
244 {
245 	if (!nb || msg_type >= OPAL_MSG_TYPE_MAX) {
246 		pr_warn("%s: Invalid arguments, msg_type:%d\n",
247 			__func__, msg_type);
248 		return -EINVAL;
249 	}
250 
251 	return atomic_notifier_chain_register(
252 				&opal_msg_notifier_head[msg_type], nb);
253 }
254 EXPORT_SYMBOL_GPL(opal_message_notifier_register);
255 
256 int opal_message_notifier_unregister(enum opal_msg_type msg_type,
257 				     struct notifier_block *nb)
258 {
259 	return atomic_notifier_chain_unregister(
260 			&opal_msg_notifier_head[msg_type], nb);
261 }
262 EXPORT_SYMBOL_GPL(opal_message_notifier_unregister);
263 
264 static void opal_message_do_notify(uint32_t msg_type, void *msg)
265 {
266 	/* notify subscribers */
267 	atomic_notifier_call_chain(&opal_msg_notifier_head[msg_type],
268 					msg_type, msg);
269 }
270 
271 static void opal_handle_message(void)
272 {
273 	s64 ret;
274 	/*
275 	 * TODO: pre-allocate a message buffer depending on opal-msg-size
276 	 * value in /proc/device-tree.
277 	 */
278 	static struct opal_msg msg;
279 	u32 type;
280 
281 	ret = opal_get_msg(__pa(&msg), sizeof(msg));
282 	/* No opal message pending. */
283 	if (ret == OPAL_RESOURCE)
284 		return;
285 
286 	/* check for errors. */
287 	if (ret) {
288 		pr_warn("%s: Failed to retrieve opal message, err=%lld\n",
289 			__func__, ret);
290 		return;
291 	}
292 
293 	type = be32_to_cpu(msg.msg_type);
294 
295 	/* Sanity check */
296 	if (type >= OPAL_MSG_TYPE_MAX) {
297 		pr_warn_once("%s: Unknown message type: %u\n", __func__, type);
298 		return;
299 	}
300 	opal_message_do_notify(type, (void *)&msg);
301 }
302 
303 static irqreturn_t opal_message_notify(int irq, void *data)
304 {
305 	opal_handle_message();
306 	return IRQ_HANDLED;
307 }
308 
309 static int __init opal_message_init(void)
310 {
311 	int ret, i, irq;
312 
313 	for (i = 0; i < OPAL_MSG_TYPE_MAX; i++)
314 		ATOMIC_INIT_NOTIFIER_HEAD(&opal_msg_notifier_head[i]);
315 
316 	irq = opal_event_request(ilog2(OPAL_EVENT_MSG_PENDING));
317 	if (!irq) {
318 		pr_err("%s: Can't register OPAL event irq (%d)\n",
319 		       __func__, irq);
320 		return irq;
321 	}
322 
323 	ret = request_irq(irq, opal_message_notify,
324 			IRQ_TYPE_LEVEL_HIGH, "opal-msg", NULL);
325 	if (ret) {
326 		pr_err("%s: Can't request OPAL event irq (%d)\n",
327 		       __func__, ret);
328 		return ret;
329 	}
330 
331 	return 0;
332 }
333 
334 int opal_get_chars(uint32_t vtermno, char *buf, int count)
335 {
336 	s64 rc;
337 	__be64 evt, len;
338 
339 	if (!opal.entry)
340 		return -ENODEV;
341 	opal_poll_events(&evt);
342 	if ((be64_to_cpu(evt) & OPAL_EVENT_CONSOLE_INPUT) == 0)
343 		return 0;
344 	len = cpu_to_be64(count);
345 	rc = opal_console_read(vtermno, &len, buf);
346 	if (rc == OPAL_SUCCESS)
347 		return be64_to_cpu(len);
348 	return 0;
349 }
350 
351 static int __opal_put_chars(uint32_t vtermno, const char *data, int total_len, bool atomic)
352 {
353 	unsigned long flags = 0 /* shut up gcc */;
354 	int written;
355 	__be64 olen;
356 	s64 rc;
357 
358 	if (!opal.entry)
359 		return -ENODEV;
360 
361 	if (atomic)
362 		spin_lock_irqsave(&opal_write_lock, flags);
363 	rc = opal_console_write_buffer_space(vtermno, &olen);
364 	if (rc || be64_to_cpu(olen) < total_len) {
365 		/* Closed -> drop characters */
366 		if (rc)
367 			written = total_len;
368 		else
369 			written = -EAGAIN;
370 		goto out;
371 	}
372 
373 	/* Should not get a partial write here because space is available. */
374 	olen = cpu_to_be64(total_len);
375 	rc = opal_console_write(vtermno, &olen, data);
376 	if (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) {
377 		if (rc == OPAL_BUSY_EVENT)
378 			opal_poll_events(NULL);
379 		written = -EAGAIN;
380 		goto out;
381 	}
382 
383 	/* Closed or other error drop */
384 	if (rc != OPAL_SUCCESS) {
385 		written = opal_error_code(rc);
386 		goto out;
387 	}
388 
389 	written = be64_to_cpu(olen);
390 	if (written < total_len) {
391 		if (atomic) {
392 			/* Should not happen */
393 			pr_warn("atomic console write returned partial "
394 				"len=%d written=%d\n", total_len, written);
395 		}
396 		if (!written)
397 			written = -EAGAIN;
398 	}
399 
400 out:
401 	if (atomic)
402 		spin_unlock_irqrestore(&opal_write_lock, flags);
403 
404 	return written;
405 }
406 
407 int opal_put_chars(uint32_t vtermno, const char *data, int total_len)
408 {
409 	return __opal_put_chars(vtermno, data, total_len, false);
410 }
411 
412 /*
413  * opal_put_chars_atomic will not perform partial-writes. Data will be
414  * atomically written to the terminal or not at all. This is not strictly
415  * true at the moment because console space can race with OPAL's console
416  * writes.
417  */
418 int opal_put_chars_atomic(uint32_t vtermno, const char *data, int total_len)
419 {
420 	return __opal_put_chars(vtermno, data, total_len, true);
421 }
422 
423 static s64 __opal_flush_console(uint32_t vtermno)
424 {
425 	s64 rc;
426 
427 	if (!opal_check_token(OPAL_CONSOLE_FLUSH)) {
428 		__be64 evt;
429 
430 		/*
431 		 * If OPAL_CONSOLE_FLUSH is not implemented in the firmware,
432 		 * the console can still be flushed by calling the polling
433 		 * function while it has OPAL_EVENT_CONSOLE_OUTPUT events.
434 		 */
435 		WARN_ONCE(1, "opal: OPAL_CONSOLE_FLUSH missing.\n");
436 
437 		opal_poll_events(&evt);
438 		if (!(be64_to_cpu(evt) & OPAL_EVENT_CONSOLE_OUTPUT))
439 			return OPAL_SUCCESS;
440 		return OPAL_BUSY;
441 
442 	} else {
443 		rc = opal_console_flush(vtermno);
444 		if (rc == OPAL_BUSY_EVENT) {
445 			opal_poll_events(NULL);
446 			rc = OPAL_BUSY;
447 		}
448 		return rc;
449 	}
450 
451 }
452 
453 /*
454  * opal_flush_console spins until the console is flushed
455  */
456 int opal_flush_console(uint32_t vtermno)
457 {
458 	for (;;) {
459 		s64 rc = __opal_flush_console(vtermno);
460 
461 		if (rc == OPAL_BUSY || rc == OPAL_PARTIAL) {
462 			mdelay(1);
463 			continue;
464 		}
465 
466 		return opal_error_code(rc);
467 	}
468 }
469 
470 /*
471  * opal_flush_chars is an hvc interface that sleeps until the console is
472  * flushed if wait, otherwise it will return -EBUSY if the console has data,
473  * -EAGAIN if it has data and some of it was flushed.
474  */
475 int opal_flush_chars(uint32_t vtermno, bool wait)
476 {
477 	for (;;) {
478 		s64 rc = __opal_flush_console(vtermno);
479 
480 		if (rc == OPAL_BUSY || rc == OPAL_PARTIAL) {
481 			if (wait) {
482 				msleep(OPAL_BUSY_DELAY_MS);
483 				continue;
484 			}
485 			if (rc == OPAL_PARTIAL)
486 				return -EAGAIN;
487 		}
488 
489 		return opal_error_code(rc);
490 	}
491 }
492 
493 static int opal_recover_mce(struct pt_regs *regs,
494 					struct machine_check_event *evt)
495 {
496 	int recovered = 0;
497 
498 	if (!(regs->msr & MSR_RI)) {
499 		/* If MSR_RI isn't set, we cannot recover */
500 		pr_err("Machine check interrupt unrecoverable: MSR(RI=0)\n");
501 		recovered = 0;
502 	} else if (evt->disposition == MCE_DISPOSITION_RECOVERED) {
503 		/* Platform corrected itself */
504 		recovered = 1;
505 	} else if (evt->severity == MCE_SEV_FATAL) {
506 		/* Fatal machine check */
507 		pr_err("Machine check interrupt is fatal\n");
508 		recovered = 0;
509 	}
510 
511 	if (!recovered && evt->sync_error) {
512 		/*
513 		 * Try to kill processes if we get a synchronous machine check
514 		 * (e.g., one caused by execution of this instruction). This
515 		 * will devolve into a panic if we try to kill init or are in
516 		 * an interrupt etc.
517 		 *
518 		 * TODO: Queue up this address for hwpoisioning later.
519 		 * TODO: This is not quite right for d-side machine
520 		 *       checks ->nip is not necessarily the important
521 		 *       address.
522 		 */
523 		if ((user_mode(regs))) {
524 			_exception(SIGBUS, regs, BUS_MCEERR_AR, regs->nip);
525 			recovered = 1;
526 		} else if (die_will_crash()) {
527 			/*
528 			 * die() would kill the kernel, so better to go via
529 			 * the platform reboot code that will log the
530 			 * machine check.
531 			 */
532 			recovered = 0;
533 		} else {
534 			die("Machine check", regs, SIGBUS);
535 			recovered = 1;
536 		}
537 	}
538 
539 	return recovered;
540 }
541 
542 void __noreturn pnv_platform_error_reboot(struct pt_regs *regs, const char *msg)
543 {
544 	panic_flush_kmsg_start();
545 
546 	pr_emerg("Hardware platform error: %s\n", msg);
547 	if (regs)
548 		show_regs(regs);
549 	smp_send_stop();
550 
551 	panic_flush_kmsg_end();
552 
553 	/*
554 	 * Don't bother to shut things down because this will
555 	 * xstop the system.
556 	 */
557 	if (opal_cec_reboot2(OPAL_REBOOT_PLATFORM_ERROR, msg)
558 						== OPAL_UNSUPPORTED) {
559 		pr_emerg("Reboot type %d not supported for %s\n",
560 				OPAL_REBOOT_PLATFORM_ERROR, msg);
561 	}
562 
563 	/*
564 	 * We reached here. There can be three possibilities:
565 	 * 1. We are running on a firmware level that do not support
566 	 *    opal_cec_reboot2()
567 	 * 2. We are running on a firmware level that do not support
568 	 *    OPAL_REBOOT_PLATFORM_ERROR reboot type.
569 	 * 3. We are running on FSP based system that does not need
570 	 *    opal to trigger checkstop explicitly for error analysis.
571 	 *    The FSP PRD component would have already got notified
572 	 *    about this error through other channels.
573 	 * 4. We are running on a newer skiboot that by default does
574 	 *    not cause a checkstop, drops us back to the kernel to
575 	 *    extract context and state at the time of the error.
576 	 */
577 
578 	panic(msg);
579 }
580 
581 int opal_machine_check(struct pt_regs *regs)
582 {
583 	struct machine_check_event evt;
584 
585 	if (!get_mce_event(&evt, MCE_EVENT_RELEASE))
586 		return 0;
587 
588 	/* Print things out */
589 	if (evt.version != MCE_V1) {
590 		pr_err("Machine Check Exception, Unknown event version %d !\n",
591 		       evt.version);
592 		return 0;
593 	}
594 	machine_check_print_event_info(&evt, user_mode(regs), false);
595 
596 	if (opal_recover_mce(regs, &evt))
597 		return 1;
598 
599 	pnv_platform_error_reboot(regs, "Unrecoverable Machine Check exception");
600 }
601 
602 /* Early hmi handler called in real mode. */
603 int opal_hmi_exception_early(struct pt_regs *regs)
604 {
605 	s64 rc;
606 
607 	/*
608 	 * call opal hmi handler. Pass paca address as token.
609 	 * The return value OPAL_SUCCESS is an indication that there is
610 	 * an HMI event generated waiting to pull by Linux.
611 	 */
612 	rc = opal_handle_hmi();
613 	if (rc == OPAL_SUCCESS) {
614 		local_paca->hmi_event_available = 1;
615 		return 1;
616 	}
617 	return 0;
618 }
619 
620 int opal_hmi_exception_early2(struct pt_regs *regs)
621 {
622 	s64 rc;
623 	__be64 out_flags;
624 
625 	/*
626 	 * call opal hmi handler.
627 	 * Check 64-bit flag mask to find out if an event was generated,
628 	 * and whether TB is still valid or not etc.
629 	 */
630 	rc = opal_handle_hmi2(&out_flags);
631 	if (rc != OPAL_SUCCESS)
632 		return 0;
633 
634 	if (be64_to_cpu(out_flags) & OPAL_HMI_FLAGS_NEW_EVENT)
635 		local_paca->hmi_event_available = 1;
636 	if (be64_to_cpu(out_flags) & OPAL_HMI_FLAGS_TOD_TB_FAIL)
637 		tb_invalid = true;
638 	return 1;
639 }
640 
641 /* HMI exception handler called in virtual mode during check_irq_replay. */
642 int opal_handle_hmi_exception(struct pt_regs *regs)
643 {
644 	/*
645 	 * Check if HMI event is available.
646 	 * if Yes, then wake kopald to process them.
647 	 */
648 	if (!local_paca->hmi_event_available)
649 		return 0;
650 
651 	local_paca->hmi_event_available = 0;
652 	opal_wake_poller();
653 
654 	return 1;
655 }
656 
657 static uint64_t find_recovery_address(uint64_t nip)
658 {
659 	int i;
660 
661 	for (i = 0; i < mc_recoverable_range_len; i++)
662 		if ((nip >= mc_recoverable_range[i].start_addr) &&
663 		    (nip < mc_recoverable_range[i].end_addr))
664 		    return mc_recoverable_range[i].recover_addr;
665 	return 0;
666 }
667 
668 bool opal_mce_check_early_recovery(struct pt_regs *regs)
669 {
670 	uint64_t recover_addr = 0;
671 
672 	if (!opal.base || !opal.size)
673 		goto out;
674 
675 	if ((regs->nip >= opal.base) &&
676 			(regs->nip < (opal.base + opal.size)))
677 		recover_addr = find_recovery_address(regs->nip);
678 
679 	/*
680 	 * Setup regs->nip to rfi into fixup address.
681 	 */
682 	if (recover_addr)
683 		regs->nip = recover_addr;
684 
685 out:
686 	return !!recover_addr;
687 }
688 
689 static int opal_sysfs_init(void)
690 {
691 	opal_kobj = kobject_create_and_add("opal", firmware_kobj);
692 	if (!opal_kobj) {
693 		pr_warn("kobject_create_and_add opal failed\n");
694 		return -ENOMEM;
695 	}
696 
697 	return 0;
698 }
699 
700 static ssize_t symbol_map_read(struct file *fp, struct kobject *kobj,
701 			       struct bin_attribute *bin_attr,
702 			       char *buf, loff_t off, size_t count)
703 {
704 	return memory_read_from_buffer(buf, count, &off, bin_attr->private,
705 				       bin_attr->size);
706 }
707 
708 static BIN_ATTR_RO(symbol_map, 0);
709 
710 static void opal_export_symmap(void)
711 {
712 	const __be64 *syms;
713 	unsigned int size;
714 	struct device_node *fw;
715 	int rc;
716 
717 	fw = of_find_node_by_path("/ibm,opal/firmware");
718 	if (!fw)
719 		return;
720 	syms = of_get_property(fw, "symbol-map", &size);
721 	if (!syms || size != 2 * sizeof(__be64))
722 		return;
723 
724 	/* Setup attributes */
725 	bin_attr_symbol_map.private = __va(be64_to_cpu(syms[0]));
726 	bin_attr_symbol_map.size = be64_to_cpu(syms[1]);
727 
728 	rc = sysfs_create_bin_file(opal_kobj, &bin_attr_symbol_map);
729 	if (rc)
730 		pr_warn("Error %d creating OPAL symbols file\n", rc);
731 }
732 
733 static ssize_t export_attr_read(struct file *fp, struct kobject *kobj,
734 				struct bin_attribute *bin_attr, char *buf,
735 				loff_t off, size_t count)
736 {
737 	return memory_read_from_buffer(buf, count, &off, bin_attr->private,
738 				       bin_attr->size);
739 }
740 
741 /*
742  * opal_export_attrs: creates a sysfs node for each property listed in
743  * the device-tree under /ibm,opal/firmware/exports/
744  * All new sysfs nodes are created under /opal/exports/.
745  * This allows for reserved memory regions (e.g. HDAT) to be read.
746  * The new sysfs nodes are only readable by root.
747  */
748 static void opal_export_attrs(void)
749 {
750 	struct bin_attribute *attr;
751 	struct device_node *np;
752 	struct property *prop;
753 	struct kobject *kobj;
754 	u64 vals[2];
755 	int rc;
756 
757 	np = of_find_node_by_path("/ibm,opal/firmware/exports");
758 	if (!np)
759 		return;
760 
761 	/* Create new 'exports' directory - /sys/firmware/opal/exports */
762 	kobj = kobject_create_and_add("exports", opal_kobj);
763 	if (!kobj) {
764 		pr_warn("kobject_create_and_add() of exports failed\n");
765 		return;
766 	}
767 
768 	for_each_property_of_node(np, prop) {
769 		if (!strcmp(prop->name, "name") || !strcmp(prop->name, "phandle"))
770 			continue;
771 
772 		if (of_property_read_u64_array(np, prop->name, &vals[0], 2))
773 			continue;
774 
775 		attr = kzalloc(sizeof(*attr), GFP_KERNEL);
776 
777 		if (attr == NULL) {
778 			pr_warn("Failed kmalloc for bin_attribute!");
779 			continue;
780 		}
781 
782 		sysfs_bin_attr_init(attr);
783 		attr->attr.name = kstrdup(prop->name, GFP_KERNEL);
784 		attr->attr.mode = 0400;
785 		attr->read = export_attr_read;
786 		attr->private = __va(vals[0]);
787 		attr->size = vals[1];
788 
789 		if (attr->attr.name == NULL) {
790 			pr_warn("Failed kstrdup for bin_attribute attr.name");
791 			kfree(attr);
792 			continue;
793 		}
794 
795 		rc = sysfs_create_bin_file(kobj, attr);
796 		if (rc) {
797 			pr_warn("Error %d creating OPAL sysfs exports/%s file\n",
798 				 rc, prop->name);
799 			kfree(attr->attr.name);
800 			kfree(attr);
801 		}
802 	}
803 
804 	of_node_put(np);
805 }
806 
807 static void __init opal_dump_region_init(void)
808 {
809 	void *addr;
810 	uint64_t size;
811 	int rc;
812 
813 	if (!opal_check_token(OPAL_REGISTER_DUMP_REGION))
814 		return;
815 
816 	/* Register kernel log buffer */
817 	addr = log_buf_addr_get();
818 	if (addr == NULL)
819 		return;
820 
821 	size = log_buf_len_get();
822 	if (size == 0)
823 		return;
824 
825 	rc = opal_register_dump_region(OPAL_DUMP_REGION_LOG_BUF,
826 				       __pa(addr), size);
827 	/* Don't warn if this is just an older OPAL that doesn't
828 	 * know about that call
829 	 */
830 	if (rc && rc != OPAL_UNSUPPORTED)
831 		pr_warn("DUMP: Failed to register kernel log buffer. "
832 			"rc = %d\n", rc);
833 }
834 
835 static void opal_pdev_init(const char *compatible)
836 {
837 	struct device_node *np;
838 
839 	for_each_compatible_node(np, NULL, compatible)
840 		of_platform_device_create(np, NULL, NULL);
841 }
842 
843 static void __init opal_imc_init_dev(void)
844 {
845 	struct device_node *np;
846 
847 	np = of_find_compatible_node(NULL, NULL, IMC_DTB_COMPAT);
848 	if (np)
849 		of_platform_device_create(np, NULL, NULL);
850 }
851 
852 static int kopald(void *unused)
853 {
854 	unsigned long timeout = msecs_to_jiffies(opal_heartbeat) + 1;
855 
856 	set_freezable();
857 	do {
858 		try_to_freeze();
859 
860 		opal_handle_events();
861 
862 		set_current_state(TASK_INTERRUPTIBLE);
863 		if (opal_have_pending_events())
864 			__set_current_state(TASK_RUNNING);
865 		else
866 			schedule_timeout(timeout);
867 
868 	} while (!kthread_should_stop());
869 
870 	return 0;
871 }
872 
873 void opal_wake_poller(void)
874 {
875 	if (kopald_tsk)
876 		wake_up_process(kopald_tsk);
877 }
878 
879 static void opal_init_heartbeat(void)
880 {
881 	/* Old firwmware, we assume the HVC heartbeat is sufficient */
882 	if (of_property_read_u32(opal_node, "ibm,heartbeat-ms",
883 				 &opal_heartbeat) != 0)
884 		opal_heartbeat = 0;
885 
886 	if (opal_heartbeat)
887 		kopald_tsk = kthread_run(kopald, NULL, "kopald");
888 }
889 
890 static int __init opal_init(void)
891 {
892 	struct device_node *np, *consoles, *leds;
893 	int rc;
894 
895 	opal_node = of_find_node_by_path("/ibm,opal");
896 	if (!opal_node) {
897 		pr_warn("Device node not found\n");
898 		return -ENODEV;
899 	}
900 
901 	/* Register OPAL consoles if any ports */
902 	consoles = of_find_node_by_path("/ibm,opal/consoles");
903 	if (consoles) {
904 		for_each_child_of_node(consoles, np) {
905 			if (!of_node_name_eq(np, "serial"))
906 				continue;
907 			of_platform_device_create(np, NULL, NULL);
908 		}
909 		of_node_put(consoles);
910 	}
911 
912 	/* Initialise OPAL messaging system */
913 	opal_message_init();
914 
915 	/* Initialise OPAL asynchronous completion interface */
916 	opal_async_comp_init();
917 
918 	/* Initialise OPAL sensor interface */
919 	opal_sensor_init();
920 
921 	/* Initialise OPAL hypervisor maintainence interrupt handling */
922 	opal_hmi_handler_init();
923 
924 	/* Create i2c platform devices */
925 	opal_pdev_init("ibm,opal-i2c");
926 
927 	/* Handle non-volatile memory devices */
928 	opal_pdev_init("pmem-region");
929 
930 	/* Setup a heatbeat thread if requested by OPAL */
931 	opal_init_heartbeat();
932 
933 	/* Detect In-Memory Collection counters and create devices*/
934 	opal_imc_init_dev();
935 
936 	/* Create leds platform devices */
937 	leds = of_find_node_by_path("/ibm,opal/leds");
938 	if (leds) {
939 		of_platform_device_create(leds, "opal_leds", NULL);
940 		of_node_put(leds);
941 	}
942 
943 	/* Initialise OPAL message log interface */
944 	opal_msglog_init();
945 
946 	/* Create "opal" kobject under /sys/firmware */
947 	rc = opal_sysfs_init();
948 	if (rc == 0) {
949 		/* Export symbol map to userspace */
950 		opal_export_symmap();
951 		/* Setup dump region interface */
952 		opal_dump_region_init();
953 		/* Setup error log interface */
954 		rc = opal_elog_init();
955 		/* Setup code update interface */
956 		opal_flash_update_init();
957 		/* Setup platform dump extract interface */
958 		opal_platform_dump_init();
959 		/* Setup system parameters interface */
960 		opal_sys_param_init();
961 		/* Setup message log sysfs interface. */
962 		opal_msglog_sysfs_init();
963 	}
964 
965 	/* Export all properties */
966 	opal_export_attrs();
967 
968 	/* Initialize platform devices: IPMI backend, PRD & flash interface */
969 	opal_pdev_init("ibm,opal-ipmi");
970 	opal_pdev_init("ibm,opal-flash");
971 	opal_pdev_init("ibm,opal-prd");
972 
973 	/* Initialise platform device: oppanel interface */
974 	opal_pdev_init("ibm,opal-oppanel");
975 
976 	/* Initialise OPAL kmsg dumper for flushing console on panic */
977 	opal_kmsg_init();
978 
979 	/* Initialise OPAL powercap interface */
980 	opal_powercap_init();
981 
982 	/* Initialise OPAL Power-Shifting-Ratio interface */
983 	opal_psr_init();
984 
985 	/* Initialise OPAL sensor groups */
986 	opal_sensor_groups_init();
987 
988 	/* Initialise OPAL Power control interface */
989 	opal_power_control_init();
990 
991 	return 0;
992 }
993 machine_subsys_initcall(powernv, opal_init);
994 
995 void opal_shutdown(void)
996 {
997 	long rc = OPAL_BUSY;
998 
999 	opal_event_shutdown();
1000 
1001 	/*
1002 	 * Then sync with OPAL which ensure anything that can
1003 	 * potentially write to our memory has completed such
1004 	 * as an ongoing dump retrieval
1005 	 */
1006 	while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) {
1007 		rc = opal_sync_host_reboot();
1008 		if (rc == OPAL_BUSY)
1009 			opal_poll_events(NULL);
1010 		else
1011 			mdelay(10);
1012 	}
1013 
1014 	/* Unregister memory dump region */
1015 	if (opal_check_token(OPAL_UNREGISTER_DUMP_REGION))
1016 		opal_unregister_dump_region(OPAL_DUMP_REGION_LOG_BUF);
1017 }
1018 
1019 /* Export this so that test modules can use it */
1020 EXPORT_SYMBOL_GPL(opal_invalid_call);
1021 EXPORT_SYMBOL_GPL(opal_xscom_read);
1022 EXPORT_SYMBOL_GPL(opal_xscom_write);
1023 EXPORT_SYMBOL_GPL(opal_ipmi_send);
1024 EXPORT_SYMBOL_GPL(opal_ipmi_recv);
1025 EXPORT_SYMBOL_GPL(opal_flash_read);
1026 EXPORT_SYMBOL_GPL(opal_flash_write);
1027 EXPORT_SYMBOL_GPL(opal_flash_erase);
1028 EXPORT_SYMBOL_GPL(opal_prd_msg);
1029 EXPORT_SYMBOL_GPL(opal_check_token);
1030 
1031 /* Convert a region of vmalloc memory to an opal sg list */
1032 struct opal_sg_list *opal_vmalloc_to_sg_list(void *vmalloc_addr,
1033 					     unsigned long vmalloc_size)
1034 {
1035 	struct opal_sg_list *sg, *first = NULL;
1036 	unsigned long i = 0;
1037 
1038 	sg = kzalloc(PAGE_SIZE, GFP_KERNEL);
1039 	if (!sg)
1040 		goto nomem;
1041 
1042 	first = sg;
1043 
1044 	while (vmalloc_size > 0) {
1045 		uint64_t data = vmalloc_to_pfn(vmalloc_addr) << PAGE_SHIFT;
1046 		uint64_t length = min(vmalloc_size, PAGE_SIZE);
1047 
1048 		sg->entry[i].data = cpu_to_be64(data);
1049 		sg->entry[i].length = cpu_to_be64(length);
1050 		i++;
1051 
1052 		if (i >= SG_ENTRIES_PER_NODE) {
1053 			struct opal_sg_list *next;
1054 
1055 			next = kzalloc(PAGE_SIZE, GFP_KERNEL);
1056 			if (!next)
1057 				goto nomem;
1058 
1059 			sg->length = cpu_to_be64(
1060 					i * sizeof(struct opal_sg_entry) + 16);
1061 			i = 0;
1062 			sg->next = cpu_to_be64(__pa(next));
1063 			sg = next;
1064 		}
1065 
1066 		vmalloc_addr += length;
1067 		vmalloc_size -= length;
1068 	}
1069 
1070 	sg->length = cpu_to_be64(i * sizeof(struct opal_sg_entry) + 16);
1071 
1072 	return first;
1073 
1074 nomem:
1075 	pr_err("%s : Failed to allocate memory\n", __func__);
1076 	opal_free_sg_list(first);
1077 	return NULL;
1078 }
1079 
1080 void opal_free_sg_list(struct opal_sg_list *sg)
1081 {
1082 	while (sg) {
1083 		uint64_t next = be64_to_cpu(sg->next);
1084 
1085 		kfree(sg);
1086 
1087 		if (next)
1088 			sg = __va(next);
1089 		else
1090 			sg = NULL;
1091 	}
1092 }
1093 
1094 int opal_error_code(int rc)
1095 {
1096 	switch (rc) {
1097 	case OPAL_SUCCESS:		return 0;
1098 
1099 	case OPAL_PARAMETER:		return -EINVAL;
1100 	case OPAL_ASYNC_COMPLETION:	return -EINPROGRESS;
1101 	case OPAL_BUSY:
1102 	case OPAL_BUSY_EVENT:		return -EBUSY;
1103 	case OPAL_NO_MEM:		return -ENOMEM;
1104 	case OPAL_PERMISSION:		return -EPERM;
1105 
1106 	case OPAL_UNSUPPORTED:		return -EIO;
1107 	case OPAL_HARDWARE:		return -EIO;
1108 	case OPAL_INTERNAL_ERROR:	return -EIO;
1109 	case OPAL_TIMEOUT:		return -ETIMEDOUT;
1110 	default:
1111 		pr_err("%s: unexpected OPAL error %d\n", __func__, rc);
1112 		return -EIO;
1113 	}
1114 }
1115 
1116 void powernv_set_nmmu_ptcr(unsigned long ptcr)
1117 {
1118 	int rc;
1119 
1120 	if (firmware_has_feature(FW_FEATURE_OPAL)) {
1121 		rc = opal_nmmu_set_ptcr(-1UL, ptcr);
1122 		if (rc != OPAL_SUCCESS && rc != OPAL_UNSUPPORTED)
1123 			pr_warn("%s: Unable to set nest mmu ptcr\n", __func__);
1124 	}
1125 }
1126 
1127 EXPORT_SYMBOL_GPL(opal_poll_events);
1128 EXPORT_SYMBOL_GPL(opal_rtc_read);
1129 EXPORT_SYMBOL_GPL(opal_rtc_write);
1130 EXPORT_SYMBOL_GPL(opal_tpo_read);
1131 EXPORT_SYMBOL_GPL(opal_tpo_write);
1132 EXPORT_SYMBOL_GPL(opal_i2c_request);
1133 /* Export these symbols for PowerNV LED class driver */
1134 EXPORT_SYMBOL_GPL(opal_leds_get_ind);
1135 EXPORT_SYMBOL_GPL(opal_leds_set_ind);
1136 /* Export this symbol for PowerNV Operator Panel class driver */
1137 EXPORT_SYMBOL_GPL(opal_write_oppanel_async);
1138 /* Export this for KVM */
1139 EXPORT_SYMBOL_GPL(opal_int_set_mfrr);
1140 EXPORT_SYMBOL_GPL(opal_int_eoi);
1141 EXPORT_SYMBOL_GPL(opal_error_code);
1142 /* Export the below symbol for NX compression */
1143 EXPORT_SYMBOL(opal_nx_coproc_init);
1144