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