Merge tag 'upstream-4.9-rc1' of git://git.infradead.org/linux-ubifs
[cascardo/linux.git] / drivers / mtd / ubi / attach.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 attaching sub-system.
23  *
24  * This sub-system is responsible for attaching MTD devices and it also
25  * implements flash media scanning.
26  *
27  * The attaching information is represented by a &struct ubi_attach_info'
28  * object. Information about volumes is represented by &struct ubi_ainf_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  * Logical eraseblocks are represented by &struct ubi_ainf_peb objects. These
33  * objects are kept in per-volume RB-trees with the root at the corresponding
34  * &struct ubi_ainf_volume object. To put it differently, we keep an RB-tree of
35  * per-volume objects and each of these objects is the root of RB-tree of
36  * per-LEB 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  * About corruptions
43  * ~~~~~~~~~~~~~~~~~
44  *
45  * UBI protects EC and VID headers with CRC-32 checksums, so it can detect
46  * whether the headers are corrupted or not. Sometimes UBI also protects the
47  * data with CRC-32, e.g., when it executes the atomic LEB change operation, or
48  * when it moves the contents of a PEB for wear-leveling purposes.
49  *
50  * UBI tries to distinguish between 2 types of corruptions.
51  *
52  * 1. Corruptions caused by power cuts. These are expected corruptions and UBI
53  * tries to handle them gracefully, without printing too many warnings and
54  * error messages. The idea is that we do not lose important data in these
55  * cases - we may lose only the data which were being written to the media just
56  * before the power cut happened, and the upper layers (e.g., UBIFS) are
57  * supposed to handle such data losses (e.g., by using the FS journal).
58  *
59  * When UBI detects a corruption (CRC-32 mismatch) in a PEB, and it looks like
60  * the reason is a power cut, UBI puts this PEB to the @erase list, and all
61  * PEBs in the @erase list are scheduled for erasure later.
62  *
63  * 2. Unexpected corruptions which are not caused by power cuts. During
64  * attaching, such PEBs are put to the @corr list and UBI preserves them.
65  * Obviously, this lessens the amount of available PEBs, and if at some  point
66  * UBI runs out of free PEBs, it switches to R/O mode. UBI also loudly informs
67  * about such PEBs every time the MTD device is attached.
68  *
69  * However, it is difficult to reliably distinguish between these types of
70  * corruptions and UBI's strategy is as follows (in case of attaching by
71  * scanning). UBI assumes corruption type 2 if the VID header is corrupted and
72  * the data area does not contain all 0xFFs, and there were no bit-flips or
73  * integrity errors (e.g., ECC errors in case of NAND) while reading the data
74  * area.  Otherwise UBI assumes corruption type 1. So the decision criteria
75  * are as follows.
76  *   o If the data area contains only 0xFFs, there are no data, and it is safe
77  *     to just erase this PEB - this is corruption type 1.
78  *   o If the data area has bit-flips or data integrity errors (ECC errors on
79  *     NAND), it is probably a PEB which was being erased when power cut
80  *     happened, so this is corruption type 1. However, this is just a guess,
81  *     which might be wrong.
82  *   o Otherwise this is corruption type 2.
83  */
84
85 #include <linux/err.h>
86 #include <linux/slab.h>
87 #include <linux/crc32.h>
88 #include <linux/math64.h>
89 #include <linux/random.h>
90 #include "ubi.h"
91
92 static int self_check_ai(struct ubi_device *ubi, struct ubi_attach_info *ai);
93
94 #define AV_FIND         BIT(0)
95 #define AV_ADD          BIT(1)
96 #define AV_FIND_OR_ADD  (AV_FIND | AV_ADD)
97
98 /**
99  * find_or_add_av - internal function to find a volume, add a volume or do
100  *                  both (find and add if missing).
101  * @ai: attaching information
102  * @vol_id: the requested volume ID
103  * @flags: a combination of the %AV_FIND and %AV_ADD flags describing the
104  *         expected operation. If only %AV_ADD is set, -EEXIST is returned
105  *         if the volume already exists. If only %AV_FIND is set, NULL is
106  *         returned if the volume does not exist. And if both flags are
107  *         set, the helper first tries to find an existing volume, and if
108  *         it does not exist it creates a new one.
109  * @created: in value used to inform the caller whether it"s a newly created
110  *           volume or not.
111  *
112  * This function returns a pointer to a volume description or an ERR_PTR if
113  * the operation failed. It can also return NULL if only %AV_FIND is set and
114  * the volume does not exist.
115  */
116 static struct ubi_ainf_volume *find_or_add_av(struct ubi_attach_info *ai,
117                                               int vol_id, unsigned int flags,
118                                               bool *created)
119 {
120         struct ubi_ainf_volume *av;
121         struct rb_node **p = &ai->volumes.rb_node, *parent = NULL;
122
123         /* Walk the volume RB-tree to look if this volume is already present */
124         while (*p) {
125                 parent = *p;
126                 av = rb_entry(parent, struct ubi_ainf_volume, rb);
127
128                 if (vol_id == av->vol_id) {
129                         *created = false;
130
131                         if (!(flags & AV_FIND))
132                                 return ERR_PTR(-EEXIST);
133
134                         return av;
135                 }
136
137                 if (vol_id > av->vol_id)
138                         p = &(*p)->rb_left;
139                 else
140                         p = &(*p)->rb_right;
141         }
142
143         if (!(flags & AV_ADD))
144                 return NULL;
145
146         /* The volume is absent - add it */
147         av = kzalloc(sizeof(*av), GFP_KERNEL);
148         if (!av)
149                 return ERR_PTR(-ENOMEM);
150
151         av->vol_id = vol_id;
152
153         if (vol_id > ai->highest_vol_id)
154                 ai->highest_vol_id = vol_id;
155
156         rb_link_node(&av->rb, parent, p);
157         rb_insert_color(&av->rb, &ai->volumes);
158         ai->vols_found += 1;
159         *created = true;
160         dbg_bld("added volume %d", vol_id);
161         return av;
162 }
163
164 /**
165  * ubi_find_or_add_av - search for a volume in the attaching information and
166  *                      add one if it does not exist.
167  * @ai: attaching information
168  * @vol_id: the requested volume ID
169  * @created: whether the volume has been created or not
170  *
171  * This function returns a pointer to the new volume description or an
172  * ERR_PTR if the operation failed.
173  */
174 static struct ubi_ainf_volume *ubi_find_or_add_av(struct ubi_attach_info *ai,
175                                                   int vol_id, bool *created)
176 {
177         return find_or_add_av(ai, vol_id, AV_FIND_OR_ADD, created);
178 }
179
180 /**
181  * ubi_alloc_aeb - allocate an aeb element
182  * @ai: attaching information
183  * @pnum: physical eraseblock number
184  * @ec: erase counter of the physical eraseblock
185  *
186  * Allocate an aeb object and initialize the pnum and ec information.
187  * vol_id and lnum are set to UBI_UNKNOWN, and the other fields are
188  * initialized to zero.
189  * Note that the element is not added in any list or RB tree.
190  */
191 struct ubi_ainf_peb *ubi_alloc_aeb(struct ubi_attach_info *ai, int pnum,
192                                    int ec)
193 {
194         struct ubi_ainf_peb *aeb;
195
196         aeb = kmem_cache_zalloc(ai->aeb_slab_cache, GFP_KERNEL);
197         if (!aeb)
198                 return NULL;
199
200         aeb->pnum = pnum;
201         aeb->ec = ec;
202         aeb->vol_id = UBI_UNKNOWN;
203         aeb->lnum = UBI_UNKNOWN;
204
205         return aeb;
206 }
207
208 /**
209  * ubi_free_aeb - free an aeb element
210  * @ai: attaching information
211  * @aeb: the element to free
212  *
213  * Free an aeb object. The caller must have removed the element from any list
214  * or RB tree.
215  */
216 void ubi_free_aeb(struct ubi_attach_info *ai, struct ubi_ainf_peb *aeb)
217 {
218         kmem_cache_free(ai->aeb_slab_cache, aeb);
219 }
220
221 /**
222  * add_to_list - add physical eraseblock to a list.
223  * @ai: attaching information
224  * @pnum: physical eraseblock number to add
225  * @vol_id: the last used volume id for the PEB
226  * @lnum: the last used LEB number for the PEB
227  * @ec: erase counter of the physical eraseblock
228  * @to_head: if not zero, add to the head of the list
229  * @list: the list to add to
230  *
231  * This function allocates a 'struct ubi_ainf_peb' object for physical
232  * eraseblock @pnum and adds it to the "free", "erase", or "alien" lists.
233  * It stores the @lnum and @vol_id alongside, which can both be
234  * %UBI_UNKNOWN if they are not available, not readable, or not assigned.
235  * If @to_head is not zero, PEB will be added to the head of the list, which
236  * basically means it will be processed first later. E.g., we add corrupted
237  * PEBs (corrupted due to power cuts) to the head of the erase list to make
238  * sure we erase them first and get rid of corruptions ASAP. This function
239  * returns zero in case of success and a negative error code in case of
240  * failure.
241  */
242 static int add_to_list(struct ubi_attach_info *ai, int pnum, int vol_id,
243                        int lnum, int ec, int to_head, struct list_head *list)
244 {
245         struct ubi_ainf_peb *aeb;
246
247         if (list == &ai->free) {
248                 dbg_bld("add to free: PEB %d, EC %d", pnum, ec);
249         } else if (list == &ai->erase) {
250                 dbg_bld("add to erase: PEB %d, EC %d", pnum, ec);
251         } else if (list == &ai->alien) {
252                 dbg_bld("add to alien: PEB %d, EC %d", pnum, ec);
253                 ai->alien_peb_count += 1;
254         } else
255                 BUG();
256
257         aeb = ubi_alloc_aeb(ai, pnum, ec);
258         if (!aeb)
259                 return -ENOMEM;
260
261         aeb->vol_id = vol_id;
262         aeb->lnum = lnum;
263         if (to_head)
264                 list_add(&aeb->u.list, list);
265         else
266                 list_add_tail(&aeb->u.list, list);
267         return 0;
268 }
269
270 /**
271  * add_corrupted - add a corrupted physical eraseblock.
272  * @ai: attaching information
273  * @pnum: physical eraseblock number to add
274  * @ec: erase counter of the physical eraseblock
275  *
276  * This function allocates a 'struct ubi_ainf_peb' object for a corrupted
277  * physical eraseblock @pnum and adds it to the 'corr' list.  The corruption
278  * was presumably not caused by a power cut. Returns zero in case of success
279  * and a negative error code in case of failure.
280  */
281 static int add_corrupted(struct ubi_attach_info *ai, int pnum, int ec)
282 {
283         struct ubi_ainf_peb *aeb;
284
285         dbg_bld("add to corrupted: PEB %d, EC %d", pnum, ec);
286
287         aeb = ubi_alloc_aeb(ai, pnum, ec);
288         if (!aeb)
289                 return -ENOMEM;
290
291         ai->corr_peb_count += 1;
292         list_add(&aeb->u.list, &ai->corr);
293         return 0;
294 }
295
296 /**
297  * add_fastmap - add a Fastmap related physical eraseblock.
298  * @ai: attaching information
299  * @pnum: physical eraseblock number the VID header came from
300  * @vid_hdr: the volume identifier header
301  * @ec: erase counter of the physical eraseblock
302  *
303  * This function allocates a 'struct ubi_ainf_peb' object for a Fastamp
304  * physical eraseblock @pnum and adds it to the 'fastmap' list.
305  * Such blocks can be Fastmap super and data blocks from both the most
306  * recent Fastmap we're attaching from or from old Fastmaps which will
307  * be erased.
308  */
309 static int add_fastmap(struct ubi_attach_info *ai, int pnum,
310                        struct ubi_vid_hdr *vid_hdr, int ec)
311 {
312         struct ubi_ainf_peb *aeb;
313
314         aeb = ubi_alloc_aeb(ai, pnum, ec);
315         if (!aeb)
316                 return -ENOMEM;
317
318         aeb->vol_id = be32_to_cpu(vid_hdr->vol_id);
319         aeb->sqnum = be64_to_cpu(vid_hdr->sqnum);
320         list_add(&aeb->u.list, &ai->fastmap);
321
322         dbg_bld("add to fastmap list: PEB %d, vol_id %d, sqnum: %llu", pnum,
323                 aeb->vol_id, aeb->sqnum);
324
325         return 0;
326 }
327
328 /**
329  * validate_vid_hdr - check volume identifier header.
330  * @ubi: UBI device description object
331  * @vid_hdr: the volume identifier header to check
332  * @av: information about the volume this logical eraseblock belongs to
333  * @pnum: physical eraseblock number the VID header came from
334  *
335  * This function checks that data stored in @vid_hdr is consistent. Returns
336  * non-zero if an inconsistency was found and zero if not.
337  *
338  * Note, UBI does sanity check of everything it reads from the flash media.
339  * Most of the checks are done in the I/O sub-system. Here we check that the
340  * information in the VID header is consistent to the information in other VID
341  * headers of the same volume.
342  */
343 static int validate_vid_hdr(const struct ubi_device *ubi,
344                             const struct ubi_vid_hdr *vid_hdr,
345                             const struct ubi_ainf_volume *av, int pnum)
346 {
347         int vol_type = vid_hdr->vol_type;
348         int vol_id = be32_to_cpu(vid_hdr->vol_id);
349         int used_ebs = be32_to_cpu(vid_hdr->used_ebs);
350         int data_pad = be32_to_cpu(vid_hdr->data_pad);
351
352         if (av->leb_count != 0) {
353                 int av_vol_type;
354
355                 /*
356                  * This is not the first logical eraseblock belonging to this
357                  * volume. Ensure that the data in its VID header is consistent
358                  * to the data in previous logical eraseblock headers.
359                  */
360
361                 if (vol_id != av->vol_id) {
362                         ubi_err(ubi, "inconsistent vol_id");
363                         goto bad;
364                 }
365
366                 if (av->vol_type == UBI_STATIC_VOLUME)
367                         av_vol_type = UBI_VID_STATIC;
368                 else
369                         av_vol_type = UBI_VID_DYNAMIC;
370
371                 if (vol_type != av_vol_type) {
372                         ubi_err(ubi, "inconsistent vol_type");
373                         goto bad;
374                 }
375
376                 if (used_ebs != av->used_ebs) {
377                         ubi_err(ubi, "inconsistent used_ebs");
378                         goto bad;
379                 }
380
381                 if (data_pad != av->data_pad) {
382                         ubi_err(ubi, "inconsistent data_pad");
383                         goto bad;
384                 }
385         }
386
387         return 0;
388
389 bad:
390         ubi_err(ubi, "inconsistent VID header at PEB %d", pnum);
391         ubi_dump_vid_hdr(vid_hdr);
392         ubi_dump_av(av);
393         return -EINVAL;
394 }
395
396 /**
397  * add_volume - add volume to the attaching information.
398  * @ai: attaching information
399  * @vol_id: ID of the volume to add
400  * @pnum: physical eraseblock number
401  * @vid_hdr: volume identifier header
402  *
403  * If the volume corresponding to the @vid_hdr logical eraseblock is already
404  * present in the attaching information, this function does nothing. Otherwise
405  * it adds corresponding volume to the attaching information. Returns a pointer
406  * to the allocated "av" object in case of success and a negative error code in
407  * case of failure.
408  */
409 static struct ubi_ainf_volume *add_volume(struct ubi_attach_info *ai,
410                                           int vol_id, int pnum,
411                                           const struct ubi_vid_hdr *vid_hdr)
412 {
413         struct ubi_ainf_volume *av;
414         bool created;
415
416         ubi_assert(vol_id == be32_to_cpu(vid_hdr->vol_id));
417
418         av = ubi_find_or_add_av(ai, vol_id, &created);
419         if (IS_ERR(av) || !created)
420                 return av;
421
422         av->used_ebs = be32_to_cpu(vid_hdr->used_ebs);
423         av->data_pad = be32_to_cpu(vid_hdr->data_pad);
424         av->compat = vid_hdr->compat;
425         av->vol_type = vid_hdr->vol_type == UBI_VID_DYNAMIC ? UBI_DYNAMIC_VOLUME
426                                                             : UBI_STATIC_VOLUME;
427
428         return av;
429 }
430
431 /**
432  * ubi_compare_lebs - find out which logical eraseblock is newer.
433  * @ubi: UBI device description object
434  * @aeb: first logical eraseblock to compare
435  * @pnum: physical eraseblock number of the second logical eraseblock to
436  * compare
437  * @vid_hdr: volume identifier header of the second logical eraseblock
438  *
439  * This function compares 2 copies of a LEB and informs which one is newer. In
440  * case of success this function returns a positive value, in case of failure, a
441  * negative error code is returned. The success return codes use the following
442  * bits:
443  *     o bit 0 is cleared: the first PEB (described by @aeb) is newer than the
444  *       second PEB (described by @pnum and @vid_hdr);
445  *     o bit 0 is set: the second PEB is newer;
446  *     o bit 1 is cleared: no bit-flips were detected in the newer LEB;
447  *     o bit 1 is set: bit-flips were detected in the newer LEB;
448  *     o bit 2 is cleared: the older LEB is not corrupted;
449  *     o bit 2 is set: the older LEB is corrupted.
450  */
451 int ubi_compare_lebs(struct ubi_device *ubi, const struct ubi_ainf_peb *aeb,
452                         int pnum, const struct ubi_vid_hdr *vid_hdr)
453 {
454         int len, err, second_is_newer, bitflips = 0, corrupted = 0;
455         uint32_t data_crc, crc;
456         struct ubi_vid_io_buf *vidb = NULL;
457         unsigned long long sqnum2 = be64_to_cpu(vid_hdr->sqnum);
458
459         if (sqnum2 == aeb->sqnum) {
460                 /*
461                  * This must be a really ancient UBI image which has been
462                  * created before sequence numbers support has been added. At
463                  * that times we used 32-bit LEB versions stored in logical
464                  * eraseblocks. That was before UBI got into mainline. We do not
465                  * support these images anymore. Well, those images still work,
466                  * but only if no unclean reboots happened.
467                  */
468                 ubi_err(ubi, "unsupported on-flash UBI format");
469                 return -EINVAL;
470         }
471
472         /* Obviously the LEB with lower sequence counter is older */
473         second_is_newer = (sqnum2 > aeb->sqnum);
474
475         /*
476          * Now we know which copy is newer. If the copy flag of the PEB with
477          * newer version is not set, then we just return, otherwise we have to
478          * check data CRC. For the second PEB we already have the VID header,
479          * for the first one - we'll need to re-read it from flash.
480          *
481          * Note: this may be optimized so that we wouldn't read twice.
482          */
483
484         if (second_is_newer) {
485                 if (!vid_hdr->copy_flag) {
486                         /* It is not a copy, so it is newer */
487                         dbg_bld("second PEB %d is newer, copy_flag is unset",
488                                 pnum);
489                         return 1;
490                 }
491         } else {
492                 if (!aeb->copy_flag) {
493                         /* It is not a copy, so it is newer */
494                         dbg_bld("first PEB %d is newer, copy_flag is unset",
495                                 pnum);
496                         return bitflips << 1;
497                 }
498
499                 vidb = ubi_alloc_vid_buf(ubi, GFP_KERNEL);
500                 if (!vidb)
501                         return -ENOMEM;
502
503                 pnum = aeb->pnum;
504                 err = ubi_io_read_vid_hdr(ubi, pnum, vidb, 0);
505                 if (err) {
506                         if (err == UBI_IO_BITFLIPS)
507                                 bitflips = 1;
508                         else {
509                                 ubi_err(ubi, "VID of PEB %d header is bad, but it was OK earlier, err %d",
510                                         pnum, err);
511                                 if (err > 0)
512                                         err = -EIO;
513
514                                 goto out_free_vidh;
515                         }
516                 }
517
518                 vid_hdr = ubi_get_vid_hdr(vidb);
519         }
520
521         /* Read the data of the copy and check the CRC */
522
523         len = be32_to_cpu(vid_hdr->data_size);
524
525         mutex_lock(&ubi->buf_mutex);
526         err = ubi_io_read_data(ubi, ubi->peb_buf, pnum, 0, len);
527         if (err && err != UBI_IO_BITFLIPS && !mtd_is_eccerr(err))
528                 goto out_unlock;
529
530         data_crc = be32_to_cpu(vid_hdr->data_crc);
531         crc = crc32(UBI_CRC32_INIT, ubi->peb_buf, len);
532         if (crc != data_crc) {
533                 dbg_bld("PEB %d CRC error: calculated %#08x, must be %#08x",
534                         pnum, crc, data_crc);
535                 corrupted = 1;
536                 bitflips = 0;
537                 second_is_newer = !second_is_newer;
538         } else {
539                 dbg_bld("PEB %d CRC is OK", pnum);
540                 bitflips |= !!err;
541         }
542         mutex_unlock(&ubi->buf_mutex);
543
544         ubi_free_vid_buf(vidb);
545
546         if (second_is_newer)
547                 dbg_bld("second PEB %d is newer, copy_flag is set", pnum);
548         else
549                 dbg_bld("first PEB %d is newer, copy_flag is set", pnum);
550
551         return second_is_newer | (bitflips << 1) | (corrupted << 2);
552
553 out_unlock:
554         mutex_unlock(&ubi->buf_mutex);
555 out_free_vidh:
556         ubi_free_vid_buf(vidb);
557         return err;
558 }
559
560 /**
561  * ubi_add_to_av - add used physical eraseblock to the attaching information.
562  * @ubi: UBI device description object
563  * @ai: attaching information
564  * @pnum: the physical eraseblock number
565  * @ec: erase counter
566  * @vid_hdr: the volume identifier header
567  * @bitflips: if bit-flips were detected when this physical eraseblock was read
568  *
569  * This function adds information about a used physical eraseblock to the
570  * 'used' tree of the corresponding volume. The function is rather complex
571  * because it has to handle cases when this is not the first physical
572  * eraseblock belonging to the same logical eraseblock, and the newer one has
573  * to be picked, while the older one has to be dropped. This function returns
574  * zero in case of success and a negative error code in case of failure.
575  */
576 int ubi_add_to_av(struct ubi_device *ubi, struct ubi_attach_info *ai, int pnum,
577                   int ec, const struct ubi_vid_hdr *vid_hdr, int bitflips)
578 {
579         int err, vol_id, lnum;
580         unsigned long long sqnum;
581         struct ubi_ainf_volume *av;
582         struct ubi_ainf_peb *aeb;
583         struct rb_node **p, *parent = NULL;
584
585         vol_id = be32_to_cpu(vid_hdr->vol_id);
586         lnum = be32_to_cpu(vid_hdr->lnum);
587         sqnum = be64_to_cpu(vid_hdr->sqnum);
588
589         dbg_bld("PEB %d, LEB %d:%d, EC %d, sqnum %llu, bitflips %d",
590                 pnum, vol_id, lnum, ec, sqnum, bitflips);
591
592         av = add_volume(ai, vol_id, pnum, vid_hdr);
593         if (IS_ERR(av))
594                 return PTR_ERR(av);
595
596         if (ai->max_sqnum < sqnum)
597                 ai->max_sqnum = sqnum;
598
599         /*
600          * Walk the RB-tree of logical eraseblocks of volume @vol_id to look
601          * if this is the first instance of this logical eraseblock or not.
602          */
603         p = &av->root.rb_node;
604         while (*p) {
605                 int cmp_res;
606
607                 parent = *p;
608                 aeb = rb_entry(parent, struct ubi_ainf_peb, u.rb);
609                 if (lnum != aeb->lnum) {
610                         if (lnum < aeb->lnum)
611                                 p = &(*p)->rb_left;
612                         else
613                                 p = &(*p)->rb_right;
614                         continue;
615                 }
616
617                 /*
618                  * There is already a physical eraseblock describing the same
619                  * logical eraseblock present.
620                  */
621
622                 dbg_bld("this LEB already exists: PEB %d, sqnum %llu, EC %d",
623                         aeb->pnum, aeb->sqnum, aeb->ec);
624
625                 /*
626                  * Make sure that the logical eraseblocks have different
627                  * sequence numbers. Otherwise the image is bad.
628                  *
629                  * However, if the sequence number is zero, we assume it must
630                  * be an ancient UBI image from the era when UBI did not have
631                  * sequence numbers. We still can attach these images, unless
632                  * there is a need to distinguish between old and new
633                  * eraseblocks, in which case we'll refuse the image in
634                  * 'ubi_compare_lebs()'. In other words, we attach old clean
635                  * images, but refuse attaching old images with duplicated
636                  * logical eraseblocks because there was an unclean reboot.
637                  */
638                 if (aeb->sqnum == sqnum && sqnum != 0) {
639                         ubi_err(ubi, "two LEBs with same sequence number %llu",
640                                 sqnum);
641                         ubi_dump_aeb(aeb, 0);
642                         ubi_dump_vid_hdr(vid_hdr);
643                         return -EINVAL;
644                 }
645
646                 /*
647                  * Now we have to drop the older one and preserve the newer
648                  * one.
649                  */
650                 cmp_res = ubi_compare_lebs(ubi, aeb, pnum, vid_hdr);
651                 if (cmp_res < 0)
652                         return cmp_res;
653
654                 if (cmp_res & 1) {
655                         /*
656                          * This logical eraseblock is newer than the one
657                          * found earlier.
658                          */
659                         err = validate_vid_hdr(ubi, vid_hdr, av, pnum);
660                         if (err)
661                                 return err;
662
663                         err = add_to_list(ai, aeb->pnum, aeb->vol_id,
664                                           aeb->lnum, aeb->ec, cmp_res & 4,
665                                           &ai->erase);
666                         if (err)
667                                 return err;
668
669                         aeb->ec = ec;
670                         aeb->pnum = pnum;
671                         aeb->vol_id = vol_id;
672                         aeb->lnum = lnum;
673                         aeb->scrub = ((cmp_res & 2) || bitflips);
674                         aeb->copy_flag = vid_hdr->copy_flag;
675                         aeb->sqnum = sqnum;
676
677                         if (av->highest_lnum == lnum)
678                                 av->last_data_size =
679                                         be32_to_cpu(vid_hdr->data_size);
680
681                         return 0;
682                 } else {
683                         /*
684                          * This logical eraseblock is older than the one found
685                          * previously.
686                          */
687                         return add_to_list(ai, pnum, vol_id, lnum, ec,
688                                            cmp_res & 4, &ai->erase);
689                 }
690         }
691
692         /*
693          * We've met this logical eraseblock for the first time, add it to the
694          * attaching information.
695          */
696
697         err = validate_vid_hdr(ubi, vid_hdr, av, pnum);
698         if (err)
699                 return err;
700
701         aeb = ubi_alloc_aeb(ai, pnum, ec);
702         if (!aeb)
703                 return -ENOMEM;
704
705         aeb->vol_id = vol_id;
706         aeb->lnum = lnum;
707         aeb->scrub = bitflips;
708         aeb->copy_flag = vid_hdr->copy_flag;
709         aeb->sqnum = sqnum;
710
711         if (av->highest_lnum <= lnum) {
712                 av->highest_lnum = lnum;
713                 av->last_data_size = be32_to_cpu(vid_hdr->data_size);
714         }
715
716         av->leb_count += 1;
717         rb_link_node(&aeb->u.rb, parent, p);
718         rb_insert_color(&aeb->u.rb, &av->root);
719         return 0;
720 }
721
722 /**
723  * ubi_add_av - add volume to the attaching information.
724  * @ai: attaching information
725  * @vol_id: the requested volume ID
726  *
727  * This function returns a pointer to the new volume description or an
728  * ERR_PTR if the operation failed.
729  */
730 struct ubi_ainf_volume *ubi_add_av(struct ubi_attach_info *ai, int vol_id)
731 {
732         bool created;
733
734         return find_or_add_av(ai, vol_id, AV_ADD, &created);
735 }
736
737 /**
738  * ubi_find_av - find volume in the attaching information.
739  * @ai: attaching information
740  * @vol_id: the requested volume ID
741  *
742  * This function returns a pointer to the volume description or %NULL if there
743  * are no data about this volume in the attaching information.
744  */
745 struct ubi_ainf_volume *ubi_find_av(const struct ubi_attach_info *ai,
746                                     int vol_id)
747 {
748         bool created;
749
750         return find_or_add_av((struct ubi_attach_info *)ai, vol_id, AV_FIND,
751                               &created);
752 }
753
754 static void destroy_av(struct ubi_attach_info *ai, struct ubi_ainf_volume *av,
755                        struct list_head *list);
756
757 /**
758  * ubi_remove_av - delete attaching information about a volume.
759  * @ai: attaching information
760  * @av: the volume attaching information to delete
761  */
762 void ubi_remove_av(struct ubi_attach_info *ai, struct ubi_ainf_volume *av)
763 {
764         dbg_bld("remove attaching information about volume %d", av->vol_id);
765
766         rb_erase(&av->rb, &ai->volumes);
767         destroy_av(ai, av, &ai->erase);
768         ai->vols_found -= 1;
769 }
770
771 /**
772  * early_erase_peb - erase a physical eraseblock.
773  * @ubi: UBI device description object
774  * @ai: attaching information
775  * @pnum: physical eraseblock number to erase;
776  * @ec: erase counter value to write (%UBI_UNKNOWN if it is unknown)
777  *
778  * This function erases physical eraseblock 'pnum', and writes the erase
779  * counter header to it. This function should only be used on UBI device
780  * initialization stages, when the EBA sub-system had not been yet initialized.
781  * This function returns zero in case of success and a negative error code in
782  * case of failure.
783  */
784 static int early_erase_peb(struct ubi_device *ubi,
785                            const struct ubi_attach_info *ai, int pnum, int ec)
786 {
787         int err;
788         struct ubi_ec_hdr *ec_hdr;
789
790         if ((long long)ec >= UBI_MAX_ERASECOUNTER) {
791                 /*
792                  * Erase counter overflow. Upgrade UBI and use 64-bit
793                  * erase counters internally.
794                  */
795                 ubi_err(ubi, "erase counter overflow at PEB %d, EC %d",
796                         pnum, ec);
797                 return -EINVAL;
798         }
799
800         ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
801         if (!ec_hdr)
802                 return -ENOMEM;
803
804         ec_hdr->ec = cpu_to_be64(ec);
805
806         err = ubi_io_sync_erase(ubi, pnum, 0);
807         if (err < 0)
808                 goto out_free;
809
810         err = ubi_io_write_ec_hdr(ubi, pnum, ec_hdr);
811
812 out_free:
813         kfree(ec_hdr);
814         return err;
815 }
816
817 /**
818  * ubi_early_get_peb - get a free physical eraseblock.
819  * @ubi: UBI device description object
820  * @ai: attaching information
821  *
822  * This function returns a free physical eraseblock. It is supposed to be
823  * called on the UBI initialization stages when the wear-leveling sub-system is
824  * not initialized yet. This function picks a physical eraseblocks from one of
825  * the lists, writes the EC header if it is needed, and removes it from the
826  * list.
827  *
828  * This function returns a pointer to the "aeb" of the found free PEB in case
829  * of success and an error code in case of failure.
830  */
831 struct ubi_ainf_peb *ubi_early_get_peb(struct ubi_device *ubi,
832                                        struct ubi_attach_info *ai)
833 {
834         int err = 0;
835         struct ubi_ainf_peb *aeb, *tmp_aeb;
836
837         if (!list_empty(&ai->free)) {
838                 aeb = list_entry(ai->free.next, struct ubi_ainf_peb, u.list);
839                 list_del(&aeb->u.list);
840                 dbg_bld("return free PEB %d, EC %d", aeb->pnum, aeb->ec);
841                 return aeb;
842         }
843
844         /*
845          * We try to erase the first physical eraseblock from the erase list
846          * and pick it if we succeed, or try to erase the next one if not. And
847          * so forth. We don't want to take care about bad eraseblocks here -
848          * they'll be handled later.
849          */
850         list_for_each_entry_safe(aeb, tmp_aeb, &ai->erase, u.list) {
851                 if (aeb->ec == UBI_UNKNOWN)
852                         aeb->ec = ai->mean_ec;
853
854                 err = early_erase_peb(ubi, ai, aeb->pnum, aeb->ec+1);
855                 if (err)
856                         continue;
857
858                 aeb->ec += 1;
859                 list_del(&aeb->u.list);
860                 dbg_bld("return PEB %d, EC %d", aeb->pnum, aeb->ec);
861                 return aeb;
862         }
863
864         ubi_err(ubi, "no free eraseblocks");
865         return ERR_PTR(-ENOSPC);
866 }
867
868 /**
869  * check_corruption - check the data area of PEB.
870  * @ubi: UBI device description object
871  * @vid_hdr: the (corrupted) VID header of this PEB
872  * @pnum: the physical eraseblock number to check
873  *
874  * This is a helper function which is used to distinguish between VID header
875  * corruptions caused by power cuts and other reasons. If the PEB contains only
876  * 0xFF bytes in the data area, the VID header is most probably corrupted
877  * because of a power cut (%0 is returned in this case). Otherwise, it was
878  * probably corrupted for some other reasons (%1 is returned in this case). A
879  * negative error code is returned if a read error occurred.
880  *
881  * If the corruption reason was a power cut, UBI can safely erase this PEB.
882  * Otherwise, it should preserve it to avoid possibly destroying important
883  * information.
884  */
885 static int check_corruption(struct ubi_device *ubi, struct ubi_vid_hdr *vid_hdr,
886                             int pnum)
887 {
888         int err;
889
890         mutex_lock(&ubi->buf_mutex);
891         memset(ubi->peb_buf, 0x00, ubi->leb_size);
892
893         err = ubi_io_read(ubi, ubi->peb_buf, pnum, ubi->leb_start,
894                           ubi->leb_size);
895         if (err == UBI_IO_BITFLIPS || mtd_is_eccerr(err)) {
896                 /*
897                  * Bit-flips or integrity errors while reading the data area.
898                  * It is difficult to say for sure what type of corruption is
899                  * this, but presumably a power cut happened while this PEB was
900                  * erased, so it became unstable and corrupted, and should be
901                  * erased.
902                  */
903                 err = 0;
904                 goto out_unlock;
905         }
906
907         if (err)
908                 goto out_unlock;
909
910         if (ubi_check_pattern(ubi->peb_buf, 0xFF, ubi->leb_size))
911                 goto out_unlock;
912
913         ubi_err(ubi, "PEB %d contains corrupted VID header, and the data does not contain all 0xFF",
914                 pnum);
915         ubi_err(ubi, "this may be a non-UBI PEB or a severe VID header corruption which requires manual inspection");
916         ubi_dump_vid_hdr(vid_hdr);
917         pr_err("hexdump of PEB %d offset %d, length %d",
918                pnum, ubi->leb_start, ubi->leb_size);
919         ubi_dbg_print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
920                                ubi->peb_buf, ubi->leb_size, 1);
921         err = 1;
922
923 out_unlock:
924         mutex_unlock(&ubi->buf_mutex);
925         return err;
926 }
927
928 static bool vol_ignored(int vol_id)
929 {
930         switch (vol_id) {
931                 case UBI_LAYOUT_VOLUME_ID:
932                 return true;
933         }
934
935 #ifdef CONFIG_MTD_UBI_FASTMAP
936         return ubi_is_fm_vol(vol_id);
937 #else
938         return false;
939 #endif
940 }
941
942 /**
943  * scan_peb - scan and process UBI headers of a PEB.
944  * @ubi: UBI device description object
945  * @ai: attaching information
946  * @pnum: the physical eraseblock number
947  * @fast: true if we're scanning for a Fastmap
948  *
949  * This function reads UBI headers of PEB @pnum, checks them, and adds
950  * information about this PEB to the corresponding list or RB-tree in the
951  * "attaching info" structure. Returns zero if the physical eraseblock was
952  * successfully handled and a negative error code in case of failure.
953  */
954 static int scan_peb(struct ubi_device *ubi, struct ubi_attach_info *ai,
955                     int pnum, bool fast)
956 {
957         struct ubi_ec_hdr *ech = ai->ech;
958         struct ubi_vid_io_buf *vidb = ai->vidb;
959         struct ubi_vid_hdr *vidh = ubi_get_vid_hdr(vidb);
960         long long ec;
961         int err, bitflips = 0, vol_id = -1, ec_err = 0;
962
963         dbg_bld("scan PEB %d", pnum);
964
965         /* Skip bad physical eraseblocks */
966         err = ubi_io_is_bad(ubi, pnum);
967         if (err < 0)
968                 return err;
969         else if (err) {
970                 ai->bad_peb_count += 1;
971                 return 0;
972         }
973
974         err = ubi_io_read_ec_hdr(ubi, pnum, ech, 0);
975         if (err < 0)
976                 return err;
977         switch (err) {
978         case 0:
979                 break;
980         case UBI_IO_BITFLIPS:
981                 bitflips = 1;
982                 break;
983         case UBI_IO_FF:
984                 ai->empty_peb_count += 1;
985                 return add_to_list(ai, pnum, UBI_UNKNOWN, UBI_UNKNOWN,
986                                    UBI_UNKNOWN, 0, &ai->erase);
987         case UBI_IO_FF_BITFLIPS:
988                 ai->empty_peb_count += 1;
989                 return add_to_list(ai, pnum, UBI_UNKNOWN, UBI_UNKNOWN,
990                                    UBI_UNKNOWN, 1, &ai->erase);
991         case UBI_IO_BAD_HDR_EBADMSG:
992         case UBI_IO_BAD_HDR:
993                 /*
994                  * We have to also look at the VID header, possibly it is not
995                  * corrupted. Set %bitflips flag in order to make this PEB be
996                  * moved and EC be re-created.
997                  */
998                 ec_err = err;
999                 ec = UBI_UNKNOWN;
1000                 bitflips = 1;
1001                 break;
1002         default:
1003                 ubi_err(ubi, "'ubi_io_read_ec_hdr()' returned unknown code %d",
1004                         err);
1005                 return -EINVAL;
1006         }
1007
1008         if (!ec_err) {
1009                 int image_seq;
1010
1011                 /* Make sure UBI version is OK */
1012                 if (ech->version != UBI_VERSION) {
1013                         ubi_err(ubi, "this UBI version is %d, image version is %d",
1014                                 UBI_VERSION, (int)ech->version);
1015                         return -EINVAL;
1016                 }
1017
1018                 ec = be64_to_cpu(ech->ec);
1019                 if (ec > UBI_MAX_ERASECOUNTER) {
1020                         /*
1021                          * Erase counter overflow. The EC headers have 64 bits
1022                          * reserved, but we anyway make use of only 31 bit
1023                          * values, as this seems to be enough for any existing
1024                          * flash. Upgrade UBI and use 64-bit erase counters
1025                          * internally.
1026                          */
1027                         ubi_err(ubi, "erase counter overflow, max is %d",
1028                                 UBI_MAX_ERASECOUNTER);
1029                         ubi_dump_ec_hdr(ech);
1030                         return -EINVAL;
1031                 }
1032
1033                 /*
1034                  * Make sure that all PEBs have the same image sequence number.
1035                  * This allows us to detect situations when users flash UBI
1036                  * images incorrectly, so that the flash has the new UBI image
1037                  * and leftovers from the old one. This feature was added
1038                  * relatively recently, and the sequence number was always
1039                  * zero, because old UBI implementations always set it to zero.
1040                  * For this reasons, we do not panic if some PEBs have zero
1041                  * sequence number, while other PEBs have non-zero sequence
1042                  * number.
1043                  */
1044                 image_seq = be32_to_cpu(ech->image_seq);
1045                 if (!ubi->image_seq)
1046                         ubi->image_seq = image_seq;
1047                 if (image_seq && ubi->image_seq != image_seq) {
1048                         ubi_err(ubi, "bad image sequence number %d in PEB %d, expected %d",
1049                                 image_seq, pnum, ubi->image_seq);
1050                         ubi_dump_ec_hdr(ech);
1051                         return -EINVAL;
1052                 }
1053         }
1054
1055         /* OK, we've done with the EC header, let's look at the VID header */
1056
1057         err = ubi_io_read_vid_hdr(ubi, pnum, vidb, 0);
1058         if (err < 0)
1059                 return err;
1060         switch (err) {
1061         case 0:
1062                 break;
1063         case UBI_IO_BITFLIPS:
1064                 bitflips = 1;
1065                 break;
1066         case UBI_IO_BAD_HDR_EBADMSG:
1067                 if (ec_err == UBI_IO_BAD_HDR_EBADMSG)
1068                         /*
1069                          * Both EC and VID headers are corrupted and were read
1070                          * with data integrity error, probably this is a bad
1071                          * PEB, bit it is not marked as bad yet. This may also
1072                          * be a result of power cut during erasure.
1073                          */
1074                         ai->maybe_bad_peb_count += 1;
1075         case UBI_IO_BAD_HDR:
1076                         /*
1077                          * If we're facing a bad VID header we have to drop *all*
1078                          * Fastmap data structures we find. The most recent Fastmap
1079                          * could be bad and therefore there is a chance that we attach
1080                          * from an old one. On a fine MTD stack a PEB must not render
1081                          * bad all of a sudden, but the reality is different.
1082                          * So, let's be paranoid and help finding the root cause by
1083                          * falling back to scanning mode instead of attaching with a
1084                          * bad EBA table and cause data corruption which is hard to
1085                          * analyze.
1086                          */
1087                         if (fast)
1088                                 ai->force_full_scan = 1;
1089
1090                 if (ec_err)
1091                         /*
1092                          * Both headers are corrupted. There is a possibility
1093                          * that this a valid UBI PEB which has corresponding
1094                          * LEB, but the headers are corrupted. However, it is
1095                          * impossible to distinguish it from a PEB which just
1096                          * contains garbage because of a power cut during erase
1097                          * operation. So we just schedule this PEB for erasure.
1098                          *
1099                          * Besides, in case of NOR flash, we deliberately
1100                          * corrupt both headers because NOR flash erasure is
1101                          * slow and can start from the end.
1102                          */
1103                         err = 0;
1104                 else
1105                         /*
1106                          * The EC was OK, but the VID header is corrupted. We
1107                          * have to check what is in the data area.
1108                          */
1109                         err = check_corruption(ubi, vidh, pnum);
1110
1111                 if (err < 0)
1112                         return err;
1113                 else if (!err)
1114                         /* This corruption is caused by a power cut */
1115                         err = add_to_list(ai, pnum, UBI_UNKNOWN,
1116                                           UBI_UNKNOWN, ec, 1, &ai->erase);
1117                 else
1118                         /* This is an unexpected corruption */
1119                         err = add_corrupted(ai, pnum, ec);
1120                 if (err)
1121                         return err;
1122                 goto adjust_mean_ec;
1123         case UBI_IO_FF_BITFLIPS:
1124                 err = add_to_list(ai, pnum, UBI_UNKNOWN, UBI_UNKNOWN,
1125                                   ec, 1, &ai->erase);
1126                 if (err)
1127                         return err;
1128                 goto adjust_mean_ec;
1129         case UBI_IO_FF:
1130                 if (ec_err || bitflips)
1131                         err = add_to_list(ai, pnum, UBI_UNKNOWN,
1132                                           UBI_UNKNOWN, ec, 1, &ai->erase);
1133                 else
1134                         err = add_to_list(ai, pnum, UBI_UNKNOWN,
1135                                           UBI_UNKNOWN, ec, 0, &ai->free);
1136                 if (err)
1137                         return err;
1138                 goto adjust_mean_ec;
1139         default:
1140                 ubi_err(ubi, "'ubi_io_read_vid_hdr()' returned unknown code %d",
1141                         err);
1142                 return -EINVAL;
1143         }
1144
1145         vol_id = be32_to_cpu(vidh->vol_id);
1146         if (vol_id > UBI_MAX_VOLUMES && !vol_ignored(vol_id)) {
1147                 int lnum = be32_to_cpu(vidh->lnum);
1148
1149                 /* Unsupported internal volume */
1150                 switch (vidh->compat) {
1151                 case UBI_COMPAT_DELETE:
1152                         ubi_msg(ubi, "\"delete\" compatible internal volume %d:%d found, will remove it",
1153                                 vol_id, lnum);
1154
1155                         err = add_to_list(ai, pnum, vol_id, lnum,
1156                                           ec, 1, &ai->erase);
1157                         if (err)
1158                                 return err;
1159                         return 0;
1160
1161                 case UBI_COMPAT_RO:
1162                         ubi_msg(ubi, "read-only compatible internal volume %d:%d found, switch to read-only mode",
1163                                 vol_id, lnum);
1164                         ubi->ro_mode = 1;
1165                         break;
1166
1167                 case UBI_COMPAT_PRESERVE:
1168                         ubi_msg(ubi, "\"preserve\" compatible internal volume %d:%d found",
1169                                 vol_id, lnum);
1170                         err = add_to_list(ai, pnum, vol_id, lnum,
1171                                           ec, 0, &ai->alien);
1172                         if (err)
1173                                 return err;
1174                         return 0;
1175
1176                 case UBI_COMPAT_REJECT:
1177                         ubi_err(ubi, "incompatible internal volume %d:%d found",
1178                                 vol_id, lnum);
1179                         return -EINVAL;
1180                 }
1181         }
1182
1183         if (ec_err)
1184                 ubi_warn(ubi, "valid VID header but corrupted EC header at PEB %d",
1185                          pnum);
1186
1187         if (ubi_is_fm_vol(vol_id))
1188                 err = add_fastmap(ai, pnum, vidh, ec);
1189         else
1190                 err = ubi_add_to_av(ubi, ai, pnum, ec, vidh, bitflips);
1191
1192         if (err)
1193                 return err;
1194
1195 adjust_mean_ec:
1196         if (!ec_err) {
1197                 ai->ec_sum += ec;
1198                 ai->ec_count += 1;
1199                 if (ec > ai->max_ec)
1200                         ai->max_ec = ec;
1201                 if (ec < ai->min_ec)
1202                         ai->min_ec = ec;
1203         }
1204
1205         return 0;
1206 }
1207
1208 /**
1209  * late_analysis - analyze the overall situation with PEB.
1210  * @ubi: UBI device description object
1211  * @ai: attaching information
1212  *
1213  * This is a helper function which takes a look what PEBs we have after we
1214  * gather information about all of them ("ai" is compete). It decides whether
1215  * the flash is empty and should be formatted of whether there are too many
1216  * corrupted PEBs and we should not attach this MTD device. Returns zero if we
1217  * should proceed with attaching the MTD device, and %-EINVAL if we should not.
1218  */
1219 static int late_analysis(struct ubi_device *ubi, struct ubi_attach_info *ai)
1220 {
1221         struct ubi_ainf_peb *aeb;
1222         int max_corr, peb_count;
1223
1224         peb_count = ubi->peb_count - ai->bad_peb_count - ai->alien_peb_count;
1225         max_corr = peb_count / 20 ?: 8;
1226
1227         /*
1228          * Few corrupted PEBs is not a problem and may be just a result of
1229          * unclean reboots. However, many of them may indicate some problems
1230          * with the flash HW or driver.
1231          */
1232         if (ai->corr_peb_count) {
1233                 ubi_err(ubi, "%d PEBs are corrupted and preserved",
1234                         ai->corr_peb_count);
1235                 pr_err("Corrupted PEBs are:");
1236                 list_for_each_entry(aeb, &ai->corr, u.list)
1237                         pr_cont(" %d", aeb->pnum);
1238                 pr_cont("\n");
1239
1240                 /*
1241                  * If too many PEBs are corrupted, we refuse attaching,
1242                  * otherwise, only print a warning.
1243                  */
1244                 if (ai->corr_peb_count >= max_corr) {
1245                         ubi_err(ubi, "too many corrupted PEBs, refusing");
1246                         return -EINVAL;
1247                 }
1248         }
1249
1250         if (ai->empty_peb_count + ai->maybe_bad_peb_count == peb_count) {
1251                 /*
1252                  * All PEBs are empty, or almost all - a couple PEBs look like
1253                  * they may be bad PEBs which were not marked as bad yet.
1254                  *
1255                  * This piece of code basically tries to distinguish between
1256                  * the following situations:
1257                  *
1258                  * 1. Flash is empty, but there are few bad PEBs, which are not
1259                  *    marked as bad so far, and which were read with error. We
1260                  *    want to go ahead and format this flash. While formatting,
1261                  *    the faulty PEBs will probably be marked as bad.
1262                  *
1263                  * 2. Flash contains non-UBI data and we do not want to format
1264                  *    it and destroy possibly important information.
1265                  */
1266                 if (ai->maybe_bad_peb_count <= 2) {
1267                         ai->is_empty = 1;
1268                         ubi_msg(ubi, "empty MTD device detected");
1269                         get_random_bytes(&ubi->image_seq,
1270                                          sizeof(ubi->image_seq));
1271                 } else {
1272                         ubi_err(ubi, "MTD device is not UBI-formatted and possibly contains non-UBI data - refusing it");
1273                         return -EINVAL;
1274                 }
1275
1276         }
1277
1278         return 0;
1279 }
1280
1281 /**
1282  * destroy_av - free volume attaching information.
1283  * @av: volume attaching information
1284  * @ai: attaching information
1285  * @list: put the aeb elements in there if !NULL, otherwise free them
1286  *
1287  * This function destroys the volume attaching information.
1288  */
1289 static void destroy_av(struct ubi_attach_info *ai, struct ubi_ainf_volume *av,
1290                        struct list_head *list)
1291 {
1292         struct ubi_ainf_peb *aeb;
1293         struct rb_node *this = av->root.rb_node;
1294
1295         while (this) {
1296                 if (this->rb_left)
1297                         this = this->rb_left;
1298                 else if (this->rb_right)
1299                         this = this->rb_right;
1300                 else {
1301                         aeb = rb_entry(this, struct ubi_ainf_peb, u.rb);
1302                         this = rb_parent(this);
1303                         if (this) {
1304                                 if (this->rb_left == &aeb->u.rb)
1305                                         this->rb_left = NULL;
1306                                 else
1307                                         this->rb_right = NULL;
1308                         }
1309
1310                         if (list)
1311                                 list_add_tail(&aeb->u.list, list);
1312                         else
1313                                 ubi_free_aeb(ai, aeb);
1314                 }
1315         }
1316         kfree(av);
1317 }
1318
1319 /**
1320  * destroy_ai - destroy attaching information.
1321  * @ai: attaching information
1322  */
1323 static void destroy_ai(struct ubi_attach_info *ai)
1324 {
1325         struct ubi_ainf_peb *aeb, *aeb_tmp;
1326         struct ubi_ainf_volume *av;
1327         struct rb_node *rb;
1328
1329         list_for_each_entry_safe(aeb, aeb_tmp, &ai->alien, u.list) {
1330                 list_del(&aeb->u.list);
1331                 ubi_free_aeb(ai, aeb);
1332         }
1333         list_for_each_entry_safe(aeb, aeb_tmp, &ai->erase, u.list) {
1334                 list_del(&aeb->u.list);
1335                 ubi_free_aeb(ai, aeb);
1336         }
1337         list_for_each_entry_safe(aeb, aeb_tmp, &ai->corr, u.list) {
1338                 list_del(&aeb->u.list);
1339                 ubi_free_aeb(ai, aeb);
1340         }
1341         list_for_each_entry_safe(aeb, aeb_tmp, &ai->free, u.list) {
1342                 list_del(&aeb->u.list);
1343                 ubi_free_aeb(ai, aeb);
1344         }
1345         list_for_each_entry_safe(aeb, aeb_tmp, &ai->fastmap, u.list) {
1346                 list_del(&aeb->u.list);
1347                 ubi_free_aeb(ai, aeb);
1348         }
1349
1350         /* Destroy the volume RB-tree */
1351         rb = ai->volumes.rb_node;
1352         while (rb) {
1353                 if (rb->rb_left)
1354                         rb = rb->rb_left;
1355                 else if (rb->rb_right)
1356                         rb = rb->rb_right;
1357                 else {
1358                         av = rb_entry(rb, struct ubi_ainf_volume, rb);
1359
1360                         rb = rb_parent(rb);
1361                         if (rb) {
1362                                 if (rb->rb_left == &av->rb)
1363                                         rb->rb_left = NULL;
1364                                 else
1365                                         rb->rb_right = NULL;
1366                         }
1367
1368                         destroy_av(ai, av, NULL);
1369                 }
1370         }
1371
1372         kmem_cache_destroy(ai->aeb_slab_cache);
1373         kfree(ai);
1374 }
1375
1376 /**
1377  * scan_all - scan entire MTD device.
1378  * @ubi: UBI device description object
1379  * @ai: attach info object
1380  * @start: start scanning at this PEB
1381  *
1382  * This function does full scanning of an MTD device and returns complete
1383  * information about it in form of a "struct ubi_attach_info" object. In case
1384  * of failure, an error code is returned.
1385  */
1386 static int scan_all(struct ubi_device *ubi, struct ubi_attach_info *ai,
1387                     int start)
1388 {
1389         int err, pnum;
1390         struct rb_node *rb1, *rb2;
1391         struct ubi_ainf_volume *av;
1392         struct ubi_ainf_peb *aeb;
1393
1394         err = -ENOMEM;
1395
1396         ai->ech = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
1397         if (!ai->ech)
1398                 return err;
1399
1400         ai->vidb = ubi_alloc_vid_buf(ubi, GFP_KERNEL);
1401         if (!ai->vidb)
1402                 goto out_ech;
1403
1404         for (pnum = start; pnum < ubi->peb_count; pnum++) {
1405                 cond_resched();
1406
1407                 dbg_gen("process PEB %d", pnum);
1408                 err = scan_peb(ubi, ai, pnum, false);
1409                 if (err < 0)
1410                         goto out_vidh;
1411         }
1412
1413         ubi_msg(ubi, "scanning is finished");
1414
1415         /* Calculate mean erase counter */
1416         if (ai->ec_count)
1417                 ai->mean_ec = div_u64(ai->ec_sum, ai->ec_count);
1418
1419         err = late_analysis(ubi, ai);
1420         if (err)
1421                 goto out_vidh;
1422
1423         /*
1424          * In case of unknown erase counter we use the mean erase counter
1425          * value.
1426          */
1427         ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
1428                 ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb)
1429                         if (aeb->ec == UBI_UNKNOWN)
1430                                 aeb->ec = ai->mean_ec;
1431         }
1432
1433         list_for_each_entry(aeb, &ai->free, u.list) {
1434                 if (aeb->ec == UBI_UNKNOWN)
1435                         aeb->ec = ai->mean_ec;
1436         }
1437
1438         list_for_each_entry(aeb, &ai->corr, u.list)
1439                 if (aeb->ec == UBI_UNKNOWN)
1440                         aeb->ec = ai->mean_ec;
1441
1442         list_for_each_entry(aeb, &ai->erase, u.list)
1443                 if (aeb->ec == UBI_UNKNOWN)
1444                         aeb->ec = ai->mean_ec;
1445
1446         err = self_check_ai(ubi, ai);
1447         if (err)
1448                 goto out_vidh;
1449
1450         ubi_free_vid_buf(ai->vidb);
1451         kfree(ai->ech);
1452
1453         return 0;
1454
1455 out_vidh:
1456         ubi_free_vid_buf(ai->vidb);
1457 out_ech:
1458         kfree(ai->ech);
1459         return err;
1460 }
1461
1462 static struct ubi_attach_info *alloc_ai(void)
1463 {
1464         struct ubi_attach_info *ai;
1465
1466         ai = kzalloc(sizeof(struct ubi_attach_info), GFP_KERNEL);
1467         if (!ai)
1468                 return ai;
1469
1470         INIT_LIST_HEAD(&ai->corr);
1471         INIT_LIST_HEAD(&ai->free);
1472         INIT_LIST_HEAD(&ai->erase);
1473         INIT_LIST_HEAD(&ai->alien);
1474         INIT_LIST_HEAD(&ai->fastmap);
1475         ai->volumes = RB_ROOT;
1476         ai->aeb_slab_cache = kmem_cache_create("ubi_aeb_slab_cache",
1477                                                sizeof(struct ubi_ainf_peb),
1478                                                0, 0, NULL);
1479         if (!ai->aeb_slab_cache) {
1480                 kfree(ai);
1481                 ai = NULL;
1482         }
1483
1484         return ai;
1485 }
1486
1487 #ifdef CONFIG_MTD_UBI_FASTMAP
1488
1489 /**
1490  * scan_fast - try to find a fastmap and attach from it.
1491  * @ubi: UBI device description object
1492  * @ai: attach info object
1493  *
1494  * Returns 0 on success, negative return values indicate an internal
1495  * error.
1496  * UBI_NO_FASTMAP denotes that no fastmap was found.
1497  * UBI_BAD_FASTMAP denotes that the found fastmap was invalid.
1498  */
1499 static int scan_fast(struct ubi_device *ubi, struct ubi_attach_info **ai)
1500 {
1501         int err, pnum;
1502         struct ubi_attach_info *scan_ai;
1503
1504         err = -ENOMEM;
1505
1506         scan_ai = alloc_ai();
1507         if (!scan_ai)
1508                 goto out;
1509
1510         scan_ai->ech = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
1511         if (!scan_ai->ech)
1512                 goto out_ai;
1513
1514         scan_ai->vidb = ubi_alloc_vid_buf(ubi, GFP_KERNEL);
1515         if (!scan_ai->vidb)
1516                 goto out_ech;
1517
1518         for (pnum = 0; pnum < UBI_FM_MAX_START; pnum++) {
1519                 cond_resched();
1520
1521                 dbg_gen("process PEB %d", pnum);
1522                 err = scan_peb(ubi, scan_ai, pnum, true);
1523                 if (err < 0)
1524                         goto out_vidh;
1525         }
1526
1527         ubi_free_vid_buf(scan_ai->vidb);
1528         kfree(scan_ai->ech);
1529
1530         if (scan_ai->force_full_scan)
1531                 err = UBI_NO_FASTMAP;
1532         else
1533                 err = ubi_scan_fastmap(ubi, *ai, scan_ai);
1534
1535         if (err) {
1536                 /*
1537                  * Didn't attach via fastmap, do a full scan but reuse what
1538                  * we've aready scanned.
1539                  */
1540                 destroy_ai(*ai);
1541                 *ai = scan_ai;
1542         } else
1543                 destroy_ai(scan_ai);
1544
1545         return err;
1546
1547 out_vidh:
1548         ubi_free_vid_buf(scan_ai->vidb);
1549 out_ech:
1550         kfree(scan_ai->ech);
1551 out_ai:
1552         destroy_ai(scan_ai);
1553 out:
1554         return err;
1555 }
1556
1557 #endif
1558
1559 /**
1560  * ubi_attach - attach an MTD device.
1561  * @ubi: UBI device descriptor
1562  * @force_scan: if set to non-zero attach by scanning
1563  *
1564  * This function returns zero in case of success and a negative error code in
1565  * case of failure.
1566  */
1567 int ubi_attach(struct ubi_device *ubi, int force_scan)
1568 {
1569         int err;
1570         struct ubi_attach_info *ai;
1571
1572         ai = alloc_ai();
1573         if (!ai)
1574                 return -ENOMEM;
1575
1576 #ifdef CONFIG_MTD_UBI_FASTMAP
1577         /* On small flash devices we disable fastmap in any case. */
1578         if ((int)mtd_div_by_eb(ubi->mtd->size, ubi->mtd) <= UBI_FM_MAX_START) {
1579                 ubi->fm_disabled = 1;
1580                 force_scan = 1;
1581         }
1582
1583         if (force_scan)
1584                 err = scan_all(ubi, ai, 0);
1585         else {
1586                 err = scan_fast(ubi, &ai);
1587                 if (err > 0 || mtd_is_eccerr(err)) {
1588                         if (err != UBI_NO_FASTMAP) {
1589                                 destroy_ai(ai);
1590                                 ai = alloc_ai();
1591                                 if (!ai)
1592                                         return -ENOMEM;
1593
1594                                 err = scan_all(ubi, ai, 0);
1595                         } else {
1596                                 err = scan_all(ubi, ai, UBI_FM_MAX_START);
1597                         }
1598                 }
1599         }
1600 #else
1601         err = scan_all(ubi, ai, 0);
1602 #endif
1603         if (err)
1604                 goto out_ai;
1605
1606         ubi->bad_peb_count = ai->bad_peb_count;
1607         ubi->good_peb_count = ubi->peb_count - ubi->bad_peb_count;
1608         ubi->corr_peb_count = ai->corr_peb_count;
1609         ubi->max_ec = ai->max_ec;
1610         ubi->mean_ec = ai->mean_ec;
1611         dbg_gen("max. sequence number:       %llu", ai->max_sqnum);
1612
1613         err = ubi_read_volume_table(ubi, ai);
1614         if (err)
1615                 goto out_ai;
1616
1617         err = ubi_wl_init(ubi, ai);
1618         if (err)
1619                 goto out_vtbl;
1620
1621         err = ubi_eba_init(ubi, ai);
1622         if (err)
1623                 goto out_wl;
1624
1625 #ifdef CONFIG_MTD_UBI_FASTMAP
1626         if (ubi->fm && ubi_dbg_chk_fastmap(ubi)) {
1627                 struct ubi_attach_info *scan_ai;
1628
1629                 scan_ai = alloc_ai();
1630                 if (!scan_ai) {
1631                         err = -ENOMEM;
1632                         goto out_wl;
1633                 }
1634
1635                 err = scan_all(ubi, scan_ai, 0);
1636                 if (err) {
1637                         destroy_ai(scan_ai);
1638                         goto out_wl;
1639                 }
1640
1641                 err = self_check_eba(ubi, ai, scan_ai);
1642                 destroy_ai(scan_ai);
1643
1644                 if (err)
1645                         goto out_wl;
1646         }
1647 #endif
1648
1649         destroy_ai(ai);
1650         return 0;
1651
1652 out_wl:
1653         ubi_wl_close(ubi);
1654 out_vtbl:
1655         ubi_free_internal_volumes(ubi);
1656         vfree(ubi->vtbl);
1657 out_ai:
1658         destroy_ai(ai);
1659         return err;
1660 }
1661
1662 /**
1663  * self_check_ai - check the attaching information.
1664  * @ubi: UBI device description object
1665  * @ai: attaching information
1666  *
1667  * This function returns zero if the attaching information is all right, and a
1668  * negative error code if not or if an error occurred.
1669  */
1670 static int self_check_ai(struct ubi_device *ubi, struct ubi_attach_info *ai)
1671 {
1672         struct ubi_vid_io_buf *vidb = ai->vidb;
1673         struct ubi_vid_hdr *vidh = ubi_get_vid_hdr(vidb);
1674         int pnum, err, vols_found = 0;
1675         struct rb_node *rb1, *rb2;
1676         struct ubi_ainf_volume *av;
1677         struct ubi_ainf_peb *aeb, *last_aeb;
1678         uint8_t *buf;
1679
1680         if (!ubi_dbg_chk_gen(ubi))
1681                 return 0;
1682
1683         /*
1684          * At first, check that attaching information is OK.
1685          */
1686         ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
1687                 int leb_count = 0;
1688
1689                 cond_resched();
1690
1691                 vols_found += 1;
1692
1693                 if (ai->is_empty) {
1694                         ubi_err(ubi, "bad is_empty flag");
1695                         goto bad_av;
1696                 }
1697
1698                 if (av->vol_id < 0 || av->highest_lnum < 0 ||
1699                     av->leb_count < 0 || av->vol_type < 0 || av->used_ebs < 0 ||
1700                     av->data_pad < 0 || av->last_data_size < 0) {
1701                         ubi_err(ubi, "negative values");
1702                         goto bad_av;
1703                 }
1704
1705                 if (av->vol_id >= UBI_MAX_VOLUMES &&
1706                     av->vol_id < UBI_INTERNAL_VOL_START) {
1707                         ubi_err(ubi, "bad vol_id");
1708                         goto bad_av;
1709                 }
1710
1711                 if (av->vol_id > ai->highest_vol_id) {
1712                         ubi_err(ubi, "highest_vol_id is %d, but vol_id %d is there",
1713                                 ai->highest_vol_id, av->vol_id);
1714                         goto out;
1715                 }
1716
1717                 if (av->vol_type != UBI_DYNAMIC_VOLUME &&
1718                     av->vol_type != UBI_STATIC_VOLUME) {
1719                         ubi_err(ubi, "bad vol_type");
1720                         goto bad_av;
1721                 }
1722
1723                 if (av->data_pad > ubi->leb_size / 2) {
1724                         ubi_err(ubi, "bad data_pad");
1725                         goto bad_av;
1726                 }
1727
1728                 last_aeb = NULL;
1729                 ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
1730                         cond_resched();
1731
1732                         last_aeb = aeb;
1733                         leb_count += 1;
1734
1735                         if (aeb->pnum < 0 || aeb->ec < 0) {
1736                                 ubi_err(ubi, "negative values");
1737                                 goto bad_aeb;
1738                         }
1739
1740                         if (aeb->ec < ai->min_ec) {
1741                                 ubi_err(ubi, "bad ai->min_ec (%d), %d found",
1742                                         ai->min_ec, aeb->ec);
1743                                 goto bad_aeb;
1744                         }
1745
1746                         if (aeb->ec > ai->max_ec) {
1747                                 ubi_err(ubi, "bad ai->max_ec (%d), %d found",
1748                                         ai->max_ec, aeb->ec);
1749                                 goto bad_aeb;
1750                         }
1751
1752                         if (aeb->pnum >= ubi->peb_count) {
1753                                 ubi_err(ubi, "too high PEB number %d, total PEBs %d",
1754                                         aeb->pnum, ubi->peb_count);
1755                                 goto bad_aeb;
1756                         }
1757
1758                         if (av->vol_type == UBI_STATIC_VOLUME) {
1759                                 if (aeb->lnum >= av->used_ebs) {
1760                                         ubi_err(ubi, "bad lnum or used_ebs");
1761                                         goto bad_aeb;
1762                                 }
1763                         } else {
1764                                 if (av->used_ebs != 0) {
1765                                         ubi_err(ubi, "non-zero used_ebs");
1766                                         goto bad_aeb;
1767                                 }
1768                         }
1769
1770                         if (aeb->lnum > av->highest_lnum) {
1771                                 ubi_err(ubi, "incorrect highest_lnum or lnum");
1772                                 goto bad_aeb;
1773                         }
1774                 }
1775
1776                 if (av->leb_count != leb_count) {
1777                         ubi_err(ubi, "bad leb_count, %d objects in the tree",
1778                                 leb_count);
1779                         goto bad_av;
1780                 }
1781
1782                 if (!last_aeb)
1783                         continue;
1784
1785                 aeb = last_aeb;
1786
1787                 if (aeb->lnum != av->highest_lnum) {
1788                         ubi_err(ubi, "bad highest_lnum");
1789                         goto bad_aeb;
1790                 }
1791         }
1792
1793         if (vols_found != ai->vols_found) {
1794                 ubi_err(ubi, "bad ai->vols_found %d, should be %d",
1795                         ai->vols_found, vols_found);
1796                 goto out;
1797         }
1798
1799         /* Check that attaching information is correct */
1800         ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
1801                 last_aeb = NULL;
1802                 ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
1803                         int vol_type;
1804
1805                         cond_resched();
1806
1807                         last_aeb = aeb;
1808
1809                         err = ubi_io_read_vid_hdr(ubi, aeb->pnum, vidb, 1);
1810                         if (err && err != UBI_IO_BITFLIPS) {
1811                                 ubi_err(ubi, "VID header is not OK (%d)",
1812                                         err);
1813                                 if (err > 0)
1814                                         err = -EIO;
1815                                 return err;
1816                         }
1817
1818                         vol_type = vidh->vol_type == UBI_VID_DYNAMIC ?
1819                                    UBI_DYNAMIC_VOLUME : UBI_STATIC_VOLUME;
1820                         if (av->vol_type != vol_type) {
1821                                 ubi_err(ubi, "bad vol_type");
1822                                 goto bad_vid_hdr;
1823                         }
1824
1825                         if (aeb->sqnum != be64_to_cpu(vidh->sqnum)) {
1826                                 ubi_err(ubi, "bad sqnum %llu", aeb->sqnum);
1827                                 goto bad_vid_hdr;
1828                         }
1829
1830                         if (av->vol_id != be32_to_cpu(vidh->vol_id)) {
1831                                 ubi_err(ubi, "bad vol_id %d", av->vol_id);
1832                                 goto bad_vid_hdr;
1833                         }
1834
1835                         if (av->compat != vidh->compat) {
1836                                 ubi_err(ubi, "bad compat %d", vidh->compat);
1837                                 goto bad_vid_hdr;
1838                         }
1839
1840                         if (aeb->lnum != be32_to_cpu(vidh->lnum)) {
1841                                 ubi_err(ubi, "bad lnum %d", aeb->lnum);
1842                                 goto bad_vid_hdr;
1843                         }
1844
1845                         if (av->used_ebs != be32_to_cpu(vidh->used_ebs)) {
1846                                 ubi_err(ubi, "bad used_ebs %d", av->used_ebs);
1847                                 goto bad_vid_hdr;
1848                         }
1849
1850                         if (av->data_pad != be32_to_cpu(vidh->data_pad)) {
1851                                 ubi_err(ubi, "bad data_pad %d", av->data_pad);
1852                                 goto bad_vid_hdr;
1853                         }
1854                 }
1855
1856                 if (!last_aeb)
1857                         continue;
1858
1859                 if (av->highest_lnum != be32_to_cpu(vidh->lnum)) {
1860                         ubi_err(ubi, "bad highest_lnum %d", av->highest_lnum);
1861                         goto bad_vid_hdr;
1862                 }
1863
1864                 if (av->last_data_size != be32_to_cpu(vidh->data_size)) {
1865                         ubi_err(ubi, "bad last_data_size %d",
1866                                 av->last_data_size);
1867                         goto bad_vid_hdr;
1868                 }
1869         }
1870
1871         /*
1872          * Make sure that all the physical eraseblocks are in one of the lists
1873          * or trees.
1874          */
1875         buf = kzalloc(ubi->peb_count, GFP_KERNEL);
1876         if (!buf)
1877                 return -ENOMEM;
1878
1879         for (pnum = 0; pnum < ubi->peb_count; pnum++) {
1880                 err = ubi_io_is_bad(ubi, pnum);
1881                 if (err < 0) {
1882                         kfree(buf);
1883                         return err;
1884                 } else if (err)
1885                         buf[pnum] = 1;
1886         }
1887
1888         ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb)
1889                 ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb)
1890                         buf[aeb->pnum] = 1;
1891
1892         list_for_each_entry(aeb, &ai->free, u.list)
1893                 buf[aeb->pnum] = 1;
1894
1895         list_for_each_entry(aeb, &ai->corr, u.list)
1896                 buf[aeb->pnum] = 1;
1897
1898         list_for_each_entry(aeb, &ai->erase, u.list)
1899                 buf[aeb->pnum] = 1;
1900
1901         list_for_each_entry(aeb, &ai->alien, u.list)
1902                 buf[aeb->pnum] = 1;
1903
1904         err = 0;
1905         for (pnum = 0; pnum < ubi->peb_count; pnum++)
1906                 if (!buf[pnum]) {
1907                         ubi_err(ubi, "PEB %d is not referred", pnum);
1908                         err = 1;
1909                 }
1910
1911         kfree(buf);
1912         if (err)
1913                 goto out;
1914         return 0;
1915
1916 bad_aeb:
1917         ubi_err(ubi, "bad attaching information about LEB %d", aeb->lnum);
1918         ubi_dump_aeb(aeb, 0);
1919         ubi_dump_av(av);
1920         goto out;
1921
1922 bad_av:
1923         ubi_err(ubi, "bad attaching information about volume %d", av->vol_id);
1924         ubi_dump_av(av);
1925         goto out;
1926
1927 bad_vid_hdr:
1928         ubi_err(ubi, "bad attaching information about volume %d", av->vol_id);
1929         ubi_dump_av(av);
1930         ubi_dump_vid_hdr(vidh);
1931
1932 out:
1933         dump_stack();
1934         return -EINVAL;
1935 }