xref: /linux/drivers/nvmem/core.c (revision 87292bca01f7ff815ada3c209a8f785ad3c79d29)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * nvmem framework core.
4  *
5  * Copyright (C) 2015 Srinivas Kandagatla <srinivas.kandagatla@linaro.org>
6  * Copyright (C) 2013 Maxime Ripard <maxime.ripard@free-electrons.com>
7  */
8 
9 #include <linux/device.h>
10 #include <linux/export.h>
11 #include <linux/fs.h>
12 #include <linux/idr.h>
13 #include <linux/init.h>
14 #include <linux/kref.h>
15 #include <linux/module.h>
16 #include <linux/nvmem-consumer.h>
17 #include <linux/nvmem-provider.h>
18 #include <linux/gpio/consumer.h>
19 #include <linux/of.h>
20 #include <linux/slab.h>
21 #include "nvmem.h"
22 
23 struct nvmem_cell {
24 	const char		*name;
25 	int			offset;
26 	int			bytes;
27 	int			bit_offset;
28 	int			nbits;
29 	struct device_node	*np;
30 	struct nvmem_device	*nvmem;
31 	struct list_head	node;
32 };
33 
34 static DEFINE_MUTEX(nvmem_mutex);
35 static DEFINE_IDA(nvmem_ida);
36 
37 static DEFINE_MUTEX(nvmem_cell_mutex);
38 static LIST_HEAD(nvmem_cell_tables);
39 
40 static DEFINE_MUTEX(nvmem_lookup_mutex);
41 static LIST_HEAD(nvmem_lookup_list);
42 
43 static BLOCKING_NOTIFIER_HEAD(nvmem_notifier);
44 
45 
46 static int nvmem_reg_read(struct nvmem_device *nvmem, unsigned int offset,
47 			  void *val, size_t bytes)
48 {
49 	if (nvmem->reg_read)
50 		return nvmem->reg_read(nvmem->priv, offset, val, bytes);
51 
52 	return -EINVAL;
53 }
54 
55 static int nvmem_reg_write(struct nvmem_device *nvmem, unsigned int offset,
56 			   void *val, size_t bytes)
57 {
58 	int ret;
59 
60 	if (nvmem->reg_write) {
61 		gpiod_set_value_cansleep(nvmem->wp_gpio, 0);
62 		ret = nvmem->reg_write(nvmem->priv, offset, val, bytes);
63 		gpiod_set_value_cansleep(nvmem->wp_gpio, 1);
64 		return ret;
65 	}
66 
67 	return -EINVAL;
68 }
69 
70 static void nvmem_release(struct device *dev)
71 {
72 	struct nvmem_device *nvmem = to_nvmem_device(dev);
73 
74 	ida_simple_remove(&nvmem_ida, nvmem->id);
75 	gpiod_put(nvmem->wp_gpio);
76 	kfree(nvmem);
77 }
78 
79 static const struct device_type nvmem_provider_type = {
80 	.release	= nvmem_release,
81 };
82 
83 static struct bus_type nvmem_bus_type = {
84 	.name		= "nvmem",
85 };
86 
87 static void nvmem_cell_drop(struct nvmem_cell *cell)
88 {
89 	blocking_notifier_call_chain(&nvmem_notifier, NVMEM_CELL_REMOVE, cell);
90 	mutex_lock(&nvmem_mutex);
91 	list_del(&cell->node);
92 	mutex_unlock(&nvmem_mutex);
93 	of_node_put(cell->np);
94 	kfree_const(cell->name);
95 	kfree(cell);
96 }
97 
98 static void nvmem_device_remove_all_cells(const struct nvmem_device *nvmem)
99 {
100 	struct nvmem_cell *cell, *p;
101 
102 	list_for_each_entry_safe(cell, p, &nvmem->cells, node)
103 		nvmem_cell_drop(cell);
104 }
105 
106 static void nvmem_cell_add(struct nvmem_cell *cell)
107 {
108 	mutex_lock(&nvmem_mutex);
109 	list_add_tail(&cell->node, &cell->nvmem->cells);
110 	mutex_unlock(&nvmem_mutex);
111 	blocking_notifier_call_chain(&nvmem_notifier, NVMEM_CELL_ADD, cell);
112 }
113 
114 static int nvmem_cell_info_to_nvmem_cell(struct nvmem_device *nvmem,
115 				   const struct nvmem_cell_info *info,
116 				   struct nvmem_cell *cell)
117 {
118 	cell->nvmem = nvmem;
119 	cell->offset = info->offset;
120 	cell->bytes = info->bytes;
121 	cell->name = kstrdup_const(info->name, GFP_KERNEL);
122 	if (!cell->name)
123 		return -ENOMEM;
124 
125 	cell->bit_offset = info->bit_offset;
126 	cell->nbits = info->nbits;
127 
128 	if (cell->nbits)
129 		cell->bytes = DIV_ROUND_UP(cell->nbits + cell->bit_offset,
130 					   BITS_PER_BYTE);
131 
132 	if (!IS_ALIGNED(cell->offset, nvmem->stride)) {
133 		dev_err(&nvmem->dev,
134 			"cell %s unaligned to nvmem stride %d\n",
135 			cell->name, nvmem->stride);
136 		return -EINVAL;
137 	}
138 
139 	return 0;
140 }
141 
142 /**
143  * nvmem_add_cells() - Add cell information to an nvmem device
144  *
145  * @nvmem: nvmem device to add cells to.
146  * @info: nvmem cell info to add to the device
147  * @ncells: number of cells in info
148  *
149  * Return: 0 or negative error code on failure.
150  */
151 static int nvmem_add_cells(struct nvmem_device *nvmem,
152 		    const struct nvmem_cell_info *info,
153 		    int ncells)
154 {
155 	struct nvmem_cell **cells;
156 	int i, rval;
157 
158 	cells = kcalloc(ncells, sizeof(*cells), GFP_KERNEL);
159 	if (!cells)
160 		return -ENOMEM;
161 
162 	for (i = 0; i < ncells; i++) {
163 		cells[i] = kzalloc(sizeof(**cells), GFP_KERNEL);
164 		if (!cells[i]) {
165 			rval = -ENOMEM;
166 			goto err;
167 		}
168 
169 		rval = nvmem_cell_info_to_nvmem_cell(nvmem, &info[i], cells[i]);
170 		if (rval) {
171 			kfree(cells[i]);
172 			goto err;
173 		}
174 
175 		nvmem_cell_add(cells[i]);
176 	}
177 
178 	/* remove tmp array */
179 	kfree(cells);
180 
181 	return 0;
182 err:
183 	while (i--)
184 		nvmem_cell_drop(cells[i]);
185 
186 	kfree(cells);
187 
188 	return rval;
189 }
190 
191 /**
192  * nvmem_register_notifier() - Register a notifier block for nvmem events.
193  *
194  * @nb: notifier block to be called on nvmem events.
195  *
196  * Return: 0 on success, negative error number on failure.
197  */
198 int nvmem_register_notifier(struct notifier_block *nb)
199 {
200 	return blocking_notifier_chain_register(&nvmem_notifier, nb);
201 }
202 EXPORT_SYMBOL_GPL(nvmem_register_notifier);
203 
204 /**
205  * nvmem_unregister_notifier() - Unregister a notifier block for nvmem events.
206  *
207  * @nb: notifier block to be unregistered.
208  *
209  * Return: 0 on success, negative error number on failure.
210  */
211 int nvmem_unregister_notifier(struct notifier_block *nb)
212 {
213 	return blocking_notifier_chain_unregister(&nvmem_notifier, nb);
214 }
215 EXPORT_SYMBOL_GPL(nvmem_unregister_notifier);
216 
217 static int nvmem_add_cells_from_table(struct nvmem_device *nvmem)
218 {
219 	const struct nvmem_cell_info *info;
220 	struct nvmem_cell_table *table;
221 	struct nvmem_cell *cell;
222 	int rval = 0, i;
223 
224 	mutex_lock(&nvmem_cell_mutex);
225 	list_for_each_entry(table, &nvmem_cell_tables, node) {
226 		if (strcmp(nvmem_dev_name(nvmem), table->nvmem_name) == 0) {
227 			for (i = 0; i < table->ncells; i++) {
228 				info = &table->cells[i];
229 
230 				cell = kzalloc(sizeof(*cell), GFP_KERNEL);
231 				if (!cell) {
232 					rval = -ENOMEM;
233 					goto out;
234 				}
235 
236 				rval = nvmem_cell_info_to_nvmem_cell(nvmem,
237 								     info,
238 								     cell);
239 				if (rval) {
240 					kfree(cell);
241 					goto out;
242 				}
243 
244 				nvmem_cell_add(cell);
245 			}
246 		}
247 	}
248 
249 out:
250 	mutex_unlock(&nvmem_cell_mutex);
251 	return rval;
252 }
253 
254 static struct nvmem_cell *
255 nvmem_find_cell_by_name(struct nvmem_device *nvmem, const char *cell_id)
256 {
257 	struct nvmem_cell *iter, *cell = NULL;
258 
259 	mutex_lock(&nvmem_mutex);
260 	list_for_each_entry(iter, &nvmem->cells, node) {
261 		if (strcmp(cell_id, iter->name) == 0) {
262 			cell = iter;
263 			break;
264 		}
265 	}
266 	mutex_unlock(&nvmem_mutex);
267 
268 	return cell;
269 }
270 
271 static int nvmem_add_cells_from_of(struct nvmem_device *nvmem)
272 {
273 	struct device_node *parent, *child;
274 	struct device *dev = &nvmem->dev;
275 	struct nvmem_cell *cell;
276 	const __be32 *addr;
277 	int len;
278 
279 	parent = dev->of_node;
280 
281 	for_each_child_of_node(parent, child) {
282 		addr = of_get_property(child, "reg", &len);
283 		if (!addr || (len < 2 * sizeof(u32))) {
284 			dev_err(dev, "nvmem: invalid reg on %pOF\n", child);
285 			return -EINVAL;
286 		}
287 
288 		cell = kzalloc(sizeof(*cell), GFP_KERNEL);
289 		if (!cell)
290 			return -ENOMEM;
291 
292 		cell->nvmem = nvmem;
293 		cell->np = of_node_get(child);
294 		cell->offset = be32_to_cpup(addr++);
295 		cell->bytes = be32_to_cpup(addr);
296 		cell->name = kasprintf(GFP_KERNEL, "%pOFn", child);
297 
298 		addr = of_get_property(child, "bits", &len);
299 		if (addr && len == (2 * sizeof(u32))) {
300 			cell->bit_offset = be32_to_cpup(addr++);
301 			cell->nbits = be32_to_cpup(addr);
302 		}
303 
304 		if (cell->nbits)
305 			cell->bytes = DIV_ROUND_UP(
306 					cell->nbits + cell->bit_offset,
307 					BITS_PER_BYTE);
308 
309 		if (!IS_ALIGNED(cell->offset, nvmem->stride)) {
310 			dev_err(dev, "cell %s unaligned to nvmem stride %d\n",
311 				cell->name, nvmem->stride);
312 			/* Cells already added will be freed later. */
313 			kfree_const(cell->name);
314 			kfree(cell);
315 			return -EINVAL;
316 		}
317 
318 		nvmem_cell_add(cell);
319 	}
320 
321 	return 0;
322 }
323 
324 /**
325  * nvmem_register() - Register a nvmem device for given nvmem_config.
326  * Also creates an binary entry in /sys/bus/nvmem/devices/dev-name/nvmem
327  *
328  * @config: nvmem device configuration with which nvmem device is created.
329  *
330  * Return: Will be an ERR_PTR() on error or a valid pointer to nvmem_device
331  * on success.
332  */
333 
334 struct nvmem_device *nvmem_register(const struct nvmem_config *config)
335 {
336 	struct nvmem_device *nvmem;
337 	int rval;
338 
339 	if (!config->dev)
340 		return ERR_PTR(-EINVAL);
341 
342 	if (!config->reg_read && !config->reg_write)
343 		return ERR_PTR(-EINVAL);
344 
345 	nvmem = kzalloc(sizeof(*nvmem), GFP_KERNEL);
346 	if (!nvmem)
347 		return ERR_PTR(-ENOMEM);
348 
349 	rval  = ida_simple_get(&nvmem_ida, 0, 0, GFP_KERNEL);
350 	if (rval < 0) {
351 		kfree(nvmem);
352 		return ERR_PTR(rval);
353 	}
354 
355 	if (config->wp_gpio)
356 		nvmem->wp_gpio = config->wp_gpio;
357 	else
358 		nvmem->wp_gpio = gpiod_get_optional(config->dev, "wp",
359 						    GPIOD_OUT_HIGH);
360 	if (IS_ERR(nvmem->wp_gpio)) {
361 		ida_simple_remove(&nvmem_ida, nvmem->id);
362 		rval = PTR_ERR(nvmem->wp_gpio);
363 		kfree(nvmem);
364 		return ERR_PTR(rval);
365 	}
366 
367 	kref_init(&nvmem->refcnt);
368 	INIT_LIST_HEAD(&nvmem->cells);
369 
370 	nvmem->id = rval;
371 	nvmem->owner = config->owner;
372 	if (!nvmem->owner && config->dev->driver)
373 		nvmem->owner = config->dev->driver->owner;
374 	nvmem->stride = config->stride ?: 1;
375 	nvmem->word_size = config->word_size ?: 1;
376 	nvmem->size = config->size;
377 	nvmem->dev.type = &nvmem_provider_type;
378 	nvmem->dev.bus = &nvmem_bus_type;
379 	nvmem->dev.parent = config->dev;
380 	nvmem->priv = config->priv;
381 	nvmem->type = config->type;
382 	nvmem->reg_read = config->reg_read;
383 	nvmem->reg_write = config->reg_write;
384 	if (!config->no_of_node)
385 		nvmem->dev.of_node = config->dev->of_node;
386 
387 	if (config->id == -1 && config->name) {
388 		dev_set_name(&nvmem->dev, "%s", config->name);
389 	} else {
390 		dev_set_name(&nvmem->dev, "%s%d",
391 			     config->name ? : "nvmem",
392 			     config->name ? config->id : nvmem->id);
393 	}
394 
395 	nvmem->read_only = device_property_present(config->dev, "read-only") ||
396 			   config->read_only || !nvmem->reg_write;
397 
398 	nvmem->dev.groups = nvmem_sysfs_get_groups(nvmem, config);
399 
400 	device_initialize(&nvmem->dev);
401 
402 	dev_dbg(&nvmem->dev, "Registering nvmem device %s\n", config->name);
403 
404 	rval = device_add(&nvmem->dev);
405 	if (rval)
406 		goto err_put_device;
407 
408 	if (config->compat) {
409 		rval = nvmem_sysfs_setup_compat(nvmem, config);
410 		if (rval)
411 			goto err_device_del;
412 	}
413 
414 	if (config->cells) {
415 		rval = nvmem_add_cells(nvmem, config->cells, config->ncells);
416 		if (rval)
417 			goto err_teardown_compat;
418 	}
419 
420 	rval = nvmem_add_cells_from_table(nvmem);
421 	if (rval)
422 		goto err_remove_cells;
423 
424 	rval = nvmem_add_cells_from_of(nvmem);
425 	if (rval)
426 		goto err_remove_cells;
427 
428 	blocking_notifier_call_chain(&nvmem_notifier, NVMEM_ADD, nvmem);
429 
430 	return nvmem;
431 
432 err_remove_cells:
433 	nvmem_device_remove_all_cells(nvmem);
434 err_teardown_compat:
435 	if (config->compat)
436 		nvmem_sysfs_remove_compat(nvmem, config);
437 err_device_del:
438 	device_del(&nvmem->dev);
439 err_put_device:
440 	put_device(&nvmem->dev);
441 
442 	return ERR_PTR(rval);
443 }
444 EXPORT_SYMBOL_GPL(nvmem_register);
445 
446 static void nvmem_device_release(struct kref *kref)
447 {
448 	struct nvmem_device *nvmem;
449 
450 	nvmem = container_of(kref, struct nvmem_device, refcnt);
451 
452 	blocking_notifier_call_chain(&nvmem_notifier, NVMEM_REMOVE, nvmem);
453 
454 	if (nvmem->flags & FLAG_COMPAT)
455 		device_remove_bin_file(nvmem->base_dev, &nvmem->eeprom);
456 
457 	nvmem_device_remove_all_cells(nvmem);
458 	device_del(&nvmem->dev);
459 	put_device(&nvmem->dev);
460 }
461 
462 /**
463  * nvmem_unregister() - Unregister previously registered nvmem device
464  *
465  * @nvmem: Pointer to previously registered nvmem device.
466  */
467 void nvmem_unregister(struct nvmem_device *nvmem)
468 {
469 	kref_put(&nvmem->refcnt, nvmem_device_release);
470 }
471 EXPORT_SYMBOL_GPL(nvmem_unregister);
472 
473 static void devm_nvmem_release(struct device *dev, void *res)
474 {
475 	nvmem_unregister(*(struct nvmem_device **)res);
476 }
477 
478 /**
479  * devm_nvmem_register() - Register a managed nvmem device for given
480  * nvmem_config.
481  * Also creates an binary entry in /sys/bus/nvmem/devices/dev-name/nvmem
482  *
483  * @dev: Device that uses the nvmem device.
484  * @config: nvmem device configuration with which nvmem device is created.
485  *
486  * Return: Will be an ERR_PTR() on error or a valid pointer to nvmem_device
487  * on success.
488  */
489 struct nvmem_device *devm_nvmem_register(struct device *dev,
490 					 const struct nvmem_config *config)
491 {
492 	struct nvmem_device **ptr, *nvmem;
493 
494 	ptr = devres_alloc(devm_nvmem_release, sizeof(*ptr), GFP_KERNEL);
495 	if (!ptr)
496 		return ERR_PTR(-ENOMEM);
497 
498 	nvmem = nvmem_register(config);
499 
500 	if (!IS_ERR(nvmem)) {
501 		*ptr = nvmem;
502 		devres_add(dev, ptr);
503 	} else {
504 		devres_free(ptr);
505 	}
506 
507 	return nvmem;
508 }
509 EXPORT_SYMBOL_GPL(devm_nvmem_register);
510 
511 static int devm_nvmem_match(struct device *dev, void *res, void *data)
512 {
513 	struct nvmem_device **r = res;
514 
515 	return *r == data;
516 }
517 
518 /**
519  * devm_nvmem_unregister() - Unregister previously registered managed nvmem
520  * device.
521  *
522  * @dev: Device that uses the nvmem device.
523  * @nvmem: Pointer to previously registered nvmem device.
524  *
525  * Return: Will be an negative on error or a zero on success.
526  */
527 int devm_nvmem_unregister(struct device *dev, struct nvmem_device *nvmem)
528 {
529 	return devres_release(dev, devm_nvmem_release, devm_nvmem_match, nvmem);
530 }
531 EXPORT_SYMBOL(devm_nvmem_unregister);
532 
533 static struct nvmem_device *__nvmem_device_get(void *data,
534 			int (*match)(struct device *dev, const void *data))
535 {
536 	struct nvmem_device *nvmem = NULL;
537 	struct device *dev;
538 
539 	mutex_lock(&nvmem_mutex);
540 	dev = bus_find_device(&nvmem_bus_type, NULL, data, match);
541 	if (dev)
542 		nvmem = to_nvmem_device(dev);
543 	mutex_unlock(&nvmem_mutex);
544 	if (!nvmem)
545 		return ERR_PTR(-EPROBE_DEFER);
546 
547 	if (!try_module_get(nvmem->owner)) {
548 		dev_err(&nvmem->dev,
549 			"could not increase module refcount for cell %s\n",
550 			nvmem_dev_name(nvmem));
551 
552 		put_device(&nvmem->dev);
553 		return ERR_PTR(-EINVAL);
554 	}
555 
556 	kref_get(&nvmem->refcnt);
557 
558 	return nvmem;
559 }
560 
561 static void __nvmem_device_put(struct nvmem_device *nvmem)
562 {
563 	put_device(&nvmem->dev);
564 	module_put(nvmem->owner);
565 	kref_put(&nvmem->refcnt, nvmem_device_release);
566 }
567 
568 #if IS_ENABLED(CONFIG_OF)
569 /**
570  * of_nvmem_device_get() - Get nvmem device from a given id
571  *
572  * @np: Device tree node that uses the nvmem device.
573  * @id: nvmem name from nvmem-names property.
574  *
575  * Return: ERR_PTR() on error or a valid pointer to a struct nvmem_device
576  * on success.
577  */
578 struct nvmem_device *of_nvmem_device_get(struct device_node *np, const char *id)
579 {
580 
581 	struct device_node *nvmem_np;
582 	int index = 0;
583 
584 	if (id)
585 		index = of_property_match_string(np, "nvmem-names", id);
586 
587 	nvmem_np = of_parse_phandle(np, "nvmem", index);
588 	if (!nvmem_np)
589 		return ERR_PTR(-ENOENT);
590 
591 	return __nvmem_device_get(nvmem_np, device_match_of_node);
592 }
593 EXPORT_SYMBOL_GPL(of_nvmem_device_get);
594 #endif
595 
596 /**
597  * nvmem_device_get() - Get nvmem device from a given id
598  *
599  * @dev: Device that uses the nvmem device.
600  * @dev_name: name of the requested nvmem device.
601  *
602  * Return: ERR_PTR() on error or a valid pointer to a struct nvmem_device
603  * on success.
604  */
605 struct nvmem_device *nvmem_device_get(struct device *dev, const char *dev_name)
606 {
607 	if (dev->of_node) { /* try dt first */
608 		struct nvmem_device *nvmem;
609 
610 		nvmem = of_nvmem_device_get(dev->of_node, dev_name);
611 
612 		if (!IS_ERR(nvmem) || PTR_ERR(nvmem) == -EPROBE_DEFER)
613 			return nvmem;
614 
615 	}
616 
617 	return __nvmem_device_get((void *)dev_name, device_match_name);
618 }
619 EXPORT_SYMBOL_GPL(nvmem_device_get);
620 
621 /**
622  * nvmem_device_find() - Find nvmem device with matching function
623  *
624  * @data: Data to pass to match function
625  * @match: Callback function to check device
626  *
627  * Return: ERR_PTR() on error or a valid pointer to a struct nvmem_device
628  * on success.
629  */
630 struct nvmem_device *nvmem_device_find(void *data,
631 			int (*match)(struct device *dev, const void *data))
632 {
633 	return __nvmem_device_get(data, match);
634 }
635 EXPORT_SYMBOL_GPL(nvmem_device_find);
636 
637 static int devm_nvmem_device_match(struct device *dev, void *res, void *data)
638 {
639 	struct nvmem_device **nvmem = res;
640 
641 	if (WARN_ON(!nvmem || !*nvmem))
642 		return 0;
643 
644 	return *nvmem == data;
645 }
646 
647 static void devm_nvmem_device_release(struct device *dev, void *res)
648 {
649 	nvmem_device_put(*(struct nvmem_device **)res);
650 }
651 
652 /**
653  * devm_nvmem_device_put() - put alredy got nvmem device
654  *
655  * @dev: Device that uses the nvmem device.
656  * @nvmem: pointer to nvmem device allocated by devm_nvmem_cell_get(),
657  * that needs to be released.
658  */
659 void devm_nvmem_device_put(struct device *dev, struct nvmem_device *nvmem)
660 {
661 	int ret;
662 
663 	ret = devres_release(dev, devm_nvmem_device_release,
664 			     devm_nvmem_device_match, nvmem);
665 
666 	WARN_ON(ret);
667 }
668 EXPORT_SYMBOL_GPL(devm_nvmem_device_put);
669 
670 /**
671  * nvmem_device_put() - put alredy got nvmem device
672  *
673  * @nvmem: pointer to nvmem device that needs to be released.
674  */
675 void nvmem_device_put(struct nvmem_device *nvmem)
676 {
677 	__nvmem_device_put(nvmem);
678 }
679 EXPORT_SYMBOL_GPL(nvmem_device_put);
680 
681 /**
682  * devm_nvmem_device_get() - Get nvmem cell of device form a given id
683  *
684  * @dev: Device that requests the nvmem device.
685  * @id: name id for the requested nvmem device.
686  *
687  * Return: ERR_PTR() on error or a valid pointer to a struct nvmem_cell
688  * on success.  The nvmem_cell will be freed by the automatically once the
689  * device is freed.
690  */
691 struct nvmem_device *devm_nvmem_device_get(struct device *dev, const char *id)
692 {
693 	struct nvmem_device **ptr, *nvmem;
694 
695 	ptr = devres_alloc(devm_nvmem_device_release, sizeof(*ptr), GFP_KERNEL);
696 	if (!ptr)
697 		return ERR_PTR(-ENOMEM);
698 
699 	nvmem = nvmem_device_get(dev, id);
700 	if (!IS_ERR(nvmem)) {
701 		*ptr = nvmem;
702 		devres_add(dev, ptr);
703 	} else {
704 		devres_free(ptr);
705 	}
706 
707 	return nvmem;
708 }
709 EXPORT_SYMBOL_GPL(devm_nvmem_device_get);
710 
711 static struct nvmem_cell *
712 nvmem_cell_get_from_lookup(struct device *dev, const char *con_id)
713 {
714 	struct nvmem_cell *cell = ERR_PTR(-ENOENT);
715 	struct nvmem_cell_lookup *lookup;
716 	struct nvmem_device *nvmem;
717 	const char *dev_id;
718 
719 	if (!dev)
720 		return ERR_PTR(-EINVAL);
721 
722 	dev_id = dev_name(dev);
723 
724 	mutex_lock(&nvmem_lookup_mutex);
725 
726 	list_for_each_entry(lookup, &nvmem_lookup_list, node) {
727 		if ((strcmp(lookup->dev_id, dev_id) == 0) &&
728 		    (strcmp(lookup->con_id, con_id) == 0)) {
729 			/* This is the right entry. */
730 			nvmem = __nvmem_device_get((void *)lookup->nvmem_name,
731 						   device_match_name);
732 			if (IS_ERR(nvmem)) {
733 				/* Provider may not be registered yet. */
734 				cell = ERR_CAST(nvmem);
735 				break;
736 			}
737 
738 			cell = nvmem_find_cell_by_name(nvmem,
739 						       lookup->cell_name);
740 			if (!cell) {
741 				__nvmem_device_put(nvmem);
742 				cell = ERR_PTR(-ENOENT);
743 			}
744 			break;
745 		}
746 	}
747 
748 	mutex_unlock(&nvmem_lookup_mutex);
749 	return cell;
750 }
751 
752 #if IS_ENABLED(CONFIG_OF)
753 static struct nvmem_cell *
754 nvmem_find_cell_by_node(struct nvmem_device *nvmem, struct device_node *np)
755 {
756 	struct nvmem_cell *iter, *cell = NULL;
757 
758 	mutex_lock(&nvmem_mutex);
759 	list_for_each_entry(iter, &nvmem->cells, node) {
760 		if (np == iter->np) {
761 			cell = iter;
762 			break;
763 		}
764 	}
765 	mutex_unlock(&nvmem_mutex);
766 
767 	return cell;
768 }
769 
770 /**
771  * of_nvmem_cell_get() - Get a nvmem cell from given device node and cell id
772  *
773  * @np: Device tree node that uses the nvmem cell.
774  * @id: nvmem cell name from nvmem-cell-names property, or NULL
775  *      for the cell at index 0 (the lone cell with no accompanying
776  *      nvmem-cell-names property).
777  *
778  * Return: Will be an ERR_PTR() on error or a valid pointer
779  * to a struct nvmem_cell.  The nvmem_cell will be freed by the
780  * nvmem_cell_put().
781  */
782 struct nvmem_cell *of_nvmem_cell_get(struct device_node *np, const char *id)
783 {
784 	struct device_node *cell_np, *nvmem_np;
785 	struct nvmem_device *nvmem;
786 	struct nvmem_cell *cell;
787 	int index = 0;
788 
789 	/* if cell name exists, find index to the name */
790 	if (id)
791 		index = of_property_match_string(np, "nvmem-cell-names", id);
792 
793 	cell_np = of_parse_phandle(np, "nvmem-cells", index);
794 	if (!cell_np)
795 		return ERR_PTR(-ENOENT);
796 
797 	nvmem_np = of_get_next_parent(cell_np);
798 	if (!nvmem_np)
799 		return ERR_PTR(-EINVAL);
800 
801 	nvmem = __nvmem_device_get(nvmem_np, device_match_of_node);
802 	of_node_put(nvmem_np);
803 	if (IS_ERR(nvmem))
804 		return ERR_CAST(nvmem);
805 
806 	cell = nvmem_find_cell_by_node(nvmem, cell_np);
807 	if (!cell) {
808 		__nvmem_device_put(nvmem);
809 		return ERR_PTR(-ENOENT);
810 	}
811 
812 	return cell;
813 }
814 EXPORT_SYMBOL_GPL(of_nvmem_cell_get);
815 #endif
816 
817 /**
818  * nvmem_cell_get() - Get nvmem cell of device form a given cell name
819  *
820  * @dev: Device that requests the nvmem cell.
821  * @id: nvmem cell name to get (this corresponds with the name from the
822  *      nvmem-cell-names property for DT systems and with the con_id from
823  *      the lookup entry for non-DT systems).
824  *
825  * Return: Will be an ERR_PTR() on error or a valid pointer
826  * to a struct nvmem_cell.  The nvmem_cell will be freed by the
827  * nvmem_cell_put().
828  */
829 struct nvmem_cell *nvmem_cell_get(struct device *dev, const char *id)
830 {
831 	struct nvmem_cell *cell;
832 
833 	if (dev->of_node) { /* try dt first */
834 		cell = of_nvmem_cell_get(dev->of_node, id);
835 		if (!IS_ERR(cell) || PTR_ERR(cell) == -EPROBE_DEFER)
836 			return cell;
837 	}
838 
839 	/* NULL cell id only allowed for device tree; invalid otherwise */
840 	if (!id)
841 		return ERR_PTR(-EINVAL);
842 
843 	return nvmem_cell_get_from_lookup(dev, id);
844 }
845 EXPORT_SYMBOL_GPL(nvmem_cell_get);
846 
847 static void devm_nvmem_cell_release(struct device *dev, void *res)
848 {
849 	nvmem_cell_put(*(struct nvmem_cell **)res);
850 }
851 
852 /**
853  * devm_nvmem_cell_get() - Get nvmem cell of device form a given id
854  *
855  * @dev: Device that requests the nvmem cell.
856  * @id: nvmem cell name id to get.
857  *
858  * Return: Will be an ERR_PTR() on error or a valid pointer
859  * to a struct nvmem_cell.  The nvmem_cell will be freed by the
860  * automatically once the device is freed.
861  */
862 struct nvmem_cell *devm_nvmem_cell_get(struct device *dev, const char *id)
863 {
864 	struct nvmem_cell **ptr, *cell;
865 
866 	ptr = devres_alloc(devm_nvmem_cell_release, sizeof(*ptr), GFP_KERNEL);
867 	if (!ptr)
868 		return ERR_PTR(-ENOMEM);
869 
870 	cell = nvmem_cell_get(dev, id);
871 	if (!IS_ERR(cell)) {
872 		*ptr = cell;
873 		devres_add(dev, ptr);
874 	} else {
875 		devres_free(ptr);
876 	}
877 
878 	return cell;
879 }
880 EXPORT_SYMBOL_GPL(devm_nvmem_cell_get);
881 
882 static int devm_nvmem_cell_match(struct device *dev, void *res, void *data)
883 {
884 	struct nvmem_cell **c = res;
885 
886 	if (WARN_ON(!c || !*c))
887 		return 0;
888 
889 	return *c == data;
890 }
891 
892 /**
893  * devm_nvmem_cell_put() - Release previously allocated nvmem cell
894  * from devm_nvmem_cell_get.
895  *
896  * @dev: Device that requests the nvmem cell.
897  * @cell: Previously allocated nvmem cell by devm_nvmem_cell_get().
898  */
899 void devm_nvmem_cell_put(struct device *dev, struct nvmem_cell *cell)
900 {
901 	int ret;
902 
903 	ret = devres_release(dev, devm_nvmem_cell_release,
904 				devm_nvmem_cell_match, cell);
905 
906 	WARN_ON(ret);
907 }
908 EXPORT_SYMBOL(devm_nvmem_cell_put);
909 
910 /**
911  * nvmem_cell_put() - Release previously allocated nvmem cell.
912  *
913  * @cell: Previously allocated nvmem cell by nvmem_cell_get().
914  */
915 void nvmem_cell_put(struct nvmem_cell *cell)
916 {
917 	struct nvmem_device *nvmem = cell->nvmem;
918 
919 	__nvmem_device_put(nvmem);
920 }
921 EXPORT_SYMBOL_GPL(nvmem_cell_put);
922 
923 static void nvmem_shift_read_buffer_in_place(struct nvmem_cell *cell, void *buf)
924 {
925 	u8 *p, *b;
926 	int i, extra, bit_offset = cell->bit_offset;
927 
928 	p = b = buf;
929 	if (bit_offset) {
930 		/* First shift */
931 		*b++ >>= bit_offset;
932 
933 		/* setup rest of the bytes if any */
934 		for (i = 1; i < cell->bytes; i++) {
935 			/* Get bits from next byte and shift them towards msb */
936 			*p |= *b << (BITS_PER_BYTE - bit_offset);
937 
938 			p = b;
939 			*b++ >>= bit_offset;
940 		}
941 	} else {
942 		/* point to the msb */
943 		p += cell->bytes - 1;
944 	}
945 
946 	/* result fits in less bytes */
947 	extra = cell->bytes - DIV_ROUND_UP(cell->nbits, BITS_PER_BYTE);
948 	while (--extra >= 0)
949 		*p-- = 0;
950 
951 	/* clear msb bits if any leftover in the last byte */
952 	*p &= GENMASK((cell->nbits%BITS_PER_BYTE) - 1, 0);
953 }
954 
955 static int __nvmem_cell_read(struct nvmem_device *nvmem,
956 		      struct nvmem_cell *cell,
957 		      void *buf, size_t *len)
958 {
959 	int rc;
960 
961 	rc = nvmem_reg_read(nvmem, cell->offset, buf, cell->bytes);
962 
963 	if (rc)
964 		return rc;
965 
966 	/* shift bits in-place */
967 	if (cell->bit_offset || cell->nbits)
968 		nvmem_shift_read_buffer_in_place(cell, buf);
969 
970 	if (len)
971 		*len = cell->bytes;
972 
973 	return 0;
974 }
975 
976 /**
977  * nvmem_cell_read() - Read a given nvmem cell
978  *
979  * @cell: nvmem cell to be read.
980  * @len: pointer to length of cell which will be populated on successful read;
981  *	 can be NULL.
982  *
983  * Return: ERR_PTR() on error or a valid pointer to a buffer on success. The
984  * buffer should be freed by the consumer with a kfree().
985  */
986 void *nvmem_cell_read(struct nvmem_cell *cell, size_t *len)
987 {
988 	struct nvmem_device *nvmem = cell->nvmem;
989 	u8 *buf;
990 	int rc;
991 
992 	if (!nvmem)
993 		return ERR_PTR(-EINVAL);
994 
995 	buf = kzalloc(cell->bytes, GFP_KERNEL);
996 	if (!buf)
997 		return ERR_PTR(-ENOMEM);
998 
999 	rc = __nvmem_cell_read(nvmem, cell, buf, len);
1000 	if (rc) {
1001 		kfree(buf);
1002 		return ERR_PTR(rc);
1003 	}
1004 
1005 	return buf;
1006 }
1007 EXPORT_SYMBOL_GPL(nvmem_cell_read);
1008 
1009 static void *nvmem_cell_prepare_write_buffer(struct nvmem_cell *cell,
1010 					     u8 *_buf, int len)
1011 {
1012 	struct nvmem_device *nvmem = cell->nvmem;
1013 	int i, rc, nbits, bit_offset = cell->bit_offset;
1014 	u8 v, *p, *buf, *b, pbyte, pbits;
1015 
1016 	nbits = cell->nbits;
1017 	buf = kzalloc(cell->bytes, GFP_KERNEL);
1018 	if (!buf)
1019 		return ERR_PTR(-ENOMEM);
1020 
1021 	memcpy(buf, _buf, len);
1022 	p = b = buf;
1023 
1024 	if (bit_offset) {
1025 		pbyte = *b;
1026 		*b <<= bit_offset;
1027 
1028 		/* setup the first byte with lsb bits from nvmem */
1029 		rc = nvmem_reg_read(nvmem, cell->offset, &v, 1);
1030 		if (rc)
1031 			goto err;
1032 		*b++ |= GENMASK(bit_offset - 1, 0) & v;
1033 
1034 		/* setup rest of the byte if any */
1035 		for (i = 1; i < cell->bytes; i++) {
1036 			/* Get last byte bits and shift them towards lsb */
1037 			pbits = pbyte >> (BITS_PER_BYTE - 1 - bit_offset);
1038 			pbyte = *b;
1039 			p = b;
1040 			*b <<= bit_offset;
1041 			*b++ |= pbits;
1042 		}
1043 	}
1044 
1045 	/* if it's not end on byte boundary */
1046 	if ((nbits + bit_offset) % BITS_PER_BYTE) {
1047 		/* setup the last byte with msb bits from nvmem */
1048 		rc = nvmem_reg_read(nvmem,
1049 				    cell->offset + cell->bytes - 1, &v, 1);
1050 		if (rc)
1051 			goto err;
1052 		*p |= GENMASK(7, (nbits + bit_offset) % BITS_PER_BYTE) & v;
1053 
1054 	}
1055 
1056 	return buf;
1057 err:
1058 	kfree(buf);
1059 	return ERR_PTR(rc);
1060 }
1061 
1062 /**
1063  * nvmem_cell_write() - Write to a given nvmem cell
1064  *
1065  * @cell: nvmem cell to be written.
1066  * @buf: Buffer to be written.
1067  * @len: length of buffer to be written to nvmem cell.
1068  *
1069  * Return: length of bytes written or negative on failure.
1070  */
1071 int nvmem_cell_write(struct nvmem_cell *cell, void *buf, size_t len)
1072 {
1073 	struct nvmem_device *nvmem = cell->nvmem;
1074 	int rc;
1075 
1076 	if (!nvmem || nvmem->read_only ||
1077 	    (cell->bit_offset == 0 && len != cell->bytes))
1078 		return -EINVAL;
1079 
1080 	if (cell->bit_offset || cell->nbits) {
1081 		buf = nvmem_cell_prepare_write_buffer(cell, buf, len);
1082 		if (IS_ERR(buf))
1083 			return PTR_ERR(buf);
1084 	}
1085 
1086 	rc = nvmem_reg_write(nvmem, cell->offset, buf, cell->bytes);
1087 
1088 	/* free the tmp buffer */
1089 	if (cell->bit_offset || cell->nbits)
1090 		kfree(buf);
1091 
1092 	if (rc)
1093 		return rc;
1094 
1095 	return len;
1096 }
1097 EXPORT_SYMBOL_GPL(nvmem_cell_write);
1098 
1099 static int nvmem_cell_read_common(struct device *dev, const char *cell_id,
1100 				  void *val, size_t count)
1101 {
1102 	struct nvmem_cell *cell;
1103 	void *buf;
1104 	size_t len;
1105 
1106 	cell = nvmem_cell_get(dev, cell_id);
1107 	if (IS_ERR(cell))
1108 		return PTR_ERR(cell);
1109 
1110 	buf = nvmem_cell_read(cell, &len);
1111 	if (IS_ERR(buf)) {
1112 		nvmem_cell_put(cell);
1113 		return PTR_ERR(buf);
1114 	}
1115 	if (len != count) {
1116 		kfree(buf);
1117 		nvmem_cell_put(cell);
1118 		return -EINVAL;
1119 	}
1120 	memcpy(val, buf, count);
1121 	kfree(buf);
1122 	nvmem_cell_put(cell);
1123 
1124 	return 0;
1125 }
1126 
1127 /**
1128  * nvmem_cell_read_u16() - Read a cell value as an u16
1129  *
1130  * @dev: Device that requests the nvmem cell.
1131  * @cell_id: Name of nvmem cell to read.
1132  * @val: pointer to output value.
1133  *
1134  * Return: 0 on success or negative errno.
1135  */
1136 int nvmem_cell_read_u16(struct device *dev, const char *cell_id, u16 *val)
1137 {
1138 	return nvmem_cell_read_common(dev, cell_id, val, sizeof(*val));
1139 }
1140 EXPORT_SYMBOL_GPL(nvmem_cell_read_u16);
1141 
1142 /**
1143  * nvmem_cell_read_u32() - Read a cell value as an u32
1144  *
1145  * @dev: Device that requests the nvmem cell.
1146  * @cell_id: Name of nvmem cell to read.
1147  * @val: pointer to output value.
1148  *
1149  * Return: 0 on success or negative errno.
1150  */
1151 int nvmem_cell_read_u32(struct device *dev, const char *cell_id, u32 *val)
1152 {
1153 	return nvmem_cell_read_common(dev, cell_id, val, sizeof(*val));
1154 }
1155 EXPORT_SYMBOL_GPL(nvmem_cell_read_u32);
1156 
1157 /**
1158  * nvmem_cell_read_u64() - Read a cell value as an u64
1159  *
1160  * @dev: Device that requests the nvmem cell.
1161  * @cell_id: Name of nvmem cell to read.
1162  * @val: pointer to output value.
1163  *
1164  * Return: 0 on success or negative errno.
1165  */
1166 int nvmem_cell_read_u64(struct device *dev, const char *cell_id, u64 *val)
1167 {
1168 	return nvmem_cell_read_common(dev, cell_id, val, sizeof(*val));
1169 }
1170 EXPORT_SYMBOL_GPL(nvmem_cell_read_u64);
1171 
1172 /**
1173  * nvmem_device_cell_read() - Read a given nvmem device and cell
1174  *
1175  * @nvmem: nvmem device to read from.
1176  * @info: nvmem cell info to be read.
1177  * @buf: buffer pointer which will be populated on successful read.
1178  *
1179  * Return: length of successful bytes read on success and negative
1180  * error code on error.
1181  */
1182 ssize_t nvmem_device_cell_read(struct nvmem_device *nvmem,
1183 			   struct nvmem_cell_info *info, void *buf)
1184 {
1185 	struct nvmem_cell cell;
1186 	int rc;
1187 	ssize_t len;
1188 
1189 	if (!nvmem)
1190 		return -EINVAL;
1191 
1192 	rc = nvmem_cell_info_to_nvmem_cell(nvmem, info, &cell);
1193 	if (rc)
1194 		return rc;
1195 
1196 	rc = __nvmem_cell_read(nvmem, &cell, buf, &len);
1197 	if (rc)
1198 		return rc;
1199 
1200 	return len;
1201 }
1202 EXPORT_SYMBOL_GPL(nvmem_device_cell_read);
1203 
1204 /**
1205  * nvmem_device_cell_write() - Write cell to a given nvmem device
1206  *
1207  * @nvmem: nvmem device to be written to.
1208  * @info: nvmem cell info to be written.
1209  * @buf: buffer to be written to cell.
1210  *
1211  * Return: length of bytes written or negative error code on failure.
1212  */
1213 int nvmem_device_cell_write(struct nvmem_device *nvmem,
1214 			    struct nvmem_cell_info *info, void *buf)
1215 {
1216 	struct nvmem_cell cell;
1217 	int rc;
1218 
1219 	if (!nvmem)
1220 		return -EINVAL;
1221 
1222 	rc = nvmem_cell_info_to_nvmem_cell(nvmem, info, &cell);
1223 	if (rc)
1224 		return rc;
1225 
1226 	return nvmem_cell_write(&cell, buf, cell.bytes);
1227 }
1228 EXPORT_SYMBOL_GPL(nvmem_device_cell_write);
1229 
1230 /**
1231  * nvmem_device_read() - Read from a given nvmem device
1232  *
1233  * @nvmem: nvmem device to read from.
1234  * @offset: offset in nvmem device.
1235  * @bytes: number of bytes to read.
1236  * @buf: buffer pointer which will be populated on successful read.
1237  *
1238  * Return: length of successful bytes read on success and negative
1239  * error code on error.
1240  */
1241 int nvmem_device_read(struct nvmem_device *nvmem,
1242 		      unsigned int offset,
1243 		      size_t bytes, void *buf)
1244 {
1245 	int rc;
1246 
1247 	if (!nvmem)
1248 		return -EINVAL;
1249 
1250 	rc = nvmem_reg_read(nvmem, offset, buf, bytes);
1251 
1252 	if (rc)
1253 		return rc;
1254 
1255 	return bytes;
1256 }
1257 EXPORT_SYMBOL_GPL(nvmem_device_read);
1258 
1259 /**
1260  * nvmem_device_write() - Write cell to a given nvmem device
1261  *
1262  * @nvmem: nvmem device to be written to.
1263  * @offset: offset in nvmem device.
1264  * @bytes: number of bytes to write.
1265  * @buf: buffer to be written.
1266  *
1267  * Return: length of bytes written or negative error code on failure.
1268  */
1269 int nvmem_device_write(struct nvmem_device *nvmem,
1270 		       unsigned int offset,
1271 		       size_t bytes, void *buf)
1272 {
1273 	int rc;
1274 
1275 	if (!nvmem)
1276 		return -EINVAL;
1277 
1278 	rc = nvmem_reg_write(nvmem, offset, buf, bytes);
1279 
1280 	if (rc)
1281 		return rc;
1282 
1283 
1284 	return bytes;
1285 }
1286 EXPORT_SYMBOL_GPL(nvmem_device_write);
1287 
1288 /**
1289  * nvmem_add_cell_table() - register a table of cell info entries
1290  *
1291  * @table: table of cell info entries
1292  */
1293 void nvmem_add_cell_table(struct nvmem_cell_table *table)
1294 {
1295 	mutex_lock(&nvmem_cell_mutex);
1296 	list_add_tail(&table->node, &nvmem_cell_tables);
1297 	mutex_unlock(&nvmem_cell_mutex);
1298 }
1299 EXPORT_SYMBOL_GPL(nvmem_add_cell_table);
1300 
1301 /**
1302  * nvmem_del_cell_table() - remove a previously registered cell info table
1303  *
1304  * @table: table of cell info entries
1305  */
1306 void nvmem_del_cell_table(struct nvmem_cell_table *table)
1307 {
1308 	mutex_lock(&nvmem_cell_mutex);
1309 	list_del(&table->node);
1310 	mutex_unlock(&nvmem_cell_mutex);
1311 }
1312 EXPORT_SYMBOL_GPL(nvmem_del_cell_table);
1313 
1314 /**
1315  * nvmem_add_cell_lookups() - register a list of cell lookup entries
1316  *
1317  * @entries: array of cell lookup entries
1318  * @nentries: number of cell lookup entries in the array
1319  */
1320 void nvmem_add_cell_lookups(struct nvmem_cell_lookup *entries, size_t nentries)
1321 {
1322 	int i;
1323 
1324 	mutex_lock(&nvmem_lookup_mutex);
1325 	for (i = 0; i < nentries; i++)
1326 		list_add_tail(&entries[i].node, &nvmem_lookup_list);
1327 	mutex_unlock(&nvmem_lookup_mutex);
1328 }
1329 EXPORT_SYMBOL_GPL(nvmem_add_cell_lookups);
1330 
1331 /**
1332  * nvmem_del_cell_lookups() - remove a list of previously added cell lookup
1333  *                            entries
1334  *
1335  * @entries: array of cell lookup entries
1336  * @nentries: number of cell lookup entries in the array
1337  */
1338 void nvmem_del_cell_lookups(struct nvmem_cell_lookup *entries, size_t nentries)
1339 {
1340 	int i;
1341 
1342 	mutex_lock(&nvmem_lookup_mutex);
1343 	for (i = 0; i < nentries; i++)
1344 		list_del(&entries[i].node);
1345 	mutex_unlock(&nvmem_lookup_mutex);
1346 }
1347 EXPORT_SYMBOL_GPL(nvmem_del_cell_lookups);
1348 
1349 /**
1350  * nvmem_dev_name() - Get the name of a given nvmem device.
1351  *
1352  * @nvmem: nvmem device.
1353  *
1354  * Return: name of the nvmem device.
1355  */
1356 const char *nvmem_dev_name(struct nvmem_device *nvmem)
1357 {
1358 	return dev_name(&nvmem->dev);
1359 }
1360 EXPORT_SYMBOL_GPL(nvmem_dev_name);
1361 
1362 static int __init nvmem_init(void)
1363 {
1364 	return bus_register(&nvmem_bus_type);
1365 }
1366 
1367 static void __exit nvmem_exit(void)
1368 {
1369 	bus_unregister(&nvmem_bus_type);
1370 }
1371 
1372 subsys_initcall(nvmem_init);
1373 module_exit(nvmem_exit);
1374 
1375 MODULE_AUTHOR("Srinivas Kandagatla <srinivas.kandagatla@linaro.org");
1376 MODULE_AUTHOR("Maxime Ripard <maxime.ripard@free-electrons.com");
1377 MODULE_DESCRIPTION("nvmem Driver Core");
1378 MODULE_LICENSE("GPL v2");
1379