xref: /openbmc/u-boot/drivers/mtd/ubi/build.c (revision 0adb5b76)
1 /*
2  * Copyright (c) International Business Machines Corp., 2006
3  * Copyright (c) Nokia Corporation, 2007
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  *
7  * Author: Artem Bityutskiy (Битюцкий Артём),
8  *         Frank Haverkamp
9  */
10 
11 /*
12  * This file includes UBI initialization and building of UBI devices.
13  *
14  * When UBI is initialized, it attaches all the MTD devices specified as the
15  * module load parameters or the kernel boot parameters. If MTD devices were
16  * specified, UBI does not attach any MTD device, but it is possible to do
17  * later using the "UBI control device".
18  */
19 
20 #ifndef __UBOOT__
21 #include <linux/module.h>
22 #include <linux/moduleparam.h>
23 #include <linux/stringify.h>
24 #include <linux/namei.h>
25 #include <linux/stat.h>
26 #include <linux/miscdevice.h>
27 #include <linux/log2.h>
28 #include <linux/kthread.h>
29 #include <linux/kernel.h>
30 #include <linux/slab.h>
31 #include <linux/major.h>
32 #else
33 #include <linux/compat.h>
34 #endif
35 #include <linux/err.h>
36 #include <ubi_uboot.h>
37 #include <linux/mtd/partitions.h>
38 
39 #include "ubi.h"
40 
41 /* Maximum length of the 'mtd=' parameter */
42 #define MTD_PARAM_LEN_MAX 64
43 
44 /* Maximum number of comma-separated items in the 'mtd=' parameter */
45 #define MTD_PARAM_MAX_COUNT 4
46 
47 /* Maximum value for the number of bad PEBs per 1024 PEBs */
48 #define MAX_MTD_UBI_BEB_LIMIT 768
49 
50 #ifdef CONFIG_MTD_UBI_MODULE
51 #define ubi_is_module() 1
52 #else
53 #define ubi_is_module() 0
54 #endif
55 
56 #if (CONFIG_SYS_MALLOC_LEN < (512 << 10))
57 #error Malloc area too small for UBI, increase CONFIG_SYS_MALLOC_LEN to >= 512k
58 #endif
59 
60 /**
61  * struct mtd_dev_param - MTD device parameter description data structure.
62  * @name: MTD character device node path, MTD device name, or MTD device number
63  *        string
64  * @vid_hdr_offs: VID header offset
65  * @max_beb_per1024: maximum expected number of bad PEBs per 1024 PEBs
66  */
67 struct mtd_dev_param {
68 	char name[MTD_PARAM_LEN_MAX];
69 	int ubi_num;
70 	int vid_hdr_offs;
71 	int max_beb_per1024;
72 };
73 
74 /* Numbers of elements set in the @mtd_dev_param array */
75 static int __initdata mtd_devs;
76 
77 /* MTD devices specification parameters */
78 static struct mtd_dev_param __initdata mtd_dev_param[UBI_MAX_DEVICES];
79 #ifndef __UBOOT__
80 #ifdef CONFIG_MTD_UBI_FASTMAP
81 /* UBI module parameter to enable fastmap automatically on non-fastmap images */
82 static bool fm_autoconvert;
83 #endif
84 #else
85 #ifdef CONFIG_MTD_UBI_FASTMAP
86 #if !defined(CONFIG_MTD_UBI_FASTMAP_AUTOCONVERT)
87 #define CONFIG_MTD_UBI_FASTMAP_AUTOCONVERT 0
88 #endif
89 static bool fm_autoconvert = CONFIG_MTD_UBI_FASTMAP_AUTOCONVERT;
90 #endif
91 #endif
92 /* Root UBI "class" object (corresponds to '/<sysfs>/class/ubi/') */
93 struct class *ubi_class;
94 
95 /* Slab cache for wear-leveling entries */
96 struct kmem_cache *ubi_wl_entry_slab;
97 
98 #ifndef __UBOOT__
99 /* UBI control character device */
100 static struct miscdevice ubi_ctrl_cdev = {
101 	.minor = MISC_DYNAMIC_MINOR,
102 	.name = "ubi_ctrl",
103 	.fops = &ubi_ctrl_cdev_operations,
104 };
105 #endif
106 
107 /* All UBI devices in system */
108 #ifndef __UBOOT__
109 static struct ubi_device *ubi_devices[UBI_MAX_DEVICES];
110 #else
111 struct ubi_device *ubi_devices[UBI_MAX_DEVICES];
112 #endif
113 
114 #ifndef __UBOOT__
115 /* Serializes UBI devices creations and removals */
116 DEFINE_MUTEX(ubi_devices_mutex);
117 
118 /* Protects @ubi_devices and @ubi->ref_count */
119 static DEFINE_SPINLOCK(ubi_devices_lock);
120 
121 /* "Show" method for files in '/<sysfs>/class/ubi/' */
122 static ssize_t ubi_version_show(struct class *class,
123 				struct class_attribute *attr, char *buf)
124 {
125 	return sprintf(buf, "%d\n", UBI_VERSION);
126 }
127 
128 /* UBI version attribute ('/<sysfs>/class/ubi/version') */
129 static struct class_attribute ubi_version =
130 	__ATTR(version, S_IRUGO, ubi_version_show, NULL);
131 
132 static ssize_t dev_attribute_show(struct device *dev,
133 				  struct device_attribute *attr, char *buf);
134 
135 /* UBI device attributes (correspond to files in '/<sysfs>/class/ubi/ubiX') */
136 static struct device_attribute dev_eraseblock_size =
137 	__ATTR(eraseblock_size, S_IRUGO, dev_attribute_show, NULL);
138 static struct device_attribute dev_avail_eraseblocks =
139 	__ATTR(avail_eraseblocks, S_IRUGO, dev_attribute_show, NULL);
140 static struct device_attribute dev_total_eraseblocks =
141 	__ATTR(total_eraseblocks, S_IRUGO, dev_attribute_show, NULL);
142 static struct device_attribute dev_volumes_count =
143 	__ATTR(volumes_count, S_IRUGO, dev_attribute_show, NULL);
144 static struct device_attribute dev_max_ec =
145 	__ATTR(max_ec, S_IRUGO, dev_attribute_show, NULL);
146 static struct device_attribute dev_reserved_for_bad =
147 	__ATTR(reserved_for_bad, S_IRUGO, dev_attribute_show, NULL);
148 static struct device_attribute dev_bad_peb_count =
149 	__ATTR(bad_peb_count, S_IRUGO, dev_attribute_show, NULL);
150 static struct device_attribute dev_max_vol_count =
151 	__ATTR(max_vol_count, S_IRUGO, dev_attribute_show, NULL);
152 static struct device_attribute dev_min_io_size =
153 	__ATTR(min_io_size, S_IRUGO, dev_attribute_show, NULL);
154 static struct device_attribute dev_bgt_enabled =
155 	__ATTR(bgt_enabled, S_IRUGO, dev_attribute_show, NULL);
156 static struct device_attribute dev_mtd_num =
157 	__ATTR(mtd_num, S_IRUGO, dev_attribute_show, NULL);
158 #endif
159 
160 /**
161  * ubi_volume_notify - send a volume change notification.
162  * @ubi: UBI device description object
163  * @vol: volume description object of the changed volume
164  * @ntype: notification type to send (%UBI_VOLUME_ADDED, etc)
165  *
166  * This is a helper function which notifies all subscribers about a volume
167  * change event (creation, removal, re-sizing, re-naming, updating). Returns
168  * zero in case of success and a negative error code in case of failure.
169  */
170 int ubi_volume_notify(struct ubi_device *ubi, struct ubi_volume *vol, int ntype)
171 {
172 	struct ubi_notification nt;
173 
174 	ubi_do_get_device_info(ubi, &nt.di);
175 	ubi_do_get_volume_info(ubi, vol, &nt.vi);
176 
177 #ifdef CONFIG_MTD_UBI_FASTMAP
178 	switch (ntype) {
179 	case UBI_VOLUME_ADDED:
180 	case UBI_VOLUME_REMOVED:
181 	case UBI_VOLUME_RESIZED:
182 	case UBI_VOLUME_RENAMED:
183 		if (ubi_update_fastmap(ubi)) {
184 			ubi_err("Unable to update fastmap!");
185 			ubi_ro_mode(ubi);
186 		}
187 	}
188 #endif
189 	return blocking_notifier_call_chain(&ubi_notifiers, ntype, &nt);
190 }
191 
192 /**
193  * ubi_notify_all - send a notification to all volumes.
194  * @ubi: UBI device description object
195  * @ntype: notification type to send (%UBI_VOLUME_ADDED, etc)
196  * @nb: the notifier to call
197  *
198  * This function walks all volumes of UBI device @ubi and sends the @ntype
199  * notification for each volume. If @nb is %NULL, then all registered notifiers
200  * are called, otherwise only the @nb notifier is called. Returns the number of
201  * sent notifications.
202  */
203 int ubi_notify_all(struct ubi_device *ubi, int ntype, struct notifier_block *nb)
204 {
205 	struct ubi_notification nt;
206 	int i, count = 0;
207 #ifndef __UBOOT__
208 	int ret;
209 #endif
210 
211 	ubi_do_get_device_info(ubi, &nt.di);
212 
213 	mutex_lock(&ubi->device_mutex);
214 	for (i = 0; i < ubi->vtbl_slots; i++) {
215 		/*
216 		 * Since the @ubi->device is locked, and we are not going to
217 		 * change @ubi->volumes, we do not have to lock
218 		 * @ubi->volumes_lock.
219 		 */
220 		if (!ubi->volumes[i])
221 			continue;
222 
223 		ubi_do_get_volume_info(ubi, ubi->volumes[i], &nt.vi);
224 #ifndef __UBOOT__
225 		if (nb)
226 			nb->notifier_call(nb, ntype, &nt);
227 		else
228 			ret = blocking_notifier_call_chain(&ubi_notifiers, ntype,
229 						     &nt);
230 #endif
231 		count += 1;
232 	}
233 	mutex_unlock(&ubi->device_mutex);
234 
235 	return count;
236 }
237 
238 /**
239  * ubi_enumerate_volumes - send "add" notification for all existing volumes.
240  * @nb: the notifier to call
241  *
242  * This function walks all UBI devices and volumes and sends the
243  * %UBI_VOLUME_ADDED notification for each volume. If @nb is %NULL, then all
244  * registered notifiers are called, otherwise only the @nb notifier is called.
245  * Returns the number of sent notifications.
246  */
247 int ubi_enumerate_volumes(struct notifier_block *nb)
248 {
249 	int i, count = 0;
250 
251 	/*
252 	 * Since the @ubi_devices_mutex is locked, and we are not going to
253 	 * change @ubi_devices, we do not have to lock @ubi_devices_lock.
254 	 */
255 	for (i = 0; i < UBI_MAX_DEVICES; i++) {
256 		struct ubi_device *ubi = ubi_devices[i];
257 
258 		if (!ubi)
259 			continue;
260 		count += ubi_notify_all(ubi, UBI_VOLUME_ADDED, nb);
261 	}
262 
263 	return count;
264 }
265 
266 /**
267  * ubi_get_device - get UBI device.
268  * @ubi_num: UBI device number
269  *
270  * This function returns UBI device description object for UBI device number
271  * @ubi_num, or %NULL if the device does not exist. This function increases the
272  * device reference count to prevent removal of the device. In other words, the
273  * device cannot be removed if its reference count is not zero.
274  */
275 struct ubi_device *ubi_get_device(int ubi_num)
276 {
277 	struct ubi_device *ubi;
278 
279 	spin_lock(&ubi_devices_lock);
280 	ubi = ubi_devices[ubi_num];
281 	if (ubi) {
282 		ubi_assert(ubi->ref_count >= 0);
283 		ubi->ref_count += 1;
284 		get_device(&ubi->dev);
285 	}
286 	spin_unlock(&ubi_devices_lock);
287 
288 	return ubi;
289 }
290 
291 /**
292  * ubi_put_device - drop an UBI device reference.
293  * @ubi: UBI device description object
294  */
295 void ubi_put_device(struct ubi_device *ubi)
296 {
297 	spin_lock(&ubi_devices_lock);
298 	ubi->ref_count -= 1;
299 	put_device(&ubi->dev);
300 	spin_unlock(&ubi_devices_lock);
301 }
302 
303 /**
304  * ubi_get_by_major - get UBI device by character device major number.
305  * @major: major number
306  *
307  * This function is similar to 'ubi_get_device()', but it searches the device
308  * by its major number.
309  */
310 struct ubi_device *ubi_get_by_major(int major)
311 {
312 	int i;
313 	struct ubi_device *ubi;
314 
315 	spin_lock(&ubi_devices_lock);
316 	for (i = 0; i < UBI_MAX_DEVICES; i++) {
317 		ubi = ubi_devices[i];
318 		if (ubi && MAJOR(ubi->cdev.dev) == major) {
319 			ubi_assert(ubi->ref_count >= 0);
320 			ubi->ref_count += 1;
321 			get_device(&ubi->dev);
322 			spin_unlock(&ubi_devices_lock);
323 			return ubi;
324 		}
325 	}
326 	spin_unlock(&ubi_devices_lock);
327 
328 	return NULL;
329 }
330 
331 /**
332  * ubi_major2num - get UBI device number by character device major number.
333  * @major: major number
334  *
335  * This function searches UBI device number object by its major number. If UBI
336  * device was not found, this function returns -ENODEV, otherwise the UBI device
337  * number is returned.
338  */
339 int ubi_major2num(int major)
340 {
341 	int i, ubi_num = -ENODEV;
342 
343 	spin_lock(&ubi_devices_lock);
344 	for (i = 0; i < UBI_MAX_DEVICES; i++) {
345 		struct ubi_device *ubi = ubi_devices[i];
346 
347 		if (ubi && MAJOR(ubi->cdev.dev) == major) {
348 			ubi_num = ubi->ubi_num;
349 			break;
350 		}
351 	}
352 	spin_unlock(&ubi_devices_lock);
353 
354 	return ubi_num;
355 }
356 
357 #ifndef __UBOOT__
358 /* "Show" method for files in '/<sysfs>/class/ubi/ubiX/' */
359 static ssize_t dev_attribute_show(struct device *dev,
360 				  struct device_attribute *attr, char *buf)
361 {
362 	ssize_t ret;
363 	struct ubi_device *ubi;
364 
365 	/*
366 	 * The below code looks weird, but it actually makes sense. We get the
367 	 * UBI device reference from the contained 'struct ubi_device'. But it
368 	 * is unclear if the device was removed or not yet. Indeed, if the
369 	 * device was removed before we increased its reference count,
370 	 * 'ubi_get_device()' will return -ENODEV and we fail.
371 	 *
372 	 * Remember, 'struct ubi_device' is freed in the release function, so
373 	 * we still can use 'ubi->ubi_num'.
374 	 */
375 	ubi = container_of(dev, struct ubi_device, dev);
376 	ubi = ubi_get_device(ubi->ubi_num);
377 	if (!ubi)
378 		return -ENODEV;
379 
380 	if (attr == &dev_eraseblock_size)
381 		ret = sprintf(buf, "%d\n", ubi->leb_size);
382 	else if (attr == &dev_avail_eraseblocks)
383 		ret = sprintf(buf, "%d\n", ubi->avail_pebs);
384 	else if (attr == &dev_total_eraseblocks)
385 		ret = sprintf(buf, "%d\n", ubi->good_peb_count);
386 	else if (attr == &dev_volumes_count)
387 		ret = sprintf(buf, "%d\n", ubi->vol_count - UBI_INT_VOL_COUNT);
388 	else if (attr == &dev_max_ec)
389 		ret = sprintf(buf, "%d\n", ubi->max_ec);
390 	else if (attr == &dev_reserved_for_bad)
391 		ret = sprintf(buf, "%d\n", ubi->beb_rsvd_pebs);
392 	else if (attr == &dev_bad_peb_count)
393 		ret = sprintf(buf, "%d\n", ubi->bad_peb_count);
394 	else if (attr == &dev_max_vol_count)
395 		ret = sprintf(buf, "%d\n", ubi->vtbl_slots);
396 	else if (attr == &dev_min_io_size)
397 		ret = sprintf(buf, "%d\n", ubi->min_io_size);
398 	else if (attr == &dev_bgt_enabled)
399 		ret = sprintf(buf, "%d\n", ubi->thread_enabled);
400 	else if (attr == &dev_mtd_num)
401 		ret = sprintf(buf, "%d\n", ubi->mtd->index);
402 	else
403 		ret = -EINVAL;
404 
405 	ubi_put_device(ubi);
406 	return ret;
407 }
408 
409 static void dev_release(struct device *dev)
410 {
411 	struct ubi_device *ubi = container_of(dev, struct ubi_device, dev);
412 
413 	kfree(ubi);
414 }
415 
416 /**
417  * ubi_sysfs_init - initialize sysfs for an UBI device.
418  * @ubi: UBI device description object
419  * @ref: set to %1 on exit in case of failure if a reference to @ubi->dev was
420  *       taken
421  *
422  * This function returns zero in case of success and a negative error code in
423  * case of failure.
424  */
425 static int ubi_sysfs_init(struct ubi_device *ubi, int *ref)
426 {
427 	int err;
428 
429 	ubi->dev.release = dev_release;
430 	ubi->dev.devt = ubi->cdev.dev;
431 	ubi->dev.class = ubi_class;
432 	dev_set_name(&ubi->dev, UBI_NAME_STR"%d", ubi->ubi_num);
433 	err = device_register(&ubi->dev);
434 	if (err)
435 		return err;
436 
437 	*ref = 1;
438 	err = device_create_file(&ubi->dev, &dev_eraseblock_size);
439 	if (err)
440 		return err;
441 	err = device_create_file(&ubi->dev, &dev_avail_eraseblocks);
442 	if (err)
443 		return err;
444 	err = device_create_file(&ubi->dev, &dev_total_eraseblocks);
445 	if (err)
446 		return err;
447 	err = device_create_file(&ubi->dev, &dev_volumes_count);
448 	if (err)
449 		return err;
450 	err = device_create_file(&ubi->dev, &dev_max_ec);
451 	if (err)
452 		return err;
453 	err = device_create_file(&ubi->dev, &dev_reserved_for_bad);
454 	if (err)
455 		return err;
456 	err = device_create_file(&ubi->dev, &dev_bad_peb_count);
457 	if (err)
458 		return err;
459 	err = device_create_file(&ubi->dev, &dev_max_vol_count);
460 	if (err)
461 		return err;
462 	err = device_create_file(&ubi->dev, &dev_min_io_size);
463 	if (err)
464 		return err;
465 	err = device_create_file(&ubi->dev, &dev_bgt_enabled);
466 	if (err)
467 		return err;
468 	err = device_create_file(&ubi->dev, &dev_mtd_num);
469 	return err;
470 }
471 
472 /**
473  * ubi_sysfs_close - close sysfs for an UBI device.
474  * @ubi: UBI device description object
475  */
476 static void ubi_sysfs_close(struct ubi_device *ubi)
477 {
478 	device_remove_file(&ubi->dev, &dev_mtd_num);
479 	device_remove_file(&ubi->dev, &dev_bgt_enabled);
480 	device_remove_file(&ubi->dev, &dev_min_io_size);
481 	device_remove_file(&ubi->dev, &dev_max_vol_count);
482 	device_remove_file(&ubi->dev, &dev_bad_peb_count);
483 	device_remove_file(&ubi->dev, &dev_reserved_for_bad);
484 	device_remove_file(&ubi->dev, &dev_max_ec);
485 	device_remove_file(&ubi->dev, &dev_volumes_count);
486 	device_remove_file(&ubi->dev, &dev_total_eraseblocks);
487 	device_remove_file(&ubi->dev, &dev_avail_eraseblocks);
488 	device_remove_file(&ubi->dev, &dev_eraseblock_size);
489 	device_unregister(&ubi->dev);
490 }
491 #endif
492 
493 /**
494  * kill_volumes - destroy all user volumes.
495  * @ubi: UBI device description object
496  */
497 static void kill_volumes(struct ubi_device *ubi)
498 {
499 	int i;
500 
501 	for (i = 0; i < ubi->vtbl_slots; i++)
502 		if (ubi->volumes[i])
503 			ubi_free_volume(ubi, ubi->volumes[i]);
504 }
505 
506 /**
507  * uif_init - initialize user interfaces for an UBI device.
508  * @ubi: UBI device description object
509  * @ref: set to %1 on exit in case of failure if a reference to @ubi->dev was
510  *       taken, otherwise set to %0
511  *
512  * This function initializes various user interfaces for an UBI device. If the
513  * initialization fails at an early stage, this function frees all the
514  * resources it allocated, returns an error, and @ref is set to %0. However,
515  * if the initialization fails after the UBI device was registered in the
516  * driver core subsystem, this function takes a reference to @ubi->dev, because
517  * otherwise the release function ('dev_release()') would free whole @ubi
518  * object. The @ref argument is set to %1 in this case. The caller has to put
519  * this reference.
520  *
521  * This function returns zero in case of success and a negative error code in
522  * case of failure.
523  */
524 static int uif_init(struct ubi_device *ubi, int *ref)
525 {
526 	int i, err;
527 #ifndef __UBOOT__
528 	dev_t dev;
529 #endif
530 
531 	*ref = 0;
532 	sprintf(ubi->ubi_name, UBI_NAME_STR "%d", ubi->ubi_num);
533 
534 	/*
535 	 * Major numbers for the UBI character devices are allocated
536 	 * dynamically. Major numbers of volume character devices are
537 	 * equivalent to ones of the corresponding UBI character device. Minor
538 	 * numbers of UBI character devices are 0, while minor numbers of
539 	 * volume character devices start from 1. Thus, we allocate one major
540 	 * number and ubi->vtbl_slots + 1 minor numbers.
541 	 */
542 	err = alloc_chrdev_region(&dev, 0, ubi->vtbl_slots + 1, ubi->ubi_name);
543 	if (err) {
544 		ubi_err("cannot register UBI character devices");
545 		return err;
546 	}
547 
548 	ubi_assert(MINOR(dev) == 0);
549 	cdev_init(&ubi->cdev, &ubi_cdev_operations);
550 	dbg_gen("%s major is %u", ubi->ubi_name, MAJOR(dev));
551 	ubi->cdev.owner = THIS_MODULE;
552 
553 	err = cdev_add(&ubi->cdev, dev, 1);
554 	if (err) {
555 		ubi_err("cannot add character device");
556 		goto out_unreg;
557 	}
558 
559 	err = ubi_sysfs_init(ubi, ref);
560 	if (err)
561 		goto out_sysfs;
562 
563 	for (i = 0; i < ubi->vtbl_slots; i++)
564 		if (ubi->volumes[i]) {
565 			err = ubi_add_volume(ubi, ubi->volumes[i]);
566 			if (err) {
567 				ubi_err("cannot add volume %d", i);
568 				goto out_volumes;
569 			}
570 		}
571 
572 	return 0;
573 
574 out_volumes:
575 	kill_volumes(ubi);
576 out_sysfs:
577 	if (*ref)
578 		get_device(&ubi->dev);
579 	ubi_sysfs_close(ubi);
580 	cdev_del(&ubi->cdev);
581 out_unreg:
582 	unregister_chrdev_region(ubi->cdev.dev, ubi->vtbl_slots + 1);
583 	ubi_err("cannot initialize UBI %s, error %d", ubi->ubi_name, err);
584 	return err;
585 }
586 
587 /**
588  * uif_close - close user interfaces for an UBI device.
589  * @ubi: UBI device description object
590  *
591  * Note, since this function un-registers UBI volume device objects (@vol->dev),
592  * the memory allocated voe the volumes is freed as well (in the release
593  * function).
594  */
595 static void uif_close(struct ubi_device *ubi)
596 {
597 	kill_volumes(ubi);
598 	ubi_sysfs_close(ubi);
599 	cdev_del(&ubi->cdev);
600 	unregister_chrdev_region(ubi->cdev.dev, ubi->vtbl_slots + 1);
601 }
602 
603 /**
604  * ubi_free_internal_volumes - free internal volumes.
605  * @ubi: UBI device description object
606  */
607 void ubi_free_internal_volumes(struct ubi_device *ubi)
608 {
609 	int i;
610 
611 	for (i = ubi->vtbl_slots;
612 	     i < ubi->vtbl_slots + UBI_INT_VOL_COUNT; i++) {
613 		kfree(ubi->volumes[i]->eba_tbl);
614 		kfree(ubi->volumes[i]);
615 	}
616 }
617 
618 static int get_bad_peb_limit(const struct ubi_device *ubi, int max_beb_per1024)
619 {
620 	int limit, device_pebs;
621 	uint64_t device_size;
622 
623 	if (!max_beb_per1024)
624 		return 0;
625 
626 	/*
627 	 * Here we are using size of the entire flash chip and
628 	 * not just the MTD partition size because the maximum
629 	 * number of bad eraseblocks is a percentage of the
630 	 * whole device and bad eraseblocks are not fairly
631 	 * distributed over the flash chip. So the worst case
632 	 * is that all the bad eraseblocks of the chip are in
633 	 * the MTD partition we are attaching (ubi->mtd).
634 	 */
635 	device_size = mtd_get_device_size(ubi->mtd);
636 	device_pebs = mtd_div_by_eb(device_size, ubi->mtd);
637 	limit = mult_frac(device_pebs, max_beb_per1024, 1024);
638 
639 	/* Round it up */
640 	if (mult_frac(limit, 1024, max_beb_per1024) < device_pebs)
641 		limit += 1;
642 
643 	return limit;
644 }
645 
646 /**
647  * io_init - initialize I/O sub-system for a given UBI device.
648  * @ubi: UBI device description object
649  * @max_beb_per1024: maximum expected number of bad PEB per 1024 PEBs
650  *
651  * If @ubi->vid_hdr_offset or @ubi->leb_start is zero, default offsets are
652  * assumed:
653  *   o EC header is always at offset zero - this cannot be changed;
654  *   o VID header starts just after the EC header at the closest address
655  *     aligned to @io->hdrs_min_io_size;
656  *   o data starts just after the VID header at the closest address aligned to
657  *     @io->min_io_size
658  *
659  * This function returns zero in case of success and a negative error code in
660  * case of failure.
661  */
662 static int io_init(struct ubi_device *ubi, int max_beb_per1024)
663 {
664 	dbg_gen("sizeof(struct ubi_ainf_peb) %zu", sizeof(struct ubi_ainf_peb));
665 	dbg_gen("sizeof(struct ubi_wl_entry) %zu", sizeof(struct ubi_wl_entry));
666 
667 	if (ubi->mtd->numeraseregions != 0) {
668 		/*
669 		 * Some flashes have several erase regions. Different regions
670 		 * may have different eraseblock size and other
671 		 * characteristics. It looks like mostly multi-region flashes
672 		 * have one "main" region and one or more small regions to
673 		 * store boot loader code or boot parameters or whatever. I
674 		 * guess we should just pick the largest region. But this is
675 		 * not implemented.
676 		 */
677 		ubi_err("multiple regions, not implemented");
678 		return -EINVAL;
679 	}
680 
681 	if (ubi->vid_hdr_offset < 0)
682 		return -EINVAL;
683 
684 	/*
685 	 * Note, in this implementation we support MTD devices with 0x7FFFFFFF
686 	 * physical eraseblocks maximum.
687 	 */
688 
689 	ubi->peb_size   = ubi->mtd->erasesize;
690 	ubi->peb_count  = mtd_div_by_eb(ubi->mtd->size, ubi->mtd);
691 	ubi->flash_size = ubi->mtd->size;
692 
693 	if (mtd_can_have_bb(ubi->mtd)) {
694 		ubi->bad_allowed = 1;
695 		ubi->bad_peb_limit = get_bad_peb_limit(ubi, max_beb_per1024);
696 	}
697 
698 	if (ubi->mtd->type == MTD_NORFLASH) {
699 		ubi_assert(ubi->mtd->writesize == 1);
700 		ubi->nor_flash = 1;
701 	}
702 
703 	ubi->min_io_size = ubi->mtd->writesize;
704 	ubi->hdrs_min_io_size = ubi->mtd->writesize >> ubi->mtd->subpage_sft;
705 
706 	/*
707 	 * Make sure minimal I/O unit is power of 2. Note, there is no
708 	 * fundamental reason for this assumption. It is just an optimization
709 	 * which allows us to avoid costly division operations.
710 	 */
711 	if (!is_power_of_2(ubi->min_io_size)) {
712 		ubi_err("min. I/O unit (%d) is not power of 2",
713 			ubi->min_io_size);
714 		return -EINVAL;
715 	}
716 
717 	ubi_assert(ubi->hdrs_min_io_size > 0);
718 	ubi_assert(ubi->hdrs_min_io_size <= ubi->min_io_size);
719 	ubi_assert(ubi->min_io_size % ubi->hdrs_min_io_size == 0);
720 
721 	ubi->max_write_size = ubi->mtd->writebufsize;
722 	/*
723 	 * Maximum write size has to be greater or equivalent to min. I/O
724 	 * size, and be multiple of min. I/O size.
725 	 */
726 	if (ubi->max_write_size < ubi->min_io_size ||
727 	    ubi->max_write_size % ubi->min_io_size ||
728 	    !is_power_of_2(ubi->max_write_size)) {
729 		ubi_err("bad write buffer size %d for %d min. I/O unit",
730 			ubi->max_write_size, ubi->min_io_size);
731 		return -EINVAL;
732 	}
733 
734 	/* Calculate default aligned sizes of EC and VID headers */
735 	ubi->ec_hdr_alsize = ALIGN(UBI_EC_HDR_SIZE, ubi->hdrs_min_io_size);
736 	ubi->vid_hdr_alsize = ALIGN(UBI_VID_HDR_SIZE, ubi->hdrs_min_io_size);
737 
738 	dbg_gen("min_io_size      %d", ubi->min_io_size);
739 	dbg_gen("max_write_size   %d", ubi->max_write_size);
740 	dbg_gen("hdrs_min_io_size %d", ubi->hdrs_min_io_size);
741 	dbg_gen("ec_hdr_alsize    %d", ubi->ec_hdr_alsize);
742 	dbg_gen("vid_hdr_alsize   %d", ubi->vid_hdr_alsize);
743 
744 	if (ubi->vid_hdr_offset == 0)
745 		/* Default offset */
746 		ubi->vid_hdr_offset = ubi->vid_hdr_aloffset =
747 				      ubi->ec_hdr_alsize;
748 	else {
749 		ubi->vid_hdr_aloffset = ubi->vid_hdr_offset &
750 						~(ubi->hdrs_min_io_size - 1);
751 		ubi->vid_hdr_shift = ubi->vid_hdr_offset -
752 						ubi->vid_hdr_aloffset;
753 	}
754 
755 	/* Similar for the data offset */
756 	ubi->leb_start = ubi->vid_hdr_offset + UBI_VID_HDR_SIZE;
757 	ubi->leb_start = ALIGN(ubi->leb_start, ubi->min_io_size);
758 
759 	dbg_gen("vid_hdr_offset   %d", ubi->vid_hdr_offset);
760 	dbg_gen("vid_hdr_aloffset %d", ubi->vid_hdr_aloffset);
761 	dbg_gen("vid_hdr_shift    %d", ubi->vid_hdr_shift);
762 	dbg_gen("leb_start        %d", ubi->leb_start);
763 
764 	/* The shift must be aligned to 32-bit boundary */
765 	if (ubi->vid_hdr_shift % 4) {
766 		ubi_err("unaligned VID header shift %d",
767 			ubi->vid_hdr_shift);
768 		return -EINVAL;
769 	}
770 
771 	/* Check sanity */
772 	if (ubi->vid_hdr_offset < UBI_EC_HDR_SIZE ||
773 	    ubi->leb_start < ubi->vid_hdr_offset + UBI_VID_HDR_SIZE ||
774 	    ubi->leb_start > ubi->peb_size - UBI_VID_HDR_SIZE ||
775 	    ubi->leb_start & (ubi->min_io_size - 1)) {
776 		ubi_err("bad VID header (%d) or data offsets (%d)",
777 			ubi->vid_hdr_offset, ubi->leb_start);
778 		return -EINVAL;
779 	}
780 
781 	/*
782 	 * Set maximum amount of physical erroneous eraseblocks to be 10%.
783 	 * Erroneous PEB are those which have read errors.
784 	 */
785 	ubi->max_erroneous = ubi->peb_count / 10;
786 	if (ubi->max_erroneous < 16)
787 		ubi->max_erroneous = 16;
788 	dbg_gen("max_erroneous    %d", ubi->max_erroneous);
789 
790 	/*
791 	 * It may happen that EC and VID headers are situated in one minimal
792 	 * I/O unit. In this case we can only accept this UBI image in
793 	 * read-only mode.
794 	 */
795 	if (ubi->vid_hdr_offset + UBI_VID_HDR_SIZE <= ubi->hdrs_min_io_size) {
796 		ubi_warn("EC and VID headers are in the same minimal I/O unit, switch to read-only mode");
797 		ubi->ro_mode = 1;
798 	}
799 
800 	ubi->leb_size = ubi->peb_size - ubi->leb_start;
801 
802 	if (!(ubi->mtd->flags & MTD_WRITEABLE)) {
803 		ubi_msg("MTD device %d is write-protected, attach in read-only mode",
804 			ubi->mtd->index);
805 		ubi->ro_mode = 1;
806 	}
807 
808 	/*
809 	 * Note, ideally, we have to initialize @ubi->bad_peb_count here. But
810 	 * unfortunately, MTD does not provide this information. We should loop
811 	 * over all physical eraseblocks and invoke mtd->block_is_bad() for
812 	 * each physical eraseblock. So, we leave @ubi->bad_peb_count
813 	 * uninitialized so far.
814 	 */
815 
816 	return 0;
817 }
818 
819 /**
820  * autoresize - re-size the volume which has the "auto-resize" flag set.
821  * @ubi: UBI device description object
822  * @vol_id: ID of the volume to re-size
823  *
824  * This function re-sizes the volume marked by the %UBI_VTBL_AUTORESIZE_FLG in
825  * the volume table to the largest possible size. See comments in ubi-header.h
826  * for more description of the flag. Returns zero in case of success and a
827  * negative error code in case of failure.
828  */
829 static int autoresize(struct ubi_device *ubi, int vol_id)
830 {
831 	struct ubi_volume_desc desc;
832 	struct ubi_volume *vol = ubi->volumes[vol_id];
833 	int err, old_reserved_pebs = vol->reserved_pebs;
834 
835 	if (ubi->ro_mode) {
836 		ubi_warn("skip auto-resize because of R/O mode");
837 		return 0;
838 	}
839 
840 	/*
841 	 * Clear the auto-resize flag in the volume in-memory copy of the
842 	 * volume table, and 'ubi_resize_volume()' will propagate this change
843 	 * to the flash.
844 	 */
845 	ubi->vtbl[vol_id].flags &= ~UBI_VTBL_AUTORESIZE_FLG;
846 
847 	if (ubi->avail_pebs == 0) {
848 		struct ubi_vtbl_record vtbl_rec;
849 
850 		/*
851 		 * No available PEBs to re-size the volume, clear the flag on
852 		 * flash and exit.
853 		 */
854 		vtbl_rec = ubi->vtbl[vol_id];
855 		err = ubi_change_vtbl_record(ubi, vol_id, &vtbl_rec);
856 		if (err)
857 			ubi_err("cannot clean auto-resize flag for volume %d",
858 				vol_id);
859 	} else {
860 		desc.vol = vol;
861 		err = ubi_resize_volume(&desc,
862 					old_reserved_pebs + ubi->avail_pebs);
863 		if (err)
864 			ubi_err("cannot auto-resize volume %d", vol_id);
865 	}
866 
867 	if (err)
868 		return err;
869 
870 	ubi_msg("volume %d (\"%s\") re-sized from %d to %d LEBs", vol_id,
871 		vol->name, old_reserved_pebs, vol->reserved_pebs);
872 	return 0;
873 }
874 
875 /**
876  * ubi_attach_mtd_dev - attach an MTD device.
877  * @mtd: MTD device description object
878  * @ubi_num: number to assign to the new UBI device
879  * @vid_hdr_offset: VID header offset
880  * @max_beb_per1024: maximum expected number of bad PEB per 1024 PEBs
881  *
882  * This function attaches MTD device @mtd_dev to UBI and assign @ubi_num number
883  * to the newly created UBI device, unless @ubi_num is %UBI_DEV_NUM_AUTO, in
884  * which case this function finds a vacant device number and assigns it
885  * automatically. Returns the new UBI device number in case of success and a
886  * negative error code in case of failure.
887  *
888  * Note, the invocations of this function has to be serialized by the
889  * @ubi_devices_mutex.
890  */
891 int ubi_attach_mtd_dev(struct mtd_info *mtd, int ubi_num,
892 		       int vid_hdr_offset, int max_beb_per1024)
893 {
894 	struct ubi_device *ubi;
895 	int i, err, ref = 0;
896 
897 	if (max_beb_per1024 < 0 || max_beb_per1024 > MAX_MTD_UBI_BEB_LIMIT)
898 		return -EINVAL;
899 
900 	if (!max_beb_per1024)
901 		max_beb_per1024 = CONFIG_MTD_UBI_BEB_LIMIT;
902 
903 	/*
904 	 * Check if we already have the same MTD device attached.
905 	 *
906 	 * Note, this function assumes that UBI devices creations and deletions
907 	 * are serialized, so it does not take the &ubi_devices_lock.
908 	 */
909 	for (i = 0; i < UBI_MAX_DEVICES; i++) {
910 		ubi = ubi_devices[i];
911 		if (ubi && mtd->index == ubi->mtd->index) {
912 			ubi_err("mtd%d is already attached to ubi%d",
913 				mtd->index, i);
914 			return -EEXIST;
915 		}
916 	}
917 
918 	/*
919 	 * Make sure this MTD device is not emulated on top of an UBI volume
920 	 * already. Well, generally this recursion works fine, but there are
921 	 * different problems like the UBI module takes a reference to itself
922 	 * by attaching (and thus, opening) the emulated MTD device. This
923 	 * results in inability to unload the module. And in general it makes
924 	 * no sense to attach emulated MTD devices, so we prohibit this.
925 	 */
926 	if (mtd->type == MTD_UBIVOLUME) {
927 		ubi_err("refuse attaching mtd%d - it is already emulated on top of UBI",
928 			mtd->index);
929 		return -EINVAL;
930 	}
931 
932 	if (ubi_num == UBI_DEV_NUM_AUTO) {
933 		/* Search for an empty slot in the @ubi_devices array */
934 		for (ubi_num = 0; ubi_num < UBI_MAX_DEVICES; ubi_num++)
935 			if (!ubi_devices[ubi_num])
936 				break;
937 		if (ubi_num == UBI_MAX_DEVICES) {
938 			ubi_err("only %d UBI devices may be created",
939 				UBI_MAX_DEVICES);
940 			return -ENFILE;
941 		}
942 	} else {
943 		if (ubi_num >= UBI_MAX_DEVICES)
944 			return -EINVAL;
945 
946 		/* Make sure ubi_num is not busy */
947 		if (ubi_devices[ubi_num]) {
948 			ubi_err("ubi%d already exists", ubi_num);
949 			return -EEXIST;
950 		}
951 	}
952 
953 	ubi = kzalloc(sizeof(struct ubi_device), GFP_KERNEL);
954 	if (!ubi)
955 		return -ENOMEM;
956 
957 	ubi->mtd = mtd;
958 	ubi->ubi_num = ubi_num;
959 	ubi->vid_hdr_offset = vid_hdr_offset;
960 	ubi->autoresize_vol_id = -1;
961 
962 #ifdef CONFIG_MTD_UBI_FASTMAP
963 	ubi->fm_pool.used = ubi->fm_pool.size = 0;
964 	ubi->fm_wl_pool.used = ubi->fm_wl_pool.size = 0;
965 
966 	/*
967 	 * fm_pool.max_size is 5% of the total number of PEBs but it's also
968 	 * between UBI_FM_MAX_POOL_SIZE and UBI_FM_MIN_POOL_SIZE.
969 	 */
970 	ubi->fm_pool.max_size = min(((int)mtd_div_by_eb(ubi->mtd->size,
971 		ubi->mtd) / 100) * 5, UBI_FM_MAX_POOL_SIZE);
972 	if (ubi->fm_pool.max_size < UBI_FM_MIN_POOL_SIZE)
973 		ubi->fm_pool.max_size = UBI_FM_MIN_POOL_SIZE;
974 
975 	ubi->fm_wl_pool.max_size = UBI_FM_WL_POOL_SIZE;
976 	ubi->fm_disabled = !fm_autoconvert;
977 
978 	if (!ubi->fm_disabled && (int)mtd_div_by_eb(ubi->mtd->size, ubi->mtd)
979 	    <= UBI_FM_MAX_START) {
980 		ubi_err("More than %i PEBs are needed for fastmap, sorry.",
981 			UBI_FM_MAX_START);
982 		ubi->fm_disabled = 1;
983 	}
984 
985 	ubi_msg("default fastmap pool size: %d", ubi->fm_pool.max_size);
986 	ubi_msg("default fastmap WL pool size: %d", ubi->fm_wl_pool.max_size);
987 #else
988 	ubi->fm_disabled = 1;
989 #endif
990 	mutex_init(&ubi->buf_mutex);
991 	mutex_init(&ubi->ckvol_mutex);
992 	mutex_init(&ubi->device_mutex);
993 	spin_lock_init(&ubi->volumes_lock);
994 	mutex_init(&ubi->fm_mutex);
995 	init_rwsem(&ubi->fm_sem);
996 
997 	ubi_msg("attaching mtd%d to ubi%d", mtd->index, ubi_num);
998 
999 	err = io_init(ubi, max_beb_per1024);
1000 	if (err)
1001 		goto out_free;
1002 
1003 	err = -ENOMEM;
1004 	ubi->peb_buf = vmalloc(ubi->peb_size);
1005 	if (!ubi->peb_buf)
1006 		goto out_free;
1007 
1008 #ifdef CONFIG_MTD_UBI_FASTMAP
1009 	ubi->fm_size = ubi_calc_fm_size(ubi);
1010 	ubi->fm_buf = vzalloc(ubi->fm_size);
1011 	if (!ubi->fm_buf)
1012 		goto out_free;
1013 #endif
1014 	err = ubi_attach(ubi, 0);
1015 	if (err) {
1016 		ubi_err("failed to attach mtd%d, error %d", mtd->index, err);
1017 		goto out_free;
1018 	}
1019 
1020 	if (ubi->autoresize_vol_id != -1) {
1021 		err = autoresize(ubi, ubi->autoresize_vol_id);
1022 		if (err)
1023 			goto out_detach;
1024 	}
1025 
1026 	err = uif_init(ubi, &ref);
1027 	if (err)
1028 		goto out_detach;
1029 
1030 	err = ubi_debugfs_init_dev(ubi);
1031 	if (err)
1032 		goto out_uif;
1033 
1034 	ubi->bgt_thread = kthread_create(ubi_thread, ubi, "%s", ubi->bgt_name);
1035 	if (IS_ERR(ubi->bgt_thread)) {
1036 		err = PTR_ERR(ubi->bgt_thread);
1037 		ubi_err("cannot spawn \"%s\", error %d", ubi->bgt_name,
1038 			err);
1039 		goto out_debugfs;
1040 	}
1041 
1042 	ubi_msg("attached mtd%d (name \"%s\", size %llu MiB) to ubi%d",
1043 		mtd->index, mtd->name, ubi->flash_size >> 20, ubi_num);
1044 	ubi_msg("PEB size: %d bytes (%d KiB), LEB size: %d bytes",
1045 		ubi->peb_size, ubi->peb_size >> 10, ubi->leb_size);
1046 	ubi_msg("min./max. I/O unit sizes: %d/%d, sub-page size %d",
1047 		ubi->min_io_size, ubi->max_write_size, ubi->hdrs_min_io_size);
1048 	ubi_msg("VID header offset: %d (aligned %d), data offset: %d",
1049 		ubi->vid_hdr_offset, ubi->vid_hdr_aloffset, ubi->leb_start);
1050 	ubi_msg("good PEBs: %d, bad PEBs: %d, corrupted PEBs: %d",
1051 		ubi->good_peb_count, ubi->bad_peb_count, ubi->corr_peb_count);
1052 	ubi_msg("user volume: %d, internal volumes: %d, max. volumes count: %d",
1053 		ubi->vol_count - UBI_INT_VOL_COUNT, UBI_INT_VOL_COUNT,
1054 		ubi->vtbl_slots);
1055 	ubi_msg("max/mean erase counter: %d/%d, WL threshold: %d, image sequence number: %u",
1056 		ubi->max_ec, ubi->mean_ec, CONFIG_MTD_UBI_WL_THRESHOLD,
1057 		ubi->image_seq);
1058 	ubi_msg("available PEBs: %d, total reserved PEBs: %d, PEBs reserved for bad PEB handling: %d",
1059 		ubi->avail_pebs, ubi->rsvd_pebs, ubi->beb_rsvd_pebs);
1060 
1061 	/*
1062 	 * The below lock makes sure we do not race with 'ubi_thread()' which
1063 	 * checks @ubi->thread_enabled. Otherwise we may fail to wake it up.
1064 	 */
1065 	spin_lock(&ubi->wl_lock);
1066 	ubi->thread_enabled = 1;
1067 	wake_up_process(ubi->bgt_thread);
1068 	spin_unlock(&ubi->wl_lock);
1069 
1070 	ubi_devices[ubi_num] = ubi;
1071 	ubi_notify_all(ubi, UBI_VOLUME_ADDED, NULL);
1072 	return ubi_num;
1073 
1074 out_debugfs:
1075 	ubi_debugfs_exit_dev(ubi);
1076 out_uif:
1077 	get_device(&ubi->dev);
1078 	ubi_assert(ref);
1079 	uif_close(ubi);
1080 out_detach:
1081 	ubi_wl_close(ubi);
1082 	ubi_free_internal_volumes(ubi);
1083 	vfree(ubi->vtbl);
1084 out_free:
1085 	vfree(ubi->peb_buf);
1086 	vfree(ubi->fm_buf);
1087 	if (ref)
1088 		put_device(&ubi->dev);
1089 	else
1090 		kfree(ubi);
1091 	return err;
1092 }
1093 
1094 /**
1095  * ubi_detach_mtd_dev - detach an MTD device.
1096  * @ubi_num: UBI device number to detach from
1097  * @anyway: detach MTD even if device reference count is not zero
1098  *
1099  * This function destroys an UBI device number @ubi_num and detaches the
1100  * underlying MTD device. Returns zero in case of success and %-EBUSY if the
1101  * UBI device is busy and cannot be destroyed, and %-EINVAL if it does not
1102  * exist.
1103  *
1104  * Note, the invocations of this function has to be serialized by the
1105  * @ubi_devices_mutex.
1106  */
1107 int ubi_detach_mtd_dev(int ubi_num, int anyway)
1108 {
1109 	struct ubi_device *ubi;
1110 
1111 	if (ubi_num < 0 || ubi_num >= UBI_MAX_DEVICES)
1112 		return -EINVAL;
1113 
1114 	ubi = ubi_get_device(ubi_num);
1115 	if (!ubi)
1116 		return -EINVAL;
1117 
1118 	spin_lock(&ubi_devices_lock);
1119 	put_device(&ubi->dev);
1120 	ubi->ref_count -= 1;
1121 	if (ubi->ref_count) {
1122 		if (!anyway) {
1123 			spin_unlock(&ubi_devices_lock);
1124 			return -EBUSY;
1125 		}
1126 		/* This may only happen if there is a bug */
1127 		ubi_err("%s reference count %d, destroy anyway",
1128 			ubi->ubi_name, ubi->ref_count);
1129 	}
1130 	ubi_devices[ubi_num] = NULL;
1131 	spin_unlock(&ubi_devices_lock);
1132 
1133 	ubi_assert(ubi_num == ubi->ubi_num);
1134 	ubi_notify_all(ubi, UBI_VOLUME_REMOVED, NULL);
1135 	ubi_msg("detaching mtd%d from ubi%d", ubi->mtd->index, ubi_num);
1136 #ifdef CONFIG_MTD_UBI_FASTMAP
1137 	/* If we don't write a new fastmap at detach time we lose all
1138 	 * EC updates that have been made since the last written fastmap. */
1139 	ubi_update_fastmap(ubi);
1140 #endif
1141 	/*
1142 	 * Before freeing anything, we have to stop the background thread to
1143 	 * prevent it from doing anything on this device while we are freeing.
1144 	 */
1145 	if (ubi->bgt_thread)
1146 		kthread_stop(ubi->bgt_thread);
1147 
1148 	/*
1149 	 * Get a reference to the device in order to prevent 'dev_release()'
1150 	 * from freeing the @ubi object.
1151 	 */
1152 	get_device(&ubi->dev);
1153 
1154 	ubi_debugfs_exit_dev(ubi);
1155 	uif_close(ubi);
1156 
1157 	ubi_wl_close(ubi);
1158 	ubi_free_internal_volumes(ubi);
1159 	vfree(ubi->vtbl);
1160 	put_mtd_device(ubi->mtd);
1161 	vfree(ubi->peb_buf);
1162 	vfree(ubi->fm_buf);
1163 	ubi_msg("mtd%d is detached from ubi%d", ubi->mtd->index, ubi->ubi_num);
1164 	put_device(&ubi->dev);
1165 	return 0;
1166 }
1167 
1168 #ifndef __UBOOT__
1169 /**
1170  * open_mtd_by_chdev - open an MTD device by its character device node path.
1171  * @mtd_dev: MTD character device node path
1172  *
1173  * This helper function opens an MTD device by its character node device path.
1174  * Returns MTD device description object in case of success and a negative
1175  * error code in case of failure.
1176  */
1177 static struct mtd_info * __init open_mtd_by_chdev(const char *mtd_dev)
1178 {
1179 	int err, major, minor, mode;
1180 	struct path path;
1181 
1182 	/* Probably this is an MTD character device node path */
1183 	err = kern_path(mtd_dev, LOOKUP_FOLLOW, &path);
1184 	if (err)
1185 		return ERR_PTR(err);
1186 
1187 	/* MTD device number is defined by the major / minor numbers */
1188 	major = imajor(path.dentry->d_inode);
1189 	minor = iminor(path.dentry->d_inode);
1190 	mode = path.dentry->d_inode->i_mode;
1191 	path_put(&path);
1192 	if (major != MTD_CHAR_MAJOR || !S_ISCHR(mode))
1193 		return ERR_PTR(-EINVAL);
1194 
1195 	if (minor & 1)
1196 		/*
1197 		 * Just do not think the "/dev/mtdrX" devices support is need,
1198 		 * so do not support them to avoid doing extra work.
1199 		 */
1200 		return ERR_PTR(-EINVAL);
1201 
1202 	return get_mtd_device(NULL, minor / 2);
1203 }
1204 #endif
1205 
1206 /**
1207  * open_mtd_device - open MTD device by name, character device path, or number.
1208  * @mtd_dev: name, character device node path, or MTD device device number
1209  *
1210  * This function tries to open and MTD device described by @mtd_dev string,
1211  * which is first treated as ASCII MTD device number, and if it is not true, it
1212  * is treated as MTD device name, and if that is also not true, it is treated
1213  * as MTD character device node path. Returns MTD device description object in
1214  * case of success and a negative error code in case of failure.
1215  */
1216 static struct mtd_info * __init open_mtd_device(const char *mtd_dev)
1217 {
1218 	struct mtd_info *mtd;
1219 	int mtd_num;
1220 	char *endp;
1221 
1222 	mtd_num = simple_strtoul(mtd_dev, &endp, 0);
1223 	if (*endp != '\0' || mtd_dev == endp) {
1224 		/*
1225 		 * This does not look like an ASCII integer, probably this is
1226 		 * MTD device name.
1227 		 */
1228 		mtd = get_mtd_device_nm(mtd_dev);
1229 #ifndef __UBOOT__
1230 		if (IS_ERR(mtd) && PTR_ERR(mtd) == -ENODEV)
1231 			/* Probably this is an MTD character device node path */
1232 			mtd = open_mtd_by_chdev(mtd_dev);
1233 #endif
1234 	} else
1235 		mtd = get_mtd_device(NULL, mtd_num);
1236 
1237 	return mtd;
1238 }
1239 
1240 #ifndef __UBOOT__
1241 static int __init ubi_init(void)
1242 #else
1243 int ubi_init(void)
1244 #endif
1245 {
1246 	int err, i, k;
1247 
1248 	/* Ensure that EC and VID headers have correct size */
1249 	BUILD_BUG_ON(sizeof(struct ubi_ec_hdr) != 64);
1250 	BUILD_BUG_ON(sizeof(struct ubi_vid_hdr) != 64);
1251 
1252 	if (mtd_devs > UBI_MAX_DEVICES) {
1253 		ubi_err("too many MTD devices, maximum is %d", UBI_MAX_DEVICES);
1254 		return -EINVAL;
1255 	}
1256 
1257 	/* Create base sysfs directory and sysfs files */
1258 	ubi_class = class_create(THIS_MODULE, UBI_NAME_STR);
1259 	if (IS_ERR(ubi_class)) {
1260 		err = PTR_ERR(ubi_class);
1261 		ubi_err("cannot create UBI class");
1262 		goto out;
1263 	}
1264 
1265 	err = class_create_file(ubi_class, &ubi_version);
1266 	if (err) {
1267 		ubi_err("cannot create sysfs file");
1268 		goto out_class;
1269 	}
1270 
1271 	err = misc_register(&ubi_ctrl_cdev);
1272 	if (err) {
1273 		ubi_err("cannot register device");
1274 		goto out_version;
1275 	}
1276 
1277 	ubi_wl_entry_slab = kmem_cache_create("ubi_wl_entry_slab",
1278 					      sizeof(struct ubi_wl_entry),
1279 					      0, 0, NULL);
1280 	if (!ubi_wl_entry_slab) {
1281 		err = -ENOMEM;
1282 		goto out_dev_unreg;
1283 	}
1284 
1285 	err = ubi_debugfs_init();
1286 	if (err)
1287 		goto out_slab;
1288 
1289 
1290 	/* Attach MTD devices */
1291 	for (i = 0; i < mtd_devs; i++) {
1292 		struct mtd_dev_param *p = &mtd_dev_param[i];
1293 		struct mtd_info *mtd;
1294 
1295 		cond_resched();
1296 
1297 		mtd = open_mtd_device(p->name);
1298 		if (IS_ERR(mtd)) {
1299 			err = PTR_ERR(mtd);
1300 			ubi_err("cannot open mtd %s, error %d", p->name, err);
1301 			/* See comment below re-ubi_is_module(). */
1302 			if (ubi_is_module())
1303 				goto out_detach;
1304 			continue;
1305 		}
1306 
1307 		mutex_lock(&ubi_devices_mutex);
1308 		err = ubi_attach_mtd_dev(mtd, p->ubi_num,
1309 					 p->vid_hdr_offs, p->max_beb_per1024);
1310 		mutex_unlock(&ubi_devices_mutex);
1311 		if (err < 0) {
1312 			ubi_err("cannot attach mtd%d", mtd->index);
1313 			put_mtd_device(mtd);
1314 
1315 			/*
1316 			 * Originally UBI stopped initializing on any error.
1317 			 * However, later on it was found out that this
1318 			 * behavior is not very good when UBI is compiled into
1319 			 * the kernel and the MTD devices to attach are passed
1320 			 * through the command line. Indeed, UBI failure
1321 			 * stopped whole boot sequence.
1322 			 *
1323 			 * To fix this, we changed the behavior for the
1324 			 * non-module case, but preserved the old behavior for
1325 			 * the module case, just for compatibility. This is a
1326 			 * little inconsistent, though.
1327 			 */
1328 			if (ubi_is_module())
1329 				goto out_detach;
1330 		}
1331 	}
1332 
1333 	err = ubiblock_init();
1334 	if (err) {
1335 		ubi_err("block: cannot initialize, error %d", err);
1336 
1337 		/* See comment above re-ubi_is_module(). */
1338 		if (ubi_is_module())
1339 			goto out_detach;
1340 	}
1341 
1342 	return 0;
1343 
1344 out_detach:
1345 	for (k = 0; k < i; k++)
1346 		if (ubi_devices[k]) {
1347 			mutex_lock(&ubi_devices_mutex);
1348 			ubi_detach_mtd_dev(ubi_devices[k]->ubi_num, 1);
1349 			mutex_unlock(&ubi_devices_mutex);
1350 		}
1351 	ubi_debugfs_exit();
1352 out_slab:
1353 	kmem_cache_destroy(ubi_wl_entry_slab);
1354 out_dev_unreg:
1355 	misc_deregister(&ubi_ctrl_cdev);
1356 out_version:
1357 	class_remove_file(ubi_class, &ubi_version);
1358 out_class:
1359 	class_destroy(ubi_class);
1360 out:
1361 #ifdef __UBOOT__
1362 	/* Reset any globals that the driver depends on being zeroed */
1363 	mtd_devs = 0;
1364 #endif
1365 	ubi_err("cannot initialize UBI, error %d", err);
1366 	return err;
1367 }
1368 late_initcall(ubi_init);
1369 
1370 #ifndef __UBOOT__
1371 static void __exit ubi_exit(void)
1372 #else
1373 void ubi_exit(void)
1374 #endif
1375 {
1376 	int i;
1377 
1378 	ubiblock_exit();
1379 
1380 	for (i = 0; i < UBI_MAX_DEVICES; i++)
1381 		if (ubi_devices[i]) {
1382 			mutex_lock(&ubi_devices_mutex);
1383 			ubi_detach_mtd_dev(ubi_devices[i]->ubi_num, 1);
1384 			mutex_unlock(&ubi_devices_mutex);
1385 		}
1386 	ubi_debugfs_exit();
1387 	kmem_cache_destroy(ubi_wl_entry_slab);
1388 	misc_deregister(&ubi_ctrl_cdev);
1389 	class_remove_file(ubi_class, &ubi_version);
1390 	class_destroy(ubi_class);
1391 #ifdef __UBOOT__
1392 	/* Reset any globals that the driver depends on being zeroed */
1393 	mtd_devs = 0;
1394 #endif
1395 }
1396 module_exit(ubi_exit);
1397 
1398 /**
1399  * bytes_str_to_int - convert a number of bytes string into an integer.
1400  * @str: the string to convert
1401  *
1402  * This function returns positive resulting integer in case of success and a
1403  * negative error code in case of failure.
1404  */
1405 static int __init bytes_str_to_int(const char *str)
1406 {
1407 	char *endp;
1408 	unsigned long result;
1409 
1410 	result = simple_strtoul(str, &endp, 0);
1411 	if (str == endp || result >= INT_MAX) {
1412 		ubi_err("incorrect bytes count: \"%s\"\n", str);
1413 		return -EINVAL;
1414 	}
1415 
1416 	switch (*endp) {
1417 	case 'G':
1418 		result *= 1024;
1419 	case 'M':
1420 		result *= 1024;
1421 	case 'K':
1422 		result *= 1024;
1423 		if (endp[1] == 'i' && endp[2] == 'B')
1424 			endp += 2;
1425 	case '\0':
1426 		break;
1427 	default:
1428 		ubi_err("incorrect bytes count: \"%s\"\n", str);
1429 		return -EINVAL;
1430 	}
1431 
1432 	return result;
1433 }
1434 
1435 int kstrtoint(const char *s, unsigned int base, int *res)
1436 {
1437 	unsigned long long tmp;
1438 
1439 	tmp = simple_strtoull(s, NULL, base);
1440 	if (tmp != (unsigned long long)(int)tmp)
1441 		return -ERANGE;
1442 
1443 	return (int)tmp;
1444 }
1445 
1446 /**
1447  * ubi_mtd_param_parse - parse the 'mtd=' UBI parameter.
1448  * @val: the parameter value to parse
1449  * @kp: not used
1450  *
1451  * This function returns zero in case of success and a negative error code in
1452  * case of error.
1453  */
1454 #ifndef __UBOOT__
1455 static int __init ubi_mtd_param_parse(const char *val, struct kernel_param *kp)
1456 #else
1457 int ubi_mtd_param_parse(const char *val, struct kernel_param *kp)
1458 #endif
1459 {
1460 	int i, len;
1461 	struct mtd_dev_param *p;
1462 	char buf[MTD_PARAM_LEN_MAX];
1463 	char *pbuf = &buf[0];
1464 	char *tokens[MTD_PARAM_MAX_COUNT], *token;
1465 
1466 	if (!val)
1467 		return -EINVAL;
1468 
1469 	if (mtd_devs == UBI_MAX_DEVICES) {
1470 		ubi_err("too many parameters, max. is %d\n",
1471 			UBI_MAX_DEVICES);
1472 		return -EINVAL;
1473 	}
1474 
1475 	len = strnlen(val, MTD_PARAM_LEN_MAX);
1476 	if (len == MTD_PARAM_LEN_MAX) {
1477 		ubi_err("parameter \"%s\" is too long, max. is %d\n",
1478 			val, MTD_PARAM_LEN_MAX);
1479 		return -EINVAL;
1480 	}
1481 
1482 	if (len == 0) {
1483 		pr_warn("UBI warning: empty 'mtd=' parameter - ignored\n");
1484 		return 0;
1485 	}
1486 
1487 	strcpy(buf, val);
1488 
1489 	/* Get rid of the final newline */
1490 	if (buf[len - 1] == '\n')
1491 		buf[len - 1] = '\0';
1492 
1493 	for (i = 0; i < MTD_PARAM_MAX_COUNT; i++)
1494 		tokens[i] = strsep(&pbuf, ",");
1495 
1496 	if (pbuf) {
1497 		ubi_err("too many arguments at \"%s\"\n", val);
1498 		return -EINVAL;
1499 	}
1500 
1501 	p = &mtd_dev_param[mtd_devs];
1502 	strcpy(&p->name[0], tokens[0]);
1503 
1504 	token = tokens[1];
1505 	if (token) {
1506 		p->vid_hdr_offs = bytes_str_to_int(token);
1507 
1508 		if (p->vid_hdr_offs < 0)
1509 			return p->vid_hdr_offs;
1510 	}
1511 
1512 	token = tokens[2];
1513 	if (token) {
1514 		int err = kstrtoint(token, 10, &p->max_beb_per1024);
1515 
1516 		if (err) {
1517 			ubi_err("bad value for max_beb_per1024 parameter: %s",
1518 				token);
1519 			return -EINVAL;
1520 		}
1521 	}
1522 
1523 	token = tokens[3];
1524 	if (token) {
1525 		int err = kstrtoint(token, 10, &p->ubi_num);
1526 
1527 		if (err) {
1528 			ubi_err("bad value for ubi_num parameter: %s", token);
1529 			return -EINVAL;
1530 		}
1531 	} else
1532 		p->ubi_num = UBI_DEV_NUM_AUTO;
1533 
1534 	mtd_devs += 1;
1535 	return 0;
1536 }
1537 
1538 module_param_call(mtd, ubi_mtd_param_parse, NULL, NULL, 000);
1539 MODULE_PARM_DESC(mtd, "MTD devices to attach. Parameter format: mtd=<name|num|path>[,<vid_hdr_offs>[,max_beb_per1024[,ubi_num]]].\n"
1540 		      "Multiple \"mtd\" parameters may be specified.\n"
1541 		      "MTD devices may be specified by their number, name, or path to the MTD character device node.\n"
1542 		      "Optional \"vid_hdr_offs\" parameter specifies UBI VID header position to be used by UBI. (default value if 0)\n"
1543 		      "Optional \"max_beb_per1024\" parameter specifies the maximum expected bad eraseblock per 1024 eraseblocks. (default value ("
1544 		      __stringify(CONFIG_MTD_UBI_BEB_LIMIT) ") if 0)\n"
1545 		      "Optional \"ubi_num\" parameter specifies UBI device number which have to be assigned to the newly created UBI device (assigned automatically by default)\n"
1546 		      "\n"
1547 		      "Example 1: mtd=/dev/mtd0 - attach MTD device /dev/mtd0.\n"
1548 		      "Example 2: mtd=content,1984 mtd=4 - attach MTD device with name \"content\" using VID header offset 1984, and MTD device number 4 with default VID header offset.\n"
1549 		      "Example 3: mtd=/dev/mtd1,0,25 - attach MTD device /dev/mtd1 using default VID header offset and reserve 25*nand_size_in_blocks/1024 erase blocks for bad block handling.\n"
1550 		      "Example 4: mtd=/dev/mtd1,0,0,5 - attach MTD device /dev/mtd1 to UBI 5 and using default values for the other fields.\n"
1551 		      "\t(e.g. if the NAND *chipset* has 4096 PEB, 100 will be reserved for this UBI device).");
1552 #ifdef CONFIG_MTD_UBI_FASTMAP
1553 module_param(fm_autoconvert, bool, 0644);
1554 MODULE_PARM_DESC(fm_autoconvert, "Set this parameter to enable fastmap automatically on images without a fastmap.");
1555 #endif
1556 MODULE_VERSION(__stringify(UBI_VERSION));
1557 MODULE_DESCRIPTION("UBI - Unsorted Block Images");
1558 MODULE_AUTHOR("Artem Bityutskiy");
1559 MODULE_LICENSE("GPL");
1560