UBI: add UBI devices reference counting
[pandora-kernel.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  * At the moment we only attach UBI devices by scanning, which will become a
32  * bottleneck when flashes reach certain large size. Then one may improve UBI
33  * and add other methods, although it does not seem to be easy to do.
34  */
35
36 #include <linux/err.h>
37 #include <linux/module.h>
38 #include <linux/moduleparam.h>
39 #include <linux/stringify.h>
40 #include <linux/stat.h>
41 #include <linux/miscdevice.h>
42 #include <linux/log2.h>
43 #include "ubi.h"
44
45 /* Maximum length of the 'mtd=' parameter */
46 #define MTD_PARAM_LEN_MAX 64
47
48 /**
49  * struct mtd_dev_param - MTD device parameter description data structure.
50  * @name: MTD device name or number string
51  * @vid_hdr_offs: VID header offset
52  * @data_offs: data offset
53  */
54 struct mtd_dev_param
55 {
56         char name[MTD_PARAM_LEN_MAX];
57         int vid_hdr_offs;
58         int data_offs;
59 };
60
61 /* Numbers of elements set in the @mtd_dev_param array */
62 static int mtd_devs = 0;
63
64 /* MTD devices specification parameters */
65 static struct mtd_dev_param mtd_dev_param[UBI_MAX_DEVICES];
66
67 /* Root UBI "class" object (corresponds to '/<sysfs>/class/ubi/') */
68 struct class *ubi_class;
69
70 /* Slab cache for lock-tree entries */
71 struct kmem_cache *ubi_ltree_slab;
72
73 /* Slab cache for wear-leveling entries */
74 struct kmem_cache *ubi_wl_entry_slab;
75
76 /* UBI control character device */
77 static struct miscdevice ubi_ctrl_cdev = {
78         .minor = MISC_DYNAMIC_MINOR,
79         .name = "ubi_ctrl",
80         .fops = &ubi_ctrl_cdev_operations,
81 };
82
83 /* All UBI devices in system */
84 static struct ubi_device *ubi_devices[UBI_MAX_DEVICES];
85
86 /* Protects @ubi_devices and @ubi->ref_count */
87 static DEFINE_SPINLOCK(ubi_devices_lock);
88
89 /* "Show" method for files in '/<sysfs>/class/ubi/' */
90 static ssize_t ubi_version_show(struct class *class, char *buf)
91 {
92         return sprintf(buf, "%d\n", UBI_VERSION);
93 }
94
95 /* UBI version attribute ('/<sysfs>/class/ubi/version') */
96 static struct class_attribute ubi_version =
97         __ATTR(version, S_IRUGO, ubi_version_show, NULL);
98
99 static ssize_t dev_attribute_show(struct device *dev,
100                                   struct device_attribute *attr, char *buf);
101
102 /* UBI device attributes (correspond to files in '/<sysfs>/class/ubi/ubiX') */
103 static struct device_attribute dev_eraseblock_size =
104         __ATTR(eraseblock_size, S_IRUGO, dev_attribute_show, NULL);
105 static struct device_attribute dev_avail_eraseblocks =
106         __ATTR(avail_eraseblocks, S_IRUGO, dev_attribute_show, NULL);
107 static struct device_attribute dev_total_eraseblocks =
108         __ATTR(total_eraseblocks, S_IRUGO, dev_attribute_show, NULL);
109 static struct device_attribute dev_volumes_count =
110         __ATTR(volumes_count, S_IRUGO, dev_attribute_show, NULL);
111 static struct device_attribute dev_max_ec =
112         __ATTR(max_ec, S_IRUGO, dev_attribute_show, NULL);
113 static struct device_attribute dev_reserved_for_bad =
114         __ATTR(reserved_for_bad, S_IRUGO, dev_attribute_show, NULL);
115 static struct device_attribute dev_bad_peb_count =
116         __ATTR(bad_peb_count, S_IRUGO, dev_attribute_show, NULL);
117 static struct device_attribute dev_max_vol_count =
118         __ATTR(max_vol_count, S_IRUGO, dev_attribute_show, NULL);
119 static struct device_attribute dev_min_io_size =
120         __ATTR(min_io_size, S_IRUGO, dev_attribute_show, NULL);
121 static struct device_attribute dev_bgt_enabled =
122         __ATTR(bgt_enabled, S_IRUGO, dev_attribute_show, NULL);
123
124 /**
125  * ubi_get_device - get UBI device.
126  * @ubi_num: UBI device number
127  *
128  * This function returns UBI device description object for UBI device number
129  * @ubi_num, or %NULL if the device does not exist. This function increases the
130  * device reference count to prevent removal of the device. In other words, the
131  * device cannot be removed if its reference count is not zero.
132  */
133 struct ubi_device *ubi_get_device(int ubi_num)
134 {
135         struct ubi_device *ubi;
136
137         spin_lock(&ubi_devices_lock);
138         ubi = ubi_devices[ubi_num];
139         if (ubi) {
140                 ubi_assert(ubi->ref_count >= 0);
141                 ubi->ref_count += 1;
142                 get_device(&ubi->dev);
143         }
144         spin_unlock(&ubi_devices_lock);
145
146         return ubi;
147 }
148
149 /**
150  * ubi_put_device - drop an UBI device reference.
151  * @ubi: UBI device description object
152  */
153 void ubi_put_device(struct ubi_device *ubi)
154 {
155         spin_lock(&ubi_devices_lock);
156         ubi->ref_count -= 1;
157         put_device(&ubi->dev);
158         spin_unlock(&ubi_devices_lock);
159 }
160
161 /**
162  * ubi_get_by_major - get UBI device description object by character device
163  *                    major number.
164  * @major: major number
165  *
166  * This function is similar to 'ubi_get_device()', but it searches the device
167  * by its major number.
168  */
169 struct ubi_device *ubi_get_by_major(int major)
170 {
171         int i;
172         struct ubi_device *ubi;
173
174         spin_lock(&ubi_devices_lock);
175         for (i = 0; i < UBI_MAX_DEVICES; i++) {
176                 ubi = ubi_devices[i];
177                 if (ubi && MAJOR(ubi->cdev.dev) == major) {
178                         ubi_assert(ubi->ref_count >= 0);
179                         ubi->ref_count += 1;
180                         get_device(&ubi->dev);
181                         spin_unlock(&ubi_devices_lock);
182                         return ubi;
183                 }
184         }
185         spin_unlock(&ubi_devices_lock);
186
187         return NULL;
188 }
189
190 /**
191  * ubi_major2num - get UBI device number by character device major number.
192  * @major: major number
193  *
194  * This function searches UBI device number object by its major number. If UBI
195  * device was not found, this function returns -ENODEV, othewise the UBI device
196  * number is returned.
197  */
198 int ubi_major2num(int major)
199 {
200         int i, ubi_num = -ENODEV;
201
202         spin_lock(&ubi_devices_lock);
203         for (i = 0; i < UBI_MAX_DEVICES; i++) {
204                 struct ubi_device *ubi = ubi_devices[i];
205
206                 if (ubi && MAJOR(ubi->cdev.dev) == major) {
207                         ubi_num = ubi->ubi_num;
208                         break;
209                 }
210         }
211         spin_unlock(&ubi_devices_lock);
212
213         return ubi_num;
214 }
215
216 /* "Show" method for files in '/<sysfs>/class/ubi/ubiX/' */
217 static ssize_t dev_attribute_show(struct device *dev,
218                                   struct device_attribute *attr, char *buf)
219 {
220         ssize_t ret;
221         struct ubi_device *ubi;
222
223         /*
224          * The below code looks weird, but it actually makes sense. We get the
225          * UBI device reference from the contained 'struct ubi_device'. But it
226          * is unclear if the device was removed or not yet. Indeed, if the
227          * device was removed before we increased its reference count,
228          * 'ubi_get_device()' will return -ENODEV and we fail.
229          *
230          * Remember, 'struct ubi_device' is freed in the release function, so
231          * we still can use 'ubi->ubi_num'.
232          */
233         ubi = container_of(dev, struct ubi_device, dev);
234         ubi = ubi_get_device(ubi->ubi_num);
235         if (!ubi)
236                 return -ENODEV;
237
238         if (attr == &dev_eraseblock_size)
239                 ret = sprintf(buf, "%d\n", ubi->leb_size);
240         else if (attr == &dev_avail_eraseblocks)
241                 ret = sprintf(buf, "%d\n", ubi->avail_pebs);
242         else if (attr == &dev_total_eraseblocks)
243                 ret = sprintf(buf, "%d\n", ubi->good_peb_count);
244         else if (attr == &dev_volumes_count)
245                 ret = sprintf(buf, "%d\n", ubi->vol_count);
246         else if (attr == &dev_max_ec)
247                 ret = sprintf(buf, "%d\n", ubi->max_ec);
248         else if (attr == &dev_reserved_for_bad)
249                 ret = sprintf(buf, "%d\n", ubi->beb_rsvd_pebs);
250         else if (attr == &dev_bad_peb_count)
251                 ret = sprintf(buf, "%d\n", ubi->bad_peb_count);
252         else if (attr == &dev_max_vol_count)
253                 ret = sprintf(buf, "%d\n", ubi->vtbl_slots);
254         else if (attr == &dev_min_io_size)
255                 ret = sprintf(buf, "%d\n", ubi->min_io_size);
256         else if (attr == &dev_bgt_enabled)
257                 ret = sprintf(buf, "%d\n", ubi->thread_enabled);
258         else
259                 BUG();
260
261         ubi_put_device(ubi);
262         return ret;
263 }
264
265 /* Fake "release" method for UBI devices */
266 static void dev_release(struct device *dev) { }
267
268 /**
269  * ubi_sysfs_init - initialize sysfs for an UBI device.
270  * @ubi: UBI device description object
271  *
272  * This function returns zero in case of success and a negative error code in
273  * case of failure.
274  */
275 static int ubi_sysfs_init(struct ubi_device *ubi)
276 {
277         int err;
278
279         ubi->dev.release = dev_release;
280         ubi->dev.devt = ubi->cdev.dev;
281         ubi->dev.class = ubi_class;
282         sprintf(&ubi->dev.bus_id[0], UBI_NAME_STR"%d", ubi->ubi_num);
283         err = device_register(&ubi->dev);
284         if (err)
285                 return err;
286
287         err = device_create_file(&ubi->dev, &dev_eraseblock_size);
288         if (err)
289                 return err;
290         err = device_create_file(&ubi->dev, &dev_avail_eraseblocks);
291         if (err)
292                 return err;
293         err = device_create_file(&ubi->dev, &dev_total_eraseblocks);
294         if (err)
295                 return err;
296         err = device_create_file(&ubi->dev, &dev_volumes_count);
297         if (err)
298                 return err;
299         err = device_create_file(&ubi->dev, &dev_max_ec);
300         if (err)
301                 return err;
302         err = device_create_file(&ubi->dev, &dev_reserved_for_bad);
303         if (err)
304                 return err;
305         err = device_create_file(&ubi->dev, &dev_bad_peb_count);
306         if (err)
307                 return err;
308         err = device_create_file(&ubi->dev, &dev_max_vol_count);
309         if (err)
310                 return err;
311         err = device_create_file(&ubi->dev, &dev_min_io_size);
312         if (err)
313                 return err;
314         err = device_create_file(&ubi->dev, &dev_bgt_enabled);
315         return err;
316 }
317
318 /**
319  * ubi_sysfs_close - close sysfs for an UBI device.
320  * @ubi: UBI device description object
321  */
322 static void ubi_sysfs_close(struct ubi_device *ubi)
323 {
324         device_remove_file(&ubi->dev, &dev_bgt_enabled);
325         device_remove_file(&ubi->dev, &dev_min_io_size);
326         device_remove_file(&ubi->dev, &dev_max_vol_count);
327         device_remove_file(&ubi->dev, &dev_bad_peb_count);
328         device_remove_file(&ubi->dev, &dev_reserved_for_bad);
329         device_remove_file(&ubi->dev, &dev_max_ec);
330         device_remove_file(&ubi->dev, &dev_volumes_count);
331         device_remove_file(&ubi->dev, &dev_total_eraseblocks);
332         device_remove_file(&ubi->dev, &dev_avail_eraseblocks);
333         device_remove_file(&ubi->dev, &dev_eraseblock_size);
334         device_unregister(&ubi->dev);
335 }
336
337 /**
338  * kill_volumes - destroy all volumes.
339  * @ubi: UBI device description object
340  */
341 static void kill_volumes(struct ubi_device *ubi)
342 {
343         int i;
344
345         for (i = 0; i < ubi->vtbl_slots; i++)
346                 if (ubi->volumes[i])
347                         ubi_free_volume(ubi, ubi->volumes[i]);
348 }
349
350 /**
351  * uif_init - initialize user interfaces for an UBI device.
352  * @ubi: UBI device description object
353  *
354  * This function returns zero in case of success and a negative error code in
355  * case of failure.
356  */
357 static int uif_init(struct ubi_device *ubi)
358 {
359         int i, err;
360         dev_t dev;
361
362         mutex_init(&ubi->volumes_mutex);
363         spin_lock_init(&ubi->volumes_lock);
364
365         sprintf(ubi->ubi_name, UBI_NAME_STR "%d", ubi->ubi_num);
366
367         /*
368          * Major numbers for the UBI character devices are allocated
369          * dynamically. Major numbers of volume character devices are
370          * equivalent to ones of the corresponding UBI character device. Minor
371          * numbers of UBI character devices are 0, while minor numbers of
372          * volume character devices start from 1. Thus, we allocate one major
373          * number and ubi->vtbl_slots + 1 minor numbers.
374          */
375         err = alloc_chrdev_region(&dev, 0, ubi->vtbl_slots + 1, ubi->ubi_name);
376         if (err) {
377                 ubi_err("cannot register UBI character devices");
378                 return err;
379         }
380
381         ubi_assert(MINOR(dev) == 0);
382         cdev_init(&ubi->cdev, &ubi_cdev_operations);
383         dbg_msg("%s major is %u", ubi->ubi_name, MAJOR(dev));
384         ubi->cdev.owner = THIS_MODULE;
385
386         err = cdev_add(&ubi->cdev, dev, 1);
387         if (err) {
388                 ubi_err("cannot add character device");
389                 goto out_unreg;
390         }
391
392         err = ubi_sysfs_init(ubi);
393         if (err)
394                 goto out_sysfs;
395
396         for (i = 0; i < ubi->vtbl_slots; i++)
397                 if (ubi->volumes[i]) {
398                         err = ubi_add_volume(ubi, ubi->volumes[i]);
399                         if (err) {
400                                 ubi_err("cannot add volume %d", i);
401                                 goto out_volumes;
402                         }
403                 }
404
405         return 0;
406
407 out_volumes:
408         kill_volumes(ubi);
409 out_sysfs:
410         ubi_sysfs_close(ubi);
411         cdev_del(&ubi->cdev);
412 out_unreg:
413         unregister_chrdev_region(ubi->cdev.dev, ubi->vtbl_slots + 1);
414         ubi_err("cannot initialize UBI %s, error %d", ubi->ubi_name, err);
415         return err;
416 }
417
418 /**
419  * uif_close - close user interfaces for an UBI device.
420  * @ubi: UBI device description object
421  */
422 static void uif_close(struct ubi_device *ubi)
423 {
424         kill_volumes(ubi);
425         ubi_sysfs_close(ubi);
426         cdev_del(&ubi->cdev);
427         unregister_chrdev_region(ubi->cdev.dev, ubi->vtbl_slots + 1);
428 }
429
430 /**
431  * attach_by_scanning - attach an MTD device using scanning method.
432  * @ubi: UBI device descriptor
433  *
434  * This function returns zero in case of success and a negative error code in
435  * case of failure.
436  *
437  * Note, currently this is the only method to attach UBI devices. Hopefully in
438  * the future we'll have more scalable attaching methods and avoid full media
439  * scanning. But even in this case scanning will be needed as a fall-back
440  * attaching method if there are some on-flash table corruptions.
441  */
442 static int attach_by_scanning(struct ubi_device *ubi)
443 {
444         int err;
445         struct ubi_scan_info *si;
446
447         si = ubi_scan(ubi);
448         if (IS_ERR(si))
449                 return PTR_ERR(si);
450
451         ubi->bad_peb_count = si->bad_peb_count;
452         ubi->good_peb_count = ubi->peb_count - ubi->bad_peb_count;
453         ubi->max_ec = si->max_ec;
454         ubi->mean_ec = si->mean_ec;
455
456         err = ubi_read_volume_table(ubi, si);
457         if (err)
458                 goto out_si;
459
460         err = ubi_wl_init_scan(ubi, si);
461         if (err)
462                 goto out_vtbl;
463
464         err = ubi_eba_init_scan(ubi, si);
465         if (err)
466                 goto out_wl;
467
468         ubi_scan_destroy_si(si);
469         return 0;
470
471 out_wl:
472         ubi_wl_close(ubi);
473 out_vtbl:
474         vfree(ubi->vtbl);
475 out_si:
476         ubi_scan_destroy_si(si);
477         return err;
478 }
479
480 /**
481  * io_init - initialize I/O unit for a given UBI device.
482  * @ubi: UBI device description object
483  *
484  * If @ubi->vid_hdr_offset or @ubi->leb_start is zero, default offsets are
485  * assumed:
486  *   o EC header is always at offset zero - this cannot be changed;
487  *   o VID header starts just after the EC header at the closest address
488  *   aligned to @io->@hdrs_min_io_size;
489  *   o data starts just after the VID header at the closest address aligned to
490  *     @io->@min_io_size
491  *
492  * This function returns zero in case of success and a negative error code in
493  * case of failure.
494  */
495 static int io_init(struct ubi_device *ubi)
496 {
497         if (ubi->mtd->numeraseregions != 0) {
498                 /*
499                  * Some flashes have several erase regions. Different regions
500                  * may have different eraseblock size and other
501                  * characteristics. It looks like mostly multi-region flashes
502                  * have one "main" region and one or more small regions to
503                  * store boot loader code or boot parameters or whatever. I
504                  * guess we should just pick the largest region. But this is
505                  * not implemented.
506                  */
507                 ubi_err("multiple regions, not implemented");
508                 return -EINVAL;
509         }
510
511         /*
512          * Note, in this implementation we support MTD devices with 0x7FFFFFFF
513          * physical eraseblocks maximum.
514          */
515
516         ubi->peb_size   = ubi->mtd->erasesize;
517         ubi->peb_count  = ubi->mtd->size / ubi->mtd->erasesize;
518         ubi->flash_size = ubi->mtd->size;
519
520         if (ubi->mtd->block_isbad && ubi->mtd->block_markbad)
521                 ubi->bad_allowed = 1;
522
523         ubi->min_io_size = ubi->mtd->writesize;
524         ubi->hdrs_min_io_size = ubi->mtd->writesize >> ubi->mtd->subpage_sft;
525
526         /* Make sure minimal I/O unit is power of 2 */
527         if (!is_power_of_2(ubi->min_io_size)) {
528                 ubi_err("min. I/O unit (%d) is not power of 2",
529                         ubi->min_io_size);
530                 return -EINVAL;
531         }
532
533         ubi_assert(ubi->hdrs_min_io_size > 0);
534         ubi_assert(ubi->hdrs_min_io_size <= ubi->min_io_size);
535         ubi_assert(ubi->min_io_size % ubi->hdrs_min_io_size == 0);
536
537         /* Calculate default aligned sizes of EC and VID headers */
538         ubi->ec_hdr_alsize = ALIGN(UBI_EC_HDR_SIZE, ubi->hdrs_min_io_size);
539         ubi->vid_hdr_alsize = ALIGN(UBI_VID_HDR_SIZE, ubi->hdrs_min_io_size);
540
541         dbg_msg("min_io_size      %d", ubi->min_io_size);
542         dbg_msg("hdrs_min_io_size %d", ubi->hdrs_min_io_size);
543         dbg_msg("ec_hdr_alsize    %d", ubi->ec_hdr_alsize);
544         dbg_msg("vid_hdr_alsize   %d", ubi->vid_hdr_alsize);
545
546         if (ubi->vid_hdr_offset == 0)
547                 /* Default offset */
548                 ubi->vid_hdr_offset = ubi->vid_hdr_aloffset =
549                                       ubi->ec_hdr_alsize;
550         else {
551                 ubi->vid_hdr_aloffset = ubi->vid_hdr_offset &
552                                                 ~(ubi->hdrs_min_io_size - 1);
553                 ubi->vid_hdr_shift = ubi->vid_hdr_offset -
554                                                 ubi->vid_hdr_aloffset;
555         }
556
557         /* Similar for the data offset */
558         if (ubi->leb_start == 0) {
559                 ubi->leb_start = ubi->vid_hdr_offset + ubi->vid_hdr_alsize;
560                 ubi->leb_start = ALIGN(ubi->leb_start, ubi->min_io_size);
561         }
562
563         dbg_msg("vid_hdr_offset   %d", ubi->vid_hdr_offset);
564         dbg_msg("vid_hdr_aloffset %d", ubi->vid_hdr_aloffset);
565         dbg_msg("vid_hdr_shift    %d", ubi->vid_hdr_shift);
566         dbg_msg("leb_start        %d", ubi->leb_start);
567
568         /* The shift must be aligned to 32-bit boundary */
569         if (ubi->vid_hdr_shift % 4) {
570                 ubi_err("unaligned VID header shift %d",
571                         ubi->vid_hdr_shift);
572                 return -EINVAL;
573         }
574
575         /* Check sanity */
576         if (ubi->vid_hdr_offset < UBI_EC_HDR_SIZE ||
577             ubi->leb_start < ubi->vid_hdr_offset + UBI_VID_HDR_SIZE ||
578             ubi->leb_start > ubi->peb_size - UBI_VID_HDR_SIZE ||
579             ubi->leb_start % ubi->min_io_size) {
580                 ubi_err("bad VID header (%d) or data offsets (%d)",
581                         ubi->vid_hdr_offset, ubi->leb_start);
582                 return -EINVAL;
583         }
584
585         /*
586          * It may happen that EC and VID headers are situated in one minimal
587          * I/O unit. In this case we can only accept this UBI image in
588          * read-only mode.
589          */
590         if (ubi->vid_hdr_offset + UBI_VID_HDR_SIZE <= ubi->hdrs_min_io_size) {
591                 ubi_warn("EC and VID headers are in the same minimal I/O unit, "
592                          "switch to read-only mode");
593                 ubi->ro_mode = 1;
594         }
595
596         ubi->leb_size = ubi->peb_size - ubi->leb_start;
597
598         if (!(ubi->mtd->flags & MTD_WRITEABLE)) {
599                 ubi_msg("MTD device %d is write-protected, attach in "
600                         "read-only mode", ubi->mtd->index);
601                 ubi->ro_mode = 1;
602         }
603
604         dbg_msg("leb_size         %d", ubi->leb_size);
605         dbg_msg("ro_mode          %d", ubi->ro_mode);
606
607         /*
608          * Note, ideally, we have to initialize ubi->bad_peb_count here. But
609          * unfortunately, MTD does not provide this information. We should loop
610          * over all physical eraseblocks and invoke mtd->block_is_bad() for
611          * each physical eraseblock. So, we skip ubi->bad_peb_count
612          * uninitialized and initialize it after scanning.
613          */
614
615         return 0;
616 }
617
618 /**
619  * attach_mtd_dev - attach an MTD device.
620  * @mtd_dev: MTD device name or number string
621  * @vid_hdr_offset: VID header offset
622  * @data_offset: data offset
623  *
624  * This function attaches an MTD device to UBI. It first treats @mtd_dev as the
625  * MTD device name, and tries to open it by this name. If it is unable to open,
626  * it tries to convert @mtd_dev to an integer and open the MTD device by its
627  * number. Returns zero in case of success and a negative error code in case of
628  * failure.
629  */
630 static int attach_mtd_dev(const char *mtd_dev, int vid_hdr_offset,
631                           int data_offset)
632 {
633         struct ubi_device *ubi;
634         struct mtd_info *mtd;
635         int i, err;
636
637         mtd = get_mtd_device_nm(mtd_dev);
638         if (IS_ERR(mtd)) {
639                 int mtd_num;
640                 char *endp;
641
642                 if (PTR_ERR(mtd) != -ENODEV)
643                         return PTR_ERR(mtd);
644
645                 /*
646                  * Probably this is not MTD device name but MTD device number -
647                  * check this out.
648                  */
649                 mtd_num = simple_strtoul(mtd_dev, &endp, 0);
650                 if (*endp != '\0' || mtd_dev == endp) {
651                         ubi_err("incorrect MTD device: \"%s\"", mtd_dev);
652                         return -ENODEV;
653                 }
654
655                 mtd = get_mtd_device(NULL, mtd_num);
656                 if (IS_ERR(mtd))
657                         return PTR_ERR(mtd);
658         }
659
660         /* Check if we already have the same MTD device attached */
661         for (i = 0; i < UBI_MAX_DEVICES; i++)
662                 ubi = ubi_devices[i];
663                 if (ubi && ubi->mtd->index == mtd->index) {
664                         ubi_err("mtd%d is already attached to ubi%d",
665                                 mtd->index, i);
666                         err = -EINVAL;
667                         goto out_mtd;
668                 }
669
670         ubi = kzalloc(sizeof(struct ubi_device), GFP_KERNEL);
671         if (!ubi) {
672                 err = -ENOMEM;
673                 goto out_mtd;
674         }
675
676         ubi->mtd = mtd;
677
678         /* Search for an empty slot in the @ubi_devices array */
679         ubi->ubi_num = -1;
680         for (i = 0; i < UBI_MAX_DEVICES; i++)
681                 if (!ubi_devices[i]) {
682                         ubi->ubi_num = i;
683                         break;
684                 }
685
686         if (ubi->ubi_num == -1) {
687                 ubi_err("only %d UBI devices may be created", UBI_MAX_DEVICES);
688                 err = -ENFILE;
689                 goto out_free;
690         }
691
692         dbg_msg("attaching mtd%d to ubi%d: VID header offset %d data offset %d",
693                 ubi->mtd->index, ubi->ubi_num, vid_hdr_offset, data_offset);
694
695         ubi->vid_hdr_offset = vid_hdr_offset;
696         ubi->leb_start = data_offset;
697         err = io_init(ubi);
698         if (err)
699                 goto out_free;
700
701         mutex_init(&ubi->buf_mutex);
702         ubi->peb_buf1 = vmalloc(ubi->peb_size);
703         if (!ubi->peb_buf1)
704                 goto out_free;
705
706         ubi->peb_buf2 = vmalloc(ubi->peb_size);
707         if (!ubi->peb_buf2)
708                  goto out_free;
709
710 #ifdef CONFIG_MTD_UBI_DEBUG
711         mutex_init(&ubi->dbg_buf_mutex);
712         ubi->dbg_peb_buf = vmalloc(ubi->peb_size);
713         if (!ubi->dbg_peb_buf)
714                  goto out_free;
715 #endif
716
717         err = attach_by_scanning(ubi);
718         if (err) {
719                 dbg_err("failed to attach by scanning, error %d", err);
720                 goto out_free;
721         }
722
723         err = uif_init(ubi);
724         if (err)
725                 goto out_detach;
726
727         ubi_msg("attached mtd%d to ubi%d", ubi->mtd->index, ubi->ubi_num);
728         ubi_msg("MTD device name:            \"%s\"", ubi->mtd->name);
729         ubi_msg("MTD device size:            %llu MiB", ubi->flash_size >> 20);
730         ubi_msg("physical eraseblock size:   %d bytes (%d KiB)",
731                 ubi->peb_size, ubi->peb_size >> 10);
732         ubi_msg("logical eraseblock size:    %d bytes", ubi->leb_size);
733         ubi_msg("number of good PEBs:        %d", ubi->good_peb_count);
734         ubi_msg("number of bad PEBs:         %d", ubi->bad_peb_count);
735         ubi_msg("smallest flash I/O unit:    %d", ubi->min_io_size);
736         ubi_msg("VID header offset:          %d (aligned %d)",
737                 ubi->vid_hdr_offset, ubi->vid_hdr_aloffset);
738         ubi_msg("data offset:                %d", ubi->leb_start);
739         ubi_msg("max. allowed volumes:       %d", ubi->vtbl_slots);
740         ubi_msg("wear-leveling threshold:    %d", CONFIG_MTD_UBI_WL_THRESHOLD);
741         ubi_msg("number of internal volumes: %d", UBI_INT_VOL_COUNT);
742         ubi_msg("number of user volumes:     %d",
743                 ubi->vol_count - UBI_INT_VOL_COUNT);
744         ubi_msg("available PEBs:             %d", ubi->avail_pebs);
745         ubi_msg("total number of reserved PEBs: %d", ubi->rsvd_pebs);
746         ubi_msg("number of PEBs reserved for bad PEB handling: %d",
747                 ubi->beb_rsvd_pebs);
748         ubi_msg("max/mean erase counter: %d/%d", ubi->max_ec, ubi->mean_ec);
749
750         /* Enable the background thread */
751         if (!DBG_DISABLE_BGT) {
752                 ubi->thread_enabled = 1;
753                 wake_up_process(ubi->bgt_thread);
754         }
755
756         ubi_devices[ubi->ubi_num] = ubi;
757         return 0;
758
759 out_detach:
760         ubi_eba_close(ubi);
761         ubi_wl_close(ubi);
762         vfree(ubi->vtbl);
763 out_free:
764         vfree(ubi->peb_buf1);
765         vfree(ubi->peb_buf2);
766 #ifdef CONFIG_MTD_UBI_DEBUG
767         vfree(ubi->dbg_peb_buf);
768 #endif
769         kfree(ubi);
770 out_mtd:
771         put_mtd_device(mtd);
772         return err;
773 }
774
775 /**
776  * detach_mtd_dev - detach an MTD device.
777  * @ubi: UBI device description object
778  */
779 static void detach_mtd_dev(struct ubi_device *ubi)
780 {
781         int ubi_num = ubi->ubi_num, mtd_num = ubi->mtd->index;
782
783         dbg_msg("detaching mtd%d from ubi%d", ubi->mtd->index, ubi_num);
784         ubi_assert(ubi->ref_count == 0);
785         uif_close(ubi);
786         ubi_eba_close(ubi);
787         ubi_wl_close(ubi);
788         vfree(ubi->vtbl);
789         put_mtd_device(ubi->mtd);
790         vfree(ubi->peb_buf1);
791         vfree(ubi->peb_buf2);
792 #ifdef CONFIG_MTD_UBI_DEBUG
793         vfree(ubi->dbg_peb_buf);
794 #endif
795         kfree(ubi_devices[ubi_num]);
796         ubi_devices[ubi_num] = NULL;
797         ubi_msg("mtd%d is detached from ubi%d", mtd_num, ubi_num);
798 }
799
800 /**
801  * ltree_entry_ctor - lock tree entries slab cache constructor.
802  * @obj: the lock-tree entry to construct
803  * @cache: the lock tree entry slab cache
804  * @flags: constructor flags
805  */
806 static void ltree_entry_ctor(struct kmem_cache *cache, void *obj)
807 {
808         struct ubi_ltree_entry *le = obj;
809
810         le->users = 0;
811         init_rwsem(&le->mutex);
812 }
813
814 static int __init ubi_init(void)
815 {
816         int err, i, k;
817
818         /* Ensure that EC and VID headers have correct size */
819         BUILD_BUG_ON(sizeof(struct ubi_ec_hdr) != 64);
820         BUILD_BUG_ON(sizeof(struct ubi_vid_hdr) != 64);
821
822         if (mtd_devs > UBI_MAX_DEVICES) {
823                 printk(KERN_ERR "UBI error: too many MTD devices, "
824                        "maximum is %d\n", UBI_MAX_DEVICES);
825                 return -EINVAL;
826         }
827
828         /* Create base sysfs directory and sysfs files */
829         ubi_class = class_create(THIS_MODULE, UBI_NAME_STR);
830         if (IS_ERR(ubi_class)) {
831                 err = PTR_ERR(ubi_class);
832                 printk(KERN_ERR "UBI error: cannot create UBI class\n");
833                 goto out;
834         }
835
836         err = class_create_file(ubi_class, &ubi_version);
837         if (err) {
838                 printk(KERN_ERR "UBI error: cannot create sysfs file\n");
839                 goto out_class;
840         }
841
842         err = misc_register(&ubi_ctrl_cdev);
843         if (err) {
844                 printk(KERN_ERR "UBI error: cannot register device\n");
845                 goto out_version;
846         }
847
848         ubi_ltree_slab = kmem_cache_create("ubi_ltree_slab",
849                                            sizeof(struct ubi_ltree_entry), 0,
850                                            0, &ltree_entry_ctor);
851         if (!ubi_ltree_slab)
852                 goto out_dev_unreg;
853
854         ubi_wl_entry_slab = kmem_cache_create("ubi_wl_entry_slab",
855                                                 sizeof(struct ubi_wl_entry),
856                                                 0, 0, NULL);
857         if (!ubi_wl_entry_slab)
858                 goto out_ltree;
859
860         /* Attach MTD devices */
861         for (i = 0; i < mtd_devs; i++) {
862                 struct mtd_dev_param *p = &mtd_dev_param[i];
863
864                 cond_resched();
865                 err = attach_mtd_dev(p->name, p->vid_hdr_offs, p->data_offs);
866                 if (err) {
867                         printk(KERN_ERR "UBI error: cannot attach %s\n",
868                                p->name);
869                         goto out_detach;
870                 }
871         }
872
873         return 0;
874
875 out_detach:
876         for (k = 0; k < i; k++)
877                 detach_mtd_dev(ubi_devices[k]);
878         kmem_cache_destroy(ubi_wl_entry_slab);
879 out_ltree:
880         kmem_cache_destroy(ubi_ltree_slab);
881 out_dev_unreg:
882         misc_deregister(&ubi_ctrl_cdev);
883 out_version:
884         class_remove_file(ubi_class, &ubi_version);
885 out_class:
886         class_destroy(ubi_class);
887 out:
888         printk(KERN_ERR "UBI error: cannot initialize UBI, error %d\n", err);
889         return err;
890 }
891 module_init(ubi_init);
892
893 static void __exit ubi_exit(void)
894 {
895         int i;
896
897         for (i = 0; i < UBI_MAX_DEVICES; i++)
898                 if (ubi_devices[i])
899                         detach_mtd_dev(ubi_devices[i]);
900         kmem_cache_destroy(ubi_wl_entry_slab);
901         kmem_cache_destroy(ubi_ltree_slab);
902         misc_deregister(&ubi_ctrl_cdev);
903         class_remove_file(ubi_class, &ubi_version);
904         class_destroy(ubi_class);
905 }
906 module_exit(ubi_exit);
907
908 /**
909  * bytes_str_to_int - convert a string representing number of bytes to an
910  * integer.
911  * @str: the string to convert
912  *
913  * This function returns positive resulting integer in case of success and a
914  * negative error code in case of failure.
915  */
916 static int __init bytes_str_to_int(const char *str)
917 {
918         char *endp;
919         unsigned long result;
920
921         result = simple_strtoul(str, &endp, 0);
922         if (str == endp || result < 0) {
923                 printk(KERN_ERR "UBI error: incorrect bytes count: \"%s\"\n",
924                        str);
925                 return -EINVAL;
926         }
927
928         switch (*endp) {
929         case 'G':
930                 result *= 1024;
931         case 'M':
932                 result *= 1024;
933         case 'K':
934         case 'k':
935                 result *= 1024;
936                 if (endp[1] == 'i' && (endp[2] == '\0' ||
937                           endp[2] == 'B'  || endp[2] == 'b'))
938                         endp += 2;
939         case '\0':
940                 break;
941         default:
942                 printk(KERN_ERR "UBI error: incorrect bytes count: \"%s\"\n",
943                        str);
944                 return -EINVAL;
945         }
946
947         return result;
948 }
949
950 /**
951  * ubi_mtd_param_parse - parse the 'mtd=' UBI parameter.
952  * @val: the parameter value to parse
953  * @kp: not used
954  *
955  * This function returns zero in case of success and a negative error code in
956  * case of error.
957  */
958 static int __init ubi_mtd_param_parse(const char *val, struct kernel_param *kp)
959 {
960         int i, len;
961         struct mtd_dev_param *p;
962         char buf[MTD_PARAM_LEN_MAX];
963         char *pbuf = &buf[0];
964         char *tokens[3] = {NULL, NULL, NULL};
965
966         if (!val)
967                 return -EINVAL;
968
969         if (mtd_devs == UBI_MAX_DEVICES) {
970                 printk(KERN_ERR "UBI error: too many parameters, max. is %d\n",
971                        UBI_MAX_DEVICES);
972                 return -EINVAL;
973         }
974
975         len = strnlen(val, MTD_PARAM_LEN_MAX);
976         if (len == MTD_PARAM_LEN_MAX) {
977                 printk(KERN_ERR "UBI error: parameter \"%s\" is too long, "
978                        "max. is %d\n", val, MTD_PARAM_LEN_MAX);
979                 return -EINVAL;
980         }
981
982         if (len == 0) {
983                 printk(KERN_WARNING "UBI warning: empty 'mtd=' parameter - "
984                        "ignored\n");
985                 return 0;
986         }
987
988         strcpy(buf, val);
989
990         /* Get rid of the final newline */
991         if (buf[len - 1] == '\n')
992                 buf[len - 1] = '\0';
993
994         for (i = 0; i < 3; i++)
995                 tokens[i] = strsep(&pbuf, ",");
996
997         if (pbuf) {
998                 printk(KERN_ERR "UBI error: too many arguments at \"%s\"\n",
999                        val);
1000                 return -EINVAL;
1001         }
1002
1003         p = &mtd_dev_param[mtd_devs];
1004         strcpy(&p->name[0], tokens[0]);
1005
1006         if (tokens[1])
1007                 p->vid_hdr_offs = bytes_str_to_int(tokens[1]);
1008         if (tokens[2])
1009                 p->data_offs = bytes_str_to_int(tokens[2]);
1010
1011         if (p->vid_hdr_offs < 0)
1012                 return p->vid_hdr_offs;
1013         if (p->data_offs < 0)
1014                 return p->data_offs;
1015
1016         mtd_devs += 1;
1017         return 0;
1018 }
1019
1020 module_param_call(mtd, ubi_mtd_param_parse, NULL, NULL, 000);
1021 MODULE_PARM_DESC(mtd, "MTD devices to attach. Parameter format: "
1022                       "mtd=<name|num>[,<vid_hdr_offs>,<data_offs>]. "
1023                       "Multiple \"mtd\" parameters may be specified.\n"
1024                       "MTD devices may be specified by their number or name. "
1025                       "Optional \"vid_hdr_offs\" and \"data_offs\" parameters "
1026                       "specify UBI VID header position and data starting "
1027                       "position to be used by UBI.\n"
1028                       "Example: mtd=content,1984,2048 mtd=4 - attach MTD device"
1029                       "with name content using VID header offset 1984 and data "
1030                       "start 2048, and MTD device number 4 using default "
1031                       "offsets");
1032
1033 MODULE_VERSION(__stringify(UBI_VERSION));
1034 MODULE_DESCRIPTION("UBI - Unsorted Block Images");
1035 MODULE_AUTHOR("Artem Bityutskiy");
1036 MODULE_LICENSE("GPL");