treewide: remove redundant IS_ERR() before error code check
[linux/fpc-iii.git] / drivers / mtd / mtdcore.c
blob5fac4355b9c2b5aeb20c34af7ce4260ed83a5b4d
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Core registration and callback routines for MTD
4 * drivers and users.
6 * Copyright © 1999-2010 David Woodhouse <dwmw2@infradead.org>
7 * Copyright © 2006 Red Hat UK Limited
8 */
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>
32 #include <linux/mtd/mtd.h>
33 #include <linux/mtd/partitions.h>
35 #include "mtdcore.h"
37 struct backing_dev_info *mtd_bdi;
39 #ifdef CONFIG_PM_SLEEP
41 static int mtd_cls_suspend(struct device *dev)
43 struct mtd_info *mtd = dev_get_drvdata(dev);
45 return mtd ? mtd_suspend(mtd) : 0;
48 static int mtd_cls_resume(struct device *dev)
50 struct mtd_info *mtd = dev_get_drvdata(dev);
52 if (mtd)
53 mtd_resume(mtd);
54 return 0;
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
63 static struct class mtd_class = {
64 .name = "mtd",
65 .owner = THIS_MODULE,
66 .pm = MTD_CLS_PM_OPS,
69 static DEFINE_IDR(mtd_idr);
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);
76 struct mtd_info *__mtd_next_device(int i)
78 return idr_get_next(&mtd_idr, &i);
80 EXPORT_SYMBOL_GPL(__mtd_next_device);
82 static LIST_HEAD(mtd_notifiers);
85 #define MTD_DEVT(index) MKDEV(MTD_CHAR_MAJOR, (index)*2)
87 /* REVISIT once MTD uses the driver model better, whoever allocates
88 * the mtd_info will probably want to use the release() hook...
90 static void mtd_release(struct device *dev)
92 struct mtd_info *mtd = dev_get_drvdata(dev);
93 dev_t index = MTD_DEVT(mtd->index);
95 /* remove /dev/mtdXro node */
96 device_destroy(&mtd_class, index + 1);
99 static ssize_t mtd_type_show(struct device *dev,
100 struct device_attribute *attr, char *buf)
102 struct mtd_info *mtd = dev_get_drvdata(dev);
103 char *type;
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";
134 return snprintf(buf, PAGE_SIZE, "%s\n", type);
136 static DEVICE_ATTR(type, S_IRUGO, mtd_type_show, NULL);
138 static ssize_t mtd_flags_show(struct device *dev,
139 struct device_attribute *attr, char *buf)
141 struct mtd_info *mtd = dev_get_drvdata(dev);
143 return snprintf(buf, PAGE_SIZE, "0x%lx\n", (unsigned long)mtd->flags);
145 static DEVICE_ATTR(flags, S_IRUGO, mtd_flags_show, NULL);
147 static ssize_t mtd_size_show(struct device *dev,
148 struct device_attribute *attr, char *buf)
150 struct mtd_info *mtd = dev_get_drvdata(dev);
152 return snprintf(buf, PAGE_SIZE, "%llu\n",
153 (unsigned long long)mtd->size);
155 static DEVICE_ATTR(size, S_IRUGO, mtd_size_show, NULL);
157 static ssize_t mtd_erasesize_show(struct device *dev,
158 struct device_attribute *attr, char *buf)
160 struct mtd_info *mtd = dev_get_drvdata(dev);
162 return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->erasesize);
164 static DEVICE_ATTR(erasesize, S_IRUGO, mtd_erasesize_show, NULL);
166 static ssize_t mtd_writesize_show(struct device *dev,
167 struct device_attribute *attr, char *buf)
169 struct mtd_info *mtd = dev_get_drvdata(dev);
171 return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->writesize);
173 static DEVICE_ATTR(writesize, S_IRUGO, mtd_writesize_show, NULL);
175 static ssize_t mtd_subpagesize_show(struct device *dev,
176 struct device_attribute *attr, char *buf)
178 struct mtd_info *mtd = dev_get_drvdata(dev);
179 unsigned int subpagesize = mtd->writesize >> mtd->subpage_sft;
181 return snprintf(buf, PAGE_SIZE, "%u\n", subpagesize);
183 static DEVICE_ATTR(subpagesize, S_IRUGO, mtd_subpagesize_show, NULL);
185 static ssize_t mtd_oobsize_show(struct device *dev,
186 struct device_attribute *attr, char *buf)
188 struct mtd_info *mtd = dev_get_drvdata(dev);
190 return snprintf(buf, PAGE_SIZE, "%lu\n", (unsigned long)mtd->oobsize);
192 static DEVICE_ATTR(oobsize, S_IRUGO, mtd_oobsize_show, NULL);
194 static ssize_t mtd_oobavail_show(struct device *dev,
195 struct device_attribute *attr, char *buf)
197 struct mtd_info *mtd = dev_get_drvdata(dev);
199 return snprintf(buf, PAGE_SIZE, "%u\n", mtd->oobavail);
201 static DEVICE_ATTR(oobavail, S_IRUGO, mtd_oobavail_show, NULL);
203 static ssize_t mtd_numeraseregions_show(struct device *dev,
204 struct device_attribute *attr, char *buf)
206 struct mtd_info *mtd = dev_get_drvdata(dev);
208 return snprintf(buf, PAGE_SIZE, "%u\n", mtd->numeraseregions);
210 static DEVICE_ATTR(numeraseregions, S_IRUGO, mtd_numeraseregions_show,
211 NULL);
213 static ssize_t mtd_name_show(struct device *dev,
214 struct device_attribute *attr, char *buf)
216 struct mtd_info *mtd = dev_get_drvdata(dev);
218 return snprintf(buf, PAGE_SIZE, "%s\n", mtd->name);
220 static DEVICE_ATTR(name, S_IRUGO, mtd_name_show, NULL);
222 static ssize_t mtd_ecc_strength_show(struct device *dev,
223 struct device_attribute *attr, char *buf)
225 struct mtd_info *mtd = dev_get_drvdata(dev);
227 return snprintf(buf, PAGE_SIZE, "%u\n", mtd->ecc_strength);
229 static DEVICE_ATTR(ecc_strength, S_IRUGO, mtd_ecc_strength_show, NULL);
231 static ssize_t mtd_bitflip_threshold_show(struct device *dev,
232 struct device_attribute *attr,
233 char *buf)
235 struct mtd_info *mtd = dev_get_drvdata(dev);
237 return snprintf(buf, PAGE_SIZE, "%u\n", mtd->bitflip_threshold);
240 static ssize_t mtd_bitflip_threshold_store(struct device *dev,
241 struct device_attribute *attr,
242 const char *buf, size_t count)
244 struct mtd_info *mtd = dev_get_drvdata(dev);
245 unsigned int bitflip_threshold;
246 int retval;
248 retval = kstrtouint(buf, 0, &bitflip_threshold);
249 if (retval)
250 return retval;
252 mtd->bitflip_threshold = bitflip_threshold;
253 return count;
255 static DEVICE_ATTR(bitflip_threshold, S_IRUGO | S_IWUSR,
256 mtd_bitflip_threshold_show,
257 mtd_bitflip_threshold_store);
259 static ssize_t mtd_ecc_step_size_show(struct device *dev,
260 struct device_attribute *attr, char *buf)
262 struct mtd_info *mtd = dev_get_drvdata(dev);
264 return snprintf(buf, PAGE_SIZE, "%u\n", mtd->ecc_step_size);
267 static DEVICE_ATTR(ecc_step_size, S_IRUGO, mtd_ecc_step_size_show, NULL);
269 static ssize_t mtd_ecc_stats_corrected_show(struct device *dev,
270 struct device_attribute *attr, char *buf)
272 struct mtd_info *mtd = dev_get_drvdata(dev);
273 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
275 return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->corrected);
277 static DEVICE_ATTR(corrected_bits, S_IRUGO,
278 mtd_ecc_stats_corrected_show, NULL);
280 static ssize_t mtd_ecc_stats_errors_show(struct device *dev,
281 struct device_attribute *attr, char *buf)
283 struct mtd_info *mtd = dev_get_drvdata(dev);
284 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
286 return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->failed);
288 static DEVICE_ATTR(ecc_failures, S_IRUGO, mtd_ecc_stats_errors_show, NULL);
290 static ssize_t mtd_badblocks_show(struct device *dev,
291 struct device_attribute *attr, char *buf)
293 struct mtd_info *mtd = dev_get_drvdata(dev);
294 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
296 return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->badblocks);
298 static DEVICE_ATTR(bad_blocks, S_IRUGO, mtd_badblocks_show, NULL);
300 static ssize_t mtd_bbtblocks_show(struct device *dev,
301 struct device_attribute *attr, char *buf)
303 struct mtd_info *mtd = dev_get_drvdata(dev);
304 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
306 return snprintf(buf, PAGE_SIZE, "%u\n", ecc_stats->bbtblocks);
308 static DEVICE_ATTR(bbt_blocks, S_IRUGO, mtd_bbtblocks_show, NULL);
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,
330 ATTRIBUTE_GROUPS(mtd);
332 static const struct device_type mtd_devtype = {
333 .name = "mtd",
334 .groups = mtd_groups,
335 .release = mtd_release,
338 static int mtd_partid_show(struct seq_file *s, void *p)
340 struct mtd_info *mtd = s->private;
342 seq_printf(s, "%s\n", mtd->dbg.partid);
344 return 0;
347 static int mtd_partid_debugfs_open(struct inode *inode, struct file *file)
349 return single_open(file, mtd_partid_show, inode->i_private);
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,
359 static int mtd_partname_show(struct seq_file *s, void *p)
361 struct mtd_info *mtd = s->private;
363 seq_printf(s, "%s\n", mtd->dbg.partname);
365 return 0;
368 static int mtd_partname_debugfs_open(struct inode *inode, struct file *file)
370 return single_open(file, mtd_partname_show, inode->i_private);
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,
380 static struct dentry *dfs_dir_mtd;
382 static void mtd_debugfs_populate(struct mtd_info *mtd)
384 struct device *dev = &mtd->dev;
385 struct dentry *root;
387 if (IS_ERR_OR_NULL(dfs_dir_mtd))
388 return;
390 root = debugfs_create_dir(dev_name(dev), dfs_dir_mtd);
391 mtd->dbg.dfs_dir = root;
393 if (mtd->dbg.partid)
394 debugfs_create_file("partid", 0400, root, mtd,
395 &mtd_partid_debug_fops);
397 if (mtd->dbg.partname)
398 debugfs_create_file("partname", 0400, root, mtd,
399 &mtd_partname_debug_fops);
402 #ifndef CONFIG_MMU
403 unsigned mtd_mmap_capabilities(struct mtd_info *mtd)
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;
416 EXPORT_SYMBOL_GPL(mtd_mmap_capabilities);
417 #endif
419 static int mtd_reboot_notifier(struct notifier_block *n, unsigned long state,
420 void *cmd)
422 struct mtd_info *mtd;
424 mtd = container_of(n, struct mtd_info, reboot_notifier);
425 mtd->_reboot(mtd);
427 return NOTIFY_DONE;
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
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.
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.
447 * From the pairing info the MTD user can find all the wunits paired with
448 * @wunit using the following loop:
450 * for (i = 0; i < mtd_pairing_groups(mtd); i++) {
451 * info.pair = i;
452 * mtd_pairing_info_to_wunit(mtd, &info);
453 * ...
456 int mtd_wunit_to_pairing_info(struct mtd_info *mtd, int wunit,
457 struct mtd_pairing_info *info)
459 int npairs = mtd_wunit_per_eb(mtd) / mtd_pairing_groups(mtd);
461 if (wunit < 0 || wunit >= npairs)
462 return -EINVAL;
464 if (mtd->pairing && mtd->pairing->get_info)
465 return mtd->pairing->get_info(mtd, wunit, info);
467 info->group = 0;
468 info->pair = wunit;
470 return 0;
472 EXPORT_SYMBOL_GPL(mtd_wunit_to_pairing_info);
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
479 * Returns a positive number representing the wunit associated to the info
480 * struct, or a negative error code.
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).
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:
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));
498 int mtd_pairing_info_to_wunit(struct mtd_info *mtd,
499 const struct mtd_pairing_info *info)
501 int ngroups = mtd_pairing_groups(mtd);
502 int npairs = mtd_wunit_per_eb(mtd) / ngroups;
504 if (!info || info->pair < 0 || info->pair >= npairs ||
505 info->group < 0 || info->group >= ngroups)
506 return -EINVAL;
508 if (mtd->pairing && mtd->pairing->get_wunit)
509 return mtd->pairing->get_wunit(mtd, info);
511 return info->pair;
513 EXPORT_SYMBOL_GPL(mtd_pairing_info_to_wunit);
516 * mtd_pairing_groups - get the number of pairing groups
517 * @mtd: pointer to new MTD device info structure
519 * Returns the number of pairing groups.
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.
525 int mtd_pairing_groups(struct mtd_info *mtd)
527 if (!mtd->pairing || !mtd->pairing->ngroups)
528 return 1;
530 return mtd->pairing->ngroups;
532 EXPORT_SYMBOL_GPL(mtd_pairing_groups);
534 static int mtd_nvmem_reg_read(void *priv, unsigned int offset,
535 void *val, size_t bytes)
537 struct mtd_info *mtd = priv;
538 size_t retlen;
539 int err;
541 err = mtd_read(mtd, offset, bytes, &retlen, val);
542 if (err && err != -EUCLEAN)
543 return err;
545 return retlen == bytes ? 0 : -EIO;
548 static int mtd_nvmem_add(struct mtd_info *mtd)
550 struct nvmem_config config = {};
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;
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);
576 return 0;
580 * add_mtd_device - register an MTD device
581 * @mtd: pointer to new MTD device info structure
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.
588 int add_mtd_device(struct mtd_info *mtd)
590 struct mtd_notifier *not;
591 int i, error;
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.
598 if (WARN_ONCE(mtd->dev.type, "MTD already registered\n"))
599 return -EEXIST;
601 BUG_ON(mtd->writesize == 0);
604 * MTD drivers should implement ->_{write,read}() or
605 * ->_{write,read}_oob(), but not both.
607 if (WARN_ON((mtd->_write && mtd->_write_oob) ||
608 (mtd->_read && mtd->_read_oob)))
609 return -EINVAL;
611 if (WARN_ON((!mtd->erasesize || !mtd->_erase) &&
612 !(mtd->flags & MTD_NO_ERASE)))
613 return -EINVAL;
615 mutex_lock(&mtd_table_mutex);
617 i = idr_alloc(&mtd_idr, mtd, 0, 0, GFP_KERNEL);
618 if (i < 0) {
619 error = i;
620 goto fail_locked;
623 mtd->index = i;
624 mtd->usecount = 0;
626 /* default value if not set by driver */
627 if (mtd->bitflip_threshold == 0)
628 mtd->bitflip_threshold = mtd->ecc_strength;
630 if (is_power_of_2(mtd->erasesize))
631 mtd->erasesize_shift = ffs(mtd->erasesize) - 1;
632 else
633 mtd->erasesize_shift = 0;
635 if (is_power_of_2(mtd->writesize))
636 mtd->writesize_shift = ffs(mtd->writesize) - 1;
637 else
638 mtd->writesize_shift = 0;
640 mtd->erasesize_mask = (1 << mtd->erasesize_shift) - 1;
641 mtd->writesize_mask = (1 << mtd->writesize_shift) - 1;
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;
654 /* Caller should have set dev.parent to match the
655 * physical device, if appropriate.
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;
667 /* Add the nvmem provider */
668 error = mtd_nvmem_add(mtd);
669 if (error)
670 goto fail_nvmem_add;
672 mtd_debugfs_populate(mtd);
674 device_create(&mtd_class, mtd->dev.parent, MTD_DEVT(i) + 1, NULL,
675 "mtd%dro", i);
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);
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;
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;
702 * del_mtd_device - unregister an MTD device
703 * @mtd: pointer to MTD device info structure
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.
711 int del_mtd_device(struct mtd_info *mtd)
713 int ret;
714 struct mtd_notifier *not;
716 mutex_lock(&mtd_table_mutex);
718 debugfs_remove_recursive(mtd->dbg.dfs_dir);
720 if (idr_find(&mtd_idr, mtd->index) != mtd) {
721 ret = -ENODEV;
722 goto out_error;
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);
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);
739 device_unregister(&mtd->dev);
741 idr_remove(&mtd_idr, mtd->index);
742 of_node_put(mtd_get_of_node(mtd));
744 module_put(THIS_MODULE);
745 ret = 0;
748 out_error:
749 mutex_unlock(&mtd_table_mutex);
750 return ret;
754 * Set a few defaults based on the parent devices, if not provided by the
755 * driver
757 static void mtd_set_dev_defaults(struct mtd_info *mtd)
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");
768 mtd->orig_flags = mtd->flags;
772 * mtd_device_parse_register - parse partitions and register an MTD device.
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
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:
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.
797 * Returns zero in case of success and a negative error code in case of failure.
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)
804 int ret;
806 mtd_set_dev_defaults(mtd);
808 if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER)) {
809 ret = add_mtd_device(mtd);
810 if (ret)
811 return ret;
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;
825 if (ret)
826 goto out;
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.
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).
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);
843 out:
844 if (ret && device_is_registered(&mtd->dev))
845 del_mtd_device(mtd);
847 return ret;
849 EXPORT_SYMBOL_GPL(mtd_device_parse_register);
852 * mtd_device_unregister - unregister an existing MTD device.
854 * @master: the MTD device to unregister. This will unregister both the master
855 * and any partitions if registered.
857 int mtd_device_unregister(struct mtd_info *master)
859 int err;
861 if (master->_reboot)
862 unregister_reboot_notifier(&master->reboot_notifier);
864 err = del_mtd_partitions(master);
865 if (err)
866 return err;
868 if (!device_is_registered(&master->dev))
869 return 0;
871 return del_mtd_device(master);
873 EXPORT_SYMBOL_GPL(mtd_device_unregister);
876 * register_mtd_user - register a 'user' of MTD devices.
877 * @new: pointer to notifier info structure
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.
883 void register_mtd_user (struct mtd_notifier *new)
885 struct mtd_info *mtd;
887 mutex_lock(&mtd_table_mutex);
889 list_add(&new->list, &mtd_notifiers);
891 __module_get(THIS_MODULE);
893 mtd_for_each_device(mtd)
894 new->add(mtd);
896 mutex_unlock(&mtd_table_mutex);
898 EXPORT_SYMBOL_GPL(register_mtd_user);
901 * unregister_mtd_user - unregister a 'user' of MTD devices.
902 * @old: pointer to notifier info structure
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.
909 int unregister_mtd_user (struct mtd_notifier *old)
911 struct mtd_info *mtd;
913 mutex_lock(&mtd_table_mutex);
915 module_put(THIS_MODULE);
917 mtd_for_each_device(mtd)
918 old->remove(mtd);
920 list_del(&old->list);
921 mutex_unlock(&mtd_table_mutex);
922 return 0;
924 EXPORT_SYMBOL_GPL(unregister_mtd_user);
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
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.
937 struct mtd_info *get_mtd_device(struct mtd_info *mtd, int num)
939 struct mtd_info *ret = NULL, *other;
940 int err = -ENODEV;
942 mutex_lock(&mtd_table_mutex);
944 if (num == -1) {
945 mtd_for_each_device(other) {
946 if (other == mtd) {
947 ret = mtd;
948 break;
951 } else if (num >= 0) {
952 ret = idr_find(&mtd_idr, num);
953 if (mtd && mtd != ret)
954 ret = NULL;
957 if (!ret) {
958 ret = ERR_PTR(err);
959 goto out;
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;
969 EXPORT_SYMBOL_GPL(get_mtd_device);
972 int __get_mtd_device(struct mtd_info *mtd)
974 int err;
976 if (!try_module_get(mtd->owner))
977 return -ENODEV;
979 if (mtd->_get_device) {
980 err = mtd->_get_device(mtd);
982 if (err) {
983 module_put(mtd->owner);
984 return err;
987 mtd->usecount++;
988 return 0;
990 EXPORT_SYMBOL_GPL(__get_mtd_device);
993 * get_mtd_device_nm - obtain a validated handle for an MTD device by
994 * device name
995 * @name: MTD device name to open
997 * This function returns MTD device description structure in case of
998 * success and an error code in case of failure.
1000 struct mtd_info *get_mtd_device_nm(const char *name)
1002 int err = -ENODEV;
1003 struct mtd_info *mtd = NULL, *other;
1005 mutex_lock(&mtd_table_mutex);
1007 mtd_for_each_device(other) {
1008 if (!strcmp(name, other->name)) {
1009 mtd = other;
1010 break;
1014 if (!mtd)
1015 goto out_unlock;
1017 err = __get_mtd_device(mtd);
1018 if (err)
1019 goto out_unlock;
1021 mutex_unlock(&mtd_table_mutex);
1022 return mtd;
1024 out_unlock:
1025 mutex_unlock(&mtd_table_mutex);
1026 return ERR_PTR(err);
1028 EXPORT_SYMBOL_GPL(get_mtd_device_nm);
1030 void put_mtd_device(struct mtd_info *mtd)
1032 mutex_lock(&mtd_table_mutex);
1033 __put_mtd_device(mtd);
1034 mutex_unlock(&mtd_table_mutex);
1037 EXPORT_SYMBOL_GPL(put_mtd_device);
1039 void __put_mtd_device(struct mtd_info *mtd)
1041 --mtd->usecount;
1042 BUG_ON(mtd->usecount < 0);
1044 if (mtd->_put_device)
1045 mtd->_put_device(mtd);
1047 module_put(mtd->owner);
1049 EXPORT_SYMBOL_GPL(__put_mtd_device);
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.
1056 int mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
1058 instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
1060 if (!mtd->erasesize || !mtd->_erase)
1061 return -ENOTSUPP;
1063 if (instr->addr >= mtd->size || instr->len > mtd->size - instr->addr)
1064 return -EINVAL;
1065 if (!(mtd->flags & MTD_WRITEABLE))
1066 return -EROFS;
1068 if (!instr->len)
1069 return 0;
1071 ledtrig_mtd_activity();
1072 return mtd->_erase(mtd, instr);
1074 EXPORT_SYMBOL_GPL(mtd_erase);
1077 * This stuff for eXecute-In-Place. phys is optional and may be set to NULL.
1079 int mtd_point(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
1080 void **virt, resource_size_t *phys)
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);
1094 EXPORT_SYMBOL_GPL(mtd_point);
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)
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);
1107 EXPORT_SYMBOL_GPL(mtd_unpoint);
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
1114 unsigned long mtd_get_unmapped_area(struct mtd_info *mtd, unsigned long len,
1115 unsigned long offset, unsigned long flags)
1117 size_t retlen;
1118 void *virt;
1119 int ret;
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;
1128 return (unsigned long)virt;
1130 EXPORT_SYMBOL_GPL(mtd_get_unmapped_area);
1132 int mtd_read(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
1133 u_char *buf)
1135 struct mtd_oob_ops ops = {
1136 .len = len,
1137 .datbuf = buf,
1139 int ret;
1141 ret = mtd_read_oob(mtd, from, &ops);
1142 *retlen = ops.retlen;
1144 return ret;
1146 EXPORT_SYMBOL_GPL(mtd_read);
1148 int mtd_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1149 const u_char *buf)
1151 struct mtd_oob_ops ops = {
1152 .len = len,
1153 .datbuf = (u8 *)buf,
1155 int ret;
1157 ret = mtd_write_oob(mtd, to, &ops);
1158 *retlen = ops.retlen;
1160 return ret;
1162 EXPORT_SYMBOL_GPL(mtd_write);
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).
1171 int mtd_panic_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1172 const u_char *buf)
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;
1186 return mtd->_panic_write(mtd, to, len, retlen, buf);
1188 EXPORT_SYMBOL_GPL(mtd_panic_write);
1190 static int mtd_check_oob_ops(struct mtd_info *mtd, loff_t offs,
1191 struct mtd_oob_ops *ops)
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.
1198 if (!ops->datbuf)
1199 ops->len = 0;
1201 if (!ops->oobbuf)
1202 ops->ooblen = 0;
1204 if (offs < 0 || offs + ops->len > mtd->size)
1205 return -EINVAL;
1207 if (ops->ooblen) {
1208 size_t maxooblen;
1210 if (ops->ooboffs >= mtd_oobavail(mtd, ops))
1211 return -EINVAL;
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;
1220 return 0;
1223 int mtd_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
1225 int ret_code;
1226 ops->retlen = ops->oobretlen = 0;
1228 ret_code = mtd_check_oob_ops(mtd, from, ops);
1229 if (ret_code)
1230 return ret_code;
1232 ledtrig_mtd_activity();
1234 /* Check the validity of a potential fallback on mtd->_read */
1235 if (!mtd->_read_oob && (!mtd->_read || ops->oobbuf))
1236 return -EOPNOTSUPP;
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);
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().
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;
1256 EXPORT_SYMBOL_GPL(mtd_read_oob);
1258 int mtd_write_oob(struct mtd_info *mtd, loff_t to,
1259 struct mtd_oob_ops *ops)
1261 int ret;
1263 ops->retlen = ops->oobretlen = 0;
1265 if (!(mtd->flags & MTD_WRITEABLE))
1266 return -EROFS;
1268 ret = mtd_check_oob_ops(mtd, to, ops);
1269 if (ret)
1270 return ret;
1272 ledtrig_mtd_activity();
1274 /* Check the validity of a potential fallback on mtd->_write */
1275 if (!mtd->_write_oob && (!mtd->_write || ops->oobbuf))
1276 return -EOPNOTSUPP;
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);
1284 EXPORT_SYMBOL_GPL(mtd_write_oob);
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
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.
1300 * Returns zero on success, a negative error code otherwise.
1302 int mtd_ooblayout_ecc(struct mtd_info *mtd, int section,
1303 struct mtd_oob_region *oobecc)
1305 memset(oobecc, 0, sizeof(*oobecc));
1307 if (!mtd || section < 0)
1308 return -EINVAL;
1310 if (!mtd->ooblayout || !mtd->ooblayout->ecc)
1311 return -ENOTSUPP;
1313 return mtd->ooblayout->ecc(mtd, section, oobecc);
1315 EXPORT_SYMBOL_GPL(mtd_ooblayout_ecc);
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
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.
1332 * Returns zero on success, a negative error code otherwise.
1334 int mtd_ooblayout_free(struct mtd_info *mtd, int section,
1335 struct mtd_oob_region *oobfree)
1337 memset(oobfree, 0, sizeof(*oobfree));
1339 if (!mtd || section < 0)
1340 return -EINVAL;
1342 if (!mtd->ooblayout || !mtd->ooblayout->free)
1343 return -ENOTSUPP;
1345 return mtd->ooblayout->free(mtd, section, oobfree);
1347 EXPORT_SYMBOL_GPL(mtd_ooblayout_free);
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
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:
1362 * mtd_ooblayout_find_region(mtd, 3, &section, &oobregion, mtd_ooblayout_ecc);
1364 * Returns zero on success, a negative error code otherwise.
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))
1372 int pos = 0, ret, section = 0;
1374 memset(oobregion, 0, sizeof(*oobregion));
1376 while (1) {
1377 ret = iter(mtd, section, oobregion);
1378 if (ret)
1379 return ret;
1381 if (pos + oobregion->length > byte)
1382 break;
1384 pos += oobregion->length;
1385 section++;
1389 * Adjust region info to make it start at the beginning at the
1390 * 'start' ECC byte.
1392 oobregion->offset += byte - pos;
1393 oobregion->length -= byte - pos;
1394 *sectionp = section;
1396 return 0;
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
1407 * Works like mtd_ooblayout_find_region() except it searches for a specific ECC
1408 * byte.
1410 * Returns zero on success, a negative error code otherwise.
1412 int mtd_ooblayout_find_eccregion(struct mtd_info *mtd, int eccbyte,
1413 int *section,
1414 struct mtd_oob_region *oobregion)
1416 return mtd_ooblayout_find_region(mtd, eccbyte, section, oobregion,
1417 mtd_ooblayout_ecc);
1419 EXPORT_SYMBOL_GPL(mtd_ooblayout_find_eccregion);
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
1430 * Extract bytes attached to a specific category (ECC or free)
1431 * from the OOB buffer and copy them into buf.
1433 * Returns zero on success, a negative error code otherwise.
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))
1441 struct mtd_oob_region oobregion;
1442 int section, ret;
1444 ret = mtd_ooblayout_find_region(mtd, start, &section,
1445 &oobregion, iter);
1447 while (!ret) {
1448 int cnt;
1450 cnt = min_t(int, nbytes, oobregion.length);
1451 memcpy(buf, oobbuf + oobregion.offset, cnt);
1452 buf += cnt;
1453 nbytes -= cnt;
1455 if (!nbytes)
1456 break;
1458 ret = iter(mtd, ++section, &oobregion);
1461 return ret;
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
1473 * Fill the OOB buffer with data provided in buf. The category (ECC or free)
1474 * is selected by passing the appropriate iterator.
1476 * Returns zero on success, a negative error code otherwise.
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))
1484 struct mtd_oob_region oobregion;
1485 int section, ret;
1487 ret = mtd_ooblayout_find_region(mtd, start, &section,
1488 &oobregion, iter);
1490 while (!ret) {
1491 int cnt;
1493 cnt = min_t(int, nbytes, oobregion.length);
1494 memcpy(oobbuf + oobregion.offset, buf, cnt);
1495 buf += cnt;
1496 nbytes -= cnt;
1498 if (!nbytes)
1499 break;
1501 ret = iter(mtd, ++section, &oobregion);
1504 return ret;
1508 * mtd_ooblayout_count_bytes - count the number of bytes in a OOB category
1509 * @mtd: mtd info structure
1510 * @iter: category iterator
1512 * Count the number of bytes in a given category.
1514 * Returns a positive value on success, a negative error code otherwise.
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))
1521 struct mtd_oob_region oobregion;
1522 int section = 0, ret, nbytes = 0;
1524 while (1) {
1525 ret = iter(mtd, section++, &oobregion);
1526 if (ret) {
1527 if (ret == -ERANGE)
1528 ret = nbytes;
1529 break;
1532 nbytes += oobregion.length;
1535 return ret;
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
1546 * Works like mtd_ooblayout_get_bytes(), except it acts on ECC bytes.
1548 * Returns zero on success, a negative error code otherwise.
1550 int mtd_ooblayout_get_eccbytes(struct mtd_info *mtd, u8 *eccbuf,
1551 const u8 *oobbuf, int start, int nbytes)
1553 return mtd_ooblayout_get_bytes(mtd, eccbuf, oobbuf, start, nbytes,
1554 mtd_ooblayout_ecc);
1556 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_eccbytes);
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
1566 * Works like mtd_ooblayout_set_bytes(), except it acts on ECC bytes.
1568 * Returns zero on success, a negative error code otherwise.
1570 int mtd_ooblayout_set_eccbytes(struct mtd_info *mtd, const u8 *eccbuf,
1571 u8 *oobbuf, int start, int nbytes)
1573 return mtd_ooblayout_set_bytes(mtd, eccbuf, oobbuf, start, nbytes,
1574 mtd_ooblayout_ecc);
1576 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_eccbytes);
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
1586 * Works like mtd_ooblayout_get_bytes(), except it acts on free bytes.
1588 * Returns zero on success, a negative error code otherwise.
1590 int mtd_ooblayout_get_databytes(struct mtd_info *mtd, u8 *databuf,
1591 const u8 *oobbuf, int start, int nbytes)
1593 return mtd_ooblayout_get_bytes(mtd, databuf, oobbuf, start, nbytes,
1594 mtd_ooblayout_free);
1596 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_databytes);
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
1606 * Works like mtd_ooblayout_get_bytes(), except it acts on free bytes.
1608 * Returns zero on success, a negative error code otherwise.
1610 int mtd_ooblayout_set_databytes(struct mtd_info *mtd, const u8 *databuf,
1611 u8 *oobbuf, int start, int nbytes)
1613 return mtd_ooblayout_set_bytes(mtd, databuf, oobbuf, start, nbytes,
1614 mtd_ooblayout_free);
1616 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_databytes);
1619 * mtd_ooblayout_count_freebytes - count the number of free bytes in OOB
1620 * @mtd: mtd info structure
1622 * Works like mtd_ooblayout_count_bytes(), except it count free bytes.
1624 * Returns zero on success, a negative error code otherwise.
1626 int mtd_ooblayout_count_freebytes(struct mtd_info *mtd)
1628 return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_free);
1630 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_freebytes);
1633 * mtd_ooblayout_count_eccbytes - count the number of ECC bytes in OOB
1634 * @mtd: mtd info structure
1636 * Works like mtd_ooblayout_count_bytes(), except it count ECC bytes.
1638 * Returns zero on success, a negative error code otherwise.
1640 int mtd_ooblayout_count_eccbytes(struct mtd_info *mtd)
1642 return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_ecc);
1644 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_eccbytes);
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.
1651 int mtd_get_fact_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
1652 struct otp_info *buf)
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);
1660 EXPORT_SYMBOL_GPL(mtd_get_fact_prot_info);
1662 int mtd_read_fact_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
1663 size_t *retlen, u_char *buf)
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);
1672 EXPORT_SYMBOL_GPL(mtd_read_fact_prot_reg);
1674 int mtd_get_user_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
1675 struct otp_info *buf)
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);
1683 EXPORT_SYMBOL_GPL(mtd_get_user_prot_info);
1685 int mtd_read_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
1686 size_t *retlen, u_char *buf)
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);
1695 EXPORT_SYMBOL_GPL(mtd_read_user_prot_reg);
1697 int mtd_write_user_prot_reg(struct mtd_info *mtd, loff_t to, size_t len,
1698 size_t *retlen, u_char *buf)
1700 int ret;
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;
1712 * If no data could be written at all, we are out of memory and
1713 * must return -ENOSPC.
1715 return (*retlen) ? 0 : -ENOSPC;
1717 EXPORT_SYMBOL_GPL(mtd_write_user_prot_reg);
1719 int mtd_lock_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len)
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);
1727 EXPORT_SYMBOL_GPL(mtd_lock_user_prot_reg);
1729 /* Chip-supported device locking */
1730 int mtd_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
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);
1740 EXPORT_SYMBOL_GPL(mtd_lock);
1742 int mtd_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
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);
1752 EXPORT_SYMBOL_GPL(mtd_unlock);
1754 int mtd_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
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);
1764 EXPORT_SYMBOL_GPL(mtd_is_locked);
1766 int mtd_block_isreserved(struct mtd_info *mtd, loff_t ofs)
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);
1774 EXPORT_SYMBOL_GPL(mtd_block_isreserved);
1776 int mtd_block_isbad(struct mtd_info *mtd, loff_t ofs)
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);
1784 EXPORT_SYMBOL_GPL(mtd_block_isbad);
1786 int mtd_block_markbad(struct mtd_info *mtd, loff_t ofs)
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);
1796 EXPORT_SYMBOL_GPL(mtd_block_markbad);
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.
1806 * This function returns zero in case of success and a negative error code in
1807 * case of failure.
1809 static int default_mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
1810 unsigned long count, loff_t to, size_t *retlen)
1812 unsigned long i;
1813 size_t totlen = 0, thislen;
1814 int ret = 0;
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;
1826 *retlen = totlen;
1827 return ret;
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.
1838 * This function returns zero in case of success and a negative error code in
1839 * case of failure.
1841 int mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
1842 unsigned long count, loff_t to, size_t *retlen)
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);
1851 EXPORT_SYMBOL_GPL(mtd_writev);
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.
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.
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.
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.
1875 * Returns a pointer to the allocated buffer on success; otherwise, NULL.
1877 void *mtd_kmalloc_up_to(const struct mtd_info *mtd, size_t *size)
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;
1883 *size = min_t(size_t, *size, KMALLOC_MAX_SIZE);
1885 while (*size > min_alloc) {
1886 kbuf = kmalloc(*size, flags);
1887 if (kbuf)
1888 return kbuf;
1890 *size >>= 1;
1891 *size = ALIGN(*size, mtd->writesize);
1895 * For the last resort allocation allow 'kmalloc()' to do all sorts of
1896 * things (write-back, dropping caches, etc) by using GFP_KERNEL.
1898 return kmalloc(*size, GFP_KERNEL);
1900 EXPORT_SYMBOL_GPL(mtd_kmalloc_up_to);
1902 #ifdef CONFIG_PROC_FS
1904 /*====================================================================*/
1905 /* Support for /proc/mtd */
1907 static int mtd_proc_show(struct seq_file *m, void *v)
1909 struct mtd_info *mtd;
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);
1918 mutex_unlock(&mtd_table_mutex);
1919 return 0;
1921 #endif /* CONFIG_PROC_FS */
1923 /*====================================================================*/
1924 /* Init code */
1926 static struct backing_dev_info * __init mtd_bdi_init(char *name)
1928 struct backing_dev_info *bdi;
1929 int ret;
1931 bdi = bdi_alloc(GFP_KERNEL);
1932 if (!bdi)
1933 return ERR_PTR(-ENOMEM);
1935 bdi->name = name;
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.
1940 ret = bdi_register(bdi, "%.28s-0", name);
1941 if (ret)
1942 bdi_put(bdi);
1944 return ret ? ERR_PTR(ret) : bdi;
1947 static struct proc_dir_entry *proc_mtd;
1949 static int __init init_mtd(void)
1951 int ret;
1953 ret = class_register(&mtd_class);
1954 if (ret)
1955 goto err_reg;
1957 mtd_bdi = mtd_bdi_init("mtd");
1958 if (IS_ERR(mtd_bdi)) {
1959 ret = PTR_ERR(mtd_bdi);
1960 goto err_bdi;
1963 proc_mtd = proc_create_single("mtd", 0, NULL, mtd_proc_show);
1965 ret = init_mtdchar();
1966 if (ret)
1967 goto out_procfs;
1969 dfs_dir_mtd = debugfs_create_dir("mtd", NULL);
1971 return 0;
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;
1984 static void __exit cleanup_mtd(void)
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);
1995 module_init(init_mtd);
1996 module_exit(cleanup_mtd);
1998 MODULE_LICENSE("GPL");
1999 MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
2000 MODULE_DESCRIPTION("Core MTD registration and access routines");