2 * Copyright (c) International Business Machines Corp., 2006
4 * SPDX-License-Identifier: GPL-2.0+
6 * Authors: Artem Bityutskiy (Битюцкий Артём), Thomas Gleixner
10 * UBI wear-leveling unit.
12 * This unit is responsible for wear-leveling. It works in terms of physical
13 * eraseblocks and erase counters and knows nothing about logical eraseblocks,
14 * volumes, etc. From this unit's perspective all physical eraseblocks are of
15 * two types - used and free. Used physical eraseblocks are those that were
16 * "get" by the 'ubi_wl_get_peb()' function, and free physical eraseblocks are
17 * those that were put by the 'ubi_wl_put_peb()' function.
19 * Physical eraseblocks returned by 'ubi_wl_get_peb()' have only erase counter
20 * header. The rest of the physical eraseblock contains only 0xFF bytes.
22 * When physical eraseblocks are returned to the WL unit by means of the
23 * 'ubi_wl_put_peb()' function, they are scheduled for erasure. The erasure is
24 * done asynchronously in context of the per-UBI device background thread,
25 * which is also managed by the WL unit.
27 * The wear-leveling is ensured by means of moving the contents of used
28 * physical eraseblocks with low erase counter to free physical eraseblocks
29 * with high erase counter.
31 * The 'ubi_wl_get_peb()' function accepts data type hints which help to pick
32 * an "optimal" physical eraseblock. For example, when it is known that the
33 * physical eraseblock will be "put" soon because it contains short-term data,
34 * the WL unit may pick a free physical eraseblock with low erase counter, and
37 * If the WL unit fails to erase a physical eraseblock, it marks it as bad.
39 * This unit is also responsible for scrubbing. If a bit-flip is detected in a
40 * physical eraseblock, it has to be moved. Technically this is the same as
41 * moving it for wear-leveling reasons.
43 * As it was said, for the UBI unit all physical eraseblocks are either "free"
44 * or "used". Free eraseblock are kept in the @wl->free RB-tree, while used
45 * eraseblocks are kept in a set of different RB-trees: @wl->used,
46 * @wl->prot.pnum, @wl->prot.aec, and @wl->scrub.
48 * Note, in this implementation, we keep a small in-RAM object for each physical
49 * eraseblock. This is surely not a scalable solution. But it appears to be good
50 * enough for moderately large flashes and it is simple. In future, one may
51 * re-work this unit and make it more scalable.
53 * At the moment this unit does not utilize the sequence number, which was
54 * introduced relatively recently. But it would be wise to do this because the
55 * sequence number of a logical eraseblock characterizes how old is it. For
56 * example, when we move a PEB with low erase counter, and we need to pick the
57 * target PEB, we pick a PEB with the highest EC if our PEB is "old" and we
58 * pick target PEB with an average EC if our PEB is not very "old". This is a
59 * room for future re-works of the WL unit.
61 * FIXME: looks too complex, should be simplified (later).
65 #include <linux/slab.h>
66 #include <linux/crc32.h>
67 #include <linux/freezer.h>
68 #include <linux/kthread.h>
71 #include <ubi_uboot.h>
74 /* Number of physical eraseblocks reserved for wear-leveling purposes */
75 #define WL_RESERVED_PEBS 1
78 * How many erase cycles are short term, unknown, and long term physical
79 * eraseblocks protected.
81 #define ST_PROTECTION 16
82 #define U_PROTECTION 10
83 #define LT_PROTECTION 4
86 * Maximum difference between two erase counters. If this threshold is
87 * exceeded, the WL unit starts moving data from used physical eraseblocks with
88 * low erase counter to free physical eraseblocks with high erase counter.
90 #define UBI_WL_THRESHOLD CONFIG_MTD_UBI_WL_THRESHOLD
93 * When a physical eraseblock is moved, the WL unit has to pick the target
94 * physical eraseblock to move to. The simplest way would be just to pick the
95 * one with the highest erase counter. But in certain workloads this could lead
96 * to an unlimited wear of one or few physical eraseblock. Indeed, imagine a
97 * situation when the picked physical eraseblock is constantly erased after the
98 * data is written to it. So, we have a constant which limits the highest erase
99 * counter of the free physical eraseblock to pick. Namely, the WL unit does
100 * not pick eraseblocks with erase counter greater then the lowest erase
101 * counter plus %WL_FREE_MAX_DIFF.
103 #define WL_FREE_MAX_DIFF (2*UBI_WL_THRESHOLD)
106 * Maximum number of consecutive background thread failures which is enough to
107 * switch to read-only mode.
109 #define WL_MAX_FAILURES 32
112 * struct ubi_wl_prot_entry - PEB protection entry.
113 * @rb_pnum: link in the @wl->prot.pnum RB-tree
114 * @rb_aec: link in the @wl->prot.aec RB-tree
115 * @abs_ec: the absolute erase counter value when the protection ends
116 * @e: the wear-leveling entry of the physical eraseblock under protection
118 * When the WL unit returns a physical eraseblock, the physical eraseblock is
119 * protected from being moved for some "time". For this reason, the physical
120 * eraseblock is not directly moved from the @wl->free tree to the @wl->used
121 * tree. There is one more tree in between where this physical eraseblock is
122 * temporarily stored (@wl->prot).
124 * All this protection stuff is needed because:
125 * o we don't want to move physical eraseblocks just after we have given them
126 * to the user; instead, we first want to let users fill them up with data;
128 * o there is a chance that the user will put the physical eraseblock very
129 * soon, so it makes sense not to move it for some time, but wait; this is
130 * especially important in case of "short term" physical eraseblocks.
132 * Physical eraseblocks stay protected only for limited time. But the "time" is
133 * measured in erase cycles in this case. This is implemented with help of the
134 * absolute erase counter (@wl->abs_ec). When it reaches certain value, the
135 * physical eraseblocks are moved from the protection trees (@wl->prot.*) to
136 * the @wl->used tree.
138 * Protected physical eraseblocks are searched by physical eraseblock number
139 * (when they are put) and by the absolute erase counter (to check if it is
140 * time to move them to the @wl->used tree). So there are actually 2 RB-trees
141 * storing the protected physical eraseblocks: @wl->prot.pnum and
142 * @wl->prot.aec. They are referred to as the "protection" trees. The
143 * first one is indexed by the physical eraseblock number. The second one is
144 * indexed by the absolute erase counter. Both trees store
145 * &struct ubi_wl_prot_entry objects.
147 * Each physical eraseblock has 2 main states: free and used. The former state
148 * corresponds to the @wl->free tree. The latter state is split up on several
150 * o the WL movement is allowed (@wl->used tree);
151 * o the WL movement is temporarily prohibited (@wl->prot.pnum and
152 * @wl->prot.aec trees);
153 * o scrubbing is needed (@wl->scrub tree).
155 * Depending on the sub-state, wear-leveling entries of the used physical
156 * eraseblocks may be kept in one of those trees.
158 struct ubi_wl_prot_entry {
159 struct rb_node rb_pnum;
160 struct rb_node rb_aec;
161 unsigned long long abs_ec;
162 struct ubi_wl_entry *e;
166 * struct ubi_work - UBI work description data structure.
167 * @list: a link in the list of pending works
168 * @func: worker function
169 * @priv: private data of the worker function
171 * @e: physical eraseblock to erase
172 * @torture: if the physical eraseblock has to be tortured
174 * The @func pointer points to the worker function. If the @cancel argument is
175 * not zero, the worker has to free the resources and exit immediately. The
176 * worker has to return zero in case of success and a negative error code in
180 struct list_head list;
181 int (*func)(struct ubi_device *ubi, struct ubi_work *wrk, int cancel);
182 /* The below fields are only relevant to erasure works */
183 struct ubi_wl_entry *e;
187 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
188 static int paranoid_check_ec(struct ubi_device *ubi, int pnum, int ec);
189 static int paranoid_check_in_wl_tree(struct ubi_wl_entry *e,
190 struct rb_root *root);
192 #define paranoid_check_ec(ubi, pnum, ec) 0
193 #define paranoid_check_in_wl_tree(e, root)
197 * wl_tree_add - add a wear-leveling entry to a WL RB-tree.
198 * @e: the wear-leveling entry to add
199 * @root: the root of the tree
201 * Note, we use (erase counter, physical eraseblock number) pairs as keys in
202 * the @ubi->used and @ubi->free RB-trees.
204 static void wl_tree_add(struct ubi_wl_entry *e, struct rb_root *root)
206 struct rb_node **p, *parent = NULL;
210 struct ubi_wl_entry *e1;
213 e1 = rb_entry(parent, struct ubi_wl_entry, rb);
217 else if (e->ec > e1->ec)
220 ubi_assert(e->pnum != e1->pnum);
221 if (e->pnum < e1->pnum)
228 rb_link_node(&e->rb, parent, p);
229 rb_insert_color(&e->rb, root);
233 * do_work - do one pending work.
234 * @ubi: UBI device description object
236 * This function returns zero in case of success and a negative error code in
239 static int do_work(struct ubi_device *ubi)
242 struct ubi_work *wrk;
247 * @ubi->work_sem is used to synchronize with the workers. Workers take
248 * it in read mode, so many of them may be doing works at a time. But
249 * the queue flush code has to be sure the whole queue of works is
250 * done, and it takes the mutex in write mode.
252 down_read(&ubi->work_sem);
253 spin_lock(&ubi->wl_lock);
254 if (list_empty(&ubi->works)) {
255 spin_unlock(&ubi->wl_lock);
256 up_read(&ubi->work_sem);
260 wrk = list_entry(ubi->works.next, struct ubi_work, list);
261 list_del(&wrk->list);
262 ubi->works_count -= 1;
263 ubi_assert(ubi->works_count >= 0);
264 spin_unlock(&ubi->wl_lock);
267 * Call the worker function. Do not touch the work structure
268 * after this call as it will have been freed or reused by that
269 * time by the worker function.
271 err = wrk->func(ubi, wrk, 0);
273 ubi_err("work failed with error code %d", err);
274 up_read(&ubi->work_sem);
280 * produce_free_peb - produce a free physical eraseblock.
281 * @ubi: UBI device description object
283 * This function tries to make a free PEB by means of synchronous execution of
284 * pending works. This may be needed if, for example the background thread is
285 * disabled. Returns zero in case of success and a negative error code in case
288 static int produce_free_peb(struct ubi_device *ubi)
292 spin_lock(&ubi->wl_lock);
293 while (!ubi->free.rb_node) {
294 spin_unlock(&ubi->wl_lock);
296 dbg_wl("do one work synchronously");
301 spin_lock(&ubi->wl_lock);
303 spin_unlock(&ubi->wl_lock);
309 * in_wl_tree - check if wear-leveling entry is present in a WL RB-tree.
310 * @e: the wear-leveling entry to check
311 * @root: the root of the tree
313 * This function returns non-zero if @e is in the @root RB-tree and zero if it
316 static int in_wl_tree(struct ubi_wl_entry *e, struct rb_root *root)
322 struct ubi_wl_entry *e1;
324 e1 = rb_entry(p, struct ubi_wl_entry, rb);
326 if (e->pnum == e1->pnum) {
333 else if (e->ec > e1->ec)
336 ubi_assert(e->pnum != e1->pnum);
337 if (e->pnum < e1->pnum)
348 * prot_tree_add - add physical eraseblock to protection trees.
349 * @ubi: UBI device description object
350 * @e: the physical eraseblock to add
351 * @pe: protection entry object to use
352 * @abs_ec: absolute erase counter value when this physical eraseblock has
353 * to be removed from the protection trees.
355 * @wl->lock has to be locked.
357 static void prot_tree_add(struct ubi_device *ubi, struct ubi_wl_entry *e,
358 struct ubi_wl_prot_entry *pe, int abs_ec)
360 struct rb_node **p, *parent = NULL;
361 struct ubi_wl_prot_entry *pe1;
364 pe->abs_ec = ubi->abs_ec + abs_ec;
366 p = &ubi->prot.pnum.rb_node;
369 pe1 = rb_entry(parent, struct ubi_wl_prot_entry, rb_pnum);
371 if (e->pnum < pe1->e->pnum)
376 rb_link_node(&pe->rb_pnum, parent, p);
377 rb_insert_color(&pe->rb_pnum, &ubi->prot.pnum);
379 p = &ubi->prot.aec.rb_node;
383 pe1 = rb_entry(parent, struct ubi_wl_prot_entry, rb_aec);
385 if (pe->abs_ec < pe1->abs_ec)
390 rb_link_node(&pe->rb_aec, parent, p);
391 rb_insert_color(&pe->rb_aec, &ubi->prot.aec);
395 * find_wl_entry - find wear-leveling entry closest to certain erase counter.
396 * @root: the RB-tree where to look for
397 * @max: highest possible erase counter
399 * This function looks for a wear leveling entry with erase counter closest to
400 * @max and less then @max.
402 static struct ubi_wl_entry *find_wl_entry(struct rb_root *root, int max)
405 struct ubi_wl_entry *e;
407 e = rb_entry(rb_first(root), struct ubi_wl_entry, rb);
412 struct ubi_wl_entry *e1;
414 e1 = rb_entry(p, struct ubi_wl_entry, rb);
427 * ubi_wl_get_peb - get a physical eraseblock.
428 * @ubi: UBI device description object
429 * @dtype: type of data which will be stored in this physical eraseblock
431 * This function returns a physical eraseblock in case of success and a
432 * negative error code in case of failure. Might sleep.
434 int ubi_wl_get_peb(struct ubi_device *ubi, int dtype)
436 int err, protect, medium_ec;
437 struct ubi_wl_entry *e, *first, *last;
438 struct ubi_wl_prot_entry *pe;
440 ubi_assert(dtype == UBI_LONGTERM || dtype == UBI_SHORTTERM ||
441 dtype == UBI_UNKNOWN);
443 pe = kmalloc(sizeof(struct ubi_wl_prot_entry), GFP_NOFS);
448 spin_lock(&ubi->wl_lock);
449 if (!ubi->free.rb_node) {
450 if (ubi->works_count == 0) {
451 ubi_assert(list_empty(&ubi->works));
452 ubi_err("no free eraseblocks");
453 spin_unlock(&ubi->wl_lock);
457 spin_unlock(&ubi->wl_lock);
459 err = produce_free_peb(ubi);
470 * For long term data we pick a physical eraseblock
471 * with high erase counter. But the highest erase
472 * counter we can pick is bounded by the the lowest
473 * erase counter plus %WL_FREE_MAX_DIFF.
475 e = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
476 protect = LT_PROTECTION;
480 * For unknown data we pick a physical eraseblock with
481 * medium erase counter. But we by no means can pick a
482 * physical eraseblock with erase counter greater or
483 * equivalent than the lowest erase counter plus
486 first = rb_entry(rb_first(&ubi->free),
487 struct ubi_wl_entry, rb);
488 last = rb_entry(rb_last(&ubi->free),
489 struct ubi_wl_entry, rb);
491 if (last->ec - first->ec < WL_FREE_MAX_DIFF)
492 e = rb_entry(ubi->free.rb_node,
493 struct ubi_wl_entry, rb);
495 medium_ec = (first->ec + WL_FREE_MAX_DIFF)/2;
496 e = find_wl_entry(&ubi->free, medium_ec);
498 protect = U_PROTECTION;
502 * For short term data we pick a physical eraseblock
503 * with the lowest erase counter as we expect it will
506 e = rb_entry(rb_first(&ubi->free),
507 struct ubi_wl_entry, rb);
508 protect = ST_PROTECTION;
517 * Move the physical eraseblock to the protection trees where it will
518 * be protected from being moved for some time.
520 paranoid_check_in_wl_tree(e, &ubi->free);
521 rb_erase(&e->rb, &ubi->free);
522 prot_tree_add(ubi, e, pe, protect);
524 dbg_wl("PEB %d EC %d, protection %d", e->pnum, e->ec, protect);
525 spin_unlock(&ubi->wl_lock);
531 * prot_tree_del - remove a physical eraseblock from the protection trees
532 * @ubi: UBI device description object
533 * @pnum: the physical eraseblock to remove
535 * This function returns PEB @pnum from the protection trees and returns zero
536 * in case of success and %-ENODEV if the PEB was not found in the protection
539 static int prot_tree_del(struct ubi_device *ubi, int pnum)
542 struct ubi_wl_prot_entry *pe = NULL;
544 p = ubi->prot.pnum.rb_node;
547 pe = rb_entry(p, struct ubi_wl_prot_entry, rb_pnum);
549 if (pnum == pe->e->pnum)
552 if (pnum < pe->e->pnum)
561 ubi_assert(pe->e->pnum == pnum);
562 rb_erase(&pe->rb_aec, &ubi->prot.aec);
563 rb_erase(&pe->rb_pnum, &ubi->prot.pnum);
569 * sync_erase - synchronously erase a physical eraseblock.
570 * @ubi: UBI device description object
571 * @e: the the physical eraseblock to erase
572 * @torture: if the physical eraseblock has to be tortured
574 * This function returns zero in case of success and a negative error code in
577 static int sync_erase(struct ubi_device *ubi, struct ubi_wl_entry *e, int torture)
580 struct ubi_ec_hdr *ec_hdr;
581 unsigned long long ec = e->ec;
583 dbg_wl("erase PEB %d, old EC %llu", e->pnum, ec);
585 err = paranoid_check_ec(ubi, e->pnum, e->ec);
589 ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
593 err = ubi_io_sync_erase(ubi, e->pnum, torture);
598 if (ec > UBI_MAX_ERASECOUNTER) {
600 * Erase counter overflow. Upgrade UBI and use 64-bit
601 * erase counters internally.
603 ubi_err("erase counter overflow at PEB %d, EC %llu",
609 dbg_wl("erased PEB %d, new EC %llu", e->pnum, ec);
611 ec_hdr->ec = cpu_to_be64(ec);
613 err = ubi_io_write_ec_hdr(ubi, e->pnum, ec_hdr);
618 spin_lock(&ubi->wl_lock);
619 if (e->ec > ubi->max_ec)
621 spin_unlock(&ubi->wl_lock);
629 * check_protection_over - check if it is time to stop protecting some
630 * physical eraseblocks.
631 * @ubi: UBI device description object
633 * This function is called after each erase operation, when the absolute erase
634 * counter is incremented, to check if some physical eraseblock have not to be
635 * protected any longer. These physical eraseblocks are moved from the
636 * protection trees to the used tree.
638 static void check_protection_over(struct ubi_device *ubi)
640 struct ubi_wl_prot_entry *pe;
643 * There may be several protected physical eraseblock to remove,
647 spin_lock(&ubi->wl_lock);
648 if (!ubi->prot.aec.rb_node) {
649 spin_unlock(&ubi->wl_lock);
653 pe = rb_entry(rb_first(&ubi->prot.aec),
654 struct ubi_wl_prot_entry, rb_aec);
656 if (pe->abs_ec > ubi->abs_ec) {
657 spin_unlock(&ubi->wl_lock);
661 dbg_wl("PEB %d protection over, abs_ec %llu, PEB abs_ec %llu",
662 pe->e->pnum, ubi->abs_ec, pe->abs_ec);
663 rb_erase(&pe->rb_aec, &ubi->prot.aec);
664 rb_erase(&pe->rb_pnum, &ubi->prot.pnum);
665 wl_tree_add(pe->e, &ubi->used);
666 spin_unlock(&ubi->wl_lock);
674 * schedule_ubi_work - schedule a work.
675 * @ubi: UBI device description object
676 * @wrk: the work to schedule
678 * This function enqueues a work defined by @wrk to the tail of the pending
681 static void schedule_ubi_work(struct ubi_device *ubi, struct ubi_work *wrk)
683 spin_lock(&ubi->wl_lock);
684 list_add_tail(&wrk->list, &ubi->works);
685 ubi_assert(ubi->works_count >= 0);
686 ubi->works_count += 1;
689 * U-Boot special: We have no bgt_thread in U-Boot!
690 * So just call do_work() here directly.
694 spin_unlock(&ubi->wl_lock);
697 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
701 * schedule_erase - schedule an erase work.
702 * @ubi: UBI device description object
703 * @e: the WL entry of the physical eraseblock to erase
704 * @torture: if the physical eraseblock has to be tortured
706 * This function returns zero in case of success and a %-ENOMEM in case of
709 static int schedule_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
712 struct ubi_work *wl_wrk;
714 dbg_wl("schedule erasure of PEB %d, EC %d, torture %d",
715 e->pnum, e->ec, torture);
717 wl_wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
721 wl_wrk->func = &erase_worker;
723 wl_wrk->torture = torture;
725 schedule_ubi_work(ubi, wl_wrk);
730 * wear_leveling_worker - wear-leveling worker function.
731 * @ubi: UBI device description object
732 * @wrk: the work object
733 * @cancel: non-zero if the worker has to free memory and exit
735 * This function copies a more worn out physical eraseblock to a less worn out
736 * one. Returns zero in case of success and a negative error code in case of
739 static int wear_leveling_worker(struct ubi_device *ubi, struct ubi_work *wrk,
742 int err, put = 0, scrubbing = 0, protect = 0;
743 struct ubi_wl_prot_entry *uninitialized_var(pe);
744 struct ubi_wl_entry *e1, *e2;
745 struct ubi_vid_hdr *vid_hdr;
752 vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
756 mutex_lock(&ubi->move_mutex);
757 spin_lock(&ubi->wl_lock);
758 ubi_assert(!ubi->move_from && !ubi->move_to);
759 ubi_assert(!ubi->move_to_put);
761 if (!ubi->free.rb_node ||
762 (!ubi->used.rb_node && !ubi->scrub.rb_node)) {
764 * No free physical eraseblocks? Well, they must be waiting in
765 * the queue to be erased. Cancel movement - it will be
766 * triggered again when a free physical eraseblock appears.
768 * No used physical eraseblocks? They must be temporarily
769 * protected from being moved. They will be moved to the
770 * @ubi->used tree later and the wear-leveling will be
773 dbg_wl("cancel WL, a list is empty: free %d, used %d",
774 !ubi->free.rb_node, !ubi->used.rb_node);
778 if (!ubi->scrub.rb_node) {
780 * Now pick the least worn-out used physical eraseblock and a
781 * highly worn-out free physical eraseblock. If the erase
782 * counters differ much enough, start wear-leveling.
784 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, rb);
785 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
787 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD)) {
788 dbg_wl("no WL needed: min used EC %d, max free EC %d",
792 paranoid_check_in_wl_tree(e1, &ubi->used);
793 rb_erase(&e1->rb, &ubi->used);
794 dbg_wl("move PEB %d EC %d to PEB %d EC %d",
795 e1->pnum, e1->ec, e2->pnum, e2->ec);
797 /* Perform scrubbing */
799 e1 = rb_entry(rb_first(&ubi->scrub), struct ubi_wl_entry, rb);
800 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
801 paranoid_check_in_wl_tree(e1, &ubi->scrub);
802 rb_erase(&e1->rb, &ubi->scrub);
803 dbg_wl("scrub PEB %d to PEB %d", e1->pnum, e2->pnum);
806 paranoid_check_in_wl_tree(e2, &ubi->free);
807 rb_erase(&e2->rb, &ubi->free);
810 spin_unlock(&ubi->wl_lock);
813 * Now we are going to copy physical eraseblock @e1->pnum to @e2->pnum.
814 * We so far do not know which logical eraseblock our physical
815 * eraseblock (@e1) belongs to. We have to read the volume identifier
818 * Note, we are protected from this PEB being unmapped and erased. The
819 * 'ubi_wl_put_peb()' would wait for moving to be finished if the PEB
820 * which is being moved was unmapped.
823 err = ubi_io_read_vid_hdr(ubi, e1->pnum, vid_hdr, 0);
824 if (err && err != UBI_IO_BITFLIPS) {
825 if (err == UBI_IO_PEB_FREE) {
827 * We are trying to move PEB without a VID header. UBI
828 * always write VID headers shortly after the PEB was
829 * given, so we have a situation when it did not have
830 * chance to write it down because it was preempted.
831 * Just re-schedule the work, so that next time it will
832 * likely have the VID header in place.
834 dbg_wl("PEB %d has no VID header", e1->pnum);
838 ubi_err("error %d while reading VID header from PEB %d",
845 err = ubi_eba_copy_leb(ubi, e1->pnum, e2->pnum, vid_hdr);
854 * For some reason the LEB was not moved - it might be because
855 * the volume is being deleted. We should prevent this PEB from
856 * being selected for wear-levelling movement for some "time",
857 * so put it to the protection tree.
860 dbg_wl("cancelled moving PEB %d", e1->pnum);
861 pe = kmalloc(sizeof(struct ubi_wl_prot_entry), GFP_NOFS);
870 ubi_free_vid_hdr(ubi, vid_hdr);
871 spin_lock(&ubi->wl_lock);
873 prot_tree_add(ubi, e1, pe, protect);
874 if (!ubi->move_to_put)
875 wl_tree_add(e2, &ubi->used);
878 ubi->move_from = ubi->move_to = NULL;
879 ubi->move_to_put = ubi->wl_scheduled = 0;
880 spin_unlock(&ubi->wl_lock);
884 * Well, the target PEB was put meanwhile, schedule it for
887 dbg_wl("PEB %d was put meanwhile, erase", e2->pnum);
888 err = schedule_erase(ubi, e2, 0);
894 err = schedule_erase(ubi, e1, 0);
901 mutex_unlock(&ubi->move_mutex);
905 * For some reasons the LEB was not moved, might be an error, might be
906 * something else. @e1 was not changed, so return it back. @e2 might
907 * be changed, schedule it for erasure.
910 ubi_free_vid_hdr(ubi, vid_hdr);
911 spin_lock(&ubi->wl_lock);
913 wl_tree_add(e1, &ubi->scrub);
915 wl_tree_add(e1, &ubi->used);
916 ubi->move_from = ubi->move_to = NULL;
917 ubi->move_to_put = ubi->wl_scheduled = 0;
918 spin_unlock(&ubi->wl_lock);
920 err = schedule_erase(ubi, e2, 0);
924 mutex_unlock(&ubi->move_mutex);
928 ubi_err("error %d while moving PEB %d to PEB %d",
929 err, e1->pnum, e2->pnum);
931 ubi_free_vid_hdr(ubi, vid_hdr);
932 spin_lock(&ubi->wl_lock);
933 ubi->move_from = ubi->move_to = NULL;
934 ubi->move_to_put = ubi->wl_scheduled = 0;
935 spin_unlock(&ubi->wl_lock);
937 kmem_cache_free(ubi_wl_entry_slab, e1);
938 kmem_cache_free(ubi_wl_entry_slab, e2);
941 mutex_unlock(&ubi->move_mutex);
945 ubi->wl_scheduled = 0;
946 spin_unlock(&ubi->wl_lock);
947 mutex_unlock(&ubi->move_mutex);
948 ubi_free_vid_hdr(ubi, vid_hdr);
953 * ensure_wear_leveling - schedule wear-leveling if it is needed.
954 * @ubi: UBI device description object
956 * This function checks if it is time to start wear-leveling and schedules it
957 * if yes. This function returns zero in case of success and a negative error
958 * code in case of failure.
960 static int ensure_wear_leveling(struct ubi_device *ubi)
963 struct ubi_wl_entry *e1;
964 struct ubi_wl_entry *e2;
965 struct ubi_work *wrk;
967 spin_lock(&ubi->wl_lock);
968 if (ubi->wl_scheduled)
969 /* Wear-leveling is already in the work queue */
973 * If the ubi->scrub tree is not empty, scrubbing is needed, and the
974 * the WL worker has to be scheduled anyway.
976 if (!ubi->scrub.rb_node) {
977 if (!ubi->used.rb_node || !ubi->free.rb_node)
978 /* No physical eraseblocks - no deal */
982 * We schedule wear-leveling only if the difference between the
983 * lowest erase counter of used physical eraseblocks and a high
984 * erase counter of free physical eraseblocks is greater then
987 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, rb);
988 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
990 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD))
992 dbg_wl("schedule wear-leveling");
994 dbg_wl("schedule scrubbing");
996 ubi->wl_scheduled = 1;
997 spin_unlock(&ubi->wl_lock);
999 wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
1005 wrk->func = &wear_leveling_worker;
1006 schedule_ubi_work(ubi, wrk);
1010 spin_lock(&ubi->wl_lock);
1011 ubi->wl_scheduled = 0;
1013 spin_unlock(&ubi->wl_lock);
1018 * erase_worker - physical eraseblock erase worker function.
1019 * @ubi: UBI device description object
1020 * @wl_wrk: the work object
1021 * @cancel: non-zero if the worker has to free memory and exit
1023 * This function erases a physical eraseblock and perform torture testing if
1024 * needed. It also takes care about marking the physical eraseblock bad if
1025 * needed. Returns zero in case of success and a negative error code in case of
1028 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
1031 struct ubi_wl_entry *e = wl_wrk->e;
1032 int pnum = e->pnum, err, need;
1035 dbg_wl("cancel erasure of PEB %d EC %d", pnum, e->ec);
1037 kmem_cache_free(ubi_wl_entry_slab, e);
1041 dbg_wl("erase PEB %d EC %d", pnum, e->ec);
1043 err = sync_erase(ubi, e, wl_wrk->torture);
1045 /* Fine, we've erased it successfully */
1048 spin_lock(&ubi->wl_lock);
1050 wl_tree_add(e, &ubi->free);
1051 spin_unlock(&ubi->wl_lock);
1054 * One more erase operation has happened, take care about protected
1055 * physical eraseblocks.
1057 check_protection_over(ubi);
1059 /* And take care about wear-leveling */
1060 err = ensure_wear_leveling(ubi);
1064 ubi_err("failed to erase PEB %d, error %d", pnum, err);
1066 kmem_cache_free(ubi_wl_entry_slab, e);
1068 if (err == -EINTR || err == -ENOMEM || err == -EAGAIN ||
1072 /* Re-schedule the LEB for erasure */
1073 err1 = schedule_erase(ubi, e, 0);
1079 } else if (err != -EIO) {
1081 * If this is not %-EIO, we have no idea what to do. Scheduling
1082 * this physical eraseblock for erasure again would cause
1083 * errors again and again. Well, lets switch to RO mode.
1088 /* It is %-EIO, the PEB went bad */
1090 if (!ubi->bad_allowed) {
1091 ubi_err("bad physical eraseblock %d detected", pnum);
1095 spin_lock(&ubi->volumes_lock);
1096 need = ubi->beb_rsvd_level - ubi->beb_rsvd_pebs + 1;
1098 need = ubi->avail_pebs >= need ? need : ubi->avail_pebs;
1099 ubi->avail_pebs -= need;
1100 ubi->rsvd_pebs += need;
1101 ubi->beb_rsvd_pebs += need;
1103 ubi_msg("reserve more %d PEBs", need);
1106 if (ubi->beb_rsvd_pebs == 0) {
1107 spin_unlock(&ubi->volumes_lock);
1108 ubi_err("no reserved physical eraseblocks");
1112 spin_unlock(&ubi->volumes_lock);
1113 ubi_msg("mark PEB %d as bad", pnum);
1115 err = ubi_io_mark_bad(ubi, pnum);
1119 spin_lock(&ubi->volumes_lock);
1120 ubi->beb_rsvd_pebs -= 1;
1121 ubi->bad_peb_count += 1;
1122 ubi->good_peb_count -= 1;
1123 ubi_calculate_reserved(ubi);
1124 if (ubi->beb_rsvd_pebs == 0)
1125 ubi_warn("last PEB from the reserved pool was used");
1126 spin_unlock(&ubi->volumes_lock);
1136 * ubi_wl_put_peb - return a physical eraseblock to the wear-leveling unit.
1137 * @ubi: UBI device description object
1138 * @pnum: physical eraseblock to return
1139 * @torture: if this physical eraseblock has to be tortured
1141 * This function is called to return physical eraseblock @pnum to the pool of
1142 * free physical eraseblocks. The @torture flag has to be set if an I/O error
1143 * occurred to this @pnum and it has to be tested. This function returns zero
1144 * in case of success, and a negative error code in case of failure.
1146 int ubi_wl_put_peb(struct ubi_device *ubi, int pnum, int torture)
1149 struct ubi_wl_entry *e;
1151 dbg_wl("PEB %d", pnum);
1152 ubi_assert(pnum >= 0);
1153 ubi_assert(pnum < ubi->peb_count);
1156 spin_lock(&ubi->wl_lock);
1157 e = ubi->lookuptbl[pnum];
1158 if (e == ubi->move_from) {
1160 * User is putting the physical eraseblock which was selected to
1161 * be moved. It will be scheduled for erasure in the
1162 * wear-leveling worker.
1164 dbg_wl("PEB %d is being moved, wait", pnum);
1165 spin_unlock(&ubi->wl_lock);
1167 /* Wait for the WL worker by taking the @ubi->move_mutex */
1168 mutex_lock(&ubi->move_mutex);
1169 mutex_unlock(&ubi->move_mutex);
1171 } else if (e == ubi->move_to) {
1173 * User is putting the physical eraseblock which was selected
1174 * as the target the data is moved to. It may happen if the EBA
1175 * unit already re-mapped the LEB in 'ubi_eba_copy_leb()' but
1176 * the WL unit has not put the PEB to the "used" tree yet, but
1177 * it is about to do this. So we just set a flag which will
1178 * tell the WL worker that the PEB is not needed anymore and
1179 * should be scheduled for erasure.
1181 dbg_wl("PEB %d is the target of data moving", pnum);
1182 ubi_assert(!ubi->move_to_put);
1183 ubi->move_to_put = 1;
1184 spin_unlock(&ubi->wl_lock);
1187 if (in_wl_tree(e, &ubi->used)) {
1188 paranoid_check_in_wl_tree(e, &ubi->used);
1189 rb_erase(&e->rb, &ubi->used);
1190 } else if (in_wl_tree(e, &ubi->scrub)) {
1191 paranoid_check_in_wl_tree(e, &ubi->scrub);
1192 rb_erase(&e->rb, &ubi->scrub);
1194 err = prot_tree_del(ubi, e->pnum);
1196 ubi_err("PEB %d not found", pnum);
1198 spin_unlock(&ubi->wl_lock);
1203 spin_unlock(&ubi->wl_lock);
1205 err = schedule_erase(ubi, e, torture);
1207 spin_lock(&ubi->wl_lock);
1208 wl_tree_add(e, &ubi->used);
1209 spin_unlock(&ubi->wl_lock);
1216 * ubi_wl_scrub_peb - schedule a physical eraseblock for scrubbing.
1217 * @ubi: UBI device description object
1218 * @pnum: the physical eraseblock to schedule
1220 * If a bit-flip in a physical eraseblock is detected, this physical eraseblock
1221 * needs scrubbing. This function schedules a physical eraseblock for
1222 * scrubbing which is done in background. This function returns zero in case of
1223 * success and a negative error code in case of failure.
1225 int ubi_wl_scrub_peb(struct ubi_device *ubi, int pnum)
1227 struct ubi_wl_entry *e;
1229 ubi_msg("schedule PEB %d for scrubbing", pnum);
1232 spin_lock(&ubi->wl_lock);
1233 e = ubi->lookuptbl[pnum];
1234 if (e == ubi->move_from || in_wl_tree(e, &ubi->scrub)) {
1235 spin_unlock(&ubi->wl_lock);
1239 if (e == ubi->move_to) {
1241 * This physical eraseblock was used to move data to. The data
1242 * was moved but the PEB was not yet inserted to the proper
1243 * tree. We should just wait a little and let the WL worker
1246 spin_unlock(&ubi->wl_lock);
1247 dbg_wl("the PEB %d is not in proper tree, retry", pnum);
1252 if (in_wl_tree(e, &ubi->used)) {
1253 paranoid_check_in_wl_tree(e, &ubi->used);
1254 rb_erase(&e->rb, &ubi->used);
1258 err = prot_tree_del(ubi, e->pnum);
1260 ubi_err("PEB %d not found", pnum);
1262 spin_unlock(&ubi->wl_lock);
1267 wl_tree_add(e, &ubi->scrub);
1268 spin_unlock(&ubi->wl_lock);
1271 * Technically scrubbing is the same as wear-leveling, so it is done
1274 return ensure_wear_leveling(ubi);
1278 * ubi_wl_flush - flush all pending works.
1279 * @ubi: UBI device description object
1281 * This function returns zero in case of success and a negative error code in
1284 int ubi_wl_flush(struct ubi_device *ubi)
1289 * Erase while the pending works queue is not empty, but not more then
1290 * the number of currently pending works.
1292 dbg_wl("flush (%d pending works)", ubi->works_count);
1293 while (ubi->works_count) {
1300 * Make sure all the works which have been done in parallel are
1303 down_write(&ubi->work_sem);
1304 up_write(&ubi->work_sem);
1307 * And in case last was the WL worker and it cancelled the LEB
1308 * movement, flush again.
1310 while (ubi->works_count) {
1311 dbg_wl("flush more (%d pending works)", ubi->works_count);
1321 * tree_destroy - destroy an RB-tree.
1322 * @root: the root of the tree to destroy
1324 static void tree_destroy(struct rb_root *root)
1327 struct ubi_wl_entry *e;
1333 else if (rb->rb_right)
1336 e = rb_entry(rb, struct ubi_wl_entry, rb);
1340 if (rb->rb_left == &e->rb)
1343 rb->rb_right = NULL;
1346 kmem_cache_free(ubi_wl_entry_slab, e);
1352 * ubi_thread - UBI background thread.
1353 * @u: the UBI device description object pointer
1355 int ubi_thread(void *u)
1358 struct ubi_device *ubi = u;
1360 ubi_msg("background thread \"%s\" started, PID %d",
1361 ubi->bgt_name, task_pid_nr(current));
1367 if (kthread_should_stop())
1370 if (try_to_freeze())
1373 spin_lock(&ubi->wl_lock);
1374 if (list_empty(&ubi->works) || ubi->ro_mode ||
1375 !ubi->thread_enabled) {
1376 set_current_state(TASK_INTERRUPTIBLE);
1377 spin_unlock(&ubi->wl_lock);
1381 spin_unlock(&ubi->wl_lock);
1385 ubi_err("%s: work failed with error code %d",
1386 ubi->bgt_name, err);
1387 if (failures++ > WL_MAX_FAILURES) {
1389 * Too many failures, disable the thread and
1390 * switch to read-only mode.
1392 ubi_msg("%s: %d consecutive failures",
1393 ubi->bgt_name, WL_MAX_FAILURES);
1403 dbg_wl("background thread \"%s\" is killed", ubi->bgt_name);
1408 * cancel_pending - cancel all pending works.
1409 * @ubi: UBI device description object
1411 static void cancel_pending(struct ubi_device *ubi)
1413 while (!list_empty(&ubi->works)) {
1414 struct ubi_work *wrk;
1416 wrk = list_entry(ubi->works.next, struct ubi_work, list);
1417 list_del(&wrk->list);
1418 wrk->func(ubi, wrk, 1);
1419 ubi->works_count -= 1;
1420 ubi_assert(ubi->works_count >= 0);
1425 * ubi_wl_init_scan - initialize the wear-leveling unit using scanning
1427 * @ubi: UBI device description object
1428 * @si: scanning information
1430 * This function returns zero in case of success, and a negative error code in
1433 int ubi_wl_init_scan(struct ubi_device *ubi, struct ubi_scan_info *si)
1436 struct rb_node *rb1, *rb2;
1437 struct ubi_scan_volume *sv;
1438 struct ubi_scan_leb *seb, *tmp;
1439 struct ubi_wl_entry *e;
1442 ubi->used = ubi->free = ubi->scrub = RB_ROOT;
1443 ubi->prot.pnum = ubi->prot.aec = RB_ROOT;
1444 spin_lock_init(&ubi->wl_lock);
1445 mutex_init(&ubi->move_mutex);
1446 init_rwsem(&ubi->work_sem);
1447 ubi->max_ec = si->max_ec;
1448 INIT_LIST_HEAD(&ubi->works);
1450 sprintf(ubi->bgt_name, UBI_BGT_NAME_PATTERN, ubi->ubi_num);
1453 ubi->lookuptbl = kzalloc(ubi->peb_count * sizeof(void *), GFP_KERNEL);
1454 if (!ubi->lookuptbl)
1457 list_for_each_entry_safe(seb, tmp, &si->erase, u.list) {
1460 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1464 e->pnum = seb->pnum;
1466 ubi->lookuptbl[e->pnum] = e;
1467 if (schedule_erase(ubi, e, 0)) {
1468 kmem_cache_free(ubi_wl_entry_slab, e);
1473 list_for_each_entry(seb, &si->free, u.list) {
1476 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1480 e->pnum = seb->pnum;
1482 ubi_assert(e->ec >= 0);
1483 wl_tree_add(e, &ubi->free);
1484 ubi->lookuptbl[e->pnum] = e;
1487 list_for_each_entry(seb, &si->corr, u.list) {
1490 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1494 e->pnum = seb->pnum;
1496 ubi->lookuptbl[e->pnum] = e;
1497 if (schedule_erase(ubi, e, 0)) {
1498 kmem_cache_free(ubi_wl_entry_slab, e);
1503 ubi_rb_for_each_entry(rb1, sv, &si->volumes, rb) {
1504 ubi_rb_for_each_entry(rb2, seb, &sv->root, u.rb) {
1507 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1511 e->pnum = seb->pnum;
1513 ubi->lookuptbl[e->pnum] = e;
1515 dbg_wl("add PEB %d EC %d to the used tree",
1517 wl_tree_add(e, &ubi->used);
1519 dbg_wl("add PEB %d EC %d to the scrub tree",
1521 wl_tree_add(e, &ubi->scrub);
1526 if (ubi->avail_pebs < WL_RESERVED_PEBS) {
1527 ubi_err("no enough physical eraseblocks (%d, need %d)",
1528 ubi->avail_pebs, WL_RESERVED_PEBS);
1532 ubi->avail_pebs -= WL_RESERVED_PEBS;
1533 ubi->rsvd_pebs += WL_RESERVED_PEBS;
1535 /* Schedule wear-leveling if needed */
1536 err = ensure_wear_leveling(ubi);
1543 cancel_pending(ubi);
1544 tree_destroy(&ubi->used);
1545 tree_destroy(&ubi->free);
1546 tree_destroy(&ubi->scrub);
1547 kfree(ubi->lookuptbl);
1552 * protection_trees_destroy - destroy the protection RB-trees.
1553 * @ubi: UBI device description object
1555 static void protection_trees_destroy(struct ubi_device *ubi)
1558 struct ubi_wl_prot_entry *pe;
1560 rb = ubi->prot.aec.rb_node;
1564 else if (rb->rb_right)
1567 pe = rb_entry(rb, struct ubi_wl_prot_entry, rb_aec);
1571 if (rb->rb_left == &pe->rb_aec)
1574 rb->rb_right = NULL;
1577 kmem_cache_free(ubi_wl_entry_slab, pe->e);
1584 * ubi_wl_close - close the wear-leveling unit.
1585 * @ubi: UBI device description object
1587 void ubi_wl_close(struct ubi_device *ubi)
1589 dbg_wl("close the UBI wear-leveling unit");
1591 cancel_pending(ubi);
1592 protection_trees_destroy(ubi);
1593 tree_destroy(&ubi->used);
1594 tree_destroy(&ubi->free);
1595 tree_destroy(&ubi->scrub);
1596 kfree(ubi->lookuptbl);
1599 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
1602 * paranoid_check_ec - make sure that the erase counter of a physical eraseblock
1604 * @ubi: UBI device description object
1605 * @pnum: the physical eraseblock number to check
1606 * @ec: the erase counter to check
1608 * This function returns zero if the erase counter of physical eraseblock @pnum
1609 * is equivalent to @ec, %1 if not, and a negative error code if an error
1612 static int paranoid_check_ec(struct ubi_device *ubi, int pnum, int ec)
1616 struct ubi_ec_hdr *ec_hdr;
1618 ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
1622 err = ubi_io_read_ec_hdr(ubi, pnum, ec_hdr, 0);
1623 if (err && err != UBI_IO_BITFLIPS) {
1624 /* The header does not have to exist */
1629 read_ec = be64_to_cpu(ec_hdr->ec);
1630 if (ec != read_ec) {
1631 ubi_err("paranoid check failed for PEB %d", pnum);
1632 ubi_err("read EC is %lld, should be %d", read_ec, ec);
1633 ubi_dbg_dump_stack();
1644 * paranoid_check_in_wl_tree - make sure that a wear-leveling entry is present
1646 * @e: the wear-leveling entry to check
1647 * @root: the root of the tree
1649 * This function returns zero if @e is in the @root RB-tree and %1 if it
1652 static int paranoid_check_in_wl_tree(struct ubi_wl_entry *e,
1653 struct rb_root *root)
1655 if (in_wl_tree(e, root))
1658 ubi_err("paranoid check failed for PEB %d, EC %d, RB-tree %p ",
1659 e->pnum, e->ec, root);
1660 ubi_dbg_dump_stack();
1664 #endif /* CONFIG_MTD_UBI_DEBUG_PARANOID */