xref: /linux/drivers/mtd/mtdcore.c (revision f6d1975cd2668d239bb97ef4833ad1ddc5ffed6d)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Core registration and callback routines for MTD
4  * drivers and users.
5  *
6  * Copyright © 1999-2010 David Woodhouse <dwmw2@infradead.org>
7  * Copyright © 2006      Red Hat UK Limited
8  */
9 
10 #include <linux/module.h>
11 #include <linux/kernel.h>
12 #include <linux/ptrace.h>
13 #include <linux/seq_file.h>
14 #include <linux/string.h>
15 #include <linux/timer.h>
16 #include <linux/major.h>
17 #include <linux/fs.h>
18 #include <linux/err.h>
19 #include <linux/ioctl.h>
20 #include <linux/init.h>
21 #include <linux/of.h>
22 #include <linux/proc_fs.h>
23 #include <linux/idr.h>
24 #include <linux/backing-dev.h>
25 #include <linux/gfp.h>
26 #include <linux/slab.h>
27 #include <linux/reboot.h>
28 #include <linux/leds.h>
29 #include <linux/debugfs.h>
30 #include <linux/nvmem-provider.h>
31 #include <linux/root_dev.h>
32 
33 #include <linux/mtd/mtd.h>
34 #include <linux/mtd/partitions.h>
35 
36 #include "mtdcore.h"
37 
38 struct backing_dev_info *mtd_bdi;
39 
40 #ifdef CONFIG_PM_SLEEP
41 
42 static int mtd_cls_suspend(struct device *dev)
43 {
44 	struct mtd_info *mtd = dev_get_drvdata(dev);
45 
46 	return mtd ? mtd_suspend(mtd) : 0;
47 }
48 
49 static int mtd_cls_resume(struct device *dev)
50 {
51 	struct mtd_info *mtd = dev_get_drvdata(dev);
52 
53 	if (mtd)
54 		mtd_resume(mtd);
55 	return 0;
56 }
57 
58 static SIMPLE_DEV_PM_OPS(mtd_cls_pm_ops, mtd_cls_suspend, mtd_cls_resume);
59 #define MTD_CLS_PM_OPS (&mtd_cls_pm_ops)
60 #else
61 #define MTD_CLS_PM_OPS NULL
62 #endif
63 
64 static struct class mtd_class = {
65 	.name = "mtd",
66 	.pm = MTD_CLS_PM_OPS,
67 };
68 
69 static DEFINE_IDR(mtd_idr);
70 
71 /* These are exported solely for the purpose of mtd_blkdevs.c. You
72    should not use them for _anything_ else */
73 DEFINE_MUTEX(mtd_table_mutex);
74 EXPORT_SYMBOL_GPL(mtd_table_mutex);
75 
76 struct mtd_info *__mtd_next_device(int i)
77 {
78 	return idr_get_next(&mtd_idr, &i);
79 }
80 EXPORT_SYMBOL_GPL(__mtd_next_device);
81 
82 static LIST_HEAD(mtd_notifiers);
83 
84 
85 #define MTD_DEVT(index) MKDEV(MTD_CHAR_MAJOR, (index)*2)
86 
87 /* REVISIT once MTD uses the driver model better, whoever allocates
88  * the mtd_info will probably want to use the release() hook...
89  */
90 static void mtd_release(struct device *dev)
91 {
92 	struct mtd_info *mtd = dev_get_drvdata(dev);
93 	dev_t index = MTD_DEVT(mtd->index);
94 
95 	/* remove /dev/mtdXro node */
96 	device_destroy(&mtd_class, index + 1);
97 }
98 
99 #define MTD_DEVICE_ATTR_RO(name) \
100 static DEVICE_ATTR(name, 0444, mtd_##name##_show, NULL)
101 
102 #define MTD_DEVICE_ATTR_RW(name) \
103 static DEVICE_ATTR(name, 0644, mtd_##name##_show, mtd_##name##_store)
104 
105 static ssize_t mtd_type_show(struct device *dev,
106 		struct device_attribute *attr, char *buf)
107 {
108 	struct mtd_info *mtd = dev_get_drvdata(dev);
109 	char *type;
110 
111 	switch (mtd->type) {
112 	case MTD_ABSENT:
113 		type = "absent";
114 		break;
115 	case MTD_RAM:
116 		type = "ram";
117 		break;
118 	case MTD_ROM:
119 		type = "rom";
120 		break;
121 	case MTD_NORFLASH:
122 		type = "nor";
123 		break;
124 	case MTD_NANDFLASH:
125 		type = "nand";
126 		break;
127 	case MTD_DATAFLASH:
128 		type = "dataflash";
129 		break;
130 	case MTD_UBIVOLUME:
131 		type = "ubi";
132 		break;
133 	case MTD_MLCNANDFLASH:
134 		type = "mlc-nand";
135 		break;
136 	default:
137 		type = "unknown";
138 	}
139 
140 	return sysfs_emit(buf, "%s\n", type);
141 }
142 MTD_DEVICE_ATTR_RO(type);
143 
144 static ssize_t mtd_flags_show(struct device *dev,
145 		struct device_attribute *attr, char *buf)
146 {
147 	struct mtd_info *mtd = dev_get_drvdata(dev);
148 
149 	return sysfs_emit(buf, "0x%lx\n", (unsigned long)mtd->flags);
150 }
151 MTD_DEVICE_ATTR_RO(flags);
152 
153 static ssize_t mtd_size_show(struct device *dev,
154 		struct device_attribute *attr, char *buf)
155 {
156 	struct mtd_info *mtd = dev_get_drvdata(dev);
157 
158 	return sysfs_emit(buf, "%llu\n", (unsigned long long)mtd->size);
159 }
160 MTD_DEVICE_ATTR_RO(size);
161 
162 static ssize_t mtd_erasesize_show(struct device *dev,
163 		struct device_attribute *attr, char *buf)
164 {
165 	struct mtd_info *mtd = dev_get_drvdata(dev);
166 
167 	return sysfs_emit(buf, "%lu\n", (unsigned long)mtd->erasesize);
168 }
169 MTD_DEVICE_ATTR_RO(erasesize);
170 
171 static ssize_t mtd_writesize_show(struct device *dev,
172 		struct device_attribute *attr, char *buf)
173 {
174 	struct mtd_info *mtd = dev_get_drvdata(dev);
175 
176 	return sysfs_emit(buf, "%lu\n", (unsigned long)mtd->writesize);
177 }
178 MTD_DEVICE_ATTR_RO(writesize);
179 
180 static ssize_t mtd_subpagesize_show(struct device *dev,
181 		struct device_attribute *attr, char *buf)
182 {
183 	struct mtd_info *mtd = dev_get_drvdata(dev);
184 	unsigned int subpagesize = mtd->writesize >> mtd->subpage_sft;
185 
186 	return sysfs_emit(buf, "%u\n", subpagesize);
187 }
188 MTD_DEVICE_ATTR_RO(subpagesize);
189 
190 static ssize_t mtd_oobsize_show(struct device *dev,
191 		struct device_attribute *attr, char *buf)
192 {
193 	struct mtd_info *mtd = dev_get_drvdata(dev);
194 
195 	return sysfs_emit(buf, "%lu\n", (unsigned long)mtd->oobsize);
196 }
197 MTD_DEVICE_ATTR_RO(oobsize);
198 
199 static ssize_t mtd_oobavail_show(struct device *dev,
200 				 struct device_attribute *attr, char *buf)
201 {
202 	struct mtd_info *mtd = dev_get_drvdata(dev);
203 
204 	return sysfs_emit(buf, "%u\n", mtd->oobavail);
205 }
206 MTD_DEVICE_ATTR_RO(oobavail);
207 
208 static ssize_t mtd_numeraseregions_show(struct device *dev,
209 		struct device_attribute *attr, char *buf)
210 {
211 	struct mtd_info *mtd = dev_get_drvdata(dev);
212 
213 	return sysfs_emit(buf, "%u\n", mtd->numeraseregions);
214 }
215 MTD_DEVICE_ATTR_RO(numeraseregions);
216 
217 static ssize_t mtd_name_show(struct device *dev,
218 		struct device_attribute *attr, char *buf)
219 {
220 	struct mtd_info *mtd = dev_get_drvdata(dev);
221 
222 	return sysfs_emit(buf, "%s\n", mtd->name);
223 }
224 MTD_DEVICE_ATTR_RO(name);
225 
226 static ssize_t mtd_ecc_strength_show(struct device *dev,
227 				     struct device_attribute *attr, char *buf)
228 {
229 	struct mtd_info *mtd = dev_get_drvdata(dev);
230 
231 	return sysfs_emit(buf, "%u\n", mtd->ecc_strength);
232 }
233 MTD_DEVICE_ATTR_RO(ecc_strength);
234 
235 static ssize_t mtd_bitflip_threshold_show(struct device *dev,
236 					  struct device_attribute *attr,
237 					  char *buf)
238 {
239 	struct mtd_info *mtd = dev_get_drvdata(dev);
240 
241 	return sysfs_emit(buf, "%u\n", mtd->bitflip_threshold);
242 }
243 
244 static ssize_t mtd_bitflip_threshold_store(struct device *dev,
245 					   struct device_attribute *attr,
246 					   const char *buf, size_t count)
247 {
248 	struct mtd_info *mtd = dev_get_drvdata(dev);
249 	unsigned int bitflip_threshold;
250 	int retval;
251 
252 	retval = kstrtouint(buf, 0, &bitflip_threshold);
253 	if (retval)
254 		return retval;
255 
256 	mtd->bitflip_threshold = bitflip_threshold;
257 	return count;
258 }
259 MTD_DEVICE_ATTR_RW(bitflip_threshold);
260 
261 static ssize_t mtd_ecc_step_size_show(struct device *dev,
262 		struct device_attribute *attr, char *buf)
263 {
264 	struct mtd_info *mtd = dev_get_drvdata(dev);
265 
266 	return sysfs_emit(buf, "%u\n", mtd->ecc_step_size);
267 
268 }
269 MTD_DEVICE_ATTR_RO(ecc_step_size);
270 
271 static ssize_t mtd_corrected_bits_show(struct device *dev,
272 		struct device_attribute *attr, char *buf)
273 {
274 	struct mtd_info *mtd = dev_get_drvdata(dev);
275 	struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
276 
277 	return sysfs_emit(buf, "%u\n", ecc_stats->corrected);
278 }
279 MTD_DEVICE_ATTR_RO(corrected_bits);	/* ecc stats corrected */
280 
281 static ssize_t mtd_ecc_failures_show(struct device *dev,
282 		struct device_attribute *attr, char *buf)
283 {
284 	struct mtd_info *mtd = dev_get_drvdata(dev);
285 	struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
286 
287 	return sysfs_emit(buf, "%u\n", ecc_stats->failed);
288 }
289 MTD_DEVICE_ATTR_RO(ecc_failures);	/* ecc stats errors */
290 
291 static ssize_t mtd_bad_blocks_show(struct device *dev,
292 		struct device_attribute *attr, char *buf)
293 {
294 	struct mtd_info *mtd = dev_get_drvdata(dev);
295 	struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
296 
297 	return sysfs_emit(buf, "%u\n", ecc_stats->badblocks);
298 }
299 MTD_DEVICE_ATTR_RO(bad_blocks);
300 
301 static ssize_t mtd_bbt_blocks_show(struct device *dev,
302 		struct device_attribute *attr, char *buf)
303 {
304 	struct mtd_info *mtd = dev_get_drvdata(dev);
305 	struct mtd_ecc_stats *ecc_stats = &mtd->ecc_stats;
306 
307 	return sysfs_emit(buf, "%u\n", ecc_stats->bbtblocks);
308 }
309 MTD_DEVICE_ATTR_RO(bbt_blocks);
310 
311 static struct attribute *mtd_attrs[] = {
312 	&dev_attr_type.attr,
313 	&dev_attr_flags.attr,
314 	&dev_attr_size.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,
321 	&dev_attr_name.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,
329 	NULL,
330 };
331 ATTRIBUTE_GROUPS(mtd);
332 
333 static const struct device_type mtd_devtype = {
334 	.name		= "mtd",
335 	.groups		= mtd_groups,
336 	.release	= mtd_release,
337 };
338 
339 static bool mtd_expert_analysis_mode;
340 
341 #ifdef CONFIG_DEBUG_FS
342 bool mtd_check_expert_analysis_mode(void)
343 {
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";
348 
349 	return WARN_ONCE(mtd_expert_analysis_mode, mtd_expert_analysis_warning);
350 }
351 EXPORT_SYMBOL_GPL(mtd_check_expert_analysis_mode);
352 #endif
353 
354 static struct dentry *dfs_dir_mtd;
355 
356 static void mtd_debugfs_populate(struct mtd_info *mtd)
357 {
358 	struct device *dev = &mtd->dev;
359 
360 	if (IS_ERR_OR_NULL(dfs_dir_mtd))
361 		return;
362 
363 	mtd->dbg.dfs_dir = debugfs_create_dir(dev_name(dev), dfs_dir_mtd);
364 }
365 
366 #ifndef CONFIG_MMU
367 unsigned mtd_mmap_capabilities(struct mtd_info *mtd)
368 {
369 	switch (mtd->type) {
370 	case MTD_RAM:
371 		return NOMMU_MAP_COPY | NOMMU_MAP_DIRECT | NOMMU_MAP_EXEC |
372 			NOMMU_MAP_READ | NOMMU_MAP_WRITE;
373 	case MTD_ROM:
374 		return NOMMU_MAP_COPY | NOMMU_MAP_DIRECT | NOMMU_MAP_EXEC |
375 			NOMMU_MAP_READ;
376 	default:
377 		return NOMMU_MAP_COPY;
378 	}
379 }
380 EXPORT_SYMBOL_GPL(mtd_mmap_capabilities);
381 #endif
382 
383 static int mtd_reboot_notifier(struct notifier_block *n, unsigned long state,
384 			       void *cmd)
385 {
386 	struct mtd_info *mtd;
387 
388 	mtd = container_of(n, struct mtd_info, reboot_notifier);
389 	mtd->_reboot(mtd);
390 
391 	return NOTIFY_DONE;
392 }
393 
394 /**
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
399  *
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
403  * paired with.
404  * The notion of page is replaced by the term wunit (write-unit) to stay
405  * consistent with the ->writesize field.
406  *
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
409  * to @wunit.
410  *
411  * From the pairing info the MTD user can find all the wunits paired with
412  * @wunit using the following loop:
413  *
414  * for (i = 0; i < mtd_pairing_groups(mtd); i++) {
415  *	info.pair = i;
416  *	mtd_pairing_info_to_wunit(mtd, &info);
417  *	...
418  * }
419  */
420 int mtd_wunit_to_pairing_info(struct mtd_info *mtd, int wunit,
421 			      struct mtd_pairing_info *info)
422 {
423 	struct mtd_info *master = mtd_get_master(mtd);
424 	int npairs = mtd_wunit_per_eb(master) / mtd_pairing_groups(master);
425 
426 	if (wunit < 0 || wunit >= npairs)
427 		return -EINVAL;
428 
429 	if (master->pairing && master->pairing->get_info)
430 		return master->pairing->get_info(master, wunit, info);
431 
432 	info->group = 0;
433 	info->pair = wunit;
434 
435 	return 0;
436 }
437 EXPORT_SYMBOL_GPL(mtd_wunit_to_pairing_info);
438 
439 /**
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
443  *
444  * Returns a positive number representing the wunit associated to the info
445  * struct, or a negative error code.
446  *
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()
449  * doc).
450  *
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:
454  *
455  * info.group = 0;
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));
461  * }
462  */
463 int mtd_pairing_info_to_wunit(struct mtd_info *mtd,
464 			      const struct mtd_pairing_info *info)
465 {
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;
469 
470 	if (!info || info->pair < 0 || info->pair >= npairs ||
471 	    info->group < 0 || info->group >= ngroups)
472 		return -EINVAL;
473 
474 	if (master->pairing && master->pairing->get_wunit)
475 		return mtd->pairing->get_wunit(master, info);
476 
477 	return info->pair;
478 }
479 EXPORT_SYMBOL_GPL(mtd_pairing_info_to_wunit);
480 
481 /**
482  * mtd_pairing_groups - get the number of pairing groups
483  * @mtd: pointer to new MTD device info structure
484  *
485  * Returns the number of pairing groups.
486  *
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.
490  */
491 int mtd_pairing_groups(struct mtd_info *mtd)
492 {
493 	struct mtd_info *master = mtd_get_master(mtd);
494 
495 	if (!master->pairing || !master->pairing->ngroups)
496 		return 1;
497 
498 	return master->pairing->ngroups;
499 }
500 EXPORT_SYMBOL_GPL(mtd_pairing_groups);
501 
502 static int mtd_nvmem_reg_read(void *priv, unsigned int offset,
503 			      void *val, size_t bytes)
504 {
505 	struct mtd_info *mtd = priv;
506 	size_t retlen;
507 	int err;
508 
509 	err = mtd_read(mtd, offset, bytes, &retlen, val);
510 	if (err && err != -EUCLEAN)
511 		return err;
512 
513 	return retlen == bytes ? 0 : -EIO;
514 }
515 
516 static int mtd_nvmem_add(struct mtd_info *mtd)
517 {
518 	struct device_node *node = mtd_get_of_node(mtd);
519 	struct nvmem_config config = {};
520 
521 	config.id = -1;
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;
528 	config.stride = 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");
533 	config.priv = mtd;
534 
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) {
539 			mtd->nvmem = NULL;
540 		} else {
541 			dev_err(&mtd->dev, "Failed to register NVMEM device\n");
542 			return PTR_ERR(mtd->nvmem);
543 		}
544 	}
545 
546 	return 0;
547 }
548 
549 static void mtd_check_of_node(struct mtd_info *mtd)
550 {
551 	struct device_node *partitions, *parent_dn, *mtd_dn = NULL;
552 	const char *pname, *prefix = "partition-";
553 	int plen, mtd_name_len, offset, prefix_len;
554 
555 	/* Check if MTD already has a device node */
556 	if (mtd_get_of_node(mtd))
557 		return;
558 
559 	if (!mtd_is_partition(mtd))
560 		return;
561 
562 	parent_dn = of_node_get(mtd_get_of_node(mtd->parent));
563 	if (!parent_dn)
564 		return;
565 
566 	if (mtd_is_partition(mtd->parent))
567 		partitions = of_node_get(parent_dn);
568 	else
569 		partitions = of_get_child_by_name(parent_dn, "partitions");
570 	if (!partitions)
571 		goto exit_parent;
572 
573 	prefix_len = strlen(prefix);
574 	mtd_name_len = strlen(mtd->name);
575 
576 	/* Search if a partition is defined with the same name */
577 	for_each_child_of_node(partitions, mtd_dn) {
578 		/* Skip partition with no/wrong prefix */
579 		if (!of_node_name_prefix(mtd_dn, prefix))
580 			continue;
581 
582 		/* Label have priority. Check that first */
583 		if (!of_property_read_string(mtd_dn, "label", &pname)) {
584 			offset = 0;
585 		} else {
586 			pname = mtd_dn->name;
587 			offset = prefix_len;
588 		}
589 
590 		plen = strlen(pname) - offset;
591 		if (plen == mtd_name_len &&
592 		    !strncmp(mtd->name, pname + offset, plen)) {
593 			mtd_set_of_node(mtd, mtd_dn);
594 			break;
595 		}
596 	}
597 
598 	of_node_put(partitions);
599 exit_parent:
600 	of_node_put(parent_dn);
601 }
602 
603 /**
604  *	add_mtd_device - register an MTD device
605  *	@mtd: pointer to new MTD device info structure
606  *
607  *	Add a device to the list of MTD devices present in the system, and
608  *	notify each currently active MTD 'user' of its arrival. Returns
609  *	zero on success or non-zero on failure.
610  */
611 
612 int add_mtd_device(struct mtd_info *mtd)
613 {
614 	struct device_node *np = mtd_get_of_node(mtd);
615 	struct mtd_info *master = mtd_get_master(mtd);
616 	struct mtd_notifier *not;
617 	int i, error, ofidx;
618 
619 	/*
620 	 * May occur, for instance, on buggy drivers which call
621 	 * mtd_device_parse_register() multiple times on the same master MTD,
622 	 * especially with CONFIG_MTD_PARTITIONED_MASTER=y.
623 	 */
624 	if (WARN_ONCE(mtd->dev.type, "MTD already registered\n"))
625 		return -EEXIST;
626 
627 	BUG_ON(mtd->writesize == 0);
628 
629 	/*
630 	 * MTD drivers should implement ->_{write,read}() or
631 	 * ->_{write,read}_oob(), but not both.
632 	 */
633 	if (WARN_ON((mtd->_write && mtd->_write_oob) ||
634 		    (mtd->_read && mtd->_read_oob)))
635 		return -EINVAL;
636 
637 	if (WARN_ON((!mtd->erasesize || !master->_erase) &&
638 		    !(mtd->flags & MTD_NO_ERASE)))
639 		return -EINVAL;
640 
641 	/*
642 	 * MTD_SLC_ON_MLC_EMULATION can only be set on partitions, when the
643 	 * master is an MLC NAND and has a proper pairing scheme defined.
644 	 * We also reject masters that implement ->_writev() for now, because
645 	 * NAND controller drivers don't implement this hook, and adding the
646 	 * SLC -> MLC address/length conversion to this path is useless if we
647 	 * don't have a user.
648 	 */
649 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION &&
650 	    (!mtd_is_partition(mtd) || master->type != MTD_MLCNANDFLASH ||
651 	     !master->pairing || master->_writev))
652 		return -EINVAL;
653 
654 	mutex_lock(&mtd_table_mutex);
655 
656 	ofidx = -1;
657 	if (np)
658 		ofidx = of_alias_get_id(np, "mtd");
659 	if (ofidx >= 0)
660 		i = idr_alloc(&mtd_idr, mtd, ofidx, ofidx + 1, GFP_KERNEL);
661 	else
662 		i = idr_alloc(&mtd_idr, mtd, 0, 0, GFP_KERNEL);
663 	if (i < 0) {
664 		error = i;
665 		goto fail_locked;
666 	}
667 
668 	mtd->index = i;
669 	mtd->usecount = 0;
670 
671 	/* default value if not set by driver */
672 	if (mtd->bitflip_threshold == 0)
673 		mtd->bitflip_threshold = mtd->ecc_strength;
674 
675 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
676 		int ngroups = mtd_pairing_groups(master);
677 
678 		mtd->erasesize /= ngroups;
679 		mtd->size = (u64)mtd_div_by_eb(mtd->size, master) *
680 			    mtd->erasesize;
681 	}
682 
683 	if (is_power_of_2(mtd->erasesize))
684 		mtd->erasesize_shift = ffs(mtd->erasesize) - 1;
685 	else
686 		mtd->erasesize_shift = 0;
687 
688 	if (is_power_of_2(mtd->writesize))
689 		mtd->writesize_shift = ffs(mtd->writesize) - 1;
690 	else
691 		mtd->writesize_shift = 0;
692 
693 	mtd->erasesize_mask = (1 << mtd->erasesize_shift) - 1;
694 	mtd->writesize_mask = (1 << mtd->writesize_shift) - 1;
695 
696 	/* Some chips always power up locked. Unlock them now */
697 	if ((mtd->flags & MTD_WRITEABLE) && (mtd->flags & MTD_POWERUP_LOCK)) {
698 		error = mtd_unlock(mtd, 0, mtd->size);
699 		if (error && error != -EOPNOTSUPP)
700 			printk(KERN_WARNING
701 			       "%s: unlock failed, writes may not work\n",
702 			       mtd->name);
703 		/* Ignore unlock failures? */
704 		error = 0;
705 	}
706 
707 	/* Caller should have set dev.parent to match the
708 	 * physical device, if appropriate.
709 	 */
710 	mtd->dev.type = &mtd_devtype;
711 	mtd->dev.class = &mtd_class;
712 	mtd->dev.devt = MTD_DEVT(i);
713 	dev_set_name(&mtd->dev, "mtd%d", i);
714 	dev_set_drvdata(&mtd->dev, mtd);
715 	mtd_check_of_node(mtd);
716 	of_node_get(mtd_get_of_node(mtd));
717 	error = device_register(&mtd->dev);
718 	if (error) {
719 		put_device(&mtd->dev);
720 		goto fail_added;
721 	}
722 
723 	/* Add the nvmem provider */
724 	error = mtd_nvmem_add(mtd);
725 	if (error)
726 		goto fail_nvmem_add;
727 
728 	mtd_debugfs_populate(mtd);
729 
730 	device_create(&mtd_class, mtd->dev.parent, MTD_DEVT(i) + 1, NULL,
731 		      "mtd%dro", i);
732 
733 	pr_debug("mtd: Giving out device %d to %s\n", i, mtd->name);
734 	/* No need to get a refcount on the module containing
735 	   the notifier, since we hold the mtd_table_mutex */
736 	list_for_each_entry(not, &mtd_notifiers, list)
737 		not->add(mtd);
738 
739 	mutex_unlock(&mtd_table_mutex);
740 
741 	if (of_find_property(mtd_get_of_node(mtd), "linux,rootfs", NULL)) {
742 		if (IS_BUILTIN(CONFIG_MTD)) {
743 			pr_info("mtd: setting mtd%d (%s) as root device\n", mtd->index, mtd->name);
744 			ROOT_DEV = MKDEV(MTD_BLOCK_MAJOR, mtd->index);
745 		} else {
746 			pr_warn("mtd: can't set mtd%d (%s) as root device - mtd must be builtin\n",
747 				mtd->index, mtd->name);
748 		}
749 	}
750 
751 	/* We _know_ we aren't being removed, because
752 	   our caller is still holding us here. So none
753 	   of this try_ nonsense, and no bitching about it
754 	   either. :) */
755 	__module_get(THIS_MODULE);
756 	return 0;
757 
758 fail_nvmem_add:
759 	device_unregister(&mtd->dev);
760 fail_added:
761 	of_node_put(mtd_get_of_node(mtd));
762 	idr_remove(&mtd_idr, i);
763 fail_locked:
764 	mutex_unlock(&mtd_table_mutex);
765 	return error;
766 }
767 
768 /**
769  *	del_mtd_device - unregister an MTD device
770  *	@mtd: pointer to MTD device info structure
771  *
772  *	Remove a device from the list of MTD devices present in the system,
773  *	and notify each currently active MTD 'user' of its departure.
774  *	Returns zero on success or 1 on failure, which currently will happen
775  *	if the requested device does not appear to be present in the list.
776  */
777 
778 int del_mtd_device(struct mtd_info *mtd)
779 {
780 	int ret;
781 	struct mtd_notifier *not;
782 	struct device_node *mtd_of_node;
783 
784 	mutex_lock(&mtd_table_mutex);
785 
786 	if (idr_find(&mtd_idr, mtd->index) != mtd) {
787 		ret = -ENODEV;
788 		goto out_error;
789 	}
790 
791 	/* No need to get a refcount on the module containing
792 		the notifier, since we hold the mtd_table_mutex */
793 	list_for_each_entry(not, &mtd_notifiers, list)
794 		not->remove(mtd);
795 
796 	if (mtd->usecount) {
797 		printk(KERN_NOTICE "Removing MTD device #%d (%s) with use count %d\n",
798 		       mtd->index, mtd->name, mtd->usecount);
799 		ret = -EBUSY;
800 	} else {
801 		mtd_of_node = mtd_get_of_node(mtd);
802 		debugfs_remove_recursive(mtd->dbg.dfs_dir);
803 
804 		/* Try to remove the NVMEM provider */
805 		nvmem_unregister(mtd->nvmem);
806 
807 		device_unregister(&mtd->dev);
808 
809 		/* Clear dev so mtd can be safely re-registered later if desired */
810 		memset(&mtd->dev, 0, sizeof(mtd->dev));
811 
812 		idr_remove(&mtd_idr, mtd->index);
813 		of_node_put(mtd_of_node);
814 
815 		module_put(THIS_MODULE);
816 		ret = 0;
817 	}
818 
819 out_error:
820 	mutex_unlock(&mtd_table_mutex);
821 	return ret;
822 }
823 
824 /*
825  * Set a few defaults based on the parent devices, if not provided by the
826  * driver
827  */
828 static void mtd_set_dev_defaults(struct mtd_info *mtd)
829 {
830 	if (mtd->dev.parent) {
831 		if (!mtd->owner && mtd->dev.parent->driver)
832 			mtd->owner = mtd->dev.parent->driver->owner;
833 		if (!mtd->name)
834 			mtd->name = dev_name(mtd->dev.parent);
835 	} else {
836 		pr_debug("mtd device won't show a device symlink in sysfs\n");
837 	}
838 
839 	INIT_LIST_HEAD(&mtd->partitions);
840 	mutex_init(&mtd->master.partitions_lock);
841 	mutex_init(&mtd->master.chrdev_lock);
842 }
843 
844 static ssize_t mtd_otp_size(struct mtd_info *mtd, bool is_user)
845 {
846 	struct otp_info *info;
847 	ssize_t size = 0;
848 	unsigned int i;
849 	size_t retlen;
850 	int ret;
851 
852 	info = kmalloc(PAGE_SIZE, GFP_KERNEL);
853 	if (!info)
854 		return -ENOMEM;
855 
856 	if (is_user)
857 		ret = mtd_get_user_prot_info(mtd, PAGE_SIZE, &retlen, info);
858 	else
859 		ret = mtd_get_fact_prot_info(mtd, PAGE_SIZE, &retlen, info);
860 	if (ret)
861 		goto err;
862 
863 	for (i = 0; i < retlen / sizeof(*info); i++)
864 		size += info[i].length;
865 
866 	kfree(info);
867 	return size;
868 
869 err:
870 	kfree(info);
871 
872 	/* ENODATA means there is no OTP region. */
873 	return ret == -ENODATA ? 0 : ret;
874 }
875 
876 static struct nvmem_device *mtd_otp_nvmem_register(struct mtd_info *mtd,
877 						   const char *compatible,
878 						   int size,
879 						   nvmem_reg_read_t reg_read)
880 {
881 	struct nvmem_device *nvmem = NULL;
882 	struct nvmem_config config = {};
883 	struct device_node *np;
884 
885 	/* DT binding is optional */
886 	np = of_get_compatible_child(mtd->dev.of_node, compatible);
887 
888 	/* OTP nvmem will be registered on the physical device */
889 	config.dev = mtd->dev.parent;
890 	config.name = kasprintf(GFP_KERNEL, "%s-%s", dev_name(&mtd->dev), compatible);
891 	config.id = NVMEM_DEVID_NONE;
892 	config.owner = THIS_MODULE;
893 	config.type = NVMEM_TYPE_OTP;
894 	config.root_only = true;
895 	config.ignore_wp = true;
896 	config.reg_read = reg_read;
897 	config.size = size;
898 	config.of_node = np;
899 	config.priv = mtd;
900 
901 	nvmem = nvmem_register(&config);
902 	/* Just ignore if there is no NVMEM support in the kernel */
903 	if (IS_ERR(nvmem) && PTR_ERR(nvmem) == -EOPNOTSUPP)
904 		nvmem = NULL;
905 
906 	of_node_put(np);
907 	kfree(config.name);
908 
909 	return nvmem;
910 }
911 
912 static int mtd_nvmem_user_otp_reg_read(void *priv, unsigned int offset,
913 				       void *val, size_t bytes)
914 {
915 	struct mtd_info *mtd = priv;
916 	size_t retlen;
917 	int ret;
918 
919 	ret = mtd_read_user_prot_reg(mtd, offset, bytes, &retlen, val);
920 	if (ret)
921 		return ret;
922 
923 	return retlen == bytes ? 0 : -EIO;
924 }
925 
926 static int mtd_nvmem_fact_otp_reg_read(void *priv, unsigned int offset,
927 				       void *val, size_t bytes)
928 {
929 	struct mtd_info *mtd = priv;
930 	size_t retlen;
931 	int ret;
932 
933 	ret = mtd_read_fact_prot_reg(mtd, offset, bytes, &retlen, val);
934 	if (ret)
935 		return ret;
936 
937 	return retlen == bytes ? 0 : -EIO;
938 }
939 
940 static int mtd_otp_nvmem_add(struct mtd_info *mtd)
941 {
942 	struct nvmem_device *nvmem;
943 	ssize_t size;
944 	int err;
945 
946 	if (mtd->_get_user_prot_info && mtd->_read_user_prot_reg) {
947 		size = mtd_otp_size(mtd, true);
948 		if (size < 0)
949 			return size;
950 
951 		if (size > 0) {
952 			nvmem = mtd_otp_nvmem_register(mtd, "user-otp", size,
953 						       mtd_nvmem_user_otp_reg_read);
954 			if (IS_ERR(nvmem)) {
955 				dev_err(&mtd->dev, "Failed to register OTP NVMEM device\n");
956 				return PTR_ERR(nvmem);
957 			}
958 			mtd->otp_user_nvmem = nvmem;
959 		}
960 	}
961 
962 	if (mtd->_get_fact_prot_info && mtd->_read_fact_prot_reg) {
963 		size = mtd_otp_size(mtd, false);
964 		if (size < 0) {
965 			err = size;
966 			goto err;
967 		}
968 
969 		if (size > 0) {
970 			nvmem = mtd_otp_nvmem_register(mtd, "factory-otp", size,
971 						       mtd_nvmem_fact_otp_reg_read);
972 			if (IS_ERR(nvmem)) {
973 				dev_err(&mtd->dev, "Failed to register OTP NVMEM device\n");
974 				err = PTR_ERR(nvmem);
975 				goto err;
976 			}
977 			mtd->otp_factory_nvmem = nvmem;
978 		}
979 	}
980 
981 	return 0;
982 
983 err:
984 	nvmem_unregister(mtd->otp_user_nvmem);
985 	return err;
986 }
987 
988 /**
989  * mtd_device_parse_register - parse partitions and register an MTD device.
990  *
991  * @mtd: the MTD device to register
992  * @types: the list of MTD partition probes to try, see
993  *         'parse_mtd_partitions()' for more information
994  * @parser_data: MTD partition parser-specific data
995  * @parts: fallback partition information to register, if parsing fails;
996  *         only valid if %nr_parts > %0
997  * @nr_parts: the number of partitions in parts, if zero then the full
998  *            MTD device is registered if no partition info is found
999  *
1000  * This function aggregates MTD partitions parsing (done by
1001  * 'parse_mtd_partitions()') and MTD device and partitions registering. It
1002  * basically follows the most common pattern found in many MTD drivers:
1003  *
1004  * * If the MTD_PARTITIONED_MASTER option is set, then the device as a whole is
1005  *   registered first.
1006  * * Then It tries to probe partitions on MTD device @mtd using parsers
1007  *   specified in @types (if @types is %NULL, then the default list of parsers
1008  *   is used, see 'parse_mtd_partitions()' for more information). If none are
1009  *   found this functions tries to fallback to information specified in
1010  *   @parts/@nr_parts.
1011  * * If no partitions were found this function just registers the MTD device
1012  *   @mtd and exits.
1013  *
1014  * Returns zero in case of success and a negative error code in case of failure.
1015  */
1016 int mtd_device_parse_register(struct mtd_info *mtd, const char * const *types,
1017 			      struct mtd_part_parser_data *parser_data,
1018 			      const struct mtd_partition *parts,
1019 			      int nr_parts)
1020 {
1021 	int ret;
1022 
1023 	mtd_set_dev_defaults(mtd);
1024 
1025 	if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER)) {
1026 		ret = add_mtd_device(mtd);
1027 		if (ret)
1028 			return ret;
1029 	}
1030 
1031 	/* Prefer parsed partitions over driver-provided fallback */
1032 	ret = parse_mtd_partitions(mtd, types, parser_data);
1033 	if (ret == -EPROBE_DEFER)
1034 		goto out;
1035 
1036 	if (ret > 0)
1037 		ret = 0;
1038 	else if (nr_parts)
1039 		ret = add_mtd_partitions(mtd, parts, nr_parts);
1040 	else if (!device_is_registered(&mtd->dev))
1041 		ret = add_mtd_device(mtd);
1042 	else
1043 		ret = 0;
1044 
1045 	if (ret)
1046 		goto out;
1047 
1048 	/*
1049 	 * FIXME: some drivers unfortunately call this function more than once.
1050 	 * So we have to check if we've already assigned the reboot notifier.
1051 	 *
1052 	 * Generally, we can make multiple calls work for most cases, but it
1053 	 * does cause problems with parse_mtd_partitions() above (e.g.,
1054 	 * cmdlineparts will register partitions more than once).
1055 	 */
1056 	WARN_ONCE(mtd->_reboot && mtd->reboot_notifier.notifier_call,
1057 		  "MTD already registered\n");
1058 	if (mtd->_reboot && !mtd->reboot_notifier.notifier_call) {
1059 		mtd->reboot_notifier.notifier_call = mtd_reboot_notifier;
1060 		register_reboot_notifier(&mtd->reboot_notifier);
1061 	}
1062 
1063 	ret = mtd_otp_nvmem_add(mtd);
1064 
1065 out:
1066 	if (ret && device_is_registered(&mtd->dev))
1067 		del_mtd_device(mtd);
1068 
1069 	return ret;
1070 }
1071 EXPORT_SYMBOL_GPL(mtd_device_parse_register);
1072 
1073 /**
1074  * mtd_device_unregister - unregister an existing MTD device.
1075  *
1076  * @master: the MTD device to unregister.  This will unregister both the master
1077  *          and any partitions if registered.
1078  */
1079 int mtd_device_unregister(struct mtd_info *master)
1080 {
1081 	int err;
1082 
1083 	if (master->_reboot) {
1084 		unregister_reboot_notifier(&master->reboot_notifier);
1085 		memset(&master->reboot_notifier, 0, sizeof(master->reboot_notifier));
1086 	}
1087 
1088 	nvmem_unregister(master->otp_user_nvmem);
1089 	nvmem_unregister(master->otp_factory_nvmem);
1090 
1091 	err = del_mtd_partitions(master);
1092 	if (err)
1093 		return err;
1094 
1095 	if (!device_is_registered(&master->dev))
1096 		return 0;
1097 
1098 	return del_mtd_device(master);
1099 }
1100 EXPORT_SYMBOL_GPL(mtd_device_unregister);
1101 
1102 /**
1103  *	register_mtd_user - register a 'user' of MTD devices.
1104  *	@new: pointer to notifier info structure
1105  *
1106  *	Registers a pair of callbacks function to be called upon addition
1107  *	or removal of MTD devices. Causes the 'add' callback to be immediately
1108  *	invoked for each MTD device currently present in the system.
1109  */
1110 void register_mtd_user (struct mtd_notifier *new)
1111 {
1112 	struct mtd_info *mtd;
1113 
1114 	mutex_lock(&mtd_table_mutex);
1115 
1116 	list_add(&new->list, &mtd_notifiers);
1117 
1118 	__module_get(THIS_MODULE);
1119 
1120 	mtd_for_each_device(mtd)
1121 		new->add(mtd);
1122 
1123 	mutex_unlock(&mtd_table_mutex);
1124 }
1125 EXPORT_SYMBOL_GPL(register_mtd_user);
1126 
1127 /**
1128  *	unregister_mtd_user - unregister a 'user' of MTD devices.
1129  *	@old: pointer to notifier info structure
1130  *
1131  *	Removes a callback function pair from the list of 'users' to be
1132  *	notified upon addition or removal of MTD devices. Causes the
1133  *	'remove' callback to be immediately invoked for each MTD device
1134  *	currently present in the system.
1135  */
1136 int unregister_mtd_user (struct mtd_notifier *old)
1137 {
1138 	struct mtd_info *mtd;
1139 
1140 	mutex_lock(&mtd_table_mutex);
1141 
1142 	module_put(THIS_MODULE);
1143 
1144 	mtd_for_each_device(mtd)
1145 		old->remove(mtd);
1146 
1147 	list_del(&old->list);
1148 	mutex_unlock(&mtd_table_mutex);
1149 	return 0;
1150 }
1151 EXPORT_SYMBOL_GPL(unregister_mtd_user);
1152 
1153 /**
1154  *	get_mtd_device - obtain a validated handle for an MTD device
1155  *	@mtd: last known address of the required MTD device
1156  *	@num: internal device number of the required MTD device
1157  *
1158  *	Given a number and NULL address, return the num'th entry in the device
1159  *	table, if any.	Given an address and num == -1, search the device table
1160  *	for a device with that address and return if it's still present. Given
1161  *	both, return the num'th driver only if its address matches. Return
1162  *	error code if not.
1163  */
1164 struct mtd_info *get_mtd_device(struct mtd_info *mtd, int num)
1165 {
1166 	struct mtd_info *ret = NULL, *other;
1167 	int err = -ENODEV;
1168 
1169 	mutex_lock(&mtd_table_mutex);
1170 
1171 	if (num == -1) {
1172 		mtd_for_each_device(other) {
1173 			if (other == mtd) {
1174 				ret = mtd;
1175 				break;
1176 			}
1177 		}
1178 	} else if (num >= 0) {
1179 		ret = idr_find(&mtd_idr, num);
1180 		if (mtd && mtd != ret)
1181 			ret = NULL;
1182 	}
1183 
1184 	if (!ret) {
1185 		ret = ERR_PTR(err);
1186 		goto out;
1187 	}
1188 
1189 	err = __get_mtd_device(ret);
1190 	if (err)
1191 		ret = ERR_PTR(err);
1192 out:
1193 	mutex_unlock(&mtd_table_mutex);
1194 	return ret;
1195 }
1196 EXPORT_SYMBOL_GPL(get_mtd_device);
1197 
1198 
1199 int __get_mtd_device(struct mtd_info *mtd)
1200 {
1201 	struct mtd_info *master = mtd_get_master(mtd);
1202 	int err;
1203 
1204 	if (!try_module_get(master->owner))
1205 		return -ENODEV;
1206 
1207 	if (master->_get_device) {
1208 		err = master->_get_device(mtd);
1209 
1210 		if (err) {
1211 			module_put(master->owner);
1212 			return err;
1213 		}
1214 	}
1215 
1216 	master->usecount++;
1217 
1218 	while (mtd->parent) {
1219 		mtd->usecount++;
1220 		mtd = mtd->parent;
1221 	}
1222 
1223 	return 0;
1224 }
1225 EXPORT_SYMBOL_GPL(__get_mtd_device);
1226 
1227 /**
1228  * of_get_mtd_device_by_node - obtain an MTD device associated with a given node
1229  *
1230  * @np: device tree node
1231  */
1232 struct mtd_info *of_get_mtd_device_by_node(struct device_node *np)
1233 {
1234 	struct mtd_info *mtd = NULL;
1235 	struct mtd_info *tmp;
1236 	int err;
1237 
1238 	mutex_lock(&mtd_table_mutex);
1239 
1240 	err = -EPROBE_DEFER;
1241 	mtd_for_each_device(tmp) {
1242 		if (mtd_get_of_node(tmp) == np) {
1243 			mtd = tmp;
1244 			err = __get_mtd_device(mtd);
1245 			break;
1246 		}
1247 	}
1248 
1249 	mutex_unlock(&mtd_table_mutex);
1250 
1251 	return err ? ERR_PTR(err) : mtd;
1252 }
1253 EXPORT_SYMBOL_GPL(of_get_mtd_device_by_node);
1254 
1255 /**
1256  *	get_mtd_device_nm - obtain a validated handle for an MTD device by
1257  *	device name
1258  *	@name: MTD device name to open
1259  *
1260  * 	This function returns MTD device description structure in case of
1261  * 	success and an error code in case of failure.
1262  */
1263 struct mtd_info *get_mtd_device_nm(const char *name)
1264 {
1265 	int err = -ENODEV;
1266 	struct mtd_info *mtd = NULL, *other;
1267 
1268 	mutex_lock(&mtd_table_mutex);
1269 
1270 	mtd_for_each_device(other) {
1271 		if (!strcmp(name, other->name)) {
1272 			mtd = other;
1273 			break;
1274 		}
1275 	}
1276 
1277 	if (!mtd)
1278 		goto out_unlock;
1279 
1280 	err = __get_mtd_device(mtd);
1281 	if (err)
1282 		goto out_unlock;
1283 
1284 	mutex_unlock(&mtd_table_mutex);
1285 	return mtd;
1286 
1287 out_unlock:
1288 	mutex_unlock(&mtd_table_mutex);
1289 	return ERR_PTR(err);
1290 }
1291 EXPORT_SYMBOL_GPL(get_mtd_device_nm);
1292 
1293 void put_mtd_device(struct mtd_info *mtd)
1294 {
1295 	mutex_lock(&mtd_table_mutex);
1296 	__put_mtd_device(mtd);
1297 	mutex_unlock(&mtd_table_mutex);
1298 
1299 }
1300 EXPORT_SYMBOL_GPL(put_mtd_device);
1301 
1302 void __put_mtd_device(struct mtd_info *mtd)
1303 {
1304 	struct mtd_info *master = mtd_get_master(mtd);
1305 
1306 	while (mtd->parent) {
1307 		--mtd->usecount;
1308 		BUG_ON(mtd->usecount < 0);
1309 		mtd = mtd->parent;
1310 	}
1311 
1312 	master->usecount--;
1313 
1314 	if (master->_put_device)
1315 		master->_put_device(master);
1316 
1317 	module_put(master->owner);
1318 }
1319 EXPORT_SYMBOL_GPL(__put_mtd_device);
1320 
1321 /*
1322  * Erase is an synchronous operation. Device drivers are epected to return a
1323  * negative error code if the operation failed and update instr->fail_addr
1324  * to point the portion that was not properly erased.
1325  */
1326 int mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
1327 {
1328 	struct mtd_info *master = mtd_get_master(mtd);
1329 	u64 mst_ofs = mtd_get_master_ofs(mtd, 0);
1330 	struct erase_info adjinstr;
1331 	int ret;
1332 
1333 	instr->fail_addr = MTD_FAIL_ADDR_UNKNOWN;
1334 	adjinstr = *instr;
1335 
1336 	if (!mtd->erasesize || !master->_erase)
1337 		return -ENOTSUPP;
1338 
1339 	if (instr->addr >= mtd->size || instr->len > mtd->size - instr->addr)
1340 		return -EINVAL;
1341 	if (!(mtd->flags & MTD_WRITEABLE))
1342 		return -EROFS;
1343 
1344 	if (!instr->len)
1345 		return 0;
1346 
1347 	ledtrig_mtd_activity();
1348 
1349 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
1350 		adjinstr.addr = (loff_t)mtd_div_by_eb(instr->addr, mtd) *
1351 				master->erasesize;
1352 		adjinstr.len = ((u64)mtd_div_by_eb(instr->addr + instr->len, mtd) *
1353 				master->erasesize) -
1354 			       adjinstr.addr;
1355 	}
1356 
1357 	adjinstr.addr += mst_ofs;
1358 
1359 	ret = master->_erase(master, &adjinstr);
1360 
1361 	if (adjinstr.fail_addr != MTD_FAIL_ADDR_UNKNOWN) {
1362 		instr->fail_addr = adjinstr.fail_addr - mst_ofs;
1363 		if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
1364 			instr->fail_addr = mtd_div_by_eb(instr->fail_addr,
1365 							 master);
1366 			instr->fail_addr *= mtd->erasesize;
1367 		}
1368 	}
1369 
1370 	return ret;
1371 }
1372 EXPORT_SYMBOL_GPL(mtd_erase);
1373 
1374 /*
1375  * This stuff for eXecute-In-Place. phys is optional and may be set to NULL.
1376  */
1377 int mtd_point(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
1378 	      void **virt, resource_size_t *phys)
1379 {
1380 	struct mtd_info *master = mtd_get_master(mtd);
1381 
1382 	*retlen = 0;
1383 	*virt = NULL;
1384 	if (phys)
1385 		*phys = 0;
1386 	if (!master->_point)
1387 		return -EOPNOTSUPP;
1388 	if (from < 0 || from >= mtd->size || len > mtd->size - from)
1389 		return -EINVAL;
1390 	if (!len)
1391 		return 0;
1392 
1393 	from = mtd_get_master_ofs(mtd, from);
1394 	return master->_point(master, from, len, retlen, virt, phys);
1395 }
1396 EXPORT_SYMBOL_GPL(mtd_point);
1397 
1398 /* We probably shouldn't allow XIP if the unpoint isn't a NULL */
1399 int mtd_unpoint(struct mtd_info *mtd, loff_t from, size_t len)
1400 {
1401 	struct mtd_info *master = mtd_get_master(mtd);
1402 
1403 	if (!master->_unpoint)
1404 		return -EOPNOTSUPP;
1405 	if (from < 0 || from >= mtd->size || len > mtd->size - from)
1406 		return -EINVAL;
1407 	if (!len)
1408 		return 0;
1409 	return master->_unpoint(master, mtd_get_master_ofs(mtd, from), len);
1410 }
1411 EXPORT_SYMBOL_GPL(mtd_unpoint);
1412 
1413 /*
1414  * Allow NOMMU mmap() to directly map the device (if not NULL)
1415  * - return the address to which the offset maps
1416  * - return -ENOSYS to indicate refusal to do the mapping
1417  */
1418 unsigned long mtd_get_unmapped_area(struct mtd_info *mtd, unsigned long len,
1419 				    unsigned long offset, unsigned long flags)
1420 {
1421 	size_t retlen;
1422 	void *virt;
1423 	int ret;
1424 
1425 	ret = mtd_point(mtd, offset, len, &retlen, &virt, NULL);
1426 	if (ret)
1427 		return ret;
1428 	if (retlen != len) {
1429 		mtd_unpoint(mtd, offset, retlen);
1430 		return -ENOSYS;
1431 	}
1432 	return (unsigned long)virt;
1433 }
1434 EXPORT_SYMBOL_GPL(mtd_get_unmapped_area);
1435 
1436 static void mtd_update_ecc_stats(struct mtd_info *mtd, struct mtd_info *master,
1437 				 const struct mtd_ecc_stats *old_stats)
1438 {
1439 	struct mtd_ecc_stats diff;
1440 
1441 	if (master == mtd)
1442 		return;
1443 
1444 	diff = master->ecc_stats;
1445 	diff.failed -= old_stats->failed;
1446 	diff.corrected -= old_stats->corrected;
1447 
1448 	while (mtd->parent) {
1449 		mtd->ecc_stats.failed += diff.failed;
1450 		mtd->ecc_stats.corrected += diff.corrected;
1451 		mtd = mtd->parent;
1452 	}
1453 }
1454 
1455 int mtd_read(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen,
1456 	     u_char *buf)
1457 {
1458 	struct mtd_oob_ops ops = {
1459 		.len = len,
1460 		.datbuf = buf,
1461 	};
1462 	int ret;
1463 
1464 	ret = mtd_read_oob(mtd, from, &ops);
1465 	*retlen = ops.retlen;
1466 
1467 	return ret;
1468 }
1469 EXPORT_SYMBOL_GPL(mtd_read);
1470 
1471 int mtd_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1472 	      const u_char *buf)
1473 {
1474 	struct mtd_oob_ops ops = {
1475 		.len = len,
1476 		.datbuf = (u8 *)buf,
1477 	};
1478 	int ret;
1479 
1480 	ret = mtd_write_oob(mtd, to, &ops);
1481 	*retlen = ops.retlen;
1482 
1483 	return ret;
1484 }
1485 EXPORT_SYMBOL_GPL(mtd_write);
1486 
1487 /*
1488  * In blackbox flight recorder like scenarios we want to make successful writes
1489  * in interrupt context. panic_write() is only intended to be called when its
1490  * known the kernel is about to panic and we need the write to succeed. Since
1491  * the kernel is not going to be running for much longer, this function can
1492  * break locks and delay to ensure the write succeeds (but not sleep).
1493  */
1494 int mtd_panic_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen,
1495 		    const u_char *buf)
1496 {
1497 	struct mtd_info *master = mtd_get_master(mtd);
1498 
1499 	*retlen = 0;
1500 	if (!master->_panic_write)
1501 		return -EOPNOTSUPP;
1502 	if (to < 0 || to >= mtd->size || len > mtd->size - to)
1503 		return -EINVAL;
1504 	if (!(mtd->flags & MTD_WRITEABLE))
1505 		return -EROFS;
1506 	if (!len)
1507 		return 0;
1508 	if (!master->oops_panic_write)
1509 		master->oops_panic_write = true;
1510 
1511 	return master->_panic_write(master, mtd_get_master_ofs(mtd, to), len,
1512 				    retlen, buf);
1513 }
1514 EXPORT_SYMBOL_GPL(mtd_panic_write);
1515 
1516 static int mtd_check_oob_ops(struct mtd_info *mtd, loff_t offs,
1517 			     struct mtd_oob_ops *ops)
1518 {
1519 	/*
1520 	 * Some users are setting ->datbuf or ->oobbuf to NULL, but are leaving
1521 	 * ->len or ->ooblen uninitialized. Force ->len and ->ooblen to 0 in
1522 	 *  this case.
1523 	 */
1524 	if (!ops->datbuf)
1525 		ops->len = 0;
1526 
1527 	if (!ops->oobbuf)
1528 		ops->ooblen = 0;
1529 
1530 	if (offs < 0 || offs + ops->len > mtd->size)
1531 		return -EINVAL;
1532 
1533 	if (ops->ooblen) {
1534 		size_t maxooblen;
1535 
1536 		if (ops->ooboffs >= mtd_oobavail(mtd, ops))
1537 			return -EINVAL;
1538 
1539 		maxooblen = ((size_t)(mtd_div_by_ws(mtd->size, mtd) -
1540 				      mtd_div_by_ws(offs, mtd)) *
1541 			     mtd_oobavail(mtd, ops)) - ops->ooboffs;
1542 		if (ops->ooblen > maxooblen)
1543 			return -EINVAL;
1544 	}
1545 
1546 	return 0;
1547 }
1548 
1549 static int mtd_read_oob_std(struct mtd_info *mtd, loff_t from,
1550 			    struct mtd_oob_ops *ops)
1551 {
1552 	struct mtd_info *master = mtd_get_master(mtd);
1553 	int ret;
1554 
1555 	from = mtd_get_master_ofs(mtd, from);
1556 	if (master->_read_oob)
1557 		ret = master->_read_oob(master, from, ops);
1558 	else
1559 		ret = master->_read(master, from, ops->len, &ops->retlen,
1560 				    ops->datbuf);
1561 
1562 	return ret;
1563 }
1564 
1565 static int mtd_write_oob_std(struct mtd_info *mtd, loff_t to,
1566 			     struct mtd_oob_ops *ops)
1567 {
1568 	struct mtd_info *master = mtd_get_master(mtd);
1569 	int ret;
1570 
1571 	to = mtd_get_master_ofs(mtd, to);
1572 	if (master->_write_oob)
1573 		ret = master->_write_oob(master, to, ops);
1574 	else
1575 		ret = master->_write(master, to, ops->len, &ops->retlen,
1576 				     ops->datbuf);
1577 
1578 	return ret;
1579 }
1580 
1581 static int mtd_io_emulated_slc(struct mtd_info *mtd, loff_t start, bool read,
1582 			       struct mtd_oob_ops *ops)
1583 {
1584 	struct mtd_info *master = mtd_get_master(mtd);
1585 	int ngroups = mtd_pairing_groups(master);
1586 	int npairs = mtd_wunit_per_eb(master) / ngroups;
1587 	struct mtd_oob_ops adjops = *ops;
1588 	unsigned int wunit, oobavail;
1589 	struct mtd_pairing_info info;
1590 	int max_bitflips = 0;
1591 	u32 ebofs, pageofs;
1592 	loff_t base, pos;
1593 
1594 	ebofs = mtd_mod_by_eb(start, mtd);
1595 	base = (loff_t)mtd_div_by_eb(start, mtd) * master->erasesize;
1596 	info.group = 0;
1597 	info.pair = mtd_div_by_ws(ebofs, mtd);
1598 	pageofs = mtd_mod_by_ws(ebofs, mtd);
1599 	oobavail = mtd_oobavail(mtd, ops);
1600 
1601 	while (ops->retlen < ops->len || ops->oobretlen < ops->ooblen) {
1602 		int ret;
1603 
1604 		if (info.pair >= npairs) {
1605 			info.pair = 0;
1606 			base += master->erasesize;
1607 		}
1608 
1609 		wunit = mtd_pairing_info_to_wunit(master, &info);
1610 		pos = mtd_wunit_to_offset(mtd, base, wunit);
1611 
1612 		adjops.len = ops->len - ops->retlen;
1613 		if (adjops.len > mtd->writesize - pageofs)
1614 			adjops.len = mtd->writesize - pageofs;
1615 
1616 		adjops.ooblen = ops->ooblen - ops->oobretlen;
1617 		if (adjops.ooblen > oobavail - adjops.ooboffs)
1618 			adjops.ooblen = oobavail - adjops.ooboffs;
1619 
1620 		if (read) {
1621 			ret = mtd_read_oob_std(mtd, pos + pageofs, &adjops);
1622 			if (ret > 0)
1623 				max_bitflips = max(max_bitflips, ret);
1624 		} else {
1625 			ret = mtd_write_oob_std(mtd, pos + pageofs, &adjops);
1626 		}
1627 
1628 		if (ret < 0)
1629 			return ret;
1630 
1631 		max_bitflips = max(max_bitflips, ret);
1632 		ops->retlen += adjops.retlen;
1633 		ops->oobretlen += adjops.oobretlen;
1634 		adjops.datbuf += adjops.retlen;
1635 		adjops.oobbuf += adjops.oobretlen;
1636 		adjops.ooboffs = 0;
1637 		pageofs = 0;
1638 		info.pair++;
1639 	}
1640 
1641 	return max_bitflips;
1642 }
1643 
1644 int mtd_read_oob(struct mtd_info *mtd, loff_t from, struct mtd_oob_ops *ops)
1645 {
1646 	struct mtd_info *master = mtd_get_master(mtd);
1647 	struct mtd_ecc_stats old_stats = master->ecc_stats;
1648 	int ret_code;
1649 
1650 	ops->retlen = ops->oobretlen = 0;
1651 
1652 	ret_code = mtd_check_oob_ops(mtd, from, ops);
1653 	if (ret_code)
1654 		return ret_code;
1655 
1656 	ledtrig_mtd_activity();
1657 
1658 	/* Check the validity of a potential fallback on mtd->_read */
1659 	if (!master->_read_oob && (!master->_read || ops->oobbuf))
1660 		return -EOPNOTSUPP;
1661 
1662 	if (ops->stats)
1663 		memset(ops->stats, 0, sizeof(*ops->stats));
1664 
1665 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
1666 		ret_code = mtd_io_emulated_slc(mtd, from, true, ops);
1667 	else
1668 		ret_code = mtd_read_oob_std(mtd, from, ops);
1669 
1670 	mtd_update_ecc_stats(mtd, master, &old_stats);
1671 
1672 	/*
1673 	 * In cases where ops->datbuf != NULL, mtd->_read_oob() has semantics
1674 	 * similar to mtd->_read(), returning a non-negative integer
1675 	 * representing max bitflips. In other cases, mtd->_read_oob() may
1676 	 * return -EUCLEAN. In all cases, perform similar logic to mtd_read().
1677 	 */
1678 	if (unlikely(ret_code < 0))
1679 		return ret_code;
1680 	if (mtd->ecc_strength == 0)
1681 		return 0;	/* device lacks ecc */
1682 	if (ops->stats)
1683 		ops->stats->max_bitflips = ret_code;
1684 	return ret_code >= mtd->bitflip_threshold ? -EUCLEAN : 0;
1685 }
1686 EXPORT_SYMBOL_GPL(mtd_read_oob);
1687 
1688 int mtd_write_oob(struct mtd_info *mtd, loff_t to,
1689 				struct mtd_oob_ops *ops)
1690 {
1691 	struct mtd_info *master = mtd_get_master(mtd);
1692 	int ret;
1693 
1694 	ops->retlen = ops->oobretlen = 0;
1695 
1696 	if (!(mtd->flags & MTD_WRITEABLE))
1697 		return -EROFS;
1698 
1699 	ret = mtd_check_oob_ops(mtd, to, ops);
1700 	if (ret)
1701 		return ret;
1702 
1703 	ledtrig_mtd_activity();
1704 
1705 	/* Check the validity of a potential fallback on mtd->_write */
1706 	if (!master->_write_oob && (!master->_write || ops->oobbuf))
1707 		return -EOPNOTSUPP;
1708 
1709 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
1710 		return mtd_io_emulated_slc(mtd, to, false, ops);
1711 
1712 	return mtd_write_oob_std(mtd, to, ops);
1713 }
1714 EXPORT_SYMBOL_GPL(mtd_write_oob);
1715 
1716 /**
1717  * mtd_ooblayout_ecc - Get the OOB region definition of a specific ECC section
1718  * @mtd: MTD device structure
1719  * @section: ECC section. Depending on the layout you may have all the ECC
1720  *	     bytes stored in a single contiguous section, or one section
1721  *	     per ECC chunk (and sometime several sections for a single ECC
1722  *	     ECC chunk)
1723  * @oobecc: OOB region struct filled with the appropriate ECC position
1724  *	    information
1725  *
1726  * This function returns ECC section information in the OOB area. If you want
1727  * to get all the ECC bytes information, then you should call
1728  * mtd_ooblayout_ecc(mtd, section++, oobecc) until it returns -ERANGE.
1729  *
1730  * Returns zero on success, a negative error code otherwise.
1731  */
1732 int mtd_ooblayout_ecc(struct mtd_info *mtd, int section,
1733 		      struct mtd_oob_region *oobecc)
1734 {
1735 	struct mtd_info *master = mtd_get_master(mtd);
1736 
1737 	memset(oobecc, 0, sizeof(*oobecc));
1738 
1739 	if (!master || section < 0)
1740 		return -EINVAL;
1741 
1742 	if (!master->ooblayout || !master->ooblayout->ecc)
1743 		return -ENOTSUPP;
1744 
1745 	return master->ooblayout->ecc(master, section, oobecc);
1746 }
1747 EXPORT_SYMBOL_GPL(mtd_ooblayout_ecc);
1748 
1749 /**
1750  * mtd_ooblayout_free - Get the OOB region definition of a specific free
1751  *			section
1752  * @mtd: MTD device structure
1753  * @section: Free section you are interested in. Depending on the layout
1754  *	     you may have all the free bytes stored in a single contiguous
1755  *	     section, or one section per ECC chunk plus an extra section
1756  *	     for the remaining bytes (or other funky layout).
1757  * @oobfree: OOB region struct filled with the appropriate free position
1758  *	     information
1759  *
1760  * This function returns free bytes position in the OOB area. If you want
1761  * to get all the free bytes information, then you should call
1762  * mtd_ooblayout_free(mtd, section++, oobfree) until it returns -ERANGE.
1763  *
1764  * Returns zero on success, a negative error code otherwise.
1765  */
1766 int mtd_ooblayout_free(struct mtd_info *mtd, int section,
1767 		       struct mtd_oob_region *oobfree)
1768 {
1769 	struct mtd_info *master = mtd_get_master(mtd);
1770 
1771 	memset(oobfree, 0, sizeof(*oobfree));
1772 
1773 	if (!master || section < 0)
1774 		return -EINVAL;
1775 
1776 	if (!master->ooblayout || !master->ooblayout->free)
1777 		return -ENOTSUPP;
1778 
1779 	return master->ooblayout->free(master, section, oobfree);
1780 }
1781 EXPORT_SYMBOL_GPL(mtd_ooblayout_free);
1782 
1783 /**
1784  * mtd_ooblayout_find_region - Find the region attached to a specific byte
1785  * @mtd: mtd info structure
1786  * @byte: the byte we are searching for
1787  * @sectionp: pointer where the section id will be stored
1788  * @oobregion: used to retrieve the ECC position
1789  * @iter: iterator function. Should be either mtd_ooblayout_free or
1790  *	  mtd_ooblayout_ecc depending on the region type you're searching for
1791  *
1792  * This function returns the section id and oobregion information of a
1793  * specific byte. For example, say you want to know where the 4th ECC byte is
1794  * stored, you'll use:
1795  *
1796  * mtd_ooblayout_find_region(mtd, 3, &section, &oobregion, mtd_ooblayout_ecc);
1797  *
1798  * Returns zero on success, a negative error code otherwise.
1799  */
1800 static int mtd_ooblayout_find_region(struct mtd_info *mtd, int byte,
1801 				int *sectionp, struct mtd_oob_region *oobregion,
1802 				int (*iter)(struct mtd_info *,
1803 					    int section,
1804 					    struct mtd_oob_region *oobregion))
1805 {
1806 	int pos = 0, ret, section = 0;
1807 
1808 	memset(oobregion, 0, sizeof(*oobregion));
1809 
1810 	while (1) {
1811 		ret = iter(mtd, section, oobregion);
1812 		if (ret)
1813 			return ret;
1814 
1815 		if (pos + oobregion->length > byte)
1816 			break;
1817 
1818 		pos += oobregion->length;
1819 		section++;
1820 	}
1821 
1822 	/*
1823 	 * Adjust region info to make it start at the beginning at the
1824 	 * 'start' ECC byte.
1825 	 */
1826 	oobregion->offset += byte - pos;
1827 	oobregion->length -= byte - pos;
1828 	*sectionp = section;
1829 
1830 	return 0;
1831 }
1832 
1833 /**
1834  * mtd_ooblayout_find_eccregion - Find the ECC region attached to a specific
1835  *				  ECC byte
1836  * @mtd: mtd info structure
1837  * @eccbyte: the byte we are searching for
1838  * @section: pointer where the section id will be stored
1839  * @oobregion: OOB region information
1840  *
1841  * Works like mtd_ooblayout_find_region() except it searches for a specific ECC
1842  * byte.
1843  *
1844  * Returns zero on success, a negative error code otherwise.
1845  */
1846 int mtd_ooblayout_find_eccregion(struct mtd_info *mtd, int eccbyte,
1847 				 int *section,
1848 				 struct mtd_oob_region *oobregion)
1849 {
1850 	return mtd_ooblayout_find_region(mtd, eccbyte, section, oobregion,
1851 					 mtd_ooblayout_ecc);
1852 }
1853 EXPORT_SYMBOL_GPL(mtd_ooblayout_find_eccregion);
1854 
1855 /**
1856  * mtd_ooblayout_get_bytes - Extract OOB bytes from the oob buffer
1857  * @mtd: mtd info structure
1858  * @buf: destination buffer to store OOB bytes
1859  * @oobbuf: OOB buffer
1860  * @start: first byte to retrieve
1861  * @nbytes: number of bytes to retrieve
1862  * @iter: section iterator
1863  *
1864  * Extract bytes attached to a specific category (ECC or free)
1865  * from the OOB buffer and copy them into buf.
1866  *
1867  * Returns zero on success, a negative error code otherwise.
1868  */
1869 static int mtd_ooblayout_get_bytes(struct mtd_info *mtd, u8 *buf,
1870 				const u8 *oobbuf, int start, int nbytes,
1871 				int (*iter)(struct mtd_info *,
1872 					    int section,
1873 					    struct mtd_oob_region *oobregion))
1874 {
1875 	struct mtd_oob_region oobregion;
1876 	int section, ret;
1877 
1878 	ret = mtd_ooblayout_find_region(mtd, start, &section,
1879 					&oobregion, iter);
1880 
1881 	while (!ret) {
1882 		int cnt;
1883 
1884 		cnt = min_t(int, nbytes, oobregion.length);
1885 		memcpy(buf, oobbuf + oobregion.offset, cnt);
1886 		buf += cnt;
1887 		nbytes -= cnt;
1888 
1889 		if (!nbytes)
1890 			break;
1891 
1892 		ret = iter(mtd, ++section, &oobregion);
1893 	}
1894 
1895 	return ret;
1896 }
1897 
1898 /**
1899  * mtd_ooblayout_set_bytes - put OOB bytes into the oob buffer
1900  * @mtd: mtd info structure
1901  * @buf: source buffer to get OOB bytes from
1902  * @oobbuf: OOB buffer
1903  * @start: first OOB byte to set
1904  * @nbytes: number of OOB bytes to set
1905  * @iter: section iterator
1906  *
1907  * Fill the OOB buffer with data provided in buf. The category (ECC or free)
1908  * is selected by passing the appropriate iterator.
1909  *
1910  * Returns zero on success, a negative error code otherwise.
1911  */
1912 static int mtd_ooblayout_set_bytes(struct mtd_info *mtd, const u8 *buf,
1913 				u8 *oobbuf, int start, int nbytes,
1914 				int (*iter)(struct mtd_info *,
1915 					    int section,
1916 					    struct mtd_oob_region *oobregion))
1917 {
1918 	struct mtd_oob_region oobregion;
1919 	int section, ret;
1920 
1921 	ret = mtd_ooblayout_find_region(mtd, start, &section,
1922 					&oobregion, iter);
1923 
1924 	while (!ret) {
1925 		int cnt;
1926 
1927 		cnt = min_t(int, nbytes, oobregion.length);
1928 		memcpy(oobbuf + oobregion.offset, buf, cnt);
1929 		buf += cnt;
1930 		nbytes -= cnt;
1931 
1932 		if (!nbytes)
1933 			break;
1934 
1935 		ret = iter(mtd, ++section, &oobregion);
1936 	}
1937 
1938 	return ret;
1939 }
1940 
1941 /**
1942  * mtd_ooblayout_count_bytes - count the number of bytes in a OOB category
1943  * @mtd: mtd info structure
1944  * @iter: category iterator
1945  *
1946  * Count the number of bytes in a given category.
1947  *
1948  * Returns a positive value on success, a negative error code otherwise.
1949  */
1950 static int mtd_ooblayout_count_bytes(struct mtd_info *mtd,
1951 				int (*iter)(struct mtd_info *,
1952 					    int section,
1953 					    struct mtd_oob_region *oobregion))
1954 {
1955 	struct mtd_oob_region oobregion;
1956 	int section = 0, ret, nbytes = 0;
1957 
1958 	while (1) {
1959 		ret = iter(mtd, section++, &oobregion);
1960 		if (ret) {
1961 			if (ret == -ERANGE)
1962 				ret = nbytes;
1963 			break;
1964 		}
1965 
1966 		nbytes += oobregion.length;
1967 	}
1968 
1969 	return ret;
1970 }
1971 
1972 /**
1973  * mtd_ooblayout_get_eccbytes - extract ECC bytes from the oob buffer
1974  * @mtd: mtd info structure
1975  * @eccbuf: destination buffer to store ECC bytes
1976  * @oobbuf: OOB buffer
1977  * @start: first ECC byte to retrieve
1978  * @nbytes: number of ECC bytes to retrieve
1979  *
1980  * Works like mtd_ooblayout_get_bytes(), except it acts on ECC bytes.
1981  *
1982  * Returns zero on success, a negative error code otherwise.
1983  */
1984 int mtd_ooblayout_get_eccbytes(struct mtd_info *mtd, u8 *eccbuf,
1985 			       const u8 *oobbuf, int start, int nbytes)
1986 {
1987 	return mtd_ooblayout_get_bytes(mtd, eccbuf, oobbuf, start, nbytes,
1988 				       mtd_ooblayout_ecc);
1989 }
1990 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_eccbytes);
1991 
1992 /**
1993  * mtd_ooblayout_set_eccbytes - set ECC bytes into the oob buffer
1994  * @mtd: mtd info structure
1995  * @eccbuf: source buffer to get ECC bytes from
1996  * @oobbuf: OOB buffer
1997  * @start: first ECC byte to set
1998  * @nbytes: number of ECC bytes to set
1999  *
2000  * Works like mtd_ooblayout_set_bytes(), except it acts on ECC bytes.
2001  *
2002  * Returns zero on success, a negative error code otherwise.
2003  */
2004 int mtd_ooblayout_set_eccbytes(struct mtd_info *mtd, const u8 *eccbuf,
2005 			       u8 *oobbuf, int start, int nbytes)
2006 {
2007 	return mtd_ooblayout_set_bytes(mtd, eccbuf, oobbuf, start, nbytes,
2008 				       mtd_ooblayout_ecc);
2009 }
2010 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_eccbytes);
2011 
2012 /**
2013  * mtd_ooblayout_get_databytes - extract data bytes from the oob buffer
2014  * @mtd: mtd info structure
2015  * @databuf: destination buffer to store ECC bytes
2016  * @oobbuf: OOB buffer
2017  * @start: first ECC byte to retrieve
2018  * @nbytes: number of ECC bytes to retrieve
2019  *
2020  * Works like mtd_ooblayout_get_bytes(), except it acts on free bytes.
2021  *
2022  * Returns zero on success, a negative error code otherwise.
2023  */
2024 int mtd_ooblayout_get_databytes(struct mtd_info *mtd, u8 *databuf,
2025 				const u8 *oobbuf, int start, int nbytes)
2026 {
2027 	return mtd_ooblayout_get_bytes(mtd, databuf, oobbuf, start, nbytes,
2028 				       mtd_ooblayout_free);
2029 }
2030 EXPORT_SYMBOL_GPL(mtd_ooblayout_get_databytes);
2031 
2032 /**
2033  * mtd_ooblayout_set_databytes - set data bytes into the oob buffer
2034  * @mtd: mtd info structure
2035  * @databuf: source buffer to get data bytes from
2036  * @oobbuf: OOB buffer
2037  * @start: first ECC byte to set
2038  * @nbytes: number of ECC bytes to set
2039  *
2040  * Works like mtd_ooblayout_set_bytes(), except it acts on free bytes.
2041  *
2042  * Returns zero on success, a negative error code otherwise.
2043  */
2044 int mtd_ooblayout_set_databytes(struct mtd_info *mtd, const u8 *databuf,
2045 				u8 *oobbuf, int start, int nbytes)
2046 {
2047 	return mtd_ooblayout_set_bytes(mtd, databuf, oobbuf, start, nbytes,
2048 				       mtd_ooblayout_free);
2049 }
2050 EXPORT_SYMBOL_GPL(mtd_ooblayout_set_databytes);
2051 
2052 /**
2053  * mtd_ooblayout_count_freebytes - count the number of free bytes in OOB
2054  * @mtd: mtd info structure
2055  *
2056  * Works like mtd_ooblayout_count_bytes(), except it count free bytes.
2057  *
2058  * Returns zero on success, a negative error code otherwise.
2059  */
2060 int mtd_ooblayout_count_freebytes(struct mtd_info *mtd)
2061 {
2062 	return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_free);
2063 }
2064 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_freebytes);
2065 
2066 /**
2067  * mtd_ooblayout_count_eccbytes - count the number of ECC bytes in OOB
2068  * @mtd: mtd info structure
2069  *
2070  * Works like mtd_ooblayout_count_bytes(), except it count ECC bytes.
2071  *
2072  * Returns zero on success, a negative error code otherwise.
2073  */
2074 int mtd_ooblayout_count_eccbytes(struct mtd_info *mtd)
2075 {
2076 	return mtd_ooblayout_count_bytes(mtd, mtd_ooblayout_ecc);
2077 }
2078 EXPORT_SYMBOL_GPL(mtd_ooblayout_count_eccbytes);
2079 
2080 /*
2081  * Method to access the protection register area, present in some flash
2082  * devices. The user data is one time programmable but the factory data is read
2083  * only.
2084  */
2085 int mtd_get_fact_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
2086 			   struct otp_info *buf)
2087 {
2088 	struct mtd_info *master = mtd_get_master(mtd);
2089 
2090 	if (!master->_get_fact_prot_info)
2091 		return -EOPNOTSUPP;
2092 	if (!len)
2093 		return 0;
2094 	return master->_get_fact_prot_info(master, len, retlen, buf);
2095 }
2096 EXPORT_SYMBOL_GPL(mtd_get_fact_prot_info);
2097 
2098 int mtd_read_fact_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
2099 			   size_t *retlen, u_char *buf)
2100 {
2101 	struct mtd_info *master = mtd_get_master(mtd);
2102 
2103 	*retlen = 0;
2104 	if (!master->_read_fact_prot_reg)
2105 		return -EOPNOTSUPP;
2106 	if (!len)
2107 		return 0;
2108 	return master->_read_fact_prot_reg(master, from, len, retlen, buf);
2109 }
2110 EXPORT_SYMBOL_GPL(mtd_read_fact_prot_reg);
2111 
2112 int mtd_get_user_prot_info(struct mtd_info *mtd, size_t len, size_t *retlen,
2113 			   struct otp_info *buf)
2114 {
2115 	struct mtd_info *master = mtd_get_master(mtd);
2116 
2117 	if (!master->_get_user_prot_info)
2118 		return -EOPNOTSUPP;
2119 	if (!len)
2120 		return 0;
2121 	return master->_get_user_prot_info(master, len, retlen, buf);
2122 }
2123 EXPORT_SYMBOL_GPL(mtd_get_user_prot_info);
2124 
2125 int mtd_read_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len,
2126 			   size_t *retlen, u_char *buf)
2127 {
2128 	struct mtd_info *master = mtd_get_master(mtd);
2129 
2130 	*retlen = 0;
2131 	if (!master->_read_user_prot_reg)
2132 		return -EOPNOTSUPP;
2133 	if (!len)
2134 		return 0;
2135 	return master->_read_user_prot_reg(master, from, len, retlen, buf);
2136 }
2137 EXPORT_SYMBOL_GPL(mtd_read_user_prot_reg);
2138 
2139 int mtd_write_user_prot_reg(struct mtd_info *mtd, loff_t to, size_t len,
2140 			    size_t *retlen, const u_char *buf)
2141 {
2142 	struct mtd_info *master = mtd_get_master(mtd);
2143 	int ret;
2144 
2145 	*retlen = 0;
2146 	if (!master->_write_user_prot_reg)
2147 		return -EOPNOTSUPP;
2148 	if (!len)
2149 		return 0;
2150 	ret = master->_write_user_prot_reg(master, to, len, retlen, buf);
2151 	if (ret)
2152 		return ret;
2153 
2154 	/*
2155 	 * If no data could be written at all, we are out of memory and
2156 	 * must return -ENOSPC.
2157 	 */
2158 	return (*retlen) ? 0 : -ENOSPC;
2159 }
2160 EXPORT_SYMBOL_GPL(mtd_write_user_prot_reg);
2161 
2162 int mtd_lock_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len)
2163 {
2164 	struct mtd_info *master = mtd_get_master(mtd);
2165 
2166 	if (!master->_lock_user_prot_reg)
2167 		return -EOPNOTSUPP;
2168 	if (!len)
2169 		return 0;
2170 	return master->_lock_user_prot_reg(master, from, len);
2171 }
2172 EXPORT_SYMBOL_GPL(mtd_lock_user_prot_reg);
2173 
2174 int mtd_erase_user_prot_reg(struct mtd_info *mtd, loff_t from, size_t len)
2175 {
2176 	struct mtd_info *master = mtd_get_master(mtd);
2177 
2178 	if (!master->_erase_user_prot_reg)
2179 		return -EOPNOTSUPP;
2180 	if (!len)
2181 		return 0;
2182 	return master->_erase_user_prot_reg(master, from, len);
2183 }
2184 EXPORT_SYMBOL_GPL(mtd_erase_user_prot_reg);
2185 
2186 /* Chip-supported device locking */
2187 int mtd_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2188 {
2189 	struct mtd_info *master = mtd_get_master(mtd);
2190 
2191 	if (!master->_lock)
2192 		return -EOPNOTSUPP;
2193 	if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
2194 		return -EINVAL;
2195 	if (!len)
2196 		return 0;
2197 
2198 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
2199 		ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2200 		len = (u64)mtd_div_by_eb(len, mtd) * master->erasesize;
2201 	}
2202 
2203 	return master->_lock(master, mtd_get_master_ofs(mtd, ofs), len);
2204 }
2205 EXPORT_SYMBOL_GPL(mtd_lock);
2206 
2207 int mtd_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2208 {
2209 	struct mtd_info *master = mtd_get_master(mtd);
2210 
2211 	if (!master->_unlock)
2212 		return -EOPNOTSUPP;
2213 	if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
2214 		return -EINVAL;
2215 	if (!len)
2216 		return 0;
2217 
2218 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
2219 		ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2220 		len = (u64)mtd_div_by_eb(len, mtd) * master->erasesize;
2221 	}
2222 
2223 	return master->_unlock(master, mtd_get_master_ofs(mtd, ofs), len);
2224 }
2225 EXPORT_SYMBOL_GPL(mtd_unlock);
2226 
2227 int mtd_is_locked(struct mtd_info *mtd, loff_t ofs, uint64_t len)
2228 {
2229 	struct mtd_info *master = mtd_get_master(mtd);
2230 
2231 	if (!master->_is_locked)
2232 		return -EOPNOTSUPP;
2233 	if (ofs < 0 || ofs >= mtd->size || len > mtd->size - ofs)
2234 		return -EINVAL;
2235 	if (!len)
2236 		return 0;
2237 
2238 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION) {
2239 		ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2240 		len = (u64)mtd_div_by_eb(len, mtd) * master->erasesize;
2241 	}
2242 
2243 	return master->_is_locked(master, mtd_get_master_ofs(mtd, ofs), len);
2244 }
2245 EXPORT_SYMBOL_GPL(mtd_is_locked);
2246 
2247 int mtd_block_isreserved(struct mtd_info *mtd, loff_t ofs)
2248 {
2249 	struct mtd_info *master = mtd_get_master(mtd);
2250 
2251 	if (ofs < 0 || ofs >= mtd->size)
2252 		return -EINVAL;
2253 	if (!master->_block_isreserved)
2254 		return 0;
2255 
2256 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
2257 		ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2258 
2259 	return master->_block_isreserved(master, mtd_get_master_ofs(mtd, ofs));
2260 }
2261 EXPORT_SYMBOL_GPL(mtd_block_isreserved);
2262 
2263 int mtd_block_isbad(struct mtd_info *mtd, loff_t ofs)
2264 {
2265 	struct mtd_info *master = mtd_get_master(mtd);
2266 
2267 	if (ofs < 0 || ofs >= mtd->size)
2268 		return -EINVAL;
2269 	if (!master->_block_isbad)
2270 		return 0;
2271 
2272 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
2273 		ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2274 
2275 	return master->_block_isbad(master, mtd_get_master_ofs(mtd, ofs));
2276 }
2277 EXPORT_SYMBOL_GPL(mtd_block_isbad);
2278 
2279 int mtd_block_markbad(struct mtd_info *mtd, loff_t ofs)
2280 {
2281 	struct mtd_info *master = mtd_get_master(mtd);
2282 	int ret;
2283 
2284 	if (!master->_block_markbad)
2285 		return -EOPNOTSUPP;
2286 	if (ofs < 0 || ofs >= mtd->size)
2287 		return -EINVAL;
2288 	if (!(mtd->flags & MTD_WRITEABLE))
2289 		return -EROFS;
2290 
2291 	if (mtd->flags & MTD_SLC_ON_MLC_EMULATION)
2292 		ofs = (loff_t)mtd_div_by_eb(ofs, mtd) * master->erasesize;
2293 
2294 	ret = master->_block_markbad(master, mtd_get_master_ofs(mtd, ofs));
2295 	if (ret)
2296 		return ret;
2297 
2298 	while (mtd->parent) {
2299 		mtd->ecc_stats.badblocks++;
2300 		mtd = mtd->parent;
2301 	}
2302 
2303 	return 0;
2304 }
2305 EXPORT_SYMBOL_GPL(mtd_block_markbad);
2306 
2307 /*
2308  * default_mtd_writev - the default writev method
2309  * @mtd: mtd device description object pointer
2310  * @vecs: the vectors to write
2311  * @count: count of vectors in @vecs
2312  * @to: the MTD device offset to write to
2313  * @retlen: on exit contains the count of bytes written to the MTD device.
2314  *
2315  * This function returns zero in case of success and a negative error code in
2316  * case of failure.
2317  */
2318 static int default_mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
2319 			      unsigned long count, loff_t to, size_t *retlen)
2320 {
2321 	unsigned long i;
2322 	size_t totlen = 0, thislen;
2323 	int ret = 0;
2324 
2325 	for (i = 0; i < count; i++) {
2326 		if (!vecs[i].iov_len)
2327 			continue;
2328 		ret = mtd_write(mtd, to, vecs[i].iov_len, &thislen,
2329 				vecs[i].iov_base);
2330 		totlen += thislen;
2331 		if (ret || thislen != vecs[i].iov_len)
2332 			break;
2333 		to += vecs[i].iov_len;
2334 	}
2335 	*retlen = totlen;
2336 	return ret;
2337 }
2338 
2339 /*
2340  * mtd_writev - the vector-based MTD write method
2341  * @mtd: mtd device description object pointer
2342  * @vecs: the vectors to write
2343  * @count: count of vectors in @vecs
2344  * @to: the MTD device offset to write to
2345  * @retlen: on exit contains the count of bytes written to the MTD device.
2346  *
2347  * This function returns zero in case of success and a negative error code in
2348  * case of failure.
2349  */
2350 int mtd_writev(struct mtd_info *mtd, const struct kvec *vecs,
2351 	       unsigned long count, loff_t to, size_t *retlen)
2352 {
2353 	struct mtd_info *master = mtd_get_master(mtd);
2354 
2355 	*retlen = 0;
2356 	if (!(mtd->flags & MTD_WRITEABLE))
2357 		return -EROFS;
2358 
2359 	if (!master->_writev)
2360 		return default_mtd_writev(mtd, vecs, count, to, retlen);
2361 
2362 	return master->_writev(master, vecs, count,
2363 			       mtd_get_master_ofs(mtd, to), retlen);
2364 }
2365 EXPORT_SYMBOL_GPL(mtd_writev);
2366 
2367 /**
2368  * mtd_kmalloc_up_to - allocate a contiguous buffer up to the specified size
2369  * @mtd: mtd device description object pointer
2370  * @size: a pointer to the ideal or maximum size of the allocation, points
2371  *        to the actual allocation size on success.
2372  *
2373  * This routine attempts to allocate a contiguous kernel buffer up to
2374  * the specified size, backing off the size of the request exponentially
2375  * until the request succeeds or until the allocation size falls below
2376  * the system page size. This attempts to make sure it does not adversely
2377  * impact system performance, so when allocating more than one page, we
2378  * ask the memory allocator to avoid re-trying, swapping, writing back
2379  * or performing I/O.
2380  *
2381  * Note, this function also makes sure that the allocated buffer is aligned to
2382  * the MTD device's min. I/O unit, i.e. the "mtd->writesize" value.
2383  *
2384  * This is called, for example by mtd_{read,write} and jffs2_scan_medium,
2385  * to handle smaller (i.e. degraded) buffer allocations under low- or
2386  * fragmented-memory situations where such reduced allocations, from a
2387  * requested ideal, are allowed.
2388  *
2389  * Returns a pointer to the allocated buffer on success; otherwise, NULL.
2390  */
2391 void *mtd_kmalloc_up_to(const struct mtd_info *mtd, size_t *size)
2392 {
2393 	gfp_t flags = __GFP_NOWARN | __GFP_DIRECT_RECLAIM | __GFP_NORETRY;
2394 	size_t min_alloc = max_t(size_t, mtd->writesize, PAGE_SIZE);
2395 	void *kbuf;
2396 
2397 	*size = min_t(size_t, *size, KMALLOC_MAX_SIZE);
2398 
2399 	while (*size > min_alloc) {
2400 		kbuf = kmalloc(*size, flags);
2401 		if (kbuf)
2402 			return kbuf;
2403 
2404 		*size >>= 1;
2405 		*size = ALIGN(*size, mtd->writesize);
2406 	}
2407 
2408 	/*
2409 	 * For the last resort allocation allow 'kmalloc()' to do all sorts of
2410 	 * things (write-back, dropping caches, etc) by using GFP_KERNEL.
2411 	 */
2412 	return kmalloc(*size, GFP_KERNEL);
2413 }
2414 EXPORT_SYMBOL_GPL(mtd_kmalloc_up_to);
2415 
2416 #ifdef CONFIG_PROC_FS
2417 
2418 /*====================================================================*/
2419 /* Support for /proc/mtd */
2420 
2421 static int mtd_proc_show(struct seq_file *m, void *v)
2422 {
2423 	struct mtd_info *mtd;
2424 
2425 	seq_puts(m, "dev:    size   erasesize  name\n");
2426 	mutex_lock(&mtd_table_mutex);
2427 	mtd_for_each_device(mtd) {
2428 		seq_printf(m, "mtd%d: %8.8llx %8.8x \"%s\"\n",
2429 			   mtd->index, (unsigned long long)mtd->size,
2430 			   mtd->erasesize, mtd->name);
2431 	}
2432 	mutex_unlock(&mtd_table_mutex);
2433 	return 0;
2434 }
2435 #endif /* CONFIG_PROC_FS */
2436 
2437 /*====================================================================*/
2438 /* Init code */
2439 
2440 static struct backing_dev_info * __init mtd_bdi_init(const char *name)
2441 {
2442 	struct backing_dev_info *bdi;
2443 	int ret;
2444 
2445 	bdi = bdi_alloc(NUMA_NO_NODE);
2446 	if (!bdi)
2447 		return ERR_PTR(-ENOMEM);
2448 	bdi->ra_pages = 0;
2449 	bdi->io_pages = 0;
2450 
2451 	/*
2452 	 * We put '-0' suffix to the name to get the same name format as we
2453 	 * used to get. Since this is called only once, we get a unique name.
2454 	 */
2455 	ret = bdi_register(bdi, "%.28s-0", name);
2456 	if (ret)
2457 		bdi_put(bdi);
2458 
2459 	return ret ? ERR_PTR(ret) : bdi;
2460 }
2461 
2462 static struct proc_dir_entry *proc_mtd;
2463 
2464 static int __init init_mtd(void)
2465 {
2466 	int ret;
2467 
2468 	ret = class_register(&mtd_class);
2469 	if (ret)
2470 		goto err_reg;
2471 
2472 	mtd_bdi = mtd_bdi_init("mtd");
2473 	if (IS_ERR(mtd_bdi)) {
2474 		ret = PTR_ERR(mtd_bdi);
2475 		goto err_bdi;
2476 	}
2477 
2478 	proc_mtd = proc_create_single("mtd", 0, NULL, mtd_proc_show);
2479 
2480 	ret = init_mtdchar();
2481 	if (ret)
2482 		goto out_procfs;
2483 
2484 	dfs_dir_mtd = debugfs_create_dir("mtd", NULL);
2485 	debugfs_create_bool("expert_analysis_mode", 0600, dfs_dir_mtd,
2486 			    &mtd_expert_analysis_mode);
2487 
2488 	return 0;
2489 
2490 out_procfs:
2491 	if (proc_mtd)
2492 		remove_proc_entry("mtd", NULL);
2493 	bdi_unregister(mtd_bdi);
2494 	bdi_put(mtd_bdi);
2495 err_bdi:
2496 	class_unregister(&mtd_class);
2497 err_reg:
2498 	pr_err("Error registering mtd class or bdi: %d\n", ret);
2499 	return ret;
2500 }
2501 
2502 static void __exit cleanup_mtd(void)
2503 {
2504 	debugfs_remove_recursive(dfs_dir_mtd);
2505 	cleanup_mtdchar();
2506 	if (proc_mtd)
2507 		remove_proc_entry("mtd", NULL);
2508 	class_unregister(&mtd_class);
2509 	bdi_unregister(mtd_bdi);
2510 	bdi_put(mtd_bdi);
2511 	idr_destroy(&mtd_idr);
2512 }
2513 
2514 module_init(init_mtd);
2515 module_exit(cleanup_mtd);
2516 
2517 MODULE_LICENSE("GPL");
2518 MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
2519 MODULE_DESCRIPTION("Core MTD registration and access routines");
2520