OSDN Git Service

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