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