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