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