Merge branch '2021-09-30-whitespace-cleanups' into next
[platform/kernel/u-boot.git] / drivers / mtd / mtdcore.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Core registration and callback routines for MTD
4  * drivers and users.
5  *
6  * Copyright © 1999-2010 David Woodhouse <dwmw2@infradead.org>
7  * Copyright © 2006      Red Hat UK Limited
8  *
9  */
10
11 #ifndef __UBOOT__
12 #include <linux/module.h>
13 #include <linux/kernel.h>
14 #include <linux/ptrace.h>
15 #include <linux/seq_file.h>
16 #include <linux/string.h>
17 #include <linux/timer.h>
18 #include <linux/major.h>
19 #include <linux/fs.h>
20 #include <linux/err.h>
21 #include <linux/ioctl.h>
22 #include <linux/init.h>
23 #include <linux/proc_fs.h>
24 #include <linux/idr.h>
25 #include <linux/backing-dev.h>
26 #include <linux/gfp.h>
27 #include <linux/slab.h>
28 #else
29 #include <linux/bitops.h>
30 #include <linux/bug.h>
31 #include <linux/err.h>
32 #include <ubi_uboot.h>
33 #endif
34
35 #include <linux/log2.h>
36 #include <linux/mtd/mtd.h>
37 #include <linux/mtd/partitions.h>
38
39 #include "mtdcore.h"
40
41 #ifndef __UBOOT__
42 /*
43  * backing device capabilities for non-mappable devices (such as NAND flash)
44  * - permits private mappings, copies are taken of the data
45  */
46 static struct backing_dev_info mtd_bdi_unmappable = {
47         .capabilities   = BDI_CAP_MAP_COPY,
48 };
49
50 /*
51  * backing device capabilities for R/O mappable devices (such as ROM)
52  * - permits private mappings, copies are taken of the data
53  * - permits non-writable shared mappings
54  */
55 static struct backing_dev_info mtd_bdi_ro_mappable = {
56         .capabilities   = (BDI_CAP_MAP_COPY | BDI_CAP_MAP_DIRECT |
57                            BDI_CAP_EXEC_MAP | BDI_CAP_READ_MAP),
58 };
59
60 /*
61  * backing device capabilities for writable mappable devices (such as RAM)
62  * - permits private mappings, copies are taken of the data
63  * - permits non-writable shared mappings
64  */
65 static struct backing_dev_info mtd_bdi_rw_mappable = {
66         .capabilities   = (BDI_CAP_MAP_COPY | BDI_CAP_MAP_DIRECT |
67                            BDI_CAP_EXEC_MAP | BDI_CAP_READ_MAP |
68                            BDI_CAP_WRITE_MAP),
69 };
70
71 static int mtd_cls_suspend(struct device *dev, pm_message_t state);
72 static int mtd_cls_resume(struct device *dev);
73
74 static struct class mtd_class = {
75         .name = "mtd",
76         .owner = THIS_MODULE,
77         .suspend = mtd_cls_suspend,
78         .resume = mtd_cls_resume,
79 };
80 #else
81 #define MAX_IDR_ID      64
82
83 struct idr_layer {
84         int     used;
85         void    *ptr;
86 };
87
88 struct idr {
89         struct idr_layer id[MAX_IDR_ID];
90         bool updated;
91 };
92
93 #define DEFINE_IDR(name)        struct idr name;
94
95 void idr_remove(struct idr *idp, int id)
96 {
97         if (idp->id[id].used) {
98                 idp->id[id].used = 0;
99                 idp->updated = true;
100         }
101
102         return;
103 }
104 void *idr_find(struct idr *idp, int id)
105 {
106         if (idp->id[id].used)
107                 return idp->id[id].ptr;
108
109         return NULL;
110 }
111
112 void *idr_get_next(struct idr *idp, int *next)
113 {
114         void *ret;
115         int id = *next;
116
117         ret = idr_find(idp, id);
118         if (ret) {
119                 id ++;
120                 if (!idp->id[id].used)
121                         id = 0;
122                 *next = id;
123         } else {
124                 *next = 0;
125         }
126
127         return ret;
128 }
129
130 int idr_alloc(struct idr *idp, void *ptr, int start, int end, gfp_t gfp_mask)
131 {
132         struct idr_layer *idl;
133         int i = 0;
134
135         while (i < MAX_IDR_ID) {
136                 idl = &idp->id[i];
137                 if (idl->used == 0) {
138                         idl->used = 1;
139                         idl->ptr = ptr;
140                         idp->updated = true;
141                         return i;
142                 }
143                 i++;
144         }
145         return -ENOSPC;
146 }
147 #endif
148
149 static DEFINE_IDR(mtd_idr);
150
151 /* These are exported solely for the purpose of mtd_blkdevs.c. You
152    should not use them for _anything_ else */
153 DEFINE_MUTEX(mtd_table_mutex);
154 EXPORT_SYMBOL_GPL(mtd_table_mutex);
155
156 struct mtd_info *__mtd_next_device(int i)
157 {
158         return idr_get_next(&mtd_idr, &i);
159 }
160 EXPORT_SYMBOL_GPL(__mtd_next_device);
161
162 bool mtd_dev_list_updated(void)
163 {
164         if (mtd_idr.updated) {
165                 mtd_idr.updated = false;
166                 return true;
167         }
168
169         return false;
170 }
171
172 #ifndef __UBOOT__
173 static LIST_HEAD(mtd_notifiers);
174
175
176 #define MTD_DEVT(index) MKDEV(MTD_CHAR_MAJOR, (index)*2)
177
178 /* REVISIT once MTD uses the driver model better, whoever allocates
179  * the mtd_info will probably want to use the release() hook...
180  */
181 static void mtd_release(struct device *dev)
182 {
183         struct mtd_info __maybe_unused *mtd = dev_get_drvdata(dev);
184         dev_t index = MTD_DEVT(mtd->index);
185
186         /* remove /dev/mtdXro node if needed */
187         if (index)
188                 device_destroy(&mtd_class, index + 1);
189 }
190
191 static int mtd_cls_suspend(struct device *dev, pm_message_t state)
192 {
193         struct mtd_info *mtd = dev_get_drvdata(dev);
194
195         return mtd ? mtd_suspend(mtd) : 0;
196 }
197
198 static int mtd_cls_resume(struct device *dev)
199 {
200         struct mtd_info *mtd = dev_get_drvdata(dev);
201
202         if (mtd)
203                 mtd_resume(mtd);
204         return 0;
205 }
206
207 static ssize_t mtd_type_show(struct device *dev,
208                 struct device_attribute *attr, char *buf)
209 {
210         struct mtd_info *mtd = dev_get_drvdata(dev);
211         char *type;
212
213         switch (mtd->type) {
214         case MTD_ABSENT:
215                 type = "absent";
216                 break;
217         case MTD_RAM:
218                 type = "ram";
219                 break;
220         case MTD_ROM:
221                 type = "rom";
222                 break;
223         case MTD_NORFLASH:
224                 type = "nor";
225                 break;
226         case MTD_NANDFLASH:
227                 type = "nand";
228                 break;
229         case MTD_DATAFLASH:
230                 type = "dataflash";
231                 break;
232         case MTD_UBIVOLUME:
233                 type = "ubi";
234                 break;
235         case MTD_MLCNANDFLASH:
236                 type = "mlc-nand";
237                 break;
238         default:
239                 type = "unknown";
240         }
241
242         return snprintf(buf, PAGE_SIZE, "%s\n", type);
243 }
244 static DEVICE_ATTR(type, S_IRUGO, mtd_type_show, NULL);
245
246 static ssize_t mtd_flags_show(struct device *dev,
247                 struct device_attribute *attr, char *buf)
248 {
249         struct mtd_info *mtd = dev_get_drvdata(dev);
250
251         return snprintf(buf, PAGE_SIZE, "0x%lx\n", (unsigned long)mtd->flags);
252
253 }
254 static DEVICE_ATTR(flags, S_IRUGO, mtd_flags_show, NULL);
255
256 static ssize_t mtd_size_show(struct device *dev,
257                 struct device_attribute *attr, char *buf)
258 {
259         struct mtd_info *mtd = dev_get_drvdata(dev);
260
261         return snprintf(buf, PAGE_SIZE, "%llu\n",
262                 (unsigned long long)mtd->size);
263
264 }
265 static DEVICE_ATTR(size, S_IRUGO, mtd_size_show, NULL);
266
267 static ssize_t mtd_erasesize_show(struct device *dev,
268                 struct device_attribute *attr, char *buf)
269 {
270         struct mtd_info *mtd = dev_get_drvdata(dev);
271
272         return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->erasesize);
273
274 }
275 static DEVICE_ATTR(erasesize, S_IRUGO, mtd_erasesize_show, NULL);
276
277 static ssize_t mtd_writesize_show(struct device *dev,
278                 struct device_attribute *attr, char *buf)
279 {
280         struct mtd_info *mtd = dev_get_drvdata(dev);
281
282         return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->writesize);
283
284 }
285 static DEVICE_ATTR(writesize, S_IRUGO, mtd_writesize_show, NULL);
286
287 static ssize_t mtd_subpagesize_show(struct device *dev,
288                 struct device_attribute *attr, char *buf)
289 {
290         struct mtd_info *mtd = dev_get_drvdata(dev);
291         unsigned int subpagesize = mtd->writesize >> mtd->subpage_sft;
292
293         return snprintf(buf, PAGE_SIZE, "%u\n", subpagesize);
294
295 }
296 static DEVICE_ATTR(subpagesize, S_IRUGO, mtd_subpagesize_show, NULL);
297
298 static ssize_t mtd_oobsize_show(struct device *dev,
299                 struct device_attribute *attr, char *buf)
300 {
301         struct mtd_info *mtd = dev_get_drvdata(dev);
302
303         return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->oobsize);
304
305 }
306 static DEVICE_ATTR(oobsize, S_IRUGO, mtd_oobsize_show, NULL);
307
308 static ssize_t mtd_numeraseregions_show(struct device *dev,
309                 struct device_attribute *attr, char *buf)
310 {
311         struct mtd_info *mtd = dev_get_drvdata(dev);
312
313         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->numeraseregions);
314
315 }
316 static DEVICE_ATTR(numeraseregions, S_IRUGO, mtd_numeraseregions_show,
317         NULL);
318
319 static ssize_t mtd_name_show(struct device *dev,
320                 struct device_attribute *attr, char *buf)
321 {
322         struct mtd_info *mtd = dev_get_drvdata(dev);
323
324         return snprintf(buf, PAGE_SIZE, "%s\n", mtd->name);
325
326 }
327 static DEVICE_ATTR(name, S_IRUGO, mtd_name_show, NULL);
328
329 static ssize_t mtd_ecc_strength_show(struct device *dev,
330                                      struct device_attribute *attr, char *buf)
331 {
332         struct mtd_info *mtd = dev_get_drvdata(dev);
333
334         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->ecc_strength);
335 }
336 static DEVICE_ATTR(ecc_strength, S_IRUGO, mtd_ecc_strength_show, NULL);
337
338 static ssize_t mtd_bitflip_threshold_show(struct device *dev,
339                                           struct device_attribute *attr,
340                                           char *buf)
341 {
342         struct mtd_info *mtd = dev_get_drvdata(dev);
343
344         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->bitflip_threshold);
345 }
346
347 static ssize_t mtd_bitflip_threshold_store(struct device *dev,
348                                            struct device_attribute *attr,
349                                            const char *buf, size_t count)
350 {
351         struct mtd_info *mtd = dev_get_drvdata(dev);
352         unsigned int bitflip_threshold;
353         int retval;
354
355         retval = kstrtouint(buf, 0, &bitflip_threshold);
356         if (retval)
357                 return retval;
358
359         mtd->bitflip_threshold = bitflip_threshold;
360         return count;
361 }
362 static DEVICE_ATTR(bitflip_threshold, S_IRUGO | S_IWUSR,
363                    mtd_bitflip_threshold_show,
364                    mtd_bitflip_threshold_store);
365
366 static ssize_t mtd_ecc_step_size_show(struct device *dev,
367                 struct device_attribute *attr, char *buf)
368 {
369         struct mtd_info *mtd = dev_get_drvdata(dev);
370
371         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->ecc_step_size);
372
373 }
374 static DEVICE_ATTR(ecc_step_size, S_IRUGO, mtd_ecc_step_size_show, NULL);
375
376 static struct attribute *mtd_attrs[] = {
377         &dev_attr_type.attr,
378         &dev_attr_flags.attr,
379         &dev_attr_size.attr,
380         &dev_attr_erasesize.attr,
381         &dev_attr_writesize.attr,
382         &dev_attr_subpagesize.attr,
383         &dev_attr_oobsize.attr,
384         &dev_attr_numeraseregions.attr,
385         &dev_attr_name.attr,
386         &dev_attr_ecc_strength.attr,
387         &dev_attr_ecc_step_size.attr,
388         &dev_attr_bitflip_threshold.attr,
389         NULL,
390 };
391 ATTRIBUTE_GROUPS(mtd);
392
393 static struct device_type mtd_devtype = {
394         .name           = "mtd",
395         .groups         = mtd_groups,
396         .release        = mtd_release,
397 };
398 #endif
399
400 /**
401  *      add_mtd_device - register an MTD device
402  *      @mtd: pointer to new MTD device info structure
403  *
404  *      Add a device to the list of MTD devices present in the system, and
405  *      notify each currently active MTD 'user' of its arrival. Returns
406  *      zero on success or 1 on failure, which currently will only happen
407  *      if there is insufficient memory or a sysfs error.
408  */
409
410 int add_mtd_device(struct mtd_info *mtd)
411 {
412 #ifndef __UBOOT__
413         struct mtd_notifier *not;
414 #endif
415         int i, error;
416
417 #ifndef __UBOOT__
418         if (!mtd->backing_dev_info) {
419                 switch (mtd->type) {
420                 case MTD_RAM:
421                         mtd->backing_dev_info = &mtd_bdi_rw_mappable;
422                         break;
423                 case MTD_ROM:
424                         mtd->backing_dev_info = &mtd_bdi_ro_mappable;
425                         break;
426                 default:
427                         mtd->backing_dev_info = &mtd_bdi_unmappable;
428                         break;
429                 }
430         }
431 #endif
432
433         BUG_ON(mtd->writesize == 0);
434         mutex_lock(&mtd_table_mutex);
435
436         i = idr_alloc(&mtd_idr, mtd, 0, 0, GFP_KERNEL);
437         if (i < 0)
438                 goto fail_locked;
439
440         mtd->index = i;
441         mtd->usecount = 0;
442
443         INIT_LIST_HEAD(&mtd->partitions);
444
445         /* default value if not set by driver */
446         if (mtd->bitflip_threshold == 0)
447                 mtd->bitflip_threshold = mtd->ecc_strength;
448
449         if (is_power_of_2(mtd->erasesize))
450                 mtd->erasesize_shift = ffs(mtd->erasesize) - 1;
451         else
452                 mtd->erasesize_shift = 0;
453
454         if (is_power_of_2(mtd->writesize))
455                 mtd->writesize_shift = ffs(mtd->writesize) - 1;
456         else
457                 mtd->writesize_shift = 0;
458
459         mtd->erasesize_mask = (1 << mtd->erasesize_shift) - 1;
460         mtd->writesize_mask = (1 << mtd->writesize_shift) - 1;
461
462         /* Some chips always power up locked. Unlock them now */
463         if ((mtd->flags & MTD_WRITEABLE) && (mtd->flags & MTD_POWERUP_LOCK)) {
464                 error = mtd_unlock(mtd, 0, mtd->size);
465                 if (error && error != -EOPNOTSUPP)
466                         printk(KERN_WARNING
467                                "%s: unlock failed, writes may not work\n",
468                                mtd->name);
469         }
470
471 #ifndef __UBOOT__
472         /* Caller should have set dev.parent to match the
473          * physical device.
474          */
475         mtd->dev.type = &mtd_devtype;
476         mtd->dev.class = &mtd_class;
477         mtd->dev.devt = MTD_DEVT(i);
478         dev_set_name(&mtd->dev, "mtd%d", i);
479         dev_set_drvdata(&mtd->dev, mtd);
480         if (device_register(&mtd->dev) != 0)
481                 goto fail_added;
482
483         if (MTD_DEVT(i))
484                 device_create(&mtd_class, mtd->dev.parent,
485                               MTD_DEVT(i) + 1,
486                               NULL, "mtd%dro", i);
487
488         pr_debug("mtd: Giving out device %d to %s\n", i, mtd->name);
489         /* No need to get a refcount on the module containing
490            the notifier, since we hold the mtd_table_mutex */
491         list_for_each_entry(not, &mtd_notifiers, list)
492                 not->add(mtd);
493 #else
494         pr_debug("mtd: Giving out device %d to %s\n", i, mtd->name);
495 #endif
496
497         mutex_unlock(&mtd_table_mutex);
498         /* We _know_ we aren't being removed, because
499            our caller is still holding us here. So none
500            of this try_ nonsense, and no bitching about it
501            either. :) */
502         __module_get(THIS_MODULE);
503         return 0;
504
505 #ifndef __UBOOT__
506 fail_added:
507         idr_remove(&mtd_idr, i);
508 #endif
509 fail_locked:
510         mutex_unlock(&mtd_table_mutex);
511         return 1;
512 }
513
514 /**
515  *      del_mtd_device - unregister an MTD device
516  *      @mtd: pointer to MTD device info structure
517  *
518  *      Remove a device from the list of MTD devices present in the system,
519  *      and notify each currently active MTD 'user' of its departure.
520  *      Returns zero on success or 1 on failure, which currently will happen
521  *      if the requested device does not appear to be present in the list.
522  */
523
524 int del_mtd_device(struct mtd_info *mtd)
525 {
526         int ret;
527 #ifndef __UBOOT__
528         struct mtd_notifier *not;
529 #endif
530
531         ret = del_mtd_partitions(mtd);
532         if (ret) {
533                 debug("Failed to delete MTD partitions attached to %s (err %d)\n",
534                       mtd->name, ret);
535                 return ret;
536         }
537
538         mutex_lock(&mtd_table_mutex);
539
540         if (idr_find(&mtd_idr, mtd->index) != mtd) {
541                 ret = -ENODEV;
542                 goto out_error;
543         }
544
545 #ifndef __UBOOT__
546         /* No need to get a refcount on the module containing
547                 the notifier, since we hold the mtd_table_mutex */
548         list_for_each_entry(not, &mtd_notifiers, list)
549                 not->remove(mtd);
550 #endif
551
552         if (mtd->usecount) {
553                 printk(KERN_NOTICE "Removing MTD device #%d (%s) with use count %d\n",
554                        mtd->index, mtd->name, mtd->usecount);
555                 ret = -EBUSY;
556         } else {
557 #ifndef __UBOOT__
558                 device_unregister(&mtd->dev);
559 #endif
560
561                 idr_remove(&mtd_idr, mtd->index);
562
563                 module_put(THIS_MODULE);
564                 ret = 0;
565         }
566
567 out_error:
568         mutex_unlock(&mtd_table_mutex);
569         return ret;
570 }
571
572 #ifndef __UBOOT__
573 /**
574  * mtd_device_parse_register - parse partitions and register an MTD device.
575  *
576  * @mtd: the MTD device to register
577  * @types: the list of MTD partition probes to try, see
578  *         'parse_mtd_partitions()' for more information
579  * @parser_data: MTD partition parser-specific data
580  * @parts: fallback partition information to register, if parsing fails;
581  *         only valid if %nr_parts > %0
582  * @nr_parts: the number of partitions in parts, if zero then the full
583  *            MTD device is registered if no partition info is found
584  *
585  * This function aggregates MTD partitions parsing (done by
586  * 'parse_mtd_partitions()') and MTD device and partitions registering. It
587  * basically follows the most common pattern found in many MTD drivers:
588  *
589  * * It first tries to probe partitions on MTD device @mtd using parsers
590  *   specified in @types (if @types is %NULL, then the default list of parsers
591  *   is used, see 'parse_mtd_partitions()' for more information). If none are
592  *   found this functions tries to fallback to information specified in
593  *   @parts/@nr_parts.
594  * * If any partitioning info was found, this function registers the found
595  *   partitions.
596  * * If no partitions were found this function just registers the MTD device
597  *   @mtd and exits.
598  *
599  * Returns zero in case of success and a negative error code in case of failure.
600  */
601 int mtd_device_parse_register(struct mtd_info *mtd, const char * const *types,
602                               struct mtd_part_parser_data *parser_data,
603                               const struct mtd_partition *parts,
604                               int nr_parts)
605 {
606         int err;
607         struct mtd_partition *real_parts;
608
609         err = parse_mtd_partitions(mtd, types, &real_parts, parser_data);
610         if (err <= 0 && nr_parts && parts) {
611                 real_parts = kmemdup(parts, sizeof(*parts) * nr_parts,
612                                      GFP_KERNEL);
613                 if (!real_parts)
614                         err = -ENOMEM;
615                 else
616                         err = nr_parts;
617         }
618
619         if (err > 0) {
620                 err = add_mtd_partitions(mtd, real_parts, err);
621                 kfree(real_parts);
622         } else if (err == 0) {
623                 err = add_mtd_device(mtd);
624                 if (err == 1)
625                         err = -ENODEV;
626         }
627
628         return err;
629 }
630 EXPORT_SYMBOL_GPL(mtd_device_parse_register);
631
632 /**
633  * mtd_device_unregister - unregister an existing MTD device.
634  *
635  * @master: the MTD device to unregister.  This will unregister both the master
636  *          and any partitions if registered.
637  */
638 int mtd_device_unregister(struct mtd_info *master)
639 {
640         int err;
641
642         err = del_mtd_partitions(master);
643         if (err)
644                 return err;
645
646         if (!device_is_registered(&master->dev))
647                 return 0;
648
649         return del_mtd_device(master);
650 }
651 EXPORT_SYMBOL_GPL(mtd_device_unregister);
652
653 /**
654  *      register_mtd_user - register a 'user' of MTD devices.
655  *      @new: pointer to notifier info structure
656  *
657  *      Registers a pair of callbacks function to be called upon addition
658  *      or removal of MTD devices. Causes the 'add' callback to be immediately
659  *      invoked for each MTD device currently present in the system.
660  */
661 void register_mtd_user (struct mtd_notifier *new)
662 {
663         struct mtd_info *mtd;
664
665         mutex_lock(&mtd_table_mutex);
666
667         list_add(&new->list, &mtd_notifiers);
668
669         __module_get(THIS_MODULE);
670
671         mtd_for_each_device(mtd)
672                 new->add(mtd);
673
674         mutex_unlock(&mtd_table_mutex);
675 }
676 EXPORT_SYMBOL_GPL(register_mtd_user);
677
678 /**
679  *      unregister_mtd_user - unregister a 'user' of MTD devices.
680  *      @old: pointer to notifier info structure
681  *
682  *      Removes a callback function pair from the list of 'users' to be
683  *      notified upon addition or removal of MTD devices. Causes the
684  *      'remove' callback to be immediately invoked for each MTD device
685  *      currently present in the system.
686  */
687 int unregister_mtd_user (struct mtd_notifier *old)
688 {
689         struct mtd_info *mtd;
690
691         mutex_lock(&mtd_table_mutex);
692
693         module_put(THIS_MODULE);
694
695         mtd_for_each_device(mtd)
696                 old->remove(mtd);
697
698         list_del(&old->list);
699         mutex_unlock(&mtd_table_mutex);
700         return 0;
701 }
702 EXPORT_SYMBOL_GPL(unregister_mtd_user);
703 #endif
704
705 /**
706  *      get_mtd_device - obtain a validated handle for an MTD device
707  *      @mtd: last known address of the required MTD device
708  *      @num: internal device number of the required MTD device
709  *
710  *      Given a number and NULL address, return the num'th entry in the device
711  *      table, if any.  Given an address and num == -1, search the device table
712  *      for a device with that address and return if it's still present. Given
713  *      both, return the num'th driver only if its address matches. Return
714  *      error code if not.
715  */
716 struct mtd_info *get_mtd_device(struct mtd_info *mtd, int num)
717 {
718         struct mtd_info *ret = NULL, *other;
719         int err = -ENODEV;
720
721         mutex_lock(&mtd_table_mutex);
722
723         if (num == -1) {
724                 mtd_for_each_device(other) {
725                         if (other == mtd) {
726                                 ret = mtd;
727                                 break;
728                         }
729                 }
730         } else if (num >= 0) {
731                 ret = idr_find(&mtd_idr, num);
732                 if (mtd && mtd != ret)
733                         ret = NULL;
734         }
735
736         if (!ret) {
737                 ret = ERR_PTR(err);
738                 goto out;
739         }
740
741         err = __get_mtd_device(ret);
742         if (err)
743                 ret = ERR_PTR(err);
744 out:
745         mutex_unlock(&mtd_table_mutex);
746         return ret;
747 }
748 EXPORT_SYMBOL_GPL(get_mtd_device);
749
750
751 int __get_mtd_device(struct mtd_info *mtd)
752 {
753         int err;
754
755         if (!try_module_get(mtd->owner))
756                 return -ENODEV;
757
758         if (mtd->_get_device) {
759                 err = mtd->_get_device(mtd);
760
761                 if (err) {
762                         module_put(mtd->owner);
763                         return err;
764                 }
765         }
766         mtd->usecount++;
767         return 0;
768 }
769 EXPORT_SYMBOL_GPL(__get_mtd_device);
770
771 #if CONFIG_IS_ENABLED(DM) && CONFIG_IS_ENABLED(OF_CONTROL)
772 static bool mtd_device_matches_name(struct mtd_info *mtd, const char *name)
773 {
774         struct udevice *dev = NULL;
775         bool is_part;
776
777         /*
778          * If the first character of mtd name is '/', try interpreting as OF
779          * path. Otherwise try comparing by mtd->name and mtd->dev->name.
780          */
781         if (*name == '/')
782                 device_get_global_by_ofnode(ofnode_path(name), &dev);
783
784         is_part = mtd_is_partition(mtd);
785
786         return (!is_part && dev && mtd->dev == dev) ||
787                !strcmp(name, mtd->name) ||
788                (is_part && mtd->dev && !strcmp(name, mtd->dev->name));
789 }
790 #else
791 static bool mtd_device_matches_name(struct mtd_info *mtd, const char *name)
792 {
793         return !strcmp(name, mtd->name);
794 }
795 #endif
796
797 /**
798  *      get_mtd_device_nm - obtain a validated handle for an MTD device by
799  *      device name
800  *      @name: MTD device name to open
801  *
802  *      This function returns MTD device description structure in case of
803  *      success and an error code in case of failure.
804  */
805 struct mtd_info *get_mtd_device_nm(const char *name)
806 {
807         int err = -ENODEV;
808         struct mtd_info *mtd = NULL, *other;
809
810         mutex_lock(&mtd_table_mutex);
811
812         mtd_for_each_device(other) {
813 #ifdef __UBOOT__
814                 if (mtd_device_matches_name(other, name)) {
815                         if (mtd)
816                                 printf("\nWarning: MTD name \"%s\" is not unique!\n\n",
817                                        name);
818                         mtd = other;
819                 }
820 #else /* !__UBOOT__ */
821                 if (!strcmp(name, other->name)) {
822                         mtd = other;
823                         break;
824                 }
825 #endif /* !__UBOOT__ */
826         }
827
828         if (!mtd)
829                 goto out_unlock;
830
831         err = __get_mtd_device(mtd);
832         if (err)
833                 goto out_unlock;
834
835         mutex_unlock(&mtd_table_mutex);
836         return mtd;
837
838 out_unlock:
839         mutex_unlock(&mtd_table_mutex);
840         return ERR_PTR(err);
841 }
842 EXPORT_SYMBOL_GPL(get_mtd_device_nm);
843
844 #if defined(CONFIG_CMD_MTDPARTS_SPREAD)
845 /**
846  * mtd_get_len_incl_bad
847  *
848  * Check if length including bad blocks fits into device.
849  *
850  * @param mtd an MTD device
851  * @param offset offset in flash
852  * @param length image length
853  * @return image length including bad blocks in *len_incl_bad and whether or not
854  *         the length returned was truncated in *truncated
855  */
856 void mtd_get_len_incl_bad(struct mtd_info *mtd, uint64_t offset,
857                           const uint64_t length, uint64_t *len_incl_bad,
858                           int *truncated)
859 {
860         *truncated = 0;
861         *len_incl_bad = 0;
862
863         if (!mtd->_block_isbad) {
864                 *len_incl_bad = length;
865                 return;
866         }
867
868         uint64_t len_excl_bad = 0;
869         uint64_t block_len;
870
871         while (len_excl_bad < length) {
872                 if (offset >= mtd->size) {
873                         *truncated = 1;
874                         return;
875                 }
876
877                 block_len = mtd->erasesize - (offset & (mtd->erasesize - 1));
878
879                 if (!mtd->_block_isbad(mtd, offset & ~(mtd->erasesize - 1)))
880                         len_excl_bad += block_len;
881
882                 *len_incl_bad += block_len;
883                 offset       += block_len;
884         }
885 }
886 #endif /* defined(CONFIG_CMD_MTDPARTS_SPREAD) */
887
888 void put_mtd_device(struct mtd_info *mtd)
889 {
890         mutex_lock(&mtd_table_mutex);
891         __put_mtd_device(mtd);
892         mutex_unlock(&mtd_table_mutex);
893
894 }
895 EXPORT_SYMBOL_GPL(put_mtd_device);
896
897 void __put_mtd_device(struct mtd_info *mtd)
898 {
899         --mtd->usecount;
900         BUG_ON(mtd->usecount < 0);
901
902         if (mtd->_put_device)
903                 mtd->_put_device(mtd);
904
905         module_put(mtd->owner);
906 }
907 EXPORT_SYMBOL_GPL(__put_mtd_device);
908
909 /*
910  * Erase is an asynchronous operation.  Device drivers are supposed
911  * to call instr->callback() whenever the operation completes, even
912  * if it completes with a failure.
913  * Callers are supposed to pass a callback function and wait for it
914  * to be called before writing to the block.
915  */
916 int mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
917 {
918         if (instr->addr > mtd->size || instr->len > mtd->size - instr->addr)
919                 return -EINVAL;
920         if (!(mtd->flags & MTD_WRITEABLE))
921                 return -EROFS;
922         instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
923         if (!instr->len) {
924                 instr->state = MTD_ERASE_DONE;
925                 mtd_erase_callback(instr);
926                 return 0;
927         }
928         return mtd->_erase(mtd, instr);
929 }
930 EXPORT_SYMBOL_GPL(mtd_erase);
931
932 #ifndef __UBOOT__
933 /*
934  * This stuff for eXecute-In-Place. phys is optional and may be set to NULL.
935  */
936 int mtd_point(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
937               void **virt, resource_size_t *phys)
938 {
939         *retlen = 0;
940         *virt = NULL;
941         if (phys)
942                 *phys = 0;
943         if (!mtd->_point)
944                 return -EOPNOTSUPP;
945         if (from < 0 || from > mtd->size || len > mtd->size - from)
946                 return -EINVAL;
947         if (!len)
948                 return 0;
949         return mtd->_point(mtd, from, len, retlen, virt, phys);
950 }
951 EXPORT_SYMBOL_GPL(mtd_point);
952
953 /* We probably shouldn't allow XIP if the unpoint isn't a NULL */
954 int mtd_unpoint(struct mtd_info *mtd, loff_t from, size_t len)
955 {
956         if (!mtd->_point)
957                 return -EOPNOTSUPP;
958         if (from < 0 || from > mtd->size || len > mtd->size - from)
959                 return -EINVAL;
960         if (!len)
961                 return 0;
962         return mtd->_unpoint(mtd, from, len);
963 }
964 EXPORT_SYMBOL_GPL(mtd_unpoint);
965 #endif
966
967 /*
968  * Allow NOMMU mmap() to directly map the device (if not NULL)
969  * - return the address to which the offset maps
970  * - return -ENOSYS to indicate refusal to do the mapping
971  */
972 unsigned long mtd_get_unmapped_area(struct mtd_info *mtd, unsigned long len,
973                                     unsigned long offset, unsigned long flags)
974 {
975         if (!mtd->_get_unmapped_area)
976                 return -EOPNOTSUPP;
977         if (offset > mtd->size || len > mtd->size - offset)
978                 return -EINVAL;
979         return mtd->_get_unmapped_area(mtd, len, offset, flags);
980 }
981 EXPORT_SYMBOL_GPL(mtd_get_unmapped_area);
982
983 int mtd_read(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
984              u_char *buf)
985 {
986         int ret_code;
987         *retlen = 0;
988         if (from < 0 || from > mtd->size || len > mtd->size - from)
989                 return -EINVAL;
990         if (!len)
991                 return 0;
992
993         /*
994          * In the absence of an error, drivers return a non-negative integer
995          * representing the maximum number of bitflips that were corrected on
996          * any one ecc region (if applicable; zero otherwise).
997          */
998         if (mtd->_read) {
999                 ret_code = mtd->_read(mtd, from, len, retlen, buf);
1000         } else if (mtd->_read_oob) {
1001                 struct mtd_oob_ops ops = {
1002                         .len = len,
1003                         .datbuf = buf,
1004                 };
1005
1006                 ret_code = mtd->_read_oob(mtd, from, &ops);
1007                 *retlen = ops.retlen;
1008         } else {
1009                 return -ENOTSUPP;
1010         }
1011
1012         if (unlikely(ret_code < 0))
1013                 return ret_code;
1014         if (mtd->ecc_strength == 0)
1015                 return 0;       /* device lacks ecc */
1016         return ret_code >= mtd->bitflip_threshold ? -EUCLEAN : 0;
1017 }
1018 EXPORT_SYMBOL_GPL(mtd_read);
1019
1020 int mtd_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1021               const u_char *buf)
1022 {
1023         *retlen = 0;
1024         if (to < 0 || to > mtd->size || len > mtd->size - to)
1025                 return -EINVAL;
1026         if ((!mtd->_write && !mtd->_write_oob) ||
1027             !(mtd->flags & MTD_WRITEABLE))
1028                 return -EROFS;
1029         if (!len)
1030                 return 0;
1031
1032         if (!mtd->_write) {
1033                 struct mtd_oob_ops ops = {
1034                         .len = len,
1035                         .datbuf = (u8 *)buf,
1036                 };
1037                 int ret;
1038
1039                 ret = mtd->_write_oob(mtd, to, &ops);
1040                 *retlen = ops.retlen;
1041                 return ret;
1042         }
1043
1044         return mtd->_write(mtd, to, len, retlen, buf);
1045 }
1046 EXPORT_SYMBOL_GPL(mtd_write);
1047
1048 /*
1049  * In blackbox flight recorder like scenarios we want to make successful writes
1050  * in interrupt context. panic_write() is only intended to be called when its
1051  * known the kernel is about to panic and we need the write to succeed. Since
1052  * the kernel is not going to be running for much longer, this function can
1053  * break locks and delay to ensure the write succeeds (but not sleep).
1054  */
1055 int mtd_panic_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1056                     const u_char *buf)
1057 {
1058         *retlen = 0;
1059         if (!mtd->_panic_write)
1060                 return -EOPNOTSUPP;
1061         if (to < 0 || to > mtd->size || len > mtd->size - to)
1062                 return -EINVAL;
1063         if (!(mtd->flags & MTD_WRITEABLE))
1064                 return -EROFS;
1065         if (!len)
1066                 return 0;
1067         return mtd->_panic_write(mtd, to, len, retlen, buf);
1068 }
1069 EXPORT_SYMBOL_GPL(mtd_panic_write);
1070
1071 static int mtd_check_oob_ops(struct mtd_info *mtd, loff_t offs,
1072                              struct mtd_oob_ops *ops)
1073 {
1074         /*
1075          * Some users are setting ->datbuf or ->oobbuf to NULL, but are leaving
1076          * ->len or ->ooblen uninitialized. Force ->len and ->ooblen to 0 in
1077          *  this case.
1078          */
1079         if (!ops->datbuf)
1080                 ops->len = 0;
1081
1082         if (!ops->oobbuf)
1083                 ops->ooblen = 0;
1084
1085         if (offs < 0 || offs + ops->len > mtd->size)
1086                 return -EINVAL;
1087
1088         if (ops->ooblen) {
1089                 size_t maxooblen;
1090
1091                 if (ops->ooboffs >= mtd_oobavail(mtd, ops))
1092                         return -EINVAL;
1093
1094                 maxooblen = ((size_t)(mtd_div_by_ws(mtd->size, mtd) -
1095                                       mtd_div_by_ws(offs, mtd)) *
1096                              mtd_oobavail(mtd, ops)) - ops->ooboffs;
1097                 if (ops->ooblen > maxooblen)
1098                         return -EINVAL;
1099         }
1100
1101         return 0;
1102 }
1103
1104 int mtd_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
1105 {
1106         int ret_code;
1107         ops->retlen = ops->oobretlen = 0;
1108
1109         ret_code = mtd_check_oob_ops(mtd, from, ops);
1110         if (ret_code)
1111                 return ret_code;
1112
1113         /* Check the validity of a potential fallback on mtd->_read */
1114         if (!mtd->_read_oob && (!mtd->_read || ops->oobbuf))
1115                 return -EOPNOTSUPP;
1116
1117         if (mtd->_read_oob)
1118                 ret_code = mtd->_read_oob(mtd, from, ops);
1119         else
1120                 ret_code = mtd->_read(mtd, from, ops->len, &ops->retlen,
1121                                       ops->datbuf);
1122
1123         /*
1124          * In cases where ops->datbuf != NULL, mtd->_read_oob() has semantics
1125          * similar to mtd->_read(), returning a non-negative integer
1126          * representing max bitflips. In other cases, mtd->_read_oob() may
1127          * return -EUCLEAN. In all cases, perform similar logic to mtd_read().
1128          */
1129         if (unlikely(ret_code < 0))
1130                 return ret_code;
1131         if (mtd->ecc_strength == 0)
1132                 return 0;       /* device lacks ecc */
1133         return ret_code >= mtd->bitflip_threshold ? -EUCLEAN : 0;
1134 }
1135 EXPORT_SYMBOL_GPL(mtd_read_oob);
1136
1137 int mtd_write_oob(struct mtd_info *mtd, loff_t to,
1138                                 struct mtd_oob_ops *ops)
1139 {
1140         int ret;
1141
1142         ops->retlen = ops->oobretlen = 0;
1143
1144         if (!(mtd->flags & MTD_WRITEABLE))
1145                 return -EROFS;
1146
1147         ret = mtd_check_oob_ops(mtd, to, ops);
1148         if (ret)
1149                 return ret;
1150
1151         /* Check the validity of a potential fallback on mtd->_write */
1152         if (!mtd->_write_oob && (!mtd->_write || ops->oobbuf))
1153                 return -EOPNOTSUPP;
1154
1155         if (mtd->_write_oob)
1156                 return mtd->_write_oob(mtd, to, ops);
1157         else
1158                 return mtd->_write(mtd, to, ops->len, &ops->retlen,
1159                                    ops->datbuf);
1160 }
1161 EXPORT_SYMBOL_GPL(mtd_write_oob);
1162
1163 /**
1164  * mtd_ooblayout_ecc - Get the OOB region definition of a specific ECC section
1165  * @mtd: MTD device structure
1166  * @section: ECC section. Depending on the layout you may have all the ECC
1167  *           bytes stored in a single contiguous section, or one section
1168  *           per ECC chunk (and sometime several sections for a single ECC
1169  *           ECC chunk)
1170  * @oobecc: OOB region struct filled with the appropriate ECC position
1171  *          information
1172  *
1173  * This function returns ECC section information in the OOB area. If you want
1174  * to get all the ECC bytes information, then you should call
1175  * mtd_ooblayout_ecc(mtd, section++, oobecc) until it returns -ERANGE.
1176  *
1177  * Returns zero on success, a negative error code otherwise.
1178  */
1179 int mtd_ooblayout_ecc(struct mtd_info *mtd, int section,
1180                       struct mtd_oob_region *oobecc)
1181 {
1182         memset(oobecc, 0, sizeof(*oobecc));
1183
1184         if (!mtd || section < 0)
1185                 return -EINVAL;
1186
1187         if (!mtd->ooblayout || !mtd->ooblayout->ecc)
1188                 return -ENOTSUPP;
1189
1190         return mtd->ooblayout->ecc(mtd, section, oobecc);
1191 }
1192 EXPORT_SYMBOL_GPL(mtd_ooblayout_ecc);
1193
1194 /**
1195  * mtd_ooblayout_free - Get the OOB region definition of a specific free
1196  *                      section
1197  * @mtd: MTD device structure
1198  * @section: Free section you are interested in. Depending on the layout
1199  *           you may have all the free bytes stored in a single contiguous
1200  *           section, or one section per ECC chunk plus an extra section
1201  *           for the remaining bytes (or other funky layout).
1202  * @oobfree: OOB region struct filled with the appropriate free position
1203  *           information
1204  *
1205  * This function returns free bytes position in the OOB area. If you want
1206  * to get all the free bytes information, then you should call
1207  * mtd_ooblayout_free(mtd, section++, oobfree) until it returns -ERANGE.
1208  *
1209  * Returns zero on success, a negative error code otherwise.
1210  */
1211 int mtd_ooblayout_free(struct mtd_info *mtd, int section,
1212                        struct mtd_oob_region *oobfree)
1213 {
1214         memset(oobfree, 0, sizeof(*oobfree));
1215
1216         if (!mtd || section < 0)
1217                 return -EINVAL;
1218
1219         if (!mtd->ooblayout || !mtd->ooblayout->rfree)
1220                 return -ENOTSUPP;
1221
1222         return mtd->ooblayout->rfree(mtd, section, oobfree);
1223 }
1224 EXPORT_SYMBOL_GPL(mtd_ooblayout_free);
1225
1226 /**
1227  * mtd_ooblayout_find_region - Find the region attached to a specific byte
1228  * @mtd: mtd info structure
1229  * @byte: the byte we are searching for
1230  * @sectionp: pointer where the section id will be stored
1231  * @oobregion: used to retrieve the ECC position
1232  * @iter: iterator function. Should be either mtd_ooblayout_free or
1233  *        mtd_ooblayout_ecc depending on the region type you're searching for
1234  *
1235  * This function returns the section id and oobregion information of a
1236  * specific byte. For example, say you want to know where the 4th ECC byte is
1237  * stored, you'll use:
1238  *
1239  * mtd_ooblayout_find_region(mtd, 3, &section, &oobregion, mtd_ooblayout_ecc);
1240  *
1241  * Returns zero on success, a negative error code otherwise.
1242  */
1243 static int mtd_ooblayout_find_region(struct mtd_info *mtd, int byte,
1244                                 int *sectionp, struct mtd_oob_region *oobregion,
1245                                 int (*iter)(struct mtd_info *,
1246                                             int section,
1247                                             struct mtd_oob_region *oobregion))
1248 {
1249         int pos = 0, ret, section = 0;
1250
1251         memset(oobregion, 0, sizeof(*oobregion));
1252
1253         while (1) {
1254                 ret = iter(mtd, section, oobregion);
1255                 if (ret)
1256                         return ret;
1257
1258                 if (pos + oobregion->length > byte)
1259                         break;
1260
1261                 pos += oobregion->length;
1262                 section++;
1263         }
1264
1265         /*
1266          * Adjust region info to make it start at the beginning at the
1267          * 'start' ECC byte.
1268          */
1269         oobregion->offset += byte - pos;
1270         oobregion->length -= byte - pos;
1271         *sectionp = section;
1272
1273         return 0;
1274 }
1275
1276 /**
1277  * mtd_ooblayout_find_eccregion - Find the ECC region attached to a specific
1278  *                                ECC byte
1279  * @mtd: mtd info structure
1280  * @eccbyte: the byte we are searching for
1281  * @sectionp: pointer where the section id will be stored
1282  * @oobregion: OOB region information
1283  *
1284  * Works like mtd_ooblayout_find_region() except it searches for a specific ECC
1285  * byte.
1286  *
1287  * Returns zero on success, a negative error code otherwise.
1288  */
1289 int mtd_ooblayout_find_eccregion(struct mtd_info *mtd, int eccbyte,
1290                                  int *section,
1291                                  struct mtd_oob_region *oobregion)
1292 {
1293         return mtd_ooblayout_find_region(mtd, eccbyte, section, oobregion,
1294                                          mtd_ooblayout_ecc);
1295 }
1296 EXPORT_SYMBOL_GPL(mtd_ooblayout_find_eccregion);
1297
1298 /**
1299  * mtd_ooblayout_get_bytes - Extract OOB bytes from the oob buffer
1300  * @mtd: mtd info structure
1301  * @buf: destination buffer to store OOB bytes
1302  * @oobbuf: OOB buffer
1303  * @start: first byte to retrieve
1304  * @nbytes: number of bytes to retrieve
1305  * @iter: section iterator
1306  *
1307  * Extract bytes attached to a specific category (ECC or free)
1308  * from the OOB buffer and copy them into buf.
1309  *
1310  * Returns zero on success, a negative error code otherwise.
1311  */
1312 static int mtd_ooblayout_get_bytes(struct mtd_info *mtd, u8 *buf,
1313                                 const u8 *oobbuf, int start, int nbytes,
1314                                 int (*iter)(struct mtd_info *,
1315                                             int section,
1316                                             struct mtd_oob_region *oobregion))
1317 {
1318         struct mtd_oob_region oobregion;
1319         int section, ret;
1320
1321         ret = mtd_ooblayout_find_region(mtd, start, &section,
1322                                         &oobregion, iter);
1323
1324         while (!ret) {
1325                 int cnt;
1326
1327                 cnt = min_t(int, nbytes, oobregion.length);
1328                 memcpy(buf, oobbuf + oobregion.offset, cnt);
1329                 buf += cnt;
1330                 nbytes -= cnt;
1331
1332                 if (!nbytes)
1333                         break;
1334
1335                 ret = iter(mtd, ++section, &oobregion);
1336         }
1337
1338         return ret;
1339 }
1340
1341 /**
1342  * mtd_ooblayout_set_bytes - put OOB bytes into the oob buffer
1343  * @mtd: mtd info structure
1344  * @buf: source buffer to get OOB bytes from
1345  * @oobbuf: OOB buffer
1346  * @start: first OOB byte to set
1347  * @nbytes: number of OOB bytes to set
1348  * @iter: section iterator
1349  *
1350  * Fill the OOB buffer with data provided in buf. The category (ECC or free)
1351  * is selected by passing the appropriate iterator.
1352  *
1353  * Returns zero on success, a negative error code otherwise.
1354  */
1355 static int mtd_ooblayout_set_bytes(struct mtd_info *mtd, const u8 *buf,
1356                                 u8 *oobbuf, int start, int nbytes,
1357                                 int (*iter)(struct mtd_info *,
1358                                             int section,
1359                                             struct mtd_oob_region *oobregion))
1360 {
1361         struct mtd_oob_region oobregion;
1362         int section, ret;
1363
1364         ret = mtd_ooblayout_find_region(mtd, start, &section,
1365                                         &oobregion, iter);
1366
1367         while (!ret) {
1368                 int cnt;
1369
1370                 cnt = min_t(int, nbytes, oobregion.length);
1371                 memcpy(oobbuf + oobregion.offset, buf, cnt);
1372                 buf += cnt;
1373                 nbytes -= cnt;
1374
1375                 if (!nbytes)
1376                         break;
1377
1378                 ret = iter(mtd, ++section, &oobregion);
1379         }
1380
1381         return ret;
1382 }
1383
1384 /**
1385  * mtd_ooblayout_count_bytes - count the number of bytes in a OOB category
1386  * @mtd: mtd info structure
1387  * @iter: category iterator
1388  *
1389  * Count the number of bytes in a given category.
1390  *
1391  * Returns a positive value on success, a negative error code otherwise.
1392  */
1393 static int mtd_ooblayout_count_bytes(struct mtd_info *mtd,
1394                                 int (*iter)(struct mtd_info *,
1395                                             int section,
1396                                             struct mtd_oob_region *oobregion))
1397 {
1398         struct mtd_oob_region oobregion;
1399         int section = 0, ret, nbytes = 0;
1400
1401         while (1) {
1402                 ret = iter(mtd, section++, &oobregion);
1403                 if (ret) {
1404                         if (ret == -ERANGE)
1405                                 ret = nbytes;
1406                         break;
1407                 }
1408
1409                 nbytes += oobregion.length;
1410         }
1411
1412         return ret;
1413 }
1414
1415 /**
1416  * mtd_ooblayout_get_eccbytes - extract ECC bytes from the oob buffer
1417  * @mtd: mtd info structure
1418  * @eccbuf: destination buffer to store ECC bytes
1419  * @oobbuf: OOB buffer
1420  * @start: first ECC byte to retrieve
1421  * @nbytes: number of ECC bytes to retrieve
1422  *
1423  * Works like mtd_ooblayout_get_bytes(), except it acts on ECC bytes.
1424  *
1425  * Returns zero on success, a negative error code otherwise.
1426  */
1427 int mtd_ooblayout_get_eccbytes(struct mtd_info *mtd, u8 *eccbuf,
1428                                const u8 *oobbuf, int start, int nbytes)
1429 {
1430         return mtd_ooblayout_get_bytes(mtd, eccbuf, oobbuf, start, nbytes,
1431                                        mtd_ooblayout_ecc);
1432 }
1433 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_eccbytes);
1434
1435 /**
1436  * mtd_ooblayout_set_eccbytes - set ECC bytes into the oob buffer
1437  * @mtd: mtd info structure
1438  * @eccbuf: source buffer to get ECC bytes from
1439  * @oobbuf: OOB buffer
1440  * @start: first ECC byte to set
1441  * @nbytes: number of ECC bytes to set
1442  *
1443  * Works like mtd_ooblayout_set_bytes(), except it acts on ECC bytes.
1444  *
1445  * Returns zero on success, a negative error code otherwise.
1446  */
1447 int mtd_ooblayout_set_eccbytes(struct mtd_info *mtd, const u8 *eccbuf,
1448                                u8 *oobbuf, int start, int nbytes)
1449 {
1450         return mtd_ooblayout_set_bytes(mtd, eccbuf, oobbuf, start, nbytes,
1451                                        mtd_ooblayout_ecc);
1452 }
1453 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_eccbytes);
1454
1455 /**
1456  * mtd_ooblayout_get_databytes - extract data bytes from the oob buffer
1457  * @mtd: mtd info structure
1458  * @databuf: destination buffer to store ECC bytes
1459  * @oobbuf: OOB buffer
1460  * @start: first ECC byte to retrieve
1461  * @nbytes: number of ECC bytes to retrieve
1462  *
1463  * Works like mtd_ooblayout_get_bytes(), except it acts on free bytes.
1464  *
1465  * Returns zero on success, a negative error code otherwise.
1466  */
1467 int mtd_ooblayout_get_databytes(struct mtd_info *mtd, u8 *databuf,
1468                                 const u8 *oobbuf, int start, int nbytes)
1469 {
1470         return mtd_ooblayout_get_bytes(mtd, databuf, oobbuf, start, nbytes,
1471                                        mtd_ooblayout_free);
1472 }
1473 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_databytes);
1474
1475 /**
1476  * mtd_ooblayout_get_eccbytes - set data bytes into the oob buffer
1477  * @mtd: mtd info structure
1478  * @eccbuf: source buffer to get data bytes from
1479  * @oobbuf: OOB buffer
1480  * @start: first ECC byte to set
1481  * @nbytes: number of ECC bytes to set
1482  *
1483  * Works like mtd_ooblayout_get_bytes(), except it acts on free bytes.
1484  *
1485  * Returns zero on success, a negative error code otherwise.
1486  */
1487 int mtd_ooblayout_set_databytes(struct mtd_info *mtd, const u8 *databuf,
1488                                 u8 *oobbuf, int start, int nbytes)
1489 {
1490         return mtd_ooblayout_set_bytes(mtd, databuf, oobbuf, start, nbytes,
1491                                        mtd_ooblayout_free);
1492 }
1493 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_databytes);
1494
1495 /**
1496  * mtd_ooblayout_count_freebytes - count the number of free bytes in OOB
1497  * @mtd: mtd info structure
1498  *
1499  * Works like mtd_ooblayout_count_bytes(), except it count free bytes.
1500  *
1501  * Returns zero on success, a negative error code otherwise.
1502  */
1503 int mtd_ooblayout_count_freebytes(struct mtd_info *mtd)
1504 {
1505         return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_free);
1506 }
1507 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_freebytes);
1508
1509 /**
1510  * mtd_ooblayout_count_freebytes - count the number of ECC bytes in OOB
1511  * @mtd: mtd info structure
1512  *
1513  * Works like mtd_ooblayout_count_bytes(), except it count ECC bytes.
1514  *
1515  * Returns zero on success, a negative error code otherwise.
1516  */
1517 int mtd_ooblayout_count_eccbytes(struct mtd_info *mtd)
1518 {
1519         return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_ecc);
1520 }
1521 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_eccbytes);
1522
1523 /*
1524  * Method to access the protection register area, present in some flash
1525  * devices. The user data is one time programmable but the factory data is read
1526  * only.
1527  */
1528 int mtd_get_fact_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
1529                            struct otp_info *buf)
1530 {
1531         if (!mtd->_get_fact_prot_info)
1532                 return -EOPNOTSUPP;
1533         if (!len)
1534                 return 0;
1535         return mtd->_get_fact_prot_info(mtd, len, retlen, buf);
1536 }
1537 EXPORT_SYMBOL_GPL(mtd_get_fact_prot_info);
1538
1539 int mtd_read_fact_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
1540                            size_t *retlen, u_char *buf)
1541 {
1542         *retlen = 0;
1543         if (!mtd->_read_fact_prot_reg)
1544                 return -EOPNOTSUPP;
1545         if (!len)
1546                 return 0;
1547         return mtd->_read_fact_prot_reg(mtd, from, len, retlen, buf);
1548 }
1549 EXPORT_SYMBOL_GPL(mtd_read_fact_prot_reg);
1550
1551 int mtd_get_user_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
1552                            struct otp_info *buf)
1553 {
1554         if (!mtd->_get_user_prot_info)
1555                 return -EOPNOTSUPP;
1556         if (!len)
1557                 return 0;
1558         return mtd->_get_user_prot_info(mtd, len, retlen, buf);
1559 }
1560 EXPORT_SYMBOL_GPL(mtd_get_user_prot_info);
1561
1562 int mtd_read_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
1563                            size_t *retlen, u_char *buf)
1564 {
1565         *retlen = 0;
1566         if (!mtd->_read_user_prot_reg)
1567                 return -EOPNOTSUPP;
1568         if (!len)
1569                 return 0;
1570         return mtd->_read_user_prot_reg(mtd, from, len, retlen, buf);
1571 }
1572 EXPORT_SYMBOL_GPL(mtd_read_user_prot_reg);
1573
1574 int mtd_write_user_prot_reg(struct mtd_info *mtd, loff_t to, size_t len,
1575                             size_t *retlen, u_char *buf)
1576 {
1577         int ret;
1578
1579         *retlen = 0;
1580         if (!mtd->_write_user_prot_reg)
1581                 return -EOPNOTSUPP;
1582         if (!len)
1583                 return 0;
1584         ret = mtd->_write_user_prot_reg(mtd, to, len, retlen, buf);
1585         if (ret)
1586                 return ret;
1587
1588         /*
1589          * If no data could be written at all, we are out of memory and
1590          * must return -ENOSPC.
1591          */
1592         return (*retlen) ? 0 : -ENOSPC;
1593 }
1594 EXPORT_SYMBOL_GPL(mtd_write_user_prot_reg);
1595
1596 int mtd_lock_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len)
1597 {
1598         if (!mtd->_lock_user_prot_reg)
1599                 return -EOPNOTSUPP;
1600         if (!len)
1601                 return 0;
1602         return mtd->_lock_user_prot_reg(mtd, from, len);
1603 }
1604 EXPORT_SYMBOL_GPL(mtd_lock_user_prot_reg);
1605
1606 /* Chip-supported device locking */
1607 int mtd_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1608 {
1609         if (!mtd->_lock)
1610                 return -EOPNOTSUPP;
1611         if (ofs < 0 || ofs > mtd->size || len > mtd->size - ofs)
1612                 return -EINVAL;
1613         if (!len)
1614                 return 0;
1615         return mtd->_lock(mtd, ofs, len);
1616 }
1617 EXPORT_SYMBOL_GPL(mtd_lock);
1618
1619 int mtd_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1620 {
1621         if (!mtd->_unlock)
1622                 return -EOPNOTSUPP;
1623         if (ofs < 0 || ofs > mtd->size || len > mtd->size - ofs)
1624                 return -EINVAL;
1625         if (!len)
1626                 return 0;
1627         return mtd->_unlock(mtd, ofs, len);
1628 }
1629 EXPORT_SYMBOL_GPL(mtd_unlock);
1630
1631 int mtd_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1632 {
1633         if (!mtd->_is_locked)
1634                 return -EOPNOTSUPP;
1635         if (ofs < 0 || ofs > mtd->size || len > mtd->size - ofs)
1636                 return -EINVAL;
1637         if (!len)
1638                 return 0;
1639         return mtd->_is_locked(mtd, ofs, len);
1640 }
1641 EXPORT_SYMBOL_GPL(mtd_is_locked);
1642
1643 int mtd_block_isreserved(struct mtd_info *mtd, loff_t ofs)
1644 {
1645         if (ofs < 0 || ofs > mtd->size)
1646                 return -EINVAL;
1647         if (!mtd->_block_isreserved)
1648                 return 0;
1649         return mtd->_block_isreserved(mtd, ofs);
1650 }
1651 EXPORT_SYMBOL_GPL(mtd_block_isreserved);
1652
1653 int mtd_block_isbad(struct mtd_info *mtd, loff_t ofs)
1654 {
1655         if (ofs < 0 || ofs > mtd->size)
1656                 return -EINVAL;
1657         if (!mtd->_block_isbad)
1658                 return 0;
1659         return mtd->_block_isbad(mtd, ofs);
1660 }
1661 EXPORT_SYMBOL_GPL(mtd_block_isbad);
1662
1663 int mtd_block_markbad(struct mtd_info *mtd, loff_t ofs)
1664 {
1665         if (!mtd->_block_markbad)
1666                 return -EOPNOTSUPP;
1667         if (ofs < 0 || ofs > mtd->size)
1668                 return -EINVAL;
1669         if (!(mtd->flags & MTD_WRITEABLE))
1670                 return -EROFS;
1671         return mtd->_block_markbad(mtd, ofs);
1672 }
1673 EXPORT_SYMBOL_GPL(mtd_block_markbad);
1674
1675 #ifndef __UBOOT__
1676 /*
1677  * default_mtd_writev - the default writev method
1678  * @mtd: mtd device description object pointer
1679  * @vecs: the vectors to write
1680  * @count: count of vectors in @vecs
1681  * @to: the MTD device offset to write to
1682  * @retlen: on exit contains the count of bytes written to the MTD device.
1683  *
1684  * This function returns zero in case of success and a negative error code in
1685  * case of failure.
1686  */
1687 static int default_mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
1688                               unsigned long count, loff_t to, size_t *retlen)
1689 {
1690         unsigned long i;
1691         size_t totlen = 0, thislen;
1692         int ret = 0;
1693
1694         for (i = 0; i < count; i++) {
1695                 if (!vecs[i].iov_len)
1696                         continue;
1697                 ret = mtd_write(mtd, to, vecs[i].iov_len, &thislen,
1698                                 vecs[i].iov_base);
1699                 totlen += thislen;
1700                 if (ret || thislen != vecs[i].iov_len)
1701                         break;
1702                 to += vecs[i].iov_len;
1703         }
1704         *retlen = totlen;
1705         return ret;
1706 }
1707
1708 /*
1709  * mtd_writev - the vector-based MTD write method
1710  * @mtd: mtd device description object pointer
1711  * @vecs: the vectors to write
1712  * @count: count of vectors in @vecs
1713  * @to: the MTD device offset to write to
1714  * @retlen: on exit contains the count of bytes written to the MTD device.
1715  *
1716  * This function returns zero in case of success and a negative error code in
1717  * case of failure.
1718  */
1719 int mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
1720                unsigned long count, loff_t to, size_t *retlen)
1721 {
1722         *retlen = 0;
1723         if (!(mtd->flags & MTD_WRITEABLE))
1724                 return -EROFS;
1725         if (!mtd->_writev)
1726                 return default_mtd_writev(mtd, vecs, count, to, retlen);
1727         return mtd->_writev(mtd, vecs, count, to, retlen);
1728 }
1729 EXPORT_SYMBOL_GPL(mtd_writev);
1730
1731 /**
1732  * mtd_kmalloc_up_to - allocate a contiguous buffer up to the specified size
1733  * @mtd: mtd device description object pointer
1734  * @size: a pointer to the ideal or maximum size of the allocation, points
1735  *        to the actual allocation size on success.
1736  *
1737  * This routine attempts to allocate a contiguous kernel buffer up to
1738  * the specified size, backing off the size of the request exponentially
1739  * until the request succeeds or until the allocation size falls below
1740  * the system page size. This attempts to make sure it does not adversely
1741  * impact system performance, so when allocating more than one page, we
1742  * ask the memory allocator to avoid re-trying, swapping, writing back
1743  * or performing I/O.
1744  *
1745  * Note, this function also makes sure that the allocated buffer is aligned to
1746  * the MTD device's min. I/O unit, i.e. the "mtd->writesize" value.
1747  *
1748  * This is called, for example by mtd_{read,write} and jffs2_scan_medium,
1749  * to handle smaller (i.e. degraded) buffer allocations under low- or
1750  * fragmented-memory situations where such reduced allocations, from a
1751  * requested ideal, are allowed.
1752  *
1753  * Returns a pointer to the allocated buffer on success; otherwise, NULL.
1754  */
1755 void *mtd_kmalloc_up_to(const struct mtd_info *mtd, size_t *size)
1756 {
1757         gfp_t flags = __GFP_NOWARN | __GFP_WAIT |
1758                        __GFP_NORETRY | __GFP_NO_KSWAPD;
1759         size_t min_alloc = max_t(size_t, mtd->writesize, PAGE_SIZE);
1760         void *kbuf;
1761
1762         *size = min_t(size_t, *size, KMALLOC_MAX_SIZE);
1763
1764         while (*size > min_alloc) {
1765                 kbuf = kmalloc(*size, flags);
1766                 if (kbuf)
1767                         return kbuf;
1768
1769                 *size >>= 1;
1770                 *size = ALIGN(*size, mtd->writesize);
1771         }
1772
1773         /*
1774          * For the last resort allocation allow 'kmalloc()' to do all sorts of
1775          * things (write-back, dropping caches, etc) by using GFP_KERNEL.
1776          */
1777         return kmalloc(*size, GFP_KERNEL);
1778 }
1779 EXPORT_SYMBOL_GPL(mtd_kmalloc_up_to);
1780 #endif
1781
1782 #ifdef CONFIG_PROC_FS
1783
1784 /*====================================================================*/
1785 /* Support for /proc/mtd */
1786
1787 static int mtd_proc_show(struct seq_file *m, void *v)
1788 {
1789         struct mtd_info *mtd;
1790
1791         seq_puts(m, "dev:    size   erasesize  name\n");
1792         mutex_lock(&mtd_table_mutex);
1793         mtd_for_each_device(mtd) {
1794                 seq_printf(m, "mtd%d: %8.8llx %8.8x \"%s\"\n",
1795                            mtd->index, (unsigned long long)mtd->size,
1796                            mtd->erasesize, mtd->name);
1797         }
1798         mutex_unlock(&mtd_table_mutex);
1799         return 0;
1800 }
1801
1802 static int mtd_proc_open(struct inode *inode, struct file *file)
1803 {
1804         return single_open(file, mtd_proc_show, NULL);
1805 }
1806
1807 static const struct file_operations mtd_proc_ops = {
1808         .open           = mtd_proc_open,
1809         .read           = seq_read,
1810         .llseek         = seq_lseek,
1811         .release        = single_release,
1812 };
1813 #endif /* CONFIG_PROC_FS */
1814
1815 /*====================================================================*/
1816 /* Init code */
1817
1818 #ifndef __UBOOT__
1819 static int __init mtd_bdi_init(struct backing_dev_info *bdi, const char *name)
1820 {
1821         int ret;
1822
1823         ret = bdi_init(bdi);
1824         if (!ret)
1825                 ret = bdi_register(bdi, NULL, "%s", name);
1826
1827         if (ret)
1828                 bdi_destroy(bdi);
1829
1830         return ret;
1831 }
1832
1833 static struct proc_dir_entry *proc_mtd;
1834
1835 static int __init init_mtd(void)
1836 {
1837         int ret;
1838
1839         ret = class_register(&mtd_class);
1840         if (ret)
1841                 goto err_reg;
1842
1843         ret = mtd_bdi_init(&mtd_bdi_unmappable, "mtd-unmap");
1844         if (ret)
1845                 goto err_bdi1;
1846
1847         ret = mtd_bdi_init(&mtd_bdi_ro_mappable, "mtd-romap");
1848         if (ret)
1849                 goto err_bdi2;
1850
1851         ret = mtd_bdi_init(&mtd_bdi_rw_mappable, "mtd-rwmap");
1852         if (ret)
1853                 goto err_bdi3;
1854
1855         proc_mtd = proc_create("mtd", 0, NULL, &mtd_proc_ops);
1856
1857         ret = init_mtdchar();
1858         if (ret)
1859                 goto out_procfs;
1860
1861         return 0;
1862
1863 out_procfs:
1864         if (proc_mtd)
1865                 remove_proc_entry("mtd", NULL);
1866 err_bdi3:
1867         bdi_destroy(&mtd_bdi_ro_mappable);
1868 err_bdi2:
1869         bdi_destroy(&mtd_bdi_unmappable);
1870 err_bdi1:
1871         class_unregister(&mtd_class);
1872 err_reg:
1873         pr_err("Error registering mtd class or bdi: %d\n", ret);
1874         return ret;
1875 }
1876
1877 static void __exit cleanup_mtd(void)
1878 {
1879         cleanup_mtdchar();
1880         if (proc_mtd)
1881                 remove_proc_entry("mtd", NULL);
1882         class_unregister(&mtd_class);
1883         bdi_destroy(&mtd_bdi_unmappable);
1884         bdi_destroy(&mtd_bdi_ro_mappable);
1885         bdi_destroy(&mtd_bdi_rw_mappable);
1886 }
1887
1888 module_init(init_mtd);
1889 module_exit(cleanup_mtd);
1890 #endif
1891
1892 MODULE_LICENSE("GPL");
1893 MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
1894 MODULE_DESCRIPTION("Core MTD registration and access routines");