Linux-libre 5.3.12-gnu
[librecmc/linux-libre.git] / drivers / mtd / ubi / wl.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines Corp., 2006
4  *
5  * Authors: Artem Bityutskiy (Битюцкий Артём), Thomas Gleixner
6  */
7
8 /*
9  * UBI wear-leveling sub-system.
10  *
11  * This sub-system is responsible for wear-leveling. It works in terms of
12  * physical eraseblocks and erase counters and knows nothing about logical
13  * eraseblocks, volumes, etc. From this sub-system's perspective all physical
14  * eraseblocks are of two types - used and free. Used physical eraseblocks are
15  * those that were "get" by the 'ubi_wl_get_peb()' function, and free physical
16  * eraseblocks are those that were put by the 'ubi_wl_put_peb()' function.
17  *
18  * Physical eraseblocks returned by 'ubi_wl_get_peb()' have only erase counter
19  * header. The rest of the physical eraseblock contains only %0xFF bytes.
20  *
21  * When physical eraseblocks are returned to the WL sub-system by means of the
22  * 'ubi_wl_put_peb()' function, they are scheduled for erasure. The erasure is
23  * done asynchronously in context of the per-UBI device background thread,
24  * which is also managed by the WL sub-system.
25  *
26  * The wear-leveling is ensured by means of moving the contents of used
27  * physical eraseblocks with low erase counter to free physical eraseblocks
28  * with high erase counter.
29  *
30  * If the WL sub-system fails to erase a physical eraseblock, it marks it as
31  * bad.
32  *
33  * This sub-system is also responsible for scrubbing. If a bit-flip is detected
34  * in a physical eraseblock, it has to be moved. Technically this is the same
35  * as moving it for wear-leveling reasons.
36  *
37  * As it was said, for the UBI sub-system all physical eraseblocks are either
38  * "free" or "used". Free eraseblock are kept in the @wl->free RB-tree, while
39  * used eraseblocks are kept in @wl->used, @wl->erroneous, or @wl->scrub
40  * RB-trees, as well as (temporarily) in the @wl->pq queue.
41  *
42  * When the WL sub-system returns a physical eraseblock, the physical
43  * eraseblock is protected from being moved for some "time". For this reason,
44  * the physical eraseblock is not directly moved from the @wl->free tree to the
45  * @wl->used tree. There is a protection queue in between where this
46  * physical eraseblock is temporarily stored (@wl->pq).
47  *
48  * All this protection stuff is needed because:
49  *  o we don't want to move physical eraseblocks just after we have given them
50  *    to the user; instead, we first want to let users fill them up with data;
51  *
52  *  o there is a chance that the user will put the physical eraseblock very
53  *    soon, so it makes sense not to move it for some time, but wait.
54  *
55  * Physical eraseblocks stay protected only for limited time. But the "time" is
56  * measured in erase cycles in this case. This is implemented with help of the
57  * protection queue. Eraseblocks are put to the tail of this queue when they
58  * are returned by the 'ubi_wl_get_peb()', and eraseblocks are removed from the
59  * head of the queue on each erase operation (for any eraseblock). So the
60  * length of the queue defines how may (global) erase cycles PEBs are protected.
61  *
62  * To put it differently, each physical eraseblock has 2 main states: free and
63  * used. The former state corresponds to the @wl->free tree. The latter state
64  * is split up on several sub-states:
65  * o the WL movement is allowed (@wl->used tree);
66  * o the WL movement is disallowed (@wl->erroneous) because the PEB is
67  *   erroneous - e.g., there was a read error;
68  * o the WL movement is temporarily prohibited (@wl->pq queue);
69  * o scrubbing is needed (@wl->scrub tree).
70  *
71  * Depending on the sub-state, wear-leveling entries of the used physical
72  * eraseblocks may be kept in one of those structures.
73  *
74  * Note, in this implementation, we keep a small in-RAM object for each physical
75  * eraseblock. This is surely not a scalable solution. But it appears to be good
76  * enough for moderately large flashes and it is simple. In future, one may
77  * re-work this sub-system and make it more scalable.
78  *
79  * At the moment this sub-system does not utilize the sequence number, which
80  * was introduced relatively recently. But it would be wise to do this because
81  * the sequence number of a logical eraseblock characterizes how old is it. For
82  * example, when we move a PEB with low erase counter, and we need to pick the
83  * target PEB, we pick a PEB with the highest EC if our PEB is "old" and we
84  * pick target PEB with an average EC if our PEB is not very "old". This is a
85  * room for future re-works of the WL sub-system.
86  */
87
88 #include <linux/slab.h>
89 #include <linux/crc32.h>
90 #include <linux/freezer.h>
91 #include <linux/kthread.h>
92 #include "ubi.h"
93 #include "wl.h"
94
95 /* Number of physical eraseblocks reserved for wear-leveling purposes */
96 #define WL_RESERVED_PEBS 1
97
98 /*
99  * Maximum difference between two erase counters. If this threshold is
100  * exceeded, the WL sub-system starts moving data from used physical
101  * eraseblocks with low erase counter to free physical eraseblocks with high
102  * erase counter.
103  */
104 #define UBI_WL_THRESHOLD CONFIG_MTD_UBI_WL_THRESHOLD
105
106 /*
107  * When a physical eraseblock is moved, the WL sub-system has to pick the target
108  * physical eraseblock to move to. The simplest way would be just to pick the
109  * one with the highest erase counter. But in certain workloads this could lead
110  * to an unlimited wear of one or few physical eraseblock. Indeed, imagine a
111  * situation when the picked physical eraseblock is constantly erased after the
112  * data is written to it. So, we have a constant which limits the highest erase
113  * counter of the free physical eraseblock to pick. Namely, the WL sub-system
114  * does not pick eraseblocks with erase counter greater than the lowest erase
115  * counter plus %WL_FREE_MAX_DIFF.
116  */
117 #define WL_FREE_MAX_DIFF (2*UBI_WL_THRESHOLD)
118
119 /*
120  * Maximum number of consecutive background thread failures which is enough to
121  * switch to read-only mode.
122  */
123 #define WL_MAX_FAILURES 32
124
125 static int self_check_ec(struct ubi_device *ubi, int pnum, int ec);
126 static int self_check_in_wl_tree(const struct ubi_device *ubi,
127                                  struct ubi_wl_entry *e, struct rb_root *root);
128 static int self_check_in_pq(const struct ubi_device *ubi,
129                             struct ubi_wl_entry *e);
130
131 /**
132  * wl_tree_add - add a wear-leveling entry to a WL RB-tree.
133  * @e: the wear-leveling entry to add
134  * @root: the root of the tree
135  *
136  * Note, we use (erase counter, physical eraseblock number) pairs as keys in
137  * the @ubi->used and @ubi->free RB-trees.
138  */
139 static void wl_tree_add(struct ubi_wl_entry *e, struct rb_root *root)
140 {
141         struct rb_node **p, *parent = NULL;
142
143         p = &root->rb_node;
144         while (*p) {
145                 struct ubi_wl_entry *e1;
146
147                 parent = *p;
148                 e1 = rb_entry(parent, struct ubi_wl_entry, u.rb);
149
150                 if (e->ec < e1->ec)
151                         p = &(*p)->rb_left;
152                 else if (e->ec > e1->ec)
153                         p = &(*p)->rb_right;
154                 else {
155                         ubi_assert(e->pnum != e1->pnum);
156                         if (e->pnum < e1->pnum)
157                                 p = &(*p)->rb_left;
158                         else
159                                 p = &(*p)->rb_right;
160                 }
161         }
162
163         rb_link_node(&e->u.rb, parent, p);
164         rb_insert_color(&e->u.rb, root);
165 }
166
167 /**
168  * wl_tree_destroy - destroy a wear-leveling entry.
169  * @ubi: UBI device description object
170  * @e: the wear-leveling entry to add
171  *
172  * This function destroys a wear leveling entry and removes
173  * the reference from the lookup table.
174  */
175 static void wl_entry_destroy(struct ubi_device *ubi, struct ubi_wl_entry *e)
176 {
177         ubi->lookuptbl[e->pnum] = NULL;
178         kmem_cache_free(ubi_wl_entry_slab, e);
179 }
180
181 /**
182  * do_work - do one pending work.
183  * @ubi: UBI device description object
184  *
185  * This function returns zero in case of success and a negative error code in
186  * case of failure.
187  */
188 static int do_work(struct ubi_device *ubi)
189 {
190         int err;
191         struct ubi_work *wrk;
192
193         cond_resched();
194
195         /*
196          * @ubi->work_sem is used to synchronize with the workers. Workers take
197          * it in read mode, so many of them may be doing works at a time. But
198          * the queue flush code has to be sure the whole queue of works is
199          * done, and it takes the mutex in write mode.
200          */
201         down_read(&ubi->work_sem);
202         spin_lock(&ubi->wl_lock);
203         if (list_empty(&ubi->works)) {
204                 spin_unlock(&ubi->wl_lock);
205                 up_read(&ubi->work_sem);
206                 return 0;
207         }
208
209         wrk = list_entry(ubi->works.next, struct ubi_work, list);
210         list_del(&wrk->list);
211         ubi->works_count -= 1;
212         ubi_assert(ubi->works_count >= 0);
213         spin_unlock(&ubi->wl_lock);
214
215         /*
216          * Call the worker function. Do not touch the work structure
217          * after this call as it will have been freed or reused by that
218          * time by the worker function.
219          */
220         err = wrk->func(ubi, wrk, 0);
221         if (err)
222                 ubi_err(ubi, "work failed with error code %d", err);
223         up_read(&ubi->work_sem);
224
225         return err;
226 }
227
228 /**
229  * in_wl_tree - check if wear-leveling entry is present in a WL RB-tree.
230  * @e: the wear-leveling entry to check
231  * @root: the root of the tree
232  *
233  * This function returns non-zero if @e is in the @root RB-tree and zero if it
234  * is not.
235  */
236 static int in_wl_tree(struct ubi_wl_entry *e, struct rb_root *root)
237 {
238         struct rb_node *p;
239
240         p = root->rb_node;
241         while (p) {
242                 struct ubi_wl_entry *e1;
243
244                 e1 = rb_entry(p, struct ubi_wl_entry, u.rb);
245
246                 if (e->pnum == e1->pnum) {
247                         ubi_assert(e == e1);
248                         return 1;
249                 }
250
251                 if (e->ec < e1->ec)
252                         p = p->rb_left;
253                 else if (e->ec > e1->ec)
254                         p = p->rb_right;
255                 else {
256                         ubi_assert(e->pnum != e1->pnum);
257                         if (e->pnum < e1->pnum)
258                                 p = p->rb_left;
259                         else
260                                 p = p->rb_right;
261                 }
262         }
263
264         return 0;
265 }
266
267 /**
268  * in_pq - check if a wear-leveling entry is present in the protection queue.
269  * @ubi: UBI device description object
270  * @e: the wear-leveling entry to check
271  *
272  * This function returns non-zero if @e is in the protection queue and zero
273  * if it is not.
274  */
275 static inline int in_pq(const struct ubi_device *ubi, struct ubi_wl_entry *e)
276 {
277         struct ubi_wl_entry *p;
278         int i;
279
280         for (i = 0; i < UBI_PROT_QUEUE_LEN; ++i)
281                 list_for_each_entry(p, &ubi->pq[i], u.list)
282                         if (p == e)
283                                 return 1;
284
285         return 0;
286 }
287
288 /**
289  * prot_queue_add - add physical eraseblock to the protection queue.
290  * @ubi: UBI device description object
291  * @e: the physical eraseblock to add
292  *
293  * This function adds @e to the tail of the protection queue @ubi->pq, where
294  * @e will stay for %UBI_PROT_QUEUE_LEN erase operations and will be
295  * temporarily protected from the wear-leveling worker. Note, @wl->lock has to
296  * be locked.
297  */
298 static void prot_queue_add(struct ubi_device *ubi, struct ubi_wl_entry *e)
299 {
300         int pq_tail = ubi->pq_head - 1;
301
302         if (pq_tail < 0)
303                 pq_tail = UBI_PROT_QUEUE_LEN - 1;
304         ubi_assert(pq_tail >= 0 && pq_tail < UBI_PROT_QUEUE_LEN);
305         list_add_tail(&e->u.list, &ubi->pq[pq_tail]);
306         dbg_wl("added PEB %d EC %d to the protection queue", e->pnum, e->ec);
307 }
308
309 /**
310  * find_wl_entry - find wear-leveling entry closest to certain erase counter.
311  * @ubi: UBI device description object
312  * @root: the RB-tree where to look for
313  * @diff: maximum possible difference from the smallest erase counter
314  *
315  * This function looks for a wear leveling entry with erase counter closest to
316  * min + @diff, where min is the smallest erase counter.
317  */
318 static struct ubi_wl_entry *find_wl_entry(struct ubi_device *ubi,
319                                           struct rb_root *root, int diff)
320 {
321         struct rb_node *p;
322         struct ubi_wl_entry *e, *prev_e = NULL;
323         int max;
324
325         e = rb_entry(rb_first(root), struct ubi_wl_entry, u.rb);
326         max = e->ec + diff;
327
328         p = root->rb_node;
329         while (p) {
330                 struct ubi_wl_entry *e1;
331
332                 e1 = rb_entry(p, struct ubi_wl_entry, u.rb);
333                 if (e1->ec >= max)
334                         p = p->rb_left;
335                 else {
336                         p = p->rb_right;
337                         prev_e = e;
338                         e = e1;
339                 }
340         }
341
342         /* If no fastmap has been written and this WL entry can be used
343          * as anchor PEB, hold it back and return the second best WL entry
344          * such that fastmap can use the anchor PEB later. */
345         if (prev_e && !ubi->fm_disabled &&
346             !ubi->fm && e->pnum < UBI_FM_MAX_START)
347                 return prev_e;
348
349         return e;
350 }
351
352 /**
353  * find_mean_wl_entry - find wear-leveling entry with medium erase counter.
354  * @ubi: UBI device description object
355  * @root: the RB-tree where to look for
356  *
357  * This function looks for a wear leveling entry with medium erase counter,
358  * but not greater or equivalent than the lowest erase counter plus
359  * %WL_FREE_MAX_DIFF/2.
360  */
361 static struct ubi_wl_entry *find_mean_wl_entry(struct ubi_device *ubi,
362                                                struct rb_root *root)
363 {
364         struct ubi_wl_entry *e, *first, *last;
365
366         first = rb_entry(rb_first(root), struct ubi_wl_entry, u.rb);
367         last = rb_entry(rb_last(root), struct ubi_wl_entry, u.rb);
368
369         if (last->ec - first->ec < WL_FREE_MAX_DIFF) {
370                 e = rb_entry(root->rb_node, struct ubi_wl_entry, u.rb);
371
372                 /* If no fastmap has been written and this WL entry can be used
373                  * as anchor PEB, hold it back and return the second best
374                  * WL entry such that fastmap can use the anchor PEB later. */
375                 e = may_reserve_for_fm(ubi, e, root);
376         } else
377                 e = find_wl_entry(ubi, root, WL_FREE_MAX_DIFF/2);
378
379         return e;
380 }
381
382 /**
383  * wl_get_wle - get a mean wl entry to be used by ubi_wl_get_peb() or
384  * refill_wl_user_pool().
385  * @ubi: UBI device description object
386  *
387  * This function returns a a wear leveling entry in case of success and
388  * NULL in case of failure.
389  */
390 static struct ubi_wl_entry *wl_get_wle(struct ubi_device *ubi)
391 {
392         struct ubi_wl_entry *e;
393
394         e = find_mean_wl_entry(ubi, &ubi->free);
395         if (!e) {
396                 ubi_err(ubi, "no free eraseblocks");
397                 return NULL;
398         }
399
400         self_check_in_wl_tree(ubi, e, &ubi->free);
401
402         /*
403          * Move the physical eraseblock to the protection queue where it will
404          * be protected from being moved for some time.
405          */
406         rb_erase(&e->u.rb, &ubi->free);
407         ubi->free_count--;
408         dbg_wl("PEB %d EC %d", e->pnum, e->ec);
409
410         return e;
411 }
412
413 /**
414  * prot_queue_del - remove a physical eraseblock from the protection queue.
415  * @ubi: UBI device description object
416  * @pnum: the physical eraseblock to remove
417  *
418  * This function deletes PEB @pnum from the protection queue and returns zero
419  * in case of success and %-ENODEV if the PEB was not found.
420  */
421 static int prot_queue_del(struct ubi_device *ubi, int pnum)
422 {
423         struct ubi_wl_entry *e;
424
425         e = ubi->lookuptbl[pnum];
426         if (!e)
427                 return -ENODEV;
428
429         if (self_check_in_pq(ubi, e))
430                 return -ENODEV;
431
432         list_del(&e->u.list);
433         dbg_wl("deleted PEB %d from the protection queue", e->pnum);
434         return 0;
435 }
436
437 /**
438  * sync_erase - synchronously erase a physical eraseblock.
439  * @ubi: UBI device description object
440  * @e: the the physical eraseblock to erase
441  * @torture: if the physical eraseblock has to be tortured
442  *
443  * This function returns zero in case of success and a negative error code in
444  * case of failure.
445  */
446 static int sync_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
447                       int torture)
448 {
449         int err;
450         struct ubi_ec_hdr *ec_hdr;
451         unsigned long long ec = e->ec;
452
453         dbg_wl("erase PEB %d, old EC %llu", e->pnum, ec);
454
455         err = self_check_ec(ubi, e->pnum, e->ec);
456         if (err)
457                 return -EINVAL;
458
459         ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
460         if (!ec_hdr)
461                 return -ENOMEM;
462
463         err = ubi_io_sync_erase(ubi, e->pnum, torture);
464         if (err < 0)
465                 goto out_free;
466
467         ec += err;
468         if (ec > UBI_MAX_ERASECOUNTER) {
469                 /*
470                  * Erase counter overflow. Upgrade UBI and use 64-bit
471                  * erase counters internally.
472                  */
473                 ubi_err(ubi, "erase counter overflow at PEB %d, EC %llu",
474                         e->pnum, ec);
475                 err = -EINVAL;
476                 goto out_free;
477         }
478
479         dbg_wl("erased PEB %d, new EC %llu", e->pnum, ec);
480
481         ec_hdr->ec = cpu_to_be64(ec);
482
483         err = ubi_io_write_ec_hdr(ubi, e->pnum, ec_hdr);
484         if (err)
485                 goto out_free;
486
487         e->ec = ec;
488         spin_lock(&ubi->wl_lock);
489         if (e->ec > ubi->max_ec)
490                 ubi->max_ec = e->ec;
491         spin_unlock(&ubi->wl_lock);
492
493 out_free:
494         kfree(ec_hdr);
495         return err;
496 }
497
498 /**
499  * serve_prot_queue - check if it is time to stop protecting PEBs.
500  * @ubi: UBI device description object
501  *
502  * This function is called after each erase operation and removes PEBs from the
503  * tail of the protection queue. These PEBs have been protected for long enough
504  * and should be moved to the used tree.
505  */
506 static void serve_prot_queue(struct ubi_device *ubi)
507 {
508         struct ubi_wl_entry *e, *tmp;
509         int count;
510
511         /*
512          * There may be several protected physical eraseblock to remove,
513          * process them all.
514          */
515 repeat:
516         count = 0;
517         spin_lock(&ubi->wl_lock);
518         list_for_each_entry_safe(e, tmp, &ubi->pq[ubi->pq_head], u.list) {
519                 dbg_wl("PEB %d EC %d protection over, move to used tree",
520                         e->pnum, e->ec);
521
522                 list_del(&e->u.list);
523                 wl_tree_add(e, &ubi->used);
524                 if (count++ > 32) {
525                         /*
526                          * Let's be nice and avoid holding the spinlock for
527                          * too long.
528                          */
529                         spin_unlock(&ubi->wl_lock);
530                         cond_resched();
531                         goto repeat;
532                 }
533         }
534
535         ubi->pq_head += 1;
536         if (ubi->pq_head == UBI_PROT_QUEUE_LEN)
537                 ubi->pq_head = 0;
538         ubi_assert(ubi->pq_head >= 0 && ubi->pq_head < UBI_PROT_QUEUE_LEN);
539         spin_unlock(&ubi->wl_lock);
540 }
541
542 /**
543  * __schedule_ubi_work - schedule a work.
544  * @ubi: UBI device description object
545  * @wrk: the work to schedule
546  *
547  * This function adds a work defined by @wrk to the tail of the pending works
548  * list. Can only be used if ubi->work_sem is already held in read mode!
549  */
550 static void __schedule_ubi_work(struct ubi_device *ubi, struct ubi_work *wrk)
551 {
552         spin_lock(&ubi->wl_lock);
553         list_add_tail(&wrk->list, &ubi->works);
554         ubi_assert(ubi->works_count >= 0);
555         ubi->works_count += 1;
556         if (ubi->thread_enabled && !ubi_dbg_is_bgt_disabled(ubi))
557                 wake_up_process(ubi->bgt_thread);
558         spin_unlock(&ubi->wl_lock);
559 }
560
561 /**
562  * schedule_ubi_work - schedule a work.
563  * @ubi: UBI device description object
564  * @wrk: the work to schedule
565  *
566  * This function adds a work defined by @wrk to the tail of the pending works
567  * list.
568  */
569 static void schedule_ubi_work(struct ubi_device *ubi, struct ubi_work *wrk)
570 {
571         down_read(&ubi->work_sem);
572         __schedule_ubi_work(ubi, wrk);
573         up_read(&ubi->work_sem);
574 }
575
576 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
577                         int shutdown);
578
579 /**
580  * schedule_erase - schedule an erase work.
581  * @ubi: UBI device description object
582  * @e: the WL entry of the physical eraseblock to erase
583  * @vol_id: the volume ID that last used this PEB
584  * @lnum: the last used logical eraseblock number for the PEB
585  * @torture: if the physical eraseblock has to be tortured
586  *
587  * This function returns zero in case of success and a %-ENOMEM in case of
588  * failure.
589  */
590 static int schedule_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
591                           int vol_id, int lnum, int torture, bool nested)
592 {
593         struct ubi_work *wl_wrk;
594
595         ubi_assert(e);
596
597         dbg_wl("schedule erasure of PEB %d, EC %d, torture %d",
598                e->pnum, e->ec, torture);
599
600         wl_wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
601         if (!wl_wrk)
602                 return -ENOMEM;
603
604         wl_wrk->func = &erase_worker;
605         wl_wrk->e = e;
606         wl_wrk->vol_id = vol_id;
607         wl_wrk->lnum = lnum;
608         wl_wrk->torture = torture;
609
610         if (nested)
611                 __schedule_ubi_work(ubi, wl_wrk);
612         else
613                 schedule_ubi_work(ubi, wl_wrk);
614         return 0;
615 }
616
617 static int __erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk);
618 /**
619  * do_sync_erase - run the erase worker synchronously.
620  * @ubi: UBI device description object
621  * @e: the WL entry of the physical eraseblock to erase
622  * @vol_id: the volume ID that last used this PEB
623  * @lnum: the last used logical eraseblock number for the PEB
624  * @torture: if the physical eraseblock has to be tortured
625  *
626  */
627 static int do_sync_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
628                          int vol_id, int lnum, int torture)
629 {
630         struct ubi_work wl_wrk;
631
632         dbg_wl("sync erase of PEB %i", e->pnum);
633
634         wl_wrk.e = e;
635         wl_wrk.vol_id = vol_id;
636         wl_wrk.lnum = lnum;
637         wl_wrk.torture = torture;
638
639         return __erase_worker(ubi, &wl_wrk);
640 }
641
642 static int ensure_wear_leveling(struct ubi_device *ubi, int nested);
643 /**
644  * wear_leveling_worker - wear-leveling worker function.
645  * @ubi: UBI device description object
646  * @wrk: the work object
647  * @shutdown: non-zero if the worker has to free memory and exit
648  * because the WL-subsystem is shutting down
649  *
650  * This function copies a more worn out physical eraseblock to a less worn out
651  * one. Returns zero in case of success and a negative error code in case of
652  * failure.
653  */
654 static int wear_leveling_worker(struct ubi_device *ubi, struct ubi_work *wrk,
655                                 int shutdown)
656 {
657         int err, scrubbing = 0, torture = 0, protect = 0, erroneous = 0;
658         int erase = 0, keep = 0, vol_id = -1, lnum = -1;
659 #ifdef CONFIG_MTD_UBI_FASTMAP
660         int anchor = wrk->anchor;
661 #endif
662         struct ubi_wl_entry *e1, *e2;
663         struct ubi_vid_io_buf *vidb;
664         struct ubi_vid_hdr *vid_hdr;
665         int dst_leb_clean = 0;
666
667         kfree(wrk);
668         if (shutdown)
669                 return 0;
670
671         vidb = ubi_alloc_vid_buf(ubi, GFP_NOFS);
672         if (!vidb)
673                 return -ENOMEM;
674
675         vid_hdr = ubi_get_vid_hdr(vidb);
676
677         down_read(&ubi->fm_eba_sem);
678         mutex_lock(&ubi->move_mutex);
679         spin_lock(&ubi->wl_lock);
680         ubi_assert(!ubi->move_from && !ubi->move_to);
681         ubi_assert(!ubi->move_to_put);
682
683         if (!ubi->free.rb_node ||
684             (!ubi->used.rb_node && !ubi->scrub.rb_node)) {
685                 /*
686                  * No free physical eraseblocks? Well, they must be waiting in
687                  * the queue to be erased. Cancel movement - it will be
688                  * triggered again when a free physical eraseblock appears.
689                  *
690                  * No used physical eraseblocks? They must be temporarily
691                  * protected from being moved. They will be moved to the
692                  * @ubi->used tree later and the wear-leveling will be
693                  * triggered again.
694                  */
695                 dbg_wl("cancel WL, a list is empty: free %d, used %d",
696                        !ubi->free.rb_node, !ubi->used.rb_node);
697                 goto out_cancel;
698         }
699
700 #ifdef CONFIG_MTD_UBI_FASTMAP
701         /* Check whether we need to produce an anchor PEB */
702         if (!anchor)
703                 anchor = !anchor_pebs_available(&ubi->free);
704
705         if (anchor) {
706                 e1 = find_anchor_wl_entry(&ubi->used);
707                 if (!e1)
708                         goto out_cancel;
709                 e2 = get_peb_for_wl(ubi);
710                 if (!e2)
711                         goto out_cancel;
712
713                 self_check_in_wl_tree(ubi, e1, &ubi->used);
714                 rb_erase(&e1->u.rb, &ubi->used);
715                 dbg_wl("anchor-move PEB %d to PEB %d", e1->pnum, e2->pnum);
716         } else if (!ubi->scrub.rb_node) {
717 #else
718         if (!ubi->scrub.rb_node) {
719 #endif
720                 /*
721                  * Now pick the least worn-out used physical eraseblock and a
722                  * highly worn-out free physical eraseblock. If the erase
723                  * counters differ much enough, start wear-leveling.
724                  */
725                 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, u.rb);
726                 e2 = get_peb_for_wl(ubi);
727                 if (!e2)
728                         goto out_cancel;
729
730                 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD)) {
731                         dbg_wl("no WL needed: min used EC %d, max free EC %d",
732                                e1->ec, e2->ec);
733
734                         /* Give the unused PEB back */
735                         wl_tree_add(e2, &ubi->free);
736                         ubi->free_count++;
737                         goto out_cancel;
738                 }
739                 self_check_in_wl_tree(ubi, e1, &ubi->used);
740                 rb_erase(&e1->u.rb, &ubi->used);
741                 dbg_wl("move PEB %d EC %d to PEB %d EC %d",
742                        e1->pnum, e1->ec, e2->pnum, e2->ec);
743         } else {
744                 /* Perform scrubbing */
745                 scrubbing = 1;
746                 e1 = rb_entry(rb_first(&ubi->scrub), struct ubi_wl_entry, u.rb);
747                 e2 = get_peb_for_wl(ubi);
748                 if (!e2)
749                         goto out_cancel;
750
751                 self_check_in_wl_tree(ubi, e1, &ubi->scrub);
752                 rb_erase(&e1->u.rb, &ubi->scrub);
753                 dbg_wl("scrub PEB %d to PEB %d", e1->pnum, e2->pnum);
754         }
755
756         ubi->move_from = e1;
757         ubi->move_to = e2;
758         spin_unlock(&ubi->wl_lock);
759
760         /*
761          * Now we are going to copy physical eraseblock @e1->pnum to @e2->pnum.
762          * We so far do not know which logical eraseblock our physical
763          * eraseblock (@e1) belongs to. We have to read the volume identifier
764          * header first.
765          *
766          * Note, we are protected from this PEB being unmapped and erased. The
767          * 'ubi_wl_put_peb()' would wait for moving to be finished if the PEB
768          * which is being moved was unmapped.
769          */
770
771         err = ubi_io_read_vid_hdr(ubi, e1->pnum, vidb, 0);
772         if (err && err != UBI_IO_BITFLIPS) {
773                 dst_leb_clean = 1;
774                 if (err == UBI_IO_FF) {
775                         /*
776                          * We are trying to move PEB without a VID header. UBI
777                          * always write VID headers shortly after the PEB was
778                          * given, so we have a situation when it has not yet
779                          * had a chance to write it, because it was preempted.
780                          * So add this PEB to the protection queue so far,
781                          * because presumably more data will be written there
782                          * (including the missing VID header), and then we'll
783                          * move it.
784                          */
785                         dbg_wl("PEB %d has no VID header", e1->pnum);
786                         protect = 1;
787                         goto out_not_moved;
788                 } else if (err == UBI_IO_FF_BITFLIPS) {
789                         /*
790                          * The same situation as %UBI_IO_FF, but bit-flips were
791                          * detected. It is better to schedule this PEB for
792                          * scrubbing.
793                          */
794                         dbg_wl("PEB %d has no VID header but has bit-flips",
795                                e1->pnum);
796                         scrubbing = 1;
797                         goto out_not_moved;
798                 } else if (ubi->fast_attach && err == UBI_IO_BAD_HDR_EBADMSG) {
799                         /*
800                          * While a full scan would detect interrupted erasures
801                          * at attach time we can face them here when attached from
802                          * Fastmap.
803                          */
804                         dbg_wl("PEB %d has ECC errors, maybe from an interrupted erasure",
805                                e1->pnum);
806                         erase = 1;
807                         goto out_not_moved;
808                 }
809
810                 ubi_err(ubi, "error %d while reading VID header from PEB %d",
811                         err, e1->pnum);
812                 goto out_error;
813         }
814
815         vol_id = be32_to_cpu(vid_hdr->vol_id);
816         lnum = be32_to_cpu(vid_hdr->lnum);
817
818         err = ubi_eba_copy_leb(ubi, e1->pnum, e2->pnum, vidb);
819         if (err) {
820                 if (err == MOVE_CANCEL_RACE) {
821                         /*
822                          * The LEB has not been moved because the volume is
823                          * being deleted or the PEB has been put meanwhile. We
824                          * should prevent this PEB from being selected for
825                          * wear-leveling movement again, so put it to the
826                          * protection queue.
827                          */
828                         protect = 1;
829                         dst_leb_clean = 1;
830                         goto out_not_moved;
831                 }
832                 if (err == MOVE_RETRY) {
833                         scrubbing = 1;
834                         dst_leb_clean = 1;
835                         goto out_not_moved;
836                 }
837                 if (err == MOVE_TARGET_BITFLIPS || err == MOVE_TARGET_WR_ERR ||
838                     err == MOVE_TARGET_RD_ERR) {
839                         /*
840                          * Target PEB had bit-flips or write error - torture it.
841                          */
842                         torture = 1;
843                         keep = 1;
844                         goto out_not_moved;
845                 }
846
847                 if (err == MOVE_SOURCE_RD_ERR) {
848                         /*
849                          * An error happened while reading the source PEB. Do
850                          * not switch to R/O mode in this case, and give the
851                          * upper layers a possibility to recover from this,
852                          * e.g. by unmapping corresponding LEB. Instead, just
853                          * put this PEB to the @ubi->erroneous list to prevent
854                          * UBI from trying to move it over and over again.
855                          */
856                         if (ubi->erroneous_peb_count > ubi->max_erroneous) {
857                                 ubi_err(ubi, "too many erroneous eraseblocks (%d)",
858                                         ubi->erroneous_peb_count);
859                                 goto out_error;
860                         }
861                         dst_leb_clean = 1;
862                         erroneous = 1;
863                         goto out_not_moved;
864                 }
865
866                 if (err < 0)
867                         goto out_error;
868
869                 ubi_assert(0);
870         }
871
872         /* The PEB has been successfully moved */
873         if (scrubbing)
874                 ubi_msg(ubi, "scrubbed PEB %d (LEB %d:%d), data moved to PEB %d",
875                         e1->pnum, vol_id, lnum, e2->pnum);
876         ubi_free_vid_buf(vidb);
877
878         spin_lock(&ubi->wl_lock);
879         if (!ubi->move_to_put) {
880                 wl_tree_add(e2, &ubi->used);
881                 e2 = NULL;
882         }
883         ubi->move_from = ubi->move_to = NULL;
884         ubi->move_to_put = ubi->wl_scheduled = 0;
885         spin_unlock(&ubi->wl_lock);
886
887         err = do_sync_erase(ubi, e1, vol_id, lnum, 0);
888         if (err) {
889                 if (e2)
890                         wl_entry_destroy(ubi, e2);
891                 goto out_ro;
892         }
893
894         if (e2) {
895                 /*
896                  * Well, the target PEB was put meanwhile, schedule it for
897                  * erasure.
898                  */
899                 dbg_wl("PEB %d (LEB %d:%d) was put meanwhile, erase",
900                        e2->pnum, vol_id, lnum);
901                 err = do_sync_erase(ubi, e2, vol_id, lnum, 0);
902                 if (err)
903                         goto out_ro;
904         }
905
906         dbg_wl("done");
907         mutex_unlock(&ubi->move_mutex);
908         up_read(&ubi->fm_eba_sem);
909         return 0;
910
911         /*
912          * For some reasons the LEB was not moved, might be an error, might be
913          * something else. @e1 was not changed, so return it back. @e2 might
914          * have been changed, schedule it for erasure.
915          */
916 out_not_moved:
917         if (vol_id != -1)
918                 dbg_wl("cancel moving PEB %d (LEB %d:%d) to PEB %d (%d)",
919                        e1->pnum, vol_id, lnum, e2->pnum, err);
920         else
921                 dbg_wl("cancel moving PEB %d to PEB %d (%d)",
922                        e1->pnum, e2->pnum, err);
923         spin_lock(&ubi->wl_lock);
924         if (protect)
925                 prot_queue_add(ubi, e1);
926         else if (erroneous) {
927                 wl_tree_add(e1, &ubi->erroneous);
928                 ubi->erroneous_peb_count += 1;
929         } else if (scrubbing)
930                 wl_tree_add(e1, &ubi->scrub);
931         else if (keep)
932                 wl_tree_add(e1, &ubi->used);
933         if (dst_leb_clean) {
934                 wl_tree_add(e2, &ubi->free);
935                 ubi->free_count++;
936         }
937
938         ubi_assert(!ubi->move_to_put);
939         ubi->move_from = ubi->move_to = NULL;
940         ubi->wl_scheduled = 0;
941         spin_unlock(&ubi->wl_lock);
942
943         ubi_free_vid_buf(vidb);
944         if (dst_leb_clean) {
945                 ensure_wear_leveling(ubi, 1);
946         } else {
947                 err = do_sync_erase(ubi, e2, vol_id, lnum, torture);
948                 if (err)
949                         goto out_ro;
950         }
951
952         if (erase) {
953                 err = do_sync_erase(ubi, e1, vol_id, lnum, 1);
954                 if (err)
955                         goto out_ro;
956         }
957
958         mutex_unlock(&ubi->move_mutex);
959         up_read(&ubi->fm_eba_sem);
960         return 0;
961
962 out_error:
963         if (vol_id != -1)
964                 ubi_err(ubi, "error %d while moving PEB %d to PEB %d",
965                         err, e1->pnum, e2->pnum);
966         else
967                 ubi_err(ubi, "error %d while moving PEB %d (LEB %d:%d) to PEB %d",
968                         err, e1->pnum, vol_id, lnum, e2->pnum);
969         spin_lock(&ubi->wl_lock);
970         ubi->move_from = ubi->move_to = NULL;
971         ubi->move_to_put = ubi->wl_scheduled = 0;
972         spin_unlock(&ubi->wl_lock);
973
974         ubi_free_vid_buf(vidb);
975         wl_entry_destroy(ubi, e1);
976         wl_entry_destroy(ubi, e2);
977
978 out_ro:
979         ubi_ro_mode(ubi);
980         mutex_unlock(&ubi->move_mutex);
981         up_read(&ubi->fm_eba_sem);
982         ubi_assert(err != 0);
983         return err < 0 ? err : -EIO;
984
985 out_cancel:
986         ubi->wl_scheduled = 0;
987         spin_unlock(&ubi->wl_lock);
988         mutex_unlock(&ubi->move_mutex);
989         up_read(&ubi->fm_eba_sem);
990         ubi_free_vid_buf(vidb);
991         return 0;
992 }
993
994 /**
995  * ensure_wear_leveling - schedule wear-leveling if it is needed.
996  * @ubi: UBI device description object
997  * @nested: set to non-zero if this function is called from UBI worker
998  *
999  * This function checks if it is time to start wear-leveling and schedules it
1000  * if yes. This function returns zero in case of success and a negative error
1001  * code in case of failure.
1002  */
1003 static int ensure_wear_leveling(struct ubi_device *ubi, int nested)
1004 {
1005         int err = 0;
1006         struct ubi_wl_entry *e1;
1007         struct ubi_wl_entry *e2;
1008         struct ubi_work *wrk;
1009
1010         spin_lock(&ubi->wl_lock);
1011         if (ubi->wl_scheduled)
1012                 /* Wear-leveling is already in the work queue */
1013                 goto out_unlock;
1014
1015         /*
1016          * If the ubi->scrub tree is not empty, scrubbing is needed, and the
1017          * the WL worker has to be scheduled anyway.
1018          */
1019         if (!ubi->scrub.rb_node) {
1020                 if (!ubi->used.rb_node || !ubi->free.rb_node)
1021                         /* No physical eraseblocks - no deal */
1022                         goto out_unlock;
1023
1024                 /*
1025                  * We schedule wear-leveling only if the difference between the
1026                  * lowest erase counter of used physical eraseblocks and a high
1027                  * erase counter of free physical eraseblocks is greater than
1028                  * %UBI_WL_THRESHOLD.
1029                  */
1030                 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, u.rb);
1031                 e2 = find_wl_entry(ubi, &ubi->free, WL_FREE_MAX_DIFF);
1032
1033                 if (!(e2->ec - e1->ec >= UBI_WL_THRESHOLD))
1034                         goto out_unlock;
1035                 dbg_wl("schedule wear-leveling");
1036         } else
1037                 dbg_wl("schedule scrubbing");
1038
1039         ubi->wl_scheduled = 1;
1040         spin_unlock(&ubi->wl_lock);
1041
1042         wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
1043         if (!wrk) {
1044                 err = -ENOMEM;
1045                 goto out_cancel;
1046         }
1047
1048         wrk->anchor = 0;
1049         wrk->func = &wear_leveling_worker;
1050         if (nested)
1051                 __schedule_ubi_work(ubi, wrk);
1052         else
1053                 schedule_ubi_work(ubi, wrk);
1054         return err;
1055
1056 out_cancel:
1057         spin_lock(&ubi->wl_lock);
1058         ubi->wl_scheduled = 0;
1059 out_unlock:
1060         spin_unlock(&ubi->wl_lock);
1061         return err;
1062 }
1063
1064 /**
1065  * __erase_worker - physical eraseblock erase worker function.
1066  * @ubi: UBI device description object
1067  * @wl_wrk: the work object
1068  * @shutdown: non-zero if the worker has to free memory and exit
1069  * because the WL sub-system is shutting down
1070  *
1071  * This function erases a physical eraseblock and perform torture testing if
1072  * needed. It also takes care about marking the physical eraseblock bad if
1073  * needed. Returns zero in case of success and a negative error code in case of
1074  * failure.
1075  */
1076 static int __erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk)
1077 {
1078         struct ubi_wl_entry *e = wl_wrk->e;
1079         int pnum = e->pnum;
1080         int vol_id = wl_wrk->vol_id;
1081         int lnum = wl_wrk->lnum;
1082         int err, available_consumed = 0;
1083
1084         dbg_wl("erase PEB %d EC %d LEB %d:%d",
1085                pnum, e->ec, wl_wrk->vol_id, wl_wrk->lnum);
1086
1087         err = sync_erase(ubi, e, wl_wrk->torture);
1088         if (!err) {
1089                 spin_lock(&ubi->wl_lock);
1090                 wl_tree_add(e, &ubi->free);
1091                 ubi->free_count++;
1092                 spin_unlock(&ubi->wl_lock);
1093
1094                 /*
1095                  * One more erase operation has happened, take care about
1096                  * protected physical eraseblocks.
1097                  */
1098                 serve_prot_queue(ubi);
1099
1100                 /* And take care about wear-leveling */
1101                 err = ensure_wear_leveling(ubi, 1);
1102                 return err;
1103         }
1104
1105         ubi_err(ubi, "failed to erase PEB %d, error %d", pnum, err);
1106
1107         if (err == -EINTR || err == -ENOMEM || err == -EAGAIN ||
1108             err == -EBUSY) {
1109                 int err1;
1110
1111                 /* Re-schedule the LEB for erasure */
1112                 err1 = schedule_erase(ubi, e, vol_id, lnum, 0, false);
1113                 if (err1) {
1114                         wl_entry_destroy(ubi, e);
1115                         err = err1;
1116                         goto out_ro;
1117                 }
1118                 return err;
1119         }
1120
1121         wl_entry_destroy(ubi, e);
1122         if (err != -EIO)
1123                 /*
1124                  * If this is not %-EIO, we have no idea what to do. Scheduling
1125                  * this physical eraseblock for erasure again would cause
1126                  * errors again and again. Well, lets switch to R/O mode.
1127                  */
1128                 goto out_ro;
1129
1130         /* It is %-EIO, the PEB went bad */
1131
1132         if (!ubi->bad_allowed) {
1133                 ubi_err(ubi, "bad physical eraseblock %d detected", pnum);
1134                 goto out_ro;
1135         }
1136
1137         spin_lock(&ubi->volumes_lock);
1138         if (ubi->beb_rsvd_pebs == 0) {
1139                 if (ubi->avail_pebs == 0) {
1140                         spin_unlock(&ubi->volumes_lock);
1141                         ubi_err(ubi, "no reserved/available physical eraseblocks");
1142                         goto out_ro;
1143                 }
1144                 ubi->avail_pebs -= 1;
1145                 available_consumed = 1;
1146         }
1147         spin_unlock(&ubi->volumes_lock);
1148
1149         ubi_msg(ubi, "mark PEB %d as bad", pnum);
1150         err = ubi_io_mark_bad(ubi, pnum);
1151         if (err)
1152                 goto out_ro;
1153
1154         spin_lock(&ubi->volumes_lock);
1155         if (ubi->beb_rsvd_pebs > 0) {
1156                 if (available_consumed) {
1157                         /*
1158                          * The amount of reserved PEBs increased since we last
1159                          * checked.
1160                          */
1161                         ubi->avail_pebs += 1;
1162                         available_consumed = 0;
1163                 }
1164                 ubi->beb_rsvd_pebs -= 1;
1165         }
1166         ubi->bad_peb_count += 1;
1167         ubi->good_peb_count -= 1;
1168         ubi_calculate_reserved(ubi);
1169         if (available_consumed)
1170                 ubi_warn(ubi, "no PEBs in the reserved pool, used an available PEB");
1171         else if (ubi->beb_rsvd_pebs)
1172                 ubi_msg(ubi, "%d PEBs left in the reserve",
1173                         ubi->beb_rsvd_pebs);
1174         else
1175                 ubi_warn(ubi, "last PEB from the reserve was used");
1176         spin_unlock(&ubi->volumes_lock);
1177
1178         return err;
1179
1180 out_ro:
1181         if (available_consumed) {
1182                 spin_lock(&ubi->volumes_lock);
1183                 ubi->avail_pebs += 1;
1184                 spin_unlock(&ubi->volumes_lock);
1185         }
1186         ubi_ro_mode(ubi);
1187         return err;
1188 }
1189
1190 static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
1191                           int shutdown)
1192 {
1193         int ret;
1194
1195         if (shutdown) {
1196                 struct ubi_wl_entry *e = wl_wrk->e;
1197
1198                 dbg_wl("cancel erasure of PEB %d EC %d", e->pnum, e->ec);
1199                 kfree(wl_wrk);
1200                 wl_entry_destroy(ubi, e);
1201                 return 0;
1202         }
1203
1204         ret = __erase_worker(ubi, wl_wrk);
1205         kfree(wl_wrk);
1206         return ret;
1207 }
1208
1209 /**
1210  * ubi_wl_put_peb - return a PEB to the wear-leveling sub-system.
1211  * @ubi: UBI device description object
1212  * @vol_id: the volume ID that last used this PEB
1213  * @lnum: the last used logical eraseblock number for the PEB
1214  * @pnum: physical eraseblock to return
1215  * @torture: if this physical eraseblock has to be tortured
1216  *
1217  * This function is called to return physical eraseblock @pnum to the pool of
1218  * free physical eraseblocks. The @torture flag has to be set if an I/O error
1219  * occurred to this @pnum and it has to be tested. This function returns zero
1220  * in case of success, and a negative error code in case of failure.
1221  */
1222 int ubi_wl_put_peb(struct ubi_device *ubi, int vol_id, int lnum,
1223                    int pnum, int torture)
1224 {
1225         int err;
1226         struct ubi_wl_entry *e;
1227
1228         dbg_wl("PEB %d", pnum);
1229         ubi_assert(pnum >= 0);
1230         ubi_assert(pnum < ubi->peb_count);
1231
1232         down_read(&ubi->fm_protect);
1233
1234 retry:
1235         spin_lock(&ubi->wl_lock);
1236         e = ubi->lookuptbl[pnum];
1237         if (e == ubi->move_from) {
1238                 /*
1239                  * User is putting the physical eraseblock which was selected to
1240                  * be moved. It will be scheduled for erasure in the
1241                  * wear-leveling worker.
1242                  */
1243                 dbg_wl("PEB %d is being moved, wait", pnum);
1244                 spin_unlock(&ubi->wl_lock);
1245
1246                 /* Wait for the WL worker by taking the @ubi->move_mutex */
1247                 mutex_lock(&ubi->move_mutex);
1248                 mutex_unlock(&ubi->move_mutex);
1249                 goto retry;
1250         } else if (e == ubi->move_to) {
1251                 /*
1252                  * User is putting the physical eraseblock which was selected
1253                  * as the target the data is moved to. It may happen if the EBA
1254                  * sub-system already re-mapped the LEB in 'ubi_eba_copy_leb()'
1255                  * but the WL sub-system has not put the PEB to the "used" tree
1256                  * yet, but it is about to do this. So we just set a flag which
1257                  * will tell the WL worker that the PEB is not needed anymore
1258                  * and should be scheduled for erasure.
1259                  */
1260                 dbg_wl("PEB %d is the target of data moving", pnum);
1261                 ubi_assert(!ubi->move_to_put);
1262                 ubi->move_to_put = 1;
1263                 spin_unlock(&ubi->wl_lock);
1264                 up_read(&ubi->fm_protect);
1265                 return 0;
1266         } else {
1267                 if (in_wl_tree(e, &ubi->used)) {
1268                         self_check_in_wl_tree(ubi, e, &ubi->used);
1269                         rb_erase(&e->u.rb, &ubi->used);
1270                 } else if (in_wl_tree(e, &ubi->scrub)) {
1271                         self_check_in_wl_tree(ubi, e, &ubi->scrub);
1272                         rb_erase(&e->u.rb, &ubi->scrub);
1273                 } else if (in_wl_tree(e, &ubi->erroneous)) {
1274                         self_check_in_wl_tree(ubi, e, &ubi->erroneous);
1275                         rb_erase(&e->u.rb, &ubi->erroneous);
1276                         ubi->erroneous_peb_count -= 1;
1277                         ubi_assert(ubi->erroneous_peb_count >= 0);
1278                         /* Erroneous PEBs should be tortured */
1279                         torture = 1;
1280                 } else {
1281                         err = prot_queue_del(ubi, e->pnum);
1282                         if (err) {
1283                                 ubi_err(ubi, "PEB %d not found", pnum);
1284                                 ubi_ro_mode(ubi);
1285                                 spin_unlock(&ubi->wl_lock);
1286                                 up_read(&ubi->fm_protect);
1287                                 return err;
1288                         }
1289                 }
1290         }
1291         spin_unlock(&ubi->wl_lock);
1292
1293         err = schedule_erase(ubi, e, vol_id, lnum, torture, false);
1294         if (err) {
1295                 spin_lock(&ubi->wl_lock);
1296                 wl_tree_add(e, &ubi->used);
1297                 spin_unlock(&ubi->wl_lock);
1298         }
1299
1300         up_read(&ubi->fm_protect);
1301         return err;
1302 }
1303
1304 /**
1305  * ubi_wl_scrub_peb - schedule a physical eraseblock for scrubbing.
1306  * @ubi: UBI device description object
1307  * @pnum: the physical eraseblock to schedule
1308  *
1309  * If a bit-flip in a physical eraseblock is detected, this physical eraseblock
1310  * needs scrubbing. This function schedules a physical eraseblock for
1311  * scrubbing which is done in background. This function returns zero in case of
1312  * success and a negative error code in case of failure.
1313  */
1314 int ubi_wl_scrub_peb(struct ubi_device *ubi, int pnum)
1315 {
1316         struct ubi_wl_entry *e;
1317
1318         ubi_msg(ubi, "schedule PEB %d for scrubbing", pnum);
1319
1320 retry:
1321         spin_lock(&ubi->wl_lock);
1322         e = ubi->lookuptbl[pnum];
1323         if (e == ubi->move_from || in_wl_tree(e, &ubi->scrub) ||
1324                                    in_wl_tree(e, &ubi->erroneous)) {
1325                 spin_unlock(&ubi->wl_lock);
1326                 return 0;
1327         }
1328
1329         if (e == ubi->move_to) {
1330                 /*
1331                  * This physical eraseblock was used to move data to. The data
1332                  * was moved but the PEB was not yet inserted to the proper
1333                  * tree. We should just wait a little and let the WL worker
1334                  * proceed.
1335                  */
1336                 spin_unlock(&ubi->wl_lock);
1337                 dbg_wl("the PEB %d is not in proper tree, retry", pnum);
1338                 yield();
1339                 goto retry;
1340         }
1341
1342         if (in_wl_tree(e, &ubi->used)) {
1343                 self_check_in_wl_tree(ubi, e, &ubi->used);
1344                 rb_erase(&e->u.rb, &ubi->used);
1345         } else {
1346                 int err;
1347
1348                 err = prot_queue_del(ubi, e->pnum);
1349                 if (err) {
1350                         ubi_err(ubi, "PEB %d not found", pnum);
1351                         ubi_ro_mode(ubi);
1352                         spin_unlock(&ubi->wl_lock);
1353                         return err;
1354                 }
1355         }
1356
1357         wl_tree_add(e, &ubi->scrub);
1358         spin_unlock(&ubi->wl_lock);
1359
1360         /*
1361          * Technically scrubbing is the same as wear-leveling, so it is done
1362          * by the WL worker.
1363          */
1364         return ensure_wear_leveling(ubi, 0);
1365 }
1366
1367 /**
1368  * ubi_wl_flush - flush all pending works.
1369  * @ubi: UBI device description object
1370  * @vol_id: the volume id to flush for
1371  * @lnum: the logical eraseblock number to flush for
1372  *
1373  * This function executes all pending works for a particular volume id /
1374  * logical eraseblock number pair. If either value is set to %UBI_ALL, then it
1375  * acts as a wildcard for all of the corresponding volume numbers or logical
1376  * eraseblock numbers. It returns zero in case of success and a negative error
1377  * code in case of failure.
1378  */
1379 int ubi_wl_flush(struct ubi_device *ubi, int vol_id, int lnum)
1380 {
1381         int err = 0;
1382         int found = 1;
1383
1384         /*
1385          * Erase while the pending works queue is not empty, but not more than
1386          * the number of currently pending works.
1387          */
1388         dbg_wl("flush pending work for LEB %d:%d (%d pending works)",
1389                vol_id, lnum, ubi->works_count);
1390
1391         while (found) {
1392                 struct ubi_work *wrk, *tmp;
1393                 found = 0;
1394
1395                 down_read(&ubi->work_sem);
1396                 spin_lock(&ubi->wl_lock);
1397                 list_for_each_entry_safe(wrk, tmp, &ubi->works, list) {
1398                         if ((vol_id == UBI_ALL || wrk->vol_id == vol_id) &&
1399                             (lnum == UBI_ALL || wrk->lnum == lnum)) {
1400                                 list_del(&wrk->list);
1401                                 ubi->works_count -= 1;
1402                                 ubi_assert(ubi->works_count >= 0);
1403                                 spin_unlock(&ubi->wl_lock);
1404
1405                                 err = wrk->func(ubi, wrk, 0);
1406                                 if (err) {
1407                                         up_read(&ubi->work_sem);
1408                                         return err;
1409                                 }
1410
1411                                 spin_lock(&ubi->wl_lock);
1412                                 found = 1;
1413                                 break;
1414                         }
1415                 }
1416                 spin_unlock(&ubi->wl_lock);
1417                 up_read(&ubi->work_sem);
1418         }
1419
1420         /*
1421          * Make sure all the works which have been done in parallel are
1422          * finished.
1423          */
1424         down_write(&ubi->work_sem);
1425         up_write(&ubi->work_sem);
1426
1427         return err;
1428 }
1429
1430 static bool scrub_possible(struct ubi_device *ubi, struct ubi_wl_entry *e)
1431 {
1432         if (in_wl_tree(e, &ubi->scrub))
1433                 return false;
1434         else if (in_wl_tree(e, &ubi->erroneous))
1435                 return false;
1436         else if (ubi->move_from == e)
1437                 return false;
1438         else if (ubi->move_to == e)
1439                 return false;
1440
1441         return true;
1442 }
1443
1444 /**
1445  * ubi_bitflip_check - Check an eraseblock for bitflips and scrub it if needed.
1446  * @ubi: UBI device description object
1447  * @pnum: the physical eraseblock to schedule
1448  * @force: dont't read the block, assume bitflips happened and take action.
1449  *
1450  * This function reads the given eraseblock and checks if bitflips occured.
1451  * In case of bitflips, the eraseblock is scheduled for scrubbing.
1452  * If scrubbing is forced with @force, the eraseblock is not read,
1453  * but scheduled for scrubbing right away.
1454  *
1455  * Returns:
1456  * %EINVAL, PEB is out of range
1457  * %ENOENT, PEB is no longer used by UBI
1458  * %EBUSY, PEB cannot be checked now or a check is currently running on it
1459  * %EAGAIN, bit flips happened but scrubbing is currently not possible
1460  * %EUCLEAN, bit flips happened and PEB is scheduled for scrubbing
1461  * %0, no bit flips detected
1462  */
1463 int ubi_bitflip_check(struct ubi_device *ubi, int pnum, int force)
1464 {
1465         int err = 0;
1466         struct ubi_wl_entry *e;
1467
1468         if (pnum < 0 || pnum >= ubi->peb_count) {
1469                 err = -EINVAL;
1470                 goto out;
1471         }
1472
1473         /*
1474          * Pause all parallel work, otherwise it can happen that the
1475          * erase worker frees a wl entry under us.
1476          */
1477         down_write(&ubi->work_sem);
1478
1479         /*
1480          * Make sure that the wl entry does not change state while
1481          * inspecting it.
1482          */
1483         spin_lock(&ubi->wl_lock);
1484         e = ubi->lookuptbl[pnum];
1485         if (!e) {
1486                 spin_unlock(&ubi->wl_lock);
1487                 err = -ENOENT;
1488                 goto out_resume;
1489         }
1490
1491         /*
1492          * Does it make sense to check this PEB?
1493          */
1494         if (!scrub_possible(ubi, e)) {
1495                 spin_unlock(&ubi->wl_lock);
1496                 err = -EBUSY;
1497                 goto out_resume;
1498         }
1499         spin_unlock(&ubi->wl_lock);
1500
1501         if (!force) {
1502                 mutex_lock(&ubi->buf_mutex);
1503                 err = ubi_io_read(ubi, ubi->peb_buf, pnum, 0, ubi->peb_size);
1504                 mutex_unlock(&ubi->buf_mutex);
1505         }
1506
1507         if (force || err == UBI_IO_BITFLIPS) {
1508                 /*
1509                  * Okay, bit flip happened, let's figure out what we can do.
1510                  */
1511                 spin_lock(&ubi->wl_lock);
1512
1513                 /*
1514                  * Recheck. We released wl_lock, UBI might have killed the
1515                  * wl entry under us.
1516                  */
1517                 e = ubi->lookuptbl[pnum];
1518                 if (!e) {
1519                         spin_unlock(&ubi->wl_lock);
1520                         err = -ENOENT;
1521                         goto out_resume;
1522                 }
1523
1524                 /*
1525                  * Need to re-check state
1526                  */
1527                 if (!scrub_possible(ubi, e)) {
1528                         spin_unlock(&ubi->wl_lock);
1529                         err = -EBUSY;
1530                         goto out_resume;
1531                 }
1532
1533                 if (in_pq(ubi, e)) {
1534                         prot_queue_del(ubi, e->pnum);
1535                         wl_tree_add(e, &ubi->scrub);
1536                         spin_unlock(&ubi->wl_lock);
1537
1538                         err = ensure_wear_leveling(ubi, 1);
1539                 } else if (in_wl_tree(e, &ubi->used)) {
1540                         rb_erase(&e->u.rb, &ubi->used);
1541                         wl_tree_add(e, &ubi->scrub);
1542                         spin_unlock(&ubi->wl_lock);
1543
1544                         err = ensure_wear_leveling(ubi, 1);
1545                 } else if (in_wl_tree(e, &ubi->free)) {
1546                         rb_erase(&e->u.rb, &ubi->free);
1547                         ubi->free_count--;
1548                         spin_unlock(&ubi->wl_lock);
1549
1550                         /*
1551                          * This PEB is empty we can schedule it for
1552                          * erasure right away. No wear leveling needed.
1553                          */
1554                         err = schedule_erase(ubi, e, UBI_UNKNOWN, UBI_UNKNOWN,
1555                                              force ? 0 : 1, true);
1556                 } else {
1557                         spin_unlock(&ubi->wl_lock);
1558                         err = -EAGAIN;
1559                 }
1560
1561                 if (!err && !force)
1562                         err = -EUCLEAN;
1563         } else {
1564                 err = 0;
1565         }
1566
1567 out_resume:
1568         up_write(&ubi->work_sem);
1569 out:
1570
1571         return err;
1572 }
1573
1574 /**
1575  * tree_destroy - destroy an RB-tree.
1576  * @ubi: UBI device description object
1577  * @root: the root of the tree to destroy
1578  */
1579 static void tree_destroy(struct ubi_device *ubi, struct rb_root *root)
1580 {
1581         struct rb_node *rb;
1582         struct ubi_wl_entry *e;
1583
1584         rb = root->rb_node;
1585         while (rb) {
1586                 if (rb->rb_left)
1587                         rb = rb->rb_left;
1588                 else if (rb->rb_right)
1589                         rb = rb->rb_right;
1590                 else {
1591                         e = rb_entry(rb, struct ubi_wl_entry, u.rb);
1592
1593                         rb = rb_parent(rb);
1594                         if (rb) {
1595                                 if (rb->rb_left == &e->u.rb)
1596                                         rb->rb_left = NULL;
1597                                 else
1598                                         rb->rb_right = NULL;
1599                         }
1600
1601                         wl_entry_destroy(ubi, e);
1602                 }
1603         }
1604 }
1605
1606 /**
1607  * ubi_thread - UBI background thread.
1608  * @u: the UBI device description object pointer
1609  */
1610 int ubi_thread(void *u)
1611 {
1612         int failures = 0;
1613         struct ubi_device *ubi = u;
1614
1615         ubi_msg(ubi, "background thread \"%s\" started, PID %d",
1616                 ubi->bgt_name, task_pid_nr(current));
1617
1618         set_freezable();
1619         for (;;) {
1620                 int err;
1621
1622                 if (kthread_should_stop())
1623                         break;
1624
1625                 if (try_to_freeze())
1626                         continue;
1627
1628                 spin_lock(&ubi->wl_lock);
1629                 if (list_empty(&ubi->works) || ubi->ro_mode ||
1630                     !ubi->thread_enabled || ubi_dbg_is_bgt_disabled(ubi)) {
1631                         set_current_state(TASK_INTERRUPTIBLE);
1632                         spin_unlock(&ubi->wl_lock);
1633                         schedule();
1634                         continue;
1635                 }
1636                 spin_unlock(&ubi->wl_lock);
1637
1638                 err = do_work(ubi);
1639                 if (err) {
1640                         ubi_err(ubi, "%s: work failed with error code %d",
1641                                 ubi->bgt_name, err);
1642                         if (failures++ > WL_MAX_FAILURES) {
1643                                 /*
1644                                  * Too many failures, disable the thread and
1645                                  * switch to read-only mode.
1646                                  */
1647                                 ubi_msg(ubi, "%s: %d consecutive failures",
1648                                         ubi->bgt_name, WL_MAX_FAILURES);
1649                                 ubi_ro_mode(ubi);
1650                                 ubi->thread_enabled = 0;
1651                                 continue;
1652                         }
1653                 } else
1654                         failures = 0;
1655
1656                 cond_resched();
1657         }
1658
1659         dbg_wl("background thread \"%s\" is killed", ubi->bgt_name);
1660         ubi->thread_enabled = 0;
1661         return 0;
1662 }
1663
1664 /**
1665  * shutdown_work - shutdown all pending works.
1666  * @ubi: UBI device description object
1667  */
1668 static void shutdown_work(struct ubi_device *ubi)
1669 {
1670         while (!list_empty(&ubi->works)) {
1671                 struct ubi_work *wrk;
1672
1673                 wrk = list_entry(ubi->works.next, struct ubi_work, list);
1674                 list_del(&wrk->list);
1675                 wrk->func(ubi, wrk, 1);
1676                 ubi->works_count -= 1;
1677                 ubi_assert(ubi->works_count >= 0);
1678         }
1679 }
1680
1681 /**
1682  * erase_aeb - erase a PEB given in UBI attach info PEB
1683  * @ubi: UBI device description object
1684  * @aeb: UBI attach info PEB
1685  * @sync: If true, erase synchronously. Otherwise schedule for erasure
1686  */
1687 static int erase_aeb(struct ubi_device *ubi, struct ubi_ainf_peb *aeb, bool sync)
1688 {
1689         struct ubi_wl_entry *e;
1690         int err;
1691
1692         e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1693         if (!e)
1694                 return -ENOMEM;
1695
1696         e->pnum = aeb->pnum;
1697         e->ec = aeb->ec;
1698         ubi->lookuptbl[e->pnum] = e;
1699
1700         if (sync) {
1701                 err = sync_erase(ubi, e, false);
1702                 if (err)
1703                         goto out_free;
1704
1705                 wl_tree_add(e, &ubi->free);
1706                 ubi->free_count++;
1707         } else {
1708                 err = schedule_erase(ubi, e, aeb->vol_id, aeb->lnum, 0, false);
1709                 if (err)
1710                         goto out_free;
1711         }
1712
1713         return 0;
1714
1715 out_free:
1716         wl_entry_destroy(ubi, e);
1717
1718         return err;
1719 }
1720
1721 /**
1722  * ubi_wl_init - initialize the WL sub-system using attaching information.
1723  * @ubi: UBI device description object
1724  * @ai: attaching information
1725  *
1726  * This function returns zero in case of success, and a negative error code in
1727  * case of failure.
1728  */
1729 int ubi_wl_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
1730 {
1731         int err, i, reserved_pebs, found_pebs = 0;
1732         struct rb_node *rb1, *rb2;
1733         struct ubi_ainf_volume *av;
1734         struct ubi_ainf_peb *aeb, *tmp;
1735         struct ubi_wl_entry *e;
1736
1737         ubi->used = ubi->erroneous = ubi->free = ubi->scrub = RB_ROOT;
1738         spin_lock_init(&ubi->wl_lock);
1739         mutex_init(&ubi->move_mutex);
1740         init_rwsem(&ubi->work_sem);
1741         ubi->max_ec = ai->max_ec;
1742         INIT_LIST_HEAD(&ubi->works);
1743
1744         sprintf(ubi->bgt_name, UBI_BGT_NAME_PATTERN, ubi->ubi_num);
1745
1746         err = -ENOMEM;
1747         ubi->lookuptbl = kcalloc(ubi->peb_count, sizeof(void *), GFP_KERNEL);
1748         if (!ubi->lookuptbl)
1749                 return err;
1750
1751         for (i = 0; i < UBI_PROT_QUEUE_LEN; i++)
1752                 INIT_LIST_HEAD(&ubi->pq[i]);
1753         ubi->pq_head = 0;
1754
1755         ubi->free_count = 0;
1756         list_for_each_entry_safe(aeb, tmp, &ai->erase, u.list) {
1757                 cond_resched();
1758
1759                 err = erase_aeb(ubi, aeb, false);
1760                 if (err)
1761                         goto out_free;
1762
1763                 found_pebs++;
1764         }
1765
1766         list_for_each_entry(aeb, &ai->free, u.list) {
1767                 cond_resched();
1768
1769                 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1770                 if (!e) {
1771                         err = -ENOMEM;
1772                         goto out_free;
1773                 }
1774
1775                 e->pnum = aeb->pnum;
1776                 e->ec = aeb->ec;
1777                 ubi_assert(e->ec >= 0);
1778
1779                 wl_tree_add(e, &ubi->free);
1780                 ubi->free_count++;
1781
1782                 ubi->lookuptbl[e->pnum] = e;
1783
1784                 found_pebs++;
1785         }
1786
1787         ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
1788                 ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
1789                         cond_resched();
1790
1791                         e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
1792                         if (!e) {
1793                                 err = -ENOMEM;
1794                                 goto out_free;
1795                         }
1796
1797                         e->pnum = aeb->pnum;
1798                         e->ec = aeb->ec;
1799                         ubi->lookuptbl[e->pnum] = e;
1800
1801                         if (!aeb->scrub) {
1802                                 dbg_wl("add PEB %d EC %d to the used tree",
1803                                        e->pnum, e->ec);
1804                                 wl_tree_add(e, &ubi->used);
1805                         } else {
1806                                 dbg_wl("add PEB %d EC %d to the scrub tree",
1807                                        e->pnum, e->ec);
1808                                 wl_tree_add(e, &ubi->scrub);
1809                         }
1810
1811                         found_pebs++;
1812                 }
1813         }
1814
1815         list_for_each_entry(aeb, &ai->fastmap, u.list) {
1816                 cond_resched();
1817
1818                 e = ubi_find_fm_block(ubi, aeb->pnum);
1819
1820                 if (e) {
1821                         ubi_assert(!ubi->lookuptbl[e->pnum]);
1822                         ubi->lookuptbl[e->pnum] = e;
1823                 } else {
1824                         bool sync = false;
1825
1826                         /*
1827                          * Usually old Fastmap PEBs are scheduled for erasure
1828                          * and we don't have to care about them but if we face
1829                          * an power cut before scheduling them we need to
1830                          * take care of them here.
1831                          */
1832                         if (ubi->lookuptbl[aeb->pnum])
1833                                 continue;
1834
1835                         /*
1836                          * The fastmap update code might not find a free PEB for
1837                          * writing the fastmap anchor to and then reuses the
1838                          * current fastmap anchor PEB. When this PEB gets erased
1839                          * and a power cut happens before it is written again we
1840                          * must make sure that the fastmap attach code doesn't
1841                          * find any outdated fastmap anchors, hence we erase the
1842                          * outdated fastmap anchor PEBs synchronously here.
1843                          */
1844                         if (aeb->vol_id == UBI_FM_SB_VOLUME_ID)
1845                                 sync = true;
1846
1847                         err = erase_aeb(ubi, aeb, sync);
1848                         if (err)
1849                                 goto out_free;
1850                 }
1851
1852                 found_pebs++;
1853         }
1854
1855         dbg_wl("found %i PEBs", found_pebs);
1856
1857         ubi_assert(ubi->good_peb_count == found_pebs);
1858
1859         reserved_pebs = WL_RESERVED_PEBS;
1860         ubi_fastmap_init(ubi, &reserved_pebs);
1861
1862         if (ubi->avail_pebs < reserved_pebs) {
1863                 ubi_err(ubi, "no enough physical eraseblocks (%d, need %d)",
1864                         ubi->avail_pebs, reserved_pebs);
1865                 if (ubi->corr_peb_count)
1866                         ubi_err(ubi, "%d PEBs are corrupted and not used",
1867                                 ubi->corr_peb_count);
1868                 err = -ENOSPC;
1869                 goto out_free;
1870         }
1871         ubi->avail_pebs -= reserved_pebs;
1872         ubi->rsvd_pebs += reserved_pebs;
1873
1874         /* Schedule wear-leveling if needed */
1875         err = ensure_wear_leveling(ubi, 0);
1876         if (err)
1877                 goto out_free;
1878
1879         return 0;
1880
1881 out_free:
1882         shutdown_work(ubi);
1883         tree_destroy(ubi, &ubi->used);
1884         tree_destroy(ubi, &ubi->free);
1885         tree_destroy(ubi, &ubi->scrub);
1886         kfree(ubi->lookuptbl);
1887         return err;
1888 }
1889
1890 /**
1891  * protection_queue_destroy - destroy the protection queue.
1892  * @ubi: UBI device description object
1893  */
1894 static void protection_queue_destroy(struct ubi_device *ubi)
1895 {
1896         int i;
1897         struct ubi_wl_entry *e, *tmp;
1898
1899         for (i = 0; i < UBI_PROT_QUEUE_LEN; ++i) {
1900                 list_for_each_entry_safe(e, tmp, &ubi->pq[i], u.list) {
1901                         list_del(&e->u.list);
1902                         wl_entry_destroy(ubi, e);
1903                 }
1904         }
1905 }
1906
1907 /**
1908  * ubi_wl_close - close the wear-leveling sub-system.
1909  * @ubi: UBI device description object
1910  */
1911 void ubi_wl_close(struct ubi_device *ubi)
1912 {
1913         dbg_wl("close the WL sub-system");
1914         ubi_fastmap_close(ubi);
1915         shutdown_work(ubi);
1916         protection_queue_destroy(ubi);
1917         tree_destroy(ubi, &ubi->used);
1918         tree_destroy(ubi, &ubi->erroneous);
1919         tree_destroy(ubi, &ubi->free);
1920         tree_destroy(ubi, &ubi->scrub);
1921         kfree(ubi->lookuptbl);
1922 }
1923
1924 /**
1925  * self_check_ec - make sure that the erase counter of a PEB is correct.
1926  * @ubi: UBI device description object
1927  * @pnum: the physical eraseblock number to check
1928  * @ec: the erase counter to check
1929  *
1930  * This function returns zero if the erase counter of physical eraseblock @pnum
1931  * is equivalent to @ec, and a negative error code if not or if an error
1932  * occurred.
1933  */
1934 static int self_check_ec(struct ubi_device *ubi, int pnum, int ec)
1935 {
1936         int err;
1937         long long read_ec;
1938         struct ubi_ec_hdr *ec_hdr;
1939
1940         if (!ubi_dbg_chk_gen(ubi))
1941                 return 0;
1942
1943         ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
1944         if (!ec_hdr)
1945                 return -ENOMEM;
1946
1947         err = ubi_io_read_ec_hdr(ubi, pnum, ec_hdr, 0);
1948         if (err && err != UBI_IO_BITFLIPS) {
1949                 /* The header does not have to exist */
1950                 err = 0;
1951                 goto out_free;
1952         }
1953
1954         read_ec = be64_to_cpu(ec_hdr->ec);
1955         if (ec != read_ec && read_ec - ec > 1) {
1956                 ubi_err(ubi, "self-check failed for PEB %d", pnum);
1957                 ubi_err(ubi, "read EC is %lld, should be %d", read_ec, ec);
1958                 dump_stack();
1959                 err = 1;
1960         } else
1961                 err = 0;
1962
1963 out_free:
1964         kfree(ec_hdr);
1965         return err;
1966 }
1967
1968 /**
1969  * self_check_in_wl_tree - check that wear-leveling entry is in WL RB-tree.
1970  * @ubi: UBI device description object
1971  * @e: the wear-leveling entry to check
1972  * @root: the root of the tree
1973  *
1974  * This function returns zero if @e is in the @root RB-tree and %-EINVAL if it
1975  * is not.
1976  */
1977 static int self_check_in_wl_tree(const struct ubi_device *ubi,
1978                                  struct ubi_wl_entry *e, struct rb_root *root)
1979 {
1980         if (!ubi_dbg_chk_gen(ubi))
1981                 return 0;
1982
1983         if (in_wl_tree(e, root))
1984                 return 0;
1985
1986         ubi_err(ubi, "self-check failed for PEB %d, EC %d, RB-tree %p ",
1987                 e->pnum, e->ec, root);
1988         dump_stack();
1989         return -EINVAL;
1990 }
1991
1992 /**
1993  * self_check_in_pq - check if wear-leveling entry is in the protection
1994  *                        queue.
1995  * @ubi: UBI device description object
1996  * @e: the wear-leveling entry to check
1997  *
1998  * This function returns zero if @e is in @ubi->pq and %-EINVAL if it is not.
1999  */
2000 static int self_check_in_pq(const struct ubi_device *ubi,
2001                             struct ubi_wl_entry *e)
2002 {
2003         if (!ubi_dbg_chk_gen(ubi))
2004                 return 0;
2005
2006         if (in_pq(ubi, e))
2007                 return 0;
2008
2009         ubi_err(ubi, "self-check failed for PEB %d, EC %d, Protect queue",
2010                 e->pnum, e->ec);
2011         dump_stack();
2012         return -EINVAL;
2013 }
2014 #ifndef CONFIG_MTD_UBI_FASTMAP
2015 static struct ubi_wl_entry *get_peb_for_wl(struct ubi_device *ubi)
2016 {
2017         struct ubi_wl_entry *e;
2018
2019         e = find_wl_entry(ubi, &ubi->free, WL_FREE_MAX_DIFF);
2020         self_check_in_wl_tree(ubi, e, &ubi->free);
2021         ubi->free_count--;
2022         ubi_assert(ubi->free_count >= 0);
2023         rb_erase(&e->u.rb, &ubi->free);
2024
2025         return e;
2026 }
2027
2028 /**
2029  * produce_free_peb - produce a free physical eraseblock.
2030  * @ubi: UBI device description object
2031  *
2032  * This function tries to make a free PEB by means of synchronous execution of
2033  * pending works. This may be needed if, for example the background thread is
2034  * disabled. Returns zero in case of success and a negative error code in case
2035  * of failure.
2036  */
2037 static int produce_free_peb(struct ubi_device *ubi)
2038 {
2039         int err;
2040
2041         while (!ubi->free.rb_node && ubi->works_count) {
2042                 spin_unlock(&ubi->wl_lock);
2043
2044                 dbg_wl("do one work synchronously");
2045                 err = do_work(ubi);
2046
2047                 spin_lock(&ubi->wl_lock);
2048                 if (err)
2049                         return err;
2050         }
2051
2052         return 0;
2053 }
2054
2055 /**
2056  * ubi_wl_get_peb - get a physical eraseblock.
2057  * @ubi: UBI device description object
2058  *
2059  * This function returns a physical eraseblock in case of success and a
2060  * negative error code in case of failure.
2061  * Returns with ubi->fm_eba_sem held in read mode!
2062  */
2063 int ubi_wl_get_peb(struct ubi_device *ubi)
2064 {
2065         int err;
2066         struct ubi_wl_entry *e;
2067
2068 retry:
2069         down_read(&ubi->fm_eba_sem);
2070         spin_lock(&ubi->wl_lock);
2071         if (!ubi->free.rb_node) {
2072                 if (ubi->works_count == 0) {
2073                         ubi_err(ubi, "no free eraseblocks");
2074                         ubi_assert(list_empty(&ubi->works));
2075                         spin_unlock(&ubi->wl_lock);
2076                         return -ENOSPC;
2077                 }
2078
2079                 err = produce_free_peb(ubi);
2080                 if (err < 0) {
2081                         spin_unlock(&ubi->wl_lock);
2082                         return err;
2083                 }
2084                 spin_unlock(&ubi->wl_lock);
2085                 up_read(&ubi->fm_eba_sem);
2086                 goto retry;
2087
2088         }
2089         e = wl_get_wle(ubi);
2090         prot_queue_add(ubi, e);
2091         spin_unlock(&ubi->wl_lock);
2092
2093         err = ubi_self_check_all_ff(ubi, e->pnum, ubi->vid_hdr_aloffset,
2094                                     ubi->peb_size - ubi->vid_hdr_aloffset);
2095         if (err) {
2096                 ubi_err(ubi, "new PEB %d does not contain all 0xFF bytes", e->pnum);
2097                 return err;
2098         }
2099
2100         return e->pnum;
2101 }
2102 #else
2103 #include "fastmap-wl.c"
2104 #endif