opal.c 26.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * PowerNV OPAL high level interfaces
 *
 * Copyright 2011 IBM Corp.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 */

12
#define pr_fmt(fmt)	"opal: " fmt
13

14
#include <linux/printk.h>
15 16
#include <linux/types.h>
#include <linux/of.h>
R
Rob Herring 已提交
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 28
#include <linux/kthread.h>
#include <linux/freezer.h>
29 30 31 32
#include <linux/printk.h>
#include <linux/kmsg_dump.h>
#include <linux/console.h>
#include <linux/sched/debug.h>
33 34

#include <asm/machdep.h>
35 36
#include <asm/opal.h>
#include <asm/firmware.h>
37
#include <asm/mce.h>
38
#include <asm/imc-pmu.h>
39
#include <asm/bug.h>
40 41 42

#include "powernv.h"

43 44 45
/* /sys/firmware/opal */
struct kobject *opal_kobj;

46 47 48
struct opal {
	u64 base;
	u64 entry;
49
	u64 size;
50 51
} opal;

52 53 54 55 56 57 58 59 60
struct mcheck_recoverable_range {
	u64 start_addr;
	u64 end_addr;
	u64 recover_addr;
};

static struct mcheck_recoverable_range *mc_recoverable_range;
static int mc_recoverable_range_len;

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 70
	u64 reinit_flags = 0;

71 72 73 74 75 76 77
	/* Do the actual re-init, This will clobber all FPRs, VRs, etc...
	 *
	 * It will preserve non volatile GPRs and HSPRG0/1. It will
	 * also restore HIDs and other SPRs to their original value
	 * but it might clobber a bunch.
	 */
#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 85 86 87
	/*
	 * POWER9 always support running hash:
	 *  ie. Host hash  supports  hash guests
	 *      Host radix supports  hash/radix guests
	 */
88
	if (early_cpu_has_feature(CPU_FTR_ARCH_300)) {
89 90 91 92 93 94 95
		reinit_flags |= OPAL_REINIT_CPUS_MMU_HASH;
		if (early_radix_enabled())
			reinit_flags |= OPAL_REINIT_CPUS_MMU_RADIX;
	}

	opal_reinit_cpus(reinit_flags);

96 97 98
	/* Restore some bits */
	if (cur_cpu_spec->cpu_restore)
		cur_cpu_spec->cpu_restore();
99 100
}

101 102 103
int __init early_init_dt_scan_opal(unsigned long node,
				   const char *uname, int depth, void *data)
{
104
	const void *basep, *entryp, *sizep;
105
	int basesz, entrysz, runtimesz;
106 107 108 109 110 111

	if (depth != 1 || strcmp(uname, "ibm,opal") != 0)
		return 0;

	basep  = of_get_flat_dt_prop(node, "opal-base-address", &basesz);
	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 116 117 118
		return 1;

	opal.base = of_read_number(basep, basesz/4);
	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 136 137
	return 1;
}

138 139 140
int __init early_init_dt_scan_recoverable_ranges(unsigned long node,
				   const char *uname, int depth, void *data)
{
141
	int i, psize, size;
142 143 144 145 146
	const __be32 *prop;

	if (depth != 1 || strcmp(uname, "ibm,opal") != 0)
		return 0;

147
	prop = of_get_flat_dt_prop(node, "mcheck-recoverable-ranges", &psize);
148 149 150 151 152 153

	if (!prop)
		return 1;

	pr_debug("Found machine check recoverable ranges.\n");

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
	/*
	 * Calculate number of available entries.
	 *
	 * Each recoverable address range entry is (start address, len,
	 * recovery address), 2 cells each for start and recovery address,
	 * 1 cell for len, totalling 5 cells per entry.
	 */
	mc_recoverable_range_len = psize / (sizeof(*prop) * 5);

	/* Sanity check */
	if (!mc_recoverable_range_len)
		return 1;

	/* Size required to hold all the entries. */
	size = mc_recoverable_range_len *
			sizeof(struct mcheck_recoverable_range);

171
	/*
172
	 * Allocate a buffer to hold the MC recoverable ranges.
173
	 */
174
	mc_recoverable_range =__va(memblock_phys_alloc(size, __alignof__(u64)));
175 176
	memset(mc_recoverable_range, 0, size);

177
	for (i = 0; i < mc_recoverable_range_len; i++) {
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
		mc_recoverable_range[i].start_addr =
					of_read_number(prop + (i * 5) + 0, 2);
		mc_recoverable_range[i].end_addr =
					mc_recoverable_range[i].start_addr +
					of_read_number(prop + (i * 5) + 2, 1);
		mc_recoverable_range[i].recover_addr =
					of_read_number(prop + (i * 5) + 3, 2);

		pr_debug("Machine check recoverable range: %llx..%llx: %llx\n",
				mc_recoverable_range[i].start_addr,
				mc_recoverable_range[i].end_addr,
				mc_recoverable_range[i].recover_addr);
	}
	return 1;
}

194 195
static int __init opal_register_exception_handlers(void)
{
196
#ifdef __BIG_ENDIAN__
197 198 199 200 201
	u64 glue;

	if (!(powerpc_firmware_features & FW_FEATURE_OPAL))
		return -ENODEV;

202 203
	/* Hookup some exception handlers except machine check. We use the
	 * fwnmi area at 0x7000 to provide the glue space to OPAL
204 205
	 */
	glue = 0x7000;
206 207 208 209 210 211 212 213 214 215 216 217 218 219

	/*
	 * Check if we are running on newer firmware that exports
	 * OPAL_HANDLE_HMI token. If yes, then don't ask OPAL to patch
	 * the HMI interrupt and we catch it directly in Linux.
	 *
	 * For older firmware (i.e currently released POWER8 System Firmware
	 * as of today <= SV810_087), we fallback to old behavior and let OPAL
	 * patch the HMI vector and handle it inside OPAL firmware.
	 *
	 * For newer firmware (in development/yet to be released) we will
	 * start catching/handling HMI directly in Linux.
	 */
	if (!opal_check_token(OPAL_HANDLE_HMI)) {
220
		pr_info("Old firmware detected, OPAL handles HMIs.\n");
221 222 223 224 225 226
		opal_register_exception_handler(
				OPAL_HYPERVISOR_MAINTENANCE_HANDLER,
				0, glue);
		glue += 128;
	}

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 236 237
/*
 * Opal message notifier based on message type. Allow subscribers to get
 * notified for specific messgae type.
 */
238
int opal_message_notifier_register(enum opal_msg_type msg_type,
239 240
					struct notifier_block *nb)
{
241
	if (!nb || msg_type >= OPAL_MSG_TYPE_MAX) {
242 243
		pr_warn("%s: Invalid arguments, msg_type:%d\n",
			__func__, msg_type);
244 245
		return -EINVAL;
	}
246

247 248 249
	return atomic_notifier_chain_register(
				&opal_msg_notifier_head[msg_type], nb);
}
250
EXPORT_SYMBOL_GPL(opal_message_notifier_register);
251

252
int opal_message_notifier_unregister(enum opal_msg_type msg_type,
253 254 255 256 257
				     struct notifier_block *nb)
{
	return atomic_notifier_chain_unregister(
			&opal_msg_notifier_head[msg_type], nb);
}
258
EXPORT_SYMBOL_GPL(opal_message_notifier_unregister);
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
static void opal_message_do_notify(uint32_t msg_type, void *msg)
{
	/* notify subscribers */
	atomic_notifier_call_chain(&opal_msg_notifier_head[msg_type],
					msg_type, msg);
}

static void opal_handle_message(void)
{
	s64 ret;
	/*
	 * TODO: pre-allocate a message buffer depending on opal-msg-size
	 * value in /proc/device-tree.
	 */
	static struct opal_msg msg;
275
	u32 type;
276 277 278 279 280 281 282 283

	ret = opal_get_msg(__pa(&msg), sizeof(msg));
	/* No opal message pending. */
	if (ret == OPAL_RESOURCE)
		return;

	/* check for errors. */
	if (ret) {
284 285
		pr_warn("%s: Failed to retrieve opal message, err=%lld\n",
			__func__, ret);
286 287 288
		return;
	}

289 290
	type = be32_to_cpu(msg.msg_type);

291
	/* Sanity check */
292
	if (type >= OPAL_MSG_TYPE_MAX) {
293
		pr_warn_once("%s: Unknown message type: %u\n", __func__, type);
294 295
		return;
	}
296
	opal_message_do_notify(type, (void *)&msg);
297 298
}

299
static irqreturn_t opal_message_notify(int irq, void *data)
300
{
301 302
	opal_handle_message();
	return IRQ_HANDLED;
303 304 305 306
}

static int __init opal_message_init(void)
{
307
	int ret, i, irq;
308 309 310 311

	for (i = 0; i < OPAL_MSG_TYPE_MAX; i++)
		ATOMIC_INIT_NOTIFIER_HEAD(&opal_msg_notifier_head[i]);

312 313 314 315 316 317 318 319 320
	irq = opal_event_request(ilog2(OPAL_EVENT_MSG_PENDING));
	if (!irq) {
		pr_err("%s: Can't register OPAL event irq (%d)\n",
		       __func__, irq);
		return irq;
	}

	ret = request_irq(irq, opal_message_notify,
			IRQ_TYPE_LEVEL_HIGH, "opal-msg", NULL);
321
	if (ret) {
322
		pr_err("%s: Can't request OPAL event irq (%d)\n",
323 324 325
		       __func__, ret);
		return ret;
	}
326

327 328 329
	return 0;
}

330 331
int opal_get_chars(uint32_t vtermno, char *buf, int count)
{
332 333
	s64 rc;
	__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 345 346
	return 0;
}

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 351 352
	int written;
	__be64 olen;
	s64 rc;
353 354

	if (!opal.entry)
355
		return -ENODEV;
356

357 358
	if (atomic)
		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 362
		/* Closed -> drop characters */
		if (rc)
363 364 365 366
			written = total_len;
		else
			written = -EAGAIN;
		goto out;
367 368
	}

369 370 371 372
	/* Should not get a partial write here because space is available. */
	olen = cpu_to_be64(total_len);
	rc = opal_console_write(vtermno, &olen, data);
	if (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) {
373
		if (rc == OPAL_BUSY_EVENT)
374 375 376 377
			opal_poll_events(NULL);
		written = -EAGAIN;
		goto out;
	}
378

379 380 381 382 383
	/* Closed or other error drop */
	if (rc != OPAL_SUCCESS) {
		written = opal_error_code(rc);
		goto out;
	}
384

385 386
	written = be64_to_cpu(olen);
	if (written < total_len) {
387 388 389 390 391
		if (atomic) {
			/* Should not happen */
			pr_warn("atomic console write returned partial "
				"len=%d written=%d\n", total_len, written);
		}
392 393
		if (!written)
			written = -EAGAIN;
394
	}
395 396

out:
397 398
	if (atomic)
		spin_unlock_irqrestore(&opal_write_lock, flags);
399 400 401 402

	return written;
}

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
int opal_put_chars(uint32_t vtermno, const char *data, int total_len)
{
	return __opal_put_chars(vtermno, data, total_len, false);
}

/*
 * opal_put_chars_atomic will not perform partial-writes. Data will be
 * atomically written to the terminal or not at all. This is not strictly
 * true at the moment because console space can race with OPAL's console
 * writes.
 */
int opal_put_chars_atomic(uint32_t vtermno, const char *data, int total_len)
{
	return __opal_put_chars(vtermno, data, total_len, true);
}

419
static s64 __opal_flush_console(uint32_t vtermno)
420 421 422 423 424 425 426 427 428 429 430
{
	s64 rc;

	if (!opal_check_token(OPAL_CONSOLE_FLUSH)) {
		__be64 evt;

		/*
		 * If OPAL_CONSOLE_FLUSH is not implemented in the firmware,
		 * the console can still be flushed by calling the polling
		 * function while it has OPAL_EVENT_CONSOLE_OUTPUT events.
		 */
431 432 433 434 435 436
		WARN_ONCE(1, "opal: OPAL_CONSOLE_FLUSH missing.\n");

		opal_poll_events(&evt);
		if (!(be64_to_cpu(evt) & OPAL_EVENT_CONSOLE_OUTPUT))
			return OPAL_SUCCESS;
		return OPAL_BUSY;
437

438 439 440 441 442 443 444
	} else {
		rc = opal_console_flush(vtermno);
		if (rc == OPAL_BUSY_EVENT) {
			opal_poll_events(NULL);
			rc = OPAL_BUSY;
		}
		return rc;
445
	}
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
}

/*
 * opal_flush_console spins until the console is flushed
 */
int opal_flush_console(uint32_t vtermno)
{
	for (;;) {
		s64 rc = __opal_flush_console(vtermno);

		if (rc == OPAL_BUSY || rc == OPAL_PARTIAL) {
			mdelay(1);
			continue;
		}

		return opal_error_code(rc);
	}
}

/*
 * opal_flush_chars is an hvc interface that sleeps until the console is
 * flushed if wait, otherwise it will return -EBUSY if the console has data,
 * -EAGAIN if it has data and some of it was flushed.
 */
int opal_flush_chars(uint32_t vtermno, bool wait)
{
	for (;;) {
		s64 rc = __opal_flush_console(vtermno);

		if (rc == OPAL_BUSY || rc == OPAL_PARTIAL) {
			if (wait) {
				msleep(OPAL_BUSY_DELAY_MS);
				continue;
480
			}
481 482
			if (rc == OPAL_PARTIAL)
				return -EAGAIN;
483 484
		}

485 486
		return opal_error_code(rc);
	}
487 488
}

489 490 491 492 493 494 495
static int opal_recover_mce(struct pt_regs *regs,
					struct machine_check_event *evt)
{
	int recovered = 0;

	if (!(regs->msr & MSR_RI)) {
		/* If MSR_RI isn't set, we cannot recover */
496
		pr_err("Machine check interrupt unrecoverable: MSR(RI=0)\n");
497 498 499 500
		recovered = 0;
	} else if (evt->disposition == MCE_DISPOSITION_RECOVERED) {
		/* Platform corrected itself */
		recovered = 1;
501 502 503 504
	} else if (evt->severity == MCE_SEV_FATAL) {
		/* Fatal machine check */
		pr_err("Machine check interrupt is fatal\n");
		recovered = 0;
505 506 507
	}

	if (!recovered && evt->severity == MCE_SEV_ERROR_SYNC) {
508
		/*
509 510 511 512
		 * Try to kill processes if we get a synchronous machine check
		 * (e.g., one caused by execution of this instruction). This
		 * will devolve into a panic if we try to kill init or are in
		 * an interrupt etc.
513 514
		 *
		 * TODO: Queue up this address for hwpoisioning later.
515 516 517
		 * TODO: This is not quite right for d-side machine
		 *       checks ->nip is not necessarily the important
		 *       address.
518
		 */
519 520 521 522 523 524 525 526 527 528 529 530 531 532
		if ((user_mode(regs))) {
			_exception(SIGBUS, regs, BUS_MCEERR_AR, regs->nip);
			recovered = 1;
		} else if (die_will_crash()) {
			/*
			 * die() would kill the kernel, so better to go via
			 * the platform reboot code that will log the
			 * machine check.
			 */
			recovered = 0;
		} else {
			die("Machine check", regs, SIGBUS);
			recovered = 1;
		}
533
	}
534

535 536 537
	return recovered;
}

538
void __noreturn pnv_platform_error_reboot(struct pt_regs *regs, const char *msg)
539
{
540 541
	panic_flush_kmsg_start();

542 543 544 545
	pr_emerg("Hardware platform error: %s\n", msg);
	if (regs)
		show_regs(regs);
	smp_send_stop();
546 547

	panic_flush_kmsg_end();
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

	/*
	 * Don't bother to shut things down because this will
	 * xstop the system.
	 */
	if (opal_cec_reboot2(OPAL_REBOOT_PLATFORM_ERROR, msg)
						== OPAL_UNSUPPORTED) {
		pr_emerg("Reboot type %d not supported for %s\n",
				OPAL_REBOOT_PLATFORM_ERROR, msg);
	}

	/*
	 * We reached here. There can be three possibilities:
	 * 1. We are running on a firmware level that do not support
	 *    opal_cec_reboot2()
	 * 2. We are running on a firmware level that do not support
	 *    OPAL_REBOOT_PLATFORM_ERROR reboot type.
	 * 3. We are running on FSP based system that does not need
	 *    opal to trigger checkstop explicitly for error analysis.
	 *    The FSP PRD component would have already got notified
	 *    about this error through other channels.
569 570 571
	 * 4. We are running on a newer skiboot that by default does
	 *    not cause a checkstop, drops us back to the kernel to
	 *    extract context and state at the time of the error.
572 573
	 */

574
	panic(msg);
575 576
}

577 578
int opal_machine_check(struct pt_regs *regs)
{
579
	struct machine_check_event evt;
580

581 582
	if (!get_mce_event(&evt, MCE_EVENT_RELEASE))
		return 0;
583 584

	/* Print things out */
585
	if (evt.version != MCE_V1) {
586 587 588 589
		pr_err("Machine Check Exception, Unknown event version %d !\n",
		       evt.version);
		return 0;
	}
590
	machine_check_print_event_info(&evt, user_mode(regs), false);
591

592 593
	if (opal_recover_mce(regs, &evt))
		return 1;
594

595
	pnv_platform_error_reboot(regs, "Unrecoverable Machine Check exception");
596 597
}

598 599 600
/* Early hmi handler called in real mode. */
int opal_hmi_exception_early(struct pt_regs *regs)
{
601 602 603 604 605 606 607 608 609 610 611 612
	s64 rc;

	/*
	 * call opal hmi handler. Pass paca address as token.
	 * The return value OPAL_SUCCESS is an indication that there is
	 * an HMI event generated waiting to pull by Linux.
	 */
	rc = opal_handle_hmi();
	if (rc == OPAL_SUCCESS) {
		local_paca->hmi_event_available = 1;
		return 1;
	}
613 614 615 616 617 618
	return 0;
}

/* HMI exception handler called in virtual mode during check_irq_replay. */
int opal_handle_hmi_exception(struct pt_regs *regs)
{
619 620
	/*
	 * Check if HMI event is available.
621
	 * if Yes, then wake kopald to process them.
622 623 624 625 626
	 */
	if (!local_paca->hmi_event_available)
		return 0;

	local_paca->hmi_event_available = 0;
627
	opal_wake_poller();
628 629

	return 1;
630 631
}

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
static uint64_t find_recovery_address(uint64_t nip)
{
	int i;

	for (i = 0; i < mc_recoverable_range_len; i++)
		if ((nip >= mc_recoverable_range[i].start_addr) &&
		    (nip < mc_recoverable_range[i].end_addr))
		    return mc_recoverable_range[i].recover_addr;
	return 0;
}

bool opal_mce_check_early_recovery(struct pt_regs *regs)
{
	uint64_t recover_addr = 0;

	if (!opal.base || !opal.size)
		goto out;

	if ((regs->nip >= opal.base) &&
651
			(regs->nip < (opal.base + opal.size)))
652 653 654 655 656 657 658 659 660 661 662 663
		recover_addr = find_recovery_address(regs->nip);

	/*
	 * Setup regs->nip to rfi into fixup address.
	 */
	if (recover_addr)
		regs->nip = recover_addr;

out:
	return !!recover_addr;
}

664 665 666 667 668 669 670 671 672 673 674
static int opal_sysfs_init(void)
{
	opal_kobj = kobject_create_and_add("opal", firmware_kobj);
	if (!opal_kobj) {
		pr_warn("kobject_create_and_add opal failed\n");
		return -ENOMEM;
	}

	return 0;
}

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
static ssize_t symbol_map_read(struct file *fp, struct kobject *kobj,
			       struct bin_attribute *bin_attr,
			       char *buf, loff_t off, size_t count)
{
	return memory_read_from_buffer(buf, count, &off, bin_attr->private,
				       bin_attr->size);
}

static BIN_ATTR_RO(symbol_map, 0);

static void opal_export_symmap(void)
{
	const __be64 *syms;
	unsigned int size;
	struct device_node *fw;
	int rc;

	fw = of_find_node_by_path("/ibm,opal/firmware");
	if (!fw)
		return;
	syms = of_get_property(fw, "symbol-map", &size);
	if (!syms || size != 2 * sizeof(__be64))
		return;

	/* Setup attributes */
	bin_attr_symbol_map.private = __va(be64_to_cpu(syms[0]));
	bin_attr_symbol_map.size = be64_to_cpu(syms[1]);

	rc = sysfs_create_bin_file(opal_kobj, &bin_attr_symbol_map);
	if (rc)
		pr_warn("Error %d creating OPAL symbols file\n", rc);
}

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
static ssize_t export_attr_read(struct file *fp, struct kobject *kobj,
				struct bin_attribute *bin_attr, char *buf,
				loff_t off, size_t count)
{
	return memory_read_from_buffer(buf, count, &off, bin_attr->private,
				       bin_attr->size);
}

/*
 * opal_export_attrs: creates a sysfs node for each property listed in
 * the device-tree under /ibm,opal/firmware/exports/
 * All new sysfs nodes are created under /opal/exports/.
 * This allows for reserved memory regions (e.g. HDAT) to be read.
 * The new sysfs nodes are only readable by root.
 */
static void opal_export_attrs(void)
{
	struct bin_attribute *attr;
	struct device_node *np;
	struct property *prop;
	struct kobject *kobj;
	u64 vals[2];
	int rc;

	np = of_find_node_by_path("/ibm,opal/firmware/exports");
	if (!np)
		return;

	/* Create new 'exports' directory - /sys/firmware/opal/exports */
	kobj = kobject_create_and_add("exports", opal_kobj);
	if (!kobj) {
		pr_warn("kobject_create_and_add() of exports failed\n");
		return;
	}

	for_each_property_of_node(np, prop) {
		if (!strcmp(prop->name, "name") || !strcmp(prop->name, "phandle"))
			continue;

		if (of_property_read_u64_array(np, prop->name, &vals[0], 2))
			continue;

750
		attr = kzalloc(sizeof(*attr), GFP_KERNEL);
751 752 753 754 755 756

		if (attr == NULL) {
			pr_warn("Failed kmalloc for bin_attribute!");
			continue;
		}

757
		sysfs_bin_attr_init(attr);
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
		attr->attr.name = kstrdup(prop->name, GFP_KERNEL);
		attr->attr.mode = 0400;
		attr->read = export_attr_read;
		attr->private = __va(vals[0]);
		attr->size = vals[1];

		if (attr->attr.name == NULL) {
			pr_warn("Failed kstrdup for bin_attribute attr.name");
			kfree(attr);
			continue;
		}

		rc = sysfs_create_bin_file(kobj, attr);
		if (rc) {
			pr_warn("Error %d creating OPAL sysfs exports/%s file\n",
				 rc, prop->name);
			kfree(attr->attr.name);
			kfree(attr);
		}
	}

	of_node_put(np);
}

782 783 784 785 786 787
static void __init opal_dump_region_init(void)
{
	void *addr;
	uint64_t size;
	int rc;

788 789 790
	if (!opal_check_token(OPAL_REGISTER_DUMP_REGION))
		return;

791 792
	/* Register kernel log buffer */
	addr = log_buf_addr_get();
793 794 795
	if (addr == NULL)
		return;

796
	size = log_buf_len_get();
797 798 799
	if (size == 0)
		return;

800 801 802 803 804 805 806 807 808
	rc = opal_register_dump_region(OPAL_DUMP_REGION_LOG_BUF,
				       __pa(addr), size);
	/* Don't warn if this is just an older OPAL that doesn't
	 * know about that call
	 */
	if (rc && rc != OPAL_UNSUPPORTED)
		pr_warn("DUMP: Failed to register kernel log buffer. "
			"rc = %d\n", rc);
}
809

810
static void opal_pdev_init(const char *compatible)
811 812 813
{
	struct device_node *np;

814
	for_each_compatible_node(np, NULL, compatible)
815 816 817
		of_platform_device_create(np, NULL, NULL);
}

818 819 820 821 822 823 824 825 826
static void __init opal_imc_init_dev(void)
{
	struct device_node *np;

	np = of_find_compatible_node(NULL, NULL, IMC_DTB_COMPAT);
	if (np)
		of_platform_device_create(np, NULL, NULL);
}

827 828
static int kopald(void *unused)
{
829
	unsigned long timeout = msecs_to_jiffies(opal_heartbeat) + 1;
830

831 832 833
	set_freezable();
	do {
		try_to_freeze();
834 835 836 837 838 839 840 841 842

		opal_handle_events();

		set_current_state(TASK_INTERRUPTIBLE);
		if (opal_have_pending_events())
			__set_current_state(TASK_RUNNING);
		else
			schedule_timeout(timeout);

843 844 845 846 847
	} while (!kthread_should_stop());

	return 0;
}

848 849 850 851 852 853
void opal_wake_poller(void)
{
	if (kopald_tsk)
		wake_up_process(kopald_tsk);
}

854 855 856 857 858 859 860 861
static void opal_init_heartbeat(void)
{
	/* Old firwmware, we assume the HVC heartbeat is sufficient */
	if (of_property_read_u32(opal_node, "ibm,heartbeat-ms",
				 &opal_heartbeat) != 0)
		opal_heartbeat = 0;

	if (opal_heartbeat)
862
		kopald_tsk = kthread_run(kopald, NULL, "kopald");
863 864
}

865 866
static int __init opal_init(void)
{
867
	struct device_node *np, *consoles, *leds;
868
	int rc;
869 870 871

	opal_node = of_find_node_by_path("/ibm,opal");
	if (!opal_node) {
872
		pr_warn("Device node not found\n");
873 874
		return -ENODEV;
	}
875 876

	/* Register OPAL consoles if any ports */
877
	consoles = of_find_node_by_path("/ibm,opal/consoles");
878 879
	if (consoles) {
		for_each_child_of_node(consoles, np) {
880
			if (!of_node_name_eq(np, "serial"))
881 882 883 884
				continue;
			of_platform_device_create(np, NULL, NULL);
		}
		of_node_put(consoles);
885
	}
886

887 888 889 890 891 892 893 894 895 896 897 898
	/* Initialise OPAL messaging system */
	opal_message_init();

	/* Initialise OPAL asynchronous completion interface */
	opal_async_comp_init();

	/* Initialise OPAL sensor interface */
	opal_sensor_init();

	/* Initialise OPAL hypervisor maintainence interrupt handling */
	opal_hmi_handler_init();

899
	/* Create i2c platform devices */
900
	opal_pdev_init("ibm,opal-i2c");
901

902 903 904
	/* Handle non-volatile memory devices */
	opal_pdev_init("pmem-region");

905 906 907
	/* Setup a heatbeat thread if requested by OPAL */
	opal_init_heartbeat();

908 909 910
	/* Detect In-Memory Collection counters and create devices*/
	opal_imc_init_dev();

911 912 913 914 915 916 917
	/* Create leds platform devices */
	leds = of_find_node_by_path("/ibm,opal/leds");
	if (leds) {
		of_platform_device_create(leds, "opal_leds", NULL);
		of_node_put(leds);
	}

918 919 920
	/* Initialise OPAL message log interface */
	opal_msglog_init();

921 922
	/* Create "opal" kobject under /sys/firmware */
	rc = opal_sysfs_init();
923
	if (rc == 0) {
924 925
		/* Export symbol map to userspace */
		opal_export_symmap();
926 927
		/* Setup dump region interface */
		opal_dump_region_init();
928 929
		/* Setup error log interface */
		rc = opal_elog_init();
930
		/* Setup code update interface */
931
		opal_flash_update_init();
932 933
		/* Setup platform dump extract interface */
		opal_platform_dump_init();
934 935
		/* Setup system parameters interface */
		opal_sys_param_init();
936 937
		/* Setup message log sysfs interface. */
		opal_msglog_sysfs_init();
938
	}
939

940 941 942
	/* Export all properties */
	opal_export_attrs();

943
	/* Initialize platform devices: IPMI backend, PRD & flash interface */
944 945 946
	opal_pdev_init("ibm,opal-ipmi");
	opal_pdev_init("ibm,opal-flash");
	opal_pdev_init("ibm,opal-prd");
947

948
	/* Initialise platform device: oppanel interface */
949
	opal_pdev_init("ibm,opal-oppanel");
950

951 952 953
	/* Initialise OPAL kmsg dumper for flushing console on panic */
	opal_kmsg_init();

954 955 956
	/* Initialise OPAL powercap interface */
	opal_powercap_init();

957 958 959
	/* Initialise OPAL Power-Shifting-Ratio interface */
	opal_psr_init();

960 961 962
	/* Initialise OPAL sensor groups */
	opal_sensor_groups_init();

963 964 965
	/* Initialise OPAL Power control interface */
	opal_power_control_init();

966 967
	return 0;
}
968
machine_subsys_initcall(powernv, opal_init);
969 970 971

void opal_shutdown(void)
{
972
	long rc = OPAL_BUSY;
973

974
	opal_event_shutdown();
975 976 977 978 979 980 981 982 983 984 985 986 987

	/*
	 * Then sync with OPAL which ensure anything that can
	 * potentially write to our memory has completed such
	 * as an ongoing dump retrieval
	 */
	while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) {
		rc = opal_sync_host_reboot();
		if (rc == OPAL_BUSY)
			opal_poll_events(NULL);
		else
			mdelay(10);
	}
988 989

	/* Unregister memory dump region */
990 991
	if (opal_check_token(OPAL_UNREGISTER_DUMP_REGION))
		opal_unregister_dump_region(OPAL_DUMP_REGION_LOG_BUF);
992
}
993 994 995

/* Export this so that test modules can use it */
EXPORT_SYMBOL_GPL(opal_invalid_call);
996 997
EXPORT_SYMBOL_GPL(opal_xscom_read);
EXPORT_SYMBOL_GPL(opal_xscom_write);
998 999
EXPORT_SYMBOL_GPL(opal_ipmi_send);
EXPORT_SYMBOL_GPL(opal_ipmi_recv);
1000 1001 1002
EXPORT_SYMBOL_GPL(opal_flash_read);
EXPORT_SYMBOL_GPL(opal_flash_write);
EXPORT_SYMBOL_GPL(opal_flash_erase);
1003
EXPORT_SYMBOL_GPL(opal_prd_msg);
1004
EXPORT_SYMBOL_GPL(opal_check_token);
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

/* Convert a region of vmalloc memory to an opal sg list */
struct opal_sg_list *opal_vmalloc_to_sg_list(void *vmalloc_addr,
					     unsigned long vmalloc_size)
{
	struct opal_sg_list *sg, *first = NULL;
	unsigned long i = 0;

	sg = kzalloc(PAGE_SIZE, GFP_KERNEL);
	if (!sg)
		goto nomem;

	first = sg;

	while (vmalloc_size > 0) {
		uint64_t data = vmalloc_to_pfn(vmalloc_addr) << PAGE_SHIFT;
		uint64_t length = min(vmalloc_size, PAGE_SIZE);

		sg->entry[i].data = cpu_to_be64(data);
		sg->entry[i].length = cpu_to_be64(length);
		i++;

		if (i >= SG_ENTRIES_PER_NODE) {
			struct opal_sg_list *next;

			next = kzalloc(PAGE_SIZE, GFP_KERNEL);
			if (!next)
				goto nomem;

			sg->length = cpu_to_be64(
					i * sizeof(struct opal_sg_entry) + 16);
			i = 0;
			sg->next = cpu_to_be64(__pa(next));
			sg = next;
		}

		vmalloc_addr += length;
		vmalloc_size -= length;
	}

	sg->length = cpu_to_be64(i * sizeof(struct opal_sg_entry) + 16);

	return first;

nomem:
	pr_err("%s : Failed to allocate memory\n", __func__);
	opal_free_sg_list(first);
	return NULL;
}

void opal_free_sg_list(struct opal_sg_list *sg)
{
	while (sg) {
		uint64_t next = be64_to_cpu(sg->next);

		kfree(sg);

		if (next)
			sg = __va(next);
		else
			sg = NULL;
	}
}
1068

1069 1070 1071 1072 1073 1074 1075
int opal_error_code(int rc)
{
	switch (rc) {
	case OPAL_SUCCESS:		return 0;

	case OPAL_PARAMETER:		return -EINVAL;
	case OPAL_ASYNC_COMPLETION:	return -EINPROGRESS;
1076
	case OPAL_BUSY:
1077 1078
	case OPAL_BUSY_EVENT:		return -EBUSY;
	case OPAL_NO_MEM:		return -ENOMEM;
1079
	case OPAL_PERMISSION:		return -EPERM;
1080 1081 1082 1083

	case OPAL_UNSUPPORTED:		return -EIO;
	case OPAL_HARDWARE:		return -EIO;
	case OPAL_INTERNAL_ERROR:	return -EIO;
1084
	case OPAL_TIMEOUT:		return -ETIMEDOUT;
1085 1086 1087 1088 1089 1090
	default:
		pr_err("%s: unexpected OPAL error %d\n", __func__, rc);
		return -EIO;
	}
}

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
void powernv_set_nmmu_ptcr(unsigned long ptcr)
{
	int rc;

	if (firmware_has_feature(FW_FEATURE_OPAL)) {
		rc = opal_nmmu_set_ptcr(-1UL, ptcr);
		if (rc != OPAL_SUCCESS && rc != OPAL_UNSUPPORTED)
			pr_warn("%s: Unable to set nest mmu ptcr\n", __func__);
	}
}

1102 1103 1104 1105 1106
EXPORT_SYMBOL_GPL(opal_poll_events);
EXPORT_SYMBOL_GPL(opal_rtc_read);
EXPORT_SYMBOL_GPL(opal_rtc_write);
EXPORT_SYMBOL_GPL(opal_tpo_read);
EXPORT_SYMBOL_GPL(opal_tpo_write);
1107
EXPORT_SYMBOL_GPL(opal_i2c_request);
1108 1109 1110
/* Export these symbols for PowerNV LED class driver */
EXPORT_SYMBOL_GPL(opal_leds_get_ind);
EXPORT_SYMBOL_GPL(opal_leds_set_ind);
1111 1112
/* Export this symbol for PowerNV Operator Panel class driver */
EXPORT_SYMBOL_GPL(opal_write_oppanel_async);
1113 1114
/* Export this for KVM */
EXPORT_SYMBOL_GPL(opal_int_set_mfrr);
1115
EXPORT_SYMBOL_GPL(opal_int_eoi);
1116
EXPORT_SYMBOL_GPL(opal_error_code);
1117 1118
/* Export the below symbol for NX compression */
EXPORT_SYMBOL(opal_nx_coproc_init);