1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Core registration and callback routines for MTD
6 * Copyright © 1999-2010 David Woodhouse <dwmw2@infradead.org>
7 * Copyright © 2006 Red Hat UK Limited
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>
18 #include <linux/err.h>
19 #include <linux/ioctl.h>
20 #include <linux/init.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>
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);
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)
60 #define MTD_CLS_PM_OPS NULL
63 static struct class mtd_class = {
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 #define MTD_DEVICE_ATTR_RO(name) \
100 static DEVICE_ATTR(name, 0444, mtd_##name##_show, NULL)
102 #define MTD_DEVICE_ATTR_RW(name) \
103 static DEVICE_ATTR(name, 0644, mtd_##name##_show, mtd_##name##_store)
105 static ssize_t mtd_type_show(struct device *dev,
106 struct device_attribute *attr, char *buf)
108 struct mtd_info *mtd = dev_get_drvdata(dev);
133 case MTD_MLCNANDFLASH:
140 return sysfs_emit(buf, "%s\n", type);
142 MTD_DEVICE_ATTR_RO(type);
144 static ssize_t mtd_flags_show(struct device *dev,
145 struct device_attribute *attr, char *buf)
147 struct mtd_info *mtd = dev_get_drvdata(dev);
149 return sysfs_emit(buf, "0x%lx\n", (unsigned long)mtd->flags);
151 MTD_DEVICE_ATTR_RO(flags);
153 static ssize_t mtd_size_show(struct device *dev,
154 struct device_attribute *attr, char *buf)
156 struct mtd_info *mtd = dev_get_drvdata(dev);
158 return sysfs_emit(buf, "%llu\n", (unsigned long long)mtd->size);
160 MTD_DEVICE_ATTR_RO(size);
162 static ssize_t mtd_erasesize_show(struct device *dev,
163 struct device_attribute *attr, char *buf)
165 struct mtd_info *mtd = dev_get_drvdata(dev);
167 return sysfs_emit(buf, "%lu\n", (unsigned long)mtd->erasesize);
169 MTD_DEVICE_ATTR_RO(erasesize);
171 static ssize_t mtd_writesize_show(struct device *dev,
172 struct device_attribute *attr, char *buf)
174 struct mtd_info *mtd = dev_get_drvdata(dev);
176 return sysfs_emit(buf, "%lu\n", (unsigned long)mtd->writesize);
178 MTD_DEVICE_ATTR_RO(writesize);
180 static ssize_t mtd_subpagesize_show(struct device *dev,
181 struct device_attribute *attr, char *buf)
183 struct mtd_info *mtd = dev_get_drvdata(dev);
184 unsigned int subpagesize = mtd->writesize >> mtd->subpage_sft;
186 return sysfs_emit(buf, "%u\n", subpagesize);
188 MTD_DEVICE_ATTR_RO(subpagesize);
190 static ssize_t mtd_oobsize_show(struct device *dev,
191 struct device_attribute *attr, char *buf)
193 struct mtd_info *mtd = dev_get_drvdata(dev);
195 return sysfs_emit(buf, "%lu\n", (unsigned long)mtd->oobsize);
197 MTD_DEVICE_ATTR_RO(oobsize);
199 static ssize_t mtd_oobavail_show(struct device *dev,
200 struct device_attribute *attr, char *buf)
202 struct mtd_info *mtd = dev_get_drvdata(dev);
204 return sysfs_emit(buf, "%u\n", mtd->oobavail);
206 MTD_DEVICE_ATTR_RO(oobavail);
208 static ssize_t mtd_numeraseregions_show(struct device *dev,
209 struct device_attribute *attr, char *buf)
211 struct mtd_info *mtd = dev_get_drvdata(dev);
213 return sysfs_emit(buf, "%u\n", mtd->numeraseregions);
215 MTD_DEVICE_ATTR_RO(numeraseregions);
217 static ssize_t mtd_name_show(struct device *dev,
218 struct device_attribute *attr, char *buf)
220 struct mtd_info *mtd = dev_get_drvdata(dev);
222 return sysfs_emit(buf, "%s\n", mtd->name);
224 MTD_DEVICE_ATTR_RO(name);
226 static ssize_t mtd_ecc_strength_show(struct device *dev,
227 struct device_attribute *attr, char *buf)
229 struct mtd_info *mtd = dev_get_drvdata(dev);
231 return sysfs_emit(buf, "%u\n", mtd->ecc_strength);
233 MTD_DEVICE_ATTR_RO(ecc_strength);
235 static ssize_t mtd_bitflip_threshold_show(struct device *dev,
236 struct device_attribute *attr,
239 struct mtd_info *mtd = dev_get_drvdata(dev);
241 return sysfs_emit(buf, "%u\n", mtd->bitflip_threshold);
244 static ssize_t mtd_bitflip_threshold_store(struct device *dev,
245 struct device_attribute *attr,
246 const char *buf, size_t count)
248 struct mtd_info *mtd = dev_get_drvdata(dev);
249 unsigned int bitflip_threshold;
252 retval = kstrtouint(buf, 0, &bitflip_threshold);
256 mtd->bitflip_threshold = bitflip_threshold;
259 MTD_DEVICE_ATTR_RW(bitflip_threshold);
261 static ssize_t mtd_ecc_step_size_show(struct device *dev,
262 struct device_attribute *attr, char *buf)
264 struct mtd_info *mtd = dev_get_drvdata(dev);
266 return sysfs_emit(buf, "%u\n", mtd->ecc_step_size);
269 MTD_DEVICE_ATTR_RO(ecc_step_size);
271 static ssize_t mtd_corrected_bits_show(struct device *dev,
272 struct device_attribute *attr, char *buf)
274 struct mtd_info *mtd = dev_get_drvdata(dev);
275 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
277 return sysfs_emit(buf, "%u\n", ecc_stats->corrected);
279 MTD_DEVICE_ATTR_RO(corrected_bits); /* ecc stats corrected */
281 static ssize_t mtd_ecc_failures_show(struct device *dev,
282 struct device_attribute *attr, char *buf)
284 struct mtd_info *mtd = dev_get_drvdata(dev);
285 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
287 return sysfs_emit(buf, "%u\n", ecc_stats->failed);
289 MTD_DEVICE_ATTR_RO(ecc_failures); /* ecc stats errors */
291 static ssize_t mtd_bad_blocks_show(struct device *dev,
292 struct device_attribute *attr, char *buf)
294 struct mtd_info *mtd = dev_get_drvdata(dev);
295 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
297 return sysfs_emit(buf, "%u\n", ecc_stats->badblocks);
299 MTD_DEVICE_ATTR_RO(bad_blocks);
301 static ssize_t mtd_bbt_blocks_show(struct device *dev,
302 struct device_attribute *attr, char *buf)
304 struct mtd_info *mtd = dev_get_drvdata(dev);
305 struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
307 return sysfs_emit(buf, "%u\n", ecc_stats->bbtblocks);
309 MTD_DEVICE_ATTR_RO(bbt_blocks);
311 static struct attribute *mtd_attrs[] = {
313 &dev_attr_flags.attr,
315 &dev_attr_erasesize.attr,
316 &dev_attr_writesize.attr,
317 &dev_attr_subpagesize.attr,
318 &dev_attr_oobsize.attr,
319 &dev_attr_oobavail.attr,
320 &dev_attr_numeraseregions.attr,
322 &dev_attr_ecc_strength.attr,
323 &dev_attr_ecc_step_size.attr,
324 &dev_attr_corrected_bits.attr,
325 &dev_attr_ecc_failures.attr,
326 &dev_attr_bad_blocks.attr,
327 &dev_attr_bbt_blocks.attr,
328 &dev_attr_bitflip_threshold.attr,
331 ATTRIBUTE_GROUPS(mtd);
333 static const struct device_type mtd_devtype = {
335 .groups = mtd_groups,
336 .release = mtd_release,
339 static bool mtd_expert_analysis_mode;
341 #ifdef CONFIG_DEBUG_FS
342 bool mtd_check_expert_analysis_mode(void)
344 const char *mtd_expert_analysis_warning =
345 "Bad block checks have been entirely disabled.\n"
346 "This is only reserved for post-mortem forensics and debug purposes.\n"
347 "Never enable this mode if you do not know what you are doing!\n";
349 return WARN_ONCE(mtd_expert_analysis_mode, mtd_expert_analysis_warning);
351 EXPORT_SYMBOL_GPL(mtd_check_expert_analysis_mode);
354 static struct dentry *dfs_dir_mtd;
356 static void mtd_debugfs_populate(struct mtd_info *mtd)
358 struct device *dev = &mtd->dev;
360 if (IS_ERR_OR_NULL(dfs_dir_mtd))
363 mtd->dbg.dfs_dir = debugfs_create_dir(dev_name(dev), dfs_dir_mtd);
367 unsigned mtd_mmap_capabilities(struct mtd_info *mtd)
371 return NOMMU_MAP_COPY | NOMMU_MAP_DIRECT | NOMMU_MAP_EXEC |
372 NOMMU_MAP_READ | NOMMU_MAP_WRITE;
374 return NOMMU_MAP_COPY | NOMMU_MAP_DIRECT | NOMMU_MAP_EXEC |
377 return NOMMU_MAP_COPY;
380 EXPORT_SYMBOL_GPL(mtd_mmap_capabilities);
383 static int mtd_reboot_notifier(struct notifier_block *n, unsigned long state,
386 struct mtd_info *mtd;
388 mtd = container_of(n, struct mtd_info, reboot_notifier);
395 * mtd_wunit_to_pairing_info - get pairing information of a wunit
396 * @mtd: pointer to new MTD device info structure
397 * @wunit: write unit we are interested in
398 * @info: returned pairing information
400 * Retrieve pairing information associated to the wunit.
401 * This is mainly useful when dealing with MLC/TLC NANDs where pages can be
402 * paired together, and where programming a page may influence the page it is
404 * The notion of page is replaced by the term wunit (write-unit) to stay
405 * consistent with the ->writesize field.
407 * The @wunit argument can be extracted from an absolute offset using
408 * mtd_offset_to_wunit(). @info is filled with the pairing information attached
411 * From the pairing info the MTD user can find all the wunits paired with
412 * @wunit using the following loop:
414 * for (i = 0; i < mtd_pairing_groups(mtd); i++) {
416 * mtd_pairing_info_to_wunit(mtd, &info);
420 int mtd_wunit_to_pairing_info(struct mtd_info *mtd, int wunit,
421 struct mtd_pairing_info *info)
423 struct mtd_info *master = mtd_get_master(mtd);
424 int npairs = mtd_wunit_per_eb(master) / mtd_pairing_groups(master);
426 if (wunit < 0 || wunit >= npairs)
429 if (master->pairing && master->pairing->get_info)
430 return master->pairing->get_info(master, wunit, info);
437 EXPORT_SYMBOL_GPL(mtd_wunit_to_pairing_info);
440 * mtd_pairing_info_to_wunit - get wunit from pairing information
441 * @mtd: pointer to new MTD device info structure
442 * @info: pairing information struct
444 * Returns a positive number representing the wunit associated to the info
445 * struct, or a negative error code.
447 * This is the reverse of mtd_wunit_to_pairing_info(), and can help one to
448 * iterate over all wunits of a given pair (see mtd_wunit_to_pairing_info()
451 * It can also be used to only program the first page of each pair (i.e.
452 * page attached to group 0), which allows one to use an MLC NAND in
453 * software-emulated SLC mode:
456 * npairs = mtd_wunit_per_eb(mtd) / mtd_pairing_groups(mtd);
457 * for (info.pair = 0; info.pair < npairs; info.pair++) {
458 * wunit = mtd_pairing_info_to_wunit(mtd, &info);
459 * mtd_write(mtd, mtd_wunit_to_offset(mtd, blkoffs, wunit),
460 * mtd->writesize, &retlen, buf + (i * mtd->writesize));
463 int mtd_pairing_info_to_wunit(struct mtd_info *mtd,
464 const struct mtd_pairing_info *info)
466 struct mtd_info *master = mtd_get_master(mtd);
467 int ngroups = mtd_pairing_groups(master);
468 int npairs = mtd_wunit_per_eb(master) / ngroups;
470 if (!info || info->pair < 0 || info->pair >= npairs ||
471 info->group < 0 || info->group >= ngroups)
474 if (master->pairing && master->pairing->get_wunit)
475 return mtd->pairing->get_wunit(master, info);
479 EXPORT_SYMBOL_GPL(mtd_pairing_info_to_wunit);
482 * mtd_pairing_groups - get the number of pairing groups
483 * @mtd: pointer to new MTD device info structure
485 * Returns the number of pairing groups.
487 * This number is usually equal to the number of bits exposed by a single
488 * cell, and can be used in conjunction with mtd_pairing_info_to_wunit()
489 * to iterate over all pages of a given pair.
491 int mtd_pairing_groups(struct mtd_info *mtd)
493 struct mtd_info *master = mtd_get_master(mtd);
495 if (!master->pairing || !master->pairing->ngroups)
498 return master->pairing->ngroups;
500 EXPORT_SYMBOL_GPL(mtd_pairing_groups);
502 static int mtd_nvmem_reg_read(void *priv, unsigned int offset,
503 void *val, size_t bytes)
505 struct mtd_info *mtd = priv;
509 err = mtd_read(mtd, offset, bytes, &retlen, val);
510 if (err && err != -EUCLEAN)
513 return retlen == bytes ? 0 : -EIO;
516 static int mtd_nvmem_add(struct mtd_info *mtd)
518 struct device_node *node = mtd_get_of_node(mtd);
519 struct nvmem_config config = {};
522 config.dev = &mtd->dev;
523 config.name = dev_name(&mtd->dev);
524 config.owner = THIS_MODULE;
525 config.reg_read = mtd_nvmem_reg_read;
526 config.size = mtd->size;
527 config.word_size = 1;
529 config.read_only = true;
530 config.root_only = true;
531 config.ignore_wp = true;
532 config.no_of_node = !of_device_is_compatible(node, "nvmem-cells");
535 mtd->nvmem = nvmem_register(&config);
536 if (IS_ERR(mtd->nvmem)) {
537 /* Just ignore if there is no NVMEM support in the kernel */
538 if (PTR_ERR(mtd->nvmem) == -EOPNOTSUPP) {
541 dev_err(&mtd->dev, "Failed to register NVMEM device\n");
542 return PTR_ERR(mtd->nvmem);
550 * add_mtd_device - register an MTD device
551 * @mtd: pointer to new MTD device info structure
553 * Add a device to the list of MTD devices present in the system, and
554 * notify each currently active MTD 'user' of its arrival. Returns
555 * zero on success or non-zero on failure.
558 int add_mtd_device(struct mtd_info *mtd)
560 struct device_node *np = mtd_get_of_node(mtd);
561 struct mtd_info *master = mtd_get_master(mtd);
562 struct mtd_notifier *not;
566 * May occur, for instance, on buggy drivers which call
567 * mtd_device_parse_register() multiple times on the same master MTD,
568 * especially with CONFIG_MTD_PARTITIONED_MASTER=y.
570 if (WARN_ONCE(mtd->dev.type, "MTD already registered\n"))
573 BUG_ON(mtd->writesize == 0);
576 * MTD drivers should implement ->_{write,read}() or
577 * ->_{write,read}_oob(), but not both.
579 if (WARN_ON((mtd->_write && mtd->_write_oob) ||
580 (mtd->_read && mtd->_read_oob)))
583 if (WARN_ON((!mtd->erasesize || !master->_erase) &&
584 !(mtd->flags & MTD_NO_ERASE)))
588 * MTD_SLC_ON_MLC_EMULATION can only be set on partitions, when the
589 * master is an MLC NAND and has a proper pairing scheme defined.
590 * We also reject masters that implement ->_writev() for now, because
591 * NAND controller drivers don't implement this hook, and adding the
592 * SLC -> MLC address/length conversion to this path is useless if we
595 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION &&
596 (!mtd_is_partition(mtd) || master->type != MTD_MLCNANDFLASH ||
597 !master->pairing || master->_writev))
600 mutex_lock(&mtd_table_mutex);
604 ofidx = of_alias_get_id(np, "mtd");
606 i = idr_alloc(&mtd_idr, mtd, ofidx, ofidx + 1, GFP_KERNEL);
608 i = idr_alloc(&mtd_idr, mtd, 0, 0, GFP_KERNEL);
617 /* default value if not set by driver */
618 if (mtd->bitflip_threshold == 0)
619 mtd->bitflip_threshold = mtd->ecc_strength;
621 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
622 int ngroups = mtd_pairing_groups(master);
624 mtd->erasesize /= ngroups;
625 mtd->size = (u64)mtd_div_by_eb(mtd->size, master) *
629 if (is_power_of_2(mtd->erasesize))
630 mtd->erasesize_shift = ffs(mtd->erasesize) - 1;
632 mtd->erasesize_shift = 0;
634 if (is_power_of_2(mtd->writesize))
635 mtd->writesize_shift = ffs(mtd->writesize) - 1;
637 mtd->writesize_shift = 0;
639 mtd->erasesize_mask = (1 << mtd->erasesize_shift) - 1;
640 mtd->writesize_mask = (1 << mtd->writesize_shift) - 1;
642 /* Some chips always power up locked. Unlock them now */
643 if ((mtd->flags & MTD_WRITEABLE) && (mtd->flags & MTD_POWERUP_LOCK)) {
644 error = mtd_unlock(mtd, 0, mtd->size);
645 if (error && error != -EOPNOTSUPP)
647 "%s: unlock failed, writes may not work\n",
649 /* Ignore unlock failures? */
653 /* Caller should have set dev.parent to match the
654 * physical device, if appropriate.
656 mtd->dev.type = &mtd_devtype;
657 mtd->dev.class = &mtd_class;
658 mtd->dev.devt = MTD_DEVT(i);
659 dev_set_name(&mtd->dev, "mtd%d", i);
660 dev_set_drvdata(&mtd->dev, mtd);
661 of_node_get(mtd_get_of_node(mtd));
662 error = device_register(&mtd->dev);
666 /* Add the nvmem provider */
667 error = mtd_nvmem_add(mtd);
671 mtd_debugfs_populate(mtd);
673 device_create(&mtd_class, mtd->dev.parent, MTD_DEVT(i) + 1, NULL,
676 pr_debug("mtd: Giving out device %d to %s\n", i, mtd->name);
677 /* No need to get a refcount on the module containing
678 the notifier, since we hold the mtd_table_mutex */
679 list_for_each_entry(not, &mtd_notifiers, list)
682 mutex_unlock(&mtd_table_mutex);
683 /* We _know_ we aren't being removed, because
684 our caller is still holding us here. So none
685 of this try_ nonsense, and no bitching about it
687 __module_get(THIS_MODULE);
691 device_unregister(&mtd->dev);
693 of_node_put(mtd_get_of_node(mtd));
694 idr_remove(&mtd_idr, i);
696 mutex_unlock(&mtd_table_mutex);
701 * del_mtd_device - unregister an MTD device
702 * @mtd: pointer to MTD device info structure
704 * Remove a device from the list of MTD devices present in the system,
705 * and notify each currently active MTD 'user' of its departure.
706 * Returns zero on success or 1 on failure, which currently will happen
707 * if the requested device does not appear to be present in the list.
710 int del_mtd_device(struct mtd_info *mtd)
713 struct mtd_notifier *not;
715 mutex_lock(&mtd_table_mutex);
717 if (idr_find(&mtd_idr, mtd->index) != mtd) {
722 /* No need to get a refcount on the module containing
723 the notifier, since we hold the mtd_table_mutex */
724 list_for_each_entry(not, &mtd_notifiers, list)
728 printk(KERN_NOTICE "Removing MTD device #%d (%s) with use count %d\n",
729 mtd->index, mtd->name, mtd->usecount);
732 debugfs_remove_recursive(mtd->dbg.dfs_dir);
734 /* Try to remove the NVMEM provider */
735 nvmem_unregister(mtd->nvmem);
737 device_unregister(&mtd->dev);
739 /* Clear dev so mtd can be safely re-registered later if desired */
740 memset(&mtd->dev, 0, sizeof(mtd->dev));
742 idr_remove(&mtd_idr, mtd->index);
743 of_node_put(mtd_get_of_node(mtd));
745 module_put(THIS_MODULE);
750 mutex_unlock(&mtd_table_mutex);
755 * Set a few defaults based on the parent devices, if not provided by the
758 static void mtd_set_dev_defaults(struct mtd_info *mtd)
760 if (mtd->dev.parent) {
761 if (!mtd->owner && mtd->dev.parent->driver)
762 mtd->owner = mtd->dev.parent->driver->owner;
764 mtd->name = dev_name(mtd->dev.parent);
766 pr_debug("mtd device won't show a device symlink in sysfs\n");
769 INIT_LIST_HEAD(&mtd->partitions);
770 mutex_init(&mtd->master.partitions_lock);
771 mutex_init(&mtd->master.chrdev_lock);
774 static ssize_t mtd_otp_size(struct mtd_info *mtd, bool is_user)
776 struct otp_info *info;
782 info = kmalloc(PAGE_SIZE, GFP_KERNEL);
787 ret = mtd_get_user_prot_info(mtd, PAGE_SIZE, &retlen, info);
789 ret = mtd_get_fact_prot_info(mtd, PAGE_SIZE, &retlen, info);
793 for (i = 0; i < retlen / sizeof(*info); i++)
794 size += info[i].length;
802 /* ENODATA means there is no OTP region. */
803 return ret == -ENODATA ? 0 : ret;
806 static struct nvmem_device *mtd_otp_nvmem_register(struct mtd_info *mtd,
807 const char *compatible,
809 nvmem_reg_read_t reg_read)
811 struct nvmem_device *nvmem = NULL;
812 struct nvmem_config config = {};
813 struct device_node *np;
815 /* DT binding is optional */
816 np = of_get_compatible_child(mtd->dev.of_node, compatible);
818 /* OTP nvmem will be registered on the physical device */
819 config.dev = mtd->dev.parent;
820 config.name = kasprintf(GFP_KERNEL, "%s-%s", dev_name(&mtd->dev), compatible);
821 config.id = NVMEM_DEVID_NONE;
822 config.owner = THIS_MODULE;
823 config.type = NVMEM_TYPE_OTP;
824 config.root_only = true;
825 config.ignore_wp = true;
826 config.reg_read = reg_read;
831 nvmem = nvmem_register(&config);
832 /* Just ignore if there is no NVMEM support in the kernel */
833 if (IS_ERR(nvmem) && PTR_ERR(nvmem) == -EOPNOTSUPP)
842 static int mtd_nvmem_user_otp_reg_read(void *priv, unsigned int offset,
843 void *val, size_t bytes)
845 struct mtd_info *mtd = priv;
849 ret = mtd_read_user_prot_reg(mtd, offset, bytes, &retlen, val);
853 return retlen == bytes ? 0 : -EIO;
856 static int mtd_nvmem_fact_otp_reg_read(void *priv, unsigned int offset,
857 void *val, size_t bytes)
859 struct mtd_info *mtd = priv;
863 ret = mtd_read_fact_prot_reg(mtd, offset, bytes, &retlen, val);
867 return retlen == bytes ? 0 : -EIO;
870 static int mtd_otp_nvmem_add(struct mtd_info *mtd)
872 struct nvmem_device *nvmem;
876 if (mtd->_get_user_prot_info && mtd->_read_user_prot_reg) {
877 size = mtd_otp_size(mtd, true);
882 nvmem = mtd_otp_nvmem_register(mtd, "user-otp", size,
883 mtd_nvmem_user_otp_reg_read);
885 dev_err(&mtd->dev, "Failed to register OTP NVMEM device\n");
886 return PTR_ERR(nvmem);
888 mtd->otp_user_nvmem = nvmem;
892 if (mtd->_get_fact_prot_info && mtd->_read_fact_prot_reg) {
893 size = mtd_otp_size(mtd, false);
900 nvmem = mtd_otp_nvmem_register(mtd, "factory-otp", size,
901 mtd_nvmem_fact_otp_reg_read);
903 dev_err(&mtd->dev, "Failed to register OTP NVMEM device\n");
904 err = PTR_ERR(nvmem);
907 mtd->otp_factory_nvmem = nvmem;
914 nvmem_unregister(mtd->otp_user_nvmem);
919 * mtd_device_parse_register - parse partitions and register an MTD device.
921 * @mtd: the MTD device to register
922 * @types: the list of MTD partition probes to try, see
923 * 'parse_mtd_partitions()' for more information
924 * @parser_data: MTD partition parser-specific data
925 * @parts: fallback partition information to register, if parsing fails;
926 * only valid if %nr_parts > %0
927 * @nr_parts: the number of partitions in parts, if zero then the full
928 * MTD device is registered if no partition info is found
930 * This function aggregates MTD partitions parsing (done by
931 * 'parse_mtd_partitions()') and MTD device and partitions registering. It
932 * basically follows the most common pattern found in many MTD drivers:
934 * * If the MTD_PARTITIONED_MASTER option is set, then the device as a whole is
936 * * Then It tries to probe partitions on MTD device @mtd using parsers
937 * specified in @types (if @types is %NULL, then the default list of parsers
938 * is used, see 'parse_mtd_partitions()' for more information). If none are
939 * found this functions tries to fallback to information specified in
941 * * If no partitions were found this function just registers the MTD device
944 * Returns zero in case of success and a negative error code in case of failure.
946 int mtd_device_parse_register(struct mtd_info *mtd, const char * const *types,
947 struct mtd_part_parser_data *parser_data,
948 const struct mtd_partition *parts,
953 mtd_set_dev_defaults(mtd);
955 if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER)) {
956 ret = add_mtd_device(mtd);
961 /* Prefer parsed partitions over driver-provided fallback */
962 ret = parse_mtd_partitions(mtd, types, parser_data);
963 if (ret == -EPROBE_DEFER)
969 ret = add_mtd_partitions(mtd, parts, nr_parts);
970 else if (!device_is_registered(&mtd->dev))
971 ret = add_mtd_device(mtd);
979 * FIXME: some drivers unfortunately call this function more than once.
980 * So we have to check if we've already assigned the reboot notifier.
982 * Generally, we can make multiple calls work for most cases, but it
983 * does cause problems with parse_mtd_partitions() above (e.g.,
984 * cmdlineparts will register partitions more than once).
986 WARN_ONCE(mtd->_reboot && mtd->reboot_notifier.notifier_call,
987 "MTD already registered\n");
988 if (mtd->_reboot && !mtd->reboot_notifier.notifier_call) {
989 mtd->reboot_notifier.notifier_call = mtd_reboot_notifier;
990 register_reboot_notifier(&mtd->reboot_notifier);
993 ret = mtd_otp_nvmem_add(mtd);
996 if (ret && device_is_registered(&mtd->dev))
1001 EXPORT_SYMBOL_GPL(mtd_device_parse_register);
1004 * mtd_device_unregister - unregister an existing MTD device.
1006 * @master: the MTD device to unregister. This will unregister both the master
1007 * and any partitions if registered.
1009 int mtd_device_unregister(struct mtd_info *master)
1013 if (master->_reboot) {
1014 unregister_reboot_notifier(&master->reboot_notifier);
1015 memset(&master->reboot_notifier, 0, sizeof(master->reboot_notifier));
1018 nvmem_unregister(master->otp_user_nvmem);
1019 nvmem_unregister(master->otp_factory_nvmem);
1021 err = del_mtd_partitions(master);
1025 if (!device_is_registered(&master->dev))
1028 return del_mtd_device(master);
1030 EXPORT_SYMBOL_GPL(mtd_device_unregister);
1033 * register_mtd_user - register a 'user' of MTD devices.
1034 * @new: pointer to notifier info structure
1036 * Registers a pair of callbacks function to be called upon addition
1037 * or removal of MTD devices. Causes the 'add' callback to be immediately
1038 * invoked for each MTD device currently present in the system.
1040 void register_mtd_user (struct mtd_notifier *new)
1042 struct mtd_info *mtd;
1044 mutex_lock(&mtd_table_mutex);
1046 list_add(&new->list, &mtd_notifiers);
1048 __module_get(THIS_MODULE);
1050 mtd_for_each_device(mtd)
1053 mutex_unlock(&mtd_table_mutex);
1055 EXPORT_SYMBOL_GPL(register_mtd_user);
1058 * unregister_mtd_user - unregister a 'user' of MTD devices.
1059 * @old: pointer to notifier info structure
1061 * Removes a callback function pair from the list of 'users' to be
1062 * notified upon addition or removal of MTD devices. Causes the
1063 * 'remove' callback to be immediately invoked for each MTD device
1064 * currently present in the system.
1066 int unregister_mtd_user (struct mtd_notifier *old)
1068 struct mtd_info *mtd;
1070 mutex_lock(&mtd_table_mutex);
1072 module_put(THIS_MODULE);
1074 mtd_for_each_device(mtd)
1077 list_del(&old->list);
1078 mutex_unlock(&mtd_table_mutex);
1081 EXPORT_SYMBOL_GPL(unregister_mtd_user);
1084 * get_mtd_device - obtain a validated handle for an MTD device
1085 * @mtd: last known address of the required MTD device
1086 * @num: internal device number of the required MTD device
1088 * Given a number and NULL address, return the num'th entry in the device
1089 * table, if any. Given an address and num == -1, search the device table
1090 * for a device with that address and return if it's still present. Given
1091 * both, return the num'th driver only if its address matches. Return
1092 * error code if not.
1094 struct mtd_info *get_mtd_device(struct mtd_info *mtd, int num)
1096 struct mtd_info *ret = NULL, *other;
1099 mutex_lock(&mtd_table_mutex);
1102 mtd_for_each_device(other) {
1108 } else if (num >= 0) {
1109 ret = idr_find(&mtd_idr, num);
1110 if (mtd && mtd != ret)
1119 err = __get_mtd_device(ret);
1123 mutex_unlock(&mtd_table_mutex);
1126 EXPORT_SYMBOL_GPL(get_mtd_device);
1129 int __get_mtd_device(struct mtd_info *mtd)
1131 struct mtd_info *master = mtd_get_master(mtd);
1134 if (!try_module_get(master->owner))
1137 if (master->_get_device) {
1138 err = master->_get_device(mtd);
1141 module_put(master->owner);
1148 while (mtd->parent) {
1155 EXPORT_SYMBOL_GPL(__get_mtd_device);
1158 * get_mtd_device_nm - obtain a validated handle for an MTD device by
1160 * @name: MTD device name to open
1162 * This function returns MTD device description structure in case of
1163 * success and an error code in case of failure.
1165 struct mtd_info *get_mtd_device_nm(const char *name)
1168 struct mtd_info *mtd = NULL, *other;
1170 mutex_lock(&mtd_table_mutex);
1172 mtd_for_each_device(other) {
1173 if (!strcmp(name, other->name)) {
1182 err = __get_mtd_device(mtd);
1186 mutex_unlock(&mtd_table_mutex);
1190 mutex_unlock(&mtd_table_mutex);
1191 return ERR_PTR(err);
1193 EXPORT_SYMBOL_GPL(get_mtd_device_nm);
1195 void put_mtd_device(struct mtd_info *mtd)
1197 mutex_lock(&mtd_table_mutex);
1198 __put_mtd_device(mtd);
1199 mutex_unlock(&mtd_table_mutex);
1202 EXPORT_SYMBOL_GPL(put_mtd_device);
1204 void __put_mtd_device(struct mtd_info *mtd)
1206 struct mtd_info *master = mtd_get_master(mtd);
1208 while (mtd->parent) {
1210 BUG_ON(mtd->usecount < 0);
1216 if (master->_put_device)
1217 master->_put_device(master);
1219 module_put(master->owner);
1221 EXPORT_SYMBOL_GPL(__put_mtd_device);
1224 * Erase is an synchronous operation. Device drivers are epected to return a
1225 * negative error code if the operation failed and update instr->fail_addr
1226 * to point the portion that was not properly erased.
1228 int mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
1230 struct mtd_info *master = mtd_get_master(mtd);
1231 u64 mst_ofs = mtd_get_master_ofs(mtd, 0);
1232 struct erase_info adjinstr;
1235 instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
1238 if (!mtd->erasesize || !master->_erase)
1241 if (instr->addr >= mtd->size || instr->len > mtd->size - instr->addr)
1243 if (!(mtd->flags & MTD_WRITEABLE))
1249 ledtrig_mtd_activity();
1251 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
1252 adjinstr.addr = (loff_t)mtd_div_by_eb(instr->addr, mtd) *
1254 adjinstr.len = ((u64)mtd_div_by_eb(instr->addr + instr->len, mtd) *
1255 master->erasesize) -
1259 adjinstr.addr += mst_ofs;
1261 ret = master->_erase(master, &adjinstr);
1263 if (adjinstr.fail_addr != MTD_FAIL_ADDR_UNKNOWN) {
1264 instr->fail_addr = adjinstr.fail_addr - mst_ofs;
1265 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
1266 instr->fail_addr = mtd_div_by_eb(instr->fail_addr,
1268 instr->fail_addr *= mtd->erasesize;
1274 EXPORT_SYMBOL_GPL(mtd_erase);
1277 * This stuff for eXecute-In-Place. phys is optional and may be set to NULL.
1279 int mtd_point(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
1280 void **virt, resource_size_t *phys)
1282 struct mtd_info *master = mtd_get_master(mtd);
1288 if (!master->_point)
1290 if (from < 0 || from >= mtd->size || len > mtd->size - from)
1295 from = mtd_get_master_ofs(mtd, from);
1296 return master->_point(master, from, len, retlen, virt, phys);
1298 EXPORT_SYMBOL_GPL(mtd_point);
1300 /* We probably shouldn't allow XIP if the unpoint isn't a NULL */
1301 int mtd_unpoint(struct mtd_info *mtd, loff_t from, size_t len)
1303 struct mtd_info *master = mtd_get_master(mtd);
1305 if (!master->_unpoint)
1307 if (from < 0 || from >= mtd->size || len > mtd->size - from)
1311 return master->_unpoint(master, mtd_get_master_ofs(mtd, from), len);
1313 EXPORT_SYMBOL_GPL(mtd_unpoint);
1316 * Allow NOMMU mmap() to directly map the device (if not NULL)
1317 * - return the address to which the offset maps
1318 * - return -ENOSYS to indicate refusal to do the mapping
1320 unsigned long mtd_get_unmapped_area(struct mtd_info *mtd, unsigned long len,
1321 unsigned long offset, unsigned long flags)
1327 ret = mtd_point(mtd, offset, len, &retlen, &virt, NULL);
1330 if (retlen != len) {
1331 mtd_unpoint(mtd, offset, retlen);
1334 return (unsigned long)virt;
1336 EXPORT_SYMBOL_GPL(mtd_get_unmapped_area);
1338 static void mtd_update_ecc_stats(struct mtd_info *mtd, struct mtd_info *master,
1339 const struct mtd_ecc_stats *old_stats)
1341 struct mtd_ecc_stats diff;
1346 diff = master->ecc_stats;
1347 diff.failed -= old_stats->failed;
1348 diff.corrected -= old_stats->corrected;
1350 while (mtd->parent) {
1351 mtd->ecc_stats.failed += diff.failed;
1352 mtd->ecc_stats.corrected += diff.corrected;
1357 int mtd_read(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
1360 struct mtd_oob_ops ops = {
1366 ret = mtd_read_oob(mtd, from, &ops);
1367 *retlen = ops.retlen;
1371 EXPORT_SYMBOL_GPL(mtd_read);
1373 int mtd_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1376 struct mtd_oob_ops ops = {
1378 .datbuf = (u8 *)buf,
1382 ret = mtd_write_oob(mtd, to, &ops);
1383 *retlen = ops.retlen;
1387 EXPORT_SYMBOL_GPL(mtd_write);
1390 * In blackbox flight recorder like scenarios we want to make successful writes
1391 * in interrupt context. panic_write() is only intended to be called when its
1392 * known the kernel is about to panic and we need the write to succeed. Since
1393 * the kernel is not going to be running for much longer, this function can
1394 * break locks and delay to ensure the write succeeds (but not sleep).
1396 int mtd_panic_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1399 struct mtd_info *master = mtd_get_master(mtd);
1402 if (!master->_panic_write)
1404 if (to < 0 || to >= mtd->size || len > mtd->size - to)
1406 if (!(mtd->flags & MTD_WRITEABLE))
1410 if (!master->oops_panic_write)
1411 master->oops_panic_write = true;
1413 return master->_panic_write(master, mtd_get_master_ofs(mtd, to), len,
1416 EXPORT_SYMBOL_GPL(mtd_panic_write);
1418 static int mtd_check_oob_ops(struct mtd_info *mtd, loff_t offs,
1419 struct mtd_oob_ops *ops)
1422 * Some users are setting ->datbuf or ->oobbuf to NULL, but are leaving
1423 * ->len or ->ooblen uninitialized. Force ->len and ->ooblen to 0 in
1432 if (offs < 0 || offs + ops->len > mtd->size)
1438 if (ops->ooboffs >= mtd_oobavail(mtd, ops))
1441 maxooblen = ((size_t)(mtd_div_by_ws(mtd->size, mtd) -
1442 mtd_div_by_ws(offs, mtd)) *
1443 mtd_oobavail(mtd, ops)) - ops->ooboffs;
1444 if (ops->ooblen > maxooblen)
1451 static int mtd_read_oob_std(struct mtd_info *mtd, loff_t from,
1452 struct mtd_oob_ops *ops)
1454 struct mtd_info *master = mtd_get_master(mtd);
1457 from = mtd_get_master_ofs(mtd, from);
1458 if (master->_read_oob)
1459 ret = master->_read_oob(master, from, ops);
1461 ret = master->_read(master, from, ops->len, &ops->retlen,
1467 static int mtd_write_oob_std(struct mtd_info *mtd, loff_t to,
1468 struct mtd_oob_ops *ops)
1470 struct mtd_info *master = mtd_get_master(mtd);
1473 to = mtd_get_master_ofs(mtd, to);
1474 if (master->_write_oob)
1475 ret = master->_write_oob(master, to, ops);
1477 ret = master->_write(master, to, ops->len, &ops->retlen,
1483 static int mtd_io_emulated_slc(struct mtd_info *mtd, loff_t start, bool read,
1484 struct mtd_oob_ops *ops)
1486 struct mtd_info *master = mtd_get_master(mtd);
1487 int ngroups = mtd_pairing_groups(master);
1488 int npairs = mtd_wunit_per_eb(master) / ngroups;
1489 struct mtd_oob_ops adjops = *ops;
1490 unsigned int wunit, oobavail;
1491 struct mtd_pairing_info info;
1492 int max_bitflips = 0;
1496 ebofs = mtd_mod_by_eb(start, mtd);
1497 base = (loff_t)mtd_div_by_eb(start, mtd) * master->erasesize;
1499 info.pair = mtd_div_by_ws(ebofs, mtd);
1500 pageofs = mtd_mod_by_ws(ebofs, mtd);
1501 oobavail = mtd_oobavail(mtd, ops);
1503 while (ops->retlen < ops->len || ops->oobretlen < ops->ooblen) {
1506 if (info.pair >= npairs) {
1508 base += master->erasesize;
1511 wunit = mtd_pairing_info_to_wunit(master, &info);
1512 pos = mtd_wunit_to_offset(mtd, base, wunit);
1514 adjops.len = ops->len - ops->retlen;
1515 if (adjops.len > mtd->writesize - pageofs)
1516 adjops.len = mtd->writesize - pageofs;
1518 adjops.ooblen = ops->ooblen - ops->oobretlen;
1519 if (adjops.ooblen > oobavail - adjops.ooboffs)
1520 adjops.ooblen = oobavail - adjops.ooboffs;
1523 ret = mtd_read_oob_std(mtd, pos + pageofs, &adjops);
1525 max_bitflips = max(max_bitflips, ret);
1527 ret = mtd_write_oob_std(mtd, pos + pageofs, &adjops);
1533 max_bitflips = max(max_bitflips, ret);
1534 ops->retlen += adjops.retlen;
1535 ops->oobretlen += adjops.oobretlen;
1536 adjops.datbuf += adjops.retlen;
1537 adjops.oobbuf += adjops.oobretlen;
1543 return max_bitflips;
1546 int mtd_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
1548 struct mtd_info *master = mtd_get_master(mtd);
1549 struct mtd_ecc_stats old_stats = master->ecc_stats;
1552 ops->retlen = ops->oobretlen = 0;
1554 ret_code = mtd_check_oob_ops(mtd, from, ops);
1558 ledtrig_mtd_activity();
1560 /* Check the validity of a potential fallback on mtd->_read */
1561 if (!master->_read_oob && (!master->_read || ops->oobbuf))
1564 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
1565 ret_code = mtd_io_emulated_slc(mtd, from, true, ops);
1567 ret_code = mtd_read_oob_std(mtd, from, ops);
1569 mtd_update_ecc_stats(mtd, master, &old_stats);
1572 * In cases where ops->datbuf != NULL, mtd->_read_oob() has semantics
1573 * similar to mtd->_read(), returning a non-negative integer
1574 * representing max bitflips. In other cases, mtd->_read_oob() may
1575 * return -EUCLEAN. In all cases, perform similar logic to mtd_read().
1577 if (unlikely(ret_code < 0))
1579 if (mtd->ecc_strength == 0)
1580 return 0; /* device lacks ecc */
1581 return ret_code >= mtd->bitflip_threshold ? -EUCLEAN : 0;
1583 EXPORT_SYMBOL_GPL(mtd_read_oob);
1585 int mtd_write_oob(struct mtd_info *mtd, loff_t to,
1586 struct mtd_oob_ops *ops)
1588 struct mtd_info *master = mtd_get_master(mtd);
1591 ops->retlen = ops->oobretlen = 0;
1593 if (!(mtd->flags & MTD_WRITEABLE))
1596 ret = mtd_check_oob_ops(mtd, to, ops);
1600 ledtrig_mtd_activity();
1602 /* Check the validity of a potential fallback on mtd->_write */
1603 if (!master->_write_oob && (!master->_write || ops->oobbuf))
1606 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
1607 return mtd_io_emulated_slc(mtd, to, false, ops);
1609 return mtd_write_oob_std(mtd, to, ops);
1611 EXPORT_SYMBOL_GPL(mtd_write_oob);
1614 * mtd_ooblayout_ecc - Get the OOB region definition of a specific ECC section
1615 * @mtd: MTD device structure
1616 * @section: ECC section. Depending on the layout you may have all the ECC
1617 * bytes stored in a single contiguous section, or one section
1618 * per ECC chunk (and sometime several sections for a single ECC
1620 * @oobecc: OOB region struct filled with the appropriate ECC position
1623 * This function returns ECC section information in the OOB area. If you want
1624 * to get all the ECC bytes information, then you should call
1625 * mtd_ooblayout_ecc(mtd, section++, oobecc) until it returns -ERANGE.
1627 * Returns zero on success, a negative error code otherwise.
1629 int mtd_ooblayout_ecc(struct mtd_info *mtd, int section,
1630 struct mtd_oob_region *oobecc)
1632 struct mtd_info *master = mtd_get_master(mtd);
1634 memset(oobecc, 0, sizeof(*oobecc));
1636 if (!master || section < 0)
1639 if (!master->ooblayout || !master->ooblayout->ecc)
1642 return master->ooblayout->ecc(master, section, oobecc);
1644 EXPORT_SYMBOL_GPL(mtd_ooblayout_ecc);
1647 * mtd_ooblayout_free - Get the OOB region definition of a specific free
1649 * @mtd: MTD device structure
1650 * @section: Free section you are interested in. Depending on the layout
1651 * you may have all the free bytes stored in a single contiguous
1652 * section, or one section per ECC chunk plus an extra section
1653 * for the remaining bytes (or other funky layout).
1654 * @oobfree: OOB region struct filled with the appropriate free position
1657 * This function returns free bytes position in the OOB area. If you want
1658 * to get all the free bytes information, then you should call
1659 * mtd_ooblayout_free(mtd, section++, oobfree) until it returns -ERANGE.
1661 * Returns zero on success, a negative error code otherwise.
1663 int mtd_ooblayout_free(struct mtd_info *mtd, int section,
1664 struct mtd_oob_region *oobfree)
1666 struct mtd_info *master = mtd_get_master(mtd);
1668 memset(oobfree, 0, sizeof(*oobfree));
1670 if (!master || section < 0)
1673 if (!master->ooblayout || !master->ooblayout->free)
1676 return master->ooblayout->free(master, section, oobfree);
1678 EXPORT_SYMBOL_GPL(mtd_ooblayout_free);
1681 * mtd_ooblayout_find_region - Find the region attached to a specific byte
1682 * @mtd: mtd info structure
1683 * @byte: the byte we are searching for
1684 * @sectionp: pointer where the section id will be stored
1685 * @oobregion: used to retrieve the ECC position
1686 * @iter: iterator function. Should be either mtd_ooblayout_free or
1687 * mtd_ooblayout_ecc depending on the region type you're searching for
1689 * This function returns the section id and oobregion information of a
1690 * specific byte. For example, say you want to know where the 4th ECC byte is
1691 * stored, you'll use:
1693 * mtd_ooblayout_find_region(mtd, 3, §ion, &oobregion, mtd_ooblayout_ecc);
1695 * Returns zero on success, a negative error code otherwise.
1697 static int mtd_ooblayout_find_region(struct mtd_info *mtd, int byte,
1698 int *sectionp, struct mtd_oob_region *oobregion,
1699 int (*iter)(struct mtd_info *,
1701 struct mtd_oob_region *oobregion))
1703 int pos = 0, ret, section = 0;
1705 memset(oobregion, 0, sizeof(*oobregion));
1708 ret = iter(mtd, section, oobregion);
1712 if (pos + oobregion->length > byte)
1715 pos += oobregion->length;
1720 * Adjust region info to make it start at the beginning at the
1723 oobregion->offset += byte - pos;
1724 oobregion->length -= byte - pos;
1725 *sectionp = section;
1731 * mtd_ooblayout_find_eccregion - Find the ECC region attached to a specific
1733 * @mtd: mtd info structure
1734 * @eccbyte: the byte we are searching for
1735 * @section: pointer where the section id will be stored
1736 * @oobregion: OOB region information
1738 * Works like mtd_ooblayout_find_region() except it searches for a specific ECC
1741 * Returns zero on success, a negative error code otherwise.
1743 int mtd_ooblayout_find_eccregion(struct mtd_info *mtd, int eccbyte,
1745 struct mtd_oob_region *oobregion)
1747 return mtd_ooblayout_find_region(mtd, eccbyte, section, oobregion,
1750 EXPORT_SYMBOL_GPL(mtd_ooblayout_find_eccregion);
1753 * mtd_ooblayout_get_bytes - Extract OOB bytes from the oob buffer
1754 * @mtd: mtd info structure
1755 * @buf: destination buffer to store OOB bytes
1756 * @oobbuf: OOB buffer
1757 * @start: first byte to retrieve
1758 * @nbytes: number of bytes to retrieve
1759 * @iter: section iterator
1761 * Extract bytes attached to a specific category (ECC or free)
1762 * from the OOB buffer and copy them into buf.
1764 * Returns zero on success, a negative error code otherwise.
1766 static int mtd_ooblayout_get_bytes(struct mtd_info *mtd, u8 *buf,
1767 const u8 *oobbuf, int start, int nbytes,
1768 int (*iter)(struct mtd_info *,
1770 struct mtd_oob_region *oobregion))
1772 struct mtd_oob_region oobregion;
1775 ret = mtd_ooblayout_find_region(mtd, start, §ion,
1781 cnt = min_t(int, nbytes, oobregion.length);
1782 memcpy(buf, oobbuf + oobregion.offset, cnt);
1789 ret = iter(mtd, ++section, &oobregion);
1796 * mtd_ooblayout_set_bytes - put OOB bytes into the oob buffer
1797 * @mtd: mtd info structure
1798 * @buf: source buffer to get OOB bytes from
1799 * @oobbuf: OOB buffer
1800 * @start: first OOB byte to set
1801 * @nbytes: number of OOB bytes to set
1802 * @iter: section iterator
1804 * Fill the OOB buffer with data provided in buf. The category (ECC or free)
1805 * is selected by passing the appropriate iterator.
1807 * Returns zero on success, a negative error code otherwise.
1809 static int mtd_ooblayout_set_bytes(struct mtd_info *mtd, const u8 *buf,
1810 u8 *oobbuf, int start, int nbytes,
1811 int (*iter)(struct mtd_info *,
1813 struct mtd_oob_region *oobregion))
1815 struct mtd_oob_region oobregion;
1818 ret = mtd_ooblayout_find_region(mtd, start, §ion,
1824 cnt = min_t(int, nbytes, oobregion.length);
1825 memcpy(oobbuf + oobregion.offset, buf, cnt);
1832 ret = iter(mtd, ++section, &oobregion);
1839 * mtd_ooblayout_count_bytes - count the number of bytes in a OOB category
1840 * @mtd: mtd info structure
1841 * @iter: category iterator
1843 * Count the number of bytes in a given category.
1845 * Returns a positive value on success, a negative error code otherwise.
1847 static int mtd_ooblayout_count_bytes(struct mtd_info *mtd,
1848 int (*iter)(struct mtd_info *,
1850 struct mtd_oob_region *oobregion))
1852 struct mtd_oob_region oobregion;
1853 int section = 0, ret, nbytes = 0;
1856 ret = iter(mtd, section++, &oobregion);
1863 nbytes += oobregion.length;
1870 * mtd_ooblayout_get_eccbytes - extract ECC bytes from the oob buffer
1871 * @mtd: mtd info structure
1872 * @eccbuf: destination buffer to store ECC bytes
1873 * @oobbuf: OOB buffer
1874 * @start: first ECC byte to retrieve
1875 * @nbytes: number of ECC bytes to retrieve
1877 * Works like mtd_ooblayout_get_bytes(), except it acts on ECC bytes.
1879 * Returns zero on success, a negative error code otherwise.
1881 int mtd_ooblayout_get_eccbytes(struct mtd_info *mtd, u8 *eccbuf,
1882 const u8 *oobbuf, int start, int nbytes)
1884 return mtd_ooblayout_get_bytes(mtd, eccbuf, oobbuf, start, nbytes,
1887 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_eccbytes);
1890 * mtd_ooblayout_set_eccbytes - set ECC bytes into the oob buffer
1891 * @mtd: mtd info structure
1892 * @eccbuf: source buffer to get ECC bytes from
1893 * @oobbuf: OOB buffer
1894 * @start: first ECC byte to set
1895 * @nbytes: number of ECC bytes to set
1897 * Works like mtd_ooblayout_set_bytes(), except it acts on ECC bytes.
1899 * Returns zero on success, a negative error code otherwise.
1901 int mtd_ooblayout_set_eccbytes(struct mtd_info *mtd, const u8 *eccbuf,
1902 u8 *oobbuf, int start, int nbytes)
1904 return mtd_ooblayout_set_bytes(mtd, eccbuf, oobbuf, start, nbytes,
1907 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_eccbytes);
1910 * mtd_ooblayout_get_databytes - extract data bytes from the oob buffer
1911 * @mtd: mtd info structure
1912 * @databuf: destination buffer to store ECC bytes
1913 * @oobbuf: OOB buffer
1914 * @start: first ECC byte to retrieve
1915 * @nbytes: number of ECC bytes to retrieve
1917 * Works like mtd_ooblayout_get_bytes(), except it acts on free bytes.
1919 * Returns zero on success, a negative error code otherwise.
1921 int mtd_ooblayout_get_databytes(struct mtd_info *mtd, u8 *databuf,
1922 const u8 *oobbuf, int start, int nbytes)
1924 return mtd_ooblayout_get_bytes(mtd, databuf, oobbuf, start, nbytes,
1925 mtd_ooblayout_free);
1927 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_databytes);
1930 * mtd_ooblayout_set_databytes - set data bytes into the oob buffer
1931 * @mtd: mtd info structure
1932 * @databuf: source buffer to get data bytes from
1933 * @oobbuf: OOB buffer
1934 * @start: first ECC byte to set
1935 * @nbytes: number of ECC bytes to set
1937 * Works like mtd_ooblayout_set_bytes(), except it acts on free bytes.
1939 * Returns zero on success, a negative error code otherwise.
1941 int mtd_ooblayout_set_databytes(struct mtd_info *mtd, const u8 *databuf,
1942 u8 *oobbuf, int start, int nbytes)
1944 return mtd_ooblayout_set_bytes(mtd, databuf, oobbuf, start, nbytes,
1945 mtd_ooblayout_free);
1947 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_databytes);
1950 * mtd_ooblayout_count_freebytes - count the number of free bytes in OOB
1951 * @mtd: mtd info structure
1953 * Works like mtd_ooblayout_count_bytes(), except it count free bytes.
1955 * Returns zero on success, a negative error code otherwise.
1957 int mtd_ooblayout_count_freebytes(struct mtd_info *mtd)
1959 return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_free);
1961 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_freebytes);
1964 * mtd_ooblayout_count_eccbytes - count the number of ECC bytes in OOB
1965 * @mtd: mtd info structure
1967 * Works like mtd_ooblayout_count_bytes(), except it count ECC bytes.
1969 * Returns zero on success, a negative error code otherwise.
1971 int mtd_ooblayout_count_eccbytes(struct mtd_info *mtd)
1973 return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_ecc);
1975 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_eccbytes);
1978 * Method to access the protection register area, present in some flash
1979 * devices. The user data is one time programmable but the factory data is read
1982 int mtd_get_fact_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
1983 struct otp_info *buf)
1985 struct mtd_info *master = mtd_get_master(mtd);
1987 if (!master->_get_fact_prot_info)
1991 return master->_get_fact_prot_info(master, len, retlen, buf);
1993 EXPORT_SYMBOL_GPL(mtd_get_fact_prot_info);
1995 int mtd_read_fact_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
1996 size_t *retlen, u_char *buf)
1998 struct mtd_info *master = mtd_get_master(mtd);
2001 if (!master->_read_fact_prot_reg)
2005 return master->_read_fact_prot_reg(master, from, len, retlen, buf);
2007 EXPORT_SYMBOL_GPL(mtd_read_fact_prot_reg);
2009 int mtd_get_user_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
2010 struct otp_info *buf)
2012 struct mtd_info *master = mtd_get_master(mtd);
2014 if (!master->_get_user_prot_info)
2018 return master->_get_user_prot_info(master, len, retlen, buf);
2020 EXPORT_SYMBOL_GPL(mtd_get_user_prot_info);
2022 int mtd_read_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
2023 size_t *retlen, u_char *buf)
2025 struct mtd_info *master = mtd_get_master(mtd);
2028 if (!master->_read_user_prot_reg)
2032 return master->_read_user_prot_reg(master, from, len, retlen, buf);
2034 EXPORT_SYMBOL_GPL(mtd_read_user_prot_reg);
2036 int mtd_write_user_prot_reg(struct mtd_info *mtd, loff_t to, size_t len,
2037 size_t *retlen, const u_char *buf)
2039 struct mtd_info *master = mtd_get_master(mtd);
2043 if (!master->_write_user_prot_reg)
2047 ret = master->_write_user_prot_reg(master, to, len, retlen, buf);
2052 * If no data could be written at all, we are out of memory and
2053 * must return -ENOSPC.
2055 return (*retlen) ? 0 : -ENOSPC;
2057 EXPORT_SYMBOL_GPL(mtd_write_user_prot_reg);
2059 int mtd_lock_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len)
2061 struct mtd_info *master = mtd_get_master(mtd);
2063 if (!master->_lock_user_prot_reg)
2067 return master->_lock_user_prot_reg(master, from, len);
2069 EXPORT_SYMBOL_GPL(mtd_lock_user_prot_reg);
2071 int mtd_erase_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len)
2073 struct mtd_info *master = mtd_get_master(mtd);
2075 if (!master->_erase_user_prot_reg)
2079 return master->_erase_user_prot_reg(master, from, len);
2081 EXPORT_SYMBOL_GPL(mtd_erase_user_prot_reg);
2083 /* Chip-supported device locking */
2084 int mtd_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2086 struct mtd_info *master = mtd_get_master(mtd);
2090 if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
2095 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
2096 ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2097 len = (u64)mtd_div_by_eb(len, mtd) * master->erasesize;
2100 return master->_lock(master, mtd_get_master_ofs(mtd, ofs), len);
2102 EXPORT_SYMBOL_GPL(mtd_lock);
2104 int mtd_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2106 struct mtd_info *master = mtd_get_master(mtd);
2108 if (!master->_unlock)
2110 if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
2115 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
2116 ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2117 len = (u64)mtd_div_by_eb(len, mtd) * master->erasesize;
2120 return master->_unlock(master, mtd_get_master_ofs(mtd, ofs), len);
2122 EXPORT_SYMBOL_GPL(mtd_unlock);
2124 int mtd_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2126 struct mtd_info *master = mtd_get_master(mtd);
2128 if (!master->_is_locked)
2130 if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
2135 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
2136 ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2137 len = (u64)mtd_div_by_eb(len, mtd) * master->erasesize;
2140 return master->_is_locked(master, mtd_get_master_ofs(mtd, ofs), len);
2142 EXPORT_SYMBOL_GPL(mtd_is_locked);
2144 int mtd_block_isreserved(struct mtd_info *mtd, loff_t ofs)
2146 struct mtd_info *master = mtd_get_master(mtd);
2148 if (ofs < 0 || ofs >= mtd->size)
2150 if (!master->_block_isreserved)
2153 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
2154 ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2156 return master->_block_isreserved(master, mtd_get_master_ofs(mtd, ofs));
2158 EXPORT_SYMBOL_GPL(mtd_block_isreserved);
2160 int mtd_block_isbad(struct mtd_info *mtd, loff_t ofs)
2162 struct mtd_info *master = mtd_get_master(mtd);
2164 if (ofs < 0 || ofs >= mtd->size)
2166 if (!master->_block_isbad)
2169 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
2170 ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2172 return master->_block_isbad(master, mtd_get_master_ofs(mtd, ofs));
2174 EXPORT_SYMBOL_GPL(mtd_block_isbad);
2176 int mtd_block_markbad(struct mtd_info *mtd, loff_t ofs)
2178 struct mtd_info *master = mtd_get_master(mtd);
2181 if (!master->_block_markbad)
2183 if (ofs < 0 || ofs >= mtd->size)
2185 if (!(mtd->flags & MTD_WRITEABLE))
2188 if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
2189 ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2191 ret = master->_block_markbad(master, mtd_get_master_ofs(mtd, ofs));
2195 while (mtd->parent) {
2196 mtd->ecc_stats.badblocks++;
2202 EXPORT_SYMBOL_GPL(mtd_block_markbad);
2205 * default_mtd_writev - the default writev method
2206 * @mtd: mtd device description object pointer
2207 * @vecs: the vectors to write
2208 * @count: count of vectors in @vecs
2209 * @to: the MTD device offset to write to
2210 * @retlen: on exit contains the count of bytes written to the MTD device.
2212 * This function returns zero in case of success and a negative error code in
2215 static int default_mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
2216 unsigned long count, loff_t to, size_t *retlen)
2219 size_t totlen = 0, thislen;
2222 for (i = 0; i < count; i++) {
2223 if (!vecs[i].iov_len)
2225 ret = mtd_write(mtd, to, vecs[i].iov_len, &thislen,
2228 if (ret || thislen != vecs[i].iov_len)
2230 to += vecs[i].iov_len;
2237 * mtd_writev - the vector-based MTD write method
2238 * @mtd: mtd device description object pointer
2239 * @vecs: the vectors to write
2240 * @count: count of vectors in @vecs
2241 * @to: the MTD device offset to write to
2242 * @retlen: on exit contains the count of bytes written to the MTD device.
2244 * This function returns zero in case of success and a negative error code in
2247 int mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
2248 unsigned long count, loff_t to, size_t *retlen)
2250 struct mtd_info *master = mtd_get_master(mtd);
2253 if (!(mtd->flags & MTD_WRITEABLE))
2256 if (!master->_writev)
2257 return default_mtd_writev(mtd, vecs, count, to, retlen);
2259 return master->_writev(master, vecs, count,
2260 mtd_get_master_ofs(mtd, to), retlen);
2262 EXPORT_SYMBOL_GPL(mtd_writev);
2265 * mtd_kmalloc_up_to - allocate a contiguous buffer up to the specified size
2266 * @mtd: mtd device description object pointer
2267 * @size: a pointer to the ideal or maximum size of the allocation, points
2268 * to the actual allocation size on success.
2270 * This routine attempts to allocate a contiguous kernel buffer up to
2271 * the specified size, backing off the size of the request exponentially
2272 * until the request succeeds or until the allocation size falls below
2273 * the system page size. This attempts to make sure it does not adversely
2274 * impact system performance, so when allocating more than one page, we
2275 * ask the memory allocator to avoid re-trying, swapping, writing back
2276 * or performing I/O.
2278 * Note, this function also makes sure that the allocated buffer is aligned to
2279 * the MTD device's min. I/O unit, i.e. the "mtd->writesize" value.
2281 * This is called, for example by mtd_{read,write} and jffs2_scan_medium,
2282 * to handle smaller (i.e. degraded) buffer allocations under low- or
2283 * fragmented-memory situations where such reduced allocations, from a
2284 * requested ideal, are allowed.
2286 * Returns a pointer to the allocated buffer on success; otherwise, NULL.
2288 void *mtd_kmalloc_up_to(const struct mtd_info *mtd, size_t *size)
2290 gfp_t flags = __GFP_NOWARN | __GFP_DIRECT_RECLAIM | __GFP_NORETRY;
2291 size_t min_alloc = max_t(size_t, mtd->writesize, PAGE_SIZE);
2294 *size = min_t(size_t, *size, KMALLOC_MAX_SIZE);
2296 while (*size > min_alloc) {
2297 kbuf = kmalloc(*size, flags);
2302 *size = ALIGN(*size, mtd->writesize);
2306 * For the last resort allocation allow 'kmalloc()' to do all sorts of
2307 * things (write-back, dropping caches, etc) by using GFP_KERNEL.
2309 return kmalloc(*size, GFP_KERNEL);
2311 EXPORT_SYMBOL_GPL(mtd_kmalloc_up_to);
2313 #ifdef CONFIG_PROC_FS
2315 /*====================================================================*/
2316 /* Support for /proc/mtd */
2318 static int mtd_proc_show(struct seq_file *m, void *v)
2320 struct mtd_info *mtd;
2322 seq_puts(m, "dev: size erasesize name\n");
2323 mutex_lock(&mtd_table_mutex);
2324 mtd_for_each_device(mtd) {
2325 seq_printf(m, "mtd%d: %8.8llx %8.8x \"%s\"\n",
2326 mtd->index, (unsigned long long)mtd->size,
2327 mtd->erasesize, mtd->name);
2329 mutex_unlock(&mtd_table_mutex);
2332 #endif /* CONFIG_PROC_FS */
2334 /*====================================================================*/
2337 static struct backing_dev_info * __init mtd_bdi_init(const char *name)
2339 struct backing_dev_info *bdi;
2342 bdi = bdi_alloc(NUMA_NO_NODE);
2344 return ERR_PTR(-ENOMEM);
2349 * We put '-0' suffix to the name to get the same name format as we
2350 * used to get. Since this is called only once, we get a unique name.
2352 ret = bdi_register(bdi, "%.28s-0", name);
2356 return ret ? ERR_PTR(ret) : bdi;
2359 static struct proc_dir_entry *proc_mtd;
2361 static int __init init_mtd(void)
2365 ret = class_register(&mtd_class);
2369 mtd_bdi = mtd_bdi_init("mtd");
2370 if (IS_ERR(mtd_bdi)) {
2371 ret = PTR_ERR(mtd_bdi);
2375 proc_mtd = proc_create_single("mtd", 0, NULL, mtd_proc_show);
2377 ret = init_mtdchar();
2381 dfs_dir_mtd = debugfs_create_dir("mtd", NULL);
2382 debugfs_create_bool("expert_analysis_mode", 0600, dfs_dir_mtd,
2383 &mtd_expert_analysis_mode);
2389 remove_proc_entry("mtd", NULL);
2392 class_unregister(&mtd_class);
2394 pr_err("Error registering mtd class or bdi: %d\n", ret);
2398 static void __exit cleanup_mtd(void)
2400 debugfs_remove_recursive(dfs_dir_mtd);
2403 remove_proc_entry("mtd", NULL);
2404 class_unregister(&mtd_class);
2405 bdi_unregister(mtd_bdi);
2407 idr_destroy(&mtd_idr);
2410 module_init(init_mtd);
2411 module_exit(cleanup_mtd);
2413 MODULE_LICENSE("GPL");
2414 MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
2415 MODULE_DESCRIPTION("Core MTD registration and access routines");