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