KVM: emulator: emulate SALC
[firefly-linux-kernel-4.4.55.git] / fs / btrfs / file.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/fs.h>
20 #include <linux/pagemap.h>
21 #include <linux/highmem.h>
22 #include <linux/time.h>
23 #include <linux/init.h>
24 #include <linux/string.h>
25 #include <linux/backing-dev.h>
26 #include <linux/mpage.h>
27 #include <linux/aio.h>
28 #include <linux/falloc.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
31 #include <linux/statfs.h>
32 #include <linux/compat.h>
33 #include <linux/slab.h>
34 #include <linux/btrfs.h>
35 #include "ctree.h"
36 #include "disk-io.h"
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
40 #include "tree-log.h"
41 #include "locking.h"
42 #include "compat.h"
43 #include "volumes.h"
44
45 static struct kmem_cache *btrfs_inode_defrag_cachep;
46 /*
47  * when auto defrag is enabled we
48  * queue up these defrag structs to remember which
49  * inodes need defragging passes
50  */
51 struct inode_defrag {
52         struct rb_node rb_node;
53         /* objectid */
54         u64 ino;
55         /*
56          * transid where the defrag was added, we search for
57          * extents newer than this
58          */
59         u64 transid;
60
61         /* root objectid */
62         u64 root;
63
64         /* last offset we were able to defrag */
65         u64 last_offset;
66
67         /* if we've wrapped around back to zero once already */
68         int cycled;
69 };
70
71 static int __compare_inode_defrag(struct inode_defrag *defrag1,
72                                   struct inode_defrag *defrag2)
73 {
74         if (defrag1->root > defrag2->root)
75                 return 1;
76         else if (defrag1->root < defrag2->root)
77                 return -1;
78         else if (defrag1->ino > defrag2->ino)
79                 return 1;
80         else if (defrag1->ino < defrag2->ino)
81                 return -1;
82         else
83                 return 0;
84 }
85
86 /* pop a record for an inode into the defrag tree.  The lock
87  * must be held already
88  *
89  * If you're inserting a record for an older transid than an
90  * existing record, the transid already in the tree is lowered
91  *
92  * If an existing record is found the defrag item you
93  * pass in is freed
94  */
95 static int __btrfs_add_inode_defrag(struct inode *inode,
96                                     struct inode_defrag *defrag)
97 {
98         struct btrfs_root *root = BTRFS_I(inode)->root;
99         struct inode_defrag *entry;
100         struct rb_node **p;
101         struct rb_node *parent = NULL;
102         int ret;
103
104         p = &root->fs_info->defrag_inodes.rb_node;
105         while (*p) {
106                 parent = *p;
107                 entry = rb_entry(parent, struct inode_defrag, rb_node);
108
109                 ret = __compare_inode_defrag(defrag, entry);
110                 if (ret < 0)
111                         p = &parent->rb_left;
112                 else if (ret > 0)
113                         p = &parent->rb_right;
114                 else {
115                         /* if we're reinserting an entry for
116                          * an old defrag run, make sure to
117                          * lower the transid of our existing record
118                          */
119                         if (defrag->transid < entry->transid)
120                                 entry->transid = defrag->transid;
121                         if (defrag->last_offset > entry->last_offset)
122                                 entry->last_offset = defrag->last_offset;
123                         return -EEXIST;
124                 }
125         }
126         set_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
127         rb_link_node(&defrag->rb_node, parent, p);
128         rb_insert_color(&defrag->rb_node, &root->fs_info->defrag_inodes);
129         return 0;
130 }
131
132 static inline int __need_auto_defrag(struct btrfs_root *root)
133 {
134         if (!btrfs_test_opt(root, AUTO_DEFRAG))
135                 return 0;
136
137         if (btrfs_fs_closing(root->fs_info))
138                 return 0;
139
140         return 1;
141 }
142
143 /*
144  * insert a defrag record for this inode if auto defrag is
145  * enabled
146  */
147 int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
148                            struct inode *inode)
149 {
150         struct btrfs_root *root = BTRFS_I(inode)->root;
151         struct inode_defrag *defrag;
152         u64 transid;
153         int ret;
154
155         if (!__need_auto_defrag(root))
156                 return 0;
157
158         if (test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags))
159                 return 0;
160
161         if (trans)
162                 transid = trans->transid;
163         else
164                 transid = BTRFS_I(inode)->root->last_trans;
165
166         defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
167         if (!defrag)
168                 return -ENOMEM;
169
170         defrag->ino = btrfs_ino(inode);
171         defrag->transid = transid;
172         defrag->root = root->root_key.objectid;
173
174         spin_lock(&root->fs_info->defrag_inodes_lock);
175         if (!test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags)) {
176                 /*
177                  * If we set IN_DEFRAG flag and evict the inode from memory,
178                  * and then re-read this inode, this new inode doesn't have
179                  * IN_DEFRAG flag. At the case, we may find the existed defrag.
180                  */
181                 ret = __btrfs_add_inode_defrag(inode, defrag);
182                 if (ret)
183                         kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
184         } else {
185                 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
186         }
187         spin_unlock(&root->fs_info->defrag_inodes_lock);
188         return 0;
189 }
190
191 /*
192  * Requeue the defrag object. If there is a defrag object that points to
193  * the same inode in the tree, we will merge them together (by
194  * __btrfs_add_inode_defrag()) and free the one that we want to requeue.
195  */
196 void btrfs_requeue_inode_defrag(struct inode *inode,
197                                 struct inode_defrag *defrag)
198 {
199         struct btrfs_root *root = BTRFS_I(inode)->root;
200         int ret;
201
202         if (!__need_auto_defrag(root))
203                 goto out;
204
205         /*
206          * Here we don't check the IN_DEFRAG flag, because we need merge
207          * them together.
208          */
209         spin_lock(&root->fs_info->defrag_inodes_lock);
210         ret = __btrfs_add_inode_defrag(inode, defrag);
211         spin_unlock(&root->fs_info->defrag_inodes_lock);
212         if (ret)
213                 goto out;
214         return;
215 out:
216         kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
217 }
218
219 /*
220  * pick the defragable inode that we want, if it doesn't exist, we will get
221  * the next one.
222  */
223 static struct inode_defrag *
224 btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
225 {
226         struct inode_defrag *entry = NULL;
227         struct inode_defrag tmp;
228         struct rb_node *p;
229         struct rb_node *parent = NULL;
230         int ret;
231
232         tmp.ino = ino;
233         tmp.root = root;
234
235         spin_lock(&fs_info->defrag_inodes_lock);
236         p = fs_info->defrag_inodes.rb_node;
237         while (p) {
238                 parent = p;
239                 entry = rb_entry(parent, struct inode_defrag, rb_node);
240
241                 ret = __compare_inode_defrag(&tmp, entry);
242                 if (ret < 0)
243                         p = parent->rb_left;
244                 else if (ret > 0)
245                         p = parent->rb_right;
246                 else
247                         goto out;
248         }
249
250         if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
251                 parent = rb_next(parent);
252                 if (parent)
253                         entry = rb_entry(parent, struct inode_defrag, rb_node);
254                 else
255                         entry = NULL;
256         }
257 out:
258         if (entry)
259                 rb_erase(parent, &fs_info->defrag_inodes);
260         spin_unlock(&fs_info->defrag_inodes_lock);
261         return entry;
262 }
263
264 void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
265 {
266         struct inode_defrag *defrag;
267         struct rb_node *node;
268
269         spin_lock(&fs_info->defrag_inodes_lock);
270         node = rb_first(&fs_info->defrag_inodes);
271         while (node) {
272                 rb_erase(node, &fs_info->defrag_inodes);
273                 defrag = rb_entry(node, struct inode_defrag, rb_node);
274                 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
275
276                 if (need_resched()) {
277                         spin_unlock(&fs_info->defrag_inodes_lock);
278                         cond_resched();
279                         spin_lock(&fs_info->defrag_inodes_lock);
280                 }
281
282                 node = rb_first(&fs_info->defrag_inodes);
283         }
284         spin_unlock(&fs_info->defrag_inodes_lock);
285 }
286
287 #define BTRFS_DEFRAG_BATCH      1024
288
289 static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
290                                     struct inode_defrag *defrag)
291 {
292         struct btrfs_root *inode_root;
293         struct inode *inode;
294         struct btrfs_key key;
295         struct btrfs_ioctl_defrag_range_args range;
296         int num_defrag;
297         int index;
298         int ret;
299
300         /* get the inode */
301         key.objectid = defrag->root;
302         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
303         key.offset = (u64)-1;
304
305         index = srcu_read_lock(&fs_info->subvol_srcu);
306
307         inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
308         if (IS_ERR(inode_root)) {
309                 ret = PTR_ERR(inode_root);
310                 goto cleanup;
311         }
312         if (btrfs_root_refs(&inode_root->root_item) == 0) {
313                 ret = -ENOENT;
314                 goto cleanup;
315         }
316
317         key.objectid = defrag->ino;
318         btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
319         key.offset = 0;
320         inode = btrfs_iget(fs_info->sb, &key, inode_root, NULL);
321         if (IS_ERR(inode)) {
322                 ret = PTR_ERR(inode);
323                 goto cleanup;
324         }
325         srcu_read_unlock(&fs_info->subvol_srcu, index);
326
327         /* do a chunk of defrag */
328         clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
329         memset(&range, 0, sizeof(range));
330         range.len = (u64)-1;
331         range.start = defrag->last_offset;
332
333         sb_start_write(fs_info->sb);
334         num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
335                                        BTRFS_DEFRAG_BATCH);
336         sb_end_write(fs_info->sb);
337         /*
338          * if we filled the whole defrag batch, there
339          * must be more work to do.  Queue this defrag
340          * again
341          */
342         if (num_defrag == BTRFS_DEFRAG_BATCH) {
343                 defrag->last_offset = range.start;
344                 btrfs_requeue_inode_defrag(inode, defrag);
345         } else if (defrag->last_offset && !defrag->cycled) {
346                 /*
347                  * we didn't fill our defrag batch, but
348                  * we didn't start at zero.  Make sure we loop
349                  * around to the start of the file.
350                  */
351                 defrag->last_offset = 0;
352                 defrag->cycled = 1;
353                 btrfs_requeue_inode_defrag(inode, defrag);
354         } else {
355                 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
356         }
357
358         iput(inode);
359         return 0;
360 cleanup:
361         srcu_read_unlock(&fs_info->subvol_srcu, index);
362         kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
363         return ret;
364 }
365
366 /*
367  * run through the list of inodes in the FS that need
368  * defragging
369  */
370 int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
371 {
372         struct inode_defrag *defrag;
373         u64 first_ino = 0;
374         u64 root_objectid = 0;
375
376         atomic_inc(&fs_info->defrag_running);
377         while(1) {
378                 /* Pause the auto defragger. */
379                 if (test_bit(BTRFS_FS_STATE_REMOUNTING,
380                              &fs_info->fs_state))
381                         break;
382
383                 if (!__need_auto_defrag(fs_info->tree_root))
384                         break;
385
386                 /* find an inode to defrag */
387                 defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
388                                                  first_ino);
389                 if (!defrag) {
390                         if (root_objectid || first_ino) {
391                                 root_objectid = 0;
392                                 first_ino = 0;
393                                 continue;
394                         } else {
395                                 break;
396                         }
397                 }
398
399                 first_ino = defrag->ino + 1;
400                 root_objectid = defrag->root;
401
402                 __btrfs_run_defrag_inode(fs_info, defrag);
403         }
404         atomic_dec(&fs_info->defrag_running);
405
406         /*
407          * during unmount, we use the transaction_wait queue to
408          * wait for the defragger to stop
409          */
410         wake_up(&fs_info->transaction_wait);
411         return 0;
412 }
413
414 /* simple helper to fault in pages and copy.  This should go away
415  * and be replaced with calls into generic code.
416  */
417 static noinline int btrfs_copy_from_user(loff_t pos, int num_pages,
418                                          size_t write_bytes,
419                                          struct page **prepared_pages,
420                                          struct iov_iter *i)
421 {
422         size_t copied = 0;
423         size_t total_copied = 0;
424         int pg = 0;
425         int offset = pos & (PAGE_CACHE_SIZE - 1);
426
427         while (write_bytes > 0) {
428                 size_t count = min_t(size_t,
429                                      PAGE_CACHE_SIZE - offset, write_bytes);
430                 struct page *page = prepared_pages[pg];
431                 /*
432                  * Copy data from userspace to the current page
433                  *
434                  * Disable pagefault to avoid recursive lock since
435                  * the pages are already locked
436                  */
437                 pagefault_disable();
438                 copied = iov_iter_copy_from_user_atomic(page, i, offset, count);
439                 pagefault_enable();
440
441                 /* Flush processor's dcache for this page */
442                 flush_dcache_page(page);
443
444                 /*
445                  * if we get a partial write, we can end up with
446                  * partially up to date pages.  These add
447                  * a lot of complexity, so make sure they don't
448                  * happen by forcing this copy to be retried.
449                  *
450                  * The rest of the btrfs_file_write code will fall
451                  * back to page at a time copies after we return 0.
452                  */
453                 if (!PageUptodate(page) && copied < count)
454                         copied = 0;
455
456                 iov_iter_advance(i, copied);
457                 write_bytes -= copied;
458                 total_copied += copied;
459
460                 /* Return to btrfs_file_aio_write to fault page */
461                 if (unlikely(copied == 0))
462                         break;
463
464                 if (unlikely(copied < PAGE_CACHE_SIZE - offset)) {
465                         offset += copied;
466                 } else {
467                         pg++;
468                         offset = 0;
469                 }
470         }
471         return total_copied;
472 }
473
474 /*
475  * unlocks pages after btrfs_file_write is done with them
476  */
477 void btrfs_drop_pages(struct page **pages, size_t num_pages)
478 {
479         size_t i;
480         for (i = 0; i < num_pages; i++) {
481                 /* page checked is some magic around finding pages that
482                  * have been modified without going through btrfs_set_page_dirty
483                  * clear it here
484                  */
485                 ClearPageChecked(pages[i]);
486                 unlock_page(pages[i]);
487                 mark_page_accessed(pages[i]);
488                 page_cache_release(pages[i]);
489         }
490 }
491
492 /*
493  * after copy_from_user, pages need to be dirtied and we need to make
494  * sure holes are created between the current EOF and the start of
495  * any next extents (if required).
496  *
497  * this also makes the decision about creating an inline extent vs
498  * doing real data extents, marking pages dirty and delalloc as required.
499  */
500 int btrfs_dirty_pages(struct btrfs_root *root, struct inode *inode,
501                       struct page **pages, size_t num_pages,
502                       loff_t pos, size_t write_bytes,
503                       struct extent_state **cached)
504 {
505         int err = 0;
506         int i;
507         u64 num_bytes;
508         u64 start_pos;
509         u64 end_of_last_block;
510         u64 end_pos = pos + write_bytes;
511         loff_t isize = i_size_read(inode);
512
513         start_pos = pos & ~((u64)root->sectorsize - 1);
514         num_bytes = ALIGN(write_bytes + pos - start_pos, root->sectorsize);
515
516         end_of_last_block = start_pos + num_bytes - 1;
517         err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
518                                         cached);
519         if (err)
520                 return err;
521
522         for (i = 0; i < num_pages; i++) {
523                 struct page *p = pages[i];
524                 SetPageUptodate(p);
525                 ClearPageChecked(p);
526                 set_page_dirty(p);
527         }
528
529         /*
530          * we've only changed i_size in ram, and we haven't updated
531          * the disk i_size.  There is no need to log the inode
532          * at this time.
533          */
534         if (end_pos > isize)
535                 i_size_write(inode, end_pos);
536         return 0;
537 }
538
539 /*
540  * this drops all the extents in the cache that intersect the range
541  * [start, end].  Existing extents are split as required.
542  */
543 void btrfs_drop_extent_cache(struct inode *inode, u64 start, u64 end,
544                              int skip_pinned)
545 {
546         struct extent_map *em;
547         struct extent_map *split = NULL;
548         struct extent_map *split2 = NULL;
549         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
550         u64 len = end - start + 1;
551         u64 gen;
552         int ret;
553         int testend = 1;
554         unsigned long flags;
555         int compressed = 0;
556
557         WARN_ON(end < start);
558         if (end == (u64)-1) {
559                 len = (u64)-1;
560                 testend = 0;
561         }
562         while (1) {
563                 int no_splits = 0;
564
565                 if (!split)
566                         split = alloc_extent_map();
567                 if (!split2)
568                         split2 = alloc_extent_map();
569                 if (!split || !split2)
570                         no_splits = 1;
571
572                 write_lock(&em_tree->lock);
573                 em = lookup_extent_mapping(em_tree, start, len);
574                 if (!em) {
575                         write_unlock(&em_tree->lock);
576                         break;
577                 }
578                 flags = em->flags;
579                 gen = em->generation;
580                 if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
581                         if (testend && em->start + em->len >= start + len) {
582                                 free_extent_map(em);
583                                 write_unlock(&em_tree->lock);
584                                 break;
585                         }
586                         start = em->start + em->len;
587                         if (testend)
588                                 len = start + len - (em->start + em->len);
589                         free_extent_map(em);
590                         write_unlock(&em_tree->lock);
591                         continue;
592                 }
593                 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
594                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
595                 clear_bit(EXTENT_FLAG_LOGGING, &flags);
596                 remove_extent_mapping(em_tree, em);
597                 if (no_splits)
598                         goto next;
599
600                 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
601                     em->start < start) {
602                         split->start = em->start;
603                         split->len = start - em->start;
604                         split->orig_start = em->orig_start;
605                         split->block_start = em->block_start;
606
607                         if (compressed)
608                                 split->block_len = em->block_len;
609                         else
610                                 split->block_len = split->len;
611                         split->orig_block_len = max(split->block_len,
612                                                     em->orig_block_len);
613                         split->generation = gen;
614                         split->bdev = em->bdev;
615                         split->flags = flags;
616                         split->compress_type = em->compress_type;
617                         ret = add_extent_mapping(em_tree, split);
618                         BUG_ON(ret); /* Logic error */
619                         list_move(&split->list, &em_tree->modified_extents);
620                         free_extent_map(split);
621                         split = split2;
622                         split2 = NULL;
623                 }
624                 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
625                     testend && em->start + em->len > start + len) {
626                         u64 diff = start + len - em->start;
627
628                         split->start = start + len;
629                         split->len = em->start + em->len - (start + len);
630                         split->bdev = em->bdev;
631                         split->flags = flags;
632                         split->compress_type = em->compress_type;
633                         split->generation = gen;
634                         split->orig_block_len = max(em->block_len,
635                                                     em->orig_block_len);
636
637                         if (compressed) {
638                                 split->block_len = em->block_len;
639                                 split->block_start = em->block_start;
640                                 split->orig_start = em->orig_start;
641                         } else {
642                                 split->block_len = split->len;
643                                 split->block_start = em->block_start + diff;
644                                 split->orig_start = em->orig_start;
645                         }
646
647                         ret = add_extent_mapping(em_tree, split);
648                         BUG_ON(ret); /* Logic error */
649                         list_move(&split->list, &em_tree->modified_extents);
650                         free_extent_map(split);
651                         split = NULL;
652                 }
653 next:
654                 write_unlock(&em_tree->lock);
655
656                 /* once for us */
657                 free_extent_map(em);
658                 /* once for the tree*/
659                 free_extent_map(em);
660         }
661         if (split)
662                 free_extent_map(split);
663         if (split2)
664                 free_extent_map(split2);
665 }
666
667 /*
668  * this is very complex, but the basic idea is to drop all extents
669  * in the range start - end.  hint_block is filled in with a block number
670  * that would be a good hint to the block allocator for this file.
671  *
672  * If an extent intersects the range but is not entirely inside the range
673  * it is either truncated or split.  Anything entirely inside the range
674  * is deleted from the tree.
675  */
676 int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
677                          struct btrfs_root *root, struct inode *inode,
678                          struct btrfs_path *path, u64 start, u64 end,
679                          u64 *drop_end, int drop_cache)
680 {
681         struct extent_buffer *leaf;
682         struct btrfs_file_extent_item *fi;
683         struct btrfs_key key;
684         struct btrfs_key new_key;
685         u64 ino = btrfs_ino(inode);
686         u64 search_start = start;
687         u64 disk_bytenr = 0;
688         u64 num_bytes = 0;
689         u64 extent_offset = 0;
690         u64 extent_end = 0;
691         int del_nr = 0;
692         int del_slot = 0;
693         int extent_type;
694         int recow;
695         int ret;
696         int modify_tree = -1;
697         int update_refs = (root->ref_cows || root == root->fs_info->tree_root);
698         int found = 0;
699
700         if (drop_cache)
701                 btrfs_drop_extent_cache(inode, start, end - 1, 0);
702
703         if (start >= BTRFS_I(inode)->disk_i_size)
704                 modify_tree = 0;
705
706         while (1) {
707                 recow = 0;
708                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
709                                                search_start, modify_tree);
710                 if (ret < 0)
711                         break;
712                 if (ret > 0 && path->slots[0] > 0 && search_start == start) {
713                         leaf = path->nodes[0];
714                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
715                         if (key.objectid == ino &&
716                             key.type == BTRFS_EXTENT_DATA_KEY)
717                                 path->slots[0]--;
718                 }
719                 ret = 0;
720 next_slot:
721                 leaf = path->nodes[0];
722                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
723                         BUG_ON(del_nr > 0);
724                         ret = btrfs_next_leaf(root, path);
725                         if (ret < 0)
726                                 break;
727                         if (ret > 0) {
728                                 ret = 0;
729                                 break;
730                         }
731                         leaf = path->nodes[0];
732                         recow = 1;
733                 }
734
735                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
736                 if (key.objectid > ino ||
737                     key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
738                         break;
739
740                 fi = btrfs_item_ptr(leaf, path->slots[0],
741                                     struct btrfs_file_extent_item);
742                 extent_type = btrfs_file_extent_type(leaf, fi);
743
744                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
745                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
746                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
747                         num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
748                         extent_offset = btrfs_file_extent_offset(leaf, fi);
749                         extent_end = key.offset +
750                                 btrfs_file_extent_num_bytes(leaf, fi);
751                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
752                         extent_end = key.offset +
753                                 btrfs_file_extent_inline_len(leaf, fi);
754                 } else {
755                         WARN_ON(1);
756                         extent_end = search_start;
757                 }
758
759                 if (extent_end <= search_start) {
760                         path->slots[0]++;
761                         goto next_slot;
762                 }
763
764                 found = 1;
765                 search_start = max(key.offset, start);
766                 if (recow || !modify_tree) {
767                         modify_tree = -1;
768                         btrfs_release_path(path);
769                         continue;
770                 }
771
772                 /*
773                  *     | - range to drop - |
774                  *  | -------- extent -------- |
775                  */
776                 if (start > key.offset && end < extent_end) {
777                         BUG_ON(del_nr > 0);
778                         BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
779
780                         memcpy(&new_key, &key, sizeof(new_key));
781                         new_key.offset = start;
782                         ret = btrfs_duplicate_item(trans, root, path,
783                                                    &new_key);
784                         if (ret == -EAGAIN) {
785                                 btrfs_release_path(path);
786                                 continue;
787                         }
788                         if (ret < 0)
789                                 break;
790
791                         leaf = path->nodes[0];
792                         fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
793                                             struct btrfs_file_extent_item);
794                         btrfs_set_file_extent_num_bytes(leaf, fi,
795                                                         start - key.offset);
796
797                         fi = btrfs_item_ptr(leaf, path->slots[0],
798                                             struct btrfs_file_extent_item);
799
800                         extent_offset += start - key.offset;
801                         btrfs_set_file_extent_offset(leaf, fi, extent_offset);
802                         btrfs_set_file_extent_num_bytes(leaf, fi,
803                                                         extent_end - start);
804                         btrfs_mark_buffer_dirty(leaf);
805
806                         if (update_refs && disk_bytenr > 0) {
807                                 ret = btrfs_inc_extent_ref(trans, root,
808                                                 disk_bytenr, num_bytes, 0,
809                                                 root->root_key.objectid,
810                                                 new_key.objectid,
811                                                 start - extent_offset, 0);
812                                 BUG_ON(ret); /* -ENOMEM */
813                         }
814                         key.offset = start;
815                 }
816                 /*
817                  *  | ---- range to drop ----- |
818                  *      | -------- extent -------- |
819                  */
820                 if (start <= key.offset && end < extent_end) {
821                         BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
822
823                         memcpy(&new_key, &key, sizeof(new_key));
824                         new_key.offset = end;
825                         btrfs_set_item_key_safe(trans, root, path, &new_key);
826
827                         extent_offset += end - key.offset;
828                         btrfs_set_file_extent_offset(leaf, fi, extent_offset);
829                         btrfs_set_file_extent_num_bytes(leaf, fi,
830                                                         extent_end - end);
831                         btrfs_mark_buffer_dirty(leaf);
832                         if (update_refs && disk_bytenr > 0)
833                                 inode_sub_bytes(inode, end - key.offset);
834                         break;
835                 }
836
837                 search_start = extent_end;
838                 /*
839                  *       | ---- range to drop ----- |
840                  *  | -------- extent -------- |
841                  */
842                 if (start > key.offset && end >= extent_end) {
843                         BUG_ON(del_nr > 0);
844                         BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
845
846                         btrfs_set_file_extent_num_bytes(leaf, fi,
847                                                         start - key.offset);
848                         btrfs_mark_buffer_dirty(leaf);
849                         if (update_refs && disk_bytenr > 0)
850                                 inode_sub_bytes(inode, extent_end - start);
851                         if (end == extent_end)
852                                 break;
853
854                         path->slots[0]++;
855                         goto next_slot;
856                 }
857
858                 /*
859                  *  | ---- range to drop ----- |
860                  *    | ------ extent ------ |
861                  */
862                 if (start <= key.offset && end >= extent_end) {
863                         if (del_nr == 0) {
864                                 del_slot = path->slots[0];
865                                 del_nr = 1;
866                         } else {
867                                 BUG_ON(del_slot + del_nr != path->slots[0]);
868                                 del_nr++;
869                         }
870
871                         if (update_refs &&
872                             extent_type == BTRFS_FILE_EXTENT_INLINE) {
873                                 inode_sub_bytes(inode,
874                                                 extent_end - key.offset);
875                                 extent_end = ALIGN(extent_end,
876                                                    root->sectorsize);
877                         } else if (update_refs && disk_bytenr > 0) {
878                                 ret = btrfs_free_extent(trans, root,
879                                                 disk_bytenr, num_bytes, 0,
880                                                 root->root_key.objectid,
881                                                 key.objectid, key.offset -
882                                                 extent_offset, 0);
883                                 BUG_ON(ret); /* -ENOMEM */
884                                 inode_sub_bytes(inode,
885                                                 extent_end - key.offset);
886                         }
887
888                         if (end == extent_end)
889                                 break;
890
891                         if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
892                                 path->slots[0]++;
893                                 goto next_slot;
894                         }
895
896                         ret = btrfs_del_items(trans, root, path, del_slot,
897                                               del_nr);
898                         if (ret) {
899                                 btrfs_abort_transaction(trans, root, ret);
900                                 break;
901                         }
902
903                         del_nr = 0;
904                         del_slot = 0;
905
906                         btrfs_release_path(path);
907                         continue;
908                 }
909
910                 BUG_ON(1);
911         }
912
913         if (!ret && del_nr > 0) {
914                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
915                 if (ret)
916                         btrfs_abort_transaction(trans, root, ret);
917         }
918
919         if (drop_end)
920                 *drop_end = found ? min(end, extent_end) : end;
921         btrfs_release_path(path);
922         return ret;
923 }
924
925 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
926                        struct btrfs_root *root, struct inode *inode, u64 start,
927                        u64 end, int drop_cache)
928 {
929         struct btrfs_path *path;
930         int ret;
931
932         path = btrfs_alloc_path();
933         if (!path)
934                 return -ENOMEM;
935         ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
936                                    drop_cache);
937         btrfs_free_path(path);
938         return ret;
939 }
940
941 static int extent_mergeable(struct extent_buffer *leaf, int slot,
942                             u64 objectid, u64 bytenr, u64 orig_offset,
943                             u64 *start, u64 *end)
944 {
945         struct btrfs_file_extent_item *fi;
946         struct btrfs_key key;
947         u64 extent_end;
948
949         if (slot < 0 || slot >= btrfs_header_nritems(leaf))
950                 return 0;
951
952         btrfs_item_key_to_cpu(leaf, &key, slot);
953         if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
954                 return 0;
955
956         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
957         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
958             btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
959             btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
960             btrfs_file_extent_compression(leaf, fi) ||
961             btrfs_file_extent_encryption(leaf, fi) ||
962             btrfs_file_extent_other_encoding(leaf, fi))
963                 return 0;
964
965         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
966         if ((*start && *start != key.offset) || (*end && *end != extent_end))
967                 return 0;
968
969         *start = key.offset;
970         *end = extent_end;
971         return 1;
972 }
973
974 /*
975  * Mark extent in the range start - end as written.
976  *
977  * This changes extent type from 'pre-allocated' to 'regular'. If only
978  * part of extent is marked as written, the extent will be split into
979  * two or three.
980  */
981 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
982                               struct inode *inode, u64 start, u64 end)
983 {
984         struct btrfs_root *root = BTRFS_I(inode)->root;
985         struct extent_buffer *leaf;
986         struct btrfs_path *path;
987         struct btrfs_file_extent_item *fi;
988         struct btrfs_key key;
989         struct btrfs_key new_key;
990         u64 bytenr;
991         u64 num_bytes;
992         u64 extent_end;
993         u64 orig_offset;
994         u64 other_start;
995         u64 other_end;
996         u64 split;
997         int del_nr = 0;
998         int del_slot = 0;
999         int recow;
1000         int ret;
1001         u64 ino = btrfs_ino(inode);
1002
1003         path = btrfs_alloc_path();
1004         if (!path)
1005                 return -ENOMEM;
1006 again:
1007         recow = 0;
1008         split = start;
1009         key.objectid = ino;
1010         key.type = BTRFS_EXTENT_DATA_KEY;
1011         key.offset = split;
1012
1013         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1014         if (ret < 0)
1015                 goto out;
1016         if (ret > 0 && path->slots[0] > 0)
1017                 path->slots[0]--;
1018
1019         leaf = path->nodes[0];
1020         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1021         BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
1022         fi = btrfs_item_ptr(leaf, path->slots[0],
1023                             struct btrfs_file_extent_item);
1024         BUG_ON(btrfs_file_extent_type(leaf, fi) !=
1025                BTRFS_FILE_EXTENT_PREALLOC);
1026         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1027         BUG_ON(key.offset > start || extent_end < end);
1028
1029         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1030         num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1031         orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
1032         memcpy(&new_key, &key, sizeof(new_key));
1033
1034         if (start == key.offset && end < extent_end) {
1035                 other_start = 0;
1036                 other_end = start;
1037                 if (extent_mergeable(leaf, path->slots[0] - 1,
1038                                      ino, bytenr, orig_offset,
1039                                      &other_start, &other_end)) {
1040                         new_key.offset = end;
1041                         btrfs_set_item_key_safe(trans, root, path, &new_key);
1042                         fi = btrfs_item_ptr(leaf, path->slots[0],
1043                                             struct btrfs_file_extent_item);
1044                         btrfs_set_file_extent_generation(leaf, fi,
1045                                                          trans->transid);
1046                         btrfs_set_file_extent_num_bytes(leaf, fi,
1047                                                         extent_end - end);
1048                         btrfs_set_file_extent_offset(leaf, fi,
1049                                                      end - orig_offset);
1050                         fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1051                                             struct btrfs_file_extent_item);
1052                         btrfs_set_file_extent_generation(leaf, fi,
1053                                                          trans->transid);
1054                         btrfs_set_file_extent_num_bytes(leaf, fi,
1055                                                         end - other_start);
1056                         btrfs_mark_buffer_dirty(leaf);
1057                         goto out;
1058                 }
1059         }
1060
1061         if (start > key.offset && end == extent_end) {
1062                 other_start = end;
1063                 other_end = 0;
1064                 if (extent_mergeable(leaf, path->slots[0] + 1,
1065                                      ino, bytenr, orig_offset,
1066                                      &other_start, &other_end)) {
1067                         fi = btrfs_item_ptr(leaf, path->slots[0],
1068                                             struct btrfs_file_extent_item);
1069                         btrfs_set_file_extent_num_bytes(leaf, fi,
1070                                                         start - key.offset);
1071                         btrfs_set_file_extent_generation(leaf, fi,
1072                                                          trans->transid);
1073                         path->slots[0]++;
1074                         new_key.offset = start;
1075                         btrfs_set_item_key_safe(trans, root, path, &new_key);
1076
1077                         fi = btrfs_item_ptr(leaf, path->slots[0],
1078                                             struct btrfs_file_extent_item);
1079                         btrfs_set_file_extent_generation(leaf, fi,
1080                                                          trans->transid);
1081                         btrfs_set_file_extent_num_bytes(leaf, fi,
1082                                                         other_end - start);
1083                         btrfs_set_file_extent_offset(leaf, fi,
1084                                                      start - orig_offset);
1085                         btrfs_mark_buffer_dirty(leaf);
1086                         goto out;
1087                 }
1088         }
1089
1090         while (start > key.offset || end < extent_end) {
1091                 if (key.offset == start)
1092                         split = end;
1093
1094                 new_key.offset = split;
1095                 ret = btrfs_duplicate_item(trans, root, path, &new_key);
1096                 if (ret == -EAGAIN) {
1097                         btrfs_release_path(path);
1098                         goto again;
1099                 }
1100                 if (ret < 0) {
1101                         btrfs_abort_transaction(trans, root, ret);
1102                         goto out;
1103                 }
1104
1105                 leaf = path->nodes[0];
1106                 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1107                                     struct btrfs_file_extent_item);
1108                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1109                 btrfs_set_file_extent_num_bytes(leaf, fi,
1110                                                 split - key.offset);
1111
1112                 fi = btrfs_item_ptr(leaf, path->slots[0],
1113                                     struct btrfs_file_extent_item);
1114
1115                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1116                 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1117                 btrfs_set_file_extent_num_bytes(leaf, fi,
1118                                                 extent_end - split);
1119                 btrfs_mark_buffer_dirty(leaf);
1120
1121                 ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
1122                                            root->root_key.objectid,
1123                                            ino, orig_offset, 0);
1124                 BUG_ON(ret); /* -ENOMEM */
1125
1126                 if (split == start) {
1127                         key.offset = start;
1128                 } else {
1129                         BUG_ON(start != key.offset);
1130                         path->slots[0]--;
1131                         extent_end = end;
1132                 }
1133                 recow = 1;
1134         }
1135
1136         other_start = end;
1137         other_end = 0;
1138         if (extent_mergeable(leaf, path->slots[0] + 1,
1139                              ino, bytenr, orig_offset,
1140                              &other_start, &other_end)) {
1141                 if (recow) {
1142                         btrfs_release_path(path);
1143                         goto again;
1144                 }
1145                 extent_end = other_end;
1146                 del_slot = path->slots[0] + 1;
1147                 del_nr++;
1148                 ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
1149                                         0, root->root_key.objectid,
1150                                         ino, orig_offset, 0);
1151                 BUG_ON(ret); /* -ENOMEM */
1152         }
1153         other_start = 0;
1154         other_end = start;
1155         if (extent_mergeable(leaf, path->slots[0] - 1,
1156                              ino, bytenr, orig_offset,
1157                              &other_start, &other_end)) {
1158                 if (recow) {
1159                         btrfs_release_path(path);
1160                         goto again;
1161                 }
1162                 key.offset = other_start;
1163                 del_slot = path->slots[0];
1164                 del_nr++;
1165                 ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
1166                                         0, root->root_key.objectid,
1167                                         ino, orig_offset, 0);
1168                 BUG_ON(ret); /* -ENOMEM */
1169         }
1170         if (del_nr == 0) {
1171                 fi = btrfs_item_ptr(leaf, path->slots[0],
1172                            struct btrfs_file_extent_item);
1173                 btrfs_set_file_extent_type(leaf, fi,
1174                                            BTRFS_FILE_EXTENT_REG);
1175                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1176                 btrfs_mark_buffer_dirty(leaf);
1177         } else {
1178                 fi = btrfs_item_ptr(leaf, del_slot - 1,
1179                            struct btrfs_file_extent_item);
1180                 btrfs_set_file_extent_type(leaf, fi,
1181                                            BTRFS_FILE_EXTENT_REG);
1182                 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1183                 btrfs_set_file_extent_num_bytes(leaf, fi,
1184                                                 extent_end - key.offset);
1185                 btrfs_mark_buffer_dirty(leaf);
1186
1187                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1188                 if (ret < 0) {
1189                         btrfs_abort_transaction(trans, root, ret);
1190                         goto out;
1191                 }
1192         }
1193 out:
1194         btrfs_free_path(path);
1195         return 0;
1196 }
1197
1198 /*
1199  * on error we return an unlocked page and the error value
1200  * on success we return a locked page and 0
1201  */
1202 static int prepare_uptodate_page(struct page *page, u64 pos,
1203                                  bool force_uptodate)
1204 {
1205         int ret = 0;
1206
1207         if (((pos & (PAGE_CACHE_SIZE - 1)) || force_uptodate) &&
1208             !PageUptodate(page)) {
1209                 ret = btrfs_readpage(NULL, page);
1210                 if (ret)
1211                         return ret;
1212                 lock_page(page);
1213                 if (!PageUptodate(page)) {
1214                         unlock_page(page);
1215                         return -EIO;
1216                 }
1217         }
1218         return 0;
1219 }
1220
1221 /*
1222  * this gets pages into the page cache and locks them down, it also properly
1223  * waits for data=ordered extents to finish before allowing the pages to be
1224  * modified.
1225  */
1226 static noinline int prepare_pages(struct btrfs_root *root, struct file *file,
1227                          struct page **pages, size_t num_pages,
1228                          loff_t pos, unsigned long first_index,
1229                          size_t write_bytes, bool force_uptodate)
1230 {
1231         struct extent_state *cached_state = NULL;
1232         int i;
1233         unsigned long index = pos >> PAGE_CACHE_SHIFT;
1234         struct inode *inode = file_inode(file);
1235         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1236         int err = 0;
1237         int faili = 0;
1238         u64 start_pos;
1239         u64 last_pos;
1240
1241         start_pos = pos & ~((u64)root->sectorsize - 1);
1242         last_pos = ((u64)index + num_pages) << PAGE_CACHE_SHIFT;
1243
1244 again:
1245         for (i = 0; i < num_pages; i++) {
1246                 pages[i] = find_or_create_page(inode->i_mapping, index + i,
1247                                                mask | __GFP_WRITE);
1248                 if (!pages[i]) {
1249                         faili = i - 1;
1250                         err = -ENOMEM;
1251                         goto fail;
1252                 }
1253
1254                 if (i == 0)
1255                         err = prepare_uptodate_page(pages[i], pos,
1256                                                     force_uptodate);
1257                 if (i == num_pages - 1)
1258                         err = prepare_uptodate_page(pages[i],
1259                                                     pos + write_bytes, false);
1260                 if (err) {
1261                         page_cache_release(pages[i]);
1262                         faili = i - 1;
1263                         goto fail;
1264                 }
1265                 wait_on_page_writeback(pages[i]);
1266         }
1267         err = 0;
1268         if (start_pos < inode->i_size) {
1269                 struct btrfs_ordered_extent *ordered;
1270                 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1271                                  start_pos, last_pos - 1, 0, &cached_state);
1272                 ordered = btrfs_lookup_first_ordered_extent(inode,
1273                                                             last_pos - 1);
1274                 if (ordered &&
1275                     ordered->file_offset + ordered->len > start_pos &&
1276                     ordered->file_offset < last_pos) {
1277                         btrfs_put_ordered_extent(ordered);
1278                         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1279                                              start_pos, last_pos - 1,
1280                                              &cached_state, GFP_NOFS);
1281                         for (i = 0; i < num_pages; i++) {
1282                                 unlock_page(pages[i]);
1283                                 page_cache_release(pages[i]);
1284                         }
1285                         btrfs_wait_ordered_range(inode, start_pos,
1286                                                  last_pos - start_pos);
1287                         goto again;
1288                 }
1289                 if (ordered)
1290                         btrfs_put_ordered_extent(ordered);
1291
1292                 clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
1293                                   last_pos - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1294                                   EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
1295                                   0, 0, &cached_state, GFP_NOFS);
1296                 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1297                                      start_pos, last_pos - 1, &cached_state,
1298                                      GFP_NOFS);
1299         }
1300         for (i = 0; i < num_pages; i++) {
1301                 if (clear_page_dirty_for_io(pages[i]))
1302                         account_page_redirty(pages[i]);
1303                 set_page_extent_mapped(pages[i]);
1304                 WARN_ON(!PageLocked(pages[i]));
1305         }
1306         return 0;
1307 fail:
1308         while (faili >= 0) {
1309                 unlock_page(pages[faili]);
1310                 page_cache_release(pages[faili]);
1311                 faili--;
1312         }
1313         return err;
1314
1315 }
1316
1317 static noinline ssize_t __btrfs_buffered_write(struct file *file,
1318                                                struct iov_iter *i,
1319                                                loff_t pos)
1320 {
1321         struct inode *inode = file_inode(file);
1322         struct btrfs_root *root = BTRFS_I(inode)->root;
1323         struct page **pages = NULL;
1324         unsigned long first_index;
1325         size_t num_written = 0;
1326         int nrptrs;
1327         int ret = 0;
1328         bool force_page_uptodate = false;
1329
1330         nrptrs = min((iov_iter_count(i) + PAGE_CACHE_SIZE - 1) /
1331                      PAGE_CACHE_SIZE, PAGE_CACHE_SIZE /
1332                      (sizeof(struct page *)));
1333         nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1334         nrptrs = max(nrptrs, 8);
1335         pages = kmalloc(nrptrs * sizeof(struct page *), GFP_KERNEL);
1336         if (!pages)
1337                 return -ENOMEM;
1338
1339         first_index = pos >> PAGE_CACHE_SHIFT;
1340
1341         while (iov_iter_count(i) > 0) {
1342                 size_t offset = pos & (PAGE_CACHE_SIZE - 1);
1343                 size_t write_bytes = min(iov_iter_count(i),
1344                                          nrptrs * (size_t)PAGE_CACHE_SIZE -
1345                                          offset);
1346                 size_t num_pages = (write_bytes + offset +
1347                                     PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1348                 size_t dirty_pages;
1349                 size_t copied;
1350
1351                 WARN_ON(num_pages > nrptrs);
1352
1353                 /*
1354                  * Fault pages before locking them in prepare_pages
1355                  * to avoid recursive lock
1356                  */
1357                 if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
1358                         ret = -EFAULT;
1359                         break;
1360                 }
1361
1362                 ret = btrfs_delalloc_reserve_space(inode,
1363                                         num_pages << PAGE_CACHE_SHIFT);
1364                 if (ret)
1365                         break;
1366
1367                 /*
1368                  * This is going to setup the pages array with the number of
1369                  * pages we want, so we don't really need to worry about the
1370                  * contents of pages from loop to loop
1371                  */
1372                 ret = prepare_pages(root, file, pages, num_pages,
1373                                     pos, first_index, write_bytes,
1374                                     force_page_uptodate);
1375                 if (ret) {
1376                         btrfs_delalloc_release_space(inode,
1377                                         num_pages << PAGE_CACHE_SHIFT);
1378                         break;
1379                 }
1380
1381                 copied = btrfs_copy_from_user(pos, num_pages,
1382                                            write_bytes, pages, i);
1383
1384                 /*
1385                  * if we have trouble faulting in the pages, fall
1386                  * back to one page at a time
1387                  */
1388                 if (copied < write_bytes)
1389                         nrptrs = 1;
1390
1391                 if (copied == 0) {
1392                         force_page_uptodate = true;
1393                         dirty_pages = 0;
1394                 } else {
1395                         force_page_uptodate = false;
1396                         dirty_pages = (copied + offset +
1397                                        PAGE_CACHE_SIZE - 1) >>
1398                                        PAGE_CACHE_SHIFT;
1399                 }
1400
1401                 /*
1402                  * If we had a short copy we need to release the excess delaloc
1403                  * bytes we reserved.  We need to increment outstanding_extents
1404                  * because btrfs_delalloc_release_space will decrement it, but
1405                  * we still have an outstanding extent for the chunk we actually
1406                  * managed to copy.
1407                  */
1408                 if (num_pages > dirty_pages) {
1409                         if (copied > 0) {
1410                                 spin_lock(&BTRFS_I(inode)->lock);
1411                                 BTRFS_I(inode)->outstanding_extents++;
1412                                 spin_unlock(&BTRFS_I(inode)->lock);
1413                         }
1414                         btrfs_delalloc_release_space(inode,
1415                                         (num_pages - dirty_pages) <<
1416                                         PAGE_CACHE_SHIFT);
1417                 }
1418
1419                 if (copied > 0) {
1420                         ret = btrfs_dirty_pages(root, inode, pages,
1421                                                 dirty_pages, pos, copied,
1422                                                 NULL);
1423                         if (ret) {
1424                                 btrfs_delalloc_release_space(inode,
1425                                         dirty_pages << PAGE_CACHE_SHIFT);
1426                                 btrfs_drop_pages(pages, num_pages);
1427                                 break;
1428                         }
1429                 }
1430
1431                 btrfs_drop_pages(pages, num_pages);
1432
1433                 cond_resched();
1434
1435                 balance_dirty_pages_ratelimited(inode->i_mapping);
1436                 if (dirty_pages < (root->leafsize >> PAGE_CACHE_SHIFT) + 1)
1437                         btrfs_btree_balance_dirty(root);
1438
1439                 pos += copied;
1440                 num_written += copied;
1441         }
1442
1443         kfree(pages);
1444
1445         return num_written ? num_written : ret;
1446 }
1447
1448 static ssize_t __btrfs_direct_write(struct kiocb *iocb,
1449                                     const struct iovec *iov,
1450                                     unsigned long nr_segs, loff_t pos,
1451                                     loff_t *ppos, size_t count, size_t ocount)
1452 {
1453         struct file *file = iocb->ki_filp;
1454         struct iov_iter i;
1455         ssize_t written;
1456         ssize_t written_buffered;
1457         loff_t endbyte;
1458         int err;
1459
1460         written = generic_file_direct_write(iocb, iov, &nr_segs, pos, ppos,
1461                                             count, ocount);
1462
1463         if (written < 0 || written == count)
1464                 return written;
1465
1466         pos += written;
1467         count -= written;
1468         iov_iter_init(&i, iov, nr_segs, count, written);
1469         written_buffered = __btrfs_buffered_write(file, &i, pos);
1470         if (written_buffered < 0) {
1471                 err = written_buffered;
1472                 goto out;
1473         }
1474         endbyte = pos + written_buffered - 1;
1475         err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
1476         if (err)
1477                 goto out;
1478         written += written_buffered;
1479         *ppos = pos + written_buffered;
1480         invalidate_mapping_pages(file->f_mapping, pos >> PAGE_CACHE_SHIFT,
1481                                  endbyte >> PAGE_CACHE_SHIFT);
1482 out:
1483         return written ? written : err;
1484 }
1485
1486 static void update_time_for_write(struct inode *inode)
1487 {
1488         struct timespec now;
1489
1490         if (IS_NOCMTIME(inode))
1491                 return;
1492
1493         now = current_fs_time(inode->i_sb);
1494         if (!timespec_equal(&inode->i_mtime, &now))
1495                 inode->i_mtime = now;
1496
1497         if (!timespec_equal(&inode->i_ctime, &now))
1498                 inode->i_ctime = now;
1499
1500         if (IS_I_VERSION(inode))
1501                 inode_inc_iversion(inode);
1502 }
1503
1504 static ssize_t btrfs_file_aio_write(struct kiocb *iocb,
1505                                     const struct iovec *iov,
1506                                     unsigned long nr_segs, loff_t pos)
1507 {
1508         struct file *file = iocb->ki_filp;
1509         struct inode *inode = file_inode(file);
1510         struct btrfs_root *root = BTRFS_I(inode)->root;
1511         loff_t *ppos = &iocb->ki_pos;
1512         u64 start_pos;
1513         ssize_t num_written = 0;
1514         ssize_t err = 0;
1515         size_t count, ocount;
1516         bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
1517
1518         mutex_lock(&inode->i_mutex);
1519
1520         err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
1521         if (err) {
1522                 mutex_unlock(&inode->i_mutex);
1523                 goto out;
1524         }
1525         count = ocount;
1526
1527         current->backing_dev_info = inode->i_mapping->backing_dev_info;
1528         err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
1529         if (err) {
1530                 mutex_unlock(&inode->i_mutex);
1531                 goto out;
1532         }
1533
1534         if (count == 0) {
1535                 mutex_unlock(&inode->i_mutex);
1536                 goto out;
1537         }
1538
1539         err = file_remove_suid(file);
1540         if (err) {
1541                 mutex_unlock(&inode->i_mutex);
1542                 goto out;
1543         }
1544
1545         /*
1546          * If BTRFS flips readonly due to some impossible error
1547          * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
1548          * although we have opened a file as writable, we have
1549          * to stop this write operation to ensure FS consistency.
1550          */
1551         if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
1552                 mutex_unlock(&inode->i_mutex);
1553                 err = -EROFS;
1554                 goto out;
1555         }
1556
1557         /*
1558          * We reserve space for updating the inode when we reserve space for the
1559          * extent we are going to write, so we will enospc out there.  We don't
1560          * need to start yet another transaction to update the inode as we will
1561          * update the inode when we finish writing whatever data we write.
1562          */
1563         update_time_for_write(inode);
1564
1565         start_pos = round_down(pos, root->sectorsize);
1566         if (start_pos > i_size_read(inode)) {
1567                 err = btrfs_cont_expand(inode, i_size_read(inode), start_pos);
1568                 if (err) {
1569                         mutex_unlock(&inode->i_mutex);
1570                         goto out;
1571                 }
1572         }
1573
1574         if (sync)
1575                 atomic_inc(&BTRFS_I(inode)->sync_writers);
1576
1577         if (unlikely(file->f_flags & O_DIRECT)) {
1578                 num_written = __btrfs_direct_write(iocb, iov, nr_segs,
1579                                                    pos, ppos, count, ocount);
1580         } else {
1581                 struct iov_iter i;
1582
1583                 iov_iter_init(&i, iov, nr_segs, count, num_written);
1584
1585                 num_written = __btrfs_buffered_write(file, &i, pos);
1586                 if (num_written > 0)
1587                         *ppos = pos + num_written;
1588         }
1589
1590         mutex_unlock(&inode->i_mutex);
1591
1592         /*
1593          * we want to make sure fsync finds this change
1594          * but we haven't joined a transaction running right now.
1595          *
1596          * Later on, someone is sure to update the inode and get the
1597          * real transid recorded.
1598          *
1599          * We set last_trans now to the fs_info generation + 1,
1600          * this will either be one more than the running transaction
1601          * or the generation used for the next transaction if there isn't
1602          * one running right now.
1603          *
1604          * We also have to set last_sub_trans to the current log transid,
1605          * otherwise subsequent syncs to a file that's been synced in this
1606          * transaction will appear to have already occured.
1607          */
1608         BTRFS_I(inode)->last_trans = root->fs_info->generation + 1;
1609         BTRFS_I(inode)->last_sub_trans = root->log_transid;
1610         if (num_written > 0 || num_written == -EIOCBQUEUED) {
1611                 err = generic_write_sync(file, pos, num_written);
1612                 if (err < 0 && num_written > 0)
1613                         num_written = err;
1614         }
1615
1616         if (sync)
1617                 atomic_dec(&BTRFS_I(inode)->sync_writers);
1618 out:
1619         current->backing_dev_info = NULL;
1620         return num_written ? num_written : err;
1621 }
1622
1623 int btrfs_release_file(struct inode *inode, struct file *filp)
1624 {
1625         /*
1626          * ordered_data_close is set by settattr when we are about to truncate
1627          * a file from a non-zero size to a zero size.  This tries to
1628          * flush down new bytes that may have been written if the
1629          * application were using truncate to replace a file in place.
1630          */
1631         if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
1632                                &BTRFS_I(inode)->runtime_flags)) {
1633                 struct btrfs_trans_handle *trans;
1634                 struct btrfs_root *root = BTRFS_I(inode)->root;
1635
1636                 /*
1637                  * We need to block on a committing transaction to keep us from
1638                  * throwing a ordered operation on to the list and causing
1639                  * something like sync to deadlock trying to flush out this
1640                  * inode.
1641                  */
1642                 trans = btrfs_start_transaction(root, 0);
1643                 if (IS_ERR(trans))
1644                         return PTR_ERR(trans);
1645                 btrfs_add_ordered_operation(trans, BTRFS_I(inode)->root, inode);
1646                 btrfs_end_transaction(trans, root);
1647                 if (inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
1648                         filemap_flush(inode->i_mapping);
1649         }
1650         if (filp->private_data)
1651                 btrfs_ioctl_trans_end(filp);
1652         return 0;
1653 }
1654
1655 /*
1656  * fsync call for both files and directories.  This logs the inode into
1657  * the tree log instead of forcing full commits whenever possible.
1658  *
1659  * It needs to call filemap_fdatawait so that all ordered extent updates are
1660  * in the metadata btree are up to date for copying to the log.
1661  *
1662  * It drops the inode mutex before doing the tree log commit.  This is an
1663  * important optimization for directories because holding the mutex prevents
1664  * new operations on the dir while we write to disk.
1665  */
1666 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
1667 {
1668         struct dentry *dentry = file->f_path.dentry;
1669         struct inode *inode = dentry->d_inode;
1670         struct btrfs_root *root = BTRFS_I(inode)->root;
1671         int ret = 0;
1672         struct btrfs_trans_handle *trans;
1673         bool full_sync = 0;
1674
1675         trace_btrfs_sync_file(file, datasync);
1676
1677         /*
1678          * We write the dirty pages in the range and wait until they complete
1679          * out of the ->i_mutex. If so, we can flush the dirty pages by
1680          * multi-task, and make the performance up.  See
1681          * btrfs_wait_ordered_range for an explanation of the ASYNC check.
1682          */
1683         atomic_inc(&BTRFS_I(inode)->sync_writers);
1684         ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
1685         if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1686                              &BTRFS_I(inode)->runtime_flags))
1687                 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
1688         atomic_dec(&BTRFS_I(inode)->sync_writers);
1689         if (ret)
1690                 return ret;
1691
1692         mutex_lock(&inode->i_mutex);
1693
1694         /*
1695          * We flush the dirty pages again to avoid some dirty pages in the
1696          * range being left.
1697          */
1698         atomic_inc(&root->log_batch);
1699         full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1700                              &BTRFS_I(inode)->runtime_flags);
1701         if (full_sync)
1702                 btrfs_wait_ordered_range(inode, start, end - start + 1);
1703         atomic_inc(&root->log_batch);
1704
1705         /*
1706          * check the transaction that last modified this inode
1707          * and see if its already been committed
1708          */
1709         if (!BTRFS_I(inode)->last_trans) {
1710                 mutex_unlock(&inode->i_mutex);
1711                 goto out;
1712         }
1713
1714         /*
1715          * if the last transaction that changed this file was before
1716          * the current transaction, we can bail out now without any
1717          * syncing
1718          */
1719         smp_mb();
1720         if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
1721             BTRFS_I(inode)->last_trans <=
1722             root->fs_info->last_trans_committed) {
1723                 BTRFS_I(inode)->last_trans = 0;
1724
1725                 /*
1726                  * We'v had everything committed since the last time we were
1727                  * modified so clear this flag in case it was set for whatever
1728                  * reason, it's no longer relevant.
1729                  */
1730                 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1731                           &BTRFS_I(inode)->runtime_flags);
1732                 mutex_unlock(&inode->i_mutex);
1733                 goto out;
1734         }
1735
1736         /*
1737          * ok we haven't committed the transaction yet, lets do a commit
1738          */
1739         if (file->private_data)
1740                 btrfs_ioctl_trans_end(file);
1741
1742         trans = btrfs_start_transaction(root, 0);
1743         if (IS_ERR(trans)) {
1744                 ret = PTR_ERR(trans);
1745                 mutex_unlock(&inode->i_mutex);
1746                 goto out;
1747         }
1748
1749         ret = btrfs_log_dentry_safe(trans, root, dentry);
1750         if (ret < 0) {
1751                 mutex_unlock(&inode->i_mutex);
1752                 goto out;
1753         }
1754
1755         /* we've logged all the items and now have a consistent
1756          * version of the file in the log.  It is possible that
1757          * someone will come in and modify the file, but that's
1758          * fine because the log is consistent on disk, and we
1759          * have references to all of the file's extents
1760          *
1761          * It is possible that someone will come in and log the
1762          * file again, but that will end up using the synchronization
1763          * inside btrfs_sync_log to keep things safe.
1764          */
1765         mutex_unlock(&inode->i_mutex);
1766
1767         if (ret != BTRFS_NO_LOG_SYNC) {
1768                 if (ret > 0) {
1769                         /*
1770                          * If we didn't already wait for ordered extents we need
1771                          * to do that now.
1772                          */
1773                         if (!full_sync)
1774                                 btrfs_wait_ordered_range(inode, start,
1775                                                          end - start + 1);
1776                         ret = btrfs_commit_transaction(trans, root);
1777                 } else {
1778                         ret = btrfs_sync_log(trans, root);
1779                         if (ret == 0) {
1780                                 ret = btrfs_end_transaction(trans, root);
1781                         } else {
1782                                 if (!full_sync)
1783                                         btrfs_wait_ordered_range(inode, start,
1784                                                                  end -
1785                                                                  start + 1);
1786                                 ret = btrfs_commit_transaction(trans, root);
1787                         }
1788                 }
1789         } else {
1790                 ret = btrfs_end_transaction(trans, root);
1791         }
1792 out:
1793         return ret > 0 ? -EIO : ret;
1794 }
1795
1796 static const struct vm_operations_struct btrfs_file_vm_ops = {
1797         .fault          = filemap_fault,
1798         .page_mkwrite   = btrfs_page_mkwrite,
1799         .remap_pages    = generic_file_remap_pages,
1800 };
1801
1802 static int btrfs_file_mmap(struct file  *filp, struct vm_area_struct *vma)
1803 {
1804         struct address_space *mapping = filp->f_mapping;
1805
1806         if (!mapping->a_ops->readpage)
1807                 return -ENOEXEC;
1808
1809         file_accessed(filp);
1810         vma->vm_ops = &btrfs_file_vm_ops;
1811
1812         return 0;
1813 }
1814
1815 static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
1816                           int slot, u64 start, u64 end)
1817 {
1818         struct btrfs_file_extent_item *fi;
1819         struct btrfs_key key;
1820
1821         if (slot < 0 || slot >= btrfs_header_nritems(leaf))
1822                 return 0;
1823
1824         btrfs_item_key_to_cpu(leaf, &key, slot);
1825         if (key.objectid != btrfs_ino(inode) ||
1826             key.type != BTRFS_EXTENT_DATA_KEY)
1827                 return 0;
1828
1829         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1830
1831         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
1832                 return 0;
1833
1834         if (btrfs_file_extent_disk_bytenr(leaf, fi))
1835                 return 0;
1836
1837         if (key.offset == end)
1838                 return 1;
1839         if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
1840                 return 1;
1841         return 0;
1842 }
1843
1844 static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
1845                       struct btrfs_path *path, u64 offset, u64 end)
1846 {
1847         struct btrfs_root *root = BTRFS_I(inode)->root;
1848         struct extent_buffer *leaf;
1849         struct btrfs_file_extent_item *fi;
1850         struct extent_map *hole_em;
1851         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1852         struct btrfs_key key;
1853         int ret;
1854
1855         key.objectid = btrfs_ino(inode);
1856         key.type = BTRFS_EXTENT_DATA_KEY;
1857         key.offset = offset;
1858
1859
1860         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1861         if (ret < 0)
1862                 return ret;
1863         BUG_ON(!ret);
1864
1865         leaf = path->nodes[0];
1866         if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
1867                 u64 num_bytes;
1868
1869                 path->slots[0]--;
1870                 fi = btrfs_item_ptr(leaf, path->slots[0],
1871                                     struct btrfs_file_extent_item);
1872                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
1873                         end - offset;
1874                 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1875                 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
1876                 btrfs_set_file_extent_offset(leaf, fi, 0);
1877                 btrfs_mark_buffer_dirty(leaf);
1878                 goto out;
1879         }
1880
1881         if (hole_mergeable(inode, leaf, path->slots[0]+1, offset, end)) {
1882                 u64 num_bytes;
1883
1884                 path->slots[0]++;
1885                 key.offset = offset;
1886                 btrfs_set_item_key_safe(trans, root, path, &key);
1887                 fi = btrfs_item_ptr(leaf, path->slots[0],
1888                                     struct btrfs_file_extent_item);
1889                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
1890                         offset;
1891                 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1892                 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
1893                 btrfs_set_file_extent_offset(leaf, fi, 0);
1894                 btrfs_mark_buffer_dirty(leaf);
1895                 goto out;
1896         }
1897         btrfs_release_path(path);
1898
1899         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
1900                                        0, 0, end - offset, 0, end - offset,
1901                                        0, 0, 0);
1902         if (ret)
1903                 return ret;
1904
1905 out:
1906         btrfs_release_path(path);
1907
1908         hole_em = alloc_extent_map();
1909         if (!hole_em) {
1910                 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
1911                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1912                         &BTRFS_I(inode)->runtime_flags);
1913         } else {
1914                 hole_em->start = offset;
1915                 hole_em->len = end - offset;
1916                 hole_em->orig_start = offset;
1917
1918                 hole_em->block_start = EXTENT_MAP_HOLE;
1919                 hole_em->block_len = 0;
1920                 hole_em->orig_block_len = 0;
1921                 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
1922                 hole_em->compress_type = BTRFS_COMPRESS_NONE;
1923                 hole_em->generation = trans->transid;
1924
1925                 do {
1926                         btrfs_drop_extent_cache(inode, offset, end - 1, 0);
1927                         write_lock(&em_tree->lock);
1928                         ret = add_extent_mapping(em_tree, hole_em);
1929                         if (!ret)
1930                                 list_move(&hole_em->list,
1931                                           &em_tree->modified_extents);
1932                         write_unlock(&em_tree->lock);
1933                 } while (ret == -EEXIST);
1934                 free_extent_map(hole_em);
1935                 if (ret)
1936                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1937                                 &BTRFS_I(inode)->runtime_flags);
1938         }
1939
1940         return 0;
1941 }
1942
1943 static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
1944 {
1945         struct btrfs_root *root = BTRFS_I(inode)->root;
1946         struct extent_state *cached_state = NULL;
1947         struct btrfs_path *path;
1948         struct btrfs_block_rsv *rsv;
1949         struct btrfs_trans_handle *trans;
1950         u64 lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
1951         u64 lockend = round_down(offset + len,
1952                                  BTRFS_I(inode)->root->sectorsize) - 1;
1953         u64 cur_offset = lockstart;
1954         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
1955         u64 drop_end;
1956         int ret = 0;
1957         int err = 0;
1958         bool same_page = ((offset >> PAGE_CACHE_SHIFT) ==
1959                           ((offset + len - 1) >> PAGE_CACHE_SHIFT));
1960
1961         btrfs_wait_ordered_range(inode, offset, len);
1962
1963         mutex_lock(&inode->i_mutex);
1964         /*
1965          * We needn't truncate any page which is beyond the end of the file
1966          * because we are sure there is no data there.
1967          */
1968         /*
1969          * Only do this if we are in the same page and we aren't doing the
1970          * entire page.
1971          */
1972         if (same_page && len < PAGE_CACHE_SIZE) {
1973                 if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE))
1974                         ret = btrfs_truncate_page(inode, offset, len, 0);
1975                 mutex_unlock(&inode->i_mutex);
1976                 return ret;
1977         }
1978
1979         /* zero back part of the first page */
1980         if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
1981                 ret = btrfs_truncate_page(inode, offset, 0, 0);
1982                 if (ret) {
1983                         mutex_unlock(&inode->i_mutex);
1984                         return ret;
1985                 }
1986         }
1987
1988         /* zero the front end of the last page */
1989         if (offset + len < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
1990                 ret = btrfs_truncate_page(inode, offset + len, 0, 1);
1991                 if (ret) {
1992                         mutex_unlock(&inode->i_mutex);
1993                         return ret;
1994                 }
1995         }
1996
1997         if (lockend < lockstart) {
1998                 mutex_unlock(&inode->i_mutex);
1999                 return 0;
2000         }
2001
2002         while (1) {
2003                 struct btrfs_ordered_extent *ordered;
2004
2005                 truncate_pagecache_range(inode, lockstart, lockend);
2006
2007                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2008                                  0, &cached_state);
2009                 ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
2010
2011                 /*
2012                  * We need to make sure we have no ordered extents in this range
2013                  * and nobody raced in and read a page in this range, if we did
2014                  * we need to try again.
2015                  */
2016                 if ((!ordered ||
2017                     (ordered->file_offset + ordered->len < lockstart ||
2018                      ordered->file_offset > lockend)) &&
2019                      !test_range_bit(&BTRFS_I(inode)->io_tree, lockstart,
2020                                      lockend, EXTENT_UPTODATE, 0,
2021                                      cached_state)) {
2022                         if (ordered)
2023                                 btrfs_put_ordered_extent(ordered);
2024                         break;
2025                 }
2026                 if (ordered)
2027                         btrfs_put_ordered_extent(ordered);
2028                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
2029                                      lockend, &cached_state, GFP_NOFS);
2030                 btrfs_wait_ordered_range(inode, lockstart,
2031                                          lockend - lockstart + 1);
2032         }
2033
2034         path = btrfs_alloc_path();
2035         if (!path) {
2036                 ret = -ENOMEM;
2037                 goto out;
2038         }
2039
2040         rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2041         if (!rsv) {
2042                 ret = -ENOMEM;
2043                 goto out_free;
2044         }
2045         rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
2046         rsv->failfast = 1;
2047
2048         /*
2049          * 1 - update the inode
2050          * 1 - removing the extents in the range
2051          * 1 - adding the hole extent
2052          */
2053         trans = btrfs_start_transaction(root, 3);
2054         if (IS_ERR(trans)) {
2055                 err = PTR_ERR(trans);
2056                 goto out_free;
2057         }
2058
2059         ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
2060                                       min_size);
2061         BUG_ON(ret);
2062         trans->block_rsv = rsv;
2063
2064         while (cur_offset < lockend) {
2065                 ret = __btrfs_drop_extents(trans, root, inode, path,
2066                                            cur_offset, lockend + 1,
2067                                            &drop_end, 1);
2068                 if (ret != -ENOSPC)
2069                         break;
2070
2071                 trans->block_rsv = &root->fs_info->trans_block_rsv;
2072
2073                 ret = fill_holes(trans, inode, path, cur_offset, drop_end);
2074                 if (ret) {
2075                         err = ret;
2076                         break;
2077                 }
2078
2079                 cur_offset = drop_end;
2080
2081                 ret = btrfs_update_inode(trans, root, inode);
2082                 if (ret) {
2083                         err = ret;
2084                         break;
2085                 }
2086
2087                 btrfs_end_transaction(trans, root);
2088                 btrfs_btree_balance_dirty(root);
2089
2090                 trans = btrfs_start_transaction(root, 3);
2091                 if (IS_ERR(trans)) {
2092                         ret = PTR_ERR(trans);
2093                         trans = NULL;
2094                         break;
2095                 }
2096
2097                 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
2098                                               rsv, min_size);
2099                 BUG_ON(ret);    /* shouldn't happen */
2100                 trans->block_rsv = rsv;
2101         }
2102
2103         if (ret) {
2104                 err = ret;
2105                 goto out_trans;
2106         }
2107
2108         trans->block_rsv = &root->fs_info->trans_block_rsv;
2109         ret = fill_holes(trans, inode, path, cur_offset, drop_end);
2110         if (ret) {
2111                 err = ret;
2112                 goto out_trans;
2113         }
2114
2115 out_trans:
2116         if (!trans)
2117                 goto out_free;
2118
2119         inode_inc_iversion(inode);
2120         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
2121
2122         trans->block_rsv = &root->fs_info->trans_block_rsv;
2123         ret = btrfs_update_inode(trans, root, inode);
2124         btrfs_end_transaction(trans, root);
2125         btrfs_btree_balance_dirty(root);
2126 out_free:
2127         btrfs_free_path(path);
2128         btrfs_free_block_rsv(root, rsv);
2129 out:
2130         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2131                              &cached_state, GFP_NOFS);
2132         mutex_unlock(&inode->i_mutex);
2133         if (ret && !err)
2134                 err = ret;
2135         return err;
2136 }
2137
2138 static long btrfs_fallocate(struct file *file, int mode,
2139                             loff_t offset, loff_t len)
2140 {
2141         struct inode *inode = file_inode(file);
2142         struct extent_state *cached_state = NULL;
2143         struct btrfs_root *root = BTRFS_I(inode)->root;
2144         u64 cur_offset;
2145         u64 last_byte;
2146         u64 alloc_start;
2147         u64 alloc_end;
2148         u64 alloc_hint = 0;
2149         u64 locked_end;
2150         struct extent_map *em;
2151         int blocksize = BTRFS_I(inode)->root->sectorsize;
2152         int ret;
2153
2154         alloc_start = round_down(offset, blocksize);
2155         alloc_end = round_up(offset + len, blocksize);
2156
2157         /* Make sure we aren't being give some crap mode */
2158         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2159                 return -EOPNOTSUPP;
2160
2161         if (mode & FALLOC_FL_PUNCH_HOLE)
2162                 return btrfs_punch_hole(inode, offset, len);
2163
2164         /*
2165          * Make sure we have enough space before we do the
2166          * allocation.
2167          */
2168         ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
2169         if (ret)
2170                 return ret;
2171         if (root->fs_info->quota_enabled) {
2172                 ret = btrfs_qgroup_reserve(root, alloc_end - alloc_start);
2173                 if (ret)
2174                         goto out_reserve_fail;
2175         }
2176
2177         /*
2178          * wait for ordered IO before we have any locks.  We'll loop again
2179          * below with the locks held.
2180          */
2181         btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
2182
2183         mutex_lock(&inode->i_mutex);
2184         ret = inode_newsize_ok(inode, alloc_end);
2185         if (ret)
2186                 goto out;
2187
2188         if (alloc_start > inode->i_size) {
2189                 ret = btrfs_cont_expand(inode, i_size_read(inode),
2190                                         alloc_start);
2191                 if (ret)
2192                         goto out;
2193         }
2194
2195         locked_end = alloc_end - 1;
2196         while (1) {
2197                 struct btrfs_ordered_extent *ordered;
2198
2199                 /* the extent lock is ordered inside the running
2200                  * transaction
2201                  */
2202                 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
2203                                  locked_end, 0, &cached_state);
2204                 ordered = btrfs_lookup_first_ordered_extent(inode,
2205                                                             alloc_end - 1);
2206                 if (ordered &&
2207                     ordered->file_offset + ordered->len > alloc_start &&
2208                     ordered->file_offset < alloc_end) {
2209                         btrfs_put_ordered_extent(ordered);
2210                         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
2211                                              alloc_start, locked_end,
2212                                              &cached_state, GFP_NOFS);
2213                         /*
2214                          * we can't wait on the range with the transaction
2215                          * running or with the extent lock held
2216                          */
2217                         btrfs_wait_ordered_range(inode, alloc_start,
2218                                                  alloc_end - alloc_start);
2219                 } else {
2220                         if (ordered)
2221                                 btrfs_put_ordered_extent(ordered);
2222                         break;
2223                 }
2224         }
2225
2226         cur_offset = alloc_start;
2227         while (1) {
2228                 u64 actual_end;
2229
2230                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
2231                                       alloc_end - cur_offset, 0);
2232                 if (IS_ERR_OR_NULL(em)) {
2233                         if (!em)
2234                                 ret = -ENOMEM;
2235                         else
2236                                 ret = PTR_ERR(em);
2237                         break;
2238                 }
2239                 last_byte = min(extent_map_end(em), alloc_end);
2240                 actual_end = min_t(u64, extent_map_end(em), offset + len);
2241                 last_byte = ALIGN(last_byte, blocksize);
2242
2243                 if (em->block_start == EXTENT_MAP_HOLE ||
2244                     (cur_offset >= inode->i_size &&
2245                      !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
2246                         ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
2247                                                         last_byte - cur_offset,
2248                                                         1 << inode->i_blkbits,
2249                                                         offset + len,
2250                                                         &alloc_hint);
2251
2252                         if (ret < 0) {
2253                                 free_extent_map(em);
2254                                 break;
2255                         }
2256                 } else if (actual_end > inode->i_size &&
2257                            !(mode & FALLOC_FL_KEEP_SIZE)) {
2258                         /*
2259                          * We didn't need to allocate any more space, but we
2260                          * still extended the size of the file so we need to
2261                          * update i_size.
2262                          */
2263                         inode->i_ctime = CURRENT_TIME;
2264                         i_size_write(inode, actual_end);
2265                         btrfs_ordered_update_i_size(inode, actual_end, NULL);
2266                 }
2267                 free_extent_map(em);
2268
2269                 cur_offset = last_byte;
2270                 if (cur_offset >= alloc_end) {
2271                         ret = 0;
2272                         break;
2273                 }
2274         }
2275         unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
2276                              &cached_state, GFP_NOFS);
2277 out:
2278         mutex_unlock(&inode->i_mutex);
2279         if (root->fs_info->quota_enabled)
2280                 btrfs_qgroup_free(root, alloc_end - alloc_start);
2281 out_reserve_fail:
2282         /* Let go of our reservation. */
2283         btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
2284         return ret;
2285 }
2286
2287 static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
2288 {
2289         struct btrfs_root *root = BTRFS_I(inode)->root;
2290         struct extent_map *em;
2291         struct extent_state *cached_state = NULL;
2292         u64 lockstart = *offset;
2293         u64 lockend = i_size_read(inode);
2294         u64 start = *offset;
2295         u64 orig_start = *offset;
2296         u64 len = i_size_read(inode);
2297         u64 last_end = 0;
2298         int ret = 0;
2299
2300         lockend = max_t(u64, root->sectorsize, lockend);
2301         if (lockend <= lockstart)
2302                 lockend = lockstart + root->sectorsize;
2303
2304         lockend--;
2305         len = lockend - lockstart + 1;
2306
2307         len = max_t(u64, len, root->sectorsize);
2308         if (inode->i_size == 0)
2309                 return -ENXIO;
2310
2311         lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
2312                          &cached_state);
2313
2314         /*
2315          * Delalloc is such a pain.  If we have a hole and we have pending
2316          * delalloc for a portion of the hole we will get back a hole that
2317          * exists for the entire range since it hasn't been actually written
2318          * yet.  So to take care of this case we need to look for an extent just
2319          * before the position we want in case there is outstanding delalloc
2320          * going on here.
2321          */
2322         if (whence == SEEK_HOLE && start != 0) {
2323                 if (start <= root->sectorsize)
2324                         em = btrfs_get_extent_fiemap(inode, NULL, 0, 0,
2325                                                      root->sectorsize, 0);
2326                 else
2327                         em = btrfs_get_extent_fiemap(inode, NULL, 0,
2328                                                      start - root->sectorsize,
2329                                                      root->sectorsize, 0);
2330                 if (IS_ERR(em)) {
2331                         ret = PTR_ERR(em);
2332                         goto out;
2333                 }
2334                 last_end = em->start + em->len;
2335                 if (em->block_start == EXTENT_MAP_DELALLOC)
2336                         last_end = min_t(u64, last_end, inode->i_size);
2337                 free_extent_map(em);
2338         }
2339
2340         while (1) {
2341                 em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
2342                 if (IS_ERR(em)) {
2343                         ret = PTR_ERR(em);
2344                         break;
2345                 }
2346
2347                 if (em->block_start == EXTENT_MAP_HOLE) {
2348                         if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2349                                 if (last_end <= orig_start) {
2350                                         free_extent_map(em);
2351                                         ret = -ENXIO;
2352                                         break;
2353                                 }
2354                         }
2355
2356                         if (whence == SEEK_HOLE) {
2357                                 *offset = start;
2358                                 free_extent_map(em);
2359                                 break;
2360                         }
2361                 } else {
2362                         if (whence == SEEK_DATA) {
2363                                 if (em->block_start == EXTENT_MAP_DELALLOC) {
2364                                         if (start >= inode->i_size) {
2365                                                 free_extent_map(em);
2366                                                 ret = -ENXIO;
2367                                                 break;
2368                                         }
2369                                 }
2370
2371                                 if (!test_bit(EXTENT_FLAG_PREALLOC,
2372                                               &em->flags)) {
2373                                         *offset = start;
2374                                         free_extent_map(em);
2375                                         break;
2376                                 }
2377                         }
2378                 }
2379
2380                 start = em->start + em->len;
2381                 last_end = em->start + em->len;
2382
2383                 if (em->block_start == EXTENT_MAP_DELALLOC)
2384                         last_end = min_t(u64, last_end, inode->i_size);
2385
2386                 if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2387                         free_extent_map(em);
2388                         ret = -ENXIO;
2389                         break;
2390                 }
2391                 free_extent_map(em);
2392                 cond_resched();
2393         }
2394         if (!ret)
2395                 *offset = min(*offset, inode->i_size);
2396 out:
2397         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2398                              &cached_state, GFP_NOFS);
2399         return ret;
2400 }
2401
2402 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
2403 {
2404         struct inode *inode = file->f_mapping->host;
2405         int ret;
2406
2407         mutex_lock(&inode->i_mutex);
2408         switch (whence) {
2409         case SEEK_END:
2410         case SEEK_CUR:
2411                 offset = generic_file_llseek(file, offset, whence);
2412                 goto out;
2413         case SEEK_DATA:
2414         case SEEK_HOLE:
2415                 if (offset >= i_size_read(inode)) {
2416                         mutex_unlock(&inode->i_mutex);
2417                         return -ENXIO;
2418                 }
2419
2420                 ret = find_desired_extent(inode, &offset, whence);
2421                 if (ret) {
2422                         mutex_unlock(&inode->i_mutex);
2423                         return ret;
2424                 }
2425         }
2426
2427         if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET)) {
2428                 offset = -EINVAL;
2429                 goto out;
2430         }
2431         if (offset > inode->i_sb->s_maxbytes) {
2432                 offset = -EINVAL;
2433                 goto out;
2434         }
2435
2436         /* Special lock needed here? */
2437         if (offset != file->f_pos) {
2438                 file->f_pos = offset;
2439                 file->f_version = 0;
2440         }
2441 out:
2442         mutex_unlock(&inode->i_mutex);
2443         return offset;
2444 }
2445
2446 const struct file_operations btrfs_file_operations = {
2447         .llseek         = btrfs_file_llseek,
2448         .read           = do_sync_read,
2449         .write          = do_sync_write,
2450         .aio_read       = generic_file_aio_read,
2451         .splice_read    = generic_file_splice_read,
2452         .aio_write      = btrfs_file_aio_write,
2453         .mmap           = btrfs_file_mmap,
2454         .open           = generic_file_open,
2455         .release        = btrfs_release_file,
2456         .fsync          = btrfs_sync_file,
2457         .fallocate      = btrfs_fallocate,
2458         .unlocked_ioctl = btrfs_ioctl,
2459 #ifdef CONFIG_COMPAT
2460         .compat_ioctl   = btrfs_ioctl,
2461 #endif
2462 };
2463
2464 void btrfs_auto_defrag_exit(void)
2465 {
2466         if (btrfs_inode_defrag_cachep)
2467                 kmem_cache_destroy(btrfs_inode_defrag_cachep);
2468 }
2469
2470 int btrfs_auto_defrag_init(void)
2471 {
2472         btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
2473                                         sizeof(struct inode_defrag), 0,
2474                                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
2475                                         NULL);
2476         if (!btrfs_inode_defrag_cachep)
2477                 return -ENOMEM;
2478
2479         return 0;
2480 }