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