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