xref: /openbmc/u-boot/fs/ubifs/gc.c (revision baefb63a)
1 /*
2  * This file is part of UBIFS.
3  *
4  * Copyright (C) 2006-2008 Nokia Corporation.
5  *
6  * SPDX-License-Identifier:	GPL-2.0
7  *
8  * Authors: Adrian Hunter
9  *          Artem Bityutskiy (Битюцкий Артём)
10  */
11 
12 /*
13  * This file implements garbage collection. The procedure for garbage collection
14  * is different depending on whether a LEB as an index LEB (contains index
15  * nodes) or not. For non-index LEBs, garbage collection finds a LEB which
16  * contains a lot of dirty space (obsolete nodes), and copies the non-obsolete
17  * nodes to the journal, at which point the garbage-collected LEB is free to be
18  * reused. For index LEBs, garbage collection marks the non-obsolete index nodes
19  * dirty in the TNC, and after the next commit, the garbage-collected LEB is
20  * to be reused. Garbage collection will cause the number of dirty index nodes
21  * to grow, however sufficient space is reserved for the index to ensure the
22  * commit will never run out of space.
23  *
24  * Notes about dead watermark. At current UBIFS implementation we assume that
25  * LEBs which have less than @c->dead_wm bytes of free + dirty space are full
26  * and not worth garbage-collecting. The dead watermark is one min. I/O unit
27  * size, or min. UBIFS node size, depending on what is greater. Indeed, UBIFS
28  * Garbage Collector has to synchronize the GC head's write buffer before
29  * returning, so this is about wasting one min. I/O unit. However, UBIFS GC can
30  * actually reclaim even very small pieces of dirty space by garbage collecting
31  * enough dirty LEBs, but we do not bother doing this at this implementation.
32  *
33  * Notes about dark watermark. The results of GC work depends on how big are
34  * the UBIFS nodes GC deals with. Large nodes make GC waste more space. Indeed,
35  * if GC move data from LEB A to LEB B and nodes in LEB A are large, GC would
36  * have to waste large pieces of free space at the end of LEB B, because nodes
37  * from LEB A would not fit. And the worst situation is when all nodes are of
38  * maximum size. So dark watermark is the amount of free + dirty space in LEB
39  * which are guaranteed to be reclaimable. If LEB has less space, the GC might
40  * be unable to reclaim it. So, LEBs with free + dirty greater than dark
41  * watermark are "good" LEBs from GC's point of few. The other LEBs are not so
42  * good, and GC takes extra care when moving them.
43  */
44 #ifndef __UBOOT__
45 #include <linux/slab.h>
46 #include <linux/pagemap.h>
47 #include <linux/list_sort.h>
48 #endif
49 #include "ubifs.h"
50 
51 #ifndef __UBOOT__
52 /*
53  * GC may need to move more than one LEB to make progress. The below constants
54  * define "soft" and "hard" limits on the number of LEBs the garbage collector
55  * may move.
56  */
57 #define SOFT_LEBS_LIMIT 4
58 #define HARD_LEBS_LIMIT 32
59 
60 /**
61  * switch_gc_head - switch the garbage collection journal head.
62  * @c: UBIFS file-system description object
63  * @buf: buffer to write
64  * @len: length of the buffer to write
65  * @lnum: LEB number written is returned here
66  * @offs: offset written is returned here
67  *
68  * This function switch the GC head to the next LEB which is reserved in
69  * @c->gc_lnum. Returns %0 in case of success, %-EAGAIN if commit is required,
70  * and other negative error code in case of failures.
71  */
72 static int switch_gc_head(struct ubifs_info *c)
73 {
74 	int err, gc_lnum = c->gc_lnum;
75 	struct ubifs_wbuf *wbuf = &c->jheads[GCHD].wbuf;
76 
77 	ubifs_assert(gc_lnum != -1);
78 	dbg_gc("switch GC head from LEB %d:%d to LEB %d (waste %d bytes)",
79 	       wbuf->lnum, wbuf->offs + wbuf->used, gc_lnum,
80 	       c->leb_size - wbuf->offs - wbuf->used);
81 
82 	err = ubifs_wbuf_sync_nolock(wbuf);
83 	if (err)
84 		return err;
85 
86 	/*
87 	 * The GC write-buffer was synchronized, we may safely unmap
88 	 * 'c->gc_lnum'.
89 	 */
90 	err = ubifs_leb_unmap(c, gc_lnum);
91 	if (err)
92 		return err;
93 
94 	err = ubifs_wbuf_sync_nolock(wbuf);
95 	if (err)
96 		return err;
97 
98 	err = ubifs_add_bud_to_log(c, GCHD, gc_lnum, 0);
99 	if (err)
100 		return err;
101 
102 	c->gc_lnum = -1;
103 	err = ubifs_wbuf_seek_nolock(wbuf, gc_lnum, 0);
104 	return err;
105 }
106 
107 /**
108  * data_nodes_cmp - compare 2 data nodes.
109  * @priv: UBIFS file-system description object
110  * @a: first data node
111  * @a: second data node
112  *
113  * This function compares data nodes @a and @b. Returns %1 if @a has greater
114  * inode or block number, and %-1 otherwise.
115  */
116 static int data_nodes_cmp(void *priv, struct list_head *a, struct list_head *b)
117 {
118 	ino_t inuma, inumb;
119 	struct ubifs_info *c = priv;
120 	struct ubifs_scan_node *sa, *sb;
121 
122 	cond_resched();
123 	if (a == b)
124 		return 0;
125 
126 	sa = list_entry(a, struct ubifs_scan_node, list);
127 	sb = list_entry(b, struct ubifs_scan_node, list);
128 
129 	ubifs_assert(key_type(c, &sa->key) == UBIFS_DATA_KEY);
130 	ubifs_assert(key_type(c, &sb->key) == UBIFS_DATA_KEY);
131 	ubifs_assert(sa->type == UBIFS_DATA_NODE);
132 	ubifs_assert(sb->type == UBIFS_DATA_NODE);
133 
134 	inuma = key_inum(c, &sa->key);
135 	inumb = key_inum(c, &sb->key);
136 
137 	if (inuma == inumb) {
138 		unsigned int blka = key_block(c, &sa->key);
139 		unsigned int blkb = key_block(c, &sb->key);
140 
141 		if (blka <= blkb)
142 			return -1;
143 	} else if (inuma <= inumb)
144 		return -1;
145 
146 	return 1;
147 }
148 
149 /*
150  * nondata_nodes_cmp - compare 2 non-data nodes.
151  * @priv: UBIFS file-system description object
152  * @a: first node
153  * @a: second node
154  *
155  * This function compares nodes @a and @b. It makes sure that inode nodes go
156  * first and sorted by length in descending order. Directory entry nodes go
157  * after inode nodes and are sorted in ascending hash valuer order.
158  */
159 static int nondata_nodes_cmp(void *priv, struct list_head *a,
160 			     struct list_head *b)
161 {
162 	ino_t inuma, inumb;
163 	struct ubifs_info *c = priv;
164 	struct ubifs_scan_node *sa, *sb;
165 
166 	cond_resched();
167 	if (a == b)
168 		return 0;
169 
170 	sa = list_entry(a, struct ubifs_scan_node, list);
171 	sb = list_entry(b, struct ubifs_scan_node, list);
172 
173 	ubifs_assert(key_type(c, &sa->key) != UBIFS_DATA_KEY &&
174 		     key_type(c, &sb->key) != UBIFS_DATA_KEY);
175 	ubifs_assert(sa->type != UBIFS_DATA_NODE &&
176 		     sb->type != UBIFS_DATA_NODE);
177 
178 	/* Inodes go before directory entries */
179 	if (sa->type == UBIFS_INO_NODE) {
180 		if (sb->type == UBIFS_INO_NODE)
181 			return sb->len - sa->len;
182 		return -1;
183 	}
184 	if (sb->type == UBIFS_INO_NODE)
185 		return 1;
186 
187 	ubifs_assert(key_type(c, &sa->key) == UBIFS_DENT_KEY ||
188 		     key_type(c, &sa->key) == UBIFS_XENT_KEY);
189 	ubifs_assert(key_type(c, &sb->key) == UBIFS_DENT_KEY ||
190 		     key_type(c, &sb->key) == UBIFS_XENT_KEY);
191 	ubifs_assert(sa->type == UBIFS_DENT_NODE ||
192 		     sa->type == UBIFS_XENT_NODE);
193 	ubifs_assert(sb->type == UBIFS_DENT_NODE ||
194 		     sb->type == UBIFS_XENT_NODE);
195 
196 	inuma = key_inum(c, &sa->key);
197 	inumb = key_inum(c, &sb->key);
198 
199 	if (inuma == inumb) {
200 		uint32_t hasha = key_hash(c, &sa->key);
201 		uint32_t hashb = key_hash(c, &sb->key);
202 
203 		if (hasha <= hashb)
204 			return -1;
205 	} else if (inuma <= inumb)
206 		return -1;
207 
208 	return 1;
209 }
210 
211 /**
212  * sort_nodes - sort nodes for GC.
213  * @c: UBIFS file-system description object
214  * @sleb: describes nodes to sort and contains the result on exit
215  * @nondata: contains non-data nodes on exit
216  * @min: minimum node size is returned here
217  *
218  * This function sorts the list of inodes to garbage collect. First of all, it
219  * kills obsolete nodes and separates data and non-data nodes to the
220  * @sleb->nodes and @nondata lists correspondingly.
221  *
222  * Data nodes are then sorted in block number order - this is important for
223  * bulk-read; data nodes with lower inode number go before data nodes with
224  * higher inode number, and data nodes with lower block number go before data
225  * nodes with higher block number;
226  *
227  * Non-data nodes are sorted as follows.
228  *   o First go inode nodes - they are sorted in descending length order.
229  *   o Then go directory entry nodes - they are sorted in hash order, which
230  *     should supposedly optimize 'readdir()'. Direntry nodes with lower parent
231  *     inode number go before direntry nodes with higher parent inode number,
232  *     and direntry nodes with lower name hash values go before direntry nodes
233  *     with higher name hash values.
234  *
235  * This function returns zero in case of success and a negative error code in
236  * case of failure.
237  */
238 static int sort_nodes(struct ubifs_info *c, struct ubifs_scan_leb *sleb,
239 		      struct list_head *nondata, int *min)
240 {
241 	int err;
242 	struct ubifs_scan_node *snod, *tmp;
243 
244 	*min = INT_MAX;
245 
246 	/* Separate data nodes and non-data nodes */
247 	list_for_each_entry_safe(snod, tmp, &sleb->nodes, list) {
248 		ubifs_assert(snod->type == UBIFS_INO_NODE  ||
249 			     snod->type == UBIFS_DATA_NODE ||
250 			     snod->type == UBIFS_DENT_NODE ||
251 			     snod->type == UBIFS_XENT_NODE ||
252 			     snod->type == UBIFS_TRUN_NODE);
253 
254 		if (snod->type != UBIFS_INO_NODE  &&
255 		    snod->type != UBIFS_DATA_NODE &&
256 		    snod->type != UBIFS_DENT_NODE &&
257 		    snod->type != UBIFS_XENT_NODE) {
258 			/* Probably truncation node, zap it */
259 			list_del(&snod->list);
260 			kfree(snod);
261 			continue;
262 		}
263 
264 		ubifs_assert(key_type(c, &snod->key) == UBIFS_DATA_KEY ||
265 			     key_type(c, &snod->key) == UBIFS_INO_KEY  ||
266 			     key_type(c, &snod->key) == UBIFS_DENT_KEY ||
267 			     key_type(c, &snod->key) == UBIFS_XENT_KEY);
268 
269 		err = ubifs_tnc_has_node(c, &snod->key, 0, sleb->lnum,
270 					 snod->offs, 0);
271 		if (err < 0)
272 			return err;
273 
274 		if (!err) {
275 			/* The node is obsolete, remove it from the list */
276 			list_del(&snod->list);
277 			kfree(snod);
278 			continue;
279 		}
280 
281 		if (snod->len < *min)
282 			*min = snod->len;
283 
284 		if (key_type(c, &snod->key) != UBIFS_DATA_KEY)
285 			list_move_tail(&snod->list, nondata);
286 	}
287 
288 	/* Sort data and non-data nodes */
289 	list_sort(c, &sleb->nodes, &data_nodes_cmp);
290 	list_sort(c, nondata, &nondata_nodes_cmp);
291 
292 	err = dbg_check_data_nodes_order(c, &sleb->nodes);
293 	if (err)
294 		return err;
295 	err = dbg_check_nondata_nodes_order(c, nondata);
296 	if (err)
297 		return err;
298 	return 0;
299 }
300 
301 /**
302  * move_node - move a node.
303  * @c: UBIFS file-system description object
304  * @sleb: describes the LEB to move nodes from
305  * @snod: the mode to move
306  * @wbuf: write-buffer to move node to
307  *
308  * This function moves node @snod to @wbuf, changes TNC correspondingly, and
309  * destroys @snod. Returns zero in case of success and a negative error code in
310  * case of failure.
311  */
312 static int move_node(struct ubifs_info *c, struct ubifs_scan_leb *sleb,
313 		     struct ubifs_scan_node *snod, struct ubifs_wbuf *wbuf)
314 {
315 	int err, new_lnum = wbuf->lnum, new_offs = wbuf->offs + wbuf->used;
316 
317 	cond_resched();
318 	err = ubifs_wbuf_write_nolock(wbuf, snod->node, snod->len);
319 	if (err)
320 		return err;
321 
322 	err = ubifs_tnc_replace(c, &snod->key, sleb->lnum,
323 				snod->offs, new_lnum, new_offs,
324 				snod->len);
325 	list_del(&snod->list);
326 	kfree(snod);
327 	return err;
328 }
329 
330 /**
331  * move_nodes - move nodes.
332  * @c: UBIFS file-system description object
333  * @sleb: describes the LEB to move nodes from
334  *
335  * This function moves valid nodes from data LEB described by @sleb to the GC
336  * journal head. This function returns zero in case of success, %-EAGAIN if
337  * commit is required, and other negative error codes in case of other
338  * failures.
339  */
340 static int move_nodes(struct ubifs_info *c, struct ubifs_scan_leb *sleb)
341 {
342 	int err, min;
343 	LIST_HEAD(nondata);
344 	struct ubifs_wbuf *wbuf = &c->jheads[GCHD].wbuf;
345 
346 	if (wbuf->lnum == -1) {
347 		/*
348 		 * The GC journal head is not set, because it is the first GC
349 		 * invocation since mount.
350 		 */
351 		err = switch_gc_head(c);
352 		if (err)
353 			return err;
354 	}
355 
356 	err = sort_nodes(c, sleb, &nondata, &min);
357 	if (err)
358 		goto out;
359 
360 	/* Write nodes to their new location. Use the first-fit strategy */
361 	while (1) {
362 		int avail;
363 		struct ubifs_scan_node *snod, *tmp;
364 
365 		/* Move data nodes */
366 		list_for_each_entry_safe(snod, tmp, &sleb->nodes, list) {
367 			avail = c->leb_size - wbuf->offs - wbuf->used;
368 			if  (snod->len > avail)
369 				/*
370 				 * Do not skip data nodes in order to optimize
371 				 * bulk-read.
372 				 */
373 				break;
374 
375 			err = move_node(c, sleb, snod, wbuf);
376 			if (err)
377 				goto out;
378 		}
379 
380 		/* Move non-data nodes */
381 		list_for_each_entry_safe(snod, tmp, &nondata, list) {
382 			avail = c->leb_size - wbuf->offs - wbuf->used;
383 			if (avail < min)
384 				break;
385 
386 			if  (snod->len > avail) {
387 				/*
388 				 * Keep going only if this is an inode with
389 				 * some data. Otherwise stop and switch the GC
390 				 * head. IOW, we assume that data-less inode
391 				 * nodes and direntry nodes are roughly of the
392 				 * same size.
393 				 */
394 				if (key_type(c, &snod->key) == UBIFS_DENT_KEY ||
395 				    snod->len == UBIFS_INO_NODE_SZ)
396 					break;
397 				continue;
398 			}
399 
400 			err = move_node(c, sleb, snod, wbuf);
401 			if (err)
402 				goto out;
403 		}
404 
405 		if (list_empty(&sleb->nodes) && list_empty(&nondata))
406 			break;
407 
408 		/*
409 		 * Waste the rest of the space in the LEB and switch to the
410 		 * next LEB.
411 		 */
412 		err = switch_gc_head(c);
413 		if (err)
414 			goto out;
415 	}
416 
417 	return 0;
418 
419 out:
420 	list_splice_tail(&nondata, &sleb->nodes);
421 	return err;
422 }
423 
424 /**
425  * gc_sync_wbufs - sync write-buffers for GC.
426  * @c: UBIFS file-system description object
427  *
428  * We must guarantee that obsoleting nodes are on flash. Unfortunately they may
429  * be in a write-buffer instead. That is, a node could be written to a
430  * write-buffer, obsoleting another node in a LEB that is GC'd. If that LEB is
431  * erased before the write-buffer is sync'd and then there is an unclean
432  * unmount, then an existing node is lost. To avoid this, we sync all
433  * write-buffers.
434  *
435  * This function returns %0 on success or a negative error code on failure.
436  */
437 static int gc_sync_wbufs(struct ubifs_info *c)
438 {
439 	int err, i;
440 
441 	for (i = 0; i < c->jhead_cnt; i++) {
442 		if (i == GCHD)
443 			continue;
444 		err = ubifs_wbuf_sync(&c->jheads[i].wbuf);
445 		if (err)
446 			return err;
447 	}
448 	return 0;
449 }
450 
451 /**
452  * ubifs_garbage_collect_leb - garbage-collect a logical eraseblock.
453  * @c: UBIFS file-system description object
454  * @lp: describes the LEB to garbage collect
455  *
456  * This function garbage-collects an LEB and returns one of the @LEB_FREED,
457  * @LEB_RETAINED, etc positive codes in case of success, %-EAGAIN if commit is
458  * required, and other negative error codes in case of failures.
459  */
460 int ubifs_garbage_collect_leb(struct ubifs_info *c, struct ubifs_lprops *lp)
461 {
462 	struct ubifs_scan_leb *sleb;
463 	struct ubifs_scan_node *snod;
464 	struct ubifs_wbuf *wbuf = &c->jheads[GCHD].wbuf;
465 	int err = 0, lnum = lp->lnum;
466 
467 	ubifs_assert(c->gc_lnum != -1 || wbuf->offs + wbuf->used == 0 ||
468 		     c->need_recovery);
469 	ubifs_assert(c->gc_lnum != lnum);
470 	ubifs_assert(wbuf->lnum != lnum);
471 
472 	if (lp->free + lp->dirty == c->leb_size) {
473 		/* Special case - a free LEB  */
474 		dbg_gc("LEB %d is free, return it", lp->lnum);
475 		ubifs_assert(!(lp->flags & LPROPS_INDEX));
476 
477 		if (lp->free != c->leb_size) {
478 			/*
479 			 * Write buffers must be sync'd before unmapping
480 			 * freeable LEBs, because one of them may contain data
481 			 * which obsoletes something in 'lp->pnum'.
482 			 */
483 			err = gc_sync_wbufs(c);
484 			if (err)
485 				return err;
486 			err = ubifs_change_one_lp(c, lp->lnum, c->leb_size,
487 						  0, 0, 0, 0);
488 			if (err)
489 				return err;
490 		}
491 		err = ubifs_leb_unmap(c, lp->lnum);
492 		if (err)
493 			return err;
494 
495 		if (c->gc_lnum == -1) {
496 			c->gc_lnum = lnum;
497 			return LEB_RETAINED;
498 		}
499 
500 		return LEB_FREED;
501 	}
502 
503 	/*
504 	 * We scan the entire LEB even though we only really need to scan up to
505 	 * (c->leb_size - lp->free).
506 	 */
507 	sleb = ubifs_scan(c, lnum, 0, c->sbuf, 0);
508 	if (IS_ERR(sleb))
509 		return PTR_ERR(sleb);
510 
511 	ubifs_assert(!list_empty(&sleb->nodes));
512 	snod = list_entry(sleb->nodes.next, struct ubifs_scan_node, list);
513 
514 	if (snod->type == UBIFS_IDX_NODE) {
515 		struct ubifs_gced_idx_leb *idx_gc;
516 
517 		dbg_gc("indexing LEB %d (free %d, dirty %d)",
518 		       lnum, lp->free, lp->dirty);
519 		list_for_each_entry(snod, &sleb->nodes, list) {
520 			struct ubifs_idx_node *idx = snod->node;
521 			int level = le16_to_cpu(idx->level);
522 
523 			ubifs_assert(snod->type == UBIFS_IDX_NODE);
524 			key_read(c, ubifs_idx_key(c, idx), &snod->key);
525 			err = ubifs_dirty_idx_node(c, &snod->key, level, lnum,
526 						   snod->offs);
527 			if (err)
528 				goto out;
529 		}
530 
531 		idx_gc = kmalloc(sizeof(struct ubifs_gced_idx_leb), GFP_NOFS);
532 		if (!idx_gc) {
533 			err = -ENOMEM;
534 			goto out;
535 		}
536 
537 		idx_gc->lnum = lnum;
538 		idx_gc->unmap = 0;
539 		list_add(&idx_gc->list, &c->idx_gc);
540 
541 		/*
542 		 * Don't release the LEB until after the next commit, because
543 		 * it may contain data which is needed for recovery. So
544 		 * although we freed this LEB, it will become usable only after
545 		 * the commit.
546 		 */
547 		err = ubifs_change_one_lp(c, lnum, c->leb_size, 0, 0,
548 					  LPROPS_INDEX, 1);
549 		if (err)
550 			goto out;
551 		err = LEB_FREED_IDX;
552 	} else {
553 		dbg_gc("data LEB %d (free %d, dirty %d)",
554 		       lnum, lp->free, lp->dirty);
555 
556 		err = move_nodes(c, sleb);
557 		if (err)
558 			goto out_inc_seq;
559 
560 		err = gc_sync_wbufs(c);
561 		if (err)
562 			goto out_inc_seq;
563 
564 		err = ubifs_change_one_lp(c, lnum, c->leb_size, 0, 0, 0, 0);
565 		if (err)
566 			goto out_inc_seq;
567 
568 		/* Allow for races with TNC */
569 		c->gced_lnum = lnum;
570 		smp_wmb();
571 		c->gc_seq += 1;
572 		smp_wmb();
573 
574 		if (c->gc_lnum == -1) {
575 			c->gc_lnum = lnum;
576 			err = LEB_RETAINED;
577 		} else {
578 			err = ubifs_wbuf_sync_nolock(wbuf);
579 			if (err)
580 				goto out;
581 
582 			err = ubifs_leb_unmap(c, lnum);
583 			if (err)
584 				goto out;
585 
586 			err = LEB_FREED;
587 		}
588 	}
589 
590 out:
591 	ubifs_scan_destroy(sleb);
592 	return err;
593 
594 out_inc_seq:
595 	/* We may have moved at least some nodes so allow for races with TNC */
596 	c->gced_lnum = lnum;
597 	smp_wmb();
598 	c->gc_seq += 1;
599 	smp_wmb();
600 	goto out;
601 }
602 
603 /**
604  * ubifs_garbage_collect - UBIFS garbage collector.
605  * @c: UBIFS file-system description object
606  * @anyway: do GC even if there are free LEBs
607  *
608  * This function does out-of-place garbage collection. The return codes are:
609  *   o positive LEB number if the LEB has been freed and may be used;
610  *   o %-EAGAIN if the caller has to run commit;
611  *   o %-ENOSPC if GC failed to make any progress;
612  *   o other negative error codes in case of other errors.
613  *
614  * Garbage collector writes data to the journal when GC'ing data LEBs, and just
615  * marking indexing nodes dirty when GC'ing indexing LEBs. Thus, at some point
616  * commit may be required. But commit cannot be run from inside GC, because the
617  * caller might be holding the commit lock, so %-EAGAIN is returned instead;
618  * And this error code means that the caller has to run commit, and re-run GC
619  * if there is still no free space.
620  *
621  * There are many reasons why this function may return %-EAGAIN:
622  * o the log is full and there is no space to write an LEB reference for
623  *   @c->gc_lnum;
624  * o the journal is too large and exceeds size limitations;
625  * o GC moved indexing LEBs, but they can be used only after the commit;
626  * o the shrinker fails to find clean znodes to free and requests the commit;
627  * o etc.
628  *
629  * Note, if the file-system is close to be full, this function may return
630  * %-EAGAIN infinitely, so the caller has to limit amount of re-invocations of
631  * the function. E.g., this happens if the limits on the journal size are too
632  * tough and GC writes too much to the journal before an LEB is freed. This
633  * might also mean that the journal is too large, and the TNC becomes to big,
634  * so that the shrinker is constantly called, finds not clean znodes to free,
635  * and requests commit. Well, this may also happen if the journal is all right,
636  * but another kernel process consumes too much memory. Anyway, infinite
637  * %-EAGAIN may happen, but in some extreme/misconfiguration cases.
638  */
639 int ubifs_garbage_collect(struct ubifs_info *c, int anyway)
640 {
641 	int i, err, ret, min_space = c->dead_wm;
642 	struct ubifs_lprops lp;
643 	struct ubifs_wbuf *wbuf = &c->jheads[GCHD].wbuf;
644 
645 	ubifs_assert_cmt_locked(c);
646 	ubifs_assert(!c->ro_media && !c->ro_mount);
647 
648 	if (ubifs_gc_should_commit(c))
649 		return -EAGAIN;
650 
651 	mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
652 
653 	if (c->ro_error) {
654 		ret = -EROFS;
655 		goto out_unlock;
656 	}
657 
658 	/* We expect the write-buffer to be empty on entry */
659 	ubifs_assert(!wbuf->used);
660 
661 	for (i = 0; ; i++) {
662 		int space_before, space_after;
663 
664 		cond_resched();
665 
666 		/* Give the commit an opportunity to run */
667 		if (ubifs_gc_should_commit(c)) {
668 			ret = -EAGAIN;
669 			break;
670 		}
671 
672 		if (i > SOFT_LEBS_LIMIT && !list_empty(&c->idx_gc)) {
673 			/*
674 			 * We've done enough iterations. Indexing LEBs were
675 			 * moved and will be available after the commit.
676 			 */
677 			dbg_gc("soft limit, some index LEBs GC'ed, -EAGAIN");
678 			ubifs_commit_required(c);
679 			ret = -EAGAIN;
680 			break;
681 		}
682 
683 		if (i > HARD_LEBS_LIMIT) {
684 			/*
685 			 * We've moved too many LEBs and have not made
686 			 * progress, give up.
687 			 */
688 			dbg_gc("hard limit, -ENOSPC");
689 			ret = -ENOSPC;
690 			break;
691 		}
692 
693 		/*
694 		 * Empty and freeable LEBs can turn up while we waited for
695 		 * the wbuf lock, or while we have been running GC. In that
696 		 * case, we should just return one of those instead of
697 		 * continuing to GC dirty LEBs. Hence we request
698 		 * 'ubifs_find_dirty_leb()' to return an empty LEB if it can.
699 		 */
700 		ret = ubifs_find_dirty_leb(c, &lp, min_space, anyway ? 0 : 1);
701 		if (ret) {
702 			if (ret == -ENOSPC)
703 				dbg_gc("no more dirty LEBs");
704 			break;
705 		}
706 
707 		dbg_gc("found LEB %d: free %d, dirty %d, sum %d (min. space %d)",
708 		       lp.lnum, lp.free, lp.dirty, lp.free + lp.dirty,
709 		       min_space);
710 
711 		space_before = c->leb_size - wbuf->offs - wbuf->used;
712 		if (wbuf->lnum == -1)
713 			space_before = 0;
714 
715 		ret = ubifs_garbage_collect_leb(c, &lp);
716 		if (ret < 0) {
717 			if (ret == -EAGAIN) {
718 				/*
719 				 * This is not error, so we have to return the
720 				 * LEB to lprops. But if 'ubifs_return_leb()'
721 				 * fails, its failure code is propagated to the
722 				 * caller instead of the original '-EAGAIN'.
723 				 */
724 				err = ubifs_return_leb(c, lp.lnum);
725 				if (err)
726 					ret = err;
727 				break;
728 			}
729 			goto out;
730 		}
731 
732 		if (ret == LEB_FREED) {
733 			/* An LEB has been freed and is ready for use */
734 			dbg_gc("LEB %d freed, return", lp.lnum);
735 			ret = lp.lnum;
736 			break;
737 		}
738 
739 		if (ret == LEB_FREED_IDX) {
740 			/*
741 			 * This was an indexing LEB and it cannot be
742 			 * immediately used. And instead of requesting the
743 			 * commit straight away, we try to garbage collect some
744 			 * more.
745 			 */
746 			dbg_gc("indexing LEB %d freed, continue", lp.lnum);
747 			continue;
748 		}
749 
750 		ubifs_assert(ret == LEB_RETAINED);
751 		space_after = c->leb_size - wbuf->offs - wbuf->used;
752 		dbg_gc("LEB %d retained, freed %d bytes", lp.lnum,
753 		       space_after - space_before);
754 
755 		if (space_after > space_before) {
756 			/* GC makes progress, keep working */
757 			min_space >>= 1;
758 			if (min_space < c->dead_wm)
759 				min_space = c->dead_wm;
760 			continue;
761 		}
762 
763 		dbg_gc("did not make progress");
764 
765 		/*
766 		 * GC moved an LEB bud have not done any progress. This means
767 		 * that the previous GC head LEB contained too few free space
768 		 * and the LEB which was GC'ed contained only large nodes which
769 		 * did not fit that space.
770 		 *
771 		 * We can do 2 things:
772 		 * 1. pick another LEB in a hope it'll contain a small node
773 		 *    which will fit the space we have at the end of current GC
774 		 *    head LEB, but there is no guarantee, so we try this out
775 		 *    unless we have already been working for too long;
776 		 * 2. request an LEB with more dirty space, which will force
777 		 *    'ubifs_find_dirty_leb()' to start scanning the lprops
778 		 *    table, instead of just picking one from the heap
779 		 *    (previously it already picked the dirtiest LEB).
780 		 */
781 		if (i < SOFT_LEBS_LIMIT) {
782 			dbg_gc("try again");
783 			continue;
784 		}
785 
786 		min_space <<= 1;
787 		if (min_space > c->dark_wm)
788 			min_space = c->dark_wm;
789 		dbg_gc("set min. space to %d", min_space);
790 	}
791 
792 	if (ret == -ENOSPC && !list_empty(&c->idx_gc)) {
793 		dbg_gc("no space, some index LEBs GC'ed, -EAGAIN");
794 		ubifs_commit_required(c);
795 		ret = -EAGAIN;
796 	}
797 
798 	err = ubifs_wbuf_sync_nolock(wbuf);
799 	if (!err)
800 		err = ubifs_leb_unmap(c, c->gc_lnum);
801 	if (err) {
802 		ret = err;
803 		goto out;
804 	}
805 out_unlock:
806 	mutex_unlock(&wbuf->io_mutex);
807 	return ret;
808 
809 out:
810 	ubifs_assert(ret < 0);
811 	ubifs_assert(ret != -ENOSPC && ret != -EAGAIN);
812 	ubifs_wbuf_sync_nolock(wbuf);
813 	ubifs_ro_mode(c, ret);
814 	mutex_unlock(&wbuf->io_mutex);
815 	ubifs_return_leb(c, lp.lnum);
816 	return ret;
817 }
818 
819 /**
820  * ubifs_gc_start_commit - garbage collection at start of commit.
821  * @c: UBIFS file-system description object
822  *
823  * If a LEB has only dirty and free space, then we may safely unmap it and make
824  * it free.  Note, we cannot do this with indexing LEBs because dirty space may
825  * correspond index nodes that are required for recovery.  In that case, the
826  * LEB cannot be unmapped until after the next commit.
827  *
828  * This function returns %0 upon success and a negative error code upon failure.
829  */
830 int ubifs_gc_start_commit(struct ubifs_info *c)
831 {
832 	struct ubifs_gced_idx_leb *idx_gc;
833 	const struct ubifs_lprops *lp;
834 	int err = 0, flags;
835 
836 	ubifs_get_lprops(c);
837 
838 	/*
839 	 * Unmap (non-index) freeable LEBs. Note that recovery requires that all
840 	 * wbufs are sync'd before this, which is done in 'do_commit()'.
841 	 */
842 	while (1) {
843 		lp = ubifs_fast_find_freeable(c);
844 		if (IS_ERR(lp)) {
845 			err = PTR_ERR(lp);
846 			goto out;
847 		}
848 		if (!lp)
849 			break;
850 		ubifs_assert(!(lp->flags & LPROPS_TAKEN));
851 		ubifs_assert(!(lp->flags & LPROPS_INDEX));
852 		err = ubifs_leb_unmap(c, lp->lnum);
853 		if (err)
854 			goto out;
855 		lp = ubifs_change_lp(c, lp, c->leb_size, 0, lp->flags, 0);
856 		if (IS_ERR(lp)) {
857 			err = PTR_ERR(lp);
858 			goto out;
859 		}
860 		ubifs_assert(!(lp->flags & LPROPS_TAKEN));
861 		ubifs_assert(!(lp->flags & LPROPS_INDEX));
862 	}
863 
864 	/* Mark GC'd index LEBs OK to unmap after this commit finishes */
865 	list_for_each_entry(idx_gc, &c->idx_gc, list)
866 		idx_gc->unmap = 1;
867 
868 	/* Record index freeable LEBs for unmapping after commit */
869 	while (1) {
870 		lp = ubifs_fast_find_frdi_idx(c);
871 		if (IS_ERR(lp)) {
872 			err = PTR_ERR(lp);
873 			goto out;
874 		}
875 		if (!lp)
876 			break;
877 		idx_gc = kmalloc(sizeof(struct ubifs_gced_idx_leb), GFP_NOFS);
878 		if (!idx_gc) {
879 			err = -ENOMEM;
880 			goto out;
881 		}
882 		ubifs_assert(!(lp->flags & LPROPS_TAKEN));
883 		ubifs_assert(lp->flags & LPROPS_INDEX);
884 		/* Don't release the LEB until after the next commit */
885 		flags = (lp->flags | LPROPS_TAKEN) ^ LPROPS_INDEX;
886 		lp = ubifs_change_lp(c, lp, c->leb_size, 0, flags, 1);
887 		if (IS_ERR(lp)) {
888 			err = PTR_ERR(lp);
889 			kfree(idx_gc);
890 			goto out;
891 		}
892 		ubifs_assert(lp->flags & LPROPS_TAKEN);
893 		ubifs_assert(!(lp->flags & LPROPS_INDEX));
894 		idx_gc->lnum = lp->lnum;
895 		idx_gc->unmap = 1;
896 		list_add(&idx_gc->list, &c->idx_gc);
897 	}
898 out:
899 	ubifs_release_lprops(c);
900 	return err;
901 }
902 
903 /**
904  * ubifs_gc_end_commit - garbage collection at end of commit.
905  * @c: UBIFS file-system description object
906  *
907  * This function completes out-of-place garbage collection of index LEBs.
908  */
909 int ubifs_gc_end_commit(struct ubifs_info *c)
910 {
911 	struct ubifs_gced_idx_leb *idx_gc, *tmp;
912 	struct ubifs_wbuf *wbuf;
913 	int err = 0;
914 
915 	wbuf = &c->jheads[GCHD].wbuf;
916 	mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
917 	list_for_each_entry_safe(idx_gc, tmp, &c->idx_gc, list)
918 		if (idx_gc->unmap) {
919 			dbg_gc("LEB %d", idx_gc->lnum);
920 			err = ubifs_leb_unmap(c, idx_gc->lnum);
921 			if (err)
922 				goto out;
923 			err = ubifs_change_one_lp(c, idx_gc->lnum, LPROPS_NC,
924 					  LPROPS_NC, 0, LPROPS_TAKEN, -1);
925 			if (err)
926 				goto out;
927 			list_del(&idx_gc->list);
928 			kfree(idx_gc);
929 		}
930 out:
931 	mutex_unlock(&wbuf->io_mutex);
932 	return err;
933 }
934 #endif
935 /**
936  * ubifs_destroy_idx_gc - destroy idx_gc list.
937  * @c: UBIFS file-system description object
938  *
939  * This function destroys the @c->idx_gc list. It is called when unmounting
940  * so locks are not needed. Returns zero in case of success and a negative
941  * error code in case of failure.
942  */
943 void ubifs_destroy_idx_gc(struct ubifs_info *c)
944 {
945 	while (!list_empty(&c->idx_gc)) {
946 		struct ubifs_gced_idx_leb *idx_gc;
947 
948 		idx_gc = list_entry(c->idx_gc.next, struct ubifs_gced_idx_leb,
949 				    list);
950 		c->idx_gc_cnt -= 1;
951 		list_del(&idx_gc->list);
952 		kfree(idx_gc);
953 	}
954 }
955 #ifndef __UBOOT__
956 /**
957  * ubifs_get_idx_gc_leb - get a LEB from GC'd index LEB list.
958  * @c: UBIFS file-system description object
959  *
960  * Called during start commit so locks are not needed.
961  */
962 int ubifs_get_idx_gc_leb(struct ubifs_info *c)
963 {
964 	struct ubifs_gced_idx_leb *idx_gc;
965 	int lnum;
966 
967 	if (list_empty(&c->idx_gc))
968 		return -ENOSPC;
969 	idx_gc = list_entry(c->idx_gc.next, struct ubifs_gced_idx_leb, list);
970 	lnum = idx_gc->lnum;
971 	/* c->idx_gc_cnt is updated by the caller when lprops are updated */
972 	list_del(&idx_gc->list);
973 	kfree(idx_gc);
974 	return lnum;
975 }
976 #endif
977