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