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