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