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