UBI: improve comment
[pandora-kernel.git] / 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 in 'ubi_eba_copy_leb()' but
1143                  * the WL unit has not put the PEB to the "used" tree yet, but
1144                  * it is about to do this. So we just set a flag which will
1145                  * tell the WL worker that the PEB is not needed anymore and
1146                  * should be sheduled for erasure.
1147                  */
1148                 dbg_wl("PEB %d is the target of data moving", pnum);
1149                 ubi_assert(!ubi->move_to_put);
1150                 ubi->move_to_put = 1;
1151                 spin_unlock(&ubi->wl_lock);
1152                 return 0;
1153         } else {
1154                 if (in_wl_tree(e, &ubi->used)) {
1155                         paranoid_check_in_wl_tree(e, &ubi->used);
1156                         rb_erase(&e->rb, &ubi->used);
1157                 } else if (in_wl_tree(e, &ubi->scrub)) {
1158                         paranoid_check_in_wl_tree(e, &ubi->scrub);
1159                         rb_erase(&e->rb, &ubi->scrub);
1160                 } else
1161                         prot_tree_del(ubi, e->pnum);
1162         }
1163         spin_unlock(&ubi->wl_lock);
1164
1165         err = schedule_erase(ubi, e, torture);
1166         if (err) {
1167                 spin_lock(&ubi->wl_lock);
1168                 wl_tree_add(e, &ubi->used);
1169                 spin_unlock(&ubi->wl_lock);
1170         }
1171
1172         return err;
1173 }
1174
1175 /**
1176  * ubi_wl_scrub_peb - schedule a physical eraseblock for scrubbing.
1177  * @ubi: UBI device description object
1178  * @pnum: the physical eraseblock to schedule
1179  *
1180  * If a bit-flip in a physical eraseblock is detected, this physical eraseblock
1181  * needs scrubbing. This function schedules a physical eraseblock for
1182  * scrubbing which is done in background. This function returns zero in case of
1183  * success and a negative error code in case of failure.
1184  */
1185 int ubi_wl_scrub_peb(struct ubi_device *ubi, int pnum)
1186 {
1187         struct ubi_wl_entry *e;
1188
1189         ubi_msg("schedule PEB %d for scrubbing", pnum);
1190
1191 retry:
1192         spin_lock(&ubi->wl_lock);
1193         e = ubi->lookuptbl[pnum];
1194         if (e == ubi->move_from || in_wl_tree(e, &ubi->scrub)) {
1195                 spin_unlock(&ubi->wl_lock);
1196                 return 0;
1197         }
1198
1199         if (e == ubi->move_to) {
1200                 /*
1201                  * This physical eraseblock was used to move data to. The data
1202                  * was moved but the PEB was not yet inserted to the proper
1203                  * tree. We should just wait a little and let the WL worker
1204                  * proceed.
1205                  */
1206                 spin_unlock(&ubi->wl_lock);
1207                 dbg_wl("the PEB %d is not in proper tree, retry", pnum);
1208                 yield();
1209                 goto retry;
1210         }
1211
1212         if (in_wl_tree(e, &ubi->used)) {
1213                 paranoid_check_in_wl_tree(e, &ubi->used);
1214                 rb_erase(&e->rb, &ubi->used);
1215         } else
1216                 prot_tree_del(ubi, pnum);
1217
1218         wl_tree_add(e, &ubi->scrub);
1219         spin_unlock(&ubi->wl_lock);
1220
1221         /*
1222          * Technically scrubbing is the same as wear-leveling, so it is done
1223          * by the WL worker.
1224          */
1225         return ensure_wear_leveling(ubi);
1226 }
1227
1228 /**
1229  * ubi_wl_flush - flush all pending works.
1230  * @ubi: UBI device description object
1231  *
1232  * This function returns zero in case of success and a negative error code in
1233  * case of failure.
1234  */
1235 int ubi_wl_flush(struct ubi_device *ubi)
1236 {
1237         int err, pending_count;
1238
1239         pending_count = ubi->works_count;
1240
1241         dbg_wl("flush (%d pending works)", pending_count);
1242
1243         /*
1244          * Erase while the pending works queue is not empty, but not more then
1245          * the number of currently pending works.
1246          */
1247         while (pending_count-- > 0) {
1248                 err = do_work(ubi);
1249                 if (err)
1250                         return err;
1251         }
1252
1253         return 0;
1254 }
1255
1256 /**
1257  * tree_destroy - destroy an RB-tree.
1258  * @root: the root of the tree to destroy
1259  */
1260 static void tree_destroy(struct rb_root *root)
1261 {
1262         struct rb_node *rb;
1263         struct ubi_wl_entry *e;
1264
1265         rb = root->rb_node;
1266         while (rb) {
1267                 if (rb->rb_left)
1268                         rb = rb->rb_left;
1269                 else if (rb->rb_right)
1270                         rb = rb->rb_right;
1271                 else {
1272                         e = rb_entry(rb, struct ubi_wl_entry, rb);
1273
1274                         rb = rb_parent(rb);
1275                         if (rb) {
1276                                 if (rb->rb_left == &e->rb)
1277                                         rb->rb_left = NULL;
1278                                 else
1279                                         rb->rb_right = NULL;
1280                         }
1281
1282                         kmem_cache_free(ubi_wl_entry_slab, e);
1283                 }
1284         }
1285 }
1286
1287 /**
1288  * ubi_thread - UBI background thread.
1289  * @u: the UBI device description object pointer
1290  */
1291 static int ubi_thread(void *u)
1292 {
1293         int failures = 0;
1294         struct ubi_device *ubi = u;
1295
1296         ubi_msg("background thread \"%s\" started, PID %d",
1297                 ubi->bgt_name, task_pid_nr(current));
1298
1299         set_freezable();
1300         for (;;) {
1301                 int err;
1302
1303                 if (kthread_should_stop())
1304                         goto out;
1305
1306                 if (try_to_freeze())
1307                         continue;
1308
1309                 spin_lock(&ubi->wl_lock);
1310                 if (list_empty(&ubi->works) || ubi->ro_mode ||
1311                                !ubi->thread_enabled) {
1312                         set_current_state(TASK_INTERRUPTIBLE);
1313                         spin_unlock(&ubi->wl_lock);
1314                         schedule();
1315                         continue;
1316                 }
1317                 spin_unlock(&ubi->wl_lock);
1318
1319                 err = do_work(ubi);
1320                 if (err) {
1321                         ubi_err("%s: work failed with error code %d",
1322                                 ubi->bgt_name, err);
1323                         if (failures++ > WL_MAX_FAILURES) {
1324                                 /*
1325                                  * Too many failures, disable the thread and
1326                                  * switch to read-only mode.
1327                                  */
1328                                 ubi_msg("%s: %d consecutive failures",
1329                                         ubi->bgt_name, WL_MAX_FAILURES);
1330                                 ubi_ro_mode(ubi);
1331                                 break;
1332                         }
1333                 } else
1334                         failures = 0;
1335
1336                 cond_resched();
1337         }
1338
1339 out:
1340         dbg_wl("background thread \"%s\" is killed", ubi->bgt_name);
1341         return 0;
1342 }
1343
1344 /**
1345  * cancel_pending - cancel all pending works.
1346  * @ubi: UBI device description object
1347  */
1348 static void cancel_pending(struct ubi_device *ubi)
1349 {
1350         while (!list_empty(&ubi->works)) {
1351                 struct ubi_work *wrk;
1352
1353                 wrk = list_entry(ubi->works.next, struct ubi_work, list);
1354                 list_del(&wrk->list);
1355                 wrk->func(ubi, wrk, 1);
1356                 ubi->works_count -= 1;
1357                 ubi_assert(ubi->works_count >= 0);
1358         }
1359 }
1360
1361 /**
1362  * ubi_wl_init_scan - initialize the wear-leveling unit using scanning
1363  * information.
1364  * @ubi: UBI device description object
1365  * @si: scanning information
1366  *
1367  * This function returns zero in case of success, and a negative error code in
1368  * case of failure.
1369  */
1370 int ubi_wl_init_scan(struct ubi_device *ubi, struct ubi_scan_info *si)
1371 {
1372         int err;
1373         struct rb_node *rb1, *rb2;
1374         struct ubi_scan_volume *sv;
1375         struct ubi_scan_leb *seb, *tmp;
1376         struct ubi_wl_entry *e;
1377
1378
1379         ubi->used = ubi->free = ubi->scrub = RB_ROOT;
1380         ubi->prot.pnum = ubi->prot.aec = RB_ROOT;
1381         spin_lock_init(&ubi->wl_lock);
1382         ubi->max_ec = si->max_ec;
1383         INIT_LIST_HEAD(&ubi->works);
1384
1385         sprintf(ubi->bgt_name, UBI_BGT_NAME_PATTERN, ubi->ubi_num);
1386
1387         ubi->bgt_thread = kthread_create(ubi_thread, ubi, ubi->bgt_name);
1388         if (IS_ERR(ubi->bgt_thread)) {
1389                 err = PTR_ERR(ubi->bgt_thread);
1390                 ubi_err("cannot spawn \"%s\", error %d", ubi->bgt_name,
1391                         err);
1392                 return err;
1393         }
1394
1395         err = -ENOMEM;
1396         ubi->lookuptbl = kzalloc(ubi->peb_count * sizeof(void *), GFP_KERNEL);
1397         if (!ubi->lookuptbl)
1398                 goto out_free;
1399
1400         list_for_each_entry_safe(seb, tmp, &si->erase, u.list) {
1401                 cond_resched();
1402
1403                 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1404                 if (!e)
1405                         goto out_free;
1406
1407                 e->pnum = seb->pnum;
1408                 e->ec = seb->ec;
1409                 ubi->lookuptbl[e->pnum] = e;
1410                 if (schedule_erase(ubi, e, 0)) {
1411                         kmem_cache_free(ubi_wl_entry_slab, e);
1412                         goto out_free;
1413                 }
1414         }
1415
1416         list_for_each_entry(seb, &si->free, u.list) {
1417                 cond_resched();
1418
1419                 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1420                 if (!e)
1421                         goto out_free;
1422
1423                 e->pnum = seb->pnum;
1424                 e->ec = seb->ec;
1425                 ubi_assert(e->ec >= 0);
1426                 wl_tree_add(e, &ubi->free);
1427                 ubi->lookuptbl[e->pnum] = e;
1428         }
1429
1430         list_for_each_entry(seb, &si->corr, u.list) {
1431                 cond_resched();
1432
1433                 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1434                 if (!e)
1435                         goto out_free;
1436
1437                 e->pnum = seb->pnum;
1438                 e->ec = seb->ec;
1439                 ubi->lookuptbl[e->pnum] = e;
1440                 if (schedule_erase(ubi, e, 0)) {
1441                         kmem_cache_free(ubi_wl_entry_slab, e);
1442                         goto out_free;
1443                 }
1444         }
1445
1446         ubi_rb_for_each_entry(rb1, sv, &si->volumes, rb) {
1447                 ubi_rb_for_each_entry(rb2, seb, &sv->root, u.rb) {
1448                         cond_resched();
1449
1450                         e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1451                         if (!e)
1452                                 goto out_free;
1453
1454                         e->pnum = seb->pnum;
1455                         e->ec = seb->ec;
1456                         ubi->lookuptbl[e->pnum] = e;
1457                         if (!seb->scrub) {
1458                                 dbg_wl("add PEB %d EC %d to the used tree",
1459                                        e->pnum, e->ec);
1460                                 wl_tree_add(e, &ubi->used);
1461                         } else {
1462                                 dbg_wl("add PEB %d EC %d to the scrub tree",
1463                                        e->pnum, e->ec);
1464                                 wl_tree_add(e, &ubi->scrub);
1465                         }
1466                 }
1467         }
1468
1469         if (ubi->avail_pebs < WL_RESERVED_PEBS) {
1470                 ubi_err("no enough physical eraseblocks (%d, need %d)",
1471                         ubi->avail_pebs, WL_RESERVED_PEBS);
1472                 goto out_free;
1473         }
1474         ubi->avail_pebs -= WL_RESERVED_PEBS;
1475         ubi->rsvd_pebs += WL_RESERVED_PEBS;
1476
1477         /* Schedule wear-leveling if needed */
1478         err = ensure_wear_leveling(ubi);
1479         if (err)
1480                 goto out_free;
1481
1482         return 0;
1483
1484 out_free:
1485         cancel_pending(ubi);
1486         tree_destroy(&ubi->used);
1487         tree_destroy(&ubi->free);
1488         tree_destroy(&ubi->scrub);
1489         kfree(ubi->lookuptbl);
1490         return err;
1491 }
1492
1493 /**
1494  * protection_trees_destroy - destroy the protection RB-trees.
1495  * @ubi: UBI device description object
1496  */
1497 static void protection_trees_destroy(struct ubi_device *ubi)
1498 {
1499         struct rb_node *rb;
1500         struct ubi_wl_prot_entry *pe;
1501
1502         rb = ubi->prot.aec.rb_node;
1503         while (rb) {
1504                 if (rb->rb_left)
1505                         rb = rb->rb_left;
1506                 else if (rb->rb_right)
1507                         rb = rb->rb_right;
1508                 else {
1509                         pe = rb_entry(rb, struct ubi_wl_prot_entry, rb_aec);
1510
1511                         rb = rb_parent(rb);
1512                         if (rb) {
1513                                 if (rb->rb_left == &pe->rb_aec)
1514                                         rb->rb_left = NULL;
1515                                 else
1516                                         rb->rb_right = NULL;
1517                         }
1518
1519                         kmem_cache_free(ubi_wl_entry_slab, pe->e);
1520                         kfree(pe);
1521                 }
1522         }
1523 }
1524
1525 /**
1526  * ubi_wl_close - close the wear-leveling unit.
1527  * @ubi: UBI device description object
1528  */
1529 void ubi_wl_close(struct ubi_device *ubi)
1530 {
1531         dbg_wl("disable \"%s\"", ubi->bgt_name);
1532         if (ubi->bgt_thread)
1533                 kthread_stop(ubi->bgt_thread);
1534
1535         dbg_wl("close the UBI wear-leveling unit");
1536
1537         cancel_pending(ubi);
1538         protection_trees_destroy(ubi);
1539         tree_destroy(&ubi->used);
1540         tree_destroy(&ubi->free);
1541         tree_destroy(&ubi->scrub);
1542         kfree(ubi->lookuptbl);
1543 }
1544
1545 #ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
1546
1547 /**
1548  * paranoid_check_ec - make sure that the erase counter of a physical eraseblock
1549  * is correct.
1550  * @ubi: UBI device description object
1551  * @pnum: the physical eraseblock number to check
1552  * @ec: the erase counter to check
1553  *
1554  * This function returns zero if the erase counter of physical eraseblock @pnum
1555  * is equivalent to @ec, %1 if not, and a negative error code if an error
1556  * occurred.
1557  */
1558 static int paranoid_check_ec(struct ubi_device *ubi, int pnum, int ec)
1559 {
1560         int err;
1561         long long read_ec;
1562         struct ubi_ec_hdr *ec_hdr;
1563
1564         ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
1565         if (!ec_hdr)
1566                 return -ENOMEM;
1567
1568         err = ubi_io_read_ec_hdr(ubi, pnum, ec_hdr, 0);
1569         if (err && err != UBI_IO_BITFLIPS) {
1570                 /* The header does not have to exist */
1571                 err = 0;
1572                 goto out_free;
1573         }
1574
1575         read_ec = be64_to_cpu(ec_hdr->ec);
1576         if (ec != read_ec) {
1577                 ubi_err("paranoid check failed for PEB %d", pnum);
1578                 ubi_err("read EC is %lld, should be %d", read_ec, ec);
1579                 ubi_dbg_dump_stack();
1580                 err = 1;
1581         } else
1582                 err = 0;
1583
1584 out_free:
1585         kfree(ec_hdr);
1586         return err;
1587 }
1588
1589 /**
1590  * paranoid_check_in_wl_tree - make sure that a wear-leveling entry is present
1591  * in a WL RB-tree.
1592  * @e: the wear-leveling entry to check
1593  * @root: the root of the tree
1594  *
1595  * This function returns zero if @e is in the @root RB-tree and %1 if it
1596  * is not.
1597  */
1598 static int paranoid_check_in_wl_tree(struct ubi_wl_entry *e,
1599                                      struct rb_root *root)
1600 {
1601         if (in_wl_tree(e, root))
1602                 return 0;
1603
1604         ubi_err("paranoid check failed for PEB %d, EC %d, RB-tree %p ",
1605                 e->pnum, e->ec, root);
1606         ubi_dbg_dump_stack();
1607         return 1;
1608 }
1609
1610 #endif /* CONFIG_MTD_UBI_DEBUG_PARANOID */