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