30b710216f264cf2c43095ea65f48876b18ef741
[platform/kernel/linux-rpi.git] / drivers / mtd / ubi / scan.c
1 /*
2  * Copyright (c) International Business Machines Corp., 2006
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
12  * the GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * Author: Artem Bityutskiy (Битюцкий Артём)
19  */
20
21 /*
22  * UBI scanning sub-system.
23  *
24  * This sub-system is responsible for scanning the flash media, checking UBI
25  * headers and providing complete information about the UBI flash image.
26  *
27  * The scanning information is represented by a &struct ubi_scan_info' object.
28  * Information about found volumes is represented by &struct ubi_scan_volume
29  * objects which are kept in volume RB-tree with root at the @volumes field.
30  * The RB-tree is indexed by the volume ID.
31  *
32  * Scanned logical eraseblocks are represented by &struct ubi_scan_leb objects.
33  * These objects are kept in per-volume RB-trees with the root at the
34  * corresponding &struct ubi_scan_volume object. To put it differently, we keep
35  * an RB-tree of per-volume objects and each of these objects is the root of
36  * RB-tree of per-eraseblock objects.
37  *
38  * Corrupted physical eraseblocks are put to the @corr list, free physical
39  * eraseblocks are put to the @free list and the physical eraseblock to be
40  * erased are put to the @erase list.
41  *
42  * UBI tries to distinguish between 2 types of corruptions.
43  * 1. Corruptions caused by power cuts. These are harmless and expected
44  *    corruptions and UBI tries to handle them gracefully, without printing too
45  *    many warnings and error messages. The idea is that we do not lose
46  *    important data in these case - we may lose only the data which was being
47  *    written to the media just before the power cut happened, and the upper
48  *    layers are supposed to handle these situations. UBI puts these PEBs to
49  *    the head of the @erase list and they are scheduled for erasure.
50  *
51  * 2. Unexpected corruptions which are not caused by power cuts. During
52  *    scanning, such PEBs are put to the @corr list and UBI preserves them.
53  *    Obviously, this lessens the amount of available PEBs, and if at some
54  *    point UBI runs out of free PEBs, it switches to R/O mode. UBI also loudly
55  *    informs about such PEBs every time the MTD device is attached.
56  */
57
58 #include <linux/err.h>
59 #include <linux/slab.h>
60 #include <linux/crc32.h>
61 #include <linux/math64.h>
62 #include <linux/random.h>
63 #include "ubi.h"
64
65 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
66 static int paranoid_check_si(struct ubi_device *ubi, struct ubi_scan_info *si);
67 #else
68 #define paranoid_check_si(ubi, si) 0
69 #endif
70
71 /* Temporary variables used during scanning */
72 static struct ubi_ec_hdr *ech;
73 static struct ubi_vid_hdr *vidh;
74
75 /**
76  * add_to_list - add physical eraseblock to a list.
77  * @si: scanning information
78  * @pnum: physical eraseblock number to add
79  * @ec: erase counter of the physical eraseblock
80  * @to_head: if not zero, add to the head of the list
81  * @list: the list to add to
82  *
83  * This function adds physical eraseblock @pnum to free, erase, or alien lists.
84  * If @to_head is not zero, PEB will be added to the head of the list, which
85  * basically means it will be processed first later. E.g., we add corrupted
86  * PEBs (corrupted due to power cuts) to the head of the erase list to make
87  * sure we erase them first and get rid of corruptions ASAP. This function
88  * returns zero in case of success and a negative error code in case of
89  * failure.
90  */
91 static int add_to_list(struct ubi_scan_info *si, int pnum, int ec, int to_head,
92                        struct list_head *list)
93 {
94         struct ubi_scan_leb *seb;
95
96         if (list == &si->free) {
97                 dbg_bld("add to free: PEB %d, EC %d", pnum, ec);
98         } else if (list == &si->erase) {
99                 dbg_bld("add to erase: PEB %d, EC %d", pnum, ec);
100         } else if (list == &si->alien) {
101                 dbg_bld("add to alien: PEB %d, EC %d", pnum, ec);
102                 si->alien_peb_count += 1;
103         } else
104                 BUG();
105
106         seb = kmalloc(sizeof(struct ubi_scan_leb), GFP_KERNEL);
107         if (!seb)
108                 return -ENOMEM;
109
110         seb->pnum = pnum;
111         seb->ec = ec;
112         if (to_head)
113                 list_add(&seb->u.list, list);
114         else
115                 list_add_tail(&seb->u.list, list);
116         return 0;
117 }
118
119 /**
120  * add_corrupted - add a corrupted physical eraseblock.
121  * @si: scanning information
122  * @pnum: physical eraseblock number to add
123  * @ec: erase counter of the physical eraseblock
124  *
125  * This function adds corrupted physical eraseblock @pnum to the 'corr' list.
126  * The corruption was presumably not caused by a power cut. Returns zero in
127  * case of success and a negative error code in case of failure.
128  */
129 static int add_corrupted(struct ubi_scan_info *si, int pnum, int ec)
130 {
131         struct ubi_scan_leb *seb;
132
133         dbg_bld("add to corrupted: PEB %d, EC %d", pnum, ec);
134
135         seb = kmalloc(sizeof(struct ubi_scan_leb), GFP_KERNEL);
136         if (!seb)
137                 return -ENOMEM;
138
139         si->corr_peb_count += 1;
140         seb->pnum = pnum;
141         seb->ec = ec;
142         list_add(&seb->u.list, &si->corr);
143         return 0;
144 }
145
146 /**
147  * validate_vid_hdr - check volume identifier header.
148  * @vid_hdr: the volume identifier header to check
149  * @sv: information about the volume this logical eraseblock belongs to
150  * @pnum: physical eraseblock number the VID header came from
151  *
152  * This function checks that data stored in @vid_hdr is consistent. Returns
153  * non-zero if an inconsistency was found and zero if not.
154  *
155  * Note, UBI does sanity check of everything it reads from the flash media.
156  * Most of the checks are done in the I/O sub-system. Here we check that the
157  * information in the VID header is consistent to the information in other VID
158  * headers of the same volume.
159  */
160 static int validate_vid_hdr(const struct ubi_vid_hdr *vid_hdr,
161                             const struct ubi_scan_volume *sv, int pnum)
162 {
163         int vol_type = vid_hdr->vol_type;
164         int vol_id = be32_to_cpu(vid_hdr->vol_id);
165         int used_ebs = be32_to_cpu(vid_hdr->used_ebs);
166         int data_pad = be32_to_cpu(vid_hdr->data_pad);
167
168         if (sv->leb_count != 0) {
169                 int sv_vol_type;
170
171                 /*
172                  * This is not the first logical eraseblock belonging to this
173                  * volume. Ensure that the data in its VID header is consistent
174                  * to the data in previous logical eraseblock headers.
175                  */
176
177                 if (vol_id != sv->vol_id) {
178                         dbg_err("inconsistent vol_id");
179                         goto bad;
180                 }
181
182                 if (sv->vol_type == UBI_STATIC_VOLUME)
183                         sv_vol_type = UBI_VID_STATIC;
184                 else
185                         sv_vol_type = UBI_VID_DYNAMIC;
186
187                 if (vol_type != sv_vol_type) {
188                         dbg_err("inconsistent vol_type");
189                         goto bad;
190                 }
191
192                 if (used_ebs != sv->used_ebs) {
193                         dbg_err("inconsistent used_ebs");
194                         goto bad;
195                 }
196
197                 if (data_pad != sv->data_pad) {
198                         dbg_err("inconsistent data_pad");
199                         goto bad;
200                 }
201         }
202
203         return 0;
204
205 bad:
206         ubi_err("inconsistent VID header at PEB %d", pnum);
207         ubi_dbg_dump_vid_hdr(vid_hdr);
208         ubi_dbg_dump_sv(sv);
209         return -EINVAL;
210 }
211
212 /**
213  * add_volume - add volume to the scanning information.
214  * @si: scanning information
215  * @vol_id: ID of the volume to add
216  * @pnum: physical eraseblock number
217  * @vid_hdr: volume identifier header
218  *
219  * If the volume corresponding to the @vid_hdr logical eraseblock is already
220  * present in the scanning information, this function does nothing. Otherwise
221  * it adds corresponding volume to the scanning information. Returns a pointer
222  * to the scanning volume object in case of success and a negative error code
223  * in case of failure.
224  */
225 static struct ubi_scan_volume *add_volume(struct ubi_scan_info *si, int vol_id,
226                                           int pnum,
227                                           const struct ubi_vid_hdr *vid_hdr)
228 {
229         struct ubi_scan_volume *sv;
230         struct rb_node **p = &si->volumes.rb_node, *parent = NULL;
231
232         ubi_assert(vol_id == be32_to_cpu(vid_hdr->vol_id));
233
234         /* Walk the volume RB-tree to look if this volume is already present */
235         while (*p) {
236                 parent = *p;
237                 sv = rb_entry(parent, struct ubi_scan_volume, rb);
238
239                 if (vol_id == sv->vol_id)
240                         return sv;
241
242                 if (vol_id > sv->vol_id)
243                         p = &(*p)->rb_left;
244                 else
245                         p = &(*p)->rb_right;
246         }
247
248         /* The volume is absent - add it */
249         sv = kmalloc(sizeof(struct ubi_scan_volume), GFP_KERNEL);
250         if (!sv)
251                 return ERR_PTR(-ENOMEM);
252
253         sv->highest_lnum = sv->leb_count = 0;
254         sv->vol_id = vol_id;
255         sv->root = RB_ROOT;
256         sv->used_ebs = be32_to_cpu(vid_hdr->used_ebs);
257         sv->data_pad = be32_to_cpu(vid_hdr->data_pad);
258         sv->compat = vid_hdr->compat;
259         sv->vol_type = vid_hdr->vol_type == UBI_VID_DYNAMIC ? UBI_DYNAMIC_VOLUME
260                                                             : UBI_STATIC_VOLUME;
261         if (vol_id > si->highest_vol_id)
262                 si->highest_vol_id = vol_id;
263
264         rb_link_node(&sv->rb, parent, p);
265         rb_insert_color(&sv->rb, &si->volumes);
266         si->vols_found += 1;
267         dbg_bld("added volume %d", vol_id);
268         return sv;
269 }
270
271 /**
272  * compare_lebs - find out which logical eraseblock is newer.
273  * @ubi: UBI device description object
274  * @seb: first logical eraseblock to compare
275  * @pnum: physical eraseblock number of the second logical eraseblock to
276  * compare
277  * @vid_hdr: volume identifier header of the second logical eraseblock
278  *
279  * This function compares 2 copies of a LEB and informs which one is newer. In
280  * case of success this function returns a positive value, in case of failure, a
281  * negative error code is returned. The success return codes use the following
282  * bits:
283  *     o bit 0 is cleared: the first PEB (described by @seb) is newer than the
284  *       second PEB (described by @pnum and @vid_hdr);
285  *     o bit 0 is set: the second PEB is newer;
286  *     o bit 1 is cleared: no bit-flips were detected in the newer LEB;
287  *     o bit 1 is set: bit-flips were detected in the newer LEB;
288  *     o bit 2 is cleared: the older LEB is not corrupted;
289  *     o bit 2 is set: the older LEB is corrupted.
290  */
291 static int compare_lebs(struct ubi_device *ubi, const struct ubi_scan_leb *seb,
292                         int pnum, const struct ubi_vid_hdr *vid_hdr)
293 {
294         void *buf;
295         int len, err, second_is_newer, bitflips = 0, corrupted = 0;
296         uint32_t data_crc, crc;
297         struct ubi_vid_hdr *vh = NULL;
298         unsigned long long sqnum2 = be64_to_cpu(vid_hdr->sqnum);
299
300         if (sqnum2 == seb->sqnum) {
301                 /*
302                  * This must be a really ancient UBI image which has been
303                  * created before sequence numbers support has been added. At
304                  * that times we used 32-bit LEB versions stored in logical
305                  * eraseblocks. That was before UBI got into mainline. We do not
306                  * support these images anymore. Well, those images still work,
307                  * but only if no unclean reboots happened.
308                  */
309                 ubi_err("unsupported on-flash UBI format\n");
310                 return -EINVAL;
311         }
312
313         /* Obviously the LEB with lower sequence counter is older */
314         second_is_newer = !!(sqnum2 > seb->sqnum);
315
316         /*
317          * Now we know which copy is newer. If the copy flag of the PEB with
318          * newer version is not set, then we just return, otherwise we have to
319          * check data CRC. For the second PEB we already have the VID header,
320          * for the first one - we'll need to re-read it from flash.
321          *
322          * Note: this may be optimized so that we wouldn't read twice.
323          */
324
325         if (second_is_newer) {
326                 if (!vid_hdr->copy_flag) {
327                         /* It is not a copy, so it is newer */
328                         dbg_bld("second PEB %d is newer, copy_flag is unset",
329                                 pnum);
330                         return 1;
331                 }
332         } else {
333                 pnum = seb->pnum;
334
335                 vh = ubi_zalloc_vid_hdr(ubi, GFP_KERNEL);
336                 if (!vh)
337                         return -ENOMEM;
338
339                 err = ubi_io_read_vid_hdr(ubi, pnum, vh, 0);
340                 if (err) {
341                         if (err == UBI_IO_BITFLIPS)
342                                 bitflips = 1;
343                         else {
344                                 dbg_err("VID of PEB %d header is bad, but it "
345                                         "was OK earlier, err %d", pnum, err);
346                                 if (err > 0)
347                                         err = -EIO;
348
349                                 goto out_free_vidh;
350                         }
351                 }
352
353                 if (!vh->copy_flag) {
354                         /* It is not a copy, so it is newer */
355                         dbg_bld("first PEB %d is newer, copy_flag is unset",
356                                 pnum);
357                         err = bitflips << 1;
358                         goto out_free_vidh;
359                 }
360
361                 vid_hdr = vh;
362         }
363
364         /* Read the data of the copy and check the CRC */
365
366         len = be32_to_cpu(vid_hdr->data_size);
367         buf = vmalloc(len);
368         if (!buf) {
369                 err = -ENOMEM;
370                 goto out_free_vidh;
371         }
372
373         err = ubi_io_read_data(ubi, buf, pnum, 0, len);
374         if (err && err != UBI_IO_BITFLIPS && err != -EBADMSG)
375                 goto out_free_buf;
376
377         data_crc = be32_to_cpu(vid_hdr->data_crc);
378         crc = crc32(UBI_CRC32_INIT, buf, len);
379         if (crc != data_crc) {
380                 dbg_bld("PEB %d CRC error: calculated %#08x, must be %#08x",
381                         pnum, crc, data_crc);
382                 corrupted = 1;
383                 bitflips = 0;
384                 second_is_newer = !second_is_newer;
385         } else {
386                 dbg_bld("PEB %d CRC is OK", pnum);
387                 bitflips = !!err;
388         }
389
390         vfree(buf);
391         ubi_free_vid_hdr(ubi, vh);
392
393         if (second_is_newer)
394                 dbg_bld("second PEB %d is newer, copy_flag is set", pnum);
395         else
396                 dbg_bld("first PEB %d is newer, copy_flag is set", pnum);
397
398         return second_is_newer | (bitflips << 1) | (corrupted << 2);
399
400 out_free_buf:
401         vfree(buf);
402 out_free_vidh:
403         ubi_free_vid_hdr(ubi, vh);
404         return err;
405 }
406
407 /**
408  * ubi_scan_add_used - add physical eraseblock to the scanning information.
409  * @ubi: UBI device description object
410  * @si: scanning information
411  * @pnum: the physical eraseblock number
412  * @ec: erase counter
413  * @vid_hdr: the volume identifier header
414  * @bitflips: if bit-flips were detected when this physical eraseblock was read
415  *
416  * This function adds information about a used physical eraseblock to the
417  * 'used' tree of the corresponding volume. The function is rather complex
418  * because it has to handle cases when this is not the first physical
419  * eraseblock belonging to the same logical eraseblock, and the newer one has
420  * to be picked, while the older one has to be dropped. This function returns
421  * zero in case of success and a negative error code in case of failure.
422  */
423 int ubi_scan_add_used(struct ubi_device *ubi, struct ubi_scan_info *si,
424                       int pnum, int ec, const struct ubi_vid_hdr *vid_hdr,
425                       int bitflips)
426 {
427         int err, vol_id, lnum;
428         unsigned long long sqnum;
429         struct ubi_scan_volume *sv;
430         struct ubi_scan_leb *seb;
431         struct rb_node **p, *parent = NULL;
432
433         vol_id = be32_to_cpu(vid_hdr->vol_id);
434         lnum = be32_to_cpu(vid_hdr->lnum);
435         sqnum = be64_to_cpu(vid_hdr->sqnum);
436
437         dbg_bld("PEB %d, LEB %d:%d, EC %d, sqnum %llu, bitflips %d",
438                 pnum, vol_id, lnum, ec, sqnum, bitflips);
439
440         sv = add_volume(si, vol_id, pnum, vid_hdr);
441         if (IS_ERR(sv))
442                 return PTR_ERR(sv);
443
444         if (si->max_sqnum < sqnum)
445                 si->max_sqnum = sqnum;
446
447         /*
448          * Walk the RB-tree of logical eraseblocks of volume @vol_id to look
449          * if this is the first instance of this logical eraseblock or not.
450          */
451         p = &sv->root.rb_node;
452         while (*p) {
453                 int cmp_res;
454
455                 parent = *p;
456                 seb = rb_entry(parent, struct ubi_scan_leb, u.rb);
457                 if (lnum != seb->lnum) {
458                         if (lnum < seb->lnum)
459                                 p = &(*p)->rb_left;
460                         else
461                                 p = &(*p)->rb_right;
462                         continue;
463                 }
464
465                 /*
466                  * There is already a physical eraseblock describing the same
467                  * logical eraseblock present.
468                  */
469
470                 dbg_bld("this LEB already exists: PEB %d, sqnum %llu, "
471                         "EC %d", seb->pnum, seb->sqnum, seb->ec);
472
473                 /*
474                  * Make sure that the logical eraseblocks have different
475                  * sequence numbers. Otherwise the image is bad.
476                  *
477                  * However, if the sequence number is zero, we assume it must
478                  * be an ancient UBI image from the era when UBI did not have
479                  * sequence numbers. We still can attach these images, unless
480                  * there is a need to distinguish between old and new
481                  * eraseblocks, in which case we'll refuse the image in
482                  * 'compare_lebs()'. In other words, we attach old clean
483                  * images, but refuse attaching old images with duplicated
484                  * logical eraseblocks because there was an unclean reboot.
485                  */
486                 if (seb->sqnum == sqnum && sqnum != 0) {
487                         ubi_err("two LEBs with same sequence number %llu",
488                                 sqnum);
489                         ubi_dbg_dump_seb(seb, 0);
490                         ubi_dbg_dump_vid_hdr(vid_hdr);
491                         return -EINVAL;
492                 }
493
494                 /*
495                  * Now we have to drop the older one and preserve the newer
496                  * one.
497                  */
498                 cmp_res = compare_lebs(ubi, seb, pnum, vid_hdr);
499                 if (cmp_res < 0)
500                         return cmp_res;
501
502                 if (cmp_res & 1) {
503                         /*
504                          * This logical eraseblock is newer than the one
505                          * found earlier.
506                          */
507                         err = validate_vid_hdr(vid_hdr, sv, pnum);
508                         if (err)
509                                 return err;
510
511                         err = add_to_list(si, seb->pnum, seb->ec, cmp_res & 4,
512                                           &si->erase);
513                         if (err)
514                                 return err;
515
516                         seb->ec = ec;
517                         seb->pnum = pnum;
518                         seb->scrub = ((cmp_res & 2) || bitflips);
519                         seb->sqnum = sqnum;
520
521                         if (sv->highest_lnum == lnum)
522                                 sv->last_data_size =
523                                         be32_to_cpu(vid_hdr->data_size);
524
525                         return 0;
526                 } else {
527                         /*
528                          * This logical eraseblock is older than the one found
529                          * previously.
530                          */
531                         return add_to_list(si, pnum, ec, cmp_res & 4,
532                                            &si->erase);
533                 }
534         }
535
536         /*
537          * We've met this logical eraseblock for the first time, add it to the
538          * scanning information.
539          */
540
541         err = validate_vid_hdr(vid_hdr, sv, pnum);
542         if (err)
543                 return err;
544
545         seb = kmalloc(sizeof(struct ubi_scan_leb), GFP_KERNEL);
546         if (!seb)
547                 return -ENOMEM;
548
549         seb->ec = ec;
550         seb->pnum = pnum;
551         seb->lnum = lnum;
552         seb->sqnum = sqnum;
553         seb->scrub = bitflips;
554
555         if (sv->highest_lnum <= lnum) {
556                 sv->highest_lnum = lnum;
557                 sv->last_data_size = be32_to_cpu(vid_hdr->data_size);
558         }
559
560         sv->leb_count += 1;
561         rb_link_node(&seb->u.rb, parent, p);
562         rb_insert_color(&seb->u.rb, &sv->root);
563         return 0;
564 }
565
566 /**
567  * ubi_scan_find_sv - find volume in the scanning information.
568  * @si: scanning information
569  * @vol_id: the requested volume ID
570  *
571  * This function returns a pointer to the volume description or %NULL if there
572  * are no data about this volume in the scanning information.
573  */
574 struct ubi_scan_volume *ubi_scan_find_sv(const struct ubi_scan_info *si,
575                                          int vol_id)
576 {
577         struct ubi_scan_volume *sv;
578         struct rb_node *p = si->volumes.rb_node;
579
580         while (p) {
581                 sv = rb_entry(p, struct ubi_scan_volume, rb);
582
583                 if (vol_id == sv->vol_id)
584                         return sv;
585
586                 if (vol_id > sv->vol_id)
587                         p = p->rb_left;
588                 else
589                         p = p->rb_right;
590         }
591
592         return NULL;
593 }
594
595 /**
596  * ubi_scan_find_seb - find LEB in the volume scanning information.
597  * @sv: a pointer to the volume scanning information
598  * @lnum: the requested logical eraseblock
599  *
600  * This function returns a pointer to the scanning logical eraseblock or %NULL
601  * if there are no data about it in the scanning volume information.
602  */
603 struct ubi_scan_leb *ubi_scan_find_seb(const struct ubi_scan_volume *sv,
604                                        int lnum)
605 {
606         struct ubi_scan_leb *seb;
607         struct rb_node *p = sv->root.rb_node;
608
609         while (p) {
610                 seb = rb_entry(p, struct ubi_scan_leb, u.rb);
611
612                 if (lnum == seb->lnum)
613                         return seb;
614
615                 if (lnum > seb->lnum)
616                         p = p->rb_left;
617                 else
618                         p = p->rb_right;
619         }
620
621         return NULL;
622 }
623
624 /**
625  * ubi_scan_rm_volume - delete scanning information about a volume.
626  * @si: scanning information
627  * @sv: the volume scanning information to delete
628  */
629 void ubi_scan_rm_volume(struct ubi_scan_info *si, struct ubi_scan_volume *sv)
630 {
631         struct rb_node *rb;
632         struct ubi_scan_leb *seb;
633
634         dbg_bld("remove scanning information about volume %d", sv->vol_id);
635
636         while ((rb = rb_first(&sv->root))) {
637                 seb = rb_entry(rb, struct ubi_scan_leb, u.rb);
638                 rb_erase(&seb->u.rb, &sv->root);
639                 list_add_tail(&seb->u.list, &si->erase);
640         }
641
642         rb_erase(&sv->rb, &si->volumes);
643         kfree(sv);
644         si->vols_found -= 1;
645 }
646
647 /**
648  * ubi_scan_erase_peb - erase a physical eraseblock.
649  * @ubi: UBI device description object
650  * @si: scanning information
651  * @pnum: physical eraseblock number to erase;
652  * @ec: erase counter value to write (%UBI_SCAN_UNKNOWN_EC if it is unknown)
653  *
654  * This function erases physical eraseblock 'pnum', and writes the erase
655  * counter header to it. This function should only be used on UBI device
656  * initialization stages, when the EBA sub-system had not been yet initialized.
657  * This function returns zero in case of success and a negative error code in
658  * case of failure.
659  */
660 int ubi_scan_erase_peb(struct ubi_device *ubi, const struct ubi_scan_info *si,
661                        int pnum, int ec)
662 {
663         int err;
664         struct ubi_ec_hdr *ec_hdr;
665
666         if ((long long)ec >= UBI_MAX_ERASECOUNTER) {
667                 /*
668                  * Erase counter overflow. Upgrade UBI and use 64-bit
669                  * erase counters internally.
670                  */
671                 ubi_err("erase counter overflow at PEB %d, EC %d", pnum, ec);
672                 return -EINVAL;
673         }
674
675         ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
676         if (!ec_hdr)
677                 return -ENOMEM;
678
679         ec_hdr->ec = cpu_to_be64(ec);
680
681         err = ubi_io_sync_erase(ubi, pnum, 0);
682         if (err < 0)
683                 goto out_free;
684
685         err = ubi_io_write_ec_hdr(ubi, pnum, ec_hdr);
686
687 out_free:
688         kfree(ec_hdr);
689         return err;
690 }
691
692 /**
693  * ubi_scan_get_free_peb - get a free physical eraseblock.
694  * @ubi: UBI device description object
695  * @si: scanning information
696  *
697  * This function returns a free physical eraseblock. It is supposed to be
698  * called on the UBI initialization stages when the wear-leveling sub-system is
699  * not initialized yet. This function picks a physical eraseblocks from one of
700  * the lists, writes the EC header if it is needed, and removes it from the
701  * list.
702  *
703  * This function returns scanning physical eraseblock information in case of
704  * success and an error code in case of failure.
705  */
706 struct ubi_scan_leb *ubi_scan_get_free_peb(struct ubi_device *ubi,
707                                            struct ubi_scan_info *si)
708 {
709         int err = 0;
710         struct ubi_scan_leb *seb, *tmp_seb;
711
712         if (!list_empty(&si->free)) {
713                 seb = list_entry(si->free.next, struct ubi_scan_leb, u.list);
714                 list_del(&seb->u.list);
715                 dbg_bld("return free PEB %d, EC %d", seb->pnum, seb->ec);
716                 return seb;
717         }
718
719         /*
720          * We try to erase the first physical eraseblock from the erase list
721          * and pick it if we succeed, or try to erase the next one if not. And
722          * so forth. We don't want to take care about bad eraseblocks here -
723          * they'll be handled later.
724          */
725         list_for_each_entry_safe(seb, tmp_seb, &si->erase, u.list) {
726                 if (seb->ec == UBI_SCAN_UNKNOWN_EC)
727                         seb->ec = si->mean_ec;
728
729                 err = ubi_scan_erase_peb(ubi, si, seb->pnum, seb->ec+1);
730                 if (err)
731                         continue;
732
733                 seb->ec += 1;
734                 list_del(&seb->u.list);
735                 dbg_bld("return PEB %d, EC %d", seb->pnum, seb->ec);
736                 return seb;
737         }
738
739         ubi_err("no free eraseblocks");
740         return ERR_PTR(-ENOSPC);
741 }
742
743 /**
744  * check_data_ff - make sure PEB contains only 0xFF data.
745  * @ubi: UBI device description object
746  * @vid_hrd: the (corrupted) VID header of this PEB
747  * @pnum: the physical eraseblock number to check
748  *
749  * This is a helper function which is used to distinguish between VID header
750  * corruptions caused by power cuts and other reasons. If the PEB contains only
751  * 0xFF bytes at the data area, the VID header is most probably corrupted
752  * because of a power cut (%0 is returned in this case). Otherwise, it was
753  * corrupted for some other reasons (%1 is returned in this case). A negative
754  * error code is returned if a read error occurred.
755  *
756  * If the corruption reason was a power cut, UBI can safely erase this PEB.
757  * Otherwise, it should preserve it to avoid possibly destroying important
758  * information.
759  */
760 static int check_data_ff(struct ubi_device *ubi, struct ubi_vid_hdr *vid_hdr,
761                          int pnum)
762 {
763         int err;
764
765         mutex_lock(&ubi->buf_mutex);
766         memset(ubi->peb_buf1, 0x00, ubi->leb_size);
767
768         err = ubi_io_read(ubi, ubi->peb_buf1, pnum, ubi->leb_start,
769                           ubi->leb_size);
770         if (err && err != UBI_IO_BITFLIPS && err != -EBADMSG)
771                 return err;
772
773         if (ubi_check_pattern(ubi->peb_buf1, 0xFF, ubi->leb_size)) {
774                 mutex_unlock(&ubi->buf_mutex);
775                 return 0;
776         }
777
778         ubi_err("PEB %d contains corrupted VID header, and the data does not "
779                 "contain all 0xFF, this may be a non-UBI PEB or a severe VID "
780                 "header corruption which requires manual inspection", pnum);
781         ubi_dbg_dump_vid_hdr(vid_hdr);
782         dbg_msg("hexdump of PEB %d offset %d, length %d",
783                 pnum, ubi->leb_start, ubi->leb_size);
784         ubi_dbg_print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
785                                ubi->peb_buf1, ubi->leb_size, 1);
786         mutex_unlock(&ubi->buf_mutex);
787         return -EINVAL;
788 }
789
790 /**
791  * process_eb - read, check UBI headers, and add them to scanning information.
792  * @ubi: UBI device description object
793  * @si: scanning information
794  * @pnum: the physical eraseblock number
795  *
796  * This function returns a zero if the physical eraseblock was successfully
797  * handled and a negative error code in case of failure.
798  */
799 static int process_eb(struct ubi_device *ubi, struct ubi_scan_info *si,
800                       int pnum)
801 {
802         long long uninitialized_var(ec);
803         int err, bitflips = 0, vol_id, ec_err = 0;
804
805         dbg_bld("scan PEB %d", pnum);
806
807         /* Skip bad physical eraseblocks */
808         err = ubi_io_is_bad(ubi, pnum);
809         if (err < 0)
810                 return err;
811         else if (err) {
812                 /*
813                  * FIXME: this is actually duty of the I/O sub-system to
814                  * initialize this, but MTD does not provide enough
815                  * information.
816                  */
817                 si->bad_peb_count += 1;
818                 return 0;
819         }
820
821         err = ubi_io_read_ec_hdr(ubi, pnum, ech, 0);
822         if (err < 0)
823                 return err;
824         switch (err) {
825         case 0:
826                 break;
827         case UBI_IO_BITFLIPS:
828                 bitflips = 1;
829                 break;
830         case UBI_IO_FF:
831                 si->empty_peb_count += 1;
832                 return add_to_list(si, pnum, UBI_SCAN_UNKNOWN_EC, 0,
833                                    &si->erase);
834         case UBI_IO_FF_BITFLIPS:
835                 si->empty_peb_count += 1;
836                 return add_to_list(si, pnum, UBI_SCAN_UNKNOWN_EC, 1,
837                                    &si->erase);
838         case UBI_IO_BAD_HDR_EBADMSG:
839         case UBI_IO_BAD_HDR:
840                 /*
841                  * We have to also look at the VID header, possibly it is not
842                  * corrupted. Set %bitflips flag in order to make this PEB be
843                  * moved and EC be re-created.
844                  */
845                 ec_err = err;
846                 ec = UBI_SCAN_UNKNOWN_EC;
847                 bitflips = 1;
848                 break;
849         default:
850                 ubi_err("'ubi_io_read_ec_hdr()' returned unknown code %d", err);
851                 return -EINVAL;
852         }
853
854         if (!ec_err) {
855                 int image_seq;
856
857                 /* Make sure UBI version is OK */
858                 if (ech->version != UBI_VERSION) {
859                         ubi_err("this UBI version is %d, image version is %d",
860                                 UBI_VERSION, (int)ech->version);
861                         return -EINVAL;
862                 }
863
864                 ec = be64_to_cpu(ech->ec);
865                 if (ec > UBI_MAX_ERASECOUNTER) {
866                         /*
867                          * Erase counter overflow. The EC headers have 64 bits
868                          * reserved, but we anyway make use of only 31 bit
869                          * values, as this seems to be enough for any existing
870                          * flash. Upgrade UBI and use 64-bit erase counters
871                          * internally.
872                          */
873                         ubi_err("erase counter overflow, max is %d",
874                                 UBI_MAX_ERASECOUNTER);
875                         ubi_dbg_dump_ec_hdr(ech);
876                         return -EINVAL;
877                 }
878
879                 /*
880                  * Make sure that all PEBs have the same image sequence number.
881                  * This allows us to detect situations when users flash UBI
882                  * images incorrectly, so that the flash has the new UBI image
883                  * and leftovers from the old one. This feature was added
884                  * relatively recently, and the sequence number was always
885                  * zero, because old UBI implementations always set it to zero.
886                  * For this reasons, we do not panic if some PEBs have zero
887                  * sequence number, while other PEBs have non-zero sequence
888                  * number.
889                  */
890                 image_seq = be32_to_cpu(ech->image_seq);
891                 if (!ubi->image_seq && image_seq)
892                         ubi->image_seq = image_seq;
893                 if (ubi->image_seq && image_seq &&
894                     ubi->image_seq != image_seq) {
895                         ubi_err("bad image sequence number %d in PEB %d, "
896                                 "expected %d", image_seq, pnum, ubi->image_seq);
897                         ubi_dbg_dump_ec_hdr(ech);
898                         return -EINVAL;
899                 }
900         }
901
902         /* OK, we've done with the EC header, let's look at the VID header */
903
904         err = ubi_io_read_vid_hdr(ubi, pnum, vidh, 0);
905         if (err < 0)
906                 return err;
907         switch (err) {
908         case 0:
909                 break;
910         case UBI_IO_BITFLIPS:
911                 bitflips = 1;
912                 break;
913         case UBI_IO_BAD_HDR_EBADMSG:
914                 if (ec_err == UBI_IO_BAD_HDR_EBADMSG)
915                         /*
916                          * Both EC and VID headers are corrupted and were read
917                          * with data integrity error, probably this is a bad
918                          * PEB, bit it is not marked as bad yet. This may also
919                          * be a result of power cut during erasure.
920                          */
921                         si->maybe_bad_peb_count += 1;
922         case UBI_IO_BAD_HDR:
923                 if (ec_err)
924                         /*
925                          * Both headers are corrupted. There is a possibility
926                          * that this a valid UBI PEB which has corresponding
927                          * LEB, but the headers are corrupted. However, it is
928                          * impossible to distinguish it from a PEB which just
929                          * contains garbage because a power cut during erase
930                          * operation. So we just schedule this PEB for erasure.
931                          */
932                         err = 0;
933                 else
934                         /*
935                          * The EC was OK, but the VID header is corrupted. We
936                          * have to check what is in the data area.
937                          */
938                         err = check_data_ff(ubi, vidh, pnum);
939                 if (!err)
940                         /* This corruption is caused by a power cut */
941                         err = add_to_list(si, pnum, ec, 1, &si->erase);
942                 else
943                         /* This is an unexpected corruption */
944                         err = add_corrupted(si, pnum, ec);
945                 if (err)
946                         return err;
947                 goto adjust_mean_ec;
948         case UBI_IO_FF_BITFLIPS:
949                 err = add_to_list(si, pnum, ec, 1, &si->erase);
950                 if (err)
951                         return err;
952                 goto adjust_mean_ec;
953         case UBI_IO_FF:
954                 if (ec_err)
955                         err = add_to_list(si, pnum, ec, 1, &si->erase);
956                 else
957                         err = add_to_list(si, pnum, ec, 0, &si->free);
958                 if (err)
959                         return err;
960                 goto adjust_mean_ec;
961         default:
962                 ubi_err("'ubi_io_read_vid_hdr()' returned unknown code %d",
963                         err);
964                 return -EINVAL;
965         }
966
967         vol_id = be32_to_cpu(vidh->vol_id);
968         if (vol_id > UBI_MAX_VOLUMES && vol_id != UBI_LAYOUT_VOLUME_ID) {
969                 int lnum = be32_to_cpu(vidh->lnum);
970
971                 /* Unsupported internal volume */
972                 switch (vidh->compat) {
973                 case UBI_COMPAT_DELETE:
974                         ubi_msg("\"delete\" compatible internal volume %d:%d"
975                                 " found, will remove it", vol_id, lnum);
976                         err = add_to_list(si, pnum, ec, 1, &si->erase);
977                         if (err)
978                                 return err;
979                         return 0;
980
981                 case UBI_COMPAT_RO:
982                         ubi_msg("read-only compatible internal volume %d:%d"
983                                 " found, switch to read-only mode",
984                                 vol_id, lnum);
985                         ubi->ro_mode = 1;
986                         break;
987
988                 case UBI_COMPAT_PRESERVE:
989                         ubi_msg("\"preserve\" compatible internal volume %d:%d"
990                                 " found", vol_id, lnum);
991                         err = add_to_list(si, pnum, ec, 0, &si->alien);
992                         if (err)
993                                 return err;
994                         return 0;
995
996                 case UBI_COMPAT_REJECT:
997                         ubi_err("incompatible internal volume %d:%d found",
998                                 vol_id, lnum);
999                         return -EINVAL;
1000                 }
1001         }
1002
1003         if (ec_err)
1004                 ubi_warn("valid VID header but corrupted EC header at PEB %d",
1005                          pnum);
1006         err = ubi_scan_add_used(ubi, si, pnum, ec, vidh, bitflips);
1007         if (err)
1008                 return err;
1009
1010 adjust_mean_ec:
1011         if (!ec_err) {
1012                 si->ec_sum += ec;
1013                 si->ec_count += 1;
1014                 if (ec > si->max_ec)
1015                         si->max_ec = ec;
1016                 if (ec < si->min_ec)
1017                         si->min_ec = ec;
1018         }
1019
1020         return 0;
1021 }
1022
1023 /**
1024  * check_what_we_have - check what PEB were found by scanning.
1025  * @ubi: UBI device description object
1026  * @si: scanning information
1027  *
1028  * This is a helper function which takes a look what PEBs were found by
1029  * scanning, and decides whether the flash is empty and should be formatted and
1030  * whether there are too many corrupted PEBs and we should not attach this
1031  * MTD device. Returns zero if we should proceed with attaching the MTD device,
1032  * and %-EINVAL if we should not.
1033  */
1034 static int check_what_we_have(struct ubi_device *ubi, struct ubi_scan_info *si)
1035 {
1036         struct ubi_scan_leb *seb;
1037         int max_corr, peb_count;
1038
1039         peb_count = ubi->peb_count - si->bad_peb_count - si->alien_peb_count;
1040         max_corr = peb_count / 20 ?: 8;
1041
1042         /*
1043          * Few corrupted PEBs is not a problem and may be just a result of
1044          * unclean reboots. However, many of them may indicate some problems
1045          * with the flash HW or driver.
1046          */
1047         if (si->corr_peb_count) {
1048                 ubi_err("%d PEBs are corrupted and preserved",
1049                         si->corr_peb_count);
1050                 printk(KERN_ERR "Corrupted PEBs are:");
1051                 list_for_each_entry(seb, &si->corr, u.list)
1052                         printk(KERN_CONT " %d", seb->pnum);
1053                 printk(KERN_CONT "\n");
1054
1055                 /*
1056                  * If too many PEBs are corrupted, we refuse attaching,
1057                  * otherwise, only print a warning.
1058                  */
1059                 if (si->corr_peb_count >= max_corr) {
1060                         ubi_err("too many corrupted PEBs, refusing this device");
1061                         return -EINVAL;
1062                 }
1063         }
1064
1065         if (si->empty_peb_count + si->maybe_bad_peb_count == peb_count) {
1066                 /*
1067                  * All PEBs are empty, or almost all - a couple PEBs look like
1068                  * they may be bad PEBs which were not marked as bad yet.
1069                  *
1070                  * This piece of code basically tries to distinguish between
1071                  * the following situations:
1072                  *
1073                  * 1. Flash is empty, but there are few bad PEBs, which are not
1074                  *    marked as bad so far, and which were read with error. We
1075                  *    want to go ahead and format this flash. While formatting,
1076                  *    the faulty PEBs will probably be marked as bad.
1077                  *
1078                  * 2. Flash contains non-UBI data and we do not want to format
1079                  *    it and destroy possibly important information.
1080                  */
1081                 if (si->maybe_bad_peb_count <= 2) {
1082                         si->is_empty = 1;
1083                         ubi_msg("empty MTD device detected");
1084                         get_random_bytes(&ubi->image_seq,
1085                                          sizeof(ubi->image_seq));
1086                 } else {
1087                         ubi_err("MTD device is not UBI-formatted and possibly "
1088                                 "contains non-UBI data - refusing it");
1089                         return -EINVAL;
1090                 }
1091
1092         }
1093
1094         return 0;
1095 }
1096
1097 /**
1098  * ubi_scan - scan an MTD device.
1099  * @ubi: UBI device description object
1100  *
1101  * This function does full scanning of an MTD device and returns complete
1102  * information about it. In case of failure, an error code is returned.
1103  */
1104 struct ubi_scan_info *ubi_scan(struct ubi_device *ubi)
1105 {
1106         int err, pnum;
1107         struct rb_node *rb1, *rb2;
1108         struct ubi_scan_volume *sv;
1109         struct ubi_scan_leb *seb;
1110         struct ubi_scan_info *si;
1111
1112         si = kzalloc(sizeof(struct ubi_scan_info), GFP_KERNEL);
1113         if (!si)
1114                 return ERR_PTR(-ENOMEM);
1115
1116         INIT_LIST_HEAD(&si->corr);
1117         INIT_LIST_HEAD(&si->free);
1118         INIT_LIST_HEAD(&si->erase);
1119         INIT_LIST_HEAD(&si->alien);
1120         si->volumes = RB_ROOT;
1121
1122         err = -ENOMEM;
1123         ech = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
1124         if (!ech)
1125                 goto out_si;
1126
1127         vidh = ubi_zalloc_vid_hdr(ubi, GFP_KERNEL);
1128         if (!vidh)
1129                 goto out_ech;
1130
1131         for (pnum = 0; pnum < ubi->peb_count; pnum++) {
1132                 cond_resched();
1133
1134                 dbg_gen("process PEB %d", pnum);
1135                 err = process_eb(ubi, si, pnum);
1136                 if (err < 0)
1137                         goto out_vidh;
1138         }
1139
1140         dbg_msg("scanning is finished");
1141
1142         /* Calculate mean erase counter */
1143         if (si->ec_count)
1144                 si->mean_ec = div_u64(si->ec_sum, si->ec_count);
1145
1146         err = check_what_we_have(ubi, si);
1147         if (err)
1148                 goto out_vidh;
1149
1150         /*
1151          * In case of unknown erase counter we use the mean erase counter
1152          * value.
1153          */
1154         ubi_rb_for_each_entry(rb1, sv, &si->volumes, rb) {
1155                 ubi_rb_for_each_entry(rb2, seb, &sv->root, u.rb)
1156                         if (seb->ec == UBI_SCAN_UNKNOWN_EC)
1157                                 seb->ec = si->mean_ec;
1158         }
1159
1160         list_for_each_entry(seb, &si->free, u.list) {
1161                 if (seb->ec == UBI_SCAN_UNKNOWN_EC)
1162                         seb->ec = si->mean_ec;
1163         }
1164
1165         list_for_each_entry(seb, &si->corr, u.list)
1166                 if (seb->ec == UBI_SCAN_UNKNOWN_EC)
1167                         seb->ec = si->mean_ec;
1168
1169         list_for_each_entry(seb, &si->erase, u.list)
1170                 if (seb->ec == UBI_SCAN_UNKNOWN_EC)
1171                         seb->ec = si->mean_ec;
1172
1173         err = paranoid_check_si(ubi, si);
1174         if (err)
1175                 goto out_vidh;
1176
1177         ubi_free_vid_hdr(ubi, vidh);
1178         kfree(ech);
1179
1180         return si;
1181
1182 out_vidh:
1183         ubi_free_vid_hdr(ubi, vidh);
1184 out_ech:
1185         kfree(ech);
1186 out_si:
1187         ubi_scan_destroy_si(si);
1188         return ERR_PTR(err);
1189 }
1190
1191 /**
1192  * destroy_sv - free the scanning volume information
1193  * @sv: scanning volume information
1194  *
1195  * This function destroys the volume RB-tree (@sv->root) and the scanning
1196  * volume information.
1197  */
1198 static void destroy_sv(struct ubi_scan_volume *sv)
1199 {
1200         struct ubi_scan_leb *seb;
1201         struct rb_node *this = sv->root.rb_node;
1202
1203         while (this) {
1204                 if (this->rb_left)
1205                         this = this->rb_left;
1206                 else if (this->rb_right)
1207                         this = this->rb_right;
1208                 else {
1209                         seb = rb_entry(this, struct ubi_scan_leb, u.rb);
1210                         this = rb_parent(this);
1211                         if (this) {
1212                                 if (this->rb_left == &seb->u.rb)
1213                                         this->rb_left = NULL;
1214                                 else
1215                                         this->rb_right = NULL;
1216                         }
1217
1218                         kfree(seb);
1219                 }
1220         }
1221         kfree(sv);
1222 }
1223
1224 /**
1225  * ubi_scan_destroy_si - destroy scanning information.
1226  * @si: scanning information
1227  */
1228 void ubi_scan_destroy_si(struct ubi_scan_info *si)
1229 {
1230         struct ubi_scan_leb *seb, *seb_tmp;
1231         struct ubi_scan_volume *sv;
1232         struct rb_node *rb;
1233
1234         list_for_each_entry_safe(seb, seb_tmp, &si->alien, u.list) {
1235                 list_del(&seb->u.list);
1236                 kfree(seb);
1237         }
1238         list_for_each_entry_safe(seb, seb_tmp, &si->erase, u.list) {
1239                 list_del(&seb->u.list);
1240                 kfree(seb);
1241         }
1242         list_for_each_entry_safe(seb, seb_tmp, &si->corr, u.list) {
1243                 list_del(&seb->u.list);
1244                 kfree(seb);
1245         }
1246         list_for_each_entry_safe(seb, seb_tmp, &si->free, u.list) {
1247                 list_del(&seb->u.list);
1248                 kfree(seb);
1249         }
1250
1251         /* Destroy the volume RB-tree */
1252         rb = si->volumes.rb_node;
1253         while (rb) {
1254                 if (rb->rb_left)
1255                         rb = rb->rb_left;
1256                 else if (rb->rb_right)
1257                         rb = rb->rb_right;
1258                 else {
1259                         sv = rb_entry(rb, struct ubi_scan_volume, rb);
1260
1261                         rb = rb_parent(rb);
1262                         if (rb) {
1263                                 if (rb->rb_left == &sv->rb)
1264                                         rb->rb_left = NULL;
1265                                 else
1266                                         rb->rb_right = NULL;
1267                         }
1268
1269                         destroy_sv(sv);
1270                 }
1271         }
1272
1273         kfree(si);
1274 }
1275
1276 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
1277
1278 /**
1279  * paranoid_check_si - check the scanning information.
1280  * @ubi: UBI device description object
1281  * @si: scanning information
1282  *
1283  * This function returns zero if the scanning information is all right, and a
1284  * negative error code if not or if an error occurred.
1285  */
1286 static int paranoid_check_si(struct ubi_device *ubi, struct ubi_scan_info *si)
1287 {
1288         int pnum, err, vols_found = 0;
1289         struct rb_node *rb1, *rb2;
1290         struct ubi_scan_volume *sv;
1291         struct ubi_scan_leb *seb, *last_seb;
1292         uint8_t *buf;
1293
1294         /*
1295          * At first, check that scanning information is OK.
1296          */
1297         ubi_rb_for_each_entry(rb1, sv, &si->volumes, rb) {
1298                 int leb_count = 0;
1299
1300                 cond_resched();
1301
1302                 vols_found += 1;
1303
1304                 if (si->is_empty) {
1305                         ubi_err("bad is_empty flag");
1306                         goto bad_sv;
1307                 }
1308
1309                 if (sv->vol_id < 0 || sv->highest_lnum < 0 ||
1310                     sv->leb_count < 0 || sv->vol_type < 0 || sv->used_ebs < 0 ||
1311                     sv->data_pad < 0 || sv->last_data_size < 0) {
1312                         ubi_err("negative values");
1313                         goto bad_sv;
1314                 }
1315
1316                 if (sv->vol_id >= UBI_MAX_VOLUMES &&
1317                     sv->vol_id < UBI_INTERNAL_VOL_START) {
1318                         ubi_err("bad vol_id");
1319                         goto bad_sv;
1320                 }
1321
1322                 if (sv->vol_id > si->highest_vol_id) {
1323                         ubi_err("highest_vol_id is %d, but vol_id %d is there",
1324                                 si->highest_vol_id, sv->vol_id);
1325                         goto out;
1326                 }
1327
1328                 if (sv->vol_type != UBI_DYNAMIC_VOLUME &&
1329                     sv->vol_type != UBI_STATIC_VOLUME) {
1330                         ubi_err("bad vol_type");
1331                         goto bad_sv;
1332                 }
1333
1334                 if (sv->data_pad > ubi->leb_size / 2) {
1335                         ubi_err("bad data_pad");
1336                         goto bad_sv;
1337                 }
1338
1339                 last_seb = NULL;
1340                 ubi_rb_for_each_entry(rb2, seb, &sv->root, u.rb) {
1341                         cond_resched();
1342
1343                         last_seb = seb;
1344                         leb_count += 1;
1345
1346                         if (seb->pnum < 0 || seb->ec < 0) {
1347                                 ubi_err("negative values");
1348                                 goto bad_seb;
1349                         }
1350
1351                         if (seb->ec < si->min_ec) {
1352                                 ubi_err("bad si->min_ec (%d), %d found",
1353                                         si->min_ec, seb->ec);
1354                                 goto bad_seb;
1355                         }
1356
1357                         if (seb->ec > si->max_ec) {
1358                                 ubi_err("bad si->max_ec (%d), %d found",
1359                                         si->max_ec, seb->ec);
1360                                 goto bad_seb;
1361                         }
1362
1363                         if (seb->pnum >= ubi->peb_count) {
1364                                 ubi_err("too high PEB number %d, total PEBs %d",
1365                                         seb->pnum, ubi->peb_count);
1366                                 goto bad_seb;
1367                         }
1368
1369                         if (sv->vol_type == UBI_STATIC_VOLUME) {
1370                                 if (seb->lnum >= sv->used_ebs) {
1371                                         ubi_err("bad lnum or used_ebs");
1372                                         goto bad_seb;
1373                                 }
1374                         } else {
1375                                 if (sv->used_ebs != 0) {
1376                                         ubi_err("non-zero used_ebs");
1377                                         goto bad_seb;
1378                                 }
1379                         }
1380
1381                         if (seb->lnum > sv->highest_lnum) {
1382                                 ubi_err("incorrect highest_lnum or lnum");
1383                                 goto bad_seb;
1384                         }
1385                 }
1386
1387                 if (sv->leb_count != leb_count) {
1388                         ubi_err("bad leb_count, %d objects in the tree",
1389                                 leb_count);
1390                         goto bad_sv;
1391                 }
1392
1393                 if (!last_seb)
1394                         continue;
1395
1396                 seb = last_seb;
1397
1398                 if (seb->lnum != sv->highest_lnum) {
1399                         ubi_err("bad highest_lnum");
1400                         goto bad_seb;
1401                 }
1402         }
1403
1404         if (vols_found != si->vols_found) {
1405                 ubi_err("bad si->vols_found %d, should be %d",
1406                         si->vols_found, vols_found);
1407                 goto out;
1408         }
1409
1410         /* Check that scanning information is correct */
1411         ubi_rb_for_each_entry(rb1, sv, &si->volumes, rb) {
1412                 last_seb = NULL;
1413                 ubi_rb_for_each_entry(rb2, seb, &sv->root, u.rb) {
1414                         int vol_type;
1415
1416                         cond_resched();
1417
1418                         last_seb = seb;
1419
1420                         err = ubi_io_read_vid_hdr(ubi, seb->pnum, vidh, 1);
1421                         if (err && err != UBI_IO_BITFLIPS) {
1422                                 ubi_err("VID header is not OK (%d)", err);
1423                                 if (err > 0)
1424                                         err = -EIO;
1425                                 return err;
1426                         }
1427
1428                         vol_type = vidh->vol_type == UBI_VID_DYNAMIC ?
1429                                    UBI_DYNAMIC_VOLUME : UBI_STATIC_VOLUME;
1430                         if (sv->vol_type != vol_type) {
1431                                 ubi_err("bad vol_type");
1432                                 goto bad_vid_hdr;
1433                         }
1434
1435                         if (seb->sqnum != be64_to_cpu(vidh->sqnum)) {
1436                                 ubi_err("bad sqnum %llu", seb->sqnum);
1437                                 goto bad_vid_hdr;
1438                         }
1439
1440                         if (sv->vol_id != be32_to_cpu(vidh->vol_id)) {
1441                                 ubi_err("bad vol_id %d", sv->vol_id);
1442                                 goto bad_vid_hdr;
1443                         }
1444
1445                         if (sv->compat != vidh->compat) {
1446                                 ubi_err("bad compat %d", vidh->compat);
1447                                 goto bad_vid_hdr;
1448                         }
1449
1450                         if (seb->lnum != be32_to_cpu(vidh->lnum)) {
1451                                 ubi_err("bad lnum %d", seb->lnum);
1452                                 goto bad_vid_hdr;
1453                         }
1454
1455                         if (sv->used_ebs != be32_to_cpu(vidh->used_ebs)) {
1456                                 ubi_err("bad used_ebs %d", sv->used_ebs);
1457                                 goto bad_vid_hdr;
1458                         }
1459
1460                         if (sv->data_pad != be32_to_cpu(vidh->data_pad)) {
1461                                 ubi_err("bad data_pad %d", sv->data_pad);
1462                                 goto bad_vid_hdr;
1463                         }
1464                 }
1465
1466                 if (!last_seb)
1467                         continue;
1468
1469                 if (sv->highest_lnum != be32_to_cpu(vidh->lnum)) {
1470                         ubi_err("bad highest_lnum %d", sv->highest_lnum);
1471                         goto bad_vid_hdr;
1472                 }
1473
1474                 if (sv->last_data_size != be32_to_cpu(vidh->data_size)) {
1475                         ubi_err("bad last_data_size %d", sv->last_data_size);
1476                         goto bad_vid_hdr;
1477                 }
1478         }
1479
1480         /*
1481          * Make sure that all the physical eraseblocks are in one of the lists
1482          * or trees.
1483          */
1484         buf = kzalloc(ubi->peb_count, GFP_KERNEL);
1485         if (!buf)
1486                 return -ENOMEM;
1487
1488         for (pnum = 0; pnum < ubi->peb_count; pnum++) {
1489                 err = ubi_io_is_bad(ubi, pnum);
1490                 if (err < 0) {
1491                         kfree(buf);
1492                         return err;
1493                 } else if (err)
1494                         buf[pnum] = 1;
1495         }
1496
1497         ubi_rb_for_each_entry(rb1, sv, &si->volumes, rb)
1498                 ubi_rb_for_each_entry(rb2, seb, &sv->root, u.rb)
1499                         buf[seb->pnum] = 1;
1500
1501         list_for_each_entry(seb, &si->free, u.list)
1502                 buf[seb->pnum] = 1;
1503
1504         list_for_each_entry(seb, &si->corr, u.list)
1505                 buf[seb->pnum] = 1;
1506
1507         list_for_each_entry(seb, &si->erase, u.list)
1508                 buf[seb->pnum] = 1;
1509
1510         list_for_each_entry(seb, &si->alien, u.list)
1511                 buf[seb->pnum] = 1;
1512
1513         err = 0;
1514         for (pnum = 0; pnum < ubi->peb_count; pnum++)
1515                 if (!buf[pnum]) {
1516                         ubi_err("PEB %d is not referred", pnum);
1517                         err = 1;
1518                 }
1519
1520         kfree(buf);
1521         if (err)
1522                 goto out;
1523         return 0;
1524
1525 bad_seb:
1526         ubi_err("bad scanning information about LEB %d", seb->lnum);
1527         ubi_dbg_dump_seb(seb, 0);
1528         ubi_dbg_dump_sv(sv);
1529         goto out;
1530
1531 bad_sv:
1532         ubi_err("bad scanning information about volume %d", sv->vol_id);
1533         ubi_dbg_dump_sv(sv);
1534         goto out;
1535
1536 bad_vid_hdr:
1537         ubi_err("bad scanning information about volume %d", sv->vol_id);
1538         ubi_dbg_dump_sv(sv);
1539         ubi_dbg_dump_vid_hdr(vidh);
1540
1541 out:
1542         ubi_dbg_dump_stack();
1543         return -EINVAL;
1544 }
1545
1546 #endif /* CONFIG_MTD_UBI_DEBUG_PARANOID */