1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  c 2001 PPC 64 Team, IBM Corp
4  *
5  * /dev/nvram driver for PPC
6  */
7 
8 #include <linux/kernel.h>
9 #include <linux/module.h>
10 #include <linux/init.h>
11 #include <linux/spinlock.h>
12 #include <linux/uaccess.h>
13 #include <asm/prom.h>
14 #include <asm/machdep.h>
15 #include <asm/rtas.h>
16 #include "chrp.h"
17 
18 static unsigned int nvram_size;
19 static unsigned char nvram_buf[4];
20 static DEFINE_SPINLOCK(nvram_lock);
21 
chrp_nvram_read_val(int addr)22 static unsigned char chrp_nvram_read_val(int addr)
23 {
24 	unsigned int done;
25 	unsigned long flags;
26 	unsigned char ret;
27 
28 	if (addr >= nvram_size) {
29 		printk(KERN_DEBUG "%s: read addr %d > nvram_size %u\n",
30 		       current->comm, addr, nvram_size);
31 		return 0xff;
32 	}
33 	spin_lock_irqsave(&nvram_lock, flags);
34 	if ((rtas_call(rtas_token("nvram-fetch"), 3, 2, &done, addr,
35 		       __pa(nvram_buf), 1) != 0) || 1 != done)
36 		ret = 0xff;
37 	else
38 		ret = nvram_buf[0];
39 	spin_unlock_irqrestore(&nvram_lock, flags);
40 
41 	return ret;
42 }
43 
chrp_nvram_write_val(int addr,unsigned char val)44 static void chrp_nvram_write_val(int addr, unsigned char val)
45 {
46 	unsigned int done;
47 	unsigned long flags;
48 
49 	if (addr >= nvram_size) {
50 		printk(KERN_DEBUG "%s: write addr %d > nvram_size %u\n",
51 		       current->comm, addr, nvram_size);
52 		return;
53 	}
54 	spin_lock_irqsave(&nvram_lock, flags);
55 	nvram_buf[0] = val;
56 	if ((rtas_call(rtas_token("nvram-store"), 3, 2, &done, addr,
57 		       __pa(nvram_buf), 1) != 0) || 1 != done)
58 		printk(KERN_DEBUG "rtas IO error storing 0x%02x at %d", val, addr);
59 	spin_unlock_irqrestore(&nvram_lock, flags);
60 }
61 
chrp_nvram_size(void)62 static ssize_t chrp_nvram_size(void)
63 {
64 	return nvram_size;
65 }
66 
chrp_nvram_init(void)67 void __init chrp_nvram_init(void)
68 {
69 	struct device_node *nvram;
70 	const __be32 *nbytes_p;
71 	unsigned int proplen;
72 
73 	nvram = of_find_node_by_type(NULL, "nvram");
74 	if (nvram == NULL)
75 		return;
76 
77 	nbytes_p = of_get_property(nvram, "#bytes", &proplen);
78 	if (nbytes_p == NULL || proplen != sizeof(unsigned int)) {
79 		of_node_put(nvram);
80 		return;
81 	}
82 
83 	nvram_size = be32_to_cpup(nbytes_p);
84 
85 	printk(KERN_INFO "CHRP nvram contains %u bytes\n", nvram_size);
86 	of_node_put(nvram);
87 
88 	ppc_md.nvram_read_val  = chrp_nvram_read_val;
89 	ppc_md.nvram_write_val = chrp_nvram_write_val;
90 	ppc_md.nvram_size      = chrp_nvram_size;
91 
92 	return;
93 }
94 
95 MODULE_LICENSE("GPL v2");
96