1
2
3
4
5
6
7
8
9#include <linux/idr.h>
10#include <linux/slab.h>
11#include <linux/vmalloc.h>
12
13#include "tb.h"
14
15static DEFINE_IDA(nvm_ida);
16
17
18
19
20
21
22
23
24struct tb_nvm *tb_nvm_alloc(struct device *dev)
25{
26 struct tb_nvm *nvm;
27 int ret;
28
29 nvm = kzalloc(sizeof(*nvm), GFP_KERNEL);
30 if (!nvm)
31 return ERR_PTR(-ENOMEM);
32
33 ret = ida_simple_get(&nvm_ida, 0, 0, GFP_KERNEL);
34 if (ret < 0) {
35 kfree(nvm);
36 return ERR_PTR(ret);
37 }
38
39 nvm->id = ret;
40 nvm->dev = dev;
41
42 return nvm;
43}
44
45
46
47
48
49
50
51
52
53
54
55
56
57int tb_nvm_add_active(struct tb_nvm *nvm, size_t size, nvmem_reg_read_t reg_read)
58{
59 struct nvmem_config config;
60 struct nvmem_device *nvmem;
61
62 memset(&config, 0, sizeof(config));
63
64 config.name = "nvm_active";
65 config.reg_read = reg_read;
66 config.read_only = true;
67 config.id = nvm->id;
68 config.stride = 4;
69 config.word_size = 4;
70 config.size = size;
71 config.dev = nvm->dev;
72 config.owner = THIS_MODULE;
73 config.priv = nvm;
74
75 nvmem = nvmem_register(&config);
76 if (IS_ERR(nvmem))
77 return PTR_ERR(nvmem);
78
79 nvm->active = nvmem;
80 return 0;
81}
82
83
84
85
86
87
88
89
90
91
92
93
94int tb_nvm_write_buf(struct tb_nvm *nvm, unsigned int offset, void *val,
95 size_t bytes)
96{
97 if (!nvm->buf) {
98 nvm->buf = vmalloc(NVM_MAX_SIZE);
99 if (!nvm->buf)
100 return -ENOMEM;
101 }
102
103 nvm->flushed = false;
104 nvm->buf_data_size = offset + bytes;
105 memcpy(nvm->buf + offset, val, bytes);
106 return 0;
107}
108
109
110
111
112
113
114
115
116
117
118
119
120
121int tb_nvm_add_non_active(struct tb_nvm *nvm, size_t size,
122 nvmem_reg_write_t reg_write)
123{
124 struct nvmem_config config;
125 struct nvmem_device *nvmem;
126
127 memset(&config, 0, sizeof(config));
128
129 config.name = "nvm_non_active";
130 config.reg_write = reg_write;
131 config.root_only = true;
132 config.id = nvm->id;
133 config.stride = 4;
134 config.word_size = 4;
135 config.size = size;
136 config.dev = nvm->dev;
137 config.owner = THIS_MODULE;
138 config.priv = nvm;
139
140 nvmem = nvmem_register(&config);
141 if (IS_ERR(nvmem))
142 return PTR_ERR(nvmem);
143
144 nvm->non_active = nvmem;
145 return 0;
146}
147
148
149
150
151
152
153
154void tb_nvm_free(struct tb_nvm *nvm)
155{
156 if (nvm) {
157 if (nvm->non_active)
158 nvmem_unregister(nvm->non_active);
159 if (nvm->active)
160 nvmem_unregister(nvm->active);
161 vfree(nvm->buf);
162 ida_simple_remove(&nvm_ida, nvm->id);
163 }
164 kfree(nvm);
165}
166
167void tb_nvm_exit(void)
168{
169 ida_destroy(&nvm_ida);
170}
171