]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - drivers/mtd/ubi/wl.c
treewide: Replace GPLv2 boilerplate/reference with SPDX - rule 156
[mirror_ubuntu-hirsute-kernel.git] / drivers / mtd / ubi / wl.c
CommitLineData
1a59d1b8 1// SPDX-License-Identifier: GPL-2.0-or-later
801c135c
AB
2/*
3 * Copyright (c) International Business Machines Corp., 2006
4 *
801c135c
AB
5 * Authors: Artem Bityutskiy (Битюцкий Артём), Thomas Gleixner
6 */
7
8/*
85c6e6e2 9 * UBI wear-leveling sub-system.
801c135c 10 *
85c6e6e2 11 * This sub-system is responsible for wear-leveling. It works in terms of
7b6c32da 12 * physical eraseblocks and erase counters and knows nothing about logical
85c6e6e2
AB
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.
801c135c
AB
17 *
18 * Physical eraseblocks returned by 'ubi_wl_get_peb()' have only erase counter
85c6e6e2 19 * header. The rest of the physical eraseblock contains only %0xFF bytes.
801c135c 20 *
85c6e6e2 21 * When physical eraseblocks are returned to the WL sub-system by means of the
801c135c
AB
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,
85c6e6e2 24 * which is also managed by the WL sub-system.
801c135c
AB
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 *
85c6e6e2
AB
30 * If the WL sub-system fails to erase a physical eraseblock, it marks it as
31 * bad.
801c135c 32 *
85c6e6e2
AB
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.
801c135c 36 *
85c6e6e2
AB
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
b86a2c56
AB
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.
7b6c32da
XX
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
44156267 53 * soon, so it makes sense not to move it for some time, but wait.
7b6c32da
XX
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);
815bc5f8 66 * o the WL movement is disallowed (@wl->erroneous) because the PEB is
b86a2c56 67 * erroneous - e.g., there was a read error;
7b6c32da
XX
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.
801c135c
AB
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
85c6e6e2 77 * re-work this sub-system and make it more scalable.
801c135c 78 *
85c6e6e2
AB
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
801c135c
AB
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
85c6e6e2 85 * room for future re-works of the WL sub-system.
801c135c
AB
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"
78d6d497 93#include "wl.h"
801c135c
AB
94
95/* Number of physical eraseblocks reserved for wear-leveling purposes */
96#define WL_RESERVED_PEBS 1
97
801c135c
AB
98/*
99 * Maximum difference between two erase counters. If this threshold is
85c6e6e2
AB
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.
801c135c
AB
103 */
104#define UBI_WL_THRESHOLD CONFIG_MTD_UBI_WL_THRESHOLD
105
106/*
85c6e6e2 107 * When a physical eraseblock is moved, the WL sub-system has to pick the target
801c135c
AB
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
85c6e6e2 113 * counter of the free physical eraseblock to pick. Namely, the WL sub-system
025dfdaf 114 * does not pick eraseblocks with erase counter greater than the lowest erase
801c135c
AB
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
7bf523ae
AB
125static int self_check_ec(struct ubi_device *ubi, int pnum, int ec);
126static int self_check_in_wl_tree(const struct ubi_device *ubi,
127 struct ubi_wl_entry *e, struct rb_root *root);
128static int self_check_in_pq(const struct ubi_device *ubi,
129 struct ubi_wl_entry *e);
801c135c 130
801c135c
AB
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 */
139static 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;
23553b2c 148 e1 = rb_entry(parent, struct ubi_wl_entry, u.rb);
801c135c
AB
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
23553b2c
XX
163 rb_link_node(&e->u.rb, parent, p);
164 rb_insert_color(&e->u.rb, root);
801c135c
AB
165}
166
ee59ba8b
RW
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 */
175static 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
801c135c
AB
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 */
188static int do_work(struct ubi_device *ubi)
189{
190 int err;
191 struct ubi_work *wrk;
192
43f9b25a
AB
193 cond_resched();
194
593dd33c
AB
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);
801c135c 202 spin_lock(&ubi->wl_lock);
801c135c
AB
203 if (list_empty(&ubi->works)) {
204 spin_unlock(&ubi->wl_lock);
593dd33c 205 up_read(&ubi->work_sem);
801c135c
AB
206 return 0;
207 }
208
209 wrk = list_entry(ubi->works.next, struct ubi_work, list);
210 list_del(&wrk->list);
16f557ec
AB
211 ubi->works_count -= 1;
212 ubi_assert(ubi->works_count >= 0);
801c135c
AB
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)
32608703 222 ubi_err(ubi, "work failed with error code %d", err);
593dd33c 223 up_read(&ubi->work_sem);
16f557ec 224
801c135c
AB
225 return err;
226}
227
801c135c
AB
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 */
236static 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
23553b2c 244 e1 = rb_entry(p, struct ubi_wl_entry, u.rb);
801c135c
AB
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
b32b78f8
RW
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 */
275static 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
801c135c 288/**
7b6c32da 289 * prot_queue_add - add physical eraseblock to the protection queue.
801c135c
AB
290 * @ubi: UBI device description object
291 * @e: the physical eraseblock to add
801c135c 292 *
7b6c32da
XX
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.
801c135c 297 */
7b6c32da 298static void prot_queue_add(struct ubi_device *ubi, struct ubi_wl_entry *e)
801c135c 299{
7b6c32da 300 int pq_tail = ubi->pq_head - 1;
801c135c 301
7b6c32da
XX
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);
801c135c
AB
307}
308
309/**
310 * find_wl_entry - find wear-leveling entry closest to certain erase counter.
8199b901 311 * @ubi: UBI device description object
801c135c 312 * @root: the RB-tree where to look for
add8287e 313 * @diff: maximum possible difference from the smallest erase counter
801c135c
AB
314 *
315 * This function looks for a wear leveling entry with erase counter closest to
add8287e 316 * min + @diff, where min is the smallest erase counter.
801c135c 317 */
8199b901
RW
318static struct ubi_wl_entry *find_wl_entry(struct ubi_device *ubi,
319 struct rb_root *root, int diff)
801c135c
AB
320{
321 struct rb_node *p;
8199b901 322 struct ubi_wl_entry *e, *prev_e = NULL;
add8287e 323 int max;
801c135c 324
23553b2c 325 e = rb_entry(rb_first(root), struct ubi_wl_entry, u.rb);
add8287e 326 max = e->ec + diff;
801c135c
AB
327
328 p = root->rb_node;
329 while (p) {
330 struct ubi_wl_entry *e1;
331
23553b2c 332 e1 = rb_entry(p, struct ubi_wl_entry, u.rb);
801c135c
AB
333 if (e1->ec >= max)
334 p = p->rb_left;
335 else {
336 p = p->rb_right;
8199b901 337 prev_e = e;
801c135c
AB
338 e = e1;
339 }
340 }
341
8199b901
RW
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
801c135c
AB
349 return e;
350}
351
352/**
8199b901
RW
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 */
361static 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
8199b901
RW
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. */
2f84c246 375 e = may_reserve_for_fm(ubi, e, root);
8199b901
RW
376 } else
377 e = find_wl_entry(ubi, root, WL_FREE_MAX_DIFF/2);
378
379 return e;
380}
381
8199b901 382/**
78d6d497 383 * wl_get_wle - get a mean wl entry to be used by ubi_wl_get_peb() or
691a8705
RW
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 */
390static 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
801c135c 413/**
7b6c32da 414 * prot_queue_del - remove a physical eraseblock from the protection queue.
801c135c
AB
415 * @ubi: UBI device description object
416 * @pnum: the physical eraseblock to remove
43f9b25a 417 *
7b6c32da
XX
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.
801c135c 420 */
7b6c32da 421static int prot_queue_del(struct ubi_device *ubi, int pnum)
801c135c 422{
7b6c32da 423 struct ubi_wl_entry *e;
801c135c 424
7b6c32da
XX
425 e = ubi->lookuptbl[pnum];
426 if (!e)
427 return -ENODEV;
801c135c 428
7bf523ae 429 if (self_check_in_pq(ubi, e))
7b6c32da 430 return -ENODEV;
43f9b25a 431
7b6c32da
XX
432 list_del(&e->u.list);
433 dbg_wl("deleted PEB %d from the protection queue", e->pnum);
43f9b25a 434 return 0;
801c135c
AB
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 */
9c9ec147
AB
446static int sync_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
447 int torture)
801c135c
AB
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
7bf523ae 455 err = self_check_ec(ubi, e->pnum, e->ec);
adbf05e3 456 if (err)
801c135c
AB
457 return -EINVAL;
458
33818bbb 459 ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
801c135c
AB
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 */
32608703 473 ubi_err(ubi, "erase counter overflow at PEB %d, EC %llu",
801c135c
AB
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
3261ebd7 481 ec_hdr->ec = cpu_to_be64(ec);
801c135c
AB
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
493out_free:
494 kfree(ec_hdr);
495 return err;
496}
497
498/**
7b6c32da 499 * serve_prot_queue - check if it is time to stop protecting PEBs.
801c135c
AB
500 * @ubi: UBI device description object
501 *
7b6c32da
XX
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.
801c135c 505 */
7b6c32da 506static void serve_prot_queue(struct ubi_device *ubi)
801c135c 507{
7b6c32da
XX
508 struct ubi_wl_entry *e, *tmp;
509 int count;
801c135c
AB
510
511 /*
512 * There may be several protected physical eraseblock to remove,
513 * process them all.
514 */
7b6c32da
XX
515repeat:
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);
801c135c 521
7b6c32da
XX
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 */
801c135c 529 spin_unlock(&ubi->wl_lock);
7b6c32da
XX
530 cond_resched();
531 goto repeat;
801c135c 532 }
801c135c 533 }
7b6c32da
XX
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);
801c135c
AB
540}
541
542/**
8199b901 543 * __schedule_ubi_work - schedule a work.
801c135c
AB
544 * @ubi: UBI device description object
545 * @wrk: the work to schedule
546 *
7b6c32da 547 * This function adds a work defined by @wrk to the tail of the pending works
e3e00445 548 * list. Can only be used if ubi->work_sem is already held in read mode!
801c135c 549 */
8199b901 550static void __schedule_ubi_work(struct ubi_device *ubi, struct ubi_work *wrk)
801c135c
AB
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;
27a0f2a3 556 if (ubi->thread_enabled && !ubi_dbg_is_bgt_disabled(ubi))
801c135c
AB
557 wake_up_process(ubi->bgt_thread);
558 spin_unlock(&ubi->wl_lock);
559}
560
8199b901
RW
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 */
569static 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
801c135c 576static int erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk,
849271a4 577 int shutdown);
801c135c
AB
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
d36e59e6
JR
583 * @vol_id: the volume ID that last used this PEB
584 * @lnum: the last used logical eraseblock number for the PEB
801c135c
AB
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 */
590static int schedule_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
2e8f08de 591 int vol_id, int lnum, int torture, bool nested)
801c135c
AB
592{
593 struct ubi_work *wl_wrk;
594
8199b901 595 ubi_assert(e);
8199b901 596
801c135c
AB
597 dbg_wl("schedule erasure of PEB %d, EC %d, torture %d",
598 e->pnum, e->ec, torture);
599
33818bbb 600 wl_wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
801c135c
AB
601 if (!wl_wrk)
602 return -ENOMEM;
603
604 wl_wrk->func = &erase_worker;
605 wl_wrk->e = e;
d36e59e6
JR
606 wl_wrk->vol_id = vol_id;
607 wl_wrk->lnum = lnum;
801c135c
AB
608 wl_wrk->torture = torture;
609
2e8f08de
RW
610 if (nested)
611 __schedule_ubi_work(ubi, wl_wrk);
612 else
613 schedule_ubi_work(ubi, wl_wrk);
801c135c
AB
614 return 0;
615}
616
1a31b20c 617static int __erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk);
8199b901
RW
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 */
627static int do_sync_erase(struct ubi_device *ubi, struct ubi_wl_entry *e,
628 int vol_id, int lnum, int torture)
629{
1a31b20c 630 struct ubi_work wl_wrk;
8199b901
RW
631
632 dbg_wl("sync erase of PEB %i", e->pnum);
633
1a31b20c
SS
634 wl_wrk.e = e;
635 wl_wrk.vol_id = vol_id;
636 wl_wrk.lnum = lnum;
637 wl_wrk.torture = torture;
8199b901 638
1a31b20c 639 return __erase_worker(ubi, &wl_wrk);
8199b901
RW
640}
641
34b89df9 642static int ensure_wear_leveling(struct ubi_device *ubi, int nested);
801c135c
AB
643/**
644 * wear_leveling_worker - wear-leveling worker function.
645 * @ubi: UBI device description object
646 * @wrk: the work object
849271a4
RW
647 * @shutdown: non-zero if the worker has to free memory and exit
648 * because the WL-subsystem is shutting down
801c135c
AB
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 */
654static int wear_leveling_worker(struct ubi_device *ubi, struct ubi_work *wrk,
849271a4 655 int shutdown)
801c135c 656{
b86a2c56 657 int err, scrubbing = 0, torture = 0, protect = 0, erroneous = 0;
23654188 658 int erase = 0, keep = 0, vol_id = -1, lnum = -1;
8199b901
RW
659#ifdef CONFIG_MTD_UBI_FASTMAP
660 int anchor = wrk->anchor;
661#endif
801c135c 662 struct ubi_wl_entry *e1, *e2;
3291b52f 663 struct ubi_vid_io_buf *vidb;
801c135c 664 struct ubi_vid_hdr *vid_hdr;
34b89df9 665 int dst_leb_clean = 0;
801c135c
AB
666
667 kfree(wrk);
849271a4 668 if (shutdown)
801c135c
AB
669 return 0;
670
3291b52f
BB
671 vidb = ubi_alloc_vid_buf(ubi, GFP_NOFS);
672 if (!vidb)
801c135c
AB
673 return -ENOMEM;
674
3291b52f
BB
675 vid_hdr = ubi_get_vid_hdr(vidb);
676
2e8f08de 677 down_read(&ubi->fm_eba_sem);
43f9b25a 678 mutex_lock(&ubi->move_mutex);
801c135c 679 spin_lock(&ubi->wl_lock);
43f9b25a
AB
680 ubi_assert(!ubi->move_from && !ubi->move_to);
681 ubi_assert(!ubi->move_to_put);
801c135c 682
43f9b25a 683 if (!ubi->free.rb_node ||
5abde384 684 (!ubi->used.rb_node && !ubi->scrub.rb_node)) {
801c135c 685 /*
43f9b25a
AB
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.
801c135c
AB
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",
5abde384 696 !ubi->free.rb_node, !ubi->used.rb_node);
43f9b25a 697 goto out_cancel;
801c135c
AB
698 }
699
8199b901
RW
700#ifdef CONFIG_MTD_UBI_FASTMAP
701 /* Check whether we need to produce an anchor PEB */
702 if (!anchor)
889027bc 703 anchor = !anchor_pebs_available(&ubi->free);
8199b901
RW
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
5abde384 718 if (!ubi->scrub.rb_node) {
8199b901 719#endif
801c135c
AB
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 */
23553b2c 725 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, u.rb);
8199b901
RW
726 e2 = get_peb_for_wl(ubi);
727 if (!e2)
728 goto out_cancel;
801c135c
AB
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);
5ef4414f
RW
733
734 /* Give the unused PEB back */
735 wl_tree_add(e2, &ubi->free);
3d21bb76 736 ubi->free_count++;
43f9b25a 737 goto out_cancel;
801c135c 738 }
7bf523ae 739 self_check_in_wl_tree(ubi, e1, &ubi->used);
23553b2c 740 rb_erase(&e1->u.rb, &ubi->used);
801c135c
AB
741 dbg_wl("move PEB %d EC %d to PEB %d EC %d",
742 e1->pnum, e1->ec, e2->pnum, e2->ec);
743 } else {
43f9b25a
AB
744 /* Perform scrubbing */
745 scrubbing = 1;
23553b2c 746 e1 = rb_entry(rb_first(&ubi->scrub), struct ubi_wl_entry, u.rb);
8199b901
RW
747 e2 = get_peb_for_wl(ubi);
748 if (!e2)
749 goto out_cancel;
750
7bf523ae 751 self_check_in_wl_tree(ubi, e1, &ubi->scrub);
23553b2c 752 rb_erase(&e1->u.rb, &ubi->scrub);
801c135c
AB
753 dbg_wl("scrub PEB %d to PEB %d", e1->pnum, e2->pnum);
754 }
755
801c135c
AB
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.
43f9b25a
AB
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.
801c135c
AB
769 */
770
3291b52f 771 err = ubi_io_read_vid_hdr(ubi, e1->pnum, vidb, 0);
801c135c 772 if (err && err != UBI_IO_BITFLIPS) {
34b89df9 773 dst_leb_clean = 1;
74d82d26 774 if (err == UBI_IO_FF) {
801c135c
AB
775 /*
776 * We are trying to move PEB without a VID header. UBI
777 * always write VID headers shortly after the PEB was
87960c0b
AB
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,
815bc5f8
AB
781 * because presumably more data will be written there
782 * (including the missing VID header), and then we'll
87960c0b 783 * move it.
801c135c
AB
784 */
785 dbg_wl("PEB %d has no VID header", e1->pnum);
87960c0b 786 protect = 1;
43f9b25a 787 goto out_not_moved;
92e1a7d9
AB
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;
23654188
RW
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;
801c135c 808 }
43f9b25a 809
32608703 810 ubi_err(ubi, "error %d while reading VID header from PEB %d",
43f9b25a 811 err, e1->pnum);
43f9b25a 812 goto out_error;
801c135c
AB
813 }
814
9c259a52
AB
815 vol_id = be32_to_cpu(vid_hdr->vol_id);
816 lnum = be32_to_cpu(vid_hdr->lnum);
817
3291b52f 818 err = ubi_eba_copy_leb(ubi, e1->pnum, e2->pnum, vidb);
801c135c 819 if (err) {
87960c0b
AB
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;
34b89df9 829 dst_leb_clean = 1;
87960c0b
AB
830 goto out_not_moved;
831 }
e801e128
BP
832 if (err == MOVE_RETRY) {
833 scrubbing = 1;
34b89df9 834 dst_leb_clean = 1;
e801e128
BP
835 goto out_not_moved;
836 }
cc831464 837 if (err == MOVE_TARGET_BITFLIPS || err == MOVE_TARGET_WR_ERR ||
b86a2c56 838 err == MOVE_TARGET_RD_ERR) {
9c259a52
AB
839 /*
840 * Target PEB had bit-flips or write error - torture it.
841 */
6fa6f5bb 842 torture = 1;
23654188 843 keep = 1;
43f9b25a 844 goto out_not_moved;
6fa6f5bb 845 }
87960c0b 846
b86a2c56
AB
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
815bc5f8
AB
853 * put this PEB to the @ubi->erroneous list to prevent
854 * UBI from trying to move it over and over again.
b86a2c56
AB
855 */
856 if (ubi->erroneous_peb_count > ubi->max_erroneous) {
32608703 857 ubi_err(ubi, "too many erroneous eraseblocks (%d)",
b86a2c56
AB
858 ubi->erroneous_peb_count);
859 goto out_error;
860 }
34b89df9 861 dst_leb_clean = 1;
b86a2c56
AB
862 erroneous = 1;
863 goto out_not_moved;
864 }
865
90bf0265
AB
866 if (err < 0)
867 goto out_error;
43f9b25a 868
87960c0b 869 ubi_assert(0);
801c135c
AB
870 }
871
6a8f483f 872 /* The PEB has been successfully moved */
6a8f483f 873 if (scrubbing)
32608703 874 ubi_msg(ubi, "scrubbed PEB %d (LEB %d:%d), data moved to PEB %d",
9c259a52 875 e1->pnum, vol_id, lnum, e2->pnum);
3291b52f 876 ubi_free_vid_buf(vidb);
8c1e6ee1 877
801c135c 878 spin_lock(&ubi->wl_lock);
3c98b0a0 879 if (!ubi->move_to_put) {
5abde384 880 wl_tree_add(e2, &ubi->used);
3c98b0a0
AB
881 e2 = NULL;
882 }
801c135c 883 ubi->move_from = ubi->move_to = NULL;
43f9b25a 884 ubi->move_to_put = ubi->wl_scheduled = 0;
801c135c
AB
885 spin_unlock(&ubi->wl_lock);
886
8199b901 887 err = do_sync_erase(ubi, e1, vol_id, lnum, 0);
3c98b0a0 888 if (err) {
21d08bbc 889 if (e2)
ee59ba8b 890 wl_entry_destroy(ubi, e2);
87960c0b 891 goto out_ro;
3c98b0a0 892 }
6a8f483f 893
3c98b0a0 894 if (e2) {
801c135c
AB
895 /*
896 * Well, the target PEB was put meanwhile, schedule it for
897 * erasure.
898 */
9c259a52
AB
899 dbg_wl("PEB %d (LEB %d:%d) was put meanwhile, erase",
900 e2->pnum, vol_id, lnum);
8199b901 901 err = do_sync_erase(ubi, e2, vol_id, lnum, 0);
aa5ad3b6 902 if (err)
87960c0b 903 goto out_ro;
801c135c
AB
904 }
905
801c135c 906 dbg_wl("done");
43f9b25a 907 mutex_unlock(&ubi->move_mutex);
2e8f08de 908 up_read(&ubi->fm_eba_sem);
43f9b25a 909 return 0;
801c135c
AB
910
911 /*
43f9b25a
AB
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
6fa6f5bb 914 * have been changed, schedule it for erasure.
801c135c 915 */
43f9b25a 916out_not_moved:
9c259a52
AB
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);
801c135c 923 spin_lock(&ubi->wl_lock);
87960c0b
AB
924 if (protect)
925 prot_queue_add(ubi, e1);
b86a2c56
AB
926 else if (erroneous) {
927 wl_tree_add(e1, &ubi->erroneous);
928 ubi->erroneous_peb_count += 1;
929 } else if (scrubbing)
43f9b25a 930 wl_tree_add(e1, &ubi->scrub);
23654188 931 else if (keep)
5abde384 932 wl_tree_add(e1, &ubi->used);
34b89df9
SS
933 if (dst_leb_clean) {
934 wl_tree_add(e2, &ubi->free);
935 ubi->free_count++;
936 }
937
6fa6f5bb 938 ubi_assert(!ubi->move_to_put);
801c135c 939 ubi->move_from = ubi->move_to = NULL;
6fa6f5bb 940 ubi->wl_scheduled = 0;
801c135c
AB
941 spin_unlock(&ubi->wl_lock);
942
3291b52f 943 ubi_free_vid_buf(vidb);
34b89df9
SS
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 }
aa5ad3b6 951
23654188
RW
952 if (erase) {
953 err = do_sync_erase(ubi, e1, vol_id, lnum, 1);
954 if (err)
955 goto out_ro;
956 }
957
43f9b25a 958 mutex_unlock(&ubi->move_mutex);
2e8f08de 959 up_read(&ubi->fm_eba_sem);
43f9b25a
AB
960 return 0;
961
962out_error:
9c259a52 963 if (vol_id != -1)
32608703 964 ubi_err(ubi, "error %d while moving PEB %d to PEB %d",
9c259a52
AB
965 err, e1->pnum, e2->pnum);
966 else
32608703 967 ubi_err(ubi, "error %d while moving PEB %d (LEB %d:%d) to PEB %d",
9c259a52 968 err, e1->pnum, vol_id, lnum, e2->pnum);
43f9b25a
AB
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
3291b52f 974 ubi_free_vid_buf(vidb);
ee59ba8b
RW
975 wl_entry_destroy(ubi, e1);
976 wl_entry_destroy(ubi, e2);
43f9b25a 977
87960c0b
AB
978out_ro:
979 ubi_ro_mode(ubi);
43f9b25a 980 mutex_unlock(&ubi->move_mutex);
2e8f08de 981 up_read(&ubi->fm_eba_sem);
87960c0b
AB
982 ubi_assert(err != 0);
983 return err < 0 ? err : -EIO;
43f9b25a
AB
984
985out_cancel:
986 ubi->wl_scheduled = 0;
987 spin_unlock(&ubi->wl_lock);
988 mutex_unlock(&ubi->move_mutex);
2e8f08de 989 up_read(&ubi->fm_eba_sem);
3291b52f 990 ubi_free_vid_buf(vidb);
43f9b25a 991 return 0;
801c135c
AB
992}
993
994/**
995 * ensure_wear_leveling - schedule wear-leveling if it is needed.
996 * @ubi: UBI device description object
8199b901 997 * @nested: set to non-zero if this function is called from UBI worker
801c135c
AB
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 */
8199b901 1003static int ensure_wear_leveling(struct ubi_device *ubi, int nested)
801c135c
AB
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 */
5abde384
AB
1019 if (!ubi->scrub.rb_node) {
1020 if (!ubi->used.rb_node || !ubi->free.rb_node)
801c135c
AB
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
025dfdaf 1027 * erase counter of free physical eraseblocks is greater than
801c135c
AB
1028 * %UBI_WL_THRESHOLD.
1029 */
23553b2c 1030 e1 = rb_entry(rb_first(&ubi->used), struct ubi_wl_entry, u.rb);
8199b901 1031 e2 = find_wl_entry(ubi, &ubi->free, WL_FREE_MAX_DIFF);
801c135c
AB
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
33818bbb 1042 wrk = kmalloc(sizeof(struct ubi_work), GFP_NOFS);
801c135c
AB
1043 if (!wrk) {
1044 err = -ENOMEM;
1045 goto out_cancel;
1046 }
1047
8199b901 1048 wrk->anchor = 0;
801c135c 1049 wrk->func = &wear_leveling_worker;
8199b901
RW
1050 if (nested)
1051 __schedule_ubi_work(ubi, wrk);
1052 else
1053 schedule_ubi_work(ubi, wrk);
801c135c
AB
1054 return err;
1055
1056out_cancel:
1057 spin_lock(&ubi->wl_lock);
1058 ubi->wl_scheduled = 0;
1059out_unlock:
1060 spin_unlock(&ubi->wl_lock);
1061 return err;
1062}
1063
1064/**
1a31b20c 1065 * __erase_worker - physical eraseblock erase worker function.
801c135c
AB
1066 * @ubi: UBI device description object
1067 * @wl_wrk: the work object
849271a4
RW
1068 * @shutdown: non-zero if the worker has to free memory and exit
1069 * because the WL sub-system is shutting down
801c135c
AB
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 */
1a31b20c 1076static int __erase_worker(struct ubi_device *ubi, struct ubi_work *wl_wrk)
801c135c 1077{
801c135c 1078 struct ubi_wl_entry *e = wl_wrk->e;
37f758a0 1079 int pnum = e->pnum;
d36e59e6
JR
1080 int vol_id = wl_wrk->vol_id;
1081 int lnum = wl_wrk->lnum;
37f758a0 1082 int err, available_consumed = 0;
801c135c 1083
d36e59e6
JR
1084 dbg_wl("erase PEB %d EC %d LEB %d:%d",
1085 pnum, e->ec, wl_wrk->vol_id, wl_wrk->lnum);
801c135c
AB
1086
1087 err = sync_erase(ubi, e, wl_wrk->torture);
1088 if (!err) {
801c135c 1089 spin_lock(&ubi->wl_lock);
5abde384 1090 wl_tree_add(e, &ubi->free);
8199b901 1091 ubi->free_count++;
801c135c
AB
1092 spin_unlock(&ubi->wl_lock);
1093
1094 /*
9c9ec147
AB
1095 * One more erase operation has happened, take care about
1096 * protected physical eraseblocks.
801c135c 1097 */
7b6c32da 1098 serve_prot_queue(ubi);
801c135c
AB
1099
1100 /* And take care about wear-leveling */
8199b901 1101 err = ensure_wear_leveling(ubi, 1);
801c135c
AB
1102 return err;
1103 }
1104
32608703 1105 ubi_err(ubi, "failed to erase PEB %d, error %d", pnum, err);
801c135c 1106
784c1454
AB
1107 if (err == -EINTR || err == -ENOMEM || err == -EAGAIN ||
1108 err == -EBUSY) {
1109 int err1;
1110
1111 /* Re-schedule the LEB for erasure */
2e8f08de 1112 err1 = schedule_erase(ubi, e, vol_id, lnum, 0, false);
784c1454 1113 if (err1) {
6b238de1 1114 wl_entry_destroy(ubi, e);
784c1454
AB
1115 err = err1;
1116 goto out_ro;
1117 }
1118 return err;
e57e0d8e
AB
1119 }
1120
ee59ba8b 1121 wl_entry_destroy(ubi, e);
e57e0d8e 1122 if (err != -EIO)
801c135c
AB
1123 /*
1124 * If this is not %-EIO, we have no idea what to do. Scheduling
1125 * this physical eraseblock for erasure again would cause
815bc5f8 1126 * errors again and again. Well, lets switch to R/O mode.
801c135c 1127 */
784c1454 1128 goto out_ro;
801c135c
AB
1129
1130 /* It is %-EIO, the PEB went bad */
1131
1132 if (!ubi->bad_allowed) {
32608703 1133 ubi_err(ubi, "bad physical eraseblock %d detected", pnum);
784c1454
AB
1134 goto out_ro;
1135 }
801c135c 1136
784c1454 1137 spin_lock(&ubi->volumes_lock);
784c1454 1138 if (ubi->beb_rsvd_pebs == 0) {
37f758a0
SL
1139 if (ubi->avail_pebs == 0) {
1140 spin_unlock(&ubi->volumes_lock);
32608703 1141 ubi_err(ubi, "no reserved/available physical eraseblocks");
37f758a0
SL
1142 goto out_ro;
1143 }
1144 ubi->avail_pebs -= 1;
1145 available_consumed = 1;
784c1454 1146 }
784c1454 1147 spin_unlock(&ubi->volumes_lock);
801c135c 1148
32608703 1149 ubi_msg(ubi, "mark PEB %d as bad", pnum);
784c1454
AB
1150 err = ubi_io_mark_bad(ubi, pnum);
1151 if (err)
1152 goto out_ro;
1153
1154 spin_lock(&ubi->volumes_lock);
37f758a0
SL
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 }
784c1454
AB
1166 ubi->bad_peb_count += 1;
1167 ubi->good_peb_count -= 1;
1168 ubi_calculate_reserved(ubi);
37f758a0 1169 if (available_consumed)
32608703 1170 ubi_warn(ubi, "no PEBs in the reserved pool, used an available PEB");
37f758a0 1171 else if (ubi->beb_rsvd_pebs)
32608703
TB
1172 ubi_msg(ubi, "%d PEBs left in the reserve",
1173 ubi->beb_rsvd_pebs);
52b605d1 1174 else
32608703 1175 ubi_warn(ubi, "last PEB from the reserve was used");
784c1454
AB
1176 spin_unlock(&ubi->volumes_lock);
1177
1178 return err;
801c135c 1179
784c1454 1180out_ro:
37f758a0
SL
1181 if (available_consumed) {
1182 spin_lock(&ubi->volumes_lock);
1183 ubi->avail_pebs += 1;
1184 spin_unlock(&ubi->volumes_lock);
1185 }
784c1454 1186 ubi_ro_mode(ubi);
801c135c
AB
1187 return err;
1188}
1189
1a31b20c
SS
1190static 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
801c135c 1209/**
85c6e6e2 1210 * ubi_wl_put_peb - return a PEB to the wear-leveling sub-system.
801c135c 1211 * @ubi: UBI device description object
d36e59e6
JR
1212 * @vol_id: the volume ID that last used this PEB
1213 * @lnum: the last used logical eraseblock number for the PEB
801c135c
AB
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
43f9b25a 1220 * in case of success, and a negative error code in case of failure.
801c135c 1221 */
d36e59e6
JR
1222int ubi_wl_put_peb(struct ubi_device *ubi, int vol_id, int lnum,
1223 int pnum, int torture)
801c135c
AB
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
111ab0b2
RW
1232 down_read(&ubi->fm_protect);
1233
43f9b25a 1234retry:
801c135c 1235 spin_lock(&ubi->wl_lock);
801c135c
AB
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 */
43f9b25a 1243 dbg_wl("PEB %d is being moved, wait", pnum);
801c135c 1244 spin_unlock(&ubi->wl_lock);
43f9b25a
AB
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;
801c135c
AB
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
85c6e6e2
AB
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.
801c135c
AB
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);
111ab0b2 1264 up_read(&ubi->fm_protect);
801c135c
AB
1265 return 0;
1266 } else {
5abde384 1267 if (in_wl_tree(e, &ubi->used)) {
7bf523ae 1268 self_check_in_wl_tree(ubi, e, &ubi->used);
23553b2c 1269 rb_erase(&e->u.rb, &ubi->used);
5abde384 1270 } else if (in_wl_tree(e, &ubi->scrub)) {
7bf523ae 1271 self_check_in_wl_tree(ubi, e, &ubi->scrub);
23553b2c 1272 rb_erase(&e->u.rb, &ubi->scrub);
b86a2c56 1273 } else if (in_wl_tree(e, &ubi->erroneous)) {
7bf523ae 1274 self_check_in_wl_tree(ubi, e, &ubi->erroneous);
b86a2c56
AB
1275 rb_erase(&e->u.rb, &ubi->erroneous);
1276 ubi->erroneous_peb_count -= 1;
1277 ubi_assert(ubi->erroneous_peb_count >= 0);
815bc5f8 1278 /* Erroneous PEBs should be tortured */
b86a2c56 1279 torture = 1;
43f9b25a 1280 } else {
7b6c32da 1281 err = prot_queue_del(ubi, e->pnum);
43f9b25a 1282 if (err) {
32608703 1283 ubi_err(ubi, "PEB %d not found", pnum);
43f9b25a
AB
1284 ubi_ro_mode(ubi);
1285 spin_unlock(&ubi->wl_lock);
111ab0b2 1286 up_read(&ubi->fm_protect);
43f9b25a
AB
1287 return err;
1288 }
1289 }
801c135c
AB
1290 }
1291 spin_unlock(&ubi->wl_lock);
1292
2e8f08de 1293 err = schedule_erase(ubi, e, vol_id, lnum, torture, false);
801c135c
AB
1294 if (err) {
1295 spin_lock(&ubi->wl_lock);
5abde384 1296 wl_tree_add(e, &ubi->used);
801c135c
AB
1297 spin_unlock(&ubi->wl_lock);
1298 }
1299
111ab0b2 1300 up_read(&ubi->fm_protect);
801c135c
AB
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 */
1314int ubi_wl_scrub_peb(struct ubi_device *ubi, int pnum)
1315{
1316 struct ubi_wl_entry *e;
1317
32608703 1318 ubi_msg(ubi, "schedule PEB %d for scrubbing", pnum);
801c135c
AB
1319
1320retry:
1321 spin_lock(&ubi->wl_lock);
1322 e = ubi->lookuptbl[pnum];
d3f6e6c6
AB
1323 if (e == ubi->move_from || in_wl_tree(e, &ubi->scrub) ||
1324 in_wl_tree(e, &ubi->erroneous)) {
801c135c
AB
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
5abde384 1342 if (in_wl_tree(e, &ubi->used)) {
7bf523ae 1343 self_check_in_wl_tree(ubi, e, &ubi->used);
23553b2c 1344 rb_erase(&e->u.rb, &ubi->used);
43f9b25a
AB
1345 } else {
1346 int err;
1347
7b6c32da 1348 err = prot_queue_del(ubi, e->pnum);
43f9b25a 1349 if (err) {
32608703 1350 ubi_err(ubi, "PEB %d not found", pnum);
43f9b25a
AB
1351 ubi_ro_mode(ubi);
1352 spin_unlock(&ubi->wl_lock);
1353 return err;
1354 }
1355 }
801c135c 1356
5abde384 1357 wl_tree_add(e, &ubi->scrub);
801c135c
AB
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 */
8199b901 1364 return ensure_wear_leveling(ubi, 0);
801c135c
AB
1365}
1366
1367/**
1368 * ubi_wl_flush - flush all pending works.
1369 * @ubi: UBI device description object
62f38455
JR
1370 * @vol_id: the volume id to flush for
1371 * @lnum: the logical eraseblock number to flush for
801c135c 1372 *
62f38455
JR
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.
801c135c 1378 */
62f38455 1379int ubi_wl_flush(struct ubi_device *ubi, int vol_id, int lnum)
801c135c 1380{
62f38455
JR
1381 int err = 0;
1382 int found = 1;
801c135c
AB
1383
1384 /*
7b6c32da 1385 * Erase while the pending works queue is not empty, but not more than
801c135c
AB
1386 * the number of currently pending works.
1387 */
62f38455
JR
1388 dbg_wl("flush pending work for LEB %d:%d (%d pending works)",
1389 vol_id, lnum, ubi->works_count);
593dd33c 1390
62f38455 1391 while (found) {
49e236bc 1392 struct ubi_work *wrk, *tmp;
62f38455 1393 found = 0;
593dd33c 1394
12027f1b 1395 down_read(&ubi->work_sem);
62f38455 1396 spin_lock(&ubi->wl_lock);
49e236bc 1397 list_for_each_entry_safe(wrk, tmp, &ubi->works, list) {
62f38455
JR
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);
12027f1b
AB
1406 if (err) {
1407 up_read(&ubi->work_sem);
1408 return err;
1409 }
1410
62f38455
JR
1411 spin_lock(&ubi->wl_lock);
1412 found = 1;
1413 break;
1414 }
1415 }
1416 spin_unlock(&ubi->wl_lock);
12027f1b 1417 up_read(&ubi->work_sem);
801c135c
AB
1418 }
1419
12027f1b
AB
1420 /*
1421 * Make sure all the works which have been done in parallel are
1422 * finished.
1423 */
1424 down_write(&ubi->work_sem);
62f38455 1425 up_write(&ubi->work_sem);
12027f1b 1426
62f38455 1427 return err;
801c135c
AB
1428}
1429
663586c0
RW
1430static 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 */
1463int ubi_bitflip_check(struct ubi_device *ubi, int pnum, int force)
1464{
04d37e5a 1465 int err = 0;
663586c0
RW
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
5578e48e 1507 if (force || err == UBI_IO_BITFLIPS) {
663586c0
RW
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
1567out_resume:
1568 up_write(&ubi->work_sem);
1569out:
1570
1571 return err;
1572}
1573
801c135c
AB
1574/**
1575 * tree_destroy - destroy an RB-tree.
ee59ba8b 1576 * @ubi: UBI device description object
801c135c
AB
1577 * @root: the root of the tree to destroy
1578 */
ee59ba8b 1579static void tree_destroy(struct ubi_device *ubi, struct rb_root *root)
801c135c
AB
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 {
23553b2c 1591 e = rb_entry(rb, struct ubi_wl_entry, u.rb);
801c135c
AB
1592
1593 rb = rb_parent(rb);
1594 if (rb) {
23553b2c 1595 if (rb->rb_left == &e->u.rb)
801c135c
AB
1596 rb->rb_left = NULL;
1597 else
1598 rb->rb_right = NULL;
1599 }
1600
ee59ba8b 1601 wl_entry_destroy(ubi, e);
801c135c
AB
1602 }
1603 }
1604}
1605
1606/**
1607 * ubi_thread - UBI background thread.
1608 * @u: the UBI device description object pointer
1609 */
cdfa788a 1610int ubi_thread(void *u)
801c135c
AB
1611{
1612 int failures = 0;
1613 struct ubi_device *ubi = u;
1614
32608703 1615 ubi_msg(ubi, "background thread \"%s\" started, PID %d",
ba25f9dc 1616 ubi->bgt_name, task_pid_nr(current));
801c135c 1617
83144186 1618 set_freezable();
801c135c
AB
1619 for (;;) {
1620 int err;
1621
45fc5c81 1622 if (kthread_should_stop())
cadb40cc 1623 break;
801c135c
AB
1624
1625 if (try_to_freeze())
1626 continue;
1627
1628 spin_lock(&ubi->wl_lock);
1629 if (list_empty(&ubi->works) || ubi->ro_mode ||
27a0f2a3 1630 !ubi->thread_enabled || ubi_dbg_is_bgt_disabled(ubi)) {
801c135c
AB
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) {
32608703 1640 ubi_err(ubi, "%s: work failed with error code %d",
801c135c
AB
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 */
32608703 1647 ubi_msg(ubi, "%s: %d consecutive failures",
801c135c
AB
1648 ubi->bgt_name, WL_MAX_FAILURES);
1649 ubi_ro_mode(ubi);
2ad49887
VG
1650 ubi->thread_enabled = 0;
1651 continue;
801c135c
AB
1652 }
1653 } else
1654 failures = 0;
1655
1656 cond_resched();
1657 }
1658
801c135c 1659 dbg_wl("background thread \"%s\" is killed", ubi->bgt_name);
6e7d8016 1660 ubi->thread_enabled = 0;
801c135c
AB
1661 return 0;
1662}
1663
1664/**
849271a4 1665 * shutdown_work - shutdown all pending works.
801c135c
AB
1666 * @ubi: UBI device description object
1667 */
849271a4 1668static void shutdown_work(struct ubi_device *ubi)
801c135c
AB
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
f78e5623
SH
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 */
1687static 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
1715out_free:
1716 wl_entry_destroy(ubi, e);
1717
1718 return err;
1719}
1720
801c135c 1721/**
41e0cd9d 1722 * ubi_wl_init - initialize the WL sub-system using attaching information.
801c135c 1723 * @ubi: UBI device description object
a4e6042f 1724 * @ai: attaching information
801c135c
AB
1725 *
1726 * This function returns zero in case of success, and a negative error code in
1727 * case of failure.
1728 */
41e0cd9d 1729int ubi_wl_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
801c135c 1730{
8199b901 1731 int err, i, reserved_pebs, found_pebs = 0;
801c135c 1732 struct rb_node *rb1, *rb2;
517af48c 1733 struct ubi_ainf_volume *av;
2c5ec5ce 1734 struct ubi_ainf_peb *aeb, *tmp;
801c135c
AB
1735 struct ubi_wl_entry *e;
1736
b86a2c56 1737 ubi->used = ubi->erroneous = ubi->free = ubi->scrub = RB_ROOT;
801c135c 1738 spin_lock_init(&ubi->wl_lock);
43f9b25a 1739 mutex_init(&ubi->move_mutex);
593dd33c 1740 init_rwsem(&ubi->work_sem);
a4e6042f 1741 ubi->max_ec = ai->max_ec;
801c135c
AB
1742 INIT_LIST_HEAD(&ubi->works);
1743
1744 sprintf(ubi->bgt_name, UBI_BGT_NAME_PATTERN, ubi->ubi_num);
1745
801c135c 1746 err = -ENOMEM;
6396bb22 1747 ubi->lookuptbl = kcalloc(ubi->peb_count, sizeof(void *), GFP_KERNEL);
801c135c 1748 if (!ubi->lookuptbl)
cdfa788a 1749 return err;
801c135c 1750
7b6c32da
XX
1751 for (i = 0; i < UBI_PROT_QUEUE_LEN; i++)
1752 INIT_LIST_HEAD(&ubi->pq[i]);
1753 ubi->pq_head = 0;
1754
73b0cd57 1755 ubi->free_count = 0;
a4e6042f 1756 list_for_each_entry_safe(aeb, tmp, &ai->erase, u.list) {
801c135c
AB
1757 cond_resched();
1758
f78e5623
SH
1759 err = erase_aeb(ubi, aeb, false);
1760 if (err)
801c135c
AB
1761 goto out_free;
1762
8199b901 1763 found_pebs++;
801c135c
AB
1764 }
1765
a4e6042f 1766 list_for_each_entry(aeb, &ai->free, u.list) {
801c135c
AB
1767 cond_resched();
1768
06b68ba1 1769 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
7233982a
WY
1770 if (!e) {
1771 err = -ENOMEM;
801c135c 1772 goto out_free;
7233982a 1773 }
801c135c 1774
2c5ec5ce
AB
1775 e->pnum = aeb->pnum;
1776 e->ec = aeb->ec;
801c135c 1777 ubi_assert(e->ec >= 0);
8199b901 1778
5abde384 1779 wl_tree_add(e, &ubi->free);
8199b901
RW
1780 ubi->free_count++;
1781
801c135c 1782 ubi->lookuptbl[e->pnum] = e;
8199b901
RW
1783
1784 found_pebs++;
801c135c
AB
1785 }
1786
517af48c
AB
1787 ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
1788 ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
801c135c
AB
1789 cond_resched();
1790
06b68ba1 1791 e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
7233982a
WY
1792 if (!e) {
1793 err = -ENOMEM;
801c135c 1794 goto out_free;
7233982a 1795 }
801c135c 1796
2c5ec5ce
AB
1797 e->pnum = aeb->pnum;
1798 e->ec = aeb->ec;
801c135c 1799 ubi->lookuptbl[e->pnum] = e;
8199b901 1800
2c5ec5ce 1801 if (!aeb->scrub) {
801c135c
AB
1802 dbg_wl("add PEB %d EC %d to the used tree",
1803 e->pnum, e->ec);
5abde384 1804 wl_tree_add(e, &ubi->used);
801c135c
AB
1805 } else {
1806 dbg_wl("add PEB %d EC %d to the scrub tree",
1807 e->pnum, e->ec);
5abde384 1808 wl_tree_add(e, &ubi->scrub);
801c135c 1809 }
8199b901
RW
1810
1811 found_pebs++;
801c135c
AB
1812 }
1813 }
1814
fdf10ed7
RW
1815 list_for_each_entry(aeb, &ai->fastmap, u.list) {
1816 cond_resched();
1817
1818 e = ubi_find_fm_block(ubi, aeb->pnum);
8199b901 1819
fdf10ed7
RW
1820 if (e) {
1821 ubi_assert(!ubi->lookuptbl[e->pnum]);
1822 ubi->lookuptbl[e->pnum] = e;
1823 } else {
f78e5623
SH
1824 bool sync = false;
1825
fdf10ed7
RW
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
f78e5623
SH
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;
68303564 1846
f78e5623
SH
1847 err = erase_aeb(ubi, aeb, sync);
1848 if (err)
fdf10ed7 1849 goto out_free;
68303564 1850 }
fdf10ed7
RW
1851
1852 found_pebs++;
68303564 1853 }
fdf10ed7
RW
1854
1855 dbg_wl("found %i PEBs", found_pebs);
1856
1857 ubi_assert(ubi->good_peb_count == found_pebs);
8199b901
RW
1858
1859 reserved_pebs = WL_RESERVED_PEBS;
acfda79f 1860 ubi_fastmap_init(ubi, &reserved_pebs);
8199b901
RW
1861
1862 if (ubi->avail_pebs < reserved_pebs) {
32608703 1863 ubi_err(ubi, "no enough physical eraseblocks (%d, need %d)",
8199b901 1864 ubi->avail_pebs, reserved_pebs);
5fc01ab6 1865 if (ubi->corr_peb_count)
32608703 1866 ubi_err(ubi, "%d PEBs are corrupted and not used",
5fc01ab6 1867 ubi->corr_peb_count);
7c7feb2e 1868 err = -ENOSPC;
801c135c
AB
1869 goto out_free;
1870 }
8199b901
RW
1871 ubi->avail_pebs -= reserved_pebs;
1872 ubi->rsvd_pebs += reserved_pebs;
801c135c
AB
1873
1874 /* Schedule wear-leveling if needed */
8199b901 1875 err = ensure_wear_leveling(ubi, 0);
801c135c
AB
1876 if (err)
1877 goto out_free;
1878
1879 return 0;
1880
1881out_free:
849271a4 1882 shutdown_work(ubi);
ee59ba8b
RW
1883 tree_destroy(ubi, &ubi->used);
1884 tree_destroy(ubi, &ubi->free);
1885 tree_destroy(ubi, &ubi->scrub);
801c135c 1886 kfree(ubi->lookuptbl);
801c135c
AB
1887 return err;
1888}
1889
1890/**
7b6c32da 1891 * protection_queue_destroy - destroy the protection queue.
801c135c
AB
1892 * @ubi: UBI device description object
1893 */
7b6c32da 1894static void protection_queue_destroy(struct ubi_device *ubi)
801c135c 1895{
7b6c32da
XX
1896 int i;
1897 struct ubi_wl_entry *e, *tmp;
801c135c 1898
7b6c32da
XX
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);
ee59ba8b 1902 wl_entry_destroy(ubi, e);
801c135c
AB
1903 }
1904 }
1905}
1906
1907/**
85c6e6e2 1908 * ubi_wl_close - close the wear-leveling sub-system.
801c135c
AB
1909 * @ubi: UBI device description object
1910 */
1911void ubi_wl_close(struct ubi_device *ubi)
1912{
85c6e6e2 1913 dbg_wl("close the WL sub-system");
74cdaf24 1914 ubi_fastmap_close(ubi);
849271a4 1915 shutdown_work(ubi);
7b6c32da 1916 protection_queue_destroy(ubi);
ee59ba8b
RW
1917 tree_destroy(ubi, &ubi->used);
1918 tree_destroy(ubi, &ubi->erroneous);
1919 tree_destroy(ubi, &ubi->free);
1920 tree_destroy(ubi, &ubi->scrub);
801c135c 1921 kfree(ubi->lookuptbl);
801c135c
AB
1922}
1923
801c135c 1924/**
7bf523ae 1925 * self_check_ec - make sure that the erase counter of a PEB is correct.
801c135c
AB
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
feddbb34
AB
1931 * is equivalent to @ec, and a negative error code if not or if an error
1932 * occurred.
801c135c 1933 */
7bf523ae 1934static int self_check_ec(struct ubi_device *ubi, int pnum, int ec)
801c135c
AB
1935{
1936 int err;
1937 long long read_ec;
1938 struct ubi_ec_hdr *ec_hdr;
1939
64575574 1940 if (!ubi_dbg_chk_gen(ubi))
92d124f5
AB
1941 return 0;
1942
33818bbb 1943 ec_hdr = kzalloc(ubi->ec_hdr_alsize, GFP_NOFS);
801c135c
AB
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
3261ebd7 1954 read_ec = be64_to_cpu(ec_hdr->ec);
8199b901 1955 if (ec != read_ec && read_ec - ec > 1) {
32608703
TB
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);
25886a36 1958 dump_stack();
801c135c
AB
1959 err = 1;
1960 } else
1961 err = 0;
1962
1963out_free:
1964 kfree(ec_hdr);
1965 return err;
1966}
1967
1968/**
7bf523ae 1969 * self_check_in_wl_tree - check that wear-leveling entry is in WL RB-tree.
d99383b0 1970 * @ubi: UBI device description object
801c135c
AB
1971 * @e: the wear-leveling entry to check
1972 * @root: the root of the tree
1973 *
adbf05e3
AB
1974 * This function returns zero if @e is in the @root RB-tree and %-EINVAL if it
1975 * is not.
801c135c 1976 */
7bf523ae
AB
1977static int self_check_in_wl_tree(const struct ubi_device *ubi,
1978 struct ubi_wl_entry *e, struct rb_root *root)
801c135c 1979{
64575574 1980 if (!ubi_dbg_chk_gen(ubi))
92d124f5
AB
1981 return 0;
1982
801c135c
AB
1983 if (in_wl_tree(e, root))
1984 return 0;
1985
32608703 1986 ubi_err(ubi, "self-check failed for PEB %d, EC %d, RB-tree %p ",
801c135c 1987 e->pnum, e->ec, root);
25886a36 1988 dump_stack();
adbf05e3 1989 return -EINVAL;
801c135c
AB
1990}
1991
7b6c32da 1992/**
7bf523ae 1993 * self_check_in_pq - check if wear-leveling entry is in the protection
7b6c32da
XX
1994 * queue.
1995 * @ubi: UBI device description object
1996 * @e: the wear-leveling entry to check
1997 *
adbf05e3 1998 * This function returns zero if @e is in @ubi->pq and %-EINVAL if it is not.
7b6c32da 1999 */
7bf523ae
AB
2000static int self_check_in_pq(const struct ubi_device *ubi,
2001 struct ubi_wl_entry *e)
7b6c32da 2002{
64575574 2003 if (!ubi_dbg_chk_gen(ubi))
92d124f5
AB
2004 return 0;
2005
b32b78f8
RW
2006 if (in_pq(ubi, e))
2007 return 0;
7b6c32da 2008
32608703 2009 ubi_err(ubi, "self-check failed for PEB %d, EC %d, Protect queue",
7b6c32da 2010 e->pnum, e->ec);
25886a36 2011 dump_stack();
adbf05e3 2012 return -EINVAL;
7b6c32da 2013}
78d6d497
RW
2014#ifndef CONFIG_MTD_UBI_FASTMAP
2015static 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 */
2037static 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 */
2063int ubi_wl_get_peb(struct ubi_device *ubi)
2064{
2065 int err;
2066 struct ubi_wl_entry *e;
2067
2068retry:
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