UBI: fix ubi_wl_flush
[linux-2.6] / drivers / mtd / ubi / wl.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  * Authors: Artem Bityutskiy (Битюцкий Артём), Thomas Gleixner
19  */
20
21 /*
22  * UBI wear-leveling unit.
23  *
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.
30  *
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.
33  *
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.
38  *
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.
42  *
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
47  * so forth.
48  *
49  * If the WL unit fails to erase a physical eraseblock, it marks it as bad.
50  *
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.
54  *
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.
59  *
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.
64  *
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.
72  *
73  * FIXME: looks too complex, should be simplified (later).
74  */
75
76 #include <linux/slab.h>
77 #include <linux/crc32.h>
78 #include <linux/freezer.h>
79 #include <linux/kthread.h>
80 #include "ubi.h"
81
82 /* Number of physical eraseblocks reserved for wear-leveling purposes */
83 #define WL_RESERVED_PEBS 1
84
85 /*
86  * How many erase cycles are short term, unknown, and long term physical
87  * eraseblocks protected.
88  */
89 #define ST_PROTECTION 16
90 #define U_PROTECTION  10
91 #define LT_PROTECTION 4
92
93 /*
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.
97  */
98 #define UBI_WL_THRESHOLD CONFIG_MTD_UBI_WL_THRESHOLD
99
100 /*
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.
110  */
111 #define WL_FREE_MAX_DIFF (2*UBI_WL_THRESHOLD)
112
113 /*
114  * Maximum number of consecutive background thread failures which is enough to
115  * switch to read-only mode.
116  */
117 #define WL_MAX_FAILURES 32
118
119 /**
120  * struct ubi_wl_prot_entry - PEB protection entry.
121  * @rb_pnum: link in the @wl->prot.pnum RB-tree
122  * @rb_aec: link in the @wl->prot.aec RB-tree
123  * @abs_ec: the absolute erase counter value when the protection ends
124  * @e: the wear-leveling entry of the physical eraseblock under protection
125  *
126  * When the WL unit returns a physical eraseblock, the physical eraseblock is
127  * protected from being moved for some "time". For this reason, the physical
128  * eraseblock is not directly moved from the @wl->free tree to the @wl->used
129  * tree. There is one more tree in between where this physical eraseblock is
130  * temporarily stored (@wl->prot).
131  *
132  * All this protection stuff is needed because:
133  *  o we don't want to move physical eraseblocks just after we have given them
134  *    to the user; instead, we first want to let users fill them up with data;
135  *
136  *  o there is a chance that the user will put the physical eraseblock very
137  *    soon, so it makes sense not to move it for some time, but wait; this is
138  *    especially important in case of "short term" physical eraseblocks.
139  *
140  * Physical eraseblocks stay protected only for limited time. But the "time" is
141  * measured in erase cycles in this case. This is implemented with help of the
142  * absolute erase counter (@wl->abs_ec). When it reaches certain value, the
143  * physical eraseblocks are moved from the protection trees (@wl->prot.*) to
144  * the @wl->used tree.
145  *
146  * Protected physical eraseblocks are searched by physical eraseblock number
147  * (when they are put) and by the absolute erase counter (to check if it is
148  * time to move them to the @wl->used tree). So there are actually 2 RB-trees
149  * storing the protected physical eraseblocks: @wl->prot.pnum and
150  * @wl->prot.aec. They are referred to as the "protection" trees. The
151  * first one is indexed by the physical eraseblock number. The second one is
152  * indexed by the absolute erase counter. Both trees store
153  * &struct ubi_wl_prot_entry objects.
154  *
155  * Each physical eraseblock has 2 main states: free and used. The former state
156  * corresponds to the @wl->free tree. The latter state is split up on several
157  * sub-states:
158  * o the WL movement is allowed (@wl->used tree);
159  * o the WL movement is temporarily prohibited (@wl->prot.pnum and
160  * @wl->prot.aec trees);
161  * o scrubbing is needed (@wl->scrub tree).
162  *
163  * Depending on the sub-state, wear-leveling entries of the used physical
164  * eraseblocks may be kept in one of those trees.
165  */
166 struct ubi_wl_prot_entry {
167         struct rb_node rb_pnum;
168         struct rb_node rb_aec;
169         unsigned long long abs_ec;
170         struct ubi_wl_entry *e;
171 };
172
173 /**
174  * struct ubi_work - UBI work description data structure.
175  * @list: a link in the list of pending works
176  * @func: worker function
177  * @priv: private data of the worker function
178  *
179  * @e: physical eraseblock to erase
180  * @torture: if the physical eraseblock has to be tortured
181  *
182  * The @func pointer points to the worker function. If the @cancel argument is
183  * not zero, the worker has to free the resources and exit immediately. The
184  * worker has to return zero in case of success and a negative error code in
185  * case of failure.
186  */
187 struct ubi_work {
188         struct list_head list;
189         int (*func)(struct ubi_device *ubi, struct ubi_work *wrk, int cancel);
190         /* The below fields are only relevant to erasure works */
191         struct ubi_wl_entry *e;
192         int torture;
193 };
194
195 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
196 static int paranoid_check_ec(struct ubi_device *ubi, int pnum, int ec);
197 static int paranoid_check_in_wl_tree(struct ubi_wl_entry *e,
198                                      struct rb_root *root);
199 #else
200 #define paranoid_check_ec(ubi, pnum, ec) 0
201 #define paranoid_check_in_wl_tree(e, root)
202 #endif
203
204 /**
205  * wl_tree_add - add a wear-leveling entry to a WL RB-tree.
206  * @e: the wear-leveling entry to add
207  * @root: the root of the tree
208  *
209  * Note, we use (erase counter, physical eraseblock number) pairs as keys in
210  * the @ubi->used and @ubi->free RB-trees.
211  */
212 static void wl_tree_add(struct ubi_wl_entry *e, struct rb_root *root)
213 {
214         struct rb_node **p, *parent = NULL;
215
216         p = &root->rb_node;
217         while (*p) {
218                 struct ubi_wl_entry *e1;
219
220                 parent = *p;
221                 e1 = rb_entry(parent, struct ubi_wl_entry, rb);
222
223                 if (e->ec < e1->ec)
224                         p = &(*p)->rb_left;
225                 else if (e->ec > e1->ec)
226                         p = &(*p)->rb_right;
227                 else {
228                         ubi_assert(e->pnum != e1->pnum);
229                         if (e->pnum < e1->pnum)
230                                 p = &(*p)->rb_left;
231                         else
232                                 p = &(*p)->rb_right;
233                 }
234         }
235
236         rb_link_node(&e->rb, parent, p);
237         rb_insert_color(&e->rb, root);
238 }
239
240 /**
241  * do_work - do one pending work.
242  * @ubi: UBI device description object
243  *
244  * This function returns zero in case of success and a negative error code in
245  * case of failure.
246  */
247 static int do_work(struct ubi_device *ubi)
248 {
249         int err;
250         struct ubi_work *wrk;
251
252         cond_resched();
253
254         /*
255          * @ubi->work_sem is used to synchronize with the workers. Workers take
256          * it in read mode, so many of them may be doing works at a time. But
257          * the queue flush code has to be sure the whole queue of works is
258          * done, and it takes the mutex in write mode.
259          */
260         down_read(&ubi->work_sem);
261         spin_lock(&ubi->wl_lock);
262
263         if (list_empty(&ubi->works)) {
264                 spin_unlock(&ubi->wl_lock);
265                 up_read(&ubi->work_sem);
266                 return 0;
267         }
268
269         wrk = list_entry(ubi->works.next, struct ubi_work, list);
270         list_del(&wrk->list);
271         spin_unlock(&ubi->wl_lock);
272
273         /*
274          * Call the worker function. Do not touch the work structure
275          * after this call as it will have been freed or reused by that
276          * time by the worker function.
277          */
278         err = wrk->func(ubi, wrk, 0);
279         if (err)
280                 ubi_err("work failed with error code %d", err);
281
282         spin_lock(&ubi->wl_lock);
283         ubi->works_count -= 1;
284         ubi_assert(ubi->works_count >= 0);
285         spin_unlock(&ubi->wl_lock);
286         up_read(&ubi->work_sem);
287         return err;
288 }
289
290 /**
291  * produce_free_peb - produce a free physical eraseblock.
292  * @ubi: UBI device description object
293  *
294  * This function tries to make a free PEB by means of synchronous execution of
295  * pending works. This may be needed if, for example the background thread is
296  * disabled. Returns zero in case of success and a negative error code in case
297  * of failure.
298  */
299 static int produce_free_peb(struct ubi_device *ubi)
300 {
301         int err;
302
303         spin_lock(&ubi->wl_lock);
304         while (!ubi->free.rb_node) {
305                 spin_unlock(&ubi->wl_lock);
306
307                 dbg_wl("do one work synchronously");
308                 err = do_work(ubi);
309                 if (err)
310                         return err;
311
312                 spin_lock(&ubi->wl_lock);
313         }
314         spin_unlock(&ubi->wl_lock);
315
316         return 0;
317 }
318
319 /**
320  * in_wl_tree - check if wear-leveling entry is present in a WL RB-tree.
321  * @e: the wear-leveling entry to check
322  * @root: the root of the tree
323  *
324  * This function returns non-zero if @e is in the @root RB-tree and zero if it
325  * is not.
326  */
327 static int in_wl_tree(struct ubi_wl_entry *e, struct rb_root *root)
328 {
329         struct rb_node *p;
330
331         p = root->rb_node;
332         while (p) {
333                 struct ubi_wl_entry *e1;
334
335                 e1 = rb_entry(p, struct ubi_wl_entry, rb);
336
337                 if (e->pnum == e1->pnum) {
338                         ubi_assert(e == e1);
339                         return 1;
340                 }
341
342                 if (e->ec < e1->ec)
343                         p = p->rb_left;
344                 else if (e->ec > e1->ec)
345                         p = p->rb_right;
346                 else {
347                         ubi_assert(e->pnum != e1->pnum);
348                         if (e->pnum < e1->pnum)
349                                 p = p->rb_left;
350                         else
351                                 p = p->rb_right;
352                 }
353         }
354
355         return 0;
356 }
357
358 /**
359  * prot_tree_add - add physical eraseblock to protection trees.
360  * @ubi: UBI device description object
361  * @e: the physical eraseblock to add
362  * @pe: protection entry object to use
363  * @abs_ec: absolute erase counter value when this physical eraseblock has
364  * to be removed from the protection trees.
365  *
366  * @wl->lock has to be locked.
367  */
368 static void prot_tree_add(struct ubi_device *ubi, struct ubi_wl_entry *e,
369                           struct ubi_wl_prot_entry *pe, int abs_ec)
370 {
371         struct rb_node **p, *parent = NULL;
372         struct ubi_wl_prot_entry *pe1;
373
374         pe->e = e;
375         pe->abs_ec = ubi->abs_ec + abs_ec;
376
377         p = &ubi->prot.pnum.rb_node;
378         while (*p) {
379                 parent = *p;
380                 pe1 = rb_entry(parent, struct ubi_wl_prot_entry, rb_pnum);
381
382                 if (e->pnum < pe1->e->pnum)
383                         p = &(*p)->rb_left;
384                 else
385                         p = &(*p)->rb_right;
386         }
387         rb_link_node(&pe->rb_pnum, parent, p);
388         rb_insert_color(&pe->rb_pnum, &ubi->prot.pnum);
389
390         p = &ubi->prot.aec.rb_node;
391         parent = NULL;
392         while (*p) {
393                 parent = *p;
394                 pe1 = rb_entry(parent, struct ubi_wl_prot_entry, rb_aec);
395
396                 if (pe->abs_ec < pe1->abs_ec)
397                         p = &(*p)->rb_left;
398                 else
399                         p = &(*p)->rb_right;
400         }
401         rb_link_node(&pe->rb_aec, parent, p);
402         rb_insert_color(&pe->rb_aec, &ubi->prot.aec);
403 }
404
405 /**
406  * find_wl_entry - find wear-leveling entry closest to certain erase counter.
407  * @root: the RB-tree where to look for
408  * @max: highest possible erase counter
409  *
410  * This function looks for a wear leveling entry with erase counter closest to
411  * @max and less then @max.
412  */
413 static struct ubi_wl_entry *find_wl_entry(struct rb_root *root, int max)
414 {
415         struct rb_node *p;
416         struct ubi_wl_entry *e;
417
418         e = rb_entry(rb_first(root), struct ubi_wl_entry, rb);
419         max += e->ec;
420
421         p = root->rb_node;
422         while (p) {
423                 struct ubi_wl_entry *e1;
424
425                 e1 = rb_entry(p, struct ubi_wl_entry, rb);
426                 if (e1->ec >= max)
427                         p = p->rb_left;
428                 else {
429                         p = p->rb_right;
430                         e = e1;
431                 }
432         }
433
434         return e;
435 }
436
437 /**
438  * ubi_wl_get_peb - get a physical eraseblock.
439  * @ubi: UBI device description object
440  * @dtype: type of data which will be stored in this physical eraseblock
441  *
442  * This function returns a physical eraseblock in case of success and a
443  * negative error code in case of failure. Might sleep.
444  */
445 int ubi_wl_get_peb(struct ubi_device *ubi, int dtype)
446 {
447         int err, protect, medium_ec;
448         struct ubi_wl_entry *e, *first, *last;
449         struct ubi_wl_prot_entry *pe;
450
451         ubi_assert(dtype == UBI_LONGTERM || dtype == UBI_SHORTTERM ||
452                    dtype == UBI_UNKNOWN);
453
454         pe = kmalloc(sizeof(struct ubi_wl_prot_entry), GFP_NOFS);
455         if (!pe)
456                 return -ENOMEM;
457
458 retry:
459         spin_lock(&ubi->wl_lock);
460         if (!ubi->free.rb_node) {
461                 if (ubi->works_count == 0) {
462                         ubi_assert(list_empty(&ubi->works));
463                         ubi_err("no free eraseblocks");
464                         spin_unlock(&ubi->wl_lock);
465                         kfree(pe);
466                         return -ENOSPC;
467                 }
468                 spin_unlock(&ubi->wl_lock);
469
470                 err = produce_free_peb(ubi);
471                 if (err < 0) {
472                         kfree(pe);
473                         return err;
474                 }
475                 goto retry;
476         }
477
478         switch (dtype) {
479                 case UBI_LONGTERM:
480                         /*
481                          * For long term data we pick a physical eraseblock
482                          * with high erase counter. But the highest erase
483                          * counter we can pick is bounded by the the lowest
484                          * erase counter plus %WL_FREE_MAX_DIFF.
485                          */
486                         e = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
487                         protect = LT_PROTECTION;
488                         break;
489                 case UBI_UNKNOWN:
490                         /*
491                          * For unknown data we pick a physical eraseblock with
492                          * medium erase counter. But we by no means can pick a
493                          * physical eraseblock with erase counter greater or
494                          * equivalent than the lowest erase counter plus
495                          * %WL_FREE_MAX_DIFF.
496                          */
497                         first = rb_entry(rb_first(&ubi->free),
498                                          struct ubi_wl_entry, rb);
499                         last = rb_entry(rb_last(&ubi->free),
500                                         struct ubi_wl_entry, rb);
501
502                         if (last->ec - first->ec < WL_FREE_MAX_DIFF)
503                                 e = rb_entry(ubi->free.rb_node,
504                                                 struct ubi_wl_entry, rb);
505                         else {
506                                 medium_ec = (first->ec + WL_FREE_MAX_DIFF)/2;
507                                 e = find_wl_entry(&ubi->free, medium_ec);
508                         }
509                         protect = U_PROTECTION;
510                         break;
511                 case UBI_SHORTTERM:
512                         /*
513                          * For short term data we pick a physical eraseblock
514                          * with the lowest erase counter as we expect it will
515                          * be erased soon.
516                          */
517                         e = rb_entry(rb_first(&ubi->free),
518                                      struct ubi_wl_entry, rb);
519                         protect = ST_PROTECTION;
520                         break;
521                 default:
522                         protect = 0;
523                         e = NULL;
524                         BUG();
525         }
526
527         /*
528          * Move the physical eraseblock to the protection trees where it will
529          * be protected from being moved for some time.
530          */
531         paranoid_check_in_wl_tree(e, &ubi->free);
532         rb_erase(&e->rb, &ubi->free);
533         prot_tree_add(ubi, e, pe, protect);
534
535         dbg_wl("PEB %d EC %d, protection %d", e->pnum, e->ec, protect);
536         spin_unlock(&ubi->wl_lock);
537
538         return e->pnum;
539 }
540
541 /**
542  * prot_tree_del - remove a physical eraseblock from the protection trees
543  * @ubi: UBI device description object
544  * @pnum: the physical eraseblock to remove
545  *
546  * This function returns PEB @pnum from the protection trees and returns zero
547  * in case of success and %-ENODEV if the PEB was not found in the protection
548  * trees.
549  */
550 static int prot_tree_del(struct ubi_device *ubi, int pnum)
551 {
552         struct rb_node *p;
553         struct ubi_wl_prot_entry *pe = NULL;
554
555         p = ubi->prot.pnum.rb_node;
556         while (p) {
557
558                 pe = rb_entry(p, struct ubi_wl_prot_entry, rb_pnum);
559
560                 if (pnum == pe->e->pnum)
561                         goto found;
562
563                 if (pnum < pe->e->pnum)
564                         p = p->rb_left;
565                 else
566                         p = p->rb_right;
567         }
568
569         return -ENODEV;
570
571 found:
572         ubi_assert(pe->e->pnum == pnum);
573         rb_erase(&pe->rb_aec, &ubi->prot.aec);
574         rb_erase(&pe->rb_pnum, &ubi->prot.pnum);
575         kfree(pe);
576         return 0;
577 }
578
579 /**
580  * sync_erase - synchronously erase a physical eraseblock.
581  * @ubi: UBI device description object
582  * @e: the the physical eraseblock to erase
583  * @torture: if the physical eraseblock has to be tortured
584  *
585  * This function returns zero in case of success and a negative error code in
586  * case of failure.
587  */
588 static int sync_erase(struct ubi_device *ubi, struct ubi_wl_entry *e, int torture)
589 {
590         int err;
591         struct ubi_ec_hdr *ec_hdr;
592         unsigned long long ec = e->ec;
593
594         dbg_wl("erase PEB %d, old EC %llu", e->pnum, ec);
595
596         err = paranoid_check_ec(ubi, e->pnum, e->ec);
597         if (err > 0)
598                 return -EINVAL;
599
600         ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
601         if (!ec_hdr)
602                 return -ENOMEM;
603
604         err = ubi_io_sync_erase(ubi, e->pnum, torture);
605         if (err < 0)
606                 goto out_free;
607
608         ec += err;
609         if (ec > UBI_MAX_ERASECOUNTER) {
610                 /*
611                  * Erase counter overflow. Upgrade UBI and use 64-bit
612                  * erase counters internally.
613                  */
614                 ubi_err("erase counter overflow at PEB %d, EC %llu",
615                         e->pnum, ec);
616                 err = -EINVAL;
617                 goto out_free;
618         }
619
620         dbg_wl("erased PEB %d, new EC %llu", e->pnum, ec);
621
622         ec_hdr->ec = cpu_to_be64(ec);
623
624         err = ubi_io_write_ec_hdr(ubi, e->pnum, ec_hdr);
625         if (err)
626                 goto out_free;
627
628         e->ec = ec;
629         spin_lock(&ubi->wl_lock);
630         if (e->ec > ubi->max_ec)
631                 ubi->max_ec = e->ec;
632         spin_unlock(&ubi->wl_lock);
633
634 out_free:
635         kfree(ec_hdr);
636         return err;
637 }
638
639 /**
640  * check_protection_over - check if it is time to stop protecting some
641  * physical eraseblocks.
642  * @ubi: UBI device description object
643  *
644  * This function is called after each erase operation, when the absolute erase
645  * counter is incremented, to check if some physical eraseblock  have not to be
646  * protected any longer. These physical eraseblocks are moved from the
647  * protection trees to the used tree.
648  */
649 static void check_protection_over(struct ubi_device *ubi)
650 {
651         struct ubi_wl_prot_entry *pe;
652
653         /*
654          * There may be several protected physical eraseblock to remove,
655          * process them all.
656          */
657         while (1) {
658                 spin_lock(&ubi->wl_lock);
659                 if (!ubi->prot.aec.rb_node) {
660                         spin_unlock(&ubi->wl_lock);
661                         break;
662                 }
663
664                 pe = rb_entry(rb_first(&ubi->prot.aec),
665                               struct ubi_wl_prot_entry, rb_aec);
666
667                 if (pe->abs_ec > ubi->abs_ec) {
668                         spin_unlock(&ubi->wl_lock);
669                         break;
670                 }
671
672                 dbg_wl("PEB %d protection over, abs_ec %llu, PEB abs_ec %llu",
673                        pe->e->pnum, ubi->abs_ec, pe->abs_ec);
674                 rb_erase(&pe->rb_aec, &ubi->prot.aec);
675                 rb_erase(&pe->rb_pnum, &ubi->prot.pnum);
676                 wl_tree_add(pe->e, &ubi->used);
677                 spin_unlock(&ubi->wl_lock);
678
679                 kfree(pe);
680                 cond_resched();
681         }
682 }
683
684 /**
685  * schedule_ubi_work - schedule a work.
686  * @ubi: UBI device description object
687  * @wrk: the work to schedule
688  *
689  * This function enqueues a work defined by @wrk to the tail of the pending
690  * works list.
691  */
692 static void schedule_ubi_work(struct ubi_device *ubi, struct ubi_work *wrk)
693 {
694         spin_lock(&ubi->wl_lock);
695         list_add_tail(&wrk->list, &ubi->works);
696         ubi_assert(ubi->works_count >= 0);
697         ubi->works_count += 1;
698         if (ubi->thread_enabled)
699                 wake_up_process(ubi->bgt_thread);
700         spin_unlock(&ubi->wl_lock);
701 }
702
703 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
704                         int cancel);
705
706 /**
707  * schedule_erase - schedule an erase work.
708  * @ubi: UBI device description object
709  * @e: the WL entry of the physical eraseblock to erase
710  * @torture: if the physical eraseblock has to be tortured
711  *
712  * This function returns zero in case of success and a %-ENOMEM in case of
713  * failure.
714  */
715 static int schedule_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
716                           int torture)
717 {
718         struct ubi_work *wl_wrk;
719
720         dbg_wl("schedule erasure of PEB %d, EC %d, torture %d",
721                e->pnum, e->ec, torture);
722
723         wl_wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
724         if (!wl_wrk)
725                 return -ENOMEM;
726
727         wl_wrk->func = &erase_worker;
728         wl_wrk->e = e;
729         wl_wrk->torture = torture;
730
731         schedule_ubi_work(ubi, wl_wrk);
732         return 0;
733 }
734
735 /**
736  * wear_leveling_worker - wear-leveling worker function.
737  * @ubi: UBI device description object
738  * @wrk: the work object
739  * @cancel: non-zero if the worker has to free memory and exit
740  *
741  * This function copies a more worn out physical eraseblock to a less worn out
742  * one. Returns zero in case of success and a negative error code in case of
743  * failure.
744  */
745 static int wear_leveling_worker(struct ubi_device *ubi, struct ubi_work *wrk,
746                                 int cancel)
747 {
748         int err, put = 0, scrubbing = 0, protect = 0;
749         struct ubi_wl_prot_entry *pe;
750         struct ubi_wl_entry *e1, *e2;
751         struct ubi_vid_hdr *vid_hdr;
752
753         kfree(wrk);
754
755         if (cancel)
756                 return 0;
757
758         vid_hdr = ubi_zalloc_vid_hdr(ubi, GFP_NOFS);
759         if (!vid_hdr)
760                 return -ENOMEM;
761
762         mutex_lock(&ubi->move_mutex);
763         spin_lock(&ubi->wl_lock);
764         ubi_assert(!ubi->move_from && !ubi->move_to);
765         ubi_assert(!ubi->move_to_put);
766
767         if (!ubi->free.rb_node ||
768             (!ubi->used.rb_node && !ubi->scrub.rb_node)) {
769                 /*
770                  * No free physical eraseblocks? Well, they must be waiting in
771                  * the queue to be erased. Cancel movement - it will be
772                  * triggered again when a free physical eraseblock appears.
773                  *
774                  * No used physical eraseblocks? They must be temporarily
775                  * protected from being moved. They will be moved to the
776                  * @ubi->used tree later and the wear-leveling will be
777                  * triggered again.
778                  */
779                 dbg_wl("cancel WL, a list is empty: free %d, used %d",
780                        !ubi->free.rb_node, !ubi->used.rb_node);
781                 goto out_cancel;
782         }
783
784         if (!ubi->scrub.rb_node) {
785                 /*
786                  * Now pick the least worn-out used physical eraseblock and a
787                  * highly worn-out free physical eraseblock. If the erase
788                  * counters differ much enough, start wear-leveling.
789                  */
790                 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, rb);
791                 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
792
793                 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD)) {
794                         dbg_wl("no WL needed: min used EC %d, max free EC %d",
795                                e1->ec, e2->ec);
796                         goto out_cancel;
797                 }
798                 paranoid_check_in_wl_tree(e1, &ubi->used);
799                 rb_erase(&e1->rb, &ubi->used);
800                 dbg_wl("move PEB %d EC %d to PEB %d EC %d",
801                        e1->pnum, e1->ec, e2->pnum, e2->ec);
802         } else {
803                 /* Perform scrubbing */
804                 scrubbing = 1;
805                 e1 = rb_entry(rb_first(&ubi->scrub), struct ubi_wl_entry, rb);
806                 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
807                 paranoid_check_in_wl_tree(e1, &ubi->scrub);
808                 rb_erase(&e1->rb, &ubi->scrub);
809                 dbg_wl("scrub PEB %d to PEB %d", e1->pnum, e2->pnum);
810         }
811
812         paranoid_check_in_wl_tree(e2, &ubi->free);
813         rb_erase(&e2->rb, &ubi->free);
814         ubi->move_from = e1;
815         ubi->move_to = e2;
816         spin_unlock(&ubi->wl_lock);
817
818         /*
819          * Now we are going to copy physical eraseblock @e1->pnum to @e2->pnum.
820          * We so far do not know which logical eraseblock our physical
821          * eraseblock (@e1) belongs to. We have to read the volume identifier
822          * header first.
823          *
824          * Note, we are protected from this PEB being unmapped and erased. The
825          * 'ubi_wl_put_peb()' would wait for moving to be finished if the PEB
826          * which is being moved was unmapped.
827          */
828
829         err = ubi_io_read_vid_hdr(ubi, e1->pnum, vid_hdr, 0);
830         if (err && err != UBI_IO_BITFLIPS) {
831                 if (err == UBI_IO_PEB_FREE) {
832                         /*
833                          * We are trying to move PEB without a VID header. UBI
834                          * always write VID headers shortly after the PEB was
835                          * given, so we have a situation when it did not have
836                          * chance to write it down because it was preempted.
837                          * Just re-schedule the work, so that next time it will
838                          * likely have the VID header in place.
839                          */
840                         dbg_wl("PEB %d has no VID header", e1->pnum);
841                         goto out_not_moved;
842                 }
843
844                 ubi_err("error %d while reading VID header from PEB %d",
845                         err, e1->pnum);
846                 if (err > 0)
847                         err = -EIO;
848                 goto out_error;
849         }
850
851         err = ubi_eba_copy_leb(ubi, e1->pnum, e2->pnum, vid_hdr);
852         if (err) {
853
854                 if (err < 0)
855                         goto out_error;
856                 if (err == 1)
857                         goto out_not_moved;
858
859                 /*
860                  * For some reason the LEB was not moved - it might be because
861                  * the volume is being deleted. We should prevent this PEB from
862                  * being selected for wear-levelling movement for some "time",
863                  * so put it to the protection tree.
864                  */
865
866                 dbg_wl("cancelled moving PEB %d", e1->pnum);
867                 pe = kmalloc(sizeof(struct ubi_wl_prot_entry), GFP_NOFS);
868                 if (!pe) {
869                         err = -ENOMEM;
870                         goto out_error;
871                 }
872
873                 protect = 1;
874         }
875
876         ubi_free_vid_hdr(ubi, vid_hdr);
877         spin_lock(&ubi->wl_lock);
878         if (protect)
879                 prot_tree_add(ubi, e1, pe, protect);
880         if (!ubi->move_to_put)
881                 wl_tree_add(e2, &ubi->used);
882         else
883                 put = 1;
884         ubi->move_from = ubi->move_to = NULL;
885         ubi->move_to_put = ubi->wl_scheduled = 0;
886         spin_unlock(&ubi->wl_lock);
887
888         if (put) {
889                 /*
890                  * Well, the target PEB was put meanwhile, schedule it for
891                  * erasure.
892                  */
893                 dbg_wl("PEB %d was put meanwhile, erase", e2->pnum);
894                 err = schedule_erase(ubi, e2, 0);
895                 if (err)
896                         goto out_error;
897         }
898
899         if (!protect) {
900                 err = schedule_erase(ubi, e1, 0);
901                 if (err)
902                         goto out_error;
903         }
904
905
906         dbg_wl("done");
907         mutex_unlock(&ubi->move_mutex);
908         return 0;
909
910         /*
911          * For some reasons the LEB was not moved, might be an error, might be
912          * something else. @e1 was not changed, so return it back. @e2 might
913          * be changed, schedule it for erasure.
914          */
915 out_not_moved:
916         ubi_free_vid_hdr(ubi, vid_hdr);
917         spin_lock(&ubi->wl_lock);
918         if (scrubbing)
919                 wl_tree_add(e1, &ubi->scrub);
920         else
921                 wl_tree_add(e1, &ubi->used);
922         ubi->move_from = ubi->move_to = NULL;
923         ubi->move_to_put = ubi->wl_scheduled = 0;
924         spin_unlock(&ubi->wl_lock);
925
926         err = schedule_erase(ubi, e2, 0);
927         if (err)
928                 goto out_error;
929
930         mutex_unlock(&ubi->move_mutex);
931         return 0;
932
933 out_error:
934         ubi_err("error %d while moving PEB %d to PEB %d",
935                 err, e1->pnum, e2->pnum);
936
937         ubi_free_vid_hdr(ubi, vid_hdr);
938         spin_lock(&ubi->wl_lock);
939         ubi->move_from = ubi->move_to = NULL;
940         ubi->move_to_put = ubi->wl_scheduled = 0;
941         spin_unlock(&ubi->wl_lock);
942
943         kmem_cache_free(ubi_wl_entry_slab, e1);
944         kmem_cache_free(ubi_wl_entry_slab, e2);
945         ubi_ro_mode(ubi);
946
947         mutex_unlock(&ubi->move_mutex);
948         return err;
949
950 out_cancel:
951         ubi->wl_scheduled = 0;
952         spin_unlock(&ubi->wl_lock);
953         mutex_unlock(&ubi->move_mutex);
954         ubi_free_vid_hdr(ubi, vid_hdr);
955         return 0;
956 }
957
958 /**
959  * ensure_wear_leveling - schedule wear-leveling if it is needed.
960  * @ubi: UBI device description object
961  *
962  * This function checks if it is time to start wear-leveling and schedules it
963  * if yes. This function returns zero in case of success and a negative error
964  * code in case of failure.
965  */
966 static int ensure_wear_leveling(struct ubi_device *ubi)
967 {
968         int err = 0;
969         struct ubi_wl_entry *e1;
970         struct ubi_wl_entry *e2;
971         struct ubi_work *wrk;
972
973         spin_lock(&ubi->wl_lock);
974         if (ubi->wl_scheduled)
975                 /* Wear-leveling is already in the work queue */
976                 goto out_unlock;
977
978         /*
979          * If the ubi->scrub tree is not empty, scrubbing is needed, and the
980          * the WL worker has to be scheduled anyway.
981          */
982         if (!ubi->scrub.rb_node) {
983                 if (!ubi->used.rb_node || !ubi->free.rb_node)
984                         /* No physical eraseblocks - no deal */
985                         goto out_unlock;
986
987                 /*
988                  * We schedule wear-leveling only if the difference between the
989                  * lowest erase counter of used physical eraseblocks and a high
990                  * erase counter of free physical eraseblocks is greater then
991                  * %UBI_WL_THRESHOLD.
992                  */
993                 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, rb);
994                 e2 = find_wl_entry(&ubi->free, WL_FREE_MAX_DIFF);
995
996                 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD))
997                         goto out_unlock;
998                 dbg_wl("schedule wear-leveling");
999         } else
1000                 dbg_wl("schedule scrubbing");
1001
1002         ubi->wl_scheduled = 1;
1003         spin_unlock(&ubi->wl_lock);
1004
1005         wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
1006         if (!wrk) {
1007                 err = -ENOMEM;
1008                 goto out_cancel;
1009         }
1010
1011         wrk->func = &wear_leveling_worker;
1012         schedule_ubi_work(ubi, wrk);
1013         return err;
1014
1015 out_cancel:
1016         spin_lock(&ubi->wl_lock);
1017         ubi->wl_scheduled = 0;
1018 out_unlock:
1019         spin_unlock(&ubi->wl_lock);
1020         return err;
1021 }
1022
1023 /**
1024  * erase_worker - physical eraseblock erase worker function.
1025  * @ubi: UBI device description object
1026  * @wl_wrk: the work object
1027  * @cancel: non-zero if the worker has to free memory and exit
1028  *
1029  * This function erases a physical eraseblock and perform torture testing if
1030  * needed. It also takes care about marking the physical eraseblock bad if
1031  * needed. Returns zero in case of success and a negative error code in case of
1032  * failure.
1033  */
1034 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
1035                         int cancel)
1036 {
1037         struct ubi_wl_entry *e = wl_wrk->e;
1038         int pnum = e->pnum, err, need;
1039
1040         if (cancel) {
1041                 dbg_wl("cancel erasure of PEB %d EC %d", pnum, e->ec);
1042                 kfree(wl_wrk);
1043                 kmem_cache_free(ubi_wl_entry_slab, e);
1044                 return 0;
1045         }
1046
1047         dbg_wl("erase PEB %d EC %d", pnum, e->ec);
1048
1049         err = sync_erase(ubi, e, wl_wrk->torture);
1050         if (!err) {
1051                 /* Fine, we've erased it successfully */
1052                 kfree(wl_wrk);
1053
1054                 spin_lock(&ubi->wl_lock);
1055                 ubi->abs_ec += 1;
1056                 wl_tree_add(e, &ubi->free);
1057                 spin_unlock(&ubi->wl_lock);
1058
1059                 /*
1060                  * One more erase operation has happened, take care about protected
1061                  * physical eraseblocks.
1062                  */
1063                 check_protection_over(ubi);
1064
1065                 /* And take care about wear-leveling */
1066                 err = ensure_wear_leveling(ubi);
1067                 return err;
1068         }
1069
1070         ubi_err("failed to erase PEB %d, error %d", pnum, err);
1071         kfree(wl_wrk);
1072         kmem_cache_free(ubi_wl_entry_slab, e);
1073
1074         if (err == -EINTR || err == -ENOMEM || err == -EAGAIN ||
1075             err == -EBUSY) {
1076                 int err1;
1077
1078                 /* Re-schedule the LEB for erasure */
1079                 err1 = schedule_erase(ubi, e, 0);
1080                 if (err1) {
1081                         err = err1;
1082                         goto out_ro;
1083                 }
1084                 return err;
1085         } else if (err != -EIO) {
1086                 /*
1087                  * If this is not %-EIO, we have no idea what to do. Scheduling
1088                  * this physical eraseblock for erasure again would cause
1089                  * errors again and again. Well, lets switch to RO mode.
1090                  */
1091                 goto out_ro;
1092         }
1093
1094         /* It is %-EIO, the PEB went bad */
1095
1096         if (!ubi->bad_allowed) {
1097                 ubi_err("bad physical eraseblock %d detected", pnum);
1098                 goto out_ro;
1099         }
1100
1101         spin_lock(&ubi->volumes_lock);
1102         need = ubi->beb_rsvd_level - ubi->beb_rsvd_pebs + 1;
1103         if (need > 0) {
1104                 need = ubi->avail_pebs >= need ? need : ubi->avail_pebs;
1105                 ubi->avail_pebs -= need;
1106                 ubi->rsvd_pebs += need;
1107                 ubi->beb_rsvd_pebs += need;
1108                 if (need > 0)
1109                         ubi_msg("reserve more %d PEBs", need);
1110         }
1111
1112         if (ubi->beb_rsvd_pebs == 0) {
1113                 spin_unlock(&ubi->volumes_lock);
1114                 ubi_err("no reserved physical eraseblocks");
1115                 goto out_ro;
1116         }
1117
1118         spin_unlock(&ubi->volumes_lock);
1119         ubi_msg("mark PEB %d as bad", pnum);
1120
1121         err = ubi_io_mark_bad(ubi, pnum);
1122         if (err)
1123                 goto out_ro;
1124
1125         spin_lock(&ubi->volumes_lock);
1126         ubi->beb_rsvd_pebs -= 1;
1127         ubi->bad_peb_count += 1;
1128         ubi->good_peb_count -= 1;
1129         ubi_calculate_reserved(ubi);
1130         if (ubi->beb_rsvd_pebs == 0)
1131                 ubi_warn("last PEB from the reserved pool was used");
1132         spin_unlock(&ubi->volumes_lock);
1133
1134         return err;
1135
1136 out_ro:
1137         ubi_ro_mode(ubi);
1138         return err;
1139 }
1140
1141 /**
1142  * ubi_wl_put_peb - return a physical eraseblock to the wear-leveling unit.
1143  * @ubi: UBI device description object
1144  * @pnum: physical eraseblock to return
1145  * @torture: if this physical eraseblock has to be tortured
1146  *
1147  * This function is called to return physical eraseblock @pnum to the pool of
1148  * free physical eraseblocks. The @torture flag has to be set if an I/O error
1149  * occurred to this @pnum and it has to be tested. This function returns zero
1150  * in case of success, and a negative error code in case of failure.
1151  */
1152 int ubi_wl_put_peb(struct ubi_device *ubi, int pnum, int torture)
1153 {
1154         int err;
1155         struct ubi_wl_entry *e;
1156
1157         dbg_wl("PEB %d", pnum);
1158         ubi_assert(pnum >= 0);
1159         ubi_assert(pnum < ubi->peb_count);
1160
1161 retry:
1162         spin_lock(&ubi->wl_lock);
1163         e = ubi->lookuptbl[pnum];
1164         if (e == ubi->move_from) {
1165                 /*
1166                  * User is putting the physical eraseblock which was selected to
1167                  * be moved. It will be scheduled for erasure in the
1168                  * wear-leveling worker.
1169                  */
1170                 dbg_wl("PEB %d is being moved, wait", pnum);
1171                 spin_unlock(&ubi->wl_lock);
1172
1173                 /* Wait for the WL worker by taking the @ubi->move_mutex */
1174                 mutex_lock(&ubi->move_mutex);
1175                 mutex_unlock(&ubi->move_mutex);
1176                 goto retry;
1177         } else if (e == ubi->move_to) {
1178                 /*
1179                  * User is putting the physical eraseblock which was selected
1180                  * as the target the data is moved to. It may happen if the EBA
1181                  * unit already re-mapped the LEB in 'ubi_eba_copy_leb()' but
1182                  * the WL unit has not put the PEB to the "used" tree yet, but
1183                  * it is about to do this. So we just set a flag which will
1184                  * tell the WL worker that the PEB is not needed anymore and
1185                  * should be scheduled for erasure.
1186                  */
1187                 dbg_wl("PEB %d is the target of data moving", pnum);
1188                 ubi_assert(!ubi->move_to_put);
1189                 ubi->move_to_put = 1;
1190                 spin_unlock(&ubi->wl_lock);
1191                 return 0;
1192         } else {
1193                 if (in_wl_tree(e, &ubi->used)) {
1194                         paranoid_check_in_wl_tree(e, &ubi->used);
1195                         rb_erase(&e->rb, &ubi->used);
1196                 } else if (in_wl_tree(e, &ubi->scrub)) {
1197                         paranoid_check_in_wl_tree(e, &ubi->scrub);
1198                         rb_erase(&e->rb, &ubi->scrub);
1199                 } else {
1200                         err = prot_tree_del(ubi, e->pnum);
1201                         if (err) {
1202                                 ubi_err("PEB %d not found", pnum);
1203                                 ubi_ro_mode(ubi);
1204                                 spin_unlock(&ubi->wl_lock);
1205                                 return err;
1206                         }
1207                 }
1208         }
1209         spin_unlock(&ubi->wl_lock);
1210
1211         err = schedule_erase(ubi, e, torture);
1212         if (err) {
1213                 spin_lock(&ubi->wl_lock);
1214                 wl_tree_add(e, &ubi->used);
1215                 spin_unlock(&ubi->wl_lock);
1216         }
1217
1218         return err;
1219 }
1220
1221 /**
1222  * ubi_wl_scrub_peb - schedule a physical eraseblock for scrubbing.
1223  * @ubi: UBI device description object
1224  * @pnum: the physical eraseblock to schedule
1225  *
1226  * If a bit-flip in a physical eraseblock is detected, this physical eraseblock
1227  * needs scrubbing. This function schedules a physical eraseblock for
1228  * scrubbing which is done in background. This function returns zero in case of
1229  * success and a negative error code in case of failure.
1230  */
1231 int ubi_wl_scrub_peb(struct ubi_device *ubi, int pnum)
1232 {
1233         struct ubi_wl_entry *e;
1234
1235         ubi_msg("schedule PEB %d for scrubbing", pnum);
1236
1237 retry:
1238         spin_lock(&ubi->wl_lock);
1239         e = ubi->lookuptbl[pnum];
1240         if (e == ubi->move_from || in_wl_tree(e, &ubi->scrub)) {
1241                 spin_unlock(&ubi->wl_lock);
1242                 return 0;
1243         }
1244
1245         if (e == ubi->move_to) {
1246                 /*
1247                  * This physical eraseblock was used to move data to. The data
1248                  * was moved but the PEB was not yet inserted to the proper
1249                  * tree. We should just wait a little and let the WL worker
1250                  * proceed.
1251                  */
1252                 spin_unlock(&ubi->wl_lock);
1253                 dbg_wl("the PEB %d is not in proper tree, retry", pnum);
1254                 yield();
1255                 goto retry;
1256         }
1257
1258         if (in_wl_tree(e, &ubi->used)) {
1259                 paranoid_check_in_wl_tree(e, &ubi->used);
1260                 rb_erase(&e->rb, &ubi->used);
1261         } else {
1262                 int err;
1263
1264                 err = prot_tree_del(ubi, e->pnum);
1265                 if (err) {
1266                         ubi_err("PEB %d not found", pnum);
1267                         ubi_ro_mode(ubi);
1268                         spin_unlock(&ubi->wl_lock);
1269                         return err;
1270                 }
1271         }
1272
1273         wl_tree_add(e, &ubi->scrub);
1274         spin_unlock(&ubi->wl_lock);
1275
1276         /*
1277          * Technically scrubbing is the same as wear-leveling, so it is done
1278          * by the WL worker.
1279          */
1280         return ensure_wear_leveling(ubi);
1281 }
1282
1283 /**
1284  * ubi_wl_flush - flush all pending works.
1285  * @ubi: UBI device description object
1286  *
1287  * This function returns zero in case of success and a negative error code in
1288  * case of failure.
1289  */
1290 int ubi_wl_flush(struct ubi_device *ubi)
1291 {
1292         int err;
1293
1294         /*
1295          * Erase while the pending works queue is not empty, but not more then
1296          * the number of currently pending works.
1297          */
1298         dbg_wl("flush (%d pending works)", ubi->works_count);
1299         while (ubi->works_count) {
1300                 err = do_work(ubi);
1301                 if (err)
1302                         return err;
1303         }
1304
1305         /*
1306          * Make sure all the works which have been done in parallel are
1307          * finished.
1308          */
1309         down_write(&ubi->work_sem);
1310         up_write(&ubi->work_sem);
1311
1312         /*
1313          * And in case last was the WL worker and it cancelled the LEB
1314          * movement, flush again.
1315          */
1316         while (ubi->works_count) {
1317                 dbg_wl("flush more (%d pending works)", ubi->works_count);
1318                 err = do_work(ubi);
1319                 if (err)
1320                         return err;
1321         }
1322
1323         return 0;
1324 }
1325
1326 /**
1327  * tree_destroy - destroy an RB-tree.
1328  * @root: the root of the tree to destroy
1329  */
1330 static void tree_destroy(struct rb_root *root)
1331 {
1332         struct rb_node *rb;
1333         struct ubi_wl_entry *e;
1334
1335         rb = root->rb_node;
1336         while (rb) {
1337                 if (rb->rb_left)
1338                         rb = rb->rb_left;
1339                 else if (rb->rb_right)
1340                         rb = rb->rb_right;
1341                 else {
1342                         e = rb_entry(rb, struct ubi_wl_entry, rb);
1343
1344                         rb = rb_parent(rb);
1345                         if (rb) {
1346                                 if (rb->rb_left == &e->rb)
1347                                         rb->rb_left = NULL;
1348                                 else
1349                                         rb->rb_right = NULL;
1350                         }
1351
1352                         kmem_cache_free(ubi_wl_entry_slab, e);
1353                 }
1354         }
1355 }
1356
1357 /**
1358  * ubi_thread - UBI background thread.
1359  * @u: the UBI device description object pointer
1360  */
1361 static int ubi_thread(void *u)
1362 {
1363         int failures = 0;
1364         struct ubi_device *ubi = u;
1365
1366         ubi_msg("background thread \"%s\" started, PID %d",
1367                 ubi->bgt_name, task_pid_nr(current));
1368
1369         set_freezable();
1370         for (;;) {
1371                 int err;
1372
1373                 if (kthread_should_stop())
1374                         goto out;
1375
1376                 if (try_to_freeze())
1377                         continue;
1378
1379                 spin_lock(&ubi->wl_lock);
1380                 if (list_empty(&ubi->works) || ubi->ro_mode ||
1381                                !ubi->thread_enabled) {
1382                         set_current_state(TASK_INTERRUPTIBLE);
1383                         spin_unlock(&ubi->wl_lock);
1384                         schedule();
1385                         continue;
1386                 }
1387                 spin_unlock(&ubi->wl_lock);
1388
1389                 err = do_work(ubi);
1390                 if (err) {
1391                         ubi_err("%s: work failed with error code %d",
1392                                 ubi->bgt_name, err);
1393                         if (failures++ > WL_MAX_FAILURES) {
1394                                 /*
1395                                  * Too many failures, disable the thread and
1396                                  * switch to read-only mode.
1397                                  */
1398                                 ubi_msg("%s: %d consecutive failures",
1399                                         ubi->bgt_name, WL_MAX_FAILURES);
1400                                 ubi_ro_mode(ubi);
1401                                 break;
1402                         }
1403                 } else
1404                         failures = 0;
1405
1406                 cond_resched();
1407         }
1408
1409 out:
1410         dbg_wl("background thread \"%s\" is killed", ubi->bgt_name);
1411         return 0;
1412 }
1413
1414 /**
1415  * cancel_pending - cancel all pending works.
1416  * @ubi: UBI device description object
1417  */
1418 static void cancel_pending(struct ubi_device *ubi)
1419 {
1420         while (!list_empty(&ubi->works)) {
1421                 struct ubi_work *wrk;
1422
1423                 wrk = list_entry(ubi->works.next, struct ubi_work, list);
1424                 list_del(&wrk->list);
1425                 wrk->func(ubi, wrk, 1);
1426                 ubi->works_count -= 1;
1427                 ubi_assert(ubi->works_count >= 0);
1428         }
1429 }
1430
1431 /**
1432  * ubi_wl_init_scan - initialize the wear-leveling unit using scanning
1433  * information.
1434  * @ubi: UBI device description object
1435  * @si: scanning information
1436  *
1437  * This function returns zero in case of success, and a negative error code in
1438  * case of failure.
1439  */
1440 int ubi_wl_init_scan(struct ubi_device *ubi, struct ubi_scan_info *si)
1441 {
1442         int err;
1443         struct rb_node *rb1, *rb2;
1444         struct ubi_scan_volume *sv;
1445         struct ubi_scan_leb *seb, *tmp;
1446         struct ubi_wl_entry *e;
1447
1448
1449         ubi->used = ubi->free = ubi->scrub = RB_ROOT;
1450         ubi->prot.pnum = ubi->prot.aec = RB_ROOT;
1451         spin_lock_init(&ubi->wl_lock);
1452         mutex_init(&ubi->move_mutex);
1453         init_rwsem(&ubi->work_sem);
1454         ubi->max_ec = si->max_ec;
1455         INIT_LIST_HEAD(&ubi->works);
1456
1457         sprintf(ubi->bgt_name, UBI_BGT_NAME_PATTERN, ubi->ubi_num);
1458
1459         ubi->bgt_thread = kthread_create(ubi_thread, ubi, ubi->bgt_name);
1460         if (IS_ERR(ubi->bgt_thread)) {
1461                 err = PTR_ERR(ubi->bgt_thread);
1462                 ubi_err("cannot spawn \"%s\", error %d", ubi->bgt_name,
1463                         err);
1464                 return err;
1465         }
1466
1467         err = -ENOMEM;
1468         ubi->lookuptbl = kzalloc(ubi->peb_count * sizeof(void *), GFP_KERNEL);
1469         if (!ubi->lookuptbl)
1470                 goto out_free;
1471
1472         list_for_each_entry_safe(seb, tmp, &si->erase, u.list) {
1473                 cond_resched();
1474
1475                 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1476                 if (!e)
1477                         goto out_free;
1478
1479                 e->pnum = seb->pnum;
1480                 e->ec = seb->ec;
1481                 ubi->lookuptbl[e->pnum] = e;
1482                 if (schedule_erase(ubi, e, 0)) {
1483                         kmem_cache_free(ubi_wl_entry_slab, e);
1484                         goto out_free;
1485                 }
1486         }
1487
1488         list_for_each_entry(seb, &si->free, u.list) {
1489                 cond_resched();
1490
1491                 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1492                 if (!e)
1493                         goto out_free;
1494
1495                 e->pnum = seb->pnum;
1496                 e->ec = seb->ec;
1497                 ubi_assert(e->ec >= 0);
1498                 wl_tree_add(e, &ubi->free);
1499                 ubi->lookuptbl[e->pnum] = e;
1500         }
1501
1502         list_for_each_entry(seb, &si->corr, u.list) {
1503                 cond_resched();
1504
1505                 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1506                 if (!e)
1507                         goto out_free;
1508
1509                 e->pnum = seb->pnum;
1510                 e->ec = seb->ec;
1511                 ubi->lookuptbl[e->pnum] = e;
1512                 if (schedule_erase(ubi, e, 0)) {
1513                         kmem_cache_free(ubi_wl_entry_slab, e);
1514                         goto out_free;
1515                 }
1516         }
1517
1518         ubi_rb_for_each_entry(rb1, sv, &si->volumes, rb) {
1519                 ubi_rb_for_each_entry(rb2, seb, &sv->root, u.rb) {
1520                         cond_resched();
1521
1522                         e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1523                         if (!e)
1524                                 goto out_free;
1525
1526                         e->pnum = seb->pnum;
1527                         e->ec = seb->ec;
1528                         ubi->lookuptbl[e->pnum] = e;
1529                         if (!seb->scrub) {
1530                                 dbg_wl("add PEB %d EC %d to the used tree",
1531                                        e->pnum, e->ec);
1532                                 wl_tree_add(e, &ubi->used);
1533                         } else {
1534                                 dbg_wl("add PEB %d EC %d to the scrub tree",
1535                                        e->pnum, e->ec);
1536                                 wl_tree_add(e, &ubi->scrub);
1537                         }
1538                 }
1539         }
1540
1541         if (ubi->avail_pebs < WL_RESERVED_PEBS) {
1542                 ubi_err("no enough physical eraseblocks (%d, need %d)",
1543                         ubi->avail_pebs, WL_RESERVED_PEBS);
1544                 goto out_free;
1545         }
1546         ubi->avail_pebs -= WL_RESERVED_PEBS;
1547         ubi->rsvd_pebs += WL_RESERVED_PEBS;
1548
1549         /* Schedule wear-leveling if needed */
1550         err = ensure_wear_leveling(ubi);
1551         if (err)
1552                 goto out_free;
1553
1554         return 0;
1555
1556 out_free:
1557         cancel_pending(ubi);
1558         tree_destroy(&ubi->used);
1559         tree_destroy(&ubi->free);
1560         tree_destroy(&ubi->scrub);
1561         kfree(ubi->lookuptbl);
1562         return err;
1563 }
1564
1565 /**
1566  * protection_trees_destroy - destroy the protection RB-trees.
1567  * @ubi: UBI device description object
1568  */
1569 static void protection_trees_destroy(struct ubi_device *ubi)
1570 {
1571         struct rb_node *rb;
1572         struct ubi_wl_prot_entry *pe;
1573
1574         rb = ubi->prot.aec.rb_node;
1575         while (rb) {
1576                 if (rb->rb_left)
1577                         rb = rb->rb_left;
1578                 else if (rb->rb_right)
1579                         rb = rb->rb_right;
1580                 else {
1581                         pe = rb_entry(rb, struct ubi_wl_prot_entry, rb_aec);
1582
1583                         rb = rb_parent(rb);
1584                         if (rb) {
1585                                 if (rb->rb_left == &pe->rb_aec)
1586                                         rb->rb_left = NULL;
1587                                 else
1588                                         rb->rb_right = NULL;
1589                         }
1590
1591                         kmem_cache_free(ubi_wl_entry_slab, pe->e);
1592                         kfree(pe);
1593                 }
1594         }
1595 }
1596
1597 /**
1598  * ubi_wl_close - close the wear-leveling unit.
1599  * @ubi: UBI device description object
1600  */
1601 void ubi_wl_close(struct ubi_device *ubi)
1602 {
1603         dbg_wl("disable \"%s\"", ubi->bgt_name);
1604         if (ubi->bgt_thread)
1605                 kthread_stop(ubi->bgt_thread);
1606
1607         dbg_wl("close the UBI wear-leveling unit");
1608
1609         cancel_pending(ubi);
1610         protection_trees_destroy(ubi);
1611         tree_destroy(&ubi->used);
1612         tree_destroy(&ubi->free);
1613         tree_destroy(&ubi->scrub);
1614         kfree(ubi->lookuptbl);
1615 }
1616
1617 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
1618
1619 /**
1620  * paranoid_check_ec - make sure that the erase counter of a physical eraseblock
1621  * is correct.
1622  * @ubi: UBI device description object
1623  * @pnum: the physical eraseblock number to check
1624  * @ec: the erase counter to check
1625  *
1626  * This function returns zero if the erase counter of physical eraseblock @pnum
1627  * is equivalent to @ec, %1 if not, and a negative error code if an error
1628  * occurred.
1629  */
1630 static int paranoid_check_ec(struct ubi_device *ubi, int pnum, int ec)
1631 {
1632         int err;
1633         long long read_ec;
1634         struct ubi_ec_hdr *ec_hdr;
1635
1636         ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
1637         if (!ec_hdr)
1638                 return -ENOMEM;
1639
1640         err = ubi_io_read_ec_hdr(ubi, pnum, ec_hdr, 0);
1641         if (err && err != UBI_IO_BITFLIPS) {
1642                 /* The header does not have to exist */
1643                 err = 0;
1644                 goto out_free;
1645         }
1646
1647         read_ec = be64_to_cpu(ec_hdr->ec);
1648         if (ec != read_ec) {
1649                 ubi_err("paranoid check failed for PEB %d", pnum);
1650                 ubi_err("read EC is %lld, should be %d", read_ec, ec);
1651                 ubi_dbg_dump_stack();
1652                 err = 1;
1653         } else
1654                 err = 0;
1655
1656 out_free:
1657         kfree(ec_hdr);
1658         return err;
1659 }
1660
1661 /**
1662  * paranoid_check_in_wl_tree - make sure that a wear-leveling entry is present
1663  * in a WL RB-tree.
1664  * @e: the wear-leveling entry to check
1665  * @root: the root of the tree
1666  *
1667  * This function returns zero if @e is in the @root RB-tree and %1 if it
1668  * is not.
1669  */
1670 static int paranoid_check_in_wl_tree(struct ubi_wl_entry *e,
1671                                      struct rb_root *root)
1672 {
1673         if (in_wl_tree(e, root))
1674                 return 0;
1675
1676         ubi_err("paranoid check failed for PEB %d, EC %d, RB-tree %p ",
1677                 e->pnum, e->ec, root);
1678         ubi_dbg_dump_stack();
1679         return 1;
1680 }
1681
1682 #endif /* CONFIG_MTD_UBI_DEBUG_PARANOID */