1 /*
2  * PowerNV nvram code.
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 DEBUG
13 
14 #include <linux/delay.h>
15 #include <linux/kernel.h>
16 #include <linux/init.h>
17 #include <linux/of.h>
18 
19 #include <asm/opal.h>
20 #include <asm/nvram.h>
21 #include <asm/machdep.h>
22 
23 static unsigned int nvram_size;
24 
25 static ssize_t opal_nvram_size(void)
26 {
27 	return nvram_size;
28 }
29 
30 static ssize_t opal_nvram_read(char *buf, size_t count, loff_t *index)
31 {
32 	s64 rc;
33 	int off;
34 
35 	if (*index >= nvram_size)
36 		return 0;
37 	off = *index;
38 	if ((off + count) > nvram_size)
39 		count = nvram_size - off;
40 	rc = opal_read_nvram(__pa(buf), count, off);
41 	if (rc != OPAL_SUCCESS)
42 		return -EIO;
43 	*index += count;
44 	return count;
45 }
46 
47 /*
48  * This can be called in the panic path with interrupts off, so use
49  * mdelay in that case.
50  */
51 static ssize_t opal_nvram_write(char *buf, size_t count, loff_t *index)
52 {
53 	s64 rc = OPAL_BUSY;
54 	int off;
55 
56 	if (*index >= nvram_size)
57 		return 0;
58 	off = *index;
59 	if ((off + count) > nvram_size)
60 		count = nvram_size - off;
61 
62 	while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) {
63 		rc = opal_write_nvram(__pa(buf), count, off);
64 		if (rc == OPAL_BUSY_EVENT) {
65 			if (in_interrupt() || irqs_disabled())
66 				mdelay(OPAL_BUSY_DELAY_MS);
67 			else
68 				msleep(OPAL_BUSY_DELAY_MS);
69 			opal_poll_events(NULL);
70 		} else if (rc == OPAL_BUSY) {
71 			if (in_interrupt() || irqs_disabled())
72 				mdelay(OPAL_BUSY_DELAY_MS);
73 			else
74 				msleep(OPAL_BUSY_DELAY_MS);
75 		}
76 	}
77 
78 	if (rc)
79 		return -EIO;
80 
81 	*index += count;
82 	return count;
83 }
84 
85 static int __init opal_nvram_init_log_partitions(void)
86 {
87 	/* Scan nvram for partitions */
88 	nvram_scan_partitions();
89 	nvram_init_oops_partition(0);
90 	return 0;
91 }
92 machine_arch_initcall(powernv, opal_nvram_init_log_partitions);
93 
94 void __init opal_nvram_init(void)
95 {
96 	struct device_node *np;
97 	const __be32 *nbytes_p;
98 
99 	np = of_find_compatible_node(NULL, NULL, "ibm,opal-nvram");
100 	if (np == NULL)
101 		return;
102 
103 	nbytes_p = of_get_property(np, "#bytes", NULL);
104 	if (!nbytes_p) {
105 		of_node_put(np);
106 		return;
107 	}
108 	nvram_size = be32_to_cpup(nbytes_p);
109 
110 	pr_info("OPAL nvram setup, %u bytes\n", nvram_size);
111 	of_node_put(np);
112 
113 	ppc_md.nvram_read = opal_nvram_read;
114 	ppc_md.nvram_write = opal_nvram_write;
115 	ppc_md.nvram_size = opal_nvram_size;
116 }
117 
118