xref: /linux/fs/ext4/extents_status.c (revision 6dfafbd0299a60bfb5d5e277fdf100037c7ded07)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  fs/ext4/extents_status.c
4  *
5  * Written by Yongqiang Yang <xiaoqiangnk@gmail.com>
6  * Modified by
7  *	Allison Henderson <achender@linux.vnet.ibm.com>
8  *	Hugh Dickins <hughd@google.com>
9  *	Zheng Liu <wenqing.lz@taobao.com>
10  *
11  * Ext4 extents status tree core functions.
12  */
13 #include <linux/list_sort.h>
14 #include <linux/proc_fs.h>
15 #include <linux/seq_file.h>
16 #include "ext4.h"
17 
18 #include <trace/events/ext4.h>
19 
20 /*
21  * According to previous discussion in Ext4 Developer Workshop, we
22  * will introduce a new structure called io tree to track all extent
23  * status in order to solve some problems that we have met
24  * (e.g. Reservation space warning), and provide extent-level locking.
25  * Delay extent tree is the first step to achieve this goal.  It is
26  * original built by Yongqiang Yang.  At that time it is called delay
27  * extent tree, whose goal is only track delayed extents in memory to
28  * simplify the implementation of fiemap and bigalloc, and introduce
29  * lseek SEEK_DATA/SEEK_HOLE support.  That is why it is still called
30  * delay extent tree at the first commit.  But for better understand
31  * what it does, it has been rename to extent status tree.
32  *
33  * Step1:
34  * Currently the first step has been done.  All delayed extents are
35  * tracked in the tree.  It maintains the delayed extent when a delayed
36  * allocation is issued, and the delayed extent is written out or
37  * invalidated.  Therefore the implementation of fiemap and bigalloc
38  * are simplified, and SEEK_DATA/SEEK_HOLE are introduced.
39  *
40  * The following comment describes the implemenmtation of extent
41  * status tree and future works.
42  *
43  * Step2:
44  * In this step all extent status are tracked by extent status tree.
45  * Thus, we can first try to lookup a block mapping in this tree before
46  * finding it in extent tree.  Hence, single extent cache can be removed
47  * because extent status tree can do a better job.  Extents in status
48  * tree are loaded on-demand.  Therefore, the extent status tree may not
49  * contain all of the extents in a file.  Meanwhile we define a shrinker
50  * to reclaim memory from extent status tree because fragmented extent
51  * tree will make status tree cost too much memory.  written/unwritten/-
52  * hole extents in the tree will be reclaimed by this shrinker when we
53  * are under high memory pressure.  Delayed extents will not be
54  * reclimed because fiemap, bigalloc, and seek_data/hole need it.
55  */
56 
57 /*
58  * Extent status tree implementation for ext4.
59  *
60  *
61  * ==========================================================================
62  * Extent status tree tracks all extent status.
63  *
64  * 1. Why we need to implement extent status tree?
65  *
66  * Without extent status tree, ext4 identifies a delayed extent by looking
67  * up page cache, this has several deficiencies - complicated, buggy,
68  * and inefficient code.
69  *
70  * FIEMAP, SEEK_HOLE/DATA, bigalloc, and writeout all need to know if a
71  * block or a range of blocks are belonged to a delayed extent.
72  *
73  * Let us have a look at how they do without extent status tree.
74  *   --	FIEMAP
75  *	FIEMAP looks up page cache to identify delayed allocations from holes.
76  *
77  *   --	SEEK_HOLE/DATA
78  *	SEEK_HOLE/DATA has the same problem as FIEMAP.
79  *
80  *   --	bigalloc
81  *	bigalloc looks up page cache to figure out if a block is
82  *	already under delayed allocation or not to determine whether
83  *	quota reserving is needed for the cluster.
84  *
85  *   --	writeout
86  *	Writeout looks up whole page cache to see if a buffer is
87  *	mapped, If there are not very many delayed buffers, then it is
88  *	time consuming.
89  *
90  * With extent status tree implementation, FIEMAP, SEEK_HOLE/DATA,
91  * bigalloc and writeout can figure out if a block or a range of
92  * blocks is under delayed allocation(belonged to a delayed extent) or
93  * not by searching the extent tree.
94  *
95  *
96  * ==========================================================================
97  * 2. Ext4 extent status tree impelmentation
98  *
99  *   --	extent
100  *	A extent is a range of blocks which are contiguous logically and
101  *	physically.  Unlike extent in extent tree, this extent in ext4 is
102  *	a in-memory struct, there is no corresponding on-disk data.  There
103  *	is no limit on length of extent, so an extent can contain as many
104  *	blocks as they are contiguous logically and physically.
105  *
106  *   --	extent status tree
107  *	Every inode has an extent status tree and all allocation blocks
108  *	are added to the tree with different status.  The extent in the
109  *	tree are ordered by logical block no.
110  *
111  *   --	operations on a extent status tree
112  *	There are three important operations on a delayed extent tree: find
113  *	next extent, adding a extent(a range of blocks) and removing a extent.
114  *
115  *   --	race on a extent status tree
116  *	Extent status tree is protected by inode->i_es_lock.
117  *
118  *   --	memory consumption
119  *      Fragmented extent tree will make extent status tree cost too much
120  *      memory.  Hence, we will reclaim written/unwritten/hole extents from
121  *      the tree under a heavy memory pressure.
122  *
123  * ==========================================================================
124  * 3. Assurance of Ext4 extent status tree consistency
125  *
126  * When mapping blocks, Ext4 queries the extent status tree first and should
127  * always trusts that the extent status tree is consistent and up to date.
128  * Therefore, it is important to adheres to the following rules when createing,
129  * modifying and removing extents.
130  *
131  *  1. Besides fastcommit replay, when Ext4 creates or queries block mappings,
132  *     the extent information should always be processed through the extent
133  *     status tree instead of being organized manually through the on-disk
134  *     extent tree.
135  *
136  *  2. When updating the extent tree, Ext4 should acquire the i_data_sem
137  *     exclusively and update the extent status tree atomically. If the extents
138  *     to be modified are large enough to exceed the range that a single
139  *     i_data_sem can process (as ext4_datasem_ensure_credits() may drop
140  *     i_data_sem to restart a transaction), it must (e.g. as ext4_punch_hole()
141  *     does):
142  *
143  *     a) Hold the i_rwsem and invalidate_lock exclusively. This ensures
144  *        exclusion against page faults, as well as reads and writes that may
145  *        concurrently modify the extent status tree.
146  *     b) Evict all page cache in the affected range and recommend rebuilding
147  *        or dropping the extent status tree after modifying the on-disk
148  *        extent tree. This ensures exclusion against concurrent writebacks
149  *        that do not hold those locks but only holds a folio lock.
150  *
151  *  3. Based on the rules above, when querying block mappings, Ext4 should at
152  *     least hold the i_rwsem or invalidate_lock or folio lock(s) for the
153  *     specified querying range.
154  *
155  * ==========================================================================
156  * 4. Performance analysis
157  *
158  *   --	overhead
159  *	1. There is a cache extent for write access, so if writes are
160  *	not very random, adding space operaions are in O(1) time.
161  *
162  *   --	gain
163  *	2. Code is much simpler, more readable, more maintainable and
164  *	more efficient.
165  *
166  *
167  * ==========================================================================
168  * 5. TODO list
169  *
170  *   -- Refactor delayed space reservation
171  *
172  *   -- Extent-level locking
173  */
174 
175 static struct kmem_cache *ext4_es_cachep;
176 static struct kmem_cache *ext4_pending_cachep;
177 
178 static int __es_insert_extent(struct inode *inode, struct extent_status *newes,
179 			      struct extent_status *prealloc);
180 static int __es_remove_extent(struct inode *inode, ext4_lblk_t lblk,
181 			      ext4_lblk_t end, int *reserved,
182 			      struct extent_status *prealloc);
183 static int es_reclaim_extents(struct ext4_inode_info *ei, int *nr_to_scan);
184 static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan,
185 		       struct ext4_inode_info *locked_ei);
186 static int __revise_pending(struct inode *inode, ext4_lblk_t lblk,
187 			    ext4_lblk_t len,
188 			    struct pending_reservation **prealloc);
189 
190 int __init ext4_init_es(void)
191 {
192 	ext4_es_cachep = KMEM_CACHE(extent_status, SLAB_RECLAIM_ACCOUNT);
193 	if (ext4_es_cachep == NULL)
194 		return -ENOMEM;
195 	return 0;
196 }
197 
198 void ext4_exit_es(void)
199 {
200 	kmem_cache_destroy(ext4_es_cachep);
201 }
202 
203 void ext4_es_init_tree(struct ext4_es_tree *tree)
204 {
205 	tree->root = RB_ROOT;
206 	tree->cache_es = NULL;
207 }
208 
209 #ifdef ES_DEBUG__
210 static void ext4_es_print_tree(struct inode *inode)
211 {
212 	struct ext4_es_tree *tree;
213 	struct rb_node *node;
214 
215 	printk(KERN_DEBUG "status extents for inode %lu:", inode->i_ino);
216 	tree = &EXT4_I(inode)->i_es_tree;
217 	node = rb_first(&tree->root);
218 	while (node) {
219 		struct extent_status *es;
220 		es = rb_entry(node, struct extent_status, rb_node);
221 		printk(KERN_DEBUG " [%u/%u) %llu %x",
222 		       es->es_lblk, es->es_len,
223 		       ext4_es_pblock(es), ext4_es_status(es));
224 		node = rb_next(node);
225 	}
226 	printk(KERN_DEBUG "\n");
227 }
228 #else
229 #define ext4_es_print_tree(inode)
230 #endif
231 
232 static inline ext4_lblk_t ext4_es_end(struct extent_status *es)
233 {
234 	BUG_ON(es->es_lblk + es->es_len < es->es_lblk);
235 	return es->es_lblk + es->es_len - 1;
236 }
237 
238 static inline void ext4_es_inc_seq(struct inode *inode)
239 {
240 	struct ext4_inode_info *ei = EXT4_I(inode);
241 
242 	WRITE_ONCE(ei->i_es_seq, ei->i_es_seq + 1);
243 }
244 
245 /*
246  * search through the tree for an delayed extent with a given offset.  If
247  * it can't be found, try to find next extent.
248  */
249 static struct extent_status *__es_tree_search(struct rb_root *root,
250 					      ext4_lblk_t lblk)
251 {
252 	struct rb_node *node = root->rb_node;
253 	struct extent_status *es = NULL;
254 
255 	while (node) {
256 		es = rb_entry(node, struct extent_status, rb_node);
257 		if (lblk < es->es_lblk)
258 			node = node->rb_left;
259 		else if (lblk > ext4_es_end(es))
260 			node = node->rb_right;
261 		else
262 			return es;
263 	}
264 
265 	if (es && lblk < es->es_lblk)
266 		return es;
267 
268 	if (es && lblk > ext4_es_end(es)) {
269 		node = rb_next(&es->rb_node);
270 		return node ? rb_entry(node, struct extent_status, rb_node) :
271 			      NULL;
272 	}
273 
274 	return NULL;
275 }
276 
277 /*
278  * ext4_es_find_extent_range - find extent with specified status within block
279  *                             range or next extent following block range in
280  *                             extents status tree
281  *
282  * @inode - file containing the range
283  * @matching_fn - pointer to function that matches extents with desired status
284  * @lblk - logical block defining start of range
285  * @end - logical block defining end of range
286  * @es - extent found, if any
287  *
288  * Find the first extent within the block range specified by @lblk and @end
289  * in the extents status tree that satisfies @matching_fn.  If a match
290  * is found, it's returned in @es.  If not, and a matching extent is found
291  * beyond the block range, it's returned in @es.  If no match is found, an
292  * extent is returned in @es whose es_lblk, es_len, and es_pblk components
293  * are 0.
294  */
295 static void __es_find_extent_range(struct inode *inode,
296 				   int (*matching_fn)(struct extent_status *es),
297 				   ext4_lblk_t lblk, ext4_lblk_t end,
298 				   struct extent_status *es)
299 {
300 	struct ext4_es_tree *tree = NULL;
301 	struct extent_status *es1 = NULL;
302 	struct rb_node *node;
303 
304 	WARN_ON(es == NULL);
305 	WARN_ON(end < lblk);
306 
307 	tree = &EXT4_I(inode)->i_es_tree;
308 
309 	/* see if the extent has been cached */
310 	es->es_lblk = es->es_len = es->es_pblk = 0;
311 	es1 = READ_ONCE(tree->cache_es);
312 	if (es1 && in_range(lblk, es1->es_lblk, es1->es_len)) {
313 		es_debug("%u cached by [%u/%u) %llu %x\n",
314 			 lblk, es1->es_lblk, es1->es_len,
315 			 ext4_es_pblock(es1), ext4_es_status(es1));
316 		goto out;
317 	}
318 
319 	es1 = __es_tree_search(&tree->root, lblk);
320 
321 out:
322 	if (es1 && !matching_fn(es1)) {
323 		while ((node = rb_next(&es1->rb_node)) != NULL) {
324 			es1 = rb_entry(node, struct extent_status, rb_node);
325 			if (es1->es_lblk > end) {
326 				es1 = NULL;
327 				break;
328 			}
329 			if (matching_fn(es1))
330 				break;
331 		}
332 	}
333 
334 	if (es1 && matching_fn(es1)) {
335 		WRITE_ONCE(tree->cache_es, es1);
336 		es->es_lblk = es1->es_lblk;
337 		es->es_len = es1->es_len;
338 		es->es_pblk = es1->es_pblk;
339 	}
340 
341 }
342 
343 /*
344  * Locking for __es_find_extent_range() for external use
345  */
346 void ext4_es_find_extent_range(struct inode *inode,
347 			       int (*matching_fn)(struct extent_status *es),
348 			       ext4_lblk_t lblk, ext4_lblk_t end,
349 			       struct extent_status *es)
350 {
351 	es->es_lblk = es->es_len = es->es_pblk = 0;
352 
353 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
354 		return;
355 
356 	trace_ext4_es_find_extent_range_enter(inode, lblk);
357 
358 	read_lock(&EXT4_I(inode)->i_es_lock);
359 	__es_find_extent_range(inode, matching_fn, lblk, end, es);
360 	read_unlock(&EXT4_I(inode)->i_es_lock);
361 
362 	trace_ext4_es_find_extent_range_exit(inode, es);
363 }
364 
365 /*
366  * __es_scan_range - search block range for block with specified status
367  *                   in extents status tree
368  *
369  * @inode - file containing the range
370  * @matching_fn - pointer to function that matches extents with desired status
371  * @lblk - logical block defining start of range
372  * @end - logical block defining end of range
373  *
374  * Returns true if at least one block in the specified block range satisfies
375  * the criterion specified by @matching_fn, and false if not.  If at least
376  * one extent has the specified status, then there is at least one block
377  * in the cluster with that status.  Should only be called by code that has
378  * taken i_es_lock.
379  */
380 static bool __es_scan_range(struct inode *inode,
381 			    int (*matching_fn)(struct extent_status *es),
382 			    ext4_lblk_t start, ext4_lblk_t end)
383 {
384 	struct extent_status es;
385 
386 	__es_find_extent_range(inode, matching_fn, start, end, &es);
387 	if (es.es_len == 0)
388 		return false;   /* no matching extent in the tree */
389 	else if (es.es_lblk <= start &&
390 		 start < es.es_lblk + es.es_len)
391 		return true;
392 	else if (start <= es.es_lblk && es.es_lblk <= end)
393 		return true;
394 	else
395 		return false;
396 }
397 /*
398  * Locking for __es_scan_range() for external use
399  */
400 bool ext4_es_scan_range(struct inode *inode,
401 			int (*matching_fn)(struct extent_status *es),
402 			ext4_lblk_t lblk, ext4_lblk_t end)
403 {
404 	bool ret;
405 
406 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
407 		return false;
408 
409 	read_lock(&EXT4_I(inode)->i_es_lock);
410 	ret = __es_scan_range(inode, matching_fn, lblk, end);
411 	read_unlock(&EXT4_I(inode)->i_es_lock);
412 
413 	return ret;
414 }
415 
416 /*
417  * __es_scan_clu - search cluster for block with specified status in
418  *                 extents status tree
419  *
420  * @inode - file containing the cluster
421  * @matching_fn - pointer to function that matches extents with desired status
422  * @lblk - logical block in cluster to be searched
423  *
424  * Returns true if at least one extent in the cluster containing @lblk
425  * satisfies the criterion specified by @matching_fn, and false if not.  If at
426  * least one extent has the specified status, then there is at least one block
427  * in the cluster with that status.  Should only be called by code that has
428  * taken i_es_lock.
429  */
430 static bool __es_scan_clu(struct inode *inode,
431 			  int (*matching_fn)(struct extent_status *es),
432 			  ext4_lblk_t lblk)
433 {
434 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
435 	ext4_lblk_t lblk_start, lblk_end;
436 
437 	lblk_start = EXT4_LBLK_CMASK(sbi, lblk);
438 	lblk_end = lblk_start + sbi->s_cluster_ratio - 1;
439 
440 	return __es_scan_range(inode, matching_fn, lblk_start, lblk_end);
441 }
442 
443 /*
444  * Locking for __es_scan_clu() for external use
445  */
446 bool ext4_es_scan_clu(struct inode *inode,
447 		      int (*matching_fn)(struct extent_status *es),
448 		      ext4_lblk_t lblk)
449 {
450 	bool ret;
451 
452 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
453 		return false;
454 
455 	read_lock(&EXT4_I(inode)->i_es_lock);
456 	ret = __es_scan_clu(inode, matching_fn, lblk);
457 	read_unlock(&EXT4_I(inode)->i_es_lock);
458 
459 	return ret;
460 }
461 
462 static void ext4_es_list_add(struct inode *inode)
463 {
464 	struct ext4_inode_info *ei = EXT4_I(inode);
465 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
466 
467 	if (!list_empty(&ei->i_es_list))
468 		return;
469 
470 	spin_lock(&sbi->s_es_lock);
471 	if (list_empty(&ei->i_es_list)) {
472 		list_add_tail(&ei->i_es_list, &sbi->s_es_list);
473 		sbi->s_es_nr_inode++;
474 	}
475 	spin_unlock(&sbi->s_es_lock);
476 }
477 
478 static void ext4_es_list_del(struct inode *inode)
479 {
480 	struct ext4_inode_info *ei = EXT4_I(inode);
481 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
482 
483 	spin_lock(&sbi->s_es_lock);
484 	if (!list_empty(&ei->i_es_list)) {
485 		list_del_init(&ei->i_es_list);
486 		sbi->s_es_nr_inode--;
487 		WARN_ON_ONCE(sbi->s_es_nr_inode < 0);
488 	}
489 	spin_unlock(&sbi->s_es_lock);
490 }
491 
492 static inline struct pending_reservation *__alloc_pending(bool nofail)
493 {
494 	if (!nofail)
495 		return kmem_cache_alloc(ext4_pending_cachep, GFP_ATOMIC);
496 
497 	return kmem_cache_zalloc(ext4_pending_cachep, GFP_KERNEL | __GFP_NOFAIL);
498 }
499 
500 static inline void __free_pending(struct pending_reservation *pr)
501 {
502 	kmem_cache_free(ext4_pending_cachep, pr);
503 }
504 
505 /*
506  * Returns true if we cannot fail to allocate memory for this extent_status
507  * entry and cannot reclaim it until its status changes.
508  */
509 static inline bool ext4_es_must_keep(struct extent_status *es)
510 {
511 	/* fiemap, bigalloc, and seek_data/hole need to use it. */
512 	if (ext4_es_is_delayed(es))
513 		return true;
514 
515 	return false;
516 }
517 
518 static inline struct extent_status *__es_alloc_extent(bool nofail)
519 {
520 	if (!nofail)
521 		return kmem_cache_alloc(ext4_es_cachep, GFP_ATOMIC);
522 
523 	return kmem_cache_zalloc(ext4_es_cachep, GFP_KERNEL | __GFP_NOFAIL);
524 }
525 
526 static void ext4_es_init_extent(struct inode *inode, struct extent_status *es,
527 		ext4_lblk_t lblk, ext4_lblk_t len, ext4_fsblk_t pblk)
528 {
529 	es->es_lblk = lblk;
530 	es->es_len = len;
531 	es->es_pblk = pblk;
532 
533 	/* We never try to reclaim a must kept extent, so we don't count it. */
534 	if (!ext4_es_must_keep(es)) {
535 		if (!EXT4_I(inode)->i_es_shk_nr++)
536 			ext4_es_list_add(inode);
537 		percpu_counter_inc(&EXT4_SB(inode->i_sb)->
538 					s_es_stats.es_stats_shk_cnt);
539 	}
540 
541 	EXT4_I(inode)->i_es_all_nr++;
542 	percpu_counter_inc(&EXT4_SB(inode->i_sb)->s_es_stats.es_stats_all_cnt);
543 }
544 
545 static inline void __es_free_extent(struct extent_status *es)
546 {
547 	kmem_cache_free(ext4_es_cachep, es);
548 }
549 
550 static void ext4_es_free_extent(struct inode *inode, struct extent_status *es)
551 {
552 	EXT4_I(inode)->i_es_all_nr--;
553 	percpu_counter_dec(&EXT4_SB(inode->i_sb)->s_es_stats.es_stats_all_cnt);
554 
555 	/* Decrease the shrink counter when we can reclaim the extent. */
556 	if (!ext4_es_must_keep(es)) {
557 		BUG_ON(EXT4_I(inode)->i_es_shk_nr == 0);
558 		if (!--EXT4_I(inode)->i_es_shk_nr)
559 			ext4_es_list_del(inode);
560 		percpu_counter_dec(&EXT4_SB(inode->i_sb)->
561 					s_es_stats.es_stats_shk_cnt);
562 	}
563 
564 	__es_free_extent(es);
565 }
566 
567 /*
568  * Check whether or not two extents can be merged
569  * Condition:
570  *  - logical block number is contiguous
571  *  - physical block number is contiguous
572  *  - status is equal
573  */
574 static int ext4_es_can_be_merged(struct extent_status *es1,
575 				 struct extent_status *es2)
576 {
577 	if (ext4_es_type(es1) != ext4_es_type(es2))
578 		return 0;
579 
580 	if (((__u64) es1->es_len) + es2->es_len > EXT_MAX_BLOCKS) {
581 		pr_warn("ES assertion failed when merging extents. "
582 			"The sum of lengths of es1 (%d) and es2 (%d) "
583 			"is bigger than allowed file size (%d)\n",
584 			es1->es_len, es2->es_len, EXT_MAX_BLOCKS);
585 		WARN_ON(1);
586 		return 0;
587 	}
588 
589 	if (((__u64) es1->es_lblk) + es1->es_len != es2->es_lblk)
590 		return 0;
591 
592 	if ((ext4_es_is_written(es1) || ext4_es_is_unwritten(es1)) &&
593 	    (ext4_es_pblock(es1) + es1->es_len == ext4_es_pblock(es2)))
594 		return 1;
595 
596 	if (ext4_es_is_hole(es1))
597 		return 1;
598 
599 	/* we need to check delayed extent */
600 	if (ext4_es_is_delayed(es1))
601 		return 1;
602 
603 	return 0;
604 }
605 
606 static struct extent_status *
607 ext4_es_try_to_merge_left(struct inode *inode, struct extent_status *es)
608 {
609 	struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
610 	struct extent_status *es1;
611 	struct rb_node *node;
612 
613 	node = rb_prev(&es->rb_node);
614 	if (!node)
615 		return es;
616 
617 	es1 = rb_entry(node, struct extent_status, rb_node);
618 	if (ext4_es_can_be_merged(es1, es)) {
619 		es1->es_len += es->es_len;
620 		if (ext4_es_is_referenced(es))
621 			ext4_es_set_referenced(es1);
622 		rb_erase(&es->rb_node, &tree->root);
623 		ext4_es_free_extent(inode, es);
624 		es = es1;
625 	}
626 
627 	return es;
628 }
629 
630 static struct extent_status *
631 ext4_es_try_to_merge_right(struct inode *inode, struct extent_status *es)
632 {
633 	struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
634 	struct extent_status *es1;
635 	struct rb_node *node;
636 
637 	node = rb_next(&es->rb_node);
638 	if (!node)
639 		return es;
640 
641 	es1 = rb_entry(node, struct extent_status, rb_node);
642 	if (ext4_es_can_be_merged(es, es1)) {
643 		es->es_len += es1->es_len;
644 		if (ext4_es_is_referenced(es1))
645 			ext4_es_set_referenced(es);
646 		rb_erase(node, &tree->root);
647 		ext4_es_free_extent(inode, es1);
648 	}
649 
650 	return es;
651 }
652 
653 #ifdef ES_AGGRESSIVE_TEST
654 #include "ext4_extents.h"	/* Needed when ES_AGGRESSIVE_TEST is defined */
655 
656 static void ext4_es_insert_extent_ext_check(struct inode *inode,
657 					    struct extent_status *es)
658 {
659 	struct ext4_ext_path *path = NULL;
660 	struct ext4_extent *ex;
661 	ext4_lblk_t ee_block;
662 	ext4_fsblk_t ee_start;
663 	unsigned short ee_len;
664 	int depth, ee_status, es_status;
665 
666 	path = ext4_find_extent(inode, es->es_lblk, NULL, EXT4_EX_NOCACHE);
667 	if (IS_ERR(path))
668 		return;
669 
670 	depth = ext_depth(inode);
671 	ex = path[depth].p_ext;
672 
673 	if (ex) {
674 
675 		ee_block = le32_to_cpu(ex->ee_block);
676 		ee_start = ext4_ext_pblock(ex);
677 		ee_len = ext4_ext_get_actual_len(ex);
678 
679 		ee_status = ext4_ext_is_unwritten(ex) ? 1 : 0;
680 		es_status = ext4_es_is_unwritten(es) ? 1 : 0;
681 
682 		/*
683 		 * Make sure ex and es are not overlap when we try to insert
684 		 * a delayed/hole extent.
685 		 */
686 		if (!ext4_es_is_written(es) && !ext4_es_is_unwritten(es)) {
687 			if (in_range(es->es_lblk, ee_block, ee_len)) {
688 				pr_warn("ES insert assertion failed for "
689 					"inode: %lu we can find an extent "
690 					"at block [%d/%d/%llu/%c], but we "
691 					"want to add a delayed/hole extent "
692 					"[%d/%d/%llu/%x]\n",
693 					inode->i_ino, ee_block, ee_len,
694 					ee_start, ee_status ? 'u' : 'w',
695 					es->es_lblk, es->es_len,
696 					ext4_es_pblock(es), ext4_es_status(es));
697 			}
698 			goto out;
699 		}
700 
701 		/*
702 		 * We don't check ee_block == es->es_lblk, etc. because es
703 		 * might be a part of whole extent, vice versa.
704 		 */
705 		if (es->es_lblk < ee_block ||
706 		    ext4_es_pblock(es) != ee_start + es->es_lblk - ee_block) {
707 			pr_warn("ES insert assertion failed for inode: %lu "
708 				"ex_status [%d/%d/%llu/%c] != "
709 				"es_status [%d/%d/%llu/%c]\n", inode->i_ino,
710 				ee_block, ee_len, ee_start,
711 				ee_status ? 'u' : 'w', es->es_lblk, es->es_len,
712 				ext4_es_pblock(es), es_status ? 'u' : 'w');
713 			goto out;
714 		}
715 
716 		if (ee_status ^ es_status) {
717 			pr_warn("ES insert assertion failed for inode: %lu "
718 				"ex_status [%d/%d/%llu/%c] != "
719 				"es_status [%d/%d/%llu/%c]\n", inode->i_ino,
720 				ee_block, ee_len, ee_start,
721 				ee_status ? 'u' : 'w', es->es_lblk, es->es_len,
722 				ext4_es_pblock(es), es_status ? 'u' : 'w');
723 		}
724 	} else {
725 		/*
726 		 * We can't find an extent on disk.  So we need to make sure
727 		 * that we don't want to add an written/unwritten extent.
728 		 */
729 		if (!ext4_es_is_delayed(es) && !ext4_es_is_hole(es)) {
730 			pr_warn("ES insert assertion failed for inode: %lu "
731 				"can't find an extent at block %d but we want "
732 				"to add a written/unwritten extent "
733 				"[%d/%d/%llu/%x]\n", inode->i_ino,
734 				es->es_lblk, es->es_lblk, es->es_len,
735 				ext4_es_pblock(es), ext4_es_status(es));
736 		}
737 	}
738 out:
739 	ext4_free_ext_path(path);
740 }
741 
742 static void ext4_es_insert_extent_ind_check(struct inode *inode,
743 					    struct extent_status *es)
744 {
745 	struct ext4_map_blocks map;
746 	int retval;
747 
748 	/*
749 	 * Here we call ext4_ind_map_blocks to lookup a block mapping because
750 	 * 'Indirect' structure is defined in indirect.c.  So we couldn't
751 	 * access direct/indirect tree from outside.  It is too dirty to define
752 	 * this function in indirect.c file.
753 	 */
754 
755 	map.m_lblk = es->es_lblk;
756 	map.m_len = es->es_len;
757 
758 	retval = ext4_ind_map_blocks(NULL, inode, &map, 0);
759 	if (retval > 0) {
760 		if (ext4_es_is_delayed(es) || ext4_es_is_hole(es)) {
761 			/*
762 			 * We want to add a delayed/hole extent but this
763 			 * block has been allocated.
764 			 */
765 			pr_warn("ES insert assertion failed for inode: %lu "
766 				"We can find blocks but we want to add a "
767 				"delayed/hole extent [%d/%d/%llu/%x]\n",
768 				inode->i_ino, es->es_lblk, es->es_len,
769 				ext4_es_pblock(es), ext4_es_status(es));
770 			return;
771 		} else if (ext4_es_is_written(es)) {
772 			if (retval != es->es_len) {
773 				pr_warn("ES insert assertion failed for "
774 					"inode: %lu retval %d != es_len %d\n",
775 					inode->i_ino, retval, es->es_len);
776 				return;
777 			}
778 			if (map.m_pblk != ext4_es_pblock(es)) {
779 				pr_warn("ES insert assertion failed for "
780 					"inode: %lu m_pblk %llu != "
781 					"es_pblk %llu\n",
782 					inode->i_ino, map.m_pblk,
783 					ext4_es_pblock(es));
784 				return;
785 			}
786 		} else {
787 			/*
788 			 * We don't need to check unwritten extent because
789 			 * indirect-based file doesn't have it.
790 			 */
791 			BUG();
792 		}
793 	} else if (retval == 0) {
794 		if (ext4_es_is_written(es)) {
795 			pr_warn("ES insert assertion failed for inode: %lu "
796 				"We can't find the block but we want to add "
797 				"a written extent [%d/%d/%llu/%x]\n",
798 				inode->i_ino, es->es_lblk, es->es_len,
799 				ext4_es_pblock(es), ext4_es_status(es));
800 			return;
801 		}
802 	}
803 }
804 
805 static inline void ext4_es_insert_extent_check(struct inode *inode,
806 					       struct extent_status *es)
807 {
808 	/*
809 	 * We don't need to worry about the race condition because
810 	 * caller takes i_data_sem locking.
811 	 */
812 	BUG_ON(!rwsem_is_locked(&EXT4_I(inode)->i_data_sem));
813 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
814 		ext4_es_insert_extent_ext_check(inode, es);
815 	else
816 		ext4_es_insert_extent_ind_check(inode, es);
817 }
818 #else
819 static inline void ext4_es_insert_extent_check(struct inode *inode,
820 					       struct extent_status *es)
821 {
822 }
823 #endif
824 
825 static int __es_insert_extent(struct inode *inode, struct extent_status *newes,
826 			      struct extent_status *prealloc)
827 {
828 	struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
829 	struct rb_node **p = &tree->root.rb_node;
830 	struct rb_node *parent = NULL;
831 	struct extent_status *es;
832 
833 	while (*p) {
834 		parent = *p;
835 		es = rb_entry(parent, struct extent_status, rb_node);
836 
837 		if (newes->es_lblk < es->es_lblk) {
838 			if (ext4_es_can_be_merged(newes, es)) {
839 				/*
840 				 * Here we can modify es_lblk directly
841 				 * because it isn't overlapped.
842 				 */
843 				es->es_lblk = newes->es_lblk;
844 				es->es_len += newes->es_len;
845 				if (ext4_es_is_written(es) ||
846 				    ext4_es_is_unwritten(es))
847 					ext4_es_store_pblock(es,
848 							     newes->es_pblk);
849 				es = ext4_es_try_to_merge_left(inode, es);
850 				goto out;
851 			}
852 			p = &(*p)->rb_left;
853 		} else if (newes->es_lblk > ext4_es_end(es)) {
854 			if (ext4_es_can_be_merged(es, newes)) {
855 				es->es_len += newes->es_len;
856 				es = ext4_es_try_to_merge_right(inode, es);
857 				goto out;
858 			}
859 			p = &(*p)->rb_right;
860 		} else {
861 			BUG();
862 			return -EINVAL;
863 		}
864 	}
865 
866 	if (prealloc)
867 		es = prealloc;
868 	else
869 		es = __es_alloc_extent(false);
870 	if (!es)
871 		return -ENOMEM;
872 	ext4_es_init_extent(inode, es, newes->es_lblk, newes->es_len,
873 			    newes->es_pblk);
874 
875 	rb_link_node(&es->rb_node, parent, p);
876 	rb_insert_color(&es->rb_node, &tree->root);
877 
878 out:
879 	tree->cache_es = es;
880 	return 0;
881 }
882 
883 /*
884  * ext4_es_insert_extent() adds information to an inode's extent
885  * status tree.
886  */
887 void ext4_es_insert_extent(struct inode *inode, ext4_lblk_t lblk,
888 			   ext4_lblk_t len, ext4_fsblk_t pblk,
889 			   unsigned int status, bool delalloc_reserve_used)
890 {
891 	struct extent_status newes;
892 	ext4_lblk_t end = lblk + len - 1;
893 	int err1 = 0, err2 = 0, err3 = 0;
894 	int resv_used = 0, pending = 0;
895 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
896 	struct extent_status *es1 = NULL;
897 	struct extent_status *es2 = NULL;
898 	struct pending_reservation *pr = NULL;
899 	bool revise_pending = false;
900 
901 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
902 		return;
903 
904 	es_debug("add [%u/%u) %llu %x %d to extent status tree of inode %lu\n",
905 		 lblk, len, pblk, status, delalloc_reserve_used, inode->i_ino);
906 
907 	if (!len)
908 		return;
909 
910 	BUG_ON(end < lblk);
911 	WARN_ON_ONCE(status & EXTENT_STATUS_DELAYED);
912 
913 	newes.es_lblk = lblk;
914 	newes.es_len = len;
915 	ext4_es_store_pblock_status(&newes, pblk, status);
916 
917 	ext4_es_insert_extent_check(inode, &newes);
918 
919 	revise_pending = sbi->s_cluster_ratio > 1 &&
920 			 test_opt(inode->i_sb, DELALLOC) &&
921 			 (status & (EXTENT_STATUS_WRITTEN |
922 				    EXTENT_STATUS_UNWRITTEN));
923 retry:
924 	if (err1 && !es1)
925 		es1 = __es_alloc_extent(true);
926 	if ((err1 || err2) && !es2)
927 		es2 = __es_alloc_extent(true);
928 	if ((err1 || err2 || err3 < 0) && revise_pending && !pr)
929 		pr = __alloc_pending(true);
930 	write_lock(&EXT4_I(inode)->i_es_lock);
931 
932 	err1 = __es_remove_extent(inode, lblk, end, &resv_used, es1);
933 	if (err1 != 0)
934 		goto error;
935 	/* Free preallocated extent if it didn't get used. */
936 	if (es1) {
937 		if (!es1->es_len)
938 			__es_free_extent(es1);
939 		es1 = NULL;
940 	}
941 
942 	err2 = __es_insert_extent(inode, &newes, es2);
943 	if (err2 == -ENOMEM && !ext4_es_must_keep(&newes))
944 		err2 = 0;
945 	if (err2 != 0)
946 		goto error;
947 	/* Free preallocated extent if it didn't get used. */
948 	if (es2) {
949 		if (!es2->es_len)
950 			__es_free_extent(es2);
951 		es2 = NULL;
952 	}
953 
954 	if (revise_pending) {
955 		err3 = __revise_pending(inode, lblk, len, &pr);
956 		if (err3 < 0)
957 			goto error;
958 		if (pr) {
959 			__free_pending(pr);
960 			pr = NULL;
961 		}
962 		pending = err3;
963 	}
964 	/*
965 	 * TODO: For cache on-disk extents, there is no need to increment
966 	 * the sequence counter, this requires future optimization.
967 	 */
968 	ext4_es_inc_seq(inode);
969 error:
970 	write_unlock(&EXT4_I(inode)->i_es_lock);
971 	/*
972 	 * Reduce the reserved cluster count to reflect successful deferred
973 	 * allocation of delayed allocated clusters or direct allocation of
974 	 * clusters discovered to be delayed allocated.  Once allocated, a
975 	 * cluster is not included in the reserved count.
976 	 *
977 	 * When direct allocating (from fallocate, filemap, DIO, or clusters
978 	 * allocated when delalloc has been disabled by ext4_nonda_switch())
979 	 * an extent either 1) contains delayed blocks but start with
980 	 * non-delayed allocated blocks (e.g. hole) or 2) contains non-delayed
981 	 * allocated blocks which belong to delayed allocated clusters when
982 	 * bigalloc feature is enabled, quota has already been claimed by
983 	 * ext4_mb_new_blocks(), so release the quota reservations made for
984 	 * any previously delayed allocated clusters instead of claim them
985 	 * again.
986 	 */
987 	resv_used += pending;
988 	if (resv_used)
989 		ext4_da_update_reserve_space(inode, resv_used,
990 					     delalloc_reserve_used);
991 
992 	if (err1 || err2 || err3 < 0)
993 		goto retry;
994 
995 	trace_ext4_es_insert_extent(inode, &newes);
996 	ext4_es_print_tree(inode);
997 	return;
998 }
999 
1000 /*
1001  * ext4_es_cache_extent() inserts information into the extent status
1002  * tree if and only if there isn't information about the range in
1003  * question already.
1004  */
1005 void ext4_es_cache_extent(struct inode *inode, ext4_lblk_t lblk,
1006 			  ext4_lblk_t len, ext4_fsblk_t pblk,
1007 			  unsigned int status)
1008 {
1009 	struct extent_status *es;
1010 	struct extent_status newes;
1011 	ext4_lblk_t end = lblk + len - 1;
1012 
1013 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
1014 		return;
1015 
1016 	newes.es_lblk = lblk;
1017 	newes.es_len = len;
1018 	ext4_es_store_pblock_status(&newes, pblk, status);
1019 	trace_ext4_es_cache_extent(inode, &newes);
1020 
1021 	if (!len)
1022 		return;
1023 
1024 	BUG_ON(end < lblk);
1025 
1026 	write_lock(&EXT4_I(inode)->i_es_lock);
1027 
1028 	es = __es_tree_search(&EXT4_I(inode)->i_es_tree.root, lblk);
1029 	if (!es || es->es_lblk > end)
1030 		__es_insert_extent(inode, &newes, NULL);
1031 	write_unlock(&EXT4_I(inode)->i_es_lock);
1032 }
1033 
1034 /*
1035  * ext4_es_lookup_extent() looks up an extent in extent status tree.
1036  *
1037  * ext4_es_lookup_extent is called by ext4_map_blocks/ext4_da_map_blocks.
1038  *
1039  * Return: 1 on found, 0 on not
1040  */
1041 int ext4_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk,
1042 			  ext4_lblk_t *next_lblk, struct extent_status *es,
1043 			  u64 *pseq)
1044 {
1045 	struct ext4_es_tree *tree;
1046 	struct ext4_es_stats *stats;
1047 	struct extent_status *es1 = NULL;
1048 	struct rb_node *node;
1049 	int found = 0;
1050 
1051 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
1052 		return 0;
1053 
1054 	trace_ext4_es_lookup_extent_enter(inode, lblk);
1055 	es_debug("lookup extent in block %u\n", lblk);
1056 
1057 	tree = &EXT4_I(inode)->i_es_tree;
1058 	read_lock(&EXT4_I(inode)->i_es_lock);
1059 
1060 	/* find extent in cache firstly */
1061 	es->es_lblk = es->es_len = es->es_pblk = 0;
1062 	es1 = READ_ONCE(tree->cache_es);
1063 	if (es1 && in_range(lblk, es1->es_lblk, es1->es_len)) {
1064 		es_debug("%u cached by [%u/%u)\n",
1065 			 lblk, es1->es_lblk, es1->es_len);
1066 		found = 1;
1067 		goto out;
1068 	}
1069 
1070 	node = tree->root.rb_node;
1071 	while (node) {
1072 		es1 = rb_entry(node, struct extent_status, rb_node);
1073 		if (lblk < es1->es_lblk)
1074 			node = node->rb_left;
1075 		else if (lblk > ext4_es_end(es1))
1076 			node = node->rb_right;
1077 		else {
1078 			found = 1;
1079 			break;
1080 		}
1081 	}
1082 
1083 out:
1084 	stats = &EXT4_SB(inode->i_sb)->s_es_stats;
1085 	if (found) {
1086 		BUG_ON(!es1);
1087 		es->es_lblk = es1->es_lblk;
1088 		es->es_len = es1->es_len;
1089 		es->es_pblk = es1->es_pblk;
1090 		if (!ext4_es_is_referenced(es1))
1091 			ext4_es_set_referenced(es1);
1092 		percpu_counter_inc(&stats->es_stats_cache_hits);
1093 		if (next_lblk) {
1094 			node = rb_next(&es1->rb_node);
1095 			if (node) {
1096 				es1 = rb_entry(node, struct extent_status,
1097 					       rb_node);
1098 				*next_lblk = es1->es_lblk;
1099 			} else
1100 				*next_lblk = 0;
1101 		}
1102 		if (pseq)
1103 			*pseq = EXT4_I(inode)->i_es_seq;
1104 	} else {
1105 		percpu_counter_inc(&stats->es_stats_cache_misses);
1106 	}
1107 
1108 	read_unlock(&EXT4_I(inode)->i_es_lock);
1109 
1110 	trace_ext4_es_lookup_extent_exit(inode, es, found);
1111 	return found;
1112 }
1113 
1114 struct rsvd_count {
1115 	int ndelayed;
1116 	bool first_do_lblk_found;
1117 	ext4_lblk_t first_do_lblk;
1118 	ext4_lblk_t last_do_lblk;
1119 	struct extent_status *left_es;
1120 	bool partial;
1121 	ext4_lblk_t lclu;
1122 };
1123 
1124 /*
1125  * init_rsvd - initialize reserved count data before removing block range
1126  *	       in file from extent status tree
1127  *
1128  * @inode - file containing range
1129  * @lblk - first block in range
1130  * @es - pointer to first extent in range
1131  * @rc - pointer to reserved count data
1132  *
1133  * Assumes es is not NULL
1134  */
1135 static void init_rsvd(struct inode *inode, ext4_lblk_t lblk,
1136 		      struct extent_status *es, struct rsvd_count *rc)
1137 {
1138 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1139 	struct rb_node *node;
1140 
1141 	rc->ndelayed = 0;
1142 
1143 	/*
1144 	 * for bigalloc, note the first delayed block in the range has not
1145 	 * been found, record the extent containing the block to the left of
1146 	 * the region to be removed, if any, and note that there's no partial
1147 	 * cluster to track
1148 	 */
1149 	if (sbi->s_cluster_ratio > 1) {
1150 		rc->first_do_lblk_found = false;
1151 		if (lblk > es->es_lblk) {
1152 			rc->left_es = es;
1153 		} else {
1154 			node = rb_prev(&es->rb_node);
1155 			rc->left_es = node ? rb_entry(node,
1156 						      struct extent_status,
1157 						      rb_node) : NULL;
1158 		}
1159 		rc->partial = false;
1160 	}
1161 }
1162 
1163 /*
1164  * count_rsvd - count the clusters containing delayed blocks in a range
1165  *	        within an extent and add to the running tally in rsvd_count
1166  *
1167  * @inode - file containing extent
1168  * @lblk - first block in range
1169  * @len - length of range in blocks
1170  * @es - pointer to extent containing clusters to be counted
1171  * @rc - pointer to reserved count data
1172  *
1173  * Tracks partial clusters found at the beginning and end of extents so
1174  * they aren't overcounted when they span adjacent extents
1175  */
1176 static void count_rsvd(struct inode *inode, ext4_lblk_t lblk, long len,
1177 		       struct extent_status *es, struct rsvd_count *rc)
1178 {
1179 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1180 	ext4_lblk_t i, end, nclu;
1181 
1182 	if (!ext4_es_is_delayed(es))
1183 		return;
1184 
1185 	WARN_ON(len <= 0);
1186 
1187 	if (sbi->s_cluster_ratio == 1) {
1188 		rc->ndelayed += (int) len;
1189 		return;
1190 	}
1191 
1192 	/* bigalloc */
1193 
1194 	i = (lblk < es->es_lblk) ? es->es_lblk : lblk;
1195 	end = lblk + (ext4_lblk_t) len - 1;
1196 	end = (end > ext4_es_end(es)) ? ext4_es_end(es) : end;
1197 
1198 	/* record the first block of the first delayed extent seen */
1199 	if (!rc->first_do_lblk_found) {
1200 		rc->first_do_lblk = i;
1201 		rc->first_do_lblk_found = true;
1202 	}
1203 
1204 	/* update the last lblk in the region seen so far */
1205 	rc->last_do_lblk = end;
1206 
1207 	/*
1208 	 * if we're tracking a partial cluster and the current extent
1209 	 * doesn't start with it, count it and stop tracking
1210 	 */
1211 	if (rc->partial && (rc->lclu != EXT4_B2C(sbi, i))) {
1212 		rc->ndelayed++;
1213 		rc->partial = false;
1214 	}
1215 
1216 	/*
1217 	 * if the first cluster doesn't start on a cluster boundary but
1218 	 * ends on one, count it
1219 	 */
1220 	if (EXT4_LBLK_COFF(sbi, i) != 0) {
1221 		if (end >= EXT4_LBLK_CFILL(sbi, i)) {
1222 			rc->ndelayed++;
1223 			rc->partial = false;
1224 			i = EXT4_LBLK_CFILL(sbi, i) + 1;
1225 		}
1226 	}
1227 
1228 	/*
1229 	 * if the current cluster starts on a cluster boundary, count the
1230 	 * number of whole delayed clusters in the extent
1231 	 */
1232 	if ((i + sbi->s_cluster_ratio - 1) <= end) {
1233 		nclu = (end - i + 1) >> sbi->s_cluster_bits;
1234 		rc->ndelayed += nclu;
1235 		i += nclu << sbi->s_cluster_bits;
1236 	}
1237 
1238 	/*
1239 	 * start tracking a partial cluster if there's a partial at the end
1240 	 * of the current extent and we're not already tracking one
1241 	 */
1242 	if (!rc->partial && i <= end) {
1243 		rc->partial = true;
1244 		rc->lclu = EXT4_B2C(sbi, i);
1245 	}
1246 }
1247 
1248 /*
1249  * __pr_tree_search - search for a pending cluster reservation
1250  *
1251  * @root - root of pending reservation tree
1252  * @lclu - logical cluster to search for
1253  *
1254  * Returns the pending reservation for the cluster identified by @lclu
1255  * if found.  If not, returns a reservation for the next cluster if any,
1256  * and if not, returns NULL.
1257  */
1258 static struct pending_reservation *__pr_tree_search(struct rb_root *root,
1259 						    ext4_lblk_t lclu)
1260 {
1261 	struct rb_node *node = root->rb_node;
1262 	struct pending_reservation *pr = NULL;
1263 
1264 	while (node) {
1265 		pr = rb_entry(node, struct pending_reservation, rb_node);
1266 		if (lclu < pr->lclu)
1267 			node = node->rb_left;
1268 		else if (lclu > pr->lclu)
1269 			node = node->rb_right;
1270 		else
1271 			return pr;
1272 	}
1273 	if (pr && lclu < pr->lclu)
1274 		return pr;
1275 	if (pr && lclu > pr->lclu) {
1276 		node = rb_next(&pr->rb_node);
1277 		return node ? rb_entry(node, struct pending_reservation,
1278 				       rb_node) : NULL;
1279 	}
1280 	return NULL;
1281 }
1282 
1283 /*
1284  * get_rsvd - calculates and returns the number of cluster reservations to be
1285  *	      released when removing a block range from the extent status tree
1286  *	      and releases any pending reservations within the range
1287  *
1288  * @inode - file containing block range
1289  * @end - last block in range
1290  * @right_es - pointer to extent containing next block beyond end or NULL
1291  * @rc - pointer to reserved count data
1292  *
1293  * The number of reservations to be released is equal to the number of
1294  * clusters containing delayed blocks within the range, minus the number of
1295  * clusters still containing delayed blocks at the ends of the range, and
1296  * minus the number of pending reservations within the range.
1297  */
1298 static unsigned int get_rsvd(struct inode *inode, ext4_lblk_t end,
1299 			     struct extent_status *right_es,
1300 			     struct rsvd_count *rc)
1301 {
1302 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1303 	struct pending_reservation *pr;
1304 	struct ext4_pending_tree *tree = &EXT4_I(inode)->i_pending_tree;
1305 	struct rb_node *node;
1306 	ext4_lblk_t first_lclu, last_lclu;
1307 	bool left_delayed, right_delayed, count_pending;
1308 	struct extent_status *es;
1309 
1310 	if (sbi->s_cluster_ratio > 1) {
1311 		/* count any remaining partial cluster */
1312 		if (rc->partial)
1313 			rc->ndelayed++;
1314 
1315 		if (rc->ndelayed == 0)
1316 			return 0;
1317 
1318 		first_lclu = EXT4_B2C(sbi, rc->first_do_lblk);
1319 		last_lclu = EXT4_B2C(sbi, rc->last_do_lblk);
1320 
1321 		/*
1322 		 * decrease the delayed count by the number of clusters at the
1323 		 * ends of the range that still contain delayed blocks -
1324 		 * these clusters still need to be reserved
1325 		 */
1326 		left_delayed = right_delayed = false;
1327 
1328 		es = rc->left_es;
1329 		while (es && ext4_es_end(es) >=
1330 		       EXT4_LBLK_CMASK(sbi, rc->first_do_lblk)) {
1331 			if (ext4_es_is_delayed(es)) {
1332 				rc->ndelayed--;
1333 				left_delayed = true;
1334 				break;
1335 			}
1336 			node = rb_prev(&es->rb_node);
1337 			if (!node)
1338 				break;
1339 			es = rb_entry(node, struct extent_status, rb_node);
1340 		}
1341 		if (right_es && (!left_delayed || first_lclu != last_lclu)) {
1342 			if (end < ext4_es_end(right_es)) {
1343 				es = right_es;
1344 			} else {
1345 				node = rb_next(&right_es->rb_node);
1346 				es = node ? rb_entry(node, struct extent_status,
1347 						     rb_node) : NULL;
1348 			}
1349 			while (es && es->es_lblk <=
1350 			       EXT4_LBLK_CFILL(sbi, rc->last_do_lblk)) {
1351 				if (ext4_es_is_delayed(es)) {
1352 					rc->ndelayed--;
1353 					right_delayed = true;
1354 					break;
1355 				}
1356 				node = rb_next(&es->rb_node);
1357 				if (!node)
1358 					break;
1359 				es = rb_entry(node, struct extent_status,
1360 					      rb_node);
1361 			}
1362 		}
1363 
1364 		/*
1365 		 * Determine the block range that should be searched for
1366 		 * pending reservations, if any.  Clusters on the ends of the
1367 		 * original removed range containing delayed blocks are
1368 		 * excluded.  They've already been accounted for and it's not
1369 		 * possible to determine if an associated pending reservation
1370 		 * should be released with the information available in the
1371 		 * extents status tree.
1372 		 */
1373 		if (first_lclu == last_lclu) {
1374 			if (left_delayed | right_delayed)
1375 				count_pending = false;
1376 			else
1377 				count_pending = true;
1378 		} else {
1379 			if (left_delayed)
1380 				first_lclu++;
1381 			if (right_delayed)
1382 				last_lclu--;
1383 			if (first_lclu <= last_lclu)
1384 				count_pending = true;
1385 			else
1386 				count_pending = false;
1387 		}
1388 
1389 		/*
1390 		 * a pending reservation found between first_lclu and last_lclu
1391 		 * represents an allocated cluster that contained at least one
1392 		 * delayed block, so the delayed total must be reduced by one
1393 		 * for each pending reservation found and released
1394 		 */
1395 		if (count_pending) {
1396 			pr = __pr_tree_search(&tree->root, first_lclu);
1397 			while (pr && pr->lclu <= last_lclu) {
1398 				rc->ndelayed--;
1399 				node = rb_next(&pr->rb_node);
1400 				rb_erase(&pr->rb_node, &tree->root);
1401 				__free_pending(pr);
1402 				if (!node)
1403 					break;
1404 				pr = rb_entry(node, struct pending_reservation,
1405 					      rb_node);
1406 			}
1407 		}
1408 	}
1409 	return rc->ndelayed;
1410 }
1411 
1412 
1413 /*
1414  * __es_remove_extent - removes block range from extent status tree
1415  *
1416  * @inode - file containing range
1417  * @lblk - first block in range
1418  * @end - last block in range
1419  * @reserved - number of cluster reservations released
1420  * @prealloc - pre-allocated es to avoid memory allocation failures
1421  *
1422  * If @reserved is not NULL and delayed allocation is enabled, counts
1423  * block/cluster reservations freed by removing range and if bigalloc
1424  * enabled cancels pending reservations as needed. Returns 0 on success,
1425  * error code on failure.
1426  */
1427 static int __es_remove_extent(struct inode *inode, ext4_lblk_t lblk,
1428 			      ext4_lblk_t end, int *reserved,
1429 			      struct extent_status *prealloc)
1430 {
1431 	struct ext4_es_tree *tree = &EXT4_I(inode)->i_es_tree;
1432 	struct rb_node *node;
1433 	struct extent_status *es;
1434 	struct extent_status orig_es;
1435 	ext4_lblk_t len1, len2;
1436 	ext4_fsblk_t block;
1437 	int err = 0;
1438 	bool count_reserved = true;
1439 	struct rsvd_count rc;
1440 
1441 	if (reserved == NULL || !test_opt(inode->i_sb, DELALLOC))
1442 		count_reserved = false;
1443 
1444 	es = __es_tree_search(&tree->root, lblk);
1445 	if (!es)
1446 		goto out;
1447 	if (es->es_lblk > end)
1448 		goto out;
1449 
1450 	/* Simply invalidate cache_es. */
1451 	tree->cache_es = NULL;
1452 	if (count_reserved)
1453 		init_rsvd(inode, lblk, es, &rc);
1454 
1455 	orig_es.es_lblk = es->es_lblk;
1456 	orig_es.es_len = es->es_len;
1457 	orig_es.es_pblk = es->es_pblk;
1458 
1459 	len1 = lblk > es->es_lblk ? lblk - es->es_lblk : 0;
1460 	len2 = ext4_es_end(es) > end ? ext4_es_end(es) - end : 0;
1461 	if (len1 > 0)
1462 		es->es_len = len1;
1463 	if (len2 > 0) {
1464 		if (len1 > 0) {
1465 			struct extent_status newes;
1466 
1467 			newes.es_lblk = end + 1;
1468 			newes.es_len = len2;
1469 			block = 0x7FDEADBEEFULL;
1470 			if (ext4_es_is_written(&orig_es) ||
1471 			    ext4_es_is_unwritten(&orig_es))
1472 				block = ext4_es_pblock(&orig_es) +
1473 					orig_es.es_len - len2;
1474 			ext4_es_store_pblock_status(&newes, block,
1475 						    ext4_es_status(&orig_es));
1476 			err = __es_insert_extent(inode, &newes, prealloc);
1477 			if (err) {
1478 				if (!ext4_es_must_keep(&newes))
1479 					return 0;
1480 
1481 				es->es_lblk = orig_es.es_lblk;
1482 				es->es_len = orig_es.es_len;
1483 				goto out;
1484 			}
1485 		} else {
1486 			es->es_lblk = end + 1;
1487 			es->es_len = len2;
1488 			if (ext4_es_is_written(es) ||
1489 			    ext4_es_is_unwritten(es)) {
1490 				block = orig_es.es_pblk + orig_es.es_len - len2;
1491 				ext4_es_store_pblock(es, block);
1492 			}
1493 		}
1494 		if (count_reserved)
1495 			count_rsvd(inode, orig_es.es_lblk + len1,
1496 				   orig_es.es_len - len1 - len2, &orig_es, &rc);
1497 		goto out_get_reserved;
1498 	}
1499 
1500 	if (len1 > 0) {
1501 		if (count_reserved)
1502 			count_rsvd(inode, lblk, orig_es.es_len - len1,
1503 				   &orig_es, &rc);
1504 		node = rb_next(&es->rb_node);
1505 		if (node)
1506 			es = rb_entry(node, struct extent_status, rb_node);
1507 		else
1508 			es = NULL;
1509 	}
1510 
1511 	while (es && ext4_es_end(es) <= end) {
1512 		if (count_reserved)
1513 			count_rsvd(inode, es->es_lblk, es->es_len, es, &rc);
1514 		node = rb_next(&es->rb_node);
1515 		rb_erase(&es->rb_node, &tree->root);
1516 		ext4_es_free_extent(inode, es);
1517 		if (!node) {
1518 			es = NULL;
1519 			break;
1520 		}
1521 		es = rb_entry(node, struct extent_status, rb_node);
1522 	}
1523 
1524 	if (es && es->es_lblk < end + 1) {
1525 		ext4_lblk_t orig_len = es->es_len;
1526 
1527 		len1 = ext4_es_end(es) - end;
1528 		if (count_reserved)
1529 			count_rsvd(inode, es->es_lblk, orig_len - len1,
1530 				   es, &rc);
1531 		es->es_lblk = end + 1;
1532 		es->es_len = len1;
1533 		if (ext4_es_is_written(es) || ext4_es_is_unwritten(es)) {
1534 			block = es->es_pblk + orig_len - len1;
1535 			ext4_es_store_pblock(es, block);
1536 		}
1537 	}
1538 
1539 out_get_reserved:
1540 	if (count_reserved)
1541 		*reserved = get_rsvd(inode, end, es, &rc);
1542 out:
1543 	return err;
1544 }
1545 
1546 /*
1547  * ext4_es_remove_extent - removes block range from extent status tree
1548  *
1549  * @inode - file containing range
1550  * @lblk - first block in range
1551  * @len - number of blocks to remove
1552  *
1553  * Reduces block/cluster reservation count and for bigalloc cancels pending
1554  * reservations as needed.
1555  */
1556 void ext4_es_remove_extent(struct inode *inode, ext4_lblk_t lblk,
1557 			   ext4_lblk_t len)
1558 {
1559 	ext4_lblk_t end;
1560 	int err = 0;
1561 	int reserved = 0;
1562 	struct extent_status *es = NULL;
1563 
1564 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
1565 		return;
1566 
1567 	es_debug("remove [%u/%u) from extent status tree of inode %lu\n",
1568 		 lblk, len, inode->i_ino);
1569 
1570 	if (!len)
1571 		return;
1572 
1573 	end = lblk + len - 1;
1574 	BUG_ON(end < lblk);
1575 
1576 retry:
1577 	if (err && !es)
1578 		es = __es_alloc_extent(true);
1579 	/*
1580 	 * ext4_clear_inode() depends on us taking i_es_lock unconditionally
1581 	 * so that we are sure __es_shrink() is done with the inode before it
1582 	 * is reclaimed.
1583 	 */
1584 	write_lock(&EXT4_I(inode)->i_es_lock);
1585 	err = __es_remove_extent(inode, lblk, end, &reserved, es);
1586 	if (err)
1587 		goto error;
1588 	/* Free preallocated extent if it didn't get used. */
1589 	if (es) {
1590 		if (!es->es_len)
1591 			__es_free_extent(es);
1592 		es = NULL;
1593 	}
1594 	ext4_es_inc_seq(inode);
1595 error:
1596 	write_unlock(&EXT4_I(inode)->i_es_lock);
1597 	if (err)
1598 		goto retry;
1599 
1600 	trace_ext4_es_remove_extent(inode, lblk, len);
1601 	ext4_es_print_tree(inode);
1602 	ext4_da_release_space(inode, reserved);
1603 }
1604 
1605 static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan,
1606 		       struct ext4_inode_info *locked_ei)
1607 {
1608 	struct ext4_inode_info *ei;
1609 	struct ext4_es_stats *es_stats;
1610 	ktime_t start_time;
1611 	u64 scan_time;
1612 	int nr_to_walk;
1613 	int nr_shrunk = 0;
1614 	int retried = 0, nr_skipped = 0;
1615 
1616 	es_stats = &sbi->s_es_stats;
1617 	start_time = ktime_get();
1618 
1619 retry:
1620 	spin_lock(&sbi->s_es_lock);
1621 	nr_to_walk = sbi->s_es_nr_inode;
1622 	while (nr_to_walk-- > 0) {
1623 		if (list_empty(&sbi->s_es_list)) {
1624 			spin_unlock(&sbi->s_es_lock);
1625 			goto out;
1626 		}
1627 		ei = list_first_entry(&sbi->s_es_list, struct ext4_inode_info,
1628 				      i_es_list);
1629 		/* Move the inode to the tail */
1630 		list_move_tail(&ei->i_es_list, &sbi->s_es_list);
1631 
1632 		/*
1633 		 * Normally we try hard to avoid shrinking precached inodes,
1634 		 * but we will as a last resort.
1635 		 */
1636 		if (!retried && ext4_test_inode_state(&ei->vfs_inode,
1637 						EXT4_STATE_EXT_PRECACHED)) {
1638 			nr_skipped++;
1639 			continue;
1640 		}
1641 
1642 		if (ei == locked_ei || !write_trylock(&ei->i_es_lock)) {
1643 			nr_skipped++;
1644 			continue;
1645 		}
1646 		/*
1647 		 * Now we hold i_es_lock which protects us from inode reclaim
1648 		 * freeing inode under us
1649 		 */
1650 		spin_unlock(&sbi->s_es_lock);
1651 
1652 		nr_shrunk += es_reclaim_extents(ei, &nr_to_scan);
1653 		write_unlock(&ei->i_es_lock);
1654 
1655 		if (nr_to_scan <= 0)
1656 			goto out;
1657 		spin_lock(&sbi->s_es_lock);
1658 	}
1659 	spin_unlock(&sbi->s_es_lock);
1660 
1661 	/*
1662 	 * If we skipped any inodes, and we weren't able to make any
1663 	 * forward progress, try again to scan precached inodes.
1664 	 */
1665 	if ((nr_shrunk == 0) && nr_skipped && !retried) {
1666 		retried++;
1667 		goto retry;
1668 	}
1669 
1670 	if (locked_ei && nr_shrunk == 0)
1671 		nr_shrunk = es_reclaim_extents(locked_ei, &nr_to_scan);
1672 
1673 out:
1674 	scan_time = ktime_to_ns(ktime_sub(ktime_get(), start_time));
1675 	if (likely(es_stats->es_stats_scan_time))
1676 		es_stats->es_stats_scan_time = (scan_time +
1677 				es_stats->es_stats_scan_time*3) / 4;
1678 	else
1679 		es_stats->es_stats_scan_time = scan_time;
1680 	if (scan_time > es_stats->es_stats_max_scan_time)
1681 		es_stats->es_stats_max_scan_time = scan_time;
1682 	if (likely(es_stats->es_stats_shrunk))
1683 		es_stats->es_stats_shrunk = (nr_shrunk +
1684 				es_stats->es_stats_shrunk*3) / 4;
1685 	else
1686 		es_stats->es_stats_shrunk = nr_shrunk;
1687 
1688 	trace_ext4_es_shrink(sbi->s_sb, nr_shrunk, scan_time,
1689 			     nr_skipped, retried);
1690 	return nr_shrunk;
1691 }
1692 
1693 static unsigned long ext4_es_count(struct shrinker *shrink,
1694 				   struct shrink_control *sc)
1695 {
1696 	unsigned long nr;
1697 	struct ext4_sb_info *sbi;
1698 
1699 	sbi = shrink->private_data;
1700 	nr = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt);
1701 	trace_ext4_es_shrink_count(sbi->s_sb, sc->nr_to_scan, nr);
1702 	return nr;
1703 }
1704 
1705 static unsigned long ext4_es_scan(struct shrinker *shrink,
1706 				  struct shrink_control *sc)
1707 {
1708 	struct ext4_sb_info *sbi = shrink->private_data;
1709 	int nr_to_scan = sc->nr_to_scan;
1710 	int ret, nr_shrunk;
1711 
1712 	ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt);
1713 	trace_ext4_es_shrink_scan_enter(sbi->s_sb, nr_to_scan, ret);
1714 
1715 	nr_shrunk = __es_shrink(sbi, nr_to_scan, NULL);
1716 
1717 	ret = percpu_counter_read_positive(&sbi->s_es_stats.es_stats_shk_cnt);
1718 	trace_ext4_es_shrink_scan_exit(sbi->s_sb, nr_shrunk, ret);
1719 	return nr_shrunk;
1720 }
1721 
1722 int ext4_seq_es_shrinker_info_show(struct seq_file *seq, void *v)
1723 {
1724 	struct ext4_sb_info *sbi = EXT4_SB((struct super_block *) seq->private);
1725 	struct ext4_es_stats *es_stats = &sbi->s_es_stats;
1726 	struct ext4_inode_info *ei, *max = NULL;
1727 	unsigned int inode_cnt = 0;
1728 
1729 	if (v != SEQ_START_TOKEN)
1730 		return 0;
1731 
1732 	/* here we just find an inode that has the max nr. of objects */
1733 	spin_lock(&sbi->s_es_lock);
1734 	list_for_each_entry(ei, &sbi->s_es_list, i_es_list) {
1735 		inode_cnt++;
1736 		if (max && max->i_es_all_nr < ei->i_es_all_nr)
1737 			max = ei;
1738 		else if (!max)
1739 			max = ei;
1740 	}
1741 	spin_unlock(&sbi->s_es_lock);
1742 
1743 	seq_printf(seq, "stats:\n  %lld objects\n  %lld reclaimable objects\n",
1744 		   percpu_counter_sum_positive(&es_stats->es_stats_all_cnt),
1745 		   percpu_counter_sum_positive(&es_stats->es_stats_shk_cnt));
1746 	seq_printf(seq, "  %lld/%lld cache hits/misses\n",
1747 		   percpu_counter_sum_positive(&es_stats->es_stats_cache_hits),
1748 		   percpu_counter_sum_positive(&es_stats->es_stats_cache_misses));
1749 	if (inode_cnt)
1750 		seq_printf(seq, "  %d inodes on list\n", inode_cnt);
1751 
1752 	seq_printf(seq, "average:\n  %llu us scan time\n",
1753 	    div_u64(es_stats->es_stats_scan_time, 1000));
1754 	seq_printf(seq, "  %lu shrunk objects\n", es_stats->es_stats_shrunk);
1755 	if (inode_cnt)
1756 		seq_printf(seq,
1757 		    "maximum:\n  %lu inode (%u objects, %u reclaimable)\n"
1758 		    "  %llu us max scan time\n",
1759 		    max->vfs_inode.i_ino, max->i_es_all_nr, max->i_es_shk_nr,
1760 		    div_u64(es_stats->es_stats_max_scan_time, 1000));
1761 
1762 	return 0;
1763 }
1764 
1765 int ext4_es_register_shrinker(struct ext4_sb_info *sbi)
1766 {
1767 	int err;
1768 
1769 	/* Make sure we have enough bits for physical block number */
1770 	BUILD_BUG_ON(ES_SHIFT < 48);
1771 	INIT_LIST_HEAD(&sbi->s_es_list);
1772 	sbi->s_es_nr_inode = 0;
1773 	spin_lock_init(&sbi->s_es_lock);
1774 	sbi->s_es_stats.es_stats_shrunk = 0;
1775 	err = percpu_counter_init(&sbi->s_es_stats.es_stats_cache_hits, 0,
1776 				  GFP_KERNEL);
1777 	if (err)
1778 		return err;
1779 	err = percpu_counter_init(&sbi->s_es_stats.es_stats_cache_misses, 0,
1780 				  GFP_KERNEL);
1781 	if (err)
1782 		goto err1;
1783 	sbi->s_es_stats.es_stats_scan_time = 0;
1784 	sbi->s_es_stats.es_stats_max_scan_time = 0;
1785 	err = percpu_counter_init(&sbi->s_es_stats.es_stats_all_cnt, 0, GFP_KERNEL);
1786 	if (err)
1787 		goto err2;
1788 	err = percpu_counter_init(&sbi->s_es_stats.es_stats_shk_cnt, 0, GFP_KERNEL);
1789 	if (err)
1790 		goto err3;
1791 
1792 	sbi->s_es_shrinker = shrinker_alloc(0, "ext4-es:%s", sbi->s_sb->s_id);
1793 	if (!sbi->s_es_shrinker) {
1794 		err = -ENOMEM;
1795 		goto err4;
1796 	}
1797 
1798 	sbi->s_es_shrinker->scan_objects = ext4_es_scan;
1799 	sbi->s_es_shrinker->count_objects = ext4_es_count;
1800 	sbi->s_es_shrinker->private_data = sbi;
1801 
1802 	shrinker_register(sbi->s_es_shrinker);
1803 
1804 	return 0;
1805 err4:
1806 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_shk_cnt);
1807 err3:
1808 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_all_cnt);
1809 err2:
1810 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_misses);
1811 err1:
1812 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_hits);
1813 	return err;
1814 }
1815 
1816 void ext4_es_unregister_shrinker(struct ext4_sb_info *sbi)
1817 {
1818 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_hits);
1819 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_misses);
1820 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_all_cnt);
1821 	percpu_counter_destroy(&sbi->s_es_stats.es_stats_shk_cnt);
1822 	shrinker_free(sbi->s_es_shrinker);
1823 }
1824 
1825 /*
1826  * Shrink extents in given inode from ei->i_es_shrink_lblk till end. Scan at
1827  * most *nr_to_scan extents, update *nr_to_scan accordingly.
1828  *
1829  * Return 0 if we hit end of tree / interval, 1 if we exhausted nr_to_scan.
1830  * Increment *nr_shrunk by the number of reclaimed extents. Also update
1831  * ei->i_es_shrink_lblk to where we should continue scanning.
1832  */
1833 static int es_do_reclaim_extents(struct ext4_inode_info *ei, ext4_lblk_t end,
1834 				 int *nr_to_scan, int *nr_shrunk)
1835 {
1836 	struct inode *inode = &ei->vfs_inode;
1837 	struct ext4_es_tree *tree = &ei->i_es_tree;
1838 	struct extent_status *es;
1839 	struct rb_node *node;
1840 
1841 	es = __es_tree_search(&tree->root, ei->i_es_shrink_lblk);
1842 	if (!es)
1843 		goto out_wrap;
1844 
1845 	while (*nr_to_scan > 0) {
1846 		if (es->es_lblk > end) {
1847 			ei->i_es_shrink_lblk = end + 1;
1848 			return 0;
1849 		}
1850 
1851 		(*nr_to_scan)--;
1852 		node = rb_next(&es->rb_node);
1853 
1854 		if (ext4_es_must_keep(es))
1855 			goto next;
1856 		if (ext4_es_is_referenced(es)) {
1857 			ext4_es_clear_referenced(es);
1858 			goto next;
1859 		}
1860 
1861 		rb_erase(&es->rb_node, &tree->root);
1862 		ext4_es_free_extent(inode, es);
1863 		(*nr_shrunk)++;
1864 next:
1865 		if (!node)
1866 			goto out_wrap;
1867 		es = rb_entry(node, struct extent_status, rb_node);
1868 	}
1869 	ei->i_es_shrink_lblk = es->es_lblk;
1870 	return 1;
1871 out_wrap:
1872 	ei->i_es_shrink_lblk = 0;
1873 	return 0;
1874 }
1875 
1876 static int es_reclaim_extents(struct ext4_inode_info *ei, int *nr_to_scan)
1877 {
1878 	struct inode *inode = &ei->vfs_inode;
1879 	int nr_shrunk = 0;
1880 	ext4_lblk_t start = ei->i_es_shrink_lblk;
1881 	static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
1882 				      DEFAULT_RATELIMIT_BURST);
1883 
1884 	if (ei->i_es_shk_nr == 0)
1885 		return 0;
1886 
1887 	if (ext4_test_inode_state(inode, EXT4_STATE_EXT_PRECACHED) &&
1888 	    __ratelimit(&_rs))
1889 		ext4_warning(inode->i_sb, "forced shrink of precached extents");
1890 
1891 	if (!es_do_reclaim_extents(ei, EXT_MAX_BLOCKS, nr_to_scan, &nr_shrunk) &&
1892 	    start != 0)
1893 		es_do_reclaim_extents(ei, start - 1, nr_to_scan, &nr_shrunk);
1894 
1895 	ei->i_es_tree.cache_es = NULL;
1896 	return nr_shrunk;
1897 }
1898 
1899 /*
1900  * Called to support EXT4_IOC_CLEAR_ES_CACHE.  We can only remove
1901  * discretionary entries from the extent status cache.  (Some entries
1902  * must be present for proper operations.)
1903  */
1904 void ext4_clear_inode_es(struct inode *inode)
1905 {
1906 	struct ext4_inode_info *ei = EXT4_I(inode);
1907 	struct extent_status *es;
1908 	struct ext4_es_tree *tree;
1909 	struct rb_node *node;
1910 
1911 	write_lock(&ei->i_es_lock);
1912 	tree = &EXT4_I(inode)->i_es_tree;
1913 	tree->cache_es = NULL;
1914 	node = rb_first(&tree->root);
1915 	while (node) {
1916 		es = rb_entry(node, struct extent_status, rb_node);
1917 		node = rb_next(node);
1918 		if (!ext4_es_must_keep(es)) {
1919 			rb_erase(&es->rb_node, &tree->root);
1920 			ext4_es_free_extent(inode, es);
1921 		}
1922 	}
1923 	ext4_clear_inode_state(inode, EXT4_STATE_EXT_PRECACHED);
1924 	write_unlock(&ei->i_es_lock);
1925 }
1926 
1927 #ifdef ES_DEBUG__
1928 static void ext4_print_pending_tree(struct inode *inode)
1929 {
1930 	struct ext4_pending_tree *tree;
1931 	struct rb_node *node;
1932 	struct pending_reservation *pr;
1933 
1934 	printk(KERN_DEBUG "pending reservations for inode %lu:", inode->i_ino);
1935 	tree = &EXT4_I(inode)->i_pending_tree;
1936 	node = rb_first(&tree->root);
1937 	while (node) {
1938 		pr = rb_entry(node, struct pending_reservation, rb_node);
1939 		printk(KERN_DEBUG " %u", pr->lclu);
1940 		node = rb_next(node);
1941 	}
1942 	printk(KERN_DEBUG "\n");
1943 }
1944 #else
1945 #define ext4_print_pending_tree(inode)
1946 #endif
1947 
1948 int __init ext4_init_pending(void)
1949 {
1950 	ext4_pending_cachep = KMEM_CACHE(pending_reservation, SLAB_RECLAIM_ACCOUNT);
1951 	if (ext4_pending_cachep == NULL)
1952 		return -ENOMEM;
1953 	return 0;
1954 }
1955 
1956 void ext4_exit_pending(void)
1957 {
1958 	kmem_cache_destroy(ext4_pending_cachep);
1959 }
1960 
1961 void ext4_init_pending_tree(struct ext4_pending_tree *tree)
1962 {
1963 	tree->root = RB_ROOT;
1964 }
1965 
1966 /*
1967  * __get_pending - retrieve a pointer to a pending reservation
1968  *
1969  * @inode - file containing the pending cluster reservation
1970  * @lclu - logical cluster of interest
1971  *
1972  * Returns a pointer to a pending reservation if it's a member of
1973  * the set, and NULL if not.  Must be called holding i_es_lock.
1974  */
1975 static struct pending_reservation *__get_pending(struct inode *inode,
1976 						 ext4_lblk_t lclu)
1977 {
1978 	struct ext4_pending_tree *tree;
1979 	struct rb_node *node;
1980 	struct pending_reservation *pr = NULL;
1981 
1982 	tree = &EXT4_I(inode)->i_pending_tree;
1983 	node = (&tree->root)->rb_node;
1984 
1985 	while (node) {
1986 		pr = rb_entry(node, struct pending_reservation, rb_node);
1987 		if (lclu < pr->lclu)
1988 			node = node->rb_left;
1989 		else if (lclu > pr->lclu)
1990 			node = node->rb_right;
1991 		else if (lclu == pr->lclu)
1992 			return pr;
1993 	}
1994 	return NULL;
1995 }
1996 
1997 /*
1998  * __insert_pending - adds a pending cluster reservation to the set of
1999  *                    pending reservations
2000  *
2001  * @inode - file containing the cluster
2002  * @lblk - logical block in the cluster to be added
2003  * @prealloc - preallocated pending entry
2004  *
2005  * Returns 1 on successful insertion and -ENOMEM on failure.  If the
2006  * pending reservation is already in the set, returns successfully.
2007  */
2008 static int __insert_pending(struct inode *inode, ext4_lblk_t lblk,
2009 			    struct pending_reservation **prealloc)
2010 {
2011 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2012 	struct ext4_pending_tree *tree = &EXT4_I(inode)->i_pending_tree;
2013 	struct rb_node **p = &tree->root.rb_node;
2014 	struct rb_node *parent = NULL;
2015 	struct pending_reservation *pr;
2016 	ext4_lblk_t lclu;
2017 	int ret = 0;
2018 
2019 	lclu = EXT4_B2C(sbi, lblk);
2020 	/* search to find parent for insertion */
2021 	while (*p) {
2022 		parent = *p;
2023 		pr = rb_entry(parent, struct pending_reservation, rb_node);
2024 
2025 		if (lclu < pr->lclu) {
2026 			p = &(*p)->rb_left;
2027 		} else if (lclu > pr->lclu) {
2028 			p = &(*p)->rb_right;
2029 		} else {
2030 			/* pending reservation already inserted */
2031 			goto out;
2032 		}
2033 	}
2034 
2035 	if (likely(*prealloc == NULL)) {
2036 		pr = __alloc_pending(false);
2037 		if (!pr) {
2038 			ret = -ENOMEM;
2039 			goto out;
2040 		}
2041 	} else {
2042 		pr = *prealloc;
2043 		*prealloc = NULL;
2044 	}
2045 	pr->lclu = lclu;
2046 
2047 	rb_link_node(&pr->rb_node, parent, p);
2048 	rb_insert_color(&pr->rb_node, &tree->root);
2049 	ret = 1;
2050 
2051 out:
2052 	return ret;
2053 }
2054 
2055 /*
2056  * __remove_pending - removes a pending cluster reservation from the set
2057  *                    of pending reservations
2058  *
2059  * @inode - file containing the cluster
2060  * @lblk - logical block in the pending cluster reservation to be removed
2061  *
2062  * Returns successfully if pending reservation is not a member of the set.
2063  */
2064 static void __remove_pending(struct inode *inode, ext4_lblk_t lblk)
2065 {
2066 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2067 	struct pending_reservation *pr;
2068 	struct ext4_pending_tree *tree;
2069 
2070 	pr = __get_pending(inode, EXT4_B2C(sbi, lblk));
2071 	if (pr != NULL) {
2072 		tree = &EXT4_I(inode)->i_pending_tree;
2073 		rb_erase(&pr->rb_node, &tree->root);
2074 		__free_pending(pr);
2075 	}
2076 }
2077 
2078 /*
2079  * ext4_remove_pending - removes a pending cluster reservation from the set
2080  *                       of pending reservations
2081  *
2082  * @inode - file containing the cluster
2083  * @lblk - logical block in the pending cluster reservation to be removed
2084  *
2085  * Locking for external use of __remove_pending.
2086  */
2087 void ext4_remove_pending(struct inode *inode, ext4_lblk_t lblk)
2088 {
2089 	struct ext4_inode_info *ei = EXT4_I(inode);
2090 
2091 	write_lock(&ei->i_es_lock);
2092 	__remove_pending(inode, lblk);
2093 	write_unlock(&ei->i_es_lock);
2094 }
2095 
2096 /*
2097  * ext4_is_pending - determine whether a cluster has a pending reservation
2098  *                   on it
2099  *
2100  * @inode - file containing the cluster
2101  * @lblk - logical block in the cluster
2102  *
2103  * Returns true if there's a pending reservation for the cluster in the
2104  * set of pending reservations, and false if not.
2105  */
2106 bool ext4_is_pending(struct inode *inode, ext4_lblk_t lblk)
2107 {
2108 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2109 	struct ext4_inode_info *ei = EXT4_I(inode);
2110 	bool ret;
2111 
2112 	read_lock(&ei->i_es_lock);
2113 	ret = (bool)(__get_pending(inode, EXT4_B2C(sbi, lblk)) != NULL);
2114 	read_unlock(&ei->i_es_lock);
2115 
2116 	return ret;
2117 }
2118 
2119 /*
2120  * ext4_es_insert_delayed_extent - adds some delayed blocks to the extents
2121  *                                 status tree, adding a pending reservation
2122  *                                 where needed
2123  *
2124  * @inode - file containing the newly added block
2125  * @lblk - start logical block to be added
2126  * @len - length of blocks to be added
2127  * @lclu_allocated/end_allocated - indicates whether a physical cluster has
2128  *                                 been allocated for the logical cluster
2129  *                                 that contains the start/end block. Note that
2130  *                                 end_allocated should always be set to false
2131  *                                 if the start and the end block are in the
2132  *                                 same cluster
2133  */
2134 void ext4_es_insert_delayed_extent(struct inode *inode, ext4_lblk_t lblk,
2135 				   ext4_lblk_t len, bool lclu_allocated,
2136 				   bool end_allocated)
2137 {
2138 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2139 	struct extent_status newes;
2140 	ext4_lblk_t end = lblk + len - 1;
2141 	int err1 = 0, err2 = 0, err3 = 0;
2142 	struct extent_status *es1 = NULL;
2143 	struct extent_status *es2 = NULL;
2144 	struct pending_reservation *pr1 = NULL;
2145 	struct pending_reservation *pr2 = NULL;
2146 
2147 	if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
2148 		return;
2149 
2150 	es_debug("add [%u/%u) delayed to extent status tree of inode %lu\n",
2151 		 lblk, len, inode->i_ino);
2152 	if (!len)
2153 		return;
2154 
2155 	WARN_ON_ONCE((EXT4_B2C(sbi, lblk) == EXT4_B2C(sbi, end)) &&
2156 		     end_allocated);
2157 
2158 	newes.es_lblk = lblk;
2159 	newes.es_len = len;
2160 	ext4_es_store_pblock_status(&newes, ~0, EXTENT_STATUS_DELAYED);
2161 
2162 	ext4_es_insert_extent_check(inode, &newes);
2163 
2164 retry:
2165 	if (err1 && !es1)
2166 		es1 = __es_alloc_extent(true);
2167 	if ((err1 || err2) && !es2)
2168 		es2 = __es_alloc_extent(true);
2169 	if (err1 || err2 || err3 < 0) {
2170 		if (lclu_allocated && !pr1)
2171 			pr1 = __alloc_pending(true);
2172 		if (end_allocated && !pr2)
2173 			pr2 = __alloc_pending(true);
2174 	}
2175 	write_lock(&EXT4_I(inode)->i_es_lock);
2176 
2177 	err1 = __es_remove_extent(inode, lblk, end, NULL, es1);
2178 	if (err1 != 0)
2179 		goto error;
2180 	/* Free preallocated extent if it didn't get used. */
2181 	if (es1) {
2182 		if (!es1->es_len)
2183 			__es_free_extent(es1);
2184 		es1 = NULL;
2185 	}
2186 
2187 	err2 = __es_insert_extent(inode, &newes, es2);
2188 	if (err2 != 0)
2189 		goto error;
2190 	/* Free preallocated extent if it didn't get used. */
2191 	if (es2) {
2192 		if (!es2->es_len)
2193 			__es_free_extent(es2);
2194 		es2 = NULL;
2195 	}
2196 
2197 	if (lclu_allocated) {
2198 		err3 = __insert_pending(inode, lblk, &pr1);
2199 		if (err3 < 0)
2200 			goto error;
2201 		if (pr1) {
2202 			__free_pending(pr1);
2203 			pr1 = NULL;
2204 		}
2205 	}
2206 	if (end_allocated) {
2207 		err3 = __insert_pending(inode, end, &pr2);
2208 		if (err3 < 0)
2209 			goto error;
2210 		if (pr2) {
2211 			__free_pending(pr2);
2212 			pr2 = NULL;
2213 		}
2214 	}
2215 	ext4_es_inc_seq(inode);
2216 error:
2217 	write_unlock(&EXT4_I(inode)->i_es_lock);
2218 	if (err1 || err2 || err3 < 0)
2219 		goto retry;
2220 
2221 	trace_ext4_es_insert_delayed_extent(inode, &newes, lclu_allocated,
2222 					    end_allocated);
2223 	ext4_es_print_tree(inode);
2224 	ext4_print_pending_tree(inode);
2225 	return;
2226 }
2227 
2228 /*
2229  * __revise_pending - makes, cancels, or leaves unchanged pending cluster
2230  *                    reservations for a specified block range depending
2231  *                    upon the presence or absence of delayed blocks
2232  *                    outside the range within clusters at the ends of the
2233  *                    range
2234  *
2235  * @inode - file containing the range
2236  * @lblk - logical block defining the start of range
2237  * @len  - length of range in blocks
2238  * @prealloc - preallocated pending entry
2239  *
2240  * Used after a newly allocated extent is added to the extents status tree.
2241  * Requires that the extents in the range have either written or unwritten
2242  * status.  Must be called while holding i_es_lock. Returns number of new
2243  * inserts pending cluster on insert pendings, returns 0 on remove pendings,
2244  * return -ENOMEM on failure.
2245  */
2246 static int __revise_pending(struct inode *inode, ext4_lblk_t lblk,
2247 			    ext4_lblk_t len,
2248 			    struct pending_reservation **prealloc)
2249 {
2250 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2251 	ext4_lblk_t end = lblk + len - 1;
2252 	ext4_lblk_t first, last;
2253 	bool f_del = false, l_del = false;
2254 	int pendings = 0;
2255 	int ret = 0;
2256 
2257 	if (len == 0)
2258 		return 0;
2259 
2260 	/*
2261 	 * Two cases - block range within single cluster and block range
2262 	 * spanning two or more clusters.  Note that a cluster belonging
2263 	 * to a range starting and/or ending on a cluster boundary is treated
2264 	 * as if it does not contain a delayed extent.  The new range may
2265 	 * have allocated space for previously delayed blocks out to the
2266 	 * cluster boundary, requiring that any pre-existing pending
2267 	 * reservation be canceled.  Because this code only looks at blocks
2268 	 * outside the range, it should revise pending reservations
2269 	 * correctly even if the extent represented by the range can't be
2270 	 * inserted in the extents status tree due to ENOSPC.
2271 	 */
2272 
2273 	if (EXT4_B2C(sbi, lblk) == EXT4_B2C(sbi, end)) {
2274 		first = EXT4_LBLK_CMASK(sbi, lblk);
2275 		if (first != lblk)
2276 			f_del = __es_scan_range(inode, &ext4_es_is_delayed,
2277 						first, lblk - 1);
2278 		if (f_del) {
2279 			ret = __insert_pending(inode, first, prealloc);
2280 			if (ret < 0)
2281 				goto out;
2282 			pendings += ret;
2283 		} else {
2284 			last = EXT4_LBLK_CMASK(sbi, end) +
2285 			       sbi->s_cluster_ratio - 1;
2286 			if (last != end)
2287 				l_del = __es_scan_range(inode,
2288 							&ext4_es_is_delayed,
2289 							end + 1, last);
2290 			if (l_del) {
2291 				ret = __insert_pending(inode, last, prealloc);
2292 				if (ret < 0)
2293 					goto out;
2294 				pendings += ret;
2295 			} else
2296 				__remove_pending(inode, last);
2297 		}
2298 	} else {
2299 		first = EXT4_LBLK_CMASK(sbi, lblk);
2300 		if (first != lblk)
2301 			f_del = __es_scan_range(inode, &ext4_es_is_delayed,
2302 						first, lblk - 1);
2303 		if (f_del) {
2304 			ret = __insert_pending(inode, first, prealloc);
2305 			if (ret < 0)
2306 				goto out;
2307 			pendings += ret;
2308 		} else
2309 			__remove_pending(inode, first);
2310 
2311 		last = EXT4_LBLK_CMASK(sbi, end) + sbi->s_cluster_ratio - 1;
2312 		if (last != end)
2313 			l_del = __es_scan_range(inode, &ext4_es_is_delayed,
2314 						end + 1, last);
2315 		if (l_del) {
2316 			ret = __insert_pending(inode, last, prealloc);
2317 			if (ret < 0)
2318 				goto out;
2319 			pendings += ret;
2320 		} else
2321 			__remove_pending(inode, last);
2322 	}
2323 out:
2324 	return (ret < 0) ? ret : pendings;
2325 }
2326