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