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