]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - drivers/mtd/ubi/eba.c
Merge branch 'master' of git://git.denx.de/u-boot-tegra
[karo-tx-uboot.git] / drivers / mtd / ubi / eba.c
1 /*
2  * Copyright (c) International Business Machines Corp., 2006
3  *
4  * SPDX-License-Identifier:     GPL-2.0+
5  *
6  * Author: Artem Bityutskiy (Битюцкий Артём)
7  */
8
9 /*
10  * The UBI Eraseblock Association (EBA) sub-system.
11  *
12  * This sub-system is responsible for I/O to/from logical eraseblock.
13  *
14  * Although in this implementation the EBA table is fully kept and managed in
15  * RAM, which assumes poor scalability, it might be (partially) maintained on
16  * flash in future implementations.
17  *
18  * The EBA sub-system implements per-logical eraseblock locking. Before
19  * accessing a logical eraseblock it is locked for reading or writing. The
20  * per-logical eraseblock locking is implemented by means of the lock tree. The
21  * lock tree is an RB-tree which refers all the currently locked logical
22  * eraseblocks. The lock tree elements are &struct ubi_ltree_entry objects.
23  * They are indexed by (@vol_id, @lnum) pairs.
24  *
25  * EBA also maintains the global sequence counter which is incremented each
26  * time a logical eraseblock is mapped to a physical eraseblock and it is
27  * stored in the volume identifier header. This means that each VID header has
28  * a unique sequence number. The sequence number is only increased an we assume
29  * 64 bits is enough to never overflow.
30  */
31
32 #define __UBOOT__
33 #ifndef __UBOOT__
34 #include <linux/slab.h>
35 #include <linux/crc32.h>
36 #else
37 #include <ubi_uboot.h>
38 #endif
39
40 #include <linux/err.h>
41 #include "ubi.h"
42
43 /* Number of physical eraseblocks reserved for atomic LEB change operation */
44 #define EBA_RESERVED_PEBS 1
45
46 /**
47  * next_sqnum - get next sequence number.
48  * @ubi: UBI device description object
49  *
50  * This function returns next sequence number to use, which is just the current
51  * global sequence counter value. It also increases the global sequence
52  * counter.
53  */
54 unsigned long long ubi_next_sqnum(struct ubi_device *ubi)
55 {
56         unsigned long long sqnum;
57
58         spin_lock(&ubi->ltree_lock);
59         sqnum = ubi->global_sqnum++;
60         spin_unlock(&ubi->ltree_lock);
61
62         return sqnum;
63 }
64
65 /**
66  * ubi_get_compat - get compatibility flags of a volume.
67  * @ubi: UBI device description object
68  * @vol_id: volume ID
69  *
70  * This function returns compatibility flags for an internal volume. User
71  * volumes have no compatibility flags, so %0 is returned.
72  */
73 static int ubi_get_compat(const struct ubi_device *ubi, int vol_id)
74 {
75         if (vol_id == UBI_LAYOUT_VOLUME_ID)
76                 return UBI_LAYOUT_VOLUME_COMPAT;
77         return 0;
78 }
79
80 /**
81  * ltree_lookup - look up the lock tree.
82  * @ubi: UBI device description object
83  * @vol_id: volume ID
84  * @lnum: logical eraseblock number
85  *
86  * This function returns a pointer to the corresponding &struct ubi_ltree_entry
87  * object if the logical eraseblock is locked and %NULL if it is not.
88  * @ubi->ltree_lock has to be locked.
89  */
90 static struct ubi_ltree_entry *ltree_lookup(struct ubi_device *ubi, int vol_id,
91                                             int lnum)
92 {
93         struct rb_node *p;
94
95         p = ubi->ltree.rb_node;
96         while (p) {
97                 struct ubi_ltree_entry *le;
98
99                 le = rb_entry(p, struct ubi_ltree_entry, rb);
100
101                 if (vol_id < le->vol_id)
102                         p = p->rb_left;
103                 else if (vol_id > le->vol_id)
104                         p = p->rb_right;
105                 else {
106                         if (lnum < le->lnum)
107                                 p = p->rb_left;
108                         else if (lnum > le->lnum)
109                                 p = p->rb_right;
110                         else
111                                 return le;
112                 }
113         }
114
115         return NULL;
116 }
117
118 /**
119  * ltree_add_entry - add new entry to the lock tree.
120  * @ubi: UBI device description object
121  * @vol_id: volume ID
122  * @lnum: logical eraseblock number
123  *
124  * This function adds new entry for logical eraseblock (@vol_id, @lnum) to the
125  * lock tree. If such entry is already there, its usage counter is increased.
126  * Returns pointer to the lock tree entry or %-ENOMEM if memory allocation
127  * failed.
128  */
129 static struct ubi_ltree_entry *ltree_add_entry(struct ubi_device *ubi,
130                                                int vol_id, int lnum)
131 {
132         struct ubi_ltree_entry *le, *le1, *le_free;
133
134         le = kmalloc(sizeof(struct ubi_ltree_entry), GFP_NOFS);
135         if (!le)
136                 return ERR_PTR(-ENOMEM);
137
138         le->users = 0;
139         init_rwsem(&le->mutex);
140         le->vol_id = vol_id;
141         le->lnum = lnum;
142
143         spin_lock(&ubi->ltree_lock);
144         le1 = ltree_lookup(ubi, vol_id, lnum);
145
146         if (le1) {
147                 /*
148                  * This logical eraseblock is already locked. The newly
149                  * allocated lock entry is not needed.
150                  */
151                 le_free = le;
152                 le = le1;
153         } else {
154                 struct rb_node **p, *parent = NULL;
155
156                 /*
157                  * No lock entry, add the newly allocated one to the
158                  * @ubi->ltree RB-tree.
159                  */
160                 le_free = NULL;
161
162                 p = &ubi->ltree.rb_node;
163                 while (*p) {
164                         parent = *p;
165                         le1 = rb_entry(parent, struct ubi_ltree_entry, rb);
166
167                         if (vol_id < le1->vol_id)
168                                 p = &(*p)->rb_left;
169                         else if (vol_id > le1->vol_id)
170                                 p = &(*p)->rb_right;
171                         else {
172                                 ubi_assert(lnum != le1->lnum);
173                                 if (lnum < le1->lnum)
174                                         p = &(*p)->rb_left;
175                                 else
176                                         p = &(*p)->rb_right;
177                         }
178                 }
179
180                 rb_link_node(&le->rb, parent, p);
181                 rb_insert_color(&le->rb, &ubi->ltree);
182         }
183         le->users += 1;
184         spin_unlock(&ubi->ltree_lock);
185
186         kfree(le_free);
187         return le;
188 }
189
190 /**
191  * leb_read_lock - lock logical eraseblock for reading.
192  * @ubi: UBI device description object
193  * @vol_id: volume ID
194  * @lnum: logical eraseblock number
195  *
196  * This function locks a logical eraseblock for reading. Returns zero in case
197  * of success and a negative error code in case of failure.
198  */
199 static int leb_read_lock(struct ubi_device *ubi, int vol_id, int lnum)
200 {
201         struct ubi_ltree_entry *le;
202
203         le = ltree_add_entry(ubi, vol_id, lnum);
204         if (IS_ERR(le))
205                 return PTR_ERR(le);
206         down_read(&le->mutex);
207         return 0;
208 }
209
210 /**
211  * leb_read_unlock - unlock logical eraseblock.
212  * @ubi: UBI device description object
213  * @vol_id: volume ID
214  * @lnum: logical eraseblock number
215  */
216 static void leb_read_unlock(struct ubi_device *ubi, int vol_id, int lnum)
217 {
218         struct ubi_ltree_entry *le;
219
220         spin_lock(&ubi->ltree_lock);
221         le = ltree_lookup(ubi, vol_id, lnum);
222         le->users -= 1;
223         ubi_assert(le->users >= 0);
224         up_read(&le->mutex);
225         if (le->users == 0) {
226                 rb_erase(&le->rb, &ubi->ltree);
227                 kfree(le);
228         }
229         spin_unlock(&ubi->ltree_lock);
230 }
231
232 /**
233  * leb_write_lock - lock logical eraseblock for writing.
234  * @ubi: UBI device description object
235  * @vol_id: volume ID
236  * @lnum: logical eraseblock number
237  *
238  * This function locks a logical eraseblock for writing. Returns zero in case
239  * of success and a negative error code in case of failure.
240  */
241 static int leb_write_lock(struct ubi_device *ubi, int vol_id, int lnum)
242 {
243         struct ubi_ltree_entry *le;
244
245         le = ltree_add_entry(ubi, vol_id, lnum);
246         if (IS_ERR(le))
247                 return PTR_ERR(le);
248         down_write(&le->mutex);
249         return 0;
250 }
251
252 /**
253  * leb_write_lock - lock logical eraseblock for writing.
254  * @ubi: UBI device description object
255  * @vol_id: volume ID
256  * @lnum: logical eraseblock number
257  *
258  * This function locks a logical eraseblock for writing if there is no
259  * contention and does nothing if there is contention. Returns %0 in case of
260  * success, %1 in case of contention, and and a negative error code in case of
261  * failure.
262  */
263 static int leb_write_trylock(struct ubi_device *ubi, int vol_id, int lnum)
264 {
265         struct ubi_ltree_entry *le;
266
267         le = ltree_add_entry(ubi, vol_id, lnum);
268         if (IS_ERR(le))
269                 return PTR_ERR(le);
270         if (down_write_trylock(&le->mutex))
271                 return 0;
272
273         /* Contention, cancel */
274         spin_lock(&ubi->ltree_lock);
275         le->users -= 1;
276         ubi_assert(le->users >= 0);
277         if (le->users == 0) {
278                 rb_erase(&le->rb, &ubi->ltree);
279                 kfree(le);
280         }
281         spin_unlock(&ubi->ltree_lock);
282
283         return 1;
284 }
285
286 /**
287  * leb_write_unlock - unlock logical eraseblock.
288  * @ubi: UBI device description object
289  * @vol_id: volume ID
290  * @lnum: logical eraseblock number
291  */
292 static void leb_write_unlock(struct ubi_device *ubi, int vol_id, int lnum)
293 {
294         struct ubi_ltree_entry *le;
295
296         spin_lock(&ubi->ltree_lock);
297         le = ltree_lookup(ubi, vol_id, lnum);
298         le->users -= 1;
299         ubi_assert(le->users >= 0);
300         up_write(&le->mutex);
301         if (le->users == 0) {
302                 rb_erase(&le->rb, &ubi->ltree);
303                 kfree(le);
304         }
305         spin_unlock(&ubi->ltree_lock);
306 }
307
308 /**
309  * ubi_eba_unmap_leb - un-map logical eraseblock.
310  * @ubi: UBI device description object
311  * @vol: volume description object
312  * @lnum: logical eraseblock number
313  *
314  * This function un-maps logical eraseblock @lnum and schedules corresponding
315  * physical eraseblock for erasure. Returns zero in case of success and a
316  * negative error code in case of failure.
317  */
318 int ubi_eba_unmap_leb(struct ubi_device *ubi, struct ubi_volume *vol,
319                       int lnum)
320 {
321         int err, pnum, vol_id = vol->vol_id;
322
323         if (ubi->ro_mode)
324                 return -EROFS;
325
326         err = leb_write_lock(ubi, vol_id, lnum);
327         if (err)
328                 return err;
329
330         pnum = vol->eba_tbl[lnum];
331         if (pnum < 0)
332                 /* This logical eraseblock is already unmapped */
333                 goto out_unlock;
334
335         dbg_eba("erase LEB %d:%d, PEB %d", vol_id, lnum, pnum);
336
337         down_read(&ubi->fm_sem);
338         vol->eba_tbl[lnum] = UBI_LEB_UNMAPPED;
339         up_read(&ubi->fm_sem);
340         err = ubi_wl_put_peb(ubi, vol_id, lnum, pnum, 0);
341
342 out_unlock:
343         leb_write_unlock(ubi, vol_id, lnum);
344         return err;
345 }
346
347 /**
348  * ubi_eba_read_leb - read data.
349  * @ubi: UBI device description object
350  * @vol: volume description object
351  * @lnum: logical eraseblock number
352  * @buf: buffer to store the read data
353  * @offset: offset from where to read
354  * @len: how many bytes to read
355  * @check: data CRC check flag
356  *
357  * If the logical eraseblock @lnum is unmapped, @buf is filled with 0xFF
358  * bytes. The @check flag only makes sense for static volumes and forces
359  * eraseblock data CRC checking.
360  *
361  * In case of success this function returns zero. In case of a static volume,
362  * if data CRC mismatches - %-EBADMSG is returned. %-EBADMSG may also be
363  * returned for any volume type if an ECC error was detected by the MTD device
364  * driver. Other negative error cored may be returned in case of other errors.
365  */
366 int ubi_eba_read_leb(struct ubi_device *ubi, struct ubi_volume *vol, int lnum,
367                      void *buf, int offset, int len, int check)
368 {
369         int err, pnum, scrub = 0, vol_id = vol->vol_id;
370         struct ubi_vid_hdr *vid_hdr;
371         uint32_t uninitialized_var(crc);
372
373         err = leb_read_lock(ubi, vol_id, lnum);
374         if (err)
375                 return err;
376
377         pnum = vol->eba_tbl[lnum];
378         if (pnum < 0) {
379                 /*
380                  * The logical eraseblock is not mapped, fill the whole buffer
381                  * with 0xFF bytes. The exception is static volumes for which
382                  * it is an error to read unmapped logical eraseblocks.
383                  */
384                 dbg_eba("read %d bytes from offset %d of LEB %d:%d (unmapped)",
385                         len, offset, vol_id, lnum);
386                 leb_read_unlock(ubi, vol_id, lnum);
387                 ubi_assert(vol->vol_type != UBI_STATIC_VOLUME);
388                 memset(buf, 0xFF, len);
389                 return 0;
390         }
391
392         dbg_eba("read %d bytes from offset %d of LEB %d:%d, PEB %d",
393                 len, offset, vol_id, lnum, pnum);
394
395         if (vol->vol_type == UBI_DYNAMIC_VOLUME)
396                 check = 0;
397
398 retry:
399         if (check) {
400                 vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
401                 if (!vid_hdr) {
402                         err = -ENOMEM;
403                         goto out_unlock;
404                 }
405
406                 err = ubi_io_read_vid_hdr(ubi, pnum, vid_hdr, 1);
407                 if (err && err != UBI_IO_BITFLIPS) {
408                         if (err > 0) {
409                                 /*
410                                  * The header is either absent or corrupted.
411                                  * The former case means there is a bug -
412                                  * switch to read-only mode just in case.
413                                  * The latter case means a real corruption - we
414                                  * may try to recover data. FIXME: but this is
415                                  * not implemented.
416                                  */
417                                 if (err == UBI_IO_BAD_HDR_EBADMSG ||
418                                     err == UBI_IO_BAD_HDR) {
419                                         ubi_warn("corrupted VID header at PEB %d, LEB %d:%d",
420                                                  pnum, vol_id, lnum);
421                                         err = -EBADMSG;
422                                 } else
423                                         ubi_ro_mode(ubi);
424                         }
425                         goto out_free;
426                 } else if (err == UBI_IO_BITFLIPS)
427                         scrub = 1;
428
429                 ubi_assert(lnum < be32_to_cpu(vid_hdr->used_ebs));
430                 ubi_assert(len == be32_to_cpu(vid_hdr->data_size));
431
432                 crc = be32_to_cpu(vid_hdr->data_crc);
433                 ubi_free_vid_hdr(ubi, vid_hdr);
434         }
435
436         err = ubi_io_read_data(ubi, buf, pnum, offset, len);
437         if (err) {
438                 if (err == UBI_IO_BITFLIPS) {
439                         scrub = 1;
440                         err = 0;
441                 } else if (mtd_is_eccerr(err)) {
442                         if (vol->vol_type == UBI_DYNAMIC_VOLUME)
443                                 goto out_unlock;
444                         scrub = 1;
445                         if (!check) {
446                                 ubi_msg("force data checking");
447                                 check = 1;
448                                 goto retry;
449                         }
450                 } else
451                         goto out_unlock;
452         }
453
454         if (check) {
455                 uint32_t crc1 = crc32(UBI_CRC32_INIT, buf, len);
456                 if (crc1 != crc) {
457                         ubi_warn("CRC error: calculated %#08x, must be %#08x",
458                                  crc1, crc);
459                         err = -EBADMSG;
460                         goto out_unlock;
461                 }
462         }
463
464         if (scrub)
465                 err = ubi_wl_scrub_peb(ubi, pnum);
466
467         leb_read_unlock(ubi, vol_id, lnum);
468         return err;
469
470 out_free:
471         ubi_free_vid_hdr(ubi, vid_hdr);
472 out_unlock:
473         leb_read_unlock(ubi, vol_id, lnum);
474         return err;
475 }
476
477 /**
478  * recover_peb - recover from write failure.
479  * @ubi: UBI device description object
480  * @pnum: the physical eraseblock to recover
481  * @vol_id: volume ID
482  * @lnum: logical eraseblock number
483  * @buf: data which was not written because of the write failure
484  * @offset: offset of the failed write
485  * @len: how many bytes should have been written
486  *
487  * This function is called in case of a write failure and moves all good data
488  * from the potentially bad physical eraseblock to a good physical eraseblock.
489  * This function also writes the data which was not written due to the failure.
490  * Returns new physical eraseblock number in case of success, and a negative
491  * error code in case of failure.
492  */
493 static int recover_peb(struct ubi_device *ubi, int pnum, int vol_id, int lnum,
494                        const void *buf, int offset, int len)
495 {
496         int err, idx = vol_id2idx(ubi, vol_id), new_pnum, data_size, tries = 0;
497         struct ubi_volume *vol = ubi->volumes[idx];
498         struct ubi_vid_hdr *vid_hdr;
499
500         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
501         if (!vid_hdr)
502                 return -ENOMEM;
503
504 retry:
505         new_pnum = ubi_wl_get_peb(ubi);
506         if (new_pnum < 0) {
507                 ubi_free_vid_hdr(ubi, vid_hdr);
508                 return new_pnum;
509         }
510
511         ubi_msg("recover PEB %d, move data to PEB %d", pnum, new_pnum);
512
513         err = ubi_io_read_vid_hdr(ubi, pnum, vid_hdr, 1);
514         if (err && err != UBI_IO_BITFLIPS) {
515                 if (err > 0)
516                         err = -EIO;
517                 goto out_put;
518         }
519
520         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
521         err = ubi_io_write_vid_hdr(ubi, new_pnum, vid_hdr);
522         if (err)
523                 goto write_error;
524
525         data_size = offset + len;
526         mutex_lock(&ubi->buf_mutex);
527         memset(ubi->peb_buf + offset, 0xFF, len);
528
529         /* Read everything before the area where the write failure happened */
530         if (offset > 0) {
531                 err = ubi_io_read_data(ubi, ubi->peb_buf, pnum, 0, offset);
532                 if (err && err != UBI_IO_BITFLIPS)
533                         goto out_unlock;
534         }
535
536         memcpy(ubi->peb_buf + offset, buf, len);
537
538         err = ubi_io_write_data(ubi, ubi->peb_buf, new_pnum, 0, data_size);
539         if (err) {
540                 mutex_unlock(&ubi->buf_mutex);
541                 goto write_error;
542         }
543
544         mutex_unlock(&ubi->buf_mutex);
545         ubi_free_vid_hdr(ubi, vid_hdr);
546
547         down_read(&ubi->fm_sem);
548         vol->eba_tbl[lnum] = new_pnum;
549         up_read(&ubi->fm_sem);
550         ubi_wl_put_peb(ubi, vol_id, lnum, pnum, 1);
551
552         ubi_msg("data was successfully recovered");
553         return 0;
554
555 out_unlock:
556         mutex_unlock(&ubi->buf_mutex);
557 out_put:
558         ubi_wl_put_peb(ubi, vol_id, lnum, new_pnum, 1);
559         ubi_free_vid_hdr(ubi, vid_hdr);
560         return err;
561
562 write_error:
563         /*
564          * Bad luck? This physical eraseblock is bad too? Crud. Let's try to
565          * get another one.
566          */
567         ubi_warn("failed to write to PEB %d", new_pnum);
568         ubi_wl_put_peb(ubi, vol_id, lnum, new_pnum, 1);
569         if (++tries > UBI_IO_RETRIES) {
570                 ubi_free_vid_hdr(ubi, vid_hdr);
571                 return err;
572         }
573         ubi_msg("try again");
574         goto retry;
575 }
576
577 /**
578  * ubi_eba_write_leb - write data to dynamic volume.
579  * @ubi: UBI device description object
580  * @vol: volume description object
581  * @lnum: logical eraseblock number
582  * @buf: the data to write
583  * @offset: offset within the logical eraseblock where to write
584  * @len: how many bytes to write
585  *
586  * This function writes data to logical eraseblock @lnum of a dynamic volume
587  * @vol. Returns zero in case of success and a negative error code in case
588  * of failure. In case of error, it is possible that something was still
589  * written to the flash media, but may be some garbage.
590  */
591 int ubi_eba_write_leb(struct ubi_device *ubi, struct ubi_volume *vol, int lnum,
592                       const void *buf, int offset, int len)
593 {
594         int err, pnum, tries = 0, vol_id = vol->vol_id;
595         struct ubi_vid_hdr *vid_hdr;
596
597         if (ubi->ro_mode)
598                 return -EROFS;
599
600         err = leb_write_lock(ubi, vol_id, lnum);
601         if (err)
602                 return err;
603
604         pnum = vol->eba_tbl[lnum];
605         if (pnum >= 0) {
606                 dbg_eba("write %d bytes at offset %d of LEB %d:%d, PEB %d",
607                         len, offset, vol_id, lnum, pnum);
608
609                 err = ubi_io_write_data(ubi, buf, pnum, offset, len);
610                 if (err) {
611                         ubi_warn("failed to write data to PEB %d", pnum);
612                         if (err == -EIO && ubi->bad_allowed)
613                                 err = recover_peb(ubi, pnum, vol_id, lnum, buf,
614                                                   offset, len);
615                         if (err)
616                                 ubi_ro_mode(ubi);
617                 }
618                 leb_write_unlock(ubi, vol_id, lnum);
619                 return err;
620         }
621
622         /*
623          * The logical eraseblock is not mapped. We have to get a free physical
624          * eraseblock and write the volume identifier header there first.
625          */
626         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
627         if (!vid_hdr) {
628                 leb_write_unlock(ubi, vol_id, lnum);
629                 return -ENOMEM;
630         }
631
632         vid_hdr->vol_type = UBI_VID_DYNAMIC;
633         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
634         vid_hdr->vol_id = cpu_to_be32(vol_id);
635         vid_hdr->lnum = cpu_to_be32(lnum);
636         vid_hdr->compat = ubi_get_compat(ubi, vol_id);
637         vid_hdr->data_pad = cpu_to_be32(vol->data_pad);
638
639 retry:
640         pnum = ubi_wl_get_peb(ubi);
641         if (pnum < 0) {
642                 ubi_free_vid_hdr(ubi, vid_hdr);
643                 leb_write_unlock(ubi, vol_id, lnum);
644                 return pnum;
645         }
646
647         dbg_eba("write VID hdr and %d bytes at offset %d of LEB %d:%d, PEB %d",
648                 len, offset, vol_id, lnum, pnum);
649
650         err = ubi_io_write_vid_hdr(ubi, pnum, vid_hdr);
651         if (err) {
652                 ubi_warn("failed to write VID header to LEB %d:%d, PEB %d",
653                          vol_id, lnum, pnum);
654                 goto write_error;
655         }
656
657         if (len) {
658                 err = ubi_io_write_data(ubi, buf, pnum, offset, len);
659                 if (err) {
660                         ubi_warn("failed to write %d bytes at offset %d of LEB %d:%d, PEB %d",
661                                  len, offset, vol_id, lnum, pnum);
662                         goto write_error;
663                 }
664         }
665
666         down_read(&ubi->fm_sem);
667         vol->eba_tbl[lnum] = pnum;
668         up_read(&ubi->fm_sem);
669
670         leb_write_unlock(ubi, vol_id, lnum);
671         ubi_free_vid_hdr(ubi, vid_hdr);
672         return 0;
673
674 write_error:
675         if (err != -EIO || !ubi->bad_allowed) {
676                 ubi_ro_mode(ubi);
677                 leb_write_unlock(ubi, vol_id, lnum);
678                 ubi_free_vid_hdr(ubi, vid_hdr);
679                 return err;
680         }
681
682         /*
683          * Fortunately, this is the first write operation to this physical
684          * eraseblock, so just put it and request a new one. We assume that if
685          * this physical eraseblock went bad, the erase code will handle that.
686          */
687         err = ubi_wl_put_peb(ubi, vol_id, lnum, pnum, 1);
688         if (err || ++tries > UBI_IO_RETRIES) {
689                 ubi_ro_mode(ubi);
690                 leb_write_unlock(ubi, vol_id, lnum);
691                 ubi_free_vid_hdr(ubi, vid_hdr);
692                 return err;
693         }
694
695         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
696         ubi_msg("try another PEB");
697         goto retry;
698 }
699
700 /**
701  * ubi_eba_write_leb_st - write data to static volume.
702  * @ubi: UBI device description object
703  * @vol: volume description object
704  * @lnum: logical eraseblock number
705  * @buf: data to write
706  * @len: how many bytes to write
707  * @used_ebs: how many logical eraseblocks will this volume contain
708  *
709  * This function writes data to logical eraseblock @lnum of static volume
710  * @vol. The @used_ebs argument should contain total number of logical
711  * eraseblock in this static volume.
712  *
713  * When writing to the last logical eraseblock, the @len argument doesn't have
714  * to be aligned to the minimal I/O unit size. Instead, it has to be equivalent
715  * to the real data size, although the @buf buffer has to contain the
716  * alignment. In all other cases, @len has to be aligned.
717  *
718  * It is prohibited to write more than once to logical eraseblocks of static
719  * volumes. This function returns zero in case of success and a negative error
720  * code in case of failure.
721  */
722 int ubi_eba_write_leb_st(struct ubi_device *ubi, struct ubi_volume *vol,
723                          int lnum, const void *buf, int len, int used_ebs)
724 {
725         int err, pnum, tries = 0, data_size = len, vol_id = vol->vol_id;
726         struct ubi_vid_hdr *vid_hdr;
727         uint32_t crc;
728
729         if (ubi->ro_mode)
730                 return -EROFS;
731
732         if (lnum == used_ebs - 1)
733                 /* If this is the last LEB @len may be unaligned */
734                 len = ALIGN(data_size, ubi->min_io_size);
735         else
736                 ubi_assert(!(len & (ubi->min_io_size - 1)));
737
738         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
739         if (!vid_hdr)
740                 return -ENOMEM;
741
742         err = leb_write_lock(ubi, vol_id, lnum);
743         if (err) {
744                 ubi_free_vid_hdr(ubi, vid_hdr);
745                 return err;
746         }
747
748         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
749         vid_hdr->vol_id = cpu_to_be32(vol_id);
750         vid_hdr->lnum = cpu_to_be32(lnum);
751         vid_hdr->compat = ubi_get_compat(ubi, vol_id);
752         vid_hdr->data_pad = cpu_to_be32(vol->data_pad);
753
754         crc = crc32(UBI_CRC32_INIT, buf, data_size);
755         vid_hdr->vol_type = UBI_VID_STATIC;
756         vid_hdr->data_size = cpu_to_be32(data_size);
757         vid_hdr->used_ebs = cpu_to_be32(used_ebs);
758         vid_hdr->data_crc = cpu_to_be32(crc);
759
760 retry:
761         pnum = ubi_wl_get_peb(ubi);
762         if (pnum < 0) {
763                 ubi_free_vid_hdr(ubi, vid_hdr);
764                 leb_write_unlock(ubi, vol_id, lnum);
765                 return pnum;
766         }
767
768         dbg_eba("write VID hdr and %d bytes at LEB %d:%d, PEB %d, used_ebs %d",
769                 len, vol_id, lnum, pnum, used_ebs);
770
771         err = ubi_io_write_vid_hdr(ubi, pnum, vid_hdr);
772         if (err) {
773                 ubi_warn("failed to write VID header to LEB %d:%d, PEB %d",
774                          vol_id, lnum, pnum);
775                 goto write_error;
776         }
777
778         err = ubi_io_write_data(ubi, buf, pnum, 0, len);
779         if (err) {
780                 ubi_warn("failed to write %d bytes of data to PEB %d",
781                          len, pnum);
782                 goto write_error;
783         }
784
785         ubi_assert(vol->eba_tbl[lnum] < 0);
786         down_read(&ubi->fm_sem);
787         vol->eba_tbl[lnum] = pnum;
788         up_read(&ubi->fm_sem);
789
790         leb_write_unlock(ubi, vol_id, lnum);
791         ubi_free_vid_hdr(ubi, vid_hdr);
792         return 0;
793
794 write_error:
795         if (err != -EIO || !ubi->bad_allowed) {
796                 /*
797                  * This flash device does not admit of bad eraseblocks or
798                  * something nasty and unexpected happened. Switch to read-only
799                  * mode just in case.
800                  */
801                 ubi_ro_mode(ubi);
802                 leb_write_unlock(ubi, vol_id, lnum);
803                 ubi_free_vid_hdr(ubi, vid_hdr);
804                 return err;
805         }
806
807         err = ubi_wl_put_peb(ubi, vol_id, lnum, pnum, 1);
808         if (err || ++tries > UBI_IO_RETRIES) {
809                 ubi_ro_mode(ubi);
810                 leb_write_unlock(ubi, vol_id, lnum);
811                 ubi_free_vid_hdr(ubi, vid_hdr);
812                 return err;
813         }
814
815         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
816         ubi_msg("try another PEB");
817         goto retry;
818 }
819
820 /*
821  * ubi_eba_atomic_leb_change - change logical eraseblock atomically.
822  * @ubi: UBI device description object
823  * @vol: volume description object
824  * @lnum: logical eraseblock number
825  * @buf: data to write
826  * @len: how many bytes to write
827  *
828  * This function changes the contents of a logical eraseblock atomically. @buf
829  * has to contain new logical eraseblock data, and @len - the length of the
830  * data, which has to be aligned. This function guarantees that in case of an
831  * unclean reboot the old contents is preserved. Returns zero in case of
832  * success and a negative error code in case of failure.
833  *
834  * UBI reserves one LEB for the "atomic LEB change" operation, so only one
835  * LEB change may be done at a time. This is ensured by @ubi->alc_mutex.
836  */
837 int ubi_eba_atomic_leb_change(struct ubi_device *ubi, struct ubi_volume *vol,
838                               int lnum, const void *buf, int len)
839 {
840         int err, pnum, tries = 0, vol_id = vol->vol_id;
841         struct ubi_vid_hdr *vid_hdr;
842         uint32_t crc;
843
844         if (ubi->ro_mode)
845                 return -EROFS;
846
847         if (len == 0) {
848                 /*
849                  * Special case when data length is zero. In this case the LEB
850                  * has to be unmapped and mapped somewhere else.
851                  */
852                 err = ubi_eba_unmap_leb(ubi, vol, lnum);
853                 if (err)
854                         return err;
855                 return ubi_eba_write_leb(ubi, vol, lnum, NULL, 0, 0);
856         }
857
858         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
859         if (!vid_hdr)
860                 return -ENOMEM;
861
862         mutex_lock(&ubi->alc_mutex);
863         err = leb_write_lock(ubi, vol_id, lnum);
864         if (err)
865                 goto out_mutex;
866
867         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
868         vid_hdr->vol_id = cpu_to_be32(vol_id);
869         vid_hdr->lnum = cpu_to_be32(lnum);
870         vid_hdr->compat = ubi_get_compat(ubi, vol_id);
871         vid_hdr->data_pad = cpu_to_be32(vol->data_pad);
872
873         crc = crc32(UBI_CRC32_INIT, buf, len);
874         vid_hdr->vol_type = UBI_VID_DYNAMIC;
875         vid_hdr->data_size = cpu_to_be32(len);
876         vid_hdr->copy_flag = 1;
877         vid_hdr->data_crc = cpu_to_be32(crc);
878
879 retry:
880         pnum = ubi_wl_get_peb(ubi);
881         if (pnum < 0) {
882                 err = pnum;
883                 goto out_leb_unlock;
884         }
885
886         dbg_eba("change LEB %d:%d, PEB %d, write VID hdr to PEB %d",
887                 vol_id, lnum, vol->eba_tbl[lnum], pnum);
888
889         err = ubi_io_write_vid_hdr(ubi, pnum, vid_hdr);
890         if (err) {
891                 ubi_warn("failed to write VID header to LEB %d:%d, PEB %d",
892                          vol_id, lnum, pnum);
893                 goto write_error;
894         }
895
896         err = ubi_io_write_data(ubi, buf, pnum, 0, len);
897         if (err) {
898                 ubi_warn("failed to write %d bytes of data to PEB %d",
899                          len, pnum);
900                 goto write_error;
901         }
902
903         if (vol->eba_tbl[lnum] >= 0) {
904                 err = ubi_wl_put_peb(ubi, vol_id, lnum, vol->eba_tbl[lnum], 0);
905                 if (err)
906                         goto out_leb_unlock;
907         }
908
909         down_read(&ubi->fm_sem);
910         vol->eba_tbl[lnum] = pnum;
911         up_read(&ubi->fm_sem);
912
913 out_leb_unlock:
914         leb_write_unlock(ubi, vol_id, lnum);
915 out_mutex:
916         mutex_unlock(&ubi->alc_mutex);
917         ubi_free_vid_hdr(ubi, vid_hdr);
918         return err;
919
920 write_error:
921         if (err != -EIO || !ubi->bad_allowed) {
922                 /*
923                  * This flash device does not admit of bad eraseblocks or
924                  * something nasty and unexpected happened. Switch to read-only
925                  * mode just in case.
926                  */
927                 ubi_ro_mode(ubi);
928                 goto out_leb_unlock;
929         }
930
931         err = ubi_wl_put_peb(ubi, vol_id, lnum, pnum, 1);
932         if (err || ++tries > UBI_IO_RETRIES) {
933                 ubi_ro_mode(ubi);
934                 goto out_leb_unlock;
935         }
936
937         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
938         ubi_msg("try another PEB");
939         goto retry;
940 }
941
942 /**
943  * is_error_sane - check whether a read error is sane.
944  * @err: code of the error happened during reading
945  *
946  * This is a helper function for 'ubi_eba_copy_leb()' which is called when we
947  * cannot read data from the target PEB (an error @err happened). If the error
948  * code is sane, then we treat this error as non-fatal. Otherwise the error is
949  * fatal and UBI will be switched to R/O mode later.
950  *
951  * The idea is that we try not to switch to R/O mode if the read error is
952  * something which suggests there was a real read problem. E.g., %-EIO. Or a
953  * memory allocation failed (-%ENOMEM). Otherwise, it is safer to switch to R/O
954  * mode, simply because we do not know what happened at the MTD level, and we
955  * cannot handle this. E.g., the underlying driver may have become crazy, and
956  * it is safer to switch to R/O mode to preserve the data.
957  *
958  * And bear in mind, this is about reading from the target PEB, i.e. the PEB
959  * which we have just written.
960  */
961 static int is_error_sane(int err)
962 {
963         if (err == -EIO || err == -ENOMEM || err == UBI_IO_BAD_HDR ||
964             err == UBI_IO_BAD_HDR_EBADMSG || err == -ETIMEDOUT)
965                 return 0;
966         return 1;
967 }
968
969 /**
970  * ubi_eba_copy_leb - copy logical eraseblock.
971  * @ubi: UBI device description object
972  * @from: physical eraseblock number from where to copy
973  * @to: physical eraseblock number where to copy
974  * @vid_hdr: VID header of the @from physical eraseblock
975  *
976  * This function copies logical eraseblock from physical eraseblock @from to
977  * physical eraseblock @to. The @vid_hdr buffer may be changed by this
978  * function. Returns:
979  *   o %0 in case of success;
980  *   o %MOVE_CANCEL_RACE, %MOVE_TARGET_WR_ERR, %MOVE_TARGET_BITFLIPS, etc;
981  *   o a negative error code in case of failure.
982  */
983 int ubi_eba_copy_leb(struct ubi_device *ubi, int from, int to,
984                      struct ubi_vid_hdr *vid_hdr)
985 {
986         int err, vol_id, lnum, data_size, aldata_size, idx;
987         struct ubi_volume *vol;
988         uint32_t crc;
989
990         vol_id = be32_to_cpu(vid_hdr->vol_id);
991         lnum = be32_to_cpu(vid_hdr->lnum);
992
993         dbg_wl("copy LEB %d:%d, PEB %d to PEB %d", vol_id, lnum, from, to);
994
995         if (vid_hdr->vol_type == UBI_VID_STATIC) {
996                 data_size = be32_to_cpu(vid_hdr->data_size);
997                 aldata_size = ALIGN(data_size, ubi->min_io_size);
998         } else
999                 data_size = aldata_size =
1000                             ubi->leb_size - be32_to_cpu(vid_hdr->data_pad);
1001
1002         idx = vol_id2idx(ubi, vol_id);
1003         spin_lock(&ubi->volumes_lock);
1004         /*
1005          * Note, we may race with volume deletion, which means that the volume
1006          * this logical eraseblock belongs to might be being deleted. Since the
1007          * volume deletion un-maps all the volume's logical eraseblocks, it will
1008          * be locked in 'ubi_wl_put_peb()' and wait for the WL worker to finish.
1009          */
1010         vol = ubi->volumes[idx];
1011         spin_unlock(&ubi->volumes_lock);
1012         if (!vol) {
1013                 /* No need to do further work, cancel */
1014                 dbg_wl("volume %d is being removed, cancel", vol_id);
1015                 return MOVE_CANCEL_RACE;
1016         }
1017
1018         /*
1019          * We do not want anybody to write to this logical eraseblock while we
1020          * are moving it, so lock it.
1021          *
1022          * Note, we are using non-waiting locking here, because we cannot sleep
1023          * on the LEB, since it may cause deadlocks. Indeed, imagine a task is
1024          * unmapping the LEB which is mapped to the PEB we are going to move
1025          * (@from). This task locks the LEB and goes sleep in the
1026          * 'ubi_wl_put_peb()' function on the @ubi->move_mutex. In turn, we are
1027          * holding @ubi->move_mutex and go sleep on the LEB lock. So, if the
1028          * LEB is already locked, we just do not move it and return
1029          * %MOVE_RETRY. Note, we do not return %MOVE_CANCEL_RACE here because
1030          * we do not know the reasons of the contention - it may be just a
1031          * normal I/O on this LEB, so we want to re-try.
1032          */
1033         err = leb_write_trylock(ubi, vol_id, lnum);
1034         if (err) {
1035                 dbg_wl("contention on LEB %d:%d, cancel", vol_id, lnum);
1036                 return MOVE_RETRY;
1037         }
1038
1039         /*
1040          * The LEB might have been put meanwhile, and the task which put it is
1041          * probably waiting on @ubi->move_mutex. No need to continue the work,
1042          * cancel it.
1043          */
1044         if (vol->eba_tbl[lnum] != from) {
1045                 dbg_wl("LEB %d:%d is no longer mapped to PEB %d, mapped to PEB %d, cancel",
1046                        vol_id, lnum, from, vol->eba_tbl[lnum]);
1047                 err = MOVE_CANCEL_RACE;
1048                 goto out_unlock_leb;
1049         }
1050
1051         /*
1052          * OK, now the LEB is locked and we can safely start moving it. Since
1053          * this function utilizes the @ubi->peb_buf buffer which is shared
1054          * with some other functions - we lock the buffer by taking the
1055          * @ubi->buf_mutex.
1056          */
1057         mutex_lock(&ubi->buf_mutex);
1058         dbg_wl("read %d bytes of data", aldata_size);
1059         err = ubi_io_read_data(ubi, ubi->peb_buf, from, 0, aldata_size);
1060         if (err && err != UBI_IO_BITFLIPS) {
1061                 ubi_warn("error %d while reading data from PEB %d",
1062                          err, from);
1063                 err = MOVE_SOURCE_RD_ERR;
1064                 goto out_unlock_buf;
1065         }
1066
1067         /*
1068          * Now we have got to calculate how much data we have to copy. In
1069          * case of a static volume it is fairly easy - the VID header contains
1070          * the data size. In case of a dynamic volume it is more difficult - we
1071          * have to read the contents, cut 0xFF bytes from the end and copy only
1072          * the first part. We must do this to avoid writing 0xFF bytes as it
1073          * may have some side-effects. And not only this. It is important not
1074          * to include those 0xFFs to CRC because later the they may be filled
1075          * by data.
1076          */
1077         if (vid_hdr->vol_type == UBI_VID_DYNAMIC)
1078                 aldata_size = data_size =
1079                         ubi_calc_data_len(ubi, ubi->peb_buf, data_size);
1080
1081         cond_resched();
1082         crc = crc32(UBI_CRC32_INIT, ubi->peb_buf, data_size);
1083         cond_resched();
1084
1085         /*
1086          * It may turn out to be that the whole @from physical eraseblock
1087          * contains only 0xFF bytes. Then we have to only write the VID header
1088          * and do not write any data. This also means we should not set
1089          * @vid_hdr->copy_flag, @vid_hdr->data_size, and @vid_hdr->data_crc.
1090          */
1091         if (data_size > 0) {
1092                 vid_hdr->copy_flag = 1;
1093                 vid_hdr->data_size = cpu_to_be32(data_size);
1094                 vid_hdr->data_crc = cpu_to_be32(crc);
1095         }
1096         vid_hdr->sqnum = cpu_to_be64(ubi_next_sqnum(ubi));
1097
1098         err = ubi_io_write_vid_hdr(ubi, to, vid_hdr);
1099         if (err) {
1100                 if (err == -EIO)
1101                         err = MOVE_TARGET_WR_ERR;
1102                 goto out_unlock_buf;
1103         }
1104
1105         cond_resched();
1106
1107         /* Read the VID header back and check if it was written correctly */
1108         err = ubi_io_read_vid_hdr(ubi, to, vid_hdr, 1);
1109         if (err) {
1110                 if (err != UBI_IO_BITFLIPS) {
1111                         ubi_warn("error %d while reading VID header back from PEB %d",
1112                                  err, to);
1113                         if (is_error_sane(err))
1114                                 err = MOVE_TARGET_RD_ERR;
1115                 } else
1116                         err = MOVE_TARGET_BITFLIPS;
1117                 goto out_unlock_buf;
1118         }
1119
1120         if (data_size > 0) {
1121                 err = ubi_io_write_data(ubi, ubi->peb_buf, to, 0, aldata_size);
1122                 if (err) {
1123                         if (err == -EIO)
1124                                 err = MOVE_TARGET_WR_ERR;
1125                         goto out_unlock_buf;
1126                 }
1127
1128                 cond_resched();
1129
1130                 /*
1131                  * We've written the data and are going to read it back to make
1132                  * sure it was written correctly.
1133                  */
1134                 memset(ubi->peb_buf, 0xFF, aldata_size);
1135                 err = ubi_io_read_data(ubi, ubi->peb_buf, to, 0, aldata_size);
1136                 if (err) {
1137                         if (err != UBI_IO_BITFLIPS) {
1138                                 ubi_warn("error %d while reading data back from PEB %d",
1139                                          err, to);
1140                                 if (is_error_sane(err))
1141                                         err = MOVE_TARGET_RD_ERR;
1142                         } else
1143                                 err = MOVE_TARGET_BITFLIPS;
1144                         goto out_unlock_buf;
1145                 }
1146
1147                 cond_resched();
1148
1149                 if (crc != crc32(UBI_CRC32_INIT, ubi->peb_buf, data_size)) {
1150                         ubi_warn("read data back from PEB %d and it is different",
1151                                  to);
1152                         err = -EINVAL;
1153                         goto out_unlock_buf;
1154                 }
1155         }
1156
1157         ubi_assert(vol->eba_tbl[lnum] == from);
1158         down_read(&ubi->fm_sem);
1159         vol->eba_tbl[lnum] = to;
1160         up_read(&ubi->fm_sem);
1161
1162 out_unlock_buf:
1163         mutex_unlock(&ubi->buf_mutex);
1164 out_unlock_leb:
1165         leb_write_unlock(ubi, vol_id, lnum);
1166         return err;
1167 }
1168
1169 /**
1170  * print_rsvd_warning - warn about not having enough reserved PEBs.
1171  * @ubi: UBI device description object
1172  *
1173  * This is a helper function for 'ubi_eba_init()' which is called when UBI
1174  * cannot reserve enough PEBs for bad block handling. This function makes a
1175  * decision whether we have to print a warning or not. The algorithm is as
1176  * follows:
1177  *   o if this is a new UBI image, then just print the warning
1178  *   o if this is an UBI image which has already been used for some time, print
1179  *     a warning only if we can reserve less than 10% of the expected amount of
1180  *     the reserved PEB.
1181  *
1182  * The idea is that when UBI is used, PEBs become bad, and the reserved pool
1183  * of PEBs becomes smaller, which is normal and we do not want to scare users
1184  * with a warning every time they attach the MTD device. This was an issue
1185  * reported by real users.
1186  */
1187 static void print_rsvd_warning(struct ubi_device *ubi,
1188                                struct ubi_attach_info *ai)
1189 {
1190         /*
1191          * The 1 << 18 (256KiB) number is picked randomly, just a reasonably
1192          * large number to distinguish between newly flashed and used images.
1193          */
1194         if (ai->max_sqnum > (1 << 18)) {
1195                 int min = ubi->beb_rsvd_level / 10;
1196
1197                 if (!min)
1198                         min = 1;
1199                 if (ubi->beb_rsvd_pebs > min)
1200                         return;
1201         }
1202
1203         ubi_warn("cannot reserve enough PEBs for bad PEB handling, reserved %d, need %d",
1204                  ubi->beb_rsvd_pebs, ubi->beb_rsvd_level);
1205         if (ubi->corr_peb_count)
1206                 ubi_warn("%d PEBs are corrupted and not used",
1207                          ubi->corr_peb_count);
1208 }
1209
1210 /**
1211  * self_check_eba - run a self check on the EBA table constructed by fastmap.
1212  * @ubi: UBI device description object
1213  * @ai_fastmap: UBI attach info object created by fastmap
1214  * @ai_scan: UBI attach info object created by scanning
1215  *
1216  * Returns < 0 in case of an internal error, 0 otherwise.
1217  * If a bad EBA table entry was found it will be printed out and
1218  * ubi_assert() triggers.
1219  */
1220 int self_check_eba(struct ubi_device *ubi, struct ubi_attach_info *ai_fastmap,
1221                    struct ubi_attach_info *ai_scan)
1222 {
1223         int i, j, num_volumes, ret = 0;
1224         int **scan_eba, **fm_eba;
1225         struct ubi_ainf_volume *av;
1226         struct ubi_volume *vol;
1227         struct ubi_ainf_peb *aeb;
1228         struct rb_node *rb;
1229
1230         num_volumes = ubi->vtbl_slots + UBI_INT_VOL_COUNT;
1231
1232         scan_eba = kmalloc(sizeof(*scan_eba) * num_volumes, GFP_KERNEL);
1233         if (!scan_eba)
1234                 return -ENOMEM;
1235
1236         fm_eba = kmalloc(sizeof(*fm_eba) * num_volumes, GFP_KERNEL);
1237         if (!fm_eba) {
1238                 kfree(scan_eba);
1239                 return -ENOMEM;
1240         }
1241
1242         for (i = 0; i < num_volumes; i++) {
1243                 vol = ubi->volumes[i];
1244                 if (!vol)
1245                         continue;
1246
1247                 scan_eba[i] = kmalloc(vol->reserved_pebs * sizeof(**scan_eba),
1248                                       GFP_KERNEL);
1249                 if (!scan_eba[i]) {
1250                         ret = -ENOMEM;
1251                         goto out_free;
1252                 }
1253
1254                 fm_eba[i] = kmalloc(vol->reserved_pebs * sizeof(**fm_eba),
1255                                     GFP_KERNEL);
1256                 if (!fm_eba[i]) {
1257                         ret = -ENOMEM;
1258                         goto out_free;
1259                 }
1260
1261                 for (j = 0; j < vol->reserved_pebs; j++)
1262                         scan_eba[i][j] = fm_eba[i][j] = UBI_LEB_UNMAPPED;
1263
1264                 av = ubi_find_av(ai_scan, idx2vol_id(ubi, i));
1265                 if (!av)
1266                         continue;
1267
1268                 ubi_rb_for_each_entry(rb, aeb, &av->root, u.rb)
1269                         scan_eba[i][aeb->lnum] = aeb->pnum;
1270
1271                 av = ubi_find_av(ai_fastmap, idx2vol_id(ubi, i));
1272                 if (!av)
1273                         continue;
1274
1275                 ubi_rb_for_each_entry(rb, aeb, &av->root, u.rb)
1276                         fm_eba[i][aeb->lnum] = aeb->pnum;
1277
1278                 for (j = 0; j < vol->reserved_pebs; j++) {
1279                         if (scan_eba[i][j] != fm_eba[i][j]) {
1280                                 if (scan_eba[i][j] == UBI_LEB_UNMAPPED ||
1281                                         fm_eba[i][j] == UBI_LEB_UNMAPPED)
1282                                         continue;
1283
1284                                 ubi_err("LEB:%i:%i is PEB:%i instead of %i!",
1285                                         vol->vol_id, i, fm_eba[i][j],
1286                                         scan_eba[i][j]);
1287                                 ubi_assert(0);
1288                         }
1289                 }
1290         }
1291
1292 out_free:
1293         for (i = 0; i < num_volumes; i++) {
1294                 if (!ubi->volumes[i])
1295                         continue;
1296
1297                 kfree(scan_eba[i]);
1298                 kfree(fm_eba[i]);
1299         }
1300
1301         kfree(scan_eba);
1302         kfree(fm_eba);
1303         return ret;
1304 }
1305
1306 /**
1307  * ubi_eba_init - initialize the EBA sub-system using attaching information.
1308  * @ubi: UBI device description object
1309  * @ai: attaching information
1310  *
1311  * This function returns zero in case of success and a negative error code in
1312  * case of failure.
1313  */
1314 int ubi_eba_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
1315 {
1316         int i, j, err, num_volumes;
1317         struct ubi_ainf_volume *av;
1318         struct ubi_volume *vol;
1319         struct ubi_ainf_peb *aeb;
1320         struct rb_node *rb;
1321
1322         dbg_eba("initialize EBA sub-system");
1323
1324         spin_lock_init(&ubi->ltree_lock);
1325         mutex_init(&ubi->alc_mutex);
1326         ubi->ltree = RB_ROOT;
1327
1328         ubi->global_sqnum = ai->max_sqnum + 1;
1329         num_volumes = ubi->vtbl_slots + UBI_INT_VOL_COUNT;
1330
1331         for (i = 0; i < num_volumes; i++) {
1332                 vol = ubi->volumes[i];
1333                 if (!vol)
1334                         continue;
1335
1336                 cond_resched();
1337
1338                 vol->eba_tbl = kmalloc(vol->reserved_pebs * sizeof(int),
1339                                        GFP_KERNEL);
1340                 if (!vol->eba_tbl) {
1341                         err = -ENOMEM;
1342                         goto out_free;
1343                 }
1344
1345                 for (j = 0; j < vol->reserved_pebs; j++)
1346                         vol->eba_tbl[j] = UBI_LEB_UNMAPPED;
1347
1348                 av = ubi_find_av(ai, idx2vol_id(ubi, i));
1349                 if (!av)
1350                         continue;
1351
1352                 ubi_rb_for_each_entry(rb, aeb, &av->root, u.rb) {
1353                         if (aeb->lnum >= vol->reserved_pebs)
1354                                 /*
1355                                  * This may happen in case of an unclean reboot
1356                                  * during re-size.
1357                                  */
1358                                 ubi_move_aeb_to_list(av, aeb, &ai->erase);
1359                         vol->eba_tbl[aeb->lnum] = aeb->pnum;
1360                 }
1361         }
1362
1363         if (ubi->avail_pebs < EBA_RESERVED_PEBS) {
1364                 ubi_err("no enough physical eraseblocks (%d, need %d)",
1365                         ubi->avail_pebs, EBA_RESERVED_PEBS);
1366                 if (ubi->corr_peb_count)
1367                         ubi_err("%d PEBs are corrupted and not used",
1368                                 ubi->corr_peb_count);
1369                 err = -ENOSPC;
1370                 goto out_free;
1371         }
1372         ubi->avail_pebs -= EBA_RESERVED_PEBS;
1373         ubi->rsvd_pebs += EBA_RESERVED_PEBS;
1374
1375         if (ubi->bad_allowed) {
1376                 ubi_calculate_reserved(ubi);
1377
1378                 if (ubi->avail_pebs < ubi->beb_rsvd_level) {
1379                         /* No enough free physical eraseblocks */
1380                         ubi->beb_rsvd_pebs = ubi->avail_pebs;
1381                         print_rsvd_warning(ubi, ai);
1382                 } else
1383                         ubi->beb_rsvd_pebs = ubi->beb_rsvd_level;
1384
1385                 ubi->avail_pebs -= ubi->beb_rsvd_pebs;
1386                 ubi->rsvd_pebs  += ubi->beb_rsvd_pebs;
1387         }
1388
1389         dbg_eba("EBA sub-system is initialized");
1390         return 0;
1391
1392 out_free:
1393         for (i = 0; i < num_volumes; i++) {
1394                 if (!ubi->volumes[i])
1395                         continue;
1396                 kfree(ubi->volumes[i]->eba_tbl);
1397                 ubi->volumes[i]->eba_tbl = NULL;
1398         }
1399         return err;
1400 }