UBI: introduce volume refcounting
[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_unlock - unlock logical eraseblock.
264  * @ubi: UBI device description object
265  * @vol_id: volume ID
266  * @lnum: logical eraseblock number
267  */
268 static void leb_write_unlock(struct ubi_device *ubi, int vol_id, int lnum)
269 {
270         int free;
271         struct ubi_ltree_entry *le;
272
273         spin_lock(&ubi->ltree_lock);
274         le = ltree_lookup(ubi, vol_id, lnum);
275         le->users -= 1;
276         ubi_assert(le->users >= 0);
277         if (le->users == 0) {
278                 rb_erase(&le->rb, &ubi->ltree);
279                 free = 1;
280         } else
281                 free = 0;
282         spin_unlock(&ubi->ltree_lock);
283
284         up_write(&le->mutex);
285         if (free)
286                 kmem_cache_free(ubi_ltree_slab, le);
287 }
288
289 /**
290  * ubi_eba_unmap_leb - un-map logical eraseblock.
291  * @ubi: UBI device description object
292  * @vol: volume description object
293  * @lnum: logical eraseblock number
294  *
295  * This function un-maps logical eraseblock @lnum and schedules corresponding
296  * physical eraseblock for erasure. Returns zero in case of success and a
297  * negative error code in case of failure.
298  */
299 int ubi_eba_unmap_leb(struct ubi_device *ubi, struct ubi_volume *vol,
300                       int lnum)
301 {
302         int err, pnum, vol_id = vol->vol_id;
303
304         ubi_assert(vol->ref_count > 0);
305
306         if (ubi->ro_mode)
307                 return -EROFS;
308
309         err = leb_write_lock(ubi, vol_id, lnum);
310         if (err)
311                 return err;
312
313         pnum = vol->eba_tbl[lnum];
314         if (pnum < 0)
315                 /* This logical eraseblock is already unmapped */
316                 goto out_unlock;
317
318         dbg_eba("erase LEB %d:%d, PEB %d", vol_id, lnum, pnum);
319
320         vol->eba_tbl[lnum] = UBI_LEB_UNMAPPED;
321         err = ubi_wl_put_peb(ubi, pnum, 0);
322
323 out_unlock:
324         leb_write_unlock(ubi, vol_id, lnum);
325         return err;
326 }
327
328 /**
329  * ubi_eba_read_leb - read data.
330  * @ubi: UBI device description object
331  * @vol: volume description object
332  * @lnum: logical eraseblock number
333  * @buf: buffer to store the read data
334  * @offset: offset from where to read
335  * @len: how many bytes to read
336  * @check: data CRC check flag
337  *
338  * If the logical eraseblock @lnum is unmapped, @buf is filled with 0xFF
339  * bytes. The @check flag only makes sense for static volumes and forces
340  * eraseblock data CRC checking.
341  *
342  * In case of success this function returns zero. In case of a static volume,
343  * if data CRC mismatches - %-EBADMSG is returned. %-EBADMSG may also be
344  * returned for any volume type if an ECC error was detected by the MTD device
345  * driver. Other negative error cored may be returned in case of other errors.
346  */
347 int ubi_eba_read_leb(struct ubi_device *ubi, struct ubi_volume *vol, int lnum,
348                      void *buf, int offset, int len, int check)
349 {
350         int err, pnum, scrub = 0, vol_id = vol->vol_id;
351         struct ubi_vid_hdr *vid_hdr;
352         uint32_t uninitialized_var(crc);
353
354         ubi_assert(vol->ref_count > 0);
355
356         err = leb_read_lock(ubi, vol_id, lnum);
357         if (err)
358                 return err;
359
360         pnum = vol->eba_tbl[lnum];
361         if (pnum < 0) {
362                 /*
363                  * The logical eraseblock is not mapped, fill the whole buffer
364                  * with 0xFF bytes. The exception is static volumes for which
365                  * it is an error to read unmapped logical eraseblocks.
366                  */
367                 dbg_eba("read %d bytes from offset %d of LEB %d:%d (unmapped)",
368                         len, offset, vol_id, lnum);
369                 leb_read_unlock(ubi, vol_id, lnum);
370                 ubi_assert(vol->vol_type != UBI_STATIC_VOLUME);
371                 memset(buf, 0xFF, len);
372                 return 0;
373         }
374
375         dbg_eba("read %d bytes from offset %d of LEB %d:%d, PEB %d",
376                 len, offset, vol_id, lnum, pnum);
377
378         if (vol->vol_type == UBI_DYNAMIC_VOLUME)
379                 check = 0;
380
381 retry:
382         if (check) {
383                 vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
384                 if (!vid_hdr) {
385                         err = -ENOMEM;
386                         goto out_unlock;
387                 }
388
389                 err = ubi_io_read_vid_hdr(ubi, pnum, vid_hdr, 1);
390                 if (err && err != UBI_IO_BITFLIPS) {
391                         if (err > 0) {
392                                 /*
393                                  * The header is either absent or corrupted.
394                                  * The former case means there is a bug -
395                                  * switch to read-only mode just in case.
396                                  * The latter case means a real corruption - we
397                                  * may try to recover data. FIXME: but this is
398                                  * not implemented.
399                                  */
400                                 if (err == UBI_IO_BAD_VID_HDR) {
401                                         ubi_warn("bad VID header at PEB %d, LEB"
402                                                  "%d:%d", pnum, vol_id, lnum);
403                                         err = -EBADMSG;
404                                 } else
405                                         ubi_ro_mode(ubi);
406                         }
407                         goto out_free;
408                 } else if (err == UBI_IO_BITFLIPS)
409                         scrub = 1;
410
411                 ubi_assert(lnum < be32_to_cpu(vid_hdr->used_ebs));
412                 ubi_assert(len == be32_to_cpu(vid_hdr->data_size));
413
414                 crc = be32_to_cpu(vid_hdr->data_crc);
415                 ubi_free_vid_hdr(ubi, vid_hdr);
416         }
417
418         err = ubi_io_read_data(ubi, buf, pnum, offset, len);
419         if (err) {
420                 if (err == UBI_IO_BITFLIPS) {
421                         scrub = 1;
422                         err = 0;
423                 } else if (err == -EBADMSG) {
424                         if (vol->vol_type == UBI_DYNAMIC_VOLUME)
425                                 goto out_unlock;
426                         scrub = 1;
427                         if (!check) {
428                                 ubi_msg("force data checking");
429                                 check = 1;
430                                 goto retry;
431                         }
432                 } else
433                         goto out_unlock;
434         }
435
436         if (check) {
437                 uint32_t crc1 = crc32(UBI_CRC32_INIT, buf, len);
438                 if (crc1 != crc) {
439                         ubi_warn("CRC error: calculated %#08x, must be %#08x",
440                                  crc1, crc);
441                         err = -EBADMSG;
442                         goto out_unlock;
443                 }
444         }
445
446         if (scrub)
447                 err = ubi_wl_scrub_peb(ubi, pnum);
448
449         leb_read_unlock(ubi, vol_id, lnum);
450         return err;
451
452 out_free:
453         ubi_free_vid_hdr(ubi, vid_hdr);
454 out_unlock:
455         leb_read_unlock(ubi, vol_id, lnum);
456         return err;
457 }
458
459 /**
460  * recover_peb - recover from write failure.
461  * @ubi: UBI device description object
462  * @pnum: the physical eraseblock to recover
463  * @vol_id: volume ID
464  * @lnum: logical eraseblock number
465  * @buf: data which was not written because of the write failure
466  * @offset: offset of the failed write
467  * @len: how many bytes should have been written
468  *
469  * This function is called in case of a write failure and moves all good data
470  * from the potentially bad physical eraseblock to a good physical eraseblock.
471  * This function also writes the data which was not written due to the failure.
472  * Returns new physical eraseblock number in case of success, and a negative
473  * error code in case of failure.
474  */
475 static int recover_peb(struct ubi_device *ubi, int pnum, int vol_id, int lnum,
476                        const void *buf, int offset, int len)
477 {
478         int err, idx = vol_id2idx(ubi, vol_id), new_pnum, data_size, tries = 0;
479         struct ubi_volume *vol = ubi->volumes[idx];
480         struct ubi_vid_hdr *vid_hdr;
481
482         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
483         if (!vid_hdr) {
484                 return -ENOMEM;
485         }
486
487         mutex_lock(&ubi->buf_mutex);
488
489 retry:
490         new_pnum = ubi_wl_get_peb(ubi, UBI_UNKNOWN);
491         if (new_pnum < 0) {
492                 mutex_unlock(&ubi->buf_mutex);
493                 ubi_free_vid_hdr(ubi, vid_hdr);
494                 return new_pnum;
495         }
496
497         ubi_msg("recover PEB %d, move data to PEB %d", pnum, new_pnum);
498
499         err = ubi_io_read_vid_hdr(ubi, pnum, vid_hdr, 1);
500         if (err && err != UBI_IO_BITFLIPS) {
501                 if (err > 0)
502                         err = -EIO;
503                 goto out_put;
504         }
505
506         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
507         err = ubi_io_write_vid_hdr(ubi, new_pnum, vid_hdr);
508         if (err)
509                 goto write_error;
510
511         data_size = offset + len;
512         memset(ubi->peb_buf1 + offset, 0xFF, len);
513
514         /* Read everything before the area where the write failure happened */
515         if (offset > 0) {
516                 err = ubi_io_read_data(ubi, ubi->peb_buf1, pnum, 0, offset);
517                 if (err && err != UBI_IO_BITFLIPS)
518                         goto out_put;
519         }
520
521         memcpy(ubi->peb_buf1 + offset, buf, len);
522
523         err = ubi_io_write_data(ubi, ubi->peb_buf1, new_pnum, 0, data_size);
524         if (err)
525                 goto write_error;
526
527         mutex_unlock(&ubi->buf_mutex);
528         ubi_free_vid_hdr(ubi, vid_hdr);
529
530         vol->eba_tbl[lnum] = new_pnum;
531         ubi_wl_put_peb(ubi, pnum, 1);
532
533         ubi_msg("data was successfully recovered");
534         return 0;
535
536 out_put:
537         mutex_unlock(&ubi->buf_mutex);
538         ubi_wl_put_peb(ubi, new_pnum, 1);
539         ubi_free_vid_hdr(ubi, vid_hdr);
540         return err;
541
542 write_error:
543         /*
544          * Bad luck? This physical eraseblock is bad too? Crud. Let's try to
545          * get another one.
546          */
547         ubi_warn("failed to write to PEB %d", new_pnum);
548         ubi_wl_put_peb(ubi, new_pnum, 1);
549         if (++tries > UBI_IO_RETRIES) {
550                 mutex_unlock(&ubi->buf_mutex);
551                 ubi_free_vid_hdr(ubi, vid_hdr);
552                 return err;
553         }
554         ubi_msg("try again");
555         goto retry;
556 }
557
558 /**
559  * ubi_eba_write_leb - write data to dynamic volume.
560  * @ubi: UBI device description object
561  * @vol: volume description object
562  * @lnum: logical eraseblock number
563  * @buf: the data to write
564  * @offset: offset within the logical eraseblock where to write
565  * @len: how many bytes to write
566  * @dtype: data type
567  *
568  * This function writes data to logical eraseblock @lnum of a dynamic volume
569  * @vol. Returns zero in case of success and a negative error code in case
570  * of failure. In case of error, it is possible that something was still
571  * written to the flash media, but may be some garbage.
572  */
573 int ubi_eba_write_leb(struct ubi_device *ubi, struct ubi_volume *vol, int lnum,
574                       const void *buf, int offset, int len, int dtype)
575 {
576         int err, pnum, tries = 0, vol_id = vol->vol_id;
577         struct ubi_vid_hdr *vid_hdr;
578
579         ubi_assert(vol->ref_count > 0);
580
581         if (ubi->ro_mode)
582                 return -EROFS;
583
584         err = leb_write_lock(ubi, vol_id, lnum);
585         if (err)
586                 return err;
587
588         pnum = vol->eba_tbl[lnum];
589         if (pnum >= 0) {
590                 dbg_eba("write %d bytes at offset %d of LEB %d:%d, PEB %d",
591                         len, offset, vol_id, lnum, pnum);
592
593                 err = ubi_io_write_data(ubi, buf, pnum, offset, len);
594                 if (err) {
595                         ubi_warn("failed to write data to PEB %d", pnum);
596                         if (err == -EIO && ubi->bad_allowed)
597                                 err = recover_peb(ubi, pnum, vol_id, lnum, buf,
598                                                   offset, len);
599                         if (err)
600                                 ubi_ro_mode(ubi);
601                 }
602                 leb_write_unlock(ubi, vol_id, lnum);
603                 return err;
604         }
605
606         /*
607          * The logical eraseblock is not mapped. We have to get a free physical
608          * eraseblock and write the volume identifier header there first.
609          */
610         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
611         if (!vid_hdr) {
612                 leb_write_unlock(ubi, vol_id, lnum);
613                 return -ENOMEM;
614         }
615
616         vid_hdr->vol_type = UBI_VID_DYNAMIC;
617         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
618         vid_hdr->vol_id = cpu_to_be32(vol_id);
619         vid_hdr->lnum = cpu_to_be32(lnum);
620         vid_hdr->compat = ubi_get_compat(ubi, vol_id);
621         vid_hdr->data_pad = cpu_to_be32(vol->data_pad);
622
623 retry:
624         pnum = ubi_wl_get_peb(ubi, dtype);
625         if (pnum < 0) {
626                 ubi_free_vid_hdr(ubi, vid_hdr);
627                 leb_write_unlock(ubi, vol_id, lnum);
628                 return pnum;
629         }
630
631         dbg_eba("write VID hdr and %d bytes at offset %d of LEB %d:%d, PEB %d",
632                 len, offset, vol_id, lnum, pnum);
633
634         err = ubi_io_write_vid_hdr(ubi, pnum, vid_hdr);
635         if (err) {
636                 ubi_warn("failed to write VID header to LEB %d:%d, PEB %d",
637                          vol_id, lnum, pnum);
638                 goto write_error;
639         }
640
641         if (len) {
642                 err = ubi_io_write_data(ubi, buf, pnum, offset, len);
643                 if (err) {
644                         ubi_warn("failed to write %d bytes at offset %d of "
645                                  "LEB %d:%d, PEB %d", len, offset, vol_id,
646                                  lnum, pnum);
647                         goto write_error;
648                 }
649         }
650
651         vol->eba_tbl[lnum] = pnum;
652
653         leb_write_unlock(ubi, vol_id, lnum);
654         ubi_free_vid_hdr(ubi, vid_hdr);
655         return 0;
656
657 write_error:
658         if (err != -EIO || !ubi->bad_allowed) {
659                 ubi_ro_mode(ubi);
660                 leb_write_unlock(ubi, vol_id, lnum);
661                 ubi_free_vid_hdr(ubi, vid_hdr);
662                 return err;
663         }
664
665         /*
666          * Fortunately, this is the first write operation to this physical
667          * eraseblock, so just put it and request a new one. We assume that if
668          * this physical eraseblock went bad, the erase code will handle that.
669          */
670         err = ubi_wl_put_peb(ubi, pnum, 1);
671         if (err || ++tries > UBI_IO_RETRIES) {
672                 ubi_ro_mode(ubi);
673                 leb_write_unlock(ubi, vol_id, lnum);
674                 ubi_free_vid_hdr(ubi, vid_hdr);
675                 return err;
676         }
677
678         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
679         ubi_msg("try another PEB");
680         goto retry;
681 }
682
683 /**
684  * ubi_eba_write_leb_st - write data to static volume.
685  * @ubi: UBI device description object
686  * @vol: volume description object
687  * @lnum: logical eraseblock number
688  * @buf: data to write
689  * @len: how many bytes to write
690  * @dtype: data type
691  * @used_ebs: how many logical eraseblocks will this volume contain
692  *
693  * This function writes data to logical eraseblock @lnum of static volume
694  * @vol. The @used_ebs argument should contain total number of logical
695  * eraseblock in this static volume.
696  *
697  * When writing to the last logical eraseblock, the @len argument doesn't have
698  * to be aligned to the minimal I/O unit size. Instead, it has to be equivalent
699  * to the real data size, although the @buf buffer has to contain the
700  * alignment. In all other cases, @len has to be aligned.
701  *
702  * It is prohibited to write more then once to logical eraseblocks of static
703  * volumes. This function returns zero in case of success and a negative error
704  * code in case of failure.
705  */
706 int ubi_eba_write_leb_st(struct ubi_device *ubi, struct ubi_volume *vol,
707                          int lnum, const void *buf, int len, int dtype,
708                          int used_ebs)
709 {
710         int err, pnum, tries = 0, data_size = len, vol_id = vol->vol_id;
711         struct ubi_vid_hdr *vid_hdr;
712         uint32_t crc;
713
714         ubi_assert(vol->ref_count > 0);
715
716         if (ubi->ro_mode)
717                 return -EROFS;
718
719         if (lnum == used_ebs - 1)
720                 /* If this is the last LEB @len may be unaligned */
721                 len = ALIGN(data_size, ubi->min_io_size);
722         else
723                 ubi_assert(len % ubi->min_io_size == 0);
724
725         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
726         if (!vid_hdr)
727                 return -ENOMEM;
728
729         err = leb_write_lock(ubi, vol_id, lnum);
730         if (err) {
731                 ubi_free_vid_hdr(ubi, vid_hdr);
732                 return err;
733         }
734
735         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
736         vid_hdr->vol_id = cpu_to_be32(vol_id);
737         vid_hdr->lnum = cpu_to_be32(lnum);
738         vid_hdr->compat = ubi_get_compat(ubi, vol_id);
739         vid_hdr->data_pad = cpu_to_be32(vol->data_pad);
740
741         crc = crc32(UBI_CRC32_INIT, buf, data_size);
742         vid_hdr->vol_type = UBI_VID_STATIC;
743         vid_hdr->data_size = cpu_to_be32(data_size);
744         vid_hdr->used_ebs = cpu_to_be32(used_ebs);
745         vid_hdr->data_crc = cpu_to_be32(crc);
746
747 retry:
748         pnum = ubi_wl_get_peb(ubi, dtype);
749         if (pnum < 0) {
750                 ubi_free_vid_hdr(ubi, vid_hdr);
751                 leb_write_unlock(ubi, vol_id, lnum);
752                 return pnum;
753         }
754
755         dbg_eba("write VID hdr and %d bytes at LEB %d:%d, PEB %d, used_ebs %d",
756                 len, vol_id, lnum, pnum, used_ebs);
757
758         err = ubi_io_write_vid_hdr(ubi, pnum, vid_hdr);
759         if (err) {
760                 ubi_warn("failed to write VID header to LEB %d:%d, PEB %d",
761                          vol_id, lnum, pnum);
762                 goto write_error;
763         }
764
765         err = ubi_io_write_data(ubi, buf, pnum, 0, len);
766         if (err) {
767                 ubi_warn("failed to write %d bytes of data to PEB %d",
768                          len, pnum);
769                 goto write_error;
770         }
771
772         ubi_assert(vol->eba_tbl[lnum] < 0);
773         vol->eba_tbl[lnum] = pnum;
774
775         leb_write_unlock(ubi, vol_id, lnum);
776         ubi_free_vid_hdr(ubi, vid_hdr);
777         return 0;
778
779 write_error:
780         if (err != -EIO || !ubi->bad_allowed) {
781                 /*
782                  * This flash device does not admit of bad eraseblocks or
783                  * something nasty and unexpected happened. Switch to read-only
784                  * mode just in case.
785                  */
786                 ubi_ro_mode(ubi);
787                 leb_write_unlock(ubi, vol_id, lnum);
788                 ubi_free_vid_hdr(ubi, vid_hdr);
789                 return err;
790         }
791
792         err = ubi_wl_put_peb(ubi, pnum, 1);
793         if (err || ++tries > UBI_IO_RETRIES) {
794                 ubi_ro_mode(ubi);
795                 leb_write_unlock(ubi, vol_id, lnum);
796                 ubi_free_vid_hdr(ubi, vid_hdr);
797                 return err;
798         }
799
800         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
801         ubi_msg("try another PEB");
802         goto retry;
803 }
804
805 /*
806  * ubi_eba_atomic_leb_change - change logical eraseblock atomically.
807  * @ubi: UBI device description object
808  * @vol: volume description object
809  * @lnum: logical eraseblock number
810  * @buf: data to write
811  * @len: how many bytes to write
812  * @dtype: data type
813  *
814  * This function changes the contents of a logical eraseblock atomically. @buf
815  * has to contain new logical eraseblock data, and @len - the length of the
816  * data, which has to be aligned. This function guarantees that in case of an
817  * unclean reboot the old contents is preserved. Returns zero in case of
818  * success and a negative error code in case of failure.
819  *
820  * UBI reserves one LEB for the "atomic LEB change" operation, so only one
821  * LEB change may be done at a time. This is ensured by @ubi->alc_mutex.
822  */
823 int ubi_eba_atomic_leb_change(struct ubi_device *ubi, struct ubi_volume *vol,
824                               int lnum, const void *buf, int len, int dtype)
825 {
826         int err, pnum, tries = 0, vol_id = vol->vol_id;
827         struct ubi_vid_hdr *vid_hdr;
828         uint32_t crc;
829
830         ubi_assert(vol->ref_count > 0);
831
832         if (ubi->ro_mode)
833                 return -EROFS;
834
835         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
836         if (!vid_hdr)
837                 return -ENOMEM;
838
839         mutex_lock(&ubi->alc_mutex);
840         err = leb_write_lock(ubi, vol_id, lnum);
841         if (err)
842                 goto out_mutex;
843
844         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
845         vid_hdr->vol_id = cpu_to_be32(vol_id);
846         vid_hdr->lnum = cpu_to_be32(lnum);
847         vid_hdr->compat = ubi_get_compat(ubi, vol_id);
848         vid_hdr->data_pad = cpu_to_be32(vol->data_pad);
849
850         crc = crc32(UBI_CRC32_INIT, buf, len);
851         vid_hdr->vol_type = UBI_VID_DYNAMIC;
852         vid_hdr->data_size = cpu_to_be32(len);
853         vid_hdr->copy_flag = 1;
854         vid_hdr->data_crc = cpu_to_be32(crc);
855
856 retry:
857         pnum = ubi_wl_get_peb(ubi, dtype);
858         if (pnum < 0) {
859                 err = pnum;
860                 goto out_leb_unlock;
861         }
862
863         dbg_eba("change LEB %d:%d, PEB %d, write VID hdr to PEB %d",
864                 vol_id, lnum, vol->eba_tbl[lnum], pnum);
865
866         err = ubi_io_write_vid_hdr(ubi, pnum, vid_hdr);
867         if (err) {
868                 ubi_warn("failed to write VID header to LEB %d:%d, PEB %d",
869                          vol_id, lnum, pnum);
870                 goto write_error;
871         }
872
873         err = ubi_io_write_data(ubi, buf, pnum, 0, len);
874         if (err) {
875                 ubi_warn("failed to write %d bytes of data to PEB %d",
876                          len, pnum);
877                 goto write_error;
878         }
879
880         if (vol->eba_tbl[lnum] >= 0) {
881                 err = ubi_wl_put_peb(ubi, vol->eba_tbl[lnum], 1);
882                 if (err)
883                         goto out_leb_unlock;
884         }
885
886         vol->eba_tbl[lnum] = pnum;
887
888 out_leb_unlock:
889         leb_write_unlock(ubi, vol_id, lnum);
890 out_mutex:
891         mutex_unlock(&ubi->alc_mutex);
892         ubi_free_vid_hdr(ubi, vid_hdr);
893         return err;
894
895 write_error:
896         if (err != -EIO || !ubi->bad_allowed) {
897                 /*
898                  * This flash device does not admit of bad eraseblocks or
899                  * something nasty and unexpected happened. Switch to read-only
900                  * mode just in case.
901                  */
902                 ubi_ro_mode(ubi);
903                 goto out_leb_unlock;
904         }
905
906         err = ubi_wl_put_peb(ubi, pnum, 1);
907         if (err || ++tries > UBI_IO_RETRIES) {
908                 ubi_ro_mode(ubi);
909                 goto out_leb_unlock;
910         }
911
912         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
913         ubi_msg("try another PEB");
914         goto retry;
915 }
916
917 /**
918  * ubi_eba_copy_leb - copy logical eraseblock.
919  * @ubi: UBI device description object
920  * @from: physical eraseblock number from where to copy
921  * @to: physical eraseblock number where to copy
922  * @vid_hdr: VID header of the @from physical eraseblock
923  *
924  * This function copies logical eraseblock from physical eraseblock @from to
925  * physical eraseblock @to. The @vid_hdr buffer may be changed by this
926  * function. Returns zero in case of success, %UBI_IO_BITFLIPS if the operation
927  * was canceled because bit-flips were detected at the target PEB, and a
928  * negative error code in case of failure.
929  */
930 int ubi_eba_copy_leb(struct ubi_device *ubi, int from, int to,
931                      struct ubi_vid_hdr *vid_hdr)
932 {
933         int err, vol_id, lnum, data_size, aldata_size, pnum, idx;
934         struct ubi_volume *vol;
935         uint32_t crc;
936
937         vol_id = be32_to_cpu(vid_hdr->vol_id);
938         lnum = be32_to_cpu(vid_hdr->lnum);
939
940         dbg_eba("copy LEB %d:%d, PEB %d to PEB %d", vol_id, lnum, from, to);
941
942         if (vid_hdr->vol_type == UBI_VID_STATIC) {
943                 data_size = be32_to_cpu(vid_hdr->data_size);
944                 aldata_size = ALIGN(data_size, ubi->min_io_size);
945         } else
946                 data_size = aldata_size =
947                             ubi->leb_size - be32_to_cpu(vid_hdr->data_pad);
948
949         /*
950          * We do not want anybody to write to this logical eraseblock while we
951          * are moving it, so we lock it.
952          */
953         err = leb_write_lock(ubi, vol_id, lnum);
954         if (err)
955                 return err;
956
957         mutex_lock(&ubi->buf_mutex);
958
959         /*
960          * But the logical eraseblock might have been put by this time.
961          * Cancel if it is true.
962          */
963         idx = vol_id2idx(ubi, vol_id);
964
965         /*
966          * We may race with volume deletion/re-size, so we have to hold
967          * @ubi->volumes_lock.
968          *
969          * Note, it is not a problem if we race with volume deletion or re-size
970          * here. If the volume is deleted or re-sized while we are moving an
971          * eraseblock which belongs to this volume, we'll end up with finding
972          * out that this LEB was unmapped at the end (see WL), and drop this
973          * PEB.
974          */
975         spin_lock(&ubi->volumes_lock);
976         vol = ubi->volumes[idx];
977         if (!vol) {
978                 dbg_eba("volume %d was removed meanwhile", vol_id);
979                 spin_unlock(&ubi->volumes_lock);
980                 goto out_unlock;
981         }
982
983         pnum = vol->eba_tbl[lnum];
984         if (pnum != from) {
985                 dbg_eba("LEB %d:%d is no longer mapped to PEB %d, mapped to "
986                         "PEB %d, cancel", vol_id, lnum, from, pnum);
987                 spin_unlock(&ubi->volumes_lock);
988                 goto out_unlock;
989         }
990         spin_unlock(&ubi->volumes_lock);
991
992         /* OK, now the LEB is locked and we can safely start moving it */
993
994         dbg_eba("read %d bytes of data", aldata_size);
995         err = ubi_io_read_data(ubi, ubi->peb_buf1, from, 0, aldata_size);
996         if (err && err != UBI_IO_BITFLIPS) {
997                 ubi_warn("error %d while reading data from PEB %d",
998                          err, from);
999                 goto out_unlock;
1000         }
1001
1002         /*
1003          * Now we have got to calculate how much data we have to to copy. In
1004          * case of a static volume it is fairly easy - the VID header contains
1005          * the data size. In case of a dynamic volume it is more difficult - we
1006          * have to read the contents, cut 0xFF bytes from the end and copy only
1007          * the first part. We must do this to avoid writing 0xFF bytes as it
1008          * may have some side-effects. And not only this. It is important not
1009          * to include those 0xFFs to CRC because later the they may be filled
1010          * by data.
1011          */
1012         if (vid_hdr->vol_type == UBI_VID_DYNAMIC)
1013                 aldata_size = data_size =
1014                         ubi_calc_data_len(ubi, ubi->peb_buf1, data_size);
1015
1016         cond_resched();
1017         crc = crc32(UBI_CRC32_INIT, ubi->peb_buf1, data_size);
1018         cond_resched();
1019
1020         /*
1021          * It may turn out to me that the whole @from physical eraseblock
1022          * contains only 0xFF bytes. Then we have to only write the VID header
1023          * and do not write any data. This also means we should not set
1024          * @vid_hdr->copy_flag, @vid_hdr->data_size, and @vid_hdr->data_crc.
1025          */
1026         if (data_size > 0) {
1027                 vid_hdr->copy_flag = 1;
1028                 vid_hdr->data_size = cpu_to_be32(data_size);
1029                 vid_hdr->data_crc = cpu_to_be32(crc);
1030         }
1031         vid_hdr->sqnum = cpu_to_be64(next_sqnum(ubi));
1032
1033         err = ubi_io_write_vid_hdr(ubi, to, vid_hdr);
1034         if (err)
1035                 goto out_unlock;
1036
1037         cond_resched();
1038
1039         /* Read the VID header back and check if it was written correctly */
1040         err = ubi_io_read_vid_hdr(ubi, to, vid_hdr, 1);
1041         if (err) {
1042                 if (err != UBI_IO_BITFLIPS)
1043                         ubi_warn("cannot read VID header back from PEB %d", to);
1044                 goto out_unlock;
1045         }
1046
1047         if (data_size > 0) {
1048                 err = ubi_io_write_data(ubi, ubi->peb_buf1, to, 0, aldata_size);
1049                 if (err)
1050                         goto out_unlock;
1051
1052                 cond_resched();
1053
1054                 /*
1055                  * We've written the data and are going to read it back to make
1056                  * sure it was written correctly.
1057                  */
1058
1059                 err = ubi_io_read_data(ubi, ubi->peb_buf2, to, 0, aldata_size);
1060                 if (err) {
1061                         if (err != UBI_IO_BITFLIPS)
1062                                 ubi_warn("cannot read data back from PEB %d",
1063                                          to);
1064                         goto out_unlock;
1065                 }
1066
1067                 cond_resched();
1068
1069                 if (memcmp(ubi->peb_buf1, ubi->peb_buf2, aldata_size)) {
1070                         ubi_warn("read data back from PEB %d - it is different",
1071                                  to);
1072                         goto out_unlock;
1073                 }
1074         }
1075
1076         ubi_assert(vol->eba_tbl[lnum] == from);
1077         vol->eba_tbl[lnum] = to;
1078
1079 out_unlock:
1080         mutex_unlock(&ubi->buf_mutex);
1081         leb_write_unlock(ubi, vol_id, lnum);
1082         return err;
1083 }
1084
1085 /**
1086  * ubi_eba_init_scan - initialize the EBA unit using scanning information.
1087  * @ubi: UBI device description object
1088  * @si: scanning information
1089  *
1090  * This function returns zero in case of success and a negative error code in
1091  * case of failure.
1092  */
1093 int ubi_eba_init_scan(struct ubi_device *ubi, struct ubi_scan_info *si)
1094 {
1095         int i, j, err, num_volumes;
1096         struct ubi_scan_volume *sv;
1097         struct ubi_volume *vol;
1098         struct ubi_scan_leb *seb;
1099         struct rb_node *rb;
1100
1101         dbg_eba("initialize EBA unit");
1102
1103         spin_lock_init(&ubi->ltree_lock);
1104         mutex_init(&ubi->alc_mutex);
1105         ubi->ltree = RB_ROOT;
1106
1107         ubi->global_sqnum = si->max_sqnum + 1;
1108         num_volumes = ubi->vtbl_slots + UBI_INT_VOL_COUNT;
1109
1110         for (i = 0; i < num_volumes; i++) {
1111                 vol = ubi->volumes[i];
1112                 if (!vol)
1113                         continue;
1114
1115                 cond_resched();
1116
1117                 vol->eba_tbl = kmalloc(vol->reserved_pebs * sizeof(int),
1118                                        GFP_KERNEL);
1119                 if (!vol->eba_tbl) {
1120                         err = -ENOMEM;
1121                         goto out_free;
1122                 }
1123
1124                 for (j = 0; j < vol->reserved_pebs; j++)
1125                         vol->eba_tbl[j] = UBI_LEB_UNMAPPED;
1126
1127                 sv = ubi_scan_find_sv(si, idx2vol_id(ubi, i));
1128                 if (!sv)
1129                         continue;
1130
1131                 ubi_rb_for_each_entry(rb, seb, &sv->root, u.rb) {
1132                         if (seb->lnum >= vol->reserved_pebs)
1133                                 /*
1134                                  * This may happen in case of an unclean reboot
1135                                  * during re-size.
1136                                  */
1137                                 ubi_scan_move_to_list(sv, seb, &si->erase);
1138                         vol->eba_tbl[seb->lnum] = seb->pnum;
1139                 }
1140         }
1141
1142         if (ubi->avail_pebs < EBA_RESERVED_PEBS) {
1143                 ubi_err("no enough physical eraseblocks (%d, need %d)",
1144                         ubi->avail_pebs, EBA_RESERVED_PEBS);
1145                 err = -ENOSPC;
1146                 goto out_free;
1147         }
1148         ubi->avail_pebs -= EBA_RESERVED_PEBS;
1149         ubi->rsvd_pebs += EBA_RESERVED_PEBS;
1150
1151         if (ubi->bad_allowed) {
1152                 ubi_calculate_reserved(ubi);
1153
1154                 if (ubi->avail_pebs < ubi->beb_rsvd_level) {
1155                         /* No enough free physical eraseblocks */
1156                         ubi->beb_rsvd_pebs = ubi->avail_pebs;
1157                         ubi_warn("cannot reserve enough PEBs for bad PEB "
1158                                  "handling, reserved %d, need %d",
1159                                  ubi->beb_rsvd_pebs, ubi->beb_rsvd_level);
1160                 } else
1161                         ubi->beb_rsvd_pebs = ubi->beb_rsvd_level;
1162
1163                 ubi->avail_pebs -= ubi->beb_rsvd_pebs;
1164                 ubi->rsvd_pebs  += ubi->beb_rsvd_pebs;
1165         }
1166
1167         dbg_eba("EBA unit is initialized");
1168         return 0;
1169
1170 out_free:
1171         for (i = 0; i < num_volumes; i++) {
1172                 if (!ubi->volumes[i])
1173                         continue;
1174                 kfree(ubi->volumes[i]->eba_tbl);
1175         }
1176         return err;
1177 }
1178
1179 /**
1180  * ubi_eba_close - close EBA unit.
1181  * @ubi: UBI device description object
1182  */
1183 void ubi_eba_close(const struct ubi_device *ubi)
1184 {
1185         int i, num_volumes = ubi->vtbl_slots + UBI_INT_VOL_COUNT;
1186
1187         dbg_eba("close EBA unit");
1188
1189         for (i = 0; i < num_volumes; i++) {
1190                 if (!ubi->volumes[i])
1191                         continue;
1192                 kfree(ubi->volumes[i]->eba_tbl);
1193         }
1194 }