2 * Copyright (c) International Business Machines Corp., 2006
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.
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.
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
18 * Authors: Artem Bityutskiy (Битюцкий Артём), Thomas Gleixner
22 * UBI wear-leveling unit.
24 * This unit is responsible for wear-leveling. It works in terms of physical
25 * eraseblocks and erase counters and knows nothing about logical eraseblocks,
26 * volumes, etc. From this unit's perspective all physical eraseblocks are of
27 * two types - used and free. Used physical eraseblocks are those that were
28 * "get" by the 'ubi_wl_get_peb()' function, and free physical eraseblocks are
29 * those that were put by the 'ubi_wl_put_peb()' function.
31 * Physical eraseblocks returned by 'ubi_wl_get_peb()' have only erase counter
32 * header. The rest of the physical eraseblock contains only 0xFF bytes.
34 * When physical eraseblocks are returned to the WL unit by means of the
35 * 'ubi_wl_put_peb()' function, they are scheduled for erasure. The erasure is
36 * done asynchronously in context of the per-UBI device background thread,
37 * which is also managed by the WL unit.
39 * The wear-leveling is ensured by means of moving the contents of used
40 * physical eraseblocks with low erase counter to free physical eraseblocks
41 * with high erase counter.
43 * The 'ubi_wl_get_peb()' function accepts data type hints which help to pick
44 * an "optimal" physical eraseblock. For example, when it is known that the
45 * physical eraseblock will be "put" soon because it contains short-term data,
46 * the WL unit may pick a free physical eraseblock with low erase counter, and
49 * If the WL unit fails to erase a physical eraseblock, it marks it as bad.
51 * This unit is also responsible for scrubbing. If a bit-flip is detected in a
52 * physical eraseblock, it has to be moved. Technically this is the same as
53 * moving it for wear-leveling reasons.
55 * As it was said, for the UBI unit all physical eraseblocks are either "free"
56 * or "used". Free eraseblock are kept in the @wl->free RB-tree, while used
57 * eraseblocks are kept in a set of different RB-trees: @wl->used,
58 * @wl->prot.pnum, @wl->prot.aec, and @wl->scrub.
60 * Note, in this implementation, we keep a small in-RAM object for each physical
61 * eraseblock. This is surely not a scalable solution. But it appears to be good
62 * enough for moderately large flashes and it is simple. In future, one may
63 * re-work this unit and make it more scalable.
65 * At the moment this unit does not utilize the sequence number, which was
66 * introduced relatively recently. But it would be wise to do this because the
67 * sequence number of a logical eraseblock characterizes how old is it. For
68 * example, when we move a PEB with low erase counter, and we need to pick the
69 * target PEB, we pick a PEB with the highest EC if our PEB is "old" and we
70 * pick target PEB with an average EC if our PEB is not very "old". This is a
71 * room for future re-works of the WL unit.
73 * FIXME: looks too complex, should be simplified (later).
76 #include <linux/slab.h>
77 #include <linux/crc32.h>
78 #include <linux/freezer.h>
79 #include <linux/kthread.h>
82 /* Number of physical eraseblocks reserved for wear-leveling purposes */
83 #define WL_RESERVED_PEBS 1
86 * How many erase cycles are short term, unknown, and long term physical
87 * eraseblocks protected.
89 #define ST_PROTECTION 16
90 #define U_PROTECTION 10
91 #define LT_PROTECTION 4
94 * Maximum difference between two erase counters. If this threshold is
95 * exceeded, the WL unit starts moving data from used physical eraseblocks with
96 * low erase counter to free physical eraseblocks with high erase counter.
98 #define UBI_WL_THRESHOLD CONFIG_MTD_UBI_WL_THRESHOLD
101 * When a physical eraseblock is moved, the WL unit has to pick the target
102 * physical eraseblock to move to. The simplest way would be just to pick the
103 * one with the highest erase counter. But in certain workloads this could lead
104 * to an unlimited wear of one or few physical eraseblock. Indeed, imagine a
105 * situation when the picked physical eraseblock is constantly erased after the
106 * data is written to it. So, we have a constant which limits the highest erase
107 * counter of the free physical eraseblock to pick. Namely, the WL unit does
108 * not pick eraseblocks with erase counter greater then the lowest erase
109 * counter plus %WL_FREE_MAX_DIFF.
111 #define WL_FREE_MAX_DIFF (2*UBI_WL_THRESHOLD)
114 * Maximum number of consecutive background thread failures which is enough to
115 * switch to read-only mode.
117 #define WL_MAX_FAILURES 32
120 * struct ubi_wl_entry - wear-leveling entry.
121 * @rb: link in the corresponding RB-tree
123 * @pnum: physical eraseblock number
125 * Each physical eraseblock has a corresponding &struct wl_entry object which
126 * may be kept in different RB-trees.
128 struct ubi_wl_entry {
135 * struct ubi_wl_prot_entry - PEB protection entry.
136 * @rb_pnum: link in the @wl->prot.pnum RB-tree
137 * @rb_aec: link in the @wl->prot.aec RB-tree
138 * @abs_ec: the absolute erase counter value when the protection ends
139 * @e: the wear-leveling entry of the physical eraseblock under protection
141 * When the WL unit returns a physical eraseblock, the physical eraseblock is
142 * protected from being moved for some "time". For this reason, the physical
143 * eraseblock is not directly moved from the @wl->free tree to the @wl->used
144 * tree. There is one more tree in between where this physical eraseblock is
145 * temporarily stored (@wl->prot).
147 * All this protection stuff is needed because:
148 * o we don't want to move physical eraseblocks just after we have given them
149 * to the user; instead, we first want to let users fill them up with data;
151 * o there is a chance that the user will put the physical eraseblock very
152 * soon, so it makes sense not to move it for some time, but wait; this is
153 * especially important in case of "short term" physical eraseblocks.
155 * Physical eraseblocks stay protected only for limited time. But the "time" is
156 * measured in erase cycles in this case. This is implemented with help of the
157 * absolute erase counter (@wl->abs_ec). When it reaches certain value, the
158 * physical eraseblocks are moved from the protection trees (@wl->prot.*) to
159 * the @wl->used tree.
161 * Protected physical eraseblocks are searched by physical eraseblock number
162 * (when they are put) and by the absolute erase counter (to check if it is
163 * time to move them to the @wl->used tree). So there are actually 2 RB-trees
164 * storing the protected physical eraseblocks: @wl->prot.pnum and
165 * @wl->prot.aec. They are referred to as the "protection" trees. The
166 * first one is indexed by the physical eraseblock number. The second one is
167 * indexed by the absolute erase counter. Both trees store
168 * &struct ubi_wl_prot_entry objects.
170 * Each physical eraseblock has 2 main states: free and used. The former state
171 * corresponds to the @wl->free tree. The latter state is split up on several
173 * o the WL movement is allowed (@wl->used tree);
174 * o the WL movement is temporarily prohibited (@wl->prot.pnum and
175 * @wl->prot.aec trees);
176 * o scrubbing is needed (@wl->scrub tree).
178 * Depending on the sub-state, wear-leveling entries of the used physical
179 * eraseblocks may be kept in one of those trees.
181 struct ubi_wl_prot_entry {
182 struct rb_node rb_pnum;
183 struct rb_node rb_aec;
184 unsigned long long abs_ec;
185 struct ubi_wl_entry *e;
189 * struct ubi_work - UBI work description data structure.
190 * @list: a link in the list of pending works
191 * @func: worker function
192 * @priv: private data of the worker function
194 * @e: physical eraseblock to erase
195 * @torture: if the physical eraseblock has to be tortured
197 * The @func pointer points to the worker function. If the @cancel argument is
198 * not zero, the worker has to free the resources and exit immediately. The
199 * worker has to return zero in case of success and a negative error code in
203 struct list_head list;
204 int (*func)(struct ubi_device *ubi, struct ubi_work *wrk, int cancel);
205 /* The below fields are only relevant to erasure works */
206 struct ubi_wl_entry *e;
210 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
211 static int paranoid_check_ec(const struct ubi_device *ubi, int pnum, int ec);
212 static int paranoid_check_in_wl_tree(struct ubi_wl_entry *e,
213 struct rb_root *root);
215 #define paranoid_check_ec(ubi, pnum, ec) 0
216 #define paranoid_check_in_wl_tree(e, root)
219 /* Slab cache for wear-leveling entries */
220 static struct kmem_cache *wl_entries_slab;
223 * tree_empty - a helper function to check if an RB-tree is empty.
224 * @root: the root of the tree
226 * This function returns non-zero if the RB-tree is empty and zero if not.
228 static inline int tree_empty(struct rb_root *root)
230 return root->rb_node == NULL;
234 * wl_tree_add - add a wear-leveling entry to a WL RB-tree.
235 * @e: the wear-leveling entry to add
236 * @root: the root of the tree
238 * Note, we use (erase counter, physical eraseblock number) pairs as keys in
239 * the @ubi->used and @ubi->free RB-trees.
241 static void wl_tree_add(struct ubi_wl_entry *e, struct rb_root *root)
243 struct rb_node **p, *parent = NULL;
247 struct ubi_wl_entry *e1;
250 e1 = rb_entry(parent, struct ubi_wl_entry, rb);
254 else if (e->ec > e1->ec)
257 ubi_assert(e->pnum != e1->pnum);
258 if (e->pnum < e1->pnum)
265 rb_link_node(&e->rb, parent, p);
266 rb_insert_color(&e->rb, root);
271 * Helper functions to add and delete wear-leveling entries from different
275 static void free_tree_add(struct ubi_device *ubi, struct ubi_wl_entry *e)
277 wl_tree_add(e, &ubi->free);
279 static inline void used_tree_add(struct ubi_device *ubi,
280 struct ubi_wl_entry *e)
282 wl_tree_add(e, &ubi->used);
284 static inline void scrub_tree_add(struct ubi_device *ubi,
285 struct ubi_wl_entry *e)
287 wl_tree_add(e, &ubi->scrub);
289 static inline void free_tree_del(struct ubi_device *ubi,
290 struct ubi_wl_entry *e)
292 paranoid_check_in_wl_tree(e, &ubi->free);
293 rb_erase(&e->rb, &ubi->free);
295 static inline void used_tree_del(struct ubi_device *ubi,
296 struct ubi_wl_entry *e)
298 paranoid_check_in_wl_tree(e, &ubi->used);
299 rb_erase(&e->rb, &ubi->used);
301 static inline void scrub_tree_del(struct ubi_device *ubi,
302 struct ubi_wl_entry *e)
304 paranoid_check_in_wl_tree(e, &ubi->scrub);
305 rb_erase(&e->rb, &ubi->scrub);
309 * do_work - do one pending work.
310 * @ubi: UBI device description object
312 * This function returns zero in case of success and a negative error code in
315 static int do_work(struct ubi_device *ubi)
318 struct ubi_work *wrk;
320 spin_lock(&ubi->wl_lock);
322 if (list_empty(&ubi->works)) {
323 spin_unlock(&ubi->wl_lock);
327 wrk = list_entry(ubi->works.next, struct ubi_work, list);
328 list_del(&wrk->list);
329 spin_unlock(&ubi->wl_lock);
332 * Call the worker function. Do not touch the work structure
333 * after this call as it will have been freed or reused by that
334 * time by the worker function.
336 err = wrk->func(ubi, wrk, 0);
338 ubi_err("work failed with error code %d", err);
340 spin_lock(&ubi->wl_lock);
341 ubi->works_count -= 1;
342 ubi_assert(ubi->works_count >= 0);
343 spin_unlock(&ubi->wl_lock);
348 * produce_free_peb - produce a free physical eraseblock.
349 * @ubi: UBI device description object
351 * This function tries to make a free PEB by means of synchronous execution of
352 * pending works. This may be needed if, for example the background thread is
353 * disabled. Returns zero in case of success and a negative error code in case
356 static int produce_free_peb(struct ubi_device *ubi)
360 spin_lock(&ubi->wl_lock);
361 while (tree_empty(&ubi->free)) {
362 spin_unlock(&ubi->wl_lock);
364 dbg_wl("do one work synchronously");
369 spin_lock(&ubi->wl_lock);
371 spin_unlock(&ubi->wl_lock);
377 * in_wl_tree - check if wear-leveling entry is present in a WL RB-tree.
378 * @e: the wear-leveling entry to check
379 * @root: the root of the tree
381 * This function returns non-zero if @e is in the @root RB-tree and zero if it
384 static int in_wl_tree(struct ubi_wl_entry *e, struct rb_root *root)
390 struct ubi_wl_entry *e1;
392 e1 = rb_entry(p, struct ubi_wl_entry, rb);
394 if (e->pnum == e1->pnum) {
401 else if (e->ec > e1->ec)
404 ubi_assert(e->pnum != e1->pnum);
405 if (e->pnum < e1->pnum)
416 * prot_tree_add - add physical eraseblock to protection trees.
417 * @ubi: UBI device description object
418 * @e: the physical eraseblock to add
419 * @pe: protection entry object to use
420 * @abs_ec: absolute erase counter value when this physical eraseblock has
421 * to be removed from the protection trees.
423 * @wl->lock has to be locked.
425 static void prot_tree_add(struct ubi_device *ubi, struct ubi_wl_entry *e,
426 struct ubi_wl_prot_entry *pe, int abs_ec)
428 struct rb_node **p, *parent = NULL;
429 struct ubi_wl_prot_entry *pe1;
432 pe->abs_ec = ubi->abs_ec + abs_ec;
434 p = &ubi->prot.pnum.rb_node;
437 pe1 = rb_entry(parent, struct ubi_wl_prot_entry, rb_pnum);
439 if (e->pnum < pe1->e->pnum)
444 rb_link_node(&pe->rb_pnum, parent, p);
445 rb_insert_color(&pe->rb_pnum, &ubi->prot.pnum);
447 p = &ubi->prot.aec.rb_node;
451 pe1 = rb_entry(parent, struct ubi_wl_prot_entry, rb_aec);
453 if (pe->abs_ec < pe1->abs_ec)
458 rb_link_node(&pe->rb_aec, parent, p);
459 rb_insert_color(&pe->rb_aec, &ubi->prot.aec);
463 * find_wl_entry - find wear-leveling entry closest to certain erase counter.
464 * @root: the RB-tree where to look for
465 * @max: highest possible erase counter
467 * This function looks for a wear leveling entry with erase counter closest to
468 * @max and less then @max.
470 static struct ubi_wl_entry *find_wl_entry(struct rb_root *root, int max)
473 struct ubi_wl_entry *e;
475 e = rb_entry(rb_first(root), struct ubi_wl_entry, rb);
480 struct ubi_wl_entry *e1;
482 e1 = rb_entry(p, struct ubi_wl_entry, rb);
495 * ubi_wl_get_peb - get a physical eraseblock.
496 * @ubi: UBI device description object
497 * @dtype: type of data which will be stored in this physical eraseblock
499 * This function returns a physical eraseblock in case of success and a
500 * negative error code in case of failure. Might sleep.
502 int ubi_wl_get_peb(struct ubi_device *ubi, int dtype)
504 int err, protect, medium_ec;
505 struct ubi_wl_entry *e, *first, *last;
506 struct ubi_wl_prot_entry *pe;
508 ubi_assert(dtype == UBI_LONGTERM || dtype == UBI_SHORTTERM ||
509 dtype == UBI_UNKNOWN);
511 pe = kmalloc(sizeof(struct ubi_wl_prot_entry), GFP_KERNEL);
516 spin_lock(&ubi->wl_lock);
517 if (tree_empty(&ubi->free)) {
518 if (ubi->works_count == 0) {
519 ubi_assert(list_empty(&ubi->works));
520 ubi_err("no free eraseblocks");
521 spin_unlock(&ubi->wl_lock);
525 spin_unlock(&ubi->wl_lock);
527 err = produce_free_peb(ubi);
538 * For long term data we pick a physical eraseblock
539 * with high erase counter. But the highest erase
540 * counter we can pick is bounded by the the lowest
541 * erase counter plus %WL_FREE_MAX_DIFF.
543 e = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
544 protect = LT_PROTECTION;
548 * For unknown data we pick a physical eraseblock with
549 * medium erase counter. But we by no means can pick a
550 * physical eraseblock with erase counter greater or
551 * equivalent than the lowest erase counter plus
554 first = rb_entry(rb_first(&ubi->free),
555 struct ubi_wl_entry, rb);
556 last = rb_entry(rb_last(&ubi->free),
557 struct ubi_wl_entry, rb);
559 if (last->ec - first->ec < WL_FREE_MAX_DIFF)
560 e = rb_entry(ubi->free.rb_node,
561 struct ubi_wl_entry, rb);
563 medium_ec = (first->ec + WL_FREE_MAX_DIFF)/2;
564 e = find_wl_entry(&ubi->free, medium_ec);
566 protect = U_PROTECTION;
570 * For short term data we pick a physical eraseblock
571 * with the lowest erase counter as we expect it will
574 e = rb_entry(rb_first(&ubi->free),
575 struct ubi_wl_entry, rb);
576 protect = ST_PROTECTION;
585 * Move the physical eraseblock to the protection trees where it will
586 * be protected from being moved for some time.
588 free_tree_del(ubi, e);
589 prot_tree_add(ubi, e, pe, protect);
591 dbg_wl("PEB %d EC %d, protection %d", e->pnum, e->ec, protect);
592 spin_unlock(&ubi->wl_lock);
598 * prot_tree_del - remove a physical eraseblock from the protection trees
599 * @ubi: UBI device description object
600 * @pnum: the physical eraseblock to remove
602 static void prot_tree_del(struct ubi_device *ubi, int pnum)
605 struct ubi_wl_prot_entry *pe = NULL;
607 p = ubi->prot.pnum.rb_node;
610 pe = rb_entry(p, struct ubi_wl_prot_entry, rb_pnum);
612 if (pnum == pe->e->pnum)
615 if (pnum < pe->e->pnum)
621 ubi_assert(pe->e->pnum == pnum);
622 rb_erase(&pe->rb_aec, &ubi->prot.aec);
623 rb_erase(&pe->rb_pnum, &ubi->prot.pnum);
628 * sync_erase - synchronously erase a physical eraseblock.
629 * @ubi: UBI device description object
630 * @e: the the physical eraseblock to erase
631 * @torture: if the physical eraseblock has to be tortured
633 * This function returns zero in case of success and a negative error code in
636 static int sync_erase(struct ubi_device *ubi, struct ubi_wl_entry *e, int torture)
639 struct ubi_ec_hdr *ec_hdr;
640 unsigned long long ec = e->ec;
642 dbg_wl("erase PEB %d, old EC %llu", e->pnum, ec);
644 err = paranoid_check_ec(ubi, e->pnum, e->ec);
648 ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
652 err = ubi_io_sync_erase(ubi, e->pnum, torture);
657 if (ec > UBI_MAX_ERASECOUNTER) {
659 * Erase counter overflow. Upgrade UBI and use 64-bit
660 * erase counters internally.
662 ubi_err("erase counter overflow at PEB %d, EC %llu",
668 dbg_wl("erased PEB %d, new EC %llu", e->pnum, ec);
670 ec_hdr->ec = cpu_to_ubi64(ec);
672 err = ubi_io_write_ec_hdr(ubi, e->pnum, ec_hdr);
677 spin_lock(&ubi->wl_lock);
678 if (e->ec > ubi->max_ec)
680 spin_unlock(&ubi->wl_lock);
688 * check_protection_over - check if it is time to stop protecting some
689 * physical eraseblocks.
690 * @ubi: UBI device description object
692 * This function is called after each erase operation, when the absolute erase
693 * counter is incremented, to check if some physical eraseblock have not to be
694 * protected any longer. These physical eraseblocks are moved from the
695 * protection trees to the used tree.
697 static void check_protection_over(struct ubi_device *ubi)
699 struct ubi_wl_prot_entry *pe;
702 * There may be several protected physical eraseblock to remove,
706 spin_lock(&ubi->wl_lock);
707 if (tree_empty(&ubi->prot.aec)) {
708 spin_unlock(&ubi->wl_lock);
712 pe = rb_entry(rb_first(&ubi->prot.aec),
713 struct ubi_wl_prot_entry, rb_aec);
715 if (pe->abs_ec > ubi->abs_ec) {
716 spin_unlock(&ubi->wl_lock);
720 dbg_wl("PEB %d protection over, abs_ec %llu, PEB abs_ec %llu",
721 pe->e->pnum, ubi->abs_ec, pe->abs_ec);
722 rb_erase(&pe->rb_aec, &ubi->prot.aec);
723 rb_erase(&pe->rb_pnum, &ubi->prot.pnum);
724 used_tree_add(ubi, pe->e);
725 spin_unlock(&ubi->wl_lock);
733 * schedule_ubi_work - schedule a work.
734 * @ubi: UBI device description object
735 * @wrk: the work to schedule
737 * This function enqueues a work defined by @wrk to the tail of the pending
740 static void schedule_ubi_work(struct ubi_device *ubi, struct ubi_work *wrk)
742 spin_lock(&ubi->wl_lock);
743 list_add_tail(&wrk->list, &ubi->works);
744 ubi_assert(ubi->works_count >= 0);
745 ubi->works_count += 1;
746 if (ubi->thread_enabled)
747 wake_up_process(ubi->bgt_thread);
748 spin_unlock(&ubi->wl_lock);
751 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
755 * schedule_erase - schedule an erase work.
756 * @ubi: UBI device description object
757 * @e: the WL entry of the physical eraseblock to erase
758 * @torture: if the physical eraseblock has to be tortured
760 * This function returns zero in case of success and a %-ENOMEM in case of
763 static int schedule_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
766 struct ubi_work *wl_wrk;
768 dbg_wl("schedule erasure of PEB %d, EC %d, torture %d",
769 e->pnum, e->ec, torture);
771 wl_wrk = kmalloc(sizeof(struct ubi_work), GFP_KERNEL);
775 wl_wrk->func = &erase_worker;
777 wl_wrk->torture = torture;
779 schedule_ubi_work(ubi, wl_wrk);
784 * wear_leveling_worker - wear-leveling worker function.
785 * @ubi: UBI device description object
786 * @wrk: the work object
787 * @cancel: non-zero if the worker has to free memory and exit
789 * This function copies a more worn out physical eraseblock to a less worn out
790 * one. Returns zero in case of success and a negative error code in case of
793 static int wear_leveling_worker(struct ubi_device *ubi, struct ubi_work *wrk,
797 struct ubi_wl_entry *e1, *e2;
798 struct ubi_vid_hdr *vid_hdr;
805 vid_hdr = ubi_zalloc_vid_hdr(ubi);
809 spin_lock(&ubi->wl_lock);
812 * Only one WL worker at a time is supported at this implementation, so
813 * make sure a PEB is not being moved already.
815 if (ubi->move_to || tree_empty(&ubi->free) ||
816 (tree_empty(&ubi->used) && tree_empty(&ubi->scrub))) {
818 * Only one WL worker at a time is supported at this
819 * implementation, so if a LEB is already being moved, cancel.
821 * No free physical eraseblocks? Well, we cancel wear-leveling
822 * then. It will be triggered again when a free physical
823 * eraseblock appears.
825 * No used physical eraseblocks? They must be temporarily
826 * protected from being moved. They will be moved to the
827 * @ubi->used tree later and the wear-leveling will be
830 dbg_wl("cancel WL, a list is empty: free %d, used %d",
831 tree_empty(&ubi->free), tree_empty(&ubi->used));
832 ubi->wl_scheduled = 0;
833 spin_unlock(&ubi->wl_lock);
834 ubi_free_vid_hdr(ubi, vid_hdr);
838 if (tree_empty(&ubi->scrub)) {
840 * Now pick the least worn-out used physical eraseblock and a
841 * highly worn-out free physical eraseblock. If the erase
842 * counters differ much enough, start wear-leveling.
844 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, rb);
845 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
847 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD)) {
848 dbg_wl("no WL needed: min used EC %d, max free EC %d",
850 ubi->wl_scheduled = 0;
851 spin_unlock(&ubi->wl_lock);
852 ubi_free_vid_hdr(ubi, vid_hdr);
855 used_tree_del(ubi, e1);
856 dbg_wl("move PEB %d EC %d to PEB %d EC %d",
857 e1->pnum, e1->ec, e2->pnum, e2->ec);
859 e1 = rb_entry(rb_first(&ubi->scrub), struct ubi_wl_entry, rb);
860 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
861 scrub_tree_del(ubi, e1);
862 dbg_wl("scrub PEB %d to PEB %d", e1->pnum, e2->pnum);
865 free_tree_del(ubi, e2);
866 ubi_assert(!ubi->move_from && !ubi->move_to);
867 ubi_assert(!ubi->move_to_put && !ubi->move_from_put);
870 spin_unlock(&ubi->wl_lock);
873 * Now we are going to copy physical eraseblock @e1->pnum to @e2->pnum.
874 * We so far do not know which logical eraseblock our physical
875 * eraseblock (@e1) belongs to. We have to read the volume identifier
879 err = ubi_io_read_vid_hdr(ubi, e1->pnum, vid_hdr, 0);
880 if (err && err != UBI_IO_BITFLIPS) {
881 if (err == UBI_IO_PEB_FREE) {
883 * We are trying to move PEB without a VID header. UBI
884 * always write VID headers shortly after the PEB was
885 * given, so we have a situation when it did not have
886 * chance to write it down because it was preempted.
887 * Just re-schedule the work, so that next time it will
888 * likely have the VID header in place.
890 dbg_wl("PEB %d has no VID header", e1->pnum);
893 ubi_err("error %d while reading VID header from PEB %d",
901 err = ubi_eba_copy_leb(ubi, e1->pnum, e2->pnum, vid_hdr);
903 if (err == UBI_IO_BITFLIPS)
908 ubi_free_vid_hdr(ubi, vid_hdr);
909 spin_lock(&ubi->wl_lock);
910 if (!ubi->move_to_put)
911 used_tree_add(ubi, e2);
914 ubi->move_from = ubi->move_to = NULL;
915 ubi->move_from_put = ubi->move_to_put = 0;
916 ubi->wl_scheduled = 0;
917 spin_unlock(&ubi->wl_lock);
921 * Well, the target PEB was put meanwhile, schedule it for
924 dbg_wl("PEB %d was put meanwhile, erase", e2->pnum);
925 err = schedule_erase(ubi, e2, 0);
927 kmem_cache_free(wl_entries_slab, e2);
932 err = schedule_erase(ubi, e1, 0);
934 kmem_cache_free(wl_entries_slab, e1);
942 * Some error occurred. @e1 was not changed, so return it back. @e2
943 * might be changed, schedule it for erasure.
947 dbg_wl("error %d occurred, cancel operation", err);
948 ubi_assert(err <= 0);
950 ubi_free_vid_hdr(ubi, vid_hdr);
951 spin_lock(&ubi->wl_lock);
952 ubi->wl_scheduled = 0;
953 if (ubi->move_from_put)
956 used_tree_add(ubi, e1);
957 ubi->move_from = ubi->move_to = NULL;
958 ubi->move_from_put = ubi->move_to_put = 0;
959 spin_unlock(&ubi->wl_lock);
963 * Well, the target PEB was put meanwhile, schedule it for
966 dbg_wl("PEB %d was put meanwhile, erase", e1->pnum);
967 err = schedule_erase(ubi, e1, 0);
969 kmem_cache_free(wl_entries_slab, e1);
974 err = schedule_erase(ubi, e2, 0);
976 kmem_cache_free(wl_entries_slab, e2);
985 * ensure_wear_leveling - schedule wear-leveling if it is needed.
986 * @ubi: UBI device description object
988 * This function checks if it is time to start wear-leveling and schedules it
989 * if yes. This function returns zero in case of success and a negative error
990 * code in case of failure.
992 static int ensure_wear_leveling(struct ubi_device *ubi)
995 struct ubi_wl_entry *e1;
996 struct ubi_wl_entry *e2;
997 struct ubi_work *wrk;
999 spin_lock(&ubi->wl_lock);
1000 if (ubi->wl_scheduled)
1001 /* Wear-leveling is already in the work queue */
1005 * If the ubi->scrub tree is not empty, scrubbing is needed, and the
1006 * the WL worker has to be scheduled anyway.
1008 if (tree_empty(&ubi->scrub)) {
1009 if (tree_empty(&ubi->used) || tree_empty(&ubi->free))
1010 /* No physical eraseblocks - no deal */
1014 * We schedule wear-leveling only if the difference between the
1015 * lowest erase counter of used physical eraseblocks and a high
1016 * erase counter of free physical eraseblocks is greater then
1017 * %UBI_WL_THRESHOLD.
1019 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, rb);
1020 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
1022 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD))
1024 dbg_wl("schedule wear-leveling");
1026 dbg_wl("schedule scrubbing");
1028 ubi->wl_scheduled = 1;
1029 spin_unlock(&ubi->wl_lock);
1031 wrk = kmalloc(sizeof(struct ubi_work), GFP_KERNEL);
1037 wrk->func = &wear_leveling_worker;
1038 schedule_ubi_work(ubi, wrk);
1042 spin_lock(&ubi->wl_lock);
1043 ubi->wl_scheduled = 0;
1045 spin_unlock(&ubi->wl_lock);
1050 * erase_worker - physical eraseblock erase worker function.
1051 * @ubi: UBI device description object
1052 * @wl_wrk: the work object
1053 * @cancel: non-zero if the worker has to free memory and exit
1055 * This function erases a physical eraseblock and perform torture testing if
1056 * needed. It also takes care about marking the physical eraseblock bad if
1057 * needed. Returns zero in case of success and a negative error code in case of
1060 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
1064 struct ubi_wl_entry *e = wl_wrk->e;
1068 dbg_wl("cancel erasure of PEB %d EC %d", pnum, e->ec);
1070 kmem_cache_free(wl_entries_slab, e);
1074 dbg_wl("erase PEB %d EC %d", pnum, e->ec);
1076 err = sync_erase(ubi, e, wl_wrk->torture);
1078 /* Fine, we've erased it successfully */
1081 spin_lock(&ubi->wl_lock);
1083 free_tree_add(ubi, e);
1084 spin_unlock(&ubi->wl_lock);
1087 * One more erase operation has happened, take care about protected
1088 * physical eraseblocks.
1090 check_protection_over(ubi);
1092 /* And take care about wear-leveling */
1093 err = ensure_wear_leveling(ubi);
1098 kmem_cache_free(wl_entries_slab, e);
1102 * If this is not %-EIO, we have no idea what to do. Scheduling
1103 * this physical eraseblock for erasure again would cause
1104 * errors again and again. Well, lets switch to RO mode.
1110 /* It is %-EIO, the PEB went bad */
1112 if (!ubi->bad_allowed) {
1113 ubi_err("bad physical eraseblock %d detected", pnum);
1119 spin_lock(&ubi->volumes_lock);
1120 need = ubi->beb_rsvd_level - ubi->beb_rsvd_pebs + 1;
1122 need = ubi->avail_pebs >= need ? need : ubi->avail_pebs;
1123 ubi->avail_pebs -= need;
1124 ubi->rsvd_pebs += need;
1125 ubi->beb_rsvd_pebs += need;
1127 ubi_msg("reserve more %d PEBs", need);
1130 if (ubi->beb_rsvd_pebs == 0) {
1131 spin_unlock(&ubi->volumes_lock);
1132 ubi_err("no reserved physical eraseblocks");
1137 spin_unlock(&ubi->volumes_lock);
1138 ubi_msg("mark PEB %d as bad", pnum);
1140 err = ubi_io_mark_bad(ubi, pnum);
1146 spin_lock(&ubi->volumes_lock);
1147 ubi->beb_rsvd_pebs -= 1;
1148 ubi->bad_peb_count += 1;
1149 ubi->good_peb_count -= 1;
1150 ubi_calculate_reserved(ubi);
1151 if (ubi->beb_rsvd_pebs == 0)
1152 ubi_warn("last PEB from the reserved pool was used");
1153 spin_unlock(&ubi->volumes_lock);
1160 * ubi_wl_put_peb - return a physical eraseblock to the wear-leveling
1162 * @ubi: UBI device description object
1163 * @pnum: physical eraseblock to return
1164 * @torture: if this physical eraseblock has to be tortured
1166 * This function is called to return physical eraseblock @pnum to the pool of
1167 * free physical eraseblocks. The @torture flag has to be set if an I/O error
1168 * occurred to this @pnum and it has to be tested. This function returns zero
1169 * in case of success and a negative error code in case of failure.
1171 int ubi_wl_put_peb(struct ubi_device *ubi, int pnum, int torture)
1174 struct ubi_wl_entry *e;
1176 dbg_wl("PEB %d", pnum);
1177 ubi_assert(pnum >= 0);
1178 ubi_assert(pnum < ubi->peb_count);
1180 spin_lock(&ubi->wl_lock);
1182 e = ubi->lookuptbl[pnum];
1183 if (e == ubi->move_from) {
1185 * User is putting the physical eraseblock which was selected to
1186 * be moved. It will be scheduled for erasure in the
1187 * wear-leveling worker.
1189 dbg_wl("PEB %d is being moved", pnum);
1190 ubi_assert(!ubi->move_from_put);
1191 ubi->move_from_put = 1;
1192 spin_unlock(&ubi->wl_lock);
1194 } else if (e == ubi->move_to) {
1196 * User is putting the physical eraseblock which was selected
1197 * as the target the data is moved to. It may happen if the EBA
1198 * unit already re-mapped the LEB but the WL unit did has not
1199 * put the PEB to the "used" tree.
1201 dbg_wl("PEB %d is the target of data moving", pnum);
1202 ubi_assert(!ubi->move_to_put);
1203 ubi->move_to_put = 1;
1204 spin_unlock(&ubi->wl_lock);
1207 if (in_wl_tree(e, &ubi->used))
1208 used_tree_del(ubi, e);
1209 else if (in_wl_tree(e, &ubi->scrub))
1210 scrub_tree_del(ubi, e);
1212 prot_tree_del(ubi, e->pnum);
1214 spin_unlock(&ubi->wl_lock);
1216 err = schedule_erase(ubi, e, torture);
1218 spin_lock(&ubi->wl_lock);
1219 used_tree_add(ubi, e);
1220 spin_unlock(&ubi->wl_lock);
1227 * ubi_wl_scrub_peb - schedule a physical eraseblock for scrubbing.
1228 * @ubi: UBI device description object
1229 * @pnum: the physical eraseblock to schedule
1231 * If a bit-flip in a physical eraseblock is detected, this physical eraseblock
1232 * needs scrubbing. This function schedules a physical eraseblock for
1233 * scrubbing which is done in background. This function returns zero in case of
1234 * success and a negative error code in case of failure.
1236 int ubi_wl_scrub_peb(struct ubi_device *ubi, int pnum)
1238 struct ubi_wl_entry *e;
1240 ubi_msg("schedule PEB %d for scrubbing", pnum);
1243 spin_lock(&ubi->wl_lock);
1244 e = ubi->lookuptbl[pnum];
1245 if (e == ubi->move_from || in_wl_tree(e, &ubi->scrub)) {
1246 spin_unlock(&ubi->wl_lock);
1250 if (e == ubi->move_to) {
1252 * This physical eraseblock was used to move data to. The data
1253 * was moved but the PEB was not yet inserted to the proper
1254 * tree. We should just wait a little and let the WL worker
1257 spin_unlock(&ubi->wl_lock);
1258 dbg_wl("the PEB %d is not in proper tree, retry", pnum);
1263 if (in_wl_tree(e, &ubi->used))
1264 used_tree_del(ubi, e);
1266 prot_tree_del(ubi, pnum);
1268 scrub_tree_add(ubi, e);
1269 spin_unlock(&ubi->wl_lock);
1272 * Technically scrubbing is the same as wear-leveling, so it is done
1275 return ensure_wear_leveling(ubi);
1279 * ubi_wl_flush - flush all pending works.
1280 * @ubi: UBI device description object
1282 * This function returns zero in case of success and a negative error code in
1285 int ubi_wl_flush(struct ubi_device *ubi)
1287 int err, pending_count;
1289 pending_count = ubi->works_count;
1291 dbg_wl("flush (%d pending works)", pending_count);
1294 * Erase while the pending works queue is not empty, but not more then
1295 * the number of currently pending works.
1297 while (pending_count-- > 0) {
1307 * tree_destroy - destroy an RB-tree.
1308 * @root: the root of the tree to destroy
1310 static void tree_destroy(struct rb_root *root)
1313 struct ubi_wl_entry *e;
1319 else if (rb->rb_right)
1322 e = rb_entry(rb, struct ubi_wl_entry, rb);
1326 if (rb->rb_left == &e->rb)
1329 rb->rb_right = NULL;
1332 kmem_cache_free(wl_entries_slab, e);
1338 * ubi_thread - UBI background thread.
1339 * @u: the UBI device description object pointer
1341 static int ubi_thread(void *u)
1344 struct ubi_device *ubi = u;
1346 ubi_msg("background thread \"%s\" started, PID %d",
1347 ubi->bgt_name, current->pid);
1352 if (kthread_should_stop())
1355 if (try_to_freeze())
1358 spin_lock(&ubi->wl_lock);
1359 if (list_empty(&ubi->works) || ubi->ro_mode ||
1360 !ubi->thread_enabled) {
1361 set_current_state(TASK_INTERRUPTIBLE);
1362 spin_unlock(&ubi->wl_lock);
1366 spin_unlock(&ubi->wl_lock);
1370 ubi_err("%s: work failed with error code %d",
1371 ubi->bgt_name, err);
1372 if (failures++ > WL_MAX_FAILURES) {
1374 * Too many failures, disable the thread and
1375 * switch to read-only mode.
1377 ubi_msg("%s: %d consecutive failures",
1378 ubi->bgt_name, WL_MAX_FAILURES);
1389 dbg_wl("background thread \"%s\" is killed", ubi->bgt_name);
1394 * cancel_pending - cancel all pending works.
1395 * @ubi: UBI device description object
1397 static void cancel_pending(struct ubi_device *ubi)
1399 while (!list_empty(&ubi->works)) {
1400 struct ubi_work *wrk;
1402 wrk = list_entry(ubi->works.next, struct ubi_work, list);
1403 list_del(&wrk->list);
1404 wrk->func(ubi, wrk, 1);
1405 ubi->works_count -= 1;
1406 ubi_assert(ubi->works_count >= 0);
1411 * ubi_wl_init_scan - initialize the wear-leveling unit using scanning
1413 * @ubi: UBI device description object
1414 * @si: scanning information
1416 * This function returns zero in case of success, and a negative error code in
1419 int ubi_wl_init_scan(struct ubi_device *ubi, struct ubi_scan_info *si)
1422 struct rb_node *rb1, *rb2;
1423 struct ubi_scan_volume *sv;
1424 struct ubi_scan_leb *seb, *tmp;
1425 struct ubi_wl_entry *e;
1428 ubi->used = ubi->free = ubi->scrub = RB_ROOT;
1429 ubi->prot.pnum = ubi->prot.aec = RB_ROOT;
1430 spin_lock_init(&ubi->wl_lock);
1431 ubi->max_ec = si->max_ec;
1432 INIT_LIST_HEAD(&ubi->works);
1434 sprintf(ubi->bgt_name, UBI_BGT_NAME_PATTERN, ubi->ubi_num);
1436 ubi->bgt_thread = kthread_create(ubi_thread, ubi, ubi->bgt_name);
1437 if (IS_ERR(ubi->bgt_thread)) {
1438 err = PTR_ERR(ubi->bgt_thread);
1439 ubi_err("cannot spawn \"%s\", error %d", ubi->bgt_name,
1444 if (ubi_devices_cnt == 0) {
1445 wl_entries_slab = kmem_cache_create("ubi_wl_entry_slab",
1446 sizeof(struct ubi_wl_entry),
1448 if (!wl_entries_slab)
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(wl_entries_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(wl_entries_slab, e);
1473 list_for_each_entry(seb, &si->free, u.list) {
1476 e = kmem_cache_alloc(wl_entries_slab, GFP_KERNEL);
1480 e->pnum = seb->pnum;
1482 ubi_assert(e->ec >= 0);
1483 free_tree_add(ubi, e);
1484 ubi->lookuptbl[e->pnum] = e;
1487 list_for_each_entry(seb, &si->corr, u.list) {
1490 e = kmem_cache_alloc(wl_entries_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(wl_entries_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(wl_entries_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 used_tree_add(ubi, e);
1519 dbg_wl("add PEB %d EC %d to the scrub tree",
1521 scrub_tree_add(ubi, e);
1526 if (WL_RESERVED_PEBS > ubi->avail_pebs) {
1527 ubi_err("no enough physical eraseblocks (%d, need %d)",
1528 ubi->avail_pebs, WL_RESERVED_PEBS);
1531 ubi->avail_pebs -= WL_RESERVED_PEBS;
1532 ubi->rsvd_pebs += WL_RESERVED_PEBS;
1534 /* Schedule wear-leveling if needed */
1535 err = ensure_wear_leveling(ubi);
1542 cancel_pending(ubi);
1543 tree_destroy(&ubi->used);
1544 tree_destroy(&ubi->free);
1545 tree_destroy(&ubi->scrub);
1546 kfree(ubi->lookuptbl);
1547 if (ubi_devices_cnt == 0)
1548 kmem_cache_destroy(wl_entries_slab);
1553 * protection_trees_destroy - destroy the protection RB-trees.
1554 * @ubi: UBI device description object
1556 static void protection_trees_destroy(struct ubi_device *ubi)
1559 struct ubi_wl_prot_entry *pe;
1561 rb = ubi->prot.aec.rb_node;
1565 else if (rb->rb_right)
1568 pe = rb_entry(rb, struct ubi_wl_prot_entry, rb_aec);
1572 if (rb->rb_left == &pe->rb_aec)
1575 rb->rb_right = NULL;
1578 kmem_cache_free(wl_entries_slab, pe->e);
1585 * ubi_wl_close - close the wear-leveling unit.
1586 * @ubi: UBI device description object
1588 void ubi_wl_close(struct ubi_device *ubi)
1590 dbg_wl("disable \"%s\"", ubi->bgt_name);
1591 if (ubi->bgt_thread)
1592 kthread_stop(ubi->bgt_thread);
1594 dbg_wl("close the UBI wear-leveling unit");
1596 cancel_pending(ubi);
1597 protection_trees_destroy(ubi);
1598 tree_destroy(&ubi->used);
1599 tree_destroy(&ubi->free);
1600 tree_destroy(&ubi->scrub);
1601 kfree(ubi->lookuptbl);
1602 if (ubi_devices_cnt == 1)
1603 kmem_cache_destroy(wl_entries_slab);
1606 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
1609 * paranoid_check_ec - make sure that the erase counter of a physical eraseblock
1611 * @ubi: UBI device description object
1612 * @pnum: the physical eraseblock number to check
1613 * @ec: the erase counter to check
1615 * This function returns zero if the erase counter of physical eraseblock @pnum
1616 * is equivalent to @ec, %1 if not, and a negative error code if an error
1619 static int paranoid_check_ec(const struct ubi_device *ubi, int pnum, int ec)
1623 struct ubi_ec_hdr *ec_hdr;
1625 ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_KERNEL);
1629 err = ubi_io_read_ec_hdr(ubi, pnum, ec_hdr, 0);
1630 if (err && err != UBI_IO_BITFLIPS) {
1631 /* The header does not have to exist */
1636 read_ec = ubi64_to_cpu(ec_hdr->ec);
1637 if (ec != read_ec) {
1638 ubi_err("paranoid check failed for PEB %d", pnum);
1639 ubi_err("read EC is %lld, should be %d", read_ec, ec);
1640 ubi_dbg_dump_stack();
1651 * paranoid_check_in_wl_tree - make sure that a wear-leveling entry is present
1653 * @e: the wear-leveling entry to check
1654 * @root: the root of the tree
1656 * This function returns zero if @e is in the @root RB-tree and %1 if it
1659 static int paranoid_check_in_wl_tree(struct ubi_wl_entry *e,
1660 struct rb_root *root)
1662 if (in_wl_tree(e, root))
1665 ubi_err("paranoid check failed for PEB %d, EC %d, RB-tree %p ",
1666 e->pnum, e->ec, root);
1667 ubi_dbg_dump_stack();
1671 #endif /* CONFIG_MTD_UBI_DEBUG_PARANOID */