Add the rt linux 4.1.3-rt3 as base
[kvmfornfv.git] / kernel / drivers / mtd / mtdcore.c
1 /*
2  * Core registration and callback routines for MTD
3  * drivers and users.
4  *
5  * Copyright © 1999-2010 David Woodhouse <dwmw2@infradead.org>
6  * Copyright © 2006      Red Hat UK Limited 
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include <linux/module.h>
25 #include <linux/kernel.h>
26 #include <linux/ptrace.h>
27 #include <linux/seq_file.h>
28 #include <linux/string.h>
29 #include <linux/timer.h>
30 #include <linux/major.h>
31 #include <linux/fs.h>
32 #include <linux/err.h>
33 #include <linux/ioctl.h>
34 #include <linux/init.h>
35 #include <linux/proc_fs.h>
36 #include <linux/idr.h>
37 #include <linux/backing-dev.h>
38 #include <linux/gfp.h>
39 #include <linux/slab.h>
40 #include <linux/reboot.h>
41 #include <linux/kconfig.h>
42
43 #include <linux/mtd/mtd.h>
44 #include <linux/mtd/partitions.h>
45
46 #include "mtdcore.h"
47
48 static struct backing_dev_info mtd_bdi = {
49 };
50
51 static int mtd_cls_suspend(struct device *dev, pm_message_t state);
52 static int mtd_cls_resume(struct device *dev);
53
54 static struct class mtd_class = {
55         .name = "mtd",
56         .owner = THIS_MODULE,
57         .suspend = mtd_cls_suspend,
58         .resume = mtd_cls_resume,
59 };
60
61 static DEFINE_IDR(mtd_idr);
62
63 /* These are exported solely for the purpose of mtd_blkdevs.c. You
64    should not use them for _anything_ else */
65 DEFINE_MUTEX(mtd_table_mutex);
66 EXPORT_SYMBOL_GPL(mtd_table_mutex);
67
68 struct mtd_info *__mtd_next_device(int i)
69 {
70         return idr_get_next(&mtd_idr, &i);
71 }
72 EXPORT_SYMBOL_GPL(__mtd_next_device);
73
74 static LIST_HEAD(mtd_notifiers);
75
76
77 #define MTD_DEVT(index) MKDEV(MTD_CHAR_MAJOR, (index)*2)
78
79 /* REVISIT once MTD uses the driver model better, whoever allocates
80  * the mtd_info will probably want to use the release() hook...
81  */
82 static void mtd_release(struct device *dev)
83 {
84         struct mtd_info *mtd = dev_get_drvdata(dev);
85         dev_t index = MTD_DEVT(mtd->index);
86
87         /* remove /dev/mtdXro node */
88         device_destroy(&mtd_class, index + 1);
89 }
90
91 static int mtd_cls_suspend(struct device *dev, pm_message_t state)
92 {
93         struct mtd_info *mtd = dev_get_drvdata(dev);
94
95         return mtd ? mtd_suspend(mtd) : 0;
96 }
97
98 static int mtd_cls_resume(struct device *dev)
99 {
100         struct mtd_info *mtd = dev_get_drvdata(dev);
101
102         if (mtd)
103                 mtd_resume(mtd);
104         return 0;
105 }
106
107 static ssize_t mtd_type_show(struct device *dev,
108                 struct device_attribute *attr, char *buf)
109 {
110         struct mtd_info *mtd = dev_get_drvdata(dev);
111         char *type;
112
113         switch (mtd->type) {
114         case MTD_ABSENT:
115                 type = "absent";
116                 break;
117         case MTD_RAM:
118                 type = "ram";
119                 break;
120         case MTD_ROM:
121                 type = "rom";
122                 break;
123         case MTD_NORFLASH:
124                 type = "nor";
125                 break;
126         case MTD_NANDFLASH:
127                 type = "nand";
128                 break;
129         case MTD_DATAFLASH:
130                 type = "dataflash";
131                 break;
132         case MTD_UBIVOLUME:
133                 type = "ubi";
134                 break;
135         case MTD_MLCNANDFLASH:
136                 type = "mlc-nand";
137                 break;
138         default:
139                 type = "unknown";
140         }
141
142         return snprintf(buf, PAGE_SIZE, "%s\n", type);
143 }
144 static DEVICE_ATTR(type, S_IRUGO, mtd_type_show, NULL);
145
146 static ssize_t mtd_flags_show(struct device *dev,
147                 struct device_attribute *attr, char *buf)
148 {
149         struct mtd_info *mtd = dev_get_drvdata(dev);
150
151         return snprintf(buf, PAGE_SIZE, "0x%lx\n", (unsigned long)mtd->flags);
152
153 }
154 static DEVICE_ATTR(flags, S_IRUGO, mtd_flags_show, NULL);
155
156 static ssize_t mtd_size_show(struct device *dev,
157                 struct device_attribute *attr, char *buf)
158 {
159         struct mtd_info *mtd = dev_get_drvdata(dev);
160
161         return snprintf(buf, PAGE_SIZE, "%llu\n",
162                 (unsigned long long)mtd->size);
163
164 }
165 static DEVICE_ATTR(size, S_IRUGO, mtd_size_show, NULL);
166
167 static ssize_t mtd_erasesize_show(struct device *dev,
168                 struct device_attribute *attr, char *buf)
169 {
170         struct mtd_info *mtd = dev_get_drvdata(dev);
171
172         return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->erasesize);
173
174 }
175 static DEVICE_ATTR(erasesize, S_IRUGO, mtd_erasesize_show, NULL);
176
177 static ssize_t mtd_writesize_show(struct device *dev,
178                 struct device_attribute *attr, char *buf)
179 {
180         struct mtd_info *mtd = dev_get_drvdata(dev);
181
182         return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->writesize);
183
184 }
185 static DEVICE_ATTR(writesize, S_IRUGO, mtd_writesize_show, NULL);
186
187 static ssize_t mtd_subpagesize_show(struct device *dev,
188                 struct device_attribute *attr, char *buf)
189 {
190         struct mtd_info *mtd = dev_get_drvdata(dev);
191         unsigned int subpagesize = mtd->writesize >> mtd->subpage_sft;
192
193         return snprintf(buf, PAGE_SIZE, "%u\n", subpagesize);
194
195 }
196 static DEVICE_ATTR(subpagesize, S_IRUGO, mtd_subpagesize_show, NULL);
197
198 static ssize_t mtd_oobsize_show(struct device *dev,
199                 struct device_attribute *attr, char *buf)
200 {
201         struct mtd_info *mtd = dev_get_drvdata(dev);
202
203         return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->oobsize);
204
205 }
206 static DEVICE_ATTR(oobsize, S_IRUGO, mtd_oobsize_show, NULL);
207
208 static ssize_t mtd_numeraseregions_show(struct device *dev,
209                 struct device_attribute *attr, char *buf)
210 {
211         struct mtd_info *mtd = dev_get_drvdata(dev);
212
213         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->numeraseregions);
214
215 }
216 static DEVICE_ATTR(numeraseregions, S_IRUGO, mtd_numeraseregions_show,
217         NULL);
218
219 static ssize_t mtd_name_show(struct device *dev,
220                 struct device_attribute *attr, char *buf)
221 {
222         struct mtd_info *mtd = dev_get_drvdata(dev);
223
224         return snprintf(buf, PAGE_SIZE, "%s\n", mtd->name);
225
226 }
227 static DEVICE_ATTR(name, S_IRUGO, mtd_name_show, NULL);
228
229 static ssize_t mtd_ecc_strength_show(struct device *dev,
230                                      struct device_attribute *attr, char *buf)
231 {
232         struct mtd_info *mtd = dev_get_drvdata(dev);
233
234         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->ecc_strength);
235 }
236 static DEVICE_ATTR(ecc_strength, S_IRUGO, mtd_ecc_strength_show, NULL);
237
238 static ssize_t mtd_bitflip_threshold_show(struct device *dev,
239                                           struct device_attribute *attr,
240                                           char *buf)
241 {
242         struct mtd_info *mtd = dev_get_drvdata(dev);
243
244         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->bitflip_threshold);
245 }
246
247 static ssize_t mtd_bitflip_threshold_store(struct device *dev,
248                                            struct device_attribute *attr,
249                                            const char *buf, size_t count)
250 {
251         struct mtd_info *mtd = dev_get_drvdata(dev);
252         unsigned int bitflip_threshold;
253         int retval;
254
255         retval = kstrtouint(buf, 0, &bitflip_threshold);
256         if (retval)
257                 return retval;
258
259         mtd->bitflip_threshold = bitflip_threshold;
260         return count;
261 }
262 static DEVICE_ATTR(bitflip_threshold, S_IRUGO | S_IWUSR,
263                    mtd_bitflip_threshold_show,
264                    mtd_bitflip_threshold_store);
265
266 static ssize_t mtd_ecc_step_size_show(struct device *dev,
267                 struct device_attribute *attr, char *buf)
268 {
269         struct mtd_info *mtd = dev_get_drvdata(dev);
270
271         return snprintf(buf, PAGE_SIZE, "%u\n", mtd->ecc_step_size);
272
273 }
274 static DEVICE_ATTR(ecc_step_size, S_IRUGO, mtd_ecc_step_size_show, NULL);
275
276 static ssize_t mtd_ecc_stats_corrected_show(struct device *dev,
277                 struct device_attribute *attr, char *buf)
278 {
279         struct mtd_info *mtd = dev_get_drvdata(dev);
280         struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
281
282         return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->corrected);
283 }
284 static DEVICE_ATTR(corrected_bits, S_IRUGO,
285                    mtd_ecc_stats_corrected_show, NULL);
286
287 static ssize_t mtd_ecc_stats_errors_show(struct device *dev,
288                 struct device_attribute *attr, char *buf)
289 {
290         struct mtd_info *mtd = dev_get_drvdata(dev);
291         struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
292
293         return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->failed);
294 }
295 static DEVICE_ATTR(ecc_failures, S_IRUGO, mtd_ecc_stats_errors_show, NULL);
296
297 static ssize_t mtd_badblocks_show(struct device *dev,
298                 struct device_attribute *attr, char *buf)
299 {
300         struct mtd_info *mtd = dev_get_drvdata(dev);
301         struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
302
303         return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->badblocks);
304 }
305 static DEVICE_ATTR(bad_blocks, S_IRUGO, mtd_badblocks_show, NULL);
306
307 static ssize_t mtd_bbtblocks_show(struct device *dev,
308                 struct device_attribute *attr, char *buf)
309 {
310         struct mtd_info *mtd = dev_get_drvdata(dev);
311         struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
312
313         return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->bbtblocks);
314 }
315 static DEVICE_ATTR(bbt_blocks, S_IRUGO, mtd_bbtblocks_show, NULL);
316
317 static struct attribute *mtd_attrs[] = {
318         &dev_attr_type.attr,
319         &dev_attr_flags.attr,
320         &dev_attr_size.attr,
321         &dev_attr_erasesize.attr,
322         &dev_attr_writesize.attr,
323         &dev_attr_subpagesize.attr,
324         &dev_attr_oobsize.attr,
325         &dev_attr_numeraseregions.attr,
326         &dev_attr_name.attr,
327         &dev_attr_ecc_strength.attr,
328         &dev_attr_ecc_step_size.attr,
329         &dev_attr_corrected_bits.attr,
330         &dev_attr_ecc_failures.attr,
331         &dev_attr_bad_blocks.attr,
332         &dev_attr_bbt_blocks.attr,
333         &dev_attr_bitflip_threshold.attr,
334         NULL,
335 };
336 ATTRIBUTE_GROUPS(mtd);
337
338 static struct device_type mtd_devtype = {
339         .name           = "mtd",
340         .groups         = mtd_groups,
341         .release        = mtd_release,
342 };
343
344 #ifndef CONFIG_MMU
345 unsigned mtd_mmap_capabilities(struct mtd_info *mtd)
346 {
347         switch (mtd->type) {
348         case MTD_RAM:
349                 return NOMMU_MAP_COPY | NOMMU_MAP_DIRECT | NOMMU_MAP_EXEC |
350                         NOMMU_MAP_READ | NOMMU_MAP_WRITE;
351         case MTD_ROM:
352                 return NOMMU_MAP_COPY | NOMMU_MAP_DIRECT | NOMMU_MAP_EXEC |
353                         NOMMU_MAP_READ;
354         default:
355                 return NOMMU_MAP_COPY;
356         }
357 }
358 EXPORT_SYMBOL_GPL(mtd_mmap_capabilities);
359 #endif
360
361 static int mtd_reboot_notifier(struct notifier_block *n, unsigned long state,
362                                void *cmd)
363 {
364         struct mtd_info *mtd;
365
366         mtd = container_of(n, struct mtd_info, reboot_notifier);
367         mtd->_reboot(mtd);
368
369         return NOTIFY_DONE;
370 }
371
372 /**
373  *      add_mtd_device - register an MTD device
374  *      @mtd: pointer to new MTD device info structure
375  *
376  *      Add a device to the list of MTD devices present in the system, and
377  *      notify each currently active MTD 'user' of its arrival. Returns
378  *      zero on success or 1 on failure, which currently will only happen
379  *      if there is insufficient memory or a sysfs error.
380  */
381
382 int add_mtd_device(struct mtd_info *mtd)
383 {
384         struct mtd_notifier *not;
385         int i, error;
386
387         mtd->backing_dev_info = &mtd_bdi;
388
389         BUG_ON(mtd->writesize == 0);
390         mutex_lock(&mtd_table_mutex);
391
392         i = idr_alloc(&mtd_idr, mtd, 0, 0, GFP_KERNEL);
393         if (i < 0)
394                 goto fail_locked;
395
396         mtd->index = i;
397         mtd->usecount = 0;
398
399         /* default value if not set by driver */
400         if (mtd->bitflip_threshold == 0)
401                 mtd->bitflip_threshold = mtd->ecc_strength;
402
403         if (is_power_of_2(mtd->erasesize))
404                 mtd->erasesize_shift = ffs(mtd->erasesize) - 1;
405         else
406                 mtd->erasesize_shift = 0;
407
408         if (is_power_of_2(mtd->writesize))
409                 mtd->writesize_shift = ffs(mtd->writesize) - 1;
410         else
411                 mtd->writesize_shift = 0;
412
413         mtd->erasesize_mask = (1 << mtd->erasesize_shift) - 1;
414         mtd->writesize_mask = (1 << mtd->writesize_shift) - 1;
415
416         /* Some chips always power up locked. Unlock them now */
417         if ((mtd->flags & MTD_WRITEABLE) && (mtd->flags & MTD_POWERUP_LOCK)) {
418                 error = mtd_unlock(mtd, 0, mtd->size);
419                 if (error && error != -EOPNOTSUPP)
420                         printk(KERN_WARNING
421                                "%s: unlock failed, writes may not work\n",
422                                mtd->name);
423         }
424
425         /* Caller should have set dev.parent to match the
426          * physical device.
427          */
428         mtd->dev.type = &mtd_devtype;
429         mtd->dev.class = &mtd_class;
430         mtd->dev.devt = MTD_DEVT(i);
431         dev_set_name(&mtd->dev, "mtd%d", i);
432         dev_set_drvdata(&mtd->dev, mtd);
433         if (device_register(&mtd->dev) != 0)
434                 goto fail_added;
435
436         device_create(&mtd_class, mtd->dev.parent, MTD_DEVT(i) + 1, NULL,
437                       "mtd%dro", i);
438
439         pr_debug("mtd: Giving out device %d to %s\n", i, mtd->name);
440         /* No need to get a refcount on the module containing
441            the notifier, since we hold the mtd_table_mutex */
442         list_for_each_entry(not, &mtd_notifiers, list)
443                 not->add(mtd);
444
445         mutex_unlock(&mtd_table_mutex);
446         /* We _know_ we aren't being removed, because
447            our caller is still holding us here. So none
448            of this try_ nonsense, and no bitching about it
449            either. :) */
450         __module_get(THIS_MODULE);
451         return 0;
452
453 fail_added:
454         idr_remove(&mtd_idr, i);
455 fail_locked:
456         mutex_unlock(&mtd_table_mutex);
457         return 1;
458 }
459
460 /**
461  *      del_mtd_device - unregister an MTD device
462  *      @mtd: pointer to MTD device info structure
463  *
464  *      Remove a device from the list of MTD devices present in the system,
465  *      and notify each currently active MTD 'user' of its departure.
466  *      Returns zero on success or 1 on failure, which currently will happen
467  *      if the requested device does not appear to be present in the list.
468  */
469
470 int del_mtd_device(struct mtd_info *mtd)
471 {
472         int ret;
473         struct mtd_notifier *not;
474
475         mutex_lock(&mtd_table_mutex);
476
477         if (idr_find(&mtd_idr, mtd->index) != mtd) {
478                 ret = -ENODEV;
479                 goto out_error;
480         }
481
482         /* No need to get a refcount on the module containing
483                 the notifier, since we hold the mtd_table_mutex */
484         list_for_each_entry(not, &mtd_notifiers, list)
485                 not->remove(mtd);
486
487         if (mtd->usecount) {
488                 printk(KERN_NOTICE "Removing MTD device #%d (%s) with use count %d\n",
489                        mtd->index, mtd->name, mtd->usecount);
490                 ret = -EBUSY;
491         } else {
492                 device_unregister(&mtd->dev);
493
494                 idr_remove(&mtd_idr, mtd->index);
495
496                 module_put(THIS_MODULE);
497                 ret = 0;
498         }
499
500 out_error:
501         mutex_unlock(&mtd_table_mutex);
502         return ret;
503 }
504
505 static int mtd_add_device_partitions(struct mtd_info *mtd,
506                                      struct mtd_partition *real_parts,
507                                      int nbparts)
508 {
509         int ret;
510
511         if (nbparts == 0 || IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER)) {
512                 ret = add_mtd_device(mtd);
513                 if (ret == 1)
514                         return -ENODEV;
515         }
516
517         if (nbparts > 0) {
518                 ret = add_mtd_partitions(mtd, real_parts, nbparts);
519                 if (ret && IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER))
520                         del_mtd_device(mtd);
521                 return ret;
522         }
523
524         return 0;
525 }
526
527
528 /**
529  * mtd_device_parse_register - parse partitions and register an MTD device.
530  *
531  * @mtd: the MTD device to register
532  * @types: the list of MTD partition probes to try, see
533  *         'parse_mtd_partitions()' for more information
534  * @parser_data: MTD partition parser-specific data
535  * @parts: fallback partition information to register, if parsing fails;
536  *         only valid if %nr_parts > %0
537  * @nr_parts: the number of partitions in parts, if zero then the full
538  *            MTD device is registered if no partition info is found
539  *
540  * This function aggregates MTD partitions parsing (done by
541  * 'parse_mtd_partitions()') and MTD device and partitions registering. It
542  * basically follows the most common pattern found in many MTD drivers:
543  *
544  * * It first tries to probe partitions on MTD device @mtd using parsers
545  *   specified in @types (if @types is %NULL, then the default list of parsers
546  *   is used, see 'parse_mtd_partitions()' for more information). If none are
547  *   found this functions tries to fallback to information specified in
548  *   @parts/@nr_parts.
549  * * If any partitioning info was found, this function registers the found
550  *   partitions. If the MTD_PARTITIONED_MASTER option is set, then the device
551  *   as a whole is registered first.
552  * * If no partitions were found this function just registers the MTD device
553  *   @mtd and exits.
554  *
555  * Returns zero in case of success and a negative error code in case of failure.
556  */
557 int mtd_device_parse_register(struct mtd_info *mtd, const char * const *types,
558                               struct mtd_part_parser_data *parser_data,
559                               const struct mtd_partition *parts,
560                               int nr_parts)
561 {
562         int ret;
563         struct mtd_partition *real_parts = NULL;
564
565         ret = parse_mtd_partitions(mtd, types, &real_parts, parser_data);
566         if (ret <= 0 && nr_parts && parts) {
567                 real_parts = kmemdup(parts, sizeof(*parts) * nr_parts,
568                                      GFP_KERNEL);
569                 if (!real_parts)
570                         ret = -ENOMEM;
571                 else
572                         ret = nr_parts;
573         }
574
575         if (ret >= 0)
576                 ret = mtd_add_device_partitions(mtd, real_parts, ret);
577
578         /*
579          * FIXME: some drivers unfortunately call this function more than once.
580          * So we have to check if we've already assigned the reboot notifier.
581          *
582          * Generally, we can make multiple calls work for most cases, but it
583          * does cause problems with parse_mtd_partitions() above (e.g.,
584          * cmdlineparts will register partitions more than once).
585          */
586         if (mtd->_reboot && !mtd->reboot_notifier.notifier_call) {
587                 mtd->reboot_notifier.notifier_call = mtd_reboot_notifier;
588                 register_reboot_notifier(&mtd->reboot_notifier);
589         }
590
591         kfree(real_parts);
592         return ret;
593 }
594 EXPORT_SYMBOL_GPL(mtd_device_parse_register);
595
596 /**
597  * mtd_device_unregister - unregister an existing MTD device.
598  *
599  * @master: the MTD device to unregister.  This will unregister both the master
600  *          and any partitions if registered.
601  */
602 int mtd_device_unregister(struct mtd_info *master)
603 {
604         int err;
605
606         if (master->_reboot)
607                 unregister_reboot_notifier(&master->reboot_notifier);
608
609         err = del_mtd_partitions(master);
610         if (err)
611                 return err;
612
613         if (!device_is_registered(&master->dev))
614                 return 0;
615
616         return del_mtd_device(master);
617 }
618 EXPORT_SYMBOL_GPL(mtd_device_unregister);
619
620 /**
621  *      register_mtd_user - register a 'user' of MTD devices.
622  *      @new: pointer to notifier info structure
623  *
624  *      Registers a pair of callbacks function to be called upon addition
625  *      or removal of MTD devices. Causes the 'add' callback to be immediately
626  *      invoked for each MTD device currently present in the system.
627  */
628 void register_mtd_user (struct mtd_notifier *new)
629 {
630         struct mtd_info *mtd;
631
632         mutex_lock(&mtd_table_mutex);
633
634         list_add(&new->list, &mtd_notifiers);
635
636         __module_get(THIS_MODULE);
637
638         mtd_for_each_device(mtd)
639                 new->add(mtd);
640
641         mutex_unlock(&mtd_table_mutex);
642 }
643 EXPORT_SYMBOL_GPL(register_mtd_user);
644
645 /**
646  *      unregister_mtd_user - unregister a 'user' of MTD devices.
647  *      @old: pointer to notifier info structure
648  *
649  *      Removes a callback function pair from the list of 'users' to be
650  *      notified upon addition or removal of MTD devices. Causes the
651  *      'remove' callback to be immediately invoked for each MTD device
652  *      currently present in the system.
653  */
654 int unregister_mtd_user (struct mtd_notifier *old)
655 {
656         struct mtd_info *mtd;
657
658         mutex_lock(&mtd_table_mutex);
659
660         module_put(THIS_MODULE);
661
662         mtd_for_each_device(mtd)
663                 old->remove(mtd);
664
665         list_del(&old->list);
666         mutex_unlock(&mtd_table_mutex);
667         return 0;
668 }
669 EXPORT_SYMBOL_GPL(unregister_mtd_user);
670
671 /**
672  *      get_mtd_device - obtain a validated handle for an MTD device
673  *      @mtd: last known address of the required MTD device
674  *      @num: internal device number of the required MTD device
675  *
676  *      Given a number and NULL address, return the num'th entry in the device
677  *      table, if any.  Given an address and num == -1, search the device table
678  *      for a device with that address and return if it's still present. Given
679  *      both, return the num'th driver only if its address matches. Return
680  *      error code if not.
681  */
682 struct mtd_info *get_mtd_device(struct mtd_info *mtd, int num)
683 {
684         struct mtd_info *ret = NULL, *other;
685         int err = -ENODEV;
686
687         mutex_lock(&mtd_table_mutex);
688
689         if (num == -1) {
690                 mtd_for_each_device(other) {
691                         if (other == mtd) {
692                                 ret = mtd;
693                                 break;
694                         }
695                 }
696         } else if (num >= 0) {
697                 ret = idr_find(&mtd_idr, num);
698                 if (mtd && mtd != ret)
699                         ret = NULL;
700         }
701
702         if (!ret) {
703                 ret = ERR_PTR(err);
704                 goto out;
705         }
706
707         err = __get_mtd_device(ret);
708         if (err)
709                 ret = ERR_PTR(err);
710 out:
711         mutex_unlock(&mtd_table_mutex);
712         return ret;
713 }
714 EXPORT_SYMBOL_GPL(get_mtd_device);
715
716
717 int __get_mtd_device(struct mtd_info *mtd)
718 {
719         int err;
720
721         if (!try_module_get(mtd->owner))
722                 return -ENODEV;
723
724         if (mtd->_get_device) {
725                 err = mtd->_get_device(mtd);
726
727                 if (err) {
728                         module_put(mtd->owner);
729                         return err;
730                 }
731         }
732         mtd->usecount++;
733         return 0;
734 }
735 EXPORT_SYMBOL_GPL(__get_mtd_device);
736
737 /**
738  *      get_mtd_device_nm - obtain a validated handle for an MTD device by
739  *      device name
740  *      @name: MTD device name to open
741  *
742  *      This function returns MTD device description structure in case of
743  *      success and an error code in case of failure.
744  */
745 struct mtd_info *get_mtd_device_nm(const char *name)
746 {
747         int err = -ENODEV;
748         struct mtd_info *mtd = NULL, *other;
749
750         mutex_lock(&mtd_table_mutex);
751
752         mtd_for_each_device(other) {
753                 if (!strcmp(name, other->name)) {
754                         mtd = other;
755                         break;
756                 }
757         }
758
759         if (!mtd)
760                 goto out_unlock;
761
762         err = __get_mtd_device(mtd);
763         if (err)
764                 goto out_unlock;
765
766         mutex_unlock(&mtd_table_mutex);
767         return mtd;
768
769 out_unlock:
770         mutex_unlock(&mtd_table_mutex);
771         return ERR_PTR(err);
772 }
773 EXPORT_SYMBOL_GPL(get_mtd_device_nm);
774
775 void put_mtd_device(struct mtd_info *mtd)
776 {
777         mutex_lock(&mtd_table_mutex);
778         __put_mtd_device(mtd);
779         mutex_unlock(&mtd_table_mutex);
780
781 }
782 EXPORT_SYMBOL_GPL(put_mtd_device);
783
784 void __put_mtd_device(struct mtd_info *mtd)
785 {
786         --mtd->usecount;
787         BUG_ON(mtd->usecount < 0);
788
789         if (mtd->_put_device)
790                 mtd->_put_device(mtd);
791
792         module_put(mtd->owner);
793 }
794 EXPORT_SYMBOL_GPL(__put_mtd_device);
795
796 /*
797  * Erase is an asynchronous operation.  Device drivers are supposed
798  * to call instr->callback() whenever the operation completes, even
799  * if it completes with a failure.
800  * Callers are supposed to pass a callback function and wait for it
801  * to be called before writing to the block.
802  */
803 int mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
804 {
805         if (instr->addr >= mtd->size || instr->len > mtd->size - instr->addr)
806                 return -EINVAL;
807         if (!(mtd->flags & MTD_WRITEABLE))
808                 return -EROFS;
809         instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
810         if (!instr->len) {
811                 instr->state = MTD_ERASE_DONE;
812                 mtd_erase_callback(instr);
813                 return 0;
814         }
815         return mtd->_erase(mtd, instr);
816 }
817 EXPORT_SYMBOL_GPL(mtd_erase);
818
819 /*
820  * This stuff for eXecute-In-Place. phys is optional and may be set to NULL.
821  */
822 int mtd_point(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
823               void **virt, resource_size_t *phys)
824 {
825         *retlen = 0;
826         *virt = NULL;
827         if (phys)
828                 *phys = 0;
829         if (!mtd->_point)
830                 return -EOPNOTSUPP;
831         if (from < 0 || from >= mtd->size || len > mtd->size - from)
832                 return -EINVAL;
833         if (!len)
834                 return 0;
835         return mtd->_point(mtd, from, len, retlen, virt, phys);
836 }
837 EXPORT_SYMBOL_GPL(mtd_point);
838
839 /* We probably shouldn't allow XIP if the unpoint isn't a NULL */
840 int mtd_unpoint(struct mtd_info *mtd, loff_t from, size_t len)
841 {
842         if (!mtd->_point)
843                 return -EOPNOTSUPP;
844         if (from < 0 || from >= mtd->size || len > mtd->size - from)
845                 return -EINVAL;
846         if (!len)
847                 return 0;
848         return mtd->_unpoint(mtd, from, len);
849 }
850 EXPORT_SYMBOL_GPL(mtd_unpoint);
851
852 /*
853  * Allow NOMMU mmap() to directly map the device (if not NULL)
854  * - return the address to which the offset maps
855  * - return -ENOSYS to indicate refusal to do the mapping
856  */
857 unsigned long mtd_get_unmapped_area(struct mtd_info *mtd, unsigned long len,
858                                     unsigned long offset, unsigned long flags)
859 {
860         if (!mtd->_get_unmapped_area)
861                 return -EOPNOTSUPP;
862         if (offset >= mtd->size || len > mtd->size - offset)
863                 return -EINVAL;
864         return mtd->_get_unmapped_area(mtd, len, offset, flags);
865 }
866 EXPORT_SYMBOL_GPL(mtd_get_unmapped_area);
867
868 int mtd_read(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
869              u_char *buf)
870 {
871         int ret_code;
872         *retlen = 0;
873         if (from < 0 || from >= mtd->size || len > mtd->size - from)
874                 return -EINVAL;
875         if (!len)
876                 return 0;
877
878         /*
879          * In the absence of an error, drivers return a non-negative integer
880          * representing the maximum number of bitflips that were corrected on
881          * any one ecc region (if applicable; zero otherwise).
882          */
883         ret_code = mtd->_read(mtd, from, len, retlen, buf);
884         if (unlikely(ret_code < 0))
885                 return ret_code;
886         if (mtd->ecc_strength == 0)
887                 return 0;       /* device lacks ecc */
888         return ret_code >= mtd->bitflip_threshold ? -EUCLEAN : 0;
889 }
890 EXPORT_SYMBOL_GPL(mtd_read);
891
892 int mtd_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
893               const u_char *buf)
894 {
895         *retlen = 0;
896         if (to < 0 || to >= mtd->size || len > mtd->size - to)
897                 return -EINVAL;
898         if (!mtd->_write || !(mtd->flags & MTD_WRITEABLE))
899                 return -EROFS;
900         if (!len)
901                 return 0;
902         return mtd->_write(mtd, to, len, retlen, buf);
903 }
904 EXPORT_SYMBOL_GPL(mtd_write);
905
906 /*
907  * In blackbox flight recorder like scenarios we want to make successful writes
908  * in interrupt context. panic_write() is only intended to be called when its
909  * known the kernel is about to panic and we need the write to succeed. Since
910  * the kernel is not going to be running for much longer, this function can
911  * break locks and delay to ensure the write succeeds (but not sleep).
912  */
913 int mtd_panic_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
914                     const u_char *buf)
915 {
916         *retlen = 0;
917         if (!mtd->_panic_write)
918                 return -EOPNOTSUPP;
919         if (to < 0 || to >= mtd->size || len > mtd->size - to)
920                 return -EINVAL;
921         if (!(mtd->flags & MTD_WRITEABLE))
922                 return -EROFS;
923         if (!len)
924                 return 0;
925         return mtd->_panic_write(mtd, to, len, retlen, buf);
926 }
927 EXPORT_SYMBOL_GPL(mtd_panic_write);
928
929 int mtd_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
930 {
931         int ret_code;
932         ops->retlen = ops->oobretlen = 0;
933         if (!mtd->_read_oob)
934                 return -EOPNOTSUPP;
935         /*
936          * In cases where ops->datbuf != NULL, mtd->_read_oob() has semantics
937          * similar to mtd->_read(), returning a non-negative integer
938          * representing max bitflips. In other cases, mtd->_read_oob() may
939          * return -EUCLEAN. In all cases, perform similar logic to mtd_read().
940          */
941         ret_code = mtd->_read_oob(mtd, from, ops);
942         if (unlikely(ret_code < 0))
943                 return ret_code;
944         if (mtd->ecc_strength == 0)
945                 return 0;       /* device lacks ecc */
946         return ret_code >= mtd->bitflip_threshold ? -EUCLEAN : 0;
947 }
948 EXPORT_SYMBOL_GPL(mtd_read_oob);
949
950 /*
951  * Method to access the protection register area, present in some flash
952  * devices. The user data is one time programmable but the factory data is read
953  * only.
954  */
955 int mtd_get_fact_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
956                            struct otp_info *buf)
957 {
958         if (!mtd->_get_fact_prot_info)
959                 return -EOPNOTSUPP;
960         if (!len)
961                 return 0;
962         return mtd->_get_fact_prot_info(mtd, len, retlen, buf);
963 }
964 EXPORT_SYMBOL_GPL(mtd_get_fact_prot_info);
965
966 int mtd_read_fact_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
967                            size_t *retlen, u_char *buf)
968 {
969         *retlen = 0;
970         if (!mtd->_read_fact_prot_reg)
971                 return -EOPNOTSUPP;
972         if (!len)
973                 return 0;
974         return mtd->_read_fact_prot_reg(mtd, from, len, retlen, buf);
975 }
976 EXPORT_SYMBOL_GPL(mtd_read_fact_prot_reg);
977
978 int mtd_get_user_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
979                            struct otp_info *buf)
980 {
981         if (!mtd->_get_user_prot_info)
982                 return -EOPNOTSUPP;
983         if (!len)
984                 return 0;
985         return mtd->_get_user_prot_info(mtd, len, retlen, buf);
986 }
987 EXPORT_SYMBOL_GPL(mtd_get_user_prot_info);
988
989 int mtd_read_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
990                            size_t *retlen, u_char *buf)
991 {
992         *retlen = 0;
993         if (!mtd->_read_user_prot_reg)
994                 return -EOPNOTSUPP;
995         if (!len)
996                 return 0;
997         return mtd->_read_user_prot_reg(mtd, from, len, retlen, buf);
998 }
999 EXPORT_SYMBOL_GPL(mtd_read_user_prot_reg);
1000
1001 int mtd_write_user_prot_reg(struct mtd_info *mtd, loff_t to, size_t len,
1002                             size_t *retlen, u_char *buf)
1003 {
1004         int ret;
1005
1006         *retlen = 0;
1007         if (!mtd->_write_user_prot_reg)
1008                 return -EOPNOTSUPP;
1009         if (!len)
1010                 return 0;
1011         ret = mtd->_write_user_prot_reg(mtd, to, len, retlen, buf);
1012         if (ret)
1013                 return ret;
1014
1015         /*
1016          * If no data could be written at all, we are out of memory and
1017          * must return -ENOSPC.
1018          */
1019         return (*retlen) ? 0 : -ENOSPC;
1020 }
1021 EXPORT_SYMBOL_GPL(mtd_write_user_prot_reg);
1022
1023 int mtd_lock_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len)
1024 {
1025         if (!mtd->_lock_user_prot_reg)
1026                 return -EOPNOTSUPP;
1027         if (!len)
1028                 return 0;
1029         return mtd->_lock_user_prot_reg(mtd, from, len);
1030 }
1031 EXPORT_SYMBOL_GPL(mtd_lock_user_prot_reg);
1032
1033 /* Chip-supported device locking */
1034 int mtd_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1035 {
1036         if (!mtd->_lock)
1037                 return -EOPNOTSUPP;
1038         if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
1039                 return -EINVAL;
1040         if (!len)
1041                 return 0;
1042         return mtd->_lock(mtd, ofs, len);
1043 }
1044 EXPORT_SYMBOL_GPL(mtd_lock);
1045
1046 int mtd_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1047 {
1048         if (!mtd->_unlock)
1049                 return -EOPNOTSUPP;
1050         if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
1051                 return -EINVAL;
1052         if (!len)
1053                 return 0;
1054         return mtd->_unlock(mtd, ofs, len);
1055 }
1056 EXPORT_SYMBOL_GPL(mtd_unlock);
1057
1058 int mtd_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
1059 {
1060         if (!mtd->_is_locked)
1061                 return -EOPNOTSUPP;
1062         if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
1063                 return -EINVAL;
1064         if (!len)
1065                 return 0;
1066         return mtd->_is_locked(mtd, ofs, len);
1067 }
1068 EXPORT_SYMBOL_GPL(mtd_is_locked);
1069
1070 int mtd_block_isreserved(struct mtd_info *mtd, loff_t ofs)
1071 {
1072         if (ofs < 0 || ofs >= mtd->size)
1073                 return -EINVAL;
1074         if (!mtd->_block_isreserved)
1075                 return 0;
1076         return mtd->_block_isreserved(mtd, ofs);
1077 }
1078 EXPORT_SYMBOL_GPL(mtd_block_isreserved);
1079
1080 int mtd_block_isbad(struct mtd_info *mtd, loff_t ofs)
1081 {
1082         if (ofs < 0 || ofs >= mtd->size)
1083                 return -EINVAL;
1084         if (!mtd->_block_isbad)
1085                 return 0;
1086         return mtd->_block_isbad(mtd, ofs);
1087 }
1088 EXPORT_SYMBOL_GPL(mtd_block_isbad);
1089
1090 int mtd_block_markbad(struct mtd_info *mtd, loff_t ofs)
1091 {
1092         if (!mtd->_block_markbad)
1093                 return -EOPNOTSUPP;
1094         if (ofs < 0 || ofs >= mtd->size)
1095                 return -EINVAL;
1096         if (!(mtd->flags & MTD_WRITEABLE))
1097                 return -EROFS;
1098         return mtd->_block_markbad(mtd, ofs);
1099 }
1100 EXPORT_SYMBOL_GPL(mtd_block_markbad);
1101
1102 /*
1103  * default_mtd_writev - the default writev method
1104  * @mtd: mtd device description object pointer
1105  * @vecs: the vectors to write
1106  * @count: count of vectors in @vecs
1107  * @to: the MTD device offset to write to
1108  * @retlen: on exit contains the count of bytes written to the MTD device.
1109  *
1110  * This function returns zero in case of success and a negative error code in
1111  * case of failure.
1112  */
1113 static int default_mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
1114                               unsigned long count, loff_t to, size_t *retlen)
1115 {
1116         unsigned long i;
1117         size_t totlen = 0, thislen;
1118         int ret = 0;
1119
1120         for (i = 0; i < count; i++) {
1121                 if (!vecs[i].iov_len)
1122                         continue;
1123                 ret = mtd_write(mtd, to, vecs[i].iov_len, &thislen,
1124                                 vecs[i].iov_base);
1125                 totlen += thislen;
1126                 if (ret || thislen != vecs[i].iov_len)
1127                         break;
1128                 to += vecs[i].iov_len;
1129         }
1130         *retlen = totlen;
1131         return ret;
1132 }
1133
1134 /*
1135  * mtd_writev - the vector-based MTD write method
1136  * @mtd: mtd device description object pointer
1137  * @vecs: the vectors to write
1138  * @count: count of vectors in @vecs
1139  * @to: the MTD device offset to write to
1140  * @retlen: on exit contains the count of bytes written to the MTD device.
1141  *
1142  * This function returns zero in case of success and a negative error code in
1143  * case of failure.
1144  */
1145 int mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
1146                unsigned long count, loff_t to, size_t *retlen)
1147 {
1148         *retlen = 0;
1149         if (!(mtd->flags & MTD_WRITEABLE))
1150                 return -EROFS;
1151         if (!mtd->_writev)
1152                 return default_mtd_writev(mtd, vecs, count, to, retlen);
1153         return mtd->_writev(mtd, vecs, count, to, retlen);
1154 }
1155 EXPORT_SYMBOL_GPL(mtd_writev);
1156
1157 /**
1158  * mtd_kmalloc_up_to - allocate a contiguous buffer up to the specified size
1159  * @mtd: mtd device description object pointer
1160  * @size: a pointer to the ideal or maximum size of the allocation, points
1161  *        to the actual allocation size on success.
1162  *
1163  * This routine attempts to allocate a contiguous kernel buffer up to
1164  * the specified size, backing off the size of the request exponentially
1165  * until the request succeeds or until the allocation size falls below
1166  * the system page size. This attempts to make sure it does not adversely
1167  * impact system performance, so when allocating more than one page, we
1168  * ask the memory allocator to avoid re-trying, swapping, writing back
1169  * or performing I/O.
1170  *
1171  * Note, this function also makes sure that the allocated buffer is aligned to
1172  * the MTD device's min. I/O unit, i.e. the "mtd->writesize" value.
1173  *
1174  * This is called, for example by mtd_{read,write} and jffs2_scan_medium,
1175  * to handle smaller (i.e. degraded) buffer allocations under low- or
1176  * fragmented-memory situations where such reduced allocations, from a
1177  * requested ideal, are allowed.
1178  *
1179  * Returns a pointer to the allocated buffer on success; otherwise, NULL.
1180  */
1181 void *mtd_kmalloc_up_to(const struct mtd_info *mtd, size_t *size)
1182 {
1183         gfp_t flags = __GFP_NOWARN | __GFP_WAIT |
1184                        __GFP_NORETRY | __GFP_NO_KSWAPD;
1185         size_t min_alloc = max_t(size_t, mtd->writesize, PAGE_SIZE);
1186         void *kbuf;
1187
1188         *size = min_t(size_t, *size, KMALLOC_MAX_SIZE);
1189
1190         while (*size > min_alloc) {
1191                 kbuf = kmalloc(*size, flags);
1192                 if (kbuf)
1193                         return kbuf;
1194
1195                 *size >>= 1;
1196                 *size = ALIGN(*size, mtd->writesize);
1197         }
1198
1199         /*
1200          * For the last resort allocation allow 'kmalloc()' to do all sorts of
1201          * things (write-back, dropping caches, etc) by using GFP_KERNEL.
1202          */
1203         return kmalloc(*size, GFP_KERNEL);
1204 }
1205 EXPORT_SYMBOL_GPL(mtd_kmalloc_up_to);
1206
1207 #ifdef CONFIG_PROC_FS
1208
1209 /*====================================================================*/
1210 /* Support for /proc/mtd */
1211
1212 static int mtd_proc_show(struct seq_file *m, void *v)
1213 {
1214         struct mtd_info *mtd;
1215
1216         seq_puts(m, "dev:    size   erasesize  name\n");
1217         mutex_lock(&mtd_table_mutex);
1218         mtd_for_each_device(mtd) {
1219                 seq_printf(m, "mtd%d: %8.8llx %8.8x \"%s\"\n",
1220                            mtd->index, (unsigned long long)mtd->size,
1221                            mtd->erasesize, mtd->name);
1222         }
1223         mutex_unlock(&mtd_table_mutex);
1224         return 0;
1225 }
1226
1227 static int mtd_proc_open(struct inode *inode, struct file *file)
1228 {
1229         return single_open(file, mtd_proc_show, NULL);
1230 }
1231
1232 static const struct file_operations mtd_proc_ops = {
1233         .open           = mtd_proc_open,
1234         .read           = seq_read,
1235         .llseek         = seq_lseek,
1236         .release        = single_release,
1237 };
1238 #endif /* CONFIG_PROC_FS */
1239
1240 /*====================================================================*/
1241 /* Init code */
1242
1243 static int __init mtd_bdi_init(struct backing_dev_info *bdi, const char *name)
1244 {
1245         int ret;
1246
1247         ret = bdi_init(bdi);
1248         if (!ret)
1249                 ret = bdi_register(bdi, NULL, "%s", name);
1250
1251         if (ret)
1252                 bdi_destroy(bdi);
1253
1254         return ret;
1255 }
1256
1257 static struct proc_dir_entry *proc_mtd;
1258
1259 static int __init init_mtd(void)
1260 {
1261         int ret;
1262
1263         ret = class_register(&mtd_class);
1264         if (ret)
1265                 goto err_reg;
1266
1267         ret = mtd_bdi_init(&mtd_bdi, "mtd");
1268         if (ret)
1269                 goto err_bdi;
1270
1271         proc_mtd = proc_create("mtd", 0, NULL, &mtd_proc_ops);
1272
1273         ret = init_mtdchar();
1274         if (ret)
1275                 goto out_procfs;
1276
1277         return 0;
1278
1279 out_procfs:
1280         if (proc_mtd)
1281                 remove_proc_entry("mtd", NULL);
1282 err_bdi:
1283         class_unregister(&mtd_class);
1284 err_reg:
1285         pr_err("Error registering mtd class or bdi: %d\n", ret);
1286         return ret;
1287 }
1288
1289 static void __exit cleanup_mtd(void)
1290 {
1291         cleanup_mtdchar();
1292         if (proc_mtd)
1293                 remove_proc_entry("mtd", NULL);
1294         class_unregister(&mtd_class);
1295         bdi_destroy(&mtd_bdi);
1296 }
1297
1298 module_init(init_mtd);
1299 module_exit(cleanup_mtd);
1300
1301 MODULE_LICENSE("GPL");
1302 MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
1303 MODULE_DESCRIPTION("Core MTD registration and access routines");