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