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